diff --git "a/4203.jsonl" "b/4203.jsonl" new file mode 100644--- /dev/null +++ "b/4203.jsonl" @@ -0,0 +1,748 @@ +{"seq_id":"533869914","text":"import sys\nfrom datetime import datetime\n\ndef read_set(fname):\n data = []\n with open(fname) as f:\n for line in f:\n line = line.strip().replace(\"\\t\", \" \")\n sline = line.split(\" \")\n sline = list(filter(lambda f: f != \"\", sline))\n year, month, day = map(lambda f: int(f), sline[0].split(\"-\"))\n hour, minute, second = map(lambda f: int(f), sline[1].split(\":\"))\n dt = datetime(year, month, day, hour, minute, second)\n vid = sline[2]\n vtype = sline[3]\n vnumber = sline[4]\n lat = float(sline[5])\n lon = float(sline[6])\n data.append({\"dt\": dt, \"ts\": dt.timestamp(), \"vid\": vid, \"vtype\": vtype, \"vnumber\": vnumber, \"point\": [lon, lat]})\n return data\n\ndef write_set(fname, data):\n with open(fname, \"w\") as f:\n for e in data:\n spoint = \"SRID=4326;POINT({0} {1})\".format(e[\"point\"][0], e[\"point\"][1])\n f.write(\"{0}${1}${2}${3}${4}\\n\".format(e[\"dt\"].isoformat(), e[\"vid\"], e[\"vtype\"], e[\"vnumber\"], spoint))\n\ngps_test = read_set(\"gps_test.tsv\")\nwrite_set(\"gps_test.$sv\", gps_test)\n","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274693788","text":"from django.conf.urls.defaults import *\nfrom django.conf import settings\nimport os\nfrom settings import SITE_ROOT\nfrom django.contrib.auth.views import login, logout\n# Uncomment the next two lines to enable the admin:\nfrom lyrics.views import IndexView, AddView, ModifyView, RemoveView,\\\n AuthorSearch, PosterSearch\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\nurlpatterns = patterns('',\n url(r'^register/', 'lyrics.views.add_user', name='register'),\n url(r'^new/', AddView.as_view(), name='lyric_add'),\n # url(r'^$', IndexView.as_view(), name='index'),\n url(r'^$', \"lyrics.views.index\" , name='index'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'(?P\\d+)/modify/$', ModifyView.as_view(), name='change_lyric'),\n url(r'(?P\\d+)/delete/$', RemoveView.as_view(), name='delete_lyric'),\n url(r'^users/', include('smartmin.users.urls')),\n url(r'^login/', login),\n url(r'^logout/$', logout, {'next_page': \"/\"}),\n url(r'^tag/(?P.*)/$', 'lyrics.views.tag_search', name=\"tag_search\"),\n # url(r'^tag/(.*)/$', TagSearch.as_view(), name = \"tag_search\"),\n url(r'^author/(.*)/$', AuthorSearch.as_view(), name=\"author_search\"),\n url(r'^detail/(?P\\d+)/$', 'lyrics.views.detail_view',\\\n name=\"detail_view\"),\n url(r'^posted_by/(.*)/$', PosterSearch.as_view(), name='poster_search'),\n url(r'^update_user/$', ('lyrics.views.update_user'), name='update_user'),\n url(r'^add_lyric/$', ('lyrics.views.add_lyric'), name='add_lyric')\n)\n\n\nurlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve',\n {'document_root': os.path.join(SITE_ROOT, 'static')}),\n)\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"513049529","text":"from datetime import date\nfrom datetime import time\nfrom datetime import datetime\nfrom time import strptime\nfrom os import *\nimport datetime\nfrom datetime import datetime\nfrom dateutil import parser\nimport time\n\nclass DTValidate:\n\t#FUNCTION THAT CONVERT THE TIME AND DATE AND CHECK VALIDATION\n\tdef CovertDate():\n\t\tCurrentDate = datetime.now()\n\t\tnew = CurrentDate\n\t\tcday = new.day\n\t\tcmonth = new.month\n\t\tcyear = new.year\n\t\tif (cmonth == 1 ):\n\t\t\tcmonth = \"January\"\n\t\tif (cmonth == 2 ):\n\t\t\tcmonth = \"February\"\n\t\tif(cmonth ==3 ):\n\t\t\tcmonth = \"March\"\n\t\tif(cmonth ==4 ):\n\t\t\tcmonth = \"April\"\n\t\tif(cmonth ==5):\n\t\t\tcmonth = \"May\"\n\t\tif(cmonth ==6 ):\n\t\t\tcmonth = \"June\"\n\t\tif(cmonth ==7 ):\n\t\t\tcmonth = \"July\"\n\t\tif(cmonth == 8 ):\n\t\t\tcmonth = \"August\"\n\t\tif(cmonth == 9):\n\t\t\tcmonth = \"September\"\n\t\tif(cmonth ==10 ):\n\t\t\tcmonth = \"October\"\n\t\tif(cmonth ==11 ):\n\t\t\tcmonth = \"November\"\n\t\tif(cmonth ==12 ):\n\t\t\tcmonth = \"December\"\n\n\t\tstringDate = str(cday) +\" \"+ str(cmonth) +\" \"+ str(cyear)\n\t\tprint(stringDate)\n\t\treturn stringDate\n\n\tdef CurrentDate():\n\t\tCurrent = datetime.now()\n\t\tprint(Current)\n\t\tprint(Current.day)\n\t\tprint(Current.month)\n\t\tprint(Current.year)\n\t\tprint (str(Current.month)+\" \"+str(Current.day)+\" \"+str(Current.year))\n\t\tstringDate = str(Current.month)+\" \"+str(Current.day)+\" \"+str(Current.year)\n\t\tprint(stringDate)\n\t\treturn stringDate\n\n\tdef DateValid(dateInput):\n\t\tdateV = dateInput\n\t\tdt = parser.parse(dateV)\n\t\tnew = dt.date()\n\t\tprint(new) \n\t\tdBit = 0\n\t\tCurrent = datetime.now()\n\t\tprint(Current.day)\n\t\tprint(Current.month)\n\t\tprint(Current.year)\n\t\tprint(new.year)\n\t\tprint(new.month)\n\t\tif(new.year == Current.year and new.month == Current.month and new.day == Current.day):\n\t\t\tdBit = 1\n\t\t\tprint(dBit , \"BIT VALUE\")\n\t\telse:\n\t\t\tdBit = 0\n\t\t\tprint(dBit)\n\t\tprint(dBit ,\"Return Value\")\n\t\treturn dBit\n\n\n\tdef DateTimeValidaion(DateVar , TimeVar):\n\t\ttBit = 0\n\t\tDateTime = DateVar\n\t\tTimeIn = TimeVar\n\t\tprint(TimeIn)\n\n\t\tcurrentDT = datetime.now()\n\t\tprint(currentDT)\n\t\tprint (\"Current Hour is: %d\" % currentDT.hour)\n\t\tprint (\"Current Minute is: %d\" % currentDT.minute)\n\t\tb=time.strptime(TimeIn,'%H:%M')\n\t\tprint(\"time is \" , b.tm_hour)\n\t\tprint(\"time mints is \" , b.tm_min )\n\t\tnow=datetime.now()\n\t\tprint (now.month)\n\t\tprint (now.day)\n\t\tprint (now.year)\n\t\tprint (str(now.month)+\"/\"+str(now.day)+\"/\"+str(now.year))\n\t\tdt = parser.parse(DateTime)\n\t\tnew = dt.date()\n\t\tprint(new) \n\t\tprint (str(new.month)+\"/\"+str(new.day)+\"/\"+str(new.year))\n\t\tprint(new.year)\n\t\tprint(now.year)\n\t\tif (new.year > now.year):\n\t\t\ttBit = 11\n\t\t\tprint (tBit)\n\t\t\tprint(\"you enter th correct date \")\n\t\telif(new.year == now.year and new.month > now.month ):\n\t\t\tprint (\"Same Year but month should be greater\")\n\t\t\ttBit = 22\n\t\t\tprint (tBit)\n\t\telif(new.year == now.year and new.month == now.month and new.day > now.day):\n\t\t\tprint (\"Same year same month but date greates\")\n\t\t\ttBit =33\n\t\t\tprint (tBit)\n\t\telif(new.year == now.year and new.month == now.month and new.day == now.day and b.tm_hour > currentDT.hour):\n\t\t\tprint(\"Year Month Date Same and Hour greates the Current\")\n\t\t\ttBit = 34\n\t\t\tprint(tBit)\n\t\telif(new.year == now.year and new.month == now.month and new.day == now.day and b.tm_hour == currentDT.hour and b.tm_min > currentDT.minute):\n\t\t\tprint(\"Year Month Date Hour Same but minutes greates the Current\")\n\t\t\ttBit = 35\n\t\t\tprint(tBit)\n\t\telse:\n\t\t\tprint (\"you did not enter Correct date and Time\")\n\t\t\tprint (tBit)\n\t\treturn tBit\n\n#FUNCTION THAT SPLIT THE REGISTRATION NUMBER\n\tdef splitString(SplitData):\n\t\tword = SplitData\n\t\tafterSplit = word.split('-')\n\t\tSession = afterSplit[0]\n\t\tDegree = afterSplit[1]\n\t\tRollNo = afterSplit[2]\n\t\tprint(afterSplit)\n\t\treturn afterSplit\n\t\tprint ('Session is',Session , 'DEgree is', Degree ,'RollNo is', RollNo)\n","sub_path":"Without Any Error/app/dateTimeVal.py","file_name":"dateTimeVal.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"518034930","text":"from openpyxl import load_workbook\nfrom openpyxl.styles import Alignment\nwb = load_workbook('MeusNumeros.xlsx')\n\nplanilha = wb['Sheet']\n\nplanilha.unmerge_cells(\"A2:A7\")\nplanilha['B1'] = \"NÚMEROS\"\nplanilha['B1'].alignment = Alignment(horizontal='center')\nwb.save('MeusNumeros.xlsx')","sub_path":"11Documentos/ex12_separar_celulas.py","file_name":"ex12_separar_celulas.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"314264617","text":"import cv2\r\nimport numpy as np\r\n\r\nface_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')\r\n\r\n\r\nclass VideoCamera(object):\r\n def __init__(self):\r\n # capturing video\r\n self.video = cv2.VideoCapture(0)\r\n\r\n def __del__(self):\r\n # releasing camera\r\n self.video.release()\r\n\r\n def get_frame(self):\r\n # extracting frames\r\n succes = False\r\n ret, frame = self.video.read()\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)\r\n max_x, max_y, max_w, max_h = 0, 0, 0, 0\r\n for (x, y, w, h) in face_rects:\r\n if w > max_w and h > max_h:\r\n max_x, max_y, max_w, max_h = x, y, w, h\r\n if max_w > 0 and max_h > 0:\r\n frame = gray[max_y:max_y + max_h, max_x:max_x + max_w]\r\n succes = True\r\n return succes, frame\r\n","sub_path":"Additional Project Files/videocamera.py","file_name":"videocamera.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"325614069","text":"import json\n\nimport paho.mqtt.client as mqtt\n\nimport config\n\nCLIENT_ID = \"Logger\"\n\ndef on_connect(client, userdata, rc):\n print(\"Client connected with result code \"+str(rc))\n client.subscribe(\"$SYS/#\")\n\ndef on_message(client, userdata, msg):\n payload = json.loads(msg.payload)\n print('\\t'.join([\n f'{payload[\"avg\"+str(n)]:.2f}' for n in config.AVG_TIME_PERIODS]))\n\nmqttc = mqtt.Client(client_id=CLIENT_ID)\nmqttc.on_connect = on_connect\nmqttc.message_callback_add(config.AGGREGATE_TOPIC, on_message)\n\nmqttc.connect(config.HOST, config.PORT, 600)\nmqttc.subscribe(config.AGGREGATE_TOPIC)\n\nprint(\"Logging data agregate for the following time periods.\")\nprint('\\t'.join([str(n)+\"min\" for n in config.AVG_TIME_PERIODS]))\n\nmqttc.loop_forever()","sub_path":"mqtt_app/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"158058989","text":"import tensorflow as tf\n\n\ndef rescale_weitghts():\n print()\n\n\nclass BLSTM(tf.keras.layers.Layer):\n def __init__(self, dim):\n super(BLSTM, self).__init__()\n self.lstm = tf.keras.layers.LSTM(dim, go_backwards=True)\n self.linear = tf.keras.layers.Dense(2 * dim * dim)\n\n def call(self, inputs, **kwargs):\n inputs = tf.transpose(inputs, perm=[2, 0, 1])\n x = self.lstm(inputs)[0]\n x = self.linear(x)\n x = tf.transpose(x, perm=[1, 2, 0])\n\n return x\n\n\nclass GLU(tf.keras.layers.Layer):\n def __init__(self):\n super(GLU, self).__init__()\n self.h1 = tf.keras.layers.Conv1D(128, 1)\n self.h1_gates = tf.keras.layers.Conv1D(128, 1)\n self.h1_glu = tf.keras.layers.Multiply()\n\n def call(self, inputs, **kwargs):\n h1 = self.h1(inputs)\n\n\nclass Demucs(tf.keras.Model):\n def __init__(self,\n sources=4,\n channels=64,\n depth=6,\n rewrite=True,\n glu=True,\n upsample=False,\n rescale=0.1,\n kernel_size=8,\n stride=4,\n growth=2.,\n lstm_layers=2,\n context=3):\n super(Demucs, self).__init__()\n self.sources = sources\n self.kernel_size = kernel_size\n self.context = context\n self.stride = stride\n self.depth = depth\n self.upsample = upsample\n self.channels = channels\n\n self.encoder = tf.keras.Sequential()\n self.decoder = tf.keras.Sequential()\n\n self.final = None\n if upsample:\n self.final = tf.keras.layers.Conv1D(sources, 1)\n stride = 1\n\n if glu:\n activation = GLU()\n ch_scale = 2\n else:\n activation = tf.keras.layers.ReLU()\n ch_scale = 1\n\n in_channels = 1\n for idx in range(depth):\n self.encoder.add(tf.keras.layers.Conv1D(channels, kernel_size, stride))\n self.encoder.add(tf.keras.layers.ReLU())\n if rewrite:\n self.encoder.add(tf.keras.layers.Conv1D(ch_scale * channels, 1))\n self.encoder.add(activation)\n\n if idx > 0:\n filters = in_channels\n else:\n if upsample:\n filters = channels\n else:\n filters = sources\n\n if rewrite:\n self.decoder.add(tf.keras.layers.Conv1D(ch_scale * channels, context))\n self.decoder.add(activation)\n\n if upsample:\n self.decoder.add(tf.keras.layers.Conv1D(filters, kernel_size))\n else:\n self.decoder.add(tf.keras.layers.Conv2DTranspose(filters, (1, kernel_size, stride)))\n\n if idx > 0:\n self.decoder.add(tf.keras.layers.ReLU())\n\n in_channels = channels\n channels = int(growth * channels)\n\n if lstm_layers:\n self.lstm = BLSTM(lstm_layers)\n else:\n self.lstm = None\n\n if rescale:\n print()\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"387111523","text":"import unittest\nfrom main import *\n\nclass TestMain(unittest.TestCase):\n def do(self, e, m, ans):\n self.assertEqual(zimbabwe(e, m), ans)\n\n def test_sample(self):\n self.do(321, 3, 5)\n self.do(123, 3, 0)\n self.do(422, 2, 2)\n self.do(12738173912, 7, 11033)\n","sub_path":"zimbabwe/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"443429774","text":"import cv2\nimport numpy as np\nimport ImageUtilities as iu\n\n# Opening the camera\ncamera = cv2.VideoCapture(0)\n\n# get the height and width of the camera feed\nw_v = int(camera.get(3))\nh_v = int(camera.get(4))\n\n# Padding Object for cropping out noise\np = 200\n\nprint(\"height and width: \", h_v, w_v)\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\nwhile True:\n grabbed, feed = camera.read()\n outputImg = feed.copy()\n gray_feed = cv2.cvtColor(feed, cv2.COLOR_BGR2GRAY)\n\n blurred_feed = cv2.GaussianBlur(feed, (7, 7), 1) # Blur the image\n hsv = cv2.cvtColor(blurred_feed, cv2.COLOR_BGR2HSV) # convert to HSV\n\n # Create the red colour mask\n # Lower Red Range\n lower_red = np.array([0, 100, 100])\n upper_red = np.array([10, 255, 255])\n mask1 = cv2.inRange(hsv, lower_red, upper_red)\n\n # Upper red range\n lower_red = np.array([170, 100, 100])\n upper_red = np.array([180, 255, 255])\n mask2 = cv2.inRange(hsv, lower_red, upper_red)\n\n # Generating the final red mask\n red_mask = mask1 + mask2\n\n # Create the yellow colour mask\n lower_yellow = np.array([20, 100, 100], np.uint8)\n upper_yellow = np.array([30, 255, 255], np.uint8)\n yellow_mask = cv2.inRange(hsv, lower_yellow, upper_yellow)\n\n # Create the blue colour mask\n lower_blue = np.array([80, 130, 50])\n upper_blue = np.array([120, 255, 255])\n blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)\n\n kernel = np.ones((3, 3), np.uint8)\n\n # Eroding the color mask\n blue_edges = cv2.erode(blue_mask, kernel, iterations=1)\n yellow_edges = cv2.erode(yellow_mask, kernel, iterations=1)\n red_edges = cv2.erode(red_mask, kernel, iterations=1)\n\n # Detecting the edges of the images\n lower_thres = 50\n upper_thres = 150\n\n red_edges = cv2.Canny(red_mask, lower_thres, upper_thres)\n blue_edges = cv2.Canny(blue_mask, lower_thres, upper_thres)\n yellow_edges = cv2.Canny(yellow_mask, lower_thres, upper_thres)\n black_edges = cv2.Canny(gray_feed, lower_thres, upper_thres)\n\n # Dilating the resulting edges\n # Dilating\n blue_edges = cv2.dilate(blue_edges, kernel, iterations=1)\n yellow_edges = cv2.dilate(yellow_edges, kernel, iterations=1)\n red_edges = cv2.dilate(red_edges, kernel, iterations=1)\n\n # Detecting the contours and displaying them.\n iu.getArrowContours(blue_edges, outputImg, 2000, \"blue\")\n iu.getArrowContours(red_edges, outputImg, 2000, \"red\")\n iu.getArrowContours(yellow_edges, outputImg, 2000, \"yellow\")\n iu.getBoxContours(red_edges, outputImg, 2000, \"red\")\n iu.getTriangleContours(red_edges, outputImg, 2000, \"red\")\n iu.getCrossContours(black_edges, outputImg, 2000, \"Black\")\n\n # Image stacking script that was open sourced\n imgStack = iu.stackImages(\n 0.5, ([feed, gray_feed, hsv], [\n red_mask, yellow_mask, blue_mask],\n [red_edges, yellow_edges, blue_edges],\n [black_edges, outputImg, outputImg]))\n\n # Displays the results\n cv2.imshow(\"Result\", imgStack)\n cv2.imshow(\"Output\", outputImg)\n\n # Closes the camera\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncamera.release()\ncv2.destroyAllWindows()\n","sub_path":"Scientific_Computing_Project.py","file_name":"Scientific_Computing_Project.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"457277514","text":"# 29. Interleaving String\n# 中文English\n# Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.\n#\n# 样例\n# Example 1:\n#\n# Input:\n# \"aabcc\"\n# \"dbbca\"\n# \"aadbbcbcac\"\n# Output:\n# true\n#\n# Example 2:\n# Input:\n# \"\"\n# \"\"\n# \"1\"\n# Output:\n# false\n#\n# Example 3:\n# Input:\n# \"aabcc\"\n# \"dbbca\"\n# \"aadbbbaccc\"\n# Output:\n# false\n#\n# 挑战\n# O(n2) time or better\n\nclass Solution:\n \"\"\"\n @param s1: A string\n @param s2: A string\n @param s3: A string\n @return: Determine whether s3 is formed by interleaving of s1 and s2\n \"\"\"\n\n # A=s1, B=s2, X=s3\n # f[i][j] = X的前i+j个字符是否为A的前i个字符和B的前j个字符交替组成。\n # A的长度为m, B的长度为n,X的长度是m+n\n # 我们看最后一步,假设X是由A和B交错形成的,那么X的最后一个字符X[m+n-1]有两种情况。\n # 情况一:X的最后一个字符X[m + n - 1] 是由A的最后一个字符A[m-1]组成的,那么\n # X[0.....m+n-2] 则由A[0...m-2] 和 B[0...n-1]交错形成的\n # 情况二:X的最后一个字符X[m + n - 1] 是由的最后一个字符B[n-1]组成的,那么\n # X[0.....m+n-2] 则由A[0...m-1] 和 B[0...n-2]交错形成的\n def isInterleave(self, s1, s2, s3):\n # write your code here\n m = len(s1)\n n = len(s2)\n A = s1\n B = s2\n X = s3\n if m + n != len(X):\n return False\n f = [[None] * (n + 1) for _ in range(m + 1)]\n\n for i in range(0, m + 1):\n for j in range(0, n + 1):\n # print(f'i:{i} j:{j}')\n if i == 0 and j == 0:\n f[0][0] = True\n continue\n f[i][j] = False\n # 情况一\n if i > 0 and X[i + j - 1] == A[i - 1] and f[i - 1][j]:\n f[i][j] = True\n # 情况二\n if j > 0 and X[i + j - 1] == B[j - 1] and f[i][j - 1]:\n f[i][j] = True\n\n return f[m][n]\n\n\nsol = Solution()\ns1 = \"abc\"\ns2 = \"a\"\ns3 = \"b\"\nsol.isInterleave(s1, s2, s3)\n\nsol = Solution()\ns1 = \"aabcc\"\ns2 = \"dbbca\"\ns3 = \"aadbbcbcac\"\nsol.isInterleave(s1, s2, s3)\n\n\nclass Solution2:\n \"\"\"\n @param s1: A string\n @param s2: A string\n @param s3: A string\n @return: Determine whether s3 is formed by interleaving of s1 and s2\n \"\"\"\n\n def isInterleave(self, s1, s2, s3):\n # write your code here\n l_1 = len(s1)\n l_2 = len(s2)\n if l_1 + l_2 != len(s3):\n return False\n\n dp = [[False] * (l_2 + 1) for _ in range(l_1 + 1)]\n\n for i in range(0, l_1 + 1):\n for j in range(0, l_2 + 1):\n if i == 0 and j == 0:\n dp[i][j] = True\n continue\n if i == 0:\n dp[0][j] = s2[0:j] == s3[0:j]\n continue\n if j == 0:\n dp[i][0] = s1[0:i] == s3[0:i]\n continue\n if s3[i + j - 1] == s1[i - 1]:\n dp[i][j] = dp[i][j] or dp[i - 1][j]\n\n if s3[i + j - 1] == s2[j - 1]:\n dp[i][j] = dp[i][j] or dp[i][j - 1]\n\n return dp[l_1][l_2]\n","sub_path":"DP/L6/29_interleaving-string.py","file_name":"29_interleaving-string.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"11580107","text":"#! /usr/bin/env python3\n\n# Training new decompounding models using a distributional thesaurus from JoBimText\n\nimport logging\nimport sys\n\nfrom secos import Trainer\n\nlogging.basicConfig(\n format=\"%(asctime)s : %(levelname)s : %(message)s\", level=logging.INFO\n)\n\ntrainer = Trainer(\n pattern=sys.argv[1] if len(sys.argv) > 1 else \".*\",\n split_dash=True if len(sys.argv) > 2 else False,\n)\n\ntrainer.train()\n","sub_path":"generateDecompoundCandidates.py","file_name":"generateDecompoundCandidates.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"54156283","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 20 05:47:02 2018\nExercise 6: Rewrite the program \nthat prompts the user for a list \nof numbers and prints out the maximum and\n minimum of the numbers at the end when\n the user enters \"done\". Write the program \n to store the numbers the user enters in a \n list and use the max()\n and min() functions to compute \n the maximum and minimum numbers \n after the loop completes.\n@author: Hasan\n\"\"\"\nnewlist=list()\nwhile True:\n input_number=input('Enter a Number: ')\n if input_number=='done':\n break\n \n newlist.append(int (input_number))\nprint(newlist)\nprint (max(newlist))\nprint (min(newlist))","sub_path":"maxminlist.py","file_name":"maxminlist.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"552200553","text":"from __future__ import print_function\nimport os\n\n## Import Pytorch and Torchvision. To download please check pytorch.org\nimport torch \nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets import ImageFolder\nfrom torchvision import transforms\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable as torchvar \nimport torch.optim as optim\n\nimport numpy as np\nimport pickle\nimport PIL.Image\nfrom multiprocessing import Pool\nimport time\n\nCUDA_FLAG = torch.cuda.is_available() #Use a GPU if it exists.\n#CUDA_FLAG = 0 #Uncomment this line if you do not want to use the GPU at all. Simultaneously comment the above line. \nif CUDA_FLAG:\n print('Using GPU')\ndef get_patches(img, size = 64): #Function to get patches of images. The patch size is 64x64\n ##First get indices of rows\n # Assumes input image is of shape C X H X W\n w, h = img.shape[2], img.shape[1]\n w_flag, h_flag = w - size, h - size\n col_idx, row_idx = [], []\n col_c, row_c = 0, 0 \n while col_c < w_flag:\n col_idx.append(col_c)\n col_c += size\n col_idx.append(w_flag)\n while row_c < h_flag:\n row_idx.append(row_c)\n row_c += size\n row_idx.append(h_flag)\n patches = np.zeros((len(col_idx)*len(row_idx), 3, size, size), dtype ='float32')\n count = 0 \n for i in row_idx:\n for j in col_idx:\n patch = img[:, i:i+size, j:j+size]\n patches[count] = patch\n count += 1\n #print(patch)\n #print(patches.shape)\n #print(col_idx,row_idx)\n return patches, col_idx, row_idx\n\nclass net(nn.Module):\n def __init__(self):\n super(net, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 32, kernel_size=5, stride=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(32, 64, kernel_size=3),\n nn.ReLU(inplace=True),\n\t\t\t nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(64, 192, kernel_size=3, stride = 1),\n nn.ReLU(inplace=True),\n nn.Conv2d(192, 128, kernel_size=3, stride = 1),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, 128, kernel_size=3, stride = 1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(128 * 3 * 3, 512),\n nn.ReLU(inplace=True),\n )\n \n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0),128*3*3)\n x = self.classifier(x)\n return x\n\nclass perform_test(object):\n def __init__(self, transform, outpath=None):\n self.transform= transform\n self.outpath = outpath\n self.MMD_bneck_layer_t = nn.Sequential(nn.Dropout(),nn.Linear(512, 256), nn.ReLU(inplace=True))\n self.classifier_source = nn.Sequential(nn.Dropout(), nn.Linear(256, 2))\n self.classifier_target = nn.Sequential(nn.Dropout(), nn.Linear(256, 2))\n\n self.Net = net()\n if CUDA_FLAG:\n a = torch.load('models/MMD_Net.pth') \n b = torch.load('models/MMD_bneck_layer_t.pth')\n c = torch.load('models/MMD_ct.pth') \n self.Net.cuda()\n self.MMD_bneck_layer_t.cuda()\n self.classifier_source.cuda()\n self.classifier_target.cuda()\n else:\n a = torch.load('models/MMD_Net.pth', map_location=lambda storage, loc: storage) \n b = torch.load('models/MMD_bneck_layer_t.pth', map_location=lambda storage, loc: storage)\n c = torch.load('models/MMD_ct.pth', map_location=lambda storage, loc: storage)\n self.Net.load_state_dict(a)\n self.MMD_bneck_layer_t.load_state_dict(b)\n self.classifier_target.load_state_dict(c)\n\n def __call__(self, img_name):\n self.Net.eval()\n self.classifier_target.eval()\n self.MMD_bneck_layer_t.eval()\n \n img_t = PIL.Image.open(img_name).convert('RGB')\n if self.transform is not None:\n img_t_new = self.transform(img_t) \n\n img_np = img_t_new.numpy().squeeze()\n patches, col_idx, row_idx = get_patches(img_np)\n ip = torch.from_numpy(patches).float()\n if CUDA_FLAG:\n ip=ip.cuda()\n ip = torchvar(ip) \n out = self.classifier_target(self.MMD_bneck_layer_t(self.Net(ip)))\n out = out.data.cpu().numpy() #Figure out multiplying by classificatioprobability\n prediction = np.argmax(out, 1).astype(np.int32)\n print(sum(prediction))\n if sum(prediction) > 50: #This number is a hyperparamter. If the incoming images are slightly different, vary this number and check.\n return 1 #Tampered\n else:\n return 0 #Non-Tampered\n \n\n\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize(mean=[0.5,0.5,0.5], \n std = [0.225, 0.225, 0.225])])\ntest = perform_test(transform) #Use this test object for testing\n#print(test(\"5620_0.png\"))\n","sub_path":"testfile2.py","file_name":"testfile2.py","file_ext":"py","file_size_in_byte":5311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649487388","text":"from KNearestNeighbor import KNearestNeighbor\nimport numpy\nclass CondensedNearestNeighbor(KNearestNeighbor):\n data = None\n data_set = None\n def run(self,data_set,regression):\n self.data_set = data_set\n original_data = self.data_set.data[0:]\n # init the condensed set to nothing\n condensed_set = []\n # say our last accuracy was 0\n last_accuracy = 0\n print(\"Accuracy on iteration {} {:2.2f}\".format(0, (last_accuracy) * 100))\n # doing batch removal\n last_data = None\n iterations = 0\n # bootstrap process by adding a single point\n original_point = original_data.pop()\n condensed_set.append(original_point)\n degraded = False\n done = False\n accuracy = None\n # stop at 20 iterations regardless\n while iterations != 21:\n # set last data\n last_data = condensed_set[0:]\n # add to iterations\n iterations+=1\n # maintain a list of points to add\n add_list = []\n # set initial index\n index = 0\n while True:\n # empty set, we should end\n if len(original_data) is 0:\n # is empty\n done = True\n break\n # check accuracy, if is wrong, add it to condensed set\n one = original_data[index]\n all = condensed_set\n closest = self.getNearestNeighbor(one,all,1)\n if(self.classify(one[self.data_set.target_location],closest) is 0):\n add_list.append(index)\n index += 1\n # if we don't add any, we are done\n if len(add_list) is 0:\n done = True\n break\n # if we reach our batch of 50, break to add those points\n if (len(add_list) == 50):\n break\n # add and keep track of what we are adding\n add_offset = 0\n for i in add_list:\n condensed_set.append(original_data[i - add_offset])\n del original_data[i-add_offset]\n add_offset += 1\n # get accuracy\n result = self.runTenFold(condensed_set)\n accuracy = result[1] / result[0]\n print(\"Condensed Size: {}\".format(result[0]))\n print(\"Accuracy on iteration {} {:2.2f}\".format(iterations, (accuracy) * 100))\n if done:\n break\n # finished, set final_data\n print(\"Set stopped growing in size, accuracy: {:2.2f}\".format((accuracy) * 100))\n self.final_data = last_data\n","sub_path":"src/CondensedNearestNeighbor.py","file_name":"CondensedNearestNeighbor.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"518857957","text":"import torch\nfrom torch import nn\nfrom torchvision import models\n\n\nclass ImageEncoder(nn.Module):\n def __init__(self, embedding_size, train_all=False):\n super(ImageEncoder, self).__init__()\n self.train_all = train_all\n self.image_model = models.resnext50_32x4d(pretrained=True)\n self.image_model.fc = nn.Linear(self.image_model.fc.in_features, embedding_size)\n self.dropout = nn.Dropout(0.5)\n self.relu = nn.ReLU()\n\n def forward(self, images):\n if not self.train_all:\n for name, param in self.image_model.named_parameters():\n if 'fc.weight' not in name and 'fc.bias' not in name:\n param.requires_grad = False\n return self.dropout(self.relu(self.image_model(images)))\n\n\nclass SequenceDecoder(nn.Module):\n def __init__(self, embedding_size, num_lstms, hidden_size, vocab_size):\n super(SequenceDecoder, self).__init__()\n self.lstm = nn.LSTM(embedding_size, hidden_size, num_lstms, batch_first=True)\n self.fc = nn.Linear(hidden_size, vocab_size)\n\n def forward(self, sequences):\n hidden_states, _ = self.lstm(sequences)\n return self.fc(hidden_states)\n\n\nclass EncoderDecoder(nn.Module):\n def __init__(self, embedding_size, train_all, num_lstms, hidden_size, vocab_size, index_to_string):\n super(EncoderDecoder, self).__init__()\n self.index_to_string = index_to_string\n self.encoder = ImageEncoder(embedding_size, train_all)\n self.decoder = SequenceDecoder(embedding_size, num_lstms, hidden_size, vocab_size)\n self.embedding = nn.Embedding(vocab_size, embedding_size)\n self.dropout = nn.Dropout(0.5)\n\n def forward(self, images, captions):\n image_features = self.encoder(images).unsqueeze(1)\n embeddings = self.dropout(self.embedding(captions))\n embeddings = torch.cat((image_features, embeddings), dim=1)\n return self.decoder(embeddings)\n\n def predict(self, image, max_pred_length):\n prediction = []\n cell_states = None\n\n with torch.no_grad():\n x = self.encoder(image).unsqueeze(0)\n\n for _ in range(max_pred_length):\n hidden_states, cell_states = self.decoder.lstm(x, cell_states)\n out = self.decoder.fc(hidden_states).argmax(-1)\n prediction.append(out.item())\n if self.index_to_string[out.item()] == '':\n break\n x = self.embedding(out)\n prediction = [self.index_to_string[idx] for idx in prediction\n if self.index_to_string[idx] not in ['', '']]\n\n return ' '.join(prediction).replace(\" .\", \".\").replace(\" ,\", \",\")\n","sub_path":"build_model.py","file_name":"build_model.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"360524242","text":"import sys\ninput = sys.stdin.readline\n\nn = int(input())\nstudents = []\n\nfor _ in range(n):\n name, *scores = input().split()\n students.append([name, *list(map(int, scores))])\n\nstudents.sort(key=lambda x: (-x[1], x[2], -x[3], x[0]))\n\nfor student in students:\n print(student[0])","sub_path":"backjoon/10825.py","file_name":"10825.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"55971339","text":"from backlog.model import Story, Backlog\n\n# Stories from g27-culrepo.txt\ns1 = Story(\"s1\", {\"Faculty Member\"}, {\"Repository\", \"Collection\"}, {\"access\"},\n \"As a faculty member, I want to access a collection within the repository\")\ns2 = Story(\"s2\", {\"Library staff\"}, {\"Repository\", \"Material\"}, {\"upload\"},\n \"As a library staff member, I want to upload material to the repository\")\ns3 = Story(\"s3\", {\"Library staff\"}, {\"Metadata\"}, {\"create\"},\n \"As a library staff member, I want to create metadata for items\")\n\n# Obtaining the empty backlog named b:\nb = Backlog.empty().named_as(\"b\")\n\n# Promoting\nb1 = ~s1\nprint(type(s1))\nprint(type(b1))\n\nb = Backlog.empty()\nb += s1\nb += s2\nb += s3\n","sub_path":"samples.py","file_name":"samples.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"572858913","text":"import copy\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport astropy.units as u\nimport ascii_info_new\nimport energistics_new\nimport graphutils_new\nimport hdfutils\nimport windows_directories_new\n\n# Take data greattable and obtain clusters to orbifit (length =/= 0)\nclusters_to_orbifit = []\ntotal_percent_table = hdfutils.hdf5_writer(windows_directories_new.datadir,\n ascii_info_new.flatfork_asciiname).read_table(ascii_info_new.fullgroup,\n \"total_percent_table_greatfitted\")\n\nfor num,clust in enumerate(total_percent_table['cluster']):\n\n if clust not in clusters_to_orbifit:\n\n if clust != -1:\n\n # Only bother if smaller than 10% fraction (i.e. Sgr/etc)\n if total_percent_table[num]['membership_fraction'] < 0.1:\n\n clusters_to_orbifit.append(clust)\n\n# Print it\nprint(\"Orbifitting for \", clusters_to_orbifit)\nimport time\ntime.sleep(10)\n\n# Load in the table, greattable, and so forth.\nwriter = hdfutils.hdf5_writer(windows_directories_new.datadir, ascii_info_new.flatfork_asciiname)\nmembership_table = writer.read_table(ascii_info_new.fullgroup, \"percent_table_greatfitted\")\n\n# Get clustering data and select for relevant data.\nclustering_final = membership_table['greatcircle_probable_clust']\n\n# Grab the data you're going to use\ntable = hdfutils.hdf5_writer(windows_directories_new.datadir,\n ascii_info_new.flatfork_asciiname).read_table(ascii_info_new.fullgroup,\n ascii_info_new.set_raw)\n\n# Prelim clust\nprelim_clust = table['prelim_clust']\n\n# Set up spec-grapher\nspecgrapher = graphutils_new.spec_graph()\n\ndo_clustplots = True\ndo_lbplots = True\ndo_energyplots = True\n\n# Iterate over clusters\nif do_lbplots == True:\n\n savedir = os.path.join(windows_directories_new.imgdir, \"flatfork_lb_plots\")\n\n try:\n os.mkdir(savedir)\n except:\n pass\n for clust in clusters_to_orbifit:\n\n # Grab an orbit fit\n orbifit = energistics_new.orbifitter().flatfork_galpy_final_fitting(table,\n clust,\n 2000,\n 0.3e9,\n 1000,\n True,\n False,\n False,\n False)\n\n # Forward Integral\n forward = copy.deepcopy(orbifit)\n backward = copy.deepcopy(orbifit)\n forward.integrate((np.linspace(0, 1e9, 2000)*u.yr), energistics_new.orbigistics().pot)\n backward.integrate((np.linspace(0, -1e9, 2000)*u.yr), energistics_new.orbigistics().pot)\n llsf, bbsf, llsb, bbsb = forward.ll((np.linspace(0, 0.7e9, 2000)*u.yr)).value, \\\n forward.bb((np.linspace(0, 0.7e9, 2000)*u.yr)).value, \\\n backward.ll((np.linspace(0, -0.15e9, 2000)*u.yr)).value, \\\n backward.bb((np.linspace(0, -0.15e9, 2000)*u.yr)).value\n lls, bbs = np.concatenate([llsf, llsb]), np.concatenate([bbsf, bbsb])\n lls = [d - 360 if d > 180 else d for d in lls]\n\n specgrapher = graphutils_new.spec_graph()\n fig, axs = specgrapher.lb_orbits(table[[True if d == clust\n else False\n for d in clustering_final]],\n 0.3e9, [-180, 180],\n [-90, 90],None,\n line=False,points=4000)\n axs.scatter(lls, bbs, color='lime', marker='o', s=3)\n # Misc axis things\n axs.set_facecolor(\"k\")\n axs.grid(True, which='major', alpha=1, linewidth=0.25, color='white')\n axs.grid(True, which='minor', alpha=1, linewidth=0.25, color='white')\n axs.grid(color=\"white\")\n\n # Savedir\n savepath = os.path.join(savedir,str(clust) + \".png\")\n plt.savefig(savepath, dpi=300, transparent=False)\n plt.close()\n\nif do_energyplots == True:\n\n savedir = os.path.join(windows_directories_new.imgdir, \"flatfork_energy_plots\")\n try:\n os.mkdir(savedir)\n except:\n pass\n prelim_path = os.path.join(savedir, \"flatfork_streamplot_prelim.png\")\n final_path = os.path.join(savedir, \"flatfork_streamplot_final.png\")\n\n specgrapher.energy_plot(table, prelim_clust, clusters_to_orbifit, [str(d) for d in clusters_to_orbifit],\n [-7000, 7000], [-150000, 0], prelim_path,\n mcmillan=False, kpcmyr=False)\n plt.close()\n specgrapher.energy_plot(table, clustering_final, clusters_to_orbifit, [str(d) for d in clusters_to_orbifit],\n [-7000,7000], [-150000,0], final_path,\n mcmillan=False, kpcmyr=False)\n plt.close()\n\nif do_clustplots == True:\n\n savedir = os.path.join(windows_directories_new.imgdir, \"flatfork_clustplots\")\n try:\n os.mkdir(savedir)\n except:\n pass\n\n # Trim noise. TODO: Make it so that we can feed in the clustercount, nice and ordered (to parity colour between two.)\n clustering_final = np.array(clustering_final)\n truefalse = [False if d == -1 else True for d in clustering_final]\n tablee, clustering_final = table[truefalse], clustering_final[truefalse]\n graphutils_new.twod_graph().tripL_colour(tablee, 15, clustering_final, os.path.join(savedir, \"tripL_final.png\"))\n\n plt.close()\n\n clustering_prelim = np.array(prelim_clust)\n truefalse = [False if d == -1 else True for d in clustering_prelim]\n tablee, clustering_prelim = table[truefalse], clustering_prelim[truefalse]\n graphutils_new.twod_graph().tripL_colour(tablee, 15, clustering_prelim, os.path.join(savedir, \"tripL_prelim.png\"))\n\n plt.close()","sub_path":"master-streams/master-streams_new/main_flatfork/windows_plot_orbifits.py","file_name":"windows_plot_orbifits.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41297732","text":"configuration_save = context.restrictedTraverse(configuration_save_url)\n\nconfiguration_save.addConfigurationItem(\"Business Process Configurator Item\",\n title=\"Default Trade Business Process\" ,\n configuration_spreadsheet_data = getattr(context, \"standard_business_process.ods\").data,\n reference=\"default_erp5_business_process\")\n\n# setup Sale Trade Condition\nconfiguration_save.addConfigurationItem(\"Advanced Sale Trade Condition Configurator Item\",\n title=\"General Sale Trade Condition\",\n reference=\"STC-General\")\n\n# setup Purchase Trade Condition\nconfiguration_save.addConfigurationItem(\"Advanced Purchase Trade Condition Configurator Item\",\n title=\"General Purchase Trade Condition\",\n reference=\"PTC-General\")\n\nrule_simulation_list = context.ConfigurationTemplate_readOOCalcFile(\"standard_simulation_rule.ods\", \n data=getattr(context,'standard_simulation_rule.ods').data)\n\nfor rule_dict in rule_simulation_list:\n configuration_save.addConfigurationItem(\"Rule Configurator Item\",\n id = rule_dict['rule_template_id'],\n reference = rule_dict['reference'],\n trade_phase = rule_dict['trade_phase'])\n\n# Create alarms to launch builders. \nconfiguration_save.addConfigurationItem(\"Alarm Configurator Item\",\n title=\"Invoice Builder Alarm\",\n id=\"invoice_builder_alarm\",\n periodicity_minute_frequency=1,\n # A clever solution should be provided for the script\n # bellow\n active_sense_method_id=\"Alarm_buildConfiguratorStandardInvoice\")\n \nconfiguration_save.addConfigurationItem(\"Alarm Configurator Item\",\n title=\"Packing List Builder Alarm\",\n id=\"packing_list_builder_alarm\",\n periodicity_minute_frequency=1,\n # A clever solution should be provided for the script\n # bellow\n active_sense_method_id=\"Alarm_buildConfiguratorStandardPackingList\")\n","sub_path":"bt5/erp5_configurator_ebusiness_lotse/SkinTemplateItem/portal_skins/erp5_configurator_ebusiness_lotse/BusinessConfiguration_setupEBusinessLotseSimulation.py","file_name":"BusinessConfiguration_setupEBusinessLotseSimulation.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323334691","text":"#!/usr/bin/env python3\n\nimport colors\nimport tdl \nfrom random import randint\n\n\n#size of the window\nSCREEN_WIDTH = 80\nSCREEN_HEIGHT = 50\n\n\n#Size of map\nMAP_WIDTH = 80\nMAP_HEIGHT = 45\n\n\n\nROOM_MAX_SIZE = 10\nROOM_MIN_SIZE = 6\nMAX_ROOMS = 30\n\n#FOV\ncolor_dark_wall = (0, 0, 0)\ncolor_light_wall = (160, 160, 180)\ncolor_dark_ground = (224, 224, 224)\ncolor_light_ground = (255,255, 150)\n\nFOV_ALGO ='BASIC'\nFOV_LIGHT_WALLS = True\nTORCH_RADIUS = 10\n\n#Map\n#------------------------------------------------------------------------\nclass Tile:\n #a tile of the map and its properties\n def __init__(self, blocked, block_sight= None): \n self.blocked = blocked\n self.explored = False\n if block_sight is None:\n block_sight = blocked\n self.block_sight = block_sight\n\n#Function to make map\ndef make_map():\n global my_map\n \n \n\n\n #fill map with \"unblcoked\" tiles\n\n my_map = [[Tile(True) for y in range(MAP_HEIGHT)] for x in range(MAP_WIDTH)]\n \n rooms = []\n num_rooms = 0\n \n for r in range(MAX_ROOMS):\n #random witdh and height\n w = randint(ROOM_MIN_SIZE,ROOM_MAX_SIZE)\n h = randint(ROOM_MIN_SIZE,ROOM_MAX_SIZE)\n #random position without going out of the boundaries of the map\n x=randint(0,MAP_WIDTH-w-1)\n y=randint(0,MAP_HEIGHT-h-1)\n\n #Rect class makes rectangles easier towork with\n new_room = Rect(x,y,w,h)\n \n failed = False\n for other_room in rooms:\n if new_room.intersect(other_room):\n failed = True\n break\n\n if not failed:\n #This means that no intersection was found and therefore this room is valid\n #\"paint\" the room with tiles\n create_room(new_room)\n\n #center coordinates of new room, will be used for later\n (new_x,new_y) = new_room.center()\n\n if num_rooms == 0:\n #This is the first room where the player starts at\n player.x = new_x\n player.y = new_y\n else:\n #all rooms after the first\n #connect it to the previous with a tunnel\n\n #center coordinates of previous room\n (prev_x,prev_y) = rooms[num_rooms-1].center()\n #draw a coin (either 1 or 0)\n if randint(0,1):\n #First move horizontally, then vertically\n create_h_tunnel(prev_x, new_x, prev_y)\n create_v_tunnel(prev_y, new_y, new_x)\n else:\n #first move vertically then horizontally\n create_v_tunnel(prev_y, new_y, new_x)\n create_h_tunnel(prev_x, new_x, prev_y)\n #finall, append the new room to the list\n place_objects(new_room)\n rooms.append(new_room)\n num_rooms +=1\n \n\n\n\n#Go through all tiles and set their background color\ndef render_all():\n global fov_recompute\n global visible_tiles\n\n if fov_recompute:\n #recompute FOV if needed (the player moved or something)\n fov_recompute = False\n visible_tiles = tdl.map.quickFOV(player.x, player.y,is_visible_tile,fov=FOV_ALGO,radius=TORCH_RADIUS,lightWalls=FOV_LIGHT_WALLS)\n\n for y in range(MAP_HEIGHT):\n for x in range(MAP_WIDTH):\n visible = (x,y) in visible_tiles\n wall = my_map[x][y].block_sight\n if not visible:\n if my_map[x][y].explored:\n #if it's not visible right now, the player can only see\n if wall:\n con.draw_char(x, y, None, fg=None, bg=color_dark_wall)\n else:\n con.draw_char(x, y, None, fg=None, bg=color_dark_ground)\n else: \n #It's visible\n if wall:\n con.draw_char(x,y, None, fg= None, bg=color_light_wall)\n else:\n con.draw_char(x, y, None, fg=None, bg=color_light_ground)\n #Since it's visible,explore it\n my_map[x][y].explored = True\n\n for obj in objects:\n obj.draw()\n \n root.blit(con,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,0,0)\n\n\n\n\n#Game Object \n#-----------------------------------------------------------------------------------------------------------------\nclass GameObject:\n #This is a generic object: the player, a monster, an item\n #It's always represented by a character on screen\n def __init__(self, x, y, char,name, color,blocks=False):\n self.x = x\n self.y = y\n self.char = char\n self.color = color\n self.name = name\n self.blocks = blocks\n\n\n\n def move(self,dx,dy):\n #move by the given amount\n if not is_blocked(self.x + dx, self.y + dy):\n self.x += dx\n self.y += dy\n\n def draw(self):\n global visible_tiles\n #draw the character that represents this object at its position\n if (self.x, self.y) in visible_tiles:\n con.draw_char(self.x, self.y, self.char, self.color, bg=None)\n\n def clear(self):\n #Erase the character that represents this object\n con.draw_char(self.x, self.y, ' ', self.color, bg=None)\n\n \n\n\n\n\n\n#\n#-----------------------------------------------------------------------------------------------\n# Function to deal with key presses\ndef handle_keys():\n global playerx,playery\n global fov_recompute\n\n user_input = tdl.event.key_wait()\n \n if game_state =='playing':\n if user_input.key == 'ENTER' and user_input.alt:\n #Toggle fullscreen\n tdl.set_fullscreen(not tdl.get_fullscreen())\n \n elif user_input.key == 'ESCAPE':\n return 'exit'\n \n if user_input.key == 'UP':\n player.move(0,-1)\n fov_recompute = True\n elif user_input.key == 'DOWN':\n player.move(0,1)\n fov_recompute = True\n elif user_input.key == 'LEFT':\n player.move(-1,0)\n fov_recompute = True\n elif user_input.key == 'RIGHT':\n player.move(1,0)\n fov_recompute = True\n else:\n return 'didnt-take-turn'\n \n\n\n\n\n#Dungeon Building Blocks\n#------------------------------------------------------------------------------\nclass Rect:\n #A rectangle on the map, used to characterize a room\n def __init__(self, x, y, w, h):\n self.x1 = x\n self.y1 = y\n self.x2 = x + w\n self.y2 = y + h\n\n def center(self):\n center_x = (self.x1 + self.x2) // 2\n center_y = (self.y1 + self.y2) // 2\n return (center_x,center_y)\n \n def intersect(self, other):\n #return true if this rectangle intersects with another one\n return (self.x1 <= other.x2 and self.x2 >= other.x1 and self.y1<=other.y2 and self.y2 >= other.y1)\n\ndef create_room(room):\n global my_map\n #go through the tiles in the rectangle and make them passable\n for x in range(room.x1+1,room.x2):\n for y in range(room.y1+1,room.y2):\n my_map[x][y].blocked = False\n my_map[x][y].block_sight= False\n #The +1 at then end takes care of the issue of python range function being right parameter exclusive\n \ndef create_h_tunnel(x1, x2, y):\n global my_map\n for x in range(min(x1, x2), max(x1, x2) + 1):\n my_map[x][y].blocked = False\n my_map[x][y].block_sight = False\n\ndef create_v_tunnel(y1, y2, x):\n global my_map\n #vertical tunnel\n for y in range(min(y1, y2), max(y1, y2) + 1):\n my_map[x][y].blocked = False\n my_map[x][y].block_sight = False\n\ndef is_blocked(x,y):\n if my_map[x][y].blocked:\n return True\n\n for obj in objects:\n if obj.blocks and obj.x == x and obj.y == y:\n return True\n return False\n\n\n\n\n\n#Field of View\n#----------------------------------------------------------\nfov_recompute = True\ndef is_visible_tile(x, y):\n global my_map\n \n if x >= MAP_WIDTH or x < 0:\n return False\n elif y >= MAP_HEIGHT or y < 0:\n return False\n elif my_map[x][y].blocked == True:\n return False\n elif my_map[x][y].block_sight == True:\n return False\n else:\n return True\n\n\n\nMAX_ROOM_MONSTERS = 3\n#Preparing for combat \n#----------------------------------------------------------\ndef place_objects(room):\n #choose random number of monsters\n num_monsters = randint(0, MAX_ROOM_MONSTERS)\n \n for i in range(num_monsters):\n #choose random spot for this monster\n x = randint(room.x1, room.x2)\n y = randint(room.y1, room.y2)\n if not is_blocked(x, y):\n choice = randint(0, 100)\n if choice < 20: \n #create an orc\n monster = GameObject(x, y, 'o', 'orc',colors.desaturated_green)\n elif choice < 20+40:\n #create a troll\n monster = GameObject(x, y, 'T', 'troll',colors.darker_green)\n elif choice < 20+40+10:\n #create a drunk dwarf\n monster = GameObject(x,y,'d','drunk dwarf',colors.azure)\n else:\n #create a goblin\n monster = GameObject(x,y,'g','Goblin',colors.green)\n\n objects.append(monster)\n\n\n\n\n\n#Initialization \n#----------------------------------------------------------\nroot = tdl.init(SCREEN_WIDTH,SCREEN_HEIGHT,title='Roguelike',fullscreen=False)\ncon = tdl.Console(SCREEN_WIDTH, SCREEN_HEIGHT)\n\n\n#create object representing the player\nplayer = GameObject(0, 0, '@', 'player', colors.black, blocks=True)\n \n#the list of objects starting with the player\nobjects = [player]\n\n\nmake_map()\n\n\n\n\ngame_state = 'playing'\nplayer_action = None \n\n#Main loop.\n\n#-------------------------------------------------------------------------\n#MAIN LOOP\n#-------------------------------------------------------------------------\nwhile not tdl.event.is_window_closed():\n render_all()\n\n tdl.flush()\n\n #erase all objects at their old locations, before they move\n for obj in objects:\n obj.clear()\n\n player_action = handle_keys()\n if player_action == 'exit':\n break\n if game_state == 'playing' and player_action != 'didnt-take-turn':\n for obj in objects:\n if obj != player:\n print(\"The \"+obj.name+' growls!')\n","sub_path":"roguelike.py","file_name":"roguelike.py","file_ext":"py","file_size_in_byte":10395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"373603977","text":"import pygame\n\npygame.init()\n\n\nsize =(900,600)\nscreen = pygame.display.set_mode(size)\nscreen.fill((250,250,250))\n\n#\t\tpygame.init()\n\n#\t\tself.screen = pygame.display.set_mode(size)\n\n#\t\tself.font = pygame.font.font(None ,30)\n\n\t\t\ndone = False\n\nclass Player:\n\tdef __init__(self,name,kleur,x,y,r):\n\t\tself.name = name\n\t\tself.kleur = kleur\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.r = r\n\n\tdef draw(self,screen):\n\t\tpygame.draw.circle(screen,self.kleur,(int(self.x),int(self.y)),int(self.r))\n\ndef Update(key,player):\n\tif key == pygame.K_LEFT:\n\t\tscreen.fill((250, 250, 250))\n\t\tplayer.x -= 40\n\t\tplayer.draw(screen)\n\telif key == pygame.K_RIGHT:\n\t\tscreen.fill((250, 250, 250))\n\t\tplayer.x += 40\n\t\tplayer.draw(screen)\n\telif key == pygame.K_UP:\n\t\tscreen.fill((250, 250, 250))\n\t\tplayer.y -= 40\n\t\tplayer.draw(screen)\n\telif key == pygame.K_DOWN:\n\t\tscreen.fill((250, 250, 250))\n\t\tplayer.y += 40\n\t\tplayer.draw(screen)\n\nclass Turn:\n\tdef __init__(self,players):\n\t\tself.players = players\n\n\nplayer1 = Player(\"A\",(155,255,140),300,30,13)\nplayer2 = Player(\"B\",(155,255,140),340,30,13)\nplayer3 = Player(\"C\",(91,183,211),380,30,13)\nplayer4 = Player(\"D\",(116,59,124),420,30,13)\nplayer5 = Player(\"E\",(237,65,56),460,30,13)\nplayer6 = Player(\"F\",(0,0,0),500,30,13)\n\nplayers = [player1,player2,player3]\nturn = Turn(players)\n\nfor x in turn.players:\n\tprint(x.name)\n\nwhile not done:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tdone = True\n\t\tif event.type == pygame.KEYDOWN:\n\t\t\tUpdate(event.key,player1)\n\n\n\t#player draw\n\tplayer1.draw(screen)\n\tplayer2.draw(screen)\n\tplayer3.draw(screen)\n\tplayer4.draw(screen)\n\tplayer5.draw(screen)\n\tplayer6.draw(screen)\n\n\tpygame.display.flip()\n\n\n\t\n\n\t\t","sub_path":"PythonApplication19/PythonApplication19/PythonApplication19.py","file_name":"PythonApplication19.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115101760","text":"from django.conf.urls import url \nfrom django.urls import path\nfrom signup import views \nfrom django.views.generic import TemplateView\n \nurlpatterns = [ \n path('registeruser', views.signuprequest),\n path('registertherapist', views.signuptherapistrequest),\n path('login', views.login),\n path('gettherapists', views.getalltherapists),\n path('gettherapist', views.istherapist),\n path('updatetherapist',views.updatetherapist),\n path('gettherapistsessions',views.getalltherapistsessions),\n path('getusersessions',views.getallusersessions),\n path('addsession',views.addSession)\n \n]","sub_path":"backend/signup/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318820378","text":"#! python3\n\nimport urllib.parse\nimport requests\n\nmain_api = \"https://maps.googleapis.com/maps/api/geocode/json?\"\naddress = \"san jose\"\nkey = \"AIzaSyCUR-QnwDM8Rk65KpX_OA8X6xQcAhclue4\"\nurl = main_api + urllib.parse.urlencode({\"address\": address, \"key\": key})\n\njson_data = requests.get(url).json()\n","sub_path":"08_parse-json1.py","file_name":"08_parse-json1.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"64866774","text":"from typing import List\n\n\ndef createDict():\n with open(\"C2ImportUsersSample.csv\", 'r') as file:\n file = file.readlines()\n\n people = {}\n\n for line in file:\n x = line.split(',')\n username = x[2]\n people[username] = {\n \"first name\": x[0],\n \"last name\": x[1],\n \"password\": x[3],\n \"email\": x[4],\n \"phone\": x[5],\n \"passport\": x[6],\n \"groups\": x[7],\n \"usercode\": x[8],\n \"title\": x[9],\n \"address 1\": x[10],\n \"address 2\": x[11],\n \"city\": x[12],\n \"state\": x[13],\n \"zip code\": x[14]\n }\n return people\n\ndef main():\n people = createDict()\n username = input(\"Enter the username of the person you wish to get info on: \")\n if username in people:\n info = input(\"What information do you want about them?: \")\n if info in people[username]:\n print(\"Okay, here's information on \" + username + \": \")\n print(info + \": \" + people[username][info])\n main()\n else:\n print(\"wut? \")\n main()\n else:\n print(\"That person doesn't exist. GTFO here.\")\n main()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"addrBook.py","file_name":"addrBook.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"588550868","text":"# 6. Необходимо создать (не программно) текстовый файл,\n# где каждая строка описывает учебный предмет и наличие лекционных,\n# практических и лабораторных занятий по этому предмету и их количество.\n# Важно, чтобы для каждого предмета не обязательно были все типы занятий.\n# Сформировать словарь, содержащий название предмета и общее количество занятий по нему.\n# Вывести словарь на экран.\n#\n# Примеры строк файла:\n# Информатика: 100(л) 50(пр) 20(лаб).\n# Физика: 30(л) — 10(лаб)\n# Физкультура: — 30(пр) —\n#\n# Пример словаря:\n# {“Информатика”: 170, “Физика”: 40, “Физкультура”: 30}\nimport re\n\nmy_file = open(\"task_06_file.txt\", \"r\", encoding='utf-8')\ndata_list = []\nresult = {}\n\n\n# функция поиска названия предмета из строки\ndef find_subject(string_line):\n return string_line[:string_line.find(\":\")]\n\n\n# функция поиска в строке времени занятий и их суммирования для данного предмета\ndef hours_sum(string_line):\n sum_result = 0\n # получаем список элементов с пробелами и скобками (признак указания часов)\n # использую регулярное выражение для поиска такого набора:\n # сначала пробел, потом любое количество цифр, а затем символ \"(\"\n dirty_list = re.findall(r' \\d+\\(', string_line)\n for item in dirty_list:\n # очищаем от начального пробела и завершающей скобки, а потом суммируем:\n sum_result += float(item[1:-1])\n return sum_result\n\n\nprint('Начальные данные из файла:')\nfor line in my_file:\n print(line.rstrip())\n # читаем строки из файла, удаляем последний символ в строке \"\\n\"\n # и помещаем в список data_list\n data_list.append(line.rstrip())\n\nfor line in data_list:\n # наполняем итоговый словарь\n result.update({find_subject(line): hours_sum(line)})\n\nprint(f'\\nИтоговый словарь: \\n{result}')\n\nmy_file.close()\n","sub_path":"lesson-05/task_06.py","file_name":"task_06.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"329641110","text":"from distutils.core import setup, Extension\nimport sys, os, numpy\n\nfrom distutils.command.install import install\n\nnumpy_include = os.path.join(os.path.dirname(numpy.__file__), \"core\", \"include\", \"numpy\")\nprint(numpy_include)\n\ndbr_lib_dir = r'e:\\Program Files (x86)\\Dynamsoft\\Barcode Reader 6.1\\Components\\C_C++\\Lib'\ndbr_dll = r'e:\\Program Files (x86)\\Dynamsoft\\Barcode Reader 6.1\\Components\\C_C++\\Redist\\x64\\DynamsoftBarcodeReaderx64.dll'\n\nmodule_dbr = Extension('dbr', sources=['dbr.c'], include_dirs=[\n numpy_include], library_dirs=[dbr_lib_dir], libraries=['DBRx64'])\n\nclass CustomInstall(install):\n def run(self):\n install.run(self)\n import shutil\n from distutils.sysconfig import get_python_lib\n src = dbr_dll\n dst = get_python_lib()\n shutil.copy2(src, dst)\n\nsetup(name='dbr',\n version='6.1',\n description='Python barcode extension',\n author='Xiao Ling',\n author_email='xiao@dynamsoft.com',\n url='https://www.dynamsoft.com/Products/Dynamic-Barcode-Reader.aspx',\n license = 'https://www.dynamsoft.com/Products/barcode-reader-license-agreement.aspx',\n ext_modules=[module_dbr],\n long_description='Dynamsoft Barcode Reader is a software development toolkit which enables barcode recognition of Code 39, Code 129, QR Code, DataMatrix, PDF417.',\n platforms=['Windows'],\n cmdclass={'install': CustomInstall}\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"105305137","text":"# Source: https://pymotw.com/2/socket/udp.html\n\nimport socket, sys, time\n\nhost = sys.argv[1]\ntextport = sys.argv[2]\nn = sys.argv[3]\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nport = int(textport)\nserver_address = (host, port)\n\nd= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\np = 1007\nsa = ('localhost', p)\nd.bind(sa)\n\n\ni = 1\nwhile 1:\n \n while(i<=int(n)): \n data = \"Message \" + str(i)\n if not len(data):\n break\n# s.sendall(data.encode('utf-8'))\n s.sendto(data.encode('utf-8'), server_address)\n while True:\n buf, address = d.recvfrom(port)\n if not len(buf):\n break\n print (\"Received %s bytes from %s %s: \" % (len(buf), address, buf ))\n break\n i= i + 1\n break\n s.shutdown(1)\n","sub_path":"udpSender-V2.py","file_name":"udpSender-V2.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"501122140","text":"# -*- coding:utf-8 -*-\n\n\nfrom poker.protocol.rpccore import markRpcCall\nfrom poker.entity.configure import gdata\nfrom freetime.util import log as ftlog\n\n@markRpcCall(groupName=\"roomId\", lockName=\"\", syncCall=1)\ndef getTableByRoomId(roomId):\n \"\"\" \n * UT调用,需要处理完之后返回消息给UT\n \"\"\"\n from majiang2.entity.create_table_list import CreateTable\n room = gdata.rooms().get(roomId, None)\n if not room:\n ftlog.info('getTableByRoomId, room is null:', roomId)\n return 0\n table_list = [] \n for table in room.maptable.values():\n table_list.append([table.realPlayerNum, table])\n table_list = sorted(table_list, reverse=True)\n ftlog.debug('===getTableByRoomId===table_list=', table_list)\n return CreateTable.get_create_table_from_table_list(table_list)\n\n","sub_path":"majiang2/src/majiang2/servers/table/rpc/table_rpc.py","file_name":"table_rpc.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"428133237","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\nfrom keras.models import Model,Input,load_model\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers import Dense,Activation\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport sys\nsys.path.append('../')\nfrom model_change_standard import accuracy_mnist\n\n\nmnist = input_data.read_data_sets(\"../MNIST_data/\", one_hot=True)\n\n\ndef model_dnn_3():\n #train:0.8596\n #test:0.9308\n input_data=Input((28*28,))\n temp_data=Dense(128)(input_data)\n temp_data=Activation('relu')(temp_data)\n temp_data=Dense(64)(temp_data)\n temp_data=Activation('relu')(temp_data)\n temp_data=Dense(48)(temp_data)\n temp_data=Activation('relu')(temp_data)\n temp_data=Dense(10)(temp_data)\n output_data=Activation('softmax')(temp_data)\n model=Model(inputs=[input_data],outputs=[output_data])\n modelcheck=ModelCheckpoint('model/model.hdf5',monitor='loss',verbose=1,save_best_only=True)\n model.compile(loss='categorical_crossentropy',optimizer='adadelta',metrics=['accuracy'])\n model.fit([mnist.train.images],[mnist.train.labels],batch_size=256,epochs=1,callbacks=[modelcheck],validation_data=(mnist.test.images,mnist.test.labels))\n print('acc:{}'.format(accuracy_mnist(model,mnist)))\n\nif __name__=='__main__':\n #model_dnn_3()\n model_path='./model/model.hdf5'\n model=load_model(model_path)\n print('acc:{}'.format(accuracy_mnist(model,mnist)))\n","sub_path":"DNNmutation-master/DNNmutation-master/Exp_cover/demo_DNN_mnist.py","file_name":"demo_DNN_mnist.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"84722455","text":"\"\"\" This script was used to parse the log file and get the sound timing from\nthe log instead of from the triggers\n\"\"\"\n\nimport os\nimport os.path as op\nimport numpy as np\nfrom psychopy.misc import fromFile\nimport glob\nfrom pandas import DataFrame\n\ndata_path = op.join('/media/jrking/harddrive/Audio_sequence/data/NY523/',\n 'NY523_AudioSequence/')\nieeg = 'NYU523_AudioSequence_complete_morning_clin1.edf'\nbehavior = 'NYU523_AudioSequence_complete_morning_clin1.edf'\nlog_path = op.join(data_path, 'Log_files', 'NY523_morning',\n '2016-02-14_10-32-43')\nlog_fname = op.join(log_path, 'NY523_2016-02-14_10-32-43.log')\nos.listdir(log_path)\n\n\n# Load log files\nall_trials = list()\nfor run in range(20):\n # Find run\n fname = glob.glob(log_path + '/*_%i_finished*.pydat.psydat' % run)\n if not len(fname):\n continue\n run = fromFile(fname[0])\n all_trials += run.entries\n\n# ############ get relative onset of each sound in each trial #################\n# --- parse sound timing\nall_sounds = list()\nfor trial_id, trial in enumerate(all_trials):\n sound_info = dict()\n if trial['task'] == 'localizer':\n this_sound = dict(sound=trial['sound'], onset=trial['onset'],\n trial_id=trial_id, task=trial['task'], sound_id=0,\n ttl=trial['trigger_value'], time=trial['trigger_on'])\n all_sounds.append(this_sound)\n elif trial['task'] == 'main':\n for TP in ['target', 'probe']:\n for sound_id in range(trial['n_sounds']):\n this_sound = dict(sound=trial[TP][sound_id], sound_id=sound_id,\n onset=trial['%s_time' % TP][sound_id],\n trial_id=trial_id, task=trial['task'],\n ttl=trial['trigger_value_%s' % TP][sound_id],\n time=trial['trigger_on_%s' % TP][sound_id])\n all_sounds.append(this_sound)\nall_sounds = DataFrame(all_sounds)\n\nlog = tuple(open(log_fname, 'r'))\nlog = [line.strip('\\n').split(' \\t') for line in log]\ntrials_start = list()\ntrial_typ = None\nrun = -1\ntrial_id = -1\nsound_id = 0\nlast_start = 0\nTP = 'probe'\n\nfor line in log:\n if len(line) < 3:\n continue\n time, typ, value = line[:3]\n\n # Detect trial type\n if typ == 'DEBUG':\n if value[:10] == 'task: main':\n trial_typ = 'main'\n run += 1\n elif value[:15] == 'task: localizer':\n trial_typ = 'localizer'\n run += 1\n continue\n\n # Detect new trial\n elif typ == 'EXP':\n if value[:9] == 'New trial':\n trial_id += 1 # increment trial #\n sound_id = 0 # reset sound #\n\n # Find sound start for localizer\n if trial_typ == 'localizer':\n trials_start.append(dict(start=last_start, run=run,\n task=trial_typ, trial_id=trial_id,\n sound_id=sound_id))\n continue\n # Find sound start for main\n if value[:14] == 'Sound started':\n # localizer start before all trials whereas\n # main start at each trial.\n last_start = float(time)\n if trial_typ == 'main':\n # only add target in main, else double # of trials\n TP = 'target' if TP == 'probe' else 'probe'\n if TP == 'probe':\n continue\n trials_start.append(dict(start=last_start, run=run,\n task=trial_typ, trial_id=trial_id,\n sound_id=sound_id))\n sound_id += 1\ntrials_start = DataFrame(trials_start)\n\n# Combine relative sound onsets and trial sound start\ntimes = []\nfor sound_id, this_sound in all_sounds.iterrows():\n loc = np.where(trials_start['trial_id'] == this_sound['trial_id'])[0]\n start = trials_start['start'][loc]\n times.append(float(this_sound['onset'] + start))\nall_sounds['time'] = times\n","sub_path":"scripts/sandbox/parse_log.py","file_name":"parse_log.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"179125355","text":"# -*- coding: utf-8 -*-\n\nBOT_NAME = 'rent_crawler'\n\nSPIDER_MODULES = ['rent_crawler.spiders']\nNEWSPIDER_MODULE = 'rent_crawler.spiders'\n\nUSER_AGENT = \\\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'\n\n# CONCURRENT_REQUESTS = 32\n\nAUTOTHROTTLE_ENABLED = True\nAUTOTHROTTLE_DEBUG = True\n\nDOWNLOAD_DELAY = 1\n\nTELNETCONSOLE_ENABLED = False\nEXTENSIONS = {\n 'scrapy.extensions.telnet.TelnetConsole': None,\n}\n\nITEM_PIPELINES = {\n 'scrapy_mongodb.MongoDBPipeline': 300,\n 'rent_crawler.pipelines.ApartmentPicturesPipeline': 1\n}\n\nMONGODB_DATABASE = 'rent'\nMONGODB_COLLECTION = 'places'\nMONGODB_UNIQUE_KEY = 'code'\n\n# LOG_STDOUT = True\n# LOG_FILE = 'spider_log.txt'\n\nIMAGES_STORE = 'pictures/'\n\nCLOSESPIDER_ITEMCOUNT = 100\n","sub_path":"rent_crawler/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"459723901","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport requests\nimport json\n\nclass telegram():\n tg_url_bot_general = \"https://api.telegram.org/bot\"\n\n def http_get(self, url):\n res = requests.get(url, proxies=self.proxies)\n answer = res.text\n # answer_json = json.loads(answer.decode('utf8'))\n answer_json = json.loads(answer)\n return answer_json\n\n def __init__(self, key, chat_id):\n self.debug = False\n self.key = key\n self.to = chat_id\n self.proxies = {}\n self.type = \"private\" # 'private' for private chats or 'group' for group chats\n self.markdown = False\n self.html = False\n self.disable_web_page_preview = False\n self.disable_notification = False\n self.reply_to_message_id = 0\n self.tmp_uids = None\n\n def get_me(self):\n url = self.tg_url_bot_general + self.key + \"/getMe\"\n me = self.http_get(url)\n return me\n\n def get_updates(self):\n url = self.tg_url_bot_general + self.key + \"/getUpdates\"\n if self.debug:\n print(url)\n updates = self.http_get(url)\n if self.debug:\n print(\"Content of /getUpdates:\")\n print(updates)\n if not updates[\"ok\"]:\n print(updates)\n return updates\n else:\n return updates\n\n def message(self, message):\n url = self.tg_url_bot_general + self.key + \"/sendMessage\"\n # message = \"\\n\".join(message)\n params = {\"chat_id\": self.to, \"text\": message, \"disable_web_page_preview\": self.disable_web_page_preview,\n \"disable_notification\": self.disable_notification}\n if self.reply_to_message_id:\n params[\"reply_to_message_id\"] = self.reply_to_message_id\n if self.markdown or self.html:\n parse_mode = \"HTML\"\n if self.markdown:\n parse_mode = \"Markdown\"\n params[\"parse_mode\"] = parse_mode\n if self.debug:\n print(\"Trying to /sendMessage:\")\n print(url)\n print(\"post params: \" + str(params))\n res = requests.post(url, params=params, proxies=self.proxies)\n answer = res.text\n # answer_json = json.loads(answer.decode('utf8'))\n answer_json = json.loads(answer)\n if not answer_json[\"ok\"]:\n print(answer_json)\n return answer_json\n else:\n return answer_json\n\nif __name__ == \"__main__\":\n chat_id = '1067694510'\n chat_token = '1170626384:AAHqMP6KYeVPEsQjbwJrB3TN240tfayxv_s'\n\n tg = telegram(chat_token, chat_id)\n result = tg.message(\"hello my friend!!!\")\n print(result)\n","sub_path":"telegram_bot.py","file_name":"telegram_bot.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"498838631","text":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\n\n# Input data files are available in the \"../input/\" directory.\n# For example, runninga this (by clicking run or pressing Shift+Enter) will list the files in the input directory\nimport pandas as pd\nimport numpy as np\nfrom sklearn import ensemble, tree, linear_model\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.metrics import r2_score, mean_squared_error, make_scorer\nfrom sklearn.utils import shuffle\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegression, RidgeCV, LassoCV, ElasticNetCV\nfrom sklearn.linear_model import Lasso\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\ntrain = pd.read_csv(r'CloudApp\\Data\\cleansed_listings.csv')\ntrain = train[train.total_price > 0]\n\n\n\ndataCols = [\n'beds'\n,'amenities_tv_ind'\n,'amenities_cable_tv_ind'\n,'amenities_internet_ind'\n,'amenities_wifi_ind'\n,'amenities_kitchen_ind'\n,'amenities_paid_park_off_ind'\n,'amenities_free_park_on_ind'\n,'amenities_heating_ind'\n,'nb_num'\n,'rt_num'\n]\n\ntrain['neighbourhood'] = train['neighbourhood'].astype('category')\ntrain['property_type'] = train['property_type'].astype('category')\ntrain['room_type'] = train['room_type'].astype('category')\n\ntrain['nb_num'] = train['neighbourhood'].cat.codes\ntrain['pt_num'] = train['property_type'].cat.codes\ntrain['rt_num'] = train['room_type'].cat.codes\n\n\nnumerical_features = train[dataCols].columns\ntrain_num = train[numerical_features]\ntrain_cat = train[categorical_features]\n\n# Handle remaining missing values for numerical features by using median as replacement\ntrain_num = train_num.fillna(train_num.median())\n\ntrain2 = train_num\n\ntrain['beds'] = train['beds'].fillna(train['beds'].median())\n\n\n#split the data to train the model \n\nX_train,X_test,y_train,y_test = train_test_split(train2,train['total_price'],test_size = 0.2,random_state= 0)\n\nX_train.shape,X_test.shape,y_train.shape,y_test.shape\n\n\n#defining cross validation\nn_folds = 5\nfrom sklearn.metrics import make_scorer\nfrom sklearn.model_selection import KFold\nscorer = make_scorer(mean_squared_error,greater_is_better = False)\ndef rmse_CV_train(model):\n kf = KFold(n_folds,shuffle=True,random_state=42).get_n_splits(train.values)\n rmse = np.sqrt(-cross_val_score(model,X_train,y_train,scoring =\"neg_mean_squared_error\",cv=kf))\n return (rmse)\ndef rmse_CV_test(model):\n kf = KFold(n_folds,shuffle=True,random_state=42).get_n_splits(train.values)\n rmse = np.sqrt(-cross_val_score(model,X_test,y_test,scoring =\"neg_mean_squared_error\",cv=kf))\n return (rmse)\n\n\n\n\nlasso = Lasso(alpha=0.0001, max_iter=10e5)\nlasso.fit(X_train,y_train)\ntrain_score=lasso.score(X_train,y_train)\ntest_score=lasso.score(X_test,y_test)\ncoeff_used = np.sum(lasso.coef_!=0)\n\ncomb = pd.read_csv(r'CloudApp\\Data\\SQLAExport.txt')\ndataCols = [\n'nb_num'\n,'rt_num'\n,'beds'\n,'amenities_tv_ind'\n,'amenities_cable_tv_ind'\n,'amenities_internet_ind'\n,'amenities_wifi_ind'\n,'amenities_kitchen_ind'\n,'amenities_paid_park_off_ind'\n,'amenities_free_park_on_ind'\n,'amenities_heating_ind'\n]\ncomb = comb[dataCols]\n\n\ncomb['predict_val'] = lasso.predict(comb)\n\n#FILE OF PERMUTATIONS AND PREDICTED VALUES.\nfile_name = r'CloudApp\\Data\\output.csv'\ncomb.to_csv(file_name, sep=',', encoding='utf-8')\n\n","sub_path":"Code/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"188323488","text":"# 在实际调试程序的过程中,有时只获得异常的类型是远远不够的,还需要借助更详细的异常信息才能解决问题。\n#\n# 捕获异常时,有 2 种方式可获得更多的异常信息,分别是:\n#\n# 使用 sys 模块中的 exc_info 方法;\n# 使用 traceback 模块中的相关函数。\n#\n# 本节首先介绍如何使用 sys 模块中的 exc_info() 方法获得更多的异常信息。\n#\n# 有关 sys 模块更详细的介绍,可阅读《Python sys模块》。\n#\n# 模块 sys 中,有两个方法可以返回异常的全部信息,分别是 exc_info() 和 last_traceback(),这两个函数有相同的功能和用法,本节仅以 exc_info() 方法为例。\n#\n# exc_info() 方法会将当前的异常信息以元组的形式返回,该元组中包含 3 个元素,分别为 type、value 和 traceback,它们的含义分别是:\n# type:异常类型的名称,它是 BaseException 的子类(有关 Python 异常类,可阅读《Python常见异常类型》一节)\n# value:捕获到的异常实例。\n# traceback:是一个 traceback 对象。\n# 使用 sys 模块之前,需使用 import 引入\nimport sys\nimport traceback\n\ntry:\n x = int(input(\"请输入一个被除数:\"))\n print(\"30除以\", x, \"等于\", 30 / x)\nexcept:\n # 输出结果中,第 2 行是抛出异常的全部信息,这是一个元组,有 3 个元素,第一个元素是一个 ZeroDivisionError 类;第 2 个元素是异常类型 ZeroDivisionError 类的一个实例;第 3 个元素为\n # 一个 traceback 对象。其中,通过前 2 个元素可以看出抛出的异常类型以及描述信息,对于第 3 个元素,是一个 traceback 对象,无法直接看出有关异常的信息,还需要对其做进一步处理。\n # print(sys.exc_info())\n traceback.print_tb(sys.exc_info()[2])\n print(\"其他异常...\")\n\n# 要查看 traceback 对象包含的内容,需要先引进 traceback 模块,然后调用 traceback 模块中的 print_tb 方法,并将 sys.exc_info() 输出的 traceback 对象作为参数参入。\n\n","sub_path":"python/src/com/python/learn/exception/ExceptionInfo.py","file_name":"ExceptionInfo.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"54288431","text":"import math\nimport torch\nimport torch.nn as nn\nimport torchvision\nfrom . import block as B\n\nclass RRDBNet(nn.Module):\n def __init__(self, in_nc, out_nc, nf, nb, gc=32, upscale=4, norm_type=None, \\\n activation='leakyrelu', mode='CNA'):\n super(RRDBNet, self).__init__()\n n_upscale = int(math.log(upscale, 2))\n if upscale == 3:\n n_upscale = 1\n\n fea_conv = B.conv_block(in_nc, nf, kernel_size=3, norm_type=None, activation=None)\n rb_blocks = [B.RRDB(nf, kernel_size=3, gc=32, stride=1, bias=True, pad_type='zero', \\\n norm_type=norm_type, activation=activation, mode='CNA') for _ in range(nb)]\n LR_conv = B.conv_block(nf, nf, kernel_size=3, norm_type=norm_type, activation=None, mode=mode)\n upsample_block = B.upconv_blcok\n\n if upscale == 3:\n upsampler = upsample_block(nf, nf, 3, activation=activation)\n else:\n upsampler = [upsample_block(nf, nf, activation=activation) for _ in range(n_upscale)]\n HR_conv0 = B.conv_block(nf, nf, kernel_size=3, norm_type=None, activation=activation)\n HR_conv1 = B.conv_block(nf, out_nc, kernel_size=3, norm_type=None, activation=None)\n\n self.model = B.BlockSequent(fea_conv, B.OperateBlock(B.BlockSequent(*rb_blocks, LR_conv)),\\\n *upsampler, HR_conv0, HR_conv1)\n\n def forward(self, x):\n x = self.model(x)\n return x\n\nclass Discriminator_VGG_128(nn.Module):\n def __init__(self, in_nc, base_nf, norm_type='batch', activation='leakyrelu', mode='CNA'):\n super(Discriminator_VGG_128, self).__init__()\n\n conv0 = B.conv_block(in_nc, base_nf, kernel_size=3, norm_type=None, activation=activation, \\\n mode=mode)\n conv1 = B.conv_block(base_nf, base_nf, kernel_size=4, stride=2, norm_type=norm_type, \\\n activation=activation, mode=mode)\n\n conv2 = B.conv_block(base_nf, base_nf*2, kernel_size=3, stride=1, norm_type=norm_type, \\\n activation=activation, mode=mode)\n conv3 = B.conv_block(base_nf*2, base_nf*2, kernel_size=4, stride=2, norm_type=norm_type, \\\n activation=activation, mode=mode)\n\n conv4 = B.conv_block(base_nf*2, base_nf*4, kernel_size=3, stride=1, norm_type=norm_type, \\\n activation=activation, mode=mode)\n conv5 = B.conv_block(base_nf*4, base_nf*4, kernel_size=4, stride=2, norm_type=norm_type, \\\n activation=activation, mode=mode)\n\n conv6 = B.conv_block(base_nf*4, base_nf*8, kernel_size=3, stride=1, norm_type=norm_type, \\\n activation=activation, mode=mode)\n conv7 = B.conv_block(base_nf*8, base_nf*8, kernel_size=4, stride=2, norm_type=norm_type, \\\n activation=activation, mode=mode)\n\n conv8 = B.conv_block(base_nf*8, base_nf*8, kernel_size=3, stride=1, norm_type=norm_type, \\\n activation=activation, mode=mode)\n conv9 = B.conv_block(base_nf*8, base_nf*8, kernel_size=4, stride=2, norm_type=norm_type, \\\n activation=activation, mode=mode)\n\n self.features = B.BlockSequent(conv0, conv1, conv2, conv3, conv4, conv5, conv6, conv7, conv8,\\\n conv9)\n\n self.classifier = nn.Sequential(\n nn.Linear(512 * 4 * 4, 100), nn.LeakyReLU(0.2, True), nn.Linear(100, 1))\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\nclass VGGFeatureExtractor(nn.Module):\n def __init__(self,\n feature_layer=34,\n device=torch.device('cpu')):\n super(VGGFeatureExtractor, self).__init__()\n model = torchvision.models.vgg19(pretrained=True)\n mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(device)\n\n std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(device)\n\n self.register_buffer('mean', mean)\n self.register_buffer('std', std)\n self.features = nn.Sequential(*list(model.features.children())[:(feature_layer + 1)])\n\n for k, v in self.features.named_parameters():\n v.requires_grad = False\n\n def forward(self, x):\n x = (x - self.mean) / self.std\n output = self.features(x)\n return output\n","sub_path":"models/architecture.py","file_name":"architecture.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"166244273","text":"import itertools\n\ndef reverse_part(a, start, end):\n k, mid = 0, (start + end) // 2 + 1\n for i in range(start, mid):\n j = end - k\n a[i], a[j] = a[j], a[i]\n k += 1\n if mid > end:\n return 0\n return 1\n\ndef rotating_sort(a):\n sorted_len, rotation_count = 0, 0\n while sorted_len != len(a):\n local_min, index = len(a) + 1, 0\n for i, element in enumerate(a[sorted_len:]):\n if element < local_min:\n local_min = element\n index = i + sorted_len\n if index > sorted_len:\n rotation_count += reverse_part(a, index, len(a) - 1)\n rotation_count += reverse_part(a, sorted_len, len(a) - 1)\n sorted_len += 1\n return rotation_count\n\nlim, n = 4, 1\nord_A = ord('A')\nmax_count, rotations = 0, []\nfor i, perm in enumerate(itertools.permutations(range(1, lim + 1))):\n rotation_count = rotating_sort(list(perm))\n if rotation_count > max_count:\n rotations = [perm]\n max_count = rotation_count\n elif rotation_count == max_count:\n rotations.append(perm)\nprint(rotations)\narrangement = sorted(rotations)[n - 1]\nprint(\"\".join(chr(i + ord_A - 1) for i in arrangement))\n","sub_path":"300_349/src/task336/s336.py","file_name":"s336.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"601035822","text":"from sklearn import datasets\nfrom sklearn.model_selection import KFold\niris = datasets.load_iris()\niris_X = iris.data\niris_Y = iris.target\nprint(iris_X)\n# validación cruzada\nprint(\"Validación cruzada\\n\")\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=7, metric='euclidean')\nscores = cross_val_score(knn, iris_X, iris_Y, cv=10)\nprint(\"Resultados:\\n\",scores)\nprint(\"Exactitud: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\n# validación cruzada con matriz de confusión\nprint(\"\\nvalidación cruzada con matriz de confusión\\n\")\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import confusion_matrix, accuracy_score\ncv_outputs = cross_val_predict(knn, iris_X, iris_Y, cv=10)\ncmat = confusion_matrix(iris_Y, cv_outputs)\nprint(\"Matriz de confusión\\n\",cmat)\nprint(\"Exactitud %0.2f%%\" % accuracy_score(iris_Y, cv_outputs))\n\nprint(\"\\nKFold\\n\")\nkf = KFold(n_splits=10, shuffle=True)\nkf.get_n_splits(iris_X)\n\nprint(kf)\nimport numpy as np\nvuelta = 1\nmt = [[0,0,0],[0,0,0],[0,0,0]]\nresults = np.matrix(mt)\nfor train_index, test_index in kf.split(iris_X):\n print(\"Vuelta %d\\n\" % vuelta)\n print(\"Entrenamiento:\", train_index, \"\\nPrueba:\", test_index)\n X_train, X_test = iris_X[train_index], iris_X[test_index]\n y_train, y_test = iris_Y[train_index], iris_Y[test_index]\n knn.fit(X_train, y_train)\n output = knn.predict(X_test)\n cv_mat = confusion_matrix(y_test, output)\n exactitud = accuracy_score(y_test, output)\n print(\"Matriz de confusión\\n\", cv_mat)\n print(\"Exactitud = %0.2f%%\" % exactitud)\n results = results + np.matrix(cv_mat)\n vuelta += 1\nprint(\"Matriz de confusión final\\n\",results)\n","sub_path":"InteligenciaArtificial/TV/Unidad2/KNN_Iris_Ejemplo/src/KnnIris_KFold.py","file_name":"KnnIris_KFold.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"83737567","text":"import numpy as np\nimport pandas as pd\nimport unittest\n\nfrom collections import OrderedDict as od\nfrom context import core\nfrom context import grama as gr\nfrom context import models\nfrom context import ev\nfrom pyDOE import lhs\n\n##################################################\nclass TestDefaults(unittest.TestCase):\n def setUp(self):\n # 2D identity model with permuted df inputs\n domain_2d = gr.Domain(bounds={\"x\": [-1.0, +1], \"y\": [0.0, 1.0]})\n marginals = {}\n marginals[\"x\"] = gr.MarginalNamed(\n d_name=\"uniform\", d_param={\"loc\": -1, \"scale\": 2}\n )\n marginals[\"y\"] = gr.MarginalNamed(\n sign=-1, d_name=\"uniform\", d_param={\"loc\": 0, \"scale\": 1}\n )\n\n self.model_2d = gr.Model(\n functions=[\n gr.Function(lambda x: [x[0], x[1]], [\"x\", \"y\"], [\"f\", \"g\"], \"test\", 0)\n ],\n domain=domain_2d,\n density=gr.Density(\n marginals=marginals, copula=gr.CopulaIndependence(var_rand=[\"x\"])\n ),\n )\n\n ## Correct results\n self.df_2d_nominal = pd.DataFrame(\n data={\"x\": [0.0], \"y\": [0.5], \"f\": [0.0], \"g\": [0.5]}\n )\n self.df_2d_grad = pd.DataFrame(\n data={\"Df_Dx\": [1.0], \"Dg_Dx\": [0.0], \"Df_Dy\": [0.0], \"Dg_Dy\": [1.0]}\n )\n self.df_2d_qe = pd.DataFrame(\n data={\"x\": [0.0], \"y\": [0.1], \"f\": [0.0], \"g\": [0.1]}\n )\n\n ## Test default evaluations\n\n def test_nominal(self):\n \"\"\"Checks the nominal evaluation is accurate\n \"\"\"\n df_res = gr.eval_nominal(self.model_2d)\n\n ## Accurate\n self.assertTrue(gr.df_equal(self.df_2d_nominal, df_res))\n\n ## Pass-through\n self.assertTrue(\n gr.df_equal(\n self.df_2d_nominal.drop([\"f\", \"g\"], axis=1),\n gr.eval_nominal(self.model_2d, skip=True),\n )\n )\n\n def test_grad_fd(self):\n \"\"\"Checks the FD code\n \"\"\"\n ## Accuracy\n df_grad = gr.eval_grad_fd(\n self.model_2d, df_base=self.df_2d_nominal, append=False\n )\n\n self.assertTrue(np.allclose(df_grad[self.df_2d_grad.columns], self.df_2d_grad))\n\n ## Subset\n df_grad_sub = gr.eval_grad_fd(\n self.model_2d, df_base=self.df_2d_nominal, var=[\"x\"], append=False\n )\n\n self.assertTrue(set(df_grad_sub.columns) == set([\"Df_Dx\", \"Dg_Dx\"]))\n\n ## Flags\n md_test = (\n gr.Model()\n >> gr.cp_function(fun=lambda x: x[0] + x[1] ** 2, var=2, out=1)\n >> gr.cp_marginals(x0={\"dist\": \"norm\", \"loc\": 0, \"scale\": 1})\n )\n df_base = pd.DataFrame(dict(x0=[0, 1], x1=[0, 1]))\n ## Multiple base points\n df_true = pd.DataFrame(dict(Dy0_Dx0=[1, 1], Dy0_Dx1=[0, 2]))\n\n df_rand = gr.eval_grad_fd(md_test, df_base=df_base, var=\"rand\", append=False)\n self.assertTrue(gr.df_equal(df_true[[\"Dy0_Dx0\"]], df_rand, close=True))\n\n df_det = gr.eval_grad_fd(md_test, df_base=df_base, var=\"det\", append=False)\n self.assertTrue(gr.df_equal(df_true[[\"Dy0_Dx1\"]], df_det, close=True))\n\n def test_conservative(self):\n ## Accuracy\n df_res = gr.eval_conservative(self.model_2d, quantiles=[0.1, 0.1])\n\n self.assertTrue(gr.df_equal(self.df_2d_qe, df_res, close=True))\n\n ## Repeat scalar value\n self.assertTrue(\n gr.df_equal(\n self.df_2d_qe,\n gr.eval_conservative(self.model_2d, quantiles=0.1),\n close=True,\n )\n )\n\n ## Pass-through\n self.assertTrue(\n gr.df_equal(\n self.df_2d_qe.drop([\"f\", \"g\"], axis=1),\n gr.eval_conservative(self.model_2d, quantiles=0.1, skip=True),\n close=True,\n )\n )\n\n\n##################################################\nclass TestRandomSampling(unittest.TestCase):\n def setUp(self):\n self.md = (\n gr.Model()\n >> gr.cp_function(fun=lambda x: x, var=1, out=1)\n >> gr.cp_marginals(x0={\"dist\": \"uniform\", \"loc\": 0, \"scale\": 1})\n >> gr.cp_copula_independence()\n )\n\n self.md_2d = (\n gr.Model()\n >> gr.cp_function(fun=lambda x: x[0], var=2, out=1)\n >> gr.cp_marginals(\n x0={\"dist\": \"uniform\", \"loc\": 0, \"scale\": 1},\n x1={\"dist\": \"uniform\", \"loc\": 0, \"scale\": 1},\n )\n >> gr.cp_copula_independence()\n )\n\n def test_lhs(self):\n ## Accurate\n n = 2\n df_res = ev.eval_lhs(self.md_2d, n=n, df_det=\"nom\", seed=101)\n\n np.random.seed(101)\n df_truth = pd.DataFrame(data=lhs(2, samples=n), columns=[\"x0\", \"x1\"])\n df_truth[\"y0\"] = df_truth[\"x0\"]\n\n self.assertTrue(gr.df_equal(df_res, df_truth))\n\n ## Rounding\n df_round = ev.eval_lhs(self.md_2d, n=n + 0.1, df_det=\"nom\", seed=101)\n\n self.assertTrue(gr.df_equal(df_round, df_truth))\n\n ## Pass-through\n df_pass = ev.eval_lhs(self.md_2d, n=n, skip=True, df_det=\"nom\", seed=101)\n\n self.assertTrue(gr.df_equal(df_pass, df_truth[[\"x0\", \"x1\"]]))\n\n def test_monte_carlo(self):\n ## Accurate\n n = 2\n df_res = gr.eval_monte_carlo(self.md, n=n, df_det=\"nom\", seed=101)\n\n np.random.seed(101)\n df_truth = pd.DataFrame({\"x0\": np.random.random(n)})\n df_truth[\"y0\"] = df_truth[\"x0\"]\n\n self.assertTrue(gr.df_equal(df_res, df_truth))\n\n ## Rounding\n df_round = gr.eval_monte_carlo(self.md, n=n + 0.1, df_det=\"nom\", seed=101)\n\n self.assertTrue(gr.df_equal(df_round, df_truth))\n\n ## Pass-through\n df_pass = gr.eval_monte_carlo(self.md, n=n, skip=True, df_det=\"nom\", seed=101)\n\n self.assertTrue(gr.df_equal(df_pass[[\"x0\"]], df_truth[[\"x0\"]]))\n\n\n##################################################\nclass TestRandom(unittest.TestCase):\n def setUp(self):\n self.md = models.make_test()\n\n self.md_mixed = (\n gr.Model()\n >> gr.cp_function(fun=lambda x: x[0], var=3, out=1)\n >> gr.cp_bounds(x2=(0, 1))\n >> gr.cp_marginals(\n x0={\"dist\": \"uniform\", \"loc\": 0, \"scale\": 1},\n x1={\"dist\": \"uniform\", \"loc\": 0, \"scale\": 1},\n )\n >> gr.cp_copula_independence()\n )\n\n def test_monte_carlo(self):\n df_min = gr.eval_monte_carlo(self.md, df_det=\"nom\")\n self.assertTrue(df_min.shape == (1, self.md.n_var + self.md.n_out))\n self.assertTrue(set(df_min.columns) == set(self.md.var + self.md.out))\n\n df_seeded = gr.eval_monte_carlo(self.md, df_det=\"nom\", seed=101)\n df_piped = self.md >> gr.ev_monte_carlo(df_det=\"nom\", seed=101)\n self.assertTrue(df_seeded.equals(df_piped))\n\n df_skip = gr.eval_monte_carlo(self.md, df_det=\"nom\", skip=True)\n self.assertTrue(set(df_skip.columns) == set(self.md.var))\n\n df_noappend = gr.eval_monte_carlo(self.md, df_det=\"nom\", append=False)\n self.assertTrue(set(df_noappend.columns) == set(self.md.out))\n\n def test_lhs(self):\n df_min = ev.eval_lhs(self.md, df_det=\"nom\")\n self.assertTrue(df_min.shape == (1, self.md.n_var + self.md.n_out))\n self.assertTrue(set(df_min.columns) == set(self.md.var + self.md.out))\n\n df_seeded = ev.eval_lhs(self.md, df_det=\"nom\", seed=101)\n df_piped = self.md >> ev.ev_lhs(df_det=\"nom\", seed=101)\n self.assertTrue(df_seeded.equals(df_piped))\n\n df_skip = ev.eval_lhs(self.md, df_det=\"nom\", skip=True)\n self.assertTrue(set(df_skip.columns) == set(self.md.var))\n\n df_noappend = ev.eval_lhs(self.md, df_det=\"nom\", append=False)\n self.assertTrue(set(df_noappend.columns) == set(self.md.out))\n\n def test_sinews(self):\n df_min = gr.eval_sinews(self.md, df_det=\"nom\")\n self.assertTrue(\n set(df_min.columns)\n == set(self.md.var + self.md.out + [\"sweep_var\", \"sweep_ind\"])\n )\n self.assertTrue(df_min._plot_info[\"type\"] == \"sinew_outputs\")\n\n df_seeded = gr.eval_sinews(self.md, df_det=\"nom\", seed=101)\n df_piped = self.md >> gr.ev_sinews(df_det=\"nom\", seed=101)\n self.assertTrue(df_seeded.equals(df_piped))\n\n df_skip = gr.eval_sinews(self.md, df_det=\"nom\", skip=True)\n self.assertTrue(df_skip._plot_info[\"type\"] == \"sinew_inputs\")\n\n df_mixed = gr.eval_sinews(self.md_mixed, df_det=\"swp\")\n\n def test_hybrid(self):\n df_min = gr.eval_hybrid(self.md, df_det=\"nom\")\n self.assertTrue(\n set(df_min.columns) == set(self.md.var + self.md.out + [\"hybrid_var\"])\n )\n self.assertTrue(df_min._meta[\"type\"] == \"eval_hybrid\")\n\n df_seeded = gr.eval_hybrid(self.md, df_det=\"nom\", seed=101)\n df_piped = self.md >> gr.ev_hybrid(df_det=\"nom\", seed=101)\n self.assertTrue(df_seeded.equals(df_piped))\n\n df_total = gr.eval_hybrid(self.md, df_det=\"nom\", plan=\"total\")\n self.assertTrue(\n set(df_total.columns) == set(self.md.var + self.md.out + [\"hybrid_var\"])\n )\n self.assertTrue(df_total._meta[\"type\"] == \"eval_hybrid\")\n\n df_skip = gr.eval_hybrid(self.md, df_det=\"nom\", skip=True)\n self.assertTrue(set(df_skip.columns) == set(self.md.var + [\"hybrid_var\"]))\n\n ## Raises\n md_buckle = models.make_plate_buckle()\n with self.assertRaises(ValueError):\n gr.eval_hybrid(md_buckle, df_det=\"nom\")\n\n\n##################################################\nclass TestOpt(unittest.TestCase):\n def test_nls(self):\n ## Setup\n md_feat = (\n gr.Model()\n >> gr.cp_function(fun=lambda x: x[0] * x[1] + x[2], var=3, out=1,)\n >> gr.cp_bounds(x0=[-1, +1], x2=[0, 0])\n >> gr.cp_marginals(x1=dict(dist=\"norm\", loc=0, scale=1))\n )\n\n md_const = (\n gr.Model()\n >> gr.cp_function(fun=lambda x: x[0], var=1, out=1)\n >> gr.cp_bounds(x0=(-1, +1))\n )\n\n df_response = md_feat >> gr.ev_df(\n df=gr.df_make(x0=0.1, x1=[-1, -0.5, +0, +0.5, +1], x2=0)\n )\n df_data = df_response[[\"x1\", \"y0\"]]\n\n ## Model with features\n df_true = gr.df_make(x0=0.1)\n df_fit = md_feat >> gr.ev_nls(df_data=df_data, append=False)\n\n pd.testing.assert_frame_equal(\n df_fit,\n df_true,\n check_exact=False,\n check_dtype=False,\n check_column_type=False,\n )\n ## Fitting synonym\n md_feat_fit = df_data >> gr.ft_nls(md=md_feat, verbose=False)\n self.assertTrue(set(md_feat_fit.var) == set([\"x1\", \"x2\"]))\n\n ## Constant model\n df_const = gr.df_make(x0=0)\n df_fit = md_const >> gr.ev_nls(df_data=gr.df_make(y0=[-1, 0, +1]))\n\n pd.testing.assert_frame_equal(\n df_fit,\n df_const,\n check_exact=False,\n check_dtype=False,\n check_column_type=False,\n )\n\n ## Multiple restarts works\n df_multi = gr.eval_nls(md_feat, df_data=df_data, n_restart=2)\n self.assertTrue(df_multi.shape[0] == 2)\n\n ## Specified initial guess\n df_spec = gr.eval_nls(\n md_feat, df_data=df_data, df_init=gr.df_make(x0=0.5), append=False\n )\n pd.testing.assert_frame_equal(\n df_spec,\n df_true,\n check_exact=False,\n check_dtype=False,\n check_column_type=False,\n )\n # Raises if incorrect guess data\n with self.assertRaises(ValueError):\n gr.eval_nls(md_feat, df_data=df_data, df_init=gr.df_make(foo=0.5))\n\n def test_opt(self):\n md_bowl = (\n gr.Model(\"Constrained bowl\")\n >> gr.cp_function(\n fun=lambda x: x[0] ** 2 + x[1] ** 2, var=[\"x\", \"y\"], out=[\"f\"],\n )\n >> gr.cp_function(\n fun=lambda x: (x[0] + x[1] + 1), var=[\"x\", \"y\"], out=[\"g1\"],\n )\n >> gr.cp_function(\n fun=lambda x: -(-x[0] + x[1] - np.sqrt(2 / 10)),\n var=[\"x\", \"y\"],\n out=[\"g2\"],\n )\n >> gr.cp_bounds(x=(-1, +1), y=(-1, +1),)\n )\n\n df_res = md_bowl >> gr.ev_min(out_min=\"f\", out_geq=[\"g1\"], out_leq=[\"g2\"],)\n\n # Check result\n self.assertTrue(abs(df_res.x[0] + np.sqrt(1 / 20)) < 1e-6)\n self.assertTrue(abs(df_res.y[0] - np.sqrt(1 / 20)) < 1e-6)\n\n # Check errors for violated invariants\n with self.assertRaises(ValueError):\n gr.eval_min(md_bowl, out_min=\"FALSE\")\n with self.assertRaises(ValueError):\n gr.eval_min(md_bowl, out_min=\"f\", out_geq=[\"FALSE\"])\n with self.assertRaises(ValueError):\n gr.eval_min(md_bowl, out_min=\"f\", out_eq=[\"FALSE\"])\n\n # Test multiple restarts\n df_multi = gr.eval_min(\n md_bowl, out_min=\"f\", out_geq=[\"g1\"], out_leq=[\"g2\"], n_restart=2,\n )\n self.assertTrue(df_multi.shape[0] == 2)\n\n\n## Run tests\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_evals.py","file_name":"test_evals.py","file_ext":"py","file_size_in_byte":13163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"428453970","text":"#! /Library/Frameworks/Python.framework/Versions/3.7/bin/python3\nimport heapq\nN, M = map(int, input().split())\nL = [[] for _ in range(10001)] # 仕事リスト(インデックス:単価、要素:最終受注可能日)\nans = []\nfor _ in range(N):\n a, b = map(int, input().split()) # a:日 b:単価\n L[M-a].append(b)\nfor i in range(M + 1):\n for j in L[i]:\n heapq.heappush(ans, j)\n if len(ans) > i+1:\n heapq.heappop(ans)\nprint(str(sum(ans)))\n","sub_path":"過去問/abc137_d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"603034379","text":"# this script is to evaluate all of the villar x roadmap x species sequence alignments without having to run the entire method2_v1,2,3 scripts\n\nimport os, sys\nimport pandas\nimport glob\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import stats\nplt.style.use('seaborn-deep')\ntoday = datetime.date.today()\n\n# This dataframe is called \"short_vrs\" in the method2_v3.py script\n\nvrs = pandas.read_csv(\"/Users/sarahfong/Desktop/CAPRA/2018-02-24/Villar_Roadmap_Species_short_vrs_overlap_2018-02-24.csv\", sep = '\\t')\nvrs = pandas.read_csv(\"/Users/sarahfong/Desktop/CAPRA/2018-02-27/short_vrs_overlap_2018-02-27.csv\", sep = '\\t')\n\nq25= int(vrs[\"sum\"].quantile(0.25))\nq50 = int(vrs[\"sum\"].quantile(0.50))\nq75 = int(vrs[\"sum\"].quantile(0.75))\nq90 = int(vrs[\"sum\"].quantile(0.90))\n # 'a' = 'all'\n # 'h' = 'human' specific enhancers\n # 'c' = 'conserved' enhancers\n # 'd' = 'dataset'\n\n #'act' = active\n #'aln' = alignable\n\ndtype = ['sum_act_sp', 'sum_aln_sp', 'sum_hq_act_sp', 'sum_hq_aln_sp']\n\nvrs_0 = vrs.loc[vrs[\"sum\"]=q25]\nvrs_25 = vrs_25.loc[vrs_25[\"sum\"]=q50]\nvrs_50 = vrs_50.loc[vrs_50[\"sum\"]=q75]\nvrs_75 = vrs_75.loc[vrs_75[\"sum\"]=q90]\n \nfor item in dtype:\n hspec = vrs_90[[\"v-chr\", \"v-start\", \"v-end\"]].loc[vrs_90['%s' %item] == 0]\n hspec.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/hspec_90_%s_zero_%s.bed\" %(today, item, today), sep = '\\t', index = False, header = False)\n\n consv = vrs_90[[\"v-chr\", \"v-start\", \"v-end\"]].loc[vrs_90['%s'%item] > 0]\n consv.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/consv_vrs_90_%s_greater_than_zero_%s.bed\" %(today ,item, today), sep = '\\t', index = False, header = False)\n \n","sub_path":"vrs_consv_v_hspecific.py","file_name":"vrs_consv_v_hspecific.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"245244017","text":"# This sample code uses the Appium python client\n# pip install Appium-Python-Client\n# Then you can paste this into a file and simply run with Python\nfrom time import sleep\n\nimport pytest\nfrom appium import webdriver\nfrom appium.webdriver.common.mobileby import MobileBy\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n\"\"\"\n改造1:使用pytest测试框架 \n\"\"\"\nclass TestWebView:\n def setup(self):\n caps = {}\n caps[\"platformName\"] = \"android\"\n caps[\"deviceName\"] = \"emulator-5554\"\n caps[\"appPackage\"] = \"com.xueqiu.android\"\n caps[\"appActivity\"] = \"com.xueqiu.android.main.view.MainActivity\"\n # caps[\"automationName\"] = \"appium\"\n\n caps[\"noReset\"] = \"true\"\n # caps[\"skipServerInstallation\"] = \"true\"\n #等待页面空闲的时间,动态页面默认等10s 太耗时了\n caps['settings[waitForIdleTimeout]'] = 1\n caps['chromedriverExecutable'] = r'C:\\Software\\Chromedriver2.20\\chromedriver.exe'\n #最重要!!户端代码与Appium Server建立连接,同时启动欢迎页\n self.driver = webdriver.Remote(\"http://localhost:4723/wd/hub\", caps)\n self.driver.implicitly_wait(5)\n def teardown(self):\n self.driver.quit()\n\n def test_webview(self):\n #点击交易\n self.driver.find_element(MobileBy.XPATH,'//*[@text=\"交易\"]').click()\n # 点击‘A股开户’\n self.driver.find_element(MobileBy.ACCESSIBILITY_ID,'A股开户').click()\n # a_locator = (MobileBy.XPATH,'//*[@id=\"Layout_app_3V4\"]/div/div/ul/li[1]/div[2]/h1')\n print(self.driver.contexts)\n #切换上下文到webview界面\n self.driver.switch_to.context(self.driver.contexts[-1])\n # 有问题的一行:1:34:20\n # print(self.driver.window_handles)\n # WebDriverWait(self.driver,10).until(expected_conditions.element_to_be_clickable(a_locator))\n # self.driver.find_element(*a_locator).click()\n print(self.driver.window_handles)\n #切换窗口\n # kaihu_window = self.driver.window_handles[-1]\n # self.driver.switch_to.window(kaihu_window)\n #显式等待\n phonenumber_locator = (MobileBy.ID,\"phone-number\")\n WebDriverWait(self.driver,60).until(expected_conditions.element_to_be_clickable(phonenumber_locator))\n #输入用户名和验证码,点击立即开户\n self.driver.find_element(*phonenumber_locator).send_keys(\"13312341234\")\n self.driver.find_element(MobileBy.ID,\"code\").send_keys(\"1234\")\n self.driver.find_element(MobileBy.CSS_SELECTOR,\"body > div > div > div.form-wrap > div > div.btn-submit\").click()\n # sleep(2)\n\n\n\n","sub_path":"Python14_class/test_webview2.py","file_name":"test_webview2.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"640424373","text":"košík = {\"jablko\": \"červené\", \"hruška\": \"zelená\", \" broskev\": \"oranžová\", \"banán\": \"žlutý\"}\n\nshnilý_košík={}\n\nfor ovoce, barva in košík.items():\n shnilý_košík[ovoce]= \"hnědo-{}\".format(barva)\n\nprint(shnilý_košík)\n\n#()metody\n#[]index, poloha - obal listu\n#{} obal slovníku - předpřipravený\n","sub_path":"04/kosik_ovoce.py","file_name":"kosik_ovoce.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"495237229","text":"from datetime import datetime, timedelta\nfrom flask import render_template, request, current_app, session, redirect, url_for, g, jsonify, abort\n\nfrom info import constants, db\nfrom info.models import User, News, Category\nfrom info.utils.common import get_login_user\nfrom info.utils.image_storage import storage\nfrom info.utils.response_code import RET\nfrom . import admin_blu\n\n\n@admin_blu.route('/logout')\ndef admin_logout():\n return redirect(url_for('passport.logout'))\n\n\n@admin_blu.route('/news_type', methods=['GET', 'POST'])\ndef news_type():\n if request.method == 'GET':\n categories = None\n try:\n categories = Category.query.all()\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')\n\n if not categories:\n return jsonify(errno=RET.NODATA, errmsg='未查询到数据')\n\n categories_dict_li = []\n\n for category in categories:\n categories_dict_li.append(category.to_dict())\n\n categories_dict_li.pop(0)\n\n data = {\n 'categories': categories_dict_li\n }\n return render_template('admin/news_type.html', data=data)\n # POST 请求\n\n params = request.json\n cid = params.get('id', None)\n cname = params.get('name', None)\n\n if not cid:\n # 添加分类\n add_cat = Category()\n add_cat.name = cname\n db.session.add(add_cat)\n\n else:\n # 修改分类\n try:\n cid = int(cid)\n category = Category.query.get(cid)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg='查询错误')\n if not category:\n return jsonify(errno=RET.NODATA, errmsg='查询错误')\n category.name = cname\n\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n db.session.rollback()\n return jsonify(errno=RET.DBERR, errmsg='数据库操作失败')\n\n return jsonify(errno=RET.OK, errmsg='操作成功')\n\n\n@admin_blu.route('/news_edit_detail', methods=['POST', 'GET'])\ndef news_edit_detail():\n if request.method == 'GET':\n # 获取参数\n news_id = request.args.get(\"news_id\")\n\n if not news_id:\n abort(404)\n\n try:\n news_id = int(news_id)\n except Exception as e:\n abort(404)\n\n news = None\n try:\n news = News.query.get(news_id)\n except Exception as e:\n current_app.logger.error(e)\n\n if not news:\n return jsonify(errno=RET.NODATA, errmsg='无此新闻')\n\n categories = []\n try:\n categories = Category.query.all()\n except Exception as e:\n current_app.logger.error(e)\n return jsonify()\n\n categories_dict_li = []\n for category in categories:\n categories_dict_li.append(category.to_dict())\n categories_dict_li.pop(0)\n\n data = {\n 'news': news.to_dict(),\n 'categories': categories_dict_li\n }\n\n return render_template('admin/news_edit_detail.html', data=data)\n\n # POST 请求\n news_id = request.form.get(\"news_id\")\n title = request.form.get(\"title\")\n digest = request.form.get(\"digest\")\n content = request.form.get(\"content\")\n index_image = request.files.get(\"index_image\")\n category_id = request.form.get(\"category_id\")\n\n # 1.1 判断数据是否有值\n if not all([title, digest, content, category_id]):\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数有误\")\n\n news = None\n try:\n news = News.query.get(news_id)\n except Exception as e:\n current_app.logger.error(e)\n if not news:\n return jsonify(errno=RET.NODATA, errmsg=\"未查询到新闻数据\")\n\n # 1.2 尝试读取图片\n if index_image:\n try:\n index_image = index_image.read()\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数有误\")\n\n # 2. 将标题图片上传到七牛\n try:\n key = storage(index_image)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.THIRDERR, errmsg=\"上传图片错误\")\n news.index_image_url = constants.QINIU_DOMIN_PREFIX + key\n # 3. 设置相关数据\n news.title = title\n news.digest = digest\n news.content = content\n news.category_id = category_id\n\n # 4. 保存到数据库\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n db.session.rollback()\n return jsonify(errno=RET.DBERR, errmsg=\"保存数据失败\")\n # 5. 返回结果\n return jsonify(errno=RET.OK, errmsg=\"编辑成功\")\n\n\n@admin_blu.route('/news_edit')\ndef news_edit():\n # 获取参数\n page = request.args.get('p', 1)\n keyword = request.args.get('keyword', None)\n\n # 参数检测\n try:\n page = int(page)\n except Exception as e:\n current_app.logger.error(e)\n\n # 查询数据\n news_list = []\n current_page = 1\n total_page = 1\n\n filters = [News.status == 0]\n if keyword:\n filters.append(News.title.contains(keyword))\n try:\n paginate = News.query.filter(*filters).order_by(\n News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, error_out=False)\n news_list = paginate.items\n current_page = paginate.page\n total_page = paginate.pages\n except Exception as e:\n current_app.logger.error(e)\n\n news_dict_li = []\n for news in news_list:\n news_dict_li.append(news.to_basic_dict())\n\n data = {\n 'news_list': news_dict_li,\n 'current_page': current_page,\n 'total_page': total_page\n }\n\n return render_template('admin/news_edit.html', data=data)\n\n\n@admin_blu.route('/news_review_action', methods=['POST'])\ndef news_review_action():\n # 读取参数\n params = request.json\n news_id = params.get('news_id')\n action = params.get('action')\n\n if not all([news_id, action]):\n return jsonify(errno=RET.PARAMERR, errmsg='参数错误')\n\n if action not in ('accept', 'reject'):\n return jsonify(errno=RET.PARAMERR, errmsg='非法请求')\n\n try:\n news_id = int(news_id)\n news = News.query.get(news_id)\n except Exception as e:\n current_app.logger.error(e)\n\n if not news:\n return jsonify(errno=RET.NODATA, errmsg='未查询到数据')\n\n if action == 'accept':\n news.status = 0\n else:\n reason = params.get('reason')\n if not reason:\n return jsonify(errno=RET.PARAMERR, errmsg='请输入拒绝原因')\n news.status = -1\n news.reason = reason\n\n return jsonify(errno=RET.OK, errmsg='OK')\n\n\n@admin_blu.route('/news_review_detail/')\ndef news_review_detail(news_id):\n try:\n news = News.query.get(news_id)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg='查询错误')\n\n if not news:\n return jsonify(errno=RET.NODATA, errmsg='新闻不存在')\n\n data = {\n 'news': news.to_dict()\n }\n return render_template('admin/news_review_detail.html', data=data)\n\n\n@admin_blu.route('/news_review')\ndef news_review():\n # 获取参数\n page = request.args.get('p', 1)\n keyword = request.args.get('keyword', None)\n\n # 参数检测\n try:\n page = int(page)\n except Exception as e:\n current_app.logger.error(e)\n\n # 查询数据\n news_list = []\n current_page = 1\n total_page = 1\n\n filters = [News.status != 0]\n if keyword:\n filters.append(News.title.contains(keyword))\n try:\n paginate = News.query.filter(*filters).order_by(\n News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, error_out=False)\n news_list = paginate.items\n current_page = paginate.page\n total_page = paginate.pages\n except Exception as e:\n current_app.logger.error(e)\n\n news_dict_li = []\n for news in news_list:\n news_dict_li.append(news.to_review_dict())\n\n data = {\n 'news_list': news_dict_li,\n 'current_page': current_page,\n 'total_page': total_page\n }\n\n return render_template('admin/news_review.html', data=data)\n\n\n@admin_blu.route('/user_list')\ndef user_list():\n # 取出参数\n page = request.args.get('p', 1)\n\n # 校验参数\n try:\n page = int(page)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.PARAMERR, errmsg='参数错误')\n\n # 查询分页数据\n user_list = []\n current_page = 1\n total_page = 1\n\n try:\n paginate = User.query.filter(\n User.is_admin == False).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, error_out=False)\n user_list = paginate.items\n current_page = paginate.page\n total_page = paginate.pages\n except Exception as e:\n current_app.logger.error(e)\n\n user_dict_li = []\n for user in user_list:\n user_dict_li.append(user.to_admin_dict())\n\n data = {\n 'user_list': user_dict_li,\n 'current_page': current_page,\n 'total_page': total_page\n }\n # data 传递到模版渲染数据\n return render_template('admin/user_list.html', data=data)\n\n\n@admin_blu.route('/user_count')\ndef user_count():\n \"\"\"\n 后台 用户统计页面渲染\n 查询 总用户数 月新用户数 日新用户数 本月用户活跃数据\n :return:\n \"\"\"\n # 总用户数\n total_user = 0\n try:\n total_user = User.query.filter(User.is_admin == False).count()\n except Exception as e:\n current_app.logger.error(e)\n\n # 取得当日的零时\n today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)\n\n # 月新增用户量\n mon_user = 0\n begin_mon_time = today.replace(day=1) # 日置1\n try:\n mon_user = User.query.filter(User.is_admin == False, User.create_time > begin_mon_time).count()\n except Exception as e:\n current_app.logger.error(e)\n\n # 日新增用户量\n day_user = 0\n begin_day_time = today\n try:\n day_user = User.query.filter(User.is_admin == False, User.create_time > begin_day_time).count()\n except Exception as e:\n current_app.logger.error(e)\n\n # 折线图数据查询\n\n # # 练习 效率没有直接用for语句快 没什么吊用\n # t = time.time()\n # active_data = [(begin_day.strftime('%Y-%m-%d'),\n # User.query.filter(User.is_admin == False, User.last_login >= begin_day,\n # User.last_login <= begin_day + timedelta(days=1)).count())\n # for begin_day in [today - timedelta(days=i) for i in range(31)]]\n # print(time.time() - t)\n\n active_time = []\n active_count = []\n try:\n for i in range(30, -1, -1):\n begin_day = today - timedelta(days=i)\n count = User.query.filter(User.is_admin == False, User.last_login >= begin_day,\n User.last_login <= begin_day + timedelta(days=1)).count()\n active_count.append(count)\n active_time.append(begin_day.strftime('%Y-%m-%d'))\n except Exception as e:\n current_app.logger.error(e)\n data = {\n 'total_user': total_user,\n 'mon_user': mon_user,\n 'day_user': day_user,\n 'active_time': active_time,\n 'active_count': active_count\n }\n return render_template('admin/user_count.html', data=data)\n\n\n@admin_blu.route('/index')\n@get_login_user\ndef index():\n \"\"\"\n 后台 主页模版渲染\n\n :return:\n \"\"\"\n user = g.user\n\n data = {\n 'user': user.to_dict()\n }\n\n return render_template('admin/index.html', data=data)\n\n\n@admin_blu.route('/login', methods=['POST', 'GET'])\ndef login():\n \"\"\"\n 后台 登录模版渲染\n :return:\n \"\"\"\n if request.method == 'GET':\n # 如果管理员已登录直接跳转至后台首页\n is_admin = session.get('is_admin', False)\n if is_admin:\n return redirect(url_for('admin.index'))\n return render_template('admin/login.html')\n elif request.method == 'POST':\n # 取出参数\n username = request.form.get('username')\n password = request.form.get('password')\n\n # 检测参数\n if not all([username, password]):\n return render_template('admin/login.html', errmsg='参数错误')\n\n # 查询用户\n try:\n user = User.query.filter(User.mobile == username,\n User.is_admin == True).first()\n except Exception as e:\n current_app.logger.error(e)\n return render_template('admin/login.html', errmsg='数据库查询失败')\n\n if not user:\n return render_template('admin/login.html', errmsg='用户或密码错误')\n\n # 校验密码\n if not user.check_passowrd(password):\n return render_template('admin/login.html', errmsg='用户或密码错误')\n\n # 保存用户的登录信息\n session[\"user_id\"] = user.id\n session[\"mobile\"] = user.mobile\n session[\"nick_name\"] = user.nick_name\n session[\"is_admin\"] = user.is_admin\n\n return redirect(url_for('admin.index'))\n","sub_path":"info/modules/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"124533590","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect, Http404\n\nfrom .models import Topic, Entry\nfrom .forms import TopicForm, EntryForm\n\n# Create your views here.\n\ndef index(request):\n\t\"\"\"Strona główna dla aplikacji Learning Log.\"\"\"\n\treturn render(request, 'index.html')\n\t\n@login_required\ndef topics(request):\n\t\"\"\"Wyświetlenie wszystkich tematów.\"\"\"\n\ttopics = Topic.objects.filter(owner=request.user).order_by('date_added')\n\tcontext = {'topics': topics}\n\treturn render(request, 'topics.html', context)\n\n@login_required\ndef topic(request, topic_id):\n\t\"\"\" Wyświetla pojedynczy temat i wszystkie powiązane z nim wpisy.\"\"\"\n\ttopic = Topic.objects.get(id=topic_id)\n\t# Upewniamy się, że temat należy do bieżącego użytkownika.\n\tif topic.owner != request.user:\n\t\traise Http404\n\n\tentries = topic.entry_set.order_by('-date_added')\n\tcontext = {'topic': topic, 'entries': entries}\n\treturn render(request, 'topic.html', context)\n\n@login_required\ndef new_topic(request):\n\t\"\"\"Dodaj nowy temat.\"\"\"\n\tif request.method != 'POST':\n\t\t# Nie przekazano żadnych danych, należy utworzyć pusty formularz.\n\t\tform = TopicForm()\n\telse:\n\t\t# Przekazono dane za pomocą żądania POST, należy je przetworzyć.\n\t\tform = TopicForm(data=request.POST)\n\t\tif form.is_valid():\n\t\t\tnew_topic = form.save(commit=False)\n\t\t\tnew_topic.owner = request.user\n\t\t\tnew_topic.save()\n\t\t\treturn redirect('learning_logs:topics')\n\n\t# Wyświetlenie pustego formularza.\n\tcontext = {'form': form}\n\treturn render(request, 'new_topic.html', context)\n\n@login_required\ndef new_entry(request, topic_id):\n\t\"\"\"Dodanie nowego wpisu dla określonego tematu.\"\"\"\n\ttopic = Topic.objects.get(id=topic_id)\n\n\tif request.method != 'POST':\n\t\t# Nie przekazano żadnych danych, należy utworzyć pusty formularz.\n\t\tform = EntryForm()\n\n\telse:\n\t\t# Przekazano dane za pomocą żądania POST, należy je przetworzyc.\n\t\tform = EntryForm(data=request.POST)\n\t\tif form.is_valid():\n\t\t\tnew_entry = form.save(commit=False)\n\t\t\tnew_entry.topic = topic\n\t\t\tnew_entry.save()\n\t\t\treturn redirect('learning_logs:topic', topic_id=topic_id)\n\n\t# Wyświetlenie pustego formularza\n\tcontext = {'topic': topic, 'form': form}\n\treturn render(request, 'new_entry.html', context)\n\n@login_required\ndef edit_entry(request, entry_id):\n\t\"\"\"Edycja istniejącego wpisu.\"\"\"\n\tentry = Entry.objects.get(id=entry_id)\n\ttopic = entry.topic\n\tif topic.owner != request.user:\n\t\traise Http404\n\n\tif request.method != 'POST':\n\t\t# Żądanie początkowe, wypełnienie formularza aktualną treścią wpisu.\n\t\tform = EntryForm(instance=entry)\n\telse:\n\t\t# Przekazano dane za pomocą żądania POST, należy je przetworzyc.\n\t\tform = EntryForm(instance=entry, data=request.POST)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn redirect('learning_logs:topic', topic_id=topic_id)\n\n\tcontext = {'entry': entry, 'topic': topic, 'form': form}\n\treturn render(request, 'edit_entry.html', context)","sub_path":"learning_logs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608541318","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ntry:\n from setuptools import setup, find_packages\nexcept ImportError:\n from distutils.core import setup\n\nrequirements = [\n 'SPARQLWrapper==1.8.4',\n 'rdflib==4.2.2'\n]\n\ntest_requirements = [\n 'coverage'\n]\n\nsetup(\n name='textminingservice-biokb',\n version='0.0.1',\n description=\"BioKB implementation of the common text mining interface\",\n url='',\n packages=find_packages(exclude=['contrib', 'docs', 'tests*']),\n package_dir={'textminingservice-biokb':\n 'textminingservice_biokb'},\n include_package_data=True,\n install_requires=requirements,\n zip_safe=False,\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3.7',\n ],\n tests_require=test_requirements,\n)\n","sub_path":"projects/11/biokb/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"306989541","text":"# coding=utf-8\nfrom qgis.testing import start_app, unittest\nimport nose2\n\nfrom qgis.PyQt.QtCore import QUrl\nfrom resource_sharing.resource_handler.symbol_resolver_mixin import (\n resolve_path,\n fix_xml_node)\nfrom test.utilities import test_data_path\n\n\nclass TestSymbolResolverMixin(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n start_app()\n\n\n def _to_str(self, buffer):\n \"\"\"For Py3 compat, this will transform a byte into string\"\"\"\n if type(buffer) == 'str':\n return buffer\n return buffer.decode('utf-8')\n\n def test_fix_xml_node(self):\n \"\"\"Test if fixing xml node works.\"\"\"\n symbol_xml = \"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \"\"\"\n collection_path = test_data_path('collections', 'test_collection')\n fixed_xml = self._to_str(fix_xml_node(symbol_xml, collection_path, []))\n expected_xml = \"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \"\"\".format(test_data_path())\n\n self.assertEqual(fixed_xml, expected_xml)\n\n\n def test_resolve_path(self):\n \"\"\"Test resolving the path works correctly.\"\"\"\n collection_path = test_data_path('collections', 'test_collection')\n search_paths = []\n\n # Test case 1: local path\n img_path = test_data_path(\n 'collections', 'test_collection', 'svg', 'blastoise.svg')\n fixed_path = resolve_path(img_path, collection_path, search_paths)\n self.assertEqual(img_path, fixed_path)\n\n # Test case 2: local url\n img_path = test_data_path(\n 'collections', 'test_collection', 'svg', 'blastoise.svg')\n img_url = QUrl.fromLocalFile(img_path)\n fixed_path = resolve_path(\n img_url.toString(), collection_path, search_paths)\n self.assertEqual(fixed_path, img_path)\n\n # Test case 3: http url\n img_path = 'http://qgis.org/test/image.svg'\n img_url = QUrl(img_path)\n fixed_path = resolve_path(\n img_url.toString(), collection_path, search_paths)\n self.assertEqual(fixed_path, img_path)\n\n # Test case 4: checking in the svg local collection path\n img_path = '/you/would/not/find/this/charizard.svg'\n fixed_path = resolve_path(img_path, collection_path, search_paths)\n expected_path = test_data_path(\n 'collections', 'test_collection', 'svg', 'charizard.svg')\n self.assertEqual(fixed_path, expected_path)\n\n # Test case 5: checking in the image local collection path\n img_path = '/you/would/not/find/this/pikachu.png'\n fixed_path = resolve_path(img_path, collection_path, search_paths)\n expected_path = test_data_path(\n 'collections', 'test_collection', 'image', 'pikachu.png')\n self.assertEqual(fixed_path, expected_path)\n\n # Test case 6: checking in the search paths\n search_paths = [\n test_data_path(\n 'collections', 'test_collection', 'preview')\n ]\n img_path = 'prev_1.png'\n fixed_path = resolve_path(img_path, collection_path, search_paths)\n expected_path = test_data_path(\n 'collections', 'test_collection', 'preview', 'prev_1.png')\n self.assertEqual(fixed_path, expected_path)\n\n # Test case 7: not finding anywhere (return the original path)\n img_path = '/you/would/not/find/this/anywhere.png'\n fixed_path = resolve_path(img_path, collection_path, search_paths)\n self.assertEqual(fixed_path, img_path)\n\n\nif __name__ == \"__main__\":\n nose2.main()\n","sub_path":"test/resource_handler/test_symbol_resolver_mixin.py","file_name":"test_symbol_resolver_mixin.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"157765950","text":"from setuptools import setup, find_packages\n\nimport pip.download\nfrom pip.req import parse_requirements\n\n\ndef get_requirements():\n requirements = parse_requirements(\n 'requirements.txt',\n session=pip.download.PipSession()\n )\n return [str(r.req) for r in list(requirements)]\n\n\nsetup(\n name='avs_client',\n version='0.7.0',\n packages=find_packages(exclude=[\"tests.*\", \"tests\"]),\n url='https://github.com/richtier/alexa-voice-service-client',\n license='MIT',\n author='Richard Tier',\n author_email='rikatee@gmail.com',\n description='Python Client for Alexa Voice Service (AVS)',\n #long_description=open('README.rst').read(),\n include_package_data=True,\n install_requires=get_requirements(),\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: Implementation :: PyPy',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"586214991","text":"import os\nfrom webScrawer import webScrawer\nfrom threading import Thread as multiprocessline\n\nallInfo = []\ndef parseHtml(html):\n allArticles = html.find_all(id='page')[0].select('.node-blog')\n for article in allArticles:\n title = article.select('h1')[0].get_text().replace('\\n', '')\n link = 'https://www.w3cplus.com' + article.select('.node_read_more')[0].get('href')\n description = article.select('.body-content')[0].get_text()\n allInfo.append({\n 'link': link,\n 'title': title,\n 'description': description,\n })\n print('{}---------------------成功解析!!'.format(title))\n\ndef moreProgress(allHtml):\n result = []\n for html in allHtml:\n t = multiprocessline(target=parseHtml, args=(html,))\n result.append(t)\n t.start()\n for t in result:\n t.join()\n\ndef main():\n urls = []\n allArticle = []\n for n in range(0, 1):\n urls.append('https://www.w3cplus.com/?page='.format(n))\n webscrawer = webScrawer(urls)\n webscrawer.startCrawUrl()\n moreProgress(webscrawer.backResult)\n webscrawer.saveFile('w3cplus.js', allInfo)\n print('总共数据:{}条'.format(len(allInfo)))\n\nmain()\n","sub_path":"w3cplus.py","file_name":"w3cplus.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"623319352","text":"# NOTE:\n# This example will be merged with user.py\n# when detector interface is ready for all detectors\n\nimport os\nfrom psana import DataSource\n\ndef filter(evt):\n return True\n\nxtc_dir = \"/reg/d/psdm/xpp/xpptut15/scratch/mona/cxid9114\"\nds = DataSource('exp=xpptut13:run=1:dir=%s'%(xtc_dir), filter=filter)\ndet = None\nif ds.nodetype == \"bd\":\n det = ds.Detector(\"DsdCsPad\")\n\nfor run in ds.runs():\n for evt in run.events():\n if det:\n raw = det.raw(evt)\n print(raw.shape)\n","sub_path":"psana/psana/tests/cctbx.py","file_name":"cctbx.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"113089667","text":"import shutil\nimport subprocess\nimport sys\nimport os\nimport locale\n\nfrom archupgrade.common import pacmanArchupgradeTmpDir, pacmanArchupgradeLogFile\nimport archupgrade.hooks as hooks\nimport archupgrade.news as news\n\n#The real pacman log.\npacmanLogFile = '/var/log/pacman.log'\npacmanDBPath = '/var/lib/pacman/'\npacmanSyncDir = pacmanDBPath + 'sync/'\npacmanLocalDir = pacmanDBPath + 'local/'\npacmanArchupgradeTmpDBLockFile = pacmanArchupgradeTmpDir + 'db.lck'\n\ndef bytes2XiB(dlSum):\n #Format the download sum for user reading.\n sumStr = '{} {}iB'\n if dlSum < 1024:\n sumStr = str(dlSum) + ' B'\n elif dlSum < 1024*1024:\n sumStr = sumStr.format(locale.format('%.2f', dlSum/1024.0, True), 'K')\n elif dlSum < 1024*1024*1024:\n sumStr = sumStr.format(locale.format('%.2f', dlSum/(1024.0*1024.0), True), 'M')\n elif dlSum >= 1024*1024*1024:\n sumStr = sumStr.format(locale.format('%.2f', dlSum/(1024.0*1024.0*1024.0), True), 'G')\n\n return sumStr\n#End: def bytes2XiB():\n\ndef handlePrompts():\n #Find out if pacman needs to ask the user to make choises between packages.\n #Run pacman to see what the first prompt is. Merge stderr into stdout, since pacman seems to send prompts via stderr.\n #Use the temporary package database, (which has been updated -- the ordinary database has not been updated), and don't touch the ordinary pacman.log.\n #This call to pacman, does not try to connect to the internet. So it is not needed to try to make this call resilient to internet outages.\n output = ''\n p = subprocess.Popen(['pacman', '--dbpath', pacmanArchupgradeTmpDir, '--logfile', pacmanArchupgradeLogFile, '-Su'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env={\"LANG\":\"\"})\n while True:\n #Collect output.\n output += p.stdout.read(1).decode()\n #Check for prompts in the output.\n if ':: Replace ' in output or 'Enter a number (default=' in output or ' are in conflict. Remove ' in output:\n p.terminate()\n #If the user hasn't requested to manually upgrade the system...\n if (len(sys.argv) == 1) or (len(sys.argv) > 1 and sys.argv[1] != '-m'):\n print(_('There are new upgrades, but they need someone to answer questions about how to handle them, for the upgrade to be successful.'))\n #Translators: {program} will be substituted with the name of the program.\n print(_('Either contact someone to help you answer the questions, or run \"{program} -m\" as root, to do it yourself.').format(program=sys.argv[0]))\n exit(0)\n else:\n return\n if ':: Proceed with installation? [Y/n]' in output:\n del output\n p.terminate()\n #pacman doesn't remove the database lock file when recieving the SIGTERM signal, so the script must do that, in order for subsequent calls to pacman to succeed.\n if os.path.exists(pacmanArchupgradeTmpDBLockFile):\n os.remove(pacmanArchupgradeTmpDBLockFile)\n return\n#End: def handlePrompts():\n\ndef upgrade():\n lastUpgrades = ''\n answer = ''\n try:\n #In case somehow the temporary directory was not removed after a previous upgrade.\n shutil.rmtree(pacmanArchupgradeTmpDir)\n except FileNotFoundError:\n pass\n #Copy the sync database files to the temporary directory, so the originals can be left untouched.\n #The copy of the sync database needs to be updated to get the latest package versions.\n #In many cases this copy should speed up the check a little, because copying a few small files is faster than downloading them, and often they are up to date, so newer versions don't need to be downloaded.\n shutil.copytree(pacmanSyncDir, pacmanArchupgradeTmpDir+'sync/')\n #Make a symlink to the local package database of installed packages, so pacman can look up installed package versions.\n #This will greatly speed up the check, because making a single symlink is much faster than copying thousands of small files.\n #It is also safe, because the check will not need to change the database of installed files.\n os.symlink(pacmanLocalDir[:-1], pacmanArchupgradeTmpDir+'local')\n\n while True:\n hooks.execute('pre-check-news')\n #Check news.\n if not news.isHandled():\n exit(0)\n\n hooks.execute('pre-check-upgrades')\n #Check for upgrades.\n #Get a list of package names of packages that can be upgraded, as well as their potential new to install dependencies.\n #The list includes lines about fetching database files -- they will be removed a little later.\n #The individual upgrades's byte size is prepended the package name, like so: :\n #Don't touch the ordinary package database or the ordinary pacman log file.\n #The returned packages are separated by a newline.\n #If there are no upgrades, this will yild an empty string.\n print(_('Looking for new upgrades')+'...')\n try:\n upgrades = subprocess.run(['pacman', '--dbpath', pacmanArchupgradeTmpDir, '--logfile', pacmanArchupgradeLogFile, '-Syup', '--print-format', '%s:%n'], universal_newlines=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={'LANG':''}).stdout.strip().split('\\n')\n except subprocess.CalledProcessError as e:\n #If the connection to the internet is lost right before checking for new upgrades, pacman will exit with returncode 1, which raises this exception.\n #Since the check for upgrades does not need to output anything from pacman to the user, this script has the benefit of being able to capture both stdout and stderr for analysis. Thus, in case of error, the script can try to output some helpful information to the user.\n if 'error: failed to init transaction (download library error)' in e.stderr:\n print(_('Could not check for new upgrades, because no package archives were accessible on the internet.'))\n else:\n print('cmd:')\n print(e.cmd)\n print('returncode:')\n print(e.returncode)\n print('output:')\n print(e.output)\n print('stdout:')\n print(e.stdout)\n print('stderr:')\n print(e.stderr)\n print(_(\"Could not check for new upgrades. Don't know why.\"))\n print(_('Please send the above information to your systems administrator.'))\n print(_('The system will not be upgraded at this time.'))\n print(_('You will have to upgrade some other time.'))\n exit(0)\n\n #Remove lines that do not contain package information.\n upgrades = [upgrade for upgrade in upgrades if upgrade.split(':',1)[0].isdigit()]\n\n if upgrades == []:\n print(_('No new upgrades since last check.'))\n exit(0)\n\n #There are upgrades available, and all news have been handled, so proceed with upgrading.\n #Get the download size from the byte sizes of the upgrades.\n dlSum = bytes2XiB(sum([int(upgrade.split(':', 1)[0]) for upgrade in upgrades]))\n #Get the package names of the upgrades as a one line string with space between package names.\n upgrades = ' '.join([upgrade.split(':', 1)[1] for upgrade in upgrades])\n\n if upgrades != lastUpgrades: #Only prompt if the upgrades have changed since last check.\n #If there are no arguments, or the first argument does not request a manual upgrade, then handle prompts.\n if len(sys.argv) == 1 or (len(sys.argv) > 1 and sys.argv[1] != '-m'):\n handlePrompts()\n #If the script continues after handeling prompts, either the upgrade can be done automatically, or the user has opted to do it manually.\n print(_('There are new upgrades which must download the following packages:'))\n print()\n print(upgrades)\n print()\n #Translators: {bytes} will be substituted with a byte size, like '1.35KiB'.\n print(_('A total of {bytes} data must be fetched.').format(bytes=dlSum))\n print()\n print(_('Do you want to upgrade now (yes/no + Enter)?')+' ', end='', flush=True)\n answer = input()\n if len(answer) == 0:\n answer = 'n'\n else:\n answer = answer[0].lower()\n\n #Translators: This is the first letter of the answer 'yes', to the question of whether the user wants to upgrade now.\n #Translators: The letter must be lower case.\n #Translators: For example, the Danish translation of the answer is 'ja', and thus the final translation must be 'j'.\n if answer == _('y'):\n if upgrades != lastUpgrades:\n lastUpgrades = upgrades\n continue\n else:\n hooks.execute('pre-upgrade')\n #Delete temporary log, so the upgrade generates a log with entries only for the actual upgrade, and no entries for checking for upgrades.\n os.remove(pacmanArchupgradeLogFile)\n #Copy the updated temporary sync database to the ordinary database, so it is updated like the temporary database.\n shutil.rmtree(pacmanSyncDir)\n shutil.copytree(pacmanArchupgradeTmpDir+'sync/', pacmanSyncDir)\n\n #Upgrade.\n #If the internet connection is lost before or during package download, pacman will not upgrade anything, but will exit successfully (returncode 0 / no exceptions).\n #So this script will not experience any errors in this particular situation, and it will run its remaining tasks, after calling pacman during an internet outage.\n if len(sys.argv) == 1:\n #Automatic upgrade.\n subprocess.run(['pacman', '--logfile', pacmanArchupgradeLogFile, '--noconfirm', '-Su'])\n else:\n #Manual upgrade.\n subprocess.run(['pacman', '--logfile', pacmanArchupgradeLogFile, '-Su'])\n\n #Remove --logfile and --noconfirm' from the log, and add y to -Su in the log, so the upgrade appears to have been done normally.\n with open(pacmanArchupgradeLogFile, 'r') as logfile:\n log = logfile.read()\n log = log.replace(' --noconfirm', '')\n log = log.replace(' --logfile {}'.format(pacmanArchupgradeLogFile), '')\n log = log.replace('pacman -Su', 'pacman -Syu')\n #Append the upgrade log to the ordinary log.\n with open(pacmanLogFile, 'a') as logfile:\n logfile.write(log)\n\n hooks.execute('post-upgrade')\n #Break the loop, so the script can end.\n break\n else: #answer = no\n print(_('You will be upgrading some other time.'))\n exit(0)\n #End while\n exit(0)\n#End: def upgrade():\n","sub_path":"usr/lib/archupgrade/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":11072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"159952114","text":"#\n# Copyright (c) 2015 Autodesk Inc.\n# 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#\nimport logging\nimport json\nimport os\nfrom toolset.io import fire, run, ZK\nfrom random import choice\nfrom toolset.tool import Template\n\n#: Our ochopod logger.\nlogger = logging.getLogger('ochopod')\n\ndef go():\n\n class _Tool(Template):\n\n help = \\\n \"\"\"\n Tool for polling the metrics returned during sanity checks.\n \"\"\"\n\n tag = 'poll'\n\n def customize(self, parser):\n\n parser.add_argument('clusters', type=str, nargs='+', help='1+ clusters (can be a glob pattern, e.g foo*).')\n parser.add_argument('-j', '--json', action='store_true', help='switch for json output')\n\n def body(self, args, proxy):\n\n #\n # - grab the user metrics returned in sanity_check()\n # - those are returned via a POST /info\n #\n outs = {}\n\n for token in args.clusters:\n\n def _query(zk):\n replies = fire(zk, token, 'info')\n return len(replies), {key: hints['metrics'] for key, (index, hints, code) in replies.items() if code == 200 and 'metrics' in hints}\n\n total, js = run(proxy, _query)\n\n outs.update(js)\n\n #\n # - prettify if not asked for a json string\n #\n if js and not args.json:\n\n pct = (len(js) * 100) / total\n logger.info('%d pods, %d%% replies ->\\n' % (len(js), pct))\n rows = [['pod', '|', 'metrics'], ['', '|', '']] + sorted([[key, '|', json.dumps(val)] for key, val in js.iteritems()])\n widths = [max(map(len, col)) for col in zip(*rows)]\n for row in rows:\n logger.info(' '.join((val.ljust(width) for val, width in zip(row, widths))))\n\n if args.json:\n\n logger.info(json.dumps(outs))\n\n return _Tool()\n","sub_path":"images/portal/resources/toolset/toolset/commands/poll.py","file_name":"poll.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497177968","text":"\"\"\"\nThis is a module to be used as a reference for building other modules\n\"\"\"\nimport numpy as np\nfrom sklearn.base import BaseEstimator, ClassifierMixin, TransformerMixin\nfrom sklearn.utils.validation import check_X_y, check_array, check_is_fitted\nfrom sklearn.utils.multiclass import unique_labels\nfrom sklearn.metrics import mean_squared_error\n\nfrom scipy.optimize import minimize\nfrom scipy.signal import savgol_filter\nfrom scipy import interpolate\n\n\nclass MeanRegularizedExtrapolation(BaseEstimator):\n \"\"\" A template estimator to be used as a reference implementation.\n For more information regarding how to build your own estimator, read more\n in the :ref:`User Guide `.\n Parameters\n ----------\n A parameter of time series depth for linear regression.\n \"\"\"\n def __init__(self, lag=10, offset=0, extrapolation='linear', savgol=False, filter_window=10, filter_polyorder=2):\n self.lag = lag\n self.extrapolation = extrapolation\n self.alpha = 0.\n self.offset = offset\n self.y_shape = 1\n self.savgol = savgol\n self.filter_window = filter_window\n self.filter_polyorder = filter_polyorder\n\n# def _more_tags(self):\n# return {'multioutput_only': True, 'multioutput': True}\n\n def fit(self, X, y):\n \"\"\"A reference implementation of a fitting function.\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,) or (n_samples, n_outputs)\n The target values (class labels in classification, real numbers in\n regression).\n Returns\n -------\n self : object\n Returns self.\n \"\"\"\n\n if X.shape[1] < self.lag:\n raise ValueError(\"Lag must be less than number of features\")\n\n X, y = check_X_y(X, y, accept_sparse=True, multi_output=True, y_numeric=True)\n\n min_result = minimize(self.mse_alpha, 0.9, args=(X, y, self.lag), method='L-BFGS-B', \n bounds=[(1e-10,1.-1.e-10)])\n\n self.y_shape = y.shape[1]\n\n self.alpha = min_result.x \n\n self.is_fitted_ = True\n # `fit` should always return `self`\n return self\n\n def predict(self, X):\n \"\"\" A reference implementation of a predicting function.\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n The training input samples.\n Returns\n -------\n y : ndarray, shape (n_samples,)\n Returns an array of ones.\n \"\"\"\n X = check_array(X, accept_sparse=True)\n check_is_fitted(self, 'is_fitted_')\n\n y = np.ndarray(shape=(X.shape[0], self.y_shape))\n\n for iX in np.arange(X.shape[0]):\n sX = X[iX]\n #print(iX, X[iX])\n if self.extrapolation == 'linear':\n y[iX,:] = self.mean_reg_extrapolate(np.arange(sX.size), sX, \n np.arange(self.y_shape)+self.offset+sX.size, \n lag=self.lag, alpha=self.alpha)\n\n return y \n\n def mean_reg_extrapolate(self, x, y, x_pred, lag=10, alpha=0):\n \n #print(x,y)\n # filter y values to get smoother extrapolation\n if self.savgol:\n y_interp = savgol_filter(y[-lag:], self.filter_window, self.filter_polyorder)\n else:\n y_interp = y[-lag:]\n\n f = interpolate.interp1d(x[-lag:], y_interp, kind='linear', fill_value='extrapolate')\n my = np.mean(y)\n \n if alpha < 0 or alpha > 1:\n return np.zeros(x_pred.shape)\n \n y_pred = f(x_pred) - alpha*(f(x_pred)-my)\n \n return y_pred\n\n\n def mse_alpha(self, alpha, X, y, lag):\n mse = 0.\n\n for sX, sy in zip(X,y):\n if self.extrapolation == 'linear':\n xpred_offset = sX.size+self.offset\n #print(np.arange(sy.size)+xpred_offset)\n\n sy_extr = self.mean_reg_extrapolate(np.arange(sX.size), sX, \n np.arange(sy.size)+xpred_offset, lag=lag, alpha=alpha)\n #print(sy, sy_extr)\n mse = mse+mean_squared_error(sy, sy_extr)**2\n\n mse = np.sqrt(mse)\n\n return mse\n","sub_path":"gasopt/MeanRegularizedExtrapolation.py","file_name":"MeanRegularizedExtrapolation.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"438183765","text":"from setuptools import setup\r\n\r\nwith open(\"README.md\", \"r\") as fh:\r\n long_description = fh.read()\r\n\r\nsetup(\r\n name='E2Yaml', # How you named your package folder (MyLib)\r\n packages=['E2Yaml'], # Chose the same as \"name\"\r\n version='0.4.1', # Start with a small number and increase it with every change you make\r\n license='MIT', # Chose a license from here: https://help.github.com/articles/licensing-a-repository\r\n description='An Environment Variable to Yaml Converter', # Give a short description about your library\r\n long_description=long_description,\r\n long_description_content_type=\"text/markdown\",\r\n author='Joseph Procopio', # Type in your name\r\n author_email='josephp27@live.com', # Type in your E-Mail\r\n url='https://github.com/josephp27/E2Yaml', # Provide either the link to your github or to your website\r\n download_url='https://github.com/josephp27/E2Yaml/archive/0.4.1.tar.gz', # I explain this later on\r\n keywords=['Yaml', 'Converter', 'Environment', 'Variables'], # Keywords that define your package best\r\n classifiers=[\r\n \"Programming Language :: Python :: 3\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Operating System :: OS Independent\",\r\n ],\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"81373609","text":"from random import randint\n\ndef abberant_stat():\n x = randint (1, 6)\n return x\n\ndef stateth():\n dice_list = []\n\n for i in range (1, 5):\n die_roll = abberant_stat()\n if die_roll <= 2:\n die_roll = abberant_stat()\n dice_list.append(die_roll)\n\n print (dice_list)\n\n dice_list.remove(min(dice_list))\n\n print (dice_list)\n return sum(dice_list)\n\n\ndef rollstats():\n another_list = []\n\n for i in range (1, 7):\n name = stateth()\n another_list.append(name)\n\n my_dictionary = {\n \"stronkth\": 0,\n \"ducksderety\": 0,\n \"constipation\": 0,\n \"intelelijans\": 0,\n \"wersdum\": 0,\n \"Krisma\": 0\n }\n\n stat_values = {}\n stat_list = [\"stronkth\", \"ducksderety\", \"constipation\", \"intelelijans\", \"wersdum\", \"Krisma\"]\n for j in stat_list:\n print (another_list)\n print('Input stat:', j)\n # this_stat = int(input())\n user_input = input()\n this_stat = int(user_input)\n if int(this_stat) in another_list:\n my_dictionary[j] = this_stat\n another_list.remove(this_stat)\n else:\n raise ValueError(\"Sory dave, that numba is not in our thingee\")\n\n print(my_dictionary)\n\n","sub_path":"abbrantstat.py","file_name":"abbrantstat.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"613861600","text":"import flax\nimport jax\nfrom jax import numpy as jnp\nimport numpy as np\n\n# Flax сурах дадлага : https://flax.readthedocs.io/en/latest/notebooks/flax_guided_tour.html\n\n\n# Flax ашиглан хамгийн хялбар неорон давхарга тодорхойлох\nclass Dense(flax.nn.Module):\n def apply(self,x,\n features,\n kernel_initialization = jax.nn.initializers.lecun_normal(),\n bias_initialization = jax.nn.initializers.zeros\n ):\n input_features = x.shape[-1]\n kernel_shape = (input_features, features)\n kernel = self.param('kernel', kernel_shape, kernel_initialization)\n bias = self.param('bias' , (features,) , bias_initialization )\n return jnp.dot(x, kernel) + bias\n\n\n# Неорон сүлжээний оролтын өгөгдлийг бэлтгэх\n# энд 1 ширхэг дата буюу batch нь 1 гэсэн үг 4-н оролтын өгөгдлийн дүрс\nx = jnp.ones((1, 4))\n\n# Оролтын өгөгдлийн дүрсээс хамааруулан неорон сүлжээний жингүүдийг \n# эхний байдлаар цэнэглэн гаргаж авах\ny, params = Dense.init(jax.random.PRNGKey(0), x, features=4)\nprint(\"Неорон сүлжээний эхний цэнэглэгдсэн параметрүүд :\")\nprint(params)\nprint(\"Эхний байдлаар predict хийсэн гаралт :\")\nprint(y)\n\n# Цэнэглэгдсэн параметрүүдээ хэрэглэн энгийн predict хийх forward дуудалт\nprediction = Dense.call(params, x, features=4)\nprint(\"predict хийсэн дуудалт :\")\nprint(prediction)\n\n\n# Зөвхөн hyperparameter-үүд тохируулсан модуль үүсгэе гэвэл partial функц ашиглаж болно\nmodule = Dense.partial(features=4)\n# Дараа нь жингүүдээ цэнэглэж болно\n_, params = module.init(jax.random.PRNGKey(0), x)\nprint(\"Модуль үүсгэсний дараа цэнэглэсэн жингүүд :\")\nprint(params)\n# Модуль хэрэглэн forward дуудалт хийх\nprediction = module.call(params, x)\nprint(\"Модулиас хийсэн prediction дуудалтын үр дүн :\")\nprint(prediction)\n\n\n# Модуль ашигласнаар хооронд нь хольж бүрдүүлж болдог нарийн \n# бүтэцтэй неорон сүлжээ зохион байгуулах боломж бүрддэг\n\ndef relu(x):\n return jnp.maximum(0., x)\n\n# Multi Layer Perceptron буюу олон давхаргатай хялбар неорон сүлжээ\nclass MLP(flax.nn.Module):\n def apply(self, x,\n hidden_features,\n output_features,\n activation_fn):\n z = Dense(x, hidden_features)\n h = activation_fn(z)\n y = Dense(h, output_features)\n return y\n\nmodule = MLP.partial(hidden_features=8, output_features=4, activation_fn=relu)\ny, params = module.init(jax.random.PRNGKey(0), x)\n# Нарийн бүтэцтэй олон давхаргатай неорон сүлжээ бий болгосон учраас \n# параметрүүд нь шаталсан бүтэцтэй dictionary байна\nprint(\"MLP параметрүүд :\")\nprint(params)\nprint(\"MLP predict хийсэн утгууд :\")\nprint(y)\n\n\n# Хэрвээ неорон давхаргад нэр оноогоогүй байвал автоматаар дугаарлагдаад явна\n# тогтсон нэр өгч ашиглах боломжтой\n\nclass NamedMLP(flax.nn.Module):\n def apply(self, x,\n hidden_features,\n output_features,\n activation_fn):\n z = Dense(x, hidden_features, name='hidden')\n h = activation_fn(z)\n y = Dense(h, output_features, name='out')\n return y\n\nmodule = NamedMLP.partial(hidden_features=8, output_features=4, activation_fn=relu)\n_, params = module.init(jax.random.PRNGKey(0), x)\n\nprint(\"Нэрлэсэн давхаргууд бүхий неорон сүлжээний бүтэц :\")\nprint(jax.tree_map(np.shape, params))\n\n\n# Олон call дуудалтанд дундын parameter-рүүд хэрэглэж болно\n\nclass SimpleRNN(flax.nn.Module):\n def apply(self, x, iterations=3):\n dense = Dense.shared(features=x.shape[-1],\n kernel_initialization=jax.nn.initializers.orthogonal(), name='cell')\n ys = []\n for i in range(iterations):\n x = dense(x)\n ys.append(x)\n return ys\n\nys, params = SimpleRNN.init(jax.random.PRNGKey(0), x)\nprint(\"Хялбар Recurrent Neural Network-ийн гаралт :\")\nprint(ys)\n\n# cell давхаргыг 3-н удаа дуудсанч shared параметер горимоор үүсгээн тул нэмэлтээр \n# 3-н давхарга болж орж ирэхгүй нэг л давхарга байдлаар харагдана гэсэн үг\n# {'cell': {'bias': (4,), 'kernel': (4, 4)}}\nprint(\"Recurrent Neural Network-ийн параметер бүтэц :\")\nprint(jax.tree_map(np.shape, params))\n\n\n# Оролтын өгөгдлийн дүрснээс хамаарч модулийг init хийх нь заримдаа шаардлагагүй нэмэлт \n# үйлдлүүд хийгдэх магадлалтай, зөвхөн оролтын дүрс нь ямар вэ гэдгээр init хийж болно\n# {'cell': {'bias': (2,), 'kernel': (2, 2)}}\ninput_spec = [(1,2)]\nout_spec, params = SimpleRNN.init_by_shape(jax.random.PRNGKey(0), input_spec)\nprint(\"Shape inference горимоор барьсан неорон сүлжээний бүтэц :\")\nprint(jax.tree_map(np.shape, params))\n\n\n# Модуль хэрэглэснээр неорон сүлжээний параметрүүдийг init болон call функцын тусламжтайгаар\n# ил хэлбэрээр track хийх боломж олгодог. Model класс бол Module классын багахан өргөтсөн\n# хэлбэр бөгөөд заавал параметрүүдийг нь track хийж байн байн дамжуулаад байх шаардлагагүй\nx = jnp.ones((1,2))\nmodule = Dense.partial(features=4)\nys, initial_params = module.init(jax.random.PRNGKey(0), x)\nmodel = flax.nn.Model(module, initial_params)\nprint(\"Моделийн бүтцийг харах :\")\nprint(jax.tree_map(np.shape, model.params))\n\nprediction = model(x)\nprint(\"Моделиор predict хийсэн үр дүн :\")\nprint(prediction)\n\nprint(\"Моделийн параметрүүд :\")\nprint(model.params)\n\n\n# Моделийн параметрүүдийг нь шинэчилж сольж болно\nbiased_model = model.replace(\n params={\n 'kernel': model.params['kernel'],\n 'bias' : model.params['bias' ]+1.\n })\n\nprint(\"Параметрүүдийг нь шинэчилсэн моделийн параметрүүд :\")\nprint(biased_model.params)\n\n\n# Модель нь JAX-ны pytree объект байдлаар зохион байгуулагддаг тул \n# JAX-н native хувиргалтуудад асуудалгүйгээр хэрэглэх боломжтой\n\n# Жишээлбэл модель объект хэрэглэн градиент утгууд олж болно\ndef loss_fn(model):\n y = model(x)\n return jnp.mean(jnp.square(y))\n\nmodel_gradients = jax.grad(loss_fn)(model)\nprint(\"Моделийн loss-оос авсан gradient утгууд\")\nprint(model_gradients.params)\n\n\n# BatchNorm мэтийн тохиолдолд batch-уудын mean, variance гэх мэт статистик өгөгдлүүдийг\n# хадгалаж хэрэглэх хэрэгцээ гардаг энэ тохиолдолд Module.state-г хэрэглэж болно\nclass BatchNorm(flax.nn.Module):\n def apply(self, x,\n red_axis = 0,\n eps = 1e-5,\n momentum = 0.99,\n training = False,\n gamma_init = jax.nn.initializers.ones,\n beta_init = jax.nn.initializers.zeros\n ):\n # Оролтын моментүүдийг тооцоолох\n mean = x.mean(red_axis, keepdims=True)\n var = jnp.square(x-mean).mean(red_axis, keepdims=True)\n # State хувьсагчууд тодорхойлох\n ra_mean = self.state('mean', mean.shape, jax.nn.initializers.zeros)\n ra_var = self.state('var' , var.shape , jax.nn.initializers.ones )\n # Жингүүдийг эхний байдлаар цэнэглэж байгаа бол \n # average утгуудыг тооцох шаардлага байхгүй\n if not self.is_initializing():\n if training:\n # Сургаж байгаа үед average-үүдийг шинэчлэх ёстой\n alpha = 1. - momentum\n ra_mean.value += alpha*(mean - ra_mean.value)\n ra_var.value += alpha*(var - ra_var.value )\n else:\n # Сургаагүй тохиолдолд average-уудаа хэрэглэнэ\n mean = ra_mean.value\n var = ra_var.value\n # Оролтын өгөгдлөө стандартчилах\n y = (x-mean)/jnp.sqrt(var+eps)\n # Оролтын scale болон bias-уудыг суралцах\n gamma = self.param('gamma', mean.shape, gamma_init)\n beta = self.param('beta' , mean.shape, beta_init )\n return gamma*y+beta\n\n# Хэрэв state хэрэглэхээр бол flax.nn.stateful context manager ашиглана\n# Энэ state-үүд flax.nn.Collection дотор хадгалагддаг\n\nclass MyModel(flax.nn.Module):\n def apply(self, x, training=False):\n x = Dense(x, features=4)\n x = BatchNorm(x, training=training, momentum=0., name='batch_norm')\n return x\n\ndist_a = lambda rng, shape: jax.random.normal(rng, shape)*jnp.array([[1., 3.]])\nx_a = dist_a(jax.random.PRNGKey(1), (1024, 2))\nprint(\"Оролтын өгөгдлын стандарт хазайлт :\", x_a.std(0))\n\nwith flax.nn.stateful() as init_state:\n y, params = MyModel.init(jax.random.PRNGKey(2), x_a)\nprint(\"Гаралтын стандарт хазайлт (init) :\", y.std(0))\n\nwith flax.nn.stateful(init_state) as new_state:\n y = MyModel.call(params, x_a, training=True)\nprint(\"Гаралтын стандарт хазайлт (training) :\", y.std(0))\n\nwith flax.nn.stateful(new_state, mutable=False):\n y = MyModel.call(params, x_a, training=False)\nprint(\"Гаралтын стандарт хазайлт (testing) :\", y.std(0))\n\n# state өгөгдлийг Collection.as_dict() ээр шалгаж болно\nprint(\"Эхлэл state :\")\nprint(init_state.as_dict())\n\nprint(\"Шинэ state :\")\nprint(new_state.as_dict())\n\n# state тооцох механизм нь ил байх ёстой жишээлбэл \n# тест хийж байх үед state тооцоолох шаардлагагүй\n# мөн өөр оролтын өгөгдлүүд хэрэглэн өөр статистик \n# state цуглуулах шаардлага гардаг энэ тохиолд\n# ил байдлаар state тооцохын үр ашиг гардаг\ndist_b = lambda rng, shape: jax.random.normal(rng, shape)*jnp.array([[2., 5.]])\nx_b = dist_b(jax.random.PRNGKey(1), (1024, 2))\nwith flax.nn.stateful(new_state, mutable=False):\n y = MyModel.call(params, x_b, training=False)\nprint(y.std(0)) # Энэ тохиолдолд зөв нормчилогдож чадахгүй\n\nwith flax.nn.stateful(init_state) as state_b:\n y = MyModel.call(params, x_b, training=True)\nprint(\"Гаралтын стандарт хазайлт (training) :\", y.std(0))\n\nwith flax.nn.stateful(state_b, mutable=False):\n y = MyModel.call(params, x_b, training=False)\nprint(\"Гаралтын стандарт хазайлт (testing) :\", y.std(0))\n","sub_path":"jax/experiments/simplified_nn_flax.py","file_name":"simplified_nn_flax.py","file_ext":"py","file_size_in_byte":12068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455001168","text":"import logging\n\nfrom requests import Session\nfrom requests.compat import urljoin\nfrom requests.exceptions import HTTPError\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\nimport threading\nimport queue\nimport time\n\nlogger = logging.getLogger(__file__)\n\n\ndef error_handler(resp, *args, **kargs):\n if not resp.ok:\n raise HTTPError(resp.status_code, resp.json(), response=resp)\n\n\nclass ResponseCodes:\n SUCCESS = 1\n FAILURE = 2\n\n\nclass OktaAPI(object):\n def __init__(self, url, key):\n # Sessions are stateless\n self.base_url = \"https://{}\".format(url)\n self.key = key\n\n # Retry with backoff in case we get rate limited, otherwise use the error handler\n retry = Retry(total=3, backoff_factor=5, status_forcelist=[429])\n adapter = HTTPAdapter(max_retries=retry)\n\n session = Session()\n session.headers['Authorization'] = 'SSWS {}'.format(self.key)\n session.headers['Accept'] = 'application/json'\n session.headers['User-Agent'] = 'pyrad/1.0'\n session.hooks = {'response': [error_handler, ]}\n session.mount('https://', adapter)\n\n self.session = session\n\n def _get(self, url, params=None):\n r = self.session.get(url, params=params)\n\n return r.json()\n\n def _post(self, url, params=None, json=None):\n r = self.session.post(url, params=params, json=json)\n\n return r.json()\n\n def get_user_id(self, username):\n url = urljoin(self.base_url, 'api/v1/users/{}'.format(username))\n\n page = self._get(url)\n\n return page[\"id\"]\n\n def get_user_push_factor(self, user_id):\n url = urljoin(self.base_url, 'api/v1/users/{}/factors'.format(user_id))\n\n page = self._get(url)\n\n # Return the first push factorType in the array, otherwise return None (no factor setup)\n try:\n return next(item for item in page if item[\"factorType\"] == \"push\")\n except StopIteration:\n return None\n\n def poll_verify(self, url, q):\n t = 0\n while True:\n page = self._get(url)\n\n if page[\"factorResult\"] == \"SUCCESS\":\n q.put(\"SUCCESS\")\n return\n elif page[\"factorResult\"] == \"REJECTED\":\n q.put(\"FAILED\")\n return\n\n time.sleep(4)\n t += 4\n\n if t > 60:\n return\n\n def push_verify(self, user_id, factor_id):\n url = urljoin(self.base_url, 'api/v1/users/{}/factors/{}/verify'.format(user_id, factor_id))\n\n page = self._post(url)\n\n poll_url = page[\"_links\"][\"poll\"][\"href\"]\n\n q = queue.Queue()\n thread = threading.Thread(target=self.poll_verify, args=(poll_url, q))\n thread.start()\n thread.join()\n\n if q.qsize() > 0:\n if q.get() == \"SUCCESS\":\n return ResponseCodes.SUCCESS\n\n return ResponseCodes.FAILURE\n\n","sub_path":"okta.py","file_name":"okta.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129419205","text":"from .dataset import Dataset\nimport torch\n\n\nclass ListDataset(Dataset):\n \"\"\"\n Considering a `list` (can be a `string`, `torch.LongTensor`, or any other\n iterable) i-th sample of a dataset will be returned by `load(list[i])`,\n where `load()` is a closure provided by the user.\n\n If `path` is provided, list is assumed to be a list of string, and will\n each element `list[i]` will prefixed by `path/` when fed to `load()`.\n Purpose: many low or medium-scale datasets can be seen as a list of files\n (for example representing input samples). For this list of file, a target\n can be often inferred in a simple manner.\n \"\"\"\n def __init__(self, elem_list, load, path=None):\n super(ListDataset, self).__init__()\n if isinstance(elem_list, str):\n with open(elem_list) as f:\n self.list = [line.replace('\\n','') for line in f]\n elif torch.is_tensor(elem_list):\n assert isinstance(elem_list, torch.LongTensor), \\\n \"Only torch.LongTensor supported as list\"\n assert elem_list.dim() == 1\n self.list = elem_list\n else:\n # just assume iterable\n self.list = elem_list\n self.path = path \n self.load = load\n\n def __len__(self):\n return len(self.list)\n\n def __getitem__(self, idx):\n super(ListDataset, self).__getitem__(idx)\n if self.path is not None:\n return self.load(\"%s/%s\" % (self.path, self.list[idx]))\n else:\n return self.load(self.list[idx])\n","sub_path":"torchnet/dataset/listdataset.py","file_name":"listdataset.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"226148712","text":"import urllib.request\nimport os\nimport re\nimport sqlite3\nimport datetime\nimport re\nfrom PIL import Image\nimport urllib.request\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\n\n\n\npalabrasProhibidas = [\"/gp/\",\"amazon.es/s\",\"/hz/\",\"ie=UTF8&qid=\",\"#\",\"amazon.es/b\",\"amazon.es/dp/\",\n \"https://advertising\",\"www.amazon.com\",\"/Mejor-Valorados\",\"/music/\"]\ndef extrae_web(url):\n options = webdriver.ChromeOptions()\n options.add_argument('--incognito')\n options.add_argument('--headless')\n options.add_argument('--disable-extensions')\n options.add_argument('start-maximized')\n options.add_argument('disable-infobars')\n browserdriver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\\Web Driver\\chromedriver.exe')\n browserdriver.get(url)\n content = browserdriver.page_source\n soup = BeautifulSoup(content, 'lxml')\n\n return soup\n\ndef extrae_info(url):\n\n datos = extrae_web(url)\n\n if datos != None:\n ASIN = datos.find(\"td\", class_=\"attrG\")\n print(ASIN)\n\n\n return ASIN\n\n\nif __name__ == '__main__':\n url = \"https://www.amazon.es/s?k=juegos+switch&rh=p_8%3A15-99\"\n paginacion = \"&page=\"\n pag = 1\n num = 1\n print(url + paginacion + str(pag))\n conexion = sqlite3.connect(\"db.sqlite3\")\n\n cursorobj = conexion.cursor()\n cursorobj.execute(\"DELETE FROM servicios_nintendo\")\n cursorobj.execute(\"DELETE FROM sqlite_sequence WHERE name = 'servicios_nintendo'\")\n #cursorobj.execute(\"CREATE TABLE ofertas( name text, url text, precio text)\")\n\n while pag != 3:\n\n link = extrae_web(url + paginacion + str(pag))\n listaofertas = link.find_all(\"div\", class_=\"sg-col-inner\")\n pag += 1\n\n for j in listaofertas:\n nombre = j.find(\"span\", class_=\"a-size-base-plus a-color-base a-text-normal\")\n enlaceoferta = j.find(\"a\", class_=\"a-link-normal a-text-normal\")\n precio = j.find(\"span\", class_=\"a-price-whole\")\n imagen = j.find(\"img\", class_=\"s-image\")\n desc = j.find(\"span\", class_=\"a-price a-text-price\")\n\n if nombre != None:\n\n nombre = str(nombre.text)\n regex = re.compile(r\"'\") #se buscan comillas simples en el nombre\n result = regex.sub('#comilla#', nombre) #se sustituye por #comillas# y luego cuando se presente en web hay que sustituirla\n\n if precio != None:\n\n precio = str(precio.text)\n #total2 = precio.replace(\",\", \".\")\n #total2 = float(total2)\n #print(total2)\n if enlaceoferta != None:\n enlaceoferta = str(\"https://amazon.es/\" + enlaceoferta[\"href\"])\n if imagen != None:\n imagen = str(imagen[\"src\"])\n\n print(result + \" \" + precio)\n print(\"URL: \")\n print(enlaceoferta)\n print(\"URL Image: \")\n print(imagen)\n fullfilename = os.path.join(\"media\\\\imagenes\\\\Videojuegos\\\\Nintendo\", \"ofertanintendo\" + str(num) + \".jpg\")\n urllib.request.urlretrieve(imagen, fullfilename)\n im = Image.open(\"media\\\\imagenes\\\\Videojuegos\\\\Nintendo\\\\ofertanintendo\" + str(num) + \".jpg\")\n\n #print(im.size)\n if desc != None:\n\n desc = str(desc.text)\n print(\"descuento origina \" + desc)\n\n #desc_trunc = desc.replace(\"€\", \" \")\n desc = desc.split()\n print(desc)\n desc_trunc = str(desc[0])\n\n #total = desc_trunc.replace(\",\",\".\")\n #total = total.replace(\"€\",\"\")\n #total = float(total)\n #porcient = (((total2 * 100) / total)-100)\n #print(desc_trunc)\n #print(total)\n #print(porcient)\n print(desc_trunc)\n\n\n\n if im.width <= 50 and im.height >= 300: # se ignoran las imagenes largas\n\n pass\n print(\"Exception ignored\")\n else:\n img = im.resize((180, 230))\n img.save('media\\\\imagenes\\\\Videojuegos\\\\Nintendo\\\\ofertanintendo' + str(num) + '.jpg', 'JPEG')\n direccion_imagen = 'media\\\\imagenes\\\\Videojuegos\\\\Nintendo\\\\ofertanintendo' + str(num) + '.jpg'\n print(img.size)\n num += 1\n cursorobj.execute(\"INSERT INTO servicios_nintendo (titulo, enlace, precio, desc, created, updated, imagen) VALUES ('\" + result + \"','\" + enlaceoferta + \"', '\" + precio + \"', '\" + desc_trunc + \"', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '\" + direccion_imagen + \"')\")\n else:\n if im.width <= 50 and im.height >= 300: # se ignoran las imagenes largas\n\n pass\n print(\"Exception ignored\")\n else:\n img = im.resize((180, 230))\n img.save('media\\\\imagenes\\\\Videojuegos\\\\Nintendo\\\\ofertanintendo' + str(num) + '.jpg', 'JPEG')\n direccion_imagen = 'media\\\\imagenes\\\\Videojuegos\\\\Nintendo\\\\ofertanintendo' + str(num) + '.jpg'\n print(img.size)\n num += 1\n cursorobj.execute(\n \"INSERT INTO servicios_nintendo (titulo, enlace, precio, desc, created, updated, imagen) VALUES ('\" + result + \"','\" + enlaceoferta + \"', '\" + precio + \"', '\" + \"DESC_VACIO\" + \"', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '\" + direccion_imagen + \"')\")\n\n\n\n\n\nconexion.commit()\nconexion.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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":"amazon_swtich.py","file_name":"amazon_swtich.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"434033569","text":"from django.shortcuts import render, redirect\nfrom .models import direct\nfrom .forms import directForm\nimport os\n\n\ndef main(request):\n return render(request, 'main/main.html')\n\n\ndef add(request):\n error = ''\n if request.method == 'POST':\n form = directForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('main')\n else:\n error = 'Фома была некорректной'\n\n form = directForm()\n context = {\n 'form': form,\n 'error': error\n }\n return render(request, 'main/add.html', context)\n\n\ndef data(request):\n files = direct.objects.all()\n extensions = []\n for el in files:\n extensions.append(os.path.splitext(el.samFile.path)[1][1:])\n fusion = zip(files, extensions)\n return render(request, 'main/data.html', {'title': 'Файлы директории',\n 'fusion': fusion,\n })\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115022322","text":"hours = float(input(\"Please enter the number of hours you work per week: \"))\n\nprint(\"\")\n\nif hours > 60:\n print(\"You mat not work this many hours per week, please retry\")\n print(\"\")\n hours = float(input(\"Please enter the number of hours you work per week: \"))\n\n\nhourlyrate = float(input(\"Please enter your hourly rate in GBP: \"))\n\nprint(\"\")\n\nrateifunder40 = hours*hourlyrate\n\nif hours > 40:\n extrahours = hours - 40\n extrapay = extrahours*1.5\n grosspay = rateifunder40+extrahours\n print(\"You earn £{0} per week (Excluding tax)\".format(grosspay))\nelse:\n print(\"You earn £{0} per week (Excluding tax)\".format(rateifunder40))\n","sub_path":"Itteration/gross pay.py","file_name":"gross pay.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"149108833","text":"import sys\nimport subprocess as sp\nimport itertools\n\n\ndef rflatten(seq):\n '''Recursive flatten'''\n for each in seq:\n if hasattr(each, '__iter__'):\n for s_each in rflatten(each):\n yield s_each\n else:\n yield each\n\n\ndef flatten(seq):\n '''Shallow flatten'''\n return (elem for subseq in seq for elem in subseq)\n\n\ndef chunks(seq, chunksize):\n for i in range(0, len(seq), chunksize):\n yield seq[i:i+chunksize]\n\n\ndef take(seq, size):\n it = iter(seq)\n for i in range(size):\n yield next(it)\n\ndef ichunks(seq, chunksize):\n # Una vez que se acaban los datos sigue retornando generators\n # sin datos :(\n it = iter(seq)\n while True:\n yield take(it, chunksize)\n\ndef printbox(text, width=80):\n width = width - 2 if width > 3 else 1\n headfoot = ''.join(['+', '-' * width, '+'])\n content = '|{: ^' + str(width) + '}|'\n lines = text.splitlines()\n\n print(headfoot)\n for line in lines:\n for logicalline in chunks(line, width):\n print(content.format(logicalline))\n print(headfoot)\n\nif __name__ == '__main__':\n assert list(flatten([[1, 2, 3], [4, 5, 6]])) == [1, 2, 3, 4, 5, 6]\n\n assert list(rflatten([1, [2, [3, 4]], 5])) == [1, 2, 3, 4, 5]\n\n print(dir())\n\n printbox('Hola')\n printbox('Hola' + 'a' * 80)\n print(''.join(take('Hola', 2)))\n\n for chunk in take(ichunks(range(20), 2), 11):\n print(chunk)\n for data in chunk:\n print(data)\n\n\nclass Mock(object):\n module = sys.modules[__name__]\n\n def __getattr__(self, attr):\n try:\n return getattr(self.module, attr)\n except AttributeError:\n def _fn(*args):\n p = sp.Popen(itertools.chain([attr], args), stdout=sp.PIPE)\n out, _ = p.communicate()\n return out\n return _fn\n\nsys.modules[__name__] = Mock()\n","sub_path":"python/pendorchos.py","file_name":"pendorchos.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"244048694","text":"from typing import (\n Any,\n Callable,\n Dict,\n Iterable,\n Sequence,\n Set,\n Tuple,\n)\n\nfrom eth_utils import (\n to_dict,\n)\nfrom eth_utils.toolz import (\n curry,\n first,\n)\n\nfrom eth2.beacon import helpers\nfrom eth2._utils.numeric import (\n is_power_of_two,\n)\nfrom eth2._utils.tuple import (\n update_tuple_item,\n)\nfrom eth2.beacon.constants import (\n FAR_FUTURE_EPOCH,\n)\nfrom eth2.beacon.committee_helpers import (\n get_attester_indices_from_attestations,\n get_beacon_proposer_index,\n get_crosslink_committees_at_slot,\n get_current_epoch_committee_count,\n slot_to_epoch,\n)\nfrom eth2.beacon.configs import (\n BeaconConfig,\n CommitteeConfig,\n)\nfrom eth2.beacon.epoch_processing_helpers import (\n get_base_reward,\n get_inactivity_penalty,\n get_inclusion_infos,\n get_previous_epoch_boundary_attestations,\n get_previous_epoch_matching_head_attestations,\n get_winning_root_and_participants,\n get_total_balance,\n get_total_balance_from_effective_balances,\n get_epoch_boundary_attesting_balances,\n)\nfrom eth2.beacon.helpers import (\n get_active_validator_indices,\n get_effective_balance,\n get_epoch_start_slot,\n get_randao_mix,\n)\nfrom eth2.beacon.validator_status_helpers import (\n activate_validator,\n exit_validator,\n prepare_validator_for_withdrawal,\n)\nfrom eth2.beacon._utils.hash import (\n hash_eth2,\n)\nfrom eth2.beacon.datastructures.inclusion_info import InclusionInfo\nfrom eth2.beacon.types.attestations import Attestation\nfrom eth2.beacon.types.crosslink_records import CrosslinkRecord\nfrom eth2.beacon.types.eth1_data_vote import Eth1DataVote\nfrom eth2.beacon.types.states import BeaconState\nfrom eth2.beacon.typing import (\n Epoch,\n Gwei,\n Slot,\n ValidatorIndex,\n)\n\n\n#\n# Eth1 data votes\n#\ndef _majority_threshold(config: BeaconConfig) -> int:\n \"\"\"\n Return the value constituting the majority threshold for an Eth1 data vote.\n \"\"\"\n return config.EPOCHS_PER_ETH1_VOTING_PERIOD * config.SLOTS_PER_EPOCH\n\n\n@curry\ndef _is_majority_vote(config: BeaconConfig, vote: Eth1DataVote) -> bool:\n return vote.vote_count * 2 > _majority_threshold(config)\n\n\ndef _update_eth1_vote_if_exists(state: BeaconState, config: BeaconConfig) -> BeaconState:\n \"\"\"\n This function searches the 'pending' Eth1 data votes in ``state`` to find one Eth1 data vote\n containing majority support.\n\n If such a vote is found, update the ``state`` entry for the latest vote.\n Regardless of the existence of such a vote, clear the 'pending' storage.\n \"\"\"\n\n latest_eth1_data = state.latest_eth1_data\n\n try:\n majority_vote = first(\n filter(_is_majority_vote(config), state.eth1_data_votes)\n )\n latest_eth1_data = majority_vote.eth1_data\n except StopIteration:\n pass\n\n return state.copy(\n latest_eth1_data=latest_eth1_data,\n eth1_data_votes=(),\n )\n\n\ndef process_eth1_data_votes(state: BeaconState, config: BeaconConfig) -> BeaconState:\n next_epoch = state.next_epoch(config.SLOTS_PER_EPOCH)\n should_process = next_epoch % config.EPOCHS_PER_ETH1_VOTING_PERIOD == 0\n if should_process:\n return _update_eth1_vote_if_exists(state, config)\n return state\n\n\n#\n# Justification\n#\n\ndef _current_previous_epochs_justifiable(\n state: BeaconState,\n current_epoch: Epoch,\n previous_epoch: Epoch,\n config: BeaconConfig) -> Tuple[bool, bool]:\n \"\"\"\n Determine if epoch boundary attesting balance is greater than 2/3 of current_total_balance\n for current and previous epochs.\n \"\"\"\n\n current_epoch_active_validator_indices = get_active_validator_indices(\n state.validator_registry,\n current_epoch,\n )\n previous_epoch_active_validator_indices = get_active_validator_indices(\n state.validator_registry,\n previous_epoch,\n )\n current_total_balance = get_total_balance(\n state.validator_balances,\n current_epoch_active_validator_indices,\n config.MAX_DEPOSIT_AMOUNT,\n )\n previous_total_balance = get_total_balance(\n state.validator_balances,\n previous_epoch_active_validator_indices,\n config.MAX_DEPOSIT_AMOUNT,\n )\n\n (\n previous_epoch_boundary_attesting_balance,\n current_epoch_boundary_attesting_balance\n ) = get_epoch_boundary_attesting_balances(current_epoch, previous_epoch, state, config)\n\n previous_epoch_justifiable = (\n 3 * previous_epoch_boundary_attesting_balance >= 2 * previous_total_balance\n )\n current_epoch_justifiable = (\n 3 * current_epoch_boundary_attesting_balance >= 2 * current_total_balance\n )\n return current_epoch_justifiable, previous_epoch_justifiable\n\n\ndef _get_finalized_epoch(\n justification_bitfield: int,\n previous_justified_epoch: Epoch,\n justified_epoch: Epoch,\n finalized_epoch: Epoch,\n previous_epoch: Epoch) -> Tuple[Epoch, int]:\n\n rule_1 = (\n (justification_bitfield >> 1) % 8 == 0b111 and\n previous_justified_epoch == previous_epoch - 2\n )\n rule_2 = (\n (justification_bitfield >> 1) % 4 == 0b11 and\n previous_justified_epoch == previous_epoch - 1\n )\n rule_3 = (\n justification_bitfield % 8 == 0b111 and\n justified_epoch == previous_epoch - 1\n )\n rule_4 = (\n justification_bitfield % 4 == 0b11 and\n justified_epoch == previous_epoch\n )\n # Check the rule in the order that can finalize higher epoch possible\n # The second output indicating what rule triggered is for testing purpose\n if rule_4:\n return justified_epoch, 4\n elif rule_3:\n return justified_epoch, 3\n elif rule_2:\n return previous_justified_epoch, 2\n elif rule_1:\n return previous_justified_epoch, 1\n else:\n return finalized_epoch, 0\n\n\ndef process_justification(state: BeaconState, config: BeaconConfig) -> BeaconState:\n\n current_epoch = state.current_epoch(config.SLOTS_PER_EPOCH)\n previous_epoch = state.previous_epoch(config.SLOTS_PER_EPOCH, config.GENESIS_EPOCH)\n\n current_epoch_justifiable, previous_epoch_justifiable = _current_previous_epochs_justifiable(\n state,\n current_epoch,\n previous_epoch,\n config,\n )\n\n _justification_bitfield = state.justification_bitfield << 1\n if previous_epoch_justifiable and current_epoch_justifiable:\n justification_bitfield = _justification_bitfield | 3\n elif previous_epoch_justifiable:\n justification_bitfield = _justification_bitfield | 2\n elif current_epoch_justifiable:\n justification_bitfield = _justification_bitfield | 1\n else:\n justification_bitfield = _justification_bitfield\n\n if current_epoch_justifiable:\n new_justified_epoch = current_epoch\n elif previous_epoch_justifiable:\n new_justified_epoch = previous_epoch\n else:\n new_justified_epoch = state.justified_epoch\n\n finalized_epoch, _ = _get_finalized_epoch(\n justification_bitfield,\n state.previous_justified_epoch,\n state.justified_epoch,\n state.finalized_epoch,\n previous_epoch,\n )\n\n return state.copy(\n previous_justified_epoch=state.justified_epoch,\n justified_epoch=new_justified_epoch,\n justification_bitfield=justification_bitfield,\n finalized_epoch=finalized_epoch,\n )\n\n\n#\n# Crosslinks\n#\ndef process_crosslinks(state: BeaconState, config: BeaconConfig) -> BeaconState:\n \"\"\"\n Implement 'per-epoch-processing.crosslinks' portion of Phase 0 spec:\n https://github.com/ethereum/eth2.0-specs/blob/master/specs/core/0_beacon-chain.md#crosslinks\n\n For each shard from the past two epochs, find the shard block\n root that has been attested to by the most stake.\n If enough(>= 2/3 total stake) attesting stake, update the crosslink record of that shard.\n Return resulting ``state``\n \"\"\"\n latest_crosslinks = state.latest_crosslinks\n effective_balances = {\n ValidatorIndex(index): get_effective_balance(\n state.validator_balances,\n ValidatorIndex(index),\n config.MAX_DEPOSIT_AMOUNT,\n )\n for index in range(len(state.validator_registry))\n }\n previous_epoch_start_slot = get_epoch_start_slot(\n state.previous_epoch(config.SLOTS_PER_EPOCH, config.GENESIS_EPOCH),\n config.SLOTS_PER_EPOCH,\n )\n next_epoch_start_slot = get_epoch_start_slot(\n state.next_epoch(config.SLOTS_PER_EPOCH),\n config.SLOTS_PER_EPOCH,\n )\n for slot in range(previous_epoch_start_slot, next_epoch_start_slot):\n crosslink_committees_at_slot = get_crosslink_committees_at_slot(\n state,\n slot,\n CommitteeConfig(config),\n )\n for crosslink_committee, shard in crosslink_committees_at_slot:\n winning_root, attesting_validator_indices = get_winning_root_and_participants(\n state=state,\n shard=shard,\n effective_balances=effective_balances,\n committee_config=CommitteeConfig(config),\n )\n if len(attesting_validator_indices) > 0:\n total_attesting_balance = get_total_balance(\n state.validator_balances,\n attesting_validator_indices,\n config.MAX_DEPOSIT_AMOUNT,\n )\n total_balance = get_total_balance(\n state.validator_balances,\n crosslink_committee,\n config.MAX_DEPOSIT_AMOUNT,\n )\n if 3 * total_attesting_balance >= 2 * total_balance:\n latest_crosslinks = update_tuple_item(\n latest_crosslinks,\n shard,\n CrosslinkRecord(\n epoch=slot_to_epoch(Slot(slot), config.SLOTS_PER_EPOCH),\n crosslink_data_root=winning_root,\n ),\n )\n state = state.copy(\n latest_crosslinks=latest_crosslinks,\n )\n return state\n\n\n@to_dict\ndef _update_rewards_or_penalies(\n index: ValidatorIndex,\n amount: Gwei,\n rewards_or_penalties: Dict[ValidatorIndex, Gwei]) -> Iterable[Tuple[ValidatorIndex, Gwei]]:\n for i in rewards_or_penalties:\n if i == index:\n yield i, Gwei(rewards_or_penalties[i] + amount)\n else:\n yield i, rewards_or_penalties[i]\n\n\ndef _compute_normal_justification_and_finalization_deltas(\n state: BeaconState,\n config: BeaconConfig,\n previous_epoch_active_validator_indices: Set[ValidatorIndex],\n previous_total_balance: Gwei,\n previous_epoch_attester_indices: Set[ValidatorIndex],\n previous_epoch_boundary_attester_indices: Set[ValidatorIndex],\n previous_epoch_head_attester_indices: Set[ValidatorIndex],\n inclusion_infos: Dict[ValidatorIndex, InclusionInfo],\n effective_balances: Dict[ValidatorIndex, Gwei],\n base_rewards: Dict[ValidatorIndex, Gwei]) -> Tuple[Dict[ValidatorIndex, Gwei], Dict[ValidatorIndex, Gwei]]: # noqa: E501\n rewards_received = {\n ValidatorIndex(index): Gwei(0)\n for index in range(len(state.validator_registry))\n }\n penalties_received = rewards_received.copy()\n previous_epoch_attesting_balance = get_total_balance_from_effective_balances(\n effective_balances,\n previous_epoch_attester_indices,\n )\n previous_epoch_boundary_attesting_balance = get_total_balance_from_effective_balances(\n effective_balances,\n previous_epoch_boundary_attester_indices,\n )\n previous_epoch_head_attesting_balance = get_total_balance_from_effective_balances(\n effective_balances,\n previous_epoch_head_attester_indices,\n )\n for index in previous_epoch_active_validator_indices:\n # Expected FFG source\n if index in previous_epoch_attester_indices:\n rewards_received = _update_rewards_or_penalies(\n index,\n base_rewards[index] * previous_epoch_attesting_balance // previous_total_balance,\n rewards_received,\n )\n # Inclusion speed bonus\n rewards_received = _update_rewards_or_penalies(\n index,\n (\n base_rewards[index] * config.MIN_ATTESTATION_INCLUSION_DELAY //\n inclusion_infos[index].inclusion_distance\n ),\n rewards_received,\n )\n else:\n penalties_received = _update_rewards_or_penalies(\n index,\n base_rewards[index],\n penalties_received,\n )\n # Expected FFG target\n if index in previous_epoch_boundary_attester_indices:\n rewards_received = _update_rewards_or_penalies(\n index,\n (\n base_rewards[index] * previous_epoch_boundary_attesting_balance //\n previous_total_balance\n ),\n rewards_received,\n )\n else:\n penalties_received = _update_rewards_or_penalies(\n index,\n base_rewards[index],\n penalties_received,\n )\n # Expected head\n if index in previous_epoch_head_attester_indices:\n rewards_received = _update_rewards_or_penalies(\n index,\n (\n base_rewards[index] * previous_epoch_head_attesting_balance //\n previous_total_balance\n ),\n rewards_received,\n )\n else:\n penalties_received = _update_rewards_or_penalies(\n index,\n base_rewards[index],\n penalties_received,\n )\n # Proposer bonus\n if index in previous_epoch_attester_indices:\n proposer_index = get_beacon_proposer_index(\n state,\n inclusion_infos[index].inclusion_slot,\n CommitteeConfig(config),\n )\n rewards_received = _update_rewards_or_penalies(\n proposer_index,\n base_rewards[index] // config.ATTESTATION_INCLUSION_REWARD_QUOTIENT,\n rewards_received,\n )\n return (rewards_received, penalties_received)\n\n\ndef _compute_inactivity_leak_deltas(\n state: BeaconState,\n config: BeaconConfig,\n previous_epoch_active_validator_indices: Set[ValidatorIndex],\n previous_epoch_attester_indices: Set[ValidatorIndex],\n previous_epoch_boundary_attester_indices: Set[ValidatorIndex],\n previous_epoch_head_attester_indices: Set[ValidatorIndex],\n inclusion_infos: Dict[ValidatorIndex, InclusionInfo],\n effective_balances: Dict[ValidatorIndex, Gwei],\n base_rewards: Dict[ValidatorIndex, Gwei],\n epochs_since_finality: int) -> Tuple[Dict[ValidatorIndex, Gwei], Dict[ValidatorIndex, Gwei]]: # noqa: E501\n inactivity_penalties = {\n ValidatorIndex(index): get_inactivity_penalty(\n base_reward=base_rewards[ValidatorIndex(index)],\n effective_balance=effective_balances[ValidatorIndex(index)],\n epochs_since_finality=epochs_since_finality,\n inactivity_penalty_quotient=config.INACTIVITY_PENALTY_QUOTIENT,\n )\n for index in range(len(state.validator_registry))\n }\n rewards_received = {\n ValidatorIndex(index): Gwei(0)\n for index in range(len(state.validator_registry))\n }\n penalties_received = rewards_received.copy()\n for index in previous_epoch_active_validator_indices:\n if index not in previous_epoch_attester_indices:\n penalties_received = _update_rewards_or_penalies(\n index,\n inactivity_penalties[index],\n penalties_received,\n )\n else:\n # If a validator did attest, apply a small penalty\n # for getting attestations included late\n rewards_received = _update_rewards_or_penalies(\n index,\n (\n base_rewards[index] // config.MIN_ATTESTATION_INCLUSION_DELAY //\n inclusion_infos[index].inclusion_distance\n ),\n rewards_received,\n )\n penalties_received = _update_rewards_or_penalies(\n index,\n base_rewards[index],\n penalties_received,\n )\n if index not in previous_epoch_boundary_attester_indices:\n penalties_received = _update_rewards_or_penalies(\n index,\n inactivity_penalties[index],\n penalties_received,\n )\n if index not in previous_epoch_head_attester_indices:\n penalties_received = _update_rewards_or_penalies(\n index,\n base_rewards[index],\n penalties_received,\n )\n\n # Penalize slashed-but-inactive validators as though they were active but offline\n current_epoch = state.current_epoch(config.SLOTS_PER_EPOCH)\n for i in range(len(state.validator_registry)):\n eligible = (\n i not in previous_epoch_active_validator_indices and\n state.validator_registry[ValidatorIndex(i)].slashed and\n current_epoch < state.validator_registry[i].withdrawable_epoch\n )\n if eligible:\n penalties_received = _update_rewards_or_penalies(\n ValidatorIndex(i),\n 2 * inactivity_penalties[ValidatorIndex(i)] + base_rewards[ValidatorIndex(i)],\n penalties_received,\n )\n return (rewards_received, penalties_received)\n\n\n@curry\ndef _process_rewards_and_penalties_for_finality(\n state: BeaconState,\n config: BeaconConfig,\n previous_epoch_active_validator_indices: Set[ValidatorIndex],\n previous_total_balance: Gwei,\n previous_epoch_attestations: Sequence[Attestation],\n previous_epoch_attester_indices: Set[ValidatorIndex],\n inclusion_infos: Dict[ValidatorIndex, InclusionInfo],\n effective_balances: Dict[ValidatorIndex, Gwei],\n base_rewards: Dict[ValidatorIndex, Gwei]) -> Tuple[Dict[ValidatorIndex, Gwei], Dict[ValidatorIndex, Gwei]]: # noqa: E501\n previous_epoch_boundary_attestations = get_previous_epoch_boundary_attestations(\n state,\n config.SLOTS_PER_EPOCH,\n config.GENESIS_EPOCH,\n config.LATEST_BLOCK_ROOTS_LENGTH,\n )\n previous_epoch_boundary_attester_indices = get_attester_indices_from_attestations(\n state=state,\n attestations=previous_epoch_boundary_attestations,\n committee_config=CommitteeConfig(config),\n )\n\n previous_epoch_head_attestations = get_previous_epoch_matching_head_attestations(\n state,\n config.SLOTS_PER_EPOCH,\n config.GENESIS_EPOCH,\n config.LATEST_BLOCK_ROOTS_LENGTH,\n )\n previous_epoch_head_attester_indices = get_attester_indices_from_attestations(\n state=state,\n attestations=previous_epoch_head_attestations,\n committee_config=CommitteeConfig(config),\n )\n\n epochs_since_finality = state.next_epoch(config.SLOTS_PER_EPOCH) - state.finalized_epoch\n if epochs_since_finality <= 4:\n return _compute_normal_justification_and_finalization_deltas(\n state,\n config,\n previous_epoch_active_validator_indices,\n previous_total_balance,\n previous_epoch_attester_indices,\n previous_epoch_boundary_attester_indices,\n previous_epoch_head_attester_indices,\n inclusion_infos,\n effective_balances,\n base_rewards,\n )\n\n # epochs_since_finality > 4\n else:\n return _compute_inactivity_leak_deltas(\n state,\n config,\n previous_epoch_active_validator_indices,\n previous_epoch_attester_indices,\n previous_epoch_boundary_attester_indices,\n previous_epoch_head_attester_indices,\n inclusion_infos,\n effective_balances,\n base_rewards,\n epochs_since_finality,\n )\n\n\n@curry\ndef _process_rewards_and_penalties_for_crosslinks(\n state: BeaconState,\n config: BeaconConfig,\n effective_balances: Dict[ValidatorIndex, Gwei],\n base_rewards: Dict[ValidatorIndex, Gwei]) -> Tuple[Dict[ValidatorIndex, Gwei], Dict[ValidatorIndex, Gwei]]: # noqa: E501\n previous_epoch_start_slot = get_epoch_start_slot(\n state.previous_epoch(config.SLOTS_PER_EPOCH, config.GENESIS_EPOCH),\n config.SLOTS_PER_EPOCH,\n )\n current_epoch_start_slot = get_epoch_start_slot(\n state.current_epoch(config.SLOTS_PER_EPOCH),\n config.SLOTS_PER_EPOCH,\n )\n rewards_received = {\n ValidatorIndex(index): Gwei(0)\n for index in range(len(state.validator_registry))\n }\n penalties_received = rewards_received.copy()\n for slot in range(previous_epoch_start_slot, current_epoch_start_slot):\n crosslink_committees_at_slot = get_crosslink_committees_at_slot(\n state,\n slot,\n CommitteeConfig(config),\n )\n for crosslink_committee, shard in crosslink_committees_at_slot:\n winning_root, attesting_validator_indices = get_winning_root_and_participants(\n state=state,\n shard=shard,\n effective_balances=effective_balances,\n committee_config=CommitteeConfig(config),\n )\n total_attesting_balance = get_total_balance(\n state.validator_balances,\n attesting_validator_indices,\n config.MAX_DEPOSIT_AMOUNT,\n )\n total_balance = get_total_balance_from_effective_balances(\n effective_balances,\n crosslink_committee,\n )\n for index in attesting_validator_indices:\n rewards_received = _update_rewards_or_penalies(\n index,\n base_rewards[index] * total_attesting_balance // total_balance,\n rewards_received,\n )\n for index in set(crosslink_committee).difference(attesting_validator_indices):\n penalties_received = _update_rewards_or_penalies(\n index,\n base_rewards[index],\n penalties_received,\n )\n return (rewards_received, penalties_received)\n\n\ndef process_rewards_and_penalties(state: BeaconState, config: BeaconConfig) -> BeaconState:\n # Compute previous epoch active validator indices and the total balance they account for\n # for later use.\n previous_epoch_active_validator_indices = set(\n get_active_validator_indices(\n state.validator_registry,\n state.previous_epoch(config.SLOTS_PER_EPOCH, config.GENESIS_EPOCH)\n )\n )\n previous_total_balance: Gwei = get_total_balance(\n state.validator_balances,\n tuple(previous_epoch_active_validator_indices),\n config.MAX_DEPOSIT_AMOUNT,\n )\n\n # Compute previous epoch attester indices and the total balance they account for\n # for later use.\n previous_epoch_attestations = state.previous_epoch_attestations\n previous_epoch_attester_indices = get_attester_indices_from_attestations(\n state=state,\n attestations=previous_epoch_attestations,\n committee_config=CommitteeConfig(config),\n )\n\n # Compute inclusion slot/distance of previous attestations for later use.\n inclusion_infos = get_inclusion_infos(\n state=state,\n attestations=previous_epoch_attestations,\n committee_config=CommitteeConfig(config),\n )\n\n # Compute effective balance of each previous epoch active validator for later use\n effective_balances = {\n ValidatorIndex(index): get_effective_balance(\n state.validator_balances,\n ValidatorIndex(index),\n config.MAX_DEPOSIT_AMOUNT,\n )\n for index in range(len(state.validator_registry))\n }\n # Compute base reward of each previous epoch active validator for later use\n base_rewards = {\n ValidatorIndex(index): get_base_reward(\n state=state,\n index=ValidatorIndex(index),\n base_reward_quotient=config.BASE_REWARD_QUOTIENT,\n previous_total_balance=previous_total_balance,\n max_deposit_amount=config.MAX_DEPOSIT_AMOUNT,\n )\n for index in range(len(state.validator_registry))\n }\n\n # 1. Process rewards and penalties for justification and finalization\n finality_rewards, finality_penalties = _process_rewards_and_penalties_for_finality(\n state,\n config,\n previous_epoch_active_validator_indices,\n previous_total_balance,\n previous_epoch_attestations,\n previous_epoch_attester_indices,\n inclusion_infos,\n effective_balances,\n base_rewards,\n )\n # 2. Process rewards and penalties for crosslinks\n crosslinks_rewards, crosslinks_penalties = _process_rewards_and_penalties_for_crosslinks(\n state,\n config,\n effective_balances,\n base_rewards,\n )\n\n # Apply the overall rewards/penalties\n for index in range(len(state.validator_registry)):\n state = state.update_validator_balance(\n ValidatorIndex(index),\n # Prevent validator balance under flow\n max(\n (\n state.validator_balances[index] +\n finality_rewards[index] +\n crosslinks_rewards[index] -\n finality_penalties[index] -\n crosslinks_penalties[index]\n ),\n 0,\n ),\n )\n\n return state\n\n\n#\n# Ejections\n#\ndef process_ejections(state: BeaconState,\n config: BeaconConfig) -> BeaconState:\n \"\"\"\n Iterate through the validator registry and eject active validators\n with balance below ``EJECTION_BALANCE``.\n \"\"\"\n active_validator_indices = get_active_validator_indices(\n state.validator_registry,\n state.current_epoch(config.SLOTS_PER_EPOCH),\n )\n for index in set(active_validator_indices):\n if state.validator_balances[index] < config.EJECTION_BALANCE:\n state = exit_validator(\n state,\n index,\n slots_per_epoch=config.SLOTS_PER_EPOCH,\n activation_exit_delay=config.ACTIVATION_EXIT_DELAY,\n )\n return state\n\n\n#\n# Validator registry and shuffling seed data\n#\ndef _update_previous_shuffling_data(state: BeaconState) -> BeaconState:\n return state.copy(\n previous_shuffling_epoch=state.current_shuffling_epoch,\n previous_shuffling_start_shard=state.current_shuffling_start_shard,\n previous_shuffling_seed=state.current_shuffling_seed,\n )\n\n\ndef _check_if_update_validator_registry(state: BeaconState,\n config: BeaconConfig) -> Tuple[bool, int]:\n if state.finalized_epoch <= state.validator_registry_update_epoch:\n return False, 0\n\n current_epoch_committee_count = get_current_epoch_committee_count(\n state,\n shard_count=config.SHARD_COUNT,\n slots_per_epoch=config.SLOTS_PER_EPOCH,\n target_committee_size=config.TARGET_COMMITTEE_SIZE,\n )\n\n # Get every shard in the current committees\n shards = set(\n (state.current_shuffling_start_shard + i) % config.SHARD_COUNT\n for i in range(current_epoch_committee_count)\n )\n for shard in shards:\n if state.latest_crosslinks[shard].epoch <= state.validator_registry_update_epoch:\n return False, 0\n\n return True, current_epoch_committee_count\n\n\ndef _update_shuffling_epoch(state: BeaconState, slots_per_epoch: int) -> BeaconState:\n \"\"\"\n Updates the ``current_shuffling_epoch`` to the ``state``'s next epoch.\n \"\"\"\n return state.copy(\n current_shuffling_epoch=state.next_epoch(slots_per_epoch),\n )\n\n\ndef _update_shuffling_start_shard(state: BeaconState,\n current_epoch_committee_count: int,\n shard_count: int) -> BeaconState:\n \"\"\"\n Updates the ``current_shuffling_start_shard`` to the current value in\n the ``state`` incremented by the number of shards we touched in the current epoch.\n \"\"\"\n return state.copy(\n current_shuffling_start_shard=(\n state.current_shuffling_start_shard + current_epoch_committee_count\n ) % shard_count,\n )\n\n\ndef _update_shuffling_seed(state: BeaconState,\n slots_per_epoch: int,\n min_seed_lookahead: int,\n activation_exit_delay: int,\n latest_active_index_roots_length: int,\n latest_randao_mixes_length: int) -> BeaconState:\n \"\"\"\n Updates the ``current_shuffling_seed`` in the ``state`` given the current state data.\n \"\"\"\n # The `helpers.generate_seed` function is only present to provide an entry point\n # for mocking this out in tests.\n current_shuffling_seed = helpers.generate_seed(\n state=state,\n epoch=state.current_shuffling_epoch,\n slots_per_epoch=slots_per_epoch,\n min_seed_lookahead=min_seed_lookahead,\n activation_exit_delay=activation_exit_delay,\n latest_active_index_roots_length=latest_active_index_roots_length,\n latest_randao_mixes_length=latest_randao_mixes_length,\n )\n return state.copy(\n current_shuffling_seed=current_shuffling_seed,\n )\n\n\ndef _is_ready_to_activate(state: BeaconState,\n index: ValidatorIndex,\n max_deposit_amount: Gwei) -> bool:\n validator = state.validator_registry[index]\n balance = state.validator_balances[index]\n return validator.activation_epoch == FAR_FUTURE_EPOCH and balance >= max_deposit_amount\n\n\ndef _is_ready_to_exit(state: BeaconState, index: ValidatorIndex) -> bool:\n validator = state.validator_registry[index]\n return validator.exit_epoch == FAR_FUTURE_EPOCH and validator.initiated_exit\n\n\ndef _churn_validators(state: BeaconState,\n config: BeaconConfig,\n check_should_churn_fn: Callable[..., Any],\n churn_fn: Callable[..., Any],\n max_balance_churn: int) -> BeaconState:\n \"\"\"\n Churn the validators. The number of the churning validators is based on\n the given ``max_balance_churn``.\n\n :param check_should_churn_fn: the funcation to determine if the validator should be churn\n :param churn_fn``: the function to churn the validators; it could be ``activate_validator`` or\n ``exit_validator``\n \"\"\"\n balance_churn = 0\n for index in range(len(state.validator_registry)):\n index = ValidatorIndex(index)\n should_churn = check_should_churn_fn(\n state,\n index,\n )\n if should_churn:\n # Check the balance churn would be within the allowance\n balance_churn += get_effective_balance(\n state.validator_balances,\n index,\n config.MAX_DEPOSIT_AMOUNT,\n )\n if balance_churn > max_balance_churn:\n break\n\n state = churn_fn(state, index)\n return state\n\n\ndef update_validator_registry(state: BeaconState, config: BeaconConfig) -> BeaconState:\n \"\"\"\n Update validator registry.\n \"\"\"\n current_epoch = state.current_epoch(config.SLOTS_PER_EPOCH)\n # The active validators\n active_validator_indices = get_active_validator_indices(state.validator_registry, current_epoch)\n # The total effective balance of active validators\n total_balance = get_total_balance(\n state.validator_balances,\n active_validator_indices,\n config.MAX_DEPOSIT_AMOUNT,\n )\n\n # The maximum balance churn in Gwei (for deposits and exits separately)\n max_balance_churn = max(\n config.MAX_DEPOSIT_AMOUNT,\n total_balance // (2 * config.MAX_BALANCE_CHURN_QUOTIENT)\n )\n\n # Activate validators within the allowable balance churn\n # linter didn't like a bare lambda\n state = _churn_validators(\n state=state,\n config=config,\n check_should_churn_fn=lambda state, index: _is_ready_to_activate(\n state,\n index,\n max_deposit_amount=config.MAX_DEPOSIT_AMOUNT,\n ),\n churn_fn=lambda state, index: activate_validator(\n state,\n index,\n is_genesis=False,\n genesis_epoch=config.GENESIS_EPOCH,\n slots_per_epoch=config.SLOTS_PER_EPOCH,\n activation_exit_delay=config.ACTIVATION_EXIT_DELAY,\n ),\n max_balance_churn=max_balance_churn,\n )\n\n # Exit validators within the allowable balance churn\n # linter didn't like a bare lambda\n state = _churn_validators(\n state=state,\n config=config,\n check_should_churn_fn=lambda state, index: _is_ready_to_exit(state, index),\n churn_fn=lambda state, index: exit_validator(\n state,\n index,\n slots_per_epoch=config.SLOTS_PER_EPOCH,\n activation_exit_delay=config.ACTIVATION_EXIT_DELAY,\n ),\n max_balance_churn=max_balance_churn,\n )\n\n state = state.copy(\n validator_registry_update_epoch=current_epoch,\n )\n\n return state\n\n\nStateUpdaterForConfig = Callable[[BeaconState, BeaconConfig], BeaconState]\n\n\n@curry\ndef _process_validator_registry_with_update(current_epoch_committee_count: int,\n state: BeaconState,\n config: BeaconConfig) -> StateUpdaterForConfig:\n state = update_validator_registry(state, config)\n\n # Update step-by-step since updated `state.current_shuffling_epoch`\n # is used to calculate other value). Follow the spec tightly now.\n state = _update_shuffling_start_shard(state, current_epoch_committee_count, config.SHARD_COUNT)\n\n state = _update_shuffling_epoch(state, config.SLOTS_PER_EPOCH)\n\n state = _update_shuffling_seed(\n state,\n config.SLOTS_PER_EPOCH,\n config.MIN_SEED_LOOKAHEAD,\n config.ACTIVATION_EXIT_DELAY,\n config.LATEST_ACTIVE_INDEX_ROOTS_LENGTH,\n config.LATEST_RANDAO_MIXES_LENGTH,\n )\n\n return state\n\n\ndef _process_validator_registry_without_update(state: BeaconState,\n config: BeaconConfig) -> BeaconState:\n epochs_since_last_registry_update = (\n state.current_epoch(config.SLOTS_PER_EPOCH) - state.validator_registry_update_epoch\n )\n\n if epochs_since_last_registry_update <= 1:\n return state\n\n if is_power_of_two(epochs_since_last_registry_update):\n # Update step-by-step since updated `state.current_shuffling_epoch`\n # is used to calculate other value). Follow the spec tightly now.\n state = _update_shuffling_epoch(state, config.SLOTS_PER_EPOCH)\n\n # NOTE: We do NOT update the \"start shard\" as we have not\n # produced a full set of new crosslinks; validators should have a chance to\n # complete this goal in future epochs.\n\n state = _update_shuffling_seed(\n state,\n config.SLOTS_PER_EPOCH,\n config.MIN_SEED_LOOKAHEAD,\n config.ACTIVATION_EXIT_DELAY,\n config.LATEST_ACTIVE_INDEX_ROOTS_LENGTH,\n config.LATEST_RANDAO_MIXES_LENGTH,\n )\n\n return state\n\n\ndef process_validator_registry(state: BeaconState,\n config: BeaconConfig) -> BeaconState:\n state = _update_previous_shuffling_data(state)\n\n need_to_update, current_epoch_committee_count = _check_if_update_validator_registry(\n state,\n config\n )\n\n if need_to_update:\n # this next function call returns a closure, linter didn't like a bare lambda\n validator_registry_transition = _process_validator_registry_with_update(\n current_epoch_committee_count,\n )\n else:\n validator_registry_transition = _process_validator_registry_without_update\n\n state = validator_registry_transition(state, config)\n\n state = process_slashings(state, config)\n\n state = process_exit_queue(state, config)\n\n return state\n\n\ndef _update_latest_active_index_roots(state: BeaconState,\n committee_config: CommitteeConfig) -> BeaconState:\n \"\"\"\n Return the BeaconState with updated `latest_active_index_roots`.\n \"\"\"\n next_epoch = state.next_epoch(committee_config.SLOTS_PER_EPOCH)\n\n # TODO: chanege to hash_tree_root\n active_validator_indices = get_active_validator_indices(\n state.validator_registry,\n Epoch(next_epoch + committee_config.ACTIVATION_EXIT_DELAY),\n )\n index_root = hash_eth2(\n b''.join(\n [\n index.to_bytes(32, 'little')\n for index in active_validator_indices\n ]\n )\n )\n\n latest_active_index_roots = update_tuple_item(\n state.latest_active_index_roots,\n (\n (next_epoch + committee_config.ACTIVATION_EXIT_DELAY) %\n committee_config.LATEST_ACTIVE_INDEX_ROOTS_LENGTH\n ),\n index_root,\n )\n\n return state.copy(\n latest_active_index_roots=latest_active_index_roots,\n )\n\n\ndef _compute_total_penalties(state: BeaconState,\n config: BeaconConfig,\n current_epoch: Epoch) -> Gwei:\n epoch_index = current_epoch % config.LATEST_SLASHED_EXIT_LENGTH\n start_index_in_latest_slashed_balances = (\n (epoch_index + 1) % config.LATEST_SLASHED_EXIT_LENGTH\n )\n total_at_start = state.latest_slashed_balances[start_index_in_latest_slashed_balances]\n total_at_end = state.latest_slashed_balances[epoch_index]\n return Gwei(total_at_end - total_at_start)\n\n\ndef _compute_individual_penalty(state: BeaconState,\n config: BeaconConfig,\n validator_index: ValidatorIndex,\n total_penalties: Gwei,\n total_balance: Gwei) -> Gwei:\n effective_balance = get_effective_balance(\n state.validator_balances,\n validator_index,\n config.MAX_DEPOSIT_AMOUNT,\n )\n return Gwei(\n max(\n effective_balance * min(total_penalties * 3, total_balance) // total_balance,\n effective_balance // config.MIN_PENALTY_QUOTIENT,\n )\n )\n\n\ndef process_slashings(state: BeaconState,\n config: BeaconConfig) -> BeaconState:\n \"\"\"\n Process the slashings.\n \"\"\"\n latest_slashed_exit_length = config.LATEST_SLASHED_EXIT_LENGTH\n max_deposit_amount = config.MAX_DEPOSIT_AMOUNT\n\n current_epoch = state.current_epoch(config.SLOTS_PER_EPOCH)\n active_validator_indices = get_active_validator_indices(state.validator_registry, current_epoch)\n total_balance = Gwei(\n sum(\n get_effective_balance(state.validator_balances, i, max_deposit_amount)\n for i in active_validator_indices\n )\n )\n total_penalties = _compute_total_penalties(\n state,\n config,\n current_epoch,\n )\n\n for validator_index, validator in enumerate(state.validator_registry):\n validator_index = ValidatorIndex(validator_index)\n is_halfway_to_withdrawable_epoch = (\n current_epoch == validator.withdrawable_epoch - latest_slashed_exit_length // 2\n )\n if validator.slashed and is_halfway_to_withdrawable_epoch:\n penalty = _compute_individual_penalty(\n state=state,\n config=config,\n validator_index=validator_index,\n total_penalties=total_penalties,\n total_balance=total_balance,\n )\n state = state.update_validator_balance(\n validator_index=validator_index,\n balance=state.validator_balances[validator_index] - penalty,\n )\n return state\n\n\ndef process_exit_queue(state: BeaconState,\n config: BeaconConfig) -> BeaconState:\n \"\"\"\n Process the exit queue.\n \"\"\"\n def eligible(index: ValidatorIndex) -> bool:\n validator = state.validator_registry[index]\n # Filter out dequeued validators\n if validator.withdrawable_epoch != FAR_FUTURE_EPOCH:\n return False\n # Dequeue if the minimum amount of time has passed\n else:\n return (\n state.current_epoch(config.SLOTS_PER_EPOCH) >=\n validator.exit_epoch + config.MIN_VALIDATOR_WITHDRAWABILITY_DELAY\n )\n\n eligible_indices = filter(\n eligible,\n tuple([ValidatorIndex(i) for i in range(len(state.validator_registry))])\n )\n # Sort in order of exit epoch, and validators that exit within the same epoch exit\n # in order of validator index\n sorted_indices = sorted(\n eligible_indices,\n key=lambda index: state.validator_registry[index].exit_epoch,\n )\n for dequeues, index in enumerate(sorted_indices):\n if dequeues >= config.MAX_EXIT_DEQUEUES_PER_EPOCH:\n break\n state = prepare_validator_for_withdrawal(\n state,\n ValidatorIndex(index),\n slots_per_epoch=config.SLOTS_PER_EPOCH,\n min_validator_withdrawability_delay=config.MIN_VALIDATOR_WITHDRAWABILITY_DELAY,\n )\n\n return state\n\n\n#\n# Final updates\n#\ndef process_final_updates(state: BeaconState,\n config: BeaconConfig) -> BeaconState:\n current_epoch = state.current_epoch(config.SLOTS_PER_EPOCH)\n next_epoch = state.next_epoch(config.SLOTS_PER_EPOCH)\n\n state = _update_latest_active_index_roots(state, CommitteeConfig(config))\n\n state = state.copy(\n latest_slashed_balances=update_tuple_item(\n state.latest_slashed_balances,\n next_epoch % config.LATEST_SLASHED_EXIT_LENGTH,\n state.latest_slashed_balances[current_epoch % config.LATEST_SLASHED_EXIT_LENGTH],\n ),\n latest_randao_mixes=update_tuple_item(\n state.latest_randao_mixes,\n next_epoch % config.LATEST_RANDAO_MIXES_LENGTH,\n get_randao_mix(\n state=state,\n epoch=current_epoch,\n slots_per_epoch=config.SLOTS_PER_EPOCH,\n latest_randao_mixes_length=config.LATEST_RANDAO_MIXES_LENGTH,\n ),\n ),\n )\n\n # Rotate current/previous epoch attestations\n state = state.copy(\n previous_epoch_attestations=state.current_epoch_attestations,\n current_epoch_attestations=(),\n )\n\n return state\n","sub_path":"eth2/beacon/state_machines/forks/serenity/epoch_processing.py","file_name":"epoch_processing.py","file_ext":"py","file_size_in_byte":43093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"88262906","text":"def egcd(a, b): \r\n x,y, u,v = 0,1, 1,0\r\n while a != 0: \r\n q, r = b//a, b%a \r\n m, n = x-u*q, y-v*q \r\n b,a, x,y, u,v = a,r, u,v, m,n \r\n gcd = b \r\n return gcd, x, y \r\n\r\ndef modinv(a, m): \r\n gcd, x, y = egcd(a, m) \r\n if gcd != 1: \r\n return None \r\n else: \r\n return x % m \r\n \r\ndef encrypt(text, key): \r\n return ''.join([ chr((( key[0]*(ord(t) - ord('A')) + key[1] ) % 26) + ord('A')) for t in text.upper().replace(' ', '') ]) \r\n\r\n\r\ndef decrypt(cipher, key): \r\n return ''.join([ chr((( modinv(key[0], 26)*(ord(c) - ord('A') - key[1])) % 26) + ord('A')) for c in cipher ]) \r\nkey = list(map(int,input(\"Enter the Key: \").split()))\r\nwhile True : \r\n \r\n t = 0\r\n opt = int(input(\"\\nEnter option \\n1. Enter text \\n2. Encrypt & Decrypt\\nEnter Option: \"))\r\n if opt == 1 : \r\n text = input(\"\\nEnter plain text: \")\r\n if opt == 2 : \r\n if text == \"\": print(\"No Plain Text\")\r\n else:\r\n enc_text = encrypt(text, key) \r\n print('Encrypted Text: {}'.format(enc_text)) \r\n print('Decrypted Text: {}'.format(decrypt(enc_text, key) )) \r\n \r\n# Enter the Key: 233 377\r\n\r\n# Enter option\r\n# 1. Enter text\r\n# 2. Encrypt & Decrypt\r\n# Enter Option: 1\r\n\r\n# Enter plain text: sabrish\r\n\r\n# Enter option\r\n# 1. Enter text\r\n# 2. Encrypt & Decrypt\r\n# Enter Option: 2\r\n# Encrypted Text: VNMWFVG\r\n# Decrypted Text: SABRISH \r\n\r\n\r\n","sub_path":"sec lab/Ciphers/affinecipher.py","file_name":"affinecipher.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"580636232","text":"#! usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function, absolute_import\nimport sys\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\nfrom PySide.QtSvg import *\n\nclass FocusManager:\n def __init__(self, gview):\n self.current = None\n self.textbox = gview.textbox\n\n def Focus(self, item, text):\n if self.current != None:\n self.current.update()\n self.current = item\n self.current.update()\n self.textbox.setText(text)\n\nclass OperationManager:\n def __init__(self, gview):\n self.move_button = gview.move_button\n self.resize_button = gview.resize_button\n self.rotate_button = gview.rotate_button\n self.move_button.toggled.connect(self.move_button_toggled)\n self.resize_button.toggled.connect(self.resize_button_toggled)\n self.rotate_button.toggled.connect(self.rotate_button_toggled)\n\n def move_button_toggled(self, checked):\n if checked:\n self.rotate_button.setChecked(False)\n self.resize_button.setChecked(False)\n\n def resize_button_toggled(self, checked):\n if checked:\n self.move_button.setChecked(False)\n self.rotate_button.setChecked(False)\n\n def rotate_button_toggled(self, checked):\n if checked:\n self.move_button.setChecked(False)\n self.resize_button.setChecked(False)\n \nclass Managers:\n def __init__(self, f, o):\n self.f = f\n self.o = o\n\nclass Object(QGraphicsItem):\n def __init__(self, m, w, h):\n QGraphicsItem.__init__(self)\n self.m = m\n self.w = w\n self.h = h\n \n def boundingRect(self):\n penWidth = 1.0\n return QRectF(-self.w / 2 - penWidth / 2, -self.h / 2 - penWidth / 2,\n self.w + penWidth, self.h + penWidth)\n\n def paint_sub(self, painter):\n pass\n \n def paint(self, painter, option, widget):\n self.paint_sub(painter)\n if self.m.f.current == self:\n pass\n #pen = QPen(Qt.red)\n #pen.setStyle(Qt.DotLine)\n #painter.setPen(pen)\n #painter.drawLine(QLineF(-self.w / 2, 0, self.w / 2, 0))\n #painter.drawLine(QLineF(0, -self.h / 2, 0, self.h / 2))\n\n def mousePressEvent( self, event ):\n self.cPos = event.scenePos()\n\n self.m.f.Focus(self, str(self.scenePos().x()) + \",\" + str(self.scenePos().y()))\n \n def mouseReleaseEvent( self, event ):\n self.cPos = None\n super(Object, self).mouseReleaseEvent( event )\n self.update()\n \n def mouseMoveEvent( self, event ):\n if self.m.o.move_button.isChecked():\n if not self.cPos:\n return\n\n # 描画位置を変更\n cur = event.scenePos()\n value = cur - self.cPos\n self.cPos = cur\n transform = self.transform()\n transform *= QTransform().translate( value.x(), value.y() )\n \n # 変更を適用\n self.setTransform(transform)\n\n self.m.f.Focus(self, str(self.scenePos().x()) + \", \" + str(self.scenePos().y()))\n \nclass Rect(Object):\n def __init__(self, m, w, h):\n Object.__init__(self, m, w, h)\n\n def paint_sub(self, painter):\n painter.drawRect(-self.w / 2, -self.h / 2, self.w, self.h)\n\nclass Triangle(Object):\n def __init__(self, m, w, h):\n Object.__init__(self, m, w, h)\n\n def paint_sub(self, painter):\n painter.setBrush(Qt.SolidPattern)\n painter.drawPolygon([QPointF(self.w / 2, self.h / 2), QPointF(0, -self.h / 2), QPointF(-self.w / 2, self.h / 2)])\n\nclass Arrow(Object):\n def __init__(self, m, l):\n Object.__init__(self, m, 4, l)\n self.l = l\n\n def paint_sub(self, painter):\n painter.setBrush(Qt.SolidPattern)\n painter.drawPolygon([QPointF(2, -self.l / 2 + 8), QPointF(0, -self.l / 2), QPointF(-2, -self.l / 2 + 8)])\n painter.drawLine(QLineF(0, -self.l / 2, 0, self.l / 2))\n\nclass Text(Object):\n def __init__(self, m, text):\n self.text = text\n fm = QFontMetrics(QPainter().font())\n w = fm.width(self.text)\n h = fm.height()\n Object.__init__(self, m, w, h)\n\n def paint_sub(self, painter):\n painter.drawText(-self.w / 2, self.h / 2, self.text)\n\nclass graphicView(QGraphicsView):\n \n def __init__(self, w, h):\n QGraphicsView.__init__(self)\n\n self.w = w\n self.h = h\n \n self.scene = QGraphicsScene()\n\n self.setScene(self.scene)\n \n rect = QRect(0, 0, self.w, self.h + 24)\n\n self.scene.setSceneRect(rect)\n\n self.textbox = QLineEdit(self)\n self.textbox.move(150, self.h)\n self.textbox.resize(self.w-150, 24)\n\n self.move_button = QPushButton('M', self)\n self.move_button.move(0, self.h)\n self.move_button.resize(50, 24)\n self.move_button.setCheckable(True)\n\n self.resize_button = QPushButton('S', self)\n self.resize_button.move(50, self.h)\n self.resize_button.resize(50, 24)\n self.resize_button.setCheckable(True)\n\n self.rotate_button = QPushButton('R', self)\n self.rotate_button.move(100, self.h)\n self.rotate_button.resize(50, 24)\n self.rotate_button.setCheckable(True)\n\n def out(self):\n svg_gen = QSvgGenerator()\n svg_gen.setFileName(\"hello.svg\")\n svg_gen.setSize(QSize(self.w, self.h))\n svg_gen.setViewBox(QRect(0, 0, self.w, self.h))\n svg_gen.setTitle(\"\")\n svg_gen.setDescription(\"\")\n \n painter = QPainter()\n painter.begin(svg_gen)\n\n self.scene.render(painter)\n\n painter.end()\n\napp = QApplication(sys.argv)\n\nwidget = graphicView(800, 200)\n\nfm = FocusManager(widget)\n\nom = OperationManager(widget)\n\nm = Managers(fm, om)\n\nnode = Rect(m, 200, 20)\nnode.setPos(50, 50)\nwidget.scene.addItem(node)\n\nnode = Rect(m, 100, 60)\nnode.setPos(700, 140)\nwidget.scene.addItem(node)\n\nnode = Triangle(m, 4, 8)\nnode.setPos(500, 140)\nwidget.scene.addItem(node)\n\nnode = Arrow(m, 100)\nnode.setPos(300, 100)\nwidget.scene.addItem(node)\n\nnode = Text(m, \"Fuga\")\nnode.setPos(200, 140)\nwidget.scene.addItem(node)\n\nnode = Text(m, \"hoge\")\nnode.setPos(700, 140)\nwidget.scene.addItem(node)\n\nwidget.out()\nwidget.show()\n\n\n\nsys.exit(app.exec_())\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"484911701","text":"# Hanya untuk m = 3\nclass Hill:\n def __init__(self, data, key, m):\n self.data = data\n self.length_data = len(data)\n self.key = key\n self.m = m\n self.inverse_key = [[0 for i in range(self.m)] for j in range(self.m)]\n\n self.set_inverse_key()\n \n def get_inverse_mod(self, val):\n for x in range(1, 26):\n if (((val % 26) * (x % 26)) % 26 == 1):\n return x\n \n return -1\n\n def transpose(self, matrix):\n return [[row[i] for row in matrix] for i in range(len(matrix[0]))]\n\n def get_matrix_minor(self, matrix, i, j):\n return [row[: j] + row[j + 1 :] for row in (matrix[: i] + matrix[i + 1 :])]\n\n def determinant(self, matrix):\n if len(matrix) == 2:\n return (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0])\n\n determinant = 0\n for c in range(len(matrix)):\n determinant += ((-1.0) ** c) * matrix[0][c] * self.determinant(self.get_matrix_minor(matrix, 0, c))\n\n return determinant\n\n\n def get_matrix_inverse(self, matrix):\n determinant = 1 / self.get_inverse_mod(self.determinant(matrix))\n # For 2x2 Matrix\n if len(matrix) == 2:\n return [[matrix[1][1] / determinant % 26, -1 * matrix[0][1] / determinant % 26] , \n [-1 * matrix[1][0] / determinant % 26, matrix[0][0] / determinant % 26]]\n\n cofactors = []\n for r in range(len(matrix)):\n cofactorRow = []\n\n for c in range(len(matrix)):\n minor = self.get_matrix_minor(matrix,r,c)\n cofactorRow.append(((-1) ** (r + c)) * self.determinant(minor))\n\n cofactors.append(cofactorRow)\n\n cofactors = self.transpose(cofactors)\n for r in range(len(cofactors)):\n for c in range(len(cofactors)):\n cofactors[r][c] = cofactors[r][c] / determinant % 26\n\n return cofactors\n\n def set_inverse_key(self):\n self.inverse_key = self.get_matrix_inverse(self.key)\n\n def format_data(self):\n remain = self.m - len(self.data) % self.m\n added_data = self.data\n if (remain != 0):\n for i in range(remain):\n added_data += 'x'\n \n formatted = ''\n for i in range(len(added_data)):\n formatted += added_data[i]\n\n if (i % self.m == self.m - 1 and i != len(added_data) - 1):\n formatted += ' '\n\n return formatted\n\n def crypt_mgram(self, mgram, key):\n encrypted_mgram = [0 for i in range(self.m)]\n i = 0\n j = 0\n while(j < self.m ** 2 and i < self.m):\n encrypted_mgram[i] += int(key[i][j]) * (ord(mgram[j]) - 97)\n j += 1\n\n if (j % self.m == 0):\n encrypted_mgram[i] = chr(encrypted_mgram[i] % 26 + 97)\n i += 1\n j = 0\n \n return ''.join(encrypted_mgram)\n\n def encrypt(self):\n formatted_data = self.format_data().split(' ')\n \n encrypted = ''\n for i in range(len(formatted_data)):\n encrypted += self.crypt_mgram(formatted_data[i], self.key)\n\n self.data = encrypted[0 : self.length_data - 1]\n return self.data\n\n def decrypt(self):\n formatted_data = self.format_data().split(' ')\n \n decrypted = ''\n for i in range(len(formatted_data)):\n decrypted += self.crypt_mgram(formatted_data[i], self.inverse_key)\n\n self.data = decrypted[0 : self.length_data - 1]\n return self.data\n\n\n\n\n\n \n\ndata = 'paymoremoneyy'\nkey = [\n [17, 17, 5],\n [21, 18, 21],\n [2, 2, 19]\n]\na = Hill(data, key, 3)\nprint(a.encrypt())\nprint(a.decrypt())\n\n\n ","sub_path":"src/cipher/hill.py","file_name":"hill.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"422335052","text":"import torch\nimport torchvision.transforms as T\n\nimport numpy as np\nimport math\n\nfrom models.with_mobilenet import PoseEstimationWithMobileNetMultiple\n# from modules.keypoints import extract_keypoints, group_keypoints\n# from modules.pose import Pose, track_poses\nfrom mob_mf_eval import Pose, extract_keypoints, group_keypoints\n\n\nimport collections\n\ndef load_state(net, checkpoint):\n source_state = checkpoint['state_dict']\n target_state = net.state_dict()\n new_target_state = collections.OrderedDict()\n for target_key, target_value in target_state.items():\n if target_key in source_state and source_state[target_key].size() == target_state[target_key].size():\n new_target_state[target_key] = source_state[target_key]\n else:\n new_target_state[target_key] = target_state[target_key]\n print('[WARNING] Not found pre-trained parameters for {}'.format(target_key))\n\n net.load_state_dict(new_target_state)\n\ndef normalize(img, img_mean, img_scale):\n img = np.array(img, dtype=np.float32)\n img = (img - img_mean) * img_scale\n return img\n\n\ndef pad_width(img, stride, min_dims):\n _, _, h, w = img.shape\n h = min(min_dims[0], h)\n min_dims[0] = math.ceil(min_dims[0] / float(stride)) * stride\n min_dims[1] = max(min_dims[1], w)\n min_dims[1] = math.ceil(min_dims[1] / float(stride)) * stride\n pad = []\n pad.append(int(math.floor((min_dims[1] - w) / 2.0)))\n pad.append(int(min_dims[1] - w - pad[0]))\n pad.append(int(math.floor((min_dims[0] - h) / 2.0)))\n pad.append(int(min_dims[0] - h - pad[2]))\n # padded_img = cv2.copyMakeBorder(img, pad[0], pad[2], pad[1], pad[3],\n # cv2.BORDER_CONSTANT, value=pad_value)\n\n padded_img = torch.nn.functional.pad(img, pad)\n return padded_img, pad\n\n\ndef init_pose(checkpoint_path):\n net = PoseEstimationWithMobileNetMultiple(3, 128, 18, 32)\n checkpoint = torch.load(checkpoint_path, map_location='cpu')\n load_state(net, checkpoint)\n\n net.eval()\n net = net.cuda()\n\n env = [net]\n\n return None, env\n\ndef infer_fast(net, img, net_input_height_size, stride, upsample_ratio):\n _, _, height, width = img.shape\n scale = net_input_height_size / height\n\n\n # scaled_img = cv2.resize(img, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)\n # scaled_img = normalize(scaled_img, img_mean, img_scale)\n scaled_img = torch.nn.functional.interpolate(img, scale_factor=scale, mode='bilinear', align_corners=False)\n # scaled_img -= 0.5\n # print(\"SCALED\", scaled_img.shape, scaled_img.min(), scaled_img.max())\n\n min_dims = [net_input_height_size, max(scaled_img.shape[3], net_input_height_size)]\n tensor_img, pad = pad_width(scaled_img, stride, min_dims)\n\n\n stages_output = net(tensor_img[:1, ...], tensor_img[1:2, ...], tensor_img[2:3, ...])\n\n stage2_heatmaps = stages_output[-2]\n heatmaps = np.transpose(stage2_heatmaps.squeeze().cpu().data.numpy(), (1, 2, 0))\n heatmaps = cv2.resize(heatmaps, (0, 0), fx=upsample_ratio, fy=upsample_ratio, interpolation=cv2.INTER_CUBIC)\n # heatmaps = torch.nn.functional.interpolate(stage2_heatmaps, scale_factor=upsample_ratio, mode='bicubic', align_corners=False)\n # heatmaps = np.transpose(heatmaps.squeeze().cpu().data.numpy(), (1, 2, 0))\n heatmaps_tensor = torch.nn.functional.interpolate(stage2_heatmaps, scale_factor=upsample_ratio, mode='bilinear', align_corners=False)\n\n stage2_pafs = stages_output[-1]\n pafs = np.transpose(stage2_pafs.squeeze().cpu().data.numpy(), (1, 2, 0))\n pafs = cv2.resize(pafs, (0, 0), fx=upsample_ratio, fy=upsample_ratio, interpolation=cv2.INTER_CUBIC)\n # pafs = torch.nn.functional.interpolate(stage2_pafs, scale_factor=upsample_ratio, mode='bicubic', align_corners=False)\n # pafs = np.transpose(pafs.squeeze().cpu().data.numpy(), (1, 2, 0))\n\n return heatmaps, pafs, scale, pad, heatmaps_tensor.squeeze(0)\n\n\ndef anime_frame(rgb, env, size=None, useSigmod=False, useTwice=False):\n if env is None:\n return init_pose(\"./multiframe_checkpoints/MOBv2.pth\")\n\n net, = env\n\n stride = 8\n upsample_ratio = 4\n\n heatmaps, pafs, scale, pad, heatmaps_tensor = infer_fast(net, rgb, 368, stride, upsample_ratio)\n\n num_keypoints = Pose.num_kpts\n total_keypoints_num = 0\n all_keypoints_by_type = []\n\n for kpt_idx in range(num_keypoints): # 19th for bg\n total_keypoints_num += extract_keypoints(heatmaps_tensor[kpt_idx, :, :], all_keypoints_by_type,\n total_keypoints_num)\n\n pose_entries, all_keypoints = group_keypoints(all_keypoints_by_type, pafs, pose_entry_size=19, demo=True)\n for kpt_id in range(all_keypoints.shape[0]):\n all_keypoints[kpt_id, 0] = (all_keypoints[kpt_id, 0] * stride / upsample_ratio - pad[\n 1]) / scale\n all_keypoints[kpt_id, 1] = (all_keypoints[kpt_id, 1] * stride / upsample_ratio - pad[\n 0]) / scale\n current_poses = []\n for n in range(len(pose_entries)):\n if len(pose_entries[n]) == 0:\n continue\n pose_keypoints = np.ones((num_keypoints, 2), dtype=np.int32) * -1\n for kpt_id in range(num_keypoints):\n if pose_entries[n][kpt_id] != -1.0: # keypoint was found\n pose_keypoints[kpt_id, 0] = int(all_keypoints[int(pose_entries[n][kpt_id]), 0])\n pose_keypoints[kpt_id, 1] = int(all_keypoints[int(pose_entries[n][kpt_id]), 1])\n pose = Pose(pose_keypoints, pose_entries[n][-2])\n current_poses.append(pose)\n\n # if track:\n # track_poses(previous_poses, current_poses, smooth=smooth)\n # previous_poses = current_poses\n # return rgb, env\n\n # print(rgb.min(), rgb.max())\n # img = rgb.squeeze(0).permute(1, 2, 0).cpu().numpy()[:, :, ::-1]# * 255\n # img = img.squeeze(0).permute(1, 2, 0).cpu().numpy()[:, :, ::-1]# * 255\n # img += 0.5\n # img *= 255\n # img = img.astype(np.uint8)\n\n img = np.zeros((rgb.shape[2], rgb.shape[3], rgb.shape[1]), dtype=np.uint8)\n\n show_info = True\n for pose in current_poses:\n pose.draw(img, show_info)\n show_info = False\n\n # for pose in current_poses:\n # cv2.rectangle(img, (pose.bbox[0], pose.bbox[1]),\n # (pose.bbox[0] + pose.bbox[2], pose.bbox[1] + pose.bbox[3]), (0, 255, 0))\n # if track:\n # cv2.putText(img, 'id: {}'.format(pose.id), (pose.bbox[0], pose.bbox[1] - 16),\n # cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255))\n\n\n img = img[:, :, ::-1] #/ 255\n # print(img.shape, img.dtype, img.min(), img.max())\n img = torch.FloatTensor(img.astype(np.float32))\n img /= 255\n\n img = img.permute(2, 0, 1).unsqueeze(0).cuda()\n output = rgb[:1, ...] * 0.3 + img * 0.7\n # output = img\n\n return output, env\n\n\nclass VideoReader(object):\n def __init__(self, file_name):\n self.file_name = file_name\n try: # OpenCV needs int to read from webcam\n self.file_name = int(file_name)\n except ValueError:\n pass\n\n def __iter__(self):\n self.cap = cv2.VideoCapture(self.file_name)\n if not self.cap.isOpened():\n raise IOError('Video {} cannot be opened'.format(self.file_name))\n return self\n\n def __next__(self):\n was_read, img = self.cap.read()\n if not was_read:\n raise StopIteration\n return img\n\nif __name__ == '__main__':\n print(\"test pose\")\n\n import cv2\n\n # frame_provider = VideoReader(\"../AlphaPose/dance3.mp4\")\n frame_provider = VideoReader(\"../AlphaPose/dance2.mp4\")\n\n env = None\n _, env = anime_frame(None, env)\n print('init done')\n\n frames = []\n\n for img in frame_provider:\n\n arr = img[:, :, ::-1].astype(np.float32) / 255\n tensor = torch.FloatTensor(arr).permute(2, 0, 1) #.unsqueeze(0)\n tensor = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])(tensor).unsqueeze(0)\n\n print(tensor.min(), tensor.max())\n\n # print(tensor.dtype, tensor.shape, tensor.min(), tensor.max())\n if len(frames) == 0:\n for i in range(3):\n t = tensor.clone()\n frames.append(t.cuda())\n else:\n frames.append(tensor.cuda())\n\n if len(frames) > 3:\n frames.pop(0)\n\n tensors = torch.cat(frames, 0)\n\n output, env = anime_frame(tensors, env)\n\n # print(output.shape)\n img = output.cpu().squeeze(0).permute(1, 2, 0).numpy()[:, :, ::-1]# * 255\n # print(img.shape, img.dtype)\n cv2.imshow('Demo', img)\n\n key = cv2.waitKey(16)\n if key == 27: # esc\n break\n","sub_path":"PoseMultiFrame.py","file_name":"PoseMultiFrame.py","file_ext":"py","file_size_in_byte":8662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"54757563","text":"#!/usr/bin/python3\n\nfrom multiprocessing import Process, Queue\nimport os\nimport time\n\n\nclass MotorController:\n \"\"\"R-Pi stepper controller.\"\"\"\n def __init__(self, name, msgque):\n self.name = name\n self.que = msgque\n self.proc = Process(target=self.run, args=())\n self.proc.start()\n\n\n def run(self):\n msg = self.que.get()\n print('msg:', msg)\n msg = self.que.get()\n print('msg:', msg)\n \n \n def step(self, steps):\n \"\"\"cycle motor steps number of steps\"\"\"\n print(\"step %d\\n\")\n pass\n \n def read(self):\n x = self.que.get()\n print(x)\n \n\ndef info(title):\n print(title)\n #print('module name:', __name__)\n #print('parent process:', os.getppid())\n print('process id:', os.getpid())\n print\n \n\n\n \ndef f(name):\n #info('function f')\n print('hello', name)\n \n \n\nif __name__ == '__main__':\n print('\\t= my pid:%d '% os.getpid())\n print('\\t======')\n names = ['stepX', 'stepY', 'stepZ']\n controls = []\n for nam in names:\n que = Queue()\n mc = MotorController( nam, que)\n controls.append(mc)\n\n\n # run\n for con in controls:\n con.que.put( con.name)\n time.sleep(2)\n for con in controls:\n con.que.put( con.name + '2')\n\n \n # time to quit\n for c in controls:\n c.proc.join()\n\n\n\n\n\n\n\n","sub_path":"multi/multi.py","file_name":"multi.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"452125856","text":"import vertica_python\r\nimport string\r\nimport sys\r\nimport math\r\nimport time\r\n \r\n \r\n######connection string to vertica #####\r\n\r\ntry:\r\n conn_info = {'host':'hostname/ip',\r\n 'port': 5433,\r\n 'user': 'username',\r\n 'password': 'passowrd',\r\n 'database':'dbname',\r\n 'read_timeout': 60000000,\r\n 'unicode_error': 'strict',\r\n 'ssl': False,\r\n 'connection_timeout': 50000\r\n }\r\n \r\n # simple connection, with manual close\r\n connection = vertica_python.connect(**conn_info)\r\n cur = connection.cursor()\r\n \r\nexcept:\r\n print(\"Database connection error\")\r\n sys.exit()\r\n \r\nsys.argv = [\"connected_component.py\", \"dataset=tree10m.csv\",\"source=6\"]\r\n \r\n \r\n####check the command line arguments ####\r\nif len(sys.argv) != 3:\r\n print(\"Not correct arguments. \");\r\n sys.exit()\r\n \r\narg2=sys.argv[1]\r\narg2=arg2.split('=')\r\ninput_dataset=arg2[1]\r\n\r\nfile = open(\"connected_component.sql\",\"w\")\r\n \r\n#####drop table######\r\ndef drop_table(table_name):\r\n sql_string=\"DROP TABLE IF EXISTS \"+table_name+\" ;\"\r\n cur.execute(sql_string)\r\n file.write(sql_string+'\\n')\r\n\r\nfor i in range(1,path_length+1):\r\n drop_table_name=\"S\"+str(i)\r\n drop_table(drop_table_name)\r\n \r\n####Create E####\r\ndrop_table('E')\r\nsql_string=\"CREATE TABLE E (i int ENCODING RLE, j int ENCODING RLE, v int ENCODING RLE, PRIMARY KEY(i,j)) ;\"\r\ncur.execute(sql_string)\r\nfile.write(sql_string+'\\n')\r\n \r\n####Load Dataset#####\r\nprint(\"Loading the CSV file..\")\r\nsql_string=\"COPY E FROM '/home/vertica/tahsin/TC_programs/\"+input_dataset+\"' parser fcsvparser();\"\r\ncur.execute(sql_string)\r\nfile.write(sql_string+'\\n')\r\n\r\n#initialization\r\ndrop_table('S0')\r\nprint(\"Creaintg table S0..\")\r\nstart_time=time.time() ##time starts\r\nsql_string=\"CREATE TABLE S0 AS SELECT DISTINCT i AS i FROM E;\"\r\ncur.execute(sql_string)\r\nfile.write(sql_string+'\\n')\r\nsql_string=\"SELECT COUNT(*) FROM S0;\"\r\ncur.execute(sql_string)\r\nSi_prev=cur.fetchone()\r\n\r\nprint(\"E[i,i]=1\")\r\nsql_string=\"INSERT INTO E SELECT S0.i AS i, S0.i as j, 1 as v FROM S0;\"\r\ncur.execute(sql_string)\r\nfile.write(sql_string+'\\n')\r\n\r\n#iteration\r\nprint(\"computing cc...\")\r\ni=1\r\nwhile 1:\r\n #sql_string=\"CREATE TABLE P\"+str(i)+\" AS SELECT P\"+str(i-1)+\".i AS i,E.j as j FROM P\"+str(i-1)+\" JOIN E ON P\"+str(i-1)+\".j=E.i GROUP BY P\"+str(i-1)+\".i, E.j;\"\r\n sql_string=\"CREATE TABLE S\"+str(i)+\" AS SELECT E.i AS i FROM S\"+str(i-1)+\" JOIN E ON S\"+str(i-1)+\".i=E.j GROUP BY E.i; \"\r\n cur.execute(sql_string)\r\n file.write(sql_string+'\\n')\r\n drop_table('S_temp')\r\n sql_string=\"CREATE TABLE S_temp AS SELECT * FROM S\"+str(i-1)+\" UNION SELECT * FROM S\"+str(i)+\";\"\r\n cur.execute(sql_string)\r\n file.write(sql_string+'\\n')\r\n sql_string=\"SELECT COUNT(*) FROM S_temp\"+\";\"\r\n file.write(sql_string+'\\n')\r\n cur.execute(sql_string)\r\n Si_next=cur.fetchone()\r\n sql_string=\"SELECT COUNT(*) FROM S\"+str(i)+\";\"\r\n cur.execute(sql_string)\r\n file.write(sql_string+'\\n')\r\n Si_prev=cur.fetchone()\r\n print(Si_prev[0],Si_next[0])\r\n if Si_prev[0]==Si_next[0] and i!=1:\r\n break\r\n i=i+1\r\n file.write('\\n\\n\\n')\r\n\r\nprint('Total time=',time.time()-start_time)\r\n\r\n##drop the tables\r\nfile.write('\\n')\r\nfor i in range(0,i+1):\r\n drop_table(\"S\"+str(i))\r\n \r\nfile.close()\r\nconnection.close()\r\n","sub_path":"connected_component.py","file_name":"connected_component.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618463975","text":"import sys\nimport numpy as np\nimport cv2\nimport os\n\n# MIN_CONTOUR_AREA = 100\n\nRESIZED_IMAGE_WIDTH = 500\nRESIZED_IMAGE_HEIGHT = 500\n\ndef main():\n for x in range(1, 2):\n for y in range(1, 2):\n if (x < 10):\n if(y < 10):\n filename = 'Img/Sample00' + str(x) + '/img00' + str(x) + '-00' + str(y) + \".png\"\n else:\n filename = 'Img/Sample00' + str(x) + '/img00' + str(x) + '-0' + str(y) + \".png\"\n else:\n if(y < 10):\n filename = 'Img/Sample0' + str(x) + '/img0' + str(x) + '-00' + str(y) + \".png\"\n else:\n filename = 'Img/Sample0' + str(x) + '/img0' + str(x) + '-0' + str(y) + \".png\"\n # print(filename)\n\n imgTrainingNumbers = cv2.imread('img045-010.png')\n\n if imgTrainingNumbers is None:\n print (\"error: image not read from file \\n\\n\")\n os.system(\"pause\")\n return\n\n imgGray = cv2.cvtColor(imgTrainingNumbers, cv2.COLOR_BGR2GRAY)\n # imgBlurred = cv2.GaussianBlur(imgGray, (5,5), 0)\n imgThresh = cv2.adaptiveThreshold(imgGray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)\n imgThreshCopy = imgThresh.copy()\n\n imgContours, npaContours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n # print(len(npaContours[0][:]))\n\n maximum = 0\n index = 0\n for npaContour in npaContours:\n if(maximum= 20:\n angle = 0\n\n # Center of rectangle in source image\n center = ((x1 + x2) / 2, (y1 + y2) / 2)\n # Size of the upright rectangle bounding the rotated rectangle\n size = (x2 - x1, y2 - y1)\n M = cv2.getRotationMatrix2D((size[0] / 2, size[1] / 2), angle, 1)\n # Cropped upright rectangle\n cropped = cv2.getRectSubPix(imgGray, size, center)\n cropped = cv2.warpAffine(cropped, M, size,\n flags=cv2.INTER_LINEAR,\n borderMode=cv2.BORDER_REPLICATE)\n croppedW = H if H > W else W\n croppedH = H if H < W else W\n # Final cropped & rotated rectangle\n # croppedRotated = cv2.getRectSubPix(cropped, (int(croppedW), int(croppedH)),\n # (size[0] / 2, size[1] / 2))\n\n imgROIResized = cv2.resize(cropped, (RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT))\n resized_bw = cv2.threshold(imgROIResized, 128, 255, cv2.THRESH_BINARY)[1]\n cv2.imwrite('img045-010-output.png', resized_bw)\n cv2.imshow(\"imgROIResized\", resized_bw)\n\n cv2.destroyAllWindows()\n return\nif __name__ == \"__main__\":\n main()\n","sub_path":"GenData.py","file_name":"GenData.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"172072774","text":"import numpy as np\nimport librosa\n\ndef wav2mfcc(file_path, max_pad_len=11):\n wave, sr = librosa.load(file_path, mono=True, sr=None)\n wave = wave[::3]\n mfcc = librosa.feature.mfcc(wave, sr=16000)\n #print(\"****\", mfcc)\n\n pad_width = max_pad_len - mfcc.shape[1]\n #print(\"****\" , mfcc.shape[1])\n #print(\"****\", pad_width)\n mfcc = np.pad(mfcc, pad_width=((0, 0), (0, pad_width)), mode='constant')\n return mfcc\n","sub_path":"mfcc.py","file_name":"mfcc.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"107016350","text":"#! creates a server\n# server methods:\n# bind() -- binds to a specific ip and port so that it can listen to \n\t# incoming requests on that ip and port.\n# listen() -- puts the server into listen mode to listen to incoming connections.\n# accept() -- initiates a connection with the client \n# close() -- closes the conneciton with the client.\n\n\nimport socket\n\n# create a socket object from the socket function\n\ns = socket.socket()\n\nprint(\"socket successfully created\")\n\n# next bind to the port\n# we have not typed any ip in the ip field\n# instead we have inputted an empty string\n# this makes the server listen to requests\n# coming from other computers on the network\n\n# notice the double brackets?! cause the function takes one arg\n\nport = 12345\ns.bind(('', port))\n\nprint('socket binded to %s' %(port))\n\n# put the socket into listening mode\n# 5 means that 5 connections are kept waiting if the server\n# is busy and if a 6th socket trys to connect then the \n# connection is refused\n\ns.listen(5)\nprint('socket is listening')\n\n# a forever loop until we interrupt it or an error occurs\n\nwhile True:\n\t# Establish connection with client\n\n\tc, addr = s.accept()\n\n\tprint('got connection from ', addr)\n\n\t# send a thank you message to the client.\n\n\tc.send('Thank you for connecting \\n')\n\n\t# close the connection with the client\n\n\tc.close()\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"368458555","text":"# Copyright (c) 2021 PaddlePaddle 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\nfrom __future__ import print_function\n\nimport numpy as np\nimport os\n\nfrom .common_dataset import CommonDataset\n\n\nclass ImageNetDataset(CommonDataset):\n def __init__(self,\n image_root,\n cls_label_path,\n transform_ops=None,\n delimiter=\" \",\n multi_label=False,\n class_num=None):\n super(ImageNetDataset, self).__init__(image_root, cls_label_path,\n transform_ops, delimiter,\n multi_label, class_num)\n\n def _load_anno(self, seed=None):\n assert os.path.exists(\n self._cls_path), f\"{self._cls_path} does not exists\"\n assert os.path.exists(\n self._img_root), f\"{self._img_root} does not exists\"\n self.images = []\n self.labels = []\n\n with open(self._cls_path) as fd:\n lines = fd.readlines()\n if seed is not None:\n np.random.RandomState(seed).shuffle(lines)\n for l in lines:\n l = l.strip().split(self.delimiter)\n self.images.append(os.path.join(self._img_root, l[0]))\n if self.multi_label:\n self.labels.append(l[1])\n else:\n self.labels.append(np.int32(l[1]))\n assert os.path.exists(self.images[\n -1]), f\"{self.images[-1]} is not exists.\"\n","sub_path":"plsc/data/dataset/imagenet_dataset.py","file_name":"imagenet_dataset.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"514962868","text":"# -*- encoding: utf-8 -*-\n'''\n@File : sina_tcptest.py\n@Time : 2020/05/03 20:52:58\n@Author : xdbcb8 \n@Version : 1.0\n@Contact : xdbcb8@qq.com\n@WebSite : www.xdbcb8.com\n'''\n\n# here put the import lib\n\nimport socket\nimport os\n\ntry:\n os.chdir(r'pythonhomework\\homework9\\01_class_prog')\nexcept FileNotFoundError as identifier:\n print(identifier)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect(('www.sina.com.cn', 80))\ns.send(b'GET / HTTP/1.1\\r\\nHost: www.sina.com.cn\\r\\nConnection: close\\r\\n\\r\\n')\nbuffer = []\nwhile True:\n d = s.recv(1024)\n if d:\n buffer.append(d)\n else:\n break\ndata = b''.join(buffer)\n\ns.close()\nheader, html = data.split(b'\\r\\n\\r\\n', 1)\nprint(header.decode('utf-8'))\nwith open('sina.html', 'wb') as f:\n f.write(html)","sub_path":"homework9/01_class_prog/sina_tcptest.py","file_name":"sina_tcptest.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"231445928","text":"import string\nimport random\nimport hashlib\nimport zmq\nimport time\nimport sys\nfrom random import sample\nfrom operator import itemgetter\n\n\n## FUNCTIONS\n## Alain T's function https://stackoverflow.com/questions/45471152/how-to-create-a-sudoku-puzzle-in-python\ndef genBoard():\n base = 4 # Will generate any size of random sudoku board in O(n^2) time\n side = base*base\n nums = sample(range(1,side+1),side) # random numbers\n board = [[nums[(base*(r%base)+r//base+c)%side] for c in range(side) ] for r in range(side)]\n rows = [ r for g in sample(range(base),base) for r in sample(range(g*base,(g+1)*base),base) ] \n cols = [ c for g in sample(range(base),base) for c in sample(range(g*base,(g+1)*base),base) ] \n board = [[board[r][c] for c in cols] for r in rows]\n return board # List of nine lists\n\ndef genSudoku(board):\n side = 16\n squares = side*side\n empties = squares * 3//4\n for p in sample(range(squares),empties):\n board[p//side][p%side] = 0\n print(\"Solving sudoku:\")\n numSize = len(str(side))\n for line in board: print(\"[\"+\" \".join(f\"{n or '.':{numSize}}\" for n in line)+\"]\")\n return board\n\ndef printSolution(sudoku):\n print('Solution Found')\n for line in sudoku:\n print(line)\n\nboard = genBoard()\n# sudoku = genSudoku(board)\n\nprintSolution(board)\n\ndef check_sudoku(sudoku):\n ## checks rows\n n = len(sudoku)\n for row in sudoku:\n i = 1\n while i <= n:\n if i not in row:\n return False\n i += 1\n ## transposes matrix (don't forget to define n=len())\n j = 0 \n transpose = []\n temp_row = []\n while j < n:\n for row in sudoku:\n temp_row.append(row[j])\n transpose.append(temp_row)\n temp_row = []\n j += 1\n ## checks columns\n for row in transpose:\n i = 1\n while i <= n:\n if i not in row:\n return False\n i += 1\n return True, sudoku\n\nprint(board)\nboard = [[8, 1, 2, 7, 5, 3, 6, 4, 9],\n[9, 4, 3, 6, 8, 2, 1, 7, 5],\n[6, 7, 5, 4, 9, 1, 2, 8, 3],\n[1, 5, 4, 2, 3, 7, 8, 9, 6],\n[3, 6, 9, 8, 4, 5, 7, 2, 1],\n[2, 8, 7, 1, 6, 9, 5, 3, 4],\n[5, 2, 1, 9, 7, 4, 3, 6, 8],\n[4, 3, 8, 5, 2, 6, 9, 1, 7],\n[7, 9, 6, 3, 1, 8, 4, 5, 2]]\n\n\nprint(check_sudoku(board))\n","sub_path":"practicas/sudoku/genetic_approach/gensudo.py","file_name":"gensudo.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"55614574","text":"import librosa\nfrom scipy.signal import find_peaks_cwt\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nnotes = [\n \"music_box1.wav\",\n \"music_box2.wav\",\n \"music_box3.wav\",\n \"music_box4.wav\",\n \"music_box5.wav\",\n \"music_box6.wav\",\n]\n\nfor note in notes:\n samples, sample_rate = librosa.load(note, sr=None)\n\n spectrogram = np.abs(librosa.stft(samples, n_fft=16 * 1024))\n\n frequencies = librosa.fft_frequencies(sr=sample_rate, n_fft=16*1024)\n spectrogram = np.mean(spectrogram, axis=1)\n\n dominant_harmonic_index = np.where(spectrogram == np.max(spectrogram))\n print(frequencies[dominant_harmonic_index])\n\n # peaks = find_peaks_cwt(fourier_output_stuff, widths=np.ones(1000)) Tried finding more peaks with this, but little luck\n\n plt.plot(frequencies, spectrogram)\n plt.xscale(\"log\")\n plt.yscale(\"log\")\n # plt.plot(peaks, fourier_output_stuff[peaks], \"x\")\n plt.title(note)\n plt.xlabel(\"Frequency (Hz)\")\n plt.ylabel(\"Amplitude\")\n plt.show()","sub_path":"music_box_analysis.py","file_name":"music_box_analysis.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605969703","text":"import sys\nfrom textwrap import wrap\n\none_to_nineteen = {'0':'nula', '1':'jeden', '2':'dva', '3':'tri', '4':'štyri',\n '5':'päť', '6':'šesť', '7':'sedem', '8':'osem', '9':'deväť',\n '10':'desat', '11':'jedenásť', '12':'dvanásť',\n '13':'trinásť', '14':'štrnásť', '15':'pätnásť',\n '16': 'šestnásť', '17':'sedmenásť', '18':'osemnásť',\n '19':'devätnásť'}\n\ntens = {'0':'', '00':'', '2':'dvadsať', '3':'tridsať', '4':'štyridsať',\n '5':'päťdesiat', '6':'šesťdesiat', '7':'sedemdesiat',\n '8':'osemdesiat', '9':'deväťdesiat'}\n\nhundreds = {'0':'', '1':'sto', '2':'dvesto', '3':'tristo',\n '4':'štyristo', '5':'pätsto', '6':'šesťsto',\n '7':'sedemsto', '8':'osemsto','9':'deväťsto'}\n\norders = {1:'', 2:'tisíc', 3:' miliónov'}\n\n\n# Function for splitting numbers in string format by triplets\ndef split_number(string_number):\n\n # Reverse the argument, split by three characters.\n _split = wrap(string_number[::-1], 3)\n\n # Iterate over above list, add each char to an empty string.\n _reversed = ''\n\n for _list in _split:\n for number in _list:\n _reversed += (number)\n _reversed += ','\n\n # List of split strings\n result = _reversed[::-1].split(',')[1:]\n\n # Return a list of integers\n return [_str for _str in result]\n\n\n# Function for transcribing triplets of numbers\ndef transcribe_number(numeric_string):\n\n result = ''\n\n '''If we are dealing with a triplet, we first transcribe the first\n digit using the 'hunreds' dictionary. Then, if the remaining two\n digits are smaller than 20, we transribe them using the one_to_nineteen\n dictionary. If they are larger, we transcribe each one separately,\n using tens and ones dictionary respectively.'''\n if len(numeric_string) == 3:\n\n result += hundreds[numeric_string[0]]\n\n _tens = numeric_string[1:]\n \n # TODO TU JE BUG\n if int(_tens) < 20 and _tens[0] != '0':\n result += tens[_tens]\n\n else:\n result += tens[numeric_string[1]]\n result += one_to_nineteen[numeric_string[2]]\n\n #To numbers smaller than 3 digits, we apply the same process\n #as described above for numbers of 2 digits and less.\n\n else:\n\n if int(numeric_string) < 20:\n result += one_to_nineteen[numeric_string]\n\n else:\n result += tens[numeric_string[0]]\n result += one_to_nineteen[numeric_string[1]]\n\n return result\n\n\n# Function for concatenating transcribed numbers with orders\ndef add_orders(list_of_transcribed_numbers):\n\n result = ''\n\n # This variable is used as a key to accessing 'orders' dictionary.\n # It gets smaller by one each iteration. \n number_of_triplets = len(list_of_transcribed_numbers)\n\n for number in list_of_transcribed_numbers:\n \n # TODO toto ma prepisovat miliony, ale nefunguje to\n if number_of_triplets == 3:\n if number == 'jeden':\n result += number + ' milión' + ' '\n elif number== 'dva':\n result += number + ' milióny' + ' '\n\n else:\n if number_of_triplets == 2 and number == '':\n break\n else:\n result += number + orders[number_of_triplets] + ' '\n \n number_of_triplets -= 1\n\n return result\n\n\ndef wrapper(number):\n\n str_cislo = str(number)\n numbers = split_number(str_cislo)\n print(numbers)\n transcribed = [transcribe_number(number) for number in numbers]\n return add_orders(transcribed)\n\n\ncisla =[23456738, 1234567, 2000000, 129523, 701198742]\n\n\nfor i in cisla:\n print(i)\n print(wrapper(i))\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"397136697","text":"#!/usr/bin/env python\n\nimport bs4\nimport const as c\nimport util\n\nclass MDChapter:\n\n def __init__(self, m_lang, m_id, m_vol, m_chap, m_title):\n self.lang = m_lang\n self.id = m_id \n self.vol = m_vol\n self.chap = m_chap\n self.title = m_title\n\n def getChapterFolderName(self):\n # NOTABENE: should this behavior be defined here? ( alt: util )\n _str_ch = \"\"\n if self.vol != \"\":\n _str_ch += \"Vol_\" + self.vol\n if self.chap != \"\":\n _str_ch += \"Ch_\" + self.chap\n\n _str_ch += \"_\" + self.title\n\n annoying_marks = [\"'\", \":\"]\n \n for mark in annoying_marks:\n _str_ch = _str_ch.replace(mark, \"--\")\n\n \n return _str_ch\n\n def getFullTitle(self):\n return \"Vol {} Chap {} - {}\".format(self.vol, self.chap, self.title)\n\n def getChapterLink(self):\n return c.N_ROOT_URL + \"chapter/\" + str(self.id)\n\n \nclass MangaParser:\n\n def __init__(self, m_type, m_source, nh=None):\n self.type = m_type\n self.source = m_source\n self.soup = bs4.BeautifulSoup(self.source, \"html.parser\")\n self.net_handler = nh\n\n def setNetHandler(self, nh):\n self.net_handler = nh\n\n def parse(self):\n\n if self.type == c.P_TYPE_TITLE_PAGE:\n return self.parseTitlePage()\n \n elif self.type == c.P_TYPE_NAV_PAGE:\n return self.parseNavPage()\n\n def parseTitlePage(self):\n \n #chapter_divs = self.soup.select(\".chapter-row\")\n chapter_page_links = self.soup.select(\".page-link\")\n\n # find the last page no. for the chapter list navigator\n index = -1\n for idx, each in enumerate(chapter_page_links):\n\n ch_list = each.findAll(\"span\")\n if ch_list:\n span = ch_list[0]\n if span[\"title\"] == \"Jump to last page\":\n index = idx\n break\n \n if index == -1:\n last_page_num = 1\n else:\n last_page_num = util.getNumPagesChapterNav(chapter_page_links[index][\"href\"])\n\n return last_page_num\n\n #print(\"No. of chapter navigation pages = \", last_page_num)\n\n\n def parseNavPage(self):\n\n #new_soup = bs4.BeautifulSoup(raw_page, \"html.parser\")\n chapter_divs = self.soup.select(\".chapter-row\")\n\n chapter_objs = []\n \n for div in chapter_divs:\n if \"data-title\" not in div.attrs:\n continue\n \n chap_obj = MDChapter( div[\"data-lang\"], div[\"data-id\"], div[\"data-volume\"], div[\"data-chapter\"], div[\"data-title\"])\n chapter_objs.append(chap_obj)\n\n return chapter_objs\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"34210646","text":"from selenium import webdriver\nfrom lxml import etree\nimport json\n\nbrowser = webdriver.Chrome()\n\nbrowser.get(\"http://www.biqukan.com/1_1094/5403177.html\")\nh = browser.page_source\nbrowser.close()\nprint(h)\nhtml = etree.HTML(h)\ntext = html.xpath(\"//div[@class='showtxt']//text()\")\nprint(text)\nwith open(\"./doc/xs.txt\", \"a\", encoding=\"utf-8\") as f:\n for t in text:\n f.write(t.strip())\n f.write(\"\\n\")\n print(\"保存成功\")\n","sub_path":"e/demo_chrome.py","file_name":"demo_chrome.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"196595369","text":"\n# coding: utf-8\n\n# In[1]:\n\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport urllib\nfrom collections import defaultdict\n\n\n# In[2]:\n\nfrom datetime import date, datetime\nfrom dateutil.rrule import rrule, DAILY\n\na = date(2015, 10, 27)\nb = datetime.now()\n#b = date(2016, 1, 26)\ndays = []\nfor dt in rrule(DAILY, dtstart=a, until=b):\n days.append(dt.strftime(\"%Y%m%d\"))\n\n\n# In[3]:\n\nnames = ['new-orleans-pelicans',\n 'miami-heat',\n 'golden-state-warriors',\n 'philadelphia-76ers',\n 'oklahoma-city-thunder',\n 'charlotte-hornets',\n 'memphis-grizzlies',\n 'boston-celtics',\n 'brooklyn-nets',\n 'sacramento-kings',\n 'phoenix-suns',\n 'new-york-knicks',\n 'cleveland-cavaliers',\n 'los-angeles-lakers',\n 'chicago-bulls',\n 'minnesota-timberwolves',\n 'washington-wizards',\n 'denver-nuggets',\n 'milwaukee-bucks',\n 'los-angeles-clippers',\n 'san-antonio-spurs',\n 'indiana-pacers',\n 'toronto-raptors',\n 'atlanta-hawks',\n 'portland-trail-blazers',\n 'dallas-mavericks',\n 'houston-rockets',\n 'detroit-pistons',\n 'orlando-magic',\n 'utah-jazz']\n\n\n# In[4]:\n\ndef spreadToFloat(spread):\n try:\n if spread[0]=='+':\n return float(spread[1:])\n elif spread[0]=='-':\n return -float(spread[1:])\n except:\n return False\n\ndef overUnderToFloat(ov):\n if ov[0]=='O' or ov[0]=='U' or ov[0]=='P':\n return float(ov[3:])\n else:\n print(ov)\n return float(ov)\n \ndef toDate(date):\n month, day = date.split('/')\n if int(month)>=10:\n return date+'/2015'\n else:\n return date+'/2016'\n\n\n# In[5]:\n\ngames_dict = defaultdict(bool)\n\ndef getTeamOdds(team):\n curr_team=team\n base_url = 'https://www.teamrankings.com/nba/team/'+team\n html_week = urllib.urlopen(base_url).read()\n soup = BeautifulSoup(html_week, 'html.parser')\n table = soup.find_all('table')[1]\n table_body = table.find('tbody')\n df = pd.DataFrame(columns=('date', 'opp', 'score', 'loc', 'spread', 'ovUnd', 'moneyline'))\n rows = table_body.find_all('tr')\n parseRows(rows, curr_team)\n\ndef parseRows(rows, curr_team):\n row_list = []\n \n for row in rows:\n cols = row.find_all('td')\n opp = cols[1].a['href'].split('/')[3]\n date = toDate(cols[0].text)\n if len(cols[2].text.split(':'))>1:\n break\n home_score, away_score = cols[2].text.split(' ')[1].split('-')\n loc = cols[3].text\n spread = spreadToFloat(cols[6].text)\n\n spread_def=''\n home=''\n away=''\n if loc=='Home':\n spread_def='home_spread'\n home=curr_team\n away=opp\n else:\n spread_def='away_spread'\n home=opp\n away=curr_team\n away_score, home_score = home_score, away_score\n\n if spread:\n ovUn = overUnderToFloat(cols[7].text)\n moneyLine = spreadToFloat(cols[8].text)\n idx = home+','+away+','+date\n if games_dict[idx]:\n games_dict[idx][spread_def]=spread\n if not (games_dict[idx]['ovUn']==ovUn):# and games_dict[idx]['moneyLine']==moneyLine):\n print('Mismatch')\n #print games_dict[idx]['ovUn']==ovUn\n else:\n #print idx\n games_dict[idx]={'date': date, 'home': home, 'away': away, 'home_score': home_score, 'away_score': away_score, spread_def: spread, 'ovUn': ovUn}\n #print row\n \n #row = {'date': date, 'home': home, 'away': away, 'home_score': home_score, 'away_score': away_score, 'loc': loc, spread_def: spread, 'ovUn': ovUn, 'moneyLine': moneyLine}\n # row_list.append(row)\n \n\n\n# In[6]:\n\ngames_dict = defaultdict(bool)\nfor team in names:\n print(team)\n getTeamOdds(team)\ngames = pd.DataFrame(games_dict.values())\n\n\n# In[7]:\n\ngames.to_csv('data/nba-games-current.csv', index=False)\n\n\n# In[8]:\n\nlen(games)\n\n\n# In[ ]:\n\n\n\n","sub_path":"NBA_data.py","file_name":"NBA_data.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"176144970","text":"\n# Map allows us to execute a function on each item in a list\n\n# list\noneTo10 = list(range(1, 11))\nprint(oneTo10)\n\n# The function to pass into map\ndef dbl_num(num):\n return num * 2\n\n# Pass in the function and the list to generate a new list\nnewList = list(map(dbl_num, oneTo10))\nprint(newList)\n\n# You could do the same thing with a lambda\nnewList = list(map((lambda x: x * 2), oneTo10))\nprint(newList)\n\n# You can perform calculations against multiple lists\nbList = list(map((lambda x, y: x + y), [1, 2, 3], [1, 2, 3]))\nprint(bList)\n","sub_path":"4 python cheet sheet/zh_lists_map.py","file_name":"zh_lists_map.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"205853836","text":"from django.conf import settings\n\ndef get_s3direct_destinations():\n \"\"\"Returns s3direct destinations.\n\n NOTE: Don't use constant as it will break ability to change at runtime (e.g. tests)\n \"\"\"\n return getattr(settings, 'S3DIRECT_DESTINATIONS', None)\n\ndef get_key(key, file_name, dest):\n if hasattr(key, '__call__'):\n fn_args = [file_name, ]\n args = dest.get('key_args')\n if args:\n fn_args.append(args)\n object_key = key(*fn_args)\n elif key == '/':\n object_key = file_name\n else:\n object_key = '%s/%s' % (key.strip('/'), file_name)\n return object_key\n","sub_path":"s3direct/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"15997387","text":"from certbot.plugins import dns_common\nfrom CloudFlare.cloudflare import CloudFlare, CloudFlareAPIError\n\nfrom middlewared.service import CallError, private, Service\n\n\nclass DNSAuthenticatorService(Service):\n\n class Config:\n namespace = 'acme.dns.authenticator'\n\n @private\n def cloudflare_txt_record_update(self, domain, challenge, key, cloudflare_email, api_key):\n cf = CloudFlare(cloudflare_email, api_key)\n zone_id = self.find_cloudflare_zone_id(cf, domain)\n record_name = challenge.validation_domain_name(domain)\n record_content = f'\"{challenge.validation(key)}\"'\n data = {'type': 'TXT', 'name': record_name, 'content': record_content, 'ttl': 3600}\n\n try:\n cf.zones.dns_records.post(zone_id, data=data)\n except CloudFlareAPIError as e:\n code = int(e)\n hint = None\n\n if code == 1009:\n hint = 'Does your API token have \"Zone:DNS:Edit\" permissions?'\n\n self.middleware.logger.error('Encountered CloudFlareAPIError adding TXT record: %d %s', code, e)\n raise CallError(\n f'Error communicating with the Cloudflare API: {e}{f\"({hint})\" if hint else \"\"}'\n )\n\n record_id = self.find_txt_record_id(cf, zone_id, record_name, record_content)\n if record_id:\n self.middleware.logger.debug('Successfully added TXT record with record_id: %s', record_id)\n else:\n raise CallError('Unable to find inserted text record via cloudflare API.')\n\n @private\n def find_cloudflare_zone_id(self, cf, domain):\n zone_name_guesses = dns_common.base_domain_name_guesses(domain)\n zones = []\n code = msg = None\n\n for zone_name in zone_name_guesses:\n params = {'name': zone_name, 'per_page': 1}\n\n try:\n zones = cf.zones.get(params=params)\n except CloudFlareAPIError as e:\n code = int(e)\n msg = str(e)\n hint = None\n\n if code == 6003:\n hint = 'Did you copy your entire API token/key?'\n elif code == 9103:\n hint = 'Did you enter the correct email address and Global key?'\n elif code == 9109:\n hint = 'Did you enter a valid Cloudflare Token?'\n\n if hint:\n raise CallError(\n f'Error determining zone_id: {code} {msg}. Please confirm that you have supplied '\n f'valid Cloudflare API credentials. ({hint})'\n )\n else:\n self.middleware.logger.debug(\n 'Unrecognised CloudFlareAPIError while finding zone_id: %d %s. '\n 'Continuing with next zone guess...', e, e\n )\n\n if zones:\n zone_id = zones[0]['id']\n return zone_id\n\n common_msg = f'Unable to determine zone_id for {domain} using zone names: {zone_name_guesses}'\n if msg is not None:\n if 'com.cloudflare.api.account.zone.list' in msg:\n raise CallError(\n f'{common_msg}. Please confirm that the domain name has been entered correctly '\n 'and your Cloudflare Token has access to the domain.'\n )\n else:\n raise CallError(f'{common_msg}. The error from Cloudflare was: {code} {msg}.')\n else:\n raise CallError(\n f'{common_msg}. Please confirm that the domain name has been entered correctly '\n 'and is already associated with the supplied Cloudflare account.'\n )\n\n @private\n def find_txt_record_id(self, cf, zone_id, record_name, record_content):\n params = {'type': 'TXT', 'name': record_name, 'content': record_content, 'per_page': 1}\n try:\n records = cf.zones.dns_records.get(zone_id, params=params)\n except CloudFlareAPIError as e:\n self.middleware.logger.debug('Encountered CloudFlareAPIError getting TXT record_id: %s', e)\n records = []\n\n if records:\n # Cleanup is returning the system to the state we found it. If, for some reason,\n # there are multiple matching records, we only delete one because we only added one.\n return records[0]['id']\n self.middleware.logger.debug('Unable to find TXT record.')\n","sub_path":"src/middlewared/middlewared/plugins/acme_protocol_/cloudflare.py","file_name":"cloudflare.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"36501547","text":"\"\"\"\nThis file contains the battle class. A battle class contains two fleets\nand facilities to have them both fire, calculate potential damage, and then\nstate which ships are destroyed.\n\nOne day, this will be modified to have a list of fleets that then battle\nin a given order according to the game rules, as opposed to simply\ncomparing two fleets.\n\"\"\"\n\nimport copy as copy_module\nimport ships\nimport fleet as fleet_object\nimport damage_models\n\nclass Battle(object):\n def __init__(self, name, offense, defense):\n self.name = name\n self.defense = defense\n self.offense = offense\n #self.Ofleet_backup = copy_module.deepcopy(Ofleet)\n #self.Dfleet_backup = copy_module.deepcopy(Dfleet)\n\n def __str__(self):\n return \"%s:\\nOffense: %sDefense: %s\"%(self.name,str(self.offense),str(self.defense))\n\n def simulate(self, num):\n '''\n Simulates battles num times\n '''\n if self.offense == None or self.defense == None:\n print(\"Missing fleet information\")\n \n print(\"Simulation begins:\")\n\n # Reverse iteration, defensive fires first\n speed = 8\n while speed >= 0:\n d_attacks = []\n # Get all attacks from defensive ships in initiative group\n for ship in defense.get_ships_by_init(speed):\n for attack in ship.get_attacks():\n d_attacks.append(attack)\n\n # Apply all damage from defensive group to offensive ships\n if len(d_attacks) > 0:\n offense.apply_damage(\n sorted(d_attacks, key=lambda atk:atk[2]),\n damage_models.DefaultDamageDistributionModel())\n\n\n # Get all defensive attacks\n #for ship in offense.get_ships_by_init(speed):\n\n # Apply all damage from offensive group\n\n speed -= 1\n\n\n def get_attacks(self):\n all_attacks = []\n if self.offense is not None:\n all_attacks.append(self.offense.attack())\n if self.defense is not None:\n all_attacks.append(self.defense.attack())\n return all_attacks\n\n def get_hulls(self):\n #INCOMPLETE\n return\n\n def get_initiatives(self):\n #INCOMPLETE\n return\n\n def get_shields(self):\n #INCOMPLETE\n return\n\nif __name__ == '__main__':\n offense = fleet_object.Fleet(name=\"Offense\")\n offense.load_from_file('human.eFu', 1, 1, 1, 1)\n defense = fleet_object.Fleet(name=\"Defense\")\n defense.load_from_file('human.eFu', 0, 0, 1, 0)\n print(offense)\n print(defense)\n battle = Battle(\"Test battle\", offense, defense)\n battle.simulate(1)\n\n print(offense)\n print(defense)\n","sub_path":"src/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"161839819","text":"import random\nimport math\nfrom CMGTools.RootTools.fwlite.Analyzer import Analyzer\nfrom CMGTools.RootTools.fwlite.AutoHandle import AutoHandle\nfrom CMGTools.RootTools.physicsobjects.PhysicsObjects import Jet, GenJet\nfrom CMGTools.RootTools.utils.DeltaR import cleanObjectCollection, matchObjectCollection, bestMatch\nfrom CMGTools.RootTools.statistics.Counter import Counter, Counters\nfrom CMGTools.RootTools.physicsobjects.PhysicsObjects import GenParticle\nfrom CMGTools.RootTools.utils.DeltaR import deltaR2\n\nclass PFSimJetAnalyzer( Analyzer ):\n \"\"\"Analyze jets ;-)\n \"\"\"\n\n def __init__(self, cfg_ana, cfg_comp, looperName):\n super(PFSimJetAnalyzer,self).__init__(cfg_ana, cfg_comp, looperName)\n\n def declareHandles(self):\n super(PFSimJetAnalyzer, self).declareHandles()\n\n def beginLoop(self):\n super(PFSimJetAnalyzer,self).beginLoop()\n self.counters.addCounter('jets')\n count = self.counters.counter('jets')\n count.register('all events')\n\n \n def process(self, iEvent, event):\n \n self.readCollections( iEvent )\n\n self.counters.counter('jets').inc('all events')\n\n event.selectedGenJets = filter(self.testJet, event.genJets)\n\n # Could have a better lepton rejection at gen level..\n event.cleanGenJets, dummy = cleanObjectCollection( event.selectedGenJets,\n masks = event.leptons,\n deltaRMin = 0.5 )\n \n\n\n def match(jet, objects, name):\n bm, dr2 = bestMatch(jet, objects)\n if bm:\n bm.dr = math.sqrt(dr2)\n setattr(jet, name, bm)\n \n for jet in event.cleanGenJets:\n if hasattr(event, 'recJets'):\n match(jet, event.recJets, 'rec')\n if jet.rec:\n response = jet.rec.pt()/jet.pt()\n## if response>0.98 and response<1.2:\n## print '-'*50\n## print jet.rec\n## pfconstituents = jet.rec.getPFConstituents()\n## for pfc in pfconstituents:\n## print pfc.pt(), pfc.pdgId()\n match(jet, event.simJets, 'sim')\n match(jet, event.genParticles3, 'genPtc3')\n \n \n return True \n \n def testJet( self, jet ):\n # 2 is loose pile-up jet id\n return jet.pt() > self.cfg_ana.jetPt and \\\n abs( jet.eta() ) < self.cfg_ana.jetEta \n\n\n","sub_path":"CMGTools/PFSim/python/analyzers/PFSimJetAnalyzer.py","file_name":"PFSimJetAnalyzer.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"180457022","text":"\"\"\"empty message\n\nRevision ID: 8fa168decf74\nRevises:\nCreate Date: 2018-09-02 23:00:20.045335\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '8fa168decf74'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table('stock',\n sa.Column('symbol', sa.String(length=20), nullable=False),\n sa.Column('name', sa.String(100), nullable=False),\n sa.Column('is_active', sa.Boolean(), nullable=True),\n sa.Column('total_count', sa.Integer(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('symbol')\n )\n op.create_table('tweet',\n sa.Column('id', sa.String(length=50), nullable=False),\n sa.Column('text', sa.String(length=500), nullable=True),\n sa.Column('language', sa.String(length=10), nullable=True),\n sa.Column('author_id', sa.String(length=50), nullable=True),\n sa.Column('author_followers', sa.Integer(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('tweet_link',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('url', sa.String(length=200), nullable=True),\n sa.Column('tweet_id', sa.String(length=50), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.ForeignKeyConstraint(['tweet_id'], ['tweet.id'], ),\n )\n op.create_table('tweet_symbol',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('symbol', sa.String(length=20), nullable=False),\n sa.Column('tweet_id', sa.String(length=50), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.ForeignKeyConstraint(['symbol'], ['stock.symbol'], ),\n sa.ForeignKeyConstraint(['tweet_id'], ['tweet.id'], ),\n )\n\n\ndef downgrade():\n op.drop_table('tweet_link')\n op.drop_table('tweet_url')\n op.drop_table('tweet')\n op.drop_table('stock')\n","sub_path":"app/backend/stream-listener/migrations/versions/8fa168decf74_.py","file_name":"8fa168decf74_.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"233397992","text":"\"\"\"\nMinimal library for interacting with REDCap's web API.\n\"\"\"\nimport logging\nimport re\nimport requests\nfrom enum import Enum\nfrom functools import lru_cache, wraps\nfrom operator import itemgetter\nfrom typing import Any, Dict, List\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass Project:\n \"\"\"\n Interact with a REDCap project via the REDCap web API.\n\n The constructor requires an *api_url* and *api_token* which must point to\n REDCap's web API endpoint. The third required parameter *project_id* must\n match the project id returned by the API. This is a sanity check that the\n API token is for the intended project, since tokens are project-specific.\n \"\"\"\n api_url: str\n api_token: str\n base_url: str\n _details: dict\n _instruments: List[str] = None\n _fields: List[dict] = None\n _redcap_version: str = None\n\n def __init__(self, api_url: str, api_token: str, project_id: int) -> None:\n self.api_url = api_url\n self.api_token = api_token\n\n # Assuming that the base url for a REDCap instance is just removing the\n # trailing 'api' from the API URL\n self.base_url = re.sub(r'api/?$', '', api_url)\n\n # Sanity check project details\n self._details = self._fetch(\"project\")\n\n assert self.id == project_id, \\\n f\"REDCap API token provided for project {project_id} is actually for project {self.id} ({self.title!r})!\"\n\n\n @property\n def id(self) -> int:\n \"\"\"Numeric ID of this project.\"\"\"\n return self._details[\"project_id\"]\n\n\n @property\n def title(self) -> str:\n \"\"\"Name of this project.\"\"\"\n return self._details[\"project_title\"]\n\n\n @property\n def instruments(self) -> List[str]:\n \"\"\"\n Names of all instruments in this REDCap project.\n \"\"\"\n if not self._instruments:\n nameof = itemgetter(\"instrument_name\")\n self._instruments = list(map(nameof, self._fetch(\"instrument\")))\n\n return self._instruments\n\n\n @property\n def fields(self) -> List[dict]:\n \"\"\"\n Metadata about all fields in this REDCap project.\n \"\"\"\n if not self._fields:\n self._fields = self._fetch(\"metadata\")\n\n return self._fields\n\n\n @property\n def record_id_field(self) -> str:\n \"\"\"\n Name of the field containing the unique id for each record.\n\n For auto-numbered projects, this is typically ``record_id``, but for\n other data entry projects, it can be any arbitrary name. It is always\n the first field in a project.\n \"\"\"\n return self.fields[0][\"field_name\"]\n\n\n @property\n def redcap_version(self) -> str:\n \"\"\"\n Version string of the REDCap instance.\n \"\"\"\n if not self._redcap_version:\n self._redcap_version = self._fetch(\"version\", format = \"text\")\n\n return self._redcap_version\n\n\n def record(self, record_id: str, *, raw: bool = False) -> List['Record']:\n \"\"\"\n Fetch the REDCap record *record_id* with all its instruments.\n\n The optional *raw* parameter controls if numeric/coded values are\n returned for multiple choice fields. When false (the default),\n string labels are returned.\n\n Note that in longitudinal projects with events or classic projects with\n repeating instruments, this may return more than one result. The\n results will be share the same record id but be differentiated by the\n fields ``redcap_event_name``, ``redcap_repeat_instrument``, and\n ``redcap_repeat_instance``.\n \"\"\"\n return self.records(ids = [record_id], raw = raw)\n\n\n def records(self, *,\n since_date: str = None,\n until_date: str = None,\n ids: List[str] = None,\n fields: List[str] = None,\n raw: bool = False) -> List['Record']:\n \"\"\"\n Fetch records for this REDCap project.\n\n Values are returned as string labels not numeric (\"raw\") codes.\n\n The optional *since_date* parameter can be used to limit records to\n those created/modified after the given timestamp.\n\n The optional *until_date* parameter can be used to limit records to\n those created/modified before the given timestamp.\n\n Both *since_date* and *until_date* must be formatted as\n ``YYYY-MM-DD HH:MM:SS`` in the REDCap server's configured timezone.\n\n The optional *ids* parameter can be used to limit results to the given\n record ids.\n\n The optional *fields* parameter can be used to limit the fields\n returned for each record.\n\n The optional *raw* parameter controls if numeric/coded values are\n returned for multiple choice fields. When false (the default), string\n labels are returned.\n \"\"\"\n parameters = {\n 'type': 'flat',\n 'rawOrLabel': 'raw' if raw else 'label',\n 'exportCheckboxLabel': 'true', # ignored by API if rawOrLabel == raw\n }\n\n assert not ((since_date or until_date) and ids), \\\n \"The REDCap API does not support fetching records filtered by id *and* date.\"\n\n if since_date:\n parameters['dateRangeBegin'] = since_date\n\n if until_date:\n parameters['dateRangeEnd'] = until_date\n\n if ids is not None:\n parameters['records'] = \",\".join(map(str, ids))\n\n if fields is not None:\n parameters['fields'] = \",\".join(map(str, fields))\n\n return [Record(self, r) for r in self._fetch(\"record\", parameters)]\n\n\n def _fetch(self, content: str, parameters: Dict[str, str] = {}, *, format: str = \"json\") -> Any:\n \"\"\"\n Fetch REDCap *content* with a POST request to the REDCap API.\n\n Consult REDCap API documentation for required and optional parameters\n to include in API request.\n \"\"\"\n LOG.debug(f\"Fetching content={content} from REDCap with params {parameters}\")\n\n headers = {\n 'Content-type': 'application/x-www-form-urlencoded',\n 'Accept': 'application/json' if format == \"json\" else 'text/*'\n }\n\n data = {\n **parameters,\n 'content': content,\n 'token': self.api_token,\n 'format': format,\n }\n\n response = requests.post(self.api_url, data=data, headers=headers)\n response.raise_for_status()\n\n return response.json() if format == \"json\" else response.text\n\n\n@lru_cache()\ndef CachedProject(api_url: str, api_token: str, project_id: int) -> Project:\n \"\"\"\n Memoized constructor for a :class:`Project`.\n\n Useful when loading projects dynamically, e.g. from REDCap DET\n notifications, to avoid the initial fetch of project details every time.\n \"\"\"\n return Project(api_url, api_token, project_id)\n\n\nclass Record(dict):\n \"\"\"\n A single REDCap record ``dict``.\n\n All key/value pairs returned by the REDCap API request are present as\n dictionary items.\n\n Must be constructed with a REDCap :py:class:``Project``, which is stored as\n the ``project`` attribute and used to set the ``id`` attribute storing the\n record's primary id.\n \"\"\"\n project: Project\n id: str\n\n def __init__(self, project: Project, data: Any = {}) -> None:\n super().__init__(data)\n self.project = project\n self.id = self[self.project.record_id_field]\n\n\nclass InstrumentStatus(Enum):\n \"\"\"\n Numeric and string codes used by REDCap for instrument status.\n \"\"\"\n Incomplete = 0\n Unverified = 1\n Complete = 2\n\n\ndef is_complete(instrument: str, data: dict) -> bool:\n \"\"\"\n Test if the named *instrument* is marked complete in the given *data*.\n\n The *data* may be a DET notification or a record.\n\n >>> is_complete(\"test\", {\"test_complete\": \"Complete\"})\n True\n >>> is_complete(\"test\", {\"test_complete\": 2})\n True\n >>> is_complete(\"test\", {\"test_complete\": \"2\"})\n True\n >>> is_complete(\"test\", {\"test_complete\": \"Incomplete\"})\n False\n >>> is_complete(\"test\", {})\n False\n \"\"\"\n return data.get(f\"{instrument}_complete\") in {\n InstrumentStatus.Complete.name,\n InstrumentStatus.Complete.value,\n str(InstrumentStatus.Complete.value)\n }\n","sub_path":"lib/id3c/cli/redcap.py","file_name":"redcap.py","file_ext":"py","file_size_in_byte":8291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567667899","text":"# -*- coding: utf-8 -*-\nfrom goose.parsers import Parser\nfrom goose.utils import ReplaceSequence\n\nclass DocumentCleaner(object):\n \n def __init__(self):\n \n self.regExRemoveNodes = (\n \"^side$|combx|retweet|mediaarticlerelated|menucontainer|navbar\"\n \"|comment|PopularQuestions|contact|foot|footer|Footer|footnote\"\n \"|cnn_strycaptiontxt|links|meta$|scroll|shoutbox|sponsor\"\n \"|tags|socialnetworking|socialNetworking|cnnStryHghLght\"\n \"|cnn_stryspcvbx|^inset$|pagetools|post-attributes\"\n \"|welcome_form|contentTools2|the_answers\"\n \"|communitypromo|runaroundLeft|subscribe|vcard|articleheadings\"\n \"|date|^print$|popup|author-dropdown|tools|socialtools|byline\"\n \"|konafilter|KonaFilter|breadcrumbs|^fn$|wp-caption-text\"\n \"|source|legende|ajoutVideo|timestamp\"\n )\n \n self.regexpNS = \"http://exslt.org/regular-expressions\"\n self.queryNaughtyIDs = \"//*[re:test(@id, '%s', 'i')]\" % self.regExRemoveNodes\n self.queryNaughtyClasses = \"//*[re:test(@class, '%s', 'i')]\" % self.regExRemoveNodes\n self.queryNaughtyNames = \"//*[re:test(@name, '%s', 'i')]\" % self.regExRemoveNodes\n \n self.divToPElementsPattern = r\"<(a|blockquote|dl|div|img|ol|p|pre|table|ul)\"\n self.captionPattern = \"^caption$\"\n self.googlePattern = \" google \"\n self.entriesPattern = \"^[^entry-]more.*$\"\n self.facebookPattern = \"[^-]facebook\"\n self.twitterPattern = \"[^-]twitter\"\n \n self.tabsAndNewLinesReplcesments = ReplaceSequence()\\\n .create(\"\\n\", \"\\n\\n\")\\\n .append(\"\\t\")\\\n .append(\"^\\\\s+$\")\n \n \n def clean(self, article):\n \n \n docToClean = article.doc\n docToClean = self.cleanEmTags(docToClean)\n docToClean = self.removeDropCaps(docToClean)\n docToClean = self.removeScriptsAndStyles(docToClean)\n docToClean = self.cleanBadTags(docToClean)\n docToClean = self.removeNodesViaRegEx(docToClean, self.captionPattern)\n docToClean = self.removeNodesViaRegEx(docToClean, self.googlePattern)\n docToClean = self.removeNodesViaRegEx(docToClean, self.entriesPattern)\n docToClean = self.removeNodesViaRegEx(docToClean, self.facebookPattern)\n docToClean = self.removeNodesViaRegEx(docToClean, self.twitterPattern)\n docToClean = self.cleanUpSpanTagsInParagraphs(docToClean)\n docToClean = self.convertDivsToParagraphs(docToClean, 'div')\n docToClean = self.convertDivsToParagraphs(docToClean, 'span')\n return docToClean\n \n \n def cleanEmTags(self, doc):\n ems = Parser.getElementsByTag(doc, tag='em')\n for node in ems:\n images = Parser.getElementsByTag(node, tag='img')\n if len(images) == 0:\n node.drop_tag()\n return doc\n \n \n def removeDropCaps(self, doc):\n items = doc.cssselect(\"span[class~=dropcap], span[class~=drop_cap]\")\n for item in items:\n item.drop_tag()\n \n return doc\n \n \n def removeScriptsAndStyles(self, doc):\n # remove scripts\n scripts = Parser.getElementsByTag(doc, tag='script')\n for item in scripts:\n Parser.remove(item)\n \n # remove styles\n styles = Parser.getElementsByTag(doc, tag='style')\n for item in styles:\n Parser.remove(item)\n \n # remove comments\n comments = Parser.getComments(doc)\n for item in comments:\n Parser.remove(item)\n \n return doc\n \n \n def cleanBadTags(self, doc):\n \n # ids\n naughtyList = doc.xpath(self.queryNaughtyIDs, \n namespaces={'re':self.regexpNS})\n for node in naughtyList:\n Parser.remove(node)\n \n # class\n naughtyClasses = doc.xpath(self.queryNaughtyClasses, \n namespaces={'re':self.regexpNS})\n for node in naughtyClasses:\n Parser.remove(node)\n \n # name\n naughtyNames = doc.xpath(self.queryNaughtyNames, \n namespaces={'re':self.regexpNS})\n for node in naughtyNames:\n Parser.remove(node)\n \n return doc\n \n \n def removeNodesViaRegEx(self, doc, pattern):\n for selector in ['id', 'class']:\n reg = \"//*[re:test(@%s, '%s', 'i')]\" % (selector, pattern)\n naughtyList = doc.xpath(reg, namespaces={'re':self.regexpNS})\n for node in naughtyList:\n Parser.remove(node)\n return doc\n \n \n \n def cleanUpSpanTagsInParagraphs(self, doc):\n spans = doc.cssselect('p > span')\n for item in spans:\n item.drop_tag()\n return doc\n \n\n def getFlushedBuffer(self, replacementText, doc):\n return Parser.textToPara(replacementText)\n \n \n def getReplacementNodes(self, doc, div):\n replacementText = []\n nodesToReturn = []\n nodesToRemove = []\n childs = Parser.childNodesWithText(div)\n \n for kid in childs:\n # node is a p\n # and already have some replacement text\n if Parser.getTag(kid) == 'p' and len(replacementText) > 0:\n newNode = self.getFlushedBuffer(''.join(replacementText), doc)\n nodesToReturn.append(newNode)\n replacementText = []\n nodesToReturn.append(kid)\n # node is a text node\n elif Parser.isTextNode(kid):\n kidTextNode = kid\n kidText = Parser.getText(kid)\n replaceText = self.tabsAndNewLinesReplcesments.replaceAll(kidText)\n if(len(replaceText)) > 1:\n prevSibNode = Parser.previousSibling(kidTextNode)\n while prevSibNode is not None \\\n and Parser.getTag(prevSibNode) == \"a\" \\\n and Parser.getAttribute(prevSibNode, 'grv-usedalready') != 'yes':\n outer = \" \" + Parser.outerHtml(prevSibNode) + \" \"\n replacementText.append(outer)\n nodesToRemove.append(prevSibNode)\n Parser.setAttribute(prevSibNode, \n attr='grv-usedalready', value='yes')\n prev = Parser.previousSibling(prevSibNode)\n prevSibNode = prev if prev is not None else None\n # append replaceText\n replacementText.append(replaceText)\n #\n nextSibNode = Parser.nextSibling(kidTextNode)\n while nextSibNode is not None \\\n and Parser.getTag(nextSibNode) == \"a\" \\\n and Parser.getAttribute(nextSibNode, 'grv-usedalready') != 'yes':\n outer = \" \" + Parser.outerHtml(nextSibNode) + \" \"\n replacementText.append(outer)\n nodesToRemove.append(nextSibNode)\n Parser.setAttribute(nextSibNode, \n attr='grv-usedalready', value='yes')\n next = Parser.nextSibling(nextSibNode)\n prevSibNode = next if next is not None else None\n \n # otherwise\n else:\n nodesToReturn.append(kid)\n \n # flush out anything still remaining\n if(len(replacementText) > 0):\n newNode = self.getFlushedBuffer(''.join(replacementText), doc)\n nodesToReturn.append(newNode)\n replacementText = []\n \n #\n for n in nodesToRemove:\n Parser.remove(n)\n \n return nodesToReturn\n \n \n def replaceElementsWithPara(self, doc, div):\n Parser.replaceTag(div, 'p')\n \n def convertDivsToParagraphs(self, doc, domType):\n badDivs = 0\n elseDivs = 0\n convertedTextNodes = 0\n divs = Parser.getElementsByTag(doc, tag=domType)\n replaceNodesList = {}\n \n divIndex = 0\n errors = []\n goods = []\n regexps = []\n selectors = []\n tags = ['a','blockquote','dl','div','img','ol','p','pre','table','ul']\n \n for div in divs:\n items = Parser.getElementsByTags(div, tags)\n if div is not None and len(items) == 0:\n self.replaceElementsWithPara(doc, div)\n badDivs += 1\n elif div is not None:\n replaceNodes = self.getReplacementNodes(doc, div)\n div.clear()\n \n for c, n in enumerate(replaceNodes):\n div.insert(c, n)\n \n elseDivs +=1\n \n return doc\n \n \n \n \n \n \n \nclass StandardDocumentCleaner(DocumentCleaner):\n pass","sub_path":"goose/cleaners/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"517708796","text":"from .react_template import ReactComponent\n\nclass UIComponent(object):\n \"\"\"\n \"\"\"\n def __init__(self, component_type, options, route_func):\n \"\"\"\"\"\"\n self.params = {\n \"type\": component_type,\n \"options\": options\n }\n self.route_func = route_func\n\n def register_route(self, app):\n \"\"\"\"\"\"\n if \"url\" not in self.params[\"options\"]:\n raise Exception(\"Component does not have a URL property\")\n\n if not hasattr(self.route_func, \"__call__\"):\n raise Exception(\"No app route function supplied\")\n\n app.add_url_rule(self.params[\"options\"][\"url\"],\n self.params[\"options\"][\"url\"],\n self.route_func)\n app.view_functions[self.params[\"options\"][\"url\"]] = self.route_func\n\nclass SimpleComponent(object):\n def __init__(self, layout, src_file, component_id, props):\n self.layout = layout\n self.src_file = src_file\n self.component_id = component_id\n self.props = props\n\n def render(self, path):\n return ReactComponent(\n self.layout,\n self.src_file,\n self.component_id,\n props=self.props,\n static_path=path)\n\nclass UILayout(object):\n\n def __init__(self, layout, src_file, component_id, dynamic=True, filter_style=\"'btn-group'\"):\n self.layout = layout\n self.src_file = src_file\n self.component_id = component_id\n self.filter_style = filter_style\n self.filters = []\n self.charts = []\n self.dynamic = dynamic\n\n def add_filter(self, component):\n if getattr(component, \"name\") != \"Filter\":\n raise Exception(\"Component is not an instance of Filter\")\n self.filters.append(component)\n\n def add_chart(self, component):\n if getattr(component, \"name\") != \"Chart\":\n raise Exception(\"Component is not an instance of Chart\")\n self.charts.append(component)\n\n def build_props(self):\n props = {}\n if self.filters:\n props[\"filters\"] = [f.params for f in self.filters]\n if self.charts:\n props[\"charts\"] = [c.params for c in self.charts]\n\n props[\"dynamic\"] = self.dynamic\n props[\"filter_style\"] = self.filter_style\n return props\n\n def assign_routes(self, app):\n for f in self.filters:\n if f.route_func:\n f.register_route(app)\n\n for c in self.charts:\n if c.route_func:\n c.register_route(app)\n\n def render_layout(self, app, path):\n self.assign_routes(app)\n return ReactComponent(\n self.layout,\n self.src_file,\n self.component_id,\n props=self.build_props(),\n static_path=path)\n","sub_path":"pyxley/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"261232656","text":"# Copyright 2015 Akanda, Inc.\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 mock\n\nfrom astara.common import config\nfrom astara.test.unit import base\n\n\nclass TestConfig(base.RugTestBase):\n def _test_get_best_config_path(self, original, expected, files_exist=()):\n def mock_isfile_f(f):\n return f in files_exist\n\n with mock.patch('os.path.isfile', side_effect=mock_isfile_f):\n self.assertEqual(\n config.get_best_config_path(original),\n expected\n )\n\n def test_get_best_config_path_preferred(self):\n self._test_get_best_config_path(\n config.PREFERRED_CONFIG_FILEPATH,\n config.PREFERRED_CONFIG_FILEPATH\n )\n\n def test_get_best_config_path_legacy(self):\n self._test_get_best_config_path(\n config.PREFERRED_CONFIG_FILEPATH,\n '/etc/akanda/rug.ini',\n ('/etc/akanda/rug.ini',)\n )\n","sub_path":"astara/test/unit/common/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"632993769","text":"import re\nfrom datetime import timedelta, datetime\nfrom selenium import webdriver\nimport time\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import StaleElementReferenceException\n\n# параметры\ndays = 30 # количество допустимых дней с момента публикации\nacc_subscriptions = 55500 # количество допустимых подписок у аккаунта\npublications = 10 # необходимый минимум публикаций\ntoday = datetime.now()\nsite = 'OFF' # 'ON' - если есть сайт не добавляет, 'OFF' - добавляет\n\n# функция проверки существования элемента на странице\ndef xpath_existence(url):\n try:\n browser.find_element_by_xpath(url)\n existence = 1\n except NoSuchElementException:\n existence = 0\n return existence\n\n\nbrowser = webdriver.Chrome(\"/home/viktor_/PycharmProjects/MyProjects/instabot/chromedriver\")\n\n# считываение из файла всех ссылок на пользователей\nwith open('persons_list.txt', 'r') as f:\n file_list = []\n for line in f:\n file_list.append(line)\n\n# ОБРАБОТКА ССЫЛОК\n\n# 1) аккаунт должен быть публичным\n# 2) у аккаунта не должно быть более указанного числа подписок\n# 3) не должно быть ссылки на сайт\n# 4) необходимо фото профиля\n# 5) необходимо не менее 10 публикаций в профиле\n# 6) последняя публикация не менее days дней назад\n\n\nfiltered_list = []\ni = 0 # количество подходящий пользователей\nj = 0 # номер вывода в терминале\n\nfor person in file_list:\n j += 1\n browser.get(person)\n time.sleep(0.4)\n\n # 1) проверка на закрытость аккаунта\n element = \"//section/main/div/div/article/div[1]/div/h2\"\n if xpath_existence(element) == 1:\n try:\n if browser.find_element_by_xpath(element).text == \"This Account is Private\" \\\n or \"Это закрытый аккаунт\":\n print(j, \"Приватный аккаунт\")\n continue\n except StaleElementReferenceException:\n print(\"Ошибка, код ошибки: 1\")\n\n # 2) Проверка на допустимое число подписок\n element = \"//section/main/div/header/section/ul/li[3]/a/span\"\n if xpath_existence(element) == 0:\n print(\"Ошибка, код ошибки: 2\")\n continue\n status = browser.find_element_by_xpath(element).text\n status = re.sub(r'\\s', '', status) # удаление пробелов из числа подписок\n if int(status) > acc_subscriptions:\n print(j, \"У аккаунта слишком много подписок\")\n continue\n\n # 3) Не должно быть ссылки на сайт\n if site == 'ON':\n element = \"//section/main/div/header/section/div[2]/a\"\n if xpath_existence(element) == 1:\n print(j, \"Есть ссылка на сайт\")\n continue\n\n # 4) Проверка на наличие как минимум заданного кол-ва публикаций\n element = \"//section/main/div/header/section/ul/li[1]/a/span\"\n\n if xpath_existence(element) == 0:\n print(j, \"Ошибка, код ошибки: 4\")\n continue\n status = browser.find_element_by_xpath(element).text\n status = re.sub(r'\\s', '', status) # удаление пробелов из числа подписок\n if int(status) < publications:\n print(j, \"У аккаунта слишком мало публикаций\")\n continue\n\n # 5) проверка на наличие аватарки\n element = \"//section/main/div/header/div/div/span/img\"\n if xpath_existence(element) == 0:\n print(j, \"Ошибка, код ошибки: 5\")\n continue\n status = browser.find_element_by_xpath(element).get_attribute(\"src\")\n if status.find(\"s150x150\") == -1:\n print(j, \"Профиль без аватарки\")\n continue\n\n # 6) Проверка на дату последней публикации\n element = \"//a[contains(@href, '/p/')]\"\n if xpath_existence(element) == 0:\n print(j, \"Ошибка, код ошибки: 6\")\n continue\n status = browser.find_element_by_xpath(element).get_attribute(\"href\")\n browser.get(status)\n post_date = browser.find_element_by_xpath(\"//time\").get_attribute(\"datetime\")\n year = int(post_date[0:4])\n month = int(post_date[5:7])\n day = int(post_date[8:10])\n post_date = datetime(year, month, day)\n period = today - post_date\n if period.days > days:\n print(j, \"Последняя публикация была очень давно\")\n continue\n\n # ДОБАВЛЕНИЕ ПОЛЬЗОВАТЕЛЯ В ОТФИЛЬТРОВАННЫЙ ФАЙЛ\n filtered_list.append(person)\n print(j, \"Добавлен новый пользователь\", person)\n i += 1\n #\n # if i > 3:\n # break\n\n# ВЫХОД ИЗ ЦИКЛА\n\n# Запись в файл\nwith open(\"filtered_persons_list.txt\", 'w') as f:\n for line in filtered_list:\n f.write(line)\nprint(\"\\nДобавлено\", i, \"пользователей\")\nbrowser.quit()","sub_path":"instabot/filtration.py","file_name":"filtration.py","file_ext":"py","file_size_in_byte":5567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"308357327","text":"from collections import defaultdict, Counter\nimport re\nimport pandas as pd\n\npd.set_option('display.max_columns', 500)\n\n\nclass Address_Dict:\n def __init__(self):\n path = './resources/zenkoku.csv'\n self.df = pd.DataFrame\n with open(path, 'r') as f:\n self.df = pd.read_csv(f, index_col='住所CD', na_filter=False)\n # print(self.df.columns.values)\n\n # 住所文字列を生成\n self.df.loc[:, '住所文字列'] = ''\n self.df.loc[self.df.事業所フラグ == 0, '住所文字列'] = self.df['都道府県'] + \\\n self.df['市区町村'] + self.df['町域'] + self.df['字丁目']\n self.df.loc[self.df.事業所フラグ == 1, '住所文字列'] = self.df['都道府県'] + \\\n self.df['市区町村'] + self.df['事業所住所']\n\n # # すべての住所文字列ができたか確認\n print(self.df.loc[self.df.住所文字列 == ''])\n\n # 転置インデックスを作成\n self.inversed_index = self.make_index(self.df)\n\n @staticmethod\n def bigram(sentence):\n \"\"\"一文のbigramと出現場所を返す\n\n :param sentence:\n :return:\n \"\"\"\n term_list = []\n location_list = []\n for i in range(len(sentence)):\n term = sentence[i:i + 2].strip()\n if len(term) == 2:\n term_list.append(term)\n location_list.append(i)\n\n return term_list, location_list\n\n def make_index(self, df):\n \"\"\"検索用のメインの辞書を作成する\n\n :param df:\n :return:\n \"\"\"\n inversed_index = defaultdict(list)\n for index, sentence in df.住所文字列.items():\n term_list, location_list = self.bigram(sentence)\n for term, loc in zip(term_list, location_list):\n inversed_index[term].append((index, loc))\n return inversed_index\n\n def address_search(self, word):\n # 検索処理\n hit_list = []\n # 1文字の場合\n if len(word) == 1:\n for i in self.inversed_index.keys():\n if re.search('.*' + word + '.*', i):\n hit_list.append(self.inversed_index[i])\n # 2文字以上の場合\n else:\n target, _ = self.bigram(word)\n for i in target:\n if i in self.inversed_index.keys():\n hit_list.append(self.inversed_index[i])\n\n print(hit_list)\n\n # インデックス値のみ抽出\n result = []\n for i in hit_list:\n for j in i:\n result.append(j[0])\n\n print(result)\n\n # 最頻値の集計\n cnt = Counter(result)\n N = 10\n top_n = cnt.most_common(50)\n if len(cnt) > N:\n print('検索結果が' + str(N) + '件以上あります')\n\n print(top_n)\n\n # 結果出力\n rslt = []\n for index, _ in top_n:\n # print(self.df.at[index, '住所文字列'])\n if self.df.loc[index, '事業所フラグ'] == 1:\n continue\n rslt.append(self.df.loc[index, '住所文字列'])\n if len(rslt) >= 40:\n break\n return rslt\n\n def random_sampling(self, num):\n \"\"\"ランダムに住所文字列を返す\n\n :param num: 抽出する数\n :return: ランダムに抽出した住所のリスト\n \"\"\"\n return self.df.sample(num)['住所文字列'].values\n\n def office_search(self, word):\n \"\"\"事業所を検索\n\n :param word: 入力文字列\n :type word: str\n \"\"\"\n # 入力なし処理\n if word is '':\n return []\n\n # 検索処理\n # インデックスを抽出\n hit_list = self.df[self.df.事業所名.str.contains(word) == True]\n print(hit_list)\n N = 10\n if len(hit_list) > N:\n print('検索結果が' + str(N) + '件以上あります')\n\n # 結果出力\n rslt = []\n for index in hit_list.index.values:\n print(self.df.at[index, '住所文字列'])\n rslt.append(self.df.at[index, '事業所名'])\n if len(rslt) >= 40:\n break\n\n rslt = list(set(rslt))\n\n return rslt\n","sub_path":"A_dict.py","file_name":"A_dict.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"179826094","text":"# [ pytorch - ignite - engine ]\n# https://pytorch.org/ignite/engine.html\n# https://github.com/pytorch/ignite/blob/master/examples/mnist/mnist.py\n\n# [ python optimizer ]\n# https://pytorch.org/tutorials/beginner/examples_nn/two_layer_net_optim.html\n\n\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\n\nfrom ignite.engine import Engine, Events\nfrom ignite.metrics import Loss\n\nimport matplotlib.pyplot as plt\n\nfrom pytorch.DataLoader.dataloader_example_extended import get_data_loaders_from_scratch\nfrom pytorch.train_model.train_model import train, test\n\n\n#\n# Model\n#\n\n# --define models\ndef get_device():\n device = 'cpu'\n if torch.cuda.is_available():\n device = \"cuda\"\n return device\n\n\ndef get_model(dim_input, dim_hidden, dim_output):\n model = torch.nn.Sequential(\n torch.nn.Linear(dim_input, dim_hidden),\n torch.nn.ReLU(),\n torch.nn.Linear(dim_hidden, dim_output),\n )\n\n device = get_device()\n model = model.to(device)\n model = model.float()\n return model\n\n\n#\n# Ignite\n#\ndef create_supervised_trainer(model, optimizer, loss_fn,\n device=None,\n output_transform=lambda x, y, y_pred, loss: loss.item()):\n \"\"\"\n Factory function for creating a trainer for supervised models.\n\n Args:\n model (`torch.nn.Module`): the models to train.\n optimizer (`torch.optim.Optimizer`): the optimizer to use.\n loss_fn (torch.nn loss function): the loss function to use.\n device (str, optional): device type specification (default: None).\n Applies to both models and batches.\n non_blocking (bool, optional): if True and this copy is between CPU and GPU, the copy may occur asynchronously\n with respect to the host. For other cases, this argument has no effect.\n prepare_batch (callable, optional): function that receives `batch`, `device`, `non_blocking` and outputs\n tuple of tensors `(batch_x, batch_y)`.\n output_transform (callable, optional): function that receives 'x', 'y', 'y_pred', 'loss' and returns value\n to be assigned to engine's state.output after each iteration. Default is returning `loss.item()`.\n\n Note: `engine.state.output` for this engine is defind by `output_transform` parameter and is the loss\n of the processed batch by default.\n\n Returns:\n Engine: a trainer engine with supervised update function.\n \"\"\"\n\n def _update(engine, batch):\n model.train()\n # x, y = prepare_batch(batch, device=device, non_blocking=non_blocking)\n x, y = batch\n x, y = x.float(), y.float()\n y_pred = model(x)\n\n optimizer.zero_grad()\n loss = loss_fn(y_pred, y)\n loss.backward()\n optimizer.step()\n return output_transform(x, y, y_pred, loss) # todo: 이 부분에 뭐가 들어가��되지 ... ?\n\n return Engine(_update) # todo: 이 부분 뭘 한걸까 ... ?\n\n\ndef create_supervised_evaluator(model, metrics=None,\n device=None,\n output_transform=lambda x, y, y_pred: (y_pred, y,)):\n \"\"\"\n Factory function for creating an evaluator for supervised models.\n\n Args:\n model (`torch.nn.Module`): the models to train.\n metrics (dict of str - :class:`~ignite.metrics.Metric`): a map of metric names to Metrics.\n device (str, optional): device type specification (default: None).\n Applies to both models and batches.\n non_blocking (bool, optional): if True and this copy is between CPU and GPU, the copy may occur asynchronously\n with respect to the host. For other cases, this argument has no effect.\n prepare_batch (callable, optional): function that receives `batch`, `device`, `non_blocking` and outputs\n tuple of tensors `(batch_x, batch_y)`.\n output_transform (callable, optional): function that receives 'x', 'y', 'y_pred' and returns value\n to be assigned to engine's state.output after each iteration. Default is returning `(y_pred, y,)` which fits\n output expected by metrics. If you change it you should use `output_transform` in metrics.\n\n Note: `engine.state.output` for this engine is defind by `output_transform` parameter and is\n a tuple of `(batch_pred, batch_y)` by default.\n\n Returns:\n Engine: an evaluator engine with supervised inference function.\n \"\"\"\n metrics = metrics or {} # todo: 이거 왜 이렇게 들어가지 ... ?\n\n def _inference(engine, batch):\n # todo: 이거 어떻게 사용되는걸까 ... ?\n # todo: 이거 _inference 에서 engine 은 왜 필요한걸까 ... ?\n model.eval()\n with torch.no_grad():\n # x, y = prepare_batch(batch, device=device, non_blocking=non_blocking)\n x, y = batch\n x, y = x.float(), y.float()\n y_pred = model(x)\n return output_transform(x, y, y_pred)\n\n engine = Engine(_inference)\n\n for name, metric in metrics.items():\n metric.attach(engine, name)\n\n return engine\n\n\ndef run(loaders_dict, model=None, loss_fn=F.mse_loss,\n epochs=10,\n lr=0.001):\n\n #\n # Init\n #\n\n # 1) loader\n train_loader, valid_loader = loaders_dict['train'], loaders_dict['valid']\n\n # 2) models\n assert model is not None\n\n # 3) device\n device = \"cpu\"\n if torch.cuda.is_available():\n device = \"cuda\"\n\n # 4) optimizer\n optimizer = optim.Adam(model.parameters(), lr=lr)\n\n # 5) trainer object of Engine class i.e. from ignite.engine import create_supervised_trainer\n # (1) device\n # (2) define 'process_function' such as step or update function\n # -. def process_function(engine, batch):\n # > this function is used in\n # > run(exactly, _run_once_on_dataset) function of engine object\n # (3) make & return object by Engine(process_fuction)\n trainer = create_supervised_trainer(model, optimizer, loss_fn, device=device)\n\n # 6) evaluator object of Engine class i.e. from ignite.engine import create_supervised_evaluator\n # (1) device\n # (2) define 'process_function' such as step or update function\n # -. def process_function(engine, batch):\n # > this function is used in\n # > run(exactly, _run_once_on_dataset) function of engine object\n # (3) make object by Engine(process_fuction)\n # (4) attach metrics\n # (5) return engine object\n evaluator = create_supervised_evaluator(model,\n metrics={'mse': Loss(loss_fn)},\n device=device)\n\n #\n # Log\n #\n @trainer.on(Events.EPOCH_COMPLETED)\n def log_training_results(engine):\n evaluator.run(train_loader)\n metrics = evaluator.state.metrics\n avg_mse = metrics['mse']\n print(\"Training Results - Epoch: {} Avg mse: {:.2f}\".format(engine.state.epoch, avg_mse))\n\n @trainer.on(Events.EPOCH_COMPLETED)\n def log_validation_result(engine):\n evaluator.run(valid_loader)\n metrics = evaluator.state.metrics\n avg_mse = metrics['mse']\n print(\"Validation Results - Epoch: {} Avg MSE: {:.3f}\\n\".format(engine.state.epoch, avg_mse))\n\n #\n # Run - Train\n #\n trainer.run(train_loader, max_epochs=epochs)\n\n return trainer, model\n\n\nif __name__ == \"__main__\":\n #\n # Data Loader\n #\n train_loader, valid_loader, test_loader = get_data_loaders_from_scratch(n_obs=100, batch_size=20)\n loaders_dict = dict()\n loaders_dict['train'] = train_loader\n loaders_dict['valid'] = valid_loader\n loaders_dict['test'] = test_loader\n\n #\n # Train & Test models\n #\n \"\"\"\n n, p = train_loader.dataset.x.shape\n models = get_model(dim_input=p, dim_hidden=10, dim_output=1)\n loss_fn = F.mse_loss\n\n # --train\n models = train(models=models, lr=1e-3, loss_fn=loss_fn, train_loader=train_loader, epochs=100)\n\n # --test\n y, y_hat, loss = test(models, loss_fn, test_loader)\n print(\"loss:\", loss)\n\n del models\n\n #\n # Plot Result\n #\n plt.plot(y, 'o-', c=\"blue\")\n plt.plot(y_hat, 'o-', c=\"red\")\n plt.title(\"without ignite\")\n plt.grid()\n plt.show()\n\n plt.plot(y, y_hat, 'o', c=\"blue\")\n plt.title(\"without ignite\")\n plt.grid()\n plt.show()\n \"\"\"\n\n #\n # Train by Ignite\n #\n n, p = train_loader.dataset.x.shape\n model = get_model(dim_input=p, dim_hidden=10, dim_output=1)\n loss_fn = F.mse_loss\n trainer, model = run(loaders_dict, model=model, loss_fn=loss_fn, epochs=100)\n\n #\n # Test\n #\n loss_fn = F.mse_loss\n y, y_hat, loss = test(model, loss_fn, test_loader)\n print(loss)\n\n #\n # Plot Result\n #\n plt.plot(y, 'o-', c=\"blue\")\n plt.plot(y_hat, 'o-', c=\"red\")\n plt.title(\"with ignite\")\n plt.grid()\n plt.show()\n\n plt.plot(y, y_hat, 'o', c=\"blue\")\n plt.title(\"with ignite\")\n plt.grid()\n plt.show()\n\n\n","sub_path":"main/engine_example.py","file_name":"engine_example.py","file_ext":"py","file_size_in_byte":9057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"160732244","text":"# ----------------------------------------------------------------------------\n# Copyright 2016 Nervana Systems Inc.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ----------------------------------------------------------------------------\n\nfrom ngraph.frontends.tensorflow.tf_importer.ops_base import OpsBase\nfrom ngraph.frontends.tensorflow.tf_importer.utils import to_int, shape_to_axes\nimport ngraph as ng\nimport numpy as np\n\n\nclass OpsGradient(OpsBase):\n \"\"\"\n Mix-in class for gradient related ops\n \"\"\"\n\n def ReluGrad(self, tf_node, inputs):\n \"\"\"\n Computes ReluGrad backprops.\n Reference: https://goo.gl/l07FXx\n\n Arguments:\n tf_node: NodeDef object, the tensorflow node to convert.\n inputs: List of ngraph Ops as inputs to this node.\n\n Returns:\n A ngraph Op corresponding to the tensorflow node.\n\n Inputs to tf_node:\n gradients, features\n \"\"\"\n # get inputs\n gradients, features = inputs\n\n # gradient of relu op\n relu_grad = ng.greater(features, 0.)\n relu_grad = ng.cast_axes(relu_grad, gradients.axes)\n\n return gradients * relu_grad\n\n def ApplyGradientDescent(self, tf_node, inputs):\n \"\"\"\n Apply gradient descent\n CPU reference: https://goo.gl/oMq2HA\n GPU reference: https://goo.gl/US3t0r\n\n Arguments:\n tf_node: NodeDef object, the tensorflow node to convert.\n inputs: List of ngraph Ops as inputs to this node.\n\n Returns:\n A ngraph Op corresponding to the tensorflow node.\n\n Inputs to tf_node:\n value, learning rate, gradient\n \"\"\"\n var, lr, grad = inputs\n return ng.assign(var, var - lr * grad)\n\n def BroadcastGradientArgs(self, tf_node, inputs):\n \"\"\"\n Given shapes of two tensors, computes the reduction indices for the\n gradient computation\n Reference:\n - BCastGradArgsOp https://goo.gl/5vx4QN\n - BCast::BCast https://goo.gl/gzOiA2\n TODO: Untested in real models, dangerous. Currently, our implementation\n only imports forward graph from tensorflow and does the gradient\n computation in ngraph.\n\n Arguments:\n tf_node: NodeDef object, the tensorflow node to convert.\n inputs: List of ngraph Ops as inputs to this node.\n\n Returns:\n A ngraph Op corresponding to the tensorflow node.\n\n Inputs to tf_node:\n sx, sy\n \"\"\"\n # get inputs\n sx, sy = list(to_int(inputs[0].const)), list(to_int(inputs[1].const))\n\n # fast path for common case of identical shapes for sx and sy\n if np.array_equal(sx, sy):\n return None, None\n\n # reverse the shape of x and y for convenience.\n x = list(reversed(sx))\n y = list(reversed(sy))\n\n # 1-extend and align x and y so that they are the same size\n if len(x) > len(y):\n y += [1] * (len(x) - len(y))\n else:\n x += [1] * (len(y) - len(x))\n\n # going through each dimension starting from the inner-most\n # dimension, compares dimension of x and y. They are compatible if\n # they are equal or either is 1\n grad_x_reduce_idx_ = []\n grad_y_reduce_idx_ = []\n n = len(x)\n for i in range(n):\n if x[i] == y[i]:\n continue\n elif x[i] == 1:\n grad_x_reduce_idx_.append(n - 1 - i)\n elif y[i] == 1:\n grad_y_reduce_idx_.append(n - 1 - i)\n else:\n raise ValueError(\"Shape %s and %s not numpy-compatible\" %\n (sx, sy))\n\n # reverse all vectors since x and y were reversed at very beginning\n grad_x_reduce_idx_ = list(reversed(grad_x_reduce_idx_))\n grad_y_reduce_idx_ = list(reversed(grad_y_reduce_idx_))\n\n # make ng constant array\n if grad_x_reduce_idx_:\n x_array = np.array(grad_x_reduce_idx_)\n ng_x_array = ng.constant(\n x_array, shape_to_axes(x_array.shape)).named(tf_node.name)\n else:\n ng_x_array = None\n\n if grad_y_reduce_idx_:\n y_array = np.array(grad_y_reduce_idx_)\n ng_y_array = ng.constant(\n y_array, axes=shape_to_axes(y_array.shape)).named(tf_node.name)\n else:\n ng_y_array = None\n\n return ng_x_array, ng_y_array\n","sub_path":"ngraph/frontends/tensorflow/tf_importer/ops_gradient.py","file_name":"ops_gradient.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274422831","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n url(r'^home/$', views.home, name='home'),\n url(r'^sacm/$', views.sacm, name='sacm'),\n url(r'^self-help/$', views.self_help, name='self-help'),\n url(r'^smart-egg/$', views.smart_egg, name='smart-egg'),\n \n url(r'^projects/$', views.projects, name='projects'),\n \n #Custom directives\n url(r'^percent/$', views.percent, name='percent'),\n\n]","sub_path":"portfolio/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612376253","text":"#!/usr/bin/env python3\n\nimport scrapy\n\n\nclass FindUtilities(scrapy.Spider):\n name = \"findUtilitiesScraper\"\n open('./resultFiles/AllEWGUtilities.txt', \"w\").close()\n\n def start_requests(self):\n with open(\"./resultFiles/EWGStates.txt\") as f:\n urls = f.read().splitlines()\n\n for url in urls:\n print(url)\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n try:\n info = response.xpath(\"//table/tbody/tr/td/a[contains(@href,'system')]/@href\").getall()\n\n with open('./resultFiles/AllEWGUtilities.txt', 'a') as f:\n for item in info:\n f.write('https://www.ewg.org/tapwater/{}\\n'.format(item))\n except Exception as e:\n print(e)\n","sub_path":"webscraper/findUtilitiesScraper.py","file_name":"findUtilitiesScraper.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29694228","text":"\"\"\"RouteProgrammerPaintTools URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom paintApp import views\n\nurlpatterns = [\n path('paintApp/', include('paintApp.urls')),\n path('admin/', admin.site.urls),\n # ex: /polls/\n path('', views.index, name='index'),\n # ex: /polls/5/\n path('/', views.detail, name='detail'),\n # ex: /polls/5/results/\n path('/results/', views.results, name='results'),\n # ex: /polls/5/vote/\n path('/vote/', views.vote, name='vote'),\n # ex: /opt/?route=''&pickup=''&delivery=''&vehicle=''/\n path('opt/', views.opt, name='opt')\n\n # path('opt////', views.opt, name='opt')\n\n]\n","sub_path":"RouteProgrammerPaintTools/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333924496","text":"#%% (1) 대소비교\r\n#두 정수 입력받기\r\nnum1Msg = \"첫번째 정수 : \"\r\nnum2Msg = \"두번째 정수 : \"\r\nnum1 = int(input(num1Msg))\r\nnum2 = int(input(num2Msg))\r\n\r\nresult = \"큰 값 :\"+str(num1) if num1 > num2 else \"두 수가 같습니다.\" if num1==num2 else num2\r\nprint(result)\r\n\r\n#%% (2) 퀴즈게임\r\n#Q. 다음 중 프로그래밍 언어가 아닌 것은?\r\n#1. JAVA\r\n#2. 파이썬\r\n#3. C언어\r\n#4. 망둥어\r\n\r\nuserAnswer = \"\"\r\nanswer = 3\r\nanswerMsg = \"정답 번호를 입력해주세요 : \"\r\nresult = \"\"\r\n \r\nprint(\"*\"*10+\"퀴즈게임\"+\"*\"*10)\r\nprint(\"Q. 다음 중 강사님의 이름은?\")\r\nprint(\"1. 강동원\\n2. 원빈\\n3. 한동석\\n4. 임꺽정\\n\")\r\nprint(\"*\"*30)\r\n \r\nuserAnswer = int(input(answerMsg))\r\nresult = \"정답!!\" if userAnswer == answer else \"정답 범위를 벗어났습니다.\" if userAnswer >4 or userAnswer < 1 else \"틀렸습니다.\"\r\nprint(result)\r\n\r\n#%% (3) 혈액형별 성격\r\nqMsg = (\"당신의 혈액형은?\\n\"\r\n +\"1. A형\\n2. B형\\n3. O형\\n4. AB형\\n\"\r\n )\r\nanswer_a = \"세심하고 거짓말을 잘 못한다.\"\r\nanswer_b = \"거침없고 추진력이 좋다.\"\r\nanswer_o = \"사교성이 좋고 폭발한다.\"\r\nanswer_ab = \"이상하다.\"\r\nerrMsg = \"잘못 입력하셨습니다.\"\r\nchoice = int(input(qMsg))\r\n\r\nprint((answer_a if choice == 1 else\r\n answer_b if choice == 2 else\r\n answer_o if choice == 3 else\r\n answer_ab if choice == 4 else errMsg))\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Python/day05/numPlay.py","file_name":"numPlay.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"71153573","text":"import matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\nimport pandas as pd \nimport matplotlib.animation as animation\nfrom scipy import stats\nimport matplotlib.cm as cm\n\nnp.random.seed(12345)\n\ndf = pd.DataFrame([np.random.normal(32000,200000,3650), \n np.random.normal(43000,100000,3650), \n np.random.normal(43500,140000,3650), \n np.random.normal(48000,70000,3650)], \n index=[1992,1993,1994,1995])\n\n#print(df.shape) # return (4, 3650), 4 rows and 3650 colums\n #shape[0 , 1]\n\nyear_avg = df.mean(axis = 1) \nyear_std = df.std(axis = 1)\nyerr = year_std / np.sqrt(df.shape[1]) * stats.t.ppf(1-0.05/2, df.shape[1]-1) # yerr is error bar\n# standard error = sd/n^(1/2), stats.t.ppf(2-tail and 95% confidence ,degree of freedom = sample size -1 ) -- return 1.96, just like look from the T-table\n# yerr = standard error * t-vlaue\nplt.figure()\nbars = plt.bar(range(df.shape[0]), year_avg, yerr = yerr, color = 'grey')\nthreshold = 37000\nplt.axhline(y = threshold, color = 'yellow', alpha = 1) # plot a h-line\n\n#cm1 = mcol.LinearSegmentedColormap.from_list(\"MyCmapName\",[\"b\", \"white\", \"purple\"]) # define your own colourmap, need to import import matplotlib.colors as mcol\ncmap = cm.ScalarMappable(cmap= \"bwr\") # set up a colourmap that we will use it as a reference to fill out bar\n # a list of builtin Colormap reference: https://matplotlib.org/gallery/color/colormap_reference.html\ncmap.set_array( [] ) # set_array for mappable, otherwise it will return error. set_array() is a method, set_array([]) means set a empty array\n\n#########################################################\n# the concept of control the bar colour respond to the horizontal line #\n# since the colourbar is respond in number, so we have to convert every bar into a \n# coressponding number in order to represent the sensitivity of the colourbar which can result different colour \n\npercentages = [] # create a list for append in the loop\n\nfor bar in bars: # bars has 4 differnt vlaues\n height = bar.get_height() # get the height values\n percentage = (height-threshold)/height # substract the height from the horizontal line and convert it as a percentage\n percentages.append(percentage)\n\n#########################################################\n\nbars = plt.bar(range(df.shape[0]), year_avg, yerr = yerr, color = cmap.to_rgba(percentages))\n\nplt.colorbar(cmap, orientation='horizontal') # plot the colorbar by using plt.colorbar(colourmap)\nplt.xticks(range(df.shape[0]), df.index, alpha = 0.8)\n\nplt.show()\n","sub_path":"code with note.py","file_name":"code with note.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"326792830","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth import login, logout\nfrom django.urls import reverse_lazy\nfrom django.views import generic\n\n# this one is for using django built in form\n'''class signup(generic.CreateView):\n form_class = UserCreationForm\n success_url = reverse_lazy('login')\n template_name = 'signup.html'''\n\ndef signup(request):\n if request.method=='POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect('profile:login')\n else:\n form = UserCreationForm()\n return render(request, 'profile/signup.html', {'form':form})\n\ndef login_view(request):\n if request.method=='POST':\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n #login\n user = form.get_user()\n login(request, user)\n if 'next'in request.POST:\n return redirect(request.POST.get('next'))\n else:\n return redirect('site:home')\n else:\n form = AuthenticationForm()\n return render(request, 'profile/login.html', {'form': form})\n\n\ndef logout_view(request):\n if request.method=='POST':\n logout(request)\n return redirect('site:home')\n","sub_path":"profile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"451725146","text":"class UserDto:\n \"\"\"\n Users as we want the client to see them.\n \"\"\"\n def __init__(self, user):\n \"\"\"\n Constructor that creates a dictionary from a user.\n\n :param user: User entity\n \"\"\"\n self.json = {\n 'id': user.id,\n 'name': user.name,\n 'email': user.email\n }\n","sub_path":"app/model/dto/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"357520575","text":"import os\nfrom jam import settings\n# Hack to force all storages into memory\nsettings.load(os.path.join(os.path.dirname(__file__), 'test.yml'))\n\nimport asyncio\nimport logging\nimport requests\nimport threading\nimport time\n\nfrom jam import NamespaceManager\nfrom jam import server\nfrom jam.backends import EphemeralBackend\nimport jam\n\n\nclass ServerThread(threading.Thread):\n def __init__(self):\n super().__init__()\n self.loop = asyncio.new_event_loop()\n\n def run(self):\n logger = logging.getLogger(jam.__name__)\n logger.setLevel(logging.ERROR)\n logging.getLogger('tornado.access').setLevel(logging.FATAL)\n asyncio.set_event_loop(self.loop)\n server.main()\n\n def stop(self):\n self.loop.call_soon_threadsafe(lambda: self.loop.stop())\n self.join()\n self.loop.close()\n\n\ndef before_all(context):\n logger = logging.getLogger(requests.__name__)\n logger.setLevel(logging.ERROR)\n context.base_url = 'http://localhost:{}'.format(settings.PORT)\n context.server_thread = ServerThread()\n context.server_thread.start()\n for _ in range(5):\n try:\n requests.get(context.base_url)\n break\n except requests.exceptions.ConnectionError:\n time.sleep(5)\n else:\n raise Exception('Unable to connect to testing server at {}'.format(context.base_url))\n\n\ndef after_all(context):\n context.server_thread.stop()\n\n\ndef before_scenario(context, senario):\n context.resources = {\n 'namespace': {},\n 'collection': {},\n 'document': {},\n }\n context.ignored_auth = []\n for v in EphemeralBackend._cls_cache.values():\n v.clear()\n context.manager = NamespaceManager()\n\n\ndef after_scenario(context, scenario):\n if hasattr(context, 'time'):\n context.time.stop()\n","sub_path":"features/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"639220737","text":"from glob import glob\nimport random\n\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\n\nimport tensorflow as tf\nfrom keras.layers import (\n Input,\n Activation,\n Dropout,\n Flatten,\n Dense,\n Reshape,\n Conv2D)\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.layers.pooling import MaxPool2D, AveragePooling2D\nimport os\nfrom tqdm import tqdm\nimport pickle\nfrom keras.utils import plot_model\nfrom utils import preprocess1\nfrom utils import preprocess3\nimport matplotlib.pyplot as plt\nimport random\nimport pandas as pd\nimport seaborn as sns\nrandom.seed(11)\n\n\ndef evaluate(y_true, y_pred, name):\n labels = sorted(list(set(y_true)))\n cmx_data = confusion_matrix(y_true, y_pred, labels=labels)\n\n df_cmx = pd.DataFrame(cmx_data, index=labels, columns=labels)\n\n plt.figure(figsize=(10, 7))\n sns.heatmap(df_cmx, annot=True)\n plt.savefig(name)\n # plt.show()\n\n\nclass strategyAE(object):\n def __init__(self, config):\n self.config = config\n\n def init_data(self):\n file_names = glob(self.config.LOG_PATH)\n X_train = []\n Y_train_1 = []\n Y_train_2 = []\n Y_train_3 = []\n Y_train_4 = []\n Y_train_5 = []\n random.seed(0)\n self.count_all = {}\n self.all_sample = {}\n self.all_calm = {}\n self.all_liar = {}\n self.all_repel = {}\n self.all_follow = {}\n random.shuffle(file_names)\n file_names = file_names[:1000]\n for name in tqdm(file_names):\n pre1 = preprocess1.preprocess1()\n pre1.update(name)\n if pre1.is_finish:\n for key, value in pre1.count_content.items():\n if key in self.count_all:\n self.count_all[key] += value\n else:\n self.count_all[key] = value\n for key, value in pre1.count_sample.items():\n if key in self.all_sample:\n self.all_sample[key] += value\n else:\n self.all_sample[key] = value\n for key, value in pre1.count_calm.items():\n if key in self.all_calm:\n self.all_calm[key] += value\n else:\n self.all_calm[key] = value\n for key, value in pre1.count_liar.items():\n if key in self.all_liar:\n self.all_liar[key] += value\n else:\n self.all_liar[key] = value\n for key, value in pre1.count_repel.items():\n if key in self.all_repel:\n self.all_repel[key] += value\n else:\n self.all_repel[key] = value\n for key, value in pre1.count_follow.items():\n if key in self.all_follow:\n self.all_follow[key] += value\n else:\n self.all_follow[key] = value\n X_train.append(pre1.f_map)\n Y_train_1.append(pre1.y_map1)\n Y_train_2.append(pre1.y_map2)\n Y_train_3.append(pre1.y_map3)\n Y_train_4.append(pre1.y_map4)\n Y_train_5.append(pre1.y_map5)\n print(self.count_all)\n print(self.all_sample)\n print(self.all_calm)\n print(self.all_liar)\n print(self.all_repel)\n print(self.all_follow)\n\n self.X_train, self.X_test = X_train[:int(len(\n X_train)*self.config.TRAIN_PAR_TEST)], X_train[int(len(X_train)*self.config.TRAIN_PAR_TEST) + 1:]\n self.Y_train_1, self.Y_test_1 = Y_train_1[:int(len(\n Y_train_1)*self.config.TRAIN_PAR_TEST)], Y_train_1[int(len(Y_train_1)*self.config.TRAIN_PAR_TEST) + 1:]\n self.Y_train_2, self.Y_test_2 = Y_train_2[:int(len(\n Y_train_2)*self.config.TRAIN_PAR_TEST)], Y_train_2[int(len(Y_train_2)*self.config.TRAIN_PAR_TEST) + 1:]\n self.Y_train_3, self.Y_test_3 = Y_train_3[:int(len(\n Y_train_3)*self.config.TRAIN_PAR_TEST)], Y_train_3[int(len(Y_train_3)*self.config.TRAIN_PAR_TEST) + 1:]\n self.Y_train_4, self.Y_test_4 = Y_train_4[:int(len(\n Y_train_4)*self.config.TRAIN_PAR_TEST)], Y_train_4[int(len(Y_train_4)*self.config.TRAIN_PAR_TEST) + 1:]\n self.Y_train_5, self.Y_test_5 = Y_train_5[:int(len(\n Y_train_5)*self.config.TRAIN_PAR_TEST)], Y_train_5[int(len(Y_train_5)*self.config.TRAIN_PAR_TEST) + 1:]\n\n self.X_test, self.X_valid = self.X_test[:int(len(\n self.X_test)*self.config.TEST_PAR_VALID)], self.X_test[int(len(self.X_test)*self.config.TEST_PAR_VALID) + 1:]\n\n self.Y_test_1, self.Y_valid_1 = self.Y_test_1[:int(len(\n self.Y_test_1)*self.config.TEST_PAR_VALID)], self.Y_test_1[int(len(self.Y_test_1)*self.config.TEST_PAR_VALID) + 1:]\n self.Y_test_2, self.Y_valid_2 = self.Y_test_2[:int(len(\n self.Y_test_2)*self.config.TEST_PAR_VALID)], self.Y_test_2[int(len(self.Y_test_2)*self.config.TEST_PAR_VALID) + 1:]\n self.Y_test_3, self.Y_valid_3 = self.Y_test_3[:int(len(\n self.Y_test_3)*self.config.TEST_PAR_VALID)], self.Y_test_3[int(len(self.Y_test_3)*self.config.TEST_PAR_VALID) + 1:]\n self.Y_test_4, self.Y_valid_4 = self.Y_test_4[:int(len(\n self.Y_test_4)*self.config.TEST_PAR_VALID)], self.Y_test_4[int(len(self.Y_test_4)*self.config.TEST_PAR_VALID) + 1:]\n self.Y_test_5, self.Y_valid_5 = self.Y_test_5[:int(len(\n self.Y_test_5)*self.config.TEST_PAR_VALID)], self.Y_test_5[int(len(self.Y_test_5)*self.config.TEST_PAR_VALID) + 1:]\n\n self.X_train = np.array(self.X_train)\n self.X_test = np.array(self.X_test)\n self.X_valid = np.array(self.X_valid)\n self.Y_train_1 = np.array(self.Y_train_1)\n self.Y_train_2 = np.array(self.Y_train_2)\n self.Y_train_3 = np.array(self.Y_train_3)\n self.Y_train_4 = np.array(self.Y_train_4)\n self.Y_train_5 = np.array(self.Y_train_5)\n self.Y_test_1 = np.array(self.Y_test_1)\n self.Y_test_2 = np.array(self.Y_test_2)\n self.Y_test_3 = np.array(self.Y_test_3)\n self.Y_test_4 = np.array(self.Y_test_4)\n self.Y_test_5 = np.array(self.Y_test_5)\n self.Y_valid_1 = np.array(self.Y_valid_1)\n self.Y_valid_2 = np.array(self.Y_valid_2)\n self.Y_valid_3 = np.array(self.Y_valid_3)\n self.Y_valid_4 = np.array(self.Y_valid_4)\n self.Y_valid_5 = np.array(self.Y_valid_5)\n\n os.makedirs(self.config.OUTPUT_PATH+\"/data\", exist_ok=True)\n pickle.dump(self.X_train, open(self.config.OUTPUT_PATH +\n \"/data/X_train.pkl\", mode=\"wb\"))\n pickle.dump(self.X_test, open(self.config.OUTPUT_PATH +\n \"/data/X_test.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_train_1, open(self.config.OUTPUT_PATH +\n \"/data/Y_train_1.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_test_1, open(self.config.OUTPUT_PATH +\n \"/data/Y_test_1.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_train_2, open(self.config.OUTPUT_PATH +\n \"/data/Y_train_2.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_test_2, open(self.config.OUTPUT_PATH +\n \"/data/Y_test_2.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_train_3, open(self.config.OUTPUT_PATH +\n \"/data/Y_train_3.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_test_3, open(self.config.OUTPUT_PATH +\n \"/data/Y_test_3.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_train_4, open(self.config.OUTPUT_PATH +\n \"/data/Y_train_4.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_test_4, open(self.config.OUTPUT_PATH +\n \"/data/Y_test_4.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_train_5, open(self.config.OUTPUT_PATH +\n \"/data/Y_train_5.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_test_5, open(self.config.OUTPUT_PATH +\n \"/data/Y_test_5.pkl\", mode=\"wb\"))\n\n pickle.dump(self.X_valid, open(self.config.OUTPUT_PATH +\n \"/data/X_valid.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_valid_1, open(self.config.OUTPUT_PATH +\n \"/data/Y_valid_1.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_valid_2, open(self.config.OUTPUT_PATH +\n \"/data/Y_valid_2.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_valid_3, open(self.config.OUTPUT_PATH +\n \"/data/Y_valid_3.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_valid_4, open(self.config.OUTPUT_PATH +\n \"/data/Y_valid_4.pkl\", mode=\"wb\"))\n pickle.dump(self.Y_valid_5, open(self.config.OUTPUT_PATH +\n \"/data/Y_valid_5.pkl\", mode=\"wb\"))\n\n def build_network_dense(self):\n main_input = Input(shape=(len(self.X_train[1]),))\n x = Dense(200,\n activation=\"relu\")(main_input)\n x = Dense(100, input_dim=200,\n activation=\"relu\")(x)\n x = Dense(50, input_dim=100,\n activation=\"relu\")(x)\n output_1 = Dense(5, activation=\"softmax\",\n input_dim=50, name=\"output_1\")(x)\n output_2 = Dense(5, activation=\"softmax\",\n input_dim=50, name=\"output_2\")(x)\n output_3 = Dense(5, activation=\"softmax\",\n input_dim=50, name=\"output_3\")(x)\n output_4 = Dense(5, activation=\"softmax\",\n input_dim=50, name=\"output_4\")(x)\n output_5 = Dense(5, activation=\"softmax\",\n input_dim=50, name=\"output_5\")(x)\n model = Model(input=main_input, output=[\n output_1, output_2, output_3, output_4, output_5])\n return model\n\n def train(self):\n\n self.init_data()\n print(\"finish init_data\")\n self.X_train = np.array(self.X_train)\n self.X_test = np.array(self.X_test)\n self.X_train_ = []\n for self.X_t in self.X_train:\n X_tra = self.X_t.reshape(\n 1, self.X_t.shape[0]*self.X_t.shape[1]*self.X_t.shape[2]).astype(\"float32\")[0]\n self.X_train_.append(X_tra)\n self.X_train_ = np.array(self.X_train_)\n self.X_test_ = []\n for self.X_t in self.X_test:\n X_tra = self.X_t.reshape(\n 1, self.X_t.shape[0]*self.X_t.shape[1]*self.X_t.shape[2]).astype(\"float32\")[0]\n self.X_test_.append(X_tra)\n self.X_valid = np.array(self.X_valid)\n self.X_valid_ = []\n for self.X_t in self.X_valid:\n X_vali = self.X_t.reshape(\n 1, self.X_t.shape[0]*self.X_t.shape[1]*self.X_t.shape[2]).astype(\"float32\")[0]\n self.X_valid_.append(X_vali)\n\n self.X_test_ = np.array(self.X_test_)\n self.X_train = np.array(self.X_train_)\n self.X_test = np.array(self.X_test_)\n self.X_valid = np.array(self.X_valid_)\n self.network_ae = self.build_network_ae()\n\n self.network = self.build_network_dense()\n self.network.summary()\n opt = Adam(lr=self.config.LEARNING_RATE)\n self.network.compile(loss={\n \"output_1\": \"categorical_crossentropy\",\n \"output_2\": \"categorical_crossentropy\",\n \"output_3\": \"categorical_crossentropy\",\n \"output_4\": \"categorical_crossentropy\",\n \"output_5\": \"categorical_crossentropy\"\n },\n optimizer=opt,\n metrics=[\"accuracy\"]\n )\n self.train_iterations_ae()\n self.train_iterations()\n\n def train_iterations(self):\n print(\"start fit\")\n #kmeans_model = KMeans(n_clusters=5,random_state=10)\n\n history = self.network.fit(\n self.X_train,\n {\n \"output_1\": self.Y_train_1,\n \"output_2\": self.Y_train_2,\n \"output_3\": self.Y_train_3,\n \"output_4\": self.Y_train_4,\n \"output_5\": self.Y_train_5\n },\n batch_size=self.config.BATCH_SIZE,\n epochs=self.config.EPOCH,\n validation_data=(\n self.X_valid, [self.Y_valid_1, self.Y_valid_2,\n self.Y_valid_3, self.Y_valid_4, self.Y_valid_5]\n ))\n\n self.network.save_weights(self.config.OUTPUT_PATH + \"/param.h5\")\n\n self.y_pred_1, self.y_pred_2, self.y_pred_3, self.y_pred_4, self.y_pred_5 = self.network.predict(\n self.X_test, batch_size=len(self.X_test))\n\n self.y_pred_1, self.y_pred_2, self.y_pred_3, self.y_pred_4, self.y_pred_5 = np.argmax(self.y_pred_1, axis=1), np.argmax(\n self.y_pred_2, axis=1), np.argmax(self.y_pred_3, axis=1), np.argmax(self.y_pred_4, axis=1), np.argmax(self.y_pred_5, axis=1)\n self.Y_test_1, self.Y_test_2, self.Y_test_3, self.Y_test_4, self.Y_test_5 = np.argmax(\n self.Y_test_1, axis=1), np.argmax(self.Y_test_2, axis=1), np.argmax(self.Y_test_3, axis=1), np.argmax(self.Y_test_4, axis=1), np.argmax(self.Y_test_5, axis=1)\n df_history = pd.DataFrame(history.history)\n df_history.plot()\n df_history.to_csv(self.config.OUTPUT_PATH + \"/loss.png\")\n evaluate(self.Y_test_1, self.y_pred_1,\n self.config.OUTPUT_PATH + \"/test1.png\")\n evaluate(self.Y_test_2, self.y_pred_2,\n self.config.OUTPUT_PATH + \"/test2.png\")\n evaluate(self.Y_test_3, self.y_pred_3,\n self.config.OUTPUT_PATH + \"/test3.png\")\n evaluate(self.Y_test_4, self.y_pred_4,\n self.config.OUTPUT_PATH + \"/test4.png\")\n evaluate(self.Y_test_5, self.y_pred_5,\n self.config.OUTPUT_PATH + \"/test5.png\")\n pickle.dump(history, open(self.config.OUTPUT_PATH +\n \"/history_\" + self.config.NETWORK + \".pkl\", mode=\"wb\"))\n","sub_path":"wolf-strategy/train/AutoEncoder.py","file_name":"AutoEncoder.py","file_ext":"py","file_size_in_byte":14382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"96790081","text":"from slack import WebClient\nfrom flask import Blueprint, request as req, current_app as app\nimport slackUtils as utils\nimport json\nfrom datetime import datetime\nimport requests as r\n\nresponse_url = \"\"\n\nslackApi = Blueprint(\"slackApi\", __name__)\n\n@slackApi.route(\"/input\", methods=[\"POST\"])\ndef response():\n\tpayload = json.loads(req.form.get(\"payload\", \"\"))\n\tif payload.get(\"type\", \"\") == \"view_submission\":\n\t\tview_id = payload[\"view\"][\"id\"]\n\t\tvalues = payload[\"view\"][\"state\"][\"values\"]\n\t\tjoin_url = values[\"join_url\"][\"join_url\"][\"value\"]\n\t\tstart_date = values[\"start_date\"][\"start_date\"][\"selected_date\"]\n\t\tstart_time = values[\"start_time\"][\"start_time\"][\"selected_time\"]\n\t\tend_date = values[\"end_date\"][\"end_date\"][\"selected_date\"]\n\t\tend_time = values[\"end_time\"][\"end_time\"][\"selected_time\"]\n\n\t\tstart_date = datetime.fromisoformat(f\"{start_date}T{start_time}\")\n\t\tend_date = datetime.fromisoformat(f\"{end_date}T{end_time}\")\n\n\t\tif(end_date <= start_date):\n\t\t\tview = utils.views.getHomeViewError(\"Error: *END TIME IS INVALID*\")\n\t\t\treturn {\n\t\t\t\t\"response_action\": \"update\",\n\t\t\t\t\"view\": view\n\t\t\t}\n\t\telse:\n\t\t\td = r.post(response_url, json={\"text\": \"We will inform you when starting recording\"})\n\t\t\tapp.config['links'].append((join_url, start_date.timestamp(), end_date.timestamp()))\n\t\t\tprint(response_url, d.text)\n\n\treturn \"\"\n\n@slackApi.route(\"/record\", methods=[\"POST\"])\ndef shortcut():\n\ttrigger_id = req.form.get(\"trigger_id\")\n\tglobal response_url\n\tresponse_url = req.form.get(\"response_url\")\n\t# print(response_url)\n\tview = utils.views.getHomeView(\"modal\")\n\td = utils.client.views_open(token=utils.TOKEN, view=view, trigger_id=trigger_id)\n\treturn \"\"","sub_path":"zoom/slackApi.py","file_name":"slackApi.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"204168906","text":"\"\"\"\nCopyright 2018 PeopleDoc\nWritten by Yann Lachiver\n Joachim Jablon\n Jacques Rott\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport requests\nimport urllib3\n\ntry:\n from urllib.parse import urljoin\nexcept ImportError:\n # Python 2\n from urlparse import urljoin\n\nfrom vault_cli.client import VaultAPIException\nfrom vault_cli.client import VaultClientBase\n\n\nclass Session(requests.Session):\n \"\"\"A wrapper for requests.Session to override 'verify' property, ignoring\n REQUESTS_CA_BUNDLE environment variable.\n\n This is a workaround for\n https://github.com/requests/requests/issues/3829\n \"\"\"\n def merge_environment_settings(self, url, proxies, stream, verify,\n *args, **kwargs):\n if self.verify is False:\n verify = False\n urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n return super(Session, self).merge_environment_settings(\n url, proxies, stream, verify, *args, **kwargs)\n\n\nclass RequestsVaultClient(VaultClientBase):\n\n def _init_session(self, url, verify):\n self.session = self.create_session(verify)\n\n self.url = urljoin(url, \"v1/\")\n\n def _full_url(self, path):\n url = urljoin(self.url, self.base_path)\n return urljoin(url, path)\n\n @staticmethod\n def handle_error(response, expected_code=requests.codes.ok):\n if response.status_code == expected_code:\n return\n raise VaultAPIException(response.status_code, response.text)\n\n @staticmethod\n def create_session(verify):\n session = Session()\n session.verify = verify\n return session\n\n def _authenticate_token(self, token):\n self.session.headers.update({'X-Vault-Token': token})\n\n def _authenticate_userpass(self, username, password):\n data = {\"password\": password}\n response = self.session.post(self.url + 'auth/userpass/login/' + username,\n json=data, headers={})\n self.handle_error(response)\n\n json_response = response.json()\n self.session.headers.update(\n {'X-Vault-Token': json_response.get('auth').get('client_token')})\n\n def get_secrets(self, path):\n url = self._full_url(path)\n response = self.session.get(url)\n self.handle_error(response)\n json_response = response.json()\n return json_response['data']\n\n def get_secret(self, path):\n data = self.get_secrets(path)\n return data['value']\n\n def list_secrets(self, path):\n url = self._full_url(path).rstrip('/')\n response = self.session.get(url, params={'list': 'true'})\n try:\n self.handle_error(response)\n except VaultAPIException as exc:\n if exc.status_code == 404:\n return []\n raise\n json_response = response.json()\n return json_response['data']['keys']\n\n def set_secret(self, path, value):\n url = self._full_url(path)\n response = self.session.put(url, json={'value': value})\n self.handle_error(response, requests.codes.no_content)\n\n def delete_secret(self, path):\n url = self._full_url(path)\n response = self.session.delete(url)\n self.handle_error(response, requests.codes.no_content)\n","sub_path":"vault_cli/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125271386","text":"import xlrd\n\n#导入作者名存在author集合里\nfile = xlrd.open_workbook('./source_file.xlsx')\nauthors = set() #作者名无重复\nwriters = [] #作者名和文章一一对应\narticles = [] #文章名\ntables = file.sheets()\ntable = file.sheets()[0]\nfor i in range(table.nrows-2):\n authors.add(table.row_values(i+2)[0])\n writers.append(table.row_values(i+2)[0])\n#print(authors)\n\n#文章放在article里\nfor i in range(table.nrows-2):\n articles.append(table.row_values(i+2)[1])\n\n# for i in range(len(writers)):\n# print(writers[i], articles[i])\n","sub_path":"douban_book/Input.py","file_name":"Input.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"251901038","text":"# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, 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 io\nimport logging\nimport os\nimport random\nimport string\nimport yaml\n\nfrom libcloud.compute.providers import get_driver as get_compute_driver\nfrom libcloud.compute.types import Provider as ComputeProvider\nfrom libcloud.loadbalancer.providers import get_driver as get_balancer_driver\nfrom libcloud.loadbalancer.types import Provider as BalancerProvider\n\nfrom exception import PlumberyException\nfrom facility import PlumberyFacility\nfrom facility import PlumberyFittings\nfrom polisher import PlumberyPolisher\nfrom plumbery import __version__\n\n__all__ = ['PlumberyEngine']\n\n\nclass PlumberyEngine:\n \"\"\"\n Infrastructure as code at Dimension Data with Apache Libcloud\n\n :param fileName: the location of the plan for the fittings\n :type fileName: ``str``\n\n Plumbery is a convenient tool for infrastructure managers at cloud times.\n It allows for easy and repeatable deployments of various\n fittings, including compute nodes and related storage. It allows also for\n quick dismandling of the fittings when required.\n The idea here is not to compete with respected solutions such as chef or\n puppet. At its name implies, plumbery is targeting pipes and fittings, the\n very basic utility stuff that sophisticated tools can leverage.\n\n Example::\n\n from plumbery.engine import PlumberyEngine\n engine = PlumberyEngine('fittings.yaml')\n engine.build_all_blueprints()\n\n In this example the overall plan, in textual format, is given to the engine\n in preparation of subsequent processing. The software is not trying to\n guess a name by default, so if you do not provide a name, no configuration\n file is loaded. You can load the plan at any stage, or restart the engine\n with an updated plan, by invoking the member function ``parse_layout()``\n\n Note:\n While plumbery is not making assumptions for your configuration files,\n if your infrastructure is simple enough to fit in one single file then\n you are highly encouraged to name it ``fittings.yaml``\n\n Beyond the plan for your fittings, plumbery is also requiring some specific\n credentials to connect to cloud providers. To preserve the confidentiality\n of such information, it is read from the environment, and not from any\n configuration file. Therefore the need for local setup before running\n plumbery. This is part of the installation process.\n\n Last but not least, plumbery sets the root password of any new server that\n it creates. For obvious security reasons this is not taken from the\n fittings plan but from the environment, or it can be set in code.\n\n Under Linux, you may want to edit ``~/.bash_profile`` like this::\n\n # credentials to access cloud resources from Dimension Data\n export MCP_USERNAME='foo.bar'\n export MCP_PASSWORD='WhatsUpDoc'\n\n # password to access nodes remotely\n export SHARED_SECRET='*you really want to put a tricky password here*'\n\n These simple precautions are aiming to protect your infrastructure as much\n as possible. The general goal is to minimize risks induced by exposure to\n your fittings plan. You may lead transformation towards so-called\n infrastructure as code, and for this you will add version control to your\n fittings plan. As a result, plans will be stored in git or equivalent, and\n shared across some people.\n\n Attributes:\n\n safeMode (boolean):\n If True, which is the default, then no actual change\n will be made against the infrastructure. This global attribute\n is coming from the fittings plan.\n\n \"\"\"\n\n safeMode = True\n\n def __init__(self, plan=None):\n \"\"\"\n Ignites the plumbing engine\n\n :param plan: the file that contains fittings plan\n :type plan: ``str`` or ``file``\n\n \"\"\"\n\n self.facilities = []\n\n self.polishers = []\n\n self._buildPolisher = None\n\n self._sharedSecret = None\n self._randomSecret = None\n\n self._userName = None\n\n self._userPassword = None\n\n if plan is not None:\n self.from_file(plan)\n\n def from_file(self, plan=None):\n \"\"\"\n Reads the fittings plan from a file\n\n :param plan: the file that contains fittings plan\n :type plan: ``str`` or ``file``\n\n The fittings plan is expected to follow YAML specifications, and it\n must have multiple documents in it. The first document provides\n general configuration parameters for the engine. Subsequent documents\n describe the various locations for the fittings.\n\n An example of a minimum fittings plan::\n\n ---\n safeMode: False\n ---\n # Frankfurt in Europe\n locationId: EU6\n regionId: dd-eu\n\n blueprints:\n\n - myBluePrint:\n domain:\n name: myDC\n ethernet:\n name: myVLAN\n subnet: 10.1.10.0\n nodes:\n - myServer\n\n In this example, the plan is to deploy a single node in the data centre\n at Frankfurt, in Europe. The node `myServer` will be placed in a\n network named `myVLAN`, and the network will be part of a network\n domain acting as a virtual data centre, `myDC`. The blueprint has a\n name, `myBluePrint`, so that it can be handled independently from\n other blueprints.\n\n \"\"\"\n\n if plan is None:\n plan = os.getenv('PLUMBERY')\n\n if isinstance(plan, str):\n plan = open(plan, 'r')\n\n documents = yaml.load_all(plan)\n\n # first document contains engine settings\n self.set(documents.next())\n\n # then one document per facility\n for document in documents:\n self.add_facility(document)\n\n if self.safeMode:\n logging.info(\n \"Running in safe mode\"\n \" - no actual change will be made to the fittings\")\n\n def from_text(self, plan):\n \"\"\"\n Reads the fittings plan\n\n :param plan: the fittings plan\n :type plan: ``str``\n\n The fittings plan is expected to follow YAML specifications, and it\n must have multiple documents in it. The first document provides\n general configuration parameters for the engine. Subsequent documents\n describe the various locations for the fittings.\n\n Example of use::\n\n myPlan = \\\"\\\"\\\"\n ---\n safeMode: True\n ---\n # Frankfurt in Europe\n locationId: EU6\n regionId: dd-eu\n\n blueprints:\n\n - myBlueprint:\n domain:\n name: myDC\n ethernet:\n name: myVLAN\n subnet: 10.1.10.0\n nodes:\n - myServer\n \\\"\\\"\\\"\n\n engine = PlumberyEngine()\n engine.from_text(myPlan)\n\n In this example, the plan is to deploy a single node in the data centre\n at Frankfurt, in Europe. The node `myServer` will be placed in a\n network named `myVLAN`, and the network will be part of a network\n domain acting as a virtual data centre, `myDC`. The blueprint has a\n name, `myBluePrint`, so that it can be handled independently from\n other blueprints.\n\n \"\"\"\n\n self.from_file(io.TextIOWrapper(io.BytesIO(plan)))\n\n def set(self, settings):\n \"\"\"\n Changes the settings of the engine\n\n :param settings: the new settings\n :type settings: ``dict``\n\n \"\"\"\n\n if not isinstance(settings, dict):\n raise TypeError('settings should be a dictionary')\n\n if 'safeMode' not in settings:\n raise LookupError('safeMode is not defined')\n\n self.safeMode = settings['safeMode']\n if self.safeMode not in [True, False]:\n raise ValueError('safeMode should be either True or False')\n\n if 'polishers' in settings:\n for item in settings['polishers']:\n key = item.keys()[0]\n value = item[key]\n self.polishers.append(\n PlumberyPolisher.from_shelf(key, value))\n\n if 'buildPolisher' in settings:\n self._buildPolisher = settings['buildPolisher']\n else:\n self._buildPolisher = 'spit'\n\n def set_shared_secret(self, secret):\n \"\"\"\n Changes the shared secret to be used with new nodes\n\n :param secret: the user name to be used with the driver\n :type secret: ``str``\n\n This function can be used to supplement the normal provision of\n the shared secret via the environment variable ``SHARED_SECRET``.\n\n \"\"\"\n\n self._sharedSecret = secret\n\n def get_shared_secret(self):\n \"\"\"\n Retrieves the secret that is communicated to new nodes during setup\n\n :return: the shared secret to be given to the driver\n :rtype: ``str``\n\n :raises: :class:`plumbery.PlumberyException`\n - if no shared secret can be found\n\n The shared secret is not put in the fittings plan, but is normally\n taken from the environment variable ``SHARED_SECRET``.\n\n Under Linux, you may want to edit ``~/.bash_profile`` like this::\n\n # password to access nodes remotely\n export SHARED_SECRET='*you really want to use a tricky password*'\n\n Alternatively, you can use the member function ``set_shared_secret()``\n to set this important attribute via code.\n\n \"\"\"\n\n if self._sharedSecret is None:\n self._sharedSecret = os.getenv('SHARED_SECRET')\n if self._sharedSecret is None or len(self._sharedSecret) < 3:\n raise PlumberyException(\n \"Error: missing node password \"\n \"in environment SHARED_SECRET\")\n\n return self._sharedSecret\n\n def get_random_secret(self):\n \"\"\"\n Retrieves a secret that is valid only during this session\n\n :return: a transient random secret\n :rtype: ``str``\n\n The random secret can be used in scripts and configuration files\n sent to nodes, for example to configure a database server.\n\n For this you would put ``{{ random.secret }}`` in your files and let\n plumbery provide a value for you.\n\n\n \"\"\"\n\n if self._randomSecret is None:\n\n self._randomSecret = ''.join(random.choice(\n string.ascii_letters+string.digits+'.-_:!=')\n for i in range(9))\n\n logging.debug(\"- using random secret '{}'\".format(\n self._randomSecret))\n\n return self._randomSecret\n\n def set_user_name(self, name):\n \"\"\"\n Changes the name used to authenticate to the API\n\n :param name: the user name to be used with the driver\n :type name: ``str``\n\n This function can be used to supplement the normal provision of\n a user name via the environment variable ``MCP_USERNAME``.\n\n \"\"\"\n\n self._userName = name\n\n def get_user_name(self):\n \"\"\"\n Retrieves user name to authenticate to the API\n\n :return: the user name to be used with the driver\n :rtype: ``str``\n\n :raises: :class:`plumbery.PlumberyException`\n - if no user name can be found\n\n The user name is not put in the fittings plan, but is normally taken\n from the environment variable ``MCP_USERNAME``.\n\n Under Linux, you may want to edit ``~/.bash_profile`` like this::\n\n # credentials to access cloud resources from Dimension Data\n export MCP_USERNAME='foo.bar'\n export MCP_PASSWORD='WhatsUpDoc'\n\n \"\"\"\n\n if self._userName is None:\n self._userName = os.getenv('MCP_USERNAME')\n if self._userName is None or len(self._userName) < 3:\n raise PlumberyException(\n \"Error: missing credentials in environment MCP_USERNAME\")\n\n return self._userName\n\n def set_user_password(self, password):\n \"\"\"\n Changes the password used to authenticate to the API\n\n :param password: the user password to be used with the driver\n :type password: ``str``\n\n This function can be used to supplement the normal provision of\n a user password via the environment variable ``MCP_PASSWORD``.\n\n \"\"\"\n\n self._userPassword = password\n\n def get_user_password(self):\n \"\"\"\n Retrieves user password to authenticate to the API\n\n :return: the user password to be used with the driver\n :rtype: ``str``\n\n :raises: :class:`plumbery.PlumberyException`\n - if no user password can be found\n\n The user password is not put in the fittings plan, but is normally\n taken from the environment variable ``MCP_PASSWORD``.\n\n Under Linux, you may want to edit ``~/.bash_profile`` like this::\n\n # credentials to access cloud resources from Dimension Data\n export MCP_USERNAME='foo.bar'\n export MCP_PASSWORD='WhatsUpDoc'\n\n \"\"\"\n\n if self._userPassword is None:\n self._userPassword = os.getenv('MCP_PASSWORD')\n if self._userPassword is None or len(self._userPassword) < 3:\n raise PlumberyException(\n \"Error: missing credentials in environment MCP_PASSWORD\")\n\n return self._userPassword\n\n def add_facility(self, facility):\n \"\"\"\n Extends the scope of this plumbing engine\n\n :param facility: description of an additional facility\n :type facility: ``dict`` or :class:`plumbery.PlumberyFacility`\n\n \"\"\"\n\n if isinstance(facility, dict):\n facility = PlumberyFacility(self, PlumberyFittings(**facility))\n\n logging.debug(\"Adding facility\")\n logging.debug(facility.fittings)\n\n self.facilities.append(facility)\n\n def list_facility(self, location):\n \"\"\"\n Retrieves facilities by their location\n\n :param location: the target location, e.g., 'EU6'\n :type location: ``str`` or ``list`` of ``str``\n\n :return: the list of matching facilities\n :rtype: ``list`` of :class:`plumbery.PlumberyFacility` or ``[]``\n\n Examples::\n\n >>>engine.list_facility(location='EU6')\n ...\n\n >>>engine.list_facility(location='EU6 NA9')\n ...\n\n >>>engine.list_facility(location=['EU6', 'NA9'])\n ...\n\n \"\"\"\n\n if isinstance(location, str):\n location = location.split(' ')\n\n matches = []\n\n for item in location:\n if isinstance(item, PlumberyFacility):\n matches.append(item)\n\n for facility in self.facilities:\n if facility.fittings.locationId in location:\n matches.append(facility)\n\n return matches\n\n def do(self, action, blueprints=None, facilities=None):\n\n if action == 'build':\n if blueprints is None:\n self.build_all_blueprints(facilities)\n else:\n self.build_blueprint(blueprints, facilities)\n\n elif action == 'start':\n if blueprints is None:\n self.start_all_blueprints(facilities)\n else:\n self.start_blueprint(blueprints, facilities)\n\n elif action == 'polish':\n if blueprints is None:\n self.polish_all_blueprints(filter=None,\n facilities=facilities)\n else:\n self.polish_blueprint(blueprints, facilities)\n\n elif action == 'stop':\n if blueprints is None:\n self.stop_all_blueprints(facilities)\n else:\n self.stop_blueprint(blueprints, facilities)\n\n elif action == 'wipe':\n if blueprints is None:\n self.wipe_all_blueprints(facilities)\n else:\n self.wipe_blueprint(blueprints, facilities)\n\n elif action == 'destroy':\n if blueprints is None:\n self.destroy_all_blueprints(facilities)\n else:\n self.destroy_blueprint(blueprints, facilities)\n\n else:\n if blueprints is None:\n self.polish_all_blueprints(filter=action,\n facilities=facilities)\n else:\n self.polish_blueprint(blueprints,\n filter=action,\n facilities=facilities)\n\n def build_all_blueprints(self, facilities=None):\n \"\"\"\n Builds all blueprints described in fittings plan\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to build all blueprints there.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n Examples::\n\n from plumbery.engine import PlumberyEngine\n PlumberyEngine('fittings.yaml').build_all_blueprints()\n\n from plumbery.engine import PlumberyEngine\n PlumberyEngine('fittings.yaml').build_all_blueprints('EU6 NA9')\n\n \"\"\"\n\n logging.info(\"Building all blueprints\")\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.build_all_blueprints()\n\n self.polish_all_blueprints(filter=self._buildPolisher,\n facilities=facilities)\n\n def build_blueprint(self, names, facilities=None):\n \"\"\"\n Builds named blueprint from fittings plan\n\n :param names: the name(s) of the blueprint(s) to deploy\n :type names: ``str`` or ``list`` of ``str``\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to build one single blueprint there.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n Example::\n\n from plumbery.engine import PlumberyEngine\n PlumberyEngine('fittings.yaml').build_blueprints('sql')\n\n \"\"\"\n\n if isinstance(names, list):\n label = ' '.join(names)\n else:\n label = names\n\n logging.info(\"Building blueprint '{}'\".format(label))\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.build_blueprint(names)\n\n self.polish_blueprint(names=names,\n filter=self._buildPolisher,\n facilities=facilities)\n\n def start_all_blueprints(self, facilities=None):\n \"\"\"\n Starts all nodes described in the fittings plan\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to start all nodes there.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n This function has no effect on nodes that are already up and running.\n\n \"\"\"\n\n logging.info(\"Starting nodes from all blueprints\")\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.start_all_blueprints()\n\n def start_blueprint(self, names, facilities=None):\n \"\"\"\n Starts nodes of one blueprint of the fittings plan\n\n :param names: the name(s) of the blueprint(s) to start\n :type names: ``str`` or ``list`` of ``str``\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to start nodes from some blueprint.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n This function has no effect on nodes that are already up and running.\n\n \"\"\"\n\n if isinstance(names, list):\n label = ' '.join(names)\n else:\n label = names\n\n logging.info(\"Starting nodes from blueprint '{}'\".format(label))\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.start_blueprint(names)\n\n def polish_all_blueprints(self, filter=None, facilities=None):\n \"\"\"\n Walks all resources and polishes them\n\n :param filter: the name of a single polisher to apply. If this\n parameter is missing, all polishers declared in the fittings plan\n will be applied\n :type filter: ``str``\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to apply polishers there.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n Example::\n\n from plumbery.engine import PlumberyEngine\n PlumberyEngine('fittings.yaml').polish_all_blueprints()\n\n \"\"\"\n\n polishers = PlumberyPolisher.filter(self.polishers, filter)\n\n if len(polishers) < 1:\n return False\n\n logging.info(\"Polishing all blueprints\")\n\n for polisher in polishers:\n polisher.go(self)\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n for polisher in polishers:\n polisher.move_to(facility)\n facility.polish_all_blueprints(polishers)\n\n for polisher in polishers:\n polisher.reap()\n\n def polish_blueprint(self, names, filter=None, facilities=None):\n \"\"\"\n Walks resources from the target blueprint and polishes them\n\n :param names: the name(s) of the blueprint(s) to polish\n :type names: ``str`` or ``list`` of ``str``\n\n :param filter: the name of a single polisher to apply. If this\n parameter is missing, all polishers declared in the fittings plan\n will be applied\n :type filter: ``str``\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to apply one polisher to one blueprint.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n Example::\n\n from plumbery.engine import PlumberyEngine\n PlumberyEngine('fittings.yaml').polish_blueprint('sql')\n\n \"\"\"\n\n polishers = PlumberyPolisher.filter(self.polishers, filter)\n\n if len(polishers) < 1:\n logging.debug('No polisher has been found')\n return\n\n if isinstance(names, list):\n label = ' '.join(names)\n else:\n label = names\n\n logging.info(\"Polishing blueprint '{}'\".format(label))\n\n for polisher in polishers:\n polisher.go(self)\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n for polisher in polishers:\n polisher.move_to(facility)\n facility.polish_blueprint(names, polishers)\n\n for polisher in polishers:\n polisher.reap()\n\n def stop_all_blueprints(self, facilities=None):\n \"\"\"\n Stops all nodes of the fittings plan\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to stop all nodes there.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n This function has no effect on nodes that are already stopped.\n\n \"\"\"\n\n logging.info(\"Stopping nodes from all blueprints\")\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.stop_all_blueprints()\n\n def stop_blueprint(self, names, facilities=None):\n \"\"\"\n Stops nodes of one blueprint of the fittings plan\n\n :param names: the name(s) of the blueprint(s) to stop\n :type names: ``str`` or ``list`` of ``str``\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to stop nodes from some blueprint.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n This function has no effect on nodes that are already stopped.\n\n \"\"\"\n\n if isinstance(names, list):\n label = ' '.join(names)\n else:\n label = names\n\n logging.info(\"Stopping nodes from blueprint '{}'\".format(label))\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.stop_blueprint(names)\n\n def wipe_all_blueprints(self, facilities=None):\n \"\"\"\n Destroys all nodes from fittings plan\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to destroy all nodes there.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n Note:\n Running nodes are always preserved from destruction.\n Therefore the need to stop nodes, in a separate command, before\n they can be actually destroyed.\n\n \"\"\"\n\n logging.info(\"Wiping all blueprints\")\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.wipe_all_blueprints()\n\n def wipe_blueprint(self, names, facilities=None):\n \"\"\"\n Destroys nodes for one or several blueprint(s) of the fittings plan\n\n :param names: the name(s) of the blueprint(s) to destroy\n :type names: ``str`` or ``list`` of ``str``\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to destroy nodes from one blueprint.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n Note:\n Running nodes are always preserved from destruction.\n Therefore the need to stop nodes, in a separate command, before\n they can be actually destroyed.\n\n \"\"\"\n\n if isinstance(names, list):\n label = ' '.join(names)\n else:\n label = names\n\n logging.info(\"Wiping blueprint '{}'\".format(label))\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.wipe_blueprint(names)\n\n def destroy_all_blueprints(self, facilities=None):\n \"\"\"\n Destroys all blueprints from fittings plan\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to destroy all blueprints there.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n Note:\n Running nodes are always preserved from destruction.\n Therefore the need to stop nodes, in a separate command, before\n they can be actually destroyed.\n\n \"\"\"\n\n logging.info(\"Destroying all blueprints\")\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.destroy_all_blueprints()\n\n def destroy_blueprint(self, names, facilities=None):\n \"\"\"\n Destroys one or several blueprint(s) from fittings plan\n\n :param names: the name(s) of the blueprint(s) to destroy\n :type names: ``str`` or ``list`` of ``str``\n\n :param facilities: explicit list of target facilities\n :type facilities: ``str`` or ``list`` of ``str``\n\n This function checks facilities to destroy one single blueprint.\n The default behaviour is to consider all facilities mentioned in the\n fittings plan. If a list of facilities is provided, than the action is\n limited to this subset only.\n\n Note:\n Running nodes are always preserved from destruction.\n Therefore the need to stop nodes, in a separate command, before\n they can be actually destroyed.\n\n \"\"\"\n\n if isinstance(names, list):\n label = ' '.join(names)\n else:\n label = names\n\n logging.info(\"Destroying blueprint '{}'\".format(label))\n\n if facilities is not None:\n facilities = self.list_facility(facilities)\n else:\n facilities = self.facilities\n\n for facility in facilities:\n facility.focus()\n facility.destroy_blueprint(names)\n\n def get_compute_driver(self, region):\n \"\"\"\n Loads a compute driver from Apache Libcloud\n\n \"\"\"\n\n driver = get_compute_driver(ComputeProvider.DIMENSIONDATA)\n\n return driver(\n key=self.get_user_name(),\n secret=self.get_user_password(),\n region=region)\n\n def get_balancer_driver(self, region):\n \"\"\"\n Loads a load balancer driver from Apache Libcloud\n\n \"\"\"\n\n driver = get_balancer_driver(BalancerProvider.DIMENSIONDATA)\n\n return driver(\n key=self.get_user_name(),\n secret=self.get_user_password(),\n region=region)\n\n def lookup(self, token):\n\n if token == 'plumbery.version':\n return __version__\n\n if token == 'random.secret':\n return self.get_random_secret()\n\n if token == 'shared.secret':\n return self.get_shared_secret()\n\n return None\n\n","sub_path":"plumbery/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":33176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"321070186","text":"# omega_matter_plot\n# Plots H0 as a function of varying omega matter\n# Omega matter in uncertainty range from\n# Planck 2015 results XIII: Cosmological Parameters:\n# https://arxiv.org/abs/1502.01589\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom h0_var_param import h0_var_param\nfrom dampc_var_param import dampc_var_param\n\n\nc = 299792.458\nomegak = 0.\n\n# Planck 2015 paper, Planck TT + lowP + BAO:\n# h0 in km/s/Mpc\nh0_planck = 67.6\n\n# WMAP gives omegam = 0.27 +/- 0.04\n# Planck gives omegam = 0.310 +/- 0.008\n# Here I will test the difference between using Planck cosmo vs WMAP cosmo\n# (omega_m = 0.27 was assumed in MCP)\n# Or alternatively, test the difference between the lower to upper uncertainties on Planck alone\n\nplanck_vs_wmap = True\n\nif planck_vs_wmap == True:\n\tomegam_low = 0.27\n\tomegam_high = 0.310\nelse:\n\n\tomegam_low = 0.310 - 0.008\n\tomegam_high = 0.310 + 0.008\n\nomegam_mid = (omegam_high+omegam_low)/2.0\n\n#Plot the points from MCP\n\n# MCP 4: UGC 3789\nDa_3789 = 49.6 #+/- 5.1Mpc\ncz_3789 = 3466 # cz = V_0 + V_p (optical vel rel to CMB and corrected for peculiar vel)\nh0_3789 = h0_var_param(cz_3789, 'Da', Da_3789, 1.-omegam_mid, omegak, omegam_mid)\nh0_low_3789 = h0_var_param(cz_3789, 'Da', Da_3789, 1.-omegam_low, omegak, omegam_low)\nh0_high_3789 = h0_var_param(cz_3789, 'Da', Da_3789, 1.-omegam_high, omegak, omegam_high)\ndiff_3789 = h0_high_3789 - h0_low_3789\nz_3789 = cz_3789 / c\n\n# MCP 5: NGC 6264: \nDa_6264 = 144 # +/- 19 Mpc\ncz_6264 = 10189.6 #V_0 because paper didn't know V_p\nh0_6264 = h0_var_param(cz_6264, 'Da', Da_6264, 1.-omegam_mid, omegak, omegam_mid)\nh0_low_6264 = h0_var_param(cz_6264, 'Da', Da_6264, 1.-omegam_low, omegak, omegam_low)\nh0_high_6264 = h0_var_param(cz_6264, 'Da', Da_6264, 1.-omegam_high, omegak, omegam_high)\ndiff_6264 = h0_high_6264 - h0_low_6264\nz_6264 = cz_6264 / c\n\n#MCP 6: NGC 6323\nDa_6323 = 107 # +42 - 29 #This may not be Da?\ncz_6323 = 7853 - 282\nh0_6323 = h0_var_param(cz_6323, 'Da', Da_6323, 1.-omegam_mid, omegak, omegam_mid)\nh0_low_6323 = h0_var_param(cz_6323, 'Da', Da_6323, 1.-omegam_low, omegak, omegam_low)\nh0_high_6323 = h0_var_param(cz_6323, 'Da', Da_6323, 1.-omegam_high, omegak, omegam_high)\ndiff_6323 = h0_high_6323 - h0_low_6323\nz_6323 = cz_6323 / c\n\n# MCP 8: NGC 5765b\nDa_5765b = 126.3 # +/- 11.6 Mpc\ncz_5765b = 8334 #km/s\nh0_5765b = h0_var_param(cz_5765b, 'Da', Da_5765b, 1.-omegam_mid, omegak, omegam_mid)\nh0_low_5765b = h0_var_param(cz_5765b, 'Da', Da_5765b, 1.-omegam_low, omegak, omegam_low)\nh0_high_5765b = h0_var_param(cz_5765b, 'Da', Da_5765b, 1.-omegam_high, omegak, omegam_high)\ndiff_5765b = h0_high_5765b - h0_low_5765b\nz_5765b = cz_5765b / c\n\n# plot Hubble constant\nredshifts = np.array([z_3789, z_6264, z_6323, z_5765b])\nh0s = np.array([h0_3789, h0_6264, h0_6323, h0_5765b])\nh0s_high = np.array([h0_high_3789, h0_high_6264, h0_high_6323, h0_high_5765b])\nerr_plus = abs(h0s_high-h0s)\nh0s_low = np.array([h0_low_3789, h0_low_6264, h0_low_6323, h0_low_5765b])\nerr_minus = abs(h0s_low-h0s)\n\n\nif planck_vs_wmap == True:\n\ttitle = 'planck_v_wmap'\nelse:\n\ttitle = 'planckrange'\n\nlabels=('UGC 3789', 'NGC 6264', 'NGC 6323', 'NGC 5765b')\nplt.errorbar(redshifts, h0s, yerr=[err_minus, err_plus], fmt='o')\nfor label, x, y in zip(labels, redshifts, h0s):\n\tplt.annotate(label, xy=(x,y))\nplt.xlabel('Redshift z')\nplt.ylabel(r'$H_0$')\nplt.title(\"H0 from MCP Galaxies\")\nplt.savefig('mcp_h0s_%s.png' %title)\nplt.show()\n\n\ndiffs = [diff_3789, diff_6264, diff_6323, diff_5765b]\nplt.plot(redshifts, diffs, 'ro')\nlabels=('UGC 3789', 'NGC 6264', 'NGC 6323', 'NGC 5765b')\nfor label, x, y in zip(labels, redshifts, diffs):\n\tplt.annotate(label, xy=(x,y))\nplt.xlabel('Redshift z')\nplt.ylabel(r'$H_0(\\Omega_m=%.3f) - H_0(\\Omega_m=%.3f$) [$km s^{-1} Mpc^{-1}$]' %(omegam_high,omegam_low))\nplt.title(\"H0 Dependence on \" + r'$\\Omega_m$' + \" for MCP Galaxies\")\nplt.savefig('mcp_h0s_var_omegam_%s.png' %title)\nplt.show()\n\n\n# Plot H0 as a function of redshift\n\nh0_range = []\nz_range = [z for z in np.arange(0.1,10,0.1)]\n\nfor z in np.arange(0.1, 10, 0.1):\n\tcz = c * z\n\tda = dampc_var_param(cz, h0_planck, 1.-omegam_mid, omegak, omegam_mid)\n\th0_low = h0_var_param(cz, 'Da', da, 1.-omegam_low, omegak, omegam_low)\n\th0_high = h0_var_param(cz, 'Da', da, 1.-omegam_high, omegak, omegam_high)\n\tdelta_h0 = h0_high - h0_low\n\th0_range.append(delta_h0)\n\n\n# Plot differences of H0 vs redshift:\n\nplt.plot(z_range, h0_range, 'ro')\nplt.xlabel('Redshift z')\nplt.ylabel(r'$H_0(\\Omega_m=%.3f) - H_0(\\Omega_m=%.3f$) [$km s^{-1} Mpc^{-1}$]' %(omegam_high,omegam_low))\nplt.savefig('h0_varied_omegam_zto10_%s.png'%title)\nplt.title('Theoretical dependence of H0 on '+r'$\\Omega_m$')\nplt.show()","sub_path":"omega_matter_plot.py","file_name":"omega_matter_plot.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"520364110","text":"import boto3\n\ndef init_dynamo(table_name=\"FlaskDynamo\"):\n dynamodb = boto3.resource(\n \"dynamodb\", \n region_name=\"region\", \n aws_access_key_id=\"access_key\", \n aws_secret_access_key=\"secret_key\")\n \n table = dynamodb.Table(table_name)\n \n return table","sub_path":"flask-and-dynamo/FlaskDynamo/App/dynamo.py","file_name":"dynamo.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"578165755","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 6 16:12:01 2020\n\n@author: Bran\n\"\"\"\n\n\nimport datetime as dt\nimport yfinance as yf\nimport pandas as pd\n\nstocks = [\"AMZN\", \"MSFT\", \"GOOG\", \"FB\"]\nstart = dt.datetime.today()-dt.timedelta(3650)\nend = dt.datetime.today()\n\n#empty data frame\ncl_price = pd.DataFrame()\n#empty dictionary\nohlcv_data = {}\n\n\n\nfor ticker in stocks:\n cl_price[ticker] = yf.download(ticker, start, end,)[\"Adj Close\"] \n\n\n\n#filling NaN values\n#fill with 0\n#cl_price.fillna(0)\n#fill with different values\n#cl_price.fillna({\"FB\":0, \"GOOG\":1})\n#backfill\ncl_price.fillna(method='bfill')\n#backfill can work along rows too (default axis is 0)\n#cl_price.fillna(method='bfill',axis=1)\n\n#if you want the changes to be permanent, use inplace=True\n#cl_price.fillna(method='bfill', inplace=True)\n\n#dropna will delete rows or columns with NaN\n\ndaily_return= cl_price.pct_change()","sub_path":"Intros/nafillIntro.py","file_name":"nafillIntro.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"394588489","text":"import sys\n\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'\ndb = SQLAlchemy(app)\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(80), unique=True)\n email = db.Column(db.String(120), unique=True)\n\n def __init__(self, username, email):\n self.username = username\n self.email = email\n\n def __repr__(self):\n return '' % self.username\n\n@app.route('/')\ndef hello_world():\n user = User.query.first()\n return 'Hello, %s!' % user.username\n\nif __name__ == \"__main__\":\n if '--init_db' in sys.argv:\n db.create_all()\n db.session.add(User('jdoe', 'jdoe@example.com'))\n db.session.commit()\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"98663210","text":"import sys\nimport os.path\nsys.path.append(os.path.join(os.path.dirname(__file__), '../..'))\n\n# Imports\nfrom math import pi\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.pyplot import axis, grid, xlim\n\nfrom lib.plot import *\nfrom lib.vector_manipulation import *\nfrom objects.vector import vector\n# Endports\n\n# Listing 11.03 Parametric plots\n# Begin\n\nz = [None] * 40\nw = [None] * 40\nth = vector(0, 2*pi/40, 2*pi)\nr = 1.1\ng = .1\ncx = sqrt(r**2 - g**2) - 1\ncy = g\nx = r*cos(th) + cx\ny = r*sin(th) + cy\nplot(x, y, 'r')\naxis('equal')\nplt.hold('true')\ngrid()\nfor i in range(0, 40):\n z[i] = complex(x[i], y[i])\n w[i] = z[i] + 1/z[i]\nplot(real(w), imag(w), 'k')\nxlim(xmax=2.1)\n\n# End\n","sub_path":"popeye/web_server/listing_exec_app/lib/default_code/ch_11/Listing_11_3.py","file_name":"Listing_11_3.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"338700308","text":"#\n# @lc app=leetcode.cn id=20 lang=python3\n#\n# [20] 有效的括号\n#\n# https://leetcode-cn.com/problems/valid-parentheses/description/\n#\n# algorithms\n# Easy (35.90%)\n# Total Accepted: 41.8K\n# Total Submissions: 116.2K\n# Testcase Example: '\"()\"'\n#\n# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。\n#\n# 有效字符串需满足:\n#\n#\n# 左括号必须用相同类型的右括号闭合。\n# 左括号必须以正确的顺序闭合。\n#\n#\n# 注意空字符串可被认为是有效字符串。\n#\n# 示例 1:\n#\n# 输入: \"()\"\n# 输出: true\n#\n#\n# 示例 2:\n#\n# 输入: \"()[]{}\"\n# 输出: true\n#\n#\n# 示例 3:\n#\n# 输入: \"(]\"\n# 输出: false\n#\n#\n# 示例 4:\n#\n# 输入: \"([)]\"\n# 输出: false\n#\n#\n# 示例 5:\n#\n# 输入: \"{[]}\"\n# 输出: true\n#\n#\nclass Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n d = {'}': '{', ']': '[', ')': '('}\n\n stack = [' ']\n\n for c in s:\n c2 = d.get(c, '')\n if stack[-1] == c2:\n stack.pop()\n elif c2:\n return False\n else:\n stack.append(c)\n return len(stack) == 1\n\ns = Solution()\nprint(s.isValid(\"(\"))","sub_path":"20.valid-parentheses.py","file_name":"20.valid-parentheses.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"646225745","text":"import subprocess as sp\nimport pymysql\nimport pymysql.cursors\n\n########\n\ndef displayActor():\n \n try:\n\n cur.execute('select * from Actor')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Aadhar_ID\")\n wid2=len(\"Name\")\n wid3=len(\"DOB\")\n wid4=len(\"Contact\")\n wid5=len(\"Remuneration\")\n wid6=len(\"Lead or Not\")\n wid7=len(\"Filmography\")\n for row in rows:\n wid1=max(wid1,len(str(row['Aadhar_ID'])))\n wid2=max(wid2,len(str(row['Name'])))\n wid3=max(wid3,len(str(row['DOB'])))\n wid4=max(wid4,len(str(row['Contact'])))\n wid5=max(wid5,len(str(row['Remuneration'])))\n wid6=max(wid6,len(str(row['Leadflag'])))\n wid7=max(wid7,len(str(row['Filmography'])))\n print(f\"{'Aadhar_ID':<{wid1}s} : {'Name':<{wid2}s} : {'DOB':<{wid3}s} : {'Contact':<{wid4}s} : {'Remuneration':<{wid5}s} : {'Lead or Not':<{wid6}s} : {'Filmography':<{wid7}s}\")\n \n \n for row in rows:\n print(f\"{str(row['Aadhar_ID']):<{wid1}s} : {str(row['Name']):<{wid2}s} : {str(row['DOB']):<{wid3}s} : {str(row['Contact']):<{wid4}s} : {str(row['Remuneration']):<{wid5}s} : {str(row['Leadflag']):<{wid6}s} : {str(row['Filmography']):<{wid7}s}\")\n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Actors List\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n########\n\ndef displayDirector():\n \n try:\n cur.execute('select * from Director')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Director_ID\")\n wid2=len(\"Name\")\n wid3=len(\"DOB\")\n wid4=len(\"Filmography\")\n wid5=len(\"Mainflag\")\n wid6=len(\"MainID\")\n \n for row in rows:\n wid1=max(wid1,len(str(row['Director_ID'])))\n wid2=max(wid2,len(str(row['Name'])))\n wid3=max(wid3,len(str(row['DOB'])))\n wid4=max(wid4,len(str(row['Filmography'])))\n wid5=max(wid5,len(str(row['Mainflag'])))\n wid6=max(wid6,len(str(row['MainID'])))\n \n print(f\"{'Director_ID':<{wid1}s} : {'Name':<{wid2}s} : {'DOB':<{wid3}s} : {'Filmography':<{wid4}s} : {'Main or not':<{wid5}s} : {'MainID':<{wid6}s}\")\n \n for row in rows:\n print(f\"{str(row['Director_ID']):<{wid1}s} : {str(row['Name']):<{wid2}s} : {str(row['DOB']):<{wid3}s} : {str(row['Filmography']):<{wid4}s} : {str(row['Mainflag']):<{wid5}s} : {str(row['MainID']):<{wid6}s}\")\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Directors List\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n########\n\ndef displayAddressofActor():\n \n try:\n Aadhar_ID= int(input(\"Enter Aadhar_ID of Actor to get Address for : \"))\n cur.execute(f'select * from Actor_Address_Country natural join (select * from Actor_Address_City natural join Actor_Address_State)t where Aadhar_ID = {Aadhar_ID}')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"City\")\n wid2=len(\"State\")\n wid3=len(\"Country\")\n for row in rows:\n wid1=max(wid1,len(str(row['City'])))\n wid2=max(wid2,len(str(row['State'])))\n wid3=max(wid3,len(str(row['Country'])))\n\n print(f\"{'City':<{wid1}s} : {'State':<{wid2}s} : {'Country':<{wid3}s}\")\n \n \n for row in rows:\n print(f\"{str(row['City']):<{wid1}s} : {str(row['State']):<{wid2}s} : {str(row['Country']):<{wid3}s}\")\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Actor's Address List\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n#########\n\ndef displayAddressofDirector():\n \n try:\n Director_ID = input(\"Enter ID of Director to get Address for : \")\n cur.execute(f'select * from Director_Address_Country natural join (select * from Director_Address_City natural join Director_Address_State)t where Director_ID = {Director_ID}')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"City\")\n wid2=len(\"State\")\n wid3=len(\"Country\")\n for row in rows:\n wid1=max(wid1,len(str(row['City'])))\n wid2=max(wid2,len(str(row['State'])))\n wid3=max(wid3,len(str(row['Country'])))\n\n print(f\"{'City':<{wid1}s} : {'State':<{wid2}s} : {'Country':<{wid3}s}\")\n \n for row in rows:\n print(f\"{str(row['City']):<{wid1}s} : {str(row['State']):<{wid2}s} : {str(row['Country']):<{wid3}s}\")\n\n except Exception as e:\n con.rollback()\n print(\"Failed to get Director's Address List\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n########\n\ndef displayAccoladesofActor():\n \n try:\n Aadhar_ID= input(\"Enter Aadhar_ID of Actor to get Accolades for : \")\n cur.execute(f'select * from Actor_Accolades where Aadhar_ID = {Aadhar_ID}')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Accolade\")\n for row in rows:\n wid1=max(wid1,len(str(row['Name_of_Accolade'])))\n\n print(f\"{'Accolade':<{wid1}s}\")\n \n \n for row in rows:\n print(f\"{str(row['Name_of_Accolade']):<{wid1}s}\")\n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Actor's Accolade List\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n#########\n\ndef displayAccoladesofDirector():\n \n try:\n Director_ID = input(\"Enter ID of Director to get Accolades for : \")\n cur.execute(f'select * from Director_Accolades where Director_ID = {Director_ID}')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Accolade\")\n for row in rows:\n wid1=max(wid1,len(str(row['Name_of_Accolade'])))\n\n print(f\"{'Accolade':<{wid1}s}\")\n \n for row in rows:\n print(f\"{str(row['Name_of_Accolade']):<{wid1}s}\")\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Director's Accolade List\")\n print(\">>>>>>>>>>>>>\", e)\n return\n\n#########\n\ndef displayVFX():\n \n try:\n\n cur.execute('select * from VFX')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Movie_ID\")\n wid2=len(\"Name\")\n wid3=len(\"VFX_Director\")\n wid4=len(\"Avg_Demand\")\n for row in rows:\n wid1=max(wid1,len(str(row['Movie_ID'])))\n wid2=max(wid2,len(str(row['Name'])))\n wid3=max(wid3,len(str(row['VFX_Director'])))\n wid4=max(wid4,len(str(row['Avg_Demand'])))\n\n print(f\"{'Movie_ID':<{wid1}s} : {'Name':<{wid2}s} : {'VFX_Director':<{wid3}s} : {'Avg_Demand':<{wid4}s} \")\n \n \n for row in rows:\n print(f\"{str(row['Movie_ID']):<{wid1}s} : {str(row['Name']):<{wid2}s} : {str(row['VFX_Director']):<{wid3}s} : {str(row['Avg_Demand']):<{wid4}s} \")\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get VFX's List\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n########\n\ndef displaySets():\n \n try:\n cur.execute('Select * from Set_Cost natural join Set_Manpower natural join Set_Location')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Movie_ID\")\n wid2=len(\"VFX_ID\")\n wid3=len(\"Cost\")\n wid4=len(\"Location_Depicted\")\n wid5=len(\"Man_Power\")\n \n for row in rows:\n wid1=max(wid1,len(str(row['Movie_ID'])))\n wid2=max(wid2,len(str(row['VFX_ID'])))\n wid3=max(wid3,len(str(row['Cost'])))\n wid4=max(wid4,len(str(row['Location_Depicted'])))\n wid5=max(wid5,len(str(row['Man_Power'])))\n\n print(f\"{'Movie_ID':<{wid1}s} : {'VFX_ID':<{wid2}s} : {'Cost':<{wid3}s} : {'Location_Depicted':<{wid4}s} : {'Man_Power':<{wid5}s} \")\n \n for row in rows:\n print(f\"{str(row['Movie_ID']):<{wid1}s} : {str(row['VFX_ID']):<{wid2}s} : {str(row['Cost']):<{wid3}s} : {str(row['Location_Depicted']):<{wid4}s} : {str(row['Man_Power']):<{wid5}s} \")\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Set's List\")\n print(\">>>>>>>>>>>>>\", e)\n return\n\n########### \n\ndef displayAddressofVFX():\n \n try:\n Movie_ID= input(\"Enter Movie_ID of VFX to get Address for : \")\n cur.execute(f'select * from VFX_Address_Country natural join (select * from VFX_Address_City natural join VFX_Address_State)t where Movie_ID = {Movie_ID}')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"City\")\n wid2=len(\"State\")\n wid3=len(\"Country\")\n for row in rows:\n wid1=max(wid1,len(str(row['City'])))\n wid2=max(wid2,len(str(row['State'])))\n wid3=max(wid3,len(str(row['Country'])))\n\n print(f\"{'City':<{wid1}s} : {'State':<{wid2}s} : {'Country':<{wid3}s}\")\n \n \n for row in rows:\n print(f\"{str(row['City']):<{wid1}s} : {str(row['State']):<{wid2}s} : {str(row['Country']):<{wid3}s}\")\n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Actor's Address List\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n##########\n\ndef displayMovies():\n \n try:\n\n cur.execute('select * from Movie_info natural join Movie_Profit_or_Loss natural join Movie_Collections')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Movie_ID\")\n wid2=len(\"Name\")\n wid3=len(\"Release_Date\")\n wid4=len(\"Avg_rate\")\n wid5=len(\"Budget\")\n wid6=len(\"Director_ID\")\n wid7=len(\"Film_No\")\n wid8=len(\"Profit_or_Loss\")\n wid9=len(\"Collections\")\n for row in rows:\n wid1=max(wid1,len(str(row['Movie_ID'])))\n wid2=max(wid2,len(str(row['Name'])))\n wid3=max(wid3,len(str(row['Release_Date'])))\n wid4=max(wid4,len(str(row['Avg_rate'])))\n wid5=max(wid5,len(str(row['Budget'])))\n wid6=max(wid6,len(str(row['Director_ID'])))\n wid7=max(wid7,len(str(row['Film_No'])))\n wid8=max(wid8,len(str(row['Profit_or_Loss'])))\n wid9=max(wid9,len(str(row['Collections'])))\n\n print(f\"{'Movie_ID':<{wid1}s} : {'Name':<{wid2}s} : {'Release_Date':<{wid3}s} : {'Avg_rate':<{wid4}s} : {'Budget':<{wid5}s} : {'Director_ID':<{wid6}s} : {'Film_No':<{wid7}s} : {'Profit_or_Loss':<{wid8}s} : {'Collections':<{wid9}s}\")\n \n \n for row in rows:\n print(f\"{str(row['Movie_ID']):<{wid1}s} : {str(row['Name']):<{wid2}s} : {str(row['Release_Date']):<{wid3}s} : {str(row['Avg_rate']):<{wid4}s} : {str(row['Budget']):<{wid5}s} : {str(row['Director_ID']):<{wid6}s} : {str(row['Film_No']):<{wid7}s} : {str(row['Profit_or_Loss']):<{wid8}s} : {str(row['Collections']):<{wid9}s}\")\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Movie's List\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n########\n\ndef displayAwardsofMovie():\n \n try:\n Movie_ID= input(\"Enter Movie_ID of Movie to get Awards for : \")\n cur.execute(f'select * from Movie_Awards where Movie_ID = {Movie_ID}')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Award\")\n for row in rows:\n wid1=max(wid1,len(str(row['Award_Name'])))\n\n print(f\"{'Award':<{wid1}s}\")\n \n \n for row in rows:\n print(f\"{str(row['Award_Name']):<{wid1}s}\")\n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Movie's Award List\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n##########\n\ndef maxMovieRating():\n\n try:\n \n cur.execute(\"select MAX(Avg_rate) from Movie_info\")\n con.commit()\n row= cur.fetchall()\n print(\"Maximum Average Movie Rating is : %s\" % (row[0]['MAX(Avg_rate)'])) \n except Exception as e:\n con.rollback()\n print(\"Failed to get Max Average\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n#########\n\ndef minMovieRating():\n \n try:\n \n cur.execute(\"select MIN(Avg_rate) from Movie_info\")\n con.commit()\n row= cur.fetchall()\n print(\"Minimum Average Movie Rating is : %s\" % (row[0]['MIN(Avg_rate)'])) \n except Exception as e:\n con.rollback()\n print(\"Failed to get Min Average\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n##########\n\ndef AvgBudget():\n \n try:\n \n cur.execute(\"select AVG(Budget) from Movie_info\")\n con.commit()\n row= cur.fetchall()\n print(\"Average Budget for a Movie is : %s\" % (row[0]['AVG(Budget)'])) \n except Exception as e:\n con.rollback()\n print(\"Failed to get Average Budget\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n###########\n\ndef sumBudget():\n \n try:\n \n cur.execute(\"select SUM(Budget) from Movie_info\")\n con.commit()\n row= cur.fetchall()\n print(\"Total Budget for all Movies allocated till now is : %s crores\" % (row[0]['SUM(Budget)'])) \n except Exception as e:\n con.rollback()\n print(\"Failed to get Total Budget\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n###########\n\ndef partialSearch( ):\n \n try:\n\n paSearch = input(\"Enter the Name to search for: \")\n cur.execute(f'select Name from Movie_info where Name like \"%{paSearch}%\"')\n \n con.commit()\n rows= cur.fetchall()\n print(\"Names: \") \n for row in rows:\n print(row['Name']) \n \n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Names in Search\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n#########\n\ndef numSuccDirectors():\n \n try: \n cur.execute(\"select AVG(Profit_or_Loss) from Movie_Profit_or_Loss\")\n con.commit()\n rowProfit = cur.fetchall()\n avgProfit = rowProfit[0]['AVG(Profit_or_Loss)']\n succIDs = set() \n cur.execute(\"select * from Director as dir, Movie_info as mi, Movie_Profit_or_Loss as mpl where dir.Director_ID = mi.Director_ID and mi.Movie_ID = mpl.Movie_ID\")\n con.commit()\n rows= cur.fetchall()\n \n for row in rows:\n if row['Profit_or_Loss'] >= avgProfit:\n succIDs.add(row['Director_ID'])\n print(f'Number of successful directors associated are {len(succIDs)}')\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get successfull directors\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n#######\n\ndef valuedActors():\n \n try:\n thresh = int(input(\"Enter the threshold experience value actors should possess: \"))\n cur.execute(f'select * from Actor as A, (select Aadhar_ID, COUNT(*) as count from Actor_Accolades group by Aadhar_ID) as B where A.Aadhar_ID = B.Aadhar_ID')\n con.commit()\n rows = cur.fetchall()\n req = 0\n awds = 0\n actedIn = 0\n \n for row in rows:\n awds = 1\n awds += row['count']\n actedIn = row['Filmography']\n \n if ((awds * actedIn) >= thresh):\n req += 1\n print(f'Number of actors with / more than given threshold experience value is {req}') \n \n except Exception as e:\n con.rollback()\n print(\"Failed to get actors having more than given threshold experience value\")\n print(\">>>>>>>>>>>>>\", e)\n return\n\n########\n\ndef displayMoviesbyYear():\n \n try:\n\n year = int(input(\"Enter the year to show movies for: \"))\n cur.execute(f'select * from Movie_info where YEAR(Release_Date)= {year}')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Movie_ID\")\n wid2=len(\"Name\")\n wid3=len(\"Release_Date\")\n wid4=len(\"Avg_rate\")\n wid5=len(\"Budget\")\n wid6=len(\"Director_ID\")\n wid7=len(\"Film_No\")\n for row in rows:\n wid1=max(wid1,len(str(row['Movie_ID'])))\n wid2=max(wid2,len(str(row['Name'])))\n wid3=max(wid3,len(str(row['Release_Date'])))\n wid4=max(wid4,len(str(row['Avg_rate'])))\n wid5=max(wid5,len(str(row['Budget'])))\n wid6=max(wid6,len(str(row['Director_ID'])))\n wid7=max(wid7,len(str(row['Film_No'])))\n\n print(f\"{'Movie_ID':<{wid1}s} : {'Name':<{wid2}s} : {'Release_Date':<{wid3}s} : {'Avg_rate':<{wid4}s} : {'Budget':<{wid5}s} : {'Director_ID':<{wid6}s} : {'Film_No':<{wid7}s}\")\n \n \n for row in rows:\n print(f\"{str(row['Movie_ID']):<{wid1}s} : {str(row['Name']):<{wid2}s} : {str(row['Release_Date']):<{wid3}s} : {str(row['Avg_rate']):<{wid4}s} : {str(row['Budget']):<{wid5}s} : {str(row['Director_ID']):<{wid6}s} : {str(row['Film_No']):<{wid7}s}\")\n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Movie by Year\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n#######\n\ndef displayMoviesbyAvgRating():\n \n try:\n\n rate = input(\"Enter the threshold of Avg.Rating to show movies for: \")\n cur.execute(f'select * from Movie_info where Avg_rate >= {rate}')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Movie_ID\")\n wid2=len(\"Name\")\n wid3=len(\"Release_Date\")\n wid4=len(\"Avg_rate\")\n wid5=len(\"Budget\")\n wid6=len(\"Director_ID\")\n wid7=len(\"Film_No\")\n for row in rows:\n wid1=max(wid1,len(str(row['Movie_ID'])))\n wid2=max(wid2,len(str(row['Name'])))\n wid3=max(wid3,len(str(row['Release_Date'])))\n wid4=max(wid4,len(str(row['Avg_rate'])))\n wid5=max(wid5,len(str(row['Budget'])))\n wid6=max(wid6,len(str(row['Director_ID'])))\n wid7=max(wid7,len(str(row['Film_No'])))\n\n print(f\"{'Movie_ID':<{wid1}s} : {'Name':<{wid2}s} : {'Release_Date':<{wid3}s} : {'Avg_rate':<{wid4}s} : {'Budget':<{wid5}s} : {'Director_ID':<{wid6}s} : {'Film_No':<{wid7}s}\")\n \n \n for row in rows:\n print(f\"{str(row['Movie_ID']):<{wid1}s} : {str(row['Name']):<{wid2}s} : {str(row['Release_Date']):<{wid3}s} : {str(row['Avg_rate']):<{wid4}s} : {str(row['Budget']):<{wid5}s} : {str(row['Director_ID']):<{wid6}s} : {str(row['Film_No']):<{wid7}s}\")\n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get Movie by Year\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n#########\n\ndef insertmovie():\n\n Avg_rate=\"\"\n Release_Date=\"\"\n Movie_ID=0\n try:\n\n Movie_ID = int(input(\"Enter Movie_ID : \"))\n if (Movie_ID < 0):\n print(\"Movie_ID cannot take negative values\")\n return\n Movie_name = input(\"Movie Name : \")\n if (Movie_name == \"\"):\n print(\"Name cannot be NULL\")\n return\n Release_Date = input(\"Release Date (yyyy-mm-dd): \")\n Avg_rate = input(\"Avg_rate : \")\n \n if(Avg_rate!=\"\"):\n Avg_rate=float(Avg_rate)\n\n if (Avg_rate < 0):\n print(\"Avg_rate cannot take negative values\")\n return\n Budget = int(input(\"Budget : \"))\n if (Budget < 0):\n print(\"Budget cannot take negative values\")\n return\n Director_ID = int(input(\"Director_ID : \"))\n if (Director_ID < 0):\n print(\"Director_ID cannot take negative values\")\n return\n Film_No = int(input(\"Film_No : \"))\n if (Film_No < 0):\n print(\"Film_No cannot take negative values\")\n return\n Movieinfo_query = f'insert into Movie_info (Movie_ID, Name, Budget, Director_ID, Film_No) VALUES ({Movie_ID},\"{Movie_name}\", {Budget}, {Director_ID}, {Film_No})'\n cur.execute(Movieinfo_query);\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n \n try:\n if(Avg_rate!=\"\"):\n cur.execute(f'update Movie_info set Avg_rate = {Avg_rate} where Movie_ID={Movie_ID}')\n cur.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n \n \n try:\n if(Release_Date!=\"\"):\n cur.execute(f'update Movie_info set Release_Date = \"{Release_Date}\" where Movie_ID={Movie_ID}')\n cur.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n \n try:\n\n Collections = input(\"Collections : \")\n if(Collections!=\"\"):\n Collections=int(Collections)\n if (Collections < 0):\n print(\"Collections cannot take negative values\")\n return\n Movie_Collectionsquery = f'insert into Movie_Collections VALUES ({Movie_ID}, {Collections})'\n cur.execute(Movie_Collectionsquery)\n con.commit()\n else:\n Movie_Collectionsquery = f'insert into Movie_Collections (Movie_ID) VALUES ({Movie_ID})'\n cur.execute(Movie_Collectionsquery)\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n try:\n\n profit = input(\"Profit/Loss +ve/-ve : \")\n if(profit!=\"\"):\n profit=int(profit)\n Movie_Collectionsquery = f'insert into Movie_Profit_or_Loss VALUES ({Movie_ID}, {profit})'\n cur.execute(Movie_Collectionsquery)\n con.commit()\n else:\n Movie_Collectionsquery = f'insert into Movie_Collections (Movie_ID) VALUES ({Movie_ID})'\n cur.execute(Movie_Collectionsquery)\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n\n return\n\n\ndef insertMovieAward():\n \n try:\n Movie_ID=input(\"Movie_ID to enter Award for:\")\n Award_Name = input(\"Award Name recieved by movie: \")\n if(Award_Name==\"\"):\n print(\"Award Name cannot be empty\")\n return\n MovieAwardquery = f'insert into Movie_Awards VALUES ({Movie_ID}, \"{Award_Name}\")'\n cur.execute(MovieAwardquery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n\ndef insertactor():\n try:\n\n Actor_Aadharid = int(input(\"Aadhar ID of actor : \"))\n if (Actor_Aadharid < 0):\n print(\"Actor Aadhar_id cannot take negative values\")\n return\n Actor_Name = input(\"Actors Name : \")\n Actor_DOB = input(\"Actor date of birth (yyyy-mm-dd): \")\n Actor_Contact = input(\"Actors Contact number : \")\n if (Actor_Contact < 0):\n print(\"Actors Contact cannot take negative values\")\n return\n Actor_Remuneration = float(input(\"Actor Remuneration : \"))\n if (Actor_Remuneration < 0):\n print(\"Actors Remuneration cannot take negative values\")\n return\n Actor_Leadflag = input(\"enter 1 if he is main actor,otherwise 0 : \")\n if(not(Actor_Leadflag==1 or Actor_Leadflag==0)):\n print(\"Invalid Input\")\n return\n Actor_Filmography = int(input(\"No of films he acted \"))\n if (Actor_Filmography < 0):\n print(\"Actors filmography cannot take negative values\")\n return \n Actorinfoquery = f'insert into Actor VALUES ({Actor_Aadharid},\"{Actor_Name}\", \"{Actor_DOB}\", \"{Actor_Contact}\", {Actor_Remuneration}, \"{Actor_Leadflag}\", {Actor_Filmography})'\n cur.execute(Actorinfoquery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef insertActorAccolades():\n\n try:\n Actor_Aadharid = int(input(\"Actor Aadhar ID : \"))\n if (Actor_Aadharid < 0):\n print(\"Actors Aadhar id cannot take negative values\")\n return\n Actor_Accolades = input(\"Award Name recieved by actor : \")\n if(Actor_Accolades==\"\"):\n print(\"It cannot be empty\")\n return\n Actor_Accoladesquery = f'insert into Actor_Accolades VALUES ({Actor_Aadharid}, \"{Actor_Accolades}\")'\n cur.execute(Actor_Accoladesquery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n return\n\n\ndef insertActorAddress():\n \n Actor_Aadharid = int(input(\"Actors Aadhar ID : \"))\n\n Actor_Address_City = input(\"Actors city name : \")\n if(Actor_Address_City==\"\"):\n print(\"It cannot be empty\")\n return\n\n Actor_Address_State = input(\"Actors state name : \")\n if(Actor_Address_State==\"\"):\n print(\"It cannot be empty\")\n return\n\n Actor_Address_Country = input(\"Actors country name : \")\n if(Actor_Address_City==\"\"):\n print(\"It cannot be empty\")\n return\n \n try:\n\n Actor_Address_Cityquery = f'insert into Actor_Address_City VALUES ({Actor_Aadharid}, \"{Actor_Address_City}\")'\n cur.execute(Actor_Address_Cityquery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n try:\n \n Actor_Address_Statequery = f'insert into Actor_Address_State VALUES ({Actor_Aadharid},\"{Actor_Address_City}\", \"{Actor_Address_State}\")'\n cur.execute(Actor_Address_Statequery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n try:\n\n Actor_Address_Countryquery = f'insert into Actor_Address_Country VALUES ({Actor_Aadharid},\"{Actor_Address_State}\", \"{Actor_Address_Country}\")'\n cur.execute(Actor_Address_Countryquery)\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n \n return\n\ndef insertDirectorAddress():\n \n Directorid = int(input(\" Director ID : \"))\n\n Director_Address_City = input(\"Director's city name : \")\n if(Director_Address_City==\"\"):\n print(\"It cannot be empty\")\n return\n\n Director_Address_State = input(\"Director's state name : \")\n if(Director_Address_State==\"\"):\n print(\"It cannot be empty\")\n return\n\n Director_Address_Country = input(\"Director's country name : \")\n if(Director_Address_City==\"\"):\n print(\"It cannot be empty\")\n return\n \n try:\n\n Director_Address_Cityquery = f'insert into Director_Address_City VALUES ({Directorid}, \"{Director_Address_City}\")'\n cur.execute(Director_Address_Cityquery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n try:\n \n Director_Address_Statequery = f'insert into Director_Address_State VALUES ({Directorid},\"{Director_Address_City}\", \"{Director_Address_State}\")'\n cur.execute(Director_Address_Statequery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n try:\n\n Director_Address_Countryquery = f'insert into Director_Address_Country VALUES ({Directorid},\"{Director_Address_State}\", \"{Director_Address_Country}\")'\n cur.execute(Director_Address_Countryquery)\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n \n return\n\ndef insertVFXAddress():\n \n VFXid = int(input(\"VFX Movie ID : \"))\n\n VFX_Address_City = input(\"VFX city name : \")\n if(VFX_Address_City==\"\"):\n print(\"It cannot be empty\")\n return\n\n VFX_Address_State = input(\"VFX state name : \")\n if(VFX_Address_State==\"\"):\n print(\"It cannot be empty\")\n return\n\n VFX_Address_Country = input(\"VFX country name : \")\n if(VFX_Address_City==\"\"):\n print(\"It cannot be empty\")\n return\n \n try:\n\n VFX_Address_Cityquery = f'insert into VFX_Address_City VALUES ({VFXid}, \"{VFX_Address_City}\")'\n cur.execute(VFX_Address_Cityquery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n try:\n \n VFX_Address_Statequery = f'insert into VFX_Address_State VALUES ({VFXid},\"{VFX_Address_City}\", \"{VFX_Address_State}\")'\n cur.execute(VFX_Address_Statequery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n try:\n\n VFX_Address_Countryquery = f'insert into VFX_Address_Country VALUES ({VFXid},\"{VFX_Address_State}\", \"{VFX_Address_Country}\")'\n cur.execute(VFX_Address_Countryquery)\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n \n return\n\n\n\ndef insertdirector(): \n Main_ID=\"\"\n Director_ID=0\n try:\n\n Director_ID = int(input(\"Director ID : \"))\n if (Director_ID < 0):\n print(\"Director_ID cannot take negative values\")\n return\n Director_Name = input(\"Director Name : \")\n if(Director_Name==\"\"):\n print(\"Cannot be empty\")\n return\n Director_DOB = input(\"Director Date of Birth (yyyy-mm-dd): \")\n if(Director_DOB==\"\"):\n print(\"Cannot be empty\")\n return\n\n Director_Filmography = int(input(\"Director Filmography : \"))\n if (Director_Filmography < 0):\n print(\"Filmography cannot take negative values\")\n return\n Director_Mainflag = int(input(\"Enter '1' if he is main director,otherwise '0' : \"))\n if(not(Director_Mainflag==1 or Director_Mainflag==0)):\n print(\"Invalid Input\")\n return\n\n if (Director_Mainflag == 0):\n Main_ID = int(input(\"Main ID of the assistant director : \"))\n else:\n Main_ID = \"NULL\"\n Directorinfoquery = f'insert into Director (Director_ID, Name, DOB, Filmography ,Mainflag) VALUES ({Director_ID}, \"{Director_Name}\", \"{Director_DOB}\", {Director_Filmography}, \"{Director_Mainflag}\")'\n cur.execute(Directorinfoquery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n try:\n if(Main_ID!=\"NULL\"):\n cur.execute(f'update Director set MainID={Main_ID} where Director_ID = {Director_ID}')\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n return\n \n\ndef insertDirector_Accolades():\n Director_ID = int(input(\"Director ID : \"))\n try:\n\n\n Director_Accolades = input(\"Director_Accolades : \")\n if(Director_Accolades==\"\"):\n print(\"Cannot be empty\")\n return\n Director_Accoladesquery = f'insert into Director_Accolades VALUES ({Director_ID},\"{Director_Accolades}\")'\n cur.execute(Director_Accoladesquery)\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n\ndef insertVFX():\n try:\n\n VFX_Director = input(\"VFX Directors name : \")\n if(VFX_Director==\"\"):\n print(\"Cannot be empty\")\n return\n Avg_Demand = float(input(\"Average demand of VFX Studio : \"))\n if (Avg_Demand < 0):\n print(\"Average demand cannot take negative values\")\n return\n VFX_NAME = input(\"VFX studio name : \")\n if(VFX_NAME==\"\"):\n print(\"Cannot be empty\")\n return\n Movie_ID = int(input(\"Movie ,the VFX studio working on : \"))\n cur.execute(f'insert into VFX VALUES (\"{VFX_Director}\", {Avg_Demand}, \"{VFX_NAME}\", {Movie_ID})')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n\n\ndef insertset():\n\n Movie_ID=0\n Location_Depicted=\"\"\n VFX_ID=0\n\n try:\n\n Movie_ID = int(input(\"Movie ID for which the set is created : \"))\n Location_Depicted = input(\"Set location : \")\n if(Location_Depicted==\"\"):\n print(\"Cannot be empty\")\n return\n VFX_ID = int(input(\"VFX id associated with that set : \"))\n cur.execute(f'insert into Set_Location VALUES ({Movie_ID}, \"{Location_Depicted}\", {VFX_ID})')\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n try:\n Man_Power = int(input(\"Number of people working for the Set\"))\n if (Man_Power < 0):\n print(\"Man power cannot take negative values\")\n return\n curr.execute(f'insert into Set_Manpower VALUES ({Movie_ID}, {Man_Power},{VFX_ID}, \"{Location_Depicted}\")')\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n try:\n Set_Cost = int(input(\"Cost for the cration os set : \"))\n if (Set_Cost < 0):\n print(\"Cost cannot take negative values\")\n return\n curr.execute(f'insert into Set_Cost VALUES ({Movie_ID}, {Set_Cost},{VFX_ID}, \"{Location_Depicted}\")')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n return\n\n\n\ndef insertCOORDINATES_WITH():\n try:\n Movie_ID = int(input(\"Id of the VFX STUDIO: \"))\n Director_ID = int(input(\"Director ID: \"))\n cur.execute(f'insert into COORDINATES_WITH VALUES ({Movie_ID}, {Director_ID}')\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef insertREQUIRES():\n \n Movie_ID = int(input(\"Movie ID : \"))\n Director_ID = int(input(\"Director ID : \"))\n noofactors = int(input(\"Number of Actors in this movie : \"))\n if (noofactors < 0):\n print(\"Number of actors cannot take negative values\")\n return\n Actors = []\n for ind in range(noofactors):\n Aadhar_ID = int(input(f'Enter Aadhar_ID of Actor {ind+1}'))\n Actors.append(Aadhar_ID)\n noofsets = int(input(\"No of sets : \"))\n Sets = []\n if (noofsets < 0):\n print(\"Number of sets cannot take negative values\")\n return \n for ind in range(noofsets):\n Set_ID = int(input(f'Enter Set_ID of Set {ind+1}'))\n Sets.append(Set_ID)\n for x in Actors:\n for y in Sets:\n try:\n\n cur.execute(f'insert into COORDINATES_WITH VALUES ({x}, {Director_ID}, {Movie_ID}, {y})')\n con.commit()\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef updatemovie():\n \n try:\n\n Movie_ID = int(input(\"Movie_ID of movie that need to updated: \"))\n if (Movie_ID < 0):\n print(\"Movie_ID cannot take negative values\")\n return\n print(\"What do you want to Update?\")\n print(\"1.Name\")\n print(\"2.Release_Date\")\n print(\"3.Avg_rate\")\n print(\"4.Budget\")\n print(\"5.Director_ID\")\n print(\"6.Film_No\")\n print(\"7.Profit/Loss\")\n print(\"8.Collections\")\n op=int(input(\"Enter Option:\"))\n newvalue=input(\"Enter new Value:\")\n if(newvalue==\"\"):\n print(\"Cannot update to empty\")\n return\n \n if(op==1):\n \n cur.execute(f'Update Movie_info set Name=\"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n\n elif(op==2):\n cur.execute(f'Update Movie_info set Release_Date=\"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n \n elif(op==3):\n newvalue=float(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Movie_info set Avg_rate=\"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n elif(op==4):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Movie_info set Budget=\"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n \n elif(op==5):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Movie_info set Director_ID=\"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n \n elif(op==6):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Movie_info set Film_No=\"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n elif(op==7):\n newvalue=int(newvalue)\n cur.execute(f'Update Movie_Profit_or_Loss set Profit_or_Loss=\"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n elif(op==8):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Movie_Collections set Collection =\"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n \n else:\n print(\"Invalid Option\")\n return\n \n \n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef updateactor():\n \n try:\n\n Aadhar_ID = int(input(\"Movie_ID of movie that need to updated: \"))\n if (Aadhar_ID < 0):\n print(\"Aadhar_ID cannot take negative values\")\n return\n print(\"What do you want to Update?\")\n print(\"1.Name\")\n print(\"2.DOB\")\n print(\"3.Contact\")\n print(\"4.Remuneration\")\n print(\"5.LeadFlag\")\n print(\"6.Filmography\")\n op=int(input(\"Enter Option:\"))\n newvalue=input(\"Enter new Value:\")\n if(newvalue==\"\"):\n print(\"Cannot update to empty\")\n return\n \n if(op==1):\n\n cur.execute(f'Update Actor set Name=\"{newvalue}\" where Aadhar_ID={Aadhar_ID}')\n con.commit()\n\n elif(op==2):\n cur.execute(f'Update Actor set DOB=\"{newvalue}\" where Aadhar_ID={Aadhar_ID}')\n con.commit()\n \n elif(op==3):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Actor set Contact={newvalue} where Aadhar_ID={Aadhar_ID}')\n con.commit()\n elif(op==4):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Actor set Remuneration ={newvalue} where Aadhar_ID={Aadhar_ID}')\n con.commit()\n \n elif(op==5):\n newvalue=int(newvalue)\n if(not(newvalue == 1 or newvalue == 0)):\n print(\"Invalid\")\n return\n cur.execute(f'Update Actor set LeadFlag={newvalue} where Aadhar_ID={Aadhar_ID}')\n con.commit()\n \n elif(op==6):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Actor set Filmography={newvalue} where Aadhar_ID={Aadhar_ID}')\n con.commit()\n else:\n print(\"Invalid Option\")\n return\n \n \n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n\n\ndef updatedirector():\n \n try:\n\n Director_ID = int(input(\"Movie_ID of movie that need to updated: \"))\n if (Director_ID < 0):\n print(\"Director_ID cannot take negative values\")\n return\n print(\"What do you want to Update?\")\n print(\"1.Name\")\n print(\"2.DOB\")\n print(\"3.Filmography\")\n print(\"4.Mainflag\")\n print(\"5.MainID\")\n op=int(input(\"Enter Option:\"))\n newvalue=input(\"Enter new Value:\")\n if(newvalue==\"\"):\n print(\"Cannot update to empty\")\n return\n \n if(op==1):\n\n cur.execute(f'Update Director set Name=\"{newvalue}\" where Director_ID={Director_ID}')\n con.commit()\n\n elif(op==2):\n cur.execute(f'Update Director set DOB=\"{newvalue}\" where Director_ID={Director_ID}')\n con.commit()\n \n elif(op==3):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Director set Filmography={newvalue} where Director_ID={Director_ID}')\n con.commit()\n elif(op==4):\n newvalue=int(newvalue)\n if(newvalue!=1):\n print(\"Invalid: Only Promotion Allowed\")\n return\n cur.execute(f'Update Actor set Mainflag = 1 , MainID = NULL where Director_ID={Director_ID}')\n con.commit()\n \n elif(op==5):\n newvalue=int(newvalue)\n cur.execute(f'select Mainflag from Actor where Director_ID={Director_ID}')\n con.commit()\n ans=cur.fetchone()\n if(ans is None):\n print(\"Director does not exist\")\n return;\n if(ans['Mainflag']==1):\n print(\"This Director is a main Director cannot add MainID\")\n return\n cur.execute(f'Update Director set Main_ID={newvalue} where Director_ID={Director_ID}')\n con.commit()\n \n else:\n print(\"Invalid Option\")\n return\n \n \n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef updateSET():\n \n try:\n\n Movie_ID = int(input(\"Movie_ID of movie that need to updated: \"))\n oldlocation = input(\"Enter the Location Depicted by the Set: \")\n if (Movie_ID < 0):\n print(\"Movie_ID cannot take negative values\")\n return\n print(\"What do you want to Update?\")\n print(\"1.Location Depicted\")\n print(\"2.Cost\")\n print(\"3.ManPower\")\n op=int(input(\"Enter Option:\"))\n newvalue=input(\"Enter new Value:\")\n if(newvalue==\"\"):\n print(\"Cannot update to empty\")\n return\n \n if(op==1):\n\n cur.execute(f'Update Set_Locaton set Location_Depicted =\"{newvalue}\" where Movie_ID={Movie_ID} and Location_Depicted= \"{oldlocation}\"')\n con.commit()\n\n elif(op==2):\n \n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Set_Cost set Cost ={newvalue} where Movie_ID={Movie_ID} and Location_Depicted= \"{oldlocation}\"')\n con.commit()\n \n elif(op==3):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update Set_Manpower set Man_Power ={newvalue} where Movie_ID={Movie_ID} and Location_Depicted= \"{oldlocation}\"')\n con.commit()\n \n else:\n print(\"Invalid Option\")\n return\n \n \n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef updateVFX():\n \n try:\n\n Movie_ID = int(input(\"Movie_ID of movie that need to updated: \"))\n if (Movie_ID < 0):\n print(\"Movie_ID cannot take negative values\")\n return\n print(\"What do you want to Update?\")\n print(\"1.Name\")\n print(\"2.VFX_Director\")\n print(\"3.Avg_Demand\")\n op=int(input(\"Enter Option:\"))\n newvalue=input(\"Enter new Value:\")\n if(newvalue==\"\"):\n print(\"Cannot update to empty\")\n return\n \n if(op==1):\n\n cur.execute(f'Update VFX set Name =\"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n\n elif(op==2):\n \n cur.execute(f'Update VFX set VFX_Director = \"{newvalue}\" where Movie_ID={Movie_ID}')\n con.commit()\n \n elif(op==3):\n newvalue=int(newvalue)\n if(newvalue<0):\n print(\"Invalid\")\n return\n cur.execute(f'Update VFX set Avg_Demand ={newvalue} where Movie_ID={Movie_ID}')\n con.commit()\n \n else:\n print(\"Invalid Option\")\n return\n \n \n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n \ndef updateREQUIRES():\n try:\n Aadhar_IDold = int(input(\"old Aadhar ID : \"))\n Movie_IDold = int(input(\"old VFX ID : \"))\n Set_IDold = int(input(\"old Set ID : \"))\n Director_IDold = int(input(\"Old director ID : \"))\n Aadhar_IDnew = int(input(\"new Aadhar ID : \"))\n Movie_IDnew = int(input(\"new VFX ID : \"))\n Set_IDnew = int(input(\"new Set ID : \"))\n Director_IDnew = int(input(\"new director ID : \"))\n cur.execute(f'update REQUIRES SET Aadhar_ID = {Aadhar_IDnew}, Director_ID = {Director_IDnew}, Movie_ID = {Movie_IDnew}, SET_ID = {Set_IDnew} where Aadhar_ID = {Aadhar_IDold} and Director_ID = {Director_IDold} and Movie_ID = {Movie_IDold} and SET_ID = Set_IDold')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef updateCOORDINATES_WITH():\n try:\n\n Director_IDold = int(input(\"Old director id : \"))\n Movie_IDold = int(input(\"Old VFX studio ID : \"))\n Director_IDnew = int(input(\"New director id : \"))\n Movie_IDnew = int(input(\"New VFX studio ID : \"))\n cur.execute(f'update COORDINATES_WITH SET Director_ID = {Director_IDnew}, Movie_ID = {Movie_IDnew} where Director_ID = {Director_IDold} and Movie_ID = {Movie_IDold}')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n\n\n\ndef REQUIRES_del():\n try:\n\n Dir = int(input(\"Enter the Director ID of row to delete : \"))\n Mov = int(input(\"Enter the Movie ID of row to delete : \"))\n Aad = int(input(\"Enter the Aadhar ID of row to delete : \"))\n Set= int(input(\"Enter the Set ID of row to delete : \"))\n cur.execute(f'delete from REQUIRES where Aadhar_ID={Aad} and Director_ID={Dir} and Movie_ID={Mov} and SET_ID={Set}')\n con.commit()\n \n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from REQUIRES\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n\ndef Actor_del():\n \n try:\n\n Aad = int(input(\"Enter the Aadhar ID of Actor to delete : \"))\n cur.execute(f'delete from Actor where Aadhar_ID={Aad}')\n con.commit()\n \n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from Actor\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef Director_del():\n \n try:\n\n Dir = int(input(\"Enter the Director ID of Director to delete : \"))\n cur.execute(f'delete from Director where Director_ID={Dir}')\n con.commit()\n \n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from Director\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n\ndef Movie_del():\n \n try:\n\n Mov = int(input(\"Enter the Movie ID of Movie to delete : \"))\n cur.execute(f'delete from Movie_info where Movie_ID={Mov}')\n con.commit()\n \n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from Movie\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n\ndef VFX_del():\n \n try:\n\n Mov = int(input(\"Enter the Movie ID of VFX to delete : \"))\n cur.execute(f'delete from VFX where Movie_ID={Mov}')\n con.commit()\n \n\n\n \n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from VFX\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef Actor_Add_del():\n \n Aadhar_ID=0\n City=\"\"\n State=\"\"\n Country=\"\"\n try:\n\n Aadhar_ID = int(input(\"Enter the Aadhar_ID of Actor to delete Address for : \"))\n City = input(\"Enter the City of the Address to delete: \")\n cur.execute(f'select State from Actor_Address_State where Aadhar_ID={Aadhar_ID} and City=\"{City}\"')\n con.commit()\n State=fetchone()\n if(State is None):\n print(\"Cannot find State for given data\")\n return\n else:\n State=State['State']\n cur.execute(f'select Country from Actor_Address_Country where Aadhar_ID={Aadhar_ID} and State=\"{State}\"')\n con.commit()\n Country=fetchone()\n if(Country is None):\n print(\"Cannot find Country for given data\")\n return\n else:\n Country=Country['Country']\n cur.execute(f'delete from Actor_Address_Country where Aadhar_ID={Aadhar_ID} and State=\"{State}\"')\n con.commit()\n cur.execute(f'delete from Actor_Address_State where Aadhar_ID={Aadhar_ID} and City=\"{City}\"')\n con.commit()\n cur.execute(f'delete from Actor_Address_City where Aadhar_ID={Aadhar_ID} and City=\"{City}\"')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from Address\")\n print(\">>>>>>>>>>>>>\", e)\n return\n \n return\n\ndef Director_Add_del():\n \n Director_ID=0\n City=\"\"\n State=\"\"\n Country=\"\"\n try:\n\n Director_ID = int(input(\"Enter the Director_ID of Director to delete Address for : \"))\n City = input(\"Enter the City of the Address to delete: \")\n cur.execute(f'select State from Director_Address_State where Director_ID={Director_ID} and City=\"{City}\"')\n con.commit()\n State=fetchone()\n if(State is None):\n print(\"Cannot find State for given data\")\n return\n else:\n State=State['State']\n cur.execute(f'select Country from Director_Address_Country where Director_ID={Director_ID} and State=\"{State}\"')\n con.commit()\n Country=fetchone()\n if(Country is None):\n print(\"Cannot find Country for given data\")\n return\n else:\n Country=Country['Country']\n cur.execute(f'delete from Director_Address_Country where Director_ID={Director_ID} and State=\"{State}\"')\n con.commit()\n cur.execute(f'delete from Director_Address_State where Director_ID={Director_ID} and City=\"{City}\"')\n con.commit()\n cur.execute(f'delete from Director_Address_City where Director_ID={Director_ID} and City=\"{City}\"')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from Address\")\n print(\">>>>>>>>>>>>>\", e)\n return\n \n return\n\ndef VFX_Add_del():\n \n Director_ID=0\n City=\"\"\n State=\"\"\n Country=\"\"\n try:\n\n Movie_ID = int(input(\"Enter the Movie_ID of VFX to delete Address for : \"))\n City = input(\"Enter the City of the Address to delete: \")\n cur.execute(f'select State from VFX_Address_State where Director_ID={Director_ID} and City=\"{City}\"')\n con.commit()\n State=fetchone()\n if(State is None):\n print(\"Cannot find State for given data\")\n return\n else:\n State=State['State']\n cur.execute(f'select Country from Director_Address_Country where Director_ID={Director_ID} and State=\"{State}\"')\n con.commit()\n Country=fetchone()\n if(Country is None):\n print(\"Cannot find Country for given data\")\n return\n else:\n Country=Country['Country']\n cur.execute(f'delete from Director_Address_Country where Director_ID={Director_ID} and State=\"{State}\"')\n con.commit()\n cur.execute(f'delete from Director_Address_State where Director_ID={Director_ID} and City=\"{City}\"')\n con.commit()\n cur.execute(f'delete from Director_Address_City where Director_ID={Director_ID} and City=\"{City}\"')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from Address\")\n print(\">>>>>>>>>>>>>\", e)\n return\n \n return\n\n\n \n\n\ndef SET_del():\n \n try:\n\n Mov = int(input(\"Enter the Movie ID of SET to delete : \"))\n loc= input(\"Enter the Location of SET to delete : \")\n cur.execute(f'delete from Set_Location where Movie_ID={Mov} and Location_Depicted = \"{loc}\"')\n con.commit()\n cur.execute(f'delete from Set_Cost where Movie_ID={Mov} and Location_Depicted = \"{loc}\"')\n con.commit()\n cur.execute(f'delete from Set_Manpower where Movie_ID={Mov} and Location_Depicted = \"{loc}\"')\n con.commit()\n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from SET\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\n\ndef COORDINATES_WITH_del():\n\n try:\n\n Mov = int(input(\"Enter the Movie ID of tuple to delete : \"))\n Dir = int(input(\"Enter the Director ID of tuple to delete : \"))\n cur.execute(f'delete from COORDINATES_WITH where Movie_ID={Mov} and Director_ID = {Dir}')\n con.commit()\n \n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from VFX\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef showREQUIRES():\n\n try:\n cur.execute('Select * from REQUIRES')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Movie_ID\")\n wid2=len(\"Aadhar_ID\")\n wid3=len(\"Director_ID\")\n wid4=len(\"SET_ID\")\n \n for row in rows:\n wid1=max(wid1,len(str(row['Movie_ID'])))\n wid2=max(wid2,len(str(row['Aadhar_ID'])))\n wid3=max(wid3,len(str(row['Director_ID'])))\n wid4=max(wid4,len(str(row['SET_ID'])))\n\n print(f\"{'Movie_ID':<{wid1}s} : {'Aadhar_ID':<{wid2}s} : {'Director_ID':<{wid3}s} : {'SET_ID':<{wid4}s} \")\n \n for row in rows:\n print(f\"{str(row['Movie_ID']):<{wid1}s} : {str(row['Aadhar_ID']):<{wid2}s} : {str(row['Director_ID']):<{wid3}s} : {str(row['SET_ID']):<{wid4}s}\")\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get REQUIRES List\")\n print(\">>>>>>>>>>>>>\", e)\n return\n\ndef showCOORDINATES_WITH():\n\n try:\n cur.execute('Select * from COORDINATES_WITH')\n con.commit()\n rows = cur.fetchall()\n wid1=len(\"Movie_ID\")\n wid2=len(\"Director_ID\")\n \n for row in rows:\n wid1=max(wid1,len(str(row['Movie_ID'])))\n wid2=max(wid2,len(str(row['Director_ID'])))\n\n print(f\"{'Movie_ID':<{wid1}s} : {'Director_ID':<{wid2}s}\")\n \n for row in rows:\n print(f\"{str(row['Movie_ID']):<{wid1}s} : {str(row['Director_ID']):<{wid2}s}\")\n \n except Exception as e:\n con.rollback()\n print(\"Failed to get COORDINATES_WITH List\")\n print(\">>>>>>>>>>>>>\", e)\n return\n\ndef Movie_Award_del():\n \n try:\n\n Mov = int(input(\"Enter the Movie ID of Award to delete : \"))\n name= input(\"Enter the name of award to delete : \")\n cur.execute(f'delete from Movie_Awards where Movie_ID={Mov} and Award_Name = \"{name}\"')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from Awards\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef Actor_Accolade_del():\n \n try:\n\n Aad = int(input(\"Enter the Aadhar ID of Accolade to delete : \"))\n name= input(\"Enter the name of Accolade to delete : \")\n cur.execute(f'delete from Actor_Accolades where Aadhar_ID={Aad} and Name_of_Accolade= \"{name}\"')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from Accolades\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef Director_Accolade_del():\n \n try:\n\n Dir = int(input(\"Enter the Director ID of Accolade to delete : \"))\n name= input(\"Enter the name of Accolade to delete : \")\n cur.execute(f'delete from Director_Accolades where Director_ID={Dir} and Name_of_Accolade= \"{name}\"')\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\"Failed to Delete from Accolades\")\n print(\">>>>>>>>>>>>>\", e)\n\n return\n\ndef dispatch(ch):\n\n\n if(ch == 1):\n maxMovieRating()\n elif(ch == 2):\n minMovieRating()\n elif(ch == 3):\n AvgBudget()\n elif(ch == 4):\n sumBudget()\n elif(ch == 5):\n partialSearch()\n elif(ch == 6):\n displayMoviesbyYear()\n elif (ch == 7):\n displayMoviesbyAvgRating()\n elif (ch == 8):\n valuedActors()\n elif (ch == 9):\n numSuccDirectors()\n elif (ch == 10):\n displayMovies()\n elif (ch == 11):\n displayAwardsofMovie()\n elif (ch == 12):\n displayDirector()\n elif (ch == 13):\n displayAccoladesofDirector()\n elif (ch == 14):\n displayAddressofDirector()\n elif (ch == 15):\n displayActor()\n elif (ch == 16):\n displayAccoladesofActor()\n elif (ch == 17):\n displayAddressofActor()\n elif (ch == 18):\n displaySets()\n elif (ch == 19):\n displayVFX()\n elif (ch == 20):\n displayAddressofVFX()\n elif (ch == 21):\n showREQUIRES()\n elif (ch == 22):\n showCOORDINATES_WITH()\n elif (ch == 23):\n insertmovie()\n elif (ch == 24):\n insertMovieAward()\n elif (ch == 25):\n insertdirector()\n elif (ch == 26):\n insertDirector_Accolades()\n elif (ch == 27):\n insertDirectorAddress()\n elif (ch == 28):\n insertactor()\n elif (ch == 29):\n insertActorAccolades()\n elif (ch == 30):\n insertActorAddress()\n elif (ch == 31):\n insertset()\n elif (ch == 32):\n insertVFX()\n elif (ch == 33):\n insertVFXAddress()\n elif (ch == 34):\n insertREQUIRES()\n elif (ch == 35):\n insertCOORDINATES_WITH()\n elif (ch == 36):\n updatemovie()\n elif (ch == 37):\n updatedirector()\n elif (ch == 38):\n updateactor()\n elif (ch == 39):\n updateSET()\n elif (ch == 40):\n updateVFX()\n elif (ch == 41):\n updateREQUIRES()\n elif (ch == 42):\n updateCOORDINATES_WITH()\n elif (ch == 43):\n Movie_del()\n elif (ch == 44):\n Movie_Award_del()\n elif (ch == 45):\n Director_del()\n elif (ch == 46):\n Director_Accolade_del()\n elif (ch == 47):\n Director_Add_del()\n elif (ch == 48):\n Actor_del()\n elif (ch == 49):\n Actor_Accolade_del()\n elif (ch == 50):\n Actor_Add_del()\n elif (ch == 51):\n SET_del()\n elif (ch == 52):\n VFX_del()\n elif (ch == 53):\n VFX_Add_del()\n elif (ch == 54):\n REQUIRES_del()\n elif (ch == 55):\n COORDINATES_WITH_del()\n else:\n print(\"Error: Invalid Option\")\n\n\n\n\nwhile(1):\n tmp = sp.call('clear', shell=True)\n username = input(\"Username: \")\n password = input(\"Password: \")\n\n\n try:\n \n con = pymysql.connect(host='localhost',\n user=username,\n port=5005,\n password=password,\n db='MOVIE_STUDIO',\n cursorclass=pymysql.cursors.DictCursor)\n tmp = sp.call('clear', shell=True)\n\n if(con.open):\n print(\"Connected\")\n else:\n print(\"Failed to connect\")\n\n tmp = input(\"Enter any key to CONTINUE>\")\n\n with con.cursor() as cur:\n while(1):\n tmp = sp.call('clear', shell=True)\n print(\"1. Display Maximum Average Movie Rating\")\n print(\"2. Display Minimum Average Movie Rating\") \n print(\"3. Display Average Budget on a Movie\")\n print(\"4. Display Total Budget allocated on Movies till now\")\n print(\"5. Partial Search for Movie Names\")\n print(\"6. Project Movies Released in a Particular Year\")\n print(\"7. Project Movies with Avg. Rating Greater than or equal to input value\")\n print(\"8. Number of actors above given threshold value\")\n print(\"9. Display the number of successful directors associated with\")\n print(\"10.Show all Movies\")\n print(\"11.Show all Awards of a Movie given its Movie_ID\")\n print(\"12.Show all Directors\")\n print(\"13.Show all Accolades of a Director given his ID\")\n print(\"14.Show all Addresses of a Director\")\n print(\"15.Show all Actors\")\n print(\"16.Show all Accolades of an Actor given his Aadhar_ID\")\n print(\"17.Show all Addresses of an Actor given his Aadhar_ID\")\n print(\"18.Show all Sets\")\n print(\"19.Show all VFX Studios\")\n print(\"20.Show all Addressess of a VFX Studio given Movie_ID\")\n print(\"21.Show REQUIRES Relation\") \n print(\"22.Show COORDINATES_WITH Relation\")\n print(\"23.Insert a Movie\")\n print(\"24.Insert an Award for a Movie given Movie_ID\")\n print(\"25.Insert a Director\")\n print(\"26.Insert an Accolade for a Director given his Director_ID \")\n print(\"27.Insert an Address for a Director\")\n print(\"28.Insert an Actor\")\n print(\"29.Insert an Accolade for an Actor\")\n print(\"30.Insert an Address for an Actor\")\n print(\"31.Insert a Set\")\n print(\"32.Insert a VFX STUDIO\")\n print(\"33.Insert an Address for a VFX Studio\")\n print(\"34.Insert into REQUIRES relation\")\n print(\"35.Insert into COORDINATES_WITH relation\")\n print(\"36.Update a Movie\")\n print(\"37.Update a Director\")\n print(\"38.Update an Actor\")\n print(\"39.Update a Set\")\n print(\"40.Update a VFX Studio\")\n print(\"41.Update REQUIRES Relation\")\n print(\"42.Update COORDINATES_WITH Relation\")\n print(\"43.Delete a Movie\")\n print(\"44.Delete an Award for a Movie\") \n print(\"45.Delete a Director\")\n print(\"46.Delete a Director Accolade\") \n print(\"47.Delete a Director Address\")\n print(\"48.Delete an Actor\")\n print(\"49.Delete an Accolade of an Actor \") \n print(\"50.Delete an Address of an Actor\")\n print(\"51.Delete a Set\")\n print(\"52.Delete a VFX Studio\")\n print(\"53.Delete a VFX Studio Address\")\n print(\"54.Delete a tuple from REQUIRES relation\")\n print(\"55.Delete a COORDINATES_WITH relation\")\n ch = int(input(\"Enter choice> \"))\n tmp = sp.call('clear', shell=True)\n if (ch == 56):\n break\n else :\n dispatch(ch)\n tmp = input(\"Enter any key to CONTINUE>\")\n\n except:\n tmp = sp.call('clear', shell=True)\n print(\"Connection Refused: Either username or password is incorrect or user doesn't have access to database\")\n tmp = input(\"Enter any key to CONTINUE>\")\n ","sub_path":"MiniWorld.py","file_name":"MiniWorld.py","file_ext":"py","file_size_in_byte":63136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"364686130","text":"import sys\nfrom pyspark import SparkContext, SparkConf\n\nif __name__ == \"__main__\":\n conf = SparkConf().setAppName(\"word count\")\n #conf.setMaster(\"local[2]\")\n\n context = SparkContext(conf = conf)\n context.setLogLevel('ERROR')\n\n # This is to find the number of workers in the cluster. But it is not correct\n no_of_workers = context.statusTracker().getActiveJobsIds()\n print('No. of workers = {}'.format(no_of_workers))\n \n data = ('This', 'is', 'is', 'cool')\n rdd = context.parallelize(data, 2).cache()\n \n print('No of partitions - {}'.format(rdd.getNumPartitions()))\n wordCounts = rdd.countByValue()\n for word, count in wordCounts.items():\n print(\"{} : {}\".format(word, count))\n\n print('\\nReduce by key:')\n new_rdd = rdd.map(lambda x: (x,1), preservesPartitioning=True)\n result = new_rdd.reduceByKey(lambda a, b: a + b).collect()\n\n print(result)\n for word, count in result:\n print(\"{} : {}\".format(word, count))\n\n print(sys.executable)","sub_path":"miscellaneous/b_01_apache-spark-excercise/a_02_word-count.py","file_name":"a_02_word-count.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"61840113","text":"import time\nimport secrets\nimport logging\nimport random\nimport logging.handlers\nimport os\nimport multiprocessing\n\nCPU_COUNT = multiprocessing.cpu_count()\n\ndef log_forver():\n \n last_log_time = 0.0\n last_log_length = 1\n update_logger = logging.getLogger(\"update\")\n while True:\n length = random.randint(2,40)\n log_str = f\"{secrets.token_urlsafe(length)},{last_log_length} {last_log_time}ms\"\n\n if last_log_time > 10:\n update_log_str = f\"CPU{CPU_COUNT} python write {last_log_length} byte {last_log_time} ms\"\n if last_log_time > 50:\n update_logger.error(update_log_str)\n else:\n update_logger.info(update_log_str)\n\n before = time.time() * 1000\n if last_log_time > 50: # 大于100毫秒\n logging.error(log_str)\n elif last_log_time > 10:\n logging.warning(log_str)\n else:\n logging.info(log_str)\n\n last_log_length = len(log_str) + len(\"2020-11-21 11:32:44,632 INFO \")\n last_log_time = time.time() * 1000 - before\n time.sleep(1)\n\n\n\nLOG_MAX_SIZE = 10*1024*1024\nLOG_DIR = r\"D:\\tools\\testIO\"\nLOG_FILENAME = \"test_io.log\"\nLOG_FULL_FILENAME = LOG_DIR+\"\\\\\"+ LOG_FILENAME\n\ndef init_log():\n root = logging.getLogger()\n root.setLevel(logging.INFO)\n os.makedirs(LOG_DIR,exist_ok=True)\n h = logging.handlers.RotatingFileHandler(LOG_FULL_FILENAME,'a',LOG_MAX_SIZE,10)\n h.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))\n root.addHandler(h)\n\n\nUPDATED_LOG_FILENAME = r\"D:\\cloudgame_log\\py_write.log\"\n\ndef init_can_updated_log():\n update_logger = logging.getLogger(\"update\")\n update_logger.setLevel(logging.INFO)\n h = logging.handlers.RotatingFileHandler(UPDATED_LOG_FILENAME,'a',LOG_MAX_SIZE,10)\n h.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))\n update_logger.addHandler(h)\n\nif __name__ == \"__main__\":\n init_log()\n init_can_updated_log()\n log_forver()","sub_path":"py/log_consume.py","file_name":"log_consume.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"283090247","text":"import os\n\nfrom yass.batch import BatchProcessor\n\n\npath_to_neuropixel_data = (os.path.expanduser('~/data/ucl-neuropixel'\n '/rawDataSample.bin'))\n\n\nbp = BatchProcessor(path_to_neuropixel_data,\n dtype='int16', n_channels=385, data_format='wide',\n max_memory='1MB')\n\n# there are two ways of traversing the data: single_channel and multi_channel\n# single_channel means that the data in a single batch comes from only one\n# channel, multi_channel means that a batch can contain data from multiple\n# channels, let's take a look at single_channel operations\n\n# traverse the whole dataset, one channel at a time\ndata = bp.single_channel()\n\n# this will raise an error since we cannot fit all observations for a single\n# channel in memory, so we either increase max_memory or set\n# force_complete_channel_batch to False\nfor d in data:\n print(d.shape)\n\n# When force_complete_channel_batch is False, each batch does not necessarily\n# correspond to all observations in the channel, the channel can be splitted\n# in several batches (although every batch data is guaranteed to come from\n# a single channel), in this case, every channel is splitted in two parts\ndata = bp.single_channel(force_complete_channel_batch=False)\n\nfor d, i in data:\n print(d.shape, 'Data from channel {}'.format(i))\n\n\n# finally, we can traverse a single channel in a temporal subset\ndata = bp.single_channel(from_time=100000, to_time=200000)\n\nfor d in data:\n print(d.shape)\n\n# we can select specific channels\ndata = bp.single_channel(from_time=100000, to_time=200000, channels=[0, 1, 2])\n\nfor d in data:\n print(d.shape)\n\n\n# now, let's to some multi_channel operations, here we will traverse all\n# channels and all observations, each batch will contain a subset in the\n# temporal dimension, the window size is determined by max_memory\ndata = bp.multi_channel()\n\nfor d in data:\n print(d.shape)\n\n# we can specify the temporal limits and subset channels\ndata = bp.multi_channel(from_time=100000, to_time=200000, channels=[0, 1, 2])\n\nfor d in data:\n print(d.shape)\n","sub_path":"examples/batch/single_channel.py","file_name":"single_channel.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"393881623","text":"from typing import List\r\n\r\nclass Solution:\r\n def twoSum(self, nums: List[int], target: int) -> List[int]:\r\n dirt = {}\r\n for i, value in enumerate(nums):\r\n dirt[value] = i\r\n for i, value in enumerate(nums):\r\n tmp_num2 = target - value\r\n index = dirt.get(tmp_num2)\r\n if (index != None and index != i):\r\n return [i, index]\r\n\r\ntmp = [2,5,5,11]\r\nresult= []\r\nsolve = Solution()\r\nresult = solve.twoSum(tmp, 10)\r\nfor index in result:\r\n print(' ', index)\r\n\r\n","sub_path":"leetcode/01_twoSum2.py","file_name":"01_twoSum2.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"106113226","text":"from . import base_synth\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import *\nfrom IPython.display import (\n Audio, display, clear_output)\nfrom functools import partial\n\nfrom scipy.signal import find_peaks\nfrom scipy.io import wavfile\nfrom scipy.fftpack import fft\nfrom scipy import signal\n\nfrom scipy.interpolate import pchip\n\nclass cello(base_synth):\n\n def __init__(self,f0,fs,duration,*args):\n \n MAXFREC=20000\n BASEFREC=220\n harmheight=0.01\n MDIST=50\n \n rate,note=wavfile.read(\"synths\\Audios\\A3cello.wav\")\n L=len(note)/rate\n \n yf=fft(note,rate)[0:MAXFREC]\n normyf=abs(yf)/np.amax(abs(yf))\n \n peaks,values=find_peaks(normyf,height=harmheight,distance=BASEFREC/10)\n \n f,t,Sxx=signal.spectrogram(note,fs=rate,window=\"hamming\",scaling='spectrum',nperseg=int(rate/BASEFREC))\n \n t2=np.linspace(0,duration,int(fs * duration))\n out=np.zeros(int(fs*duration))\n\n nSxx=np.zeros((len(Sxx)+1,len(t)+1))\n nt=np.concatenate(([0],t))\n \n for i in range(0,len(Sxx)):\n Sxx[i]=Sxx[i]/np.amax(Sxx[i]) \n nSxx[i]=np.concatenate(([0],Sxx[i]))\n \n for i in range(0,len(peaks)):\n \n npe,nva=find_peaks(Sxx[int(peaks[i]/BASEFREC)],distance=MDIST/nt[-1]) \n test1=Sxx[int(peaks[i]/BASEFREC)][npe]\n test2=nt[npe]\n env=pchip(test2*duration/L,test1*duration/L)\n out+=np.sin(peaks[i]*2*np.pi*t2*f0/BASEFREC)*abs(normyf[peaks[i]])*abs(env(t2))\n \n \n self.wavData = out\n mx = 1.059*(max(abs(self.wavData)))\n self.wavData = self.wavData/mx\n \n \n","sub_path":"synths/cello.py","file_name":"cello.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"158676704","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport pyexcel\n\n#1 Connect to the page\nurl = 'https://dantri.com.vn/' \nconn = urlopen(url)\n\n\n#2.download the page content\nraw_data = conn.read()\npage = raw_data.decode('utf8')\n\n\n# with open('dantri.html', 'wb') as f:\n# f.write(raw_data)\n\n\n\n#3. find ROI region\nsoup = BeautifulSoup(page, 'html.parser')\nul = soup.find('ul', 'ul1 ulnew')\n# print(ul.prettify())\n\n#4.Extract data\n\nli_list = ul.find_all('li')\nnews_list = []\nfor li in li_list:\n a = li.h4.a\n title = a.string\n link = url + a['href']\n\n new = {\n 'title': title,\n 'link': link,\n }\n news_list.append(new)\n \n\n# print(a.string)\n# print(a['href'])\n#5. save data\npyexcel.save_as(records = news_list, dest_file_name=\"my_file.xls\")\n","sub_path":"Lab2/dantri.py","file_name":"dantri.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"585832044","text":"import sys\r\nimport tkinter as tk\r\nfrom tkinter import *\r\nfrom client import *\r\nfrom random import randint\r\n\r\nclt=None\r\n\r\nwindow=tk.Tk()\r\nwindow.title(\"Client Console\")\r\n\r\nFrame1=tk.Frame(window,highlightbackground=\"black\",highlightthickness=1)\r\nFrame1.grid(row=0,column=0,rowspan=4, sticky=tk.W+tk.E)\r\nl1=tk.Label(Frame1,text=\"Enter Port Number\")\r\nl1.grid(row=3,column=0,sticky = W,pady = 2)\r\n\r\ne1 = tk.Text(Frame1, width=20, height=2)\r\ne1.insert(tk.END,\"1115\")\r\ne1.delete(1.0, tk.END)\r\ne1.grid(row = 3, column = 1, pady = 2)\r\n\r\ndef start_clt():\r\n port=e1.get(1.0,tk.END)\r\n global clt\r\n if clt == None:\r\n clt=Client(int(port))\r\n clt.startListening()\r\n clt.startclient()\r\n\r\nb1=tk.Button(Frame1,text=\"Start Client\",command=start_clt)\r\nb1.grid(row=5,column=0,pady = 2,sticky=tk.W+tk.E)\r\n\r\ndef stop_clt():\r\n clt.stopclient()\r\n\r\nb3=tk.Button(Frame1,text=\"Stop Client\",command=stop_clt)\r\nb3.grid(row=5,column=1,sticky=tk.W+tk.E,pady = 2)\r\n\r\n\r\n\r\nFrame2=tk.Frame(window,highlightbackground=\"black\",highlightthickness=1)\r\nFrame2.grid(row=5,column=0,rowspan=8, sticky=tk.W+tk.E)\r\n\r\nl5=tk.Label(Frame2,text=\"Transaction console\")\r\nl2=tk.Label(Frame2,text=\"Enter Your Account Name\")\r\nl3=tk.Label(Frame2,text=\"Enter Beneficiary Name\")\r\nl4=tk.Label(Frame2,text=\"Enter Amount\")\r\n\r\n\r\nl5.grid(row=0,columnspan=2,sticky=tk.W+tk.E)\r\nl2.grid(row=1,column=0,sticky=W)\r\nl3.grid(row=2,column=0,sticky=W)\r\nl4.grid(row=3,column=0,sticky=W)\r\n\r\ne2 = tk.Text(Frame2, width=20, height=2)\r\ne2.delete(1.0, tk.END)\r\ne3 = tk.Text(Frame2, width=20, height=2)\r\ne3.delete(1.0, tk.END)\r\ne4 = tk.Text(Frame2, width=20, height=2)\r\ne4.delete(1.0, tk.END)\r\n\r\ne2.grid(row = 1, column = 1,sticky = W, pady = 2)\r\ne3.grid(row = 2, column = 1,sticky = W, pady = 2)\r\ne4.grid(row = 3, column = 1,sticky = W, pady = 2)\r\n\r\ndef transaction():\r\n trans=str(str(e2.get(1.0,'end-1c'))+\" \"+str(e3.get(1.0,'end-1c'))+\" \"+str(e4.get(1.0,tk.END)))\r\n print(trans)\r\n chese=clt.cheeseChain.createCheese(str(trans+'\\n'))\r\n if chese !=-1:\r\n clt.bradcastchain(chese.id)\r\n\r\nb2=tk.Button(Frame2,text=\"Make Transaction\",command=transaction)\r\nb2.grid(row=4,columnspan=2,sticky=tk.W+tk.E,pady = 2)\r\n\r\n\r\n\r\nFrame3=tk.Frame(window,highlightbackground=\"black\",highlightthickness=1)\r\nFrame3.grid(row=0,column=1,rowspan=8, sticky=tk.W+tk.E)\r\n\r\ndef print_cheese():\r\n print(clt.cheeseChain)\r\n\r\n\r\ntxt_output = tk.Text(Frame3);\r\nprintcheese=tk.Button(Frame3,text=\"Print Cheese Chain\",command=print_cheese)\r\nprintcheese.grid(row=0)\r\ntxt_output.grid(row=1,sticky = W,rowspan=7)\r\n\r\nclass stdoutRedirector:\r\n def __init__(self, tkwidget):\r\n self.tkwidget = tkwidget\r\n\r\n def write(self, string):\r\n self.tkwidget.insert('end', string)\r\n self.tkwidget.see('end')\r\n\r\nsys.stdout = stdoutRedirector(txt_output)\r\n\r\nwindow.geometry('900x400')\r\nwindow.mainloop()\r\n\r\n","sub_path":"ClientConsole.py","file_name":"ClientConsole.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"140950117","text":"from django.conf.urls.defaults import *\nfrom views import *\n\nurlpatterns = patterns('',\n url(r'^cart/$', cart_details, name='cart_details'),\n url(r'^cart/edit/$', ajax_cart_edit, name='ajax_cart_edit'),\n url(r'^cart/count/$', ajax_get_cart_count, name='ajax_get_cart_count'),\n url(r'^orders/$', order_list, name='order_list'),\n url(r'^order/create/$', order_create, name='order_create'),\n url(r'^order/delete/(?P[^//]+)/$', order_delete, name='order_delete'),\n url(r'^order/details/(?P[^//]+)/$', order_details, name='order_details'),\n url(r'^order/cancel/(?P[^//]+)/$', order_cancel, name='order_cancel'),\n url(r'^order/print/(?P[^//]+)/$', order_print, name='order_print'),\n url(r'^order/adminedit/(?P[^//]+)/$', order_adminedit, name='order_adminedit'),\n\n)\n","sub_path":"apps/orders/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"217726185","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/loup/Workspace/Projects/personal/palmer/palmer/response.py\n# Compiled at: 2016-11-16 03:39:02\n# Size of source mod 2**32: 1369 bytes\nfrom __future__ import unicode_literals\nimport datetime\nfrom flask import request, Response\nfrom flask._compat import text_type, string_types\nfrom palmer.utils import http_statuses\n\nclass APIResponse(Response):\n\n def __init__(self, content=None, *args, **kwargs):\n super(APIResponse, self).__init__(None, *args, **kwargs)\n self.response_at = datetime.datetime.utcnow()\n media_type = None\n if isinstance(content, (list, dict, text_type, string_types)):\n renderer = request.renderer\n media_type = renderer.media_type\n if self.status_code == http_statuses.HTTP_204_NO_CONTENT:\n self.status_code = http_statuses.HTTP_200_OK\n content = self.get_cleaned_content(content)\n content = renderer.render(content, media_type)\n if content is None:\n content = []\n if isinstance(content, (text_type, bytes, bytearray)):\n self.set_data(content)\n else:\n self.response = content\n if media_type is not None:\n self.headers['Content-Type'] = str(media_type)\n\n def get_cleaned_content(self, content):\n return dict(request_at=request.request_at, response_at=self.response_at, status_code=self.status_code, result=content)","sub_path":"pycfiles/palmer-0.0.4.tar/response.cpython-35.py","file_name":"response.cpython-35.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"526534699","text":"# Removing outliers using a StatisticalOutlierRemoval filter\n# http://pointclouds.org/documentation/tutorials/statistical_outlier.php#statistical-outlier-removal\n\nimport pcl\n\np = pcl.load(\"table_scene_lms400.pcd\")\n\nfil = p.make_statistical_outlier_filter()\nfil.set_mean_k(50)\nfil.set_std_dev_mul_thresh(1.0)\n\npcl.save(fil.filter(), \"table_scene_lms400_inliers.pcd\")\n\nfil.set_negative(True)\npcl.save(fil.filter(), \"table_scene_lms400_outliers.pcd\")\n","sub_path":"examples/official/Filtering/statistical_removal.py","file_name":"statistical_removal.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"350916330","text":"# -*- coding:utf-8 -*-\r\n# Author: washing\r\n# DateTime: 2022/8/16 10:40\r\n# File: 1656.py\r\n# Desc: \r\n\r\n\r\nclass OrderedStream:\r\n\r\n def __init__(self, n: int):\r\n self.l = [''] * n\r\n self.pos = 0\r\n\r\n def insert(self, idKey: int, value: str) -> List[str]:\r\n ret = []\r\n self.l[idKey-1] = value\r\n pos = self.pos\r\n while pos < len(self.l) and self.l[pos] != '':\r\n ret.append(self.l[pos])\r\n pos += 1\r\n if ret: self.pos = pos\r\n return ret\r\n\r\n\r\n\r\n# Your OrderedStream object will be instantiated and called as such:\r\n# obj = OrderedStream(n)\r\n# param_1 = obj.insert(idKey,value)\r\n","sub_path":"Solutions/1656/1656.py","file_name":"1656.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"350892000","text":"def run(app, db, c, json):\n @app.route(\"/stat/create\", methods=[\"POST\"])\n async def create(request):\n c.stat.create(db, request)\n return json({\"message\": \"success\"})\n\n @app.route(\"/stat\", methods=[\"GET\"])\n async def read(request):\n return json({\"response\": c.stat.read(db, request)})\n\n @app.route(\"/stat\", methods=[\"POST\"])\n async def update(request):\n c.stat.update(db, request)\n return json({\"message\": \"success\"})\n\n @app.route(\"/stat\", methods=[\"DELETE\"])\n async def delete(request):\n c.stat.delete(db, request)\n return json({\"message\": \"success\"})\n","sub_path":"routes/stat.py","file_name":"stat.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128781010","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n\n[env]\n# Conda Environment\nconda create --name nft_insights python=3.9.7\nconda info --envs\nsource activate nft_insights\nsource activate eda_made_easy\nconda deactivate\n# if needed to remove\nconda env remove -n [NAME_OF_THE_CONDA_ENVIRONMENT]\n\n[path]\ncd /Users/brunoflaven/Documents/03_git/BlogArticlesExamples/nft_insights/010_frida_kahlo_project/\n\n# CAUTION\n# check \"Generate Amount\": 55, # fix the amount for NFT in config.py\n# remove the output dir before\nrm -R output\n\n[file]\npython generator.py\n\n[source]\nhttps://github.com/DavidGameDev/py-nft-generator\n\n\n[required]\n# install\npip install numpy\npip install pillow\npip install streamlit\npip install watchdog\npip install python-dotenv\n\n# show what the requirements\npip freeze > nft_image_generator_requirements_1.txt\npip install -r nft_image_generator_requirements_1.txt\n\n\n\"\"\"\n\n\nimport os\nfrom pathlib import Path\nfrom PIL import Image\nfrom random import randint\nimport json\n\nfrom config import config\n\n###########################################\n# VARIABLE DECLARATION AND INITIALIZATION #\n###########################################\n\n#Load in all the Configuration for easier use\ndir = config[\"Trait Directory\"]\noutputDir = config[\"Output Directory\"]\noutputName = config[\"Output NFT Name\"]\njsonName = config[\"Output JSON Name\"]\namountToGen = config[\"Generate Amount\"]\nimageSize = config[\"Image Size\"]\nuseWeightedDistribution = config[\"Weighted Distribution\"]\ncanBeEmpty = config[\"Can Generate Empty\"]\ntraitData = config['Trait Data']\n\n#Declare and Initialize Variables\ntraits = traitData.keys()\nstatsTraits = {}\nnfts = {}\ncount = {}\nmaxGen = 0\nposition = [0,0]\ngenerated = [0]*amountToGen\n\n\n#Count all Possibilities for each Trait AND calculate Maximum non-duplicate Possibilities\nfor trait in traits:\n\tcount[trait] = len([item for item in os.listdir(dir + '/' + trait)])\n\tif trait in canBeEmpty:\n\t\tcount[trait] += 1\n\tmaxGen = count[trait] if maxGen == 0 else maxGen * count[trait]\n\nprint(\"Maximum is \"+str(maxGen))\n\n#Make sure no more NFTs are generated then possible [Prevent Duplicates]\nif amountToGen > maxGen:\n\tamountToGen = maxGen\n\n####################\n# HELPER FUNCTIONS #\n####################\n\n'''\nUpdate Statistics of Traits in Dictionary with Label instead of Int [getTraitLabel]\n@param trait - Name of the Trait\n@param id - Trait Index\n'''\ndef addStat(trait, id):\n\ttraitName = getTraitLabel(trait, id)\n\tif (trait in statsTraits):\n\t\tif traitName in statsTraits[trait]:\n\t\t\tstatsTraits[trait][traitName] += 1\n\t\telse:\n\t\t\tstatsTraits[trait][traitName] = 1\n\telse:\n\t\tstatsTraits[trait] = {}\n\t\tstatsTraits[trait][traitName] = 1\n\n'''\nReturn the Trait Index from all the weighted Pairs\n@param , )>pairs - [(Weight, Trait Index), ...]\n@return \n'''\ndef weighted_random(pairs):\n total = sum(pair[0] for pair in pairs)\n r = randint(1, total)\n for (weight, value) in pairs:\n r -= weight\n if r <= 0: return value\n\n'''\nGet All Trait Weight Distribution Pairs(Weight, Trait Index) for one Trait\n@param trait - Trait Name\n@return [Pair(Wieght, Trait Index), ...]\n'''\ndef getWeight(trait):\n\tdata = traitData[trait]\n\tpairs = [0] * len(data)\n\tfor i, trait in enumerate(data):\n\t\tpairs[i] = (trait[\"weight\"], i)\n\treturn pairs\n\n'''\nGet the Trait Label\n@param trait - Trait Name\n@param id - Trait Index\n@return \n'''\ndef getTraitLabel(trait, id):\n\treturn traitData[trait][id][\"label\"]\n\n'''\nGet Trait Filename\n@param trait - Trait Name\n@param id - Trait Index\n@return \n'''\ndef getTraitFile(trait, id):\n\treturn traitData[trait][id][\"file\"]\n\n\n'''\nGenerate a NFT with random Traits\n@return {\"traits\": {Trait: Trait Index, ...} \"gen\": NFT 'Hash'}\n'''\ndef generateNftTraits():\n\tnft = {}\n\tgen = ''\n\tfor trait in traits:\n\t\ttraitId = None\n\n\t\t#Choose wheter to use Trait Weighted Distribution or not\n\t\tif useWeightedDistribution:\n\t\t\ttraitId = weighted_random(getWeight(trait))\n\t\telse:\n\t\t\ttraitId = randint(1, count[trait]) - 1 if trait in canBeEmpty else randint(0, count[trait] - 1)\n\n\t\tnft[trait] = traitId\n\t\t#Generate a NFT 'Hash' for Duplication Check '...'\n\t\tgen = (f'{gen}{traitId}')\n\treturn {\"traits\": nft, \"gen\": gen}\n\n'''\nGenerate a NFT with Trait Labels instead of Trait Indices [getTraitLabel]\n@param nft - {Trait: Trait Index, ...}\n@return {Trait: Trait Label, ...}\n'''\ndef getJsonNft(nft):\n\tjsonNft = {}\n\tfor trait in traits:\t\t\n\t\t\ttraitId = nft[trait]\n\t\t\tjsonNft[trait] = getTraitLabel(trait, traitId)\n\treturn jsonNft\n\n#Make sure the Output Directory exists, if not, create one \nPath(outputDir).mkdir(parents=True, exist_ok=True)\n\n#################\n# NFT GENERATOR #\n#################\n\n'''\nGenerate NFTs until the specified Amount is reached [Generate Amount]\nPrevent Duplicates\nOutput Images\n'''\ncounter = 1\nwhile len([item for item in os.listdir(outputDir)]) < amountToGen:\n\tid = counter\n\n\t#Generate NFT with random Traits\n\tgeneratedNft = generateNftTraits()\n\tnft = generatedNft[\"traits\"]\n\tgen = generatedNft[\"gen\"]\n\n\t#Check for Duplicates\n\tif gen in generated:\n\t\t#Skip Duplicate\n\t\tprint(\"Duplicate found\")\n\telse:\n\t\t#Generate blank NFT Image\n\t\trender = Image.new('RGBA', imageSize)\n\n\t\t#Go through each Trait and generate the final NFT Image\n\t\tfor trait in traits:\t\t\n\t\t\ttraitId = nft[trait]\n\n\t\t\t#Update Statistics Dictionary\n\t\t\taddStat(trait, traitId)\n\n\t\t\t#Get Trait Image File and Merge it with the existing NFT Image\n\t\t\tfile = getTraitFile(trait, traitId)\n\t\t\tif file != \"\":\n\t\t\t\timage = Image.open(f'{dir}/{trait}/{getTraitFile(trait, traitId)}.png').convert(\"RGBA\")\n\t\t\t\trender.paste(image, position, mask=image)\n\t\t\n\t\t#Save current NFT 'Hash' for next Duplicate Check\n\t\tgenerated[id - 1] = gen\t\t\n\n\t\t#Add NFT with Trait Labels to NFTs Dictionary\n\t\tnfts[id] = getJsonNft(nft)\n\n\t\t#Output NFT Image\n\t\trender.save(f'{outputDir}/{outputName}{id}.png')\n\n\t\t#Increase ID Counter\n\t\tcounter += 1\n\t\t\t\n\n\n#####################\n# STATISTICS OUTPUT #\n#####################\n\n#Prepare Statistics for easier use later\ndata = {\n\t\"statistics\": statsTraits,\n\t\"nfts\": nfts\n}\n\n#Output the JSON File with all Statistics and NFTs Information\nwith open(f'./{outputDir}/{jsonName}.json', 'w') as outfile:\n\tjson.dump(data, outfile)\n\n","sub_path":"nft_insights/010_frida_kahlo_project/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":6292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"114415335","text":"from keras.models import Sequential\nfrom keras.layers.core import Flatten\nfrom keras.layers.core import Dense\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\n\n\nclass LeNet:\n @staticmethod\n def build(width, height, depth, classes):\n input_shape = (height, width, depth)\n\n model = Sequential([\n # 1st conv layer\n Conv2D(20, (5, 5), input_shape=input_shape,\n activation='relu', padding='same'),\n MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n # 2nd conv layer\n Conv2D(50, (5, 5), activation='relu', padding='same'),\n MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n # 1st FC layer\n Flatten(),\n Dense(500, activation='relu'),\n # 2nd FC layer\n Dense(classes, activation='softmax')\n ])\n\n return model\n","sub_path":"pyimagesearch/nn/conv/lenet.py","file_name":"lenet.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"311120550","text":"#!/usr/bin/env python\n\n# author : Stepan Ruzicka\n# date : 2018.11.22\n\nimport sys\nimport os\nimport argparse\nimport xmltodict\nfrom argparse import RawTextHelpFormatter\nfrom collections import OrderedDict\n\n# script context variables\nSCRIPT_FOLDER_PATH = os.path.dirname(os.path.realpath(__file__))\nCURRENT_WORKING_PATH = os.getcwd()\nthis = sys.modules[__name__]\nSCRIPT_NAME = os.path.basename(__file__)\n\n# default config values\nDEBUG = False\n\ndef print_info(info):\n if(DEBUG):\n print(info)\n\ndef update_package_xml_dict(original_package_xml_map, update_package_xml_map, version = None):\n if not original_package_xml_map:\n original_package_xml_map = update_package_xml_map\n else:\n if 'Package' in original_package_xml_map and 'Package' in update_package_xml_map and '@xmlns' in update_package_xml_map['Package'] and 'version' in update_package_xml_map['Package']:\n if original_package_xml_map['Package']['@xmlns'] != update_package_xml_map['Package']['@xmlns']:\n # raise exception\n raise SystemExit('Different metadata namespaces! Please align metadata namespace first.')\n \n if version is not None:\n original_package_xml_map['Package']['version'] = version\n elif original_package_xml_map['Package']['version'] != update_package_xml_map['Package']['version']:\n # raise exception\n raise SystemExit('Different API versions! Please specify the result API version.')\n \n\n for type_name in update_package_xml_map['Package']['types']:\n if type_name in original_package_xml_map['Package']['types']:\n original_list = original_package_xml_map['Package']['types'][type_name]\n update_list = update_package_xml_map['Package']['types'][type_name]\n original_package_xml_map['Package']['types'][type_name] = original_list + list(set(update_list) - set(original_list))\n else:\n original_package_xml_map['Package']['types'][type_name] = update_package_xml_map['Package']['types'][type_name]\n else:\n raise SystemExit('Source package.xml is missing one of the required elements. Please check it contains \\'Package\\', \\'xmlns\\' and \\'version\\'')\n\n return original_package_xml_map\n\ndef convert_package_xml_dict_to_map(package_xml_dict):\n package_xml_map = OrderedDict()\n if 'Package' in package_xml_dict:\n package_xml_map['Package'] = OrderedDict()\n root = package_xml_dict['Package']\n for element in root:\n # root element attributes\n if element in ['@xmlns', 'version']:\n package_xml_map['Package'][element] = root[element]\n # root child elements\n elif element == 'types':\n if 'types' not in package_xml_map['Package']:\n package_xml_map['Package']['types'] = OrderedDict()\n\n types = package_xml_map['Package']['types']\n\n # if list then more then one type\n if type(root[element]) is list:\n for type_child in root[element]:\n members = []\n for key in type_child:\n if key == 'name':\n name = type_child[key]\n elif key == 'members':\n if type(type_child[key]) is list:\n # add list of members\n members.extend(type_child[key])\n else:\n # add one member\n members.append(type_child[key])\n else:\n raise SystemExit(('Child element of Type: ' + color_string('{}', Color.RED) + ' not recognized!').format(key))\n \n types[name] = members\n # one type only\n else:\n type_child = root[element]\n members = []\n for key in type_child:\n if key == 'name':\n name = type_child[key]\n elif key == 'members':\n members.append(type_child[key])\n if name:\n types[name] = members\n else:\n raise SystemExit(('Child element \\'Name\\' is missing!'))\n else:\n raise SystemExit(('Element ' + color_string('{}', Color.RED) + ' not recognized!').format(element))\n return package_xml_map\n\ndef convert_package_xml_map_to_dict(package_xml_map):\n package_xml_dict = OrderedDict()\n\n if 'Package' in package_xml_map:\n package_xml_dict['Package'] = OrderedDict()\n root = package_xml_map['Package']\n for element in root:\n # root element attributes\n if element in ['@xmlns', 'version']:\n package_xml_dict['Package'][element] = root[element]\n elif element == 'types':\n for type_name in root[element]:\n if element not in package_xml_dict['Package']:\n package_xml_dict['Package'][element] = []\n # xmltodict expects the xml in a specific format \n type_name_tuple = tuple(('name', type_name))\n type_members_tuple = tuple(('members', root[element][type_name]))\n type_array = []\n type_array.append(type_members_tuple)\n type_array.append(type_name_tuple)\n type_ordered_dict = OrderedDict(type_array)\n package_xml_dict['Package'][element].append(type_ordered_dict)\n else:\n raise SystemExit(('Element ' + color_string('{}', Color.RED) + ' not recognized!').format(element))\n return package_xml_dict\n\ndef main():\n parser = argparse.ArgumentParser(description='Merges Salesforce package.xml files.\\n' +\n 'Example:\\n' +\n '\\t' + os.path.basename(__file__),\n\t\t\t\t\t\tformatter_class=RawTextHelpFormatter)\n\n parser.add_argument(\n \"-d\", \"--debug\", dest=\"debug\",\n help=\"Debug mode\", action=\"store_true\")\n\n parser.add_argument(\n \"-o\", \"--output\", dest=\"output\",\n help=\"Output file\")\n\n parser.add_argument(\n \"-v\", \"--version\", dest=\"version\",\n help=\"Result Metadata API version\")\n\n parser.add_argument(\n \"items\", nargs=\"*\",\n help=\"package.xml list\")\n\n args = parser.parse_args()\n\n # arguments assignment to global variables\n this.DEBUG = args.debug\n \n # init\n merged_package_xml_map = {}\n first_package_xml_file = None\n for item in args.items:\n # check if the xml file exists\n if not os.path.isfile(item):\n raise SystemExit(('File ' + color_string('{}', Color.RED) + ' doesn\\'t exist!').format(args.item))\n else:\n package_xml_dict = {}\n with open(item) as package_xml_file:\n print_info(\"Parsing file \" + item)\n package_xml_dict = xmltodict.parse(package_xml_file.read())\n package_xml_map = convert_package_xml_dict_to_map(package_xml_dict)\n\n if first_package_xml_file is None:\n first_package_xml_file = item\n else:\n print_info(\"Updating file \" + first_package_xml_file + \" with \" + item)\n\n if args.version:\n print_info(\"Updating result version to \" + args.version)\n merged_package_xml_map = update_package_xml_dict(merged_package_xml_map, package_xml_map, args.version)\n else:\n merged_package_xml_map = update_package_xml_dict(merged_package_xml_map, package_xml_map)\n\n merged_package_xml_dict = convert_package_xml_map_to_dict(merged_package_xml_map)\n\n if args.output:\n print_info(\"Writing result to \" + args.output)\n outputfile = open(args.output, \"w\")\n else:\n print_info(\"Writing result to standard output.\")\n outputfile = sys.stdout\n\n xml_text = xmltodict.unparse(merged_package_xml_dict, output = outputfile, encoding = 'UTF-8', pretty = True, indent = \" \")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/merge_package_xml.py","file_name":"merge_package_xml.py","file_ext":"py","file_size_in_byte":8018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"457131911","text":"import platform\r\nfrom socket import *\r\n\r\nserverPort = 8001\r\nclientSocket = socket(AF_INET, SOCK_STREAM)\r\nserverName = platform.uname()[1]\r\nclientSocket.connect((serverName,serverPort))\r\nwhile True:\r\n\tsentence = input('Input lowercase sentence: ')\r\n\tif sentence == None or len(sentence) <= 1:\r\n\t\tprint(\"cannot read from server\")\r\n\telse:\r\n\t\tclientSocket.send(bytes(sentence,'utf-8'))\r\n\t\tmodifiedSentence = clientSocket.recv(1024).decode(\"utf-8\")\r\n\t\tprint('From Server:', modifiedSentence)\r\nclientSocket.close()","sub_path":"TCPClient.py","file_name":"TCPClient.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234568021","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Forms for scheduling actions.\"\"\"\n\nimport datetime\nfrom builtins import object\n\nimport pytz\nfrom bootstrap_datepicker_plus import DateTimePickerInput\nfrom django import forms\nfrom django.conf import settings\nfrom django.utils.dateparse import parse_datetime\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ontask import is_correct_email\nfrom ontask.core.forms import FormWithPayload, date_time_widget_options\nfrom ontask.dataops.sql.row_queries import get_rows\nfrom ontask.models import Column, ScheduledAction\n\n\nclass ScheduleBasicForm(FormWithPayload, forms.ModelForm):\n \"\"\"Form to create/edit objects of the ScheduleAction.\n\n To be used for the various types of actions.\n \"\"\"\n action = None\n\n def __init__(self, form_data, *args, **kwargs):\n \"\"\"Set item_column values.\"\"\"\n self.action = kwargs.pop('action')\n\n # Call the parent constructor\n super().__init__(form_data, *args, **kwargs)\n\n self.set_fields_from_dict(['name', 'description_text'])\n self.fields['execute'].initial = parse_datetime(\n self._FormWithPayload__form_info.get('execute', ''))\n\n def clean(self):\n \"\"\"Verify that the date is corre ct.\"\"\"\n form_data = super().clean()\n\n self.store_fields_in_dict([\n ('name', None),\n ('description_text', None),\n ('execute', str(form_data['execute']))])\n\n # The executed time must be in the future\n now = datetime.datetime.now(pytz.timezone(settings.TIME_ZONE))\n when_data = self.cleaned_data.get('execute')\n if when_data and when_data <= now:\n self.add_error(\n 'execute',\n _('Date/time must be in the future'))\n\n return form_data\n\n class Meta(object):\n \"\"\"Define model, fields and widgets.\"\"\"\n\n model = ScheduledAction\n fields = ('name', 'description_text', 'execute')\n widgets = {\n 'execute': DateTimePickerInput(options=date_time_widget_options),\n }\n\n\nclass ScheduleMailSubjectForm(FormWithPayload):\n subject = forms.CharField(\n initial='',\n label=_('Email subject'),\n strip=True,\n required=True)\n\n def __init__(self, form_data, *args, **kwargs):\n \"\"\"Set subject value.\"\"\"\n # Call the parent constructor\n super().__init__(form_data, *args, **kwargs)\n\n self.set_field_from_dict('subject')\n\n def clean(self):\n form_data = super().clean()\n self.store_field_in_dict('subject')\n return form_data\n\nclass ScheduleMailCCForm(FormWithPayload):\n cc_email = forms.CharField(\n initial='',\n label=_('CC Emails (separated by spaces)'),\n strip=True,\n required=False)\n\n bcc_email = forms.CharField(\n initial='',\n label=_('List of BCC Emails (separated by spaces)'),\n strip=True,\n required=False)\n\n instance = None\n\n def __init__(self, form_data, *args, **kwargs):\n \"\"\"Set cc and bcc data.\"\"\"\n # Call the parent constructor\n super().__init__(form_data, *args, **kwargs)\n\n self.set_fields_from_dict(['cc_email', 'bcc_email'])\n\n def clean(self):\n \"\"\"Verify that the date is correct.\"\"\"\n form_data = super().clean()\n\n self.store_fields_in_dict([\n (\n 'cc_email',\n (' ').join([\n email.strip()\n for email in form_data['cc_email'].split() if email\n ])\n ),\n (\n 'bcc_email',\n (' ').join([\n email.strip()\n for email in form_data['bcc_email'].split() if email\n ])\n )])\n\n if not all(\n is_correct_email(email) for email in form_data['cc_email'].split()\n ):\n self.add_error(\n 'cc_email',\n _('This field must be a comma-separated list of emails.'))\n\n if not all(\n is_correct_email(email) for email in form_data['bcc_email'].split()\n ):\n self.add_error(\n 'bcc_email',\n _('This field must be a comma-separated list of emails.'))\n\n return form_data\n\n\nclass ScheduleItemsForm(ScheduleBasicForm):\n \"\"\"Form to handle item_column and confirm_items fields.\"\"\"\n item_column = forms.ModelChoiceField(queryset=Column.objects.none())\n\n confirm_items = forms.BooleanField(\n initial=False,\n required=False,\n label=_('Check/exclude email addresses before scheduling?'),\n )\n\n def __init__(self, form_data, *args, **kwargs):\n \"\"\"Set item_column values.\"\"\"\n columns = kwargs.pop('columns')\n\n # Call the parent constructor\n super().__init__(form_data, *args, **kwargs)\n\n self.set_field_from_dict('confirm_items')\n # Special case: get the column from the name\n self.fields['item_column'].queryset = columns\n column_name = self._FormWithPayload__form_info.get('item_column')\n if column_name:\n column = self.action.workflow.columns.get(name=column_name)\n self.fields['item_column'].initial = column.pk\n\n def clean(self):\n form_data = super().clean()\n\n self.store_fields_in_dict([\n ('item_column', form_data['item_column'].name),\n ('confirm_items', None)])\n\n item_column = self.cleaned_data['item_column']\n\n # Check if the values in the email column are correct emails\n try:\n column_data = get_rows(\n self.action.workflow.get_data_frame_table_name(),\n column_names=[item_column.name])\n if not all(\n is_correct_email(row[item_column.name]) for row in column_data\n ):\n # column has incorrect email addresses\n self.add_error(\n 'item_column',\n _('The column with email addresses has incorrect values.'))\n except TypeError:\n self.add_error(\n 'item_column',\n _('The column with email addresses has incorrect values.'))\n\n return form_data\n\n class Meta(ScheduleBasicForm.Meta):\n \"\"\"Define model, fields and widgets.\"\"\"\n\n fields = ('name', 'description_text', 'item_column', 'execute')\n\n\nclass ScheduleTokenForm(FormWithPayload):\n # Token to use when sending the JSON request\n token = forms.CharField(\n initial='',\n label=_('Authentication Token'),\n strip=True,\n required=True,\n help_text=_('Authentication token provided by the external platform.'),\n widget=forms.Textarea(\n attrs={\n 'rows': 1,\n 'cols': 120,\n 'placeholder': _(\n 'Authentication token to be sent with the JSON object.'),\n }),\n )\n\n instance = None\n\n def __init__(self, form_data, *args, **kwargs):\n \"\"\"Set label and required for the item_column field.\"\"\"\n # Call the parent constructor\n super().__init__(form_data, *args, **kwargs)\n\n self.set_field_from_dict('token')\n\n def clean(self):\n \"\"\"Store the values in the form info.\"\"\"\n form_data = super().clean()\n self.store_field_in_dict('token', None)\n return form_data\n\n\nclass EmailScheduleForm(\n ScheduleMailSubjectForm,\n ScheduleMailCCForm,\n ScheduleItemsForm,\n):\n \"\"\"Form to create/edit objects of the ScheduleAction of type email.\n\n One of the fields is a reference to a key column, which is a subset of\n the columns attached to the action. The subset is passed as the name\n arguments \"columns\" (list of key columns).\n\n There is an additional field to allow for an extra step to review and\n filter email addresses.\n \"\"\"\n\n send_confirmation = forms.BooleanField(\n initial=False,\n required=False,\n label=_('Send you a confirmation email'))\n\n track_read = forms.BooleanField(\n initial=False,\n required=False,\n label=_('Track if emails are read?'))\n\n def __init__(self, form_data, *args, **kwargs):\n \"\"\"Set additional field items.\"\"\"\n # Call the parent constructor\n super().__init__(form_data, *args, **kwargs)\n\n self.set_fields_from_dict(['send_confirmation', 'track_read'])\n self.fields['item_column'].label = _(\n 'Column in the table containing the email')\n\n self.order_fields([\n 'name',\n 'description_text',\n 'execute',\n 'item_column',\n 'subject',\n 'cc_email',\n 'bcc_email',\n 'confirm_items',\n 'send_confirmation',\n 'track_read'])\n\n def clean(self):\n \"\"\"Store the values in the form info.\"\"\"\n form_data = super().clean()\n self.store_fields_in_dict([\n ('send_confirmation', None),\n ('track_read', None)\n ])\n return form_data\n\n\nclass SendListScheduleForm(\n ScheduleMailSubjectForm, ScheduleMailCCForm, ScheduleBasicForm\n):\n \"\"\"Form to create/edit objects of the ScheduleAction of type send list.\"\"\"\n\n email_to = forms.CharField(label=_('Recipient'), required=True)\n\n def __init__(self, form_data, *args, **kwargs):\n \"\"\"Set additional field items.\"\"\"\n\n # Call the parent constructor\n super().__init__(form_data, *args, **kwargs)\n\n self.set_field_from_dict('email_to')\n\n self.order_fields([\n 'name',\n 'description_text',\n 'execute',\n 'email_to',\n 'subject',\n 'cc_email',\n 'bcc_email'])\n\n def clean(self):\n \"\"\"Process errors and add them to the form.\"\"\"\n form_data = super().clean()\n\n self.store_field_in_dict('email_to')\n\n if not is_correct_email(form_data['email_to']):\n self.add_error(\n 'email_to',\n _('This field must be a valid email address.'))\n\n return form_data\n\n\nclass JSONScheduleForm(ScheduleTokenForm, ScheduleItemsForm):\n \"\"\"Form to edit ScheduleAction of types JSON and JSON List.\"\"\"\n\n class Meta(ScheduleItemsForm.Meta):\n \"\"\"Redefine the order.\"\"\"\n\n fields = (\n 'name',\n 'description_text',\n 'execute',\n 'item_column',\n 'confirm_items',\n 'token')\n\n\nclass JSONListScheduleForm(ScheduleTokenForm, ScheduleBasicForm):\n \"\"\"Form to edit ScheduleAction of types JSON List.\"\"\"\n\n class Meta(ScheduleBasicForm.Meta):\n \"\"\"Redefine the order.\"\"\"\n\n fields = (\n 'name',\n 'description_text',\n 'execute',\n 'token')\n\n\nclass CanvasEmailScheduleForm(ScheduleMailSubjectForm, ScheduleItemsForm):\n \"\"\"Form to create/edit ScheduleAction of type canvas email.\"\"\"\n\n def __init__(self, form_data, *args, **kwargs):\n \"\"\"Assign item_column field.\"\"\"\n # Call the parent constructor\n super().__init__(form_data, *args, **kwargs)\n\n self.fields['item_column'].label = _(\n 'Column in the table containing the Canvas ID')\n\n class Meta(ScheduleItemsForm.Meta):\n \"\"\"Field order.\"\"\"\n\n fields = (\n 'name',\n 'description_text',\n 'item_column',\n 'confirm_items',\n 'subject',\n 'execute')\n","sub_path":"ontask/scheduler/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":11459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"486176128","text":"import json\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nimport sys\nsys.path.insert(0, './modules')\n\nimport rds\nimport ec2\nimport vpc\nimport s3\n\ndef main():\n price = [0,0]\n upfront = 0\n session = requests.Session()\n retry = Retry(connect=3, backoff_factor=0.5)\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n for _ in range(int(raw_input())):\n arr = map(str, raw_input().split(\"/\"))\n if (arr[0] == \"#\") or (arr[0] == \"\"):\n break\n else:\n if arr[0].lower() == \"rds\":\n region = arr[2].lower()\n r = session.get('https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonRDS/current/'+region+'/index.json')\n print(\"The detail of your option: %s\" % arr)\n if r.status_code == 200:\n offer = r.json()\n rdsprice = list(rds.main(arr,offer))\n if len(rdsprice) == 2:\n price[0] = price[0]+rdsprice[0]\n price[1] = price[1]+rdsprice[1]\n else:\n upfront = upfront + rdsprice[2]\n else:\n print(\"THE SERVICE RDS IS NOT AVAILABLE IN REGION %s\" % region)\n print(\"\\n\")\n elif arr[0].lower() == \"ec2\":\n region = arr[2].lower()\n r = session.get('https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/'+region+'/index.json')\n print(\"The detail of your option: %s\" % arr)\n if r.status_code == 200:\n offer = r.json()\n ec2price = list(ec2.main(arr,offer))\n if len(ec2price) == 2:\n price[0] = price[0]+ec2price[0]\n price[1] = price[1]+ec2price[1]\n else:\n upfront = upfront + ec2price[2]\n else:\n print(\"THE SERVICE EC2 IS NOT AVAILABLE IN REGION %s\" % region)\n print(\"\\n\")\n elif arr[0].lower() == \"vpc\":\n region = arr[2].lower()\n r = session.get('https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonVPC/current/'+region+'/index.json')\n print(\"The detail of your option: %s\" % arr)\n if r.status_code == 200:\n offer = r.json()\n vpcprice = list(vpc.main(arr,offer))\n if len(vpcprice) == 2:\n price[0] = price[0]+vpcprice[0]\n price[1] = price[1]+vpcprice[1]\n else:\n upfront = upfront + vpcprice[2]\n else:\n print(\"THE SERVICE VPC IS NOT AVAILABLE IN REGION %s\" % region)\n print(\"\\n\")\n elif arr[0].lower() == \"s3\":\n region = arr[2].lower()\n r = session.get('https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonS3/current/'+region+'/index.json')\n print(\"The detail of your option: %s\" % arr)\n if r.status_code == 200:\n offer = r.json()\n s3price = list(s3.main(arr,offer))\n if len(s3price) == 2:\n price[0] = price[0]+s3price[0]\n price[1] = price[1]+s3price[1]\n else:\n upfront = upfront + s3price[2]\n else:\n print(\"THE SERVICE S3 IS NOT AVAILABLE IN REGION %s\" % region)\n print(\"\\n\")\n print(\"Summary: \")\n print(\"The total hourly price for all your services is: $%s\" % price[0])\n print(\"The total monthly price for all your services is: $%s\" % price[1])\n if upfront != 0:\n print(\"The upfront for all your services is: $%s\" % upfront)\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"453158682","text":"import gi;gi.require_version('Gtk','3.0');from gi.repository import Gtk as gtk, GdkPixbuf, Gdk\nfrom MenuBar import *\nfrom Insetos import *\n\ndef Sol(self):\n\tself.Soly = gtk.Window()\n\tself.grid_result = gtk.Grid(column_spacing=6, row_spacing=6)\n\tself.Button = []\n\n\tscrolled = gtk.ScrolledWindow()\n\tscrolled.set_policy(gtk.PolicyType.NEVER, gtk.PolicyType.AUTOMATIC)\n\tscrolled.add(self.grid_result)\n\tself.Soly.add(scrolled)\n\tself.Soly.set_default_size(1000, 1000)\n\t\t\n\tfor c in range(len(self.label)):\n\t\tself.Button.append(gtk.Button())\n\t\n\t#Image0\n\tself.image0 = gtk.Image()\n\tpixbuf0 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto0.jpeg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image0.set_from_pixbuf(pixbuf0)\n\t\n\t#Image1\n\tself.image1 = gtk.Image()\n\tpixbuf1 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto1.jpeg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image1.set_from_pixbuf(pixbuf1)\n\n\t#image2\n\tself.image2= gtk.Image()\n\tpixbuf2 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto2.jpeg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image2.set_from_pixbuf(pixbuf2)\n\t\n\t#image3\n\tself.image3= gtk.Image()\n\tpixbuf3 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto3.jpeg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image3.set_from_pixbuf(pixbuf3)\n\n\t#image4\n\tself.image4= gtk.Image()\n\tpixbuf4 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto4.jpeg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image4.set_from_pixbuf(pixbuf4)\n\n\t#image5\n\tself.image5= gtk.Image()\n\tpixbuf5 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto5.jpeg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image5.set_from_pixbuf(pixbuf5)\n\n\t#image6\n\tself.image6= gtk.Image()\n\tpixbuf6 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto6.png', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image6.set_from_pixbuf(pixbuf6)\n\n\t#image7\n\tself.image7= gtk.Image()\n\tpixbuf7 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto7.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image7.set_from_pixbuf(pixbuf7)\n\n\t#image8\n\tself.image8= gtk.Image()\n\tpixbuf8 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto8.png', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image8.set_from_pixbuf(pixbuf8)\n\n\t#image9\n\tself.image9= gtk.Image()\n\tpixbuf9 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto9.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image9.set_from_pixbuf(pixbuf9)\n\n\t#image10\n\tself.image10= gtk.Image()\n\tpixbuf10 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto10.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image10.set_from_pixbuf(pixbuf10)\n\n\t#image11\n\tself.image11= gtk.Image()\n\tpixbuf11 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto11.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image11.set_from_pixbuf(pixbuf11)\n\n\t#image12\n\tself.image12= gtk.Image()\n\tpixbuf12 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto12.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image12.set_from_pixbuf(pixbuf12)\n\n\t#image13\n\tself.image13= gtk.Image()\n\tpixbuf13 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto13.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image13.set_from_pixbuf(pixbuf13)\n\n\t#image14\n\tself.image14= gtk.Image()\n\tpixbuf14 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto14.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image14.set_from_pixbuf(pixbuf14)\n\n\t#image15\n\tself.image15= gtk.Image()\n\tpixbuf15 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto15.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image15.set_from_pixbuf(pixbuf15)\n\n\t#image16\n\tself.image16= gtk.Image()\n\tpixbuf16 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto16.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image16.set_from_pixbuf(pixbuf16)\n\n\t#image17\n\tself.image17= gtk.Image()\n\tpixbuf17 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto17.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image17.set_from_pixbuf(pixbuf17)\n\n\t#image18\n\tself.image18= gtk.Image()\n\tpixbuf18 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto18.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image18.set_from_pixbuf(pixbuf18)\n\n\t#image19\n\tself.image19= gtk.Image()\n\tpixbuf19 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto19.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image19.set_from_pixbuf(pixbuf19)\n\n\t#image20\n\tself.image20= gtk.Image()\n\tpixbuf20 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto20.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image20.set_from_pixbuf(pixbuf20)\n\n\t#image21\n\tself.image21= gtk.Image()\n\tpixbuf21 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto21.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image21.set_from_pixbuf(pixbuf21)\n\n\t#image22\n\tself.image22= gtk.Image()\n\tpixbuf22 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto22.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image22.set_from_pixbuf(pixbuf22)\n\n\t#image23\n\tself.image23= gtk.Image()\n\tpixbuf23 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto23.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image23.set_from_pixbuf(pixbuf23)\n\n\t#image24\n\tself.image24= gtk.Image()\n\tpixbuf24 = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n\tfilename='Pics/inseto24.jpg', \n\twidth=250, \n\theight=250, \n\tpreserve_aspect_ratio=True)\n\tself.image24.set_from_pixbuf(pixbuf24)\n\t\n\t#Button0\n\tself.Button[0].add(self.image0)\n\tself.Button[0].set_size_request(100,100)\n\tself.Button[0].connect('clicked', lambda arg: Inseto0(self))\n\t#----------------------------------------\n\t#Button1\n\tself.Button[1].add(self.image1)\n\tself.Button[1].set_size_request(100,100)\n\tself.Button[1].connect('clicked', lambda arg: Inseto1(self))\n\t#----------------------------------------\n\t#Button2\n\tself.Button[2].add(self.image2)\n\tself.Button[2].set_size_request(100,100)\n\tself.Button[2].connect('clicked', lambda arg: Inseto2(self))\n\t#----------------------------------------\n\n\t#Button3\n\tself.Button[3].add(self.image3)\n\tself.Button[3].set_size_request(100,100)\n\tself.Button[3].connect('clicked', lambda arg: Inseto3(self))\n\t#----------------------------------------\n\n\t#Button4\n\tself.Button[4].add(self.image4)\n\tself.Button[4].set_size_request(100,100)\n\tself.Button[4].connect('clicked', lambda arg: Inseto4(self))\n\t#----------------------------------------\n\n\t#Button5\n\tself.Button[5].add(self.image5)\n\tself.Button[5].set_size_request(100,100)\n\tself.Button[5].connect('clicked', lambda arg: Inseto5(self))\n\t#----------------------------------------\t\n\n\t#Button6\n\tself.Button[6].add(self.image6)\n\tself.Button[6].set_size_request(100,100)\n\tself.Button[6].connect('clicked', lambda arg: Inseto6(self))\n\t#----------------------------------------\n\n\t#Button7\n\tself.Button[7].add(self.image7)\n\tself.Button[7].set_size_request(100,100)\n\tself.Button[7].connect('clicked', lambda arg: Inseto7(self))\n\t#----------------------------------------\t\n\n\t#Button8\n\tself.Button[8].add(self.image8)\n\tself.Button[8].set_size_request(100,100)\n\tself.Button[8].connect('clicked', lambda arg: Inseto8(self))\n\t#----------------------------------------\n\n\t#Button9\n\tself.Button[9].add(self.image9)\n\tself.Button[9].set_size_request(100,100)\n\tself.Button[9].connect('clicked', lambda arg: Inseto9(self))\n\t#----------------------------------------\n\n\t#Button10\n\tself.Button[10].add(self.image10)\n\tself.Button[10].set_size_request(100,100)\n\tself.Button[10].connect('clicked', lambda arg: Inseto10(self))\n\t#----------------------------------------\t\t\n\n\t#Button11\n\tself.Button[11].add(self.image11)\n\tself.Button[11].set_size_request(100,100)\n\tself.Button[11].connect('clicked', lambda arg: Inseto11(self))\n\t#----------------------------------------\t\t\n\n\t#Button12\n\tself.Button[12].add(self.image12)\n\tself.Button[12].set_size_request(100,100)\n\tself.Button[12].connect('clicked', lambda arg: Inseto12(self))\n\t#----------------------------------------\t\n\n\t#Button13\n\tself.Button[13].add(self.image13)\n\tself.Button[13].set_size_request(100,100)\n\tself.Button[13].connect('clicked', lambda arg: Inseto13(self))\n\t#----------------------------------------\t\n\n\t#Button14\n\tself.Button[14].add(self.image14)\n\tself.Button[14].set_size_request(100,100)\n\tself.Button[14].connect('clicked', lambda arg: Inseto14(self))\n\t#----------------------------------------\n\n\t#Button15\n\tself.Button[15].add(self.image15)\n\tself.Button[15].set_size_request(100,100)\n\tself.Button[15].connect('clicked', lambda arg: Inseto15(self))\n\t#----------------------------------------\t\t\n\n\t#Button16\n\tself.Button[16].add(self.image16)\n\tself.Button[16].set_size_request(100,100)\n\tself.Button[16].connect('clicked', lambda arg: Inseto16(self))\n\t#----------------------------------------\t\n\n\t#Button17\n\tself.Button[17].add(self.image17)\n\tself.Button[17].set_size_request(100,100)\n\tself.Button[17].connect('clicked', lambda arg: Inseto17(self))\n\t#----------------------------------------\t\n\n\t#Button18\n\tself.Button[18].add(self.image18)\n\tself.Button[18].set_size_request(100,100)\n\tself.Button[18].connect('clicked', lambda arg: Inseto18(self))\n\t#----------------------------------------\n\n\t#Button19\n\tself.Button[19].add(self.image19)\n\tself.Button[19].set_size_request(100,100)\n\tself.Button[19].connect('clicked', lambda arg: Inseto19(self))\n\t#----------------------------------------\t\n\n\t#Button20\n\tself.Button[20].add(self.image20)\n\tself.Button[20].set_size_request(100,100)\n\tself.Button[20].connect('clicked', lambda arg: Inseto20(self))\n\t#----------------------------------------\n\n\t#Button21\n\tself.Button[21].add(self.image21)\n\tself.Button[21].set_size_request(100,100)\n\tself.Button[21].connect('clicked', lambda arg: Inseto21(self))\n\t#----------------------------------------\n\n\t#Button22\n\tself.Button[22].add(self.image22)\n\tself.Button[22].set_size_request(100,100)\n\tself.Button[22].connect('clicked', lambda arg: Inseto22(self))\n\t#----------------------------------------\t\n\n\t#Button23\n\tself.Button[23].add(self.image23)\n\tself.Button[23].set_size_request(100,100)\n\tself.Button[23].connect('clicked', lambda arg: Inseto23(self))\n\t#----------------------------------------\t\n\n\t#Button24\n\tself.Button[24].add(self.image24)\n\tself.Button[24].set_size_request(100,100)\n\tself.Button[24].connect('clicked', lambda arg: Inseto24(self))\n\t#----------------------------------------\t\n\treturn 0","sub_path":"projectBIO-Finish/Result.py","file_name":"Result.py","file_ext":"py","file_size_in_byte":10873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"276416958","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nimport random\nimport operator\n\nG=nx.gnp_random_graph(10,0.5,directed=True)\nnx.draw(G,with_labels=True)\nplt.show()\n\nx=random.choice([i for i in range(G.number_of_nodes())]) #pick node randomly\ndict_counter={}\nfor i in range(G.number_of_nodes()):\n dict_counter[i]=0\n\ndict_counter[x]+=1\nfor i in range(1000000):\n list_n=list(G.neighbors(x))\n if(len(list_n)==0):\n x=random.choice([i for i in range(G.number_of_nodes())])\n else:\n x=random.choice(list_n)\n dict_counter[x]+=1\n\np=nx.pagerank(G)\nsorted_p=sorted(p.items(),key=operator.itemgetter(1)) #by operator lib.(sorted based on values..... to sorted by key put 0)\nsorted_rw=sorted(dict_counter.items(),key=operator.itemgetter(1))\nprint(p)\nprint(dict_counter)\n","sub_path":"27 Page Rank-2.py","file_name":"27 Page Rank-2.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"198061733","text":"import glob\nimport psycopg2\nimport face_recognition\nimport cv2\nimport requests\nimport time\n\n\nvideo_capture = cv2.VideoCapture(0)\n\n# Load a sample picture and learn how to recognize it.\nknown_face_names_pre = glob.glob('dataset/*.jpg')\nknown_image = []\nknown_face_encodings = []\nknown_face_names = []\nfor i in range(len(known_face_names_pre)):\n image_for_append = face_recognition.load_image_file(known_face_names_pre[i])\n known_image.append(image_for_append)\n known_face_encodings.append(face_recognition.face_encodings(image_for_append)[0])\n known_face_names.append(known_face_names_pre[i][8:-4])\n\n\t\nconnection = psycopg2.connect(user = \"dpcwdmmygwvxqe\",\n password = \"d113638b455977377844724fea4f9e7aac7ff8dbc4685516ecbdd25d5b52a39b\",\n host = \"ec2-54-246-86-167.eu-west-1.compute.amazonaws.com\",\n port = \"5432\",\n database = \"darsad67es2t64\")\ncursor = connection.cursor() \n# Initialize some variables\nface_locations = []\nface_encodings = []\nface_names = []\nprocess_this_frame = True\n\n\ncount = 0\nwhile True:\n ret, frame = video_capture.read()\n\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n\n rgb_small_frame = small_frame[:, :, ::-1]\n\n if process_this_frame:\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n\n face_names = []\n for face_encoding in face_encodings:\n # See if the face is a match for the known face(s)\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding)\n name = \"Unknown\"#; \n \n\t\t\t\n\t\t\t\n # If a match was found in known_face_encodings, just use the first one.\n if True in matches:\n first_match_index = matches.index(True)\n name = known_face_names[first_match_index]\n\n face_names.append(name)\n\n process_this_frame = not process_this_frame\n \n\n\t\n if len(face_names) > 0:\n rec = face_names[0]\n #print(type(face_names[0][8:-4]))\n query = \"UPDATE people SET status = 'yes' WHERE name = '\" + str(rec) + \"'\"\n\t\t\n cursor.execute(query)\n connection.commit()\n\n #req = requests.request('GET', 'https://facevision27.herokuapp.com/refresh')\n\n for (top, right, bottom, left), name in zip(face_locations, face_names):\n\n if name == \"Unknown\":\n count += 1\n print('Не авторизованный пользователь')\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n #query_count = \"UPDATE people SET count = \" + str(count) + \" WHERE id = '4' \"\n\t\t\n\t\t\n\t\t\n #cursor.execute(query_count)\n #connection.commit()\n\t\t\n # Draw a box around the face\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n\n # Draw a label with a name below the face\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n \n query_count = \"'UPDATE people SET count = '\" + str(count) + \"'WHERE id = 1'\"\n cursor.execute(query)\n connection.commit()\n\t\t\n\t\t\n # Display the resulting image\n cv2.imshow('LifeBug', frame)\n \n # Hit 'q' on the keyboard to quit!\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Release handle to the webcam\nvideo_capture.release()\ncv2.destroyAllWindows()\ncursor.close()","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":3674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"507508474","text":"# 三国演义人物出场统计.py\r\nimport jieba\r\nexcludes={\"将军\",\"二人\",\"荆州\",\"不可\",\"不能\",\"如此\",\"却说\",\"商议\"}\r\ntxt=open(\"D:\\Desktop\\python小练习\\python——revive\\教材案例\\三国演义.txt\",\"r\",encoding='utf-8').read()\r\nwords = jieba.lcut(txt)\r\ncounts={}\r\nfor word in words:\r\n\tif len(word)==1:\r\n\t\t# 排除单个字符的分词结果\r\n\t\tcontinue\r\n\telif word==\"诸葛亮\" or word==\"孔明曰\":\r\n\t\trword=\"孔明\"\r\n\r\n\telif word==\"关公\" or word==\"云长\":\r\n\t\trword=\"关羽\"\r\n\telif word==\"玄德\" or word==\"玄德曰\":\r\n\t\trword=\"刘备\"\r\n\telif word==\"孟德\" or word==\"丞相\":\r\n\t\trword=\"曹操\"\r\n\telse:\r\n\t\treword=word\r\n\t\tcounts[word]=counts.get(word,0)+1\r\n\r\nfor word in excludes:\r\n\tdel(counts[word])\r\nitems=list(counts.items())\r\nitems.sort(key=lambda x:x[1],reverse=True)\r\nfor i in range(5):\r\n\tword,count=items[i]\r\n\tprint(\"{0:<10}{1:<5}\".format(word,count))\r\n\r\n","sub_path":"教材案例/# 三国演义人物出场统计.py","file_name":"# 三国演义人物出场统计.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"250927829","text":"import os\nimport sys\nimport unittest\n\nfrom PySide2.QtTest import QTest\nfrom PySide2.QtCore import Qt\n\nimport angr\nfrom angrmanagement.ui.main_window import MainWindow\nfrom angrmanagement.ui.dialogs.rename_label import RenameLabel\nfrom angrmanagement.ui.dialogs.rename_node import RenameNode\n\nfrom common import setUp, test_location\n\n\nclass TestRenameFunctions(unittest.TestCase):\n def setUp(self):\n setUp()\n\n def test_rename_a_function_in_disasm_and_pseudocode_views(self):\n main = MainWindow(show=False)\n binpath = os.path.join(test_location, \"x86_64\", \"fauxware\")\n main.workspace.instance.project.am_obj = angr.Project(binpath, auto_load_libs=False)\n main.workspace.instance.project.am_event()\n main.workspace.instance.join_all_jobs()\n\n func = main.workspace.instance.project.kb.functions['main']\n self.assertIsNotNone(func)\n\n # decompile the function\n disasm_view = main.workspace._get_or_create_disassembly_view()\n disasm_view._t_flow_graph_visible = True\n disasm_view.display_function(func)\n disasm_view.decompile_current_function()\n main.workspace.instance.join_all_jobs()\n pseudocode_view = main.workspace._get_or_create_pseudocode_view()\n\n # find the node for function\n for _, item in pseudocode_view.codegen.map_pos_to_node.items():\n if isinstance(item.obj, angr.analyses.decompiler.structured_codegen.c.CFunction):\n func_node = item.obj\n break\n else:\n self.fail(\"The CFunction instance is not found.\")\n\n self.assertEqual(func_node.name, \"main\")\n\n # rename the function in the disassembly view\n rlabel = RenameLabel(disasm_view, func.addr, parent=None)\n rlabel._name_box.setText(\"\")\n QTest.keyClicks(rlabel._name_box, \"asdf\")\n QTest.mouseClick(rlabel._ok_button, Qt.MouseButton.LeftButton)\n\n self.assertEqual(func.name, \"asdf\")\n self.assertEqual(func_node.name, \"main\")\n\n # rename the function in the pseudocode view\n rnode = RenameNode(code_view=pseudocode_view, node=func_node)\n rnode._name_box.setText(\"\")\n QTest.keyClicks(rnode._name_box, \"fdsa\")\n QTest.mouseClick(rnode._ok_button, Qt.MouseButton.LeftButton)\n\n self.assertEqual(func.name, \"fdsa\")\n\n\nif __name__ == \"__main__\":\n unittest.main(argv=sys.argv)\n","sub_path":"tests/test_rename_functions.py","file_name":"test_rename_functions.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"529843202","text":"def main():\r\n texto = abrirArquivo(\"texto.txt\")\r\n texto_lista = listaDePalavras(texto)\r\n dicionario = criarDict(texto_lista)\r\n imprimiDicionario(dicionario)\r\n\r\n\r\ndef abrirArquivo(none_arquivo):\r\n arquivo = open(none_arquivo, encoding=\"UTF-8\")\r\n texto = arquivo.read()\r\n arquivo.close()\r\n return texto\r\n\r\n\r\ndef listaDePalavras(texto):\r\n saida_texto = texto.split()\r\n return saida_texto\r\n\r\n\r\ndef criarDict(lista_palavras):\r\n dicionario_palavras = {}\r\n for palavra in lista_palavras:\r\n if palavra in dicionario_palavras:\r\n dicionario_palavras[palavra] += 1\r\n else:\r\n dicionario_palavras[palavra] = 1\r\n return dicionario_palavras\r\n\r\n\r\ndef imprimiDicionario(dicionario):\r\n for valor in dicionario:\r\n print(f\"{valor}: {dicionario[valor]}\")\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Capitulo_09/exercicio-9.11/licao9-11.py","file_name":"licao9-11.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"590493011","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\n__author__ = 'YYF'\n__mtime__ = '2018/11/10'\n# code is far away from bugs with the god animal protecting\n I love animals. They taste delicious.\n ┏┓ ┏┓\n ┏┛┻━━━┛┻┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┃ ┗━━━┓\n ┃ 神兽保佑 ┣┓\n ┃ 永无BUG! ┏┛\n ┗┓┓┏ ━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛\n\"\"\"\nimport tensorflow as tf\nimport tensorflow.examples.tutorials.mnist.input_data as input_data\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\nmnist = input_data.read_data_sets('MNIST_data/', one_hot=True)\n# save_path = r\"E:\\Pycharmprojects\\GAN_Net\\CNN_GAN\\cnngan_2_ckpt\\1_ckpt\"\n\n\nclass Dnet:\n def __init__(self):\n with tf.variable_scope('D_params'):\n # 定义第一个卷积层\n self.conv1_w = tf.Variable(tf.truncated_normal([3, 3, 1, 16], dtype=tf.float32, stddev=0.1))\n self.conv1_b = tf.Variable(tf.zeros([16]))\n # 定义第二个卷积层\n self.conv2_w = tf.Variable(tf.truncated_normal([3, 3, 16, 32], dtype=tf.float32, stddev=0.1))\n self.conv2_b = tf.Variable(tf.zeros([32]))\n # 卷积后进行全连接输出\n self.w = tf.Variable(tf.truncated_normal([7 * 7 * 32, 128], dtype=tf.float32, stddev=0.1))\n self.b = tf.Variable(tf.zeros([128]))\n # 定义输出层w\n self.out_w = tf.Variable(tf.truncated_normal([128, 1], dtype=tf.float32, stddev=0.1))\n\n def forward(self, x):\n # 第一个卷积层\n conv1 = tf.nn.leaky_relu(tf.nn.conv2d(x, self.conv1_w, [1, 2, 2, 1], padding='SAME') + self.conv1_b)\n # 第二个卷积层\n # conv2_bn = tf.layers.batch_normalization(\n # tf.nn.conv2d(conv1, self.conv2_w, [1, 2, 2, 1], padding='SAME') + self.conv2_b)\n conv2 = tf.nn.leaky_relu(tf.nn.conv2d(conv1, self.conv2_w, [1, 2, 2, 1], padding='SAME') + self.conv2_b)\n # 卷层reshape转换形状\n conv2_flat = tf.reshape(conv2, [-1, 7 * 7 * 32])\n # 第一个全连接层输入\n # mlp_bn = tf.layers.batch_normalization(tf.matmul(conv2_flat, self.w) + self.b)\n mlp = tf.nn.leaky_relu(tf.matmul(conv2_flat, self.w) + self.b)\n # 输出\n # output_bn = tf.layers.batch_normalization(tf.matmul(mlp, self.out_w))\n output = tf.nn.sigmoid(tf.matmul(mlp, self.out_w))\n # output = tf.nn.sigmoid(output_bn)\n\n return output\n\n def getparamas(self):\n return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='D_params')\n\n\nclass Gnet:\n def __init__(self):\n with tf.variable_scope('G_params'):\n # 数据输入后,然后定义第一个全连接\n self.in_w1 = tf.Variable(tf.truncated_normal(dtype=tf.float32, shape=[128, 1024], stddev=0.1))\n self.in_b1 = tf.Variable(tf.zeros([1024]))\n # 定义第二个全连接w,转换至可以输入反卷积的水平\n self.in_w2 = tf.Variable(tf.truncated_normal(dtype=tf.float32, shape=[1024, 7 * 7 * 32], stddev=0.1))\n self.in_b2 = tf.Variable(tf.zeros([7 * 7 * 32]))\n # 定义反卷积核1的大小,和判别器的卷积核相反\n self.deconv1_w = tf.Variable(tf.truncated_normal([3, 3, 16, 32], dtype=tf.float32, stddev=0.1))\n # self.conv1_b = tf.Variable(tf.zeros([32]))\n # 定义反卷积核2的大小,和判别器的卷积核相反\n self.deconv2_w = tf.Variable(tf.truncated_normal([3, 3, 1, 16], dtype=tf.float32, stddev=0.1))\n # self.conv2_b = tf.Variable(tf.zeros([16]))\n\n def forward(self, x):\n # 定义第一个全连接输出\n # mlp1_bn = tf.layers.batch_normalization(tf.matmul(x, self.in_w1) + self.in_b1)\n mlp1 = tf.nn.leaky_relu(tf.matmul(x, self.in_w1) + self.in_b1)\n # 定义第二个全连接输出\n # mlp2_bn = tf.layers.batch_normalization(tf.matmul(mlp1, self.in_w2) + self.in_b2)\n mlp2 = tf.nn.leaky_relu(tf.matmul(mlp1, self.in_w2) + self.in_b2)\n # 对全连接输出值进行形状转换\n mlp2_conv = tf.reshape(mlp2, [-1, 7, 7, 32])\n # 定义反卷积的第一个输出\n # deconv1_bn = tf.layers.batch_normalization(\n # tf.nn.conv2d_transpose(mlp2_conv, self.deconv1_w, [100, 14, 14, 16], [1, 2, 2, 1], padding='SAME'))\n deconv1 = tf.nn.leaky_relu(\n tf.nn.conv2d_transpose(mlp2_conv, self.deconv1_w, [100, 14, 14, 16], [1, 2, 2, 1], padding='SAME'))\n # 定义反卷积的第二个输出\n deconv2 = tf.nn.conv2d_transpose(deconv1, self.deconv2_w, [100, 28, 28, 1], [1, 2, 2, 1], padding='SAME')\n\n return deconv2\n\n def getparams(self):\n return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='G_params')\n\n\nclass CNNgannet:\n def __init__(self):\n self.d_input_x = tf.placeholder(dtype=tf.float32, shape=[None, 28, 28, 1])\n # 定义判别器卷积层输入\n self.g_input_x = tf.placeholder(dtype=tf.float32, shape=[None, 128])\n # 定义生成随机样本的特征值\n\n self.dnet = Dnet()\n self.gnet = Gnet()\n\n self.forward()\n self.backward()\n\n def forward(self):\n self.D_out = self.dnet.forward(self.d_input_x)\n self.G_out = self.gnet.forward(self.g_input_x)\n self.G_D_out = self.dnet.forward(self.G_out)\n\n def backward(self):\n self.D_loss = -(tf.reduce_mean(tf.log(self.D_out)) + tf.reduce_mean(tf.log(1 - self.G_D_out)))\n # 定义损失\n\n self.D_opt = tf.train.GradientDescentOptimizer(0.02).minimize(self.D_loss, var_list=self.dnet.getparamas())\n # 优化器\n\n self.G_loss = tf.reduce_mean(-tf.log(self.G_D_out))\n\n # 定义损失\n self.G_opt = tf.train.GradientDescentOptimizer(0.02).minimize(self.G_loss, var_list=self.gnet.getparams())\n\n\nif __name__ == '__main__':\n net = CNNgannet()\n init = tf.global_variables_initializer()\n save = tf.train.Saver()\n\n with tf.Session() as sess:\n sess.run(init)\n # save.restore(sess, save_path=save_path)\n\n plt.ion()\n i = 0\n for epoch in range(100000):\n # 训练判别器\n d_input, _ = mnist.train.next_batch(100)\n d_x = np.reshape(d_input, (100, 28, 28, 1))\n g_x = np.random.uniform(-1, 1, size=(100, 128))\n # if epoch % 3 == 0:\n # _D_loss, _ = sess.run([net.D_loss, net.D_opt],feed_dict={net.d_input_x: d_x, net.g_input_x: g_x})\n _D_loss, _ = sess.run([net.D_loss, net.D_opt], feed_dict={net.d_input_x: d_x, net.g_input_x: g_x})\n\n # 训练��成器\n g_x = np.random.uniform(-1, 1, size=(100, 128))\n _G_outs, _G_loss, _ = sess.run([net.G_out, net.G_loss, net.G_opt], feed_dict={net.g_input_x: g_x})\n\n if epoch % 100 == 0:\n i += 1\n print('epoch:{}, D_loss:{:5.2f}, G_loss:{:5.2f}'.format(epoch, _D_loss, _G_loss))\n # 测试图片输入\n test_input_x = np.random.uniform(-1, 1, size=(100, 128))\n test_image_data = sess.run(net.G_out, feed_dict={net.g_input_x: test_input_x})\n test_image = np.reshape(test_image_data[5], (28, 28))\n\n # 输出上面训练后的输出图片\n train_image = np.reshape(_G_outs[5], (28, 28))\n\n plt.clf()\n plt.subplot(121) # 创建字图\n plt.imshow(test_image)\n plt.title('test image')\n plt.subplot(122)\n plt.imshow(train_image)\n plt.title('train image')\n plt.pause(0.1)\n # plt.savefig('E:\\Pycharmprojects\\GAN_Net\\CNN_GAN\\cnngan_image\\{}.png'.format(str(i).zfill(3)))\n # save.save(sess, save_path=save_path)\n plt.ioff()\n","sub_path":"NeuralNetworkModel/cnngan_yyf_2.py","file_name":"cnngan_yyf_2.py","file_ext":"py","file_size_in_byte":8097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"276623168","text":"#Desafio 2 - Data de nascimento e informações adicionais\n\nnome = input('Qual o seu nome? ')\nprint('É um grande prazer te conhecer,',nome)\nidade = input('Qual a sua idade? ')\npeso = input('Obrigado, agora preciso saber seu peso ')\nprint('Muito obrigado pelas informações, registramos que o(a)', nome, 'possui', idade,'anos e tem', peso,'kilos')\n\nprint('Agora precisarei saber a data de seu nascimento...')\ndia = input('Digite o dia ')\nmes = input('Digite o mês ')\nano = input('Digite o ano ')\n\nprint('Identificamos que você nasceu em', dia,'de',mes,'de',ano, 'ou',dia,'/',mes,'/',ano)\n","sub_path":"python/curso-em-video/exercicios/ex002 - Diálogo com usuário.py","file_name":"ex002 - Diálogo com usuário.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"421502603","text":"\"\"\"Feedbus client\"\"\"\n\nfrom __future__ import annotations\nfrom abc import ABCMeta, abstractmethod\nimport asyncio\nfrom asyncio import Queue\nimport logging\nfrom typing import Optional, Set, List, cast\nfrom ssl import SSLContext\nfrom uuid import UUID\n\ntry:\n from jetblack_negotiate_stream import open_negotiate_stream\nexcept ImportError:\n pass\n\nfrom .io import DataReader, DataWriter, DataPacket\nfrom .messages import (\n MessageType,\n Message,\n SubscriptionRequest,\n NotificationRequest,\n ForwardedSubscriptionRequest,\n MulticastData,\n UnicastData,\n AuthorizationRequest,\n AuthorizationResponse,\n ForwardedMulticastData,\n ForwardedUnicastData\n)\nfrom .authentication import Authenticator, NullAuthenticator, SspiAuthenticator\nfrom .utils import read_aiter\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass Client(metaclass=ABCMeta):\n \"\"\"Feedbus client\"\"\"\n\n def __init__(\n self,\n reader: DataReader,\n writer: DataWriter,\n authenticator: Optional[Authenticator],\n monitor_heartbeat: bool\n ):\n self._reader = reader\n self._writer = writer\n self._authenticator = authenticator\n self._monitor_heartbeat = monitor_heartbeat\n self._read_queue: Queue = asyncio.Queue()\n self._write_queue: Queue = asyncio.Queue()\n self._token = asyncio.Event()\n\n @classmethod\n async def create(\n cls,\n host: str,\n port: int,\n *,\n authenticator: Optional[Authenticator] = None,\n ssl: Optional[SSLContext] = None,\n monitor_heartbeat: bool = False\n ) -> Client:\n \"\"\"Create the client\n\n Args:\n host (str): The host name of the distributor.\n port (int): The distributor port\n authenticator (Optional[Authenticator], optional): An authenticator. Defaults to None.\n ssl (Optional[SSLContext], optional): The context for an ssl connection. Defaults to None.\n monitor_heartbeat (bool, optional): If true use the monitor heartbeat. Defaults to False.\n\n Returns:\n Client: The connected client.\n \"\"\"\n if authenticator is None:\n authenticator = NullAuthenticator()\n\n reader, writer = await asyncio.open_connection(host, port, ssl=ssl)\n\n return cls(\n DataReader(reader),\n DataWriter(writer),\n authenticator,\n monitor_heartbeat\n )\n\n\n @classmethod\n async def create_sspi(\n cls,\n host: str,\n port: int,\n *,\n authenticator: Optional[Authenticator] = None,\n monitor_heartbeat: bool = False\n ) -> Client:\n \"\"\"Create the client using SSPI authentication.\n\n Args:\n host (str): The host name of the distributor.\n port (int): The distributor port\n authenticator (Optional[Authenticator], optional): An authenticator. Defaults to None.\n monitor_heartbeat (bool, optional): If true use the monitor heartbeat. Defaults to False.\n\n Returns:\n Client: The connected client.\n \"\"\"\n if authenticator is None:\n authenticator = SspiAuthenticator()\n\n reader, writer = await open_negotiate_stream(host, port)\n\n return cls(\n DataReader(reader), # type: ignore\n DataWriter(writer), # type: ignore\n authenticator,\n monitor_heartbeat\n )\n\n async def start(self) -> None:\n \"\"\"Start handling messages\"\"\"\n\n if self._authenticator:\n await self._authenticator.authenticate(self._reader, self._writer)\n\n if self._monitor_heartbeat:\n await self.add_subscription('__admin__', 'heartbeat')\n\n async for message in read_aiter(self._read, self._write, self._dequeue, self._token):\n if message.message_type == MessageType.AUTHORIZATION_REQUEST:\n await self._raise_authorization_request(\n cast(AuthorizationRequest, message)\n )\n elif message.message_type == MessageType.FORWARDED_MULTICAST_DATA:\n await self._raise_multicast_data(\n cast(ForwardedMulticastData, message)\n )\n elif message.message_type == MessageType.FORWARDED_UNICAST_DATA:\n await self._raise_unicast_data(\n cast(ForwardedUnicastData, message)\n )\n elif message.message_type == MessageType.FORWARDED_SUBSCRIPTION_REQUEST:\n await self._raise_forwarded_subscription_request(\n cast(ForwardedSubscriptionRequest, message)\n )\n else:\n raise RuntimeError(\n f'Invalid message type {message.message_type}')\n\n is_faulted = not self._token.is_set()\n if not is_faulted:\n await self._writer.close()\n\n await self.on_closed(is_faulted)\n\n LOGGER.info('Done')\n\n def stop(self) -> None:\n \"\"\"Stop handling messages\"\"\"\n self._token.set()\n\n async def _read_message(self) -> Message:\n return await Message.read(self._reader)\n\n async def _raise_authorization_request(\n self,\n message: AuthorizationRequest\n ) -> None:\n await self.on_authorization(\n message.client_id,\n message.host,\n message.user,\n message.feed,\n message.topic\n )\n\n @abstractmethod\n async def on_authorization(\n self,\n client_id: UUID,\n host: str,\n user: str,\n feed: str,\n topic: str\n ) -> None:\n \"\"\"Called when authorization is requested\"\"\"\n\n async def _raise_multicast_data(\n self,\n message: ForwardedMulticastData\n ) -> None:\n await self.on_data(\n message.user,\n message.host,\n message.feed,\n message.topic,\n message.data_packets,\n message.content_type\n )\n\n async def _raise_unicast_data(\n self,\n message: ForwardedUnicastData\n ) -> None:\n await self.on_data(\n message.user,\n message.host,\n message.feed,\n message.topic,\n message.data_packets,\n message.content_type\n )\n\n @abstractmethod\n async def on_data(\n self,\n user: str,\n host: str,\n feed: str,\n topic: str,\n data_packets: Optional[List[DataPacket]],\n content_type: str\n ) -> None:\n \"\"\"Called when data is received\n\n Args:\n user (str): The user name of the sender.\n host (str): The host from which the data was sent.\n feed (str): The feed name.\n topic (str): The topic name.\n data_packets (Optional[List[DataPacket]]): The data packets.\n content_type (str): The type of the message contents.\n \"\"\"\n\n async def _raise_forwarded_subscription_request(\n self,\n message: ForwardedSubscriptionRequest\n ) -> None:\n await self.on_forwarded_subscription_request(\n message.client_id,\n message.user,\n message.host,\n message.feed,\n message.topic,\n message.is_add\n )\n\n @abstractmethod\n async def on_forwarded_subscription_request(\n self,\n client_id: UUID,\n user: str,\n host: str,\n feed: str,\n topic: str,\n is_add: bool\n ) -> None:\n \"\"\"Called for a notification.\n\n Args:\n client_id (UUID): An identifier for the client.\n user (str): The name of the user that requested the subscription.\n host (str): The host from which the subscription was requested.\n feed (str): The feed name.\n topic (str): The topic name.\n is_add (bool): If true the request was to add a subscription.\n \"\"\"\n\n @abstractmethod\n async def on_closed(self, is_faulted: bool) -> None:\n \"\"\"Called when the connection has been closed\n\n Args:\n is_faulted (bool): If true the connection was closed by the server\n \"\"\"\n\n async def authorize(\n self,\n client_id: UUID,\n feed: str,\n topic: str,\n is_authorization_required: bool,\n entitlements: Optional[Set[int]]\n ) -> None:\n \"\"\"Send an authorization response.\n\n Args:\n client_id (UUID): An identifier for the client.\n feed (str): The feed name.\n topic (str): The topic name.\n is_authorization_required (bool): If True, authorization is required.\n entitlements (Optional[Set[int]]): The entitlements of the user.\n \"\"\"\n await self._write_queue.put(\n AuthorizationResponse(\n client_id,\n feed,\n topic,\n is_authorization_required,\n entitlements\n )\n )\n\n async def publish(\n self,\n feed: str,\n topic: str,\n content_type: str,\n data_packets: Optional[List[DataPacket]]\n ) -> None:\n \"\"\"Publish data to subscribers\n\n Args:\n feed (str): The feed name.\n topic (str): The topic name.\n content_type (str): The type of the message contents.\n data_packets (Optional[List[DataPacket]]): Th data packets.\n \"\"\"\n await self._write_queue.put(\n MulticastData(\n feed,\n topic,\n content_type,\n data_packets\n )\n )\n\n async def send(\n self,\n client_id: UUID,\n feed: str,\n topic: str,\n content_type: str,\n data_packets: Optional[List[DataPacket]]\n ) -> None:\n \"\"\"Send data to a client\n\n Args:\n client_id (UUID): The clint id.\n feed (str): The feed name.\n topic (str): The topic name.\n content_type (str): The type of the message contents.\n data_packets (Optional[List[DataPacket]]): Th data packets.\n \"\"\"\n await self._write_queue.put(\n UnicastData(\n client_id,\n feed,\n topic,\n content_type,\n data_packets\n )\n )\n\n async def add_subscription(self, feed: str, topic: str) -> None:\n \"\"\"Add a subscription\n\n Args:\n feed (str): The feed name.\n topic (str): The topic name.\n \"\"\"\n await self._write_queue.put(\n SubscriptionRequest(\n feed,\n topic,\n True\n )\n )\n\n async def remove_subscription(self, feed: str, topic: str) -> None:\n \"\"\"Remove a subscription\n\n Args:\n feed (str): The feed name.\n topic (str): The topic name.\n \"\"\"\n await self._write_queue.put(\n SubscriptionRequest(\n feed,\n topic,\n False\n )\n )\n\n async def add_notification(self, feed: str) -> None:\n \"\"\"Add a notification\n\n Args:\n feed (str): The feed name.\n \"\"\"\n await self._write_queue.put(\n NotificationRequest(\n feed,\n True\n )\n )\n\n async def remove_notification(self, feed: str) -> None:\n \"\"\"Remove a notification\n\n Args:\n feed (str): The feed name.\n \"\"\"\n await self._write_queue.put(\n NotificationRequest(\n feed,\n False\n )\n )\n\n async def _read(self) -> None:\n message = await Message.read(self._reader)\n await self._read_queue.put(message)\n\n async def _dequeue(self) -> Message:\n return await self._read_queue.get()\n\n async def _write(self):\n message = await self._write_queue.get()\n await message.write(self._writer)\n","sub_path":"jetblack_messagebus/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":12303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"146449328","text":"# This Python file uses the following encoding: utf-8\nimport random\nimport math\nimport guide\n\nSettings.DelayAfterDrag = 0.2\nSettings.DelayBeforeDrag = 0.2\nSettings.MoveMouseDelay = 0\n\nisStarted = False\nisHi = False\n\n\n#******************************************\nhotKeyX = False # global to communicate with main loop\ndef xHandler(event):\n global hotKeyX\n hotKeyX = True\nEnv.addHotkey(\"z\", KeyModifier.SHIFT, xHandler)\n\nhotKeyN = False\ndef nHandler(event):\n global hotKeyN\n hotKeyN = True\nEnv.addHotkey(\"n\", KeyModifier.CTRL + KeyModifier.SHIFT, nHandler)\n\n#******************************************\ndef showROI(faucet = \"freebitco.in\"):\n global isStarted\n isStarted = True\n if faucet == \"freebitco.in\":\n title = addressRegion.exists(Pattern(\"1521302065814.png\").similar(0.44))\n else:\n title = addressRegion.exists(Pattern(\"1521896762577.png\").similar(0.49))\n \n ROI = Region(title.x, title.y, title.w + 1000, title.w + 1500)\n ROI.highlight(1)\n exists(Pattern(\"1522402073106.png\").similar(0.75)).click(Pattern(\"1522402073106.png\").targetOffset(42,3))\n wait(0.25)\n getBetField()\n\ndef stopApp():\n popup(\"processing Shift+Z key: stopping\")\n exit()\n \n#region\naddressRegion = Region(Region(16,38,1878,127))\nregionResult = Region(Region(315,179,1270,852))\nregionRec = Region(Region(769,573,418,331))\n#Patterns\nHiLost = \"HiLost.png\"\nLoWon = \"LoWon.png\"\nLoLost = \"LoLost.png\"\nHiWon = \"HiWon.png\"\n#endregion\n\n\ndef OppositeToLastWin(waitingTime = 0.5):\n global lastVictoryHiLo\n type(lastVictoryHiLo)\n wait(waitingTime)\n\ndef getBalance():\n try:\n tit = find(Pattern(\"1522151168385.png\").similar(0.72))\n regionBalance = Region(tit.x + tit.w, tit.y, 150, tit.h) \n s = regionBalance.text()\n newS = s.replace(\"BTC\", \"\")\n newS2 = newS.replace(\" \", \"\")\n newS3 = newS2.replace(\"-\", \"\")\n newS4 = newS3.replace(\"!\", \"\")\n newS5 = newS4.replace(\"A\", \"0\")\n newS6 = newS5.replace(\"O\", \"0\")\n if float(newS6) == 0:\n popup(\"Not enought money.\")\n exit()\n return newS6\n except ValueError as e:\n print(e.args)\n popup(\"Error recognizing balance.\")\n isPlaying = False\n return 0\n\n# Recognition to screen element, then click below\ndef getBetField():\n title = exists(\"1522214983309.png\")\n title.click(Pattern(\"1522214983309.png\").targetOffset(74,35))\n regionBet = Region(title.x + 50, title.y + 30, title.w + 45, 35)\n regionBet.highlight(1)\n betValue = regionBet.text()\n return betValue\n\n# Returns total rolls was made last session\ndef getRolls():\n return rolls\n\n# Converts to float point of bitcoin divide size\ndef fixNumber(x):\n return '{:.8f}'.format(x)\n\ndef RandomBetHiLo(waitingTime = 0.5):\n #0001 0001 0101 1110 1001\n rndNum = random.randint(0,1) \n if rndNum == 0:\n type(\"H\") \n else:\n type(\"L\") \n wait(waitingTime)\n\ndef SpecialStrategy(waiting = 0.5):\n #Hi Lo Hi Lo Lo Hi Hi Lo \n # type(\"d\")\n isStarted = True\n while isStarted:\n typeTimes(\"S\", 5)\n type(\"h\")\n #HI - 1\n wait(waiting)\n try:\n if regionResult.find(HiLost):\n type(\"s\")\n print (\"hi - 1\")\n except FindFailed:\n if regionResult.find(HiWon):\n type(\"d\")\n break\n #LO - 2\n type(\"L\")\n wait(waiting)\n try:\n if regionResult.find(LoLost):\n type(\"s\")\n print (\"lo - 2\")\n except FindFailed:\n if regionResult.find(LoWon):\n type(\"d\") \n break\n #HI - 3\n type(\"H\")\n wait(waiting)\n try:\n if regionResult.find(HiLost):\n type(\"s\")\n print (\"hi - 3\")\n except FindFailed:\n if regionResult.find(HiWon):\n type(\"d\") \n break\n #LO - 4\n type(\"L\")\n wait(waiting)\n try:\n if regionResult.find(LoLost):\n type(\"s\")\n print (\"lo - 4\")\n except FindFailed:\n if regionResult.find(LoWon):\n type(\"d\") \n break\n #LO - 5\n type(\"L\")\n wait(waiting)\n try:\n if regionResult.find(LoLost):\n type(\"s\")\n print (\"lo - 5\")\n except FindFailed:\n if regionResult.find(LoWon):\n type(\"d\") \n break\n #HI - 6\n type(\"H\")\n wait(waiting)\n try:\n if regionResult.find(HiLost):\n type(\"s\")\n print (\"hi - 6\")\n except FindFailed:\n if regionResult.find(HiWon):\n type(\"d\") \n break\n #LO - 7\n type(\"L\")\n wait(waiting)\n try:\n if regionResult.find(LoLost):\n type(\"s\")\n print (\"lo - 7\")\n except FindFailed:\n if regionResult.find(LoWon):\n type(\"d\")\n break\n print (\"new cycle\")\n \ndef AutoBet(start):\n isStarted = start\n isHi = False\n while isStarted: \n click(Pattern(\"1521343340926.png\").similar(0.53))\n #balance = Region(Region(811,927,276,35)).text() #TODO\n balance = 0\n if float(balance) < 0.00000502:\n click(Pattern(\"1521343372617.png\").similar(0.50))\n if isHi == False:\n click(Pattern(\"1521343390593.png\").similar(0.42).targetOffset(6,35)) \n isHi = True\n else:\n click(Pattern(\"1521343390593.png\").similar(0.42).targetOffset(-113,39))\n isHi = False\n click(Pattern(\"1521343340926.png\").similar(0.46))\n wait(0.25)\ndef setAutoBetSettings():\n print (\"starting to set autobet settings, be parient.\")\n click(Pattern(\"1521330217210.png\").similar(0.67))\n type(Key.DOWN)\n wait(0.5)\n click(\"1521330124368.png\") \n click(Pattern(\"1521294776902.png\").targetOffset(-60,0))\n wait(0.25)\n click(Pattern(\"1521294842043.png\").targetOffset(-64,-1))\n wait(0.25)\n click(Pattern(\"1521332512719.png\").targetOffset(-105,1)) #Opinion №1\n wait(0.25)\n click(Pattern(\"1521332530624.png\").targetOffset(-77,-2)) #Opinion №2\n wait(0.25)\n click(Pattern(\"1521332545249.png\").targetOffset(-65,-4)) #Opinion №3\n wait(0.25)\n click(Pattern(\"1521332783636.png\").targetOffset(64,-3))\n wait(0.25)\n type(\"a\", KeyModifier.CTRL)\n paste(\"200\")\n click(Pattern(\"1521332821949.png\").targetOffset(2,18))\n wait(0.25)\n type(\"a\", KeyModifier.CTRL)\n paste(\"10000\")\n click(Pattern(\"1521332715800.png\").targetOffset(63,-4))\n wait(0.25)\n type(\"a\", KeyModifier.CTRL)\n paste(\"2\")\n click(Pattern(\"1521332849440.png\").targetOffset(45,1))\n wait(0.25)\n type(\"a\", KeyModifier.CTRL)\n paste(\"0.00000001\")\n click(Pattern(\"1521332875031.png\").targetOffset(0,20))\n wait(0.25)\n type(\"a\", KeyModifier.CTRL)\n paste(\"2\")\n print (\"Autobet settings is set for now.\")\n popup(\"Autobet settings is set for now.\")\n\ndef StartingValues():\n rolls = 0\n countKeyPressed = 0\n regionResult.setFindFailedResponse(PROMPT) \n timerMod = 0\n active = False\n lastVictoryHiLo = \"H\"\n showROI()\n \n global StartingBalance\n StartingBalance = getBalance()\n print(\"Starting balance: {}\".format(StartingBalance))\n \nStartingValues()\nstrategy = int(input(\"Choose strategy [1] Random, [2] Opposite, [3] Special\", \"1\"))\nwhile True:\n if isStarted == False:\n stopApp()\n if (hotKeyX):\n stopApp()\n if (hotKeyN):\n hotKeyN = False\n countKeyPressed += 1\n popup(\"processing ctrl+shift+n: %d\" % countKeyPressed)\n lastBalance = float(getBalance())\n\n rolls += 1 \n print(\"Roll {}, balance: {}\".format(getRolls(), getBalance()))\n\n if strategy == 1:\n RandomBetHiLo(0.5)\n elif strategy == 2:\n OppositeToLastWin(0.5)\n elif strategy == 3:\n SpecialStrategy(0.5)\n \n if float(getBalance()) < float(lastBalance):\n print (\"current {} < {} from last bet = LOST\".format(getBalance(), fixNumber(lastBalance)))\n type(\"S\") \n if lastVictoryHiLo == \"H\":\n lastVictoryHiLo = \"L\"\n else:\n lastVictoryHiLo = \"H\"\n else:\n print (\"current {} > {} from last bet = VICTORY\".format(getBalance(), fixNumber(lastBalance)))\n type(\"DS\")\n \n if timerMod <= 0: \n if active == True:\n type(\"W\")\n active = False\n timerMod = 10\n else:\n type(\"Q\")\n active = True\n timerMod = 10\n timerMod -= 1 \n","sub_path":"presets.sikuli/presets.py","file_name":"presets.py","file_ext":"py","file_size_in_byte":8867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"138807255","text":"\n\nfrom xai.brain.wordbase.conjunctions._suppose import _SUPPOSE\n\n#calss header\nclass _SUPPOSING(_SUPPOSE, ):\n\tdef __init__(self,): \n\t\t_SUPPOSE.__init__(self)\n\t\tself.name = \"SUPPOSING\"\n\t\tself.specie = 'conjunctions'\n\t\tself.basic = \"suppose\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/conjunctions/_supposing.py","file_name":"_supposing.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"114326118","text":"#\r\n# [922] Possible Bipartition\r\n#\r\n# https://leetcode.com/problems/possible-bipartition/description/\r\n#\r\n# algorithms\r\n# Medium (35.09%)\r\n# Total Accepted: 2.5K\r\n# Total Submissions: 7.2K\r\n# Testcase Example: '4\\n[[1,2],[1,3],[2,4]]'\r\n#\r\n# Given a set of N people (numbered 1, 2, ..., N), we would like to split\r\n# everyone into two groups of any size.\r\n#\r\n# Each person may dislike some other people, and they should not go into the\r\n# same group.\r\n#\r\n# Formally, if dislikes[i] = [a, b], it means it is not allowed to put the\r\n# people numbered a and b into the same group.\r\n#\r\n# Return true if and only if it is possible to split everyone into two groups\r\n# in this way.\r\n#\r\n#\r\n#\r\n#\r\n#\r\n#\r\n#\r\n#\r\n#\r\n#\r\n#\r\n# Example 1:\r\n#\r\n#\r\n# Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]\r\n# Output: true\r\n# Explanation: group1 [1,4], group2 [2,3]\r\n#\r\n#\r\n#\r\n# Example 2:\r\n#\r\n#\r\n# Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]\r\n# Output: false\r\n#\r\n#\r\n#\r\n# Example 3:\r\n#\r\n#\r\n# Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]\r\n# Output: false\r\n#\r\n#\r\n#\r\n#\r\n# Note:\r\n#\r\n#\r\n# 1 <= N <= 2000\r\n# 0 <= dislikes.length <= 10000\r\n# 1 <= dislikes[i][j] <= N\r\n# dislikes[i][0] < dislikes[i][1]\r\n# There does not exist i != j for which dislikes[i] == dislikes[j].\r\n#\r\n#\r\n#\r\n#\r\n#\r\nclass Solution:\r\n def possibleBipartition(self, N, dislikes):\r\n \"\"\"\r\n :type N: int\r\n :type dislikes: List[List[int]]\r\n :rtype: bool\r\n \"\"\"\r\n if not dislikes:\r\n return True\r\n if N < 2:\r\n return False\r\n dislikeMap = {}\r\n # generate dislike map (must be bi-direction)\r\n for pair in dislikes:\r\n a = pair[0]\r\n b = pair[1]\r\n if a not in dislikeMap:\r\n dislikeMap[a] = set()\r\n if b not in dislikeMap:\r\n dislikeMap[b] = set()\r\n dislikeMap[a].add(b)\r\n dislikeMap[b].add(a)\r\n curSet = {}\r\n while dislikeMap:\r\n # traverse keys in set and update mapping\r\n if not curSet:\r\n # means current group dislike handle complete, fetch a new one from dislikeMap\r\n curSet = {list(dislikeMap.keys())[0]}\r\n newSet = set()\r\n for key in curSet:\r\n if key in dislikeMap:\r\n for value in dislikeMap[key]:\r\n if value in curSet:\r\n return False\r\n newSet.add(value)\r\n dislikeMap.pop(key)\r\n if not curSet.isdisjoint(newSet):\r\n return False\r\n curSet = newSet\r\n return True\r\n","sub_path":"Medium/886.possible-bipartition.python3.py","file_name":"886.possible-bipartition.python3.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"308236091","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nfrom pymysql import connect\nfrom match_result_500.items import MatchResult500Item\n\n\nclass A500Spider(scrapy.Spider):\n name = 'a500'\n allowed_domains = ['500.com']\n start_urls = ['http://zx.500.com/jczq/kaijiang.php']\n\n def parse(self, response):\n\n data = response.body.decode('gbk')\n node_list = re.findall('(周.*?).*?(\\d+-\\d+ \\d+:\\d+).*?(-\\d+|\\+\\d+).*?class=\"eng\">\\((.*?)\\).*?(\\d+:\\d+)',data,re.S)\n\n for changci,match_date,goalline,first_half,whole in node_list:\n item = MatchResult500Item()\n item['changci'] = changci\n item['match_date'] = match_date\n item['goalline'] = goalline\n item['first_half'] = first_half\n item['whole'] = whole\n yield item\n\n\n","sub_path":"t_spider/dl_newResult/match_result_500/match_result_500/spiders/a500.py","file_name":"a500.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"380557158","text":"import flask\nfrom flask import request, jsonify, render_template\nimport random\n\napplication = flask.Flask(__name__)\napplication.config[\"DEBUG\"] = True\n\n# List of excuses\nexcuses = [\n {'id': 0,\n 'title':'It works on my machine',\n 'type':'Client'},\n {'id': 1,\n 'title':'It seemed to be working yesterday.',\n 'type':'Client'},\n {'id': 2,\n 'title':'Have you tried turning it off and on again?',\n 'type':'Client'},\n {'id': 3,\n 'title':'Are you sure its not a hardware issue?',\n 'type':'Client'},\n {'id': 4,\n 'title':'Are you using the correct version?',\n 'type':'Client'},\n {'id': 5,\n 'title':\"It's never done that before\",\n 'type':'Client'},\n {'id': 6,\n 'title':\"I can't seem to test anything\",\n 'type':'Client'},\n {'id': 7,\n 'title':'Somebody must have changed the code',\n 'type':'Client'},\n {'id': 8,\n 'title':\"That's weird...\",\n 'type':'Client'},\n {'id': 9,\n 'title':\"It's working on my computer\",\n 'type':'Client'},\n {'id': 10,\n 'title':'It seemed to be working yesterday',\n 'type':'Client'},\n {'id': 11,\n 'title':\"There are delays on the Jubilee Line. Going to be abit late\",\n 'type':'Job'},\n {'id': 12,\n 'title':'Not going to be able to go to work today, am playing golf with a client.',\n 'type':'Job'},\n {'id': 13,\n 'title':\"Oh didn't I mention, I'm, working from home today.\",\n 'type':'Job'},\n {'id': 14,\n 'title':\"Running abit late, washing machine is currently flooding my house.\",\n 'type':'Job'},\n {'id': 15,\n 'title':\"I don't think I'll be able to make it today, I've had an allergic reaction to my neighbour's new cat.\",\n 'type':'Job'},\n {'id': 16,\n 'title':'My dog was sick last night, waiting at the vet now. Will not be able to make it in today.',\n 'type':'Job'},\n {'id': 17,\n 'title':\"Not going to be able to come into work today, I've got food poisioning.\",\n 'type':'Job'},\n {'id': 18,\n 'title':\"Don't think I'll be able to come into work today, I've come down with the flu.\",\n 'type':'Job'}\n]\n\n@application.route('/', methods=['GET'])\ndef home():\n return render_template('index.html', rand_excuse =random.choice(excuses)['title'])\n\n\n@application.route('/api/v1/resources/excuses/all', methods=['GET'])\ndef api_all():\n return jsonify(excuses)\n\n@application.route('/api/v1/resources/excuses/random', methods=['GET'])\ndef api_random():\n return jsonify(random.choice(excuses))\n\n\n\n@application.route('/api/v1/resources/excuses', methods=['GET'])\ndef api():\n if 'id' in request.args:\n string = int(request.args['id'])\n elif 'type' in request.args:\n \tstring = str(request.args['type'])\n else:\n \traise TypeError(\"Error: Invalid Parameters pvoid\")\n\n\n # Create an empty list for our results\n results = []\n\n\n # Loop through the data and match results that fit the requested ID.\n for excuse in excuses:\n if excuse['id'] == string:\n results.append(excuse)\n elif excuse['type'] == string:\n \tresults.append(excuse)\n\n # Use the jsonify function from Flask to convert our list of\n # Python dictionaries to the JSON format.\n return jsonify(results)\n\napplication.run(port=5050)\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"294144608","text":"# This module contains classes and utilities for modeling the central objects of the business logic. Objects are\n# modeled by writing a subclass of AgaveDAO equipped with a PARAMS tuple of attributes and implementations of methods\n# such as get_derived_value(), get_hypermedia(), disply(), etc.\n\nimport uuid\n\nfrom .utils import RequestParser\nfrom .config import Config\nfrom .errors import DAOError\n\n\ndef under_to_camel(value):\n def camel_case():\n yield type(value).lower\n while True:\n yield type(value).capitalize\n c = camel_case()\n return \"\".join(c.__next__()(x) if x else '_' for x in value.split(\"_\"))\n\ndef dict_to_camel(d):\n \"\"\"Convert all keys in a dictionary to camel case.\"\"\"\n d2 = {}\n for k,v in d.items():\n d2[under_to_camel(k)] = v\n return d2\n\n\nclass DbDict(dict):\n \"\"\"Class for persisting a Python dictionary.\"\"\"\n\n def __getattr__(self, key):\n # returning an AttributeError is important for making deepcopy work. cf.,\n # http://stackoverflow.com/questions/25977996/supporting-the-deep-copy-operation-on-a-custom-class\n try:\n return self[key]\n except KeyError as e:\n raise AttributeError(e)\n\n def __setattr__(self, key, value):\n self[key] = value\n\n\nclass AgaveDAO(DbDict):\n \"\"\"Base Data Access Object class for Agaveflask models.\"\"\"\n\n # the parameters for the DAO\n # tuples of the form (param name, required/optional/provided/derived, attr_name, type, help, default)\n # should be defined in the subclass.\n #\n #\n # required: these fields are required in the post/put methods of the web app.\n # optional: these fields are optional in the post/put methods of the web app and have a default value.\n # provided: these fields are required to construct the DAO but are provided by the abaco client code, not the user\n # and not the DAO class code.\n # derived: these fields are derived by the DAO class code and do not need to be passed.\n PARAMS = []\n\n @classmethod\n def request_parser(cls):\n \"\"\"Return a flask RequestParser object that can be used in post/put processing.\"\"\"\n parser = RequestParser()\n for name, source, attr, typ, help, default in cls.PARAMS:\n if source == 'derived':\n continue\n required = source == 'required'\n parser.add_argument(name, type=typ, required=required, help=help, default=default)\n return parser\n\n @classmethod\n def from_db(cls, db_json):\n \"\"\"Construct a DAO from a db serialization.\"\"\"\n return cls(**db_json)\n\n def __init__(self, **kwargs):\n \"\"\"Construct a DAO from **kwargs. Client can also create from a dictionary, d, using AbacoDAO(**d)\"\"\"\n for name, source, attr, typ, help, default in self.PARAMS:\n if source == 'required':\n try:\n value = kwargs[name]\n except KeyError:\n raise DAOError(\"Required field {} missing\".format(name))\n elif source == 'optional':\n value = kwargs.get(name, default)\n elif source == 'provided':\n try:\n value = kwargs[name]\n except KeyError:\n raise DAOError(\"Required field {} missing.\".format(name))\n else:\n # derived value - check to see if already computed\n if hasattr(self, name):\n value = getattr(self, name)\n else:\n value = self.get_derived_value(name, kwargs)\n setattr(self, attr, value)\n\n def get_uuid(self):\n \"\"\"Generate a random uuid.\"\"\"\n return '{}-{}'.format(str(uuid.uuid1()), self.get_uuid_code())\n\n def get_derived_value(self, name, d):\n \"\"\"Compute a derived value for the attribute `name` from the dictionary d of attributes provided.\"\"\"\n raise NotImplementedError\n\n def case(self):\n \"\"\"Convert to camel case, if required.\"\"\"\n case = Config.get('web', 'case')\n if not case == 'camel':\n return self\n # if camel case, convert all attributes\n for name, _, _, _, _, _ in self.PARAMS:\n val = self.pop(name, None)\n if val is not None:\n self.__setattr__(under_to_camel(name), val)\n return self\n\n def get_hypermedia(self):\n \"\"\" Add the hypermedia attribute to the DAO. Subclass should override this method. \"\"\"\n return {'_links': {}}\n\n def display(self):\n \"\"\"A default display method, for those subclasses that do not define their own.\"\"\"\n self.update(self.get_hypermedia())\n return self.case()","sub_path":"agaveflask/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"351398237","text":"def LeerDatos(nombre):\n try :\n archivo = open(nombre,\"r\")\n suma = \"\"\n aux = []\n datos = []\n i = 0\n for linea in archivo.readlines():\n for x in linea:\n if x != \" \" and x != \"\\n\" and x != \"-\":\n suma += x\n else:\n if(len(suma) > 0):\n aux.append(float(suma))\n suma = \"\"\n if(len(aux)>0):\n i += 1\n datos.append(aux)\n aux = []\n return datos\n except ValueError:\n print('format error')\n return \n\ndef menu(opciones, texto):\n opcion = -100\n while(opcion < 0 or opcion > len(opciones)):\n while True:\n print('\\t Menu Selecione una opcion') \n print(texto)\n for i, x in enumerate(opciones):\n print(str(i+1)+ \"-. \"+ str(x))\n try:\n opcion = int(input(\"ingrese una opcion valida: \"))\n break\n except ValueError:\n os.system (\"cls\")\n print(\"ingrese una opcion valida\")\n return opcion\n\ndef GenerarRandom():\n pass\ndef Manual():\n pass\ndef printMatrix(datos):\n for x in range(len(datos)):\n print(datos[x])\ndef sacarDiferencias(datos):\n diferencias = [[1,2,3],[4,5,6],[7,8,0]]\n suma = 0\n for i, x in enumerate(datos):\n for y, z in enumerate(datos[i]):\n diferencias[i][y] = (z - diferencias[i][y])\n if diferencias[i][y] < 0:\n diferencias[i][y] *= -1\n suma += diferencias[i][y]\n else:\n suma += diferencias[i][y]\n print(suma)\n return diferencias\ndef Main():\n opcion = menu([\"archivo de texto\",\"Random\",\"Manual\"], 'leer datos por medio de: ')\n datos = {\n 1: LeerDatos('../txt/puzzle.txt'),\n 2: GenerarRandom(),\n 3: Manual()\n }.get(opcion,2)\n if(not(datos)):\n return\n print(datos)\n printMatrix(datos)\n sacarDiferencias(datos)\n \nMain()","sub_path":"Programas/puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"347970110","text":"\"\"\"\n\"\"\"\nimport sys\nimport time\n\nfrom obspy import UTCDateTime\n\nfrom waveform_locator.waveformLocator import WaveformLocator\nfrom waveform_locator.waveformRequest import WaveformRequest\n\nfrom nordb import getNordic\n\nif __name__ == \"__main__\":\n waveform_locator = WaveformLocator('example_config.json')\n start_date = UTCDateTime('2018/10/01 00:00:00.0000')\n\n while start_date < UTCDateTime():\n try:\n request = WaveformRequest('HE', 'OBF8', 'ENZ', start_date, 86400)\n print(\"Fetching waveforms: {0}\".format(start_date))\n streams = waveform_locator.getWaveforms([request,])\n start_date += 86400\n\n for tr in streams:\n tr.write('/levy/ilmosalm/tietokantajutut/obf8_waves/{0}.{1}{2:03d}'.format(tr.id, start_date.year, start_date.julday), format='MSEED')\n except Exception as e:\n print(\"Exception occurred: {0}. Waiting for 10 seconds and trying again\".format(e))\n time.sleep(10)\n","sub_path":"waveformlocator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"568600729","text":"# encoding: utf-8\n# coding: utf-8\n\n\ndef snapshot(url):\n\n import urllib\n from xml.dom import minidom, Node\n \n response = minidom.parse(urllib.urlopen(url))\n\n docids = []\n descs = []\n\n for entry in response.getElementsByTagName(\"item\"):\n docids.append(entry.getElementsByTagName(\"link\").item(0).childNodes[0].data)\n descs.append(entry.getElementsByTagName(\"description\").item(0).childNodes[0].data)\n\n return zip(docids, descs)\n\n\nif __name__ == \"__main__\":\n import sys\n args = sys.argv\n\n ss = snapshot(args[1])\n\n for s, t in ss:\n print(s)\n print(t)\n\n\n","sub_path":"lib/snapshot.py","file_name":"snapshot.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333106835","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport django\n\nsys.path.append('/Users/fengzhengyi/Desktop/work/project/healthreport')\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"healthreport.settings\")\ndjango.setup()\n\nimport pymysql\nfrom pymysql.cursors import DictCursor\nfrom monitor.models import History, Monitors\nfrom monitor.utils import get_avg, get_max\nimport datetime\nimport time\n\n\nclass ConnectionMysql(object):\n def __init__(self):\n self.host = 'localhost'\n self.port = 3306\n self.user = 'root'\n self.passwd = '1234567'\n self.db = 'ucloud_proxy03'\n\n def conn(self):\n conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db,\n charset='utf8', cursorclass=DictCursor)\n return conn\n\n def close(self):\n self.conn().close()\n\n\nclass GetHistory(ConnectionMysql):\n def __init__(self, end_date, end_time):\n self.end_date = end_date\n self.end_time = end_time\n\n def _end_timestrap(self):\n end_date_str = self.end_date.strftime(\"%Y-%m-%d\")\n end_time_str = self.end_time.strftime(\"%H:%M%S\")\n end_datetime_str = end_date_str + \" \" + end_time_str\n end_datetime = datetime.datetime.strptime(end_datetime_str, \"%Y-%m-%d %H:%M:%S\")\n end_timestrap = time.mktime(end_datetime.timetuple())\n return end_timestrap\n\n def _from_timestrap(self):\n from_timestrap = self._end_timestrap() - 3600\n return from_timestrap\n\n def get_history(self, key):\n sql = (\n \"SELECT `items`.`name`, `items`.`key_`, `items`.`hostid`, `hosts`.`host`, `history`.`value` FROM `items` \"\n \"INNER JOIN `history` ON `history`.`itemid` = `items`.`itemid` \"\n \"INNER JOIN `hosts` ON `hosts`.`hostid` = `items`.`hostid` \"\n \"WHERE `items`.`key_` LIKE '%(key)s' \"\n \"AND `history`.`clock` > '%(from_time)s' AND `history`.`clock` < %(end_time)s\"\n )\n cur = self.conn().cursor()\n cur.execute(sql, {'key': key, 'from_time': self._from_timestrap(), 'end_time': self._end_timestrap()})\n m = cur.fetchall()\n cur.close()\n self.conn().close()\n return m\n\n def get_hisotry(self, key):\n m = self.get_history(key)\n relust = []\n k = 0\n while True:\n infodict = {}\n value_l = []\n try:\n m_pop = m.pop()\n infodict[u'host'] = m_pop[u'host']\n for m_item in m:\n if infodict[u'host'] == m_item[u'host']:\n value_l.append(float(m_item['value']))\n m.remove(m_item)\n else:\n pass\n infodict[u'avg_value'] = get_avg(value_l)\n infodict[u'max_value'] = get_max(value_l)\n relust.append(infodict)\n k = k + 1\n except IndexError:\n break\n return relust\n\n def insert_history(self, key):\n relust = self.get_history(key)\n for relust_item in relust:\n host = relust_item[u'host']\n avg_value = relust_item[u'avg_value']\n max_value = relust_item[u'max_value']\n monitor = Monitor.objects.get(asset_id__name=host, monitor_template__key=key)\n History.objects.get_or_create(history_date=self.end_date, history_time=self.end_time, avg_value=avg_value,\n max_value=max_value, monitor=monitor)\n","sub_path":"assets/update/update_monitor.py","file_name":"update_monitor.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"180637765","text":"# Say you have an array for which the ith element is the price of a given stock \n# on day i. \n# \n# Design an algorithm to find the maximum profit. You may complete as many tran\n# sactions as you like (ie, buy one and sell one share of the stock multiple times\n# ) with the following restrictions: \n# \n# \n# You may not engage in multiple transactions at the same time (ie, you must se\n# ll the stock before you buy again). \n# After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 \n# day) \n# \n# \n# Example: \n# \n# \n# Input: [1,2,3,0,2]\n# Output: 3 \n# Explanation: transactions = [buy, sell, cooldown, buy, sell]\n# Related Topics 动态规划 \n# 👍 488 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices) in (0, 1): return 0\n dp = [[0, 0] for _ in range(len(prices))]\n dp[0][1] = -prices[0]\n dp[1][0] = max(dp[0][0], dp[0][1] + prices[1])\n dp[1][1] = max(dp[0][1], dp[0][0] - prices[1])\n for i in range(2, len(prices)):\n dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])\n dp[i][1] = max(dp[i-1][1], dp[i-2][0] - prices[i])\n return dp[-1][0]\n\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_04/[309]Best Time to Buy and Sell Stock with Cooldown.py","file_name":"[309]Best Time to Buy and Sell Stock with Cooldown.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"164358934","text":"#!/usr/bin/env python3\n\n# TechKnAcq: Concept Graph\n# Jonathan Gordon\n\nimport codecs\nimport csv\nimport math\nimport os\nimport re\nimport sys\nfrom collections import defaultdict\nfrom itertools import combinations\n\nimport click\nfrom numpy import zeros\nfrom techknacq.conceptgraph import ConceptGraph\n\n\ndef read_composition(compfile):\n \"\"\"Read the file giving the topic composition of each document, and\n generate a matrix of topic co-occurrence counts.\"\"\"\n\n filecontents = compfile.readlines()\n num_topics = len(filecontents[0].split()) - 2\n\n topic_doc = []\n for i in range(num_topics):\n topic_doc.append([])\n\n co_occur = zeros((num_topics, num_topics), int)\n\n # We need a cut-off for a topic to count as non-trivially occurring\n # in a document, and this needs to vary depending on the number of\n # topics. Based on experiments with 20 and 200 topic models, I chose\n # the thresholds (20, 0.3) and (200, 0.1) and fit the line\n # y = -1/900*x + 290/900\n # with a min of 0.01.\n thresh = max((290.0 - num_topics) / 900.0, 0.01)\n\n r = csv.reader(filecontents, delimiter='\\t')\n for row in r:\n if row[0][0] == '#':\n continue\n m = re.search('([^/]+)\\.(xml|txt)$', row[1])\n if not m:\n continue\n base = m.group(1)\n\n topics = row[2:]\n\n # Read into document topic breakdown information.\n for (topic_id, percent) in enumerate(topics):\n if float(percent) > thresh:\n topic_doc[topic_id].append((base, percent))\n\n # Read into co-occurrence matrix.\n filt_topics = [(a,b) for (a,b) in enumerate(topics) if float(b) > thresh]\n for topic_pair in combinations(filt_topics, 2):\n i1 = int(topic_pair[0][0])\n i2 = int(topic_pair[1][0])\n # Symmetric matrix.\n co_occur[i1][i2] += 1\n co_occur[i2][i1] += 1\n\n return (topic_doc, co_occur)\n\ndef read_weighted_keys(keyfile):\n r = csv.reader(keyfile, delimiter='\\t')\n word_weights = []\n for row in r:\n topicnum = row[0]\n weighted_words = [(x, float(y)) for (x, y) in\n zip(row[1::2], row[2::2])]\n word_weights.append(weighted_words)\n return word_weights\n\ndef read_keys(keyfile):\n names = []\n topics = []\n r = csv.reader(keyfile, delimiter='\\t')\n for row in r:\n words = row[2].split()\n if len(words) > 5:\n names[int(row[0])] = ' '.join(words[:6])\n else:\n names[int(row[0])] = ' '.join(words)\n topics[int(row[0])] = row[2]\n return (names, topics)\n\ndef split_topic(topic_counts_path):\n topic_unigrams = defaultdict(set)\n topic_bigrams = defaultdict(set)\n topic_entities = defaultdict(set)\n\n for line in open(topic_counts_path):\n tokens = line.split()\n word = tokens[1]\n counts = tokens[2:]\n for c in counts:\n (topic, count) = c.split(':')\n if word.startswith('#') and word.endswith('#'):\n topic_entities[int(topic)].add((word, float(count)))\n elif word.count('_') >= 1:\n topic_bigrams[int(topic)].add((word, float(count)))\n else:\n topic_unigrams[int(topic)].add((word, float(count)))\n\n unigrams = []\n for topic in topic_unigrams.keys():\n unigrams.append( sorted(topic_unigrams[topic], key=lambda x: x[1],reverse=True)[:100])\n\n bigrams = []\n for topic in topic_bigrams.keys():\n bigrams.append( sorted(topic_bigrams[topic], key=lambda x: x[1],reverse=True)[:100])\n\n entities = []\n for topic in topic_bigrams.keys():\n entities.append( sorted(topic_entities[topic], key=lambda x: x[1],reverse=True)[:100])\n\n return (unigrams, bigrams, entities)\n\n\ndef topic_name_html(word_weights, global_min=None, global_max=None):\n def invert_hex(hex_number):\n inverse = hex(abs(int(hex_number, 16) - 255))[2:]\n # If the number is a single digit add a preceding zero\n if len(inverse) == 1:\n inverse = '0' + inverse\n return inverse\n\n def float_to_color(f):\n val = '%x' % int(f * 255)\n val = invert_hex(val)\n return '#%s%s%s' % (val, val, val)\n\n vals = [x[1] for x in word_weights]\n val_max = max(vals)\n val_min = math.sqrt(min(vals) / 2)\n val_diff = float(val_max - val_min)\n global_diff = float(global_max - global_min)\n\n ret = ''\n for (y, z) in sorted(word_weights, key=lambda x: x[1],\n reverse=True):\n\n p = float(z - val_min) / val_diff\n\n if global_min and global_max:\n q = float(z - global_min) / global_diff\n else:\n q = p\n\n if y.startswith('#') and y.endswith('#'):\n y = y.replace('#', '')\n ret += '' +\\\n '%s' % (\n float_to_color(p), int(q * 100), y.replace('_', ' ')) + ', '\n else:\n ret += '%s\\n' % (\n float_to_color(p), int(q * 100), y.replace('_', ' '))\n #ret = ret[:-2]\n return ret\n\ndef list_topic_components(keys_file, composition_file):\n g_unigram = ConceptGraph()\n g_unigram.read_keys(open(sys.argv[1], 'r'))\n g_unigram.read_weighted_keys(open(sys.argv[2], 'r'))\n\n g_bigram = ConceptGraph()\n g_bigram.read_keys(open(sys.argv[1], 'r'))\n g_bigram.read_weighted_keys(open(sys.argv[3], 'r'))\n\n g_entity = ConceptGraph()\n g_entity.read_keys(open(sys.argv[1], 'r'))\n g_entity.read_weighted_keys(open(sys.argv[4], 'r'))\n\n uniout = open('unigram-names.tsv', 'w')\n biout = open('bigram-names.tsv', 'w')\n entout = open('entity-names.tsv', 'w')\n\n for n in g_unigram.nodes:\n all_vals = [x[1] for x in g_unigram.word_weights[n]] + \\\n [x[1] for x in g_bigram.word_weights[n]] + \\\n [x[1] for x in g_entity.word_weights[n]]\n mi = min(all_vals)\n ma = max(all_vals)\n\n if g_unigram.word_weights[n] != []:\n print >> uniout, str(n) + '\\t' + \\\n topic_name_html(g_unigram.word_weights[n],\n global_min=mi, global_max=ma)\n\n if g_bigram.word_weights[n] != []:\n print >> biout, str(n) + '\\t' + \\\n topic_name_html(g_bigram.word_weights[n],\n global_min=mi, global_max=ma)\n\n if g_entity.word_weights[n] != []:\n print >> entout, str(n) + '\\t' + \\\n topic_name_html(g_entity.word_weights[n],\n global_min=mi, global_max=ma)\n\n\ndef doc_name(did, doc_names):\n try:\n name = doc_names[did]['author'] + ': ' + '' + doc_names[did]['title'] + ''\n name = name.replace(' A ', ' a ')\n name = name.replace(' Of ', ' of ')\n name = name.replace(' As ', ' as ')\n name = name.replace(' The ', ' the ')\n name = name.replace(' To ', ' to ')\n name = name.replace(' And ', ' and ')\n name = name.replace(' For ', ' for ')\n name = name.replace(' In ', ' in ')\n name = name.replace(' With ', ' with ')\n name = name.replace(' By ', ' by ')\n name = name.replace(' On ', ' on ')\n name = name.replace(' - ', ' – ')\n name = name.replace(' -- ', ' – ')\n name = re.sub(', [^;,<>]+;', ', ', name)\n name = re.sub(', [^,:]+:', ':', name)\n return name\n except KeyError:\n return None\n\ndef read_documents(corpus_dir):\n first_lines = {}\n for root, dirs, files in os.walk(corpus_dir):\n for file in files:\n id = file.replace('.txt','')\n if os.path.isfile(root + '/' + file) and file[-4:] == '.txt':\n with codecs.open(root + '/' + file, 'r', 'utf-8') as f:\n first_line = f.readline()\n first_lines[id] = first_line\n return first_lines\n\ndef list_topic_docs(keys_file, composition_file, corpus_dir, n_docs_per_topic):\n\n docs_per_topic = []\n word_weights = read_weighted_keys(open(keys_file, 'r'))\n (topic_doc, co_occur) = read_composition(open(composition_file, 'r'))\n\n first_lines_dict = read_documents(corpus_dir)\n\n for t in topic_doc:\n doc_list = []\n ordered_doc_refs = sorted(t,key=lambda x:(x[1]),reverse=True)\n\n for i in range(n_docs_per_topic):\n doc_ref = ordered_doc_refs[i][0]\n first_line = first_lines_dict.get(doc_ref, None)\n if(first_line is None):\n first_line = 'Error'\n doc_list.append(first_line + ' [' + doc_ref + ']')\n docs_per_topic.append(doc_list)\n\n return docs_per_topic\n\ndef make_eval_html_page(unigrams, bigrams, entities, docs):\n\n html_string = \"\"\"\n \n \n Topic Evaluation\n \n \n \n

Topic Evaluation

\n
\n
\n
\n

Instructions

\n

You will be shown topics related to a given subject under investigation\n and asked to judge them.

\n

Each topic is represented by a weighted collection of words, phrases,\n and entities, where the darker the color, the more important it is to\n the topic.

\n

Phrases may be missing common function words\n like ‘of’, making ‘part of speech’ show up as\n ‘part speech’. Other phrases may be truncated or split, e.g.,\n ‘automatic speech recognition’ will be displayed as\n ‘automatic speech’ and ‘speech recognition’.

\n

You can click on the name of each entity to see its Wikipedia page. (You may need to choose the most relevant sense for ambiguous entities.

\n

For each\n topic you will also see a list of related papers, which you can click on to view\n in full.

\n

For each phrase associated with the topic you can hover your mouse to\n see how relevant it is to the topic. For each listed document, the\n percent of the document that is about the topic is displayed after the\n title.

\n

For each topic, you are asked how clear it is to you. A topic may be\n unclear because it is a mix of distinct ideas or because it is an area of\n research that is unfamiliar to you.

\n

Your Name:

\n

Your Email:

\n
\n \"\"\"\n\n for topic in range(0, len(unigrams)):\n html_string += '
\\n'\n html_string += '
\\n'\n html_string += '

Topic ' + str(topic) + '

'\n html_string += '
'\n\n '''\n html_string += '

Relevant entities:

'\n html_string += '

', topic_rep[topic]['entity'], '

'\n html_string += '

Relevant pairs of words:

'\n html_string += '

', topic_rep[topic]['bigram'], '

'\n '''\n\n html_string += '

Relevant words:

'\n html_string += topic_name_html(unigrams[topic],0,unigrams[topic][0][1])\n\n if len(docs[topic]) > 0:\n html_string += '

Relevant documents:

    '\n for doc_text in docs[topic]:\n html_string += '
  • '+doc_text+'
  • '\n html_string += '
'\n\n html_string += '

How clear and coherent is the meaning of this topic?

'\n html_string += '

'\n for i, label in enumerate(['Very clear', 'Somewhat clear', 'Not very clear', 'Not clear at all'], 1):\n html_string += ''\n html_string += ''\n html_string += '

'\n\n html_string += '

Does this look like a combination of two or more distinct topics?

'\n html_string += '

'\n for i, label in enumerate(['No', 'Yes'], 1):\n html_string += ''\n html_string += ''\n html_string += '

'\n html_string += '

What short name would you give this topic?

'\n html_string += '

'\n html_string += ''\n html_string += '

'\n html_string += '

Any comments?

'\n html_string += '

'\n html_string += ''\n html_string += '

'\n html_string += '
'\n html_string += '
'\n\n html_string += \"\"\"\n
\n

\n
\n
\n
\n \n \n \"\"\"\n\n return html_string\n\n'''\nin_dir,\ndocs_file='docs.tsv',\nunigram_names_file='unigram-names.tsv',\nbigram_names_file='bigram-names.tsv',\nentity_names_file\n'''\n\n@click.command()\n@click.argument('in_dir', type=click.Path(exists=True))\n@click.argument('topic_counts_filename', type=click.STRING)\n@click.argument('keys_filename', type=click.STRING)\n@click.argument('composition_filename', type=click.STRING)\n@click.argument('corpus_dir', type=click.STRING)\n@click.argument('n_docs_per_topic', type=click.INT)\n@click.argument('out_file', type=click.STRING)\ndef main(in_dir, topic_counts_filename, keys_filename, composition_filename, corpus_dir, n_docs_per_topic, out_file):\n\n '''\n json_str = \"\"\n progress = 0\n fileSize = os.path.getsize(cg_file)\n print('loading ' + cg_file)\n with open(cg_file, 'r') as inputFile:\n for line in inputFile:\n progress = progress + len(line)\n progressPercent = (1.0 * progress) / fileSize\n\n sys.stdout.write('\\r')\n sys.stdout.write(\"[%-20s] %d%%\" % ('='*(20*int(progressPercent)), (100 * progressPercent)))\n sys.stdout.flush()\n sys.stdout.write(\"\")\n\n json_str += line\n\n cg = json.loads(json_str)\n '''\n\n (unigrams, bigrams, entities) = split_topic(in_dir+'/'+topic_counts_filename)\n docs_per_topic = list_topic_docs(in_dir+'/'+keys_filename, in_dir+'/'+composition_filename, corpus_dir, n_docs_per_topic)\n #list_topic_components(in_dir + '/' + keys_filename)\n html = make_eval_html_page(unigrams, bigrams, entities, docs_per_topic)\n \n output = open(out_file, 'w')\n output.write(html)\n output.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"sciknowmap/make-evaluation-page.py","file_name":"make-evaluation-page.py","file_ext":"py","file_size_in_byte":16401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"107685347","text":"#\n# $Id: welcome.py,v 1.23 2012/11/27 00:48:01 phil Exp $\n#\n# Our patch to redhat's installer\n#\n# @Copyright@\n# \n# \t\t\t\tRocks(r)\n# \t\t www.rocksclusters.org\n# \t\t version 5.6 (Emerald Boa)\n# \t\t version 6.1 (Emerald Boa)\n# \n# Copyright (c) 2000 - 2013 The Regents of the University of California.\n# All rights reserved.\t\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice unmodified and in its entirety, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided \n# with the distribution.\n# \n# 3. All advertising and press materials, printed or electronic, mentioning\n# features or use of this software must display the following acknowledgement: \n# \n# \t\"This product includes software developed by the Rocks(r)\n# \tCluster Group at the San Diego Supercomputer Center at the\n# \tUniversity of California, San Diego and its contributors.\"\n# \n# 4. Except as permitted for the purposes of acknowledgment in paragraph 3,\n# neither the name or logo of this software nor the names of its\n# authors may be used to endorse or promote products derived from this\n# software without specific prior written permission. The name of the\n# software includes the following terms, and any derivatives thereof:\n# \"Rocks\", \"Rocks Clusters\", and \"Avalanche Installer\". For licensing of \n# the associated name, interested parties should contact Technology \n# Transfer & Intellectual Property Services, University of California, \n# San Diego, 9500 Gilman Drive, Mail Code 0910, La Jolla, CA 92093-0910, \n# Ph: (858) 534-5815, FAX: (858) 534-7345, E-MAIL:invent@ucsd.edu\n# \n# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# \n# @Copyright@\n#\n# $Log: welcome.py,v $\n# Revision 1.23 2012/11/27 00:48:01 phil\n# Copyright Storm for Emerald Boa\n#\n# Revision 1.22 2012/05/06 05:48:10 phil\n# Copyright Storm for Mamba\n#\n# Revision 1.21 2011/07/23 02:30:14 phil\n# Viper Copyright\n#\n# Revision 1.20 2010/09/07 23:52:46 bruno\n# star power for gb\n#\n# Revision 1.19 2009/05/01 19:06:48 mjk\n# chimi con queso\n#\n# Revision 1.18 2009/03/04 01:32:12 bruno\n# attributes work for frontend installs\n#\n# Revision 1.17 2008/10/18 00:55:45 mjk\n# copyright 5.1\n#\n# Revision 1.16 2008/05/22 21:02:06 bruno\n# rocks-dist is dead!\n#\n# moved default location of distro from /export/home/install to\n# /export/rocks/install\n#\n# Revision 1.15 2008/03/06 23:41:30 mjk\n# copyright storm on\n#\n# Revision 1.14 2007/12/10 21:28:33 bruno\n# the base roll now contains several elements from the HPC roll, thus\n# making the HPC roll optional.\n#\n# this also includes changes to help build and configure VMs for V.\n#\n# Revision 1.13 2007/06/23 04:03:18 mjk\n# mars hill copyright\n#\n# Revision 1.12 2006/12/04 22:05:48 bruno\n# lights-out tweak\n#\n# Revision 1.11 2006/11/29 23:12:40 bruno\n# prototype support for lights out frontend installs\n#\n# Revision 1.10 2006/09/11 22:47:01 mjk\n# monkey face copyright\n#\n# Revision 1.9 2006/08/10 00:09:25 mjk\n# 4.2 copyright\n#\n# Revision 1.8 2006/06/22 22:13:27 bruno\n# cleanup of installclass files\n#\n# Revision 1.7 2006/06/21 03:09:52 bruno\n# updates to put the frontend networking info in the database just like\n# a compute node\n#\n# Revision 1.6 2006/06/05 17:57:33 bruno\n# first steps towards 4.2 beta\n#\n# Revision 1.5 2006/01/18 01:39:24 yuchan\n# add code _ and rhpl.translate for supporting localization - yuchan\n#\n# Revision 1.4 2005/10/12 18:08:28 mjk\n# final copyright for 4.1\n#\n# Revision 1.3 2005/09/16 01:02:08 mjk\n# updated copyright\n#\n# Revision 1.2 2005/05/24 21:21:47 mjk\n# update copyright, release is not any closer\n#\n# Revision 1.1 2005/03/01 00:22:52 mjk\n# moved to base roll\n#\n# Revision 1.2 2004/03/25 03:15:43 bruno\n# touch 'em all!\n#\n# update version numbers to 3.2.0 and update copyrights\n#\n# Revision 1.1 2004/03/08 21:01:23 mjk\n# *** empty log message ***\n#\n# Revision 1.6 2003/11/30 15:04:10 bruno\n# removing redhat trademarks\n#\n# Revision 1.5 2003/09/24 17:08:45 fds\n# Bruno's changes for RH 9\n#\n# Revision 1.4 2003/08/15 22:34:46 mjk\n# 3.0.0 copyright\n#\n# Revision 1.3 2003/08/13 22:39:18 bruno\n# added spaces to cleanup first line on install screen\n#\n# Revision 1.2 2003/05/22 16:36:23 mjk\n# copyright\n#\n# Revision 1.1 2003/04/25 18:15:09 bruno\n# first pass at adding all the new rocks config screens\n#\n#\n#\n\n#\n# support for GUI installs\n#\nimport gtk\nimport gui\nfrom iw_gui import *\nfrom rhpl.translate import _, N_\n\nclass RocksWelcomeWindowGUI(InstallWindow):\n\n\twindowTitle = N_(\"Welcome to Rocks\")\n\n\tdef displayBrowser(self):\n\t\timport os\n\n\t\turl = 'http://127.0.0.1'\n\t\turl += '/tmp/updates/opt/rocks/screens/getrolls.html'\n\n\t\tos.system('/opt/rocks/firerox/bin/firefox ' + url\n\t\t\t+ ' > /tmp/firerox.debug 2>&1')\n\n\t\treturn\n\n\n\tdef displayXterm(self):\n\t\t#\n\t\t# bring up and xterm that we can use for debugging\n\t\t#\n\t\tos.system('/tmp/updates/usr/X11R6/bin/xterm '\n\t\t\t+ '> /tmp/xterm.debug 2>&1')\n\t\treturn\n\n\n\tdef regenerateKickstartFile(self):\n\t\timport rocks.util\n\n\t\tnativearch = rocks.util.getNativeArch()\n\n\t\tcmd = '/opt/rocks/bin/rocks report distro'\n\t\tfor line in os.popen(cmd).readlines():\n\t\t\tdistrodir = line[:-1]\n\n\t\tos.chdir('%s/rocks-dist/%s/build' % (distrodir, nativearch))\n\n\t\tos.environ['PYTHONPATH'] = ''\n\n\t\tcmd = '/opt/rocks/sbin/kpp root '\n\t\tcmd += '| /opt/rocks/sbin/kgen > '\n\t\tcmd += '/tmp/ks.cfg 2> /tmp/ks.cfg.debug'\n\t\tos.system(cmd)\n\t\treturn\n\n\n\tdef restartAnaconda(self):\n\t\tos.system('rm /tmp/ks.cfg.new*')\n\t\tos.system('rm /tmp/ksclass.py*')\n\t\tsys.exit(0)\n\n\t\n\tdef frontendLightsOut(self):\n\t\tinstallcgi = rocks.installcgi.InstallCGI()\n\t\tgenerator = rocks.roll.Generator()\n\n\t\tgenerator.parse('/tmp/rolls.xml')\n\t\trollList = generator.rolls\n\n\t\tos.environ['PYTHONPATH'] = ''\n\t\tfor roll in rollList:\n\t\t\tinstallcgi.getKickstartFiles(roll)\n\n\t\tinstallcgi.rebuildDistro(rollList)\n\n\t\treturn\n\n\n\tdef __init__ (self, ics):\n\t\tInstallWindow.__init__(self, ics)\n\t\tics.setGrabNext(1)\n\n\t\tif not os.path.exists('/tmp/site.attrs'):\n\t\t\t#\n\t\t\t# run the browser to select the rolls and\n\t\t\t# to build the /tmp/site.attrs file\n\t\t\t#\n\t\t\tself.displayBrowser()\n\t\telif os.path.exists('/tmp/rolls.xml'):\n\t\t\t#\n\t\t\t# if /tmp/site.attrs exists and if /tmp/rolls.xml\n\t\t\t# exists, then this is a 'lights out' frontend\n\t\t\t# install -- go get the roll-*-kickstart files\n\t\t\t#\n\t\t\tself.frontendLightsOut()\n\n\t\tfile = open('/proc/cmdline', 'r')\n\t\targs = string.split(file.readline())\n\t\tfile.close()\n\t\tfor arg in args:\n\t\t\tif arg.count('xterm'):\n\t\t\t\tself.displayXterm()\n\n\t\t#\n\t\t# this will ensure that this screen is *not* called\n\t\t# again when anaconda is restarted in the __init__\n\t\t# method below\n\t\t#\n\t\tos.system('touch /tmp/rocks-skip-welcome')\n\t\t\t\n\n\t\tself.regenerateKickstartFile()\n\n\t\t#\n\t\t# after rebuilding the kickstart file, stop this\n\t\t# version of anaconda and let the anaconda script\n\t\t# in ekv restart it.\n\t\t#\n\t\tself.restartAnaconda()\n\n\t\treturn\n\n\n\tdef getScreen (self, configFileData):\n\t\timport gtk\n\n\t\tframe = gtk.Frame()\n\t\tframe.set_shadow_type(gtk.SHADOW_NONE)\n\n\t\timage = configFileData[\"WelcomeScreen\"]\n\t\tpix = self.ics.readPixmapDithered(image)\n \n\t\tif pix:\n\t\t\tbox = gtk.EventBox()\n\t\t\tbox.add(pix)\n\t\t\tframe.add(box)\n\n\t\treturn frame\n\n","sub_path":"include/screens/welcome.py","file_name":"welcome.py","file_ext":"py","file_size_in_byte":8181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"9929437","text":"# importing the required modules\nimport timeit\nimport os\n\n\ndef benchIt(dir):\n if not dir:\n raise ValueError(\"Parameter 'dir' is required.\")\n\n SETUP_CODE = '''\nfrom {dir} import gen_range\n '''.format(**locals())\n\n TEST_CODE = '''\nx = gen_range.myRange(1, 10000)'''.format(**globals())\n\n # timeit.repeat statement\n times = timeit.repeat(\n setup=SETUP_CODE,\n stmt=TEST_CODE,\n repeat=5,\n number=1000\n )\n\n # printing minimum exec. time\n return min(times)\n\n\nif __name__ == \"__main__\":\n print(\"\\nRunning benchmark 'gen_range'.\".format(**globals()))\n print(\"---------------------------------------------------------\")\n\n dictTimes = dict()\n\n for benchName in ['Python', 'Nuitka', 'Cython', 'Numba', 'Nim']:\n dirName = '_'+benchName\n path = os.getcwd()+os.path.sep+dirName\n if os.path.exists(os.path.abspath(path)):\n time = benchIt(dirName)\n dictTimes[benchName] = time\n speedup = dictTimes['Python'] / time\n print('{benchName:7}: {time:.4f}s'.format(**locals()) + '{speedup:>40,.2f}x'.format(**locals()))\n","sub_path":"range/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608599956","text":"from gat_impl.TensorflowGraphGAT import *\nfrom keras.optimizers import Adam\nfrom keras.callbacks import Callback, EarlyStopping\nfrom keras.backend import clear_session\nfrom sklearn.metrics import mean_squared_error\nimport time\nimport pickle\nimport os\n\n\nclass GATModel(TensorflowGraphGAT):\n\n def __init__(self, config):\n '''\n Initialize the GAT model object\n :param config: hyperparameters configuration object for the model\n '''\n # load the GAT architecture configuration object of the current model\n if config is None:\n raise TypeError('No GAT configuration object specified')\n else:\n self.config = config\n # load the hyper-parameter configuration of the current model\n self.params = self.config.params\n # Print the model details\n self.config.print_model_details()\n # wrapped Keras GAT model and its status flags\n self.model = None\n self.is_built = False\n self.is_trained = False\n\n class CustomEarlyStopping(Callback):\n def __init__(self, k_strip_epochs, pq_threshold, train_prog_threshold, **kwargs):\n '''\n Initialize the Callback object for PQ early stopping\n :param k_strip_epochs: number of previous consecutive epochs to consider for the training progress\n :param pq_threshold: threshold for the PQ ration dictating when to stop\n :param train_prog_threshold: threshold for stopping the training when there is no training progress\n :param kwargs: accept dictionary of any actual parameters to instantiate the formal ones\n '''\n super(Callback, self).__init__()\n # time the training time per epoch\n self.total_time_start = 0.0\n # initialize the parameters of the stopping\n self.best_vl_loss = np.inf\n self.k_strip_epochs = k_strip_epochs\n self.pq_threshold = pq_threshold\n self.train_prog_threshold = train_prog_threshold\n self.tr_k_logs = np.zeros(self.k_strip_epochs)\n # store the history of the stopping criterion\n self._data = {'pq_ratio': [], 'train_prog': []}\n\n def on_epoch_begin(self, epoch, logs=None):\n '''\n Lambda function to apply at the beginning of each epoch, here it is just resetting the timer\n :param epoch: epoch number\n :param logs: the logs of training and validation losses and other metrics\n :return: void\n '''\n self.total_time_start = time.time()\n\n def on_epoch_end(self, epoch, logs=None):\n '''\n Lambda function to apply at the end of each epoch, here it computes the training and generalization\n progress from the metrics obtained on this particular epoch and stops the training if the conditions are\n met. It also pretty prints the metric values of the epoch.\n :param epoch: epoch number\n :param logs: the logs of training and validation losses and other metrics\n :return: void\n '''\n # pop last tr loss and push the current one\n self.best_vl_loss = min(self.best_vl_loss, logs['val_loss'])\n self.tr_k_logs[:-1] = self.tr_k_logs[1:]\n self.tr_k_logs[-1] = logs['loss']\n gl = 0.0\n pk = np.inf\n if 0.0 not in self.tr_k_logs:\n best_k_tr_loss = np.min(self.tr_k_logs)\n last_k_tr_loss = np.sum(self.tr_k_logs)\n gl = (logs['val_loss'] / self.best_vl_loss - 1.0) * 100.0\n pk = (last_k_tr_loss / (self.k_strip_epochs * best_k_tr_loss) - 1.0) * 1e3\n if gl / pk >= self.pq_threshold:\n self.model.stop_training = True\n if pk <= self.train_prog_threshold:\n self.model.stop_training = True\n self._data['pq_ratio'].append(gl / pk)\n self._data['train_prog'].append(pk)\n epoch_time = time.time() - self.total_time_start\n print(\n 'Training: loss = %.5f | Val: loss = %.5f | PQ ratio: %.5f | Train progress: %.5f | Elapsed epoch time:'\n ' %.5f seconds | Epoch number: %d' % (logs['loss'], logs['val_loss'], gl / pk, pk, epoch_time, epoch))\n\n def get_stopping_data(self):\n '''\n Retrieves the stopping history of the training phase.\n :return: dict of training progress and PQ ratio\n '''\n return self._data\n\n def build(self, features_shape: tuple):\n '''\n Build the GAT architecture and define the optimizer.\n :return: void\n '''\n # Allocate as much memory as needed and at most a pre-decided fraction of the GPU total memory\n tensorflow_config = tf.ConfigProto()\n tensorflow_config.gpu_options.allow_growth = True\n tensorflow_config.gpu_options.per_process_gpu_memory_fraction = 0.5\n # Create a session with the particular options.\n K.set_session(tf.Session(config=tensorflow_config))\n\n # input tensors dimensionality\n feed_data = {'dim_nodes': features_shape[0],\n 'dim_feats': features_shape[1]}\n # parameters and inputs for building the Keras model\n inference_args = {**feed_data, **self.params}\n\n # Keras GAT model\n self.model = TensorflowGraphGAT.inference_keras(**inference_args)\n # plot_model(self.model, 'gat_model.pdf', show_shapes=True)\n\n # Define the optimizer for the training of the model and compile it for optimizing on a loss function\n optimizer = Adam(lr=self.params['learning_rate'])\n self.model.compile(optimizer=optimizer, loss='mean_squared_error')\n self.is_built = True\n\n def fit(self, training_data):\n '''\n Trains the build GAT model.\n :param training_data: the training data of node features, adjacency matrices and masks and score labels\n :param validation_data: the validation data of node features, adjacency matrices and masks and score labels\n :return:\n '''\n # load the data as building the model requires the graph order and node features dimensions beforehand\n tr_feats, tr_adjs, tr_biases = training_data['ftr_in'], training_data['adj_in'], training_data['bias_in']\n tr_scores = training_data['score_in']\n\n # the graph order of example graphs\n N = tr_adjs.shape[-1]\n # the initial node features dimension\n F = tr_feats.shape[-1]\n # build the architecture\n if not self.is_built:\n self.build(features_shape=(N, F))\n\n # if the model is already trained and its parameters saved on disk, load them into the skeleton\n if os.path.exists(self.config.checkpoint_file()):\n self.model.load_weights(self.config.checkpoint_file())\n self.is_trained = True\n return\n # report the number training examples\n print('The training size is %d for the GAT model %s' % (len(tr_feats), self.config))\n\n # define the custom early stopping callback\n custom_early_stop = self.CustomEarlyStopping(**self.params)\n es = EarlyStopping(monitor='val_loss', patience=5)\n # fit the Keras model with the provided data\n history = self.model.fit(x=[tr_feats, tr_adjs, tr_biases],\n y=tr_scores,\n batch_size=self.params['batch_size'],\n epochs=self.params['num_epochs'],\n verbose=0,\n callbacks=[custom_early_stop, es],\n validation_split=0.2,\n validation_data=None,\n shuffle=True,\n class_weight=None,\n sample_weight=None,\n initial_epoch=0,\n steps_per_epoch=None,\n validation_steps=None)\n # save the model weights after training\n self.model.save_weights(self.config.checkpoint_file())\n # save the training history, early stopping logs along with the hyper-parameters configuration\n with open(self.config.logs_file(), 'wb') as logs_binary:\n pickle.dump({'history': history.history,\n 'early_stop': custom_early_stop.get_stopping_data(),\n 'params': self.config.params}, logs_binary)\n self.is_trained = True\n\n def save_results(self, predicted, observed):\n '''\n Save the results of the evaluation of the model: predictions and real scores, the loss on predicting each\n individual trait along with the hyperparameters used\n :param predicted: array of predictions\n :param observed: array of true scores\n :return: dict of these result values\n '''\n # stack the results per trait\n predictions = np.transpose(predicted)\n ts_scores = np.transpose(observed)\n # save the results and losses of the evaluation on disk along with the hyper-parameter configuration\n with open(self.config.results_file(), 'wb') as results_binary:\n results = {'predictions': {},\n 'test_loss': {},\n 'params': self.config.params}\n for index, pers_trait in enumerate(self.config.params['pers_traits_selection']):\n results['predictions'][pers_trait] = list(zip(ts_scores[index], predictions[index]))\n results['test_loss'][pers_trait] = mean_squared_error(y_true=ts_scores[index],\n y_pred=predictions[index])\n print('The test loss for trait %s is %.2f:' % (pers_trait, results['test_loss'][pers_trait]))\n pickle.dump(results, results_binary)\n return results\n\n def evaluate(self, test_data):\n '''\n Evaluate the trained GAT model.\n :param test_data: the test data of node features, adjacency matrices and masks and score labels\n :return: dict of the evaluation results: metric values and actual predictions\n '''\n if not self.is_trained:\n print('The GAT model %s was not trained yet' % self.config)\n return\n ts_feats, ts_adjs, ts_biases = test_data['ftr_in'], test_data['adj_in'], test_data['bias_in']\n ts_scores = test_data['score_in']\n ts_size = len(ts_feats)\n print('The size of the evaluation set is %d' % ts_size)\n # predict the scores for the evaluation graphs\n predictions = self.model.predict(x=[ts_feats, ts_adjs, ts_biases],\n batch_size=ts_size,\n verbose=0,\n steps=None)\n # clear the memory of the Keras model\n self.delete()\n # calculate the MSE for individual traits even if they were predicted all at once\n return self.save_results(predicted=predictions, observed=ts_scores)\n\n def delete(self):\n '''\n Clear the main memory/ GPU memory of the Keras model and Tensorflow default session\n :return: void\n '''\n # delete the main memory of the GAT model\n del self.model\n # clear the Tensorflow default session\n clear_session()\n","sub_path":"gat_impl/ExecuteGAT.py","file_name":"ExecuteGAT.py","file_ext":"py","file_size_in_byte":11556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"623527286","text":"# Python3 program to find a route by operating BFS \n# from a given matrix(map) \n\nimport collections\n\n# To create a queue\nclass Queue(object):\n def __init__(self):\n self.elements = collections.deque()\n\n def length(self):\n return len(self.elements)\n\n def push(self, x):\n self.elements.append(x)\n\n def pop(self):\n return self.elements.popleft()\n\n# Map for python(0 = wall or object, 1 = path)\ngrid = [[0,0,0,0,0,0,0,0,0,0],\n [0,1,1,1,1,1,1,1,1,0],\n [0,1,0,0,0,0,1,0,1,0],\n [0,1,1,1,1,0,1,0,1,0],\n [0,0,1,0,1,0,1,1,1,0],\n [0,1,1,0,1,1,1,0,1,0],\n [0,0,0,0,0,0,0,0,0,0]]\n\n# Set start point and goal\nstart = (1,5)\ngoal = (8,1)\n\n# Create a queue for BFS\nqueue = Queue()\n\n# Enqueue the start node\nqueue.push(start)\ncame_from = {}\n\nwhile queue.length()>0:\n\n # Dequeue a current vertex from queue\n current = queue.pop()\n\n # If find the goal, break\n if current == goal:\n break\n\n (x,y) = current\n # Get adjacent vertices of the dequeued vertex start.\n # If a adjacent has not been visited, then mark it came_from(=visited) \n # and enqueue it\n candidates = [(x+1, y), (x, y-1), (x-1, y), (x, y+1)]\n for next in [(h,v) for h, v in candidates if grid[v][h] != 0]:\n if next not in came_from:\n queue.push(next)\n came_from[next] = current\n\ncurrent = goal\npath = []\n\n# Path back tracking\nwhile current is not start:\n path.append(current)\n current = came_from[current]\n\n# Print the path from start to goal\npath.reverse()\nprint(path)","sub_path":"Breadth_First_Search/Breadth_First_Search.py","file_name":"Breadth_First_Search.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"164870206","text":"import random\nimport sys\n\nbank = {\"account\" : 200}\nfullDeckOfCards = {}\nclass GameStatus:\n list_shuffledKeys = []\n winLoseStatus = ''\n\nclass ValueCards:\n card_values= []\n userFirstCard = 0\n userSecondCard = 0\n DealerFirstCard = 0\n DealerSecondCard = 0\n findPairs = False\n findFlush = False\n\n#flush you look between the ranges of cards, like creating a deck\n#pairs you look at the value of the mods and if they are the same\n\ngameOver = False\ndef createDeck():\n for i in range(52):\n if(i <= 12):\n fullDeckOfCards[i] = str((i % 13) + 2) + \" of Clubs\"\n if i % 13 == 9:\n fullDeckOfCards[i] = \"Jack of Clubs\"\n if i % 13 == 10:\n fullDeckOfCards[i] = \"Queen of Clubs\"\n if i % 13 == 11:\n fullDeckOfCards[i] = \"King of Clubs\"\n if i % 13 == 12:\n fullDeckOfCards[i] = \"Ace of Clubs\"\n\n if (i > 12 and i <= 25):\n fullDeckOfCards[i] = str((i % 13) + 2) + \" of Diamonds\"\n if i % 13 == 9:\n fullDeckOfCards[i] = \"Jack of Diamonds\"\n if i % 13 == 10:\n fullDeckOfCards[i] = \"Queen of Diamonds\"\n if i % 13 == 11:\n fullDeckOfCards[i] = \"King of Diamonds\"\n if i % 13 == 12:\n fullDeckOfCards[i] = \"Ace of Diamonds\"\n\n if (i >= 26 and i <= 38):\n fullDeckOfCards[i] = str((i % 13) + 2) + \" of Hearts\"\n if i % 13 == 9:\n fullDeckOfCards[i] = \"Jack of Hearts\"\n if i % 13 == 10:\n fullDeckOfCards[i] = \"Queen of Hearts\"\n if i % 13 == 11:\n fullDeckOfCards[i] = \"King of Hearts\"\n if i % 13 == 12:\n fullDeckOfCards[i] = \"Ace of Hearts\"\n\n if (i >= 39 and i <= 51):\n fullDeckOfCards[i] = str((i % 13) + 2) + \" of Spades\"\n if i % 13 == 9:\n fullDeckOfCards[i] = \"Jack of Spades\"\n if i % 13 == 10:\n fullDeckOfCards[i] = \"Queen of Spades\"\n if i % 13 == 11:\n fullDeckOfCards[i] = \"King of Spades\"\n if i % 13 == 12:\n fullDeckOfCards[i] = \"Ace of Spades\"\n\n\ndef exit(string):\n if string == \"0\":\n print('-->> G A M E O V E R <<--')\n sys.exit()\n\ndef prompt():\n print('\\nEnter 1 to play, 0 to quit')\n line = input('2Card Poker> ')\n exit(line)\n\ndef printDeck():\n for i in fullDeckOfCards:\n print(str(i) + \": \" + fullDeckOfCards[GameStatus.list_shuffledKeys[i]])\n\ndef accountBalance():\n if(GameStatus.winLoseStatus == \"lost\"):\n bank['account'] = bank['account'] - int(bet)\n print('Your Account Balance is {}!'.format(bank['account']))\n if (GameStatus.winLoseStatus == \"win\"):\n bank['account'] = bank['account'] + int(bet)\n print('Your Account Balance is {}!'.format(bank['account']))\n\ndef shuffling(dict):\n shuffledKeys = list(fullDeckOfCards)\n\n for i in shuffledKeys:\n print(str(i) + \" \" + str(shuffledKeys[i]))\n random.shuffle(shuffledKeys)\n\n ValueCards.card_values = shuffledKeys\n for i in ValueCards.card_values:\n print(str(i) + \" ** \" + str(ValueCards.card_values[i]))\n\n # for i in shuffledKeys:\n # print(str(i) + \" -- \" + str(shuffledKeys[i]))\n # ValueCards.card_values = shuffledKeys\n\n\n # GameStatus.list_shuffledKeys = shuffledKeys[:52]\n\n\n#checking if deck has less than 3 cards and shuffles deck\ndef deckCheck(array):\n if len(GameStatus.list_shuffledKeys) < 3:\n print('Creating new Deck and Shuffling')\n shuffling(fullDeckOfCards)\n # printDeck()\n\ndef __checkRules__():\n GameStatus.winLoseStatus = \"win\"\n accountBalance()\n\ndef firstDeal():\n print('\\nD E A L I N G')\n deckCheck(GameStatus.list_shuffledKeys)\n print('Your First Card is {}'.format(fullDeckOfCards[GameStatus.list_shuffledKeys[0]]))\n GameStatus.list_shuffledKeys.pop(0)\n print('Your Second Card is {}'.format(fullDeckOfCards[GameStatus.list_shuffledKeys[0]]))\n GameStatus.list_shuffledKeys.pop(0)\n print('Dealers First Card is {}'.format(fullDeckOfCards[GameStatus.list_shuffledKeys[0]]))\n GameStatus.list_shuffledKeys.pop(0)\n print('Dealers Second Card is |-|')\n\ndef secondDeal():\n print('Dealers Second Card is {}'.format(fullDeckOfCards[GameStatus.list_shuffledKeys[0]]))\n GameStatus.list_shuffledKeys.pop(0)\n\ndef printDeck2():\n for i in GameStatus.list_shuffledKeys:\n print(str(i) + \": \" + fullDeckOfCards[GameStatus.list_shuffledKeys[i]])\n\n\n\n# for i in GameStatus.list_shuffledKeys:\n# print(GameStatus.list_shuffledKeys[i])\n\ncreateDeck()\nshuffling(fullDeckOfCards)\n\n# printDeck2()\n# printDeck()\n\nfor i in ValueCards.card_values:\n print( str(i)+ \" \" + str(ValueCards.card_values[i]))\n\nprompt()\nfirstDeal()\nwhile(gameOver == False):\n # check deck and shuffle\n deckCheck(GameStatus.list_shuffledKeys)\n # print the shuffled deck\n bet = input('Enter your bet $')\n secondDeal()\n __checkRules__()\n prompt()\n firstDeal()\n","sub_path":"Python/Fall_2016/Homework/lab_04_scratch.py","file_name":"lab_04_scratch.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"183061137","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n if l1 == None:\n return l2\n if l2 == None:\n return l1\n if l1.val <= l2.val:\n result = ListNode(l1.val)\n result.next = self.mergeTwoLists(l1.next, l2)\n else:\n result = ListNode(l2.val)\n result.next = self.mergeTwoLists(l1, l2.next)\n return result\n","sub_path":"21. Merge Two Sorted Lists.py","file_name":"21. Merge Two Sorted Lists.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"152953358","text":"import KratosMultiphysics as Kratos\nimport KratosMultiphysics.FluidDynamicsApplication as KratosFluid\nimport KratosMultiphysics.KratosUnittest as UnitTest\nimport KratosMultiphysics.kratos_utilities as KratosUtils\n\nclass FluidAuxiliaryUtilitiesTest(UnitTest.TestCase):\n\n def setUp(self):\n self.model = Kratos.Model()\n fluid_model_part = self.model.CreateModelPart(\"FluidModelPart\")\n fluid_model_part.SetBufferSize(2)\n fluid_model_part.ProcessInfo.SetValue(Kratos.DOMAIN_SIZE, 2)\n fluid_model_part.AddNodalSolutionStepVariable(Kratos.DISTANCE)\n fluid_model_part.AddNodalSolutionStepVariable(Kratos.VELOCITY)\n Kratos.ModelPartIO(\"Cavity/square5\").ReadModelPart(fluid_model_part)\n\n def testCalculateFluidVolume(self):\n fluid_model_part = self.model.GetModelPart(\"FluidModelPart\")\n fluid_volume = KratosFluid.FluidAuxiliaryUtilities.CalculateFluidVolume(fluid_model_part)\n self.assertAlmostEqual(fluid_volume, 1.0, 12)\n\n def testCalculateFluidPositiveVolume(self):\n # Set fluid level set\n level_set_y = 1.0/3.0\n fluid_model_part = self.model.GetModelPart(\"FluidModelPart\")\n for node in fluid_model_part.Nodes:\n node.SetSolutionStepValue(Kratos.DISTANCE, 0, node.Y - level_set_y)\n\n # Calculate the fluid positive volume\n fluid_positive_volume = KratosFluid.FluidAuxiliaryUtilities.CalculateFluidPositiveVolume(fluid_model_part)\n self.assertAlmostEqual(fluid_positive_volume, 1.0 - level_set_y, 12)\n\n def testCalculateFluidNegativeVolume(self):\n # Set fluid level set\n level_set_y = 2.0/3.0\n fluid_model_part = self.model.GetModelPart(\"FluidModelPart\")\n for node in fluid_model_part.Nodes:\n node.SetSolutionStepValue(Kratos.DISTANCE, 0, node.Y - level_set_y)\n\n # Calculate the fluid negative volume\n fluid_negative_volume = KratosFluid.FluidAuxiliaryUtilities.CalculateFluidNegativeVolume(fluid_model_part)\n self.assertAlmostEqual(fluid_negative_volume, level_set_y, 12)\n\n def testCalculateFlowRatePositiveSkin(self):\n # Set fluid level set\n level_set_y = 2.0/3.0\n fluid_model_part = self.model.GetModelPart(\"FluidModelPart\")\n for node in fluid_model_part.Nodes:\n node.SetSolutionStepValue(Kratos.VELOCITY, 0, [1.0,0.0,0.0])\n node.SetSolutionStepValue(Kratos.DISTANCE, 0, node.Y - level_set_y)\n\n # Call the tetrahedral mesh orientation process to calculate the normals and neighbours\n tmoc = Kratos.TetrahedralMeshOrientationCheck\n throw_errors = False\n flags = (tmoc.COMPUTE_NODAL_NORMALS).AsFalse() | (tmoc.COMPUTE_CONDITION_NORMALS).AsFalse() | tmoc.ASSIGN_NEIGHBOUR_ELEMENTS_TO_CONDITIONS\n Kratos.TetrahedralMeshOrientationCheck(fluid_model_part, throw_errors, flags).Execute()\n\n # Calculate the left wall flow\n ref_positive_flow_rate_left = -1.0/3.0\n left_skin_model_part = self.model.GetModelPart(\"FluidModelPart.NoSlip2D_left_wall\")\n for cond in left_skin_model_part.Conditions:\n cond.Set(Kratos.INLET, True)\n positive_flow_rate_left = KratosFluid.FluidAuxiliaryUtilities.CalculateFlowRatePositiveSkin(left_skin_model_part, Kratos.INLET)\n self.assertAlmostEqual(positive_flow_rate_left, ref_positive_flow_rate_left, 12)\n\n # Calculate the right wall flow\n ref_positive_flow_rate_right = 1.0/3.0\n right_skin_model_part = self.model.GetModelPart(\"FluidModelPart.NoSlip2D_right_wall\")\n for cond in right_skin_model_part.Conditions:\n cond.Set(Kratos.OUTLET, True)\n positive_flow_rate_right = KratosFluid.FluidAuxiliaryUtilities.CalculateFlowRatePositiveSkin(right_skin_model_part, Kratos.OUTLET)\n self.assertAlmostEqual(positive_flow_rate_right, ref_positive_flow_rate_right, 12)\n\n # Calculate the top wall flow (without flag)\n ref_positive_flow_rate_top = 0.0\n top_skin_model_part = self.model.GetModelPart(\"FluidModelPart.NoSlip2D_top_wall\")\n positive_flow_rate_top = KratosFluid.FluidAuxiliaryUtilities.CalculateFlowRatePositiveSkin(top_skin_model_part)\n self.assertAlmostEqual(positive_flow_rate_top, ref_positive_flow_rate_top, 12)\n\n def testCalculateFlowRateNegativeSkin(self):\n # Set fluid level set\n level_set_y = 2.0/3.0\n fluid_model_part = self.model.GetModelPart(\"FluidModelPart\")\n for node in fluid_model_part.Nodes:\n node.SetSolutionStepValue(Kratos.VELOCITY, 0, [1.0,0.0,0.0])\n node.SetSolutionStepValue(Kratos.DISTANCE, 0, node.Y - level_set_y)\n\n # Call the tetrahedral mesh orientation process to calculate the normals and neighbours\n tmoc = Kratos.TetrahedralMeshOrientationCheck\n throw_errors = False\n flags = (tmoc.COMPUTE_NODAL_NORMALS).AsFalse() | (tmoc.COMPUTE_CONDITION_NORMALS).AsFalse() | tmoc.ASSIGN_NEIGHBOUR_ELEMENTS_TO_CONDITIONS\n Kratos.TetrahedralMeshOrientationCheck(fluid_model_part, throw_errors, flags).Execute()\n\n # Calculate the left wall flow\n ref_negative_flow_rate_left = -2.0/3.0\n left_skin_model_part = self.model.GetModelPart(\"FluidModelPart.NoSlip2D_left_wall\")\n for cond in left_skin_model_part.Conditions:\n cond.Set(Kratos.INLET, True)\n negative_flow_rate_left = KratosFluid.FluidAuxiliaryUtilities.CalculateFlowRateNegativeSkin(left_skin_model_part, Kratos.INLET)\n self.assertAlmostEqual(negative_flow_rate_left, ref_negative_flow_rate_left, 12)\n\n # Calculate the right wall flow\n ref_negative_flow_rate_right = 2.0/3.0\n right_skin_model_part = self.model.GetModelPart(\"FluidModelPart.NoSlip2D_right_wall\")\n for cond in right_skin_model_part.Conditions:\n cond.Set(Kratos.OUTLET, True)\n negative_flow_rate_right = KratosFluid.FluidAuxiliaryUtilities.CalculateFlowRateNegativeSkin(right_skin_model_part, Kratos.OUTLET)\n self.assertAlmostEqual(negative_flow_rate_right, ref_negative_flow_rate_right, 12)\n\n # Calculate the top wall flow (without flag)\n ref_negative_flow_rate_top = 0.0\n top_skin_model_part = self.model.GetModelPart(\"FluidModelPart.NoSlip2D_top_wall\")\n negative_flow_rate_top = KratosFluid.FluidAuxiliaryUtilities.CalculateFlowRateNegativeSkin(top_skin_model_part)\n self.assertAlmostEqual(negative_flow_rate_top, ref_negative_flow_rate_top, 12)\n\n def tearDown(self):\n KratosUtils.DeleteFileIfExisting(\"Cavity/square5.time\")\n\n\nif __name__ == '__main__':\n UnitTest.main()\n","sub_path":"applications/FluidDynamicsApplication/tests/test_fluid_auxiliary_utilities.py","file_name":"test_fluid_auxiliary_utilities.py","file_ext":"py","file_size_in_byte":6598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"337990794","text":"import csv\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data as Data\nimport pandas as pd\nimport numpy as np\n\nBATCH_SIZE = 2000000\nCROSS_VALIDATION_NUM = 5\n\n\nclass TestNet(nn.Module):\n def __init__(self, n_input, n_hidden_1, n_hidden_2, n_hidden_3, n_output):\n super(TestNet, self).__init__()\n self.l1 = nn.Linear(n_input, n_hidden_1)\n self.l2 = nn.Linear(n_hidden_1, n_hidden_2)\n self.l3 = nn.Linear(n_hidden_2, n_hidden_3)\n self.l4 = nn.Linear(n_hidden_3, n_output)\n\n def forward(self, x):\n x = F.relu(self.l1(x))\n x = F.sigmoid(self.l2(x))\n x = F.relu(self.l3(x))\n x = self.l4(x)\n return x\n\n\nmonth_to_season = [3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3]\n\ndef csv_reader(read_path='file/train.csv', header=0, chunksize=5000000):\n pd_reader = pd.read_csv(read_path, header=header, chunksize=chunksize)\n for chunk_index, chunk in enumerate(pd_reader):\n df = pd.DataFrame(chunk)\n df.rename(columns={'fare_amount': 'fare',\n 'pickup_datetime': 'datetime',\n 'pickup_longitude': 'slong',\n 'pickup_latitude': 'slati',\n 'dropoff_longitude': 'elong',\n 'dropoff_latitude': 'elati',\n 'passenger_count': 'pnum',}, inplace = True)\n\n # df['year'] = list(int(datetime[:4]) for datetime in df['datetime'])\n season = pd.get_dummies(list(month_to_season[int(datetime[5:7]) - 1] for datetime in df['datetime']))\n season.index = range(chunk_index * chunksize, chunk_index * chunksize + len(season))\n df['spring'], df['summer'], df['autumn'], df['winter'] = season[0], season[1], season[2], season[3]\n del season\n del df['datetime']\n del df['key']\n\n df['abs_diff_longitude'] = (df.slong - df.elong).abs()\n df['abs_diff_latitude'] = (df.slati - df.elati).abs()\n df = df[(df.abs_diff_longitude<5) & (df.abs_diff_latitude<5)]\n del df['abs_diff_longitude']\n del df['abs_diff_latitude']\n print('csv_reader: ', chunk_index)\n yield torch.tensor(df.values, dtype=torch.float)\n\ntrain_data = torch.cat([partial_tensor for partial_tensor in csv_reader()])\n\ntrain_input = train_data[:, 1:]\ntrain_target = train_data[:, :1]\ndistance = ((train_input[:, 0:1] - train_input[:, 2:3]).abs() + (train_input[:, 1:2] - train_input[:, 3:4]).abs()) * 1000\ntrain_input[:, 3:4] = distance\ntrain_input = train_input[:, 3:]\ntrain_torch_dataset = Data.TensorDataset(train_input, train_target)\n\ntrain_loader = Data.DataLoader(\n dataset=train_torch_dataset,\n batch_size=BATCH_SIZE,\n shuffle=True,\n num_workers=2,\n)\n\ntnet = TestNet(6, 15, 20, 10, 1).cuda()\noptimizer = torch.optim.Adam(tnet.parameters(), lr=0.02)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.2)\nloss_func = torch.nn.MSELoss()\n\nfor epoch in range(25):\n for step, (batch_x, batch_y) in enumerate(train_loader):\n batch_x = batch_x.cuda()\n batch_y = batch_y.cuda()\n out = tnet(batch_x)\n loss = loss_func(out, batch_y)\n optimizer.zero_grad() # clear gradients for next train\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n print('epoch: ' + str(epoch) + ' - step: ' + str(step) + ' - RMSE: ' + str(loss.pow(0.5).item()))\n scheduler.step()\n\n# gen result\ntest_path = 'file/test.csv'\ntest_df = pd.DataFrame(pd.read_csv('file/test.csv', header=0))\ntest_df.rename(columns={'pickup_datetime': 'datetime',\n 'pickup_longitude': 'slong',\n 'pickup_latitude': 'slati',\n 'dropoff_longitude': 'elong',\n 'dropoff_latitude': 'elati',\n 'passenger_count': 'pnum',}, inplace = True)\n\n# test_df['year'] = list(int(datetime[:4]) for datetime in test_df['datetime'])\nseason = pd.get_dummies(list(month_to_season[int(datetime[5:7]) - 1] for datetime in test_df['datetime']))\ntest_df['spring'], test_df['summer'], test_df['autumn'], test_df['winter'] = season[0], season[1], season[2], season[3]\ndel season\ndel test_df['datetime']\ntest_keys = test_df['key'].values\ndel test_df['key']\ntest_input = torch.tensor(test_df.values, dtype=torch.float)\ndistance = ((test_input[:, 0:1] - test_input[:, 2:3]).abs() + (test_input[:, 1:2] - test_input[:, 3:4]).abs()) * 1000\ntest_input[:, 3:4] = distance\ntest_input = test_input[:, 3:]\n\ntest_input = test_input.cuda()\ntest_out = tnet(test_input)\nwrite_list = [['key', 'fare_amount'],]\nfor key, out in zip(test_keys, test_out):\n write_list.append([key, out.item()])\n\nwith open('result.csv', 'w', newline=\"\") as w:\n writer = csv.writer(w)\n if write_list:\n for line in write_list:\n if line[0]:\n line[0] = line[0].strip()\n writer.writerow(line)","sub_path":"kaggleTaxi/script_1.py","file_name":"script_1.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318534184","text":"# holy shit this is spaghet\n\nfrom fractions import Fraction\n\ndef rowswap(m, a, b):\n m[a], m[b] = m[b], m[a]\n print(f'R{a+1}, R{b+1} → R{b+1}, R{a+1}')\n\ndef rowmul(m, a, s):\n m[a] = [x*s for x in m[a]]\n print(f'{s}*R{a+1} → R{a+1}')\n\ndef rowadd(m, a, b, s = 1):\n m[b] = [i*s+j for i,j in zip(m[a], m[b])]\n print(f'{s}*R{a+1} + R{b+1} → R{b+1}')\n \ndef printmat(m, aug=0):\n s = ''\n w = 0\n for r in m:\n for x in r:\n w = max(w, len(str(x)))\n w += 2\n for i,r in enumerate(m):\n if i == 0:\n s += '┌'\n elif i == len(m)-1:\n s += '└'\n else:\n s += '│'\n for j,x in enumerate(r):\n if aug == j and aug != 0:\n if i == 0:\n s += ' ╷'\n elif i == len(m)-1:\n s += ' ╵'\n else:\n s+= ' │'\n s += ' ' * (w-len(str(x)))\n s += str(x)\n if i == 0:\n s += ' ┐\\n'\n elif i == len(m)-1:\n s += ' ┘\\n'\n else:\n s += ' │\\n'\n return s\n \ndef gauss(m):\n for i in range(len(m)):\n if m[i][i] == 0:\n for j in range(len(m)):\n if m[j][i] != 0:\n rowswap(m, i, j)\n break\n pivot = m[i][i]\n if pivot != 1:\n rowmul(m, i, 1/pivot)\n print(printmat(m, aug=len(m)))\n for j in range(i+1, len(m)):\n if -m[j][i] != 0:\n rowadd(m, i, j, -m[j][i])\n print(printmat(m, aug=len(m)))\n\n for i in range(len(m)-2, -1, -1):\n for j in range(len(m)-i-1):\n if -m[i][i+j+1] != 0:\n rowadd(m, i+j+1, i, -m[i][i+j+1])\n print(printmat(m, aug=len(m)))\n\n return m\n\nmat = []\nwhile True:\n inp = input()\n if inp == '':\n break\n mat.append(list(map(Fraction, inp.split(' '))))\nprint(printmat(mat, aug=len(mat)))\ngauss(mat)\n","sub_path":"linalg.py","file_name":"linalg.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"617274183","text":"# Copyright 2017 Google 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.\n\n\"\"\"Handlers related to Constants.\"\"\"\nimport httplib\nimport logging\n\nfrom upvote.gae.modules.upvote_app.api import monitoring\nfrom upvote.gae.modules.upvote_app.api.handlers import base\nfrom upvote.gae.shared.common import handlers\nfrom upvote.shared import constants\n\n\nclass Constant(base.BaseHandler):\n \"\"\"Get the value for a constant.\"\"\"\n\n @property\n def RequestCounter(self):\n return monitoring.constant_requests\n\n @base.RequireCapability(constants.PERMISSIONS.VIEW_CONSTANTS)\n @handlers.RecordRequest\n def get(self, constant): # pylint: disable=g-bad-name\n \"\"\"Get handler for single setting.\n\n NOTE: The `constant` URI parameter will be properly parsed if it contains\n special URI characters (e.g. underscores).\n\n Args:\n constant: str. The name of the constant being requested.\n \"\"\"\n logging.debug('Constants handler get method called.')\n if constant.lower() == 'userrole':\n constant_value = {'UserRole': constants.USER_ROLE.SET_ALL}\n self.respond_json(constant_value)\n else:\n logging.debug('Unknown constant requested: %s', constant)\n self.abort(httplib.NOT_FOUND, explanation='Unknown constant requested')\n","sub_path":"upvote/gae/modules/upvote_app/api/handlers/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"233643633","text":"class BST:\n class Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n def __init__(self, data):\n self.root = self.Node(data)\n\n def find(self, key):\n current = self.root\n\n while current.data != key:\n if key < current.data:\n current = current.left\n else:\n current = current.right\n\n if current == None:\n return None\n\n return current\n\n def insert(self, key):\n node = self.Node(key)\n\n if self.root == None:\n self.root = node\n return\n\n current = self.root\n\n while True:\n parent = current\n\n if key == current.data:\n return\n elif key < current.data:\n current = current.left\n\n if current == None:\n parent.left = node\n return\n else:\n current = current.right\n\n if current == None:\n parent.right = node\n return\n\n def inorder(self):\n vals = []\n self.do_inorder(self.root, vals)\n return vals\n\n def do_inorder(self, node, vals):\n if node != None:\n self.do_inorder(node.left, vals)\n vals.append(node.data)\n self.do_inorder(node.right, vals)\n\n def postorder(self):\n vals = []\n self.do_postorder(self.root, vals)\n return vals\n\n def do_postorder(self, node, vals):\n if node != None:\n self.do_postorder(node.right, vals)\n vals.append(node.data)\n self.do_postorder(node.left, vals)\n\n def min(self):\n current = self.root\n last = None\n\n while current != None:\n last = current\n current = current.left\n\n return last\n\n def max(self):\n current = self.root\n last = None\n\n while current != None:\n last = current\n current = current.right\n\n return last\n\n def get_successor(self, node):\n parent = node\n successor = node\n current = node.right\n\n while current != None:\n parent = successor\n successor = current\n current = current.left\n\n if successor != node.right:\n parent.left = successor.right\n successor.right = node.right\n\n return successor\n\n def delete(self, key):\n current = self.root\n parent = self.root\n del_left = True\n\n while current.data != key:\n parent = current\n\n if key < current.data:\n del_left = True\n current = current.left\n else:\n del_left = False\n current = current.right\n\n if current == None:\n return False\n\n if current.left == None and current.right == None:\n if current == self.root:\n self.root = None\n elif del_left == True:\n parent.left = None\n else:\n parent.right = None\n elif current.right == None:\n if current == self.root:\n self.root = current.left\n elif del_left == True:\n parent.left = current.left\n else:\n parent.right = current.left\n elif current.left == None:\n if current == self.root:\n self.root = current.right\n elif del_left == True:\n parent.left = current.right\n else:\n parent.right = current.right\n else:\n successor = self.get_successor(current)\n\n if current == self.root:\n self.root = successor\n elif del_left == True:\n parent.left = successor\n else:\n parent.right = successor\n\n successor.left = current.left\n\n return True\n","sub_path":"dsa/python/BST.py","file_name":"BST.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"195895190","text":"'''\n@author: MRB\n'''\nimport socket\nimport threading\nimport time\nimport os\nfrom gbn import SendingWindow, RecvingWindow\n\nfrom args import args\nfrom utils import *\nfrom gbn import *\n\nfile_in = 'resource/Harry Potter.txt'\n\nip = '127.0.0.1' # 服务器ip和端口\nport1, port2, port3, port4 = args.port1, args.port2, args.port3, args.port4\ndata_size = args.data_size\n\n\n\ndef get_sw(my_binding, sock_to, file):\n '读文件,调用SW发送,返回一个SenderWindow实例'\n content = [file.encode()]\n with open(file, 'rb') as f:\n while True:\n # time.sleep(1e-2) # significant\n data = f.read(data_size)\n if data == b'':\n break\n content.append(data)\n print(\"共发送%d个包\" % len(content))\n sw = SendingWindow(my_binding, sock_to, content)\n return sw\n\ndef receiver(name, my_binding, sws):\n '接下来在每个receiver线程中,每接收到一个新端口的包就在线程中建立一个新的receiver_window'\n '注意需要知道本端口所有的sender_windows'\n for port in sws:\n sws[port].start() # 开启传输窗口\n all_ports = [] # 记录是否是一个新端口向我方传输数据(包括info和ack)\n rws = {} # 本端口为每个信道对岸都建立一个rw\n cnt = 0\n while True:\n cnt += 1\n print(cnt)\n binpack, sender_ip = my_binding.recvfrom(PDU.size) # 仅接收PDU帧的大小\n seq, ack, info = unpack_pdu(binpack) # 解码数据包\n '''判断有无问题'''\n # 丢包\n if loss_with_rate(loss_rate):\n print(f'Loss: seq={seq}, ack={ack}\\n')\n continue\n # 坏包\n if not crc_check(binpack):\n print(f'check crc error: seq={seq}, ack={ack}\\n')\n continue\n '''此时可以认为是正确的数据包'''\n port = sender_ip[1]\n if port not in all_ports:\n all_ports.append(port) # 加到数组里\n rws[port] = RecvingWindow(my_binding, (ip, port))\n rws[port].start()\n\n # 无意义包\n if seq == -1 and ack == -1:\n continue\n if seq == -1:\n 'ack包'\n sws[port].get_ack(ack)\n elif ack == -1:\n 'info包'\n rws[port].get_seq_and_info(seq, info)\n\n\ndef main():\n\n sock1 = (ip, port1)\n sock2 = (ip, port2)\n sock3 = (ip, port3)\n sock4 = (ip, port4)\n\n binding1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n binding2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n binding3 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n binding4 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n binding1.bind(sock1)\n binding2.bind(sock2)\n binding3.bind(sock3)\n binding4.bind(sock4)\n\n \"\"\"\n alice_server = threading.Thread(target=receiver, args=(binding1, 'alice'))\n bob_server = threading.Thread(target=receiver, args=(binding2, 'bob'))\n carl_server = threading.Thread(target=receiver, args=(binding3, 'carl'))\n david_server = threading.Thread(target=receiver, args=(binding4, 'david'))\n alice_client = threading.Thread(target=get_sw, args=(binding1, sock2, file_in))\n bob_client = threading.Thread(target=get_sw, args=(binding2, sock1, file_in))\n carl_client = threading.Thread(target=get_sw, args=(binding3, sock4, file_in))\n david_client = threading.Thread(target=get_sw, args=(binding4, sock2, file_in))\n\n # alice_server.start(), alice_client.start()\n # bob_server.start(), bob_client.start()\n # carl_server.start(), carl_client.start()\n # david_server.start(), david_client.start()\n \"\"\"\n\n alice_sws, bob_sws, carl_sws, david_sws = {}, {}, {}, {}\n alice_sws[port2] = get_sw(binding1, sock2, file_in) # a to b\n # alice_sws[port3] = get_sw(binding1, sock3, file_in) # a to c\n bob_sws[port1] = get_sw(binding2, sock1, file_in) # b to a\n\n alice_server = threading.Thread(target=receiver, args=('alice', binding1, alice_sws))\n bob_server = threading.Thread(target=receiver, args=('bob', binding2, bob_sws))\n alice_server.start()\n bob_server.start()\n\n # 全部开始\n\n # 还没有结束处理,所以只能强行停止 todo:改进结束处理\n time.sleep(90)\n # ab_sw.stop()\n # bob_from_alice_rw.stop()\n # 还没办法停止receiver todo:重写receiver\n\n\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"1/Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"241056382","text":"# coding: utf-8\nimport numpy as np\nimport cv2\n\nleft_img = cv2.imread(\"left.jpg\")\nleft_img = cv2.resize(left_img, (600, 400))\nright_img = cv2.imread(\"right.jpg\")\nright_img = cv2.resize(right_img, (600, 400))\nleft_gray = cv2.cvtColor(left_img, cv2.COLOR_BGR2GRAY)\nright_gray = cv2.cvtColor(right_img, cv2.COLOR_BGR2GRAY)\n\n# Set Hessian Threshold to 400 (Bigger the threshold, less the features that can be detected)\nhessian = 300\nsurf = cv2.xfeatures2d.SIFT_create(hessian)\nkp1, des1 = surf.detectAndCompute(left_gray, None) # Look for key points and descriptors\nkp2, des2 = surf.detectAndCompute(right_gray, None)\n\n# kp1s = np.float32([kp.pt for kp in kp1])\n# kp2s = np.float32([kp.pt for kp in kp2])\n\n# Draw key points\nimg_with_drawKeyPoint_left = cv2.drawKeypoints(left_gray, kp1, np.array([]), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\ncv2.imshow(\"img_with_drawKeyPoint_left\", img_with_drawKeyPoint_left)\n\nimg_with_drawKeyPoint_right = cv2.drawKeypoints(right_gray, kp2, np.array([]), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\ncv2.imshow(\"img_with_drawKeyPoint_right\", img_with_drawKeyPoint_right)\n\n'''\nBFMatcher: Brute-Force Matcher, which means trying all matches and find the best one\n\nFlannBasedMatcher: Fast Library for Approximate Nearest Neighbors, which is not necessarily the best matche but much faster\nParameters can be adjusted to increase the accuracy or change the speed of algorithm\nReference: https://blog.csdn.net/claroja/article/details/83411108\n'''\nFLANN_INDEX_KDTREE = 0 # FLANN parameter setting\n\nindexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) # Set index, 5 KD trees\nsearchParams = dict(checks=50) # Set iteration\n# FlannBasedMatcher: fastest feature match algorithm now (search for the approximate nearest neighbor)\nflann = cv2.FlannBasedMatcher(indexParams, searchParams) # Set matcher\n\n# Reference: https://docs.opencv.org/master/db/d39/classcv_1_1DescriptorMatcher.html#a378f35c9b1a5dfa4022839a45cdf0e89\n'''\nint queryIdx –>是测试图像的特征点描述符(descriptor)的下标,同时也是描述符对应特征点(keypoint)的下标。\n\nint trainIdx –> 是样本图像的特征点描述符的下标,同样也是相应的特征点的下标。\n\nint imgIdx –>当样本是多张图像的话有用。\n\nfloat distance –>代表这一对匹配的特征点描述符(本质是向量)的欧氏距离,数值越小也就说明两个特征点越相像。\n'''\n\nmatches = flann.knnMatch(des1, des2, k=2) # Get matched key points\n\ngood = []\n# Extract good feature points\nfor m, n in matches:\n if m.distance < 0.7 * n.distance:\n good.append(m)\n\nsrc_pts = np.array([kp1[m.queryIdx].pt for m in good]) # Descriptor index of searching image\ndst_pts = np.array([kp2[m.trainIdx].pt for m in good]) # Descriptor index of training/model image\n\n# findHomography: https://docs.opencv.org/master/d9/d0c/group__calib3d.html#ga4abc2ece9fab9398f2e560d53c8c9780\n# Homography: https://www.cnblogs.com/wangguchangqing/p/8287585.html\nH = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5) # Generate matrix of transformation\n\nh1, w1 = left_gray.shape[:2]\nh2, w2 = right_gray.shape[:2]\nshift = np.array([[1.0, 0, w1], [0, 1.0, 0], [0, 0, 1.0]])\n# Dot product / Scalar product\nM = np.dot(shift, H[0]) # Get the mapping from left image to right image\n\n# Perspective transformation, new image could contain completely 2 images\ndst = cv2.warpPerspective(left_img, M, (w1+w2, max(h1, h2)))\ncv2.imshow('left_img', dst) # Display left image in the standard position\ndst[0:h2, w1:w1+w2] = right_img # Put 2nd image on the right\n# cv2.imwrite('tiled.jpg',dst_corners)\ncv2.imshow('total_img', dst)\ncv2.imshow('leftgray', left_img)\ncv2.imshow('rightgray', right_img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"P01_ImageStitching/01_UsingCVSIFT/ImageStitching.py","file_name":"ImageStitching.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"414588473","text":"\"\"\"\npicture.py\nAuthor: James Eiler\nCredit: Instruction and Tutorials From Mr Dennison\n\nAssignment:\n\nUse the ggame library to \"paint\" a graphical picture of something (e.g. a house, a face or landscape).\n\nUse at least:\n1. Three different Color objects.\n2. Ten different Sprite objects.\n3. One (or more) RectangleAsset objects.\n4. One (or more) CircleAsset objects.\n5. One (or more) EllipseAsset objects.\n6. One (or more) PolygonAsset objects.\n\nSee:\nhttps://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Displaying-Graphics\nfor general information on how to use ggame.\n\nSee:\nhttp://brythonserver.github.io/ggame/\nfor detailed information on ggame.\n\n\"\"\"\nfrom ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset\n\n# add your code here \\/ \\/ \\/\nfrom ggame import App, Color, LineStyle, Sprite\nfrom ggame import RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset\napp=App()\napp.run()\nred = Color(0xff0000, 1.0)\ngreen = Color(0x00ff00, 1.0)\nblue = Color(0x0000ff, 1.0)\nblack = Color(0x000000, 1.0)\nlinea = LineStyle(1, blue)\nlineb = LineStyle(1, green)\nlinec = LineStyle(1, red)\nrectangle1 = RectangleAsset(20, 80, linea, red)\ncircle1 = CircleAsset(20, lineb, green)\npolygon1 = PolygonAsset([(100,200),(150,100),(3,2)], linec, blue)\nEllipse1 = EllipseAsset(10, 20, linea, red)\ncircle2 = CircleAsset(20, linec, blue)\nSprite(rectangle1, (250, 10))\nSprite(polygon1, (50, 10))\nSprite(Ellipse1, (50, 10))\nSprite(circle1, (275, 375))\nSprite(circle1, (300, 400))\nSprite(rectangle1, (500, 10))\nSprite(polygon1, (500, 300))\nSprite(Ellipse1, (10, 13))\nSprite(rectangle1, (250, 355))\nSprite(circle2, (300, 350))\nSprite(circle2, (325, 375))\n\n\n# add your code here /\\ /\\ /\\\n\n\nmyapp = App()\nmyapp.run()\n","sub_path":"picture.py","file_name":"picture.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"279434899","text":"from Mathlibs import *\r\n\r\nclass Derivative():\r\n\tdef __init__(self,root):\r\n\t\tself.root=root\r\n\t\tself.root.geometry(\"1920x1080\")\r\n\t\tself.root.title(\"Project Math\")\r\n\t\tself.root.config(bg=\"White\")\r\n\r\n\r\n\tdef HeaderLabel(self):\r\n\t\t\r\n\t\tLab1=Label(self.root,text=\"Project Math\",bg=\"BLACK\",fg=\"White\",font=(\"Arial\",20,\"bold\"))\r\n\t\tLab1.pack(fill=X)\r\n\r\n\t\tLab2=Label(self.root,text=\"Math Engine\",bg=\"BLACK\",fg=\"White\",\r\n\t\t\tfont=(\"Arial\",20,\"bold\"),border=5)\r\n\t\tLab2.pack(pady=20)\r\n\r\n\t\tft=IntVar()\r\n\t\tft.set(30)\r\n\r\n\t\tlab3=Button(self.root,text=\"Font Size\",bg=\"BLACK\",fg=\"White\",\r\n\t\tfont=(\"Arial\",10,\"bold\"),relief=GROOVE,border=5)\r\n\t\tlab3.place(x=1200,y=60)\r\n\r\n\t\tfntsize=Entry(self.root,text=ft,font=(\"Arial\",10,\"bold\"),relief=SUNKEN,border=5)\r\n\t\tfntsize.place(x=1200,y=100)\r\n\r\n\t\tself.ft=ft\r\n\r\n\t\t\r\n\r\n\r\n\tdef DerivativeFrame(self):\r\n\t\tx=emoji.emojize(\":red_heart:\")\r\n\t\tf1=LabelFrame(self.root,text=f\"I Love Maths {x}\",bg=\"WHITE\",fg=\"black\",\r\n\t\t\tfont=(\"Arial\",15,\"bold\"),relief=SUNKEN,border=5)\r\n\t\tf1.pack(fill=BOTH)\r\n\r\n\t\tf2=LabelFrame(self.root,bg=\"WHITE\",fg=\"black\",\r\n\t\t\tfont=(\"Arial\",15,\"bold\"),relief=SUNKEN,border=5)\r\n\t\tf2.pack(fill=BOTH,expand=True)\r\n\r\n\t\tf3=LabelFrame(f2,text=\"Function\",width=300,height=480,bg=\"WHITE\",fg=\"black\",\r\n\t\t\tfont=(\"Arial\",15,\"bold\"),relief=GROOVE,border=7)\r\n\t\tf4=LabelFrame(f2,text=\"Derivative of Function\",width=300,height=480,bg=\"WHITE\",fg=\"black\",\r\n\t\t\tfont=(\"Arial\",15,\"bold\"),relief=GROOVE,border=7)\r\n\t\t\r\n\r\n\t\tself.f1=f1\r\n\t\tself.f2=f2\r\n\t\tself.f3=f3\r\n\t\tself.f4=f4\r\n\t\t\r\n\t\t\r\n\tdef EntryFrame(self):\r\n\t\t\"\"\"Label \"\"\"\r\n\t\tlab3=Label(self.f1,text=\"Enter Your Function\",fg=\"Black\",\r\n\t\t\tfont=(\"Arial\",20,\"bold\"),bg=\"White\")\r\n\t\tlab3.grid(row=0,column=0,pady=40)\r\n\t\t\"\"\"Label \"\"\"\r\n\r\n\t\tinp=StringVar()\r\n\t\tres=StringVar()\r\n\t\tres.set(\"x\")\r\n\t\t\"\"\"Entry Widget\"\"\"\r\n\t\tMyinput=Entry(self.f1,text=inp,font=(\"Arial\",30,\"bold\"),relief=SUNKEN,border=5)\r\n\t\tMyinput.grid(row=0,column=1,padx=20)\r\n\t\tMyinput.focus()\r\n\r\n\t\trespectlab=Label(self.f1,text=\"With Respect\",bg=\"White\",font=(\"Arial\",10,\"bold\"))\r\n\t\trespectlab.grid(row=0,column=4)\r\n\r\n\t\trespect=Entry(self.f1,text=res,font=(\"Arial\",10,\"bold\"),relief=SUNKEN,border=5)\r\n\t\trespect.grid(row=0,column=5)\r\n\r\n\t\t\r\n\t\tself.inp=inp\r\n\t\tself.res=res\r\n\tdef eceptclass(self):\r\n\t\tnewlab=Label(self.f2,text=\"Please Check Your Function\",bg=\"BLACK\",fg=\"White\",font=(\"Arial\",60,\"bold\"))\r\n\t\t# newlab.pack(anchor=\"center\",pady=150)\r\n\t\tself.newlab=newlab\r\n\r\n\tdef ButtonFrame(self):\r\n\r\n\t\tdef getdiff():\r\n\t\t\tself.newlab.pack_forget()\r\n\t\t\tself.f2.pack_forget()\r\n\t\t\tself.f3.pack_forget()\r\n\t\t\tself.f4.pack_forget()\r\n\t\t\ttry:\r\n\t\t\t\t\r\n\t\t\t\tself.f2.pack(fill=BOTH,expand=True)\r\n\t\t\t\tlx=self.inp.get()\r\n\t\t\t\tfig0= plt.gca()\r\n\t\t\t\tplt.clf()\r\n\r\n\t\t\t\t# print(diff(self.inp.get()))\r\n\t\t\t\ta,b,c,p,q,r,d,e,f,g,h,i,j,k,l,m,n,o,s,t,u,v,w,y,z=symbols(\"a b c p q r d e f g h i j k l m n o s t u v w y z\")\r\n\t\t\t\tx=Symbol(\"X\")\r\n\t\t\t\ty=Symbol(\"Y\")\r\n\t\t\t\tz=Symbol(\"Z\")\r\n\r\n\t\t\t\tfunc=latex(eval(self.inp.get()))\r\n\r\n\t\t\t\tplt.text(-0.1,0.6,fr\"${func}$\",fontsize=self.ft.get())\r\n\r\n\t\t\t\t\"\"\" Input Function\"\"\" \r\n\r\n\t\t\t\tfig = plt.gca() \r\n\t\t\t\tfig.axes.get_xaxis().set_visible(False) \r\n\t\t\t\tfig.axes.get_yaxis().set_visible(False) \r\n\t\t\t\tfig.axes.spines[\"left\"].set_color(\"none\")\r\n\t\t\t\tfig.axes.spines[\"right\"].set_color(\"none\")\r\n\t\t\t\tfig.axes.spines[\"top\"].set_color(\"none\")\r\n\t\t\t\tfig.axes.spines[\"bottom\"].set_color(\"none\") \r\n\t\t\t\tplt.draw() #or savefig \r\n\t\t\t\tplt.savefig(\"1.png\")\r\n\t\t\t\timg = Image.open(\"1.png\")\r\n\t\t\t\timg.mode = 'RGBA' \r\n\t\t\t\t# img = img.resize((750, 590), Image.ANTIALIAS)\r\n\t\t\t\tprint(img.size)\r\n\t\t\t\tpimg = ImageTk.PhotoImage(img)\r\n\t\t\t\tlbl = Label(self.f3,image=pimg)\r\n\t\t\t\tlbl.image=pimg\r\n\t\t\t\tlbl.grid(row=0,column=1)\r\n\t\t\t\tself.f3.pack(side=LEFT,fill=Y,expand=True)\r\n\t\t\t\tself.plt=plt\r\n\t\t\t\tplt.clf()\r\n\r\n\t\t\t\t\"\"\"Output Function\"\"\"\r\n\r\n\t\t\t\tsymdiff=diff(eval(self.inp.get()),eval(self.res.get()))\r\n\t\t\t\tnewfunc=latex(symdiff)\r\n\r\n\t\t\t\tplt.text(-0.1,0.6,fr\"${newfunc}$\",fontsize=self.ft.get())\r\n\t \r\n\t\t\t\tfig1 = plt.gca() \r\n\t\t\t\tfig1.axes.get_xaxis().set_visible(False) \r\n\t\t\t\tfig1.axes.get_yaxis().set_visible(False) \r\n\t\t\t\tfig1.axes.spines[\"left\"].set_color(\"none\")\r\n\t\t\t\tfig1.axes.spines[\"right\"].set_color(\"none\")\r\n\t\t\t\tfig1.axes.spines[\"top\"].set_color(\"none\")\r\n\t\t\t\tfig1.axes.spines[\"bottom\"].set_color(\"none\") \r\n\t\t \r\n\t\t\t\tplt.savefig(\"2.png\")\r\n\r\n\r\n\t\t\t\timg1 = Image.open(\"2.png\")\r\n\t\t\t\timg1.mode = 'RGBA' \r\n\t\t\t\t# img = img.resize((1360, 500), Image.ANTIALIAS)\r\n\t\t\r\n\r\n\t\t\t\tpimgpic = ImageTk.PhotoImage(img1)\r\n\t\t\t\tlbl1 = Label(self.f4,image=pimgpic)\r\n\t\t\t\tlbl1.image=pimgpic\r\n\t\t\t\tlbl1.grid(row=0,column=1)\r\n\t\t\t\tself.f4.pack(side=RIGHT,fill=Y,expand=True)\r\n\t\t\texcept:\r\n\t\t\t\tself.newlab.pack(anchor=\"center\",pady=150)\r\n\t\t\t\t\r\n\t\tdef clear():\r\n\t\t\tself.f2.pack_forget()\r\n\t\t\tself.f3.pack_forget()\r\n\t\t\tself.f4.pack_forget()\r\n\t\t\tself.newlab.pack_forget()\r\n\t\t\tself.plt.clf()\r\n\t\t\tself.plt.clf()\r\n\t\tmybutton=Button(self.f1,text=\"Derivative\",font=(\"Arial\",10,\"bold\"),relief=GROOVE,border=5,command=getdiff)\r\n\t\tmybutton.grid(row=0,column=2,padx=20)\r\n\t\tclearbutton=Button(self.f1,text=\"Clear\",font=(\"Arial\",10,\"bold\"),relief=GROOVE,border=5,command=clear)\r\n\t\tclearbutton.grid(row=0,column=3,padx=20)\r\n\r\n\r\n\r\n\r\n\r\n# root=Tk()\r\n\r\n# diffr=Derivative(root)\r\n# diffr.HeaderLabel()\r\n# diffr.DerivativeFrame()\r\n# diffr.eceptclass()\r\n# # diffr.InsideFrame()\r\n# diffr.EntryFrame()\r\n# diffr.ButtonFrame()\r\n\r\n# root.mainloop()\r\n","sub_path":"Project Maths/der.py","file_name":"der.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390294995","text":"'''\nColourApp/core.py\nCore starter library\nBy:\n* Ken Shibata, Dec 2018\n'''\n\nimport unpack, validate, copy_\n\nclass core():\n def __init__(self):\n self.pack_path = None\n def _start(self, pack_path):\n self.pack_path = pack_path\n unpacker_inst = unpack.unpack(self.pack_path)\n unpacker_inst._find_format()\n unpacker_inst._unpack()\n validator_inst = validate.validate()\n validator_inst._validate_app_data()\n copier_inst = copy_.copy()\n copier_inst._copy()\n\ndef auto(pack_path):\n core_inst = core()\n core_inst._start(pack_path)\n\nif __name__ == '__main__':\n print(' ColourApp/core.py Direct Run')\n pack_path = input('Input Pack Path ')\n print('Info Starting...')\n core_inst = core()\n core_inst._start(pack_path)\n print('Info Done.')\n","sub_path":"unpacker_result/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66755393","text":"import socket\nimport subprocess\nimport sys\nimport random\n\nprint(\"CS421 testing program, FALL 2018 BILKENT UNIVERSITY\")\nLEN_ARR = 100\n\nport1 = \"10000\"\nport2 = \"10001\"\nport3 = \"10002\"\nport4 = \"10003\"\nport5 = \"10004\"\n\nif(len(sys.argv) == 7):\n port1 = sys.argv[2]\n port2 = sys.argv[3]\n port3 = sys.argv[4]\n port4 = sys.argv[5]\n port5 = sys.argv[6]\n\nports = [port1, port2, port3, port4, port5]\n\noccupancies = [round(random.random() * 100) for i in range(5)]\nproportions = [1 / (u + 1) for u in occupancies]\ndenom = sum(proportions)\nproportions = list(map(lambda x: x/denom, proportions))\nindices = [int(LEN_ARR * p) for p in proportions]\n\nprocesses = []\nfor i in range(5):\n processes.append(subprocess.Popen([sys.executable, 'Operator.py', ports[i], str(occupancies[i]), str(indices[i])], stdout=subprocess.PIPE, stderr=subprocess.STDOUT))\n\naddr = sys.argv[1]\naddr,port = addr.split(':')\nport = int(port)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((addr, port))\n\n# Numbers\nnumbers_list = random.choices(range(0, 30), k=LEN_ARR)\nnumbers = \",\".join(map(str, numbers_list))\nmessage_numbers = (\"DATA:%s\\n\" % numbers).encode(\"utf-8\")\n\n# Functions\nmessage_funcs = (\"FUNCS:%s\\n\" % \"f2,f1,f3,f1\").encode(\"utf-8\")\n\n# Decide whether to send numbers or functions first\nif random.random() > 0.5:\n s.sendall(message_numbers)\n s.sendall(message_funcs)\nelse:\n s.sendall(message_funcs)\n s.sendall(message_numbers)\n\n# =============================================================================\n# Error checking\n# =============================================================================\ntry:\n print(\"Waiting for operators to terminate...\")\n p_outs = []\n for p in processes:\n p_outs.extend(p.communicate(timeout=30)[0].decode(\"utf-8\").splitlines())\n\nexcept subprocess.TimeoutExpired:\n print(\"\"\"Operators could not finish their jobs in 30 seconds. Some possible reasons:\n1) Your code is extremely inefficient,\n2) You forgot to send \"END\" message to the operators,\n3) Operator processes from your previous experiments might be alive and interfering with the sockets. Try different ports.\n\"\"\")\n for p in processes:\n p.kill()\n s.close()\n\nelse: \n error_flag = False\n if \"1\" in p_outs:\n print(\"Too many elements sent to one of the operators. Please check your code.\")\n error_flag = True\n \n while True:\n try:\n p_outs.remove(\"1\")\n except:\n break\n \n if \"2\" in p_outs:\n print(\"Too few elements sent to one of the operators. Please check your code.\")\n error_flag = True\n \n while True:\n try:\n p_outs.remove(\"2\")\n except:\n break\n \n if len(p_outs) != 0:\n error_flag = True\n for e in p_outs:\n print(e)\n \n if error_flag:\n s.close()\n# =============================================================================\n# Error checking\n# =============================================================================\n \n \n else:\n f = s.makefile(buffering=1, encoding=\"utf-8\")\n l = f.readline()\n s.close()\n \n data = l[:-1].split(\":\")[1] \n expected_numbers = [(number ** 2 * 17 + 53) * 17 for number in numbers_list]\n expected_numbers = \",\".join(map(str, expected_numbers)) \n \n if data == expected_numbers:\n print(\"RESULTS ARE CORRECT, YAAAY!\")\n \n else: \n print(\"Received data:\", data, \"\\n\")\n print(\"Expected data:\", expected_numbers, \"\\n\")\n print(\"WRONG RESULTS, PLEASE CHECK YOUR CODE :(\")\n","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"2319981","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nWrite a program which accept one number form user and return addition of its factors.\r\nInput : 12 Output : 16 (1+2+3+4+6\r\n\"\"\"\r\n\r\ndef factors(no):\r\n x=0\r\n for i in range(1,no):\r\n if(no%i==0):\r\n x=x+i\r\n print(i)\r\n return x \r\n \r\ndef main():\r\n num= int(input(\"enter the value\"))\r\n k=factors(num)\r\n print(\"factors of {} is as fallows {} \".format(num,k))\r\n \r\nif __name__==\"__main__\":\r\n main() ","sub_path":"2. assignments/4 factors of given numbers.py","file_name":"4 factors of given numbers.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"554222419","text":"from colorama import Fore, Back\nimport colorama\nimport os\n\n\nclass Console:\n MAX_LINE_LENGTH = 120\n\n PRINT_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&\\'()*+,-./:;?@[\\\\]^_`{|}~ '\n\n font_colours = {\n 'black': Fore.BLACK,\n 'red': Fore.RED,\n 'green': Fore.GREEN,\n 'yellow': Fore.YELLOW,\n 'white': Fore.WHITE,\n 'blue': Fore.BLUE,\n 'light blue': Fore.LIGHTBLUE_EX,\n 'light cyan': Fore.LIGHTCYAN_EX,\n }\n\n background_colours = {\n 'black': Back.BLACK,\n 'red': Back.RED,\n 'green': Back.GREEN,\n 'yellow': Back.YELLOW,\n 'white': Back.WHITE,\n 'blue': Back.BLUE,\n }\n\n style_reset = Fore.RESET + Back.RESET\n\n def __init__(self):\n colorama.init()\n\n def clear(self):\n os.system('cls')\n\n def default_print(self, *args):\n print(*args)\n\n @staticmethod\n def split_into_words(line):\n words = []\n\n for word in line.split(' '):\n words.append(word)\n\n return words\n","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"346756096","text":"import base64\nimport json\nimport os\nfrom functools import wraps\n\nimport requests\n\nfrom flask import abort, request\n\n# Adaption of the jwt extended library for flask\ntry:\n from flask import _app_ctx_stack as ctx_stack\nexcept ImportError: # pragma: no cover\n from flask import _request_ctx_stack as ctx_stack\n\n\ndef jwt_required(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n base_url = os.getenv(\"OPENPATCH_AUTHENTIFICATION_SERVICE\")\n if base_url:\n headers = {\"Authorization\": request.headers.get(\"Authorization\", None)}\n url = \"%s/v1/verify\" % base_url\n r = requests.get(url, headers=headers)\n if r.status_code != 200:\n abort(401)\n return func(*args, **kwargs)\n\n return wrapper\n\n\ndef jwt_roles_required(roles):\n def decorator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n jwt_claims = get_jwt_claims()\n role = jwt_claims.get(\"role\")\n if role not in roles:\n abort(403)\n return func(*args, **kwargs)\n\n return wrapper\n\n return decorator\n\n\ndef get_jwt_claims(optional=False):\n headers = request.headers\n jwt = _decode_jwt_from_headers(headers)\n if jwt is None and optional:\n return None\n elif jwt is None:\n abort(401)\n return jwt.get(\"user_claims\")\n\n\ndef _decode_jwt_from_headers(headers):\n if not headers:\n return None\n jwt_header = headers.get(\"Authorization\", None)\n\n if not jwt_header:\n return None\n\n parts = jwt_header.split()\n jwt = parts[1].split(\".\")\n claims = jwt[1]\n return json.loads(base64url_decode(claims).decode(\"utf-8\"))\n\n\ndef base64url_decode(input):\n if isinstance(input, str):\n input = input.encode(\"ascii\")\n\n rem = len(input) % 4\n\n if rem > 0:\n input += b\"=\" * (4 - rem)\n\n return base64.urlsafe_b64decode(input)\n","sub_path":"openpatch_core/jwt/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"156140959","text":"def pay(hoursByDay, wage):\n \"\"\"\n function pay() takes 2 parameters:\n hoursByDay: a list of hours worked each day of the week\n wage: a float representing hourly wage\n and prints the pay per day as well as total for the week\n \"\"\"\n daysPay = 0\n weeksHours = 0\n weeksPay = 0\n wage = float(wage)\n for day in hoursByDay:\n day = day.split(' ')\n daysPay = 0\n for hour in range(int(day[1])):\n if weeksHours < 40:\n daysPay += wage\n elif weeksHours >= 40 and weeksHours < 60:\n daysPay += (1.5 * wage)\n elif weeksHours >= 60:\n daysPay += (2 * wage)\n weeksHours += 1\n weeksPay += daysPay\n print('On {} you worked {} hours and earned {} dollars'.format(day[0], day[1], daysPay, weeksHours))\n print('This week you made {} dollars'.format(weeksPay))\n\ndef whatLine(fileName, lineNumber):\n \"\"\"\n function whatLine() takes 2 parameters:\n fileName: a string representing a file name\n lineNumber: an integer representing the index of the line to be returned\n and returns the line of the file as determined by lineNumber\n \"\"\" \n infile = open(fileName, 'r')\n lines = infile.readlines()\n try:\n print(lines[int(lineNumber)])\n except IndexError:\n print('Please enter a smaller index')\n infile.close()\n","sub_path":"labs/lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93300578","text":"#!/usr/bin/python\nimport math\n\n\"\"\"\nCombinatoric selections\nProblem 53\nThere are exactly ten ways of selecting three from five, 12345:\n\n123, 124, 125, 134, 135, 145, 234, 235, 245, and 345\n\nIn combinatorics, we use the notation, 5C3 = 10.\n\nIn general,\n\nnCr =\nn!\nr!(n-r)!\n,where r <= n, n! = nx(n-1)x...x3x2x1, and 0! = 1.\nIt is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.\n\nHow many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million?\n\"\"\"\n\ndef chose(x, y):\n return float(math.factorial(x)) / (math.factorial(y) * math.factorial(x - y))\n\ndef main():\n sum = 0\n for i in range(1, 100 + 1):\n for j in range(1, 100 + 1):\n if i > j:\n if chose(i, j) > 1000000:\n sum = sum + 1\n print(sum)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/main/python/projecteuler/problem053.py","file_name":"problem053.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"24412434","text":"class AsyncCamera:\n def __init__(self, session):\n super().__init__()\n self._session = session\n\n def getDeviceCameraAnalyticsLive(self, serial: str):\n \"\"\"\n **Returns live state from camera of analytics zones**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-analytics-live\n\n - serial (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'monitor', 'analytics', 'live'],\n 'operation': 'getDeviceCameraAnalyticsLive'\n }\n resource = f'/devices/{serial}/camera/analytics/live'\n\n return self._session.get(metadata, resource)\n\n def getDeviceCameraAnalyticsOverview(self, serial: str, **kwargs):\n \"\"\"\n **Returns an overview of aggregate analytics data for a timespan**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-analytics-overview\n\n - serial (string): (required)\n - t0 (string): The beginning of the timespan for the data. The maximum lookback period is 365 days from today.\n - t1 (string): The end of the timespan for the data. t1 can be a maximum of 7 days after t0.\n - timespan (number): The timespan for which the information will be fetched. If specifying timespan, do not specify parameters t0 and t1. The value must be in seconds and be less than or equal to 7 days. The default is 1 hour.\n - objectType (string): [optional] The object type for which analytics will be retrieved. The default object type is person. The available types are [person, vehicle].\n \"\"\"\n\n kwargs.update(locals())\n\n if 'objectType' in kwargs:\n options = ['person', 'vehicle']\n assert kwargs['objectType'] in options, f'''\"objectType\" cannot be \"{kwargs['objectType']}\", & must be set to one of: {options}'''\n\n metadata = {\n 'tags': ['camera', 'monitor', 'analytics', 'overview'],\n 'operation': 'getDeviceCameraAnalyticsOverview'\n }\n resource = f'/devices/{serial}/camera/analytics/overview'\n\n query_params = ['t0', 't1', 'timespan', 'objectType', ]\n params = {k.strip(): v for k, v in kwargs.items() if k.strip() in query_params}\n\n return self._session.get(metadata, resource, params)\n\n def getDeviceCameraAnalyticsRecent(self, serial: str, **kwargs):\n \"\"\"\n **Returns most recent record for analytics zones**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-analytics-recent\n\n - serial (string): (required)\n - objectType (string): [optional] The object type for which analytics will be retrieved. The default object type is person. The available types are [person, vehicle].\n \"\"\"\n\n kwargs.update(locals())\n\n if 'objectType' in kwargs:\n options = ['person', 'vehicle']\n assert kwargs['objectType'] in options, f'''\"objectType\" cannot be \"{kwargs['objectType']}\", & must be set to one of: {options}'''\n\n metadata = {\n 'tags': ['camera', 'monitor', 'analytics', 'recent'],\n 'operation': 'getDeviceCameraAnalyticsRecent'\n }\n resource = f'/devices/{serial}/camera/analytics/recent'\n\n query_params = ['objectType', ]\n params = {k.strip(): v for k, v in kwargs.items() if k.strip() in query_params}\n\n return self._session.get(metadata, resource, params)\n\n def getDeviceCameraAnalyticsZones(self, serial: str):\n \"\"\"\n **Returns all configured analytic zones for this camera**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-analytics-zones\n\n - serial (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'monitor', 'analytics', 'zones'],\n 'operation': 'getDeviceCameraAnalyticsZones'\n }\n resource = f'/devices/{serial}/camera/analytics/zones'\n\n return self._session.get(metadata, resource)\n\n def getDeviceCameraAnalyticsZoneHistory(self, serial: str, zoneId: str, **kwargs):\n \"\"\"\n **Return historical records for analytic zones**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-analytics-zone-history\n\n - serial (string): (required)\n - zoneId (string): (required)\n - t0 (string): The beginning of the timespan for the data. The maximum lookback period is 365 days from today.\n - t1 (string): The end of the timespan for the data. t1 can be a maximum of 14 hours after t0.\n - timespan (number): The timespan for which the information will be fetched. If specifying timespan, do not specify parameters t0 and t1. The value must be in seconds and be less than or equal to 14 hours. The default is 1 hour.\n - resolution (integer): The time resolution in seconds for returned data. The valid resolutions are: 60. The default is 60.\n - objectType (string): [optional] The object type for which analytics will be retrieved. The default object type is person. The available types are [person, vehicle].\n \"\"\"\n\n kwargs.update(locals())\n\n if 'objectType' in kwargs:\n options = ['person', 'vehicle']\n assert kwargs['objectType'] in options, f'''\"objectType\" cannot be \"{kwargs['objectType']}\", & must be set to one of: {options}'''\n\n metadata = {\n 'tags': ['camera', 'monitor', 'analytics', 'zones', 'history'],\n 'operation': 'getDeviceCameraAnalyticsZoneHistory'\n }\n resource = f'/devices/{serial}/camera/analytics/zones/{zoneId}/history'\n\n query_params = ['t0', 't1', 'timespan', 'resolution', 'objectType', ]\n params = {k.strip(): v for k, v in kwargs.items() if k.strip() in query_params}\n\n return self._session.get(metadata, resource, params)\n\n def generateDeviceCameraSnapshot(self, serial: str, **kwargs):\n \"\"\"\n **Generate a snapshot of what the camera sees at the specified time and return a link to that image.**\n https://developer.cisco.com/meraki/api-v1/#!generate-device-camera-snapshot\n\n - serial (string): (required)\n - timestamp (string): [optional] The snapshot will be taken from this time on the camera. The timestamp is expected to be in ISO 8601 format. If no timestamp is specified, we will assume current time.\n - fullframe (boolean): [optional] If set to \"true\" the snapshot will be taken at full sensor resolution. This will error if used with timestamp.\n \"\"\"\n\n kwargs.update(locals())\n\n metadata = {\n 'tags': ['camera', 'monitor'],\n 'operation': 'generateDeviceCameraSnapshot'\n }\n resource = f'/devices/{serial}/camera/generateSnapshot'\n\n body_params = ['timestamp', 'fullframe', ]\n payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}\n\n return self._session.post(metadata, resource, payload)\n\n def getDeviceCameraQualityAndRetention(self, serial: str):\n \"\"\"\n **Returns quality and retention settings for the given camera**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-quality-and-retention\n\n - serial (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'configure', 'qualityAndRetention'],\n 'operation': 'getDeviceCameraQualityAndRetention'\n }\n resource = f'/devices/{serial}/camera/qualityAndRetention'\n\n return self._session.get(metadata, resource)\n\n def updateDeviceCameraQualityAndRetention(self, serial: str, **kwargs):\n \"\"\"\n **Update quality and retention settings for the given camera**\n https://developer.cisco.com/meraki/api-v1/#!update-device-camera-quality-and-retention\n\n - serial (string): (required)\n - profileId (string): The ID of a quality and retention profile to assign to the camera. The profile's settings will override all of the per-camera quality and retention settings. If the value of this parameter is null, any existing profile will be unassigned from the camera.\n - motionBasedRetentionEnabled (boolean): Boolean indicating if motion-based retention is enabled(true) or disabled(false) on the camera\n - audioRecordingEnabled (boolean): Boolean indicating if audio recording is enabled(true) or disabled(false) on the camera\n - restrictedBandwidthModeEnabled (boolean): Boolean indicating if restricted bandwidth is enabled(true) or disabled(false) on the camera\n - quality (string): Quality of the camera. Can be one of 'Standard', 'High' or 'Enhanced'. Not all qualities are supported by every camera model.\n - resolution (string): Resolution of the camera. Can be one of '1280x720', '1920x1080', '1080x1080' or '2058x2058'. Not all resolutions are supported by every camera model.\n - motionDetectorVersion (integer): The version of the motion detector that will be used by the camera. Only applies to Gen 2 cameras. Defaults to v2.\n \"\"\"\n\n kwargs.update(locals())\n\n if 'quality' in kwargs:\n options = ['Standard', 'High', 'Enhanced']\n assert kwargs['quality'] in options, f'''\"quality\" cannot be \"{kwargs['quality']}\", & must be set to one of: {options}'''\n if 'resolution' in kwargs:\n options = ['1280x720', '1920x1080', '1080x1080', '2058x2058']\n assert kwargs['resolution'] in options, f'''\"resolution\" cannot be \"{kwargs['resolution']}\", & must be set to one of: {options}'''\n if 'motionDetectorVersion' in kwargs:\n options = [1, 2]\n assert kwargs['motionDetectorVersion'] in options, f'''\"motionDetectorVersion\" cannot be \"{kwargs['motionDetectorVersion']}\", & must be set to one of: {options}'''\n\n metadata = {\n 'tags': ['camera', 'configure', 'qualityAndRetention'],\n 'operation': 'updateDeviceCameraQualityAndRetention'\n }\n resource = f'/devices/{serial}/camera/qualityAndRetention'\n\n body_params = ['profileId', 'motionBasedRetentionEnabled', 'audioRecordingEnabled', 'restrictedBandwidthModeEnabled', 'quality', 'resolution', 'motionDetectorVersion', ]\n payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}\n\n return self._session.put(metadata, resource, payload)\n\n def getDeviceCameraSense(self, serial: str):\n \"\"\"\n **Returns sense settings for a given camera**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-sense\n\n - serial (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'configure', 'sense'],\n 'operation': 'getDeviceCameraSense'\n }\n resource = f'/devices/{serial}/camera/sense'\n\n return self._session.get(metadata, resource)\n\n def updateDeviceCameraSense(self, serial: str, **kwargs):\n \"\"\"\n **Update sense settings for the given camera**\n https://developer.cisco.com/meraki/api-v1/#!update-device-camera-sense\n\n - serial (string): (required)\n - senseEnabled (boolean): Boolean indicating if sense(license) is enabled(true) or disabled(false) on the camera\n - mqttBrokerId (string): The ID of the MQTT broker to be enabled on the camera. A value of null will disable MQTT on the camera\n - detectionModelId (string): The ID of the object detection model\n \"\"\"\n\n kwargs.update(locals())\n\n metadata = {\n 'tags': ['camera', 'configure', 'sense'],\n 'operation': 'updateDeviceCameraSense'\n }\n resource = f'/devices/{serial}/camera/sense'\n\n body_params = ['senseEnabled', 'mqttBrokerId', 'detectionModelId', ]\n payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}\n\n return self._session.put(metadata, resource, payload)\n\n def getDeviceCameraSenseObjectDetectionModels(self, serial: str):\n \"\"\"\n **Returns the MV Sense object detection model list for the given camera**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-sense-object-detection-models\n\n - serial (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'configure', 'sense', 'objectDetectionModels'],\n 'operation': 'getDeviceCameraSenseObjectDetectionModels'\n }\n resource = f'/devices/{serial}/camera/sense/objectDetectionModels'\n\n return self._session.get(metadata, resource)\n\n def getDeviceCameraVideoSettings(self, serial: str):\n \"\"\"\n **Returns video settings for the given camera**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-video-settings\n\n - serial (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'configure', 'video', 'settings'],\n 'operation': 'getDeviceCameraVideoSettings'\n }\n resource = f'/devices/{serial}/camera/video/settings'\n\n return self._session.get(metadata, resource)\n\n def updateDeviceCameraVideoSettings(self, serial: str, **kwargs):\n \"\"\"\n **Update video settings for the given camera**\n https://developer.cisco.com/meraki/api-v1/#!update-device-camera-video-settings\n\n - serial (string): (required)\n - externalRtspEnabled (boolean): Boolean indicating if external rtsp stream is exposed\n \"\"\"\n\n kwargs.update(locals())\n\n metadata = {\n 'tags': ['camera', 'configure', 'video', 'settings'],\n 'operation': 'updateDeviceCameraVideoSettings'\n }\n resource = f'/devices/{serial}/camera/video/settings'\n\n body_params = ['externalRtspEnabled', ]\n payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}\n\n return self._session.put(metadata, resource, payload)\n\n def getDeviceCameraVideoLink(self, serial: str, **kwargs):\n \"\"\"\n **Returns video link to the specified camera**\n https://developer.cisco.com/meraki/api-v1/#!get-device-camera-video-link\n\n - serial (string): (required)\n - timestamp (string): [optional] The video link will start at this time. The timestamp should be a string in ISO8601 format. If no timestamp is specified, we will assume current time.\n \"\"\"\n\n kwargs.update(locals())\n\n metadata = {\n 'tags': ['camera', 'configure', 'videoLink'],\n 'operation': 'getDeviceCameraVideoLink'\n }\n resource = f'/devices/{serial}/camera/videoLink'\n\n query_params = ['timestamp', ]\n params = {k.strip(): v for k, v in kwargs.items() if k.strip() in query_params}\n\n return self._session.get(metadata, resource, params)\n\n def getNetworkCameraQualityRetentionProfiles(self, networkId: str):\n \"\"\"\n **List the quality retention profiles for this network**\n https://developer.cisco.com/meraki/api-v1/#!get-network-camera-quality-retention-profiles\n\n - networkId (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'configure', 'qualityRetentionProfiles'],\n 'operation': 'getNetworkCameraQualityRetentionProfiles'\n }\n resource = f'/networks/{networkId}/camera/qualityRetentionProfiles'\n\n return self._session.get(metadata, resource)\n\n def createNetworkCameraQualityRetentionProfile(self, networkId: str, name: str, **kwargs):\n \"\"\"\n **Creates new quality retention profile for this network.**\n https://developer.cisco.com/meraki/api-v1/#!create-network-camera-quality-retention-profile\n\n - networkId (string): (required)\n - name (string): The name of the new profile. Must be unique. This parameter is required.\n - motionBasedRetentionEnabled (boolean): Deletes footage older than 3 days in which no motion was detected. Can be either true or false. Defaults to false.\n - restrictedBandwidthModeEnabled (boolean): Disable features that require additional bandwidth such as Motion Recap. Can be either true or false. Defaults to false.\n - audioRecordingEnabled (boolean): Whether or not to record audio. Can be either true or false. Defaults to false.\n - cloudArchiveEnabled (boolean): Create redundant video backup using Cloud Archive. Can be either true or false. Defaults to false.\n - motionDetectorVersion (integer): The version of the motion detector that will be used by the camera. Only applies to Gen 2 cameras. Defaults to v2.\n - scheduleId (string): Schedule for which this camera will record video, or 'null' to always record.\n - maxRetentionDays (integer): The maximum number of days for which the data will be stored, or 'null' to keep data until storage space runs out. If the former, it can be one of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 30, 60, 90] days\n - videoSettings (object): Video quality and resolution settings for all the camera models.\n \"\"\"\n\n kwargs.update(locals())\n\n metadata = {\n 'tags': ['camera', 'configure', 'qualityRetentionProfiles'],\n 'operation': 'createNetworkCameraQualityRetentionProfile'\n }\n resource = f'/networks/{networkId}/camera/qualityRetentionProfiles'\n\n body_params = ['name', 'motionBasedRetentionEnabled', 'restrictedBandwidthModeEnabled', 'audioRecordingEnabled', 'cloudArchiveEnabled', 'motionDetectorVersion', 'scheduleId', 'maxRetentionDays', 'videoSettings', ]\n payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}\n\n return self._session.post(metadata, resource, payload)\n\n def getNetworkCameraQualityRetentionProfile(self, networkId: str, qualityRetentionProfileId: str):\n \"\"\"\n **Retrieve a single quality retention profile**\n https://developer.cisco.com/meraki/api-v1/#!get-network-camera-quality-retention-profile\n\n - networkId (string): (required)\n - qualityRetentionProfileId (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'configure', 'qualityRetentionProfiles'],\n 'operation': 'getNetworkCameraQualityRetentionProfile'\n }\n resource = f'/networks/{networkId}/camera/qualityRetentionProfiles/{qualityRetentionProfileId}'\n\n return self._session.get(metadata, resource)\n\n def updateNetworkCameraQualityRetentionProfile(self, networkId: str, qualityRetentionProfileId: str, **kwargs):\n \"\"\"\n **Update an existing quality retention profile for this network.**\n https://developer.cisco.com/meraki/api-v1/#!update-network-camera-quality-retention-profile\n\n - networkId (string): (required)\n - qualityRetentionProfileId (string): (required)\n - name (string): The name of the new profile. Must be unique.\n - motionBasedRetentionEnabled (boolean): Deletes footage older than 3 days in which no motion was detected. Can be either true or false. Defaults to false.\n - restrictedBandwidthModeEnabled (boolean): Disable features that require additional bandwidth such as Motion Recap. Can be either true or false. Defaults to false.\n - audioRecordingEnabled (boolean): Whether or not to record audio. Can be either true or false. Defaults to false.\n - cloudArchiveEnabled (boolean): Create redundant video backup using Cloud Archive. Can be either true or false. Defaults to false.\n - motionDetectorVersion (integer): The version of the motion detector that will be used by the camera. Only applies to Gen 2 cameras. Defaults to v2.\n - scheduleId (string): Schedule for which this camera will record video, or 'null' to always record.\n - maxRetentionDays (integer): The maximum number of days for which the data will be stored, or 'null' to keep data until storage space runs out. If the former, it can be one of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 30, 60, 90] days\n - videoSettings (object): Video quality and resolution settings for all the camera models.\n \"\"\"\n\n kwargs.update(locals())\n\n metadata = {\n 'tags': ['camera', 'configure', 'qualityRetentionProfiles'],\n 'operation': 'updateNetworkCameraQualityRetentionProfile'\n }\n resource = f'/networks/{networkId}/camera/qualityRetentionProfiles/{qualityRetentionProfileId}'\n\n body_params = ['name', 'motionBasedRetentionEnabled', 'restrictedBandwidthModeEnabled', 'audioRecordingEnabled', 'cloudArchiveEnabled', 'motionDetectorVersion', 'scheduleId', 'maxRetentionDays', 'videoSettings', ]\n payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}\n\n return self._session.put(metadata, resource, payload)\n\n def deleteNetworkCameraQualityRetentionProfile(self, networkId: str, qualityRetentionProfileId: str):\n \"\"\"\n **Delete an existing quality retention profile for this network.**\n https://developer.cisco.com/meraki/api-v1/#!delete-network-camera-quality-retention-profile\n\n - networkId (string): (required)\n - qualityRetentionProfileId (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'configure', 'qualityRetentionProfiles'],\n 'operation': 'deleteNetworkCameraQualityRetentionProfile'\n }\n resource = f'/networks/{networkId}/camera/qualityRetentionProfiles/{qualityRetentionProfileId}'\n\n return self._session.delete(metadata, resource)\n\n def getNetworkCameraSchedules(self, networkId: str):\n \"\"\"\n **Returns a list of all camera recording schedules.**\n https://developer.cisco.com/meraki/api-v1/#!get-network-camera-schedules\n\n - networkId (string): (required)\n \"\"\"\n\n metadata = {\n 'tags': ['camera', 'configure', 'schedules'],\n 'operation': 'getNetworkCameraSchedules'\n }\n resource = f'/networks/{networkId}/camera/schedules'\n\n return self._session.get(metadata, resource)","sub_path":"meraki/aio/api/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":21929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"342134851","text":"class Solution:\n def accountsMerge(self, accounts: [[str]]) -> [[str]]:\n graph = defaultdict(set)\n email_name = defaultdict(str)\n merged_accounts = []\n for acc in accounts:\n emails = acc[1:]\n for email in emails:\n graph[emails[0]].add(email)\n graph[email].add(emails[0])\n for acc in accounts:\n emails = acc[1:]\n name = acc[0]\n for i in range(len(emails)):\n email_name[emails[i]] = name\n visited = set()\n for email in graph:\n stack = defaultdict(list)\n stack = [email]\n connected_emails = []\n while stack:\n email = stack.pop()\n if email in visited:\n continue\n connected_emails.append(email)\n visited.add(email)\n neighbors = graph[email]\n for neigh in neighbors:\n stack.append(neigh)\n if connected_emails:\n merged_accounts.append([email_name[email]] + sorted(connected_emails)) \n return merged_accounts\n","sub_path":"accounts-merge.py","file_name":"accounts-merge.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"244283362","text":"import pandas as pd\r\nfrom datetime import datetime\r\nimport sys\r\nimport time\r\nimport numpy as np\r\n\r\n\r\ndef data_importer(path, all=False, label=True):\r\n\tcsv_file_path = path\r\n\r\n\twith open(csv_file_path, 'r') as f:\r\n\t\tprint('Importing data...')\r\n\t\tdf = pd.read_csv(f)\r\n\r\n\t\tif not all and label:\r\n\t\t\tdf = df.loc[list(map(lambda x: isinstance(x, str), df['mode']))]\r\n\t\telif not all and not label:\r\n\t\t\tdf = df.loc[list(map(lambda x: not isinstance(x, str), df['mode']))]\r\n\t\r\n\t# gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.longitude, df.latitude))\r\n\r\n\tprint('Import complete! Wait a little moment for some other settings...')\r\n\r\n\t# change user id from float to str\r\n\tdf['user_id'] = list(map(lambda x: '0' * (3 - len(str(int(x)))) + str(int(x)), df['user_id']))\r\n\r\n\t# change datetime from str to datetime.datetime\r\n\tdf['datetime'] = list(map(lambda s: datetime.strptime(s, '%Y-%m-%d %H:%M:%S'), df['datetime'].values))\r\n\r\n\t# sort all values according to user ID and datetime\r\n\tdf = df.sort_values(by=['user_id', 'datetime'])\r\n\tdf.index = [i for i in range(len(df))]\r\n\r\n\tprint('Import all complete!')\r\n\treturn df\r\n\r\n\r\ndef calculate_box_plot_characteristics(my_list: list):\r\n result = {}\r\n \r\n result[\"minimum\"] = np.min(my_list)\r\n result[\"maximum\"] = np.max(my_list)\r\n result[\"median\"] = np.median(my_list)\r\n \r\n q1 = np.percentile(my_list, 25)\r\n q3 = np.percentile(my_list, 75)\r\n iqr = q3 - q1\r\n result[\"lower_quartile\"] = q1\r\n result[\"upper_quartile\"] = q3\r\n \r\n lower_whisker = q1 - 1.5 * iqr\r\n upper_whisker = q3 + 1.5 * iqr\r\n rpa_sort = np.sort(my_list)\r\n for i in range(len(rpa_sort)):\r\n if rpa_sort[i] > lower_whisker:\r\n result[\"lower_whisker\"] = rpa_sort[i]\r\n break\r\n if i == len(rpa_sort) - 1:\r\n \tresult[\"lower_whisker\"] = lower_whisker\r\n \tbreak\r\n for i in reversed(range(len(rpa_sort))):\r\n if rpa_sort[i] < upper_whisker:\r\n result[\"upper_whisker\"] = rpa_sort[i]\r\n break\r\n if i == 0:\r\n \tresult[\"upper_whisker\"] = upper_whisker\r\n \tbreak\r\n \r\n return result\r\n\r\n\r\ndef metadata_exporter(df):\r\n\tspeeds = []\r\n\taccs = []\r\n\r\n\tspeed_avg = []\r\n\tacc_avg = []\r\n\tspeed_max = []\r\n\tacc_max = []\r\n\tlabel = []\r\n\tuser_id = []\r\n\tend_time = []\r\n\r\n\r\n\tfor i, row in df.iterrows():\r\n\t\tassert(len(speed_avg) == len(acc_avg) == len(speed_max) == len(acc_max) == len(label) == len(user_id) == len(end_time))\t\t\r\n\t\tif i % 100 == 0: sys.stdout.write('\\r{} / {}'.format(i, len(df)))\r\n\t\tif i == 0 or i == len(df) - 1: \r\n\t\t\tspeeds.append(row['speed'])\r\n\t\t\taccs.append(row['acceleration'])\r\n\r\n\t\telse:\r\n\t\t\tlast_row = df.iloc[i - 1]\r\n\t\t\tduration = row['datetime'] - last_row['datetime']\r\n\t\t\tif duration.seconds > 300 or row['mode'] != last_row['mode'] or row['user_id'] != last_row['user_id']:\r\n\t\t\t\tif speeds and accs:\r\n\t\t\t\t\tspeed_avg.append(np.mean(speeds))\r\n\t\t\t\t\tacc_avg.append(np.mean(accs))\r\n\t\t\t\t\tspeed_max.append(calculate_box_plot_characteristics(speeds)['upper_whisker'])\r\n\t\t\t\t\tacc_max.append(calculate_box_plot_characteristics(accs)['upper_whisker'])\r\n\t\t\t\t\tlabel.append(last_row['mode'])\r\n\t\t\t\t\tuser_id.append(last_row['user_id'])\r\n\t\t\t\t\tend_time.append(last_row['datetime'])\r\n\r\n\t\t\t\tspeeds = []\r\n\t\t\t\taccs = []\r\n\r\n\t\t\tspeeds.append(row['speed'])\r\n\t\t\taccs.append(row['acceleration'])\r\n\r\n\tif speeds and accs:\r\n\t\tspeed_avg.append(np.mean(speeds))\r\n\t\tacc_avg.append(np.mean(accs))\r\n\t\tspeed_max.append(calculate_box_plot_characteristics(speeds)['upper_whisker'])\r\n\t\tacc_max.append(calculate_box_plot_characteristics(accs)['upper_whisker'])\r\n\t\tlabel.append(df.iloc[len(df)-1]['mode'])\r\n\t\tuser_id.append(df.iloc[len(df)-1]['user_id'])\r\n\t\tend_time.append(df.iloc[len(df)-1]['datetime'])\r\n\r\n\tassert(len(speed_avg) == len(acc_avg) == len(speed_max) == len(acc_max) == len(label) == len(user_id) == len(end_time))\t\r\n\tmetadata_df = pd.DataFrame(data={'average_speed':speed_avg, 'average_acceleration':acc_avg, 'max_speed':speed_max, 'max_acceleration':acc_max, 'mode':label, 'user_id':user_id, 'end_time':end_time})\r\n\r\n\tprint('\\nCalculate compelete!')\r\n\r\n\treturn metadata_df\r\n\r\n\r\ndef main():\r\n\tpath = './df_all.csv'\r\n\tdf = data_importer(path, all=False, label=True)\r\n\tmetadata_df = metadata_exporter(df)\r\n\r\n\tprint('Writing into metadata_df.csv...')\r\n\tmetadata_df.to_csv('./metadata_df.csv', index=False)\r\n\tprint('All complete!')\r\n\r\n\tsys.exit(0)\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"metadata_exporter.py","file_name":"metadata_exporter.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"231944526","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport pymongo\nfrom pymongo import MongoClient\n#from pymongo import collection\nfrom scrapy.conf import settings\nfrom scrapy import log\n\n\nclass TestsearchPipeline(object):\n def __init__(self):\n self.server = settings['MONGODB_SERVER']\n self.port = settings['MONGODB_PORT']\n self.db = settings['MONGODB_DB']\n self.col = settings['MONGODB_COLLECTION']\n connection = pymongo.Connection(self.server, self.port)\n db = connection[self.db]\n self.collection = db[self.col]\n \n \n\n \n #self.db = MongoClient().htmlcache\n \n def process_item(self, item, spider):\n valid = True\n for data in item:\n # here we only check if the data is not null\n # but we could do any crazy validation we want\n \t if not data:\n valid = False\n raise DropItem(\"Missing %s of blogpost from %s\" %(data, item['url']))\n if valid:\n self.collection.insert(dict(item))\n log.msg(\"Item wrote to MongoDB database %s/%s\" %\n (settings['MONGODB_DB'], settings['MONGODB_COLLECTION']),\n level=log.DEBUG, spider=spider) \n return item\n \n \n \n \n \n \n #self.collection.insert(dict(item))\n #return item\n","sub_path":"backup/testsearch/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"592735645","text":"\"\"\"Kerasのカスタムレイヤーなど。\"\"\"\nimport numpy as np\nimport tensorflow as tf\n\nimport pytoolkit as tk\n\nfrom . import utils as tk_utils\n\nK = tf.keras.backend\n\n\n@tk_utils.register_keras_custom_object\nclass ConvertColor(tf.keras.layers.Layer):\n \"\"\"ColorNet 用の色変換とついでにスケーリング。\n\n 入力は[0, 255]、出力はモード次第だが-3 ~ +3程度。\n\n Args:\n mode:\n 'rgb_to_rgb'\n 'rgb_to_lab'\n 'rgb_to_hsv'\n 'rgb_to_yuv'\n 'rgb_to_ycbcr'\n 'rgb_to_hed'\n 'rgb_to_yiq'\n のいずれか。\n\n \"\"\"\n\n def __init__(self, mode: str, **kargs):\n super().__init__(**kargs)\n self.mode = mode\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def call(self, inputs, **kwargs):\n del kwargs\n if self.mode == \"rgb_to_rgb\":\n outputs = inputs / 127.5 - 1\n elif self.mode == \"rgb_to_lab\":\n x = inputs / 255\n mask = K.cast(x > 0.04045, \"float32\")\n t = mask * K.pow((x + 0.055) / 1.055, 2.4) + (1 - mask) * (x / 12.92)\n m = K.constant(\n np.transpose(\n [\n [0.412453, 0.357580, 0.180423],\n [0.212671, 0.715160, 0.072169],\n [0.019334, 0.119193, 0.950227],\n ]\n )\n )\n xyz = K.dot(t, m)\n\n t = xyz / K.constant(\n np.reshape([0.95047, 1.0, 1.08883], (1,) * (K.ndim(inputs) - 1) + (3,))\n )\n mask = K.cast(t > 0.008856, \"float32\")\n fxfyfz = mask * K.pow(t, 1 / 3) + (1 - mask) * (7.787 * t + 16 / 116)\n\n x, y, z = fxfyfz[..., 0], fxfyfz[..., 1], fxfyfz[..., 2]\n L = (1.16 * y) - 0.16\n a = 5 * (x - y)\n b = 2 * (y - z)\n outputs = K.stack([L, a, b], axis=-1)\n elif self.mode == \"rgb_to_hsv\":\n outputs = tf.image.rgb_to_hsv(inputs / 255)\n elif self.mode == \"rgb_to_yuv\":\n outputs = tf.image.rgb_to_yuv(inputs / 255)\n elif self.mode == \"rgb_to_ycbcr\":\n m = K.constant(\n np.transpose(\n [\n [65.481, 128.553, 24.966],\n [-37.797, -74.203, 112.0],\n [112.0, -93.786, -18.214],\n ]\n )\n )\n b = np.array([16, 128, 128]).reshape((1,) * (K.ndim(inputs) - 1) + (3,))\n outputs = (K.dot(inputs / 255, m) + K.constant(b)) / 255\n elif self.mode == \"rgb_to_hed\":\n t = inputs / 255 + 2\n m = K.constant(\n [\n [1.87798274, -1.00767869, -0.55611582],\n [-0.06590806, 1.13473037, -0.1355218],\n [-0.60190736, -0.48041419, 1.57358807],\n ]\n )\n outputs = K.dot(-K.log(t) / K.constant(np.log(10)), m)\n elif self.mode == \"rgb_to_yiq\":\n m = K.constant(\n np.transpose(\n [\n [0.299, 0.587, 0.114],\n [0.59590059, -0.27455667, -0.32134392],\n [0.21153661, -0.52273617, 0.31119955],\n ]\n )\n )\n outputs = K.dot(inputs / 255, m)\n else:\n raise ValueError(f\"Mode error: {self.mode}\")\n return outputs\n\n def get_config(self):\n config = {\"mode\": self.mode}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass RemoveMask(tf.keras.layers.Layer):\n \"\"\"マスクを取り除く。\"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.supports_masking = True\n\n def compute_mask(self, inputs, mask=None): # pylint: disable=useless-return\n _ = inputs, mask\n return None\n\n def call(self, inputs, **kwargs):\n _ = kwargs\n return inputs\n\n\n@tk_utils.register_keras_custom_object\nclass Resize2D(tf.keras.layers.Layer):\n \"\"\"リサイズ。\n\n Args:\n size: (new_height, new_width)\n scale: float (sizeと排他でどちらか必須)\n interpolation: 'bilinear', 'nearest', 'bicubic', 'lanczos3', 'lanczos5', 'area'\n\n \"\"\"\n\n def __init__(self, size=None, scale=None, interpolation=\"bilinear\", **kwargs):\n super().__init__(**kwargs)\n assert (size is None) != (scale is None)\n assert interpolation in (\n \"bilinear\",\n \"nearest\",\n \"bicubic\",\n \"lanczos3\",\n \"lanczos5\",\n \"area\",\n )\n self.size = None if size is None else tuple(size)\n self.scale = None if scale is None else float(scale)\n self.interpolation = interpolation\n\n def compute_output_shape(self, input_shape):\n assert len(input_shape) == 4\n if self.size is not None:\n return (input_shape[0], self.size[0], self.size[1], input_shape[-1])\n else:\n new_h = None if input_shape[1] is None else int(input_shape[1] * self.scale)\n new_w = None if input_shape[2] is None else int(input_shape[2] * self.scale)\n return (input_shape[0], new_h, new_w, input_shape[-1])\n\n def call(self, inputs, **kwargs):\n del kwargs\n method = {\n \"bilinear\": tf.image.ResizeMethod.BILINEAR,\n \"nearest\": tf.image.ResizeMethod.NEAREST_NEIGHBOR,\n \"bicubic\": tf.image.ResizeMethod.BICUBIC,\n \"area\": tf.image.ResizeMethod.AREA,\n }[self.interpolation]\n if self.size is not None:\n size = self.size\n else:\n shape = K.shape(inputs)\n scale = K.constant(self.scale, dtype=\"float32\")\n new_h = K.cast(K.cast(shape[1], \"float32\") * scale, \"int32\")\n new_w = K.cast(K.cast(shape[2], \"float32\") * scale, \"int32\")\n size = (new_h, new_w)\n return tf.image.resize(inputs, size, method=method)\n\n def get_config(self):\n config = {\n \"size\": self.size,\n \"scale\": self.scale,\n \"interpolation\": self.interpolation,\n }\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass CoordChannel1D(tf.keras.layers.Layer):\n \"\"\"CoordConvなレイヤー。\n\n ■[1807.03247] An Intriguing Failing of Convolutional Neural Networks and the CoordConv Solution\n https://arxiv.org/abs/1807.03247\n \"\"\"\n\n def compute_output_shape(self, input_shape):\n assert len(input_shape) == 3\n input_shape = list(input_shape)\n input_shape[-1] += 1\n return tuple(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n input_shape = K.shape(inputs)\n pad_shape = (input_shape[0], input_shape[1], 1)\n ones = tf.ones(pad_shape, K.floatx())\n gradation = K.cast(K.arange(0, input_shape[1]), K.floatx()) / K.cast(\n input_shape[1], K.floatx()\n )\n pad_channel = ones * K.reshape(gradation, (1, input_shape[1], 1))\n return K.concatenate([inputs] + [pad_channel], axis=-1)\n\n\n@tk_utils.register_keras_custom_object\nclass CoordChannel2D(tf.keras.layers.Layer):\n \"\"\"CoordConvなレイヤー。\n\n ■[1807.03247] An Intriguing Failing of Convolutional Neural Networks and the CoordConv Solution\n https://arxiv.org/abs/1807.03247\n \"\"\"\n\n def __init__(self, x_channel=True, y_channel=True, **kwargs):\n super().__init__(**kwargs)\n self.x_channel = x_channel\n self.y_channel = y_channel\n\n def compute_output_shape(self, input_shape):\n assert len(input_shape) == 4\n input_shape = list(input_shape)\n if self.x_channel:\n input_shape[-1] += 1\n if self.y_channel:\n input_shape[-1] += 1\n return tuple(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n input_shape = K.shape(inputs)\n pad_shape = (input_shape[0], input_shape[1], input_shape[2], 1)\n ones = tf.ones(pad_shape, K.floatx())\n pad_channels = []\n if self.x_channel:\n gradation = K.cast(K.arange(0, input_shape[2]), K.floatx()) / K.cast(\n input_shape[2], K.floatx()\n )\n pad_channels.append(ones * K.reshape(gradation, (1, 1, input_shape[2], 1)))\n if self.y_channel:\n gradation = K.cast(K.arange(0, input_shape[1]), K.floatx()) / K.cast(\n input_shape[1], K.floatx()\n )\n pad_channels.append(ones * K.reshape(gradation, (1, input_shape[1], 1, 1)))\n return K.concatenate([inputs] + pad_channels, axis=-1)\n\n def get_config(self):\n config = {\"x_channel\": self.x_channel, \"y_channel\": self.y_channel}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass ChannelPair2D(tf.keras.layers.Layer):\n \"\"\"チャンネル同士の2個の組み合わせの積。\"\"\"\n\n def compute_output_shape(self, input_shape):\n return input_shape[:-1] + ((input_shape[-1] * (input_shape[-1] - 1) // 2),)\n\n def call(self, inputs, **kwargs):\n del kwargs\n ch = K.int_shape(inputs)[-1]\n return K.concatenate(\n [inputs[..., i : i + 1] * inputs[..., i + 1 :] for i in range(ch - 1)],\n axis=-1,\n )\n\n\n@tk_utils.register_keras_custom_object\nclass SyncBatchNormalization(tf.keras.layers.BatchNormalization):\n \"\"\"Sync BN。\"\"\"\n\n def call(self, inputs, training=None, **kwargs): # pylint: disable=arguments-differ\n del kwargs\n return K.in_train_phase(\n lambda: self._bn_train(inputs), lambda: self._bn_test(inputs), training\n )\n\n def _bn_train(self, inputs):\n \"\"\"学習時のBN。\"\"\"\n # self.axisを除く軸で平均・分散を算出する\n target_axis = self.axis\n if isinstance(target_axis, int):\n target_axis = [target_axis]\n stat_axes = [a for a in range(K.ndim(inputs)) if a not in target_axis]\n\n # 平均・分散の算出\n x = inputs if K.dtype(inputs) == \"float32\" else K.cast(inputs, \"float32\")\n mean = K.mean(x, axis=stat_axes)\n squared_mean = K.mean(K.square(x), axis=stat_axes)\n # Sync BN\n if tk.hvd.initialized():\n import horovod.tensorflow as _hvd\n\n mean = _hvd.allreduce(mean, average=True)\n squared_mean = _hvd.allreduce(squared_mean, average=True)\n var = squared_mean - K.square(mean)\n\n # exponential moving average:\n # m_new = m_old * 0.99 + x * 0.01\n # m_new - m_old = (x - m_old) * 0.01\n decay = 1 - self.momentum\n update1 = tf.compat.v1.assign_add(\n self.moving_mean, (mean - self.moving_mean) * decay\n )\n update2 = tf.compat.v1.assign_add(\n self.moving_variance, (var - self.moving_variance) * decay\n )\n self.add_update([update1, update2], inputs)\n\n # y = (x - mean) / (sqrt(var) + epsilon) * gamma + beta\n # = x * gamma / (sqrt(var) + epsilon) + (beta - mean * gamma / (sqrt(var) + epsilon))\n # = x * a + (beta - mean * a)\n a = self.gamma * tf.math.rsqrt(var + 1e-7)\n b = self.beta - mean * a\n return inputs * K.cast(a, K.dtype(inputs)) + K.cast(b, K.dtype(inputs))\n\n def _bn_test(self, inputs):\n \"\"\"予測時のBN。\"\"\"\n a = self.gamma / tf.math.rsqrt(self.moving_variance + 1e-7)\n b = self.beta - self.moving_mean * a\n return inputs * K.cast(a, K.dtype(inputs)) + K.cast(b, K.dtype(inputs))\n\n\n@tk_utils.register_keras_custom_object\nclass GroupNormalization(tf.keras.layers.Layer):\n \"\"\"Group Normalization。\n\n Args:\n groups: グループ数\n\n References:\n - Group Normalization \n\n \"\"\"\n\n def __init__(\n self,\n groups=32,\n epsilon=1e-5,\n center=True,\n scale=True,\n beta_initializer=\"zeros\",\n gamma_initializer=\"ones\",\n beta_regularizer=None,\n gamma_regularizer=None,\n beta_constraint=None,\n gamma_constraint=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.supports_masking = True\n self.groups = groups\n self.epsilon = epsilon\n self.center = center\n self.scale = scale\n self.beta_initializer = tf.keras.initializers.get(beta_initializer)\n self.gamma_initializer = tf.keras.initializers.get(gamma_initializer)\n self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer)\n self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer)\n self.beta_constraint = tf.keras.constraints.get(beta_constraint)\n self.gamma_constraint = tf.keras.constraints.get(gamma_constraint)\n self.gamma = None\n self.beta = None\n\n def build(self, input_shape):\n dim = int(input_shape[-1])\n groups = min(dim, self.groups)\n assert dim is None or dim % groups == 0\n shape = (dim,)\n if self.scale:\n self.gamma = self.add_weight(\n shape=shape,\n name=\"gamma\",\n initializer=self.gamma_initializer,\n regularizer=self.gamma_regularizer,\n constraint=self.gamma_constraint,\n )\n else:\n self.gamma = None\n if self.center:\n self.beta = self.add_weight(\n shape=shape,\n name=\"beta\",\n initializer=self.beta_initializer,\n regularizer=self.beta_regularizer,\n constraint=self.beta_constraint,\n )\n else:\n self.beta = None\n super().build(input_shape)\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def call(self, inputs, **kwargs):\n del kwargs\n x = inputs\n ndim = K.ndim(x)\n shape = K.shape(x)\n if ndim == 4: # 2D\n N, H, W, C = shape[0], shape[1], shape[2], shape[3]\n g = K.minimum(self.groups, C)\n x = K.reshape(x, [N, H, W, g, C // g])\n mean, var = tf.nn.moments(x=x, axes=[1, 2, 4], keepdims=True)\n x = (x - mean) * tf.math.rsqrt(var + self.epsilon)\n x = K.reshape(x, [N, H, W, C])\n elif ndim == 5: # 3D\n N, T, H, W, C = shape[0], shape[1], shape[2], shape[3], shape[4]\n g = K.minimum(self.groups, C)\n x = K.reshape(x, [N, T, H, W, g, C // g])\n mean, var = tf.nn.moments(x=x, axes=[1, 2, 3, 5], keepdims=True)\n x = (x - mean) * tf.math.rsqrt(var + self.epsilon)\n x = K.reshape(x, [N, T, H, W, C])\n else:\n assert ndim in (4, 5)\n if self.scale:\n x = x * self.gamma\n if self.center:\n x = x + self.beta\n # tf.keras用\n x.set_shape(K.int_shape(inputs))\n return x\n\n def get_config(self):\n config = {\n \"groups\": self.groups,\n \"epsilon\": self.epsilon,\n \"center\": self.center,\n \"scale\": self.scale,\n \"beta_initializer\": tf.keras.initializers.serialize(self.beta_initializer),\n \"gamma_initializer\": tf.keras.initializers.serialize(\n self.gamma_initializer\n ),\n \"beta_regularizer\": tf.keras.regularizers.serialize(self.beta_regularizer),\n \"gamma_regularizer\": tf.keras.regularizers.serialize(\n self.gamma_regularizer\n ),\n \"beta_constraint\": tf.keras.constraints.serialize(self.beta_constraint),\n \"gamma_constraint\": tf.keras.constraints.serialize(self.gamma_constraint),\n }\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass InstanceNormalization(tf.keras.layers.Layer):\n \"\"\"Instance Normalization\"\"\"\n\n def __init__(\n self,\n epsilon=1e-5,\n center=True,\n scale=True,\n beta_initializer=\"zeros\",\n gamma_initializer=\"ones\",\n beta_regularizer=None,\n gamma_regularizer=None,\n beta_constraint=None,\n gamma_constraint=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.supports_masking = True\n self.epsilon = epsilon\n self.center = center\n self.scale = scale\n self.beta_initializer = tf.keras.initializers.get(beta_initializer)\n self.gamma_initializer = tf.keras.initializers.get(gamma_initializer)\n self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer)\n self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer)\n self.beta_constraint = tf.keras.constraints.get(beta_constraint)\n self.gamma_constraint = tf.keras.constraints.get(gamma_constraint)\n self.beta = None\n self.gamma = None\n\n def build(self, input_shape):\n affine_shape = (input_shape[-1],)\n if self.scale:\n self.gamma = self.add_weight(\n shape=affine_shape,\n name=\"gamma\",\n initializer=self.gamma_initializer,\n regularizer=self.gamma_regularizer,\n constraint=self.gamma_constraint,\n )\n else:\n self.gamma = None\n if self.center:\n self.beta = self.add_weight(\n shape=affine_shape,\n name=\"beta\",\n initializer=self.beta_initializer,\n regularizer=self.beta_regularizer,\n constraint=self.beta_constraint,\n )\n else:\n self.beta = None\n super().build(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n input_shape = K.int_shape(inputs)\n\n reduction_axes = list(range(1, len(input_shape) - 1))\n mean = K.mean(inputs, reduction_axes, keepdims=True)\n std = K.std(inputs, reduction_axes, keepdims=True)\n outputs = (inputs - mean) / (std + self.epsilon)\n\n broadcast_shape = [1] * len(input_shape)\n broadcast_shape[-1] = input_shape[-1]\n if self.scale:\n outputs = outputs * K.reshape(self.gamma, broadcast_shape)\n if self.center:\n outputs = outputs + K.reshape(self.beta, broadcast_shape)\n\n return outputs\n\n def get_config(self):\n config = {\n \"epsilon\": self.epsilon,\n \"center\": self.center,\n \"scale\": self.scale,\n \"beta_initializer\": tf.keras.initializers.serialize(self.beta_initializer),\n \"gamma_initializer\": tf.keras.initializers.serialize(\n self.gamma_initializer\n ),\n \"beta_regularizer\": tf.keras.regularizers.serialize(self.beta_regularizer),\n \"gamma_regularizer\": tf.keras.regularizers.serialize(\n self.gamma_regularizer\n ),\n \"beta_constraint\": tf.keras.constraints.serialize(self.beta_constraint),\n \"gamma_constraint\": tf.keras.constraints.serialize(self.gamma_constraint),\n }\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass RMSNormalization(tf.keras.layers.Layer):\n \"\"\"Root Mean Square Layer Normalization \"\"\"\n\n def __init__(\n self,\n axis=-1,\n epsilon=1e-7,\n center=True,\n scale=True,\n beta_initializer=\"zeros\",\n gamma_initializer=\"ones\",\n beta_regularizer=None,\n gamma_regularizer=None,\n beta_constraint=None,\n gamma_constraint=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.supports_masking = True\n self.axis = axis\n self.epsilon = epsilon\n self.center = center\n self.scale = scale\n self.beta_initializer = tf.keras.initializers.get(beta_initializer)\n self.gamma_initializer = tf.keras.initializers.get(gamma_initializer)\n self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer)\n self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer)\n self.beta_constraint = tf.keras.constraints.get(beta_constraint)\n self.gamma_constraint = tf.keras.constraints.get(gamma_constraint)\n self.beta = None\n self.gamma = None\n\n def build(self, input_shape):\n affine_shape = (input_shape[-1],)\n if self.scale:\n self.gamma = self.add_weight(\n shape=affine_shape,\n name=\"gamma\",\n initializer=self.gamma_initializer,\n regularizer=self.gamma_regularizer,\n constraint=self.gamma_constraint,\n )\n else:\n self.gamma = None\n if self.center:\n self.beta = self.add_weight(\n shape=affine_shape,\n name=\"beta\",\n initializer=self.beta_initializer,\n regularizer=self.beta_regularizer,\n constraint=self.beta_constraint,\n )\n else:\n self.beta = None\n super().build(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n\n ms = tf.math.reduce_mean(inputs ** 2, axis=self.axis, keepdims=True)\n outputs = inputs * tf.math.rsqrt(ms + self.epsilon)\n\n broadcast_shape = (1,) * (K.ndim(inputs) - 1) + (-1,)\n if self.scale:\n outputs = outputs * tf.reshape(self.gamma, broadcast_shape)\n if self.center:\n outputs = outputs + tf.reshape(self.beta, broadcast_shape)\n\n return outputs\n\n def get_config(self):\n config = {\n \"axis\": self.axis,\n \"epsilon\": self.epsilon,\n \"center\": self.center,\n \"scale\": self.scale,\n \"beta_initializer\": tf.keras.initializers.serialize(self.beta_initializer),\n \"gamma_initializer\": tf.keras.initializers.serialize(\n self.gamma_initializer\n ),\n \"beta_regularizer\": tf.keras.regularizers.serialize(self.beta_regularizer),\n \"gamma_regularizer\": tf.keras.regularizers.serialize(\n self.gamma_regularizer\n ),\n \"beta_constraint\": tf.keras.constraints.serialize(self.beta_constraint),\n \"gamma_constraint\": tf.keras.constraints.serialize(self.gamma_constraint),\n }\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass FilterResponseNormalization(tf.keras.layers.Layer):\n \"\"\"Filter Response Normalization Layer \"\"\"\n\n def __init__(\n self,\n epsilon=1e-6,\n center=True,\n scale=True,\n beta_initializer=\"zeros\",\n gamma_initializer=\"ones\",\n beta_regularizer=None,\n gamma_regularizer=None,\n beta_constraint=None,\n gamma_constraint=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.supports_masking = True\n self.epsilon = epsilon\n self.center = center\n self.scale = scale\n self.beta_initializer = tf.keras.initializers.get(beta_initializer)\n self.gamma_initializer = tf.keras.initializers.get(gamma_initializer)\n self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer)\n self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer)\n self.beta_constraint = tf.keras.constraints.get(beta_constraint)\n self.gamma_constraint = tf.keras.constraints.get(gamma_constraint)\n self.beta = None\n self.gamma = None\n\n def build(self, input_shape):\n affine_shape = (input_shape[-1],)\n if self.scale:\n self.gamma = self.add_weight(\n shape=affine_shape,\n name=\"gamma\",\n initializer=self.gamma_initializer,\n regularizer=self.gamma_regularizer,\n constraint=self.gamma_constraint,\n )\n if self.center:\n self.beta = self.add_weight(\n shape=affine_shape,\n name=\"beta\",\n initializer=self.beta_initializer,\n regularizer=self.beta_regularizer,\n constraint=self.beta_constraint,\n )\n super().build(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n x = inputs\n axes = list(range(1, K.ndim(x) - 1))\n nu2 = tf.math.reduce_mean(tf.math.square(x), axis=axes, keepdims=True)\n x *= tf.math.rsqrt(nu2 + tf.math.abs(self.epsilon))\n if self.scale:\n x *= self.gamma\n if self.center:\n x += self.beta\n return x\n\n def get_config(self):\n config = {\n \"epsilon\": self.epsilon,\n \"center\": self.center,\n \"scale\": self.scale,\n \"beta_initializer\": tf.keras.initializers.serialize(self.beta_initializer),\n \"gamma_initializer\": tf.keras.initializers.serialize(\n self.gamma_initializer\n ),\n \"beta_regularizer\": tf.keras.regularizers.serialize(self.beta_regularizer),\n \"gamma_regularizer\": tf.keras.regularizers.serialize(\n self.gamma_regularizer\n ),\n \"beta_constraint\": tf.keras.constraints.serialize(self.beta_constraint),\n \"gamma_constraint\": tf.keras.constraints.serialize(self.gamma_constraint),\n }\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass TLU(tf.keras.layers.Layer):\n \"\"\"Thresholded Linear Unit \"\"\"\n\n def __init__(\n self,\n tau_initializer=\"zeros\",\n tau_regularizer=None,\n tau_constraint=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.supports_masking = True\n self.tau_initializer = tf.keras.initializers.get(tau_initializer)\n self.tau_regularizer = tf.keras.regularizers.get(tau_regularizer)\n self.tau_constraint = tf.keras.constraints.get(tau_constraint)\n self.tau = None\n\n def build(self, input_shape):\n affine_shape = (input_shape[-1],)\n self.tau = self.add_weight(\n shape=affine_shape,\n name=\"tau\",\n initializer=self.tau_initializer,\n regularizer=self.tau_regularizer,\n constraint=self.tau_constraint,\n )\n super().build(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n return tf.maximum(inputs, self.tau)\n\n def get_config(self):\n config = {\n \"tau_initializer\": tf.keras.initializers.serialize(self.tau_initializer),\n \"tau_regularizer\": tf.keras.regularizers.serialize(self.tau_regularizer),\n \"tau_constraint\": tf.keras.constraints.serialize(self.tau_constraint),\n }\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass RandomRMSNormalization(tf.keras.layers.Layer):\n \"\"\"ランダム要素のあるrmsを使ったnormalization。\"\"\"\n\n def __init__(\n self,\n channel_size=32,\n center=True,\n scale=True,\n beta_initializer=\"zeros\",\n gamma_initializer=\"ones\",\n beta_regularizer=None,\n gamma_regularizer=None,\n beta_constraint=None,\n gamma_constraint=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.supports_masking = True\n self.channel_size = channel_size\n self.center = center\n self.scale = scale\n self.beta_initializer = tf.keras.initializers.get(beta_initializer)\n self.gamma_initializer = tf.keras.initializers.get(gamma_initializer)\n self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer)\n self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer)\n self.beta_constraint = tf.keras.constraints.get(beta_constraint)\n self.gamma_constraint = tf.keras.constraints.get(gamma_constraint)\n self.beta = None\n self.gamma = None\n\n def build(self, input_shape):\n affine_shape = (input_shape[-1],)\n if self.scale:\n self.gamma = self.add_weight(\n shape=affine_shape,\n name=\"gamma\",\n initializer=self.gamma_initializer,\n regularizer=self.gamma_regularizer,\n constraint=self.gamma_constraint,\n )\n if self.center:\n self.beta = self.add_weight(\n shape=affine_shape,\n name=\"beta\",\n initializer=self.beta_initializer,\n regularizer=self.beta_regularizer,\n constraint=self.beta_constraint,\n )\n super().build(input_shape)\n\n def call(self, inputs, training=None, **kwargs):\n del kwargs\n x = inputs\n axes = list(range(1, K.ndim(x)))\n\n if x.shape[-1] <= self.channel_size:\n x_target = x\n else:\n\n def pick_random():\n r = tf.random.uniform(shape=(x.shape[-1],))\n _, indices = tf.nn.top_k(r, self.channel_size)\n return tf.gather(x, indices, axis=-1)\n\n x_target = K.in_train_phase(pick_random, x, training)\n\n nu2 = tf.math.reduce_mean(tf.math.square(x_target), axis=axes, keepdims=True)\n x *= tf.math.rsqrt(nu2 + 1e-6)\n if self.scale:\n x *= self.gamma\n if self.center:\n x += self.beta\n return x\n\n def get_config(self):\n config = {\n \"channel_size\": self.channel_size,\n \"center\": self.center,\n \"scale\": self.scale,\n \"beta_initializer\": tf.keras.initializers.serialize(self.beta_initializer),\n \"gamma_initializer\": tf.keras.initializers.serialize(\n self.gamma_initializer\n ),\n \"beta_regularizer\": tf.keras.regularizers.serialize(self.beta_regularizer),\n \"gamma_regularizer\": tf.keras.regularizers.serialize(\n self.gamma_regularizer\n ),\n \"beta_constraint\": tf.keras.constraints.serialize(self.beta_constraint),\n \"gamma_constraint\": tf.keras.constraints.serialize(self.gamma_constraint),\n }\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass MixFeat(tf.keras.layers.Layer):\n \"\"\"MixFeat \"\"\"\n\n def __init__(self, sigma=0.2, **kargs):\n super().__init__(**kargs)\n self.sigma = sigma\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def call(self, inputs, training=None): # pylint: disable=arguments-differ\n def _passthru():\n return inputs\n\n def _mixfeat():\n @tf.custom_gradient\n def _forward(x):\n shape = K.shape(x)\n indices = K.arange(start=0, stop=shape[0])\n indices = tf.random.shuffle(indices)\n rs = K.concatenate([K.constant([1], dtype=\"int32\"), shape[1:]])\n r = K.random_normal(rs, 0, self.sigma, dtype=\"float16\")\n theta = K.random_uniform(rs, -np.pi, +np.pi, dtype=\"float16\")\n a = 1 + r * K.cos(theta)\n b = r * K.sin(theta)\n y = x * K.cast(a, K.floatx()) + K.gather(x, indices) * K.cast(\n b, K.floatx()\n )\n\n def _backword(dy):\n inv = tf.math.invert_permutation(indices)\n return dy * K.cast(a, K.floatx()) + K.gather(dy, inv) * K.cast(\n b, K.floatx()\n )\n\n return y, _backword\n\n return _forward(inputs)\n\n return K.in_train_phase(_mixfeat, _passthru, training=training)\n\n def get_config(self):\n config = {\"sigma\": self.sigma}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass DropActivation(tf.keras.layers.Layer):\n \"\"\"Drop-Activation \"\"\"\n\n def __init__(self, keep_rate=0.95, **kargs):\n super().__init__(**kargs)\n assert 0 <= keep_rate < 1\n self.keep_rate = keep_rate\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def call(self, inputs, training=None): # pylint: disable=arguments-differ\n def _train():\n shape = K.shape(inputs)\n r = K.random_uniform(shape=(shape[0],) + (1,) * (K.ndim(inputs) - 1))\n return tf.where(r <= self.keep_rate, K.relu(inputs), inputs)\n\n def _test():\n return K.relu(inputs, alpha=1 - self.keep_rate)\n\n return K.in_train_phase(_train, _test, training=training)\n\n def get_config(self):\n config = {\"keep_rate\": self.keep_rate}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass ParallelGridPooling2D(tf.keras.layers.Layer):\n \"\"\"Parallel Grid Poolingレイヤー。\n\n ■ Parallel Grid Pooling for Data Augmentation\n https://arxiv.org/abs/1803.11370\n\n ■ akitotakeki/pgp-chainer: Chainer Implementation of Parallel Grid Pooling for Data Augmentation\n https://github.com/akitotakeki/pgp-chainer\n\n \"\"\"\n\n def __init__(self, pool_size=(2, 2), **kargs):\n super().__init__(**kargs)\n if isinstance(pool_size, int):\n self.pool_size = (pool_size, pool_size)\n else:\n self.pool_size = pool_size\n assert len(self.pool_size) == 2\n\n def compute_output_shape(self, input_shape):\n assert len(input_shape) == 4\n assert input_shape[1] % self.pool_size[0] == 0 # パディングはとりあえず未対応\n assert input_shape[2] % self.pool_size[1] == 0 # パディングはとりあえず未対応\n b, h, w, c = input_shape\n return b, h // self.pool_size[0], w // self.pool_size[1], c\n\n def call(self, inputs, **kwargs):\n del kwargs\n shape = K.shape(inputs)\n int_shape = K.int_shape(inputs)\n rh, rw = self.pool_size\n b, h, w, c = shape[0], shape[1], shape[2], int_shape[3]\n outputs = K.reshape(inputs, (b, h // rh, rh, w // rw, rw, c))\n outputs = tf.transpose(a=outputs, perm=(2, 4, 0, 1, 3, 5))\n outputs = K.reshape(outputs, (rh * rw * b, h // rh, w // rw, c))\n # tf.keras用workaround\n if hasattr(outputs, \"set_shape\"):\n outputs.set_shape(self.compute_output_shape(int_shape))\n return outputs\n\n def get_config(self):\n config = {\"pool_size\": self.pool_size}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass ParallelGridGather(tf.keras.layers.Layer):\n \"\"\"ParallelGridPoolingでparallelにしたのを戻すレイヤー。\"\"\"\n\n def __init__(self, r, **kargs):\n super().__init__(**kargs)\n self.r = r\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def call(self, inputs, **kwargs):\n del kwargs\n shape = K.shape(inputs)\n b = shape[0]\n gather_shape = K.concatenate([[self.r, b // self.r], shape[1:]], axis=0)\n outputs = K.reshape(inputs, gather_shape)\n outputs = K.mean(outputs, axis=0)\n # tf.keras用workaround\n if hasattr(outputs, \"set_shape\"):\n outputs.set_shape(K.int_shape(inputs))\n return outputs\n\n def get_config(self):\n config = {\"r\": self.r}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass SubpixelConv2D(tf.keras.layers.Layer):\n \"\"\"Sub-Pixel Convolutional Layer。\n\n ■ Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network\n https://arxiv.org/abs/1609.05158\n\n \"\"\"\n\n def __init__(self, scale=2, **kargs):\n super().__init__(**kargs)\n self.scale = scale\n\n def compute_output_shape(self, input_shape):\n assert len(input_shape) == 4\n assert input_shape[-1] % (self.scale ** 2) == 0\n h = None if input_shape[1] is None else input_shape[1] * self.scale\n w = None if input_shape[2] is None else input_shape[2] * self.scale\n return input_shape[0], h, w, input_shape[3] // (self.scale ** 2)\n\n def call(self, inputs, **kwargs):\n del kwargs\n return tf.compat.v1.depth_to_space(input=inputs, block_size=self.scale)\n\n def get_config(self):\n config = {\"scale\": self.scale}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass WSConv2D(tf.keras.layers.Conv2D):\n \"\"\"Weight StandardizationなConv2D \"\"\"\n\n def call(self, inputs, **kwargs):\n del kwargs\n\n kernel_mean = K.mean(self.kernel, axis=[0, 1, 2])\n kernel_std = K.std(self.kernel, axis=[0, 1, 2])\n kernel = (self.kernel - kernel_mean) / (kernel_std + 1e-5)\n\n outputs = K.conv2d(\n inputs,\n kernel,\n strides=self.strides,\n padding=self.padding,\n data_format=self.data_format,\n dilation_rate=self.dilation_rate,\n )\n if self.use_bias:\n outputs = K.bias_add(outputs, self.bias, self.data_format)\n if self.activation is not None:\n outputs = self.activation(outputs)\n return outputs\n\n\n@tk_utils.register_keras_custom_object\nclass BlurPooling2D(tf.keras.layers.Layer):\n \"\"\"Blur Pooling Layer \"\"\"\n\n def __init__(self, taps=5, strides=2, **kwargs):\n super().__init__(**kwargs)\n self.taps = taps\n self.strides = tk_utils.normalize_tuple(strides, 2)\n\n def compute_output_shape(self, input_shape):\n assert len(input_shape) == 4\n input_shape = list(input_shape)\n input_shape[1] = (\n input_shape[1] + int(input_shape[1]) % self.strides[0]\n ) // self.strides[0]\n input_shape[2] = (\n input_shape[2] + int(input_shape[2]) % self.strides[1]\n ) // self.strides[1]\n return tuple(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n in_filters = K.int_shape(inputs)[-1]\n\n pascals_tr = np.zeros((self.taps, self.taps))\n pascals_tr[0, 0] = 1\n for i in range(1, self.taps):\n pascals_tr[i, :] = pascals_tr[i - 1, :]\n pascals_tr[i, 1:] += pascals_tr[i - 1, :-1]\n filter1d = pascals_tr[self.taps - 1, :]\n filter2d = filter1d[np.newaxis, :] * filter1d[:, np.newaxis]\n filter2d = filter2d * (self.taps ** 2 / filter2d.sum())\n kernel = np.tile(filter2d[:, :, np.newaxis, np.newaxis], (1, 1, in_filters, 1))\n kernel = K.constant(kernel)\n\n return tf.nn.depthwise_conv2d(\n inputs, kernel, strides=(1,) + self.strides + (1,), padding=\"SAME\"\n )\n\n def get_config(self):\n config = {\"taps\": self.taps, \"strides\": self.strides}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass ScaleValue(tf.keras.layers.Layer):\n \"\"\"値だけをスケーリングしてシフトするレイヤー。回帰の出力前とかに。\"\"\"\n\n def __init__(self, scale, shift=0, **kargs):\n super().__init__(**kargs)\n self.scale = np.float32(scale)\n self.shift = np.float32(shift)\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def call(self, inputs, **kwargs):\n del kwargs\n\n @tf.custom_gradient\n def _forward(x):\n def _backword(dy):\n return dy\n\n return x * self.scale + self.shift, _backword\n\n return _forward(inputs)\n\n def get_config(self):\n config = {\"scale\": self.scale, \"shift\": self.shift}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass ScaleGradient(tf.keras.layers.Layer):\n \"\"\"勾配だけをスケーリングするレイヤー。転移学習するときとかに。\"\"\"\n\n def __init__(self, scale, **kargs):\n super().__init__(**kargs)\n self.scale = np.float32(scale)\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def call(self, inputs, **kwargs):\n del kwargs\n\n @tf.custom_gradient\n def _forward(x):\n def _backword(dy):\n return dy * self.scale\n\n return x, _backword\n\n return _forward(inputs)\n\n def get_config(self):\n config = {\"scale\": self.scale}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass ImputeNaN(tf.keras.layers.Layer):\n \"\"\"NaNを適当な値に変換する層。\"\"\"\n\n def __init__(self, units, **kwargs):\n super().__init__(**kwargs)\n self.units = units\n self.kernel1 = None\n self.kernel2 = None\n self.bias = None\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def build(self, input_shape):\n dim = int(input_shape[-1])\n self.kernel1 = self.add_weight(\n shape=(dim, self.units),\n initializer=tf.keras.initializers.he_uniform(),\n regularizer=tf.keras.regularizers.l2(1e-4),\n name=\"kernel1\",\n )\n self.kernel2 = self.add_weight(\n shape=(self.units, dim),\n initializer=tf.keras.initializers.he_uniform(),\n regularizer=tf.keras.regularizers.l2(1e-4),\n name=\"kernel2\",\n )\n self.bias = self.add_weight(\n shape=(dim,), initializer=tf.keras.initializers.zeros(), name=\"bias\"\n )\n super().build(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n mask = tf.math.is_nan(inputs)\n output = tf.where(mask, K.ones_like(inputs), inputs) # nanを1に置き換え\n output = K.dot(output, self.kernel1)\n output = K.relu(output)\n output = K.dot(output, self.kernel2)\n output = K.bias_add(output, self.bias, data_format=\"channels_last\")\n output = tf.where(mask, output, inputs) # nan以外はinputsを出力\n return output\n\n def get_config(self):\n config = {\"units\": self.units}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass GeM2D(tf.keras.layers.Layer):\n \"\"\"Generalized Mean Pooling (GeM) \"\"\"\n\n def __init__(self, p=3, epsilon=1e-6, **kargs):\n super().__init__(**kargs)\n self.p = p\n self.epsilon = epsilon\n\n def compute_output_shape(self, input_shape):\n assert len(input_shape) == 4\n return (input_shape[0], input_shape[3])\n\n def call(self, inputs, **kwargs):\n del kwargs\n x = K.pow(K.maximum(inputs, self.epsilon), self.p)\n x = K.mean(x, axis=[1, 2]) # GAP\n x = K.pow(x, 1 / self.p)\n return x\n\n def get_config(self):\n config = {\"p\": self.p, \"epsilon\": self.epsilon}\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass PositionalEncoding(tf.keras.layers.Layer):\n \"\"\"Positional Encodingレイヤー。\n\n x(i) = pos / pow(10000, 2 * i / depth)\n PE(pos, 2 * i) = sin(x(i))\n PE(pos, 2 * i + 1) = cos(x(i))\n\n ↑これを入力に足す。\n\n → 偶数・奇数で分けるのがやや面倒なので、depthの最初半分がsin, 後ろ半分がcosになるようにする\n && depthは偶数前提にしてしまう\n\n \"\"\"\n\n def call(self, inputs, **kwargs):\n del kwargs\n _, max_length, depth = tf.unstack(K.shape(inputs))\n pos = K.cast(tf.range(max_length), K.floatx())\n i = K.cast(tf.range(depth // 2), K.floatx())\n d = K.cast(depth // 2, K.floatx())\n x_i = K.expand_dims(pos, -1) / K.expand_dims(\n K.pow(10000.0, 2.0 * i / d), 0\n ) # (max_length, depth // 2)\n pe0 = K.sin(x_i)\n pe1 = K.cos(x_i)\n pe = K.concatenate([pe0, pe1], axis=-1) # (max_length, depth)\n pe = K.expand_dims(pe, axis=0) # (1, max_length, depth)\n return inputs + pe\n\n\n@tk_utils.register_keras_custom_object\nclass MultiHeadAttention(tf.keras.layers.Layer):\n \"\"\"Multi-head Attetion\"\"\"\n\n def __init__(\n self, units, heads=8, hidden_rate=1.0, drop_rate=0.1, causal=False, **kwargs\n ):\n super().__init__(**kwargs)\n assert units % heads == 0\n self.units = units\n self.heads = heads\n self.hidden_rate = hidden_rate\n self.drop_rate = drop_rate\n self.causal = causal\n self.Wq = None\n self.Wk = None\n self.Wv = None\n self.bq = None\n self.bk = None\n self.bv = None\n\n def compute_output_shape(self, input_shape):\n seq_shape, _ = input_shape\n return (seq_shape[0], seq_shape[1], self.units)\n\n def build(self, input_shape):\n seq_shape, ctx_shape = input_shape\n output_units = self.units // self.heads\n hidden_units = int(output_units * self.hidden_rate)\n self.Wq = self.add_weight(\n shape=(self.heads, int(seq_shape[-1]), hidden_units),\n initializer=tf.keras.initializers.glorot_uniform(),\n name=\"Wq\",\n )\n self.Wk = self.add_weight(\n shape=(self.heads, int(ctx_shape[-1]), hidden_units),\n initializer=tf.keras.initializers.glorot_uniform(),\n name=\"Wk\",\n )\n self.Wv = self.add_weight(\n shape=(self.heads, int(ctx_shape[-1]), output_units),\n initializer=tf.keras.initializers.glorot_uniform(),\n name=\"Wv\",\n )\n self.bq = self.add_weight(\n shape=(self.heads, hidden_units),\n initializer=tf.keras.initializers.zeros(),\n name=\"bq\",\n )\n self.bk = self.add_weight(\n shape=(self.heads, hidden_units),\n initializer=tf.keras.initializers.zeros(),\n name=\"bk\",\n )\n self.bv = self.add_weight(\n shape=(self.heads, output_units),\n initializer=tf.keras.initializers.zeros(),\n name=\"bv\",\n )\n super().build(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n seq, ctx = inputs\n\n outputs = []\n for h in range(self.heads):\n # q.shape == (None, seq.shape[1], hidden_units)\n # k.shape == (None, ctx.shape[1], hidden_units)\n # v.shape == (None, ctx.shape[1], output_units)\n q = K.bias_add(K.dot(seq, self.Wq[h]), self.bq[h])\n k = K.bias_add(K.dot(ctx, self.Wk[h]), self.bk[h])\n v = K.bias_add(K.dot(ctx, self.Wv[h]), self.bv[h])\n k = k / np.sqrt(K.int_shape(k)[-1])\n w = K.batch_dot(q, k, axes=(2, 2)) # (None, seq.shape[1], ctx.shape[1])\n if self.causal:\n w_shape = K.shape(w)\n mask_ones = tf.ones(shape=w_shape, dtype=\"int32\")\n row_index = K.cumsum(mask_ones, axis=1)\n col_index = K.cumsum(mask_ones, axis=2)\n causal_mask = K.greater_equal(row_index, col_index)\n w = tf.where(causal_mask, w, K.tile([[[-np.inf]]], w_shape))\n w = K.softmax(w)\n w = K.dropout(w, level=self.drop_rate) # Attention Dropout\n a = K.batch_dot(w, K.tanh(v), axes=(2, 1))\n # a.shape == (None, seq.shape[1], output_units)\n outputs.append(a)\n\n outputs = K.concatenate(outputs, axis=-1)\n return outputs\n\n def get_config(self):\n config = {\n \"units\": self.units,\n \"heads\": self.heads,\n \"hidden_rate\": self.hidden_rate,\n \"drop_rate\": self.drop_rate,\n \"causal\": self.causal,\n }\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass MultiHeadAttention2D(tf.keras.layers.Layer):\n \"\"\"Multi-head Attetionの2D版のようなもの。(怪)\"\"\"\n\n def __init__(self, units, heads=8, hidden_rate=1.0, drop_rate=0.1, **kwargs):\n super().__init__(**kwargs)\n assert units % heads == 0\n self.units = units\n self.heads = heads\n self.hidden_rate = hidden_rate\n self.drop_rate = drop_rate\n self.Wq = None\n self.Wk = None\n self.Wv = None\n self.bq = None\n self.bk = None\n self.bv = None\n\n def compute_output_shape(self, input_shape):\n seq_shape, _ = input_shape\n return (seq_shape[0], seq_shape[1], seq_shape[2], self.units)\n\n def build(self, input_shape):\n seq_shape, ctx_shape = input_shape\n output_units = self.units // self.heads\n hidden_units = int(output_units * self.hidden_rate)\n self.Wq = self.add_weight(\n shape=(self.heads, int(seq_shape[-1]), hidden_units),\n initializer=tf.keras.initializers.glorot_uniform(),\n regularizer=tf.keras.regularizers.l2(1e-4),\n name=\"Wq\",\n )\n self.Wk = self.add_weight(\n shape=(self.heads, int(ctx_shape[-1]), hidden_units),\n initializer=tf.keras.initializers.glorot_uniform(),\n regularizer=tf.keras.regularizers.l2(1e-4),\n name=\"Wk\",\n )\n self.Wv = self.add_weight(\n shape=(self.heads, int(ctx_shape[-1]), output_units),\n initializer=tf.keras.initializers.glorot_uniform(),\n regularizer=tf.keras.regularizers.l2(1e-4),\n name=\"Wv\",\n )\n self.bq = self.add_weight(\n shape=(self.heads, hidden_units),\n initializer=tf.keras.initializers.zeros(),\n regularizer=tf.keras.regularizers.l2(1e-4),\n name=\"bq\",\n )\n self.bk = self.add_weight(\n shape=(self.heads, hidden_units),\n initializer=tf.keras.initializers.zeros(),\n regularizer=tf.keras.regularizers.l2(1e-4),\n name=\"bk\",\n )\n self.bv = self.add_weight(\n shape=(self.heads, output_units),\n initializer=tf.keras.initializers.zeros(),\n regularizer=tf.keras.regularizers.l2(1e-4),\n name=\"bv\",\n )\n super().build(input_shape)\n\n def call(self, inputs, **kwargs):\n del kwargs\n seq, ctx = inputs\n batch_size = K.shape(seq)[0]\n\n outputs = []\n for h in range(self.heads):\n # q.shape == (None, seq.shape[1], seq.shape[2], hidden_units)\n # k.shape == (None, ctx.shape[1], ctx.shape[2], hidden_units)\n # v.shape == (None, ctx.shape[1], ctx.shape[2], output_units)\n q = K.bias_add(K.dot(seq, self.Wq[h]), self.bq[h])\n k = K.bias_add(K.dot(seq, self.Wk[h]), self.bk[h])\n v = K.bias_add(K.dot(seq, self.Wv[h]), self.bv[h])\n q = K.reshape(q, (batch_size, -1, K.int_shape(k)[-1]))\n k = K.reshape(k, (batch_size, -1, K.int_shape(k)[-1]))\n v = K.reshape(v, (batch_size, -1, K.int_shape(k)[-1]))\n k = k / np.sqrt(K.int_shape(k)[-1])\n w = K.batch_dot(q, k, axes=(2, 2)) # (None, seq.shape[1], ctx.shape[1])\n w = K.softmax(w)\n w = K.dropout(w, level=self.drop_rate) # Attention Dropout\n a = K.batch_dot(w, K.tanh(v), axes=(2, 1))\n # a.shape == (None, seq.shape[1], output_units)\n outputs.append(a)\n\n outputs = K.concatenate(outputs, axis=-1)\n output_shape = self.compute_output_shape([K.shape(seq), K.shape(ctx)])\n outputs = K.reshape(outputs, output_shape)\n return outputs\n\n def get_config(self):\n config = {\n \"units\": self.units,\n \"heads\": self.heads,\n \"hidden_rate\": self.hidden_rate,\n \"drop_rate\": self.drop_rate,\n }\n base_config = super().get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@tk_utils.register_keras_custom_object\nclass TrainOnly(tf.keras.layers.Wrapper):\n \"\"\"訓練時のみ適用するlayer wrapper\"\"\"\n\n def call(self, inputs, training=None, **kwargs):\n return K.in_train_phase(\n lambda: self.layer.call(inputs, **kwargs), inputs, training\n )\n\n\n@tk_utils.register_keras_custom_object\nclass TestOnly(tf.keras.layers.Wrapper):\n \"\"\"推論時のみ適用するlayer wrapper\"\"\"\n\n def call(self, inputs, training=None, **kwargs):\n return K.in_train_phase(\n inputs, lambda: self.layer.call(inputs, **kwargs), training\n )\n","sub_path":"pytoolkit/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":53983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"337418422","text":"\npage_title = \"Sample Functions\"\n\n\ndef main():\n\n title = \"main\"\n\n def add(n1, n2, *n3):\n\n title = \"add\"\n total = n1 + n2\n for number in n3:\n total += number\n\n def format():\n nonlocal title\n title = \"format\"\n title = \"add\" # this is a new local(er) variable\n return total\n\n # this is where my code goes\n global page_title # this function changes the page_title global variable\n page_title = \"Main Function\"\n\n print(\"start\", page_title)\n answer = add(10, 20, 30, 40, 50)\n print(answer)\n\n\nmain()\nprint(\"end\", page_title)\n","sub_path":"day3/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"344765559","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n__author__ = 'hstking hstking@hotmail.com'\n\n\nimport time\nfrom myLog import MyLog\n''' 这里的myLog 是自建的模块,处于该文件的同一目录下'''\n\nclass TestTime(object):\n\tdef __init__(self):\n\t\tself.log = MyLog()\n\t\tself.testTime()\n\t\tself.testLocaltime()\n\t\tself.testSleep()\n\t\tself.testStrftime()\n\n\tdef testTime(self):\n\t\tself.log.info('开始测试time.time()函数')\n\t\tprint('当前时间戳为:time.time() = %f' %time.time())\n\t\tprint('这里返回的是一个浮点型的数值,它是从1970纪元后经过的浮点秒数')\n\t\tprint('\\n')\n\n\tdef testLocaltime(self):\n\t\tself.log.info('开始测试time.localtime()函数')\n\t\tprint('当前本地时间为:time.localtime() = %s' %str(time.localtime()))\n\t\tprint('这里返回的是一个struct_time结构的元组')\n\t\tprint('\\n')\n\n\tdef testSleep(self):\n\t\tself.log.info('开始测试time.sleep()函数')\n\t\tprint('这是个计时器:time.sleep(5)')\n\t\tprint('闭上眼睛数上5秒就可以了')\n\t\ttime.sleep(5)\n\t\tprint('\\n')\n\n\tdef testStrftime(self):\n\t\tself.log.info('开始测试time.strftime()函数')\n\t\tprint('这个函数返回的是一个格式化的时间')\n\t\tprint('time.strftime(\"%%Y-%%m-%%d %%X\",time.localtime()) = %s' %time.strftime(\"%Y-%m-%d %X\",time.localtime()))\n\t\tprint('\\n')\n\n\nif __name__ == '__main__':\n\ttt = TestTime()\n","sub_path":"Book-Of-Python网络爬虫实战/testTime.py","file_name":"testTime.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"461305305","text":"import json\nimport collections\nimport urllib2\n\nfrom gclol import manager_info\nfrom gclol.data_export import export_round_results\nfrom gclol.email_utils import notify_winners_to_Riot, send_round_results, notify_ip_to_team\nfrom gclol.models import Round, Result, Statistic, Team, League, Match\nfrom gclol.results_generator import get_match_results\n\n\ndef update_points():\n for league in manager_info.leagues:\n for team in manager_info.leagues[league]:\n manager_info.leagues[league][team] = Team.objects.get(name=team).points\n\n\ndef last_round(round):\n num_rounds = Round.objects.all().count()\n this_round = int(round.name[-1])\n return num_rounds == this_round\n\n\ndef get_avg_result(stat, results):\n total = 0\n results_list = results.filter(statistic=stat)\n for result in results_list:\n total += result.quantity\n return total / results_list.count()\n\n\ndef decide_winner_by_results(team1, team2):\n stats_to_check = [\"Ratio\", \"Kill\", \"Death\", \"Assist\"]\n results_team1 = Result.objects.filter(team=team1)\n results_team2 = Result.objects.filter(team=team2)\n\n for stat in stats_to_check:\n stat_instance = Statistic.objects.get(stat=stat)\n avg_team1 = get_avg_result(stat_instance, results_team1)\n avg_team2 = get_avg_result(stat_instance, results_team2)\n\n if avg_team1 != avg_team2:\n return (1, -1)[avg_team1 > avg_team2]\n return 1\n\n\ndef team_compare(team1, team2):\n winner = 1\n if team1.points > team2.points:\n winner = -1\n elif team1.points < team2.points:\n winner = 1\n elif team1.points == team2.points:\n winner = decide_winner_by_results(team1, team2)\n\n return winner\n\n\ndef get_league_winners(league):\n league_teams = Team.objects.filter(league=league)\n teams_sorted = sorted(league_teams, cmp=team_compare)\n return teams_sorted[:3]\n\n\ndef save_winners():\n leagues = League.objects.all()\n for league in leagues:\n winner = get_league_winners(league)\n podium = {\"first\": winner[0]}\n if len(winner) > 1:\n podium[\"second\"] = winner[1]\n if len(winner) > 2:\n podium[\"third\"] = winner[2]\n manager_info.winners[league.name] = podium\n\n\ndef finalize_competition():\n save_winners()\n manager_info.competition_finished = True\n notify_winners_to_Riot()\n\n\ndef finalize_round(round):\n round_resume = {}\n matches = Match.objects.filter(round=round)\n for match in matches:\n finalize_match(round_resume, match)\n update_points()\n json_data = export_round_results('json', round_resume)\n send_round_results(json_data, round)\n if last_round(round):\n finalize_competition()\n\n\ndef update_team(match, team, results):\n if results[\"Winner\"] == 1:\n team.points += 1\n team.save()\n match.winner = team\n match.save()\n\n for key in results:\n if key == \"Winner\":\n continue\n\n statistic = Statistic.objects.get(stat=key)\n if Result.objects.filter(team=team).filter(match=match).filter(statistic=statistic).count() == 0:\n Result(statistic=statistic,\n team=team,\n match=match,\n quantity=results[key]) \\\n .save()\n else:\n result = Result.objects.filter(team=team, match=match, statistic=statistic)[0]\n result.quantity = results[key]\n result.save()\n\n\ndef finalize_match(round_resume, match):\n teams = list(match.teams.all())\n match_result = json.loads(get_match_results(teams[0].name, teams[1].name),\n object_pairs_hook=collections.OrderedDict)\n update_team(match, teams[0], match_result[\"match_results\"][teams[0].name])\n update_team(match, teams[1], match_result[\"match_results\"][teams[1].name])\n\n if str(teams[0].league) not in round_resume:\n round_resume[str(teams[0].league)] = {}\n if str(match.round) not in round_resume[str(teams[0].league)]:\n round_resume[str(teams[0].league)][str(match.round)] = {}\n\n round_resume[str(teams[0].league)][str(match.round)][str(match)] = match_result[\"match_results\"]\n match.played = True\n match.save()\n\n\ndef get_new_ip():\n f = urllib2.urlopen(manager_info.URL_IP_SERVER)\n data = f.read()\n json_data = json.loads(data)\n f.close()\n return json_data[\"generated-ip\"]\n\n\ndef clean_ips():\n for match in Match.objects.all():\n match.ip = \"127.0.0.1\"\n match.save()\n\n\ndef generate_ips(matches_to_prepare, num_matches_to_prepare):\n clean_ips()\n for i in range(num_matches_to_prepare):\n match = matches_to_prepare[i]\n ip = get_new_ip()\n match.ip = ip\n match.save()\n for team in match.teams.all():\n notify_ip_to_team(team, match)\n\n\ndef prepare_new_round(round):\n matches_to_prepare = Match.objects.filter(round=round)\n num_matches_to_prepare = matches_to_prepare.count()\n manager_info.waiting_players = num_matches_to_prepare * 2 * 5\n generate_ips(matches_to_prepare, num_matches_to_prepare)\n","sub_path":"gclol/competition_develop.py","file_name":"competition_develop.py","file_ext":"py","file_size_in_byte":5074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"561273243","text":"import torch\nimport torch.nn as nn\nimport torch.distributions as td\n\n\nclass Latent(nn.Module):\n\n def __init__(self, hidden_dim, latent_dim):\n super(Latent, self).__init__()\n\n self.project_to_mu = nn.Linear(hidden_dim, latent_dim)\n self.project_to_logvar = nn.Linear(hidden_dim, latent_dim)\n\n self.KL = torch.tensor([0])\n self.monte_carlo_samples = 10\n\n def sample(self, mu, logvar):\n var = torch.exp(logvar)\n std = torch.sqrt(var)\n\n eps = torch.randn_like(mu)\n z = mu + std * eps\n return z\n\n def KL_divergence_prior_std_normal(self, mu, logvar):\n KL = -0.5 * (1 + logvar - mu ** 2 - torch.exp(logvar)).sum(dim=1)\n return KL\n\n def q_z_dist(self, mu, logvar):\n var = torch.exp(logvar)\n cov = torch.diag_embed(var)\n return td.MultivariateNormal(mu, cov)\n\n def p_z_dist(self, mu, logvar):\n mu_prior = torch.zeros_like(mu)\n var_prior = torch.ones_like(logvar)\n cov_prior = torch.diag_embed(var_prior)\n return td.MultivariateNormal(mu_prior, cov_prior)\n\n def KL_divergence(self, mu, logvar):\n p_dist = self.p_z_dist(mu, logvar)\n q_dist = self.q_z_dist(mu, logvar)\n\n KL = td.kl_divergence(q_dist, p_dist)\n return KL\n\n def forward(self, h, monte_carlo_samples):\n\n mu = self.project_to_mu(h)\n logvar = self.project_to_logvar(h)\n\n if self.training:\n z_samples = [self.sample(mu, logvar)\n for s in range(monte_carlo_samples)]\n else:\n z_samples = mu\n\n self.KL = self.KL_divergence_prior_std_normal(mu, logvar)\n\n return z_samples","sub_path":"Autoencoder_MNIST/Latent_modules.py","file_name":"Latent_modules.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"550883604","text":"# ----------------------------------------------\r\n# Script Recorded by ANSYS Electronics Desktop Version 2020.2.0\r\n# December 21, 2020\r\n# ----------------------------------------------\r\n\r\nimport ScriptEnv\r\n\r\nScriptEnv.Initialize(\"Ansoft.ElectronicsDesktop\")\r\noDesktop.RestoreWindow()\r\noProject = oDesktop.NewProject()\r\noProject.InsertDesign(\"Maxwell 2D\", \"Maxwell2DDesign1\", \"DCConduction\", \"\")\r\noDesign = oProject.GetActiveDesign()\r\noEditor = oDesign.SetActiveEditor(\"3D Modeler\")\r\n\r\noEditor.CreateRectangle(\r\n [\r\n \"NAME:RectangleParameters\",\r\n \"IsCovered:=\", True,\r\n \"XStart:=\", \"0.1mm\",\r\n \"YStart:=\", \"0mm\",\r\n \"ZStart:=\", \"0mm\",\r\n \"Width:=\", \"100mm\",\r\n \"Height:=\", \"10mm\",\r\n \"WhichAxis:=\", \"Z\"\r\n ],\r\n\r\n [\r\n \"NAME:Attributes\",\r\n \"Name:=\", \"Rectangle1\",\r\n \"Flags:=\", \"\",\r\n \"Color:=\", \"(143 175 143)\",\r\n \"Transparency:=\", 0,\r\n \"PartCoordinateSystem:=\", \"Global\",\r\n \"UDMId:=\", \"\",\r\n \"MaterialValue:=\", \"\\\"vacuum\\\"\",\r\n \"SurfaceMaterialValue:=\", \"\\\"\\\"\",\r\n \"SolveInside:=\", False,\r\n \"ShellElement:=\", False,\r\n \"ShellElementThickness:=\", \"0mm\",\r\n \"IsMaterialEditable:=\", True,\r\n \"UseMaterialAppearance:=\", False,\r\n \"IsLightweight:=\", False\r\n ])\r\n\r\noDesign.ChangeProperty(\r\n [\r\n \"NAME:AllTabs\",\r\n [\r\n \"NAME:LocalVariableTab\",\r\n [\r\n \"NAME:PropServers\",\r\n \"LocalVariables\"\r\n ],\r\n\r\n [\r\n \"NAME:NewProps\",\r\n [\r\n \"NAME:a1\",\r\n \"PropType:=\", \"VariableProp\",\r\n \"UserDef:=\", True,\r\n \"Value:=\", \"100mm\"\r\n ]\r\n ]\r\n ]\r\n ])\r\n\r\noEditor.ChangeProperty(\r\n [\r\n \"NAME:AllTabs\",\r\n [\r\n \"NAME:Geometry3DCmdTab\",\r\n [\r\n \"NAME:PropServers\",\r\n \"Rectangle1:CreateRectangle:1\"\r\n ],\r\n\r\n [\r\n \"NAME:ChangedProps\",\r\n [\r\n \"NAME:XSize\",\r\n \"Value:=\", \"a1\"\r\n ]\r\n ]\r\n ]\r\n ])\r\n\r\noDesign.ChangeProperty(\r\n [\r\n \"NAME:AllTabs\",\r\n [\r\n \"NAME:LocalVariableTab\",\r\n [\r\n \"NAME:PropServers\",\r\n \"LocalVariables\"\r\n ],\r\n\r\n [\r\n \"NAME:NewProps\",\r\n [\r\n \"NAME:b1\",\r\n \"PropType:=\", \"VariableProp\",\r\n \"UserDef:=\", True,\r\n \"Value:=\", \"10mm\"\r\n ]\r\n ]\r\n ]\r\n ])\r\n\r\noEditor.ChangeProperty(\r\n [\r\n \"NAME:AllTabs\",\r\n [\r\n \"NAME:Geometry3DCmdTab\",\r\n [\r\n \"NAME:PropServers\",\r\n \"Rectangle1:CreateRectangle:1\"\r\n ],\r\n\r\n [\r\n \"NAME:ChangedProps\",\r\n [\r\n \"NAME:YSize\",\r\n \"Value:=\", \"b1\"\r\n ]\r\n ]\r\n ]\r\n ])\r\n\r\noEditor.AssignMaterial(\r\n\r\n [\r\n \"NAME:Selections\",\r\n \"AllowRegionDependentPartSelectionForPMLCreation:=\", True,\r\n \"AllowRegionSelectionForPMLCreation:=\", True,\r\n \"Selections:=\", \"Rectangle1\"\r\n ],\r\n\r\n [\r\n \"NAME:Attributes\",\r\n \"MaterialValue:=\", \"\\\"copper\\\"\",\r\n \"SolveInside:=\", True,\r\n \"ShellElement:=\", False,\r\n \"ShellElementThickness:=\", \"nan \",\r\n \"IsMaterialEditable:=\", True,\r\n \"UseMaterialAppearance:=\", False,\r\n \"IsLightweight:=\", False\r\n\r\n ])\r\n\r\noEditor.ChangeProperty(\r\n\r\n [\r\n\r\n \"NAME:AllTabs\",\r\n [\r\n \"NAME:Geometry3DAttributeTab\",\r\n [\r\n \"NAME:PropServers\",\r\n \"Rectangle1\"\r\n ],\r\n [\r\n \"NAME:ChangedProps\",\r\n [\r\n \"NAME:Color\",\r\n \"R:=\", 255,\r\n \"G:=\", 128,\r\n \"B:=\", 64\r\n ]\r\n ]\r\n ]\r\n ])\r\noEditor.ChangeProperty(\r\n [\r\n \"NAME:AllTabs\",\r\n [\r\n \"NAME:Geometry3DAttributeTab\",\r\n [\r\n \"NAME:PropServers\",\r\n \"Rectangle1\"\r\n ],\r\n [\r\n \"NAME:ChangedProps\",\r\n [\r\n \"NAME:Transparent\",\r\n \"Value:=\", 0.6\r\n ]\r\n ]\r\n ]\r\n ])\r\n\r\noModule = oDesign.GetModule(\"BoundarySetup\")\r\noModule.AssignVoltage(\r\n [\r\n \"NAME:Voltage1\",\r\n \"Edges:=\", [10],\r\n \"Value:=\", \"0V\",\r\n \"CoordinateSystem:=\", \"\"\r\n ])\r\n\r\noModule.AssignVoltage(\r\n [\r\n \"NAME:Voltage2\",\r\n \"Edges:=\", [8],\r\n \"Value:=\", \"24V\",\r\n \"CoordinateSystem:=\", \"\"\r\n ])\r\n\r\noModule = oDesign.GetModule(\"AnalysisSetup\")\r\n\r\noModule.InsertSetup(\"DCConduction\",\r\n [\r\n \"NAME:Setup1\",\r\n \"Enabled:=\", True,\r\n\r\n [\r\n \"NAME:MeshLink\",\r\n \"ImportMesh:=\", False\r\n\r\n ],\r\n\r\n \"MaximumPasses:=\", 10,\r\n \"MinimumPasses:=\", 2,\r\n \"MinimumConvergedPasses:=\", 1,\r\n \"PercentRefinement:=\", 30,\r\n \"SolveFieldOnly:=\", False,\r\n \"PercentError:=\", 0.5,\r\n \"SolveMatrixAtLast:=\", True,\r\n \"NonLinearResidual:=\", 0.001\r\n\r\n ])\r\n\r\noDesign.AnalyzeAll()\r\noModule = oDesign.GetModule(\"FieldsReporter\")\r\noModule.CreateFieldPlot(\r\n\r\n [\r\n \"NAME:Mag_J1\",\r\n \"SolutionName:=\", \"Setup1 : LastAdaptive\",\r\n \"UserSpecifyName:=\", 0,\r\n \"UserSpecifyFolder:=\", 0,\r\n \"QuantityName:=\", \"Mag_J\",\r\n \"PlotFolder:=\", \"J\",\r\n \"StreamlinePlot:=\", False,\r\n \"AdjacentSidePlot:=\", False,\r\n \"FullModelPlot:=\", False,\r\n \"IntrinsicVar:=\", \"\",\r\n \"PlotGeomInfo:=\", [1, \"Surface\", \"FacesList\", 1, \"6\"],\r\n \"FilterBoxes:=\", [0],\r\n\r\n [\r\n \"NAME:PlotOnSurfaceSettings\",\r\n \"Filled:=\", False,\r\n \"IsoValType:=\", \"Fringe\",\r\n \"AddGrid:=\", False,\r\n \"MapTransparency:=\", True,\r\n \"Refinement:=\", 0,\r\n \"Transparency:=\", 0,\r\n \"SmoothingLevel:=\", 0,\r\n \"ShadingType:=\", 0,\r\n\r\n [\r\n\r\n \"NAME:Arrow3DSpacingSettings\",\r\n \"ArrowUniform:=\", True,\r\n \"ArrowSpacing:=\", 0,\r\n \"MinArrowSpacing:=\", 0,\r\n \"MaxArrowSpacing:=\", 0\r\n\r\n ],\r\n\r\n \"GridColor:=\", [255, 255, 255]\r\n\r\n ],\r\n\r\n \"EnableGaussianSmoothing:=\", False\r\n\r\n ], \"Field\")\r\n\r\noDesign.ChangeProperty(\r\n [\r\n\r\n \"NAME:AllTabs\",\r\n [\r\n \"NAME:LocalVariableTab\",\r\n [\r\n \"NAME:PropServers\",\r\n \"LocalVariables\"\r\n ],\r\n\r\n [\r\n \"NAME:ChangedProps\",\r\n [\r\n \"NAME:b1\",\r\n \"Value:=\", \"25mm\"\r\n ]\r\n ]\r\n ]\r\n ])\r\n\r\noDesign.Undo()\r\n\r\noProject.Save()\r\n","sub_path":"examples/superconducting_cable_with_Ansys/example_conductor.py","file_name":"example_conductor.py","file_ext":"py","file_size_in_byte":7428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"202822360","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom base.base_net import BaseNet\nfrom .grad_Reverse import GradReverse\nclass DigitLeNet(BaseNet):\n\n def __init__(self):\n super().__init__()\n self.backbone = Feature()\n self.classifier1 = nn.Linear(100, 10)\n self.classifier2 = nn.Linear(100, 10)\n self.s_centroid = torch.zeros(10, 100)\n self.t_centroid = torch.zeros(10, 100)\n self.domain_classifier = AdversarialNetwork(in_feature=100)\n def forward(self, x):\n feature = self.backbone(x)\n class_logit1 = self.classifier1(feature)\n class_logit2 = self.classifier2(feature)\n return feature, class_logit1, class_logit2\n\n\nclass Feature(nn.Module):\n def __init__(self):\n super(Feature, self).__init__()\n self.conv1 = nn.Conv2d(3, 32, kernel_size=5, stride=1)\n self.bn1 = nn.BatchNorm2d(32)\n self.conv2 = nn.Conv2d(32, 48, kernel_size=5, stride=1)\n self.bn2 = nn.BatchNorm2d(48)\n self.fc1 = nn.Linear(48*5*5, 100)\n self.bn1_fc = nn.BatchNorm1d(100)\n self.fc2 = nn.Linear(100, 100)\n self.bn2_fc = nn.BatchNorm1d(100)\n \n\n def forward(self, x):\n x = F.max_pool2d(F.relu(self.bn1(self.conv1(x))), stride=2, kernel_size=2, dilation=(1, 1))\n x = F.max_pool2d(F.relu(self.bn2(self.conv2(x))), stride=2, kernel_size=2, dilation=(1, 1))\n x = x.view(x.size(0), 48*5*5)\n x = F.relu(self.bn1_fc(self.fc1(x)))\n x = F.relu(self.bn2_fc(self.fc2(x)))\n return x \nclass AdversarialNetwork(nn.Module):\n def __init__(self, in_feature):\n super(AdversarialNetwork, self).__init__()\n self.ad_layer1 = nn.Linear(in_feature,100)\n self.ad_layer2 = nn.Linear(100,1)\n self.ad_layer1.weight.data.normal_(0, 0.01)\n self.ad_layer2.weight.data.normal_(0, 0.01)\n self.ad_layer1.bias.data.fill_(0.0)\n self.ad_layer2.bias.data.fill_(0.0)\n self.relu1 = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x,constant):\n x = GradReverse.grad_reverse(x, constant)\n x = self.ad_layer1(x)\n x = self.relu1(x)\n x = self.ad_layer2(x)\n x = self.sigmoid(x)\n return x\n\n def output_num(self):\n return 1\nclass GradReverse(torch.autograd.Function):\n \"\"\"\n Extension of grad reverse layer\n \"\"\"\n @staticmethod\n def forward(ctx, x, constant):\n ctx.constant = constant\n return x.view_as(x)\n\n @staticmethod\n def backward(ctx, grad_output):\n grad_output = grad_output.neg() * ctx.constant\n return grad_output, None\n\n def grad_reverse(x, constant):\n return GradReverse.apply(x, constant)","sub_path":"src/networks/digit_LeNet.py","file_name":"digit_LeNet.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"469731459","text":"# Time: O(s1 * min(s2, n1))\n# Space: O(s2)\n\n# 466\n# Define S = [s,n] as the string S which consists of n connected strings s.\n# For example, [\"abc\", 3] =\"abcabcabc\".\n#\n# On the other hand, we define that string s1 can be obtained from string s2\n# if we can remove some characters from s2 such that it becomes s1.\n# For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”.\n#\n# You are given two non-empty strings s1 and s2 (each at most 100 characters long)\n# and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2,\n# where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.\n#\n# Example:\n#\n# Input:\n# s1=\"acb\", n1=4\n# s2=\"ab\", n2=2\n#\n# Return:\n# 2\n\nclass Solution(object):\n # 利用贪心算法计算s1与s2对应字符的匹配位置,由于s1与s2的循环匹配呈现周期性规律,因此通过辅助数组dp进行记录\n # 记l1, l2为s1, s2的长度;x1, x2为拓展后的s1*n1, s2*n2的字符下标\n #\n # 令y1, y2 = x1 % l1, x2 % l2\n # 当s1[y1] == s2[y2]时:\n # 若dp[y1,y2]不存在,则令dp[y1,y2] = x1, x2\n # 否则,记px1, px2 = dp[y1,y2],循环节为s1[px1 ... x1], s2[px2 ... x2]\n #\n # 用完n1个s1,看拓展后的s2的下标能前进到哪里\n def getMaxRepetitions(self, s1, n1, s2, n2): # USE THIS\n if not set(s2) <= set(s1):\n return 0\n\n dp = {}\n l1, l2 = len(s1), len(s2)\n x1 = x2 = 0\n while x1 < l1 * n1:\n while s1[x1 % l1] != s2[x2 % l2]:\n x1 += 1\n if x1 >= l1 * n1:\n break\n y1, y2 = x1 % l1, x2 % l2\n if (y1, y2) not in dp:\n dp[y1, y2] = (x1, x2)\n else:\n px1, px2 = dp[y1, y2]\n loop = (l1 * n1 - px1) // (x1 - px1)\n x1 = px1 + loop * (x1 - px1)\n x2 = px2 + loop * (x2 - px2)\n if x1 < l1 * n1:\n x1 += 1\n x2 += 1\n\n # x2下标前进到最后,优于计算prefix_count + pattern_count + suffix_count\n return x2 // (n2 * l2)\n\n\n # https://leetcode.com/problems/count-the-repetitions/solution/\n def getMaxRepetitions_kamyu(self, s1, n1, s2, n2):\n \"\"\"\n :type s1: str\n :type n1: int\n :type s2: str\n :type n2: int\n :rtype: int\n \"\"\"\n repeat_count = [0] * (len(s2)+1) # count of repititions till the present s1 block\n lookup = {} # each index in s2 uses how many s1\n j, count = 0, 0 # j is index in s2, count is for s2\n for k in range(1, n1+1):\n # iterate s1, see what is j and count for s2\n for i in range(len(s1)):\n if s1[i] == s2[j]:\n j = (j + 1) % len(s2)\n count += (j == 0)\n\n if j in lookup: # cyclic\n i = lookup[j]\n prefix_count = repeat_count[i]\n pattern_count = (count - repeat_count[i]) * ((n1 - i) // (k - i))\n suffix_count = repeat_count[i + (n1 - i) % (k - i)] - repeat_count[i]\n return (prefix_count + pattern_count + suffix_count) / n2\n lookup[j] = k\n repeat_count[k] = count\n\n return repeat_count[n1] / n2 # not cyclic iff n1 <= s2\n\n\nprint(Solution().getMaxRepetitions('acb', 4, 'd', 1)) # 0\nprint(Solution().getMaxRepetitions('acb', 4, 'ab', 2)) # 2\nprint(Solution().getMaxRepetitions('acb', 4, 'aba', 2)) # 1\nprint(Solution().getMaxRepetitions('acbacb', 4, 'ab', 2)) # 4\n","sub_path":"Python/count-the-repetitions.py","file_name":"count-the-repetitions.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66775175","text":"# coding: utf-8\n# Universidade Federal de Campina Grande - UFCG\n# Programação I - UFCG\n# Aluno: Walisson Nascimento de Farias\n# Matrícula: 117210716\n# Unidade: 8\tQuestão: Questões para mt\n\ndef seleciona_questoes(todas, utilizadas):\n\tfor i in range(len(utilizadas)-1,-1,-1):\n\t\tfor j in range(len(todas)-1,-1,-1):\n\t\t\tif utilizadas[i] == todas[j]:\n\t\t\t\ttodas.pop(j)\n","sub_path":"Unidade_8/questoes_mt/questoes_mt.py","file_name":"questoes_mt.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"240188961","text":"import json\nimport boto3\nimport logging\n\n#setup simple logging for INFO\nlogger = logging.getLogger()\nlogger.setLevel(logging.ERROR)\n\nclient = boto3.client('ec2', region_name='us-east-1')\nec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]\n\ndef lambda_handler(event, context):\n\n for region in ec2_regions:\n #define the connection region\n try:\n ec2 = boto3.resource('ec2', region_name=region)\n print(\"[INFO]: \" + str(region) + \" started\")\n except botocore.exceptions.NoRegionError as e:\n print(\"Error initiating AWS client!\")\n exit(1)\n\n #Set this to True if you don't want the function to perform any actions\n debugMode = False\n\n #List all EC2 instances\n base = ec2.instances.all()\n \n #loop through by running instances\n for instance in base:\n \n #Tag the Volumes\n for vol in instance.volumes.all():\n #print(vol.attachments[0]['Device'])\n if debugMode == True:\n print(\"[DEBUG] \" + str(vol))\n tag_cleanup(instance, vol.attachments[0]['Device'])\n else:\n tag = vol.create_tags(Tags=tag_cleanup(instance, vol.attachments[0]['Device']))\n print(\"[INFO]: \" + str(tag))\n \n #Tag the Network Interfaces\n for eni in instance.network_interfaces:\n #print(eni.attachment['DeviceIndex'])\n if debugMode == True:\n print(\"[DEBUG] \" + str(eni))\n tag_cleanup(instance, \"eth\"+str(eni.attachment['DeviceIndex']))\n else:\n tag = eni.create_tags(Tags=tag_cleanup(instance, \"eth\"+str(eni.attachment['DeviceIndex'])))\n print(\"[INFO]: \" + str(tag))\n \n print(\"[INFO]: \" + str(region) + \" complete\")\n \n#------------- Functions ------------------\n# Returns the type of configuration that was performed \n \ndef tag_cleanup(instance, detail):\n tempTags=[]\n v={}\n \n for t in instance.tags:\n #pull the name tag\n if t['Key'] == 'Name':\n v['Value'] = t['Value'] + \" - \" + str(detail)\n v['Key'] = 'Name'\n tempTags.append(v)\n #Set the important tags that should be written here \n elif t['Key'] == 'ApplicationID':\n print(\"[INFO]: ApplicationID Tag \" + str(t))\n tempTags.append(t) \n elif t['Key'] == 'Customer':\n print(\"[INFO]: Customer Tag \" + str(t))\n tempTags.append(t) \n elif t['Key'] == 'Environment':\n print(\"[INFO]: Environment Tag \" + str(t))\n tempTags.append(t) \n elif t['Key'] == 'Owner':\n print(\"[INFO]: Owner Tag \" + str(t))\n tempTags.append(t) \n elif t['Key'] == 'Project':\n print(\"[INFO]: Project Tag \" + str(t))\n tempTags.append(t)\n elif t['Key'] == 'Terraform':\n print(\"[INFO]: Terraform Tag \" + str(t))\n tempTags.append(t)\n else:\n print(\"[INFO]: Skip Tag - \" + str(t))\n \n print(\"[INFO] \" + str(tempTags))\n return(tempTags)\n\nif __name__ == '__main__':\n lambda_handler(None, None)\n","sub_path":"TagEC2Resources/TagEC2Resources.py","file_name":"TagEC2Resources.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56864150","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.backends.cudnn as cudnn\n\n\n\nclass Inception(nn.Module):\n def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes):\n super(Inception, self).__init__()\n # 1x1 conv branch\n self.b1 = nn.Sequential(\n nn.Conv2d(in_planes, n1x1, kernel_size=1),\n nn.BatchNorm2d(n1x1),\n nn.ReLU(True),\n )\n\n # 1x1 conv -> 3x3 conv branch\n self.b2 = nn.Sequential(\n nn.Conv2d(in_planes, n3x3red, kernel_size=1),\n nn.BatchNorm2d(n3x3red),\n nn.ReLU(True),\n nn.Conv2d(n3x3red, n3x3, kernel_size=3, padding=1),\n nn.BatchNorm2d(n3x3),\n nn.ReLU(True),\n )\n\n # 1x1 conv -> 5x5 conv branch\n self.b3 = nn.Sequential(\n nn.Conv2d(in_planes, n5x5red, kernel_size=1),\n nn.BatchNorm2d(n5x5red),\n nn.ReLU(True),\n nn.Conv2d(n5x5red, n5x5, kernel_size=3, padding=1),\n nn.BatchNorm2d(n5x5),\n nn.ReLU(True),\n nn.Conv2d(n5x5, n5x5, kernel_size=3, padding=1),\n nn.BatchNorm2d(n5x5),\n nn.ReLU(True),\n )\n\n # 3x3 pool -> 1x1 conv branch\n self.b4 = nn.Sequential(\n nn.MaxPool2d(3, stride=1, padding=1),\n nn.Conv2d(in_planes, pool_planes, kernel_size=1),\n nn.BatchNorm2d(pool_planes),\n nn.ReLU(True),\n )\n\n def forward(self, x):\n y1 = self.b1(x)\n y2 = self.b2(x)\n y3 = self.b3(x)\n y4 = self.b4(x)\n return torch.cat([y1,y2,y3,y4], 1)\n\n\nclass GoogLeNet(nn.Module):\n def __init__(self):\n super(GoogLeNet, self).__init__()\n self.pre_layers = nn.Sequential(\n nn.Conv2d(3, 192, kernel_size=3, padding=1),\n nn.BatchNorm2d(192),\n nn.ReLU(True),\n )\n\n self.a3 = Inception(192, 64, 96, 128, 16, 32, 32)\n self.b3 = Inception(256, 128, 128, 192, 32, 96, 64)\n\n self.maxpool = nn.MaxPool2d(3, stride=2, padding=1)\n\n self.a4 = Inception(480, 192, 96, 208, 16, 48, 64)\n self.b4 = Inception(512, 160, 112, 224, 24, 64, 64)\n self.c4 = Inception(512, 128, 128, 256, 24, 64, 64)\n self.d4 = Inception(512, 112, 144, 288, 32, 64, 64)\n self.e4 = Inception(528, 256, 160, 320, 32, 128, 128)\n\n self.a5 = Inception(832, 256, 160, 320, 32, 128, 128)\n self.b5 = Inception(832, 384, 192, 384, 48, 128, 128)\n\n self.avgpool = nn.AvgPool2d(8, stride=1)\n self.linear = nn.Linear(1024, 10)\n\n def forward(self, x):\n out = self.pre_layers(x)\n out = self.a3(out)\n out = self.b3(out)\n out = self.maxpool(out)\n out = self.a4(out)\n out = self.b4(out)\n out = self.c4(out)\n out = self.d4(out)\n out = self.e4(out)\n out = self.maxpool(out)\n out = self.a5(out)\n out = self.b5(out)\n out = self.avgpool(out)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n# 定义是否使用GPU\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ncudnn.benchmark = True\n\n# 模型定义 VGG19\nnet = GoogLeNet().to(device)\n\n\n# 超参数设置\nEPOCH = 50 #遍历数据集次数\npre_epoch = 0 # 定义已经遍历数据集的次数\nBATCH_SIZE = 20 #批处理尺寸(batch_size)\nLR = 0.001 #学习率\n\n# 准备数据集并预处理\ntransform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4), #先四周填充0,在吧图像随机裁剪成32*32\n transforms.RandomHorizontalFlip(), #图像一半的概率翻转,一半的概率不翻转\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), #R,G,B每层的归一化用到的均值和方差\n])\n\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntrainset = torchvision.datasets.CIFAR10(root='./data/', train=True, download=False, transform=transform_train) #训练数据集\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=2) #生成一个个batch进行批训练,组成batch的时候顺序打乱取\n\ntestset = torchvision.datasets.CIFAR10(root='./data/', train=False, download=False, transform=transform_test)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)\n\n\n\n# 定义损失函数和优化方式\ncriterion = nn.CrossEntropyLoss() #损失函数为交叉熵,多用于多分类问题\noptimizer = optim.SGD(net.parameters(), lr=LR, momentum=0.9, weight_decay=5e-4) #优化方式为mini-batch momentum-SGD,并采用L2正则化(权重衰减)\nwith open(\"./data/acc.txt\", \"w\") as f:\n with open(\"./data/log.txt\", \"w\") as f2:\n for epoch in range(pre_epoch, EPOCH):\n print('\\nEpoch: %d' % (epoch + 1))\n net.train()\n sum_loss = 0.0\n correct = 0.0\n total = 0.0\n for i, data in enumerate(trainloader, 0):\n # 准备数据\n length = len(trainloader)\n inputs, labels = data\n inputs, labels = inputs.to(device), labels.to(device)\n optimizer.zero_grad()\n\n # forward + backward\n outputs = net(inputs).to(device)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n sum_loss += loss.item()\n # 打���一次loss和准确率 \n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += predicted.eq(labels.data).cpu().sum()\n print('[epoch:%d, | loss: %.4f | acc: %.3f%% '\n % (epoch + 1, sum_loss / (i + 1), 100 * float(correct) / total))\n f2.write('%03d %05d |Loss: %.03f | Acc: %.3f%% '\n % (epoch + 1, (i + 1 + epoch * length), sum_loss / (i + 1), 100. * correct / total))\n f2.write('\\n')\n f2.flush()\n # 训练完测试一下准确率\n print(\"Waiting Test!\")\n with torch.no_grad():\n correct = 0\n total = 0\n for data in testloader:\n net.eval()\n images, labels = data\n images, labels = images.to(device), labels.to(device)\n outputs = net(images).to(device)\n # 取得分最高的那个类 (outputs.data的索引号)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n print('测试分类准确率为:%.3f%%' % (100 * float(correct) / total))\n acc = 100 * float(correct) / total\n # 将每次测试结果实时写入acc.txt文件中\n print('Saving model......')\n f.write(\"EPOCH=%03d,Accuracy= %.3f%%\" % (epoch + 1, acc))\n f.write('\\n')\n f.flush()\n print(\"Training Finished, TotalEPOCH=%d\" % EPOCH)\n\n\n","sub_path":"Googlenet/googlenet.py","file_name":"googlenet.py","file_ext":"py","file_size_in_byte":7412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234196839","text":"from azure.common.client_factory import get_client_from_auth_file\r\nfrom azure.mgmt.storage import StorageManagementClient\r\nfrom azure.mgmt.storage.models import StorageAccountCreateParameters, ProvisioningState, Sku, Kind\r\nfrom azure.storage.common import SharedAccessSignature\r\nfrom azure.storage.file import FileService\r\nfrom haikunator import Haikunator\r\nfrom random import getrandbits\r\nfrom tkinter import messagebox\r\nfrom tkinter import ttk\r\nimport datetime\r\nimport json\r\nimport os\r\nimport tkinter as tk\r\n\r\n\r\nclass BaseInterface(tk.Tk):\r\n def __init__(self):\r\n tk.Tk.__init__(self)\r\n tk.Tk.iconbitmap(self, default='fujitsu.ico')\r\n tk.Tk.wm_title(self, 'Fujitsu CTI - SILO IR Deploy')\r\n\r\n self.main_window = tk.Frame(self)\r\n self.access_key = tk.StringVar()\r\n self.secret_access_key = tk.StringVar()\r\n self.customer_name = tk.StringVar()\r\n self.text = tk.StringVar()\r\n\r\n # Padding around the outer edges\r\n self.set_seperator(row=0, column=0, rowspan=1, width=10)\r\n self.set_seperator(row=0, column=0, columnspan=1, height=10)\r\n self.set_seperator(row=0, column=6, rowspan=1, width=10)\r\n self.set_seperator(row=10, column=0, rowspan=1, height=10)\r\n\r\n # Padding between the entry fields/button and text box\r\n self.set_seperator(row=0, column=4, rowspan=1, width=10)\r\n\r\n # An empty box beneath the button to push the grid together\r\n self.set_seperator(row=8, column=0, pady=130)\r\n\r\n self.set_label(text=\"Customer:\", row=3, column=2, sticky=tk.W)\r\n self.set_entry(textvariable=self.customer_name, show=\"\", row=3, column=3, width=35)\r\n\r\n self.set_button(text=\"Submit\", row=4, column=3, command=self.submit_entry_content, sticky=tk.N+tk.E)\r\n\r\n # self.set_label(text=\"Username:\", row=5, column=2, sticky=tk.W)\r\n # self.set_entry(textvariable=self.access_key, show=\"\", row=5, column=3, width=35)\r\n\r\n # self.set_label(text=\"Password:\", row=6, column=2, sticky=tk.W)\r\n # self.set_entry(textvariable=self.secret_access_key, show=\"*\", row=6, column=3, width=35)\r\n\r\n self.set_textbox(row=3, column=5, rowspan=6, width=80)\r\n\r\n self.display_output(self.title())\r\n\r\n def set_seperator(self, row=None, column=None, rowspan=None, columnspan=None, width=None, height=None, padx=None,\r\n pady=None):\r\n self.seperator = ttk.Frame(width=width, height=height)\r\n self.seperator.grid(row=row, column=column, rowspan=rowspan, columnspan=columnspan, padx=padx, pady=pady)\r\n\r\n\r\n def set_label(self, text=None, row=None, column=None, sticky=None, relief=None, fg=None, columnspan=None,\r\n anchor=None, pady=None, height=None, ipady=None):\r\n self.label = ttk.Label(text=text, relief=relief, fg=fg, anchor=anchor, pady=pady, height=height)\r\n self.label.grid(row=row, column=column, sticky=sticky, columnspan=columnspan, ipady=ipady)\r\n\r\n\r\n def set_entry(self, textvariable=None, show=None, row=None, column=None, pady=None, sticky=None, width=None):\r\n self.entry = ttk.Entry(textvariable=textvariable, show=show, width=width)\r\n self.entry.grid(row=row, column=column, pady=pady, sticky=sticky )\r\n\r\n\r\n def set_button(self, text=None, row=None, column=None, sticky=None, command=None):\r\n self.send_button = ttk.Button(text=text, command=command)\r\n self.send_button.grid(row=row, column=column, sticky=sticky)\r\n\r\n\r\n def set_textbox(self, row=None, column=None, rowspan=None, width=None, columnspan=None):\r\n self.textbox = tk.Text(width=width)\r\n self.textbox.grid(row=row, column=column, rowspan=rowspan, columnspan=columnspan)\r\n\r\n\r\n def set_infobox(self, title=None, message=None):\r\n messagebox.showinfo(title, message)\r\n\r\n\r\n def display_output(self, out):\r\n self.textbox.insert(tk.END, out + '\\n\\n')\r\n\r\n\r\n def submit_entry_content(self, generate_storage=True):\r\n '''\r\n\r\n Given a customer name only, this program will provision three storage accounts in Azure each with a file share\r\n activated. The three storage account names will be prefixed with 'customer', 'working' and 'master' followed by\r\n a 10 digit string.\r\n\r\n An incident alias will also be generated and will be used to name the file shares with.\r\n\r\n A connection string to the *customer* storage account file share will be returned along with the incident alias.\r\n\r\n If a customer name is provided as well as having the 'generate_storage' parameter set to False, only an incident\r\n alias will be returned and no storage in Azure generated.\r\n\r\n :param customer_name: a customer name, provided as a string to provision storage for\r\n :param generate_storage: set True to generate storage by default\r\n :return: (list) [(string) the incident alias, (string) the connection string]\r\n\r\n '''\r\n\r\n self.textbox.delete(1.0, tk.END)\r\n\r\n self.customer_name = self.customer_name.get()\r\n\r\n if self.customer_name == '':\r\n self.display_output(\"Customer name cannot be empty. Exiting...\")\r\n quit()\r\n\r\n incident_alias = generate_incident_alias()\r\n c_connection_string = ''\r\n w_connection_string = ''\r\n m_connection_string = ''\r\n\r\n # If no storage is required, return the incident alias only\r\n if not generate_storage:\r\n return incident_alias\r\n\r\n # Authentication file parameters\r\n auth_file_path = 'credentials.json'\r\n auth_file_contents = {\r\n \"clientId\": \"d4b27d44-fb20-4ef5-865f-86c70ae97c65\",\r\n \"clientSecret\": \"46b16021-e8ac-4a37-a51d-2d1b4f283c33\",\r\n \"subscriptionId\": \"e2c62cfd-29f1-4c04-8556-572c5d3a084d\",\r\n \"tenantId\": \"dc8653ba-af5f-472e-b0ce-fa0876aace30\",\r\n \"activeDirectoryEndpointUrl\": \"https://login.microsoftonline.com\",\r\n \"resourceManagerEndpointUrl\": \"https://management.azure.com/\",\r\n \"activeDirectoryGraphResourceId\": \"https://graph.windows.net/\",\r\n \"sqlManagementEndpointUrl\": \"https://management.core.windows.net:8443/\",\r\n \"galleryEndpointUrl\": \"https://gallery.azure.com/\",\r\n \"managementEndpointUrl\": \"https://management.core.windows.net/\"\r\n }\r\n\r\n # Storage account parameters\r\n resource_group = 'soar_pp-silo-ir-weu-rg'\r\n storage_account_name_suffix = generate_storage_account_name_suffix()\r\n customer_storage_account_name = 'customer' + storage_account_name_suffix\r\n master_storage_account_name = 'master' + storage_account_name_suffix\r\n working_storage_account_name = 'working' + storage_account_name_suffix\r\n storage_account_names = [customer_storage_account_name, master_storage_account_name, working_storage_account_name]\r\n\r\n tags = {\r\n 'Category': 'Test',\r\n 'Customer': self.customer_name,\r\n 'Incident': incident_alias,\r\n 'SILO': 'IR',\r\n 'Suffix': storage_account_name_suffix\r\n }\r\n\r\n storage_account_parameters = StorageAccountCreateParameters(\r\n enable_https_traffic_only=True,\r\n kind=Kind('StorageV2'),\r\n location='westeurope',\r\n sku=Sku(name='Standard_ZRS'),\r\n tags=tags\r\n )\r\n\r\n # Connection string parameters\r\n services = 'f'\r\n permissions = 'rwl'\r\n resource = 'sco'\r\n expiry = str(datetime.date.today() + datetime.timedelta(+30)) + 'T12:00:00Z'\r\n\r\n generate_auth_file(auth_file_contents, auth_file_path)\r\n\r\n storage_client = get_client_from_auth_file(StorageManagementClient, auth_path=auth_file_path)\r\n\r\n self.display_output(\"The incident alias is {}.\".format(incident_alias))\r\n self.display_output(\"The storage account name suffix is {}.\".format(storage_account_name_suffix))\r\n self.display_output(\"{}\".format(\"Checking storage account names are not already in use.\"))\r\n check_account_name_availability(storage_client, storage_account_names)\r\n self.set_infobox(\"Info\", \"Generating storage accounts.\\n\\nPlease be patient as this will take a couple of minutes.\")\r\n\r\n # Create the client, master and working storage accounts\r\n for storage_account_name in storage_account_names:\r\n create_storage_account(storage_client, storage_account_name, resource_group, storage_account_parameters)\r\n\r\n # Retrieve a storage account key\r\n storage_account_key = (storage_client.storage_accounts.list_keys(resource_group_name=resource_group,\r\n account_name=storage_account_name)).keys[0].value\r\n\r\n # Create an Azure Files share\r\n create_file_share(storage_account_name, storage_account_key, incident_alias)\r\n\r\n # Create a connection string for access to the customer storage account\r\n if storage_account_name.startswith('customer'):\r\n c_connection_string = generate_connection_string(storage_account_name, storage_account_key, services,\r\n permissions, resource, expiry)\r\n\r\n elif storage_account_name.startswith('working'):\r\n w_connection_string = generate_connection_string(storage_account_name, storage_account_key, services,\r\n permissions, resource, expiry)\r\n\r\n elif storage_account_name.startswith('master'):\r\n m_connection_string = generate_connection_string(storage_account_name, storage_account_key, services,\r\n permissions, resource, expiry)\r\n\r\n os.remove(auth_file_path)\r\n\r\n with open(incident_alias + \"-connection-strings.txt\", \"wt\") as f:\r\n f.write(\"Customer connection string:\\n{}\".format(c_connection_string))\r\n f.write(\"\\nWorking connection string:\\n{}\".format(w_connection_string))\r\n f.write(\"\\nMaster connection string:\\n{}\".format(m_connection_string))\r\n f.close()\r\n\r\n self.display_output(\"Customer connection string:\\n{}\".format(c_connection_string))\r\n self.display_output(\"Working connection string:\\n{}\".format(w_connection_string))\r\n self.display_output(\"Master connection string:\\n{}\".format(m_connection_string))\r\n self.display_output(\"Connection strings will expire at the following datetime: {}\".format(expiry))\r\n self.display_output(\"{}\".format(\"Done!\"))\r\n\r\n\r\n def title(self):\r\n return (\r\n ' ______ __ ________ ____ __________ __ ______ __ '\r\n ' / ____/ / / / _/ __ \\ / __ \\/ ____/ __ \\/ / / __ \\ \\/ / '\r\n ' / /___ / / / // /_/ / / / / / __/ / /_/ / / / / / /\\ / '\r\n ' / __/ /_/ / _/ // _, _/ / /_/ / /___/ ____/ /___/ /_/ / / / '\r\n ' /_/ \\____/ /___/_/ |_| /_____/_____/_/ /_____/\\____/ /_/ '\r\n ' ============================================================ '\r\n '\\n'\r\n )\r\n\r\n\r\ndef generate_incident_alias():\r\n '''\r\n\r\n :return: (string) two words separated by a hyphen\r\n\r\n '''\r\n\r\n haikunator = Haikunator()\r\n return haikunator.haikunate(token_length=0)\r\n\r\n\r\ndef generate_auth_file(auth_file_contents, auth_file_path):\r\n '''\r\n\r\n :param auth_file_contents: the json formatted content required for authentication\r\n :param auth_file_path: a relative or absolute path of the file to be written\r\n :return: (None)\r\n\r\n '''\r\n\r\n with open(auth_file_path, 'w') as file:\r\n json.dump(auth_file_contents, file, indent=4)\r\n\r\n file.close()\r\n\r\n\r\ndef generate_storage_account_name_suffix():\r\n '''\r\n\r\n :return: (string) a 10 digit long number\r\n\r\n '''\r\n\r\n account_name = ''\r\n while len(account_name) != 10:\r\n account_name = str(getrandbits(33))\r\n\r\n return account_name\r\n\r\n\r\ndef check_account_name_availability(storage_client, storage_account_names):\r\n '''\r\n\r\n This function is a wrapper around the check_name_availability method to ensure that the given account name is\r\n available for use in the creation of a new storage account.\r\n\r\n https://docs.microsoft.com/en-us/python/api/azure-mgmt-storage/azure.mgmt.storage.v2019_04_01.operations.storageacco\r\n untsoperations?view=azure-python#check-name-availability-name--custom-headers-none--raw-false----operation-config-\r\n\r\n :param storage_client: a storage client object\r\n :param storage_account_names: the three full (prefix and suffix) prospective storage account names\r\n :return: (None) if the storage account names are not already in use\r\n\r\n '''\r\n\r\n for storage_account_name in storage_account_names:\r\n availability_check = storage_client.storage_accounts.check_name_availability(storage_account_name)\r\n if not availability_check.name_available:\r\n exit(\"Fail. A storage account with this name already exists.\\nMessage: {}\".format(availability_check.reason))\r\n\r\n\r\ndef create_storage_account(storage_client, storage_account_name, resource_group, storage_account_parameters):\r\n '''\r\n\r\n Creates a storage account and returns nothing if successful. An asynchronous operation runs while the account is\r\n being generated and will exit the program if a storage account fails to provision.\r\n\r\n :param storage_client: a storage client object\r\n :param storage_account_name: the name of the storage account to be created\r\n :param resource_group: the resource group the storage account will belong to\r\n :param storage_account_parameters: location, storage type, tags, etc\r\n :return: (None)\r\n\r\n '''\r\n\r\n storage_async_operation = storage_client.storage_accounts.create(resource_group_name=resource_group,\r\n account_name=storage_account_name,\r\n parameters=storage_account_parameters,\r\n use_env_proxies=True)\r\n\r\n if storage_async_operation.result().provisioning_state != ProvisioningState.succeeded:\r\n exit(\"Fail. Storage Account could not be created.\")\r\n\r\n\r\ndef create_file_share(storage_account_name, storage_account_key, incident_alias):\r\n '''\r\n\r\n Creates a file share in a given storage account. The file share is named after the incident alias. A number of\r\n default directories are also created in each file share.\r\n\r\n https://docs.microsoft.com/en-gb/python/api/azure-storage-file/azure.storage.file.fileservice.fileservice?view=azure\r\n -python#create-share-share-name--metadata-none--quota-none--fail-on-exist-false--timeout-none-\r\n\r\n File Service\r\n https://docs.microsoft.com/en-gb/python/api/azure-storage-file/azure.storage.file.fileservice.fileservice?view=\r\n azure-python\r\n\r\n :param storage_account_name: the name of the storage account to have the file share created in\r\n :param storage_account_key: the key to perform operations on a storage account\r\n :param incident_alias: the two, hyphenated words used for the incident alias\r\n :return: (None)\r\n\r\n '''\r\n\r\n file_service_client = FileService(account_name=storage_account_name, account_key=storage_account_key,\r\n protocol='https')\r\n\r\n if not file_service_client.create_share(share_name=incident_alias):\r\n exit(\"The file share already exists\")\r\n\r\n for directory in ['Logs', 'Malware', 'Disk Images', 'Memory Images', 'Misc']:\r\n file_service_client.create_directory(incident_alias, directory)\r\n\r\n\r\ndef generate_connection_string(storage_account_name, storage_account_key, services, permissions, resource, expiry):\r\n '''\r\n\r\n Creates a connection string to access the given service with the given permissions. The permissions are granted at\r\n different levels, such as service, container and object. The expiry puts a limit on how long a connection string is\r\n valid for.\r\n\r\n :param storage_account_name: the name of the storage account to be created\r\n :param storage_account_key: the key to perform operations on a storage account\r\n :param services: the Azure service that the connection string is being generated for\r\n :param permissions: the permissions being granted by the connection string\r\n :param resource: the resource level that the connection string will have access to\r\n :param expiry: the time at which the connection string invalidates\r\n :return: (string) a connection string to connect to the storage account with\r\n\r\n '''\r\n\r\n sas_key = SharedAccessSignature(account_name=storage_account_name, account_key=storage_account_key)\r\n sas = sas_key.generate_account(services=services, permission=permissions, resource_types=resource, expiry=expiry,\r\n protocol='https')\r\n\r\n return \"FileEndpoint=https://{0}.file.core.windows.net/;SharedAccessSignature={1}\".format(storage_account_name, sas)\r\n\r\n\r\ndef main():\r\n root = BaseInterface()\r\n root.resizable(False, False)\r\n root.mainloop()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"silo-ir-storage.py","file_name":"silo-ir-storage.py","file_ext":"py","file_size_in_byte":17389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"459232058","text":"# Function Credits: https://github.com/lekum/pyduino/blob/master/pyduino/pyduino.py (lekum (as of 2014))\r\n# Written By: ItzTheDodo\r\n\r\nfrom Pyduino.Boards.Uno import UnoInfo\r\nfrom Pyduino.Boards.Mega import MegaInfo\r\nfrom Pyduino.Boards.Diecimila import DiecimilaInfo\r\nfrom Pyduino.Boards.Due import DueInfo\r\nfrom Pyduino.Boards.Nano import NanoInfo\r\nfrom Pyduino.Boards.Mini import MiniInfo\r\nfrom Pyduino.Boards.Lilypad import LilypadInfo\r\nfrom Pyduino.Boards.CustomBoardProfile import BoardProfileInfo\r\nfrom Pyduino.Utils.Pins import *\r\nfrom Pyduino.Utils.ReadWrite import *\r\nfrom Pyduino.Utils.ReadOnly import *\r\nimport serial\r\nimport time\r\nimport sys\r\n\r\n\r\nclass Pyduino(object):\r\n\r\n def __init__(self, board, serial_port='COM5', baud_rate='9600', read_timeout=5):\r\n\r\n __metaclass__ = ReadOnly\r\n\r\n self.serialPort = serial_port\r\n self.baudRate = baud_rate\r\n self.readTimeout = read_timeout\r\n\r\n self.board = board\r\n self.run = True\r\n self.pinnames = {}\r\n self.pins = {}\r\n self.pinModes = {}\r\n self.conn = serial.Serial(self.serialPort, self.baudRate)\r\n self.conn.timeout = self.readTimeout\r\n\r\n if self.board.lower() == \"uno\":\r\n self.boardinfo = UnoInfo()\r\n elif self.board.lower() == \"mega\":\r\n self.boardinfo = MegaInfo()\r\n elif self.board.lower() == \"diecimila\":\r\n self.boardinfo = DiecimilaInfo()\r\n elif self.board.lower() == \"due\":\r\n self.boardinfo = DueInfo()\r\n\r\n def getBoardType(self):\r\n return self.board\r\n\r\n def getBoardInfo(self):\r\n return self.boardinfo\r\n\r\n def getPinsInUse(self):\r\n return self.pins\r\n\r\n def mainloop(self, loop, *params):\r\n\r\n while self.run:\r\n\r\n loop(*params)\r\n\r\n def setup(self, definition, *params):\r\n\r\n definition(*params)\r\n\r\n def define(self, name, pin):\r\n\r\n if pin > self.boardinfo.getMainInfo()[0]:\r\n return\r\n\r\n self.pinnames[name] = pin\r\n return name\r\n\r\n def setPin(self, pin, option):\r\n\r\n if option != HIGH or option != LOW:\r\n return\r\n\r\n dv = None\r\n\r\n if option == HIGH:\r\n dv = 1\r\n elif option == LOW:\r\n dv = 0\r\n\r\n if type(pin) is str:\r\n a = self.pinnames[pin]\r\n\r\n self.pins[str(a)] = option\r\n\r\n command = (\"DW:\" + str(a) + \":\" + str(dv)).encode()\r\n self.conn.write(command)\r\n\r\n elif type(pin) is int:\r\n\r\n if pin > self.boardinfo.getMainInfo()[0]:\r\n return\r\n\r\n self.pins[str(pin)] = option\r\n\r\n command = (\"DW:\" + str(pin) + \":\" + str(dv)).encode()\r\n self.conn.write(command)\r\n else:\r\n return\r\n\r\n def newSerial(self, serial_port, baud_rate, read_timeout):\r\n self.conn = serial.Serial(serial_port, baud_rate)\r\n self.conn.timeout = read_timeout\r\n\r\n def pinMode(self, pin, mode):\r\n\r\n if mode != INPUT or mode != OUTPUT or mode != INPUT_PULLUP:\r\n return\r\n\r\n m = \"\"\r\n\r\n if mode == INPUT:\r\n m = \"I\"\r\n elif mode == OUTPUT:\r\n m = \"O\"\r\n elif mode == INPUT_PULLUP:\r\n m = \"P\"\r\n else:\r\n return\r\n\r\n if type(pin) is str:\r\n a = self.pinnames[pin]\r\n\r\n self.pins[str(a)] = mode\r\n\r\n command = (\"M:\" + str(a) + \":\" + m).encode()\r\n self.conn.write(command)\r\n\r\n elif type(pin) is int:\r\n\r\n if pin > self.boardinfo.getMainInfo()[0]:\r\n return\r\n\r\n self.pins[str(pin)] = mode\r\n\r\n command = (\"M:\" + str(pin) + \":\" + m).encode()\r\n self.conn.write(command)\r\n else:\r\n return\r\n\r\n def newReadWrite(self, pin, digitalval=None, analogval=None):\r\n\r\n if digitalval is not None and analogval is not None:\r\n return ReadWrite(self.conn, pin, digitalval=digitalval, analogval=analogval)\r\n elif digitalval is not None:\r\n return ReadWrite(self.conn, pin, digitalval=digitalval)\r\n elif analogval is not None:\r\n return ReadWrite(self.conn, pin, analogval=analogval)\r\n else:\r\n return ReadWrite(self.conn, pin)\r\n\r\n def createCustomBoardProfile(self, datapins, analogInPins, GND, pow, TX, RX):\r\n self.boardinfo = BoardProfileInfo(datapins, analogInPins, GND, pow, TX, RX)\r\n\r\n def delay(self, t):\r\n a = int(t) / 1000\r\n time.sleep(a)\r\n\r\n def stop(self):\r\n sys.exit(2)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # set all pins high for 1 sec then low for 0.5 sec\r\n\r\n p = Pyduino(\"Uno\")\r\n\r\n for i in range(p.getBoardInfo().getMainInfo()[\"0\"]):\r\n p.pinMode(i, OUTPUT)\r\n\r\n while True:\r\n for i in range(p.getBoardInfo().getMainInfo()[\"0\"]):\r\n p.setPin(i, HIGH)\r\n p.delay(1000)\r\n for i in range(p.getBoardInfo().getMainInfo()[\"0\"]):\r\n p.setPin(i, LOW)\r\n p.delay(500)\r\n","sub_path":"Pyduino/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"89084282","text":"import hmac\n\nfrom django.conf import settings\nfrom django.core.exceptions import SuspiciousOperation\nfrom django.utils.hashcompat import sha_constructor\nfrom django.utils import simplejson as json\nfrom formwizard.storage.base import BaseStorage, NoFileStorageException\nfrom django.core.files.uploadedfile import UploadedFile\nfrom django.core.files import File\n\nsha_hmac = sha_constructor\n\nclass CookieStorage(BaseStorage):\n step_cookie_key = 'step'\n step_data_cookie_key = 'step_data'\n step_files_cookie_key = 'step_files'\n extra_context_cookie_key = 'extra_context'\n\n def __init__(self, prefix, request, file_storage, *args, **kwargs):\n super(CookieStorage, self).__init__(prefix)\n self.file_storage = file_storage\n self.request = request\n self.cookie_data = self.load_cookie_data()\n if self.cookie_data is None:\n self.init_storage()\n\n def init_storage(self):\n self.cookie_data = {\n self.step_cookie_key: None,\n self.step_data_cookie_key: {},\n self.step_files_cookie_key: {},\n self.extra_context_cookie_key: {},\n }\n return True\n\n def get_current_step(self):\n return self.cookie_data[self.step_cookie_key]\n\n def set_current_step(self, step):\n self.cookie_data[self.step_cookie_key] = step\n return True\n\n def get_step_data(self, step):\n return self.cookie_data[self.step_data_cookie_key].get(step, None)\n\n def get_current_step_data(self):\n return self.get_step_data(self.get_current_step())\n\n def set_step_data(self, step, cleaned_data):\n self.cookie_data[self.step_data_cookie_key][step] = cleaned_data\n return True\n\n\n def set_step_files(self, step, files):\n if files and not self.file_storage:\n raise NoFileStorageException\n\n if not self.cookie_data[self.step_files_cookie_key].has_key(step):\n self.cookie_data[self.step_files_cookie_key][step] = {}\n\n for field, field_file in (files or {}).items():\n tmp_filename = self.file_storage.save(field_file.name, field_file)\n file_dict = {\n 'tmp_name': tmp_filename,\n 'name': field_file.name,\n 'content_type': field_file.content_type,\n 'size': field_file.size,\n 'charset': field_file.charset\n }\n self.cookie_data[self.step_files_cookie_key][step][field] = file_dict\n\n return True\n\n def get_current_step_files(self):\n return self.get_step_files(self.get_current_step())\n\n def get_step_files(self, step):\n session_files = self.cookie_data[self.step_files_cookie_key].get(step, {})\n\n if session_files and not self.file_storage:\n raise NoFileStorageException\n\n files = {}\n for field, field_dict in session_files.items():\n files[field] = UploadedFile(\n file=self.file_storage.open(field_dict['tmp_name']),\n name=field_dict['name'],\n content_type=field_dict['content_type'],\n size=field_dict['size'],\n charset=field_dict['charset'],\n )\n return files or None\n\n def get_extra_context_data(self):\n return self.cookie_data[self.extra_context_cookie_key] or {}\n\n def set_extra_context_data(self, extra_context):\n self.cookie_data[self.extra_context_cookie_key] = extra_context\n return True\n\n def reset(self):\n return self.init_storage()\n\n def update_response(self, response):\n if len(self.cookie_data) > 0:\n response.set_cookie(self.prefix, self.create_cookie_data(self.cookie_data))\n else:\n response.delete_cookie(self.prefix)\n return response\n\n def load_cookie_data(self):\n data = self.request.COOKIES.get(self.prefix, None)\n if data is None:\n return None\n\n bits = data.split('$', 1)\n if len(bits) == 2:\n if bits[0] == self.get_cookie_hash(bits[1]):\n return json.loads(bits[1], cls=json.JSONDecoder)\n\n raise SuspiciousOperation('FormWizard cookie manipulated')\n\n def get_cookie_hash(self, data):\n return hmac.new('%s$%s' % (settings.SECRET_KEY, self.prefix), data, sha_hmac).hexdigest()\n\n def create_cookie_data(self, data):\n encoder = json.JSONEncoder(separators=(',', ':'))\n encoded_data = encoder.encode(data)\n return '%s$%s' % (self.get_cookie_hash(encoded_data), encoded_data)\n","sub_path":"formwizard/storage/cookie.py","file_name":"cookie.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"97510766","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nimport math\nfrom groupy.gconv.pytorch_gconv import P4MConvZ2, P4MConvP4M\nfrom groupy.gconv.pytorch_gconv.splitgconv2d import SplitGConv2D\nfrom custom import OptimisedDivGalaxyOutputLayer\n#from groupy.gconv.pytorch_gconv.pooling import plane_group_spatial_max_pooling\n\nnclasses = 37 # GTSRB as 43 classes\n\n\ndef to_bn(x):\n xs = x.size()\n x = x.view(xs[0], xs[1] * xs[2], xs[3], xs[4])\n # x = x.view(xs[0], xs[1], xs[2], x.size()[2], x.size()[3])\n return x\n\n\ndef from_bn(x, channels=8):\n xs = x.size()\n x = x.view(xs[0], xs[1] // channels, channels, x.size()[2], x.size()[3])\n return x\n\nclass Net(nn.Module):\n def __init__(self, no_dp=False, p=0.5, optimized=False):\n super(Net, self).__init__()\n self.no_dp = no_dp\n self.p = p\n self.optimized = optimized\n self.conv1 = P4MConvZ2(in_channels=3, out_channels=8, kernel_size=5)\n self.bn1 = nn.BatchNorm2d(64)\n self.conv2 = P4MConvP4M(in_channels=8, out_channels=16, kernel_size=5)\n self.bn2 = nn.BatchNorm2d(128)\n self.conv3 = P4MConvP4M(in_channels=16, out_channels=32, kernel_size=3)\n self.bn3 = nn.BatchNorm2d(256)\n self.conv4 = P4MConvP4M(in_channels=32, out_channels=32, kernel_size=3)\n self.bn4 = nn.BatchNorm2d(256)\n self.conv5 = P4MConvP4M(in_channels=32, out_channels=64, kernel_size=3)\n self.bn5 = nn.BatchNorm2d(512)\n self.conv6 = P4MConvP4M(in_channels=64, out_channels=64, kernel_size=3)\n self.bn6 = nn.BatchNorm2d(512)\n\n #self.fc1 = nn.Linear(8192, 2048)\n #self.fc2 = nn.Linear(2048, 2048)\n #self.fc3 = nn.Linear(2048, nclasses)\n self.fc1 = nn.Linear(8192, 512)\n self.fc2 = nn.Linear(512, nclasses)\n\n self.optimized_output = OptimisedDivGalaxyOutputLayer()\n\n self.op_loss = 0\n\n # Initilize the parameters\n '''\n for m in self.modules():\n if isinstance(m, SplitGConv2D):\n #n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n '''\n\n def optimized_loss(self):\n return self.op_loss\n\n def forward(self, x):\n #print(x.size())\n x = F.relu(self.bn1(to_bn(self.conv1(x))))\n x = F.max_pool2d(x, kernel_size=3, stride=3, padding=1)\n x = from_bn(x)\n #print(x.size())\n x = F.relu(self.bn2(to_bn(self.conv2(x))))\n x = F.max_pool2d(x, kernel_size=2, stride=2, padding=1)\n x = from_bn(x)\n #print(x.size())\n x = from_bn(F.relu(self.bn3(to_bn(self.conv3(x)))))\n x = from_bn(F.relu(self.bn4(to_bn(self.conv4(x)))))\n x = from_bn(F.relu(self.bn5(to_bn(self.conv5(x)))))\n\n x = F.relu(self.bn6(to_bn(self.conv6(x))))\n x = F.max_pool2d(x, kernel_size=3, stride=3, padding=1)\n #print(x.size())\n x = x.view(-1, 8192)\n\n x = F.dropout(F.relu(self.fc1(x)), p=self.p, training=self.training)\n #x = F.dropout(F.relu(self.fc2(x)), p=self.p, training=self.training)\n #x = F.relu(self.fc3(x))\n x = F.relu(self.fc2(x))\n\t\n with torch.no_grad():\n y = self.optimized_output.predictions(x)\n\n self.op_loss = F.mse_loss(x,y)\n \n if self.optimized:\n x = self.optimized_output.predictions(x)\n \n return x\n","sub_path":"paper_groupy.py","file_name":"paper_groupy.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"204965503","text":"class LinkedQueue:\n\n # Nested _Node class\n class _Node:\n\n __slots__ = (\"_element\", \"_next\")\n\n def __init__ (self, element):\n self._element = element\n self._next = None\n\n # Queue methods - FIFO\n\n # Queue as a linked list -> include tail pointer\n def __init__(self):\n self._head = None\n self._tail = None\n self._size = 0\n \n def __len__(self):\n return self._size\n \n def is_empty(self):\n return self._size == 0\n\n def first(self):\n if self.is_empty():\n raise (\"Queue is Empty\")\n return self._head._element\n \n def dequeue(self):\n if self.is_empty():\n raise (\"Queue is Empty\")\n answer = self._head\n self._head = self._head._next\n self._size -= 1\n if self.is_empty():\n self._tail = None\n return answer\n\n def enqueue(self, e):\n newest = self._Node(e)\n if self.is_empty():\n self._head = newest\n else:\n self._tail._next = newest\n self._tail = newest\n self._size += 1\n\ntest = LinkedQueue()\n# test = 1 -> 44 -> 9 -> 10 -> 7\ntest.enqueue(1)\ntest.enqueue(44)\ntest.enqueue(9)\ntest.enqueue(10)\ntest.enqueue(7)\n# test.first() -> 1\nprint(test.first())\n\n\"\"\"\nremove first element of the queue, and reassign the header pointer\n\nbefore -> 5\nafter -> 4\n\"\"\"\nbefore = test.__len__()\ntest.dequeue()\nafter = test.__len__()\nprint (\"before: {}\\nafter: {}\".format(before, after))","sub_path":"Data_Structures/LinkedLists/Queues/LinkedQueue.py","file_name":"LinkedQueue.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"594991119","text":"from transformers import BertForQuestionAnswering,BertTokenizerFast\nimport torch\nfrom redisai import ClusterClient\nimport numpy as np\n\ndef export_bert():\n model = BertForQuestionAnswering.from_pretrained(\"bert-large-uncased-whole-word-masking-finetuned-squad\", torchscript=True)\n model.eval()\n\n inputs = [torch.ones(1, 2, dtype=torch.int64),\n torch.ones(1, 2, dtype=torch.int64),\n torch.ones(1, 2, dtype=torch.int64)]\n\n with torch.no_grad():\n traced_model = torch.jit.trace(model, inputs)\n\n torch.jit.save(traced_model, \"traced_bert_qa.pt\")\n\ndef load_bert():\n model_file = 'traced_bert_qa.pt'\n\n with open(model_file, 'rb') as f:\n model = f.read()\n startup_nodes = [{\"host\": \"127.0.0.1\", \"port\": \"30001\"}, {\"host\": \"127.0.0.1\", \"port\":\"30002\"}, {\"host\":\"127.0.0.1\", \"port\":\"30003\"}]\n cc = ClusterClient(startup_nodes = startup_nodes)\n hash_tags = cc.execute_command(\"RG.PYEXECUTE\", \"gb = GB('ShardsIDReader').map(lambda x:hashtag()).run()\")[0]\n print(hash_tags)\n for hash_tag in hash_tags:\n print(\"Loading model bert-qa{%s}\" %hash_tag.decode('utf-8'))\n cc.modelset('bert-qa{%s}' %hash_tag.decode('utf-8'), 'TORCH', 'CPU', model)\n print(cc.infoget('bert-qa{%s}' %hash_tag.decode('utf-8')))\n\ndef main():\n export_bert()\n load_bert()\nif __name__ == \"__main__\":\n main()","sub_path":"qasearch/export_load_bert.py","file_name":"export_load_bert.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497882212","text":"import itertools\r\nimport math as m\r\nimport functools\r\n\r\ncidades = {'Lisboa': (38.7452, -9.1604), \r\n 'Vila Nova de Gaia': (41.1333, -8.6167),\r\n 'Porto': (41.1495, -8.6108),\r\n 'Braga': (41.5333, -8.4167),\r\n 'Matosinhos': (41.2077, -8.6674),\r\n 'Amadora': (38.75, -9.2333),\r\n 'Almada': (38.6803, -9.1583),\r\n 'Oeiras': (38.697, -9.3017),\r\n 'Gondomar': (41.15, -8.5333),\r\n 'Guimarães': (41.445, -8.2908),\r\n 'Odivelas': (38.8, -9.1833),\r\n 'Coimbra': (40.2111, -8.4291),\r\n 'Vila Franca de Xira': (38.95, -8.9833),\r\n 'Maia': (41.2333, -8.6167),\r\n 'Leiria': (39.7431, -8.8069),\r\n 'Setúbal': (38.5243, -8.8926),\r\n 'Viseu': (40.6667, -7.9167),\r\n 'Valongo': (41.1833, -8.5),\r\n 'Viana do Castelo': (41.7, -8.8333),\r\n 'Paredes': (41.2, -8.3333),\r\n 'Vila do Conde': (41.35, -8.75),\r\n 'Torres Vedras': (39.0833, -9.2667),\r\n 'Barreiro': (38.6609, -9.0733),\r\n 'Aveiro': (40.6389, -8.6553),\r\n 'Queluz': (38.7566, -9.2545),\r\n 'Mafra': (38.9333, -9.3333),\r\n 'Penafiel': (41.2, -8.2833),\r\n 'Loulé': (37.144, -8.0235)}\r\n\r\ndef conversor(graus):\r\n return (graus[0]*111.1949,graus[1]*85.1102)\r\n\r\n\r\ndef distancia_pontos(p1, p2):\r\n\r\n distancia=m.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)\r\n return distancia\r\n\r\n\r\ndef difY(coord1, coord2):\r\n return m.fabs(coord1-coord2)\r\n\r\ndef distancia_itinerario(itinerario):\r\n dT=[]\r\n coord = map(lambda x: cidades[x] , itinerario)\r\n distancias=list(map(conversor, coord))\r\n\r\n for n in range(len(distancias)-1):\r\n dT.append(distancia_pontos(distancias[n], distancias[n+1]))\r\n\r\n return sum(dT)\r\n\r\ndef adicionar_cidade(itinerario, cidade):\r\n \r\n comparacoes=[]\r\n cidadeY=cidades[cidade][1]\r\n coordY = list(map(lambda x: cidades[x][1], itinerario))\r\n \r\n for n in range(len(coordY)):\r\n comparacoes.append(difY(coordY[n], cidadeY))\r\n\r\n add = comparacoes.index(min(comparacoes))\r\n\r\n if add == 0:\r\n itinerario.insert(1, cidade)\r\n\r\n elif add == (len(itinerario)-1):\r\n itinerario.insert((len(itinerario)-1), cidade)\r\n \r\n elif comparacoes[add]comparacoes[add+1]:\r\n itinerario.insert(add+2, cidade)\r\n\r\n return itinerario\r\n\r\n\r\n\r\ndef construir_itinerario(origem, destino,lista_cidades):\r\n \"\"\"Contrói um itinerário de forma a gerar a melhor forma de percorrer o mesmo\r\n\r\n Pre:\r\n -Deve conter pelo menos uma origem e um destino\r\n\r\n Args:\r\n origem (str): Primeira cidade do itinerário\r\n destino (str]): Última cidade do itinerário\r\n lista_cidades (list): lista que contém as várias cidades que iram pertencer ao itinerário\r\n\r\n Returns:\r\n list: itinerário final\r\n\r\n >>> construir_itinerario('Lisboa', 'Porto', ['Viseu', 'Coimbra', 'Aveiro', 'Setúbal'])\r\n ['Lisboa', 'Setúbal', 'Coimbra', 'Viseu', 'Aveiro', 'Porto']\r\n\r\n >>> construir_itinerario('Lisboa', 'Porto', [])\r\n ['Lisboa', 'Porto']\r\n \r\n >>> construir_itinerario('Porto', 'Lisboa', ['Viseu', 'Coimbra', 'Aveiro', 'Setúbal'])\r\n ['Porto', 'Aveiro', 'Viseu', 'Coimbra', 'Setúbal', 'Lisboa']\r\n\r\n >>> construir_itinerario( 'Almada', 'Aveiro', ['Lisboa', 'Coimbra', 'Leiria', 'Torres Vedras', 'Mafra'])\r\n ['Almada', 'Lisboa', 'Mafra', 'Torres Vedras', 'Leiria', 'Coimbra', 'Aveiro']\r\n \"\"\"\r\n validas=[]\r\n it = [origem, destino]\r\n combinacoes = itertools.chain(it, lista_cidades)\r\n for i in itertools.permutations(combinacoes):\r\n \r\n if i[0]==origem and i[len(i)-1]==destino:\r\n validas.append(i)\r\n\r\n validas_list = list(map(lambda x: list(x), validas))\r\n distancias_it = list(map(distancia_itinerario, validas_list))\r\n\r\n return validas_list[distancias_it.index(min(distancias_it))]\r\n \r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n itinerario=[origem]\r\n dest = conversor(cidades[destino])\r\n coord = list(map(lambda x: cidades[x], lista_cidades))\r\n\r\n\r\n coord_to_distancias = list(map(conversor, coord))\r\n distancias = list(map(lambda x: distancia_pontos(dest , x), coord_to_distancias))\r\n duplas_coord_city = sorted(list(map(lambda x,y:(x,y), distancias, lista_cidades)), reverse=True)\r\n lista_City_Order = list(map(lambda x: x[1], duplas_coord_city)) #alterar para distancias\r\n\r\n itinerario_f = list(itertools.chain(itinerario, lista_City_Order))\r\n itinerario_f.append(destino)\r\n\r\n return itinerario_f\r\n\"\"\"\r\n","sub_path":"Trabalho3/teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612870866","text":"# Define some useful constants and functions\n\nfrom datetime import datetime\nimport numpy as np\nsettings = {'num_lines': 51,\n 'pos_tol': 1e-2,\n 'gap_tol': 0.05,\n 'move_tol': 0.2,\n 'iterator': range(50, 81, 4),\n 'min_neighbour_dist': 1e-4,\n }\nsettings_strict = {'num_lines': 81,\n 'pos_tol': 1e-3,\n 'gap_tol': 0.001,\n 'move_tol': 0.4,\n 'iterator': range(80, 201, 5),\n 'min_neighbour_dist': 5e-6,\n }\n\n# sig_xyz = pauli_xyz tensor identity\nsig_x, sig_y, sig_z = [np.zeros([4, 4], dtype=complex) for i in range(3)]\nsig_x[0, 2], sig_x[1, 3], sig_x[2, 0], sig_x[3, 1] = 1, 1, 1, 1\nsig_y[0, 2], sig_y[1, 3], sig_y[2, 0], sig_y[3, 1] = -1j, -1j, 1j, 1j\nsig_z[0, 0], sig_z[1, 1], sig_z[2, 2], sig_z[3, 3] = 1, 1, -1, -1\nsig = np.array([sig_x, sig_y, sig_z])\n\n# Constants related to real material\n# unit of length: angstrom\n# unit of energy: eV\n\n# Consts from PHYSICAL REVIEW B 82, 045122 (2010)\nCONST_HJZ = {\n \"A1\": 2.26, \"A2\": 3.33, \"C\": -0.0083, \"D1\": 5.74, \"D2\": 30.4,\n \"M\": 0.28, \"B1\": 6.86, \"B2\": 44.5\n}\n# Consts from New J. Phys. 12 043048 (2010)\nCONST_HZL = { # Interesting!!!!!\n \"A1\": 3.3, \"A2\": 4.1, \"C\": -0.0068, \"D1\": 1.2, \"D2\": -30.1,\n \"M\": 0.28, \"B1\": 1.5, \"B2\": -54.1\n}\n\ndef nt():\n '''\n Format the time.\n '''\n return datetime.now().strftime(\"%y-%m-%d-%H-%M-%S\")\n\n\ndef convertSpin(S):\n r'''\n Convert the spin array with a form of $(r,\\theta,\\phi)$ into a form of $(Sx,Sy,Sz)$\n '''\n return np.array([([s[0]*np.sin(s[1])*np.cos(s[2]), s[0]*np.sin(s[1])\n * np.sin(s[2]), s[0]*np.cos(s[1])])for s in S])\n ","sub_path":"Release/_utils.py","file_name":"_utils.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"78513652","text":"import numpy as np\nfrom random import random as rand\nimport matplotlib.pyplot as plt\nimport time\nfrom waveletleader import WaveletTransform\n\n\nclass Process():\n def __init__(self):\n self.name = None\n self.X = None\n self.dX = None\n \n def plot(self):\n if self.X is not None:\n \n fig = plt.figure()\n ax0 = plt.subplot2grid((2,1),(0,0),rowspan=1)\n plt.ylabel('$X$')\n plt.title(self.name)\n ax1 = plt.subplot2grid((2,1),(1,0),rowspan=1,sharex=ax0)\n plt.ylabel('$dX$')\n ax0.set_xlim([0,len(self.X)])\n ax0.plot(self.X)\n ax1.plot(self.dX)\n ax0.grid(True)\n ax1.grid(True)\n plt.show()\n \n\nclass MRW(Process):\n ''' produces a MRW as in Bacry, Delour, Muzy\n number of point (nbpoint) should be 2^j + 1\n X is the increment process the walk is cumsum(X) \n zetaq = (H+lambda^2)*q-lambda^2*q.^2/2 '''\n def __init__(self,H,lambd,L,npoint,q,seed=None):\n self.H = H\n self.lambd = lambd\n self.L = L\n self.npoint = npoint\n self.q = q\n self.dX = None\n self.X = None\n self.name = 'MRW'\n if seed is not None:\n self.seed = seed\n else :\n self.init_seed()\n\n def init_seed(self):\n seed0 = round(10*time.time())\n seed1 = round(100*rand()*seed0)\n seed2 = round(100*rand()*seed1)\n self.seed = np.array([seed0,seed1,seed2])\n \n def gen(self):\n fbm = FBM(H=self.H,npoint=self.npoint)\n fbm.gen()\n # Covariance of gaussian random walk \n dL = np.arange(self.L)\n cov = np.ones(self.npoint) \n cov[dL] = self.L/(1+dL) \n cov = self.lambd**2*np.log(cov)\n # Circulant matrix\n rz = np.concatenate((cov,cov[::-1][1:self.npoint-1]))\n # Root of the circulant matrix via fft\n roots = np.fft.fft(rz).real\n w = np.random.normal(0,1,2*self.npoint-2) + 1j*np.random.normal(0,1,2*self.npoint-2)\n W = np.sqrt(roots/(2*self.npoint-2))*w\n Z = np.fft.fft(W)\n omega = Z[0:self.npoint].real\n self.dX = fbm.dX*np.exp(omega)\n #print(self.dX)\n self.X = np.concatenate(([0],np.cumsum(self.dX[:-1])))\n\n\nclass FBM(Process):\n ''' Fractional Brownian motion synthesis with circulant matrix method\n B(t) is synthetized for t in [0,1] and variance (of white gaussian noise) equal to 1.\n Inputs:\n N : number of samples\n H : Hurst parameter (0 < H < 1)\n [seed] : states (integers) for random number generators\n Outputs:\n X : H-fBm N-length trace\n dX : H-fGn : dX[n] = X[n+1] - X[n] ''' \n \n def __init__(self,H,npoint,seed=None):\n self.H = H\n self.npoint = npoint\n self.dX = None\n self.X = None\n self.name = 'FBM'\n if seed is not None:\n self.seed = seed\n else :\n self.seed = round(time.time())\n \n \n def gen(self):\n s,n,tmax = 1,np.arange(self.npoint),1\n dt = tmax/self.npoint\n # Covariance of fractional Gaussian noise (i.e., increments of the fbm)\n cov = (dt)**(2*self.H)*s/2*(abs(n-1)**(2*self.H) + abs(n+1)**(2*self.H) - 2*abs(n)**(2*self.H))\n # Circulant matrix\n rz = np.concatenate((cov,cov[::-1][1:self.npoint-1]))\n # Roots of circulant matrix via fft \n roots = np.fft.fft(rz).real\n # White noise\n w = np.random.normal(0,1,2*self.npoint-2) + 1j*np.random.normal(0,1,2*self.npoint-2)\n # \n W = np.sqrt(roots/(2*self.npoint-2))*w\n Z = np.fft.fft(W)\n self.dX = Z[0:self.npoint].real\n self.X = np.concatenate(([0],np.cumsum(self.dX[:-1])))\n #self.X = np.cumsum(self.dX[:-1])\n\n\n \nif __name__ == '__main__':\n # FBM \n fbm = FBM(H=0.4,npoint=2048);fbm.gen()\n fbm.plot()\n # MRW \n c1,c2 = 0.7,-.08\n mrw = MRW(c1+c2,sqrt(-c2),1,2048,0);mrw.gen()\n mrw.plot()\n dx_fbm, Lx_fbm = WT.DxLx1d(fbm.X)\n#==============================================================================\n# WT = WaveletTransform()\n# # FBM\n# fbm = FBM(H=0.4,npoint=2048)\n# fbm.gen()\n# dx_fbm, Lx_fbm = WT.DxLx1d(fbm.X)\n# fig = plt.figure()\n# ax0 = plt.subplot2grid((3,1),(0,0),rowspan=1)\n# plt.ylabel('$X$')\n# plt.title('FBM')\n# ax1 = plt.subplot2grid((3,1),(1,0),rowspan=1,sharex=ax0)\n# ax2 = plt.subplot2grid((3,1),(2,0),rowspan=1)\n# ax0.set_xlim([0,len(fbm.X)])\n# ax0.plot(fbm.X)\n# ax1.plot(fbm.dX)\n# ax2.plot(WT.scales,[np.var(np.log(Lx_fbm.value[j])) for j in WT.scales])\n# plt.ylabel('$dX$')\n# ax0.grid(True)\n# ax1.grid(True)\n# ax2.grid(True)\n# plt.show()\n# \n# c2 = -.08\n# c1 = 0.7\n# mrw = MRW(c1+c2,sqrt(-c2),1,2048,0)\n# mrw.gen()\n# dx_mrw, Lx_mrw = WT.DxLx1d(mrw.X)\n#==============================================================================\n ","sub_path":"first-attempt-no-tensorflow/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"606897738","text":"import scrapy\nimport re\nfrom scrapy.http import Request\nfrom items import NovelprojectItem\nfrom items import NovelprojectItem2\n#翻页爬取\n\nclass NovelSpider(scrapy.Spider):\n name = 'novel'\n allowed_domains = ['www.quanshuwang.com']\n offset=1\n adr = \".html\"\n url=\"http://www.quanshuwang.com/list/1_\"\n start_urls=[url+str(offset)+\".html\"]\n # start_urls = ['http://www.quanshuwang.com/list/1_1.html'] # 全书网玄幻魔法类第一页\n\n # ********** Begin **********#\n # 1.定义函数,通过'马上阅读'获取每一本书的 URL\n def parse(self, response):\n book_urls = response.xpath('//li/a[@class=\"l mr10\"]/@href').extract()#\n three_book_urls = book_urls[0:32]\n # three_book_urls= self.start_urls[0:32]\n for book_url in three_book_urls:\n yield Request(book_url, callback=self.parse_read)\n # offset+=1,在函数的最后实现翻页功能\n\n if self.offset < 10:\n self.offset += 1\n yield Request(self.url + str(self.offset) + self.adr, callback=self.parse)\n\n # 2.定义函数,进入小说简介页面,获取信息,得到后yield返回给pipelines处理,并获取'开始阅读'的url,进入章节目录\n def parse_read(self, response):\n item = NovelprojectItem()\n name = response.xpath('//div[@class=\"b-info\"]/h1/text()').extract_first()\n description = response.xpath('//div[@class=\"infoDetail\"]/div/text()').extract_first()\n state = response.xpath('//div[@class=\"bookDetail\"]/dl[1]/dd/text()').extract_first()\n author = response.xpath('//div[@class=\"bookDetail\"]/dl[2]/dd/text()').extract_first()\n item['name'] = name\n item['description'] = description\n item['state'] = state\n item['author'] = author\n #随着需要导出哪个数据变化,有时不要注释这一句。\n yield item\n read_url = response.xpath('//a[@class=\"reader\"]/@href').extract()[0]\n #读取详细信息,章节。\n yield Request(read_url, callback=self.parse_info)\n\n # 3.定义函数,进入章节目录,获取小说章节名并yield返回\n def parse_info(self, response):\n item = NovelprojectItem2()\n # tablename=response.xpath('//div[@class=\"b-info\"]/h1/text()').extract_first()\n # tablename = response.xpath('//div[@class=\"main-index\"]/a3/text()').extract_first()\n titles = response.xpath('//div[@class=\"clearfix dirconone\"]/li')\n tablename=response.xpath('//*[@id=\"chapter\"]/div[3]/div[1]/strong/text()').extract_first()\n for each in titles:\n title = each.xpath('.//a/text()').extract_first()\n item['tablename'] = tablename\n item['title'] = title\n #有时要注释这一句\n # yield item\n\n # ********** End **********#\n","sub_path":"2020421/bookNameSpider/novel.py","file_name":"novel.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"44784805","text":"import unittest\n\n\ndef cipher(s):\n \"\"\"\n 文字列を暗号化する\n \n Args:\n s (str): 文字列\n\n Returns:\n str: 暗号化された文字列\n \"\"\"\n\n return \"\".join([str(219 - ord(x)) if \"a\" <= x <= \"z\" else x for x in s])\n\n\ndef uncipher(s):\n \"\"\"\n 暗号化された文字列を復号化する\n\n Args:\n s (str): 暗号化された文字列\n\n Returns:\n str: 元の文字列\n \"\"\"\n\n result = \"\"\n i = 0\n while i < len(s):\n if s[i].isdecimal():\n result += chr(219 - int(s[i:i + 3]))\n i += 3\n else:\n result += s[i]\n i += 1\n return result\n\n\nclass FuncTest(unittest.TestCase):\n def test(self):\n s = \"I'm a perfect human.\"\n self.assertEqual(cipher(s), \"I'110 122 107118105117118120103 115102110122109.\")\n self.assertEqual(uncipher(cipher(s)), s)\n\n\nunittest.main()\n\n","sub_path":"0/08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"631932583","text":"# Settings -> Project Settings -> Project Interpreter -> Gear Icon (show all) -> Select new project -> click tree icon ->\n# select lib/site-packages from the AcousticRendererConda project in order to import torch, cv2, numpy, etc...\n\nimport torch\nfrom torch.autograd import Function\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport torch.optim\nfrom utils import *\nfrom RenderParameters import RenderParameters\nfrom ProjData import ProjData\nfrom timeDelay import *\nfrom scipy.signal import hilbert\n\nfs = 100\n\n\ndef genCos(f):\n T = 1 / fs\n tStop = 1\n x = np.arange(0, tStop, T)\n w = 2 * math.pi * f * x\n _y = np.cos(w)\n return x, _y\n\n\ndef genCosFFT(y):\n _Y = np.fft.fft(y)\n _freq = np.fft.fftfreq(_Y.shape[-1])\n _freq = _freq * fs\n\n return _freq, _Y\n\n\nif __name__ == '__main__':\n RP = RenderParameters()\n\n RP.generateTransmitSignal()\n\n RP.defineProjectorPos(thetaStart=0, thetaStop=359, thetaStep=1, rStart=1, rStop=1, zStart=.3, zStop=.3)\n\n pDataNP = ProjData(projPos=RP.projectors[0, :], Fs=RP.Fs, tdur=RP.tDur)\n pDataTorch = ProjData(projPos=RP.projectors[0, :], Fs=RP.Fs, tdur=RP.tDur)\n\n tauGT = torch.tensor([.005], requires_grad=True)\n\n pDataTorch.wfm = torchTimeDelay(RP.transmitSignal, torch.tensor(RP.Fs, requires_grad=True, dtype=torch.float64),\n tauGT)\n\n pDataNP.wfm = timeDelay(RP.transmitSignal.detach().numpy(), RP.Fs, tauGT.detach().numpy())\n\n pDataNP.RC(RP.transmitSignal.detach().numpy())\n\n pDataTorch.RCTorch(RP.transmitSignal)\n\n #plt.stem(pDataNP.wfmRC.real)\n #plt.show()\n #print(pDataTorch.wfmRC)\n #print(pDataNP.wfmRC)\n\n print(np.sum(pDataTorch.wfmRC[:, 0].detach().numpy() - pDataNP.wfmRC.real))\n print(np.sum(pDataTorch.wfmRC[:, 1].detach().numpy() - pDataNP.wfmRC.imag))\n\n plt.subplot(2, 1, 1)\n f1 = plt.stem(pDataTorch.wfmRC[:, 0].detach().numpy())\n\n plt.subplot(2, 1, 2)\n f2 = plt.stem(pDataNP.wfmRC.real, linefmt='-')\n plt.show()","sub_path":"unit_tests/RCTest.py","file_name":"RCTest.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462947970","text":"from PyQt4.QtCore import pyqtSignal\nfrom PyQt4.QtGui import QWidget, QVBoxLayout\nfrom ert_gui.tools.plot import ReportStepWidget, ScaleTracker, PlotScalesWidget\n\nclass PlotMetricsWidget(QWidget):\n\n VALUE_MIN = \"Value Minimum\"\n VALUE_MAX = \"Value Maximum\"\n\n DEPTH_MIN = \"Depth Minimum\"\n DEPTH_MAX = \"Depth Maximum\"\n\n TIME_MIN = \"Time Minimum\"\n TIME_MAX = \"Time Maximum\"\n\n plotSettingsChanged = pyqtSignal()\n\n def __init__(self):\n QWidget.__init__(self)\n self.__layout = QVBoxLayout()\n\n self.__data_type_key = None\n self.__trackers = {}\n self.__spinners = {}\n\n self.__layout.addWidget(self.addScaler(\"value_min\", self.VALUE_MIN))\n self.__layout.addWidget(self.addScaler(\"value_max\", self.VALUE_MAX))\n self.__layout.addWidget(self.addScaler(\"time_min\", self.TIME_MIN, True,True))\n self.__layout.addWidget(self.addScaler(\"time_max\", self.TIME_MAX, True))\n self.__layout.addWidget(self.addScaler(\"depth_min\", self.DEPTH_MIN))\n self.__layout.addWidget(self.addScaler(\"depth_max\", self.DEPTH_MAX))\n\n self.__layout.addSpacing(10)\n\n self.__report_step_widget = ReportStepWidget()\n self.__report_step_widget.reportStepTimeSelected.connect(self.plotSettingsChanged)\n self.__layout.addWidget(self.__report_step_widget)\n\n self.__layout.addStretch()\n\n self.setLayout(self.__layout)\n\n def updateTrackers(self, values):\n type_key = values[\"type_key\"]\n enabled = values[\"enabled\"]\n value = values[\"value\"]\n tracker = self.__trackers[type_key]\n tracker.setValues(self.__data_type_key, value, enabled)\n self.plotSettingsChanged.emit()\n\n def addScaler(self, type_key, title, time_spinner=False,min_value=False):\n valueSpinner = PlotScalesWidget(type_key, title, time_spinner,min_value)\n valueSpinner.plotScaleChanged.connect(self.updateTrackers)\n self.__spinners[type_key] = valueSpinner\n self.__trackers[type_key] = ScaleTracker(type_key)\n return valueSpinner\n\n def getDataKeyType(self):\n return self.__data_type_key\n\n def setDataKeyType(self, data_key_type):\n self.__data_type_key = data_key_type\n for key in self.__spinners:\n scaler = self.__spinners[key]\n self.blockSignals(True)\n values = {\"type_key\": key, \"enabled\": self.getIsEnabled(key), \"value\": self.getValue(key)}\n scaler.setValues(values)\n self.blockSignals(False)\n\n def getValue(self, type_key):\n if type_key in self.__trackers:\n return self.__trackers[type_key].getScaleValue(self.__data_type_key)\n else:\n return None\n\n def getIsEnabled(self, type_key):\n if type_key in self.__trackers:\n return self.__trackers[type_key].isEnabled(self.__data_type_key)\n else:\n return None\n\n def getSettings(self):\n settings = {\n \"value_min\" : self.getValue(\"value_min\"),\n \"value_max\" : self.getValue(\"value_max\"),\n \"time_min\" : self.getValue(\"time_min\"),\n \"time_max\" : self.getValue(\"time_max\"),\n \"depth_min\" : self.getValue(\"depth_min\"),\n \"depth_max\" : self.getValue(\"depth_max\"),\n \"report_step_time\" : self.__report_step_widget.getSelectedValue().ctime()\n }\n return settings","sub_path":"devel/python/python/ert_gui/tools/plot/plot_metrics_widget.py","file_name":"plot_metrics_widget.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"146964852","text":"'''\nCreated on Feb 21, 2018\n\n@author: hshi\n'''\nimport numpy as np\ndef extractRelativeJointFeatureFromDataList_spatial_temporal(sampleList, frameLabelList, usedJoints=np.linspace(0, 24, 25).astype('int')):\n \n \n outSampleList = list()\n outFrameLabelList = list()\n segLenList = list()\n \n jointNum = len(usedJoints)\n #selectedColumns = np.concatenate((usedJoints * 3, usedJoints * 3 + 1, usedJoints * 3 + 2))\n #selectedColumns.sort()\n #featureMat_all = np.zeros([1, ((jointNum * (jointNum)/2)*3) + ((jointNum ** 2) * 3)])\n \n for i in range(len(sampleList)):\n currentSample = sampleList[i]#[:, selectedColumns]\n \n currentSpatialFeature = extractRelativeJointFeatureFromMat_spatial(currentSample, jointNum)\n currentTemporalFeature = extractRelativeJointFeatureFromMat_temporal(currentSample, jointNum)\n \n currentFeature = np.concatenate((currentSpatialFeature[1: , :], currentTemporalFeature), axis = 1)\n \n outSampleList.append(currentFeature)\n outFrameLabelList.append(frameLabelList[i][1:])\n segLenList.append(currentFeature.shape[0])\n \n \n return outSampleList, outFrameLabelList, segLenList\n\ndef extractRelativeJointFeatureFromMat_spatial(sampleMat, jointNum):\n feature = np.zeros((sampleMat.shape[0], (jointNum * (jointNum - 1)/2)*3))\n \n featureColumnIte = 0\n for jointIte1 in range(jointNum - 1):\n for jointIte2 in range(jointIte1 + 1, jointNum):\n feature[:,featureColumnIte * 3 : (featureColumnIte + 1) * 3] = \\\n sampleMat[:, jointIte1 * 3 : (jointIte1 + 1) * 3] - sampleMat[:, jointIte2 * 3 : (jointIte2 + 1) * 3]\n featureColumnIte += 1\n \n return feature\n \n \n \ndef extractRelativeJointFeatureFromMat_temporal(sampleMat, jointNum):\n \n feature = np.zeros((sampleMat.shape[0] - 1, (jointNum ** 2) * 3))\n \n featureColumnIte = 0\n \n for jointIte1 in range(jointNum):\n for jointIte2 in range(jointNum):\n feature[:, featureColumnIte * 3 : (featureColumnIte + 1) * 3] = \\\n sampleMat[1:, jointIte1 * 3 : (jointIte1 + 1) * 3] - sampleMat[0:-1, jointIte2 * 3 : (jointIte2 + 1) * 3]\n \n featureColumnIte += 1\n \n return feature\ndef list2Mat_fast(inList, sequenceLengthsList):\n sequenceLengths = np.array(sequenceLengthsList)\n totalLength = sequenceLengths.sum()\n outMat = np.zeros([totalLength, inList[0].shape[-1]])\n beg = 0\n end = 0\n \n for i in range(len(inList)):\n beg = end\n end = beg + sequenceLengths[i]\n outMat[beg:end, :] = inList[i]\n \n return outMat[1:]\ndef frameLabelList2FrameStateList(frameLabelList, stateNumPerClass):\n \n frameStateList = list()\n \n for i in range(len(frameLabelList)):\n currentFrameLabels = frameLabelList[i]\n currentFrameStates = currentFrameLabels * stateNumPerClass + np.round(np.linspace(-0.5, stateNumPerClass - 0.51, currentFrameLabels.shape[0])).astype('int')\n frameStateList.append(currentFrameStates)\n \n return frameStateList\n\ndef basicNormalization(sampleList, prior):\n \n for i in range(len(sampleList)):\n sampleList[i] = prior.transform(sampleList[i])\n\n return sampleList\n\n\nimport numpy as np\ndef paddingData(sampleList, segLen_max):\n \n paddedDataList = list()\n sampleNum = len(sampleList)\n dataShape = list(sampleList[0].shape)\n dataShape[0] = segLen_max\n \n for sampleIte in range(sampleNum):\n currentPaddedData = np.zeros(dataShape)\n currentPaddedData[:sampleList[sampleIte].shape[0],...] = sampleList[sampleIte]\n paddedDataList.append(currentPaddedData)\n \n return paddedDataList\n\n","sub_path":"src/Tools/Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":3834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"272019125","text":"from kafka import KafkaConsumer\nfrom json import loads\nfrom elasticsearch import Elasticsearch\nfrom time import sleep\ndef connect_elasticsearch():\n _es = None\n _es = Elasticsearch([{'host': 'localhost', 'port': 9200}])\n if _es.ping():\n print('Connected')\n else:\n print('Awww it could not connect!')\n return _es\n\nconsumer = KafkaConsumer(\n 'numtest',\n bootstrap_servers=['localhost:9092'],\n auto_offset_reset='earliest',\n enable_auto_commit=True,\n group_id='my-group3',\n value_deserializer=lambda x: loads(x.decode('utf-8')))\n\nes = connect_elasticsearch()\n\nfor message in consumer:\n data = loads(str(message.value))\n res = es.index(index='codeforces',doc_type='user_data',id=1,body=data)\n # print(\"The recieved data is \", data)\n print(\"result is \", res)\n sleep(5)\n","sub_path":"consumer3.py","file_name":"consumer3.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316357650","text":"\"\"\"\nprob: n computer science, edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another by counting the minimum number of operations required to transform one string into the other.\n\nThere are three operations permitted on a word: replace, delete, insert. For example, the edit distance between \"a\" and \"b\" is 1, the edit distance between \"abc\" and \"def\" is 3\nidea:\ncomp:\n\"\"\"\n\n\ndef edit_distance(w1, w2):\n distance = [[i] for i in range(len(w1) + 1)]\n distance[0] = [j for j in range(len(w2) + 1)]\n for i in range(1, len(w1) + 1):\n for j in range(1, len(w2) + 1):\n insert = distance[i][j - 1] + 1\n delete = distance[i - 1][j] + 1\n replace = distance[i - 1][j - 1]\n if w1[i - 1] != w2[j - 1]:\n replace += 1\n distance[i].append(min(insert, delete, replace))\n return distance[-1][-1]\n\n\nexpected = 1\nactual = edit_distance(\"a\", \"b\")\nprint(expected == actual)\n\nexpected = 3\nactual = edit_distance(\"abc\", \"def\")\nprint(expected == actual)\n","sub_path":"dp/edit_distance.py","file_name":"edit_distance.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"158904839","text":"# demonstrate the use of variable argument lists\n\n# define a function that takes variable argument\n\ndef addition(base, *args):\n result = 0\n for arg in args:\n result += arg\n return result\n\n\ndef main():\n # pass different argument\n print(addition(20, 50, 5, 15))\n print(addition(1, 2, 3))\n\n # pass an existing list\n myNum = [1, 50, 20]\n print(addition(*myNum))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"26-03-2021/variable-args.py","file_name":"variable-args.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"260679580","text":"#!/usr/bin/env python\n\n__author__ = \"Vivek \"\n__copyright__ = \"Copyright 2014, http://radical.rutgers.edu\"\n__license__ = \"MIT\"\n\nfrom copy import deepcopy\n\nfrom radical.entk import NoKernelConfigurationError\nfrom radical.entk import KernelBase\n\n# ------------------------------------------------------------------------------\n# \n_KERNEL_INFO = {\n \"name\": \"post_analysis\",\n \"description\": \"Analysis kernel\",\n \"arguments\": {\"--template=\": \n {\n \"mandatory\": True,\n \"description\": \"Template filename\"\n },\n \"--newname=\": \n {\n \"mandatory\": True,\n \"description\": \"New mdp filename\"\n },\n \"--dir=\":\n {\n \"mandatory\": True,\n \"description\": \"New mdp filename\"\n },\n \"--run=\":\n {\n \"mandatory\": True,\n \"description\": \"Run number\"\n },\n \"--gen=\":\n {\n \"mandatory\": True,\n \"description\": \"Gen number\"\n },\n },\n \"machine_configs\": \n {\n \"*\": {\n \"environment\" : None,\n \"pre_exec\" : None,\n \"executable\" : \"python\",\n \"uses_mpi\" : False\n },\n \"xsede.stampede\":{\n \"environment\" : None,\n \"pre_exec\" : ['module load python','export PYTHONPATH=$PYTHONPATH:/home1/02734/vivek91/expanded-ensemble/alchemical_analysis:/home1/02734/vivek91/.local/lib/python2.7/site-packages','sh transfer_local_files.sh'],\n \"executable\" : \"python\",\n \"uses_mpi\" : False\n },\n \"xsede.supermic\":{\n \"environment\" : None,\n \"pre_exec\" : ['module load python','export PYTHONPATH=/home/vivek91/modules/alchemical-analysis/alchemical_analysis:/home/vivek91/modules/alchemical-analysis:/home/vivek91/.local/lib/python2.7/site-packages:$PYTHONPATH','ln -s ../staging_area data'],\n \"executable\" : \"python\",\n \"uses_mpi\" : False\n },\n \"local.localhost\":{\n \"environment\" : None,\n \"pre_exec\" : ['export PYTHONPATH=$PYTHONPATH:/home/vivek/Research/repos/expanded-ensemble/alchemical_analysis:/home/vivek/.local/lib/python2.7/site-packages'],\n \"executable\" : \"python\",\n \"uses_mpi\" : False\n }, \n \"xsede.comet\":{\n \"environment\" : None,\n \"pre_exec\" : ['. /usr/share/Modules/init/sh','module load python', 'export PYTHONPATH=$PYTHONPATH:/home/vivek91/expanded-ensemble/alchemical_analysis:/home/vivek91/.local/lib/python2.7/site-packages', 'export LAPACK=/opt/lapack/intel','export BLAS=/opt/lapack/intel', 'export LAPACKHOME=/opt/lapack/intel','export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/lapack/intel/lib','export LIBPATH=$LIBPATH:/opt/lapack/intel/lib'],\n \"executable\" : \"python\",\n \"uses_mpi\" : False\n },\n }\n }\n\n\n# ------------------------------------------------------------------------------\n# \nclass post_analysis_kernel(KernelBase):\n\n # --------------------------------------------------------------------------\n #\n def __init__(self):\n \"\"\"Le constructor.\n \"\"\"\n super(post_analysis_kernel, self).__init__(_KERNEL_INFO)\n\n\n # --------------------------------------------------------------------------\n #\n def _bind_to_resource(self, resource_key):\n \"\"\"(PRIVATE) Implements parent class method. \n \"\"\"\n if resource_key not in _KERNEL_INFO[\"machine_configs\"]:\n if \"*\" in _KERNEL_INFO[\"machine_configs\"]:\n # Fall-back to generic resource key\n resource_key = \"*\"\n else:\n raise NoKernelConfigurationError(kernel_name=_KERNEL_INFO[\"name\"], resource_key=resource_key)\n\n cfg = _KERNEL_INFO[\"machine_configs\"][resource_key]\n\n executable = cfg['executable']\n arguments = [ 'analysis_2.py',\n '--template', self.get_arg(\"--template=\"), \n '--newname', self.get_arg(\"--newname=\"),\n '--dir', self.get_arg(\"--dir=\"),\n '--run', self.get_arg(\"--run=\"),\n '--gen', self.get_arg(\"--gen=\")\n ]\n\n self._executable = executable\n self._arguments = arguments\n self._environment = cfg[\"environment\"]\n self._uses_mpi = cfg[\"uses_mpi\"]\n self._pre_exec = cfg[\"pre_exec\"]\n\n","sub_path":"expanded-ensemble-experiments/exp-1/bin/post_analysis.py","file_name":"post_analysis.py","file_ext":"py","file_size_in_byte":5356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"6524377","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 15 14:31:09 2020\r\n\r\n@author: Olly\r\n\"\"\"\r\n\r\n#imports \r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport matplotlib.cm as cm\r\nfrom Boris_functions import E_boris\r\nfrom Boris_functions import B_boris\r\nfrom Boris_functions import damp_boris\r\nfrom field_functions4 import E_field \r\nfrom field_functions4 import B_field\r\nfrom field_functions4 import a_field\r\n\r\n#constants\r\nmass_e = 9.11e-31\r\ncharge_e = -1.6e-19\r\nc = 2.998e8\r\nepp0 = 8.85e-12\r\nThom_cross = 6.652e-29\r\nred_planck = 1.0546e-34\r\n\r\n#functions\r\ndef modulus(lst):\r\n mod2 = 0\r\n for i in range(len(lst)):\r\n mod2 += lst[i]**2\r\n mod = np.sqrt(mod2)\r\n return mod\r\n\r\ndef Gamma_p(p):\r\n modp = modulus(p)\r\n gamma = np.sqrt(1 + (modp**2)/((mass_e*c)**2))\r\n return gamma\r\n\r\ndef eta(p, E, B):\r\n factor_1 = (charge_e*red_planck)/((mass_e**2)*(c**3))\r\n gam = Gamma_p(p)\r\n v = p/(gam*mass_e)\r\n factor_0 = np.dot(v, v)\r\n if factor_0 == 0:\r\n factor_2 = E\r\n Eta = abs(factor_1*modulus(factor_2) )\r\n else:\r\n dot_factor = ((np.dot(E, v))/(np.dot(v, v)))\r\n E_perp = E - dot_factor*v\r\n B_term = np.cross(v, B)\r\n factor_2 = E_perp + B_term\r\n factor_3 = dot_factor*(modulus(v))/gam\r\n factor_4 = np.dot(factor_2, factor_2) + np.dot(factor_3, factor_3)\r\n Eta = gam*abs(factor_1*np.sqrt(factor_4))\r\n return Eta\r\n\r\n#beam characheristics\r\npulse_length = 3.4e-14\r\nlamda = 1e-6\r\nk = 2*np.pi/lamda\r\nw = c*k\r\nrc = 7\r\n\r\ne = (1/6)*(charge_e**2)*w/((np.pi)*(epp0)*mass_e*(c**3))\r\nI = ((mass_e**2)*(w**2)*(c**3)*(epp0)/(4*(charge_e**2)))*((rc/e)**(2/3))\r\nprint(I)\r\nratio = 0.2\r\n#m = 10\r\n#pulse_length = (2*m)*(np.pi/w)\r\nE0 = np.sqrt((2*I)/(c*epp0))\r\nalpha = ((np.pi)/(w*pulse_length))\r\nk0 = alpha*k\r\n\r\n#initial conditions and setup\r\npart = 1500\r\ndt = 2*(np.pi)/(part*w)\r\nn = 1\r\niter_num = int(n*pulse_length/dt + part/2)\r\nnum_pos = 50\r\n\r\n#position, momentum and E_field\r\nx_ = []\r\ny_ = []\r\nz_ = []\r\npx_ = []\r\npy_ = []\r\npz_ = []\r\nt_ = []\r\ngam_ = []\r\neta_ = []\r\nx_1 = []\r\ny_1 = []\r\nz_1 = []\r\npx_1 = []\r\npy_1 = []\r\npz_1 = []\r\nt_1 = []\r\ngam_1 = []\r\neta_1 = []\r\n\r\n#field functions\r\ndef e_field(z, t):\r\n e1 = E_field(z, t, k, w, k0, E0, 0, 0)\r\n e2 = E_field(z, t, k, w, k0, E0, -(np.pi/2), (np.pi/2))\r\n e3 = ratio*E_field(z, t, -k, w, -k0, E0, 0, 0)\r\n e4 = ratio*E_field(z, t, -k, w, -k0, E0, -(np.pi/2), (np.pi/2))\r\n E1 = (np.sqrt(0.5))*(e1 + e2 + e3 + e4)\r\n return E1\r\n\r\ndef b_field(z, t):\r\n b1 = B_field(z, t, k, w, k0, E0, 0, 0)\r\n b2 = B_field(z, t, k, w, k0, E0, -(np.pi/2), (np.pi/2))\r\n b3 = ratio*B_field(z, t, -k, w, -k0, E0, 0, 0)\r\n b4 = ratio*B_field(z, t, -k, w, -k0, E0, -(np.pi/2), (np.pi/2))\r\n E1 = (np.sqrt(0.5))*(b1 + b2 + b3 + b4)\r\n return E1\r\n\r\ndef A_field(z, t):\r\n A1 = a_field(z, t, k, w, k0, E0, 0, 0)\r\n A2 = a_field(z, t, k, w, k0, E0, -(np.pi/2), (np.pi/2))\r\n A3 = ratio*a_field(z, t, -k, w, -k0, E0, 0, 0)\r\n A4 = ratio*a_field(z, t, -k, w, -k0, E0, -(np.pi/2), (np.pi/2))\r\n a1 = (np.sqrt(0.5))*(A1 + A2 + A3 + A4)\r\n return a1\r\n\r\nfor j in range(num_pos):\r\n print(j)\r\n x=[0]\r\n y=[0]\r\n z=[(j-(num_pos/2))*lamda/num_pos]\r\n px= [0]\r\n py= [0]\r\n pz= [0]\r\n l = 0\r\n l1 = 0\r\n Ein = e_field(z[0], (-1)*part*dt/(2))\r\n Bin = b_field(z[0], (-1)*part*dt/(2))\r\n p_in = np.array([px[0], py[0], pz[0]])\r\n ETa = [eta(p_in, Ein, Bin)]\r\n for i in range(iter_num):\r\n r_old = np.array([x[i], y[i], z[i]])\r\n p_old = np.array([px[i], py[i], pz[i]])\r\n T = (i-part/2)*dt\r\n E = e_field(z[i], T)\r\n B = b_field(z[i], T)\r\n A = A_field(z[i], T)\r\n q = (charge_e*dt)/2\r\n p1 = E_boris(p_old, q, E)\r\n p2 = B_boris(p1, q/2, B)\r\n p3 = damp_boris(p2, q, E, B)\r\n p4 = B_boris(p3, q/2, B)\r\n p5 = E_boris(p4, q, E)\r\n px.append(p5[0])\r\n py.append(p5[1])\r\n pz.append(p5[2])\r\n #checks\r\n gamma = Gamma_p(p5)\r\n #positions\r\n modp2 = modulus(p5)**2\r\n v_new = c*p5/(np.sqrt(((mass_e*c)**2)+modp2))\r\n r_new = r_old + dt*v_new\r\n x.append(r_new[0])\r\n y.append(r_new[1])\r\n z.append(r_new[2])\r\n E2 = e_field(z[i+1], T)\r\n B2 = b_field(z[i+1], T)\r\n ETa.append(eta(p5, E2, B2))\r\n if i%(part) == 0:\r\n l += 1\r\n x_.append((1e6)*x[i])\r\n y_.append((1e6)*y[i])\r\n z_.append((1e6)*z[i])\r\n px_.append(px[i]/(mass_e*c))\r\n py_.append(py[i]/(mass_e*c))\r\n pz_.append(pz[i]/(mass_e*c))\r\n t_.append(T)\r\n gam_.append(gamma)\r\n eta_.append(ETa[i])\r\n if i%(part/15) == 0:\r\n l1 += 1\r\n x_1.append((1e6)*x[i])\r\n y_1.append((1e6)*y[i])\r\n z_1.append((1e6)*z[i])\r\n px_1.append(px[i]/(mass_e*c))\r\n py_1.append(py[i]/(mass_e*c))\r\n pz_1.append(pz[i]/(mass_e*c))\r\n t_1.append(T)\r\n gam_1.append(gamma)\r\n eta_1.append(ETa[i])\r\n \r\n\r\n#colour map\r\ncolors = cm.rainbow(np.linspace(0, 1, l))\r\ncolors2 = cm.rainbow(np.linspace(0, 1, l))\r\nfor k in range((num_pos)-1):\r\n colors = np.append(colors, colors2, axis = 0)\r\n\r\ncolors3 = cm.rainbow(np.linspace(0, 1, l1))\r\ncolors4 = cm.rainbow(np.linspace(0, 1, l1))\r\nfor k in range((num_pos)-1):\r\n colors3 = np.append(colors3, colors4, axis = 0)\r\n \r\n#graphs\r\nplt.figure()\r\nplt.xlim(1.1*min(t_), 1.1*max(t_))\r\nplt.ylim(1.1*min(z_), 1.1*max(z_))\r\nplt.scatter(t_, z_, s = 0.6 ,c = colors)\r\nplt.xlabel('$t/s$', fontsize = 16)\r\nplt.ylabel('$z/\\mu m$', fontsize = 16)\r\nplt.savefig('tz_rc_'+str(rc)+'_rat_'+str(ratio)+'_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(px_), 1.1*max(px_))\r\nplt.ylim(1.1*min(py_), 1.1*max(py_))\r\nplt.scatter(px_, py_, s = 0.6, c = colors)\r\nplt.xlabel('$p_x$/$m_e c$', fontsize = 16)\r\nplt.ylabel('$p_y$/$m_e c$', fontsize = 16)\r\nplt.savefig('pxpy_rc_'+str(rc)+'_rat_'+str(ratio)+'_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(z_), 1.1*max(z_))\r\nplt.ylim(1.1*min(pz_), 1.1*max(pz_))\r\nplt.scatter(z_, pz_, s=0.6, c = colors)\r\nplt.xlabel('$z/\\mu m$', fontsize = 16)\r\nplt.ylabel('$p_z$/$m_e c$', fontsize = 16)\r\nplt.savefig('zpz_rc_'+str(rc)+'_rat_'+str(ratio)+'_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(t_), 1.1*max(t_))\r\nplt.ylim(1.1*min(pz_), 1.1*max(pz_))\r\nplt.scatter(t_, pz_, s=0.6, c = colors)\r\nplt.xlabel('$t/s$', fontsize = 16)\r\nplt.ylabel('$p_z$/$m_e c$', fontsize = 16)\r\nplt.savefig('tpz_rc_'+str(rc)+'_rat_'+str(ratio)+'_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(t_), 1.1*max(t_))\r\nplt.ylim(0, 1.1*max(gam_))\r\nplt.scatter(t_, gam_, s = 0.6 ,c = colors)\r\nplt.xlabel('$t/s$', fontsize = 16)\r\nplt.ylabel('$\\gamma$', fontsize = 16)\r\nplt.savefig('tgamma_rc_'+str(rc)+'_rat_'+str(ratio)+'_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(z_), 1.1*max(z_))\r\nplt.ylim(0, 1.1*max(gam_))\r\nplt.scatter(z_, gam_, s = 0.6 ,c = colors)\r\nplt.xlabel('$z/\\mu m$', fontsize = 16)\r\nplt.ylabel('$\\gamma$', fontsize = 16)\r\nplt.savefig('zgamma_rc_'+str(rc)+'_rat_'+str(ratio)+'_final_env_norm.pdf')\r\n\r\n#graphs\r\nplt.figure()\r\nplt.xlim(1.1*min(t_1), 1.1*max(t_1))\r\nplt.ylim(1.1*min(z_1), 1.1*max(z_1))\r\nplt.scatter(t_1, z_1, s = 0.6 ,c = colors3)\r\nplt.xlabel('$t/s$', fontsize = 16)\r\nplt.ylabel('$z/\\mu m$', fontsize = 16)\r\nplt.savefig('tz_rc_'+str(rc)+'_rat_'+str(ratio)+'_detailed_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(px_1), 1.1*max(px_1))\r\nplt.ylim(1.1*min(py_1), 1.1*max(py_1))\r\nplt.scatter(px_1, py_1, s = 0.6, c = colors3)\r\nplt.xlabel('$p_x$/$m_e c$', fontsize = 16)\r\nplt.ylabel('$p_y$/$m_e c$', fontsize = 16)\r\nplt.savefig('pxpy_rc_'+str(rc)+'_rat_'+str(ratio)+'_detailed_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(z_1), 1.1*max(z_1))\r\nplt.ylim(1.1*min(pz_1), 1.1*max(pz_1))\r\nplt.scatter(z_1, pz_1, s=0.6, c = colors3)\r\nplt.xlabel('$z/\\mu m$', fontsize = 16)\r\nplt.ylabel('$p_z$/$m_e c$', fontsize = 16)\r\nplt.savefig('zpz_rc_'+str(rc)+'_rat_'+str(ratio)+'_detailed_final_env__norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(t_1), 1.1*max(t_1))\r\nplt.ylim(1.1*min(pz_1), 1.1*max(pz_1))\r\nplt.scatter(t_1, pz_1, s=0.6, c = colors3)\r\nplt.xlabel('$t/s$', fontsize = 16)\r\nplt.ylabel('$p_z$/$m_e c$', fontsize = 16)\r\nplt.savefig('tpz_rc_'+str(rc)+'_rat_'+str(ratio)+'_detailed_final_env__norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(t_1), 1.1*max(t_1))\r\nplt.ylim(0, 1.1*max(gam_1))\r\nplt.scatter(t_1, gam_1, s = 0.6 ,c = colors3)\r\nplt.xlabel('$t/s$', fontsize = 16)\r\nplt.ylabel('$\\gamma$', fontsize = 16)\r\nplt.savefig('tgamma_rc_'+str(rc)+'_rat_'+str(ratio)+'_detailed_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(z_1), 1.1*max(z_1))\r\nplt.ylim(0, 1.1*max(gam_1))\r\nplt.scatter(z_1, gam_1, s = 0.6 ,c = colors3)\r\nplt.xlabel('$z/\\mu m$', fontsize = 16)\r\nplt.ylabel('$\\gamma$', fontsize = 16)\r\nplt.savefig('zgamma_rc_'+str(rc)+'_rat_'+str(ratio)+'_detailed_final_env_norm.pdf')\r\n\r\n#other graphs\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(t_), 1.1*max(t_))\r\nplt.ylim(1.1*min(eta_), 1.1*max(eta_))\r\nplt.scatter(t_, eta_, s = 0.6 ,c = colors)\r\nplt.xlabel('$t/s$', fontsize = 16)\r\nplt.ylabel('$\\eta$', fontsize = 16)\r\nplt.savefig('etat_rc_'+str(rc)+'_rat_'+str(ratio)+'_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(z_), 1.1*max(z_))\r\nplt.ylim(1.1*min(eta_), 1.1*max(eta_))\r\nplt.scatter(z_, eta_, s=0.6, c = colors)\r\nplt.xlabel('$z/\\mu m$', fontsize = 16)\r\nplt.ylabel('$\\eta$', fontsize = 16)\r\nplt.savefig('etaz_rc_'+str(rc)+'_rat_'+str(ratio)+'_final_env_norm.pdf')\r\n\r\n#graphs\r\nplt.figure()\r\nplt.xlim(1.1*min(t_1), 1.1*max(t_1))\r\nplt.ylim(1.1*min(eta_1), 1.1*max(eta_1))\r\nplt.scatter(t_1, eta_1, s = 0.6 ,c = colors3)\r\nplt.xlabel('$t/s$', fontsize = 16)\r\nplt.ylabel('$\\eta$', fontsize = 16)\r\nplt.savefig('etat_rc_'+str(rc)+'_rat_'+str(ratio)+'_detailed_final_env_norm.pdf')\r\n\r\nplt.figure()\r\nplt.xlim(1.1*min(z_1), 1.1*max(z_1))\r\nplt.ylim(1.1*min(eta_1), 1.1*max(eta_1))\r\nplt.scatter(z_1, eta_1, s=0.6, c = colors3)\r\nplt.xlabel('$z/\\mu m$', fontsize = 16)\r\nplt.ylabel('$\\eta$', fontsize = 16)\r\nplt.savefig('etaz_rc_'+str(rc)+'_rat_'+str(ratio)+'_detailed_final_env_norm.pdf')\r\n","sub_path":"FINAL FINAL eta test.py","file_name":"FINAL FINAL eta test.py","file_ext":"py","file_size_in_byte":10155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"629321691","text":"import tensorflow as tf\nimport numpy as np\n\nfrom src.model import model\nfrom src.utl.load_param import *\nfrom src.utl.utl import *\nimport math\nimport time\nfrom src.create_dataset_csv import create_dataset_csv\nfrom src.eval_viseme import eval_viseme\n\n\ndef load_graph(frozen_graph_filename):\n # Load the protobuf file to unserialized graph_def\n with tf.io.gfile.GFile(frozen_graph_filename, \"rb\") as f:\n graph_def = tf.compat.v1.GraphDef()\n graph_def.ParseFromString(f.read())\n\n # Import the graph_def into a new Graph\n with tf.Graph().as_default() as graph:\n tf.import_graph_def(graph_def, name='')\n\n # Print all operators\n for op in graph.get_operations():\n if op.type == 'Placeholder':\n print(op.name)\n\n return graph\n\n\ndef test_frozen(graph, test_audio_name):\n\n # Output nodes\n v_cls = graph.get_tensor_by_name('net2_output/add_1:0')\n v_reg = graph.get_tensor_by_name('net2_output/add_4:0')\n jali = graph.get_tensor_by_name('net2_output/add_6:0')\n\n # Input nodes\n x = graph.get_tensor_by_name('input/Placeholder_1:0')\n x_face_id = graph.get_tensor_by_name('input/Placeholder_2:0')\n phase = graph.get_tensor_by_name('input/phase:0')\n dropout = graph.get_tensor_by_name('net1_shared_rnn/Placeholder:0')\n\n # ------------ Modification of original train_visemenet.py ----------------\n csv_test_audio = csv_dir + test_audio_name + '/'\n print(csv_test_audio)\n\n try_mkdir(pred_dir)\n\n data_dir = {'train': {}, 'test': {}}\n data_dir['test']['wav'] = open(csv_test_audio + \"test/wav.csv\", 'r')\n data_dir['test']['clip_len'] = open(csv_test_audio + \"test/clip_len.csv\", 'r')\n cv_file_len = simple_read_clip_len(data_dir['test']['clip_len'])\n print('Loading wav_raw.txt file in {:}'.format(csv_test_audio))\n\n train_wav_raw = np.loadtxt(csv_test_audio + 'wav_raw.csv')\n test_wav_raw = train_wav_raw\n\n # ============================== TRAIN SET CHUNK ITERATION ============================== #\n\n for key in ['train', 'test']:\n for lpw_key in data_dir[key].keys():\n data_dir[key][lpw_key].seek(0)\n\n print(\"===================== TEST/CV CHUNK - {:} ======================\".format(csv_test_audio))\n eof = False\n chunk_num = 0\n chunk_size_sum = 0\n\n batch_size = test_wav_raw.shape[0]\n chunk_size = batch_size * batch_per_chunk_size\n\n with tf.compat.v1.Session(graph=graph) as sess:\n\n while (not eof):\n cv_data, eof = read_chunk_data(data_dir, 'test', chunk_size)\n chunk_num += 1\n chunk_size_sum += len(cv_data['wav'])\n\n print('Load Chunk {:d}, size {:d}, total_size {:d} ({:2.2f})'\n .format(chunk_num, len(cv_data['wav']), chunk_size_sum, chunk_size_sum / cv_file_len))\n\n full_idx_array = np.arange(len(cv_data['wav']))\n # np.random.shuffle(full_idx_array)\n for next_idx in range(0, int(np.floor(len(cv_data['wav']) / batch_size))):\n batch_idx_array = full_idx_array[next_idx * batch_size: (next_idx + 1) * batch_size]\n batch_x, batch_x_face_id, batch_x_pose, batch_y_landmark, batch_y_phoneme, batch_y_lipS, batch_y_maya_param = \\\n read_next_batch_easy_from_raw(test_wav_raw, cv_data, 'face_close', batch_idx_array, batch_size, n_steps, n_input, n_landmark,\n n_phoneme, n_face_id)\n npClose = np.loadtxt(lpw_dir + 'saved_param/maya_close_face.txt')\n batch_x_face_id = np.tile(npClose, (batch_x_face_id.shape[0], 1))\n\n # Forward session\n pred_v_cls, pred_v_reg, pred_jali = sess.run(\n [v_cls, v_reg, jali],\n feed_dict={x: batch_x, x_face_id: batch_x_face_id,\n dropout: 0, phase: 0 })\n\n def save_output(filename, npTxt, fmt):\n f = open(filename, 'wb')\n np.savetxt(f, npTxt, fmt=fmt)\n f.close()\n\n try_mkdir(pred_dir + test_audio_name)\n\n def sigmoid(x):\n return 1/(1+np.exp(-x))\n save_output(pred_dir + test_audio_name + \"/mayaparam_pred_cls.txt\",\n np.concatenate([pred_jali, sigmoid(pred_v_cls)], axis=1), '%.4f')\n save_output(pred_dir + test_audio_name + \"/mayaparam_pred_reg.txt\",\n np.concatenate([pred_jali, pred_v_reg], axis=1), '%.4f')\n\n\nif __name__ == '__main__':\n # Audio filename to process.\n test_audio_name = 'visemenet_intro.wav'\n\n # convert audio wav to network input format\n create_dataset_csv(csv_dir, test_audio_name=test_audio_name)\n\n # feedforward testing\n # Edit path to `visemenet_frozen.pb` as you wish\n graph = load_graph('visemenet_frozen.pb')\n test_frozen(graph=graph, test_audio_name=test_audio_name[:-4])\n print('Finish forward testing.')\n\n # output viseme parameter\n eval_viseme(test_audio_name[:-4])\n print('Done.')\n","sub_path":"v2_use_frozen.py","file_name":"v2_use_frozen.py","file_ext":"py","file_size_in_byte":5058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"235672719","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport random\nimport string\n\nclass Image(object):\n\n def __init__(self, name=None, content=None):\n self.name = name.split('?')[0]\n self.content = content\n\n if not '.jpg' in name and not '.jpeg' in name and not '.png' in name and not '.gif' in name:\n self.name = self.name + '.jpg'\n\n items = self.name.split('.')\n self.extension = items[-1]\n self.name = self._get_random_id(10) + '.' + self.extension\n\n def _get_random_id(self, length):\n return ''.join(random.choice(string.lowercase) for i in range(length))\n","sub_path":"attachment.py","file_name":"attachment.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"363272855","text":"import argparse\nimport time\nimport subprocess\nfrom os.path import isfile\nimport pysais\nimport ctypes, sys\n# import sys\nfrom Bio import SeqIO\n\n\ndef read_sequence(file_path):\n with open(file_path) as file:\n for record in SeqIO.parse(file, \"fasta\"):\n return str(record.seq)\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Run SAIS algorithm on the given genome file\")\n parser.add_argument(\"-g\", \"--genome\", dest=\"file\", required=True, help=\"Genome file\")\n parser.add_argument(\"-sa\", \"--suffix_array\", dest=\"sa_file\", required=True, help=\"Output file for the suffix array\")\n parser.add_argument(\"-bwt\", \"--bwt\", dest=\"bwt_file\", required=True, help=\"Output file for the BWT\")\n\n args = parser.parse_args()\n # sys.argv[0]\n\n if not isfile(args.file):\n print(args.file, \" is not a file\")\n parser.print_usage()\n return\n\n text = read_sequence(args.file)\n print(\"Start printing sequence in file for the SAIS\")\n start = time.time()\n sa_file = open(\"seq.txt\", \"w\")\n sa_file.write(text + '$')\n sa_file.close()\n end = time.time()\n print(\"Done writing sequence in\", end - start, \"seconds\")\n\n print(\"Start SAIS\")\n subprocess.check_output([\"./main\", \"seq.txt\", args.sa_file, args.bwt_file])\n print(\"SAIS done\")\n\ndef is_admin():\n try:\n return ctypes.windll.shell32.IsUserAnAdmin()\n except:\n return False\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/sais.py","file_name":"sais.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"642354007","text":"from sampling.inference.rain_bayesian_network import *\n\nimport arviz as az\nfrom collections import defaultdict\nfrom itertools import accumulate\nimport matplotlib as mpl\n\n\ndef freq_plot(variables_dict, sampling_history):\n \"\"\"Plot changes of given variable values during one sampling run.\n\n Parameters\n ----------\n variables_dict : dict\n Keys are variable names, values - their values of interest, for example True or 'T'.\n sampling_history : list of dict\n Sampling history returned when sampling using GibbsSampler class.\n \"\"\"\n mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=['deepskyblue', 'rebeccapurple', 'gold', 'magenta'])\n ax = plt.subplot()\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n\n for variable, value in variables_dict.items():\n freqs = [int(state[variable] == value) for state in sampling_history]\n # we accumulate computed values, so we can plot evolution of their frequency\n freqs = list(accumulate(freqs))\n\n for i in range(len(freqs)):\n # compute mean frequency\n freqs[i] /= (i + 1)\n\n ax.plot(freqs, label=f'{variable}={value}')\n\n plt.legend(fontsize='medium')\n plt.title('Change in variable frequencies during sampling')\n plt.show()\n\n\ndef reorder_data(sampling_runs, variables):\n \"\"\"Prepare data for computing Gelman-Rubin shrink factor.\n Parameters\n ----------\n sampling_runs : list\n List of sampling history returned by GibbsSampler.\n variables : list of str\n Names of variables, same as ones defined before running the sampler.\n \"\"\"\n data = defaultdict(list)\n for sampling_run in sampling_runs:\n for variable in variables:\n # we need numeric data to compute shrink factor\n sampled_values = [1 if sampling_run[i][variable] == 'T' else 0 for i in range(len(sampling_run))]\n data[variable].append(sampled_values)\n\n return data\n\n\ndef gelman_plot_data(sampling_runs, variables, bin_width):\n \"\"\"Prepare sampled data for plotting evolution of Gelman-Rubin shrink factor.\n\n Parameters\n ----------\n sampling_runs : dict of list\n Sampled data prepared by function reorder_data.\n variables : list of str\n Names of variables of interest.\n bin_width : int\n Number of observations per segment.\n \"\"\"\n shrink_factors = defaultdict(list)\n medians = defaultdict(list)\n\n for variable in variables:\n sampled_runs = sampling_runs[variable]\n length = len(sampled_runs[0])\n for end in range(bin_width, length + 1, bin_width):\n sampled_data = [run[:end] for run in sampled_runs]\n # we create special arviz object to compute shrink factor using rhat function\n sampled_data = az.convert_to_dataset({variable: sampled_data})\n shrink_factors[variable].append(float(az.rhat(sampled_data)[variable]))\n medians[variable].append(np.median(shrink_factors[variable]))\n\n return shrink_factors, medians\n\n\ndef gelman_plot(shrink_factors, medians, variable, bin_width, zoom=None):\n \"\"\"Plot exact and median values of Gelman-Rubin shrink factor during sampling.\n Parameters\n ----------\n shrink_factors : dict of list\n Keys are variable names, values - list of computed shrink factor values.\n medians : dict of list\n Keys are variable names, values - list of computed shrink factor medians.\n variable : str\n bin_width : int\n Number of observations per segment.\n zoom : int\n Number of shrink factors to consider. If your sampling run took quite long, you may want to zoom results to\n take a closer look at the beginning of the simulation. If None, all shrink factors will be shown.\n \"\"\"\n if zoom is None:\n zoom = len(medians[variable])\n\n ax = plt.subplot()\n xs = [i * bin_width for i in range(1, len(medians[variable][:zoom]) + 1)]\n ax.plot(xs, medians[variable][:zoom], label='median', c='rebeccapurple')\n ax.plot(xs, shrink_factors[variable][:zoom], '--', label='exact', c='deepskyblue', alpha=0.7)\n\n plt.title(f'Change of Gelman-Rubin shrink factor for variable {variable}')\n plt.xlabel('sample')\n plt.ylabel('shrink factor')\n plt.legend()\n plt.show()\n","sub_path":"diagnostics/convergence.py","file_name":"convergence.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618793524","text":"# -*- coding: utf-8 -*-\n# from plone.dexterity.interfaces import IDexterityFTI\n# from Products.EasyNewsletter.config import IS_PLONE_5\n# from zope.component import getUtility\nfrom Acquisition import aq_base\nfrom plone import api\nfrom plone.app.testing import setRoles\nfrom plone.app.testing import TEST_USER_ID\nfrom plone.uuid.interfaces import IUUID\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFPlone.tests.utils import MockMailHost\nfrom Products.EasyNewsletter.interfaces import IENLIssue\nfrom Products.EasyNewsletter.testing import EASYNEWSLETTER_FUNCTIONAL_TESTING\nfrom Products.EasyNewsletter.utils.mail import get_portal_mail_settings\nfrom Products.MailHost.interfaces import IMailHost\nfrom zExceptions import BadRequest\nfrom zope.component import getMultiAdapter\nfrom zope.component import getSiteManager\n\nimport unittest\n\n\nclass DailyIssueBaseTestCase(unittest.TestCase):\n \"\"\"Test case sending a daily Newsletter issue\"\"\"\n\n layer = EASYNEWSLETTER_FUNCTIONAL_TESTING\n\n def setUp(self):\n self.portal = self.layer[\"portal\"]\n self.catalog = getToolByName(self.portal, \"portal_catalog\")\n setRoles(self.portal, TEST_USER_ID, [\"Manager\"])\n\n # creating test objects: folder, news, newsletter and subscriber\n self.portal.invokeFactory(\"Folder\", \"testfolder\")\n self.folder = self.portal[\"testfolder\"]\n self.folder.invokeFactory(\"News Item\", \"news01\")\n\n self.folder.invokeFactory(\"EasyNewsletter\", \"daily-news\")\n self.newsletter = self.folder[\"daily-news\"]\n self.newsletter.setTitle(\"Daily News\")\n\n # if IS_PLONE_5:\n # # make sure that Collections have the referenceable behavior:\n # fti = getUtility(IDexterityFTI, name='Collection')\n # referenceable = u'plone.app.referenceablebehavior.referenceable.IReferenceable' # noqa\n # behaviors = list(fti.behaviors)\n # if referenceable not in behaviors:\n # behaviors.append(referenceable)\n # fti.behaviors = tuple(behaviors)\n\n news_collection = api.content.create(\n type=\"Collection\",\n id='news-collection',\n title=u'News Collection',\n container=self.folder)\n query = [{\n 'i': 'portal_type',\n 'o': 'plone.app.querystring.operation.selection.is',\n 'v': ['News Item'],\n }]\n news_collection.setQuery(query)\n self.newsletter.setContentAggregationSources(IUUID(news_collection))\n\n self.newsletter.invokeFactory(\"ENLSubscriber\", \"subscriber01\")\n self.view = getMultiAdapter(\n (self.newsletter, self.layer[\"request\"]),\n name=\"daily-issue\"\n )\n\n self.mail_settings = get_portal_mail_settings()\n self.mail_settings.email_from_address = \"noreply@plone.org\"\n # setting a Mock mailhost\n self.portal._original_MailHost = self.portal.MailHost\n self.portal.MailHost = mailhost = MockMailHost(\"MailHost\")\n sm = getSiteManager(context=self.portal)\n sm.unregisterUtility(provided=IMailHost)\n sm.registerUtility(mailhost, provided=IMailHost)\n\n def tearDown(self):\n self.portal.MailHost = self.portal._original_MailHost\n sm = getSiteManager(context=self.portal)\n sm.unregisterUtility(provided=IMailHost)\n sm.registerUtility(\n aq_base(self.portal._original_MailHost),\n provided=IMailHost\n )\n\n\nclass DailyIssueContent(DailyIssueBaseTestCase):\n def test_create_new_issue(self):\n issues = self.catalog(\n object_provides=IENLIssue.__identifier__,\n path=\"/\".join(self.newsletter.getPhysicalPath())\n )\n self.assertEqual(len(issues), 0)\n self.assertFalse(self.view.already_sent())\n self.view.create_issue()\n # try:\n # self.view.create_issue()\n # except Exception, e:\n # import pdb; pdb.set_trace()\n # self.fail(\"Couldn't create an issue! (%s)\" % e)\n\n issues = self.catalog(\n object_provides=IENLIssue.__identifier__,\n path=\"/\".join(self.newsletter.getPhysicalPath())\n )\n\n self.assertTrue(self.view.already_sent())\n self.assertEqual(len(issues), 1)\n self.assertEqual(self.view.issue.Title(), \"Daily News\")\n\n def test_empty_issue(self):\n self.assertTrue(self.view.has_content())\n self.folder.manage_delObjects([\"news01\"])\n self.assertFalse(self.view.has_content())\n\n def test_send_issue(self):\n try:\n self.view.create_issue()\n except Exception:\n self.fail(\"Couldn't create issue!\")\n\n self.view.send()\n self.assertEqual(len(self.portal.MailHost.messages), 1)\n\n\nclass DailyIssueMethodGET(DailyIssueBaseTestCase):\n\n def setUp(self):\n self.layer[\"request\"][\"REQUEST_METHOD\"] = \"GET\"\n DailyIssueBaseTestCase.setUp(self)\n\n def test_get_with_an_empty_issue(self):\n self.folder.manage_delObjects([\"news01\"])\n self.view()\n self.assertEqual(self.view.request.response.getStatus(), 204)\n\n def test_get_with_a_non_empty_issue(self):\n self.view()\n self.assertEqual(self.view.request.response.getStatus(), 100)\n\n def test_get_an_alredy_sent_issue(self):\n self.view.create_issue()\n self.view()\n self.assertEqual(self.view.request.response.getStatus(), 200)\n\n\nclass DailyIssueMethodPOST(DailyIssueBaseTestCase):\n\n def setUp(self):\n self.layer[\"request\"][\"REQUEST_METHOD\"] = \"POST\"\n DailyIssueBaseTestCase.setUp(self)\n\n def test_do_not_create_or_send_an_empty_issue(self):\n self.folder.manage_delObjects([\"news01\"])\n self.view()\n issues = self.catalog(\n object_provides=IENLIssue.__identifier__,\n path=\"/\".join(self.newsletter.getPhysicalPath())\n )\n self.assertFalse(issues)\n self.assertEqual(self.view.request.response.getStatus(), 204)\n self.assertEqual(len(self.portal.MailHost.messages), 0)\n\n def test_send_issue_and_check_http_status(self):\n self.view()\n self.assertEqual(self.view.request.response.getStatus(), 200)\n self.assertEqual(len(self.portal.MailHost.messages), 1)\n\n def test_do_not_send_same_issue_twice(self):\n self.view() # 200 OK\n self.assertEqual(self.view.request.response.getStatus(), 200)\n self.assertRaises(BadRequest, self.view.create_issue)\n self.view() # 409 Already Sent\n self.assertEqual(self.view.request.response.getStatus(), 409)\n\n\nclass DailyIssueMethodOtherThanGETorPOST(DailyIssueBaseTestCase):\n\n def setUp(self):\n self.layer[\"request\"][\"REQUEST_METHOD\"] = \"FOOBAR\"\n DailyIssueBaseTestCase.setUp(self)\n\n def test_trying_another_method_on_view(self):\n self.view()\n self.assertEqual(self.view.request.response.getStatus(), 405)\n self.assertEqual(\n self.view.request.response.getHeader(\"Allow\"),\n \"GET, POST\"\n )\n\n\ndef test_suite():\n return unittest.defaultTestLoader.loadTestsFromName(__name__)\n","sub_path":"Products/EasyNewsletter/tests/test_daily_issue.py","file_name":"test_daily_issue.py","file_ext":"py","file_size_in_byte":7134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"434272007","text":"import pickle\n\nimport matplotlib.pyplot as plt\n\nfrom archived import data_helper\n\n# maximum length of a sentence\nmax_sent_len = 20\n# maximum number of words to consider in the representations\nmax_features = 3000\n\nseg_list, seg_list_inline, sentiment_list, label_list = data_helper.load_data(file='mydata/data_ext_mod',\n read_dump=False,\n dump_name='mydata/seg_list.pkl')\n\ndef fold(eval_error=False):\n with open('result/eval_error', 'w', encoding='utf-8') as f:\n f.write('reviews\\treal_label\\tpredict_label\\n')\n for i in range(1, 11, 1):\n print('Position: %d' % i)\n SVM = SVM.SVM(seg_list=seg_list,\n label_list=label_list,\n max_features=max_features,\n test_position=i)\n\n SVM.train()\n SVM.eval(eval_error=eval_error)\n\nfold(eval_error=False)\n\n# reviews = open('mydata/test', 'r', encoding='utf-8').read().split('\\n')\n#\n# SVM = Linear_SVM.SVM(seg_list=seg_list,\n# label_list=label_list,\n# max_features=max_features,\n# max_sent_len=max_sent_len,\n# test_position=1)\n#\n# SVM.train()\n# SVM.eval()\n# SVM.predict(reviews)\n\ndef save():\n SVM = SVM.SVM(seg_list=seg_list,\n label_list=label_list,\n max_features=max_features,\n test_position=7)\n\n SVM.train()\n # SVM.eval(eval_error=False)\n with open('SVM.model', 'wb') as f:\n pickle.dump(SVM, f)\n\n\n\ndef best_max_features():\n x = range(100, 120, 10)\n y = []\n for i in x:\n print('Max Features: %d' % i)\n SVM = SVM.SVM(seg_list=seg_list,\n label_list=label_list,\n max_features=i,\n test_position=7)\n\n SVM.train()\n # SVM.eval(eval_error=False)\n y.append(SVM.accu())\n\n plt.plot(x, y)\n plt.xlabel(\"Max Features\")\n plt.ylabel(\"Accuracy\")\n plt.show()\n\n# best_max_features()\n","sub_path":"archived/old_run_SVM.py","file_name":"old_run_SVM.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125161960","text":"\nimport torch\n# import matplotlib.pyplot as plt\nimport numpy as np\nfrom util import get_args, compute_acc, update_args_opp, update_args_samplewise, compute_acc_elementwise\nfrom model_lstm_reuse_c import LSTMSampleWise\nfrom model_lstm_reuse_c_2 import LSTMSampleWiseC\nfrom model_attention_element import AttentionSampleWise\nfrom model_att_tunning import AttentionSampleWiseT\nfrom model_convlstm_attention import AttentionConvLstm\nfrom sklearn.metrics import f1_score, classification_report, confusion_matrix\nfrom prepare_data import getdata\nfrom prepare_data_opp import get_data\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nargs = get_args('LSTM')\n\n# ConvLSTM\n\n\nOverlap = 'Normal'\n\nminibatches, minibatches_v, minibatches_t = get_data(args)\n\n# model = LSTMSampleWiseC(args)\n\nmodel = AttentionSampleWiseT(args).to(device=args.device)\n\nmodel.load_state_dict(torch.load('/Users/boyang/Desktop/attenion_opp_Result/acc0.9156250357627869f10.6279927170401911f1test0.73507687631581', map_location=lambda storage, loc: storage))\n\n\n\n\ndef running_model(minibatches,\n model=model):\n\n\n y_pred_total = []\n y_total = []\n\n model.clear_hidden()\n\n model.eval()\n\n for minibatch in minibatches:\n (minibatch_X, minibatch_Y) = minibatch\n\n minibatch_X = Variable(minibatch_X.cuda())\n minibatch_Y = Variable(minibatch_Y.cuda())\n\n # shape: n * win_len * num_classes\n y_pred = model(minibatch_X)\n\n\n # reshape to n, num_classes to compute loss\n # y_pred = y_pred.view(-1, args.num_classes)\n # minibatch_Y = minibatch_Y.view(-1)\n\n # add to compute total acc\n y_pred_total.append(y_pred)\n y_total.append(minibatch_Y)\n\n # acc = compute_acc(y_pred, minibatch_Y)\n\n\n\n # concat the list of y to compute acc\n y_pred_total = torch.cat(y_pred_total, 0)\n y_total = torch.cat(y_total, 0)\n\n acc_total = []\n f1_total = []\n\n for t in range(24):\n y_pred = y_pred_total[:, t, :]\n y_gt = y_total[:, t]\n\n acc = compute_acc(y_pred, y_gt)\n f1 = f1_score(y_gt, y_pred.max(dim=1)[1], average='macro')\n\n\n acc_total.append(acc)\n f1_total.append(f1)\n\n\n\n return acc_total, f1_total\n\n\nwith torch.no_grad():\n acc_total, f1_total = running_model(minibatches_t)\n\n\n\n# plt.plot(acc_total,'g--')\nplt.plot(f1_total,'r--')\n\nplt.show()","sub_path":"har_pytorch/test_samplewise.py","file_name":"test_samplewise.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"491116373","text":"#-*- encoding: utf-8 -*-\n\n\n\nimport os\nfrom eve import Eve\nfrom flask import abort\n\nif 'PORT' in os.environ:\n port = int(os.environ.get('PORT'))\n # use '0.0.0.0' to ensure your REST API is reachable from all your\n # network (and not only your computer).\n host = '0.0.0.0'\nelse:\n port = 5000\n host = '127.0.0.1'\n\n\n\ndef pre_get_callback(resource, request, lookup):\n print('A GET request on the \"%s\" endpoint has just been received!' % resource)\n ##访问api之前的一个回调函数\n\ndef pre_contacts_get_callback(request, lookup):\n print('A GET request on the contacts endpoint has just been received!')\n\n\"\"\"def pre_GET(resource, request, lookup):\n # only return documents that have a 'username' field.\n lookup[\"title\"] = {'$exists': True}\n ##查询数据库结果显示之前的过滤结果\"\"\"\ndef post_get_callback(resource, request, payload):\n print('A GET on the \"%s\" endpoint was just performed!' % resource)\n\ndef post_contacts_get_callback(request, payload):\n print('A get on \"contacts\" was just performed!')\n\ndef add_signature(resource, response):\n response['SIGNATURE'] = \"A %s from eve\" % resource\n print( ' \"%s\" ' % response)\n\ndef check_update_access(resource, updates, original):\n abort(403)\n\napp = Eve()\n\napp.on_pre_GET += pre_get_callback\napp.on_pre_GET_contacts += pre_contacts_get_callback\n##app.on_pre_GET += pre_GET\napp.on_post_GET += post_get_callback\napp.on_post_GET_contacts += post_contacts_get_callback\napp.on_fetched_item += add_signature\napp.on_insert_item += check_update_access\n\nif __name__ == '__main__':\n app.run(debug=True,host=host, port=port)\n\n\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"508438790","text":"# script to plot the dv_dt values for cases in given file (with class separation)\n# marks at placed at the intervals used for input and target for the machine learning algorithm\n\nimport matplotlib.pyplot as plt\nimport pickle\nimport numpy as np\n\ndef load_obj(name ):\n with open('obj/' + name + '.pkl', 'rb') as f:\n return pickle.load(f)\n\n\n\n\n# Inputs needed\nfault_clearance_time = 0.31\ninputFeatureNo = 60\nsteadyStateSamples = 100\n#inputFile = 'CaseV.txt' # classification of V\n#inputFile = 'Casedvdt.txt' # classification of dv dt\ninputFile = 'CasedvdtTmp.txt'\n\n# make directories\nimport os\ncurrentdir = os.getcwd()\n\n\n# create directories for the false positives and false negatives\nerrorPlotDir = currentdir + '/Visualizations'\n# for V\n#class0Dir = errorPlotDir + '/class0PlotsV'\n#class1Dir = errorPlotDir + '/class1PlotsV'\n# for dv_dt visualization\n#class0Dir = errorPlotDir + '/class0Plotsdvdt'\n#class1Dir = errorPlotDir + '/class1Plotsdvdt'\n\n# just a temp dv_dt threshold test\nclass0Dir = errorPlotDir + '/class0PlotsdvdtTmpdvdt'\nclass1Dir = errorPlotDir + '/class1PlotsdvdtTmpdvdt'\n##############\n\n# create directories if they dont exist\nif not os.path.isdir(errorPlotDir):\n os.mkdir(errorPlotDir)\nif not os.path.isdir(class0Dir):\n os.mkdir(class0Dir)\n\nif not os.path.isdir(class1Dir):\n os.mkdir(class1Dir)\n\n\n\n# read the file\nwith open(inputFile,'r') as f:\n fileLines = f.read().split('\\n')\n\nfpStartIndex = fileLines.index('Class 0:') + 1\nfpEndIndex = fileLines.index('Class 1:')\nfnStartIndex = fpEndIndex + 1\n\n# get the false positive cases\nclass0Lines = []\nclass1Lines = []\nfor i in range(fpStartIndex,fpEndIndex):\n line = fileLines[i]\n class0Lines.append(line)\n\n# get the false positive cases\nfor i in range(fnStartIndex,len(fileLines)):\n line = fileLines[i]\n if line == '':\n continue\n class1Lines.append(line)\n\n\n\n\n\nVoltageDataDict = load_obj('VoltageData') # this voltage data dictionary has been generated from the script 'TS3phSimN_2FaultDataSave.py', see it for key format\n\n# save all the class 1 data\nk=1\nfor key in class1Lines:\n #key = '154,3008,1;151,201,1;F151/151'\n words = key.split('/')\n event = words[0].strip()\n Bus = words[1].strip()\n voltage = VoltageDataDict[key] \n tme = VoltageDataDict['time']\n timestep = tme[1] - tme[0]\n VmagSize = voltage.shape[0]\n dv_dt = np.zeros(VmagSize) # initialize dv_dt array with all zeros\n for i in range(VmagSize):\n try:\n dv_dt[i] = abs((voltage[i] - voltage[i-1]))/timestep\n except: # will happen if i = 0, since there is no i-1\n continue\n\n\n\n\n ind_input_start = int(fault_clearance_time/timestep) + 1 # time index when fault is cleared\n ind_input_end = ind_input_start + inputFeatureNo # end time index for ML input\n\n ind_target_start = len(tme) - steadyStateSamples\n\n # get the special co-ordinates to mark\n spclTimePts = []\n spcldvdtplots = []\n\n spclTimePts.append(tme[ind_input_start])\n spcldvdtplots.append(dv_dt[ind_input_start])\n\n spclTimePts.append(tme[ind_input_end])\n spcldvdtplots.append(dv_dt[ind_input_end])\n\n spclTimePts.append(tme[ind_target_start])\n spcldvdtplots.append(dv_dt[ind_target_start])\n\n #timeStep = range(len(voltageValues))\n plt.plot(tme, dv_dt)\n plt.plot(spclTimePts,spcldvdtplots, ls=\"\", marker=\"o\", label=\"special points\")\n titleStr = 'Event: ' + event + 'Bus ' + Bus\n plt.title(titleStr)\n plt.ylabel('dv_dt (pu)')\n plt.xlabel('Time (s)')\n plt.ticklabel_format(useOffset=False)\n #plt.xlabel('Time step after line clearance')\n plt.ylim(0.0,0.1)\n plt.grid()\n plt.legend()\n #plt.show()\n figName = class1Dir + '/' + 'Plot' + str(k) + '.png'\n plt.savefig(figName)\n plt.close()\n k+=1\n\n\n\n\n\n\"\"\"\n\n# generate random 100 samples from the class 0 data (since there are too many to plot)\nk=1\nimport random\nrandomInd = [] # random sample index for the class 0 data\nfor i in range(100):\n out = random.choice(range(len(class0Lines)))\n randomInd.append(out)\n# save all the class 0 data\nfor j in range(len(randomInd)):\n key = class0Lines[randomInd[j]]\n #key = '154,3008,1;151,201,1;F151/151'\n words = key.split('/')\n event = words[0].strip()\n Bus = words[1].strip()\n voltage = VoltageDataDict[key] \n tme = VoltageDataDict['time']\n timestep = tme[1] - tme[0]\n ind_input_start = int(fault_clearance_time/timestep) + 1 # time index when fault is cleared\n ind_input_end = ind_input_start + inputFeatureNo # end time index for ML input\n\n ind_target_start = len(tme) - steadyStateSamples\n\n # get the special co-ordinates to mark\n spclTimePts = []\n spclVoltPts = []\n\n spclTimePts.append(tme[ind_input_start])\n spclVoltPts.append(voltage[ind_input_start])\n\n spclTimePts.append(tme[ind_input_end])\n spclVoltPts.append(voltage[ind_input_end])\n\n spclTimePts.append(tme[ind_target_start])\n spclVoltPts.append(voltage[ind_target_start])\n\n #timeStep = range(len(voltageValues))\n plt.plot(tme, voltage)\n plt.plot(spclTimePts,spclVoltPts, ls=\"\", marker=\"o\", label=\"special points\")\n titleStr = 'Event: ' + event + 'Bus ' + Bus\n plt.title(titleStr)\n plt.ylabel('Voltage (pu)')\n plt.xlabel('Time (s)')\n plt.ticklabel_format(useOffset=False)\n #plt.xlabel('Time step after line clearance')\n #plt.ylim(0.75,1.5)\n plt.grid()\n plt.legend()\n #plt.show()\n figName = class0Dir + '/' + 'Plot' + str(k) + '.png'\n plt.savefig(figName)\n plt.close()\n k+=1\n\"\"\"\n","sub_path":"visualize_dv_dt.py","file_name":"visualize_dv_dt.py","file_ext":"py","file_size_in_byte":5515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"471489146","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data! How exhiting!')\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n city=input('Please select a city - data availiable for: Chicago, New York City or Washington:\\n').lower()\n while city not in ['chicago','new york city','washington']:\n print('Typo? - Please try again!')\n city=input('Please select a city: Chicago, New York City or Washington:\\n').lower()\n\n # get user input for month (all, january, february, ... , june)\n month=input('Is there a month you are interested in? Type in a month between January and June - or all (for all months):\\n').lower()\n while month not in ['all','january','february','march','april','may','june']:\n print('Sorry - there is only data for January to June. Please try again.')\n month=input('Type in a month between January and June - or all (for all months):\\n').lower()\n\n # get user input for day of week (all, monday, tuesday, ... sunday)\n day=input('Great - any day you\\'d like to see? - Please select one or type in all (for all days):\\n').lower()\n while day not in ['all', 'monday','tuesday','wednesday','thursday','friday','saturday','sunday']:\n print('Ups - please try again!')\n day=input('Please select a day (Monday to Sunday) or type in all (for all days):\\n').lower()\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n df = pd.read_csv(CITY_DATA[city])\n\n df['Start Time']=pd.to_datetime(df['Start Time'])\n df['s_month']=df['Start Time'].dt.month_name()\n df['s_day']=df['Start Time'].dt.day_name()\n\n if month !='all':\n df= df[df['s_month'] == month.title()]\n if day != 'all':\n df= df[df['s_day'] == day.title()]\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n mostcom_month=df['s_month'].mode()[0]\n print('Most common month:',mostcom_month)\n\n # display the most common day of week\n mostcom_day=df['s_day'].mode()[0]\n print('Most common weekday:',mostcom_day)\n\n # display the most common start hour\n df['s_hour']=df['Start Time'].dt.hour\n mostcom_hour=df['s_hour'].mode()[0]\n print('Most common starting hour for a trip:',mostcom_hour)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n most_common_start=df['Start Station'].mode()[0]\n print('Most popular station for starting a trip:',most_common_start)\n\n # display most commonly used end station\n most_common_end=df['End Station'].mode()[0]\n print('Most popular station for ending a trip:',most_common_end)\n\n # display most frequent combination of start station and end station trip\n df['trip']= df['Start Station'] + \" - \" + df['End Station']\n most_common_trip=df['trip'].mode()[0]\n print('Most popular trip:',most_common_trip)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n tot_travel=round(((df['Trip Duration'].sum()/60)/60),2)\n print('Total travel time (h):',tot_travel)\n\n # display mean travel time\n mean_travel=round((df['Trip Duration'].mean()/60),2)\n print('Average travel time (min):',mean_travel)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n user_typ=df['User Type'].value_counts()\n print(\"\\nNumer of different user types:\\n\", user_typ)\n\n # Display counts of gender\n user_gen=df['Gender'].value_counts()\n print(\"\\nNumer of female and male users:\\n\", user_gen)\n\n # Display earliest, most recent, and most common year of birth\n user_min_by=round(df['Birth Year'].min())\n user_max_by=round(df['Birth Year'].max())\n user_mode_by=df['Birth Year'].mode()[0]\n print(\"\\nYoungest User, born in:\", user_max_by)\n print(\"\\nOldest User, born in:\", user_min_by)\n print(\"\\nMost common year of birth:\", user_mode_by)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef show_raw_data(df):\n \"\"\"Not included in template - but mentioned in rubric:\n displays some raw data for city, month, day - always in blocks of 5 rows.\"\"\"\n start_time = time.time()\n\n while True:\n show=input('\\nWould you like to see some (more) raw data (Yes or No)?').lower()\n if show=='yes':\n for i in range(0,len(df),5):\n if show=='yes':\n print(df[i:i+5])\n show=input('\\nWould you like to see some (more) raw data (Yes or No)?').lower()\n if show=='no':\n print('\\nOk - no more raw data.')\n break\n else:\n print('\\nTypo - try again.')\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n\n if city in['chicago','new york city']:\n user_stats(df)\n else:\n print('\\nSorry - no user data for Washington.')\n\n show_raw_data(df)\n\n restart = input('\\nWould you like to restart? Enter Yes or No.\\n')\n if restart.lower() != 'yes':\n break\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":7034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618349438","text":"from pyquaternion import Quaternion\n\nimport numpy as np\nimport pybullet as pb\n\n\nclass Script(object):\n def __init__(self, scene):\n self._dt = scene.dt\n self._max_tool_velocity = scene.max_tool_velocity\n self._max_gripper_velocity = scene.max_gripper_velocity\n\n # report used scripts to the scene\n self.scene = scene\n\n def joint_move(self, arm, pos=None, orn=None, t_acc=1.0, script_id=None):\n \"\"\" Move in joint space with trap velocity profile \"\"\"\n pos0, orn0 = arm.controller.tool_target\n if pos is None:\n pos = pos0\n if orn is None:\n orn = orn0\n elif len(orn) == 3:\n orn = pb.getQuaternionFromEuler(orn)\n\n q0 = np.array(arm.controller.joints_target)\n q = arm.kinematics.inverse(pos, orn, q0)\n assert q is not None, 'Cannot find IK solution for target configuration'\n dq_max = np.array(arm.max_joint_velocity) * 0.15\n velocities = trap_velocity_profile(\n [q - q0], [dq_max], self._dt, t_acc)\n for dq, in velocities:\n self._report_script_to_scene(script_id)\n q = np.array(arm.controller.joints_target)\n v, w = arm.kinematics.forward_vel(q, dq, self._dt)\n yield dict(\n linear_velocity=v,\n angular_velocity=w,\n joint_velocity=dq)\n\n def joint_step(self, arm, pos=None, orn=None, t_acc=1.0, tool_cs=True, script_id=None):\n pos0, orn0 = arm.controller.tool_target\n if pos is not None:\n if tool_cs:\n pos = np.add(pos0, to_quat(orn0).rotate(pos))\n else:\n pos = np.add(pos0, pos)\n if orn is not None:\n if len(orn) == 3:\n orn = pb.getQuaternionFromEuler(orn)\n q0, q = to_quat(orn0), to_quat(orn)\n if tool_cs:\n orn = to_orn(q0 * q)\n else:\n orn = to_orn(q * q0)\n for a in self.joint_move(arm, pos, orn, t_acc):\n self._report_script_to_scene(script_id)\n yield a\n\n def tool_move(self, arm, pos=None, orn=None, t_acc=1.0, script_id=None):\n \"\"\" Linear move with trap velocity profile \"\"\"\n max_v, max_w = self._max_tool_velocity\n pos0, orn0 = arm.controller.tool_target\n dist, axis, angle = np.zeros(3), np.zeros(3), 0.0\n if pos is not None:\n dist = np.subtract(pos, pos0)\n if orn is not None:\n if len(orn) == 3:\n orn = pb.getQuaternionFromEuler(orn)\n diff = to_quat(orn) * to_quat(orn0).inverse\n axis, angle = diff.get_axis(undefined=np.array([0, 0, 0])), diff.angle\n\n velocities = trap_velocity_profile(\n [dist, angle * axis], [max_v, max_w], self._dt, t_acc)\n\n for v, w in velocities:\n self._report_script_to_scene(script_id)\n q = np.array(arm.controller.joints_target)\n dq = arm.kinematics.inverse_vel(q, v, w, self._dt)\n yield dict(\n linear_velocity=v,\n angular_velocity=w,\n joint_velocity=dq)\n\n def tool_step(self, arm, pos=None, orn=None, t_acc=1.0, tool_cs=True, script_id=None):\n pos0, orn0 = arm.controller.tool_target\n if pos is not None:\n if tool_cs:\n pos = np.add(pos0, to_quat(orn0).rotate(pos))\n else:\n pos = np.add(pos0, pos)\n if orn is not None:\n q0, q = to_quat(orn0), to_quat(orn)\n if tool_cs:\n orn = to_orn(q0 * q)\n else:\n orn = to_orn(q * q0)\n for a in self.tool_move(arm, pos, orn, t_acc):\n self._report_script_to_scene(script_id)\n yield a\n\n def grip_close(self, gripper, script_id=None):\n self._report_script_to_scene(script_id)\n yield dict(grip_velocity=-self._max_gripper_velocity)\n for _ in np.arange(0, 2, self._dt):\n if gripper.controller.grasped():\n break\n self._report_script_to_scene(script_id)\n yield dict(grip_velocity=-self._max_gripper_velocity)\n self._report_script_to_scene(script_id)\n yield dict(grip_velocity=0)\n\n def grip_open(self, gripper, script_id=None):\n for _ in np.arange(0, 5, self._dt):\n if gripper.controller.opened():\n break\n self._report_script_to_scene(script_id)\n yield dict(grip_velocity=self._max_gripper_velocity)\n\n def idle(self, num_steps, script_id=None):\n for _ in range(num_steps):\n self._report_script_to_scene(script_id)\n yield dict(linear_velocity=[0, 0, 0], angular_velocity=[0, 0, 0])\n\n def color_change(self, cup, color):\n cup.color = color\n\n def _report_script_to_scene(self, script_id):\n if script_id is not None:\n self.scene.scripts_used.append(script_id)\n\n\ndef trap_velocity_profile(distances, max_velocities, dt, t_acc=1.0):\n t_max = [np.linalg.norm(d / v)\n for d, v in zip(distances, max_velocities)]\n\n t_dec = np.max(t_max)\n t_acc = np.min([t_acc, t_dec])\n t_end = t_dec + t_acc\n\n v_coeff = [d / t_dec for d in distances]\n\n vels = []\n for t in np.arange(0.0, t_end, dt) + dt:\n k = 1.0\n if t > t_end:\n k = 0.0\n elif t <= t_acc:\n k = t / t_acc\n elif t >= t_dec:\n k = 1 - (t - t_dec) / t_acc\n vels.append([k * v for v in v_coeff])\n return vels\n\n\ndef to_quat(orn):\n if len(orn) == 3:\n orn = pb.getQuaternionFromEuler(orn)\n return Quaternion(w=orn[3], x=orn[0], y=orn[1], z=orn[2])\n\n\ndef to_orn(q):\n return [q[1], q[2], q[3], q[0]]\n","sub_path":"mime/envs/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"503076978","text":"# Лотерея PowerBall.\n# Не доделано:\n# 10 наиболее \"созревших\" чисел (чисел, которые не использовались\n# долгое время),\n# упорядоченных от наиболее созревших до наименее созревших;\n# частоту каждого числа от 1 до 69 и частоту каждого PowerBall\n# числа от 1 до 26.\n\n# Импортирую модуль чтобы сгенерировать числа\n# и записать их в файл.\nimport random\n\ndef main():\n \"\"\"Основная функция.\"\"\"\n\n print(\n \"\"\"\n Меню:\n 1 - Сгенерировать числа в файл(*при повторном запуске\n числа дописываются в файл).\n 2 - 1О наиболее распространенных чисел\n 3 - 1О наименее распространенных чисел\n \"\"\"\n )\n\n num_list, coun_list = frequent_numbers(read_file())\n num_list2, coun_list2 = uncirculated_numbers(read_file())\n\n choice = int(input('Сделайте выбор: '))\n if choice == 1:\n gen_nun_powerBall()\n elif choice == 2:\n for i in range(len(num_list)):\n print('Число', num_list[i], 'выпадало:', coun_list[i], 'раз(а).')\n elif choice == 3:\n for i in range(len(num_list2)):\n print('Число', num_list2[i], 'выпадало:', coun_list2[i], 'раз(а).')\n\ndef gen_nun_powerBall():\n \"\"\"Генерирую 5 чисел в диапазоне от 1 до 69 и\n генерирую число 'PowerBall' от 1 до 26.\n После чего записываю данные в файл.\"\"\"\n\n # Список куда буду сохранять числа\n # которые получу при генерации.\n gen_num = []\n\n # Генерирую 5 чисел от 1 до 69\n # и записываю в список gen_num.\n while len(gen_num) != 5:\n gen = random.randint(1, 69)\n if gen not in gen_num:\n gen_num.append(gen)\n\n # Генерирую число 'PowerBall'\n # от 1 до 26.\n powerball = random.randint(1, 26)\n gen_num.append(powerball)\n\n # Перебираю список и записываю цифры\n # переменную.\n str_gen = ''\n\n for g in gen_num:\n str_gen += str(g) + \" \"\n\n # Удаляю лишний пробел в конце.\n str_gen = str_gen.rstrip()\n\n # Записываю данные в файл.\n with open('pbnumbers.txt', 'a') as pbnumbers:\n pbnumbers.write(str_gen + \"\\n\")\n\n # Закрываю файл.\n pbnumbers.close()\n\ndef read_file():\n \"\"\"Чтение данных из файла.\"\"\"\n\n # Читаю файл.\n with open('pbnumbers.txt', 'r', encoding='utf-8') as pbnumbers:\n\n # Сохраняю в список строку.\n list_pb = pbnumbers.read().split()\n\n # Переменная для посчёта индекса.\n count_index = 0\n\n # Перевожу символы в списке из строковых\n # в целые.\n for l in list_pb:\n list_pb[count_index] = int(l)\n count_index += 1\n\n # Закрывю файл.\n pbnumbers.close()\n\n return list_pb\n\ndef frequent_numbers(pb):\n \"\"\"1О наиболее распространенных чисел, упорядоченных по частоте.\"\"\"\n\n # Испортированный список с числами.\n list_pb = pb\n\n # Список для чисел\n num_list = []\n\n # Сколько раз число из num_list повторяется.\n coun_list = []\n\n # Перебираю испортированый список.\n for p in sorted(list_pb):\n if list_pb.count(p) > 1:\n if p not in num_list:\n num_list.append(p)\n coun_list.append(list_pb.count(p))\n\n # Списки для упорядочевания чисел.\n num_list2 = []\n coun_list2 = []\n\n # Индекс масимального числа.\n index_count = 0\n\n # Ищу в списке coun_list максимальное число\n # это повторения числа в списке.\n\n # Цикл работает пока длина списка coun_list не\n # будет равна 0.\n while len(coun_list) != 0:\n\n # Нахожу индекс максимального числа.\n index_count = coun_list.index(max(coun_list))\n\n # Записываю в новый список число с\n # наибольшим количеством повторений.\n num_list2.append(num_list[index_count])\n\n # Записываю в новый список количество\n # повторений числа с наибольшим повторением.\n coun_list2.append(coun_list[index_count])\n\n # Удаляю числа по индексу из старых списков.\n del num_list[index_count]\n del coun_list[index_count]\n\n # Возвращаю первые 10 чисел.\n return num_list2[:10], coun_list2[:10]\n\ndef uncirculated_numbers(pb):\n \"\"\"1О наименее распространенных чисел, упорядоченных по частоте.\"\"\"\n\n # Испортированный список с числами.\n list_pb = pb\n\n # Список для чисел\n num_list = []\n\n # Сколько раз число из num_list повторяется.\n coun_list = []\n\n # Перебираю испортированый список.\n for p in sorted(list_pb):\n if p not in num_list:\n num_list.append(p)\n coun_list.append(list_pb.count(p))\n\n # Списки для упорядочевания чисел.\n num_list2 = []\n coun_list2 = []\n\n # Индекс минимального числа.\n index_count = 0\n\n # Ищу в списке coun_list минимальное число\n # это повторения числа в списке.\n\n # Цикл работает пока длина списка coun_list не\n # будет равна 0.\n while len(coun_list) != 0:\n\n # Нахожу индекс минимального числа.\n index_count = coun_list.index(min(coun_list))\n\n # Записываю в новый список число с\n # наименьшим количеством повторений.\n num_list2.append(num_list[index_count])\n\n # Записываю в новый список количество\n # повторений числа с наименьшим повторением.\n coun_list2.append(coun_list[index_count])\n\n # Удаляю числа по индексу из старых списков.\n del num_list[index_count]\n del coun_list[index_count]\n\n # Возвращаю первые 10 чисел.\n return num_list2[:10], coun_list2[:10]\n\nmain()\n","sub_path":"8/tasks/8.13.py","file_name":"8.13.py","file_ext":"py","file_size_in_byte":7188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"100814538","text":"from numpy import *\nfrom block import *\nimport pyfits\nfilename='../fits/sub400.fits'\nd = pyfits.open(filename)[0].data.copy()\n#d = concatenate([zeros([4,len(d.T)]),d])\n#d = concatenate([zeros([len(d),4]),d],axis=1) #expand the array to use '-' drizzle\nd = concatenate([d,zeros([10,len(d.T)])])\nd = concatenate([d,zeros([len(d),10])],axis=1) #expand the array\nsc=(len(d.T)-10)/4\n#print sum(d[65:69,67:71])\n#[0:136] x ,y -> y, x\n#### y x\n#0:174\na=[0,2,0,2,1,3,1,3]\nb=[0,0,2,2,3,3,1,1] #from the info. given by observation\n#a=[-2+4,-2+4,-2+4,-1+4,-1+4,0+4,0+4,1+4,1+4,2+4,2+4,2+4]\n#b=[-2+4,0+4,-2+4,-1+4,1+4,-2+4,2+4,-1+4,1+4,-2+4,0+4,2+4]\nfor i in range(len(a)):\n dd=d[a[i]:sc*4+a[i],b[i]:sc*4+b[i]]\n aaa=block(dd,(sc,sc))\n\n pyfits.PrimaryHDU(aaa).writeto('../fits/binpsf/psf{0}.fits'.format(i+1),clobber=True)\n\n\n","sub_path":"WFI2033/simulation/rebin/rebinpsf.py","file_name":"rebinpsf.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"501041484","text":"import argparse\nimport os\nfrom datetime import datetime\nfrom os.path import join as pjoin\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom sklearn.model_selection import train_test_split\nfrom tensorboardX import SummaryWriter\nfrom torch.utils import data\nfrom tqdm import tqdm\n\nimport core.loss\nimport torchvision.utils as vutils\nfrom core.augmentations import (\n Compose, RandomHorizontallyFlip, RandomRotate, AddNoise)\nfrom core.loader.data_loader import *\nfrom core.metrics import runningScore\nfrom core.models import get_model\nfrom core.utils import np_to_tb\n\n# Fix the random seeds: \ntorch.backends.cudnn.deterministic = True\ntorch.manual_seed(2019)\nif torch.cuda.is_available(): torch.cuda.manual_seed_all(2019)\nnp.random.seed(seed=2019)\n\n\ndef split_train_val(args, per_val=0.1):\n # create inline and crossline sections for training and validation:\n loader_type = 'section'\n labels = np.load(pjoin('data', 'train', 'train_labels.npy'))\n i_list = list(range(labels.shape[0]))\n i_list = ['i_'+str(inline) for inline in i_list]\n\n x_list = list(range(labels.shape[1]))\n x_list = ['x_'+str(crossline) for crossline in x_list]\n\n list_train_val = i_list + x_list\n\n # create train and test splits:\n list_train, list_val = train_test_split(\n list_train_val, test_size=per_val, shuffle=True)\n\n # write to files to disK:\n file_object = open(\n pjoin('data', 'splits', loader_type + '_train_val.txt'), 'w')\n file_object.write('\\n'.join(list_train_val))\n file_object.close()\n file_object = open(\n pjoin('data', 'splits', loader_type + '_train.txt'), 'w')\n file_object.write('\\n'.join(list_train))\n file_object.close()\n file_object = open(pjoin('data', 'splits', loader_type + '_val.txt'), 'w')\n file_object.write('\\n'.join(list_val))\n file_object.close()\n\n\ndef train(args):\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n # Generate the train and validation sets for the model:\n split_train_val(args, per_val=args.per_val)\n\n current_time = datetime.now().strftime('%b%d_%H%M%S')\n log_dir = os.path.join('runs', current_time +\n \"_{}\".format(args.arch))\n writer = SummaryWriter(log_dir=log_dir)\n # Setup Augmentations\n if args.aug:\n data_aug = Compose(\n [RandomRotate(10), RandomHorizontallyFlip(), AddNoise()])\n else:\n data_aug = None\n\n train_set = section_loader(is_transform=True,\n split='train',\n augmentations=data_aug)\n\n # Without Augmentation:\n val_set = section_loader(is_transform=True,\n split='val',)\n\n n_classes = train_set.n_classes\n\n # Create sampler:\n\n shuffle = False # must turn False if using a custom sampler\n with open(pjoin('data', 'splits', 'section_train.txt'), 'r') as f:\n train_list = f.read().splitlines()\n with open(pjoin('data', 'splits', 'section_val.txt'), 'r') as f:\n val_list = f.read().splitlines()\n\n class CustomSamplerTrain(torch.utils.data.Sampler):\n def __iter__(self):\n char = ['i' if np.random.randint(2) == 1 else 'x']\n self.indices = [idx for (idx, name) in enumerate(\n train_list) if char[0] in name]\n return (self.indices[i] for i in torch.randperm(len(self.indices)))\n\n class CustomSamplerVal(torch.utils.data.Sampler):\n def __iter__(self):\n char = ['i' if np.random.randint(2) == 1 else 'x']\n self.indices = [idx for (idx, name) in enumerate(\n val_list) if char[0] in name]\n return (self.indices[i] for i in torch.randperm(len(self.indices)))\n\n trainloader = data.DataLoader(train_set,\n batch_size=args.batch_size,\n sampler=CustomSamplerTrain(train_list),\n num_workers=4,\n shuffle=shuffle)\n valloader = data.DataLoader(val_set,\n batch_size=args.batch_size,\n sampler=CustomSamplerVal(val_list),\n num_workers=4)\n\n # Setup Metrics\n running_metrics = runningScore(n_classes)\n running_metrics_val = runningScore(n_classes)\n\n # Setup Model\n if args.resume is not None:\n if os.path.isfile(args.resume):\n print(\"Loading model and optimizer from checkpoint '{}'\".format(args.resume))\n model = torch.load(args.resume)\n else:\n print(\"No checkpoint found at '{}'\".format(args.resume))\n else:\n model = get_model(args.arch, args.pretrained, n_classes)\n\n # Use as many GPUs as we can\n model = torch.nn.DataParallel(\n model, device_ids=range(torch.cuda.device_count()))\n model = model.to(device) # Send to GPU\n\n # PYTROCH NOTE: ALWAYS CONSTRUCT OPTIMIZERS AFTER MODEL IS PUSHED TO GPU/CPU,\n\n # Check if model has custom optimizer / loss\n if hasattr(model.module, 'optimizer'):\n print('Using custom optimizer')\n optimizer = model.module.optimizer\n else:\n # optimizer = torch.optim.Adadelta(model.parameters())\n optimizer = torch.optim.Adam(model.parameters(), amsgrad=True)\n\n loss_fn = core.loss.cross_entropy\n\n if args.class_weights:\n # weights are inversely proportional to the frequency of the classes in the training set\n class_weights = torch.tensor(\n [0.7151, 0.8811, 0.5156, 0.9346, 0.9683, 0.9852], device=device, requires_grad=False)\n else:\n class_weights = None\n\n best_iou = -100.0\n class_names = ['upper_ns', 'middle_ns', 'lower_ns',\n 'rijnland_chalk', 'scruff', 'zechstein']\n\n for arg in vars(args):\n text = arg + ': ' + str(getattr(args, arg))\n writer.add_text('Parameters/', text)\n\n # training\n for epoch in range(args.n_epoch):\n # Training Mode:\n model.train()\n loss_train, total_iteration = 0, 0\n\n for i, (images, labels) in enumerate(trainloader):\n image_original, labels_original = images, labels\n images, labels = images.to(device), labels.to(device)\n\n optimizer.zero_grad()\n outputs = model(images)\n\n pred = outputs.detach().max(1)[1].cpu().numpy()\n gt = labels.detach().cpu().numpy()\n running_metrics.update(gt, pred)\n\n loss = loss_fn(input=outputs, target=labels, weight=class_weights)\n loss_train += loss.item()\n loss.backward()\n\n # gradient clipping\n if args.clip != 0:\n torch.nn.utils.clip_grad_norm(model.parameters(), args.clip)\n optimizer.step()\n total_iteration = total_iteration + 1\n\n if (i) % 20 == 0:\n print(\"Epoch [%d/%d] training Loss: %.4f\" %\n (epoch + 1, args.n_epoch, loss.item()))\n\n numbers = [0]\n if i in numbers:\n # number 0 image in the batch\n tb_original_image = vutils.make_grid(\n image_original[0][0], normalize=True, scale_each=True)\n writer.add_image('train/original_image',\n tb_original_image, epoch + 1)\n\n labels_original = labels_original.numpy()[0]\n correct_label_decoded = train_set.decode_segmap(\n np.squeeze(labels_original))\n writer.add_image('train/original_label',\n np_to_tb(correct_label_decoded), epoch + 1)\n out = F.softmax(outputs, dim=1)\n\n # this returns the max. channel number:\n prediction = out.max(1)[1].cpu().numpy()[0]\n # this returns the confidence:\n confidence = out.max(1)[0].cpu().detach()[0]\n tb_confidence = vutils.make_grid(\n confidence, normalize=True, scale_each=True)\n\n decoded = train_set.decode_segmap(np.squeeze(prediction))\n writer.add_image('train/predicted', np_to_tb(decoded), epoch + 1)\n writer.add_image('train/confidence', tb_confidence, epoch + 1)\n\n unary = outputs.cpu().detach()\n unary_max = torch.max(unary)\n unary_min = torch.min(unary)\n unary = unary.add((-1*unary_min))\n unary = unary/(unary_max - unary_min)\n\n for channel in range(0, len(class_names)):\n decoded_channel = unary[0][channel]\n tb_channel = vutils.make_grid(\n decoded_channel, normalize=True, scale_each=True)\n writer.add_image(\n f'train_classes/_{class_names[channel]}', tb_channel, epoch + 1)\n\n # Average metrics, and save in writer()\n loss_train /= total_iteration\n score, class_iou = running_metrics.get_scores()\n writer.add_scalar('train/Pixel Acc', score['Pixel Acc: '], epoch+1)\n writer.add_scalar('train/Mean Class Acc',\n score['Mean Class Acc: '], epoch+1)\n writer.add_scalar('train/Freq Weighted IoU',\n score['Freq Weighted IoU: '], epoch+1)\n writer.add_scalar('train/Mean_IoU', score['Mean IoU: '], epoch+1)\n running_metrics.reset()\n writer.add_scalar('train/loss', loss_train, epoch+1)\n\n if args.per_val != 0:\n with torch.no_grad(): # operations inside don't track history\n # Validation Mode:\n model.eval()\n loss_val, total_iteration_val = 0, 0\n\n for i_val, (images_val, labels_val) in tqdm(enumerate(valloader)):\n image_original, labels_original = images_val, labels_val\n images_val, labels_val = images_val.to(\n device), labels_val.to(device)\n\n outputs_val = model(images_val)\n pred = outputs_val.detach().max(1)[1].cpu().numpy()\n gt = labels_val.detach().cpu().numpy()\n\n running_metrics_val.update(gt, pred)\n\n loss = loss_fn(input=outputs_val, target=labels_val)\n\n total_iteration_val = total_iteration_val + 1\n\n if (i_val) % 20 == 0:\n print(\"Epoch [%d/%d] validation Loss: %.4f\" %\n (epoch, args.n_epoch, loss.item()))\n\n numbers = [0]\n if i_val in numbers:\n # number 0 image in the batch\n tb_original_image = vutils.make_grid(\n image_original[0][0], normalize=True, scale_each=True)\n writer.add_image('val/original_image',\n tb_original_image, epoch)\n labels_original = labels_original.numpy()[0]\n correct_label_decoded = train_set.decode_segmap(\n np.squeeze(labels_original))\n writer.add_image('val/original_label',\n np_to_tb(correct_label_decoded), epoch + 1)\n\n out = F.softmax(outputs_val, dim=1)\n\n # this returns the max. channel number:\n prediction = out.max(1)[1].cpu().detach().numpy()[0]\n # this returns the confidence:\n confidence = out.max(1)[0].cpu().detach()[0]\n tb_confidence = vutils.make_grid(\n confidence, normalize=True, scale_each=True)\n\n decoded = train_set.decode_segmap(np.squeeze(prediction))\n writer.add_image('val/predicted', np_to_tb(decoded), epoch + 1)\n writer.add_image('val/confidence',tb_confidence, epoch + 1)\n\n unary = outputs.cpu().detach()\n unary_max, unary_min = torch.max(\n unary), torch.min(unary)\n unary = unary.add((-1*unary_min))\n unary = unary/(unary_max - unary_min)\n\n for channel in range(0, len(class_names)):\n tb_channel = vutils.make_grid(\n unary[0][channel], normalize=True, scale_each=True)\n writer.add_image(\n f'val_classes/_{class_names[channel]}', tb_channel, epoch + 1)\n\n score, class_iou = running_metrics_val.get_scores()\n for k, v in score.items():\n print(k, v)\n\n writer.add_scalar(\n 'val/Pixel Acc', score['Pixel Acc: '], epoch+1)\n writer.add_scalar('val/Mean IoU', score['Mean IoU: '], epoch+1)\n writer.add_scalar('val/Mean Class Acc',\n score['Mean Class Acc: '], epoch+1)\n writer.add_scalar('val/Freq Weighted IoU',\n score['Freq Weighted IoU: '], epoch+1)\n\n writer.add_scalar('val/loss', loss.item(), epoch+1)\n running_metrics_val.reset()\n\n if score['Mean IoU: '] >= best_iou:\n best_iou = score['Mean IoU: ']\n model_dir = os.path.join(\n log_dir, f\"{args.arch}_model.pkl\")\n torch.save(model, model_dir)\n\n else: # validation is turned off:\n # just save the latest model:\n if (epoch+1) % 10 == 0:\n model_dir = os.path.join(\n log_dir, f\"{args.arch}_ep{epoch+1}_model.pkl\")\n torch.save(model, model_dir)\n\n writer.close()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Hyperparams')\n parser.add_argument('--arch', nargs='?', type=str, default='section_deconvnet',\n help='Architecture to use [\\'patch_deconvnet, path_deconvnet_skip, section_deconvnet, section_deconvnet_skip\\']')\n parser.add_argument('--n_epoch', nargs='?', type=int, default=61,\n help='# of the epochs')\n parser.add_argument('--batch_size', nargs='?', type=int, default=8,\n help='Batch Size')\n parser.add_argument('--resume', nargs='?', type=str, default=None,\n help='Path to previous saved model to restart from')\n parser.add_argument('--clip', nargs='?', type=float, default=0.1,\n help='Max norm of the gradients if clipping. Set to zero to disable. ')\n parser.add_argument('--per_val', nargs='?', type=float, default=0.1,\n help='percentage of the training data for validation')\n parser.add_argument('--pretrained', nargs='?', type=bool, default=False,\n help='Pretrained models not supported. Keep as False for now.')\n parser.add_argument('--aug', nargs='?', type=bool, default=False,\n help='Whether to use data augmentation.')\n parser.add_argument('--class_weights', nargs='?', type=bool, default=False,\n help='Whether to use class weights to reduce the effect of class imbalance')\n\n args = parser.parse_args()\n train(args)\n","sub_path":"section_train.py","file_name":"section_train.py","file_ext":"py","file_size_in_byte":15452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"470816033","text":"import os\nimport time\nimport requests\nimport datetime\n\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.support.ui import Select\nfrom requests.exceptions import ConnectionError as RequestConnectionError\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\n\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n\nmain_page_url = 'http://library.ou.edu/'\nsource_url = 'https://libraries.ou.edu/resources-subject/business-economics'\nusername = 'arav0000'\npassword = 'Library121'\n\n\nclass JournalMetadataScrapper:\n def __init__(self):\n self.driver = webdriver.Chrome(ROOT_DIR + '/chromedriver')\n self.login_page_url = 'https://login.libraries.ou.edu/login'\n self.search_page_url = 'https://login.ezproxy.lib.ou.edu/login?url=' \\\n 'http://search.proquest.com/econlit/advanced?accountid=12964'\n self.cookies = {}\n self.max_count = None\n\n def authorize(self):\n self.driver.get(self.login_page_url)\n username_input = self.driver.find_element_by_id('username')\n password_input = self.driver.find_element_by_id('password')\n username_input.send_keys(username)\n time.sleep(1)\n password_input.send_keys(password)\n login_submit_button = self.driver.find_element_by_class_name('btn-submit')\n time.sleep(1)\n login_submit_button.click()\n time.sleep(1)\n\n def save_cookies(self):\n all_cookies = self.driver.get_cookies()\n\n for s_cookie in all_cookies:\n self.cookies[s_cookie[\"name\"]] = s_cookie[\"value\"]\n\n def open_search_page(self):\n try:\n self.driver.get(self.search_page_url)\n time.sleep(1.5)\n self.save_cookies()\n except NoSuchElementException as e:\n print(e)\n time.sleep(3)\n self.open_search_page()\n\n def get_filtered_results(self):\n self.driver.execute_script('window.scrollTo({}, {})'.format(0, 750))\n time.sleep(1)\n date_range_selector = Select(self.driver.find_element_by_id('select_multiDateRange'))\n date_range_selector.select_by_value('RANGE')\n date_range_year_1 = self.driver.find_element_by_id('year2')\n date_range_year_2 = self.driver.find_element_by_id('year2_0')\n date_range_year_1.send_keys('2010')\n date_range_year_2.send_keys('2018')\n result_page_options_button = self.driver.find_element_by_id('showResultPageOptions')\n result_page_options_button.click()\n time.sleep(4)\n results_per_page_selector = Select(self.driver.find_element_by_xpath(\"//select[starts-with(@id, 'itemsPerPage')]\"))\n results_per_page_selector.select_by_value('100')\n journal_article_checkbox = self.driver.find_element_by_id('RecordType_Journal_Article')\n time.sleep(1)\n english_lang_checkbox = self.driver.find_element_by_id('Language_ENG')\n time.sleep(1)\n search_button = self.driver.find_element_by_id('searchToResultPage')\n time.sleep(1)\n journal_article_checkbox.click()\n time.sleep(1)\n english_lang_checkbox.click()\n time.sleep(1)\n search_button.click()\n time.sleep(1)\n # self.driver.find_element_by_xpath('//select[@id=\"itemsPerPage\"]/option[text()=\"100\"]').click()\n\n def get_journal_url_list(self):\n number_of_results = int(self.driver.find_element_by_id('pqResultsCount').text.\n split('results')[0].replace(',', ''))\n\n self.max_count = number_of_results\n\n url_counter_in_file = 0\n with open('identifiers.txt', 'r') as f:\n for row in f:\n url_counter_in_file += 1\n\n url_identifiers_file = 'identifiers.txt'\n\n while url_counter_in_file < self.max_count:\n journals_on_the_page = self.driver.find_elements_by_id('citationDocTitleLink')\n\n for journal in journals_on_the_page:\n if url_counter_in_file < self.max_count:\n try:\n journal_url = journal.get_attribute('href')\n except:\n time.sleep(3)\n journal_url = journal.get_attribute('href')\n\n journal_identifier = journal_url.split('docview/')[-1].split('/')[0]\n\n with open(url_identifiers_file, 'r') as f:\n if journal_identifier + '\\n' in f:\n break\n\n filename = 'journals.txt'\n\n with open(filename, 'a') as file:\n file.write(journal_url + '\\n')\n url_counter_in_file += 1\n\n with open(url_identifiers_file, 'a') as idf:\n idf.write(journal_identifier + '\\n')\n\n if url_counter_in_file < self.max_count:\n try:\n next_page_button = self.driver.find_element_by_xpath('//a[@aria-label=\"Next page\"]')\n self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')\n next_page_button.click()\n time.sleep(1.5)\n except:\n print('counter is {}'.format(url_counter_in_file))\n print('ending the session')\n self.driver.close()\n print('exiting from the browser')\n self.driver.quit()\n print('creating new driver')\n self.driver = webdriver.Chrome(ROOT_DIR + '/chromedriver')\n print('authorizing')\n self.authorize()\n print('searching new journals')\n self.open_search_page()\n print('getting filtered results')\n self.get_filtered_results()\n time.sleep(1.5)\n else:\n break\n\n return True\n\n def chain_save_journal_urls(self):\n self._prepare_session_before_saving_urls()\n self._save_journal_urls()\n\n def _prepare_session_before_saving_urls(self):\n headers = {\n 'Accept': 'text / html, application / xhtml + xml, application / xml;',\n 'q': '0.9, image / webp, image / apng, * / *;q = 0.8',\n 'Accept - Encoding': 'gzip, deflate, br',\n 'Accept - Language': \"en - 'US, en;\",\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep - alive'\n }\n\n self.session = requests.Session()\n self.session.headers.update(headers)\n\n for cookie in self.driver.get_cookies():\n c = {cookie['name']: cookie['value']}\n self.session.cookies.update(c)\n\n def download_journal_html(self, url):\n filename = url.split('docview')[-1].split('/')[-3]\n folder = 'downloads_new/'\n ext = '.html'\n file = ROOT_DIR + '/' + folder + filename + ext\n\n if os.path.isfile(file):\n print('{} already exists. Skipping...'.format(filename))\n return\n\n try:\n page = self.session.get(url).text\n except RequestConnectionError:\n time.sleep(5)\n page = self.session.get(url).text\n\n soup = BeautifulSoup(page, 'html.parser')\n\n print('current url: {}'.format(url))\n main_download_folder = ROOT_DIR + '/downloads_new'\n\n if not os.path.exists(main_download_folder):\n os.makedirs(main_download_folder)\n\n journal_data = soup.find('div', {'class': 'contentPadingDocview'})\n try:\n prettified_journal_data = journal_data.prettify()\n except AttributeError as e:\n print(e)\n self.driver = webdriver.Chrome(ROOT_DIR + '/chromedriver')\n self.authorize()\n self.open_search_page()\n self._prepare_session_before_saving_urls()\n self.driver.close()\n return\n\n with open(main_download_folder + '/' + filename + '.html', 'w') as f:\n f.write(str(prettified_journal_data))\n f.close()\n\n def _save_journal_urls(self):\n\n journal_urls_file = 'journals.txt'\n\n with open(journal_urls_file, 'r') as file:\n for url in file:\n try:\n self.download_journal_html(url)\n except AttributeError as e:\n print(e)\n\n try:\n self.driver.close()\n except Exception as ex:\n print(ex)\n\n self.driver = webdriver.Chrome(ROOT_DIR + '/chromedriver')\n self.authorize()\n self.open_search_page()\n self._prepare_session_before_saving_urls()\n self.driver.close()\n self.download_journal_html(url)\n continue\n\n\nx = JournalMetadataScrapper()\nx.authorize()\nx.open_search_page()\nx.get_filtered_results()\nx.get_journal_url_list()\nx.chain_save_journal_urls()\n\n\n\n","sub_path":"journal_scrapper.py","file_name":"journal_scrapper.py","file_ext":"py","file_size_in_byte":9043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"212750217","text":"\"\"\"Provide wrapper funcs that do some extra stuff all in a go.\"\"\"\n\nimport statsmodels.formula.api as smf\n\ndef report_logitreg(formula, data, verbose=True):\n \"\"\"Fit logistic regression, print a report, and return the fit object.\"\"\"\n results = smf.logit(formula, data=data).fit()\n summary = results.summary()\n margeff = results.get_margeff().summary()\n\n\n if verbose:\n report = \"\"\"\n{summary}\\n\\n\n{margeff}\\n\"\"\".format(summary=summary,margeff=margeff)\n\n print(report)\n\n return results\n","sub_path":"tests/statsmodels_helpers/lazy_stats.py","file_name":"lazy_stats.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"148645103","text":"from matplotlib.pyplot import style, subplots, show\nfrom datetime import datetime\nfrom csv import reader\nfrom os import path, chdir\n\ndef main():\n dirPath = path.dirname(path.realpath(__file__))\n chdir(dirPath)\n\n fileName = 'Little_Rock_Weather_2019.csv'\n\n with open(fileName) as f:\n r = reader(f)\n headerRow = next(r)\n\n highs = []\n lows = []\n dates = []\n\n for row in r:\n if row[0] == 'USW00003952':\n high = int(row[5])\n highs.append(high)\n\n low = int(row[6])\n lows.append(low)\n\n date = datetime.strptime(row[2], '%Y-%m-%d')\n dates.append(date)\n\n fig, ax = subplots()\n ax.plot(dates, highs, c='red', alpha=0.5)\n ax.plot(dates, lows, c='blue', alpha=0.5)\n\n ax.set_title('Little Rock Daily Temperatures, 2019', fontsize=26)\n\n ax.set_xlabel('Dates', fontsize=18)\n fig.autofmt_xdate()\n\n ax.set_ylabel('Temperatures (\\u00b0F)', fontsize=18)\n\n show()\n\n\nif __name__ == '__main__':\n main()","sub_path":"WeatherData/weather_processor.py","file_name":"weather_processor.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"625689716","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProfile: http://hl7.org/fhir/StructureDefinition/PaymentNotice\nRelease: R4\nVersion: 4.0.1\nBuild ID: 9346c8cc45\nLast updated: 2019-11-01T09:29:23.356+11:00\n\"\"\"\nfrom typing import List as ListType\n\nfrom pydantic import Field\n\nfrom . import domainresource, fhirtypes\n\n\nclass PaymentNotice(domainresource.DomainResource):\n \"\"\"Disclaimer: Any field name ends with ``__ext`` does't part of\n Resource StructureDefinition, instead used to enable Extensibility feature\n for FHIR Primitive Data Types.\n\n PaymentNotice request.\n This resource provides the status of the payment for goods and services\n rendered, and the request and response resource references.\n \"\"\"\n\n resource_type = Field(\"PaymentNotice\", const=True)\n\n amount: fhirtypes.MoneyType = Field(\n ...,\n alias=\"amount\",\n title=\"Monetary amount of the payment\",\n description=\"The amount sent to the payee.\",\n # if property is element of this resource.\n element_property=True,\n )\n\n created: fhirtypes.DateTime = Field(\n ...,\n alias=\"created\",\n title=\"Creation date\",\n description=\"The date when this resource was created.\",\n # if property is element of this resource.\n element_property=True,\n )\n created__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_created\", title=\"Extension field for ``created``.\"\n )\n\n identifier: ListType[fhirtypes.IdentifierType] = Field(\n None,\n alias=\"identifier\",\n title=\"Business Identifier for the payment noctice\",\n description=\"A unique identifier assigned to this payment notice.\",\n # if property is element of this resource.\n element_property=True,\n )\n\n payee: fhirtypes.ReferenceType = Field(\n None,\n alias=\"payee\",\n title=\"Party being paid\",\n description=(\n \"The party who will receive or has received payment that is the subject\"\n \" of this notification.\"\n ),\n # if property is element of this resource.\n element_property=True,\n # note: Listed Resource Type(s) should be allowed as Reference.\n enum_reference_types=[\"Practitioner\", \"PractitionerRole\", \"Organization\"],\n )\n\n payment: fhirtypes.ReferenceType = Field(\n ...,\n alias=\"payment\",\n title=\"Payment reference\",\n description=\"A reference to the payment which is the subject of this notice.\",\n # if property is element of this resource.\n element_property=True,\n # note: Listed Resource Type(s) should be allowed as Reference.\n enum_reference_types=[\"PaymentReconciliation\"],\n )\n\n paymentDate: fhirtypes.Date = Field(\n None,\n alias=\"paymentDate\",\n title=\"Payment or clearing date\",\n description=\"The date when the above payment action occurred.\",\n # if property is element of this resource.\n element_property=True,\n )\n paymentDate__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_paymentDate\", title=\"Extension field for ``paymentDate``.\"\n )\n\n paymentStatus: fhirtypes.CodeableConceptType = Field(\n None,\n alias=\"paymentStatus\",\n title=\"Issued or cleared Status of the payment\",\n description=\"A code indicating whether payment has been sent or cleared.\",\n # if property is element of this resource.\n element_property=True,\n )\n\n provider: fhirtypes.ReferenceType = Field(\n None,\n alias=\"provider\",\n title=\"Responsible practitioner\",\n description=(\n \"The practitioner who is responsible for the services rendered to the \"\n \"patient.\"\n ),\n # if property is element of this resource.\n element_property=True,\n # note: Listed Resource Type(s) should be allowed as Reference.\n enum_reference_types=[\"Practitioner\", \"PractitionerRole\", \"Organization\"],\n )\n\n recipient: fhirtypes.ReferenceType = Field(\n ...,\n alias=\"recipient\",\n title=\"Party being notified\",\n description=\"The party who is notified of the payment status.\",\n # if property is element of this resource.\n element_property=True,\n # note: Listed Resource Type(s) should be allowed as Reference.\n enum_reference_types=[\"Organization\"],\n )\n\n request: fhirtypes.ReferenceType = Field(\n None,\n alias=\"request\",\n title=\"Request reference\",\n description=\"Reference of resource for which payment is being made.\",\n # if property is element of this resource.\n element_property=True,\n # note: Listed Resource Type(s) should be allowed as Reference.\n enum_reference_types=[\"Resource\"],\n )\n\n response: fhirtypes.ReferenceType = Field(\n None,\n alias=\"response\",\n title=\"Response reference\",\n description=\"Reference of response to resource for which payment is being made.\",\n # if property is element of this resource.\n element_property=True,\n # note: Listed Resource Type(s) should be allowed as Reference.\n enum_reference_types=[\"Resource\"],\n )\n\n status: fhirtypes.Code = Field(\n ...,\n alias=\"status\",\n title=\"active | cancelled | draft | entered-in-error\",\n description=\"The status of the resource instance.\",\n # if property is element of this resource.\n element_property=True,\n # note: Enum values can be used in validation,\n # but use in your own responsibilities, read official FHIR documentation.\n enum_values=[\"active\", \"cancelled\", \"draft\", \"entered-in-error\"],\n )\n status__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_status\", title=\"Extension field for ``status``.\"\n )\n","sub_path":"fhir/resources/paymentnotice.py","file_name":"paymentnotice.py","file_ext":"py","file_size_in_byte":5848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"630118377","text":"import pygame\nimport constants\nimport spritesheet\nimport spriteanim\n\nclass Erik(pygame.sprite.Sprite):\n def __init__(self, x = 0, y = 0):\n super(Erik, self).__init__()\n\n ss = spritesheet.spritesheet(\"images/erik.png\", -1)\n\n self.sprite_stand = spriteanim.AnimSprite(\n ss.load_sprites(5, 5, 2, W=constants.HERO_W - 1), \n constants.ERIK_STAND_BLINK_TIME, \n animInterval=[\n constants.ERIK_STAND_BLINK_TIME - constants.ERIK_STAND_BLINK_DELAY, \n constants.ERIK_STAND_BLINK_TIME])\n\n sprite_running = ss.load_sprites(6, 114, 8)\n self.running_interval = constants.ERIK_WALK_SPEED * len(sprite_running)\n self.sprite_running = spriteanim.AnimSprite(sprite_running, self.running_interval)\n\n self.sprite_stoping = spriteanim.AnimSprite(ss.load_sprites(6, 249, 3, W=constants.HERO_W-1), 130, [2, 1, 0, 1, 2, 1, 0, 1, 2, 1, 0, 1, 2])\n self.sprite_jumping = spriteanim.AnimSprite(ss.load_sprites(6, 212, 4), 2 * constants.ERIK_JUMP_FORCE, animInterval=constants.ERIK_JUMP_INTERVAL)\n self.sprite_falling = spriteanim.AnimSprite(ss.load_sprites(80, 212, 2), 40)\n self.sprite_tying = spriteanim.AnimSprite(ss.load_sprites(9, 363, 3, W=constants.HERO_W-1), 105, [0,1,2,1,2,1,0])\n self.sprite_climbing = spriteanim.AnimSprite(ss.load_sprites(4, 288, 4), 40)\n\n self.image = self.sprite_stand.getAt()\n self.rect = self.image.get_rect()\n\n self.x = x\n self.y = y\n self.jumpGround = y\n self.index = 0\n self.running_time = 0\n self.stopping = -1\n self.jumpMove = constants.ERIK_JUMP_FORCE + 1\n self.lastMoveLeft = self.moveLeft = self.moveRight = False\n\n self.status = constants.HERO_STATUS_STANDING\n\n self.onLadder = False\n self.doClimbing = False\n self.climbingUp = False\n\n self.rect.x = self.x\n # self.rect.y = self.y\n self.rect.bottom = self.y\n\n def isFalling(self):\n if self.status == constants.HERO_STATUS_FALLING:\n self.y += constants.ERIK_JUMP_FORCE // 4\n\n def goLeft(self, platform = None):\n self.onLadder = False\n self.x -= constants.ERIK_WALK_SPEED\n self.isFalling()\n self.moveLeft = self.lastMoveLeft= True\n self.index = 0\n\n if platform != None:\n self.y = platform.rect.y + 2\n self.jumpGround = platform.rect.y + 2\n\n def goRight(self, platform = None):\n self.onLadder = False\n self.x += constants.ERIK_WALK_SPEED\n self.isFalling()\n self.moveRight = True\n self.lastMoveLeft = False\n self.index = 0\n\n if platform != None:\n self.y = platform.rect.y + 2\n self.jumpGround = platform.rect.y + 2\n\n def goClimbUp(self, Ladder = None):\n self.y -= constants.HERO_CLIMB_SPEED\n self.onLadder = True\n self.doClimbing = True\n self.climbingUp = True\n self.index = 0\n if Ladder is not None:\n self.rect.centerx = Ladder.rect.centerx\n self.x = self.rect.x\n\n def goClimbDown(self, Ladder = None):\n self.y += constants.HERO_CLIMB_SPEED\n self.onLadder = True\n self.doClimbing = True\n self.climbingUp = False\n self.index = 0\n\n def doStopClimbing(self):\n self.doClimbing = False\n\n def doStopRunning(self):\n self.index = 0\n self.stopping = 140\n self.moveLeft = self.moveRight = False\n\n def doActionOne(self, ground_y):\n # print(self.rect.bottom, ground_y, self.y)\n self.onLadder = False\n self.doClimbing = True\n if self.rect.bottom == ground_y:\n self.jumpMove = -constants.ERIK_JUMP_FORCE\n self.jumpGround = ground_y\n self.stopping = -1\n self.running_time = 0\n\n def render_jumping(self):\n self.image = self.sprite_jumping.next(self.lastMoveLeft) \n\n def render_climbing(self):\n if self.doClimbing:\n if self.climbingUp:\n self.image = self.sprite_climbing.next()\n else:\n self.image = self.sprite_climbing.prev()\n else:\n self.image = self.sprite_climbing.curr()\n\n def render_standing(self):\n if self.jumpMove <= constants.ERIK_JUMP_FORCE:\n self.render_jumping()\n self.index = 0\n else:\n self.index += 1\n self.index %= constants.ERIK_STAND_TYING_TIME \n\n if self.index > constants.ERIK_STAND_TYING_TIME - constants.ERIK_STAND_TYING_DELAY:\n self.image = self.sprite_tying.next(self.lastMoveLeft)\n else:\n self.image = self.sprite_stand.next(self.lastMoveLeft)\n\n def render_running(self):\n self.index += 1\n self.index %= self.running_interval\n\n if self.jumpMove <= constants.ERIK_JUMP_FORCE:\n self.render_jumping()\n else:\n self.image = self.sprite_running.next(self.moveLeft)\n\n def render_stoping(self):\n self.stopping -= 1 # -1, 0..140\n if self.stopping < 0:\n self.running_time = 0\n\n self.image = self.sprite_stoping.next(self.lastMoveLeft)\n\n def update(self, platform = None):\n self.isFalling()\n if self.onLadder:\n if self.doClimbing:\n if self.climbingUp:\n self.y -= constants.HERO_CLIMB_SPEED\n else:\n self.y += constants.HERO_CLIMB_SPEED\n self.render_climbing()\n else:\n # calc jumping mechanics\n if self.jumpMove <= constants.ERIK_JUMP_FORCE:\n if self.y + self.jumpMove < self.jumpGround:\n self.y += self.jumpMove\n if self.jumpMove < constants.ERIK_JUMP_FORCE:\n self.jumpMove += 1\n else:\n self.y = self.jumpGround\n self.jumpMove = constants.ERIK_JUMP_FORCE + 1\n self.sprite_jumping.reset()\n\n # if standing\n if not (self.moveLeft or self.moveRight):\n if self.stopping >= 0 and self.running_time > 40:\n self.render_stoping()\n else:\n self.render_standing()\n self.running_time = 0\n\n else: # if running\n if self.moveLeft:\n self.x -= constants.ERIK_WALK_SPEED\n else:\n self.x += constants.ERIK_WALK_SPEED\n self.render_running()\n self.running_time += 1\n\n self.rect.x = self.x\n # self.rect.y = self.y\n self.rect.bottom = self.y\n","sub_path":"hero_erik.py","file_name":"hero_erik.py","file_ext":"py","file_size_in_byte":6733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"452830669","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n#author:iuyyoy \n#content:Minion\n\nfrom __future__ import division, print_function, unicode_literals\n\nimport cocos.collision_model as cm\nfrom cocos import sprite as CSprite\n\nfrom BasicCard import *\n\n#随从类\nclass MinionCard(BasicCard):\n def __init__(self, \n name, \n belong='neutral', \n rarity='free', \n set='basic', \n type='minion', \n race='other', \n cost=0, \n attack=0, \n hp=1, \n description='MinionCard', \n background='Missing', \n consume=0, \n gain=0, \n golden=0, \n img='TestMinion.jpg', \n sign=0):\n super(MinionCard, self).__init__(name, belong, rarity, set, type, race, cost, description, background, consume, gain, golden, img, sign)\n self.hp = HealthPoint(hp, hp, hp)\n self.attack = Attack(attack, attack)\n self.status = {\n 'Sleepy':True,\n 'Frozen':False,\n 'AttackTimes':1,\n 'AttackedTimes':0,\n 'AttackLevel':0,\n }\n def canBeUsed(self, player, opponent=None):\n if super(MinionCard, self).canBeUsed(player, opponent):\n if player.minions.present < player.minions.max:\n return True\n return False\n def canBeUsedToSth(self, player, target=None):\n if super(MinionCard, self).canBeUsedToSth(player, target):\n if player.minions.present < player.minions.max:\n return True\n return False\n def canAttack(self, opponent):\n if opponent.canBeAttacked() and not self.status['Sleepy'] and not self.status['Frozen'] and self.status['AttackedTimes'] < self.status['AttackTimes'] and self.attack.present > 0:\n return True\n return False\n def canAttackToSth(self, opponent, target):\n if self.canAttack(opponent) and target.status['AttackLevel'] == opponent.status['AttackLevel']:\n return True\n return False\n def addAttackedTimes(self, number=1):\n self.status['AttackedTimes'] += number\n def awaken(self):\n if self.status['Sleepy']:\n self.status['Sleepy'] = False\n self.status['AttackedTimes'] = 0\n def battleCry(self):\n pass\n def deathrattle(self):\n pass\n #收到伤害\n def beHurt(self, point=1):\n isdead = False\n if point > 0:\n isdead = not(self.hp - point)\n return isdead\n def checkDeath(self):\n return True if self.hp.present <= 0 else False\n#生命值\nclass HealthPoint(object):\n def __init__(self, present, origin, limit, max=9999):\n super(HealthPoint, self).__init__()\n self.present = present\n self.origin = origin\n self.limit = limit\n self.max = max\n #生命值减少\n def __sub__(self, point): \n point = point if point > 0 else -point \n self.present -= point\n return False if self.present < 0 else True\n\n #生命值增加\n def __add__(self, point):\n if point > 0:\n self.present += point\n self.checkPresentLimit()\n return self.present\n#攻击\nclass Attack(object):\n def __init__(self, present, origin, max=9999):\n super(Attack, self).__init__()\n self.present = present\n self.origin = origin\n self.max = max","sub_path":"Game/Cards/MinionCard.py","file_name":"MinionCard.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"509802766","text":"import xarray as xa\nimport umap, time, pickle\nimport umap.plot\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom typing import List, Union, Tuple, Optional\nfrom geoproc.classification.plots import datashade_points, point_cloud_3d\n\nimport os, math\n\ndef get_color_data( filepath: str, iband: int, subsampling: int ) -> xa.DataArray:\n print( f\"Reading data file {filepath}\")\n dset: xa.Dataset = xa.open_dataset(filepath)\n band_data: xa.DataArray = dset['band_data'][iband]\n nodata_value = band_data.attrs.get('data_ignore_value', -9999 )\n band_data: xa.DataArray = band_data.where(band_data != nodata_value, float('nan'))\n band_data = band_data.stack(samples=band_data.dims).dropna( dim=\"samples\" )\n return band_data[::subsampling]\n\nc0 = (1000,1000)\nc1 = (2000,2000)\ncolor_band = 200\nsubsampling = 5\nndims = 3\n\ndata_dir = \"/Users/tpmaxwel/Dropbox/Tom/Data/Aviris/processed\"\noutput_dir = \"/usr/local/web/ILAB/data/results/umap\"\ndata_file = os.path.join( data_dir, f\"ang20170720t004130.{c0[0]}-{c0[1]}_{c1[0]}-{c1[1]}.nc\" )\nmapping_file = os.path.join( output_dir, f\"umap-model.ang20170720t004130.{c0[0]}-{c1[1]}_{c1[0]}-{c1[1]}.s-{subsampling}.d-{ndims}.pkl\" )\ncolor_data = get_color_data( data_file, color_band, subsampling )\n\nt0 = time.time()\nmapper = pickle.load( open( mapping_file, \"rb\" ) )\nt1 = time.time()\nprint( f\"Completed map load in {(t1-t0)} sec, Now transforming data\")\n\nif ndims == 2:\n datashade_points( mapper.embedding_, values = color_data.values, vrange = [ 0, 10 ], cmap=\"jet\" )\nelse:\n point_cloud_3d( mapper.embedding_, values = color_data.values, cmap=\"jet\", vrange = [ -10, 10 ] )\n\n\n\n\n\n\n\n","sub_path":"geoproc/classification/view_umap_results.py","file_name":"view_umap_results.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"258897496","text":"import pandas as pd\nimport numpy as np\n\n# Для работы с матрицами\nfrom implicit.bpr import BayesianPersonalizedRanking\nfrom scipy.sparse import csr_matrix\n\n# Матричная факторизация\nfrom implicit.als import AlternatingLeastSquares\nfrom implicit.nearest_neighbours import ItemItemRecommender # нужен для одного трюка\nfrom implicit.nearest_neighbours import bm25_weight, tfidf_weight\n\nclass MainRecommender:\n \"\"\"Рекоммендации, которые можно получить из ALS\n\n Input\n -----\n _user_item_matrix: pd.DataFrame\n Матрица взаимодействий user-item\n \"\"\"\n\n def __init__(self, data, item_features,data_for_price_calc, n_factors=20, regularization=0.001, iterations=15,\n num_threads=4,weighting=True, use_item_prices=False,model_name='ALS',fit_main_model=True,fit_own_model=True,\n target_values='sales_value',funcs=np.sum):\n # Топ покупок каждого юзера\n self._item_prices = None\n self._model_name=model_name\n if use_item_prices:\n self._item_prices=self.get_item_prices(data_for_price_calc)\n self.top_purchases = data.groupby(['user_id', 'item_id'])['sales_value'].count().reset_index()\n self.top_purchases.sort_values('sales_value', ascending=False, inplace=True)\n self.top_purchases = self.top_purchases[self.top_purchases['item_id'] != 999999]\n self.item_features = item_features\n\n # Топ покупок по всему датасету\n self.overall_top_purchases = data.groupby('item_id')['sales_value'].count().reset_index()\n self.overall_top_purchases.sort_values('sales_value', ascending=False, inplace=True)\n self.overall_top_purchases = self.overall_top_purchases[self.overall_top_purchases['item_id'] != 999999]\n self.overall_top_purchases = self.overall_top_purchases.item_id.tolist()\n\n self._user_item_matrix = self.prepare_matrix(data,target_values,funcs) # pd.DataFrame\n self.id_to_itemid, self.id_to_userid, \\\n self.itemid_to_id, self.userid_to_id = self.prepare_dicts(self._user_item_matrix)\n\n # Словарь {item_id: 0/1}. 0/1 - факт принадлежности товара к СТМ\n self.item_id_to_ctm = self.prepare_to_ctm_dict(self.item_features, self._user_item_matrix) # your_code\n\n # Own recommender обучается до взвешивания матрицы\n if fit_own_model==True:\n self.own_recommender = self.fit_own_recommender(self._user_item_matrix)\n\n matrix_to_fit=self._user_item_matrix\n if weighting:\n matrix_to_fit = bm25_weight(self._user_item_matrix.T).T\n\n if fit_main_model==True:\n self._model = self.fit(matrix_to_fit, n_factors, regularization, iterations, num_threads,model_name)\n\n self.sparse_user_item = csr_matrix(self._user_item_matrix).tocsr()\n\n\n #self.itemid_to_id[999999]=0\n\n @property\n def user_item_matrix(self):\n return self._user_item_matrix\n\n @property\n def model(self):\n return self._model\n\n @property\n def item_prices(self):\n return self._item_prices\n\n @staticmethod\n def get_item_prices(data_for_price_calc):\n item_prices = data_for_price_calc.groupby(['item_id']).agg(\n {'sales_value': \"sum\", 'quantity': \"sum\"}).reset_index()\n item_prices['price'] = item_prices['sales_value'] / item_prices['quantity']\n item_prices.drop(['sales_value', 'quantity'], axis=1, inplace=True)\n return item_prices\n\n @staticmethod\n def prepare_to_ctm_dict(item_features, _user_item_matrix):\n itemids = _user_item_matrix.columns.values\n item_features = item_features[item_features['item_id'].isin(itemids)]\n item_ids_ctm = item_features[item_features['brand'] == 'Private'].item_id.unique().tolist()\n\n matrix_itemids = [0 for i in range(len(itemids))]\n item_id_to_ctm = dict(map(lambda itemid, ctm: (itemid, (itemid in item_ids_ctm) * 1), itemids, matrix_itemids))\n\n return item_id_to_ctm\n\n @staticmethod\n def prepare_matrix(data,target_values,funcs):\n _user_item_matrix = pd.pivot_table(data,\n index='user_id', columns='item_id',\n values=target_values, # Можно пробовать другие варианты\n aggfunc=funcs,\n fill_value=0\n )\n _user_item_matrix = _user_item_matrix.astype(float) # необходимый тип матрицы для implicit\n return _user_item_matrix\n\n @staticmethod\n def prepare_dicts(user_item_matrix):\n \"\"\"Подготавливает вспомогательные словари\"\"\"\n\n userids = user_item_matrix.index.values\n itemids = user_item_matrix.columns.values\n\n matrix_userids = np.arange(len(userids))\n matrix_itemids = np.arange(len(itemids))\n\n id_to_itemid = dict(zip(matrix_itemids, itemids))\n id_to_userid = dict(zip(matrix_userids, userids))\n\n itemid_to_id = dict(zip(itemids, matrix_itemids))\n userid_to_id = dict(zip(userids, matrix_userids))\n\n return id_to_itemid, id_to_userid, itemid_to_id, userid_to_id\n\n @staticmethod\n def fit_own_recommender(user_item_matrix):\n \"\"\"Обучает модель, которая рекомендует товары, среди товаров, к��пленных юзером\"\"\"\n\n own_recommender = ItemItemRecommender(K=1, num_threads=16)\n own_recommender.fit(csr_matrix(user_item_matrix).T.tocsr())\n\n return own_recommender\n\n @staticmethod\n def fit(useritemmatrix, n_factors, regularization, iterations, num_threads,model_name):\n \"\"\"Обучает ALS\"\"\"\n\n model=None\n if model_name=='ALS':\n model = AlternatingLeastSquares(factors=n_factors,\n regularization=regularization,\n iterations=iterations,\n calculate_training_loss=True,\n num_threads=num_threads)\n elif model_name=='BPR':\n model = BayesianPersonalizedRanking(factors=n_factors,\n regularization=regularization,\n iterations=iterations,\n num_threads=num_threads)\n\n model.fit(csr_matrix(useritemmatrix).T.tocsr(), show_progress=True)\n\n return model\n\n\n def get_similar_items_recommendation(self, user, filter_ctm=True, N=5):\n \"\"\"Рекомендуем товары, похожие на топ-N купленных юзером товаров\"\"\"\n popularity = self.top_purchases[self.top_purchases['user_id'] == user].head(N)\n # СТМ = товары под брендом Private\n if filter_ctm == True:\n ctm = self.item_features[self.item_features['brand'] == 'Private'].item_id.unique()\n popularity = popularity[~popularity['item_id'].isin(ctm)]\n\n popularity['similar_recommendation'] = popularity['item_id'].apply(lambda x: self.get_rec(x, N))\n res = popularity['similar_recommendation'].values.tolist()\n res = self._extend_with_top_popular(res, N=N)\n\n return res\n\n def get_rec(self, itemid, N):\n recs = self._model.similar_items(self.itemid_to_id[itemid], N=N)\n top_rec = recs[1][0]\n\n return self.id_to_itemid[top_rec]\n\n def get_similar_users_recommendation(self, user, N=5):\n \"\"\"Рекомендуем топ-N товаров, среди купленных похожими юзерами\"\"\"\n res = []\n\n # Находим топ-N похожих users\n similar_users = self._model.similar_users(self.userid_to_id[user], N=N + 1)\n similar_users = [rec[0] for rec in similar_users]\n similar_users = similar_users[1:] # удалим юзера из запроса\n\n for user in similar_users:\n res.extend(self.get_own_recommendations(user, N=1))\n\n res = self._extend_with_top_popular(res, N=N)\n\n return res\n\n def _extend_with_top_popular(self, recommendations, N=5):\n \"\"\"Если кол-во рекоммендаций < N, то дополняем их топ-популярными\"\"\"\n\n if len(recommendations) < N:\n recommendations.extend(self.overall_top_purchases[:N])\n recommendations = recommendations[:N]\n\n return recommendations\n\n def _update_dict(self, user_id):\n \"\"\"Если появился новыю user / item, то нужно обновить словари\"\"\"\n\n if user_id not in self.userid_to_id.keys():\n max_id = max(list(self.userid_to_id.values()))\n max_id += 1\n\n self.userid_to_id.update({user_id: max_id})\n self.id_to_userid.update({max_id: user_id})\n return True\n\n return False\n\n def get_own_recommendations(self, user, N=5):\n \"\"\"Рекомендуем товары среди тех, которые юзер уже купил\"\"\"\n\n is_updated = self._update_dict(user_id=user)\n if not is_updated:\n return self.get_recommendations(user, model=self.own_recommender, N=N)\n else:\n res = []\n\n res = self._extend_with_top_popular(res, N=N)\n\n return res\n\n def get_recommendations(self, user, model, N=5):\n \"\"\"Рекомендации через стардартные библиотеки implicit\"\"\"\n\n is_updated=self._update_dict(user_id=user)\n if not is_updated:\n res=[]\n if self._model_name=='ALS':\n res = [self.id_to_itemid[rec[0]] for rec in model.recommend(userid=self.userid_to_id[user],\n user_items=self.sparse_user_item,\n N=N,\n filter_already_liked_items=False,\n filter_items=None, #[self.itemid_to_id[999999]],\n recalculate_user=True)]\n elif self._model_name=='BPR':\n res = [self.id_to_itemid[rec[0]] for rec in model.recommend(userid=self.userid_to_id[user],\n user_items=self.sparse_user_item,\n N=N,\n filter_already_liked_items=False,\n filter_items=None\n )]\n else:\n res=[]\n\n res = self._extend_with_top_popular(res, N=N)\n\n return res\n\n def get_recomendations_per_user(self,user, model, N=5):\n recs = []\n if self._model_name == 'ALS':\n recs = model.recommend(userid=self.userid_to_id[user], # userid - id от 0 до N\n user_items=self.sparse_user_item, # на вход user-item matrix\n N=N, # кол-во рекомендаций\n filter_already_liked_items=False,\n filter_items=None,\n recalculate_user=False)\n elif self._model_name == 'BPR':\n recs = model.recommend(userid=self.userid_to_id[user],\n user_items=self.sparse_user_item,\n N=N,\n filter_already_liked_items=False,\n filter_items=None\n )\n return recs\n\n def fill_prices(self,item_ids):\n price_arr = []\n for item_id in item_ids:\n price_arr.append(self._item_prices[self._item_prices['item_id'] == item_id]['price'].values[0])\n\n return price_arr\n\n","sub_path":"CourseProject/src/recommenders.py","file_name":"recommenders.py","file_ext":"py","file_size_in_byte":12557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169285697","text":"import sys\nsys.path.append('/home/wwx/wwx/Instance-weight-Balanced-Factorization-Machine') \nimport argparse\nfrom util.dataset import FrappeDataSet\nfrom torch.utils.data import DataLoader\nfrom util.LoadData import LoadData\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport numpy as np\nimport math\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nfrom time import time\n\n\nparser = argparse.ArgumentParser(description='Hyperparameter tuning')\nparser.add_argument('-use_cuda', default=1, type=int)\nparser.add_argument('-path', default='../data/', type=str, help='Input data path')\nparser.add_argument('-dataset', default='frappe', type=str, help='Choose a dataset.')\nparser.add_argument('-pretrain', default=-1, type=int, help='flag for pretrain. 1: initialize from pretrain; 0: randomly initialize; -1: save to pretrain file')\nparser.add_argument('-epochs', default=100, type=int, help='Number of epochs')\nparser.add_argument('-metric', default='RMSE', type=str, help='MAE or RMSE')\nparser.add_argument('-batch_size', default=2048, type=int, help='batch size')\nparser.add_argument('-embedding_size', default=256, type=int, help='embedding size')\nparser.add_argument('-field_size', default=10, type=int, help='field size of dataset')\nparser.add_argument('-l2', default=0, type=float, help='Regularizer')\nparser.add_argument('-lr', default=0.01, type=float, help='learning rate')\nparser.add_argument('-save', default=1, type=int, help='save model state_dict')\nparser.add_argument('-dropout', default=0.3, type=float, help='dropout ratio')\nparser.add_argument('-verbose', default=1, type=int, help='Whether to show the performance of each epoch (0 or 1)')\npars = parser.parse_args()\n\nif not torch.cuda.is_available():\n pars.use_cuda = 0\n\nclass FM(nn.Module):\n def __init__(self, features_M, field_size, embedding_size, epochs, metric_type, learning_rate, l2,\n dropout, pretrain, save_path, verbose, use_cuda, random_seed=2021):\n super(FM, self).__init__()\n self.field_size = field_size\n self.embedding_size = embedding_size\n self.epochs = epochs\n self.learning_rate = learning_rate\n self.l2 = l2\n self.dropout = dropout\n self.metric_type = metric_type\n self.verbose = verbose\n self.random_seed = random_seed\n self.features_M = features_M\n self.pretrain = pretrain\n self.use_cuda = use_cuda\n self.save_path = save_path\n self.num_pair = self.field_size * (self.field_size - 1) // 2\n\n self.train_rmse, self.valid_rmse, self.test_rmse = [], [], []\n\n np.random.seed(self.random_seed)\n torch.manual_seed(self.random_seed)\n torch.cuda.manual_seed(self.random_seed)\n\n self.bias = nn.Parameter(torch.tensor([.0]))\n self.fm_1st_embedding = nn.Embedding(self.features_M, 1)\n self.fm_2nd_embedding = nn.Embedding(self.features_M, self.embedding_size)\n\n nn.init.uniform_(self.fm_1st_embedding.weight.data, 0.0, 0.0)\n nn.init.normal_(self.fm_2nd_embedding.weight.data, 0, 0.01)\n\n self.dropout_layer = nn.Dropout(self.dropout)\n\n def forward(self, xi):\n fm_1st_embedding = self.fm_1st_embedding(xi).squeeze()\n fm_2nd_embedding = self.fm_2nd_embedding(xi)\n\n interaction_part1 = torch.pow(torch.sum(fm_2nd_embedding, 1), 2)\n interaction_part2 = torch.sum(torch.pow(fm_2nd_embedding, 2), 1)\n\n fm_2nd_order = 0.5 * torch.sub(interaction_part1, interaction_part2)\n fm_2nd_order = self.dropout_layer(fm_2nd_order)\n \n total_sum = torch.sum(fm_1st_embedding, 1) + torch.sum(fm_2nd_order, 1) + self.bias\n return total_sum\n\n def fit(self, train_data, valid_data, test_data):\n optimizer = torch.optim.Adagrad(self.parameters(), lr=self.learning_rate, weight_decay=0)\n criterion = nn.MSELoss(reduction='sum')\n if self.verbose:\n t2 = time()\n init_train = self.evaluate(train_data)\n init_valid = self.evaluate(valid_data)\n print(\"Init \\t train=%.4f, validation=%.4f [%.1f s]\" % (init_train, init_valid, time() - t2))\n\n for epoch in range(self.epochs):\n model = self.train()\n t1 = time()\n for (xi, y) in train_data:\n xi = xi.long()\n y = y.float()\n if self.use_cuda:\n xi, y = xi.cuda(), y.cuda()\n optimizer.zero_grad()\n y_pred = model(xi)\n loss = criterion(y, y_pred)\n loss.backward()\n optimizer.step()\n t2 = time()\n train_result = self.evaluate(train_data)\n valid_result = self.evaluate(valid_data)\n self.train_rmse.append(train_result)\n self.valid_rmse.append(valid_result)\n if self.verbose > 0 and epoch % self.verbose == 0:\n print(\"Epoch %d [%.1f s]\\t train=%.4f, validation=%.4f [%.1f s]\"\n % (epoch + 1, t2 - t1, train_result, valid_result, time() - t2))\n test_result = self.evaluate(test_data)\n self.test_rmse.append(test_result)\n print(\"Epoch %d [%.1f s]\\t test=%.4f [%.1f s]\"\n % (epoch + 1, t2 - t1, test_result, time() - t2))\n\n if self.eva_termination(self.valid_rmse):\n break\n \n if self.pretrain == -1:\n bias = model.bias.cpu().detach().numpy()\n fm_1st_embedding = model.fm_1st_embedding.cpu().weight.data.numpy()\n fm_2nd_embedding = model.fm_2nd_embedding.cpu().weight.data.numpy()\n np.save('../pretrain/bias.npy', bias)\n np.save('../pretrain/fm_1st.npy', fm_1st_embedding)\n np.save('../pretrain/fm_2nd.npy', fm_2nd_embedding)\n\n if self.save_path != '':\n torch.save(model.state_dict(), save_path)\n\n def eva_termination(self, valid):\n if len(valid) > 5:\n if valid[-1] > valid[-2] and valid[-2] > valid[-3] and valid[-3] > valid[-4] and valid[-4] > valid[-5]:\n return True\n return False\n\n def evaluate(self, data_loader):\n model = self.eval()\n y_pred = []\n y_true = []\n with torch.no_grad():\n for (xi, y) in data_loader:\n xi = xi.long()\n y = y.float()\n if self.use_cuda:\n xi, y = xi.cuda(), y.cuda()\n outputs = model(xi)\n y_pred.extend(outputs.cpu().data.numpy())\n y_true.extend(y.cpu().data.numpy())\n predictions_bounded = np.maximum(y_pred, np.ones(data_loader.dataset.__len__()) * min(y_true))\n predictions_bounded = np.minimum(predictions_bounded, np.ones(data_loader.dataset.__len__()) * max(y_true))\n RMSE = math.sqrt(mean_squared_error(y_true, predictions_bounded))\n MAE = mean_absolute_error(y_true, predictions_bounded)\n if self.metric_type == 'MAE':\n return MAE\n else:\n return RMSE\n\n\nif __name__ == '__main__':\n\n data = LoadData(pars.path, pars.dataset)\n save_path = ''\n if pars.save:\n save_path = '../save/' + pars.dataset + '/' + pars.metric + '/FM.pt' \n model = FM(features_M=data.features_M, field_size=pars.field_size, embedding_size=pars.embedding_size,\n epochs=pars.epochs, metric_type=pars.metric, l2=pars.l2, learning_rate=pars.lr, dropout=pars.dropout, \n pretrain=pars.pretrain, save_path=save_path, use_cuda=pars.use_cuda, verbose=pars.verbose)\n model = model.cuda()\n train_dataset = FrappeDataSet(data.Train_data)\n valid_dataset = FrappeDataSet(data.Validation_data)\n test_dataset = FrappeDataSet(data.Test_data)\n train_DataLoader = DataLoader(train_dataset, batch_size=pars.batch_size, shuffle=True, num_workers=1)\n valid_DataLoader = DataLoader(valid_dataset, batch_size=pars.batch_size, shuffle=False, num_workers=1)\n test_DataLoader = DataLoader(test_dataset, batch_size=pars.batch_size, shuffle=False, num_workers=1)\n t1 = time()\n model.fit(train_DataLoader, valid_DataLoader, test_DataLoader)\n\n best_valid_score = 0\n best_valid_score = min(model.valid_rmse)\n best_epoch = model.valid_rmse.index(best_valid_score)\n print(\"Best Iter(validation)= %d\\t train = %.4f, valid = %.4f, test = %.4f, [%.1f s]\"\n % (best_epoch + 1, model.train_rmse[best_epoch], model.valid_rmse[best_epoch], model.test_rmse[best_epoch], time() - t1))","sub_path":"code/FM.py","file_name":"FM.py","file_ext":"py","file_size_in_byte":8590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"212139926","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import print_function\r\n \r\nfrom pprint import pprint\r\nimport numpy as np\r\n\r\nM = 6\r\n\r\ndef pg_eq(p,q):\r\n return (np.cross(p,q) % M == 0).all()\r\n\r\ndef incident(p, l):\r\n return not (np.dot(p,l) % M)\r\n\r\ndef join(p,q):\r\n return np.cross(p, q) % M\r\n\r\ndef meet(l,m):\r\n return np.cross(l, m) % M\r\n\r\ndef collinear(p, q, r):\r\n return incident(join(p,q), r)\r\n\r\ndef concurrent(l, m, n):\r\n return incident(meet(l,m), n)\r\n\r\ndef coI(L):\r\n if len(L) < 3: return True\r\n p , q = L[0], L[1]\r\n assert not pg_eq(p,q)\r\n for r in L[2:]:\r\n if not collinear(p,q,r): return False\r\n return True\r\n\r\ndef persp(L, M):\r\n if len(L) != len(M): return False\r\n if len(L) < 3: return True\r\n pL , qL = L[0], L[1]\r\n pM , qM = M[0], M[1]\r\n assert not pg_eq(pL,qL)\r\n assert not pg_eq(pM,qM)\r\n assert not pg_eq(pL,pM)\r\n assert not pg_eq(qL,qM)\r\n O = meet(join(pL,pM), join(qL,qM))\r\n for rL, rM in zip(L[2:],M[2:]):\r\n if not collinear(rL, rM, O): return False\r\n return True\r\n\r\ndef check_pappus(A, B, C, D, E, F):\r\n G = meet(join(A,E), join(B,D))\r\n H = meet(join(A,F), join(C,D))\r\n I = meet(join(B,F), join(C,E))\r\n assert collinear(G, H, I)\r\n\r\ndef check_desargue(A, B, C, D, E, F):\r\n a = join(B,C)\r\n b = join(A,C)\r\n c = join(B,A)\r\n d = join(E,F)\r\n e = join(D,F)\r\n f = join(E,D)\r\n \r\n b1 = persp([A,B,C],[D,E,F])\r\n b2 = persp([a,b,c], [d,e,f])\r\n if b1: assert b2\r\n else: assert not b2\r\n\r\nif __name__ == \"__main__\":\r\n p = np.array([1, 3, 2])\r\n q = np.array([-2, 1, -1])\r\n r = np.array([2, -2, 1])\r\n s = np.array([2, 2, 3])\r\n t = np.array([2, -2, 2])\r\n assert incident(p,join(p,q))\r\n print(coI([p,q,p+q,p-q])) # True\r\n print(persp([p,q,p+q], [r, p+r, p])) # False\r\n check_pappus(p, q, p+q, r, s, r-s)\r\n O = meet(join(p,s), join(q,t))\r\n r = join(p,q)\r\n u = O - r\r\n # check_desargue(p,q,r,s,t,u)\r\n # l = np.array([1,2,1])\r\n cnt = 0\r\n for i in range(M):\r\n for j in range(M):\r\n for k in range(M):\r\n p = np.array([i,j,k])\r\n count = 0\r\n for i2 in range(M):\r\n for j2 in range(M):\r\n for k2 in range(M):\r\n q = np.array([i2,j2,k2])\r\n if (np.cross(p,q) % M == 0).all():\r\n count += 1\r\n if count != M: \r\n print(count,p)\r\n cnt += 1\r\n print(cnt)\r\n p = np.array([0,3,0])\r\n for i in range(M):\r\n for j in range(M):\r\n for k in range(M):\r\n q = np.array([i,j,k])\r\n if (np.cross(p,q) % M == 0).all():\r\n print(q)\r\n\r\n\r\n","sub_path":"test_ring.py","file_name":"test_ring.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"204446700","text":"'''\nA3C network for RL learning\nenvironment of The Pendulum example.\n''' \n\nimport tensorflow as tf\nimport numpy as np \nimport gym\nimport matplotlib.pyplot as plt \n\nimport multiprocessing\nimport threading \nimport os \nimport shutil\n\n############ global variable ###################\n\n# for thr net\nN_WORKERS = multiprocessing.cpu_count()\nMAX_EP_STEP = 200 # most steps in a ep\nMAX_GLOBAL_EP = 2000 # most ep in a train_op\nGLOBAL_NET_SCOPE = 'Global_Net'\nUPDATE_GLOBAL_ITER = 10 # update global net every 10 tiers \nGAMMA = 0.9 # hyperparamters of Q-learning\nENTROPY_BETA = 0.01 \nLR_A = 0.0001 # learning rate for actor\nLR_C = 0.001 # learning rate for critic\nGLOBAL_RUNNING_R = [] # running reward\nGLOBAL_EP = 0 \n\n# for the envrionment\nGAME = 'Pendulum-v0'\nenv = gym.make(GAME)\nN_S = env.observation_space.shape[0] # dimension of statement\nN_A = env.action_space.shape[0] #dimension of action\nA_BOUND = [env.action_space.low, env.action_space.high] # bound of action\n\n\n############# define ACNet ###################\nclass ACNet(object):\n\tdef __init__(self, scope, globalAC):\n\n\t\t# in the __init__ , we defined some important variables to make some function\n\t\t# such as define loss, train_op\n\t\t# define some important tensor graph ...\n\n\t\tif scope == GLOBAL_NET_SCOPE: # let us make a global net\n\n\t\t\twith tf.variable_scope(scope):\n\n\t\t\t\t# give me some placeholders, come on !\n\t\t\t\tself.s = tf.placeholder(tf.float32, [None, N_S],'S')\n\n\t\t\t\t# the network will return para according to self.s\n\t\t\t\t# para of action net and critic net\n\t\t\t\tself.a_para, self.c_para = self._build_net(scope)[-2:]\n\n\t\telse: # let us make a local worker network\n\t\t\twith tf.variable_scope(scope):\n\n\t\t\t\t# give me some placeholder to give the net\n\n\t\t\t\t# this is the input of net\n\t\t\t\tself.s = self.s = tf.placeholder(tf.float32, [None, N_S],'S')\n\n\t\t\t\t# this is the action from memory\n\t\t\t\tself.a_memory = tf.placeholder(tf.float32, [None, A_S],'A')\n\n\t\t\t\t# this is the value target of q_value\n\t\t\t\tself.v_target = tf.placeholder(tf.float32, [None, 1],'v_target')\n\n\t\t\t\t# the network will return para according to self.s\n\t\t\t\t# para of action net and critic net\n\t\t\t\t# mu and sigma are the output about chosen action from actio_net\n\t\t\t\t# mu and sigma are the parameters of a normal distribution\n\t\t\t\t# self.v is the value of this statement\n\t\t\t\tmu, sigma, self.v, self.a_para, self.c_para = self._build_net(scope)\n\n\t\t\t\t# we need self,v_target and self.v to grt c_loss \n\t\t\t\ttd = tf.subtract(self.v_target, self.v, name ='td_error')\n\t\t\t\t# this is the the loss for q_learning , for the train_operation of critic_net\n\n\t\t\t\twith tf.variable_scope('c_loss'):\n\t\t\t\t\tself.c_loss = tf.reduce_mean(tf.squared(td))\n\n\n\t\t\t\twith tf.variable_scope('get_action_distribution'):\n\t\t\t\t\tmu = mu*A_BOUND[1]\n\t\t\t\t\tsigma += 1e-4\n\t\t\t\t\tnormal_dist = tf.distributions.Normal(mu, sigma)\n\n\n\t\t\t\twith tf.variable_scope('a_loss'):\n\t\t\t\t\t# we need the action from memory to get a_loss\n\t\t\t\t\tlog_prob = normal.dist.log_prob(self.a_memory)\n\n\t\t\t\t\terror = log_prob*td\n\n\t\t\t\t\tentropy = normal_dist.entropy() # encourage exploration\n\n\t\t\t\t\terror = ENTROPY_BETA * entropy + error\n\n\t\t\t\t\tself.a_loss = tf.reduce_mean(error)\n\n\t\t\t\twith tf.variable_scope('chosen_action'):\n\t\t\t\t\t# use the action_net of local net to choose action\n\t\t\t\t\tself.a = tf.clip_by_value(\n\t\t\t\t\t\t\t\t\t\t\ttf.squeeze(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnormal_dist.sample(1),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taxis = 0\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\tA_BOUND[0],\n\t\t\t\t\t\t\t\t\t\t\tA_BOUND[1]\n\t\t\t\t\t\t\t\t\t\t\t)\n\n\t\t\t\twith tf.variable_scope('local_gradient'):\n\t\t\t\t\t# get the gradient of local net\n\t\t\t\t\t# to train local network and update global network\n\t\t\t\t\tself.a_grad = tf.gradient(self.a_loss, self.a_para)\n\t\t\t\t\tself.c_grad = tf.gradient(self.c_loss, self.c_para)\n\n\t\t\t\twith tf.variable_scope('sync'):\n\t\t\t\t\t# todo\n\t\t\t\t\tpass\n\n\n\t\t\t\twith tf.variable_scope('pull'):\n\t\t\t\t\t# pull the para of global action_net to the local action_net\n\t\t\t\t\tself.pull_a_para_op = [local_para.assign(global_para) for local_para, global_para in zip(self.a_para, globalAC.a_para)]\n\n\t\t\t\t\t# pull the para of global critic_net to the local critic_net\n\t\t\t\t\tself.pull_c_para_op = [local_para.assign(global_para) for local_para, global_para in zip(self.c_para, globalAC.c_para)]\n\n\n\t\t\t\twith tf.variable_scope('push'):\n\t\t\t\t\t# push the gradients of training to the global net\n\t\t\t\t\t# use the gradients caculated from local net to train global net\n\n\t\t\t\t\tself.update_gradient_action_op = optimizer_action.apply_gradients(zip(self.a_grad, globalAC.a_para))\n\t\t\t\t\tself.update_gradient_critic_op = optimizer_critic.apply_gradients(zip(self.c_para, globalAC.c_para))\n\n\n\n\tdef _build_net(self, scope):\n\t\t# to define a network structure for action_net ,critic_net in global and local network\n\t\tw_init = tf.random_normal_initializer(0.0, 0.1)\n\n\t\twith tf.variable_scope('actor'):\n\t\t\t# we will get some normal_distributions of action, number of distributions is N_A\n\t\t\toutput_a = tf.layers.dense(\n\t\t\t\t\t\t\t\t\t\tself.s,\n\t\t\t\t\t\t\t\t\t\t20,\n\t\t\t\t\t\t\t\t\t\ttf.nn.relu6,\n\t\t\t\t\t\t\t\t\t\tkernel_initializer = w_init,\n\t\t\t\t\t\t\t\t\t\tname = 'output_a'\n\t\t\t\t\t\t\t\t\t\t)\n\n\t\t\tmu = tf.layers.dense( # get the mu of a normal distribution of action, dim of mu is N_A\n\t\t\t\t\t\t\t\t\toutput_a,\n\t\t\t\t\t\t\t\t\tN_A,\n\t\t\t\t\t\t\t\t\ttf.nn.tanh,\n\t\t\t\t\t\t\t\t\tkernel_initializer = w_init,\n\t\t\t\t\t\t\t\t\tname = 'mu'\n\t\t\t\t\t\t\t\t)\n\n\t\t\tsigma = tf.layers.dense( # get the sigma of a normal distribution of action, dim of sigma is N_A\n\t\t\t\t\t\t\t\t\toutput_a,\n\t\t\t\t\t\t\t\t\tN_A,\n\t\t\t\t\t\t\t\t\ttf.nn.softplus,\n\t\t\t\t\t\t\t\t\tkernel_initializer = w_init,\n\t\t\t\t\t\t\t\t\tname = 'sigma'\n\t\t\t\t\t\t\t\t)\n\n\t\twith tf.variable_scope('critic'):\n\t\t\toutput_c = tf.layers.dense(\n\t\t\t\t\t\t\t\t\t\tself.s,\n\t\t\t\t\t\t\t\t\t\t20,\n\t\t\t\t\t\t\t\t\t\ttf.nn.relu6,\n\t\t\t\t\t\t\t\t\t\tkernel_initializer = w_init,\n\t\t\t\t\t\t\t\t\t\tname = 'output_c'\n\t\t\t\t\t\t\t\t\t\t)\n\n\t\t\tv = tf.layers.dense( # we get the value of this statement self.s\n\t\t\t\t\t\t\t\toutput_c,\n\t\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\t\tkernel_initializer = w_init,\n\t\t\t\t\t\t\t\tname = 'v'\n\t\t\t\t\t\t\t\t)\n\n\t\ta_para = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope = scope+'/actor')\n\t\tc_para = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope = scope+'/critic')\n\n\t\treturn mu, sigma, v, a_para, c_para\n\n \n\tdef update_global(self, feed_dict): # push the gradients to the global net to train\n\t\t# to train global net using the gradiients caculated from local net\n\n\t\tSESS.run([self.update_gradient_action_op, self.update_gradient_critic_op], feed_dict)\n\t\t# some data is from placeholder\n\n\tdef pull_global(self): #pull the new para from global net to local net\n\t\tSESS.run([self.pull_a_para_op, self.pull_c_para_op])\n\n\tdef choose_action(self, s):\n\t\t# we need the statement of this moment to caculate a action\n\t\ts = s[np.new.axis, :]\n\n\t\treturn SESS.run(self.a, {self.s:s})[0]\n\t\t# we need figure out the structure of output action\n\nclass Worker(object):\n\t\"\"\" define local worker net , and train with envrionment itself \"\"\"\n\tdef __init__(self, name, globalAC):\n\t\t\n\t\tself.env = gym.make(GAME).unwarpped\n\n\t\tself.name = name\n\n\t\tself.AC = ACNet(name,globalAC)\n\t\t# globalAC is the global net connecting with the local net\n\n\tdef work(self):\n\t\tglobal GLOBAL_RUNNNING_R, GOBAL_EP\n\n\t\ttotal_step = 1\n\t\tbuffer_s = []\n\t\tbuffer_a = []\n\t\tbuffer_r = []\n\n\t\t# let us train \n\t\twhile not COORP.should_stop() and GLOBAL_EP < MAX_GLOBAL_EP:\n\t\t\ts = self.env.reset()\n\n\t\t\tep_r = 0\n\n\t\t\t# let us do every step\n\t\t\tfor i in range(MAX_EP_STEP):\n\n\t\t\t\t# get the action for now\n\t\t\t\ta = self.ACNet.choose_action(s)\n\n\t\t\t\t# interaction with envrionment\n\t\t\t\ts_, r, done, info = self.env.step(a)\n\n\t\t\t\tdone = True if i ==MAX_EP_STEP else False\n\n\t\t\t\tep_r += r\n\n\t\t\t\t# store\n\t\t\t\tbuffer_s.append(s)\n\t\t\t\tbuffer_a.append(a)\n\t\t\t\tbuffer_r.append((r+8)/8)\n\n\t\t\t\t# shuold update global net ?------------------------------------\n\t\t\t\tif total_step%UPDATE_GLOBAL_ITER ==0 or done:\n\t\t\t\t\tif done:\n\t\t\t\t\t\tv_s_ = 0 \n\t\t\t\t\t\t# it is the value of next statement\n\t\t\t\t\t\t# if it is done, we assume it is 0\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tv_s_ = SESS.run(self.AC.v, {self.AC.s:s_[np.newaxis, :]})[0, 0]\n\n\t\t\t\t\tbuffer_v_target = []\n\t\t\t\t\t#store the v_target for caculating the loss\n\n\t\t\t\t\tfor r in buffer_r[::-1]: # reverse the buffer_r\n\t\t\t\t\t\tv_target_element = r + GAMMA*v_s_\n\t\t\t\t\t\tbuffer_v_target.append(v_target_element)\n\n\t\t\t\t\tbuffer_v_target.reverse()\n\n\t\t\t\t\tbuffer_s = np.vstack(buffer_s)\n\t\t\t\t\tbuffer_a = np.vstack(buffer_a)\n\t\t\t\t\tbuffer_v_target = np.vstack(buffer_v_target)\n\n\t\t\t\t\t# update global_net para with gradients from local net \n\t\t\t\t\t# and give the new para from global net to local net\n\t\t\t\t\tfeed_dict = {\n\t\t\t\t\t\t\t\t\tself.AC.s: buffer_s,\n\t\t\t\t\t\t\t\t\tself.AC.a_memory: a,\n\t\t\t\t\t\t\t\t\tself.AC.v_target: buffer_v_target\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t# here are caculating gradients from local net\n\t\t\t\t\t# and push them to global net to update para of global net\n\t\t\t\t\tself.AC.update_global(feed_dict)\n\n\t\t\t\t\t# and givr the new para to local net\n\t\t\t\t\tself.AC.pull_global()\n\n\t\t\t\t\tbuffer_s = []\n\t\t\t\t\tbuffer_a = []\n\t\t\t\t\tbuffer_r = []\n\n\n\n\t\t\t\ts = s_\n\t\t\t\ttotal_step += 1\n\n\t\t\t\tif done:\n\t\t\t\t\t# put running reward of every step into GLOBAL_RUNNING_R\n\t\t\t\t\tif len(GLOBAL_RUNNING_R) == 0: # record running episode reward\n\t\t\t\t\t\tGLOBAL_RUNNING_R.append(ep_r)\n\t\t\t\t\telse:\n\t\t\t\t\t\tGLOBAL_RUNNING_R.append(0.9 * GLOBAL_RUNNING_R[-1] + 0.1 * ep_r)\n\t\t\t\t\tprint(self.name,\"Ep:\", GLOBAL_EP,\"| Ep_r: %i\" % GLOBAL_RUNNING_R[-1])\n\t\t\t\t\tGLOBAL_EP += 1\n\t\t\t\t\tbreak\n\n\nif __name__ == \"__main__\":\n\tSESS = tf.Session()\n\n\twith tf.device(\"/cpu:0\"):\n\n\t\toptimizer_action = tf.train.RMSPropOptimizer(LR_A, name = 'RMSProp_ACTION')\n\t\toptimizer_critic = tf.train.RMSPropOptimizer(LR_C, name = 'RMSProp_CRITIC')\n\n\t\tglobalAC = ACNet(GLOBAL_NET_SCOPE,None)\n\t\t# define the global net and we only need its parameters\n\n\t\tworkers = [] # a list to store local nets\n\n\t\tfor i in range(N_WORKERS):\n\t\t\ti_name = \"%s_worker\"%i\n\t\t\tworkers.append( Worker(i_name, globalAC) )\n\n\t\tCOORD = tf.train.Coordinator()\n\n\t\tSESS.run(tf.global_variables_initializer())\n\n\t\tworker_threads = []\n\n\t\tfor worker in workers:\n\t\t\tjob = lambda : worker.work() \n\t\t\tt = threading.Thread(target = job)\n\t\t\tt.start()\n\t\t\tworker_threads.append(t)\n\n\t\tCOORD.join(worker_threads)\n\n\tplt.plot(np.arange(len(GLOBAL_RUNNING_R)), GLOBAL_RUNNING_R)\n\tplt.xlabel('step')\n\tplt.ylabel('total moving reward')\n\tplt.show()\n","sub_path":"RL/A3C.py","file_name":"A3C.py","file_ext":"py","file_size_in_byte":10026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"435611211","text":"import os\nsite = \"\"\"SEMESTRE 1 202\n ELEMENTOS DE COMPUTACION GR 7\n APRECIACION DE CINE GR 3\n CALCULO Y ALGEBRA LINEAL GR 8\n DIBUJO TECNICO GR 3\n FISICA GENERAL II GR 7\n INTR. TEC. CIENCIA Y TECNOLOGIA GR 12\n LABORATORIO FISICA GENERAL II GR 11\n COMUNICACION ESCRITA GR 25\"\"\"\n\ncourses = site.split(\"\\n\")\nsemester = courses[0]\ncourses.pop(0)\nfor place, course in enumerate(courses):\n course = course.strip()\n courses[place] = course\npath = \"C:/Users/Mariano/Desktop/Mariano/Documents\"\nos.mkdir(path + \"/\" + semester)\nfor course in courses:\n course_path = path + \"/\" + semester + \"/\" + course\n os.mkdir(course_path)\n print(\"creating directory {}\".format(course_path))","sub_path":"PyProjects/Practices/mkdir.py","file_name":"mkdir.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"186954006","text":"from scrapy.spider import BaseSpider\nfrom scrapy.selector import Selector\nimport re\nfrom tutorial.items import lbpItem\n\nclass lbpSpider(BaseSpider):\n name = \"lbp\"\n allowed_domains = [\"http://lbp.me\"]\n start_urls = [\n \"http://lbp.me/search?q=\"\n ]\n\n def parse(self, response):\n sel = Selector(response)\n sites = sel.xpath('//div[@class = \"event-details\"]/h3/a/@href').extract()\n items = []\n \n item = lbpItem()\n item['creator'] = sel.xpath('//p[@class=\"level-creator\"]/a/@href').extract()\n item['title'] = sel.xpath('//div[@class=\"event-details\"]/h3/a/text()').extract()\n # item['thumbsup'] = sel.xpath('//ul[@class=\"feedback clearfix\"]/li')[0].extract()\n item['thumbsup_num'] = sel.xpath('//ul[@class=\"feedback clearfix\"]/li[@class=\"thumbsup\"]/text()').extract()\n # item['hearted'] = sel.xpath('//ul[@class=\"feedback clearfix\"]/li')[1].extract()\n item['hearted_num'] = sel.xpath('//ul[@class=\"feedback clearfix\"]/li[@class=\"hearted\"]/text()').extract()\n # item['played'] = sel.xpath('//ul[@class=\"feedback clearfix\"]/li')[2].extract()\n item['played_num'] = sel.xpath('//ul[@class=\"feedback clearfix\"]/li[@class=\"plays\"]/text()').extract()\n # item['published'] = sel.xpath('//ul[@class=\"feedback clearfix\"]/li')[3].extract()\n item['published_num'] = sel.xpath('//ul[@class=\"feedback clearfix\"]/li[@class=\"listed\"]/text()').extract()\n item['first_published'] = sel.xpath('//div[@id=\"moar-info\"]/ul/li/text()').extract()\n\n items.append(item)\n return items\n\n\n\n","sub_path":"Scrapy_project/spiders/lbp_spider.py","file_name":"lbp_spider.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234695187","text":"from IPython.core.display import display_html, HTML\n\ndef to_html_table(res, style=None):\n html = ''\n html += ''.join(res.keys) + ''\n html += ''.join([''.join([str(cell) for cell in row]) for row in list(res)])\n return html + ''\n\ndef side_by_side(l, r):\n s = \"display: inline-block;\"\n html = to_html_table(l, style=s) + ' ' + to_html_table(r, style=s)\n display_html(HTML(data=html))\n","sub_path":"lectures/lecture20-21-22/display_tools.py","file_name":"display_tools.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"132675443","text":"from data import *\nfrom pathlib import Path\n#from pandas import read_csv\nfrom urllib.parse import unquote\nimport json\nimport numpy as np\nimport hashlib\n\ndata_dir = '../Data/'\n\n'''def get_dest_file(dt):\n data_source = get_data_source(dt)\n source_file = get_data_file(dt)\n dest_file = 'processed_'+source_file\n dest_file = Path(data_dir,data_source,dest_file)\n return dest_file\n\ndef load_processed_data(dt,d_file):\n delm = get_delimiter(dt)\n cols = get_use_columns(dt)\n print(\"reading from %s \" %d_file)\n df = read_csv(d_file,sep=delm,names=cols,header=None,dtype=object)\n return df\n'''\ndef save_data(dt,df):\n dest_file = get_dest_file(dt)\n df.to_csv(dest_file, sep='\\t', header=False,index=False)\n\n'''def load_source_data(dt):\n data_source = get_data_source(dt)\n source_file = get_data_file(dt)\n source_file = Path(data_dir,data_source,source_file)\n print(\"reading from %s \" %source_file)\n delm = get_delimiter(dt)\n cols = get_column_names(dt)\n use_cols = get_use_columns(dt)\n skr = get_rows_to_skip(dt)\n df = read_csv(source_file,sep=delm,names=cols,usecols=use_cols,skiprows=skr,header=None)\n return df\n'''\ndef preprocess(dt):\n dest_file = get_dest_file(dt)\n if dest_file.is_file():\n df = load_processed_data(dt,dest_file)\n return df\n \n df = load_source_data(dt)\n print(\"total number of queries (before preprocessing): %d\" % len(df.index))\n df = df[df['query_text'].notna()] # we get rid of the rows with query_text is na\n df['query_text'] = df['query_text'].apply(unquote) #we noticed that some queries are url encoded\n df['query_text'] = df['query_text'].str.lower() #we dont differntiate between lower and upper case\n #nonasc_df = df[~df.query_text.map(str.isascii)] # get the statistics of non-ascii queries\n #null_cols = df.columns[df.isnull().any()]\n #print(df[null_cols].isnull().sum())\n #sz_series = df.groupby(['session_id']).size()\n #print(df.loc[df.session_id == ma,['session_id','query_text']])\n df['query_text'] = df['query_text'].str.replace('http\\S+', ' ',regex=True) #we get rid of url\n df['query_text'] = df['query_text'].str.replace('[-_:,.]',' ',regex=True) #to normalize the use of - and _. we replace it with space\n df['query_text'] = df['query_text'].str.replace(r'[^\\w\\s]','',regex=True) #replace all non-langauge and space characters\n df = df[df.query_text.map(str.isascii)] # for the time being we deal with only english based queries\n df.query_text = df['query_text'].str.replace('\\s+',' ',regex=True)\n #df['query_text'] = df['query_text'].str.strip()\n df = df[df['query_text'].str.strip().astype(bool)]\n df.query_text = df['query_text'].str.replace('^\\d[\\.\\s\\d]+$','0',regex=True) \n #df = df[~df.id.str.isnumeric()]\n df = df[~ df.query_text.str.isnumeric()]\n dd = df[['session_id','query_text']]\n df = df[dd.ne(dd.shift()).any(1)] # to get rid of the continous repetations\n df = df[df.groupby('session_id',sort=False)['session_id'].transform('size').between(4, 50, inclusive=True)]\n #df['hashed'] = df.query_text.apply(lambda x: hashlib.md5(x.encode()).hexdigest())\n #df = df[df.groupby('session_id')['session_id'].transform('size') > 4]\n #df = df[df.groupby('session_id')['session_id'].transform('size') < 51]\n print(\"total number of queries (after preprocessing): %d\" % len(df.index))\n print(\"group statistics\")\n print(\" %s\" % df.groupby(['session_id']).size().describe())\n #(a,b) = tuple(dg.size().agg(['idxmax','max']))\n #(a,b) = tuple(dg.size().agg(['idxmin','min']))\n #print(df.loc[df.session_id == a,['session_id','query_text']])\n save_data(dt,df)\n return df\n\ndef tokenize(dt,df):\n from tokenizers import Tokenizer\n from tokenizers.pre_tokenizers import WhitespaceSplit\n from tokenizers import normalizers\n from tokenizers.normalizers import NFD, StripAccents\n from tokenizers.models import WordLevel\n from tokenizers.trainers import WordLevelTrainer\n #from tokenizers.models import WordPiece\n #from tokenizers.trainers import WordPieceTrainer\n #from tokenizers import ByteLevelBPETokenizer\n #from tokenizers.trainers import WordLevelTrainer\n #from tokenizers.models import BPE\n #from tokenizers.trainers import BpeTrainer\n #print(df.head())\n #print(df.query_text.head())\n #print(df.query_text.to_list())\n #exit(0)\n data_source = get_data_source(dt)\n token_file = Path(data_dir,data_source,'tokenizer.json')\n vocab_file = Path(data_dir,data_source,'vocab.txt')\n corpus_file = Path(data_dir,data_source,'corpus.txt')\n if not corpus_file.is_file():\n print(\"corpus file is generating\")\n corpus = df.groupby('session_id', sort=False)['query_text'].apply(' [sep] '.join)\n corpus.to_csv(corpus_file,header=False,index=False)\n else:\n print(\"corpus file already generated\")\n \n if vocab_file.is_file() and corpus_file.is_file():\n print(\"corpus and token files already generated\")\n return 0\n\n tokenizer = Tokenizer(WordLevel(unk_token=\"[unk]\"))\n tokenizer.normalizer = normalizers.Sequence([NFD(), StripAccents()])\n tokenizer.pre_tokenizer = WhitespaceSplit()\n trainer = WordLevelTrainer(vocab_size=30000,min_frequency=3,special_tokens=[\"[unk]\", \"[bos]\", \"[eos]\", \"[sep]\", \"[pad]\"])\n tokenizer.train_from_iterator(df.query_text.to_list(),trainer)\n tokenizer.model.save('../Data/semanticscholar/tokenizer/wordlevel')\n \n\n '''tokenizer = Tokenizer(BPE(unk_token=\"[unk]\"))\n pre_tokenizer = WhitespaceSplit()\n trainer = BpeTrainer(min_frequency=2,special_tokens=[\"[unk]\", \"[bos]\", \"[eos]\", \"[sep]\", \"[pad]\"])\n tokenizer.train_from_iterator(df.query_text.to_list(),trainer)\n tokenizer.model.save('../Data/semanticscholar/tokenizer/')\n\n\n tokenizer = Tokenizer(WordLevel(unk_token=\"[unk]\"))\n tokenizer.pre_tokenizer = WhitespaceSplit()\n trainer = WordLevelTrainer(special_tokens=[\"[unk]\", \"[bos]\", \"[eos]\", \"[sep]\"])\n tokenizer.train_from_iterator(df.query_text.to_list(),trainer)\n tokenizer.save(str(token_file)) \n #bert_tokenizer = Tokenizer(WordPiece(unk_token=\"[unk]\"))\n #bert_tokenizer.normalizer = normalizers.Sequence([NFD(), StripAccents()])\n #bert_tokenizer.pre_tokenizer = Whitespace()\n #bert_tokenizer.post_processor = TemplateProcessing(\n # single=\"[bos] $0 [eos]\",\n # special_tokens=[(\"[bos]\", 1),(\"[eos]\", 2),],)\n #trainer = WordPieceTrainer(vocab_size=25000,min_frequency=3,special_tokens=[\"[unk]\", \"[bos]\", \"[eos]\", \"[pad]\", \"[mask]\"])\n #print(df.query_text.to_list())\n #bert_tokenizer.train_from_iterator(df.hashed.to_list(),trainer)\n #bert_tokenizer.save(str(token_file))\n #bert_tokenizer.save_model(directory=data_dir,name='tokenizer')\n #df['range_idx'] = range(0, df.shape[0])\n #df['mean_rank_group'] = df.groupby(['session_id'],sort=False)['range_idx'].transform(np.mean)\n #df['separate_column'] = df['range_idx'] < df['mean_rank_group']\n #df = df.groupby(['session_id'], as_index=False, sort=False)['hashed'].agg(' '.join)\n #df = df.groupby('session_id').agg({'query_text':' '.join}).reset_index()\n with open(token_file) as token_f:\n jdata = json.load(token_f)\n with open(vocab_file, \"w\") as fd:\n for k in jdata['model']['vocab'].keys():\n print(k, file=fd)\n \n #dct = set(' '.join(df.query_text).split())\n #val_cnts = df['query_text'].str.split().explode().value_counts()\n #print(val_cnts[:10])\n #print(val_cnts[-10:])\n #dct = dict(val_cnts)\n #with open(vocab_file, \"w\") as fd:\n # for key in dct:\n # print(key, file=fd)\n\n '''\n\ndef main():\n for dt in dataset:\n df = preprocess(dt)\n tokenize(dt,df)\n \n \n\nif __name__ == '__main__':\n main()\n \n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"314284868","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 7 10:22:58 2020\n\n@author: jguerrero\n\"\"\"\n\n# BOSQUE ALEATORIO\n# Como importar las librerias\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importar el dataset\ndataset = pd.read_csv('Social_Network_ads.csv')\n\nX = dataset.iloc[:, 2:4].values\ny = dataset.iloc[:, 4].values\n\n# Dividir el dataset en entrenamiento y prueba\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) # random_state = 0 SOLO ES PARA QUE SIEMPRE SELECCIONE LOS MISMOS ELEMENTOS\n\n# Ajustar la clasificacion con el conjunto de entrenamiento\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier = RandomForestClassifier(n_estimators = 1000, criterion = 'entropy')\nclassifier.fit(X_train, y_train)\n\n# Prediccion de la clasificacion con el conjunto de prueba\ny_pred = classifier.predict(X_test)\n\n# Evaluar resultados con matriz de confusion\nfrom sklearn.metrics import confusion_matrix\nconf_matrix = confusion_matrix(y_test, y_pred)\n\n# Visualizacion de los resultados\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_train, y_train\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 1),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 500))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Random Forest (Conjunto de Entrenamiento)')\nplt.xlabel('Edad')\nplt.ylabel('Sueldo Estimado')\nplt.legend()\nplt.show()\n","sub_path":"datasets/Part 3 - Classification/Section 20 - Random Forest Classification/random_forest_classification_sbn.py","file_name":"random_forest_classification_sbn.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115338592","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.contrib.gis.geoip import GeoIP\n\n\nclass RedirectToNoSlash(object):\n @staticmethod\n def process_request(request):\n if request.path == '/':\n ip = str(get_client_ip(request))\n g = GeoIP()\n code = g.country(ip)\n if code.get('country_code') == 'RU':\n return HttpResponsePermanentRedirect('/ru/')\n elif code.get('country_code') == 'UA':\n return HttpResponsePermanentRedirect('/uk/')\n else:\n return HttpResponsePermanentRedirect('/en/')\n\n if '__debug__' not in request.path and '/media/' not in request.path:\n if not request.path in ['/uk/', '/ru/', '/en/']:\n if request.path[-1] == '/':\n return HttpResponsePermanentRedirect(request.path[:-1])\n\n# Add by spirit BEGIN:\nclass URLRedirectEN(object):\n @staticmethod\n def process_request(request):\n if all([('_' in request.path), ('/en/' in request.path), ('/en/load' not in request.path)]): # Если url содержит \"_\"\n abs_url = request.path.replace('_', '-') # меняем '_' на '-' в адресе\n return HttpResponsePermanentRedirect(abs_url) # Делаем 301 редирект на нужную страницу\n\nclass URLRedirectRU(object):\n @staticmethod\n def process_request(request):\n if all([('_' in request.path), ('/ru/' in request.path)]): # Если url содержит \"_\"\n abs_url = request.path.replace('_', '-') # меняем '_' на '-' в адресе\n return HttpResponsePermanentRedirect(abs_url) # Делаем 301 редирект на нужную страницу\n\nclass URLRedirectUK(object):\n @staticmethod\n def process_request(request):\n if all([('_' in request.path), ('/uk/' in request.path)]): # Если url содержит \"_\"\n abs_url = request.path.replace('_', '-') # меняем '_' на '-' в адресе\n return HttpResponsePermanentRedirect(abs_url) # Делаем 301 редирект на нужную страницу\n\n\n# Add by spirit END\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\n\ndef get_or_none(classmodel, **kwargs):\n try:\n return classmodel.objects.get(**kwargs)\n except classmodel.DoesNotExist:\n return None\n\n\ndef transliterate_slug(t):\n t = (t.lower().strip().replace('\"', '')).replace(u'\\xa0', u'')\n t = [k for k in t if k in u\" абвгдеёжзийклмнопрстуфхцчшщъыьэюяіїєАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯІЇЄ:;-().,'\"]\n t = ''.join(t)\n symbols = (u\" абвгдеёжзийклмнопрстуфхцчшщъыьэюяіїєАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯІЇЄ:;-().,'\",\n \"-abvgdeejzijklmnoprstufhzcss-y-euaiieABVGDEEJZIJKLMNOPRSTUFHZCSS-Y-EUAIIE--------\")\n tr = dict([(ord(a), ord(b)) for (a, b) in zip(*symbols)])\n return t.translate(tr).replace(' ', '-')\n","sub_path":"apps/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"177511195","text":"w = input('你的体重(kg): ')\nh = input('你的身高(m): ')\nheight = float(h)\nweight = float(w)\nBMI = weight / (height**2)\nif BMI > 32:\n print('胖死你')\nelif BMI > 28:\n print('好胖啊')\nelif BMI > 25:\n print('少吃点')\nelif BMI > 18.5:\n print('漂亮哦')\nelse:\n print('瘦死你')\n","sub_path":"pythonifelse.py","file_name":"pythonifelse.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"283369574","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 27 09:57:45 2018\n\n@author: L1817\n\"\"\"\n#%%\nimport numpy as np\nimport rasterio\nimport scipy.sparse\nimport pandas as pd\nimport geopandas\nimport networkx as nx\nimport pickle\nfrom shapely.geometry import LineString, Point\n\nimport cwl_utilities\n\n# %%\n\n\ndef read_params(fn=r\"/home/inaki/GitHub/dd_winrock/data/params.xlsx\"):\n df = pd.read_excel(fn, engine='openpyxl')\n return df\n\n\ndef peat_depth_map(peat_depth_type_arr):\n peat_depth_arr = np.ones(shape=peat_depth_type_arr.shape)\n # information from excel\n peat_depth_arr[peat_depth_type_arr == 1] = 2. # depth in meters.\n peat_depth_arr[peat_depth_type_arr == 2] = 2.\n peat_depth_arr[peat_depth_type_arr == 3] = 4.\n peat_depth_arr[peat_depth_type_arr == 4] = 0.\n peat_depth_arr[peat_depth_type_arr == 5] = 0.\n peat_depth_arr[peat_depth_type_arr == 6] = 2.\n peat_depth_arr[peat_depth_type_arr == 7] = 4.\n peat_depth_arr[peat_depth_type_arr == 8] = 8.\n\n return peat_depth_arr\n\n\ndef read_raster(raster_filename):\n with rasterio.open(raster_filename) as raster:\n rst = raster.read(1)\n return rst\n\n\ndef preprocess_can_arr_raster(can_arr):\n can_arr[can_arr < 0.5] = 0\n can_arr[abs(can_arr) > 0.5] = 1\n can_arr = np.array(can_arr, dtype=int)\n return can_arr\n\n\ndef preprocess_dem(dem):\n dem[dem < -10] = -9999.0\n dem[np.where(np.isnan(dem))] = -9999.0\n dem[dem > 1e20] = -9999.0 # just in case\n return dem\n\n\ndef preprocess_peat_type(peat_type_arr, dem):\n peat_type_arr[peat_type_arr < 0] = -1\n # fill some nodata values to get same size as dem\n peat_type_arr[(np.where(dem > 0.1) and np.where(peat_type_arr < 0.1))] = 1.\n return peat_type_arr\n\n\ndef preprocess_peat_depth(peat_depth_arr, dem):\n peat_depth_arr[peat_depth_arr < 0] = -1\n # translate number keys to depths\n peat_depth_arr = peat_depth_map(peat_depth_arr)\n # fill some nodata values to get same size as dem\n peat_depth_arr[(np.where(dem > 0.1) and np.where(\n peat_depth_arr < 0.1))] = 1.\n return peat_depth_arr\n\n\ndef mask_non_acquatic_blocks(blocks_arr, can_arr):\n return blocks_arr*can_arr\n\n\ndef resize_study_area(sa, raster):\n return raster[sa[0][0]:sa[0][1], sa[1][0]:sa[1][1]]\n\n\ndef read_preprocess_rasters(sa, wtd_old_rst_fn, can_rst_fn, dem_rst_fn, peat_type_rst_fn, peat_depth_rst_fn, blocks_rst_fn, sensor_loc_fn):\n \"\"\"\n Deals with issues specific to each input raster.\n Corrects nodatas, resizes to selected study area, etc.\n sa: integers giving array slicing to constrain. Study area.\n \"\"\"\n\n wtd_old = read_raster(wtd_old_rst_fn)\n can_arr = read_raster(can_rst_fn)\n dem = read_raster(dem_rst_fn)\n peat_type_arr = read_raster(peat_type_rst_fn)\n peat_depth_arr = read_raster(peat_depth_rst_fn)\n blocks_arr = read_raster(blocks_rst_fn)\n sensor_loc_arr = read_raster(sensor_loc_fn)\n\n # Get mask of canals: 1 where canals exist, 0 otherwise\n can_arr = preprocess_can_arr_raster(can_arr)\n dem = preprocess_dem(dem) # Convert from numpy no data to -9999.0\n # control nodata values, impose same size as dem\n peat_type_arr = preprocess_peat_type(peat_type_arr, dem)\n # nodatas, same size as dem and give peat depth map values\n peat_depth_arr = preprocess_peat_depth(peat_depth_arr, dem)\n # only useful blocks are those that are in water! (I.e., that coincide with a water pixel)\n blocks_arr = mask_non_acquatic_blocks(blocks_arr, can_arr)\n\n # Apply study area restriction\n wtd_old = resize_study_area(sa, wtd_old)\n dem = resize_study_area(sa, dem)\n can_arr = resize_study_area(sa, can_arr)\n peat_depth_arr = resize_study_area(sa, peat_depth_arr)\n peat_type_arr = resize_study_area(sa, peat_type_arr)\n blocks_arr = resize_study_area(sa, blocks_arr)\n sensor_loc_arr = resize_study_area(sa, sensor_loc_arr)\n\n return can_arr, wtd_old, dem, peat_type_arr, peat_depth_arr, blocks_arr, sensor_loc_arr\n\n\ndef read_preprocess_landcover(sa, lc_fn):\n lc = read_raster(lc_fn)\n lc[lc < 0] = 0 # NoData Values\n lc = resize_study_area(sa, lc)\n return lc\n\n\n# Build the adjacency matrix up\ndef _prop_to_neighbours(pixel_coords, rasterized_canals, dem, threshold=0.0, is_diagonal_a_neighbor=False):\n \"\"\"Given a pixel where a canals exists, return list of canals that it would propagate to.\n Info taken for allowing propagation: DEM height.\n Threshold gives strictness of the propagation condition: if 0, then only strictly increasing water tables are propagated.\n If is_diagonal_a_neighbor=True, diagonally adjacent pixels are seen as neighbours.\n \"\"\"\n padded_can_arr = np.pad(rasterized_canals, pad_width=1, mode='constant')\n padded_dem = np.pad(dem, pad_width=1, mode='constant')\n pc0 = pixel_coords[0] + 1\n pc1 = pixel_coords[1] + 1 # plus one bc of padding\n prop_to = []\n\n if is_diagonal_a_neighbor:\n candidate_coords_list = ([(pc0-1, pc1-1), (pc0-1, pc1), (pc0-1, pc1+1),\n (pc0, pc1-1), (pc0, pc1+1),\n (pc0+1, pc1-1), (pc0+1, pc1), (pc0+1, pc1+1)])\n else:\n candidate_coords_list = ([(pc0-1, pc1),\n (pc0, pc1-1), (pc0, pc1+1),\n (pc0+1, pc1)])\n\n for cc in candidate_coords_list:\n if padded_can_arr[cc] > 0: # pixel corresponds to a canal\n if padded_dem[cc] - padded_dem[pc0, pc1] > -threshold:\n prop_to.append(int(padded_can_arr[cc]))\n return prop_to\n\n\ndef label_canal_pixels(can_arr, dem):\n # Convert labels of canals to 1,2,3...\n aux = can_arr.flatten()\n can_flat_arr = np.array(aux)\n aux_dem = dem.flatten()\n\n counter = 1\n for i, value in enumerate(aux):\n # if there is a canal in that pixel and if we have a dem value for that pixel. (Missing dem data points are labelled as -9999)\n if value > 0 and aux_dem[i] > 0:\n can_flat_arr[i] = counter\n counter += 1\n # contains labels and positions of canals\n labelled_canals = can_flat_arr.reshape(can_arr.shape)\n\n return labelled_canals\n\n\ndef gen_can_matrix_and_label_map(labelled_canals, dem):\n \"\"\" Gets canal RASTER FILE and generates adjacency matrix.\n\n Input:\n - labelled canals: output oof label_canal_pixels\n -dem: dem is used as a template\n\n Output:\n - matrix: canal adjacency matrix NumPy array.\n - out_arr: canal raster in NumPy array.\n - can_to_raster_list: list. Pixels corresponding to each canal.\n \"\"\"\n\n n_canals = int(labelled_canals.max() + 1)\n # compute matrix AND dict\n # lil matrix is good to build it incrementally\n matrix = scipy.sparse.lil_matrix((n_canals, n_canals))\n\n c_to_r_list = [0] * n_canals\n for coords, label in np.ndenumerate(labelled_canals):\n if labelled_canals[coords] > 0: # if coords correspond to a canal.\n # label=0 is not a canal. But do not delete it, otherwise everything would be corrido.\n c_to_r_list[int(label)] = coords\n propagated_to = _prop_to_neighbours(\n coords, labelled_canals, dem, threshold=0.0, is_diagonal_a_neighbor=False)\n for i in propagated_to:\n # adjacency matrix of the directed graph\n matrix[int(label), i] = 1\n\n matrix_csr = matrix.tocsr() # compressed row format is more efficient for later\n matrix_csr.eliminate_zeros() # happens in place. Frees disk usage.\n\n return matrix_csr, c_to_r_list\n\n\ndef get_array_indices_by_rows(array_shape):\n rows, cols = np.indices(array_shape)\n indices = np.array(list(zip(rows.flatten(), cols.flatten())))\n final_shape = list(array_shape) + [2] # The 2 comes from the 2D\n\n return indices.reshape(final_shape)\n\n\ndef nearest_neighbors_mask_from_coordinates(array_shape, points_coordinates):\n \"\"\"\n Takes the shape of an array and a set of points within the array and returns a mask\n that contains, for each index in the array, the label of the closest point\n (and closeness is measured by Euclidean distance).\n In this particular application, it is used to know what weather station to \n pick the data from for each pixel.\n NOTE: When two positions are exactly at the same distance, the first\n points_coordinate in order is chosen\n\n Parameters\n ----------\n array_shape : tuple\n The shape of the mask. Computed with numpy's shape\n points_coordinates : list of coordinate tuples\n Each key is used as a value in the mask array. The tuples are used\n to compute the distaance to other elements of the array\n\n Returns\n -------\n mask : np.array\n\n mask_dictionary: dict\n Keys are the values in the returned mask, and values are the corresponding\n point coordinates from the input\n\n \"\"\"\n\n from scipy.spatial import distance\n\n # Check that point coordinates lie inside the array\n mask = np.zeros(shape=array_shape)\n for coord in points_coordinates:\n try:\n mask[coord[0], coord[1]]\n except:\n raise ValueError(\"the coordinates are out of the array's bounds\")\n\n indices_by_row = get_array_indices_by_rows(array_shape)\n\n # Create output dictionary of points\n mask_dictionary = {}\n for npoint, point in enumerate(points_coordinates):\n mask_dictionary[npoint] = point\n\n for row_n, row in enumerate(indices_by_row):\n dists = distance.cdist(row, np.array(points_coordinates))\n mask[row_n] = np.argmin(dists.T, axis=0)\n\n return mask, mask_dictionary\n\n\ndef get_lists_of_node_coords_and_node_heights(raster_src, lines_gpkg):\n # get all unique line edpoints\n nodes_coords = cwl_utilities.get_unique_nodes_in_line_gpkg(lines_gpkg)\n \n nodes_heights = []\n nodes_coords_copy = nodes_coords.copy()\n for i, dem_height in enumerate(raster_src.sample(nodes_coords)):\n if np.isnan(dem_height[0]) or dem_height[0] < 0: # Coordinates are outside the DEM\n # Remove from list of nodes\n nodes_coords_copy.remove(nodes_coords[i])\n else:\n nodes_heights.append(dem_height[0])\n nodes_coords = nodes_coords_copy.copy()\n del nodes_coords_copy\n\n return nodes_coords, nodes_heights\n\n\ndef build_coords_to_height_dict(nodes_coords, nodes_heights):\n return {coords: h for coords, h in zip(nodes_coords, nodes_heights)}\n\n\ndef build_number_nodes_to_coord_dict(nodes_coords):\n return {n: (coord_x, coord_y) for n, (coord_x, coord_y) in enumerate(nodes_coords)}\n\n\ndef build_coords_to_number_nodes_dict(nodes_coords):\n return {(coord_x, coord_y): n for n, (coord_x, coord_y) in enumerate(nodes_coords)}\n\n\ndef create_graph_from_edges_with_node_attributes(edges, nodes_attribute_dict):\n graph = nx.DiGraph()\n graph.add_edges_from(edges)\n graph.add_nodes_from(nodes_attribute_dict)\n return graph\n\ndef create_geodataframe_with_simplified_straight_lines(geodf):\n # Takes a geodataframe with LineStrings as geometries and selects only\n # the beginning and end points of the LineStrings to make a new, simplified, straight\n # Linestring object. Then,\n # returns a new gdf with those simple lines\n geometries = []\n for index, row in geodf.iterrows():\n coords = [(coords) for coords in list(row['geometry'].coords)]\n first_coord, last_coord = [ coords[i] for i in (0, -1) ]\n geometries.append(LineString([Point(first_coord), Point(last_coord)]))\n \n return geopandas.GeoDataFrame(geometry=geometries) \n\ndef read_lines_and_raster_and_produce_dirty_graph(gpkg_fn, fn_dtm, edge_direction_is_local=False, simplify_straighten_lines=True):\n lines_gpkg = geopandas.read_file(gpkg_fn)\n if simplify_straighten_lines:\n lines_gpkg = create_geodataframe_with_simplified_straight_lines(lines_gpkg)\n raster_src = rasterio.open(fn_dtm)\n nodes_coords, nodes_heights = get_lists_of_node_coords_and_node_heights(\n raster_src, lines_gpkg)\n\n dict_coords_to_height_nodes = build_coords_to_height_dict(\n nodes_coords, nodes_heights)\n\n dict_coords_to_number_nodes = build_coords_to_number_nodes_dict(\n nodes_coords)\n if edge_direction_is_local:\n # Edge direction from height difference between neighbors\n edges = cwl_utilities.get_slope_directed_edges_with_node_number_name(\n lines_gpkg, dict_coords_to_number_nodes, dict_coords_to_height_nodes)\n else:\n # Edge direction inherited from file\n edges = []\n for line in lines_gpkg.geometry:\n try:\n up_node_number = dict_coords_to_number_nodes[line.coords[0]]\n down_node_number = dict_coords_to_number_nodes[line.coords[-1]]\n edges.append((up_node_number, down_node_number))\n except: # canal node outside of dem\n continue\n \n nodes_attribute_dict = [(n, {\"x\": coord_x, \"y\": coord_y, 'DEM': dict_coords_to_height_nodes[(coord_x, coord_y)]})\n for n, (coord_x, coord_y) in enumerate(nodes_coords)]\n\n graph = create_graph_from_edges_with_node_attributes(\n edges, nodes_attribute_dict)\n\n return graph\n\n\ndef get_duplicated_up_and_down_junction_nodes(all_junctions):\n # Returns nodes that are downstream and upstream nodes in more than 1 junction\n all_up_junction_nodes = [up_node for up_nodes,\n _ in all_junctions for up_node in up_nodes]\n all_down_junction_nodes = [\n down_node for _, down_nodes in all_junctions for down_node in down_nodes]\n\n up_dupli = list(cwl_utilities.get_duplicates_in_list(\n all_up_junction_nodes))\n down_dupli = list(cwl_utilities.get_duplicates_in_list(\n all_down_junction_nodes))\n\n return up_dupli, down_dupli\n\n\ndef remove_edge_between_nodes(adj_mat, source_node, target_node):\n # source_node is where the (directed!) edge begins and target_node is where it ends\n adj_changed = adj_mat.copy()\n if adj_changed[target_node, source_node] == 0:\n raise ValueError('The edge you want to remove does not exist')\n else:\n adj_changed[target_node, source_node] = 0\n\n return adj_changed\n\n\ndef does_cnm_have_bad_junctions(down_junction_duplicated):\n if len(down_junction_duplicated) == 0:\n return False\n else:\n return True\n\n\ndef remove_one_bad_edge(canal_network_matrix, up_junction_duplicated, down_junction_duplicated):\n # Remove bad junctions, one edge at a time\n cnm = canal_network_matrix.copy()\n\n down_dupli = down_junction_duplicated[0] # take only the first one\n # predecessors of down_dupli\n predecessors = list(np.where(cnm[down_dupli])[0])\n predecessors_that_are_up_junctions = [\n p for p in predecessors if p in up_junction_duplicated]\n if len(predecessors_that_are_up_junctions) > 0:\n cnm = remove_edge_between_nodes(\n cnm, predecessors_that_are_up_junctions[0], down_dupli)\n else:\n raise ValueError(\n 'None of the predecessors appear in more than one junction!')\n\n return cnm\n\n\ndef clean_cnm_from_strange_junctions(cnm):\n \"\"\"Removes faulty multiple count of junctions in the \n canal network matrix. By \"faulty\" here I mean the case where\n one node is the up- or downstream node of more than one junction.\n To do that, it simply removes annoying edges from the cnm. \n\n Args:\n cnm (numpy.ndarray): Canal network matrix\n\n Returns:\n cnm (numpy.ndarray): Canal network matrix without faulty junctions\n \"\"\"\n cnm_is_dirty = True\n cnm_clean = cnm.copy()\n while cnm_is_dirty:\n junctions = cwl_utilities.get_all_junctions(cnm_clean)\n up_junction_duplicated, down_junction_duplicated = get_duplicated_up_and_down_junction_nodes(\n junctions)\n if does_cnm_have_bad_junctions(down_junction_duplicated):\n try:\n cnm_clean = remove_one_bad_edge(\n cnm_clean, up_junction_duplicated, down_junction_duplicated)\n except:\n print('could not remove edge')\n else:\n cnm_is_dirty = False\n\n return cnm_clean\n\n\ndef clean_graph_from_strange_junctions(graph):\n \"\"\"Removes faulty multiple count of junctions in the \n canal network matrix. By \"faulty\" here I mean the case where\n one node is the up- or downstream node of more than one junction.\n To do that, it simply removes annoying edges from the cnm. \n\n Args:\n graph (networkx.DiGraph): Graph of the canal network matrix\n\n Returns:\n graph (networkx.DiGraph): Graph of the canal network matrix without faulty junctions\n \"\"\"\n\n graph_is_dirty = True\n nodelist = list(range(0, len(graph.nodes)))\n while graph_is_dirty:\n # nodelist forces the adjacency matrix to have an order.\n cnm = nx.to_numpy_array(graph, nodelist).T\n junctions = cwl_utilities.get_all_junctions(cnm)\n up_junction_duplicated, down_junction_duplicated = get_duplicated_up_and_down_junction_nodes(\n junctions)\n if does_cnm_have_bad_junctions(down_junction_duplicated):\n try: # Remove one bad edge\n # take only the first one\n down_dupli = down_junction_duplicated[0]\n # predecessors of down_dupli\n predecessors = list(np.where(cnm[down_dupli])[0])\n predecessors_that_are_up_junctions = [\n p for p in predecessors if p in up_junction_duplicated]\n edge_to_remove = (\n predecessors_that_are_up_junctions[0], down_dupli)\n graph.remove_edge(*edge_to_remove)\n except:\n raise ValueError('could not remove edge')\n\n else:\n graph_is_dirty = False\n\n return graph\n\n\ndef find_first_match_in_two_lists(list1: list, list2: list):\n \"\"\"Finds the first occurrence of an equal element between two lists.\n It avoids iterating over the whole lists just to get a match.\n Args:\n list1 (list): A list\n list2 (list): A list\n\n Returns:\n [type] or None: If an element exists in both lists, then the first such element is returned.\n If not, then None is returned.\n \"\"\"\n return next((i for i in list1 if i in set(list2)), None)\n\n\ndef get_junction_up_or_downsteam_nodes(junctions, mode):\n # mode = 'up' or 'down'\n nodes = []\n if mode == 'down':\n for _, downs in junctions:\n nodes = nodes + downs\n return nodes\n elif mode == 'up':\n for ups, _ in junctions:\n nodes = nodes + ups\n return nodes\n else:\n raise ValueError('mode should be either \"up\" or \"down\"')\n return None\n\n\ndef clean_graph_from_spy_nodes(graph, mode):\n # Spy nodes are nodes that are simultaneously either\n # downstream BCs AND downstream junction nodes\n # OR\n # upstream BCs AND upstream junction nodes\n # mode can be 'delete_all' or 'delete_only_necessary', depending on\n # whether all spy nodes are deleted at once, or they are deleted in a loop one at a time\n graph_is_dirty = True\n nodelist = list(range(0, len(graph.nodes)))\n while graph_is_dirty:\n # nodelist forces the adjacency matrix to have an order.\n cnm = nx.to_numpy_array(graph, nodelist).T\n\n junctions = cwl_utilities.get_all_junctions(cnm)\n junction_downs = get_junction_up_or_downsteam_nodes(\n junctions, mode='down')\n junction_ups = get_junction_up_or_downsteam_nodes(junctions, mode='up')\n\n upstream_bool, downstream_bool = cwl_utilities.infer_extreme_nodes(\n cnm) # BC nodes\n downstream_nodes = tuple(np.argwhere(downstream_bool).flatten())\n upstream_nodes = tuple(np.argwhere(upstream_bool).flatten())\n\n if mode == 'delete_only_necessary':\n down_spy_node = find_first_match_in_two_lists(\n downstream_nodes, junction_downs)\n up_spy_node = find_first_match_in_two_lists(\n upstream_nodes, junction_ups)\n\n if down_spy_node is not None:\n predecessor = list(np.where(cnm[down_spy_node])[0])\n edge_to_remove = (predecessor[0], down_spy_node)\n graph.remove_edge(*edge_to_remove)\n if up_spy_node is not None:\n succesor = list(np.where(cnm[:, up_spy_node])[0])\n edge_to_remove = (up_spy_node, succesor[0])\n graph.remove_edge(*edge_to_remove)\n else:\n graph_is_dirty = False\n\n elif mode == 'delete_all':\n down_spy_nodes = set(\n [n for n in downstream_nodes if n in junction_downs])\n predecessors_of_down = [list(graph.predecessors(n))[\n 0] for n in down_spy_nodes]\n\n up_spy_nodes = set(\n [n for n in upstream_nodes if n in junction_ups])\n successors_of_up = [list(graph.successors(n))[0]\n for n in up_spy_nodes]\n\n edges_to_remove = [(u, d) for d, u in zip(\n down_spy_nodes, predecessors_of_down)]\n edges_to_remove = edges_to_remove + \\\n [(u, d) for u, d in zip(up_spy_nodes, successors_of_up)]\n edges_to_remove = set(edges_to_remove)\n\n if len(edges_to_remove) < 1:\n graph_is_dirty = False\n\n for e in edges_to_remove:\n try:\n graph.remove_edge(*e)\n except:\n print('edge not found. Could not be removed')\n\n else:\n return ValueError('mode not understood')\n\n return graph\n\n\ndef compute_channel_network_graph(gpkg_fn, fn_dtm):\n # This takes a long time! (approx. 1hour)\n # 1st, clean from streange junctions, then clean from spy nodes\n graph = read_lines_and_raster_and_produce_dirty_graph(\n gpkg_fn, fn_dtm)\n graph_clean = clean_graph_from_strange_junctions(graph)\n graph_clean = clean_graph_from_spy_nodes(\n graph_clean.copy(), mode='delete_all')\n\n return graph_clean.copy()\n\n\ndef load_graph(load_from_pickled=True):\n if load_from_pickled:\n graph = pickle.load(open(\"canal_network_matrix.p\", \"rb\"))\n else:\n # Windows\n gpkg_fn = r\"C:\\Users\\03125327\\github\\canal_net\\qgis\\final_lines.gpkg\"\n fn_dtm = r\"C:\\Users\\03125327\\Documents\\qgis\\canal_networks\\dtm_10x10.tif\"\n # Linux -own computer-\n #gpkg_fn = r\"/home/txart/Programming/GitHub/canal_net/qgis/final_lines.gpkg\"\n #fn_dtm10x10 = r\"/home/txart/Programming/data/dtm_10x10.tif\"\n\n graph = compute_channel_network_graph(gpkg_fn, fn_dtm)\n\n return graph\n\n# %%\n\n# %%\n","sub_path":"cwl_preprocess_data.py","file_name":"cwl_preprocess_data.py","file_ext":"py","file_size_in_byte":22718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"464802061","text":"import pickle\nimport sklearn.linear_model\nimport sklearn.metrics\nimport matplotlib.pyplot as plt\n\n# Load the training and test data from the Pickle file\nwith open(\"../datasets/credit_card_default_dataset.pickle\", \"rb\") as f:\n train_data, train_labels, test_data, test_labels = pickle.load(f)\n\n# Select columns of interest\ncols = train_data.columns\n\n# Create and train a new LinearRegression model\nmodel = sklearn.linear_model.LinearRegression()\n\n# Train it with the training data and labels\nmodel.fit(train_data[cols], train_labels)\n\n# Predict new labels for test data\nY_pred_proba = model.predict(test_data[cols])\n\n# Compute a precision & recall graph\nprecisions, recalls, thresholds = \\\n sklearn.metrics.precision_recall_curve(test_labels, Y_pred_proba)\nplt.plot(thresholds, precisions[:-1], \"b--\", label=\"Precision\")\nplt.plot(thresholds, recalls[:-1], \"g-\", label=\"Recall\")\nplt.legend(loc=\"center left\")\nplt.xlabel(\"Threshold\")\nplt.show()\n\n\n# Plot a ROC curve (Receiver Operating Characteristic)\n# Compares true positive rate with false positive rate\nfpr, tpr, _ = sklearn.metrics.roc_curve(test_labels, Y_pred_proba)\nplt.plot(fpr,tpr)\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic')\nplt.show()\nauc_score = sklearn.metrics.roc_auc_score(test_labels, Y_pred_proba)\nprint(\"AUC score: {:.3f}\".format(auc_score))\n\n\n# Predict new labels for training data\nY_pred_proba_training = model.predict(train_data[cols])\nauc_score_training = sklearn.metrics.roc_auc_score(\\\n train_labels, Y_pred_proba_training)\nprint(\"Training AUC score: {:.3f}\".format(auc_score_training))","sub_path":"practices/week3/assignment_excercise_3.py","file_name":"assignment_excercise_3.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618850576","text":"import sys\nimport grabData\nfrom classes import BookmarkManager\n\n\ndef main():\n payload = {'Content-Encoding': 'gzip',\n 'Content-Type': 'text/html',\n 'Connection': 'keep-alive',\n 'username': '',\n 'password': ''}\n url = 'https://royalroadl.com/user/login?ReturnUrl=%2Fmy%2Fbookmarks'\n url2 = 'http://royalroadl.com'\n prefix = '/my/bookmarks?page='\n\n print(\"Python version: \" + sys.version)\n \n try:\n print(\"Connecting to database...\")\n connection = BookmarkManager()\n connection.connect('localhost', 'root', '______', 'pythontests', 'utf8')\n except Exception as e:\n print(\"Failure connecting to the database...\")\n print(\"Exception thrown: \" + str(e))\n return 1\n\n print(\"Connection to database established...\")\n\n try:\n # connection.query((\"\"\"DROP TABLE IF EXISTS bookmarks\"\"\", ())) # To be removed after updating script is complete\n # connection.query((\"\"\"DROP TABLE IF EXISTS chapters\"\"\", ())) # To be removed after updating script is complete\n #\n connection.query((\"\"\"CREATE TABLE IF NOT EXISTS `bookmarks` ( # To be changed to CREATE TABLE IF NOT EXISTS\n `title` varchar(200) NOT NULL, # after updating script is complete\n `author` varchar(99) DEFAULT NULL,\n `link` varchar(20) NOT NULL,\n `lastUpdated` varchar(45) NOT NULL,\n PRIMARY KEY (`link`),\n UNIQUE KEY `link_UNIQUE` (`link`)\n )ENGINE=InnoDB DEFAULT CHARSET=utf8\"\"\", ()))\n connection.query((\"\"\"CREATE TABLE IF NOT EXISTS `chapters` ( # To be changed to CREATE TABLE IF NOT EXISTS\n `fictionLink` varchar(20) NOT NULL, # after updating script is complete\n `chapterTitle` varchar(200) NOT NULL,\n `chapterLink` varchar(40) NOT NULL,\n `postTime` double NOT NULL,\n PRIMARY KEY (`chapterLink`)\n )ENGINE=InnoDB DEFAULT CHARSET=utf8\"\"\", ()))\n c = connection.query((\"\"\"SELECT count(*) as tot FROM bookmarks\"\"\", ()))\n\n except Exception as e:\n print(\"Failure to initialize database...\")\n print(\"Exception Thrown: \" + str(e))\n return 1\n\n # try:\n is_empty = c.fetchone()\n\n c = connection.query((\"\"\"SELECT lastUpdated FROM bookmarks\"\"\",()))\n last_check = connection.get_last_updated()\n last_check = grabData.fetchlatest(connection, payload, url, url2, prefix, last_check)\n print(last_check)\n\n # if int(is_empty[0]) == 0:\n # print(\"Database empty...\")\n # print(\"Fetching data...\")\n # print()\n # #\n # # if grabData.fetchall(connection, payload, url, url2, prefix):\n # # print(\"Data saved and ready for manipulation...\")\n # # print()\n # else:\n # print(\"Database not empty...\")\n # print(\"Checking for updates...\")\n # print()\n\n c.close()\n connection.close()\n return 0\n\n # except Exception as e:\n print(\"Failure to grab data...\")\n print(\"Exception Thrown: \" + str(e))\n return 1\n\n\n# Begin program\nmain()\n","sub_path":"RoyalRoadL/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"589066665","text":"from library import images\nfrom flags import *\n\nclass Block:\n def __init__(self,image='None',flags=0):\n #self.__image_name = image\n self.save_cache(image)\n \n self.flags=flags\n self.invisible = bool(INVISIBLE & flags)\n self.tall = bool(TALL & flags)\n self.floor = not bool(NOT_FLOOR & flags)\n self.block = bool(BLOCK & flags)\n \n def getcache(self):\n return images.getImage(self.__image_name) \n \n def save_cache(self,image):\n self.__image_name=image\n return images.cacheImage(image)\n\n image = property(getcache, save_cache )\n \n def __str__(self):\n r = 'image :' + str(self.image_name) + \"\\n\"\n r+= 'flags :' + str(self.flags) + \"\\n\"\n r+= 'invisible:' + str(self.invisible) + \"\\n\"\n r+= 'tall :' + str(self.tall) + \"\\n\"\n r+= 'floor :' + str(self.floor) + \"\\n\"\n r+= 'block :' + str(self.block) + \"\\n\"\n return r\n","sub_path":"tags/tag/cuterpg v0.03/rpg/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"17507658","text":"__author__ = 'Rybkin & Kravchenko'\n\nfrom keras.preprocessing import sequence\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.layers.recurrent import LSTM\nfrom keras.layers.core import RepeatVector\nimport numpy as np\n\n\nn = 10\nm = 2\nsample_size = 20000\n\n\nX_train = np.random.ranf((sample_size,n,1))\nY_train = X_train\nfor i in range(m - 1):\n Y_train = np.concatenate((Y_train, X_train), 1)\nprint(X_train.shape)\nprint(Y_train.shape)\nmodel = Sequential()\nmodel.add(LSTM(64, return_sequences=True, input_shape = (n,1)))\nmodel.add(LSTM(64, return_sequences=False))\nmodel.add(Dropout(0.5))\nmodel.add(RepeatVector(m*n))\nmodel.add(LSTM(1, return_sequences=True))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='mse', optimizer='adam')\n\nmodel.fit(X_train, Y_train, batch_size=1000, nb_epoch=1)\n","sub_path":"LSTM.py","file_name":"LSTM.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"604855589","text":"\"\"\"Модуль для топологій комунікаційних мереж КС\"\"\"\n\nfrom math import log2, ceil, floor, sqrt, pow\n\n__author__ = \"dima\"\n__version__ = \"1.0.2\"\n\n\ndef _get_linear_grid(*args):\n \"\"\"\n Повертає метрики лінійної решітки (магістралі)\n \"\"\"\n nodes_num = args[0]\n min_num = 3\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має б��ти не менше {}\".format(min_num))\n topology_name = \"Лінійна решітка або магістраль\"\n links_num = nodes_num - 1\n max_diameter = nodes_num - 1\n nodes_rank = 1, 2\n bisection_width = 1\n symmetry_factor = 1 - 1 / nodes_num\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_square_grid(*args):\n \"\"\"\n Повертає метрики квадратної решітки\n \"\"\"\n nodes_num = args[0]\n min_num = 4\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Квадратна решітка\"\n axis = ceil(sqrt(nodes_num))\n nodes_num = pow(axis, 2)\n links_num = 2 * axis * (axis - 1)\n max_diameter = 2 * (axis - 1)\n nodes_rank = 2, 3, 4\n bisection_width = axis\n symmetry_factor = 1 - 1 / axis\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_cubic_grid(*args):\n \"\"\"\n Повертає метрики кубічної решітки\n \"\"\"\n nodes_num = args[0]\n min_num = 8\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Кубічна решітка\"\n axis = ceil(pow(nodes_num, 1/3))\n nodes_num = pow(axis, 3)\n links_num = 3 * axis * axis * (axis - 1)\n max_diameter = 3 * (axis - 1)\n nodes_rank = 3, 4, 5, 6\n bisection_width = axis * axis\n symmetry_factor = 1 - 1 / axis\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_2D_rectangular_grid(*args):\n \"\"\"\n Повертає метрики прямокутної 2D-решітки\n \"\"\"\n nodes_num = args[0]\n axis1 = ceil(sqrt(nodes_num))\n axis2 = ceil(nodes_num / axis1)\n nodes_num = axis1 * axis2\n min_num = 4\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Прямокутна 2D-решітка\"\n links_num = nodes_num * (2 - (sum(map(lambda i: 1/i, (axis1, axis2)))))\n max_diameter = axis1 + axis2 - 2\n nodes_rank = 2, 3, 4\n bisection_width = min(axis1, axis2)\n symmetry_factor = 1 - (sum(map(lambda i: 1/i, (axis1, axis2)))) / 2\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_3D_rectangular_grid(*args):\n \"\"\"\n Повертає метрики прямокутної 3D-решітки\n \"\"\"\n nodes_num = args[0]\n axis1 = ceil(pow(nodes_num, 1/3))\n axis2 = ceil(sqrt(nodes_num / axis1))\n axis3 = ceil(nodes_num / (axis1 * axis2))\n nodes_num = axis1 * axis2 * axis3\n min_num = 8\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Прямокутна 3D-решітка\"\n links_num = nodes_num * (3 - sum(map(lambda i: 1/i, (axis1, axis2, axis3))))\n max_diameter = axis1 + axis2 + axis3 - 3\n nodes_rank = 3, 4, 5, 6\n bisection_width = min(axis1 * axis2, axis1 * axis3, axis2 * axis3)\n symmetry_factor = 1 - (sum(map(lambda i: 1/i, (axis1, axis2, axis3)))) / 3\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_linear_tor(*args):\n \"\"\"\n Повертає метрики лінійного тору (кільця)\n \"\"\"\n nodes_num = args[0]\n min_num = 3\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Лінійний тор або кільце\"\n links_num = nodes_num\n max_diameter = floor(nodes_num / 2)\n nodes_rank = 2\n bisection_width = 2\n symmetry_factor = 1\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_square_tor(*args):\n \"\"\"\n Повертає метрики квадратного тору\n \"\"\"\n nodes_num = args[0]\n min_num = 4\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Квадратний тор\"\n axis = ceil(sqrt(nodes_num))\n nodes_num = pow(axis, 2)\n links_num = 2 * nodes_num\n max_diameter = 2 * floor(axis / 2)\n nodes_rank = 4\n bisection_width = 2 * axis\n symmetry_factor = 1\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_cubic_tor(*args):\n \"\"\"\n Повертає метрики кубічного тору\n \"\"\"\n nodes_num = args[0]\n min_num = 8\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Кубічний тор\"\n axis = ceil(pow(nodes_num, 1/3))\n nodes_num = pow(axis, 3)\n links_num = 3 * nodes_num\n max_diameter = 3 * floor(axis / 2)\n nodes_rank = 6\n bisection_width = 2 * axis * axis\n symmetry_factor = 1\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_2D_rectangular_tor(*args):\n \"\"\"\n Повертає метрики прямокутного 2D-тору\n \"\"\"\n nodes_num = args[0]\n min_num = 4\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Прямокутний 2D-тор\"\n axis1 = ceil(sqrt(nodes_num))\n axis2 = ceil(nodes_num / axis1)\n nodes_num = axis1 * axis2\n links_num = 2 * nodes_num\n max_diameter = floor(axis1 / 2) + floor(axis2 / 2)\n nodes_rank = 4\n bisection_width = 2 * min(axis1, axis2)\n symmetry_factor = 1\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_3D_rectangular_tor(*args):\n \"\"\"\n Повертає метрики прямокутного 3D-тору\n \"\"\"\n nodes_num = args[0]\n min_num = 8\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Прямокутний 3D-тор\"\n axis1 = ceil(pow(nodes_num, 1/3))\n axis2 = ceil(sqrt(nodes_num / axis1))\n axis3 = ceil(nodes_num / (axis1 * axis2))\n nodes_num = axis1 * axis2 * axis3\n links_num = 3 * nodes_num\n max_diameter = floor(axis1 / 2) + floor(axis2 / 2) + floor(axis3 / 2)\n nodes_rank = 6\n bisection_width = 2 * min(axis1 * axis2, axis1 * axis3, axis2 * axis3)\n symmetry_factor = 1\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_fully_connected_network(*args):\n \"\"\"\n Повертає метрики повнозв'язної мережі\n \"\"\"\n nodes_num = args[0]\n min_num = 3\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Повнозв'язна мережа\"\n links_num = nodes_num * (nodes_num - 1) / 2\n max_diameter = 1\n nodes_rank = nodes_num - 1\n bisection_width = nodes_num * nodes_num / 4\n symmetry_factor = 1\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_star(*args):\n \"\"\"\n Повертає метрики зірки\n \"\"\"\n nodes_num = args[0]\n min_num = 3\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Зірка\"\n links_num = nodes_num - 1\n max_diameter = 2\n nodes_rank = 1, nodes_num - 1\n bisection_width = 1\n symmetry_factor = 2 / nodes_num\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_binary_tree(*args):\n \"\"\"\n Повертає метрики двійкового дерева\n \"\"\"\n nodes_num = args[0]\n min_num = 7\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n topology_name = \"Двійкове дерево\"\n links_num = nodes_num - 1\n max_diameter = ceil(2 * log2((nodes_num + 1) / 2))\n nodes_rank = 1, 2, 3\n bisection_width = 1\n symmetry_factor = 2 * (nodes_num - 1) / (3 * nodes_num)\n return [topology_name, int(nodes_num), int(links_num), int(max_diameter), nodes_rank, int(bisection_width),\n round(symmetry_factor, 6)]\n\n\ndef _get_ND_cubic_grid(nodes_num, max_node_rank=0):\n \"\"\"\n Повертає метрики всіх n-вимірних кубічних решіток\n \"\"\"\n min_num = 4\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n result = []\n d = 2\n\n # Якщо максимал��ний порядок не заданий\n if not max_node_rank:\n max_node_rank = nodes_num\n\n while pow(nodes_num, 1 / d) >= 3 and 2 * d <= max_node_rank:\n axis = ceil(pow(nodes_num, 1 / d))\n if pow(axis, d) >= nodes_num:\n dimension_nodes_num = int(pow(axis, d))\n dimension = d\n topology_name = \"Кубічна {}-вимірна решітка\".format(dimension)\n links_num = dimension * pow(axis, dimension - 1) * (axis - 1)\n max_diameter = dimension * (axis - 1)\n nodes_rank = tuple(i for i in range(dimension, 2 * dimension + 1))\n bisection_width = pow(axis, dimension - 1)\n symmetry_factor = 1 - pow(axis, -1)\n\n result.append([topology_name, int(dimension_nodes_num), int(links_num), int(max_diameter), nodes_rank,\n int(bisection_width), round(symmetry_factor, 6)])\n d += 1\n return result\n\n\ndef _get_ND_cubic_tor(nodes_num, max_node_rank=0):\n \"\"\"\n Повертає метрики всіх n-вимірних кубічних торів\n \"\"\"\n min_num = 4\n if nodes_num < min_num:\n raise ValueError(\"Кількість вузлів має бути не менше {}\".format(min_num))\n result = []\n d = 2\n\n if not max_node_rank:\n max_node_rank = nodes_num\n while pow(nodes_num, 1 / d) >= 3 and 2 * d <= max_node_rank:\n axis = ceil(pow(nodes_num, 1 / d))\n if pow(axis, d) >= nodes_num:\n dimension_nodes_num = int(pow(axis, d))\n dimension = d\n topology_name = \"Кубічний {}-вимірний тор\".format(dimension)\n links_num = dimension * dimension_nodes_num\n max_diameter = dimension * floor(axis / 2)\n nodes_rank = 2 * dimension\n bisection_width = 2 * pow(axis, dimension - 1)\n symmetry_factor = 1\n result.append([topology_name, int(dimension_nodes_num), int(links_num), int(max_diameter), nodes_rank,\n int(bisection_width), round(symmetry_factor, 6)])\n d += 1\n return result\n\n\ndef calc_topology(topology, nodes_num, max_node_rank=0):\n \"\"\"\n Повертає метрики топології\n \"\"\"\n if not (isinstance(nodes_num, int) and nodes_num >= 1):\n raise ValueError(\"Неправильна кількість вузлів\")\n\n for t in _topology_types.values():\n if t.get(topology):\n return t.get(topology)(nodes_num, max_node_rank)\n raise ValueError(\"Введена топологія не підтримується.\")\n\n\ndef calc_all_topology(nodes_num, max_node_rank=0, max_links_num=0):\n \"\"\"\n Обчислює всі метрики всіх наявних топологій\n \"\"\"\n simple, multidimensional = _topology_types[\"simple\"], _topology_types[\"multidimensional\"]\n result = []\n for t in simple.keys():\n try:\n result.append(calc_topology(t, nodes_num))\n except ValueError:\n pass\n\n # Фільтр топологій по максимальному порядку\n if max_node_rank:\n result = list(filter(lambda t: (t[4] if isinstance(t[4], int)\n else max(t[4])) <= max_node_rank, result))\n for t in multidimensional.keys():\n result.extend(calc_topology(t, nodes_num, max_node_rank))\n\n # Фільтр топологій по максимальній кількості зв'язків\n if max_links_num:\n result = list(filter(lambda t: t[2] <= max_links_num, result))\n return result\n\n\ndef get_optimal_topology(topology_list):\n \"\"\"\n Повертає оптимальну топологію\n \"\"\"\n result_topology = topology_list[0]\n min_diameter = result_topology[3]\n bisection = result_topology[5]\n for t in topology_list:\n if t[3] < min_diameter:\n min_diameter = t[3]\n bisection = t[5]\n result_topology = t\n elif t[3] == min_diameter:\n if t[5] > bisection:\n min_diameter = t[3]\n bisection = t[5]\n result_topology = t\n return result_topology\n\n\n_topology_types = {\n \"simple\": {\n \"Лінійна решітка або магістраль\": _get_linear_grid,\n \"Квадратна решітка\": _get_square_grid,\n \"Кубічна решітка\": _get_cubic_grid,\n \"Прямокутна 2D-решітка\": _get_2D_rectangular_grid,\n \"Прямокутна 3D-решітка\": _get_3D_rectangular_grid,\n \"Лінійний тор або кільце\": _get_linear_tor,\n \"Квадратний тор\": _get_square_tor,\n \"Кубічний тор\": _get_cubic_tor,\n \"Прямокутний 2D-тор\": _get_2D_rectangular_tor,\n \"Прямокутний 3D-тор\": _get_3D_rectangular_tor,\n \"Повнозв'язна мережа\": _get_fully_connected_network,\n \"Зірка\": _get_star,\n \"Двійкове дерево\": _get_binary_tree\n },\n \"multidimensional\": {\n \"Кубічна n-вимірна решітка\": _get_ND_cubic_grid,\n \"Кубічний n-вимірний тор\": _get_ND_cubic_tor\n }\n}\n\n\nif __name__ == \"__main__\":\n print(__doc__)\n","sub_path":"communication_networks/topology/topology_types.py","file_name":"topology_types.py","file_ext":"py","file_size_in_byte":15648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560884646","text":"# coding: gbk\n# Python爬虫过程-获取数据-解析数据-提取数据-存储数据\nimport requests\nimport json\n\nsession = requests.session()\nheaders ={\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'\n}\n\n\n\n# 函数定义\n# 读取cookies\ndef cookies_read():\n cookies_txt = open('cookies.txt', 'r')\n cookies_dict = json.load(cookies_txt.read())\n cookies = requests.utils.cookiejar_from_dict(cookies_dict)\n return cookies\n\n\n# 登录\ndef sign_in():\n url = 'https://wordpress-edu-3autumn.localprod.oc.forchange.cn/wp-login.php'\n data = {\n 'log': input('请输入你的账号'),\n 'pwd': input('请输入你的密码'),\n 'wp-submit': '登录',\n 'redirect_to': 'https://wordpress-edu-3autumn.localprod.oc.forchange.cn',\n 'testcookie': '1'\n }\n # cookies存储\n session.post(url, headers=headers, data=data)\n cookies_dict = requests.utils.dict_from_cookiejar(session.cookies)\n cookies_str = json.dumps(cookies_dict)\n f = open('cookies.txt','w')\n f.write(cookies_str)\n f.close()\n\n\ndef write_message():\n url_2 = 'https://wordpress-edu-3autumn.localprod.oc.forchange.cn/wp-comments-post.php'\n data_2 ={\n 'comment': input('请输入你要发表的评论:'),\n 'submit': '发表评论',\n 'comment_post_ID': '13',\n 'comment_parent': '0'\n }\n return session.post(url_2, headers=headers, data=data_2)\n\ntry:\n session.cookies = cookies_read()\nexcept FileNotFoundError:\n sign_in()\n\nnum = write_message()\nif num.status_code == 200:\n print('成功了')\nelse:\n sign_in()\n num = write_message()","sub_path":"借助Python发表评论-终极优化版.py","file_name":"借助Python发表评论-终极优化版.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"211419960","text":"# -*- coding: utf-8 -*-\nimport logging\nimport datetime\nimport time\nimport platform\n# from os import path\nimport os\n\nclass DefaultConfig():\n def __init__(self):\n # ------------ 数据路径 ------------\n # 数据集根目录\n\n if (platform.system() == 'Windows'):\n self.base_dir = os.path.dirname(os.path.dirname(__file__))\n print(self.base_dir)\n self.result_filename =self.base_dir+'\\\\result\\\\dep_date_pred_result.csv'\n self.predict_offline_data =self.base_dir+'/dataset/dep_date_prediction_data.csv'\n self.train_offline_data =self.base_dir+'/dataset/dep_date_prediction_train_data.csv'\n self.model_dir = '../model'\n else:\n self.base_dir = '/home/q/tmp/f_algorithm_model/flight_growth/'\n # 结果保存文件名\n self.result_filename = self.base_dir+'/result/dep_date_pred_' + self.getdate() + '_result.csv' # 修改保存的结果文件名\n # 预测数据路径\n self.predict_offline_data = self.base_dir + '/dataset/dep_date_pred_data_'+ self.getdate()+'.csv'\n # 模型保存路径\n self.model_dir = './model'\n # 模型名称\n self.model_pkl = 'user_dep_date_prediction_v1.2'\n # xgboost模型参数\n self.booster = 'gbtree'\n self.objective = 'binary:logistic'\n self.gamma = 0.03\n self.max_depth = 7\n self.lambda_xgb = 1\n self.alpha = 1\n self.subsample = 0.75\n self.colsample_bytree = 0.9\n self.colsample_bylevel = 0.9\n self.eval_metric = 'auc'\n self.min_child_weight = 0.8\n self.max_delta_step = 0\n self.silent = 0\n self.eta = 0.01\n self.seed = 123\n self.scale_pos_weight = 1\n self.tree_method = 'auto'\n self.nthread = -1\n self.early_stopping_rounds = 50\n self.num_boost_round = 2000\n\n # 阈值设置\n self.threshold = 0.5\n # dt设置\n self.dt = self.getUpdateDate() # '2019-05-23' #注意修改dt,用于确定预测数据集的dt\n\n # 数据采样的样本量设置\n self.n_sample = 2 # 注意修改n_sample,用于确定训练集的正负采样样本量\n\n # 创建一个日志对象\n self.logger = logging.getLogger()\n self.logger.setLevel(logging.DEBUG)\n # 创建Handler,用于写入日志文件\n rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))\n if (platform.system() == 'Windows'):\n fh=logging.FileHandler('../udp-logger.log', mode='a')\n else:\n fh = logging.FileHandler(self.base_dir + '/udp-logger.log', mode='a') ##模式,有w和a,w就是写模式,每次都会重新写日志,覆盖之前的日志\n # a是追加模式,默认如果不写的话,就是追加模式\n fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关\n # 控制台输出日志\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n # 第三步,定义handler的输出格式\n formatter = logging.Formatter(\"%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s\")\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n # 第四步,将logger添加到handler里面\n self.logger.addHandler(fh)\n self.logger.addHandler(ch)\n\n def getdate(self):\n yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime('%Y%m%d')\n return str(yesterday)\n\n def getUpdateDate(self):\n yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime('%Y%m%d')\n return str(yesterday)","sub_path":"code/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"409144569","text":"import xml.dom.minidom\nimport logging\nimport pprint\n\npp = pprint.PrettyPrinter(indent=4)\nl = logging.getLogger(\"ogslb\")\n\ndef getText(nodelist):\n rc = []\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n rc.append(node.data)\n return ''.join(rc)\n\ndef parseConfig(filename='config.xml'):\n dom = xml.dom.minidom.parse(filename);\n config = {}\n try:\n dbc = dom.getElementsByTagName('CONFIG')[0]\n for a in dbc.attributes.keys():\n config[a] = dbc.attributes[a].value\n except:\n l.debug(\"error getting config\")\n\n\n return(config)\n\n","sub_path":"lib/ParseConfig.py","file_name":"ParseConfig.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"265001644","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\nfrom ReverseProxied import ReverseProxied\nimport datetime\nimport paho.mqtt.client as mqtt\nimport re\nimport os\nimport time\n\nimport flask\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom sqlalchemy.exc import DatabaseError, IntegrityError\nfrom flask.ext.security import Security, SQLAlchemyUserDatastore, \\\n UserMixin, RoleMixin, login_required, current_user\nfrom flask.ext.security.utils import encrypt_password, verify_password\nimport sqlalchemy\nfrom sqlalchemy.sql import func\nfrom sqlalchemy import or_\n\n# https://github.com/miguelgrinberg/Flask-Runner\n# http://flask.pocoo.org/docs/0.10/deploying/mod_wsgi/\n\napp = flask.Flask(__name__)\napp.wsgi_app = ReverseProxied(app.wsgi_app)\ndb = SQLAlchemy(app)\n\n\napp.config['LOCALE'] = 'de_DE'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///roster.db'\napp.config['SECRET_KEY'] = 'developmentNotSoSecretKey'\napp.config['SECURITY_PASSWORD_HASH'] = 'sha512_crypt'\napp.config['SECURITY_PASSWORD_SALT'] = 'developmentNotSoSecretKey'\napp.config['DEFAULT_MAIL_SENDER'] = 'VVM Dienstplan '\napp.config['COUNTER_CORRECTION_FACTOR'] = 3.0\n\nif 'VVMROSTER_APPLICATION_SETTINGS_PATH' in os.environ:\n\tapp.config.from_envvar('VVMROSTER_APPLICATION_SETTINGS_PATH')\n\n\n@sqlalchemy.event.listens_for(sqlalchemy.engine.Engine, \"connect\")\ndef set_sqlite_pragma(dbapi_connection, connection_record):\n\t'''\n\tEnable foreign key constraints in SQLite.\n\t'''\n\tcursor = dbapi_connection.cursor()\n\ttry:\n\t\tcursor.execute(\"PRAGMA foreign_keys=ON\")\n\texcept:\n\t\tpass\n\tcursor.close()\n\nroles_users = db.Table('roles_users',\n\t\tdb.Column('user_id', db.Integer(), db.ForeignKey('user.id')),\n\t\tdb.Column('role_id', db.Integer(), db.ForeignKey('role.id')))\n\n\nclass Role(db.Model, RoleMixin):\n\t'''\n\tStandard Flask-Security role model\n\t'''\n\tid = db.Column(db.Integer(), primary_key=True)\n\tname = db.Column(db.String(80), unique=True)\n\tdescription = db.Column(db.String(255))\n\tdef __repr__(self):\n\t\treturn ''.format(self.id, self.name)\n\tdef __unicode__(self):\n\t\treturn self.name\n\nclass User(db.Model, UserMixin):\n\t'''\n\tUser model based on the Flask Security example.\n\t'''\n\tid = db.Column(db.Integer, primary_key=True)\n\tname = db.Column(db.String(255))\n\temail = db.Column(db.String(255), unique=True)\n\tpassword = db.Column(db.String(255))\n\tactive = db.Column(db.Boolean())\n\tconfirmed_at = db.Column(db.DateTime())\n\troles = db.relationship('Role', secondary=roles_users,\n\t\t\tbackref=db.backref('users', lazy='dynamic'))\n\tdef __repr__(self):\n\t\treturn ''.format(self.id, self.email)\n\tdef __unicode__(self):\n\t\treturn self.email\n\nuser_datastore = SQLAlchemyUserDatastore(db, User, Role)\nsecurity = Security(app, user_datastore)\n\n\nclass Roster(db.Model):\n\t'''\n\tModel to store roster entries. The day and the user are the composite primary key.\n\t'''\n\t__tablename__ = 'roster'\n\tday = db.Column(db.DateTime, primary_key=True)\n\tuser_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)\n\tuser = db.relationship('User')\n\twill_open = db.Column(db.Integer)\n\twill_service = db.Column(db.Integer)\n\twill_close = db.Column(db.Integer)\n\tcomment = db.Column(db.String(1000))\n\n\t@classmethod\n\tdef getCountsForSundays(self, days=None, filled=None):\n\t\t\"\"\"\n\t\tReturns a report for specified days including the sums of volunteers. If\n\t\tdays is not specified, all dates for which entries exist are returned. If\n\t\tfilled is specified, the report will include a result for every specified date,\n\t\teven if the roster does not contain any entries for it. Filled defaults to True\n\t\tif days are specified, False otherwise.\n\t\tReturns an array of dicts.\n\t\t\"\"\"\n\t\tif days and filled == None:\n\t\t\tfilled = True\n\t\tquery = db.session.query(self.day,\n\t\t\tfunc.sum(self.will_open).label('sum_open'),\n\t\t\tfunc.sum(self.will_service).label('sum_service'),\n\t\t\tfunc.sum(self.will_close).label('sum_close'),\n\t\t\tfunc.count(self.will_open).label('count'),\n\t\t\t)\n\t\tquery = query.filter(or_(self.will_open > 0, self.will_service > 0, self.will_close > 0))\n\t\tif days:\n\t\t\tquery = query.filter(self.day.in_(days))\n\t\tquery = query.group_by(self.day).order_by(self.day)\n\t\tresult = []\n\t\trows = query.all()\n\t\tfor row in rows:\n\t\t\td = row._asdict()\n\t\t\t# int() workaround for MySQL returning Decimal which jsonify doesn't grok\n\t\t\td['sum_open'] = int(d['sum_open'])\n\t\t\td['sum_service'] = int(d['sum_service'])\n\t\t\td['sum_close'] = int(d['sum_close'])\n\t\t\td['count'] = int(d['count'])\n\t\t\tresult.append(d)\n\t\tif filled:\n\t\t\tif days == None:\n\t\t\t\traise ValueError(\"when filling, days need to be specified\")\n\t\t\tfilledResult = []\n\t\t\tfor day in days:\n\t\t\t\tfor r in result:\n\t\t\t\t\tif r['day'] == day:\n\t\t\t\t\t\tfilledResult.append(r)\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tfilledResult.append({\n\t\t\t\t\t\t'day': day,\n\t\t\t\t\t\t'sum_open': 0,\n\t\t\t\t\t\t'sum_service': 0,\n\t\t\t\t\t\t'sum_close': 0,\n\t\t\t\t\t\t'count': 0,\n\t\t\t\t\t})\n\t\t\treturn filledResult\n\t\treturn result\n\n\tdef __init__(self):\n\t\tself.day = datetime.date.today()\n\t\tself.will_open = False\n\t\tself.will_service = False\n\t\tself.will_close = False\n\t\tself.comment = ''\n\n\tdef __repr__(self):\n\t\treturn ''.format(self.day, self.user.email)\n\n\nclass VisitorCounter(db.Model):\n\t__tablename__ = 'visitorcounter'\n\tts = db.Column(db.DateTime, primary_key=True)\n\tvc = db.Column(db.Integer)\n\tut = db.Column(db.Integer)\n\n\tdef __init__(self, ts, vc, ut):\n\t\tself.ts = ts\n\t\tself.vc = vc\n\t\tself.ut = ut\n\tdef __repr__(self):\n\t\treturn ''.format(self.ts, self.vc)\n\n\nclass VisitorCountPerHour(db.Model):\n\t__tablename__ = 'visitorcounter_perhour'\n\tts = db.Column(db.DateTime, primary_key=True)\n\tcount = db.Column(db.Integer)\n\n\tdef __init__(self, ts, count):\n\t\tself.ts = ts\n\t\tself.count = count\n\tdef __repr__(self):\n\t\treturn ''.format(self.ts, self.count)\n\n\nclass CounterListener:\n\tdef on_connect(self, client, userdata, flags, rc):\n\t\tclient.subscribe(\"/vvm/visitorcounter/#\")\n\n\tdef on_message(self, client, userdata, msg):\n\t\tif msg.topic.endswith(\"/uptime\"):\n\t\t\tself.ut = int(msg.payload)\n\t\tif msg.topic.endswith(\"/counter\"):\n\t\t\tself.vc = int(msg.payload)\n\t\tself.ts = datetime.datetime.now()\n\n\tdef __init__(self):\n\t\tself.vc = 0\n\t\tself.ut = 0\n\t\tself.ts = datetime.datetime(1970, 1, 1)\n\t\tself.client = mqtt.Client(userdata=self)\n\t\tself.client.on_connect = self.on_connect\n\t\tself.client.on_message = self.on_message\n\t\tif 'VISITORCOUNTER_USER' in app.config:\n\t\t\tself.client.username_pw_set(app.config['VISITORCOUNTER_USER'],\n\t\t\t\tapp.config['VISITORCOUNTER_PASS'])\n\t\t\tself.client.connect_async(app.config['VISITORCOUNTER_BROKER'], 1883, 60)\n\t\t\tself.client.loop_start()\n\n\tdef __repr__(self):\n\t\treturn ''.format(self.vc, self.ut)\n\n\n@app.before_first_request\ndef before_first_request():\n\tglobal counterListener\n\tinitdb()\n\tif not 'counterListener' in globals():\n\t\tcounterListener = CounterListener()\n\n\ndef initdb():\n\t'''\n\tFill in a minimum of data on a virgin database.\n\t'''\n\tdb.create_all()\n\tadmin_role = Role.query.filter_by(name='admin').first()\n\tif admin_role == None:\n\t\tadmin_role = user_datastore.create_role(name='admin',\n\t\t\tdescription='manage users etc.')\n\tif user_datastore.get_user('stb@lassitu.de') == None:\n\t\tuser_datastore.create_user(name='Stefan Bethke',\n\t\t\temail='stb@lassitu.de',\n\t\t\tpassword=encrypt_password('password'), roles=[admin_role])\n\tdb.session.commit()\n\n\ndef upcomingDays():\n\t'''\n\tReturns a list of upcoming days for which we want to show entries.\n\t'''\n\ttoday = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time())\n\t# Sunday is the 6th day of the week\n\tsunday = today + datetime.timedelta(days=6-today.weekday())\n\tsundays = list((sunday + datetime.timedelta(days=i*7)) for i in range(6))\n\talldays = sundays\n\t# FIXME: store special days in the database\n\tspecialdays = []\n\tspecialdays.append(datetime.datetime(2015, 10, 3)) # reunification\n\tspecialdays.append(datetime.datetime(2016, 3, 24)) # easter\n\tspecialdays.append(datetime.datetime(2016, 3, 25))\n\tspecialdays.append(datetime.datetime(2016, 3, 28))\n\tspecialdays.append(datetime.datetime(2016, 5, 5)) # ascention\n\tspecialdays.append(datetime.datetime(2016, 5, 16)) # pentecost\n\tspecialdays.append(datetime.datetime(2016, 10, 3)) # reunification\n\tspecialdays.append(datetime.datetime(2016, 12, 26)) # boxing day\n\n\tspecialdays.append(datetime.datetime(2018, 10, 31)) # reformation\n\tspecialdays.append(datetime.datetime(2018, 12, 25)) # xmas day\n\tspecialdays.append(datetime.datetime(2018, 12, 26)) # boxing day\n\n\tspecialdays.append(datetime.datetime(2019, 4, 19)) # good friday\n\tspecialdays.append(datetime.datetime(2019, 3, 22)) # easter monday\n\tspecialdays.append(datetime.datetime(2019, 5, 1)) # may day\n\tspecialdays.append(datetime.datetime(2019, 5, 30)) # ascention\n\tspecialdays.append(datetime.datetime(2019, 6, 10)) # pentecost\n\tspecialdays.append(datetime.datetime(2019, 10, 3)) # reunification\n\tspecialdays.append(datetime.datetime(2019, 10, 31)) # reformation\n\tspecialdays.append(datetime.datetime(2019, 12, 25)) # xmas day\n\tspecialdays.append(datetime.datetime(2019, 12, 26)) # boxing day\n\talldays.extend(specialdays)\n\talldays.sort()\n\talldays = [i for i in alldays if i >= today]\n\treturn alldays[0:5]\n\ndef currentDay():\n\t'''\n\tReturns the next day we're showing entries for.\n\t'''\n\treturn upcomingDays()[0]\n\n\ndef url_for(fn, _external=True):\n\treturn flask.url_for(fn, _external=_external)\n\n\n@app.route('/')\n@login_required\ndef index():\n\treturn flask.render_template('index.html')\n\n\n@app.route('/api/status')\n@app.route('/api/status/1')\ndef status():\n\t'''\n\tAPI that returns status information for the currently logged in user, including a list\n\tof Sundays to display in the front-end, with their roster counts attached.\n\t'''\n\tif current_user.is_authenticated():\n\t\tsunday = currentDay()\n\t\tr = dict()\n\t\tr['id'] = 1\n\t\tr['logged_in'] = True\n\t\tr['email'] = current_user.email\n\t\tr['name'] = current_user.name\n\t\tr['user_id'] = current_user.id\n\t\tr['admin_user'] = current_user.has_role('admin')\n\t\tr['today'] = sunday.isoformat()\n\t\tr['days'] = [day.isoformat() for day in upcomingDays()[1:]]\n\t\tr['day_status'] = dict()\n\t\tfor c in Roster.getCountsForSundays(upcomingDays()):\n\t\t\tc['day'] = c['day'].isoformat()\n\t\t\tr['day_status'][c['day']] = c\n\t\treturn flask.jsonify(items=[r])\n\treturn flask.jsonify(logged_in=False)\n\n\n@app.route('/api/settings', methods=['POST', 'GET'])\n@app.route('/api/settings/', methods=['GET', 'PUT', 'POST'])\ndef settings(id=None):\n\t'''\n\tAPI that returns and stores user settings, including user name, email, and\n\tpassword.\n\t'''\n\tif not current_user.is_authenticated():\n\t\tflask.abort(403)\n\tuser = current_user\n\tif flask.request.method == 'GET':\n\t\tjson = [{\n\t\t\t'id': user.id,\n\t\t\t'name': user.name,\n\t\t\t'email': user.email,\n\t\t\t'passwprd': '',\n\t\t\t'roles': [unicode(role.name) for role in user.roles],\n\t\t}]\n\t\treturn flask.jsonify(items=json)\n\tif flask.request.method == 'PUT':\n\t\treq = flask.request.get_json()\n\t\tcurrent_user.email = req['email']\n\t\tcurrent_user.name = req['name']\n\t\tdb.session.commit()\n\t\treturn flask.jsonify(ok=True)\n\tif flask.request.method == 'POST':\n\t\treq = flask.request.get_json()\n\t\tif not verify_password(req['old'], current_user.password):\n\t\t\tresponse = flask.jsonify(ok=False, msg='Das alte Passwort stimmt nicht.')\n\t\t\tresponse.status_code=409\n\t\t\treturn response\n\t\tif req['new1'] != req['new2']:\n\t\t\tresponse = flask.jsonify(ok=False, msg='Die beiden neuen Passwörter stimmen nicht überein.')\n\t\t\tresponse.status_code=409\n\t\t\treturn response\n\t\tcurrent_user.password = encrypt_password(req['new1'])\n\t\tdb.session.commit()\n\t\treturn flask.jsonify(ok=True)\n\tflask.abort(405)\n\n\n@app.route('/api/users', methods=['GET', 'POST'])\n@app.route('/api/users/', methods=['GET', 'PUT', 'DELETE'])\ndef users(id=None):\n\t'''\n\tAPI that allows creating, reading, updating and deleting users. The logged in\n\tuser needs to habe the admin role.\n\t'''\n\tif not current_user.is_authenticated():\n\t\tflask.abort(403)\n\tif not current_user.has_role('admin'):\n\t\tflask.abort(403)\n\n\tadmin_role = Role.query.filter_by(name='admin').first()\n\tif id:\n\t\tuser = User.query.filter_by(id=id).first()\n\tif flask.request.method == 'GET':\n\t\tjson = []\n\t\tfor user in User.query.all():\n\t\t\tu = {\n\t\t\t\t'id': user.id,\n\t\t\t\t'name': user.name,\n\t\t\t\t'email': user.email,\n\t\t\t\t'passwprd': '',\n\t\t\t\t'roles': [unicode(role.name) for role in user.roles],\n\t\t\t\t'admin_user': admin_role in user.roles,\n\t\t\t}\n\t\t\tjson.append(u)\n\t\treturn flask.jsonify(items=json)\n\tif flask.request.method == 'DELETE' and id:\n\t\ttry:\n\t\t\tRoster.query.filter_by(user=user).delete()\n\t\t\tdb.session.delete(user)\n\t\t\tdb.session.commit()\n\t\texcept DatabaseError as e:\n\t\t\tresponse = flask.jsonify(ok=False, msg='Benutzer kann nicht gelöscht werden: ' + e.message)\n\t\t\tresponse.status_code=409\n\t\t\treturn response\n\t\treturn flask.jsonify(ok=True)\n\tif flask.request.method == 'PUT':\n\t\troles = []\n\t\treq = flask.request.get_json()\n\t\tif 'admin_user' in req:\n\t\t\troles.append(admin_role)\n\t\ttry:\n\t\t\tuser.name = req['name']\n\t\t\tuser.email = req['email']\n\t\t\tif 'password' in req:\n\t\t\t\tuser.password = encrypt_password(req['password'])\n\t\t\tuser.roles = roles\n\t\t\tdb.session.commit()\n\t\texcept IntegrityError:\n\t\t\tresponse = flask.jsonify(ok=False, msg='Es gibt bereits einen Benutzer mit dieser Email (doppelter Datensatz)')\n\t\t\tresponse.status_code=409\n\t\t\treturn response\n\t\texcept DatabaseError as e:\n\t\t\tresponse = flask.jsonify(ok=False, msg='beim Speichern des Benutzers: ' + e.message)\n\t\t\tresponse.status_code=409\n\t\t\treturn response\n\t\treturn flask.jsonify(ok=True, id=user.id)\n\tif flask.request.method == 'POST':\n\t\troles = []\n\t\treq = flask.request.get_json()\n\t\tif 'admin_user' in req and req['admin_user']:\n\t\t\troles.append(admin_role)\n\t\ttry:\n\t\t\tuser = user_datastore.create_user(name=req['name'],\n\t\t\t\temail=req['email'],\n\t\t\t\tpassword=encrypt_password(req['password']),\n\t\t\t\troles=roles)\n\t\t\tdb.session.commit()\n\t\texcept IntegrityError:\n\t\t\tresponse = flask.jsonify(ok=False, msg='Es gibt bereits einen Benutzer mit dieser Email (doppelter Datensatz)')\n\t\t\tresponse.status_code=409\n\t\t\treturn response\n\t\texcept DatabaseError as e:\n\t\t\tresponse = flask.jsonify(ok=False, msg='beim Speichern des Benutzers: ' + e.message)\n\t\t\tresponse.status_code=409\n\t\t\treturn response\n\t\treturn flask.jsonify(ok=True, id=user.id)\n\tflask.abort(405)\n\n\n@app.route('/api/roster/', methods=['GET', 'POST'])\n@app.route('/api/roster//', methods=['PUT'])\ndef rosterentries(day, id=None):\n\t'''\n\tAPI that allows creating, reading and updating roster entries. Deleting is not\n\timplemented. To create or update entries for a different user than the currently\n\tlogged in user, the user needs to have the admin role.\n\t'''\n\tif not current_user.is_authenticated():\n\t\tflask.abort(403)\n\tif not day:\n\t\tresponse = flask.jsonify(ok=False, msg='')\n\t\tresponse.status_code = 404\n\t\treturn response\n\tday = datetime.datetime(*map(int, re.split('[^\\d]', day)[:-1]))\n\tif flask.request.method == 'GET':\n\t\tresults = Roster.query.filter_by(day=day).all()\n\t\tjson_results = []\n\t\tfor result in results:\n\t\t\td = {\n\t\t\t\t'day': result.day.isoformat(),\n\t\t\t\t'member': result.user.name,\n\t\t\t\t'user_id': result.user.id,\n\t\t\t\t'id': result.user.id,\n\t\t\t\t'will_open': result.will_open != 0,\n\t\t\t\t'will_service': result.will_service != 0,\n\t\t\t\t'will_close': result.will_close != 0,\n\t\t\t\t'comment': result.comment\n\t\t\t\t}\n\t\t\tjson_results.append(d)\n\t\treturn flask.jsonify(items=json_results)\n\tif flask.request.method == 'POST':\n\t\treq = flask.request.get_json()\n\t\tif req['user_id'] != current_user.id and not current_user.has_role('admin'):\n\t\t\tflask.abort(403)\n\t\tr = Roster()\n\t\tr.day = day;\n\t\tr.user = User.query.get(req['user_id'])\n\t\tr.will_open = int(req['will_open'])\n\t\tr.will_service = int(req['will_service'])\n\t\tr.will_close = int(req['will_close'])\n\t\tr.comment = req['comment']\n\t\tdb.session.add(r)\n\t\tdb.session.commit()\n\t\treturn flask.jsonify(ok=True)\n\tif flask.request.method == 'PUT':\n\t\treq = flask.request.get_json()\n\t\tif id != current_user.id and not current_user.has_role('admin'):\n\t\t\tflask.abort(403)\n\t\tr = Roster.query.filter_by(day=day, user_id=id).first()\n\t\tr.will_open = int(req['will_open'])\n\t\tr.will_service = int(req['will_service'])\n\t\tr.will_close = int(req['will_close'])\n\t\tr.comment = req['comment']\n\t\tdb.session.commit()\n\t\treturn flask.jsonify(ok=True)\n\tflask.abort(405)\n\n\ndef calcVisitorEntry(start, elevenam, fivepm, end):\n\tf = app.config['COUNTER_CORRECTION_FACTOR'];\n\treturn {\n\t\t'ts': start.ts.isoformat(),\n\t\t'day': int((end.vc - start.vc) / f),\n\t\t'midnighttoeleven': int((elevenam.vc - start.vc) / f),\n\t\t'eleventofive': int((fivepm.vc - elevenam.vc) / f),\n\t\t'fivetomidnight': int((end.vc - fivepm.vc) / f)\n\t}\n\ndef accumulateVisitorsPerDay(results):\n\t'''\n\tGiven a result set of counter values, accumulate them to produce a visitor\n\tcount for each day\n\t'''\n\tif len(results) < 2:\n\t\treturn []\n\tcountsPerDay = []\n\tstart = results[0]\n\tstart.ts = start.ts.replace(hour=0, minute=0, second=0, microsecond=0)\n\televenam = start\n\tfivepm = start\n\tfor result in results[1:]:\n\t\tif result.ts - start.ts >= datetime.timedelta(1):\n\t\t\tcountsPerDay.append(calcVisitorEntry(start, elevenam, fivepm, result))\n\t\t\tstart = result\n\t\t\tstart.ts = start.ts.replace(hour=0, minute=0, second=0, microsecond=0)\n\t\t\televenam = start\n\t\t\tfivepm = start\n\t\tif result.ts.hour <= 11:\n\t\t\televenam = result\n\t\tif result.ts.hour <= 17:\n\t\t\tfivepm = result\n\tcountsPerDay.append(calcVisitorEntry(start, elevenam, fivepm, results[-1]))\n\treturn countsPerDay\n\n\n@app.route('/api/visitorcount', methods=['GET'])\n@app.route('/api/visitorcount/', methods=['GET'])\n@app.route('/api/visitorcount/-', methods=['GET'])\ndef visitorcount(start=None, end=None):\n\t'''\n\tAPI providing accumulated visitor counts based on the VisitorCounter values\n\tstored in the database.\n\t'''\n\tif not current_user.is_authenticated():\n\t\tflask.abort(403)\n\tif not start:\n\t\t# Two Sundays ago\n\t\tstart = datetime.datetime.now() + datetime.timedelta(days=6-datetime.datetime.now().weekday() - 21)\n\telse:\n\t\tstart = datetime.datetime(*map(int, re.split('[^\\d]', day)[:-1]))\n\tstart = start.replace(hour=0, minute=0, second=0, microsecond=0)\n\tif not end:\n\t\tend = datetime.datetime.now() + datetime.timedelta(1)\n\telse:\n\t\tend = datetime.datetime(*map(int, re.split('[^\\d]', day)[:-1]))\n\tend = end.replace(hour=0, minute=0, second=0, microsecond=0)\n\n\tjson_results = []\n\tresults = VisitorCounter.query.filter(VisitorCounter.ts >= start,\n\t\t\t\t\t\t\t\t\t\t VisitorCounter.ts < end)\\\n\t\t\t\t\t\t\t\t .order_by(VisitorCounter.ts)\\\n\t\t\t\t\t\t\t\t .all()\n\tlatest = VisitorCounter.query.order_by(VisitorCounter.ts.desc()).first();\n\textra = {\n\t\t'end': (end + datetime.timedelta(-1)).isoformat(),\n\t\t'start': start.isoformat(),\n\t\t'latest': {\n\t\t\t'ts': latest.ts.isoformat(),\n\t\t\t'vc': latest.vc,\n\t\t\t'ut': latest.ut,\n\t\t\t'ut_hms': '{:d}:{:02d}:{:02d}'.format(latest.ut / 3600,\n\t\t\t\t(latest.ut / 60) % 60, latest.ut % 60),\n\t\t},\n\t\t'broker': {\n\t\t\t'ts': counterListener.ts.isoformat(),\n\t\t\t'vc': counterListener.vc,\n\t\t\t'ut': counterListener.ut,\n\t\t\t'ut_hms': '{:d}:{:02d}:{:02d}'.format(counterListener.ut / 3600,\n\t\t\t\t(counterListener.ut / 60) % 60, counterListener.ut % 60),\n\t\t},\n\t}\n\treturn flask.jsonify(items=accumulateVisitorsPerDay(results),\n\t\textra=extra)\n\nif __name__ == '__main__':\n\tapp.run(port=5001, debug=True)\n","sub_path":"vvmroster.py","file_name":"vvmroster.py","file_ext":"py","file_size_in_byte":19129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"285858747","text":"# Dependencies\nimport tweepy\nimport json\nimport time\n\n# Twitter API Keys\nconsumer_key = \"08EqISwEDtqFEkVcBhuyOanW9\"\nconsumer_secret = \"em4eZfyTs8AQoK7wrujJ5ASVjTgduUYqvJkE29bsEqfMmrHwbS\"\naccess_token = \"971208969124327425-NVqSLKf93E0DsaMMFYJY4MwJrIUPULD\"\naccess_token_secret = \"4UFYtnJCuTd6tzDtAOwxQtpOjHSGrhjzn7A2c2LnRHCeg\"\n\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\n\n\n# Create a function that tweets\n# CODE GOES HERE","sub_path":"ChatterBot.py","file_name":"ChatterBot.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"223591966","text":"\n\nfrom xai.brain.wordbase.nouns._profiteer import _PROFITEER\n\n#calss header\nclass _PROFITEERS(_PROFITEER, ):\n\tdef __init__(self,): \n\t\t_PROFITEER.__init__(self)\n\t\tself.name = \"PROFITEERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"profiteer\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_profiteers.py","file_name":"_profiteers.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"252331477","text":"#!/usr/bin/python3\n\n\ndef main(h, w, a, b, c):\n\n h, w = sorted([h, w])\n a, b, c = sorted([a, b, c])\n\n if h > a and w > b:\n return True\n\n return False\n\n\nif __name__ == \"__main__\":\n print(main(5, 10, 7, 4, 5))\n","sub_path":"door_and_box/door_and_box.py","file_name":"door_and_box.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"215215985","text":"import streamlit as st\n\nimport pandas as pd\nimport numpy as np\n\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\nimport altair as alt\n\n\nfrom lrg_omics.LSARP.tools import get_shipments, get_broad_plates, get_proteomics_plates,\\\n get_metabolomics_plates, get_growth_protein, get_growth_monitor\n\nst.beta_set_page_config(layout='wide')\nst.sidebar.title('LSARP Metadata')\n\nshow = st.sidebar.selectbox('Show', ['APL Shipments', 'Broad', 'Metabolomics', 'Proteomics', 'Growth'])\n\nif show == 'APL Shipments':\n st.title('APL Shipments')\n\n shipments = get_shipments().fillna('')\n gprs = shipments.groupby('PLATE_ID')\n\n _plates = list( gprs.groups.keys() )\n show_element = st.selectbox('Show', ['Layout', 'Table', 'Statistics'])\n \n plates = st.multiselect('Plate', _plates + ['All plates'] )\n\n if plates is not None:\n if 'All plates' in plates: plates = _plates\n for plate in plates:\n\n st.write(plate)\n _plate = gprs.get_group(plate).fillna('')\n\n if show_element == 'Layout':\n crosstab = pd.crosstab(_plate.PLATE_COL, _plate.PLATE_ROW, \n _plate.ISOLATE_NBR, aggfunc=sum)\n\n st.dataframe(crosstab) \n\n if show_element == 'Table':\n st.dataframe(_plate)\n\n st.markdown('---')\n\n if show_element == 'Statistics':\n\n print(shipments.columns)\n _data = shipments['DATE shipped'].value_counts().to_frame().reset_index()\n _data.columns = ['DATE shipped', '# Isolates']\n\n chart = alt.Chart(_data).mark_bar()\\\n .encode(y='# Isolates', x='DATE shipped')\n\n st.altair_chart(chart, use_container_width=True)\n\n _data = shipments.ORGANISM.value_counts().to_frame().reset_index()\n _data.columns = ['ORGANISM', 'Counts']\n\n chart = alt.Chart(_data).mark_bar()\\\n .encode(x='ORGANISM', y='Counts')\n\n st.altair_chart(chart, use_container_width=True)\n\n\n\nif show == 'Broad':\n st.title('Broad DNA plates')\n\n broad_plates = get_broad_plates()\n grps = broad_plates.groupby('Filename')\n\n _plates = list( grps.groups.keys() )\n plates = st.multiselect('Plate', _plates+['All plates'])\n\n if plates is not None:\n if 'All plates' in plates: plates = _plates\n for plate in plates:\n st.header(plate)\n _data = grps.get_group(plate)\n st.dataframe(_data)\n\n _bi_counts = _data.iloc[:,3].value_counts()\n _broad_id_counts = _data.iloc[:,1].value_counts()\n\n if _bi_counts.max() > 1:\n st.dataframe(_bi_counts[_bi_counts>1].to_frame()\\\n .style.highlight_max(axis=0, color='red'))\n \n if _broad_id_counts.max() > 1:\n st.write(_broad_id_counts[_broad_id_counts>1].to_frame()\\\n .style.highlight_max(axis=0, color='red'))\n st.markdown('---')\n\n\n\nif show == 'Proteomics':\n st.title('Proteomics plates')\n\n proteomics_plates = get_proteomics_plates()\n #grps = proteomics_plates\n\n st.dataframe(proteomics_plates)\n\n\nif show == 'Metabolomics':\n st.title('Metabolomics plates')\n\n metabolomics_plates = get_metabolomics_plates()\n grps = metabolomics_plates.groupby('PLATE_ID')\n\n show_element = st.selectbox('Show', ['Layout', 'Table', 'Statistics'])\n\n _plates = list( grps.groups.keys() )\n plates = st.multiselect('Plates', _plates+['All plates'])\n\n ms_mode = st.selectbox('MS-Mode', ['Positive', 'Negative'])\n\n if ms_mode == 'Positive': ms_mode = 'pos'\n if ms_mode == 'Negative': ms_mode = 'neg'\n\n if show_element == 'Layout':\n if 'All plates' in plates: plates = _plates\n for plate in plates:\n st.header(plate)\n tmp = grps.get_group(plate)[['PLATE_ROW', 'PLATE_COL', 'BI_NBR']].fillna('').drop_duplicates()\n crosstab = pd.crosstab(tmp['PLATE_ROW'], tmp['PLATE_COL'], tmp['BI_NBR'], aggfunc=sum)\n st.dataframe(crosstab)\n st.markdown('---')\n\n elif show_element == 'Table':\n \n if plates is not None:\n if 'All plates' in plates: plates = _plates\n if ms_mode == 'Positive': ms_mode = 'pos'\n if ms_mode == 'Negative': ms_mode = 'neg'\n for plate in plates:\n st.header(plate)\n tmp = grps.get_group(plate)\n tmp = tmp[tmp.MS_MODE.str.lower() == ms_mode]\n st.dataframe(tmp)\n st.markdown('---')\n\nif show == 'Growth':\n st.title('Isolate growth data')\n\n show_element = st.selectbox('Show', ['Layout', 'Table', 'Statistics'])\n\n growth_type = st.selectbox('Growth Type', ['Protein', 'Monitor'])\n\n if growth_type == 'Protein':\n growth_data = get_growth_protein()\n elif growth_type == 'Monitor':\n growth_data = get_growth_monitor()\n timepoint = st.selectbox('Time', growth_data.TIME.drop_duplicates().values )\n growth_data = growth_data[growth_data.TIME == timepoint]\n\n grps = growth_data.groupby('PLATE_ID')\n\n od_min = growth_data.OD.min()\n od_max = growth_data.OD.max()\n\n _plates = list( grps.groups.keys() )\n plates = st.multiselect('Plates', _plates+['All plates'])\n\n if plates is not None:\n if 'All plates' in plates: plates = _plates\n for plate in plates:\n _data = grps.get_group(plate)\n if len(_data) == 0:\n continue\n st.header(plate)\n\n if show_element == 'Table':\n st.dataframe(_data)\n\n if show_element == 'Layout':\n crosstab = pd.crosstab(_data['PLATE_ROW'], _data['PLATE_COL'], _data['OD'], aggfunc=np.mean)\n cm = sns.light_palette(\"green\", as_cmap=True)\n st.dataframe(crosstab.style.background_gradient(cmap=cm, low=od_min, high=od_max))\n \n st.markdown('---')\n\n","sub_path":"streamlit/LSARP_data.py","file_name":"LSARP_data.py","file_ext":"py","file_size_in_byte":5934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497948402","text":"import numpy as np \r\nimport cv2\r\n# original RGB image\r\ntulips = cv2.imread('C:\\\\Users\\\\smriti rastogi\\\\Pictures\\\\Saved Pictures\\\\tulips.jfif')\r\ncv2.imshow('original_color_image',tulips)\r\ncv2.moveWindow('original_color_image',400,25)\r\n\r\n# gray image\r\n# the 0 in second argument loads a grayscale image\r\ntulips_grayscale = cv2.imread('C:\\\\Users\\\\smriti rastogi\\\\Pictures\\\\Saved Pictures\\\\tulips.jfif', 0)\r\ncv2.imshow('gray_image',tulips_grayscale)\r\n\r\n# or by\r\n\r\ntulips_grayscale_1 = cv2.cvtColor(tulips,cv2.COLOR_BGR2GRAY)\r\ncv2.imshow('gray_img_2',tulips_grayscale_1)\r\ncv2.moveWindow('gray_img_2',25,300)\r\n\r\n# HSV image(hue,saturation,value)\r\nhsv_image = cv2.cvtColor(tulips,cv2.COLOR_BGR2HSV)\r\ncv2.imshow('hsv_color_image',hsv_image)\r\ncv2.moveWindow('hsv_color_image',800,25)\r\n\r\ncv2.waitKey(10000)\r\ncv2.destroyAllWindows()\r\n","sub_path":"color_spaces.py","file_name":"color_spaces.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"575246394","text":"#-*-coding:utf-8-*-\n\nimport requests\nimport os\n\n\n\ndef getHeaders():\n\t'''获取请求头信息'''\n\theaders={\n \"Content-Type\": \"application/json\",\n \"App-Id\": \"wob071913289742227\",\n \"appsecret\": \"$2b$10$1ZbzRhmxxPZAtwzb/2zFc..lvkByyQiJFrxITmaV0tRQXAHuWSoN2\"\\\n }\n\treturn headers\n\ndef post(api,data):\n\t'''\n\t对post请求进行二次封装\n\t:parameter api:请求ip地址+api\n\t:parameter data:请求参数\n\t'''\n\tr=requests.post(url='http://47.75.105.222/'+api,json=data,timeout=6,headers=getHeaders())\n\treturn r","sub_path":"page/ntfgetnew.py","file_name":"ntfgetnew.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"328145005","text":"import datetime\nimport json\n\nfrom flask_restplus import Namespace, fields, Resource, reqparse\nimport pymysql\nimport jwt\nfrom settings import DATABASES, JWT\n\nPay = Namespace('pay', description='급여')\n\nmodel_pay = Pay.model('Pay Data', {\n 'token': fields.String(description='로그인 토큰', required=True),\n 'workplace_id': fields.String(description='매장 아이디', required=True),\n 'employee_id': fields.String(description='알바 아이디', required=True),\n 'year': fields.Integer(description='Year', required=True),\n 'month': fields.Integer(description='Month', required=True),\n})\n\n\n@Pay.route('')\nclass PostLogin(Resource):\n @Pay.expect(model_pay)\n @Pay.response(200, 'OK')\n @Pay.response(400, 'Bad Request')\n @Pay.response(401, 'Unauthorized')\n @Pay.response(500, 'Internal Server Error')\n def post(self):\n '''급여 조회'''\n __parser = reqparse.RequestParser()\n __parser.add_argument('token', type=str)\n __parser.add_argument('workplace_id', type=str)\n __parser.add_argument('employee_id', type=str)\n __parser.add_argument('year', type=int)\n __parser.add_argument('month', type=int)\n __args = __parser.parse_args()\n\n __token = __args['token']\n __workplace_id = __args['workplace_id']\n __employee_id = __args['employee_id']\n __year = __args['year']\n __month = __args['month']\n\n\n try:\n __auth = jwt.decode(__token, JWT[\"key\"], algorithms=\"HS256\")\n except:\n return {'result': 'Fail', \"error\": \"Auth Failed\"}, 401\n\n try:\n alba_db = pymysql.connect(user=DATABASES['user'],\n passwd=DATABASES['passwd'],\n host=DATABASES['db_host'],\n db=DATABASES['db_name'],\n charset=DATABASES[\"charset\"])\n except:\n return {'result': 'Fail', \"error\": \"DB Connection Error\"}, 500\n\n cursor = alba_db.cursor(pymysql.cursors.DictCursor)\n query = 'select * from workplace_schedule ' \\\n 'where workplace_id = \"{workplace_id}\" and employee_id = \"{employee_id}\" ' \\\n 'and Year(date) = {year} and Month(date) = {month} and is_checked = 2;'\n\n\n cursor.execute(query.format(workplace_id=__workplace_id,\n employee_id=__employee_id,\n year=__year,\n month=__month\n ))\n __result = cursor.fetchall()\n\n def default(o):\n if isinstance(o, (datetime.date, datetime.datetime, datetime.timedelta)):\n return o.__str__()\n\n __result = json.loads(json.dumps(__result, default=default))\n return {\n 'result': 'Success',\n 'data': __result\n }\n","sub_path":"Api/pay.py","file_name":"pay.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"174317702","text":"import math\nimport cv2\nimport numpy as np\nimport tensorflow\nfrom skimage import color\nfrom scipy import ndimage\nfrom skimage.measure import label\nfrom scipy import ndimage\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom vektor import distance, point2line\n\n\ndef resize_region(region):\n '''Transformisati selektovani region na sliku dimenzija 28x28'''\n return cv2.resize(region,(28,28), interpolation = cv2.INTER_NEAREST)\n\ncnt = -1\ndef next_id():\n global cnt\n cnt += 1\n return cnt\n\ndef get_br_img(broj, frame):\n\n y1 = broj.y - 7\n y2 = broj.y + 21\n x1 = broj.x - 7\n x2 = broj.x + 21\n\n br_img = frame[y1:y2, x1:x2]\n br_img_normalizovan = tensorflow.keras.utils.normalize(br_img)\n\n return br_img_normalizovan\n\ndef ne_treba_detektovati(br):\n if (br.x - 16 <= 0):\n return True\n if (br.y - 16 <= 0):\n return True\n\ndef brojevi_u_radiusu(broj, brojevi, radius):\n\n u_radiusu = []\n koo_broj = (int(broj.x), int(broj.y))\n\n for br in brojevi:\n\n tracked_item_koo = (int(br.x), int(br.y))\n center_distance = distance(koo_broj, tracked_item_koo)\n\n if(center_distance < radius):\n u_radiusu.append(br)\n return u_radiusu\n\ndef draw_detection_rectangle(br, detected_digit, img):\n y1 = br.y - 17\n y2 = br.y + 11\n x1 = br.x - 16\n x2 = br.x + 12\n cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 1)\n cv2.putText(img, str(detected_digit), (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n #cv2.imshow('img', img)\n\n\ndef tacka_presla_liniju(point, line):\n\n line_distance, nearest_point, radius = point2line(point, (line['x1'], line['y1']), (line['x2'], line['y2']))\n\n return (radius > 0 and line_distance < 9)\n\ndef br_presao_liniju(br, line):\n\n centar = (br.x, br.y)\n bottom_left_corner = (br.x, br.y + br.h // 2)\n return tacka_presla_liniju(centar, line) or tacka_presla_liniju(bottom_left_corner, line)\n\nclass Number:\n\n def __init__(self,x,y,w,h):\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n self.id = next_id()\n self.predicted_br = None\n\nmodel = tensorflow.keras.models.load_model('neuronska.model')\n\n\ndef detect_line(img):\n\n kernel_line = np.ones((2,2),np.uint8)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n erosion = cv2.erode(gray, kernel_line,iterations = 1)\n #Second and third arguments are our minVal and maxVal respectively.Third argument is aperture_size default 3\n edges = cv2.Canny(erosion,50,150,3)\n lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=1, maxLineGap=5)\n\n x1 = lines[0][0][0]\n y1 = lines[0][0][1]\n x2 = lines[0][0][2]\n y2 = lines[0][0][3]\n\n return { 'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2 }\n\ndef get_sum(video_path):\n\n frame_num = 0;\n video = cv2.VideoCapture(video_path)\n video.set(1, frame_num)\n kernel = np.ones((3, 3), np.uint8) # strukturni element 2x2 blok\n\n brojevi = []\n suma = 0\n\n passed_ids = []\n current_id = 0\n brojac = 0\n suma = 0\n\n\n while True:\n\n frame_num += 1\n ret_val, frame = video.read()\n\n if not ret_val:\n break\n\n frame_org = frame.copy()\n\n lower = np.array([230, 230, 230])\n upper = np.array([255, 255, 255])\n # Threshold the HSV image to get only white colors\n mask = cv2.inRange(frame, lower, upper)\n\n img_dilate = cv2.dilate(mask, kernel)\n img_dilate = cv2.dilate(img_dilate, kernel)\n\n\n image_orig = frame.copy()\n contours, hierarchy = cv2.findContours(img_dilate.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n sorted_regions = [] # lista sortiranih regiona po x osi (sa leva na desno)\n regions_array = []\n\n line = detect_line(frame)\n\n x1 = line['x1']\n y1 = line['y1']\n x2 = line['x2']\n y2 = line['y2']\n\n for contour in contours:\n x, y, w, h = cv2.boundingRect(contour)\n\n area = cv2.contourArea(contour)\n if area > 100 and h < 100 and h > 8 and w > 6:\n\n broj = Number(x, y, w, h)\n\n if ne_treba_detektovati(broj):\n continue\n\n brojevi_blizu = brojevi_u_radiusu(broj, brojevi, 22)\n\n if len(brojevi_blizu) == 0:\n\n br_img = get_br_img(broj, mask)\n predictions = model.predict([[br_img]])\n predicted_br = np.argmax(predictions[0])\n broj.predicted_br = predicted_br\n brojevi.append(broj)\n continue\n\n for broj in brojevi:\n draw_detection_rectangle(broj, broj.predicted_br, frame)\n if not br_presao_liniju(broj, line):\n continue\n if (passed_ids.__contains__(broj.id)):\n continue\n passed_ids.append(broj.id)\n brojac += 1\n suma += broj.predicted_br\n print('brojac:', str(brojac), 'brojac + ' + str(broj.predicted_br), ' = ',\n str(suma))\n\n region = img_dilate[y:y + h + 1, x:x + w + 1]\n\n regions_array.append([resize_region(region), (x, y, w, h)])\n cv2.rectangle(image_orig, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n regions_array = sorted(regions_array, key=lambda item: item[1][0])\n sorted_regions = sorted_regions = [region[0] for region in regions_array]\n\n cv2.imshow('sel_r', image_orig)\n\n if cv2.waitKey(1) & 0xFF == ord('c'):\n break\n video.release()\n cv2.destroyAllWindows()\n return suma\n\n\ndef proba():\n prediction_results = []\n\n for i in range(10):\n video_name = 'video-' + str(i) + '.avi'\n\n sum = get_sum(video_name)\n prediction_results.append({'video': video_name, 'sum': sum})\n print(video_name, sum)\n\n\nproba()","sub_path":"proj.py","file_name":"proj.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"425501235","text":"import pygame\r\n\r\nfrom pygame.sprite import Group\r\n\r\nfrom button import Button\r\nfrom bullet import Bullet\r\nfrom settings import Settings\r\nfrom ship import Ship\r\nfrom rectangle import Rectangle\r\nfrom game_stats import GameStats\r\nimport game_functions as gf\r\n\r\ndef run_game():\r\n #初始化游戏并创建一个屏幕对象\r\n pygame.init()\r\n ai_settings=Settings()\r\n screen=pygame.display.set_mode(\r\n (ai_settings.screen_width,ai_settings.screen_height))#创建一个窗口\r\n pygame.display.set_caption('hit')#窗口名\r\n \r\n #设置背景色\r\n bg_color=ai_settings.bg_color\r\n \r\n #创建一艘飞船\r\n ship=Ship(screen,ai_settings)\r\n \r\n #创建一个矩形\r\n rectangle=Rectangle(ai_settings,screen)\r\n\r\n #创建play按钮\r\n msg='play'\r\n play_button=Button(ai_settings,screen,msg)\r\n \r\n #创建控制游戏的实例\r\n stats=GameStats(ai_settings)\r\n \r\n \r\n bullets=pygame.sprite.Group()#这个编组是pygame.sprite.Group 类的一个实例;pygame.sprite.Group\r\n #类似于列表,但提供了有助于开发游戏的额外功 能。\r\n rectangles=pygame.sprite.Group()\r\n rectangles.add(rectangle)\r\n \r\n #开始游戏的主循环\r\n while True:\r\n \r\n #监视鼠标和电脑事件\r\n gf.check_events(ai_settings, stats,play_button,screen, ship, bullets)\r\n \r\n \r\n if stats.game_active:\r\n \r\n ship.update()\r\n \r\n #删除已消失的子弹\r\n gf.update_bullets(bullets)\r\n \r\n gf.update_rectangles(ai_settings,rectangle)\r\n \r\n gf.update_bullets(bullets)\r\n \r\n #更新屏幕上的图像并切换到新屏幕 \r\n \r\n \r\n screen.fill(ai_settings.bg_color)\r\n #背景色填充屏幕\r\n \r\n ship.blitme()\r\n gf.update_screen(ai_settings,stats,play_button,ship, bullets,rectangle,rectangles )\r\n #让最近绘制的屏幕可见\r\n pygame.display.flip()\r\nrun_game()\r\n\r\n\r\n","sub_path":"run_game.py","file_name":"run_game.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"438548686","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 11 15:23:35 2017\n\n@author: mmrosek\n\"\"\"\nfrom skimage.filters import threshold_otsu, rank, threshold_local\nimport imageio\nimport skimage.filters as filters\nimport skimage.morphology as morphology\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport skimage\nimport time\n\n### Read in video file and convert frames to RGB ###\ndef read_in_video(video_path, color, max_frames=np.inf):\n # Read in video\n reader = imageio.get_reader(str(video_path))\n # Generates dictionary containing information about video\n info_dict = reader.get_meta_data()\n height, width = info_dict['size']\n # Determine number of frames to extract\n if max_frames < np.inf:\n nframes = max_frames\n else:\n nframes = info_dict['nframes']\n if color in \"RGBrgb\": \n # Pre-allocates array for video file to populate with rgb frames\n video_array = np.zeros(shape=(nframes, height, width, 3), dtype=np.uint8)\n # Populate video_array with video frames\n for idx, im in enumerate(reader):\n video_array[idx] = im\n if idx >= nframes-1:\n break \n else:\n video_array = np.zeros(shape=(nframes, height, width), dtype=np.uint8)\n for idx, im in enumerate(reader):\n # Converts rgb frames to grayscale\n video_array[idx] = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n if idx >= nframes-1:\n break\n return(video_array)\n\nvideo = 'DsRed2-HeLa_3_23_LLO_1 (2) (Converted).mov_every_10th_frame.mov'\noffset = -0.2\n\n# Read in video file\nvideo_frames = read_in_video(\"/home/mmrosek/Documents/shannon_vids/{}\".format(video), \"gray\")\n\n\n####################################################################################################\n\ndef hull_and_thresh_hist_eq(image, block_size_img_to_keep, dilation_disk_size, median_disk_size, hist_eq = False, low_res_thresh_for_hull = False, block_size_thresh_hull = 105):\n \n if hist_eq == True:\n \n image = cv2.equalizeHist(image)\n \n if low_res_thresh_for_hull == False:\n\n adaptive_thresh_hull = threshold_local(image, block_size_thresh_hull, offset = offset) # Higher block size = less granular, cells more easily separated\n thresh_hull = image > adaptive_thresh_hull\n \n else:\n \n # Use when cells are close together --> less granular so helps keep them separated but less detailed\n ret , thresh_hull = cv2.threshold(image,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n \n adaptive_thresh_to_keep = threshold_local(image, block_size_img_to_keep, offset = offset) # Offset = 0 results in large portion of image being white\n thresh_to_keep = image > adaptive_thresh_to_keep\n \n # Dilation\n dilation_disk = morphology.disk(dilation_disk_size)\n new_mask = morphology.binary_dilation(thresh_hull, selem = dilation_disk)\n \n # Median filtering\n median_filtering_disk = morphology.disk(median_disk_size)\n filtered = np.array(filters.median(new_mask, selem = median_filtering_disk), dtype = np.bool)\n \n # Removing small objects\n new_mask = morphology.remove_small_objects(filtered, min_size = 640, connectivity = 8)\n \n # Computing convex hull\n hull = morphology.convex_hull_object(new_mask)\n\n return(hull,thresh_to_keep)\n\n####################################################################################################\n\n### Frame-to-frame cell segmentation ###\n\n\ndef hull_overlap(hull_prev_frame, hull_curr_frame):\n \n return ( ( ( np.sum(hull_prev_frame) - np.sum(hull_curr_frame ^ hull_prev_frame) ) / np.sum(hull_prev_frame) ) ) \n\n\nsegmentation_vid_save_path = '/home/mmrosek/Documents/segmented_cell_vid_arrays/' \ndict_save_path = segmentation_vid_save_path\nblock_size_img_to_keep = 25\n\ndilation_disk_size_list = [6, 5, 4, 2.5, 2.5]\n\nmedian_disk_size_list = [1, 1.5, 1.5, 1.5, 1.5]\n\nlabel_of_interest_list = [1, 4, 3, 10, 14] \n\n\n#dilation_disk_size_list = [6]\n#\n#median_disk_size_list = [1]\n#\n#label_of_interest_list = [1]\n\n\n\nlow_res_label_list = []\n\n\n# No significance, just to avoid error on first frame\nhull_prev_frame = 1 \nlabels_prev_frame = 1\n \nfirst_frame = 0\n\nfirst_hull_overlap_threshold = 0.95\n\ndiff_label_hull_overlap_threshold = 0.95\n\nnew_disk_size_hull_overlap_threshold = 0.85\n\nlabel_count = 1\n\nframes_in_low_res_count = 0\n\nstart = time.time()\n\nfor label_num in label_of_interest_list:\n \n dilation_disk_size = dilation_disk_size_list[label_count-1]\n \n median_disk_size = median_disk_size_list[label_count-1]\n \n broken_frame_dict = {}\n \n print(\"Label count: {}\\n\".format(label_count))\n \n print('Label Num, Dil Disk, Med Disk: {}'.format((label_num, dilation_disk_size, median_disk_size)))\n \n # Initializing array for hull_i+1\n label_vid_array = np.zeros(shape = video_frames.shape, dtype = 'uint8')\n \n for frame_num in range(first_frame,video_frames.shape[0]):\n \n image = video_frames[frame_num]\n \n if label_count in low_res_label_list:\n \n frames_in_low_res_count += 1 # Eventually need to try high res thresholding so remove label_count from low_res_list periodically\n \n if frames_in_low_res_count == 20:\n \n low_res_label_list.remove(label_count)\n \n print('\\nRemoved label from low res label list\\n')\n \n # Calculate convex hull and thresholded image of current frame\n hulls_curr_frame, thresh_img_curr_frame = hull_and_thresh_hist_eq(image, block_size_img_to_keep, dilation_disk_size , median_disk_size, hist_eq = False, low_res_thresh_for_hull = True)\n \n else:\n \n # Calculate convex hull and thresholded image of current frame\n hulls_curr_frame, thresh_img_curr_frame = hull_and_thresh_hist_eq(image, block_size_img_to_keep, dilation_disk_size , median_disk_size, hist_eq = False)\n \n \n # Generating labels for convex hulls of current frame\n labels_curr_frame, num_labels_curr_frame = skimage.measure.label(hulls_curr_frame, return_num = True)\n \n # Isolate a single hull\n hull_curr_frame = labels_curr_frame == label_num # No +1 b/c label_num is not coming from range()\n \n overlap = hull_overlap(hull_prev_frame, hull_curr_frame) \n \n # Checking to ensure overlap of hull_i+1 is > 80% hull_i+1 from previous frame\n if ( overlap > first_hull_overlap_threshold ) or ( frame_num == first_frame ): \n \n if frame_num % 100 == 0:\n \n print(\"Frame: {0}, overlap: {1}, disk: {2}, label: {3}\\n\".format(frame_num, overlap, dilation_disk_size, label_num ))\n \n # Isolate part of thresholded image overlapped by hull_i+1\n hull_segmentation_curr_frame = hull_curr_frame * thresh_img_curr_frame\n \n # Add isolated part of thresholded image to new array\n label_vid_array[frame_num] = hull_segmentation_curr_frame\n \n # Converting number of labels from current frame to number of labels from the now previous frame\n num_labels_prev_frame = num_labels_curr_frame\n\n # Converting hulls from current frame to hulls from the now previous frame\n hull_prev_frame = hull_curr_frame\n \n \n else: # If hull_i+1 doesn't overlap enough with hull_i+1 from previous frame, see if it matches with another label\n \n print( 'Overlap didnt pass threshold: {}'.format( overlap ) )\n \n \n for curr_frame_label_num in range(1, num_labels_curr_frame + 1): # Check if hull of interest matches hull with diff label_num\n \n hull_curr_frame = labels_curr_frame == curr_frame_label_num \n \n overlap = hull_overlap(hull_prev_frame, hull_curr_frame) \n \n \n if ( overlap > diff_label_hull_overlap_threshold ) or ( frame_num == first_frame ): # Need to make 0.95 an argument to function\n \n print( 'Overlap passed threshold for label: {0}'.format(curr_frame_label_num ) ) \n \n hull_segmentation_curr_frame = hull_curr_frame * thresh_img_curr_frame\n \n label_vid_array[frame_num] = hull_segmentation_curr_frame\n \n hull_prev_frame = hull_curr_frame\n \n num_labels_prev_frame = num_labels_curr_frame\n \n print('New label num frame {}\\n'.format(frame_num))\n \n # Re-assigning label_num to speed up label search process for next frame\n label_num = curr_frame_label_num\n \n break\n \n \n if curr_frame_label_num == num_labels_curr_frame: # If the above loop didn't work, try different dilation disk sizes with each label\n \n # None of the existing hulls are the right shape, trying different dilation disk sizes\n x = dilation_disk_size\n \n if label_count in low_res_label_list:\n \n low_res_dil_disk_sizes = [ max(1.05, x ** ( 1 - ( i/25 )**3 ) ) if i % 2 == 0 else min(40, ( x ** ( 1 + ( i/25 )**3 ) )) for i in range(20)] \n \n elif x >= 3:\n \n new_dil_disk_sizes = [ max(1.05, x ** ( 1 - ( i/14 )**3 ) ) if i % 2 == 0 else min(40, ( x ** ( 1 + ( i/14 )**3 ) )) for i in range(16)]\n \n else:\n \n new_dil_disk_sizes = [ max(1.05, x ** ( 1 - ( i/10 )**3 ) ) if i % 2 == 0 else min(40, ( x ** ( 1 + ( i/10 )**3 ) )) for i in range(18)]\n \n max_overlap = 0\n \n opt_dil_disk_size = .1\n \n opt_label_num = .1\n \n print('Trying new disk sizes frame {}'.format(frame_num))\n \n dil_disk_count = 0\n \n for dil_disk_size in new_dil_disk_sizes:\n \n dil_disk_count += 1\n \n if label_count in low_res_label_list:\n \n hulls_curr_frame, thresh_img_curr_frame = hull_and_thresh_hist_eq(image, block_size_img_to_keep, dil_disk_size , median_disk_size, hist_eq = False, low_res_thresh_for_hull = True)\n \n else:\n \n hulls_curr_frame, thresh_img_curr_frame = hull_and_thresh_hist_eq(image, block_size_img_to_keep, dil_disk_size , median_disk_size, hist_eq = False)\n \n \n labels_curr_frame, num_labels_curr_frame = skimage.measure.label(hulls_curr_frame, return_num = True)\n \n for curr_frame_label_num in range(1, num_labels_curr_frame + 1): # Check if hull_i+1 matches hull with diff label_num\n \n hull_curr_frame = labels_curr_frame == curr_frame_label_num \n \n test_overlap = hull_overlap(hull_prev_frame, hull_curr_frame) \n \n\n if (test_overlap - 0.001) > max_overlap: # Saving optimal disk size based on max overlap\n \n max_overlap = test_overlap\n \n opt_dil_disk_size = dil_disk_size\n \n opt_label_num = curr_frame_label_num\n \n \n if ( dil_disk_count == len(new_dil_disk_sizes) ): # Tested each disk size...\n \n # If overlap passes new_disk_size_hull_overlap_threshold or we are already using low res threshold...\n if ( max_overlap > new_disk_size_hull_overlap_threshold ) or ( label_count in low_res_label_list ):\n \n print('Max overlap: {0} for new disk size: {1}'.format(max_overlap, opt_dil_disk_size))\n \n if label_count in low_res_label_list:\n \n print('Low res label: {}'.format(label_count))\n \n hulls_curr_frame, thresh_img_curr_frame = hull_and_thresh_hist_eq(image, block_size_img_to_keep, opt_dil_disk_size , median_disk_size, hist_eq = False, low_res_thresh_for_hull = True)\n \n else:\n \n hulls_curr_frame, thresh_img_curr_frame = hull_and_thresh_hist_eq(image, block_size_img_to_keep, opt_dil_disk_size , median_disk_size, hist_eq = False) \n \n \n labels_curr_frame, num_labels_curr_frame = skimage.measure.label(hulls_curr_frame, return_num = True)\n \n hull_curr_frame = labels_curr_frame == opt_label_num\n \n hull_segmentation_curr_frame = hull_curr_frame * thresh_img_curr_frame\n \n label_vid_array[frame_num] = hull_segmentation_curr_frame\n \n hull_prev_frame = hull_curr_frame \n \n broken_frame_dict[frame_num] = (max_overlap, opt_dil_disk_size)\n \n dilation_disk_size = opt_dil_disk_size\n \n # Re-assigning label_num to speed up label search process for next frame\n label_num = opt_label_num\n \n print(\"Didn't try low res or already low res\\n\")\n \n \n else: # Trying low res threshold to try to improve upon max_threshold\n \n x = dilation_disk_size\n \n print('Low_res_dil_disk_size being used to initiate low_res_dil_disk_sizes: {}'.format(x))\n \n low_res_dil_disk_sizes = [ max(1.05, x ** ( 1 - ( i/25 )**3 ) ) if i % 2 == 0 else min(30, ( x ** ( 1 + ( i/25 )**3 ) )) for i in range(20)]\n \n max_low_res_overlap = 0\n \n opt_low_res_dil_disk_size = .1\n \n opt_low_res_label_num = .1\n \n print('Trying new low_res disk sizes frame {}'.format(frame_num))\n \n low_res_dil_disk_count = 0\n \n for dil_disk_size in low_res_dil_disk_sizes:\n \n low_res_dil_disk_count += 1\n \n hulls_curr_frame, thresh_img_curr_frame = hull_and_thresh_hist_eq(image, block_size_img_to_keep, dil_disk_size , median_disk_size, hist_eq = False, low_res_thresh_for_hull = True)\n \n labels_curr_frame, num_labels_curr_frame = skimage.measure.label(hulls_curr_frame, return_num = True)\n \n \n for curr_frame_label_num in range(1, num_labels_curr_frame + 1): # Check if hull_i+1 matches hull with diff label_num\n \n hull_curr_frame = labels_curr_frame == curr_frame_label_num \n \n test_overlap = hull_overlap(hull_prev_frame, hull_curr_frame) \n \n \n if (test_overlap - 0.001) > max_low_res_overlap: # Saving optimal disk size based on max overlap\n \n max_low_res_overlap = test_overlap\n \n opt_low_res_dil_disk_size = dil_disk_size\n \n opt_low_res_label_num = curr_frame_label_num\n \n \n if ( low_res_dil_disk_count == len(low_res_dil_disk_sizes) ): # Tested each low_res disk size...\n \n print('Max normal overlap: {}'.format(max_overlap))\n \n print('Max low res overlap: {}'.format(max_low_res_overlap))\n \n if max_overlap > max_low_res_overlap:\n \n print('Max overlap: {0} for new disk size: {1}\\n'.format(max_overlap, opt_dil_disk_size))\n \n hulls_curr_frame, thresh_img_curr_frame = hull_and_thresh_hist_eq(image, block_size_img_to_keep, opt_dil_disk_size , median_disk_size, hist_eq = False) \n \n labels_curr_frame, num_labels_curr_frame = skimage.measure.label(hulls_curr_frame, return_num = True)\n \n hull_curr_frame = labels_curr_frame == opt_label_num\n \n hull_segmentation_curr_frame = hull_curr_frame * thresh_img_curr_frame\n \n label_vid_array[frame_num] = hull_segmentation_curr_frame\n \n hull_prev_frame = hull_curr_frame \n \n broken_frame_dict[frame_num] = (max_overlap, opt_dil_disk_size)\n \n dilation_disk_size = opt_dil_disk_size\n \n # Re-assigning label_num to speed up label search process for next frame\n label_num = opt_label_num\n \n else:\n \n print('Max low res overlap: {0} for disk size: {1}'.format(max_low_res_overlap, opt_low_res_dil_disk_size))\n \n hulls_curr_frame, thresh_img_curr_frame = hull_and_thresh_hist_eq(image, block_size_img_to_keep, opt_low_res_dil_disk_size , median_disk_size, hist_eq = False, low_res_thresh_for_hull = True) \n \n labels_curr_frame, num_labels_curr_frame = skimage.measure.label(hulls_curr_frame, return_num = True)\n \n hull_curr_frame = labels_curr_frame == opt_low_res_label_num\n \n hull_segmentation_curr_frame = hull_curr_frame * thresh_img_curr_frame\n \n label_vid_array[frame_num] = hull_segmentation_curr_frame\n \n hull_prev_frame = hull_curr_frame \n \n broken_frame_dict[frame_num] = (max_low_res_overlap, opt_low_res_dil_disk_size)\n \n dilation_disk_size = opt_low_res_dil_disk_size\n \n # Re-assigning label_num to speed up label search process for next frame\n label_num = opt_low_res_label_num\n \n low_res_label_list.append(label_count) # This label is now using low res thresholding\n \n print('\\nLabel {} now in low_res_label_list\\n'.format(label_count))\n \n \n\n np.save(segmentation_vid_save_path + video + '/hull_{0}_segmentation_7_26_{1}.npy'.format(label_count, block_size_img_to_keep), label_vid_array)\n \n del label_vid_array\n \n np.save(dict_save_path + video + '/broken_frames_dict_label_{0}_7_26_{1}.npy'.format(label_count, block_size_img_to_keep), broken_frame_dict)\n \n label_count+=1\n\n\nend = time.time()\nprint(end-start)\n\n#####################################################################################################################################################################\n#####################################################################################################################################################################\n\n# Debugging\n\narray_name = \"/hull_1_segmentation_7_25_25.npy\"\n\n\nhull_1_array = np.load(segmentation_vid_save_path + video + array_name)\n\n\nplt.imshow(hull_1_array[200], cmap='gray')\n\nplt.imshow(label_vid_array[201], cmap='gray')\n\n##########################################################\n\n\ndilation_disk_size_list = [5, 5, 4, 2.5, 2.5]\n\nmedian_disk_size_list = [1.25, 1.5, 1.5, 1.5, 1.5]\n\nlabel_of_interest_list = [1, 4, 3, 10, 14] \n\nimage = video_frames[200]\n\nc1,t1 = hull_and_thresh_hist_eq(image,25, 1.9, 1, False, False)\n\nplt.imshow(t1, cmap = 'gray')\n\nplt.imshow(c1, cmap='gray')\n\nplt.imshow(t1*c1, cmap='gray')\n\nlabels1, num1 = skimage.measure.label(c1, return_num = True)\n\nnum1\n\nhull_prev_frame = labels1 == 1\n\nhull_curr_frame = labels1 == 1\n\nplt.imshow(hull_prev_frame, cmap='gray')\n\nplt.imshow(hull_curr_frame, cmap='gray')\n\n\nimage = video_frames[201]\n\nc1,t1 = hull_and_thresh_hist_eq(image,25, 1.9, 1, False, False)\n\nplt.imshow(t1, cmap = 'gray')\n\nplt.imshow(c1, cmap='gray')\n\nplt.imshow(t1*c1, cmap='gray')\n\nlabels2, num1 = skimage.measure.label(c1, return_num = True)\n\nhull_curr_frame = labels2 == 1\n\n\nhull_overlap(hull_prev_frame, hull_curr_frame)\n","sub_path":"Cell Segmentation/3_23_seg_full_7_22.py","file_name":"3_23_seg_full_7_22.py","file_ext":"py","file_size_in_byte":23571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"348729952","text":"import random\n\nquestions = {\n \"strong\": \"Do ye like yer drinks strong?\",\n \"salty\": \"Do ye like it with a salty tang?\",\n \"bitter\": \"Are ye a lubber who like it bitter?\",\n \"sweet\": \"Would you like a bit of sweetness with yer poison?\",\n \"fruity\": \"Are ye one for the fruity finish?\",\n}\n\ningredients = {\n \"strong\": [\"glug of rum\", \"slug of whisky\", \"splash of gin\"],\n \"salty\": [\"olive on a stick\", \"salt-dusted rim\", \"rasher of bacon\"],\n \"bitter\": [\"shake of bitters\", \"splash of tonic\", \"twist of lemon peel\"],\n \"sweet\": [\"sugar cube\", \"spoonful of honey\", \"splash of cola\"],\n \"fruity\": [\"slice of orange\", \"dash of cassis\", \"cherry on top\"],\n}\n\nadjectives = [\n \"Salty\", \"Fizzy\", \"Soothing\", \"Sweet\", \"Briny\", \n \"Mucilaginous\", \"Stiff\", \"Demulcent\", \"Exotic\",\n \"Sweet\", \"Tangy\", \"Bubbly\", \"Flaming\", \"Fluffy\"\n]\n\nnouns = [\n \"Debutante\", \"Sea-Dog\", \"Mime\", \"Siren\", \"Gentleman\",\n \"Rapscallion\", \"Sugar Plum Fairy\", \"Bloodhound\", \"Derby\",\n \"Volcano\", \"Critter\", \"Zombie\", \"Toker\"\n]\n\ncustomers = {}\n\ndef test_value(answer):\n while True:\n try:\n if answer in {\"Y\", \"Ye\", \"Yes\", \"y\", \"yes\" \"ye\"}:\n result = True\n return result\n elif answer in {\"N\", \"No\", \"n\", \"no\"}:\n result = False\n return result\n else:\n answer = str(input(\"Ye chose poorly! Answer yes/no.\"))\n except(ValueError, NameError, TypeError):\n answer = str(input(\"Ye chose poorly! Answer yes/no.\"))\n pass\n\ndef get_pref():\n characteristics = list(questions.keys())\n answers = {}\n for question in questions:\n answer = str(input(questions[question]))\n result = test_value(answer)\n answers[characteristics[characteristics.index(question)]] = result\n return answers\n \ndef make_drink(preferences):\n drink = []\n for ingredient in preferences:\n if preferences[ingredient] == True:\n drink.append(random.choice(ingredients[ingredient]))\n else:\n pass\n return drink\n\ndef name_cocktail():\n adj = random.choice(adjectives)\n noun = random.choice(nouns)\n return (adj + \" \" + noun)\n\ndef user_pref(name):\n if name in customers:\n print(\"A return customer! I remember what ye like. \",\n \"I'll mix ye up another drink.\")\n return customers[name]\n else:\n print(\"A newcomer! Tell me, what'll quench ye thirst?\")\n customers[name] = get_pref()\n return customers[name]\n\nif __name__ == '__main__':\n print(\"Oi matey! I'll make ye a drink.\")\n while True:\n cust = input(\"Who be orderin'?\")\n prefs = user_pref(cust)\n drink = make_drink(prefs)\n name = name_cocktail()\n print(\"Right! Got it! Coming right up.\")\n print(\"Orderup! This is a {}.\".format(name))\n print(\"It's made up of the following:\")\n for item in drink:\n print(item)\n round = str(input(\"You downed that fast. Care for another drink?\"))\n if test_value(round) == True:\n pass\n elif test_value(round) == False:\n break","sub_path":"bartender.py","file_name":"bartender.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"17952004","text":"import sys\r\nimport yagmail\r\nimport datetime\r\nfrom requests import get\r\nfrom requests.exceptions import RequestException\r\nfrom contextlib import closing\r\nfrom bs4 import BeautifulSoup\r\nfrom datetime import date\r\n\r\ndef simple_get(url):\r\n \"\"\"\r\n Attempts to get the content at `url` by making an HTTP GET request.\r\n If the content-type of response is some kind of HTML/XML, return the\r\n text content, otherwise return None.\r\n \"\"\"\r\n try:\r\n with closing(get(url, stream=True)) as resp:\r\n if is_good_response(resp):\r\n return resp.content\r\n else:\r\n return None\r\n\r\n except RequestException as e:\r\n log_error('Error during requests to {0} : {1}'.format(url, str(e)))\r\n return None\r\n\r\n\r\ndef is_good_response(resp):\r\n \"\"\"\r\n Returns True if the response seems to be HTML, False otherwise.\r\n \"\"\"\r\n content_type = resp.headers['Content-Type'].lower()\r\n return (resp.status_code == 200 \r\n and content_type is not None \r\n and content_type.find('html') > -1)\r\n\r\n\r\ndef log_error(e):\r\n \"\"\"\r\n It is always a good idea to log errors. \r\n This function just prints them, but you can\r\n make it do anything.\r\n \"\"\"\r\n print(e)\r\n\r\ntoday = datetime.date.today() + datetime.timedelta(days = 1)\r\nmonth = today.strftime(\"%m\")\r\nday = today.strftime(\"%d\")\r\ndaynum = today.weekday()\r\n\r\nif daynum == 5 or daynum == 6:\r\n sys.exit()\r\n\r\nif month == \"01\":\r\n month = \"Jan\"\r\nelif month == \"02\":\r\n month = \"Feb\"\r\nelif month == \"03\":\r\n month = \"Mar\"\r\nelif month == \"04\":\r\n month = \"Apr\"\r\nelif month == \"05\":\r\n month = \"May\"\r\nelif month == \"06\":\r\n month = \"Jun\"\r\nelif month == \"07\":\r\n month = \"Jul\"\r\nelif month == \"08\":\r\n month = \"Aug\"\r\nelif month == \"09\":\r\n month = \"Sep\"\r\nelif month == \"10\":\r\n month = \"Oct\"\r\nelif month == \"11\":\r\n month = \"Nov\"\r\nelse:\r\n month = \"Dec\"\r\n\r\nif int(day) < 10: day = day[1:]\r\ndate = month + day + \"page\"\r\n\r\nraw_html = simple_get(\"https://www.marketwatch.com/tools/earningscalendar?mod=side_nav\")\r\nhtml = BeautifulSoup(raw_html, 'html.parser')\r\n\r\nfor i in html.select('div'):\r\n if i.has_attr('id') and i['id'] == date:\r\n break\r\n \r\nj = 0\r\nx = \"\"\r\nfor k in i.select('td'):\r\n if(j == 0):\r\n x += (\"Company Name: \" + k.text + \"\\n\")\r\n j += 1\r\n continue \r\n if(j == 1):\r\n x += (\"Symbol: \" + k.text + \"\\n\")\r\n j += 1\r\n continue\r\n if(j == 2):\r\n x += (\"Fiscal Quarter: \" + k.text + \"\\n\")\r\n j += 1\r\n continue\r\n if(j == 3):\r\n x += (\"EPS Forecast: \" + k.text + \"\\n\")\r\n j += 1\r\n continue\r\n if(j == 4):\r\n x += (\"EPS Actual: \" + k.text + \"\\n\")\r\n j += 1\r\n continue\r\n if(j == 5):\r\n x += (\"Surprise: \" + k.text + \"\\n\\n\")\r\n j = 0\r\n\r\nreceiver = \"babu.chimmi@gmail.com\"\r\nbody = x[0:-2]\r\nif len(body) != 0:\r\n yag = yagmail.SMTP(\"noreply.playservices@gmail.com\")\r\n yag.send(\r\n to = receiver,\r\n subject = \"Companies' Earnings for Tomorrow (\" + today.strftime(\"%B %d, %Y\") + \")\",\r\n contents = body\r\n )\r\n","sub_path":"MarketWatch Webscraper/Tomorrow'sAutomatedEarningsCalendar.py","file_name":"Tomorrow'sAutomatedEarningsCalendar.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"282722544","text":"from flask import Flask\nfrom threading import Thread\nimport urllib.request\nimport os\nimport time\nimport random\napp = Flask('')\nhdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)',\n 'Authorization': os.getenv('o7APIKey'),\n }\nurl = \"https://o7-api.glitch.me/api/json/graphical/classification/https://github.com/o7-Fire/General/raw/master/Human/Logo/o7A.png\"\n\n\ndef main():\n return \"alive 200\"\n\ndef assad(path):\n return path +\" assad\" + str(random.randint(60, 250))\n\n@app.route(\"/\", defaults={\"path\": \"\"})\n@app.route(\"/\")\ndef all_routes(path):\n if path.startswith('assad'):\n return assad(path)\n else:\n return main()\n\n\ndef fetch(url):\n try:\n req = urllib.request.Request(url, headers=hdr)\n response = urllib.request.urlopen(req)\n return str(response.read().decode())\n except Exception as e:\n return str(e)\n\ndef alive():\n while True:\n time.sleep(int(random.randint(160, 250)))\n try:\n fetch(url)\n except Exception as e:\n print(e)\n\ndef run():\n app.run(host=\"0.0.0.0\", port=8080)\n\ndef keep_alive():\n server = Thread(target=run)\n server.start()\n aliveT = Thread(target=alive)\n aliveT.start()","sub_path":"keep_alive.py","file_name":"keep_alive.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"215220711","text":"'''\nStarting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.\n\n37 36 35 34 33 32 31\n38 17 16 15 14 13 30\n39 18 5 4 3 12 29\n40 19 6 1 2 11 28\n41 20 7 8 9 10 27\n42 21 22 23 24 25 26\n43 44 45 46 47 48 49\n\nIt is interesting to note that the odd squares lie along the bottom right diagonal, \nbut what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, \na ratio of 8/13 ≈ 62%.\n\nIf one complete new layer is wrapped around the spiral above, \na square spiral with side length 9 will be formed. \nIf this process is continued, \nwhat is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?\n\n\n'''\n# from prob 28, pattern is different, but diagnols are the same\ndef calcDivisors(target):\n if target < 0:\n return False\n divisors = []\n for i in range(2,int(target**(1/2))+1):\n if target % i == 0:\n if target/i == i:\n divisors.append(i)\n return False\n else:\n divisors.append(i)\n divisors.append(target/i)\n return False\n return True\n\ndef calcDiags():\n numDiags = 1\n primeDiags = 0\n curr_side = 0\n sum = 1\n last = 1\n x = 1\n while primeDiags*1.0/numDiags == 0 or primeDiags*1.0/numDiags > .1:\n curr_side = 2*x\n last = last + 2*x\n numDiags = numDiags + 1\n if calcDivisors(last):\n primeDiags = primeDiags + 1\n for y in range(3):\n last = last + curr_side\n numDiags = numDiags + 1\n if calcDivisors(last):\n primeDiags = primeDiags + 1\n x = x + 1\n\n print(primeDiags, numDiags, primeDiags*1.0/numDiags)\n print(curr_side + 1)\n\ndef main():\n calcDiags()\n\nif __name__ == '__main__':\n main()","sub_path":"lvl_02/prob_058/prob58.py","file_name":"prob58.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"140786616","text":"\"\"\"\n desc: regist callback function\n \n [ refer to ]\n https://collectd.org/documentation/manpages/collectd-python.5.shtml\n\n\"\"\"\n\nfrom init import Init\ninit = Init()\n\nimport collectd\n\nfrom send import Send\nfrom custom import Custom\nfrom splitdata import SplitData\nfrom filter import filter\n\nsend = Send()\ncustom = Custom()\nsplitdata = SplitData()\n\nfrom plugin_manager import PluginManager \nimport plugins \n\ndef configer(confObj):\n collectd.info(\"config called\")\n\ndef init_fun():\n collectd.info(\"init\")\n\ndef reader(input_data=None):\n\n PluginManager().read()\n\ndef writer(input_data=None):\n '''\n if input_data.type == \"gauge\":\n collectd.info(str(input_data.plugin))\n collectd.info(str(input_data.plugin_instance))\n collectd.info(str(input_data.type))\n collectd.info(str(input_data.type_instance))\n collectd.info(str(input_data.host))\n collectd.info(str(input_data.interval))\n collectd.info(str(input_data.time))\n '''\n# collectd.info(str(input_data))\n\n if not filter.filter(input_data):\n return\n\n result = splitdata.splitData(input_data)\n for item in result:\n\n records = custom.custom(item)\n if \"msg\" in records:\n collectd.info(records[\"msg\"])\n return\n for record in records:\n res = send.send(record.values())\n# collectd.info(str(res))\n\ncollectd.register_config(configer)\n#collectd.register_init(init_fun)\ncollectd.register_read(reader)\ncollectd.register_write(writer)\n","sub_path":"collectd/upyun_custom/plugins/python_filter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"60887883","text":"from java.awt import GridLayout, Dimension\nfrom javax.swing import JFrame, JScrollPane, JPanel, JTable, JButton, ListSelectionModel, BoxLayout\nfrom javax.swing.table import DefaultTableModel, TableRowSorter\n\nclass TableApp:\n \n def make_ui(self):\n frame = JFrame(\"Table demo\")\n frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)\n frame.setLayout(BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS))\n scrollPane = JScrollPane()\n scrollPane.setPreferredSize(Dimension(300,100))\n self.table = self.createTable()\n scrollPane.getViewport().setView(self.table)\n buttonPanel = JPanel(GridLayout())\n button0 = self.createButton(\"Remove Name\", \"Name\")\n button1 = self.createButton(\"Remove Age\", \"Age\")\n button2 = self.createButton(\"Remove Gender\", \"Gender\")\n buttonPanel.add(button0)\n buttonPanel.add(button1)\n buttonPanel.add(button2)\n panel = JPanel()\n panel.add(scrollPane)\n frame.add(buttonPanel)\n frame.add(panel)\n frame.pack()\n frame.setVisible(True)\n\n def createButton(self, name, action):\n button = JButton(name, actionPerformed=self.handleButton)\n button.setActionCommand(action)\n return button\n\n def handleButton(self, event):\n button = event.getSource()\n button.setEnabled(False)\n column = self.table.getColumn(button.getActionCommand())\n self.table.removeColumn(column)\n\n def createTable(self):\n data = [\n ['Eva', '22', 'female'],\n ['Anika', '31' ,'female'],\n ['Anna', '25' ,'female'],\n ['Anders', '21' ,'male'],\n ]\n columns = (\"A\", \"B\", \"C\")\n model = DefaultTableModel(data, columns)\n table = JTable(model)\n table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)\n table.setCellSelectionEnabled(True)\n sorter = TableRowSorter(table.getModel())\n table.setRowSorter(sorter)\n table.setName(\"Persons\")\n for i, value in enumerate((\"Name\", \"Age\", \"Gender\")):\n table.getColumnModel().getColumn(i).setHeaderValue(value)\n return table\n \n @staticmethod \n def main():\n app = TableApp()\n app.make_ui()\n\nTableApp.main()\n","sub_path":"swing/tables/table_view_changes/column_names_in_view/target_ui.py","file_name":"target_ui.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"60312651","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nDEFAULT_OUT = \"out_alg_sort_selection.txt\"\nDEFAULT_SEED = None\n\nDEFAULT_N_START = 1\nDEFAULT_N_STOP = 10\nDEFAULT_N_STEP = 1\nDEFAULT_TRIALS = 3\n\nfrom subprocess import Popen, PIPE\nfrom time import sleep, time\nfrom multiprocessing import Process\nimport shlex\nimport json\n\nimport sys\nimport os\nimport argparse\nimport logging\nimport subprocess\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize as opt\nimport matplotlib.colors as colors\nimport matplotlib.cm as cmx\n\nimport timeit\n\n\ndef sort_selection(lista):\n\t'''\n\tImplementação do Selection Sort\n\t:param lista: qualquer ordem\n\t:return: lista ordenada\n\t'''\n\tn = len(lista)\n\t# percorre a lista\n\tfor i in range(n):\n\t\t#print(\"i:{}\".format(i))\n\t\tpos_min = i\n\t\t# procura o menor valor desde então\n\t\tfor j in range(i,n):\n\t\t\t#print(\"\\ti:{} j:{}\".format(i, j))\n\t\t\tif lista[j] < lista[pos_min]:\n\t\t\t\t#print(\"\\t\\tmin lista[j]:{} < lista[pos_min]:{}\".format(lista[j], lista[pos_min]))\n\t\t\t\tpos_min = j\n\t\t# swap\n\t\tlista[i], lista[pos_min] = lista[pos_min], lista[i]\n\treturn lista\n\n\ndef main():\n\t# Definição de argumentos\n\tparser = argparse.ArgumentParser(description='Naive TPS')\n\thelp_msg = \"arquivo de saída. Padrão:{}\".format(DEFAULT_OUT)\n\tparser.add_argument(\"--out\", \"-o\", help=help_msg, default=DEFAULT_OUT, type=str)\n\n\thelp_msg = \"semente aleatória. Padrão:{}\".format(DEFAULT_SEED)\n\tparser.add_argument(\"--seed\", \"-s\", help=help_msg, default=DEFAULT_SEED, type=int)\n\n\thelp_msg = \"n máximo. Padrão:{}\".format(DEFAULT_N_STOP)\n\tparser.add_argument(\"--nstop\", \"-n\", help=help_msg, default=DEFAULT_N_STOP, type=int)\n\n\thelp_msg = \"n mínimo. Padrão:{}\".format(DEFAULT_N_START)\n\tparser.add_argument(\"--nstart\", \"-a\", help=help_msg, default=DEFAULT_N_START, type=int)\n\n\thelp_msg = \"n passo. Padrão:{}\".format(DEFAULT_N_STEP)\n\tparser.add_argument(\"--nstep\", \"-e\", help=help_msg, default=DEFAULT_N_STEP, type=int)\n\n\thelp_msg = \"tentativas. Padrão:{}\".format(DEFAULT_N_STEP)\n\tparser.add_argument(\"--trials\", \"-t\", help=help_msg, default=DEFAULT_TRIALS, type=int)\n\n\t# Lê argumentos from da linha de comando\n\targs = parser.parse_args()\n\n\n\ttrials = args.trials\n\tf = open(args.out, \"w\")\n\tf.write(\"#Selection sort\\n\")\n\tf.write(\"#n time_s_avg time_s_std (for {} trials)\\n\".format(trials))\n\tm = 100\n\tnp.random.seed(args.seed)\n\tfor n in range(args.nstart, args.nstop+1, args.nstep): #range(1, 100):\n\t\tresultados = [0 for i in range(trials)]\n\t\ttempos = [0 for i in range(trials)]\n\t\tfor trial in range(trials):\n\t\t\tprint(\"\\n-------\")\n\t\t\tprint(\"n: {} trial: {}\".format(n, trial+1))\n\t\t\tentrada = np.random.randint(0, n, n)\n\t\t\tprint(\"Entrada: {}\".format(entrada))\n\t\t\ttempo_inicio = timeit.default_timer()\n\t\t\tresultados[trial] = sort_selection(entrada)\n\t\t\ttempo_fim = timeit.default_timer()\n\t\t\ttempos[trial] = tempo_fim - tempo_inicio\n\t\t\tprint(\"Saída: {}\".format(resultados[trial]))\n\t\t\tprint('Tempo: {} s'.format(tempos[trial]))\n\t\t\tprint(\"\")\n\n\t\ttempos_avg = np.average(tempos) # calcula média\n\t\ttempos_std = np.std(a=tempos, ddof=False) # ddof=calcula desvio padrao de uma amostra?\n\n\n\t\tf.write(\"{} {} {}\\n\".format(n, tempos_avg, tempos_std))\n\tf.close()\n\n\nif __name__ == '__main__':\n\tsys.exit(main())\n","sub_path":"lab_4/alg_sort_selection.py","file_name":"alg_sort_selection.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"421072408","text":"from django.conf.urls import patterns, include, url\nfrom . import views\n\nurlpatterns = [\n\turl(r'^$', views.index),\n\turl(r'^department/$', views.department),\n\turl(r'^news/(?P[0-9]+)/$', views.news_detail),\n\turl(r'^news/$', views.news),\n\turl(r'^about/$', views.about),\n\turl(r'^contact/(?P[0-9]+)/$', views.contact_detail),\n\turl(r'^contact/$', views.contact),\n]","sub_path":"website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"82739427","text":"import requests\nfrom utils.lazystore import LazyMysql\nfrom lxml import etree\nfrom multiprocessing import Pool\nimport time\n\ndef getJianshuInfo(user_id,page):\n '''\n 抓取指定用户一页的文章数据,并存入数据库\n :param user_id: 用户id 网页中获取\n :param page: 当前抓取的页码\n :return:\n '''\n base_url = 'https://www.jianshu.com'\n target_url = 'https://www.jianshu.com/u/' + user_id\n # 模拟浏览器请求头\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'\n ' Chrome/59.0.3071.115 Safari/537.36'\n }\n # 构造查询字符串\n payload = {\n 'order_by':'shared_at',\n 'page':''\n }\n payload['page'] = page\n try:\n response = requests.get(url=target_url, headers=headers,params=payload)\n if response.status_code == 200:\n html = response.text\n result_list = analysis_data(base_url, html)\n save_data(result_list)\n except Exception as e:\n print(e)\n\n\ndef analysis_data(base_url, html):\n '''\n 解析网页数据 返回数据字典列表\n :param base_url: 基础url 用于拼接文章链接\n :param html: 网页html\n :return: 数据字典列表\n '''\n et = etree.HTML(html)\n # 标题\n titles = et.xpath('//ul[@class=\"note-list\"]/li/div[@class=\"content\"]/a[@class=\"title\"]/text()')\n # 文章链接\n links = et.xpath('//ul[@class=\"note-list\"]/li/div[@class=\"content\"]/a[@class=\"title\"]/@href')\n # 作者\n nicknames = et.xpath('//ul[@class=\"note-list\"]/li/div[@class=\"content\"]/div[@class=\"author\"]'\n '/div[@class=\"info\"]/a[@class=\"nickname\"]/text()')\n # 看的次数\n lookeds = et.xpath('//ul[@class=\"note-list\"]/li/div[@class=\"content\"]/div[@class=\"meta\"]/a[1]/text()')\n # 评论数\n comments = et.xpath('//ul[@class=\"note-list\"]/li/div[@class=\"content\"]/div[@class=\"meta\"]/a[2]/text()')\n # 喜欢数\n likes = et.xpath('//ul[@class=\"note-list\"]/li/div[@class=\"content\"]/div[@class=\"meta\"]/span/text()')\n # 发布时间\n # report_times = et.xpath('//ul[@class=\"note-list\"]/li/div[@class=\"content\"]/div[@class=\"author\"]'\n # '/div[@class=\"info\"]/span[@class=\"time\"]/text()')\n result_list = []\n for i in range(0, len(titles)):\n result_dict = {\n 'title': '',\n 'link': '',\n 'nickname': '',\n 'looked': '',\n 'comment': '',\n 'like': ''\n }\n result_dict['title'] = titles[i]\n result_dict['link'] = base_url + links[i]\n result_dict['nickname'] = nicknames[i]\n result_dict['looked'] = lookeds[i]\n result_dict['comment'] = comments[i]\n result_dict['like'] = likes[i]\n # result_dict['report_time'] = report_times[i]\n result_list.append(result_dict)\n return result_list\n\n\ndef save_data(result_list):\n '''\n 保存数据\n :param result_list: 每页数据的字典列表\n :return:\n '''\n # 数据库信息\n db_config = {\n 'host': 'xx.xx.xx.xx',\n 'user': 'root',\n 'password': 'xxxxxx',\n 'db': 'db_test'\n }\n # 初始化数据库操作\n lazyStore = LazyMysql(db_config)\n lazyStore.save_data_list(result_list,'jianshu_info')\n\n\n\ndef main(user_id,page_num):\n '''\n 封装抓取指定用户,指定页数数量的文章数据\n :param user_id: 用户id,网页中获取\n :param page_num: 要抓取的页数\n :return:\n '''\n # 开启进程池\n pool = Pool(processes=8)\n # 开始时间\n start = time.time()\n for page in range(0, page_num):\n print('开始抓取第{}页数据'.format(page))\n # 多进程调用\n pool.apply_async(getJianshuInfo, args=(user_id, page))\n # getJianshuInfo(user_id=user_id,page=page)\n pool.close()\n pool.join()\n print('数据抓取完成!!耗时{}s'.format(time.time() - start))\n\n\nif __name__ == '__main__':\n # https://www.jianshu.com/u/383970bef0a0?order_by=shared_at&page=0\n user_id = '383970bef0a0'\n page_num = 15\n main(user_id=user_id,page_num=page_num)","sub_path":"jianshuInfoSpider.py","file_name":"jianshuInfoSpider.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318096389","text":"\"\"\"Winix C545 Air Purifier Device.\"\"\"\n\nimport asyncio\nfrom collections.abc import Mapping\nfrom datetime import timedelta\nimport logging\nfrom typing import Any, Callable, Optional, Union\n\nfrom homeassistant.components.fan import (\n DOMAIN,\n SUPPORT_PRESET_MODE,\n SUPPORT_SET_SPEED,\n FanEntity,\n)\nfrom homeassistant.const import ATTR_ENTITY_ID\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.entity import DeviceInfo\nfrom homeassistant.helpers.typing import (\n ConfigType,\n DiscoveryInfoType,\n HomeAssistantType,\n)\nfrom homeassistant.util.percentage import (\n ordered_list_item_to_percentage,\n percentage_to_ordered_list_item,\n)\nimport voluptuous as vol\n\nfrom custom_components.winix.device_wrapper import WinixDeviceWrapper\nfrom custom_components.winix.manager import WinixManager\n\nfrom .const import (\n ATTR_AIRFLOW,\n ATTR_FILTER_REPLACEMENT_DATE,\n ATTR_LOCATION,\n ATTR_POWER,\n DOMAIN as WINIX_DOMAIN,\n ORDERED_NAMED_FAN_SPEEDS,\n PRESET_MODE_AUTO,\n PRESET_MODE_AUTO_PLASMA_OFF,\n PRESET_MODE_MANUAL,\n PRESET_MODE_MANUAL_PLASMA_OFF,\n PRESET_MODE_SLEEP,\n PRESET_MODES,\n SERVICES,\n WINIX_DATA_KEY,\n)\n\n_LOGGER = logging.getLogger(__name__)\nSCAN_INTERVAL = timedelta(seconds=15)\n\n\n# pylint: disable=unused-argument\nasync def async_setup_platform(\n hass: HomeAssistantType,\n config: ConfigType,\n async_add_entities: Callable,\n discovery_info: Optional[DiscoveryInfoType] = None,\n) -> None:\n \"\"\"Set up the Winix air purifiers.\"\"\"\n\n # Create WINIX_DATA_KEY entry if not present\n if WINIX_DATA_KEY not in hass.data:\n hass.data[WINIX_DATA_KEY] = []\n\n manager: WinixManager = hass.data[WINIX_DOMAIN]\n\n entities = []\n for wrapper in manager.get_device_wrappers():\n entities.append(WinixPurifier(wrapper))\n\n # Keep track of etities in WINIX_DATA_KEY storage area for service processing\n hass.data[WINIX_DATA_KEY].extend(entities)\n async_add_entities(entities, False)\n\n async def async_service_handler(service_call):\n \"\"\"Service handler.\"\"\"\n method = \"async_\" + service_call.service\n _LOGGER.debug(\"Service '%s' invoked\", service_call.service)\n\n # The defined services do not accept any additional parameters\n params = {}\n\n entity_ids = service_call.data.get(ATTR_ENTITY_ID)\n if entity_ids:\n devices = [\n entity\n for entity in hass.data[WINIX_DATA_KEY]\n if entity.entity_id in entity_ids\n ]\n else:\n devices = hass.data[WINIX_DATA_KEY]\n\n state_update_tasks = []\n for device in devices:\n if not hasattr(device, method):\n continue\n\n await getattr(device, method)(**params)\n state_update_tasks.append(device.async_update_ha_state(True))\n\n if state_update_tasks:\n # Update device states in HA\n await asyncio.wait(state_update_tasks)\n\n for service in SERVICES:\n hass.services.async_register(\n WINIX_DOMAIN,\n service,\n async_service_handler,\n schema=vol.Schema({ATTR_ENTITY_ID: cv.entity_ids}),\n )\n\n _LOGGER.info(\"Added %s Winix fans\", len(entities))\n\n\nclass WinixPurifier(FanEntity):\n \"\"\"Representation of a Winix Purifier device.\"\"\"\n\n def __init__(self, wrapper: WinixDeviceWrapper) -> None:\n \"\"\"Initialize the device.\"\"\"\n self._wrapper = wrapper\n\n self._unique_id = f\"{DOMAIN}.{WINIX_DOMAIN}_{wrapper.info.mac.lower()}\"\n self._name = f\"Winix {self._wrapper.info.alias}\"\n\n @property\n def available(self) -> bool:\n \"\"\"Return True if entity is available.\"\"\"\n state = self._wrapper.get_state()\n return state is not None\n\n @property\n def device_state_attributes(self) -> Union[Mapping[str, Any], None]:\n \"\"\"Return the state attributes.\"\"\"\n attributes = {}\n state = self._wrapper.get_state()\n\n if state is not None:\n for key, value in state.items():\n # The power attribute is the entity state, so skip it\n if not key == ATTR_POWER:\n attributes[key] = value\n\n attributes[ATTR_LOCATION] = self._wrapper.info.location_code\n attributes[\n ATTR_FILTER_REPLACEMENT_DATE\n ] = self._wrapper.info.filter_replace_date\n\n return attributes\n\n @property\n def unique_id(self) -> str:\n \"\"\"Return the unique id of the switch.\"\"\"\n return self._unique_id\n\n @property\n def device_info(self) -> DeviceInfo:\n \"\"\"Return device specific attributes.\"\"\"\n return {\n \"identifiers\": {(WINIX_DOMAIN, self._wrapper.info.mac.lower())},\n \"name\": self._name,\n }\n\n @property\n def name(self) -> str:\n \"\"\"Return the name of the switch.\"\"\"\n return self._name\n\n @property\n def is_on(self) -> bool:\n \"\"\"Return true if switch is on.\"\"\"\n return self._wrapper.is_on\n\n @property\n def percentage(self) -> Union[int, None]:\n \"\"\"Return the current speed percentage.\"\"\"\n state = self._wrapper.get_state()\n if state is None:\n return None\n elif self._wrapper.is_sleep or self._wrapper.is_auto:\n return None\n elif state.get(ATTR_AIRFLOW) is None:\n return None\n else:\n return ordered_list_item_to_percentage(\n ORDERED_NAMED_FAN_SPEEDS, state.get(ATTR_AIRFLOW)\n )\n\n @property\n def preset_mode(self) -> Union[str, None]:\n \"\"\"Return the current preset mode, e.g., auto, smart, interval, favorite.\"\"\"\n state = self._wrapper.get_state()\n if state is None:\n return None\n if self._wrapper.is_sleep:\n return PRESET_MODE_SLEEP\n if self._wrapper.is_auto:\n return (\n PRESET_MODE_AUTO\n if self._wrapper.is_plasma_on\n else PRESET_MODE_AUTO_PLASMA_OFF\n )\n if self._wrapper.is_manual:\n return (\n PRESET_MODE_MANUAL\n if self._wrapper.is_plasma_on\n else PRESET_MODE_MANUAL_PLASMA_OFF\n )\n else:\n return None\n\n @property\n def preset_modes(self) -> Union[list[str], None]:\n \"\"\"Return a list of available preset modes.\"\"\"\n return PRESET_MODES\n\n @property\n def speed_list(self) -> list:\n \"\"\"Get the list of available speeds.\"\"\"\n return ORDERED_NAMED_FAN_SPEEDS\n\n @property\n def speed_count(self) -> int:\n \"\"\"Return the number of speeds the fan supports.\"\"\"\n return len(ORDERED_NAMED_FAN_SPEEDS)\n\n # https://developers.home-assistant.io/docs/core/entity/fan/\n\n @property\n def supported_features(self) -> int:\n \"\"\"Flag supported features.\"\"\"\n return SUPPORT_PRESET_MODE | SUPPORT_SET_SPEED\n\n async def async_set_percentage(self, percentage: int) -> None:\n \"\"\"Set the speed percentage of the fan.\"\"\"\n if percentage == 0:\n await self.async_turn_off()\n else:\n await self._wrapper.async_set_speed(\n percentage_to_ordered_list_item(ORDERED_NAMED_FAN_SPEEDS, percentage)\n )\n\n await self.async_update_ha_state() # Update state without forcing a refresh\n\n async def async_turn_on(\n self,\n speed: Optional[str] = None,\n percentage: Optional[int] = None,\n preset_mode: Optional[str] = None,\n **kwargs: Any,\n ) -> None:\n \"\"\"Turn on the purifier.\"\"\"\n if percentage:\n await self.async_set_percentage(percentage)\n return\n if preset_mode:\n await self._wrapper.async_set_preset_mode(preset_mode)\n else:\n await self._wrapper.async_turn_on()\n\n await self.async_update_ha_state()\n\n async def async_turn_off(self, **kwargs: Any) -> None:\n \"\"\"Turn off the purifier.\"\"\"\n await self._wrapper.async_turn_off()\n await self.async_update_ha_state()\n\n async def async_plasmawave_on(self) -> None:\n \"\"\"Turn on plasma wave.\"\"\"\n await self._wrapper.async_plasmawave_on()\n await self.async_update_ha_state()\n\n async def async_plasmawave_off(self) -> None:\n \"\"\"Turn off plasma wave.\"\"\"\n await self._wrapper.async_plasmawave_off()\n await self.async_update_ha_state()\n\n async def async_plasmawave_toggle(self) -> None:\n \"\"\"Toggle plasma wave.\"\"\"\n\n if self._wrapper.is_plasma_on:\n await self._wrapper.async_plasmawave_off()\n else:\n await self._wrapper.async_plasmawave_on()\n\n await self.async_update_ha_state()\n\n async def async_set_preset_mode(self, preset_mode: str) -> None:\n \"\"\"Set new preset mode.\"\"\"\n await self._wrapper.async_set_preset_mode(preset_mode)\n await self.async_update_ha_state()\n","sub_path":"custom_components/winix/fan.py","file_name":"fan.py","file_ext":"py","file_size_in_byte":8981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"374418364","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\n\r\n@author: vedashri\r\n\"\"\"\r\n\r\nfrom flask import Flask, render_template, Response,request\r\nfrom werkzeug.utils import secure_filename\r\nfrom camera1 import VideoCamera\r\nfrom imgdect import get_img\r\nimport cv2\r\n#from detect import pre_dect\r\nimport os\r\nimport sqlite3 as sql\r\n\r\napp = Flask(__name__)\r\nUPLOAD_FOLDER = '.\\\\imgssave'\r\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\r\n\r\n@app.route('/a')\r\ndef index():\r\n return render_template('Home.html')\r\n\r\n@app.route('/image', methods=['POST','GET'])\r\ndef image():\r\n return render_template('image.html')\r\n\r\ndef img_gen():\r\n while True:\r\n frame=cv2.imread('./static/detectedimgs/img_3.jpg')\r\n ret, jpeg = cv2.imencode('.jpg', frame)\r\n frame=jpeg.tobytes()\r\n yield (b'--frame\\r\\n'\r\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\r\n@app.route('/img_feed')\r\ndef img_feed():\r\n return Response(img_gen(),mimetype='multipart/x-mixed-replace; boundary=frame')\r\n\r\n\r\n@app.route('/showimage',methods= ['GET', 'POST']) \r\ndef showimage():\r\n if request.method == 'POST':\r\n try:\r\n for imgs in os.listdir('./imgssave/'):\r\n f='./imgssave/'+imgs\r\n os.remove(f)\r\n except :\r\n pass\r\n image = request.files['myfile']\r\n filename = secure_filename(image.filename)\r\n image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\r\n get_img()\r\n \r\n return render_template('imageshow.html')\r\n return render_template('image.html')\r\n\r\n@app.route('/vedio')\r\ndef vedio():\r\n return render_template('vedio.html')\r\n\r\n\r\n\r\n@app.route('/')\r\ndef getDB():\r\n global rows\r\n con = sql.connect('Mask_db.db')\r\n con.row_factory = sql.Row\r\n\r\n cur = con.cursor()\r\n cur.execute(\"SELECT * FROM Mask_Camera\")\r\n\r\n rows = cur.fetchall();\r\n\r\n return render_template('vedio.html', rows = rows)\r\n # return rows\r\n\r\n\r\n@app.route(\"/savedetails\",methods = [\"POST\",\"GET\"]) \r\ndef saveDetails(): \r\n msg = \"msg\" \r\n if request.method == \"POST\": \r\n try: \r\n url_name = request.form[\"url_name\"] \r\n camname = request.form[\"camname\"] \r\n id = request.form[\"id\"]\r\n with sql.connect('Mask_db.db') as con: \r\n # con = sql.connect('Mask_db.db')\r\n cur = con.cursor() \r\n cur.execute(\"INSERT INTO Mask_Camera(id,cam_url,cam_name) VALUES (?,?,?)\",(id,url_name,camname)) \r\n con.commit() \r\n msg = \"Url and Camera Name successfully Added\" \r\n \r\n except: \r\n con.rollback() \r\n msg = \"We can not add the url and camera name to the list\" \r\n finally: \r\n return render_template(\"success.html\",msg = msg) \r\n con.close() \r\n return render_template('Add_Url.html')\r\n\r\n\r\n@app.route(\"/deleterecord\",methods = [\"POST\",\"GET\"]) \r\ndef deleterecord(): \r\n # id = request.form[\"id\"] \r\n with sql.connect(\"Mask_db.db\") as con: \r\n \r\n try: \r\n con.row_factory = sql.Row \r\n cur = con.cursor() \r\n # cur.execute(\"delete from Mask_Camera where id ?\",id) \r\n cur.execute(\"SELECT * FROM Mask_Camera\")\r\n\r\n rows = cur.fetchall();\r\n\r\n if request.method == 'POST': \r\n \r\n #test = request.form.getlist('mycheckbox')\r\n for getid in request.form.getlist('mycheckbox'):\r\n print(getid)\r\n cur.execute('DELETE FROM Mask_Camera WHERE id = {0}'.format(getid)) \r\n con.commit()\r\n msg = \"record successfully deleted\" \r\n \r\n except: \r\n msg = \"can't be deleted\" \r\n finally: \r\n return render_template(\"delete_selector.html\",rows=rows, msg=msg) \r\n return render_template(\"delete_record.html\",msg=msg,rows=rows) \r\n \r\ndef ved_gen(camera):\r\n \r\n \r\n camera.update(0)\r\n\r\n\r\n while True:\r\n #get camera frame\r\n \r\n frame = camera.get_frame()\r\n\t\r\n yield (b'--frame\\r\\n'\r\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\r\n\r\n\r\n\t\r\n\r\n@app.route('/video_feed')\r\ndef video_feed():\r\n return Response(ved_gen(VideoCamera()),mimetype='multipart/x-mixed-replace; boundary=frame')\r\n\r\n\r\ndef ved(cam):\r\n return cam.me\r\n\r\n\r\n@app.route('/technology')\r\ndef tech():\r\n return Response(ved(VideoCamera()),mimetype='multipart/x-mixed-replace; boundary=frame')\r\n\r\n\r\n\r\n\r\n\r\n\r\n@app.route('/')\r\ndef getCamera():\r\n con = sql.connect('Mask_db.db')\r\n con.row_factory = sql.Row\r\n\r\n cur = con.cursor()\r\n cur.execute(\"SELECT * FROM Mask_Camera\")\r\n\r\n rows = cur.fetchall();\r\n\r\n return render_template('vedio.html', rows = rows)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True,port='5000')","sub_path":"camera_app1.py","file_name":"camera_app1.py","file_ext":"py","file_size_in_byte":4837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"407985583","text":"from Data_structure.SingleLinkeList.Merge_Output_Display import Merge_Output_Print\r\nfrom Data_structure.SingleLinkeList.SingleLinkedList import SingleLinkedList\r\n\r\n\r\ndef main():\r\n list = SingleLinkedList()\r\n list.create_list()\r\n while True:\r\n\r\n print(\"1.Display list\")\r\n print(\"2.Count the number of nodes\")\r\n print('3.Search for an element')\r\n print('4.Insert in empty list/Insert in beginning fo the list')\r\n print('5.Insert a node at the end of the list')\r\n print('6. Insert a node after a specified node')\r\n print('7. Insert a node before a specified node')\r\n print('8. Insert a node at a given position')\r\n print('9. Delete first node')\r\n print('10. Delete last node')\r\n print('11.Delete any node')\r\n print('12. Reverse the list')\r\n print('13. Bubble sort by exchanging data')\r\n print('14. Bubble sort by exchanging links')\r\n print('15.Merge sort by exchanging data and rearranging link')\r\n print('16.Merge sort')\r\n print('17.Insert cycle')\r\n print('18.Detect cycle')\r\n print('19. Remove cycle')\r\n print('20.Quit')\r\n option = int(input('Enter your choice:'))\r\n if option == 1:\r\n list.display_list()\r\n elif option == 2:\r\n list.count_nodes()\r\n elif option == 3:\r\n data = int(input('enter the element to be searched: '))\r\n list.search(data)\r\n elif option == 4:\r\n data = int(input('enter the element to be inserted: '))\r\n list.insert_in_beginning(data)\r\n elif option == 5:\r\n data = int(input('enter the element to be inserted: '))\r\n list.insert_at_end(data)\r\n elif option == 6:\r\n data = int(input('enter the element to be inserted: '))\r\n x = int(input('Enter the element after which to insert: '))\r\n list.insert_after(data, x)\r\n elif option == 7:\r\n data = int(input('enter the element to be inserted: '))\r\n x = int(input('Enter the element before which to insert: '))\r\n list.insert_before(data, x)\r\n elif option == 8:\r\n data = int(input('enter the element to be inserted: '))\r\n k = int(input('Enter the positon at which to insert : '))\r\n list.insert_at_position(data, k)\r\n elif option == 9:\r\n list.delete_first_node()\r\n elif option == 10:\r\n list.delete_last_node()\r\n elif option == 11:\r\n data = int(input('enter the element to be deleted: '))\r\n list.delete_node(data)\r\n elif option == 12:\r\n list.reverse_list()\r\n elif option == 13:\r\n list.bubble_sort_exdata()\r\n elif option == 14:\r\n list.bubble_sort_exlinks()\r\n elif option == 15:\r\n # list.merge_sort()\r\n\r\n a = Merge_Output_Print()\r\n elif option == 16:\r\n list.merge_sort()\r\n elif option == 17:\r\n data = int(input('enter the element at which the cycle to be inserted: '))\r\n list.insert_cycle(data)\r\n elif option == 18:\r\n if list.has_cycle():\r\n print('List has a cycle')\r\n else:\r\n print('List does not have a cycle')\r\n elif option == 19:\r\n list.remove_cycle()\r\n\r\n elif option == 20:\r\n break\r\n else:\r\n print('Wrong option')\r\n print()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"340022069","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nimport uuid\nimport copy\nimport pickle\n\nimport pytest\n\nfrom acli import types\n\n\ndef test_deepcopyable():\n type_ = types.Unprocessed\n copied = copy.deepcopy(type_)\n assert type_.name == copied.name\n\n\ndef test_Unprocessed():\n orig = object()\n converted = types.Unprocessed(orig)\n assert orig is converted\n\n type_ = types.Unprocessed\n assert pickle.loads(pickle.dumps(type_))\n\n\ndef test_String():\n orig = 'foo'\n converted = types.String(orig)\n assert orig == converted\n\n orig = b'bar'\n converted = types.String(orig)\n assert converted == 'bar'\n\n class X(object):\n def __repr__(self):\n return 'baz'\n\n orig = X()\n converted = types.String(orig)\n assert converted == 'baz'\n\n type_ = types.String\n assert pickle.loads(pickle.dumps(type_))\n\n\ndef test_Choice():\n choice = types.Choice(('a', 'b'))\n converted = choice('a')\n assert converted == 'a'\n\n choice = types.Choice((1, 2, 3), item_type=types.Int)\n converted = choice(2)\n\n assert converted == 2\n with pytest.raises(ValueError):\n choice(10)\n with pytest.raises(ValueError):\n choice('x')\n\n type_ = choice\n assert pickle.loads(pickle.dumps(type_))\n\n\ndef test_CaseInsensitiveChoice():\n choice = types.CaseInsensitiveChoice(('a', 'b'))\n converted = choice('A')\n assert converted == 'A'\n\n with pytest.raises(ValueError):\n choice('c')\n\n type_ = choice\n assert pickle.loads(pickle.dumps(type_))\n\n\ndef test_Bool():\n for s in (False, 'no', 'n', 'false', '0', 'FALSE', 'NO'):\n assert types.Bool(s) is False\n for s in (True, 'yes', 'y', 'true', '1', 'TRUE', 'YES'):\n assert types.Bool(s) is True\n\n with pytest.raises(ValueError):\n types.Bool('not-a-boolean')\n\n type_ = types.Bool\n assert pickle.loads(pickle.dumps(type_))\n\n\ndef test_Int():\n orig = 1\n converted = types.Int(orig)\n assert converted == 1\n\n with pytest.raises(ValueError):\n types.Int('foo')\n\n type_ = types.Int\n assert pickle.loads(pickle.dumps(type_))\n\n\ndef test_Float():\n orig = '1.3'\n converted = types.Float(orig)\n assert converted == 1.3\n\n with pytest.raises(ValueError):\n types.Float('bar')\n\n type_ = types.Float\n assert pickle.loads(pickle.dumps(type_))\n\n\ndef test_IntRange():\n irange = types.IntRange(low=0)\n assert irange(10) == 10\n with pytest.raises(ValueError):\n irange(-5)\n\n irange = types.IntRange(high=0)\n assert irange(-10) == -10\n with pytest.raises(ValueError):\n irange(5)\n\n irange = types.IntRange(low=1, high=3)\n\n with pytest.raises(ValueError):\n irange(10)\n\n irange = types.IntRange(low=1, high=3, clamp=True)\n assert irange(-10) == 1\n assert irange(20) == 3\n\n with pytest.raises(ValueError):\n irange('not-a-number')\n\n type_ = irange\n assert pickle.loads(pickle.dumps(type_))\n\n\ndef test_UUID():\n orig = '3b61f1c3-4fac-40d0-b51c-a909f2eb76c1'\n converted = types.UUID(orig)\n assert isinstance(converted, uuid.UUID)\n\n with pytest.raises(ValueError):\n types.UUID('not-a-uuid')\n\n type_ = types.UUID\n assert pickle.loads(pickle.dumps(type_))\n","sub_path":"tests/test_types.py","file_name":"test_types.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274570287","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mykhail Kravchenko\n\n\"\"\"\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndataset=pd.read_csv(\"50-Startups.csv\")\ndel dataset[\"State\"]\nX = dataset.iloc[:,:-1].values\ny = dataset.iloc[:,:4].values\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n\nLabelEncoder = LabelEncoder()\n\nX[:,2] = LabelEncoder.fit_transform(X[:,2])\nonehotencoder = OneHotEncoder(categorical_features=[2]) \n\nX = onehotencoder.fit_transform(X).toarray()\n\nfrom sklearn.model_selection import train_test_split\n\nX_train,x_test,y_train,y_test, = train_test_split(X, y,test_size=0.2, random_state=0)\n\nfrom sklearn.linear_model import LinearRegression\n\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\ny_pred = regressor.predict(x_test)\n\nprint(y_pred)\nprint(y_test)\n\n\nplt.scatter(y_pred, y_test)\nplt.xlabel(\"y_pred\")\nplt.ylabel(\"y_test\")\n\nplt.show()\n\n\n\n","sub_path":"LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567066527","text":"\"\"\"\r\nMinIo Reader - may work with AWS\r\n\"\"\"\r\nfrom ...utils import paths, common\r\nimport lzma\r\nimport io\r\nfrom .internals import BaseReader\r\ntry:\r\n from minio import Minio # type:ignore\r\nexcept ImportError:\r\n pass\r\n\r\n\r\nclass MinIoReader(BaseReader):\r\n\r\n def __init__(\r\n self,\r\n end_point: str,\r\n access_key: str,\r\n secret_key: str,\r\n **kwargs):\r\n super().__init__(**kwargs)\r\n\r\n secure = kwargs.get('secure', True)\r\n self.minio = Minio(end_point, access_key, secret_key, secure=secure)\r\n\r\n\r\n def list_of_sources(self):\r\n bucket, object_path, _, _ = paths.get_parts(self.from_path)\r\n for cycle_date in common.date_range(self.start_date, self.end_date):\r\n cycle_path = paths.build_path(path=object_path, date=cycle_date)\r\n objects = self.minio.list_objects(\r\n bucket_name=bucket,\r\n prefix=cycle_path,\r\n recursive=True)\r\n for obj in objects:\r\n yield bucket + '/' + obj.object_name\r\n\r\n\r\n def read_from_source(self, object_name):\r\n bucket, object_path, name, extension = paths.get_parts(object_name)\r\n stream = self.minio.get_object(bucket, object_path + name + extension).read()\r\n\r\n if extension == '.lzma':\r\n # converting to an IO stream is about 10% faster\r\n io_stream = io.BytesIO(stream)\r\n with lzma.open(io_stream, 'rb') as file:\r\n yield from file\r\n else:\r\n for item in stream.splitlines():\r\n yield item.decode()\r\n","sub_path":"gva/data/readers/minio_reader.py","file_name":"minio_reader.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"435810160","text":"__author__ = 'user'\n\ndef filesInDir(root_dir):\n results = []\n return results;\n\ndef calculate_lengths(root_dir,results):\n for result in results:\n path = root_dir + \"/\" + result\n result_file = open(\"./genomes_length.txt\",'w')\n with open(path, 'r') as f:\n count = 0;\n for line in f:\n if line[0] == \">\":\n count = count + 1\n result_file.write(result + \": \" + count)\n result_file.close()\n\ndef compute_length(root_dir):\n results = filesInDir(root_dir);\n calculate_lengths(root_dir,results);","sub_path":"ParseFasta.py","file_name":"ParseFasta.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559275184","text":"import time\r\nimport numpy as np\r\nimport sys\r\n\r\n\r\nclass Cooler(object):\r\n def __init__(self, GPIO, tmp_aim, therm, tmp_amb, name, precision=.1, input_pin=24):\r\n \"\"\"\r\n Cooler class which controls the state of the cooling element through various convergence methods.\r\n :param GPIO: (class) GPIO class from RPi.GPIO library.\r\n :param tmp_aim: (float) The aim temperature in degrees Celsius.\r\n :param therm: (object) Thermometer class object measuring the temperature of the substance.\r\n :param tmp_amb: (object) Thermometer class object measuring the ambient (room) temperature.\r\n :param name: (string) Cooler name.\r\n :param precision: (float) Range around aim temperature that the cooler will operate.\r\n :param input_pin: (float) Pin number where the cooler state is controlled.\r\n \"\"\"\r\n self.ip = input_pin\r\n self.GPIO = GPIO\r\n self.tmp_aim = tmp_aim\r\n self.therm = therm\r\n self.amb_therm = tmp_amb\r\n self.name = name\r\n self.precision = precision\r\n\r\n GPIO.setmode(GPIO.BCM)\r\n GPIO.setup(self.ip, GPIO.OUT) # Set pin as an output\r\n\r\n self.on_time = 0 # Initialize on times.\r\n self.init_time = 0\r\n self.final_time = 0\r\n\r\n self.total_on_time = 0\r\n self.on = False # Set initial on/off state\r\n\r\n self.first_on = False\r\n self.first_off = False\r\n self.eff_calced = False\r\n\r\n def get_tmp_aim(self):\r\n \"\"\"\r\n :return: (float) Current aim temperature.\r\n \"\"\"\r\n return self.tmp_aim\r\n\r\n def set_tmp_aim(self, tmp, pr=False):\r\n \"\"\"\r\n Sets the aim temperature of the cooling unit.\r\n :param tmp: (float) New aim temperature in degrees C.\r\n :param pr: (boolean) Print new aim temperature.\r\n :return: (float) Current aim temperature.\r\n \"\"\"\r\n self.tmp_aim = tmp\r\n self.therm.tmp_aim = tmp # Reset tmp aim for the Thermometer class\r\n if pr:\r\n print(\"Temperature aim set to %.2f degrees.\" % self.tmp_aim)\r\n return self.tmp_aim\r\n\r\n def get_precision(self):\r\n \"\"\"\r\n :return: Current precision level of the cooling unit.\r\n \"\"\"\r\n return self.precision\r\n\r\n def set_precision(self, pre, pr=False):\r\n \"\"\"\r\n Sets the precision of the Cooler class with the min_precision of the given thermometer as a default minimum.\r\n :param pre: (float) Precision tmp +/- precision.\r\n :param pr: Print confirming change.\r\n :return: New changed precision.\r\n \"\"\"\r\n self.precision = pre\r\n if pre < self.therm.min_precision:\r\n self.precision = self.therm.min_precision\r\n print(\"Set below minimum precision of thermometer.\")\r\n if pr:\r\n print(\"Precision of %s set to %.2f degrees.\" % (self.name, self.precision))\r\n return self.precision\r\n\r\n def get_total_on_time(self):\r\n \"\"\"\r\n Calculates the total time the cooling chip has been on.\r\n :return: (float) Total on time in seconds.\r\n \"\"\"\r\n if self.on:\r\n return self.total_on_time + (time.time() - self.on_time)\r\n else:\r\n return self.total_on_time\r\n\r\n def turn_on(self):\r\n \"\"\"\r\n Turns on the cooling chip and records the time the chip is turned on.\r\n :return: True when complete.\r\n \"\"\"\r\n self.GPIO.output(self.ip, self.GPIO.HIGH) # Turn on the cooling chip.\r\n if not self.on:\r\n print(\"Cooling chip: ON\")\r\n self.on = True\r\n self.on_time = time.time()\r\n\r\n # Set up for measuring the energy used.\r\n if not self.first_on:\r\n self.first_on = self.therm.get_tmp()\r\n self.init_time = time.time()\r\n return True\r\n\r\n def turn_off(self):\r\n \"\"\"\r\n Turns off the cooling chip and records the total on time of the chip by taking the difference between the\r\n current off time and the start time.\r\n :return: False when complete.\r\n \"\"\"\r\n self.GPIO.output(self.ip, self.GPIO.LOW) # Turn off the cooling chip.\r\n if self.on:\r\n print(\"Cooling chip: OFF\")\r\n self.on = False\r\n self.total_on_time += time.time() - self.on_time # Set the total on time.\r\n\r\n # Set up for measuring the energy used.\r\n if not self.first_off and self.first_on:\r\n self.first_off = self.therm.get_tmp()\r\n self.final_time = time.time()\r\n\r\n return False\r\n\r\n def converge(self):\r\n \"\"\"\r\n Method to set the state of the cooling chip to converge on the aim_tmp.\r\n Turns on if the temperature of the substance is above the aim_tmp and turns off when below.\r\n :return: The difference in temperate between the current temperature and the aim_tmp.\r\n \"\"\"\r\n tmp = self.therm.get_tmp()\r\n tmp_dif = np.abs(self.tmp_aim - tmp)\r\n\r\n if tmp != self.tmp_aim:\r\n if tmp < self.tmp_aim and tmp_dif > self.precision:\r\n self.turn_off()\r\n\r\n if tmp > self.tmp_aim and tmp_dif > self.precision:\r\n self.turn_on()\r\n\r\n return tmp_dif\r\n\r\n def hysteretic_conv(self):\r\n \"\"\"\r\n Crude hysteretic convergence method where the high limit before the cooling chip is turned on is half that of\r\n the limit before the chip is turned off.\r\n :return: The difference in temperate between the current temperature and the aim_tmp.\r\n \"\"\"\r\n tmp = self.therm.get_tmp()\r\n tmp_dif = np.abs(self.tmp_aim - tmp)\r\n\r\n if tmp != self.tmp_aim:\r\n if tmp < self.tmp_aim and tmp_dif > self.precision:\r\n self.turn_off()\r\n\r\n if tmp > self.tmp_aim and tmp_dif > self.precision / 2: # since room tmp is higher then reduce the heating time as it will take longet to cool than it will to heat.\r\n self.turn_on()\r\n\r\n return tmp_dif\r\n\r\n def rate_limit_conv(self):\r\n \"\"\"\r\n Reduces the upper limit that the temperature can reach before switching on the cooling chip based on\r\n the expected heating rate obtained from the difference between the temperature and the heating room temperature.\r\n \"\"\"\r\n tmp = self.therm.get_tmp()\r\n tmp_dif = np.abs(self.tmp_aim - tmp)\r\n upper = self.upper_limit()\r\n\r\n if tmp != self.tmp_aim:\r\n if tmp < self.tmp_aim and tmp_dif > self.precision:\r\n self.turn_off()\r\n\r\n if tmp > self.tmp_aim and tmp_dif > upper:\r\n self.turn_on()\r\n\r\n def upper_limit(self):\r\n \"\"\"\r\n Calculates upper limit based on ambient and aim temperatures\r\n :return: (float) Upper temperature limit in degrees.\r\n \"\"\"\r\n amb = self.amb_therm.get_tmp()\r\n upper = self.precision / (amb - self.tmp_aim)\r\n return upper\r\n\r\n def pre_empt_conv(self, rate):\r\n \"\"\"\r\n Truns on and of the cooling chip before the temperature has changed to being above or below the aim temperature\r\n respectively based on the rate of change over the last few time steps.\r\n :param rate: (float) Average temperature rate of change over the last 5 time steps in degrees / s.\r\n \"\"\"\r\n tmp = self.therm.get_tmp()\r\n tmp_dif = np.abs(self.tmp_aim - tmp)\r\n if rate <= 0 and tmp_dif < 2. * rate: # If cooling and close to aim tmp turn off.\r\n self.turn_off()\r\n elif rate > 0 and tmp_dif < 2. * rate: # If heating and close to aim tmp turn on.\r\n self.turn_on()\r\n elif tmp > self.tmp_aim and not self.on:\r\n self.turn_on()\r\n elif tmp < self.tmp_aim and self.on:\r\n self.turn_off()\r\n\r\n def energy_used(self, v, I):\r\n \"\"\"\r\n Calculates the energy used by the power source. First calculates the power (P=IV) then multiplies this\r\n with the time taken to change the temperature by a known amount.\r\n :param v: (float) Power supply voltage.\r\n :param I: (float) Power supply current.\r\n :return: (float) The energy used if calculated, 0 otherwise.\r\n \"\"\"\r\n if self.first_on and self.first_off:\r\n p = I * v\r\n t = self.final_time - self.init_time # Total time the chip was on.\r\n energy_used = p * t\r\n return energy_used\r\n else:\r\n return 0\r\n\r\n def energy_water(self, mass, c=4186):\r\n \"\"\"\r\n Calculates the energy requited to change the temperature of water by a given amount.\r\n :param mass: (float) Mass of substance in kJ.\r\n :param c: (float) Heat capacity of substance in KJ/kg/K.\r\n :return: (float) The energy required.\r\n \"\"\"\r\n delta_tmp = self.first_on - self.first_off\r\n cooling_energy = c * mass * delta_tmp\r\n print(\"delta_tmp: %.2f, mass: %.2f, c: %.2f.\" %(delta_tmp, mass, c))\r\n return cooling_energy\r\n\r\n def efficiency(self, mass, v, i):\r\n \"\"\"\r\n Calculates the efficency of the cooling system by comparing the energy used by the power source to the energy\r\n needed to change the temperature of the substance by the changes amount.\r\n :param mass: (float) Mass of substance kg.\r\n :param v: (float) Voltage of power source.\r\n :param i: (float) Current of power source.\r\n :return: Fractional efficiency if calculated and false otherwise.\r\n \"\"\"\r\n if self.first_on and self.first_off and not self.eff_calced:\r\n # Only calculates between the first time the chip is turned on and the first time the chip is turned\r\n # of (reaches aim temperature - precision)\r\n self.eff_calced = True\r\n eff = self.energy_water(mass) / self.energy_used(v, i)\r\n print(\"The efficiency of the refrigerator is: %.2f %%.\" %(eff*100))\r\n return eff\r\n else:\r\n return False\r\n","sub_path":"Prescision_Refrigerator/Cooler.py","file_name":"Cooler.py","file_ext":"py","file_size_in_byte":9980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"5254338","text":"import requests\nimport json\nimport time\n\n\ntenant_id = \"<>\"\nclient_id = \"<>\"\nclient_secret = \"<>\"\nresource = \"https://management.azure.com\"\nsubscription_id = \"<>\"\ngrant_type = \"client_credentials\"\n\naksResourceGroup = \"<>\"\naksClusterName = \"<>\"\naksAgentPoolName = \"<>\"\n\nminNodeCount = 1\nmaxNodeCount = 1\n\nsleepTimeInSecs = 60\nretryCtr = 5\n\n\n# Function to Fetch AccessToken\n\ndef fetchAccessToken(tenant_id, client_id, client_secret, resource, subscription_id, grant_type):\n\n accessToken = \"\"\n\n try: \n\n accessTokenURL = \"https://login.microsoftonline.com/\"+tenant_id+\"/oauth2/token\"\n\n accessTokenHeaders = {\"Content-Type\":\"application/x-www-form-urlencoded\"}\n\n accessTokenReqBody = {\"tenant_id\":tenant_id, \"client_id\":client_id, \"client_secret\":client_secret, \"resource\":resource, \"subscription_id\":subscription_id, \"grant_type\":grant_type}\n\n tokenResponse = requests.post(url=accessTokenURL, data=accessTokenReqBody, headers=accessTokenHeaders)\n\n tokenResponseJson = json.loads(tokenResponse.text)\n\n accessToken = tokenResponseJson[\"access_token\"]\n\n# print(tokenResponse.json())\n\n# print(tokenResponseJson[\"access_token\"])\n\n\n except: \n print(\"Error while fetching the access token!\")\n return accessToken\n\n\n print (\"AccessToken fetched!\") \n\n return accessToken\n\n\n\n# Function to Disable AutoScaling\n\ndef disableAutoScaling(subscription_id, aksResourceGroup, aksClusterName, aksAgentPoolName, accessToken):\n\n try: \n aksNodePoolMgmtURL = \"https://management.azure.com/subscriptions/\"+subscription_id+\"/resourceGroups/\"+aksResourceGroup+\"/providers/Microsoft.ContainerService/managedClusters/\"+aksClusterName+\"/agentPools/\"+aksAgentPoolName+\"?api-version=2020-02-01\"\n\n nodePoolMgmtHeaders = {\"Authorization\":\"Bearer \"+accessToken, \"Content-Type\":\"application/json\"}\n\n nodePoolMgmtBodyPy = { \"properties\": {\n \"enableAutoScaling\": False\n } }\n\n nodePoolMgmtBody = json.dumps(nodePoolMgmtBodyPy)\n\n nodePoolMgmtResponse = requests.put(url=aksNodePoolMgmtURL, data=nodePoolMgmtBody, headers=nodePoolMgmtHeaders)\n\n# print(nodePoolMgmtResponse.json())\n except:\n print(\"Not able to disable autoscaling!\")\n return False\n \n \n print(\"AutoScaling disabled!\")\n\n return True\n\n\n\n# Function to Set Node Count\n\ndef setNodeCount(sleepInterval, retryCtr, subscription_id, aksResourceGroup, aksClusterName, aksAgentPoolName, accessToken, nodeCount):\n\n try:\n\n while retryCtr > 0:\n time.sleep(sleepInterval)\n\n aksNodePoolMgmtURL = \"https://management.azure.com/subscriptions/\"+subscription_id+\"/resourceGroups/\"+aksResourceGroup+\"/providers/Microsoft.ContainerService/managedClusters/\"+aksClusterName+\"/agentPools/\"+aksAgentPoolName+\"?api-version=2020-02-01\"\n\n nodePoolMgmtHeaders = {\"Authorization\":\"Bearer \"+accessToken, \"Content-Type\":\"application/json\"}\n \n\n nodePoolMgmtBodyPy = { \"properties\": {\n \"enableAutoScaling\": False,\n \"count\" : nodeCount\n } }\n\n nodePoolMgmtBody = json.dumps(nodePoolMgmtBodyPy)\n \n nodePoolMgmtResponse = requests.put(url=aksNodePoolMgmtURL, data=nodePoolMgmtBody, headers=nodePoolMgmtHeaders)\n\n print(nodePoolMgmtResponse.json())\n\n\n nodePoolMgmtResponseJson = json.loads(nodePoolMgmtResponse.text)\n\n\n if 'code' not in nodePoolMgmtResponseJson:\n# print(nodePoolMgmtResponse.json())\n print(\"Node count set successfully!\")\n return True\n break\n\n retryCtr -= 1\n\n except: \n print(\"Error while setting the node count!\")\n\n\n print(\"Not able to set the node count \")\n\n return False \n\n\n\n# Fetch AccessToken\n\naccessToken = fetchAccessToken(tenant_id, client_id, client_secret, resource, subscription_id, grant_type)\n\n\n# Disable autoscaling \n\nautoScalingStatus = disableAutoScaling(subscription_id, aksResourceGroup, aksClusterName, aksAgentPoolName, accessToken)\n\n\n# Set the nodeCount to 1\n\nnodeCountSetStatus = setNodeCount(sleepTimeInSecs, retryCtr, subscription_id, aksResourceGroup, aksClusterName, aksAgentPoolName, accessToken, minNodeCount)\n\n\n\n","sub_path":"nodescaledown.py","file_name":"nodescaledown.py","file_ext":"py","file_size_in_byte":4401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"347445895","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Blog\nfrom .forms import CommentForm\n\n\ndef all_blogs(request):\n blogs = Blog.objects.order_by('-date')\n return render(request, 'blog/blog.html', {'blogs': blogs})\n\n\ndef blog_details(request, blog_id):\n blog = get_object_or_404(Blog, pk=blog_id)\n comments = blog.comments.filter(active=True).order_by(\"-date\")\n new_comment = None\n comment_form = CommentForm()\n\n # comment posted\n if request.method == 'POST':\n comment_form = CommentForm(data=request.POST)\n\n if comment_form.is_valid():\n\n # Create Comment object but does not save to db\n new_comment = comment_form.save(commit=False)\n # assign the current blog to the comment\n new_comment.blog = blog\n # save the comment to the db\n new_comment.save()\n else:\n comment_form = CommentForm()\n\n return render(request, 'blog/blog-details.html', {\n 'blog': blog,\n 'comments': comments,\n 'comment_form': comment_form,\n 'new_comment': new_comment\n })\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"569624050","text":"#!/usr/bin/env python\n\"\"\"\nScan pcap file and output raw data (packet) to csv files\n\"\"\"\nimport dpkt\nimport datetime\nimport socket\nimport os\nimport csv\nimport multiprocessing\nimport itertools\n\ndef mac_addr(address):\n \"\"\"Convert a MAC address to a readable/printable string\n Args:\n address (str): a MAC address in hex form (e.g. '\\x01\\x02\\x03\\x04\\x05\\x06')\n Returns:\n str: Printable/readable MAC address\n \"\"\"\n return ':'.join('%02x' % ord(b) for b in address)\n\n\ndef ip_to_str(address):\n \"\"\"Print out an IP address given a string\n Args:\n address (inet struct): inet network address\n Returns:\n str: Printable/readable IP address\n \"\"\"\n return socket.inet_ntop(socket.AF_INET, address)\n\n\ndef scan_packets(pcap):\n \"\"\"Print out information about each packet in a pcap\n Args:\n pcap: dpkt pcap reader object (dpkt.pcap.Reader)\n \"\"\"\n # For each packet in the pcap process the contents\n\n packet = []\n for timestamp, buf in pcap:\n\n # Print out the timestamp in UTC\n time = datetime.datetime.utcfromtimestamp(timestamp)\n time = str(time).split(\" \")\n #print 'Timestamp: ', str(datetime.datetime.utcfromtimestamp(timestamp))\n\n # Unpack the Ethernet frame (mac src/dst, ethertype)\n eth = dpkt.ethernet.Ethernet(buf)\n #print 'Ethernet Frame: ', mac_addr(eth.src), mac_addr(eth.dst), eth.type\n # Make sure the Ethernet frame contains an IP packet\n # EtherType (IP, ARP, PPPoE, IP6... see http://en.wikipedia.org/wiki/EtherType)\n if eth.type != dpkt.ethernet.ETH_TYPE_IP:\n #print 'Non IP Packet type not supported %s\\n' % eth.data.__class__.__name__\n continue\n # Now unpack the data within the Ethernet frame (the IP packet) \n # Pulling out src, dst, length, fragment info, TTL, and Protocol\n ip = eth.data\n\n # Pull out fragment information (flags and offset all packed into off field, so use bitmasks)\n source_ip = ip_to_str(ip.src)\n dest_ip = ip_to_str(ip.dst)\n length = ip.len\n ttl = ip.ttl\n protocol = ip.p\n do_not_fragment = bool(ip.off & dpkt.ip.IP_DF)\n more_fragments = bool(ip.off & dpkt.ip.IP_MF)\n fragment_offset = ip.off & dpkt.ip.IP_OFFMASK\n packet.append([time[0],time[1],source_ip,dest_ip,length,ttl,protocol,do_not_fragment,more_fragments,fragment_offset])\n\n return packet\n\n # print 'IP: %s -> %s (len=%d ttl=%d DF=%d MF=%d offset=%d)\\n' % \\\n # (ip_to_str(ip.src), ip_to_str(ip.dst), ip.len, ip.ttl, do_not_fragment, more_fragments, fragment_offset)\n\n\ndef write_packet(filename):\n \"\"\"Open up a test pcap file and write out the packets\"\"\"\n try:\n with open(filename, 'rb') as f:\n pcap = dpkt.pcap.Reader(f)\n packet = scan_packets(pcap)\n packet_name = (filename[filename.rfind(\"/\")+1:]+\".csv\")\n write_path = \"/data/network/packets\"\n with open(os.path.join(write_path,packet_name),\"wb+\") as f:\n w = csv.writer(f)\n w.writerow([\"Date\",\"Time\",\"src_ip\",\"des_ip\",\"length\",\"ttl\",\"protocol\",\"do_not_fragment\",\"more_fragments\",\"fragment_offset\"])\n for item in packet:\n w.writerow(item)\n print(\"Done writing files: \"+ str(packet_name))\n except:\n with open((\"/data/network/log.csv\"),\"ab+\") as f:\n \tprint(\"Error scanning packets: \"+filename)\n \tw = csv.writer(f)\n \tw.writerow([\"Error scanning packets: \"+filename])\n\n\n\ndef main():\n pool = multiprocessing.Pool(processes = 40)\n walk = os.walk(\"/data/network/pcap\")\n fn_gen = itertools.chain.from_iterable((os.path.join(root,file) for file in files) for root, dirs, files in walk)\n pool.map(write_packet,fn_gen)\n pool.terminate()\n\nif __name__ == '__main__':\n main()","sub_path":"extract_packet.py","file_name":"extract_packet.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318282948","text":"import random\n\n\ndef main():\n print('Welcome to the Gopher Population Simulator!')\n start = 1000\n for i in range(10):\n bornRate = random.randint(10, 20)\n bornRate = bornRate/100\n deathRate = random.randint(5, 25)\n deathRate = deathRate/100\n print('Year {}\\n'.format(i+1))\n print('{} gophers were born {} died.'.format(\n round((start*bornRate), 0), round((start*deathRate), 0)))\n start = start+start*bornRate-start*deathRate\n print('Population: '+str(round(start, 0)))\n\n\nmain()\n","sub_path":"practical3/GPS.py","file_name":"GPS.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"416770780","text":"\"\"\"\nCreated on 3/5/20\nMarquette Robotics Club\nDanny Hudetz\nPurpose: read from the hdf5 format and visualize the coordinates mapped nearest\n to user input in 3 dimensions\n\"\"\"\n\nfrom math import pi, sin, cos\nfrom numpy import deg2rad\nfrom random import random\nimport vis\nfrom direct.showbase.ShowBase import ShowBase\nfrom direct.task import Task\nfrom pandac.PandaModules import *\nfrom panda3d.core import *\nfrom direct.interval.IntervalGlobal import *\nimport threading\nimport sys,os\n\nclass visualizer(ShowBase):\n\n def __init__(self):\n ShowBase.__init__(self)\n w, h = 750, 750\n self.thickness=50\n\n props = WindowProperties()\n props.setSize(w, h)\n\n mydir = os.path.abspath(sys.path[0])\n self.mydir = Filename.fromOsSpecific(mydir).getFullpath()\n\n base.win.requestProperties(props)\n base.setBackgroundColor(0,0,0)\n self.a=self.b=self.c=self.counter=0\n self.center = LVector3f(0,0,0)\n self.back=vis.backEnd(self.a,self.b,self.c)\n self.aSeg = LineSegs(\"a\")\n self.bSeg = LineSegs(\"b\")\n self.cSeg = LineSegs(\"c\")\n self.aSeg.setColor(1, 1 ,1 ,1)\n self.bSeg.setColor(1, 1 ,1 ,1)\n self.cSeg.setColor(1, 1 ,1 ,1)\n self.segments=(self.aSeg,self.bSeg,self.cSeg)\n self.models=[]\n self.currentColor=1\n self.colorForward=True\n for s in self.segments:\n s.setThickness(self.thickness)\n self.segmentNodes=[]\n for s in self.segments:\n self.segmentNodes.append(s.create(False))\n #grid drawing\n tileSize=10\n numLines=100\n doGrid=False\n if doGrid:\n for x in range(int(-numLines/2),int(numLines/2)):\n gridSegment=LineSegs(\"g\")\n gridSegment.setColor(0.3,0.3,0.3,1)\n gridSegment.setThickness(5)\n gridSegment.drawTo(x*tileSize, (-numLines/2)*tileSize, 0)\n gridSegment.drawTo(x*tileSize, (numLines/2)*tileSize, 0)\n render.attachNewNode(gridSegment.create(False))\n for y in range(int(-numLines/2),int(numLines/2)):\n gridSegment=LineSegs(\"g\")\n gridSegment.setColor(0.3,0.3,0.3,1)\n gridSegment.setThickness(5)\n gridSegment.drawTo((-numLines/2)*tileSize, y*tileSize, 0)\n gridSegment.drawTo((numLines/2)*tileSize, y*tileSize, 0)\n render.attachNewNode(gridSegment.create(False))\n self.taskMgr.add(self.spinCameraTask, \"SpinCameraTask\")\n\n def changeSegments(self,a,b,c):\n self.a=a\n self.b=b\n self.c=c\n self.back=vis.backEnd(self.a,self.b,self.c)\n\n\n def drawSegments(self, t0, t1, t2, t3):\n numModels=400\n if self.currentColor==numModels or self.currentColor==0:\n self.colorForward=(not self.colorForward)\n for sNode in self.segmentNodes:\n np=NodePath(sNode)\n np.removeNode()\n if len(self.models)>numModels:\n self.models[0].removeNode()\n self.models.pop(0)\n (ar,az,br,bz,cr,cz)=self.back.calculateComponents(t1,t2,t3)\n aVector = LVector3f(ar,0,az)\n bVector = LVector3f(br,0,bz)\n cVector = LVector3f(cr,0,cz)\n POI = self.center+aVector+bVector+cVector\n vertices=[self.center,self.center+aVector,self.center+aVector+bVector,POI]\n rotatedVertices=[]\n for vertex in vertices:\n q=Quat()\n q.set_from_axis_angle(t0+180, LVector3f(0,0,1))\n rotatedVertices.append(q.xform(vertex))\n drawSegs=False\n if drawSegs:\n self.aSeg.drawTo(rotatedVertices[0])\n self.aSeg.drawTo(rotatedVertices[1])\n self.bSeg.drawTo(rotatedVertices[1])\n self.bSeg.drawTo(rotatedVertices[2])\n self.cSeg.drawTo(rotatedVertices[2])\n self.cSeg.drawTo(rotatedVertices[3])\n self.segmentNodes=[]\n for s in self.segments:\n self.segmentNodes.append(s.create(False))\n #for vertex in rotatedVertices:\n modelIso = loader.loadModel(self.mydir + \"/models/Icosahedron.egg\")\n self.models.append(modelIso)\n randomConstant1=random()\n randomConstant2=random()\n randomConstant3=random()\n modelIso.setColor(randomConstant1,randomConstant2,randomConstant3,1)\n modelIso.setPos(rotatedVertices[3])\n modelIso.setScale(0.6,0.6,0.6)\n modelIso.reparentTo(self.render)\n for sNode in self.segmentNodes:\n render.attachNewNode(sNode)\n if self.colorForward:\n self.currentColor+=1\n else:\n self.currentColor-=1\n\n def spinCameraTask(self, task):\n angleDegrees = task.time * 10.0\n angleRadians = angleDegrees * (pi / 180.0)\n self.camera.setPos(200 * sin(angleRadians), -200 * cos(angleRadians), -200)\n self.camera.setHpr(angleDegrees, 45, 180)\n return Task.cont\n\n def generationTask(self, task):\n currentFrame = task.frame\n self.degrees+=.8\n while currentFrame<10000:\n c0=1.1\n c1=-1.2\n c2=1.3\n c3=-1.4\n self.drawSegments(c0*self.degrees,c1*self.degrees,c2*self.degrees,c3*self.degrees)\n return Task.cont\n\n def newGeneration(self):\n self.degrees=0\n self.taskMgr.add(self.generationTask, \"generationTask\")\n\n def close(self):\n sys.exit()\n\napp = visualizer()\ndone=False\n\ndef userInputLoop():\n global done, currentAngles, previousAngles, back, app\n print(\"\\nGenerative Visualizer\")\n while not done:\n userInput = input(\"q to quit, go to generate: \")\n words=userInput.split()\n if words[0] == 'q':\n done=True\n elif words[0] == 'go':\n app.newGeneration()\n\ntry:\n userThread = threading.Thread(target=userInputLoop, args=())\n userThread.start()\nexcept:\n print(\"Error: unable to start thread\")\n\napp.changeSegments(25,25,25)\napp.run()\n","sub_path":"rainbowSnake.py","file_name":"rainbowSnake.py","file_ext":"py","file_size_in_byte":6019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"353346411","text":"\"\"\"\nDjango settings for steam_wordclouds project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\ntry:\n SECRET_KEY = os.environ['DJANGO_SECRET_KEY']\nexcept KeyError:\n pass\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = ['*']\n\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'portal',\n 'widget_tweaks',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'steam_wordclouds.urls'\n\nWSGI_APPLICATION = 'steam_wordclouds.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {}\n\n# Cache setup\ntry:\n CACHES = {\n 'default': {\n 'BACKEND': 'django_bmemcached.memcached.BMemcached',\n 'LOCATION': os.environ['MEMCACHEDCLOUD_SERVERS'].split(','),\n 'LOCATION': 'pub-memcache-14561.us-east-1-4.1.ec2.garantiadata.com:14561',\n 'TIMEOUT': 900,\n 'MAX_ENTRIES': 300,\n 'OPTIONS': {\n 'username': os.environ['MEMCACHEDCLOUD_USERNAME'],\n 'password': os.environ['MEMCACHEDCLOUD_PASSWORD']\n }\n }\n }\nexcept:\n CACHES = {\n 'default': {\n 'BACKEND': 'django_bmemcached.memcached.BMemcached',\n 'LOCATION': 'localhost:11211',\n 'TIMEOUT': 900, # 15 minute timeout\n 'MAX_ENTRIES': 300,\n 'OPTIONS': {\n\n }\n }\n }\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = 'staticfiles'\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\n\nTEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s',\n 'formattime': '%Y-%m-%d %H:%M:%S'\n }\n },\n 'handlers': {\n 'file': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': 'django.log',\n 'formatter': 'verbose'\n }\n },\n 'loggers': {\n 'portal': {\n 'handlers': ['file'],\n 'level': 'DEBUG'\n },\n 'utils': {\n 'handlers': ['file'],\n 'level': 'DEBUG'\n }\n }\n}\n\ntry:\n from settings_debug import *\nexcept:\n pass\n","sub_path":"steam_wordclouds/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"195298711","text":"# coding: utf-8\n# Author: Miracle Yoo\nfrom .BasicModule import BasicModule\nimport jieba\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nfrom gensim.models import word2vec\ntorch.manual_seed(1)\n\n\nclass TextCNN(BasicModule):\n def __init__(self, opt):\n super(TextCNN, self).__init__()\n self.model_name = \"DoubleCNNTextBNDeep\"\n if opt.USE_CHAR:\n opt.VOCAB_SIZE = opt.CHAR_SIZE\n self.encoder = nn.Embedding(opt.VOCAB_SIZE, opt.EMBEDDING_DIM)\n question_convs = [nn.Sequential(\n nn.Conv1d(in_channels=opt.EMBEDDING_DIM,\n out_channels=opt.TITLE_DIM,\n kernel_size=kernel_size),\n nn.BatchNorm1d(opt.TITLE_DIM),\n nn.ReLU(inplace=True),\n \n nn.Conv1d(in_channels=opt.TITLE_DIM,\n out_channels=opt.TITLE_DIM,\n kernel_size=kernel_size),\n nn.BatchNorm1d(opt.TITLE_DIM),\n nn.ReLU(inplace=True),\n nn.MaxPool1d(kernel_size=(opt.SENT_LEN - kernel_size*2 + 2))\n )for kernel_size in opt.KERNEL_SIZE]\n\n self.question_convs = nn.ModuleList(question_convs)\n self.fc = nn.Sequential(\n nn.Linear(len(opt.KERNEL_SIZE)*(opt.TITLE_DIM), opt.LINER_HID_SIZE),\n nn.BatchNorm1d(opt.LINER_HID_SIZE),\n nn.ReLU(inplace=True),\n nn.Dropout(0.5),\n nn.Linear(opt.LINER_HID_SIZE, opt.NUM_CLASSES)\n )\n\n def forward(self, question):\n question = self.encoder(question)\n # permute 的作用是交换维度,因为词嵌入的维度200要作为后面conv1的输入的channel,所以第二和三维交换\n question_out = [question_conv(question.permute(0, 2, 1)) for question_conv in self.question_convs]\n conv_out = torch.cat(question_out, dim=1)\n reshaped = conv_out.view(conv_out.size(0), -1)\n logits = self.fc(reshaped)\n return logits\n\n\n","sub_path":"models/TextCNN.py","file_name":"TextCNN.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"252339645","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pytest\n\nimport riff\n\n\n# def pytest_addoption(parser):\n# parser.addoption(\n# \"--headless\",\n# action=\"store_true\",\n# default=False,\n# help=\"Run headless browser\",\n# )\n\n\n@pytest.fixture(scope=\"session\")\ndef headless(request):\n return request.config.getoption(\"--headless\")\n\n\ndef pytest_runtest_makereport(item, call):\n if \"incremental\" in item.keywords:\n if call.excinfo is not None:\n parent = item.parent\n parent._previousfailed = item\n\n\ndef pytest_runtest_setup(item):\n if \"incremental\" in item.keywords:\n previousfailed = getattr(item.parent, \"_previousfailed\", None)\n if previousfailed is not None:\n pytest.xfail(\"previous test failed (%s)\" % previousfailed.name)\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"162685364","text":"#!/usr/bin/python\n#encoding: UTF8\n\nimport sys\nimport smbus\nimport rospy\nimport time\nimport datetime\nfrom std_msgs.msg import UInt8,UInt64MultiArray,Float32MultiArray\nfrom geometry_msgs.msg import Twist\n\n#indice des capteurs\nUS_BACKLEFTB\t\t= 0\nUS_BACKLEFTU\t\t= 1\nUS_SIDELEFT\t\t\t= 2\nUS_FRONTLEFT\t\t= 3\nUS_FRONTRIGHT\t\t= 4\nUS_SIDERIGHT\t\t= 5\nUS_BACKRIGHTU\t\t= 6\nUS_BACKRIGHTB\t\t= 7\nIR_RIGHT\t\t\t= 9\nIR_LEFT\t\t\t\t= 8\n\n# Valeurs limites des capteurs\nMAXIR\t\t\t\t= 2.0\t# en mètre\n\nMINUSFRONT\t\t\t= 0.20\t# en mètre\nMINUSSIDE\t\t\t= 0.10\t# en mètre\nMINUSBACK\t\t\t= 0.20\t# en mètre\nMINUSBACKSIDE\t\t= 0.10\t# en mètre\n\nSPEEDRATE\t\t\t= 2\t\t# Ratio de régulation de la vitesse / distance des capteurs\n\t\t\t\t\t\t\t# diviser la distance minimale au capteur en cm pour obtenir une vitesse de 0 à 127\n\nclass Motor_safe:\n\n\tdef __init__(self):\n\n\t\tself.proximity = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]\n\t\tself.vitesse = 0\n\t\tself.sensor=False\n\n\t\tself.maxir=rospy.get_param('~max_ir',MAXIR) # en mètre\n\n\t\tself.cmdvel = rospy.Publisher(\"cmd_vel\", Twist, queue_size=10)\t\t\n\t\tself.cmdstop = rospy.Publisher(\"cmd_stop\", UInt8, queue_size=10)\t\t\n\t\trospy.Subscriber(\"~cmd_vel\", Twist, self.on_move, queue_size=10)\n\t\trospy.Subscriber(\"proximity\", Float32MultiArray, self.on_proximity, queue_size=10)\n\n\tdef on_proximity(self, msg):\n\n\t\tself.sensor=True\n\t\tfor x in range(0,10):\n\t\t\tself.proximity[x]=msg.data[x]\n\t\t#loginfo(\"IRR=%.2F IRG=%.2f\"%(self.proximity[IR_RIGHT],self.proximity[IR_LEFT]))\n\t\tstop = False\n\t\t# S'il y a un obstacle s'arréter\n\t\tif self.vitesse != 0:\n\t\t\tif self.vitesse > 0 and self.test_devant():\n\t\t\t\tstop=True\n\t\t\telif self.vitesse < 0 and self.test_derriere():\n\t\t\t\tstop=True\n\t\t\tif stop:\n\t\t\t\tloginfo(\"EMERGENCY\")\n\t\t\t\tself.cmdstop.publish(10)\n\n\tdef on_move(self,msg):\n\n\t\tif msg.linear.x != 0:\n\n\t\t\tif msg.linear.x > 0:\n\t\t\t\td = self.dist_devant()\n\t\t\t\tif d < MINUSFRONT: msg.linear.x=0\n\t\t\t\telif d < 3:\n\t\t\t\t\tx = d / SPEEDRATE\n\t\t\t\t\tif msg.linear.x > x:\n\t\t\t\t\t\tmsg.linear.x = x\n\t\t\telif msg.linear.x < 0:\n\t\t\t\td = self.dist_derriere()\n\t\t\t\tif d < MINUSBACK: msg.linear.x=0\n\t\t\t\tif d < 3:\n\t\t\t\t\tx = d / SPEEDRATE\n\t\t\t\t\tif msg.linear.x < -x:\n\t\t\t\t\t\tmsg.linear.x = -x\n\n\t\tself.vitesse=msg.linear.x\n\t\t#loginfo(\"vitesse %.2f\"%self.vitesse)\n\t\tself.cmdvel.publish(msg)\n\n\n\tdef dist_devant(self):\n\t\tif self.proximity[IR_RIGHT] > self.maxir or self.proximity[IR_LEFT] > self.maxir:\n\t\t\tloginfo(\"Obst devant IRR=%.2f IRG=%.2f\"%(self.proximity[IR_RIGHT],self.proximity[IR_LEFT]))\n\t\t\treturn 0\n\t\tres = min(self.proximity[US_FRONTRIGHT],self.proximity[US_FRONTLEFT])\n\t\tres = min(res,self.proximity[US_SIDERIGHT])\n\t\tres = min(res,self.proximity[US_SIDELEFT])\n\t\treturn res\n\n\tdef dist_derriere(self):\n\t\tres = min(self.proximity[US_BACKRIGHTB],self.proximity[US_BACKLEFTB])\n\t\tres = min(res,self.proximity[US_BACKRIGHTU])\n\t\tres = min(res,self.proximity[US_BACKLEFTU])\n\t\treturn res\n\n\tdef test_devant(self):\n\n\t\tif self.proximity[IR_RIGHT] > self.maxir or self.proximity[IR_LEFT] > self.maxir:\n\t\t\tloginfo(\"Obst IRR=%.2f IRG=%.2f\"%(self.proximity[IR_RIGHT],self.proximity[IR_LEFT]))\n\t\t\treturn True\n\n\t\tif self.proximity[US_FRONTRIGHT] < MINUSFRONT or self.proximity[US_FRONTLEFT] < MINUSFRONT:\n\t\t\tloginfo(\"Obst USFR=%.2f USFL=%.2f\"%(self.proximity[US_FRONTRIGHT],self.proximity[US_FRONTLEFT]))\n\t\t\treturn True\n\n\t\tif self.proximity[US_SIDERIGHT] < MINUSSIDE or self.proximity[US_SIDELEFT] < MINUSSIDE:\t\n\t\t\tloginfo(\"Obst USSR=%.2f USSL=%.2f\"%(self.proximity[US_SIDERIGHT],self.proximity[US_SIDELEFT]))\n\t\t\treturn True\n\n\t\treturn False\n\n\n\tdef test_derriere(self):\n\n\t\tif self.proximity[US_BACKRIGHTB] < MINUSBACK or self.proximity[US_BACKLEFTB] < MINUSBACK:\n\t\t\tloginfo(\"Obst USBRU=%.2f USBLU=%.2f\"%(self.proximity[US_BACKRIGHTU],self.proximity[US_BACKLEFTU]))\n\t\t\treturn True\n\n\t\tif self.proximity[US_BACKRIGHTU] < MINUSBACKSIDE or self.proximity[US_BACKLEFTU] < MINUSBACKSIDE:\n\t\t\tloginfo(\"Obst USBRB=%.2f USBLB=%.2f\"%(self.proximity[US_BACKRIGHTB],self.proximity[US_BACKLEFTB]))\n\t\t\treturn True\n\n\t\treturn False\n\n\ndef loginfo(str):\n\trospy.loginfo(\"%s %s\",datetime.datetime.strftime(datetime.datetime.now(),\"%Y-%m-%d %H:%M:%S\"),str)\n\nif __name__ == \"__main__\":\n\n\trospy.init_node(\"motor_safe\")\n\tmotor = Motor_safe()\n\n\trate = rospy.Rate(5)\n\twhile not rospy.is_shutdown():\n\t\trate.sleep()\t\t\t\t# 5 fois par seconde\n\t\tif not motor.sensor:\n\t\t\tloginfo(\"SAFE control : pas de données des capteurs\")\n\t\t\tmotor.cmdstop.publish(10)\t# Arrêt décélération 10\n\t\tmotor.sensor=False\n\n\t\t\n\n\t\t\n\n\n\n\n\n","sub_path":"ubo_pkg/scripts/motor_safe.py","file_name":"motor_safe.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"229627756","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.views import View\nfrom django.contrib import messages\nfrom django.conf import settings\n\nimport requests\n\nfrom .forms import (LoginForm, AdminRegistrationForm, RegistrationForm)\n\nfrom requestHandlers import get_user\n\n\nclass Registration(View):\n template_name = 'users/'\n url = settings.API_URL + 'Users/'\n\n def get(self, request, *args, **kwargs):\n user = get_user(request.COOKIES.get('access', False))\n\n form = None\n if user:\n if user['admin']:\n form = AdminRegistrationForm()\n self.template_name += 'admin_registration.html'\n else:\n self.template_name = '404_not_found.html'\n else:\n form = RegistrationForm()\n self.template_name += 'customer_registration.html'\n\n return render(request, template_name=self.template_name, context={'form': form})\n\n def post(self, request, *args, **kwargs):\n form = AdminRegistrationForm(request.POST)\n\n if form.is_valid():\n payload = {\n 'email': form.cleaned_data['email'],\n 'password': form.cleaned_data['password'],\n 'admin': form.cleaned_data.get('admin', False),\n 'vendor': form.cleaned_data.get('vendor', False),\n 'customer': form.cleaned_data.get('customer', False)\n }\n requests.post(self.url, data=payload)\n\n response = redirect('/users/login')\n return response\n return HttpResponse(form.errors)\n\n\nclass Login(View):\n template_name = 'users/login.html'\n \n def get(self, request, *args, **kwargs):\n # If user is logged in login page will not be rendered\n if not (get_user(request.COOKIES.get('access', False))):\n form = LoginForm()\n return render(request, template_name=self.template_name, context={'form': form})\n return render(request, template_name='404_not_found.html')\n\n def post(self, request, *args, **kwargs):\n form = LoginForm(request.POST)\n\n if form.is_valid():\n url = settings.API_URL + 'token/'\n payload = {\n 'email': form.cleaned_data['email'], 'password': form.cleaned_data['password']}\n r = requests.post(url, data=payload)\n\n\n if r.status_code == 200:\n user = get_user(r.json()['access'])\n print(user)\n \n if user['admin']:\n user_type = 1\n elif user['vendor']:\n user_type = 2\n else:\n user_type = 3\n\n response = redirect('/')\n\n response.set_cookie('email', form.cleaned_data['email'])\n response.set_cookie('user', user_type)\n response.set_cookie('access', r.json()['access'])\n response.set_cookie('refresh', r.json()['refresh'], httponly=True)\n\n return response\n return HttpResponse(r.text)\n return HttpResponse(form.errors)\n\n\ndef logout(request):\n response = redirect('/users/login/')\n response.delete_cookie('access')\n response.delete_cookie('refresh')\n response.delete_cookie('email')\n response.delete_cookie('user')\n\n return response\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"458771913","text":"# coding:utf-8\nfrom random_data import random_data as ran\nfrom test import Test\n\nhost = 'http://127.0.0.1:5050'\n\n\nclass user(Test):\n \"\"\"用户\"\"\"\n global host\n _host = host\n _url = '/users/'\n _headers = ''\n _log_dir = 'err_log'\n _object_file = 'datas/users.data'\n _output = 'outputs/output.log'\n\n def __init__(self):\n self.id = None\n self.telephone = ran().telephone()\n self.nickname = ran().people_name()\n self.sex = ran().sex()\n self.img_url = ran().img_url()\n self.openid = ran().id()\n self.pwd = ran().strings()\n self._save_pwd = self.pwd\n\n\nclass login(Test):\n \"\"\"登录\"\"\"\n global host\n _host = host\n _url = '/logins/'\n _headers = ''\n _log_dir = 'err_log'\n _object_file = 'datas/logins.data'\n _output = 'outputs/output.log'\n\n def __init__(self, user=None):\n self.id = None\n self.user_id = None\n self.base = None\n self.login_time = None\n if user is None:\n self.pwd = ran().strings()\n self.openid = ran().id()\n else:\n self.pwd = user._save_pwd\n self.user_id = user.id\n self.openid = user.openid\n self._headers = user._headers\n\n\nclass address(Test):\n \"\"\"地址\"\"\"\n global host\n _host = host\n _url = '/addresses/'\n _headers = ''\n _log_dir = 'err_log'\n _object_file = 'datas/address.data'\n _output = 'outputs/output.log'\n\n def __init__(self, user=None):\n if user is None:\n self.user_id = ran().id()\n else:\n self._headers = user._headers\n self.user_id = user.id\n self.id = None\n self.consignee = ran().people_name()\n self.phone = ran().telephone()\n self.community = ran().address()\n self.build = ran().address()\n self.detail = ran().address()\n self.describe = ran().address()\n self.is_default = ran().bool()\n self.is_authentic = ran().bool()\n\n\nclass escort(Test):\n \"\"\"镖单\"\"\"\n global host\n _host = host\n _url = '/escorts/'\n _headers = ''\n _log_dir = 'err_log'\n _object_file = 'datas/escort.data'\n _output = 'outputs/output.log'\n\n def __init__(self, user=None, address=None):\n\n self.id = None\n self.paid = None\n self.is_transfer = None\n self.trade_number = None\n self.create_at = None\n if user is None:\n self.user_id = ran().id()\n self.name = ran().people_name()\n else:\n self.name = user.nickname\n self.user_id = user.id\n self._headers = user._headers\n self.progress = 'on'\n self.topic = '花草秀陪你过圣诞'\n self.time = ran().time()\n self.escortor_id = None\n self.phone = ran().telephone()\n self.information = ran().sentence()\n self.hide_information = ran().address() + ran().sentence()\n if address is None:\n self.address = ran().address()\n else:\n self.address = address.community + address.build + address.detail\n self.is_hide = ran().bool()\n self.fee = ran().int(0, 20)\n self.tip = ran().int(1, 10)\n self.expire_at = ran().time()\n self.pay_index = ran().int(0, 2)\n self.create_time = ''\n\n def put(self, progress, escortor_id=None):\n self.progress = progress\n self.escortor_id = escortor_id\n super(escort, self).put()\n # self.escortor_id = None\n\n\nclass escortor(Test):\n \"\"\"镖师\"\"\"\n global host\n _host = host\n _url = '/escortores/'\n _headers = ''\n _log_dir = 'err_log'\n _object_file = 'datas/escortor.data'\n _output = 'outputs/output.log'\n\n def __init__(self, user):\n self._headers = user._headers\n self.id = None\n self.user_id = user.id\n self.passed = False\n self.name = user.nickname\n self.telephone = ran().telephone()\n self.school = ran().address()\n self.address_detail = ran().address()\n\nif __name__ == '__main__':\n import requests\n requests.get(host + '/create_db/')\n for i in xrange(10000):\n user_1 = user()\n user_1._headers = {\n 'XXX-base': 'base'\n }\n user_1.post()\n login_1 = login(user_1).post()\n user_1._headers = {\n 'XXX-base': login_1.base\n }\n address_1 = address(user_1).post()\n # e = escort(user_1)\n # e.post()\n # e.put('off')\n # escort(user_1).post()\n escortor(user_1).post()\n","sub_path":"SinglePage/test/logic_test.py","file_name":"logic_test.py","file_ext":"py","file_size_in_byte":4551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128287681","text":"#%load q04_count/build.py\n\n\ndef deliveries_count(data):\n \n import yaml\n\n data=open('./data/ipl_match.yaml','r')\n data1=yaml.load(data) \n d=data1['innings'][0]['1st innings']['deliveries']\n\n #d1=d\n count=0\n \n for key,value in enumerate(d):\n value1=d[key]\n #print(value)\n #print(key,value,type(value))\n for k,v in value1.items():\n \n \n #print(v)\n if value1[k]['batsman']=='RT Ponting':\n \n count += 1\n\n return count\n\n\n#deliveries_count(d1)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"q04_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"446292860","text":"\"\"\"Handles the display and interaction of the UI\nwith the user.\n\nAuthor: Kyle McCahill\n\n\"\"\"\n\nimport sys\nimport logging\nfrom manager.Entry import Entry\nfrom manager.EntryManager import EntryManager\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout,\n QTableView, QPushButton, QListWidget, QInputDialog,\n QListWidgetItem, QStatusBar, QToolBar)\n\n\n# TODO: Clean up init and break into methods\n# TODO: Add status and info messages with QLabels <------\n# TODO: CLEAN UP THE INIT ITS SO BAD\nclass MainWindow(QWidget):\n def __init__(self, *args, **kwargs):\n super().__init__()\n\n self.setWindowTitle('To Do List')\n self.setGeometry(500, 500, 385, 450)\n\n self.manager = EntryManager()\n self.manager.loadDB() # loads and initializes the sqlite db if it doesn't exist\n\n vBox = QVBoxLayout()\n\n self.taskView = QListWidget()\n # this will make it so that when an item in the list is clicked it is removed immediately.\n # self.taskView.clicked.connect(self.__removeTask)\n\n self.statusBar = QStatusBar()\n self.toolbar = QToolBar()\n\n self.__setupToolbar()\n\n self.__setStyling()\n\n vBox.addWidget(self.toolbar)\n vBox.addWidget(self.taskView)\n\n self.setLayout(vBox)\n\n self.taskView.show()\n self.__redrawTaskView()\n\n self.show()\n\n \"\"\"Sets up the QToolBar widget at the top of the window.\"\"\"\n def __setupToolbar(self):\n addButton = QPushButton(\"Add\", self)\n addButton.clicked.connect(self.__addTask)\n\n removeButton = QPushButton(\"Remove\", self)\n removeButton.clicked.connect(self.__removeTask)\n\n saveButton = QPushButton(\"Save\")\n saveButton.clicked.connect(self.__saveList)\n\n self.toolbar.addWidget(saveButton)\n self.toolbar.addWidget(addButton)\n self.toolbar.addWidget(removeButton)\n\n self.toolbar.addWidget(self.statusBar)\n\n \"\"\"Establishes the styling and formatting of mainly the tableView\"\"\"\n def __setStyling(self):\n font = QtGui.QFont()\n font.setFamily(\"Arial\")\n font.setPointSize(11)\n self.taskView.setFont(font)\n\n statusFont = font\n statusFont.setPointSize(9)\n self.statusBar.setFont(font)\n self.statusBar.setSizeGripEnabled(False)\n\n self.toolbar.setStyleSheet(\"QToolBar{spacing: 5px;}\")\n\n \"\"\"Adds a new entry to the entry manager\"\"\"\n def __addTask(self):\n item, ok = QInputDialog.getText(self, \"Add Task\", \"Enter the task: \")\n if ok:\n date, ok = QInputDialog.getText(self, \"Add Task\", \"Enter the due date: \")\n if ok:\n self.manager.addEntry(Entry(item, date))\n self.__redrawTaskView()\n self.statusBar.showMessage(\"Added\", MESSAGE_TIME)\n\n \"\"\"Removes the selected item from the list\"\"\"\n def __removeTask(self):\n try:\n self.manager.removeEntry(self.taskView.currentItem().text())\n self.__redrawTaskView()\n self.statusBar.showMessage(\"Removed\", MESSAGE_TIME)\n except Exception: # bad but cant find the exception to catch here\n logging.error('Error nothing was selected')\n self.statusBar.showMessage(\"Error: No selection\", MESSAGE_TIME)\n\n \"\"\"Saves the list of tasks to the database\"\"\"\n def __saveList(self):\n self.manager.saveToDB()\n self.statusBar.showMessage(\"Saved\", MESSAGE_TIME)\n\n \"\"\"Redraws the taskView to keep it up to date\"\"\"\n def __redrawTaskView(self):\n self.taskView.clear()\n for entry in self.manager.entryList:\n entryString = entry.to_string()\n\n entryString = QListWidgetItem(entryString)\n entryString.setTextAlignment(QtCore.Qt.AlignHCenter)\n self.taskView.addItem(entryString)\n\n\n# CONSTANTS #\nMESSAGE_TIME = 2000\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n mw = MainWindow()\n sys.exit(app.exec_())","sub_path":"ui/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"35971277","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nCreated on 2015年2月28日\n\n@author: xuxu\n'''\n\nimport os\n\nfrom scriptUtils import utils\n\n#5037端口占用时杀掉占用该端口的进程\n\ndef linux():\n pid = os.popen(\"netstat -anop | grep 5037 | grep LISTEN\").read().split()[6].split(\"/\")[0]\n os.system(\"kill %s\" %pid)\n\ndef win():\n pid = os.popen(\"netstat -ano | findstr 5037 | findstr LISTENING\").read().split()[-1]\n os.system(\"taskkill /F /PID %s\" %pid)\n \n\nif __name__ == \"__main__\":\n if utils.system is \"Windows\":\n win()\n else:\n linux()","sub_path":"python/kill_5037.py","file_name":"kill_5037.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"476552470","text":"#!/usr/bin/env python3\nimport unittest\n\nfrom Crypto.Cipher import AES\n\nfrom set1 import from_b64\nfrom set2 import *\n\n\nclass TestSet2(unittest.TestCase):\n def test_challenge9(self):\n input1 = b\"YELLOW SUBMARINE\"\n result = pkcs7_pad(input1, 20)\n expected = b\"YELLOW SUBMARINE\\x04\\x04\\x04\\x04\"\n\n self.assertEqual(result, expected)\n\n def test_challenge10(self):\n key = b\"YELLOW SUBMARINE\"\n iv = b\"\\x00\" * 16\n msg = b\"Another round of shorts\"\n cipher = encrypt_aes_cbc(pkcs7_pad(msg), key, iv)\n result = decrypt_aes_cbc(cipher, key, iv)\n ctrl_result = AES.new(key, AES.MODE_CBC, iv).decrypt(cipher)\n expected = pkcs7_pad(msg)\n\n self.assertEqual(result, expected)\n self.assertEqual(result, ctrl_result)\n\n with open(\"10.txt\", \"rb\") as f1, open(\"10-expected.txt\", \"rb\") as f2:\n result = decrypt_aes_cbc(from_b64(f1.read()), key, iv)\n expected = f2.read().rstrip(b\"\\n\")\n\n self.assertEqual(result, expected)\n\n def test_challenge11(self):\n input1 = b\"A\" * 50\n\n for _ in range(100):\n cipher = encrypt_oracle(input1)\n result = detect_cipher_mode(cipher[\"cipher\"])\n expected = cipher[\"mode\"]\n\n self.assertEqual(result, expected)\n\n def test_challenge12(self):\n result_block_size = find_oracle_block_size(ecb_encrypt_oracle)\n result_mode = detect_cipher_mode(ecb_encrypt_oracle(b\"a\" * 50))\n result_msg = break_ecb_oracle(ecb_encrypt_oracle, block_size=result_block_size)\n expected_block_size = 16\n expected_mode = \"ECB\"\n expected_msg = (\n b\"Rollin' in my 5.0\\nWith my rag-top down so my hair\"\n b\" can blow\\nThe girlies on standby waving just to say\"\n b\" hi\\nDid you stop? No, I just drove by\\n\"\n )\n\n self.assertEqual(result_block_size, expected_block_size)\n self.assertEqual(result_mode, expected_mode)\n self.assertEqual(result_msg, expected_msg)\n\n def test_challenge13(self):\n self.assertTrue(create_admin_profile())\n\n def test_challenge14(self):\n result = break_ecb_oracle2(ecb_encrypt_oracle2)\n expected = (\n b\"Rollin' in my 5.0\\nWith my rag-top down so my hair\"\n b\" can blow\\nThe girlies on standby waving just to say\"\n b\" hi\\nDid you stop? No, I just drove by\\n\"\n )\n\n self.assertEqual(result, expected)\n\n def test_challenge15(self):\n input1 = b\"ICE ICE BABY\\x04\\x04\\x04\\x04\"\n input2 = b\"ICE ICE BABY\\x05\\x05\\x05\\x05\"\n input3 = b\"ICE ICE BABY\\x01\\x02\\x03\\x04\"\n\n result1 = pkcs7_unpad(input1)\n expected1 = b\"ICE ICE BABY\"\n\n with self.assertRaises(ValueError) as context:\n pkcs7_unpad(input2)\n result2 = context.exception\n\n with self.assertRaises(ValueError) as context:\n pkcs7_unpad(input3)\n result3 = context.exception\n\n self.assertEqual(result1, expected1)\n self.assertTrue(\"Wrong padding.\" in str(result2))\n self.assertTrue(\"Wrong padding.\" in str(result3))\n\n def test_challenge16(self):\n self.assertTrue(cbc_bitflipping_attack())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"cryptopals/python3/test_set2.py","file_name":"test_set2.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"611064235","text":"import FWCore.ParameterSet.Config as cms\n\nfrom RecoBTag.ImpactParameter.variableJTA_cff import *\n\n# negativeTrackCounting3D2nd btag computer\ncandidateNegativeTrackCounting3D2ndComputer = cms.ESProducer(\"CandidateNegativeTrackCountingESProducer\",\n variableJTAPars,\n minimumImpactParameter = cms.double(-1),\n useSignedImpactParameterSig = cms.bool(True),\n impactParameterType = cms.int32(0), ## 0 = 3D, 1 = 2D\n maximumDistanceToJetAxis = cms.double(0.07),\n deltaR = cms.double(-1.0), ## use cut from JTA\n maximumDecayLength = cms.double(5.0),\n nthTrack = cms.int32(2),\n trackQualityClass = cms.string(\"any\"),\n useVariableJTA = cms.bool(False)\n)\n","sub_path":"RecoBTag/ImpactParameter/python/candidateNegativeTrackCounting3D2ndComputer_cfi.py","file_name":"candidateNegativeTrackCounting3D2ndComputer_cfi.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"45176765","text":"# -*- encoding= utf-8 -*-\n\n# 题目url: https://leetcode.com/problems/island-perimeter/description/\n\nclass Solution:\n def islandPerimeter(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n cnt = 0\n for row in range(len(grid)):\n subGrid = grid[row];\n for col in range(len(subGrid)):\n if grid[row][col] == 1:\n sum=0\n if col -1 >= 0:\n sum += grid[row][col -1 ]\n if col + 1 < len(subGrid):\n sum += grid[row][col + 1]\n if row - 1 >= 0:\n sum += grid[row - 1][col]\n if row + 1 < len(grid):\n sum += grid[row + 1][col]\n cnt = cnt + 4 - sum\n return cnt\nprint(Solution.islandPerimeter(Solution,\n[[0,1,0,0],\n [1,1,1,0],\n [0,1,0,0],\n [1,1,0,0]]))","sub_path":"com/guoyang/leetcode/easy/IslandPerimeter.py","file_name":"IslandPerimeter.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"105981982","text":"import random\n\n\ndef compare(p1, p2):\n if p1 == p2:\n return 0\n return -1 if p2 in options.get(p1) else 1\n\n\noptions = {\n 'rock': 'paper',\n 'paper': 'scissors',\n 'scissors': 'rock',\n}\n\nuser_name = input('Enter your name:')\nuser_score = 0\nprint(f'Hello, {user_name}')\n\nrating_file = open('rating.txt', 'r')\nfor entry in rating_file:\n if user_name in entry:\n user_score = int(entry.split(' ')[1][:-1])\nrating_file.close()\n\noptions_list = input()\nif options_list:\n options.clear()\n options_list = options_list.split(',')\n length = len(options_list)\n half = length // 2\n\n for i in range(length):\n losing_to = []\n for j in range(i + 1, i + half + 1):\n losing_to.append(options_list[j % length])\n options[options_list[i]] = losing_to\n\nprint(\"Okay, let's start\")\nwhile True:\n user_choice = input().lower()\n if user_choice == '!exit':\n print('Bye!')\n break\n if user_choice == '!rating':\n print(f'Your rating: {user_score}')\n continue\n if user_choice not in options:\n print('Invalid input')\n continue\n\n comp_choice = random.choice(list(options))\n res = compare(comp_choice, user_choice)\n\n if res == 1:\n print(f'Sorry, but the computer chose {comp_choice}')\n elif res == 0:\n print(f'There is a draw ({comp_choice})')\n user_score += 50\n else:\n print(f'Well done. The computer chose {comp_choice} and failed')\n user_score += 100\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"310029257","text":"#!/usr/bin/env python3\n\nimport base64\nimport json\nimport os\nimport re\nfrom subprocess import PIPE, Popen\n\nfrom graphqlclient import GraphQLClient\n\nGITHUB_GPG_KEY = \"\"\"\n-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nxsBNBFmUaEEBCACzXTDt6ZnyaVtueZASBzgnAmK13q9Urgch+sKYeIhdymjuMQta\nx15OklctmrZtqre5kwPUosG3/B2/ikuPYElcHgGPL4uL5Em6S5C/oozfkYzhwRrT\nSQzvYjsE4I34To4UdE9KA97wrQjGoz2Bx72WDLyWwctD3DKQtYeHXswXXtXwKfjQ\n7Fy4+Bf5IPh76dA8NJ6UtjjLIDlKqdxLW4atHe6xWFaJ+XdLUtsAroZcXBeWDCPa\nbuXCDscJcLJRKZVc62gOZXXtPfoHqvUPp3nuLA4YjH9bphbrMWMf810Wxz9JTd3v\nyWgGqNY0zbBqeZoGv+TuExlRHT8ASGFS9SVDABEBAAHNNUdpdEh1YiAod2ViLWZs\nb3cgY29tbWl0IHNpZ25pbmcpIDxub3JlcGx5QGdpdGh1Yi5jb20+wsBiBBMBCAAW\nBQJZlGhBCRBK7hj4Ov3rIwIbAwIZAQAAmQEIACATWFmi2oxlBh3wAsySNCNV4IPf\nDDMeh6j80WT7cgoX7V7xqJOxrfrqPEthQ3hgHIm7b5MPQlUr2q+UPL22t/I+ESF6\n9b0QWLFSMJbMSk+BXkvSjH9q8jAO0986/pShPV5DU2sMxnx4LfLfHNhTzjXKokws\n+8ptJ8uhMNIDXfXuzkZHIxoXk3rNcjDN5c5X+sK8UBRH092BIJWCOfaQt7v7wig5\n4Ra28pM9GbHKXVNxmdLpCFyzvyMuCmINYYADsC848QQFFwnd4EQnupo6QvhEVx1O\nj7wDwvuH5dCrLuLwtwXaQh0onG4583p0LGms2Mf5F+Ick6o/4peOlBoZz48=\n=HXDP\n-----END PGP PUBLIC KEY BLOCK-----\n\"\"\"\n\n\ndef extract_user(line):\n if '\"' not in line:\n return\n\n user_id = line.split('\"')[1]\n match = re.search(pattern, user_id, re.IGNORECASE)\n if match:\n first_name = match.group(1)\n last_name = match.group(2)\n email = match.group(4)\n\n org_id = email.split(\"@\")[0]\n\n if last_name:\n full_name = \" \".join([first_name, last_name])\n else:\n full_name = first_name\n\n full_name = full_name.strip().lower()\n\n if org_id.lower() in user_dict:\n confirmed_users.add(org_id)\n elif full_name in user_dict:\n confirmed_users.add(user_dict[full_name])\n else:\n orphaned_users.add(user_id)\n\n\ndef get_github_actions_user():\n github_actions_user = {}\n github_actions_user[\"org_username\"] = \"Github\"\n github_actions_user[\"full_name\"] = \"GitHub\"\n github_actions_user[\"public_gpg_key\"] = _read_local_github_gpg_key_file()\n return github_actions_user\n\n\ndef _read_local_github_gpg_key_file():\n return base64.b64encode(GITHUB_GPG_KEY.encode(\"ascii\")).decode()\n\n\nquery = \"\"\"{\n users: users_v1 {\n public_gpg_key\n org_username\n full_name: name\n }\n}\"\"\"\n\nDEFAULT_URL = \"http://localhost:4000/graphql\"\n\nAPP_INTERFACE_BASE_URL = os.getenv(\"APP_INTERFACE_BASE_URL\")\n\nQONTRACT_BASE_URL = os.getenv(\n \"QONTRACT_BASE_URL\",\n f\"https://{APP_INTERFACE_BASE_URL}/graphql\"\n if APP_INTERFACE_BASE_URL\n else DEFAULT_URL,\n)\n\nclient = GraphQLClient(QONTRACT_BASE_URL)\n\nif os.getenv(\"QONTRACT_TOKEN\"):\n client.inject_token(os.getenv(\"QONTRACT_TOKEN\"))\nelse:\n username = os.getenv(\"APP_INTERFACE_USERNAME\")\n password = os.getenv(\"APP_INTERFACE_PASSWORD\")\n basic_auth = base64.b64encode(f\"{username}:{password}\".encode(\"utf-8\")).decode(\n \"ascii\"\n )\n client.inject_token(f\"Basic {basic_auth}\")\n\nusers = json.loads(client.execute(query))[\"data\"][\"users\"]\n\ngpg_users = set()\nuser_dict = {}\nbig_bytes = b\"\"\nbig_gpg_output = \"\"\n\ngithub_actions_user = get_github_actions_user()\nusers.append(github_actions_user)\n\nfor user in (u for u in users if u[\"public_gpg_key\"]):\n if user[\"org_username\"] == \"jmoshenk\":\n continue\n if user[\"org_username\"] == \"rzaleski\":\n continue\n\n proc = Popen(\"base64 -d\", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n stdout, _ = proc.communicate(user[\"public_gpg_key\"].encode(\"ascii\"))\n\n if proc.returncode > 0:\n print(\"Bad GPG key: %s\" % user[\"org_username\"])\n continue\n\n big_bytes = stdout\n\n proc = Popen(\n \"gpg --no-default-keyring --keyring=$PWD/git.gpg --import -\",\n shell=True,\n stdin=PIPE,\n stdout=PIPE,\n stderr=PIPE,\n )\n\n stdout, stderr = proc.communicate(big_bytes)\n\n if proc.returncode > 0:\n print(\"Bad time with key: %s\" % user[\"org_username\"])\n continue\n\n print(\"Encoded: %s\" % stderr)\n big_gpg_output += stderr.decode(\"utf-8\", errors=\"ignore\")\n\n gpg_users.add(user[\"org_username\"])\n user_dict[user[\"org_username\"].lower()] = user[\"full_name\"].lower().strip()\n user_dict[user[\"full_name\"].lower().strip()] = user[\"org_username\"].lower()\n\nconfirmed_users = set()\norphaned_users = set()\npattern = r\"(\\w+) (\\w+ )?(\\(.*\\) )?<(.*)>\"\n\nfor line in big_gpg_output.splitlines():\n extract_user(line)\n\nmissing_users = gpg_users - confirmed_users\n\nprint(\"Missing users:\")\nfor missing_user in missing_users:\n print(missing_user)\n\nprint()\n\nprint(\"Orphaned users:\")\nfor orphan in orphaned_users:\n print(orphan)\n","sub_path":"import_gpg.py","file_name":"import_gpg.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"12245793","text":"'''\n simple MNIST\n\n'''\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data\", one_hot=True)\n\n# first setup the computation graph\n\n## setup the placeholders and variables\n\n# create a placeholder for the data array which is a 28 sq image == 784 vector\nx = tf.placeholder(tf.float32, shape=[None, 784])\n\n# create another placeholder for the probability of each class(0-9 in this case)\n# these probabilities should sum to 1\ny_ = tf.placeholder(tf.float32, shape=[None, 10])\n\n# define the variable objects for Weights and Balances\n\nW = tf.Variable(tf.zeros([784, 10]))\nb = tf.Variable(tf.zeros([10]))\n\n\n# second, multiply the weights and x and then add the bias\n# note that the order of x, W matters because the shapes must match for matmul\ny = tf.nn.softmax(tf.matmul(x, W) + b)\n\n# now define the loss function\n# we use reduce mean to get the mean across the array\ncross_entropy = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=y)\n)\n\n# next we define our optimizer\n\ntrain_step = tf.train.GradientDescentOptimizer(.5).minimize(cross_entropy)\n\n# at this point our computation graph is populated so initialize all variables\n\ninit = tf.global_variables_initializer()\n\n# create an interactive session. we must close this session later\n\nsess = tf.Session()\n\n# variable initialization in the session\nsess.run(init)\n\n# execute 1000 training steps\n\nfor i in range(1000):\n # batch_xs is the image\n # batch_ys is the actual class of the image (some number 0-9)\n batch_xs, batch_ys = mnist.train.next_batch(100) # this pulls 100 random\n # examples from data\n sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n\n# compare performance across y and y_\ncorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\ntest_accuracy = sess.run(accuracy, feed_dict=\n {\n x: mnist.test.images, y_: mnist.test.labels\n }\n)\nprint(\"Test accuracy: {}\".format(test_accuracy * 100))\n\nsess.close()\n","sub_path":"mnist/simple_mnist.py","file_name":"simple_mnist.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"476242559","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 28 15:44:32 2020\n\n@author: jlo\n\"\"\"\n\nimport itertools\nimport math\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\nimport scipy.sparse as sp \nimport torch.backends.cudnn as cudnn\nimport os\nimport matplotlib.pyplot as plt\nfrom harmony import harmonize\nfrom sklearn.neighbors import NearestNeighbors, KNeighborsClassifier\nfrom scipy.sparse import csr_matrix, find, csgraph\nfrom scipy.spatial import distance_matrix\nfrom scipy.linalg import block_diag\nfrom torchvision import models\nfrom itertools import chain\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch\nimport keras.optimizers\nfrom unioncom import UnionCom\n\nclass Project(nn.Module):\n\tdef __init__(self, input_dim, output_dim):\n\t\tsuper(Project, self).__init__()\n\t\tself.restored = False\n\t\tself.input_dim = input_dim\n\t\tself.output_dim = output_dim\n\n\t\tnum = len(input_dim)\n\t\tfeature = []\n\n\t\tfor i in range(num):\n\t\t\tfeature.append(\n\t\t\tnn.Sequential(\n\t\t\tnn.Linear(self.input_dim[i],2*self.input_dim[i]),\n\t\t\tnn.BatchNorm1d(2*self.input_dim[i]),\n\t\t\tnn.LeakyReLU(0.1, True),\n\t\t\tnn.Linear(2*self.input_dim[i],2*self.input_dim[i]),\n\t\t\tnn.BatchNorm1d(2*self.input_dim[i]),\n\t\t\tnn.LeakyReLU(0.1, True),\n\t\t\tnn.Linear(2*self.input_dim[i],self.input_dim[i]),\n\t\t\tnn.BatchNorm1d(self.input_dim[i]),\n\t\t\tnn.LeakyReLU(0.1, True),\n\t\t\tnn.Linear(self.input_dim[i],self.output_dim),\n\t\t\tnn.BatchNorm1d(self.output_dim),\n\t\t\tnn.LeakyReLU(0.1, True),\n\t\t))\n\n\t\tself.feature = nn.ModuleList(feature)\n\n\t\tself.feature_show = nn.Sequential(\n\t\t\tnn.Linear(self.output_dim,self.output_dim),\n\t\t\tnn.BatchNorm1d(self.output_dim),\n\t\t\tnn.LeakyReLU(0.1, True),\n\t\t\tnn.Linear(self.output_dim,self.output_dim),\n\t\t\tnn.BatchNorm1d(self.output_dim),\n\t\t\tnn.LeakyReLU(0.1, True),\n\t\t\tnn.Linear(self.output_dim,self.output_dim),\n\t\t)\n\n\tdef forward(self, input_data, domain):\n\t\tfeature = self.feature[domain](input_data)\n\t\tfeature = self.feature_show(feature)\n\n\t\treturn feature\n \nclass params():\n epoch_pd = 20000\n epoch_DNN = 200\n epsilon = 0.001\n lr = 0.001\n batch_size = 100\n rho = 10\n log_DNN = 10\n log_pd = 500\n manual_seed = 8888\n delay = 0\n kmax = 20\n beta = 1\n\n\nos.chdir(r\"C:\\Users\\jlo\\Documents\\Summer20\\HUANG\\Data\")\npp_donorA = \"donorA/filtered_matrices_mex/hg19/write/donorA_pp.h5ad\"\npp_donorB = \"donorB/filtered_matrices_mex/hg19/write/donorB_pp.h5ad\"\npp_donorA_sample = \"donorA/filtered_matrices_mex/hg19/write/donorA_sample_pp.h5ad\"\npp_donorB_sample = \"donorB/filtered_matrices_mex/hg19/write/donorB_sample_pp.h5ad\"\npp_donors_merged = \"donors_merged/donors_merged_pp.h5ad\"\npp_donors_merged_control = \"donors_merged/donors_merged__control_pp.h5ad\"\n\nsc.settings.verbosity = 3\nsc.logging.print_versions()\nsc.settings.set_figure_params(dpi=80, facecolor = 'white')\n\nDonorA = sc.read_10x_mtx(path = r'C:\\Users\\jlo\\Documents\\Summer20\\HUANG\\Data\\donorA\\filtered_matrices_mex\\hg19',var_names = 'gene_symbols', cache = True)\nDonorB = sc.read_10x_mtx(path = r'C:\\Users\\jlo\\Documents\\Summer20\\HUANG\\Data\\donorB\\filtered_matrices_mex\\hg19',var_names = 'gene_symbols', cache = True)\nDonorA_sample = sc.pp.subsample(DonorA, fraction = .1, copy = True)\nDonorB_sample = sc.pp.subsample(DonorB, fraction = .1, copy = True)\nDonors_merged_control = DonorA_sample.concatenate(DonorB_sample, join = 'outer')\n\n\n#artificially change labels for donor B\noldvars = DonorB_sample.var_names\nnewvars = [str(i) for i in range(1,(len(DonorB_sample.var_names)+1))]\nDonorB_sample.var_names = newvars\nDonors_merged= DonorA_sample.concatenate(DonorB_sample, join = 'outer')\n\nsc.pl.highest_expr_genes(DonorA, n_top=20,)\nsc.pl.highest_expr_genes(DonorB, n_top=20,)\nsc.pl.highest_expr_genes(DonorA_sample, n_top=20,)\nsc.pl.highest_expr_genes(DonorB_sample, n_top=20,)\nsc.pl.highest_expr_genes(Donors_merged, n_top = 20,)\nsc.pl.highest_expr_genes(Donors_merged_control, n_top = 20,)\nsc.pp.filter_cells(DonorA, min_genes = 200)\nsc.pp.filter_cells(DonorB, min_genes = 200)\nsc.pp.filter_cells(DonorA_sample, min_genes = 200)\nsc.pp.filter_cells(DonorB_sample, min_genes = 200)\nsc.pp.filter_cells(Donors_merged, min_genes = 200)\nsc.pp.filter_cells(Donors_merged_control, min_genes = 200)\nsc.pp.filter_genes(DonorA, min_cells=5)\nsc.pp.filter_genes(DonorB, min_cells=5)\nsc.pp.filter_genes(DonorA_sample, min_cells=5)\nsc.pp.filter_genes(DonorB_sample, min_cells=5)\nsc.pp.filter_genes(Donors_merged, min_cells = 5)\nsc.pp.filter_genes(Donors_merged_control, min_cells = 5)\nDonorA.var['mt'] = DonorA.var_names.str.startswith('MT-')###not sure why spyder marks this as a syntax error\nDonorB.var['mt'] = DonorB.var_names.str.startswith('MT-')###not sure why spyder marks this as a syntax error\n\nsc.pp.calculate_qc_metrics(DonorA, qc_vars = ['mt'], percent_top = None, log1p=False, inplace = True)\nsc.pp.calculate_qc_metrics(DonorB, qc_vars = ['mt'], percent_top = None, log1p=False, inplace = True)\nsc.pp.calculate_qc_metrics(Donors_merged, percent_top = None, log1p=False, inplace = True)\nsc.pp.calculate_qc_metrics(Donors_merged_control, percent_top = None, log1p=False, inplace = True)\nsc.pp.calculate_qc_metrics(DonorA_sample, percent_top = None, log1p=False, inplace = True)\nsc.pp.calculate_qc_metrics(DonorB_sample, percent_top = None, log1p=False, inplace = True)\n\n\nsc.pl.violin(DonorA, ['n_genes_by_counts', 'total_counts', 'pct_counts_mt'], jitter = .4, multi_panel = True)\nsc.pl.violin(DonorB, ['n_genes_by_counts', 'total_counts', 'pct_counts_mt'], jitter = .4, multi_panel = True)\nsc.pl.violin(DonorA_sample, ['n_genes_by_counts', 'total_counts'], jitter = .4, multi_panel = True)\nsc.pl.violin(DonorB_sample, ['n_genes_by_counts', 'total_counts'], jitter = .4, multi_panel = True)\nsc.pl.violin(Donors_merged, ['n_genes_by_counts', 'total_counts'], jitter = .4, multi_panel = True)\nsc.pl.violin(Donors_merged_control, ['n_genes_by_counts', 'total_counts'], jitter = .4, multi_panel = True)\n\n\nsc.pl.scatter(DonorA, x = 'total_counts', y = 'pct_counts_mt')\nsc.pl.scatter(DonorB, x = 'total_counts', y = 'pct_counts_mt')#visualize - note that the mt percentage is on average higher for this dataset, and there appears to be a clear elbow starting at around 18\nDonorA = DonorA[DonorA.obs.pct_counts_mt<5, :]\nDonorB = DonorB[DonorB.obs.pct_counts_mt<6, :]\nsc.pl.scatter(DonorA, x = 'total_counts', y = 'pct_counts_mt')#visualize after\nsc.pl.scatter(DonorB, x = 'total_counts', y = 'pct_counts_mt')\n\nsc.pl.scatter(DonorA, x = 'total_counts', y = 'n_genes_by_counts')\nsc.pl.scatter(DonorB, x = 'total_counts', y = 'n_genes_by_counts')#visualize\nsc.pl.scatter(DonorA_sample, x = 'total_counts', y = 'n_genes_by_counts')\nsc.pl.scatter(DonorB_sample, x = 'total_counts', y = 'n_genes_by_counts')#visualize\nsc.pl.scatter(Donors_merged, x = 'total_counts', y = 'n_genes_by_counts')\nsc.pl.scatter(Donors_merged_control, x = 'total_counts', y = 'n_genes_by_counts')\n\nDonorA = DonorA[DonorA.obs.n_genes_by_counts <2000, :]\nDonorB = DonorB[DonorB.obs.n_genes_by_counts <2000, :]\nDonorA_sample = DonorA_sample[DonorA_sample.obs.n_genes_by_counts <2000, :]\nDonorB_sample = DonorB_sample[DonorB_sample.obs.n_genes_by_counts <2000, :]\nDonors_merged = Donors_merged[Donors_merged.obs.n_genes_by_counts <2000, :]\nDonors_merged_control = Donors_merged_control[Donors_merged_control.obs.n_genes_by_counts <2000, :]\n\nsc.pl.scatter(DonorA, x = 'total_counts', y = 'n_genes_by_counts')\nsc.pl.scatter(DonorB, x = 'total_counts', y = 'n_genes_by_counts')\nsc.pl.scatter(DonorA_sample, x = 'total_counts', y = 'n_genes_by_counts')\nsc.pl.scatter(DonorB_sample, x = 'total_counts', y = 'n_genes_by_counts')\nsc.pl.scatter(Donors_merged, x = 'total_counts', y = 'n_genes_by_counts')\nsc.pl.scatter(Donors_merged_control, x = 'total_counts', y = 'n_genes_by_counts')\n\nsc.pp.normalize_total(DonorA)\nsc.pp.normalize_total(DonorB)\nsc.pp.normalize_total(DonorA_sample)\nsc.pp.normalize_total(DonorB_sample)\nsc.pp.normalize_total(Donors_merged)\nsc.pp.normalize_total(Donors_merged_control)\n\nsc.pp.log1p(DonorA)\nsc.pp.log1p(DonorB)\nsc.pp.log1p(DonorA_sample)\nsc.pp.log1p(DonorB_sample)\nsc.pp.log1p(Donors_merged)\nsc.pp.log1p(Donors_merged_control)\n\nsc.pp.highly_variable_genes(DonorA, min_mean = .0125, max_mean = 3, min_disp = .5)\nsc.pp.highly_variable_genes(DonorB, min_mean = .0125, max_mean = 3, min_disp = .5)\nsc.pp.highly_variable_genes(DonorA_sample, min_mean = .0125, max_mean = 3, min_disp = .5)\nsc.pp.highly_variable_genes(DonorB_sample, min_mean = .0125, max_mean = 3, min_disp = .5)\nsc.pp.highly_variable_genes(Donors_merged, min_mean = .0125, max_mean = 3, min_disp = .5)\nsc.pp.highly_variable_genes(Donors_merged_control, min_mean = .0125, max_mean = 3, min_disp = .5)\n\n\nsc.pl.highly_variable_genes(DonorA)\nsc.pl.highly_variable_genes(DonorB)\nsc.pl.highly_variable_genes(DonorA_sample)\nsc.pl.highly_variable_genes(DonorB_sample)\nsc.pl.highly_variable_genes(Donors_merged)\nsc.pl.highly_variable_genes(Donors_merged_control)\nDonorA = DonorA[:, DonorA.var.highly_variable]\nDonorB = DonorB[:, DonorB.var.highly_variable]\nDonorA_sample = DonorA_sample[:, DonorA_sample.var.highly_variable]\nDonorB_sample = DonorB_sample[:, DonorB_sample.var.highly_variable]\nDonors_merged = Donors_merged[:, Donors_merged.var.highly_variable]\nDonors_merged_control = Donors_merged_control[:, Donors_merged_control.var.highly_variable]\n\nsc.pp.regress_out(DonorA, ['total_counts', 'pct_counts_mt'])\nsc.pp.regress_out(DonorB, ['total_counts', 'pct_counts_mt'])\nsc.pp.regress_out(DonorA_sample, ['total_counts'])\nsc.pp.regress_out(DonorB_sample, ['total_counts'])\nsc.pp.regress_out(Donors_merged, ['total_counts'])\nsc.pp.regress_out(Donors_merged_control, ['total_counts'])\n##scale to unit variance\nsc.pp.scale(DonorA, max_value = 10)\nsc.pp.scale(DonorB, max_value = 10)\nsc.pp.scale(DonorA_sample, max_value = 10)\nsc.pp.scale(DonorB_sample, max_value = 10)\nsc.pp.scale(Donors_merged, max_value = 10)\nsc.pp.scale(Donors_merged_control, max_value = 10)\n\n\nsc.tl.pca(DonorA, svd_solver='arpack')\nsc.tl.pca(DonorB, svd_solver='arpack')\nsc.tl.pca(DonorA_sample, svd_solver='arpack')\nsc.tl.pca(DonorB_sample, svd_solver='arpack')\nsc.tl.pca(Donors_merged, svd_solver = 'arpack')\nsc.tl.pca(Donors_merged_control, svd_solver = 'arpack')\n#save\nDonorA.write(pp_donorA)\nDonorB.write(pp_donorB)\nDonorA_sample.write(pp_donorA_sample)\nDonorB_sample.write(pp_donorB_sample)\nDonors_merged.write(pp_donors_merged)\nDonors_merged_control.write(pp_donors_merged_control)\n\n#neighborhood graph\nneighbors = 5\nsc.pp.neighbors(DonorA, n_neighbors=neighbors, n_pcs=40)#increase # neighbors to account for larger dataset\nsc.pp.neighbors(DonorB, n_neighbors=neighbors, n_pcs=40)#increase # neighbors to account for larger dataset\nsc.pp.neighbors(Donors_merged, n_neighbors=neighbors, n_pcs=40)#increase # neighbors to account for larger dataset\nsc.pp.neighbors(Donors_merged_control, n_neighbors=neighbors, n_pcs=40)#increase # neighbors to account for larger dataset\n\n\nsc.tl.umap(DonorA)\nsc.tl.umap(DonorB)\nsc.tl.umap(Donors_merged)\nsc.tl.umap(Donors_merged_control)\nsc.pl.umap(DonorA, color = ['CST3'])\nsc.pl.umap(DonorB, color = ['CST3'])\nsc.pl.umap(Donors_merged_control, color = ['CST3'])\n\nsc.pl.pca(DonorA)\nsc.pl.pca(DonorB)\nsc.pl.pca(DonorA_sample)\nsc.pl.pca(DonorB_sample)\nsc.pl.pca(Donors_merged, color = 'batch')\nsc.pl.pca(Donors_merged_control, color = 'batch')\n#################Begin UnionCom######################credit to Kai et al#########\nd_x = DonorA.X.shape[1]\nn_x = DonorA.X.shape[0]\n\nd_y = DonorB.X.shape[1]\nn_y = DonorB.X.shape[0]\n\ndata = DonorA.X\nobs = list(range(0,len(DonorA.X)))\ndf = pd.DataFrame(data, columns = DonorA.var_names, index = obs)\nK_x = distance_matrix(df.values, df.values)\n\ndata = DonorB.X\nobs = list(range(0,len(DonorB.X)))\ndf = pd.DataFrame(data, columns = DonorB.var_names, index = obs)\nK_y = distance_matrix(df.values, df.values)\n\ndata_x = DonorA_sample.X\ndata_y = DonorB_sample.X\n\n\n######get geodesic distances#####\nkmin_x = 5 \nkmax = 50\nnbrs_x = NearestNeighbors(n_neighbors=kmin_x, metric='euclidean', n_jobs=-1).fit(data_x)\nknn_x = nbrs_x.kneighbors_graph(data_x, mode='distance')\n#check if graph is fully connected\nconnected = csgraph.connected_components(knn_x, directed=False)[0]\n\nwhile connected != 1:\n\tif kmin_x > np.max((kmax, 0.01*len(X))):\n\t\tbreak\n\tkmin_x += 2\n\tnbrs_x = NearestNeighbors(n_neighbors=kmin_x, metric='euclidean', n_jobs=-1).fit(data_y)\n\tknn_x = nbrs_x.kneighbors_graph(data_x, mode='distance')\n\tconnected = csgraph.connected_components(knn_x, directed=False)[0]\n\n#floyd-warshall\ndist_x = csgraph.floyd_warshall(knn_x, directed=False)\n#replace inf values\ndist_max = np.nanmax(dist_x[dist_x != np.inf])\ndist_x[dist_x > dist_max] = 2*dist_max\n\n\nkmin_y = 5 \nkmax = 50\nnbrs_y = NearestNeighbors(n_neighbors=kmin_y, metric='euclidean', n_jobs=-1).fit(data_y)\nknn_y = nbrs_y.kneighbors_graph(data_y, mode='distance')\n#check if graph is fully connected\nconnected = csgraph.connected_components(knn_y, directed=False)[0]\n\nwhile connected != 1:\n\tif kmin_y > np.max((kmax, 0.01*len(X))):\n\t\tbreak\n\tkmin_y += 2\n\tnbrs_y = NearestNeighbors(n_neighbors=kmin_y, metric='euclidean', n_jobs=-1).fit(data_y)\n\tknn_y = nbrs_y.kneighbors_graph(data_y, mode='distance')\n\tconnected = csgraph.connected_components(knn_y, directed=False)[0]\n\n#floyd-warshall\ndist_y = csgraph.floyd_warshall(knn_y, directed=False)\n#replace inf values\ndist_max = np.nanmax(dist_y[dist_y != np.inf])\ndist_y[dist_y > dist_max] = 2*dist_max\n\ndist = np.array([dist_x, dist_y])\nkmin = list([kmin_x, kmin_y])\n\n#########align cells across datasets by matching geometric distance matrices#######\n\ndef perplexity(distances, sigmas):\n\treturn calc_perplexity(calc_P(distances, sigmas))\n\ndef calc_perplexity(prob_matrix):\n\tentropy = -np.sum(prob_matrix * np.log2(prob_matrix), 1)\n\tperplexity = 2 ** entropy\n\treturn perplexity\n\ndef calc_P(distances, sigmas=None):\n\tif sigmas is not None:\n\t\ttwo_sig_sq = 2. * np.square(sigmas.reshape((-1, 1)))\n\t\treturn softmax(distances / two_sig_sq)\n\telse:\n\t\treturn softmax(distances)\n \ndef softmax(D, diag_zero=True):\n\t# e_x = np.exp(D)\n\te_x = np.exp(D - np.max(D, axis=1).reshape([-1, 1]))\n\tif diag_zero:\n\t\tnp.fill_diagonal(e_x, 0)\n\te_x = e_x + 1e-15\n\treturn e_x / e_x.sum(axis=1).reshape([-1,1]) \n \ndef binary_search(eval_fn, target ,tol=1e-10, max_iter=10000, lower=1e-20, upper=1000.):\n\tfor i in range(max_iter):\n\t\tguess = (lower + upper) /2.\n\t\tval = eval_fn(guess)\n\t\tif val > target:\n\t\t\tupper = guess\n\t\telse:\n\t\t\tlower = guess\n\t\tif np.abs(val - target) <= tol:\n\t\t\tbreak\n\treturn guess\n\ndef p_conditional_to_joint(P):\n\treturn (P + P.T) / (2. * P.shape[0])\n\ndef init_model(net, device, restore):\n\tif restore is not None and os.path.exits(restore):\n\t\tnet.load_state_dict(torch.load(restore))\n\t\tnet.restored = True\n\t\tprint(\"Restore model from: {}\".format(os.path.abspath(restore)))\n\telse:\n\t\tprint(\"No trained model, train UnionCom from scratch.\")\n\n\tif torch.cuda.is_available():\n\t\tcudnn.benchmark =True\n\t\tnet.to(device)\n\n\treturn net\n\np = []\n##negative square distances\nneg_dist_x = -dist[0]\nneg_dist_y = -dist[1]\n###find sigmas\nsigmas_x = []\nfor i in range(neg_dist_x.shape[0]):\n\teval_fn = lambda sigma: perplexity(neg_dist_x[i:i+1, :], np.array(sigma))\n\tcorrect_sigma = binary_search(eval_fn, kmin[0])\n\tsigmas_x.append(correct_sigma)\nsigmas_x = np.array(sigmas_x)\n\nsigmas_y = []\nfor i in range(neg_dist_y.shape[0]):\n\teval_fn = lambda sigma: perplexity(neg_dist_y[i:i+1, :], np.array(sigma))\n\tcorrect_sigma = binary_search(eval_fn, kmin[1])\n\tsigmas_y.append(correct_sigma) \nsigmas_y = np.array(sigmas_y)\n\np_cond_x = calc_P(neg_dist_x, sigmas_x)\np_cond_y = calc_P(neg_dist_y, sigmas_y)\n\np_x = p_conditional_to_joint(p_cond_x)\np_y = p_conditional_to_joint(p_cond_y)\n\np = [p_x, p_y]\n\n#############Project unmatched features into common space#################\ninput_dims = [data_x.shape[1], data_y.shape[1]]\noutput_dim = 32\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nnet = Project(input_dims, output_dim)\nproject_net = init_model(net, device, restore=None)\n\n\nresult = UnionCom.train(project_net, params, [data_x,data_y], dist, p, device)\n\nfinal = UnionCom.fit_transform([data_x,data_y], datatype=None, epoch_pd=1000, epoch_DNN=100, epsilon=0.001, \nlr=0.001, batch_size=100, rho=10, log_DNN=10, manual_seed=666, delay=0, \nbeta=1, kmax=20, distance = 'geodesic', project='tsne', output_dim=32, test=False)\n\nUnionCom.visualize([data_x, data_y], final)\n\n################################MMD-RESNET#######################credit Uri Shaham\n\nimport os.path\nimport keras.optimizers\nfrom Calibration_Util import DataHandler as dh \nfrom Calibration_Util import FileIO as io\nfrom keras.layers import Input, Dense, merge, Activation, add\nfrom keras.models import Model\nfrom keras import callbacks as cb\nimport numpy as np\nimport matplotlib\nfrom keras.layers.normalization import BatchNormalization\n#detect display\nimport os\nhavedisplay = \"DISPLAY\" in os.environ\n#if we have a display use a plotting backend\nif havedisplay:\n matplotlib.use('TkAgg')\nelse:\n matplotlib.use('Agg')\n\nimport CostFunctions as cf\nimport Monitoring as mn\nfrom keras.regularizers import l2\nfrom sklearn import decomposition\nfrom keras.callbacks import LearningRateScheduler\nimport math\nimport ScatterHist as sh\nfrom keras import initializers\nfrom numpy import genfromtxt\nimport sklearn.preprocessing as prep\nimport tensorflow as tf\nimport keras.backend as K\n\n\n# configuration hyper parameters\ndenoise = False # whether or not to train a denoising autoencoder to remove the zeros\nkeepProb=.8\n\n# AE confiduration\nae_encodingDim = 25\nl2_penalty_ae = 1e-2 \n\n#MMD net configuration\nmmdNetLayerSizes = [25, 25]\nl2_penalty = 1e-2\n#init = lambda shape, name:initializations.normal(shape, scale=.1e-4, name=name)\n#def my_init (shape):\n# return initializers.normal(stddev=.1e-4)\n#my_init = 'glorot_normal'\n\n#######################\n###### read data ######\n#######################\n# we load two CyTOF samples \n\n \nsource = data_x\ntarget = data_y\n\n# pre-process data: log transformation, a standard practice with CyTOF data\ntarget = dh.preProcessCytofData(target)\nsource = dh.preProcessCytofData(source) \n\nnumZerosOK=1\ntoKeepS = np.sum((source==0), axis = 1) <=numZerosOK\nprint(np.sum(toKeepS))\ntoKeepT = np.sum((target==0), axis = 1) <=numZerosOK\nprint(np.sum(toKeepT))\n\ninputDim = target.shape[1]\n\nif denoise:\n trainTarget_ae = np.concatenate([source[toKeepS], target[toKeepT]], axis=0)\n np.random.shuffle(trainTarget_ae)\n trainData_ae = trainTarget_ae * np.random.binomial(n=1, p=keepProb, size = trainTarget_ae.shape)\n input_cell = Input(shape=(inputDim,))\n encoded = Dense(ae_encodingDim, activation='relu',W_regularizer=l2(l2_penalty_ae))(input_cell)\n encoded1 = Dense(ae_encodingDim, activation='relu',W_regularizer=l2(l2_penalty_ae))(encoded)\n decoded = Dense(inputDim, activation='linear',W_regularizer=l2(l2_penalty_ae))(encoded1)\n autoencoder = Model(input=input_cell, output=decoded)\n autoencoder.compile(optimizer='rmsprop', loss='mse')\n autoencoder.fit(trainData_ae, trainTarget_ae, epochs=500, batch_size=128, shuffle=True, validation_split=0.1,\n callbacks=[mn.monitor(), cb.EarlyStopping(monitor='val_loss', patience=25, mode='auto')]) \n source = autoencoder.predict(source)\n target = autoencoder.predict(target)\n\n# rescale source to have zero mean and unit variance\n# apply same transformation to the target\npreprocessor = prep.StandardScaler().fit(source)\nsource = preprocessor.transform(source) \ntarget = preprocessor.transform(target) \n\n#############################\n######## train MMD net ######\n#############################\n\n\ncalibInput = Input(shape=(inputDim,))\nblock1_bn1 = BatchNormalization()(calibInput)\nblock1_a1 = Activation('relu')(block1_bn1)\nblock1_w1 = Dense(mmdNetLayerSizes[0], activation='linear',kernel_regularizer=l2(l2_penalty), \n kernel_initializer=initializers.RandomNormal(stddev=1e-4))(block1_a1) \nblock1_bn2 = BatchNormalization()(block1_w1)\nblock1_a2 = Activation('relu')(block1_bn2)\nblock1_w2 = Dense(inputDim, activation='linear',kernel_regularizer=l2(l2_penalty),\n kernel_initializer=initializers.RandomNormal(stddev=1e-4))(block1_a2) \nblock1_output = add([block1_w2, calibInput])\nblock2_bn1 = BatchNormalization()(block1_output)\nblock2_a1 = Activation('relu')(block2_bn1)\nblock2_w1 = Dense(mmdNetLayerSizes[1], activation='linear',kernel_regularizer=l2(l2_penalty), \n kernel_initializer=initializers.RandomNormal(stddev=1e-4))(block2_a1) \nblock2_bn2 = BatchNormalization()(block2_w1)\nblock2_a2 = Activation('relu')(block2_bn2)\nblock2_w2 = Dense(inputDim, activation='linear',kernel_regularizer=l2(l2_penalty), \n kernel_initializer=initializers.RandomNormal(stddev=1e-4))(block2_a2) \nblock2_output = add([block2_w2, block1_output])\nblock3_bn1 = BatchNormalization()(block2_output)\nblock3_a1 = Activation('relu')(block3_bn1)\nblock3_w1 = Dense(mmdNetLayerSizes[1], activation='linear',kernel_regularizer=l2(l2_penalty), \n kernel_initializer=initializers.RandomNormal(stddev=1e-4))(block3_a1) \nblock3_bn2 = BatchNormalization()(block3_w1)\nblock3_a2 = Activation('relu')(block3_bn2)\nblock3_w2 = Dense(inputDim, activation='linear',kernel_regularizer=l2(l2_penalty), \n kernel_initializer=initializers.RandomNormal(stddev=1e-4))(block3_a2) \nblock3_output = add([block3_w2, block2_output])\n\ncalibMMDNet = Model(inputs=calibInput, outputs=block3_output)\n\n# learning rate schedule\ndef step_decay(epoch):\n initial_lrate = 0.001\n drop = 0.1\n epochs_drop = 150.0\n lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop))\n return lrate\nlrate = LearningRateScheduler(step_decay)\n\n#train MMD net\noptimizer = keras.optimizers.rmsprop(lr=0.0)\n\ncalibMMDNet.compile(optimizer=optimizer, loss=lambda y_true,y_pred: \n cf.MMD(block3_output,target,MMDTargetValidation_split=0.1).KerasCost(y_true,y_pred))\nK.get_session().run(tf.global_variables_initializer())\n\nsourceLabels = np.zeros(source.shape[0])\ncalibMMDNet.fit(source,sourceLabels,nb_epoch=500,batch_size=1000,validation_split=0.1,verbose=1,\n callbacks=[lrate, mn.monitorMMD(source, target, calibMMDNet.predict),\n cb.EarlyStopping(monitor='val_loss',patience=50,mode='auto')])\n\n##############################\n###### evaluate results ######\n##############################\n\ncalibratedSource = calibMMDNet.predict(source)\n\n##################################### qualitative evaluation: PCA #####################################\npca = decomposition.PCA()\npca.fit(target)\n\n# project data onto PCs\ntarget_sample_pca = pca.transform(target)\nprojection_before = pca.transform(source)\nprojection_after = pca.transform(calibratedSource)\n\n# choose PCs to plot\npc1 = 0\npc2 = 1\naxis1 = 'PC'+str(pc1)\naxis2 = 'PC'+str(pc2)\nsh.scatterHist(target_sample_pca[:,pc1], target_sample_pca[:,pc2], projection_before[:,pc1], projection_before[:,pc2], axis1, axis2)\nsh.scatterHist(target_sample_pca[:,pc1], target_sample_pca[:,pc2], projection_after[:,pc1], projection_after[:,pc2], axis1, axis2)\n \n# save models\nautoencoder.save(os.path.join(io.DeepLearningRoot(),'savedModels/person1_baseline_DAE.h5')) \ncalibMMDNet.save_weights(os.path.join(io.DeepLearningRoot(),'savedModels/person1_baseline_ResNet_weights.h5')) \n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 6 00:17:31 2020\n@author: urixs\n\"\"\"\n\nimport numpy as np\nfrom sklearn import decomposition\nimport argparse\nfrom itertools import count\nimport os\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import lr_scheduler\n\n\n\nfrom matplotlib.ticker import NullFormatter\nfrom torch.autograd import Variable\n\ndef compute_dist_mat(X, Y=None, device=torch.device(\"cpu\")):\n \"\"\"\n Computes nxm matrix of squared distances\n args:\n X: nxd tensor of data points\n Y: mxd tensor of data points (optional)\n \"\"\"\n if Y is None:\n Y = X\n \n X = X.to(device=device) \n Y = Y.to(device=device) \n dtype = X.data.type()\n dist_mat = Variable(torch.Tensor(X.size()[0], Y.size()[0]).type(dtype)).to(device=device) \n\n for i, row in enumerate(X.split(1)):\n r_v = row.expand_as(Y)\n sq_dist = torch.sum((r_v - Y) ** 2, 1)\n dist_mat[i] = sq_dist.view(1, -1)\n return dist_mat\n\ndef nn_search(X, Y=None, k=10):\n \"\"\"\n Computes nearest neighbors in Y for points in X\n args:\n X: nxd tensor of query points\n Y: mxd tensor of data points (optional)\n k: number of neighbors\n \"\"\"\n if Y is None:\n Y = X\n X = X.cpu().detach().numpy()\n Y = Y.cpu().detach().numpy()\n nbrs = NearestNeighbors(n_neighbors=k, algorithm='ball_tree').fit(Y)\n Dis, Ids = nbrs.kneighbors(X)\n return Dis, Ids\n \ndef compute_scale(Dis, k=5):\n \"\"\"\n Computes scale as the max distance to the k neighbor\n args:\n Dis: nxk' numpy array of distances (output of nn_search)\n k: number of neighbors\n \"\"\"\n scale = np.median(Dis[:, k - 1])\n return scale\n\ndef compute_kernel_mat(D, scale, device=torch.device('cpu')):\n \"\"\"\n Computes RBF kernal matrix\n args:\n D: nxn tenosr of squared distances\n scale: standard dev \n \"\"\"\n W = torch.exp(-D / (scale ** 2))\n\n return W \n \ndef scatterHist(x1,x2, y1,y2, axis1='', axis2='', title='', name1='', name2='',\n plots_dir=''):\n nullfmt = NullFormatter() # no labels\n \n # definitions for the axes\n left, width = 0.1, 0.65\n bottom, height = 0.1, 0.65\n bottom_h = left_h = left + width + 0.02\n \n rect_scatter = [left, bottom, width, height]\n rect_histx = [left, bottom_h, width, 0.2]\n rect_histy = [left_h, bottom, 0.2, height]\n \n # start with a rectangular Figure\n fig = plt.figure(figsize=(8, 8))\n \n axScatter = plt.axes(rect_scatter)\n axHistx = plt.axes(rect_histx)\n axHisty = plt.axes(rect_histy)\n \n # no labels\n axHistx.xaxis.set_major_formatter(nullfmt)\n axHisty.yaxis.set_major_formatter(nullfmt)\n \n # the scatter plot:\n axScatter.scatter(x1, x2, color = 'blue', s=3)\n axScatter.scatter(y1, y2, color = 'red', s=3) \n\n\n # now determine nice limits by hand:\n binwidth = 0.5\n xymax = np.max([np.max(np.fabs(x1)), np.max(np.fabs(x2))])\n lim = (int(xymax/binwidth) + 1) * binwidth\n \n axScatter.set_xlim((-lim, lim))\n axScatter.set_ylim((-lim, lim))\n \n bins = np.arange(-lim, lim + binwidth, binwidth)\n axHistx.hist(x1, bins=bins, color = 'blue', density=True, stacked = True, histtype='step' )\n axHisty.hist(x2, bins=bins, orientation='horizontal', color = 'blue', density=True, stacked = True, histtype='step')\n axHistx.hist(y1, bins=bins, color = 'red', density=True, stacked = True, histtype='step')\n axHisty.hist(y2, bins=bins, orientation='horizontal', color = 'red', density=True, stacked = True, histtype='step')\n \n axHistx.set_xlim(axScatter.get_xlim())\n axHisty.set_ylim(axScatter.get_ylim())\n \n axHistx.set_xticklabels([])\n axHistx.set_yticklabels([])\n axHisty.set_xticklabels([])\n axHisty.set_yticklabels([])\n axScatter.set_xlabel(axis1, fontsize=18)\n axScatter.set_ylabel(axis2, fontsize=18)\n \n axHistx.set_title(title, fontsize=18)\n axScatter.legend([name1, name2], fontsize=18)\n plt.show(block=False)\n if not plots_dir=='':\n fig.savefig(plots_dir+'/'+title+'.eps' ,format='eps')\n# ==============================================================================\n# = Input arguments =\n# ==============================================================================\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--n_blocks', \n type=int, \n default=2, \n help='Number of resNet blocks')\nparser.add_argument('--file1', \n type=str, \n default=\"./data/sample1.csv\",\n help='path to file 1')\nparser.add_argument('--file2', \n type=str, \n default=\"./data/sample2.csv\",\n help='path to file 2')\nparser.add_argument(\"--scale_k\",\n type=int,\n default=5,\n help=\"Number of neighbors for determining the RBF scale\")\nparser.add_argument('--batch_size', \n type=int, \n default=256,\n help='Batch size (default=128)')\nparser.add_argument('--lr', \n type=float, \n default=1e-5,\n help='learning_rate (default=1e-3)')\nparser.add_argument(\"--min_lr\",\n type=float,\n default=1e-6,\n help=\"Minimal learning rate\")\nparser.add_argument(\"--decay_step_size\",\n type=int,\n default=10,\n help=\"LR decay step size\")\nparser.add_argument(\"--lr_decay_factor\",\n type=float,\n default=0.1,\n help=\"LR decay factor\")\nparser.add_argument(\"--weight_decay\",\n type=float,\n default=1e-4,\n help=\"l_2 weight penalty\")\nparser.add_argument(\"--epochs_wo_im\",\n type=int,\n default=5,\n help=\"Number of epochs without improvement before stopping\")\nparser.add_argument(\"--save_dir\",\n type=str,\n default='./calibrated_data',\n help=\"Directory for calibrated data\")\n\nargs = parser.parse_args()\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n# ==============================================================================\n# = Dataset =\n# ==============================================================================\n\nsample1 = DonorA_sample.X[:,0:1300]\nsample2 = DonorB_sample.X[:,0:1300]\n\nsample1_tensor = torch.Tensor(sample1)\nsample1_dataset = torch.utils.data.TensorDataset(sample1_tensor)\n\nsample2_tensor = torch.Tensor(sample2)\nsample2_dataset = torch.utils.data.TensorDataset(sample2_tensor)\n\nsample1_loader = torch.utils.data.DataLoader(sample1_dataset,\n batch_size=128,\n shuffle=True)\n\nsample2_loader = torch.utils.data.DataLoader(sample2_dataset,\n batch_size=128,\n shuffle=True)\n\ninput_dim1 = sample1.shape[1]\ninput_dim2 = sample2.shape[1]\nassert input_dim1 == input_dim2, \"samples are of different dimensions\"\ninput_dim = input_dim1\n\n# ==============================================================================\n# = Model =\n# ==============================================================================\n\nclass ResnetBlock(nn.Module):\n \"\"\"Define a Resnet block\"\"\"\n \n def __init__(self, \n dim,\n use_dropout=False):\n \"\"\"Initialize the Resnet block\"\"\"\n \n super(ResnetBlock, self).__init__()\n self.block = self.build_resnet_block(dim,\n use_dropout)\n\n def build_resnet_block(self,\n dim,\n use_dropout=False):\n \n block = [torch.nn.Linear(dim, dim),\n torch.nn.BatchNorm1d(dim),\n torch.nn.PReLU()]\n if use_dropout:\n block += [nn.Dropout(0.5)]\n \n block += [torch.nn.Linear(dim, dim),\n torch.nn.BatchNorm1d(dim),\n torch.nn.PReLU()]\n if use_dropout:\n block += [nn.Dropout(0.5)]\n \n return nn.Sequential(*block)\n \n def forward(self, x):\n \"\"\"Forward function (with skip connections)\"\"\"\n out = x + self.block(x) # add skip connections\n return out\n \n\nclass Mmd_resnet(nn.Module): \n def __init__(self, \n input_dim,\n n_blocks,\n use_dropout=False):\n super(Mmd_resnet, self).__init__()\n \n model = []\n for i in range(n_blocks): # add resnet blocks layers\n model += [ResnetBlock(input_dim,\n use_dropout)]\n \n self.model = nn.Sequential(*model)\n \n def forward(self, input):\n \"\"\"Forward function (with skip connections)\"\"\"\n out = input + self.model(input) # add skip connection\n return out\n\n \nmmd_resnet = Mmd_resnet(input_dim,\n args.n_blocks) \n \n# ==============================================================================\n# = Optimizer and Learning rate =\n# ============================================================================== \n\noptim = torch.optim.SGD(mmd_resnet.parameters(), \n lr=args.lr, \n weight_decay=args.weight_decay) \n\ndef lambda_rule(epoch) -> float:\n \"\"\" stepwise learning rate calculator \"\"\"\n exponent = int(np.floor((epoch + 1) / args.decay_step_size))\n return np.power(args.lr_decay_factor, exponent)\n\nscheduler = lr_scheduler.LambdaLR(optim, \n lr_lambda=lambda_rule) \n\ndef update_lr():\n \"\"\" Learning rate updater \"\"\"\n \n scheduler.step()\n lr = optim.param_groups[0]['lr']\n if lr < args.min_lr:\n optim.param_groups[0]['lr'] = args.min_lr\n lr = optim.param_groups[0]['lr']\n print('Learning rate = %.7f' % lr) \n\n# ==============================================================================\n# = Training procedure =\n# ============================================================================== \n\ndef training_step(batch1, batch2):\n \n mmd_resnet.train(True)\n \n calibrated_batch2 = mmd_resnet(batch2)\n \n # Compute distance matrices\n D1 = compute_dist_mat(batch1, device=device)\n D2 = compute_dist_mat(calibrated_batch2, device=device)\n D12 = compute_dist_mat(batch1, calibrated_batch2)\n \n # Compute scale\n Dis, _ =nn_search(batch1, k=args.scale_k)\n scale = compute_scale(Dis, k=args.scale_k)\n \n # Compute kernel matrices\n K1 = compute_kernel_mat(D1, scale) \n K2 = compute_kernel_mat(D2, scale) \n K12 = compute_kernel_mat(D12, scale)\n \n # Loss function and backprop\n mmd = torch.mean(K1) - 2 * torch.mean(K12) + torch.mean(K2) \n loss = torch.sqrt(mmd) \n\n optim.zero_grad()\n loss.backward()\n optim.step()\n return loss.item()\n \n# ==============================================================================\n# = Main =\n# ============================================================================== \n \ndef main():\n \n best_loss = 100\n eps = 1e-4\n epoch_counter = 0\n for epoch in count(1):\n batch_losses = []\n \n samp2_batches = enumerate(sample2_loader)\n for batch_idx, batch1 in enumerate(sample1_loader):\n try:\n _, batch2 = next(samp2_batches)\n except:\n samp2_batches = enumerate(sample2_loader)\n _, batch2 = next(samp2_batches)\n \n batch1 = batch1[0].to(device=device)\n batch2 = batch2[0].to(device=device)\n \n batch_loss = training_step(batch1, batch2)\n batch_losses.append(batch_loss)\n \n epoch_loss = np.mean(batch_losses)\n \n if epoch_loss < best_loss - eps:\n best_loss = epoch_loss\n epoch_counter = 0\n else:\n epoch_counter += 1\n \n print('Epoch {}, loss: {:.3f}, counter: {}'.format(epoch, \n epoch_loss,\n epoch_counter)\n )\n \n update_lr()\n \n if epoch_counter == args.epochs_wo_im:\n break\n print('Finished training')\n \n # calibrate sample2 -> batch 1 \n \n mmd_resnet.train(False)\n \n calibrated_sample2 = []\n for batch_idx, batch2 in enumerate(sample2_loader):\n batch2 = batch2[0].to(device=device)\n calibrated_batch = mmd_resnet(batch2)\n calibrated_sample2 += [calibrated_batch.detach().cpu().numpy()]\n \n calibrated_sample2 = np.concatenate(calibrated_sample2)\n \n # ==============================================================================\n # = visualize calibration =\n # ==============================================================================\n \n # PCA\n pca = decomposition.PCA()\n pca.fit(sample1)\n pc1 = 0\n pc2 = 1\n axis1 = 'PC'+str(pc1)\n axis2 = 'PC'+str(pc2)\n \n # plot data before calibration\n sample1_pca = pca.transform(sample1)\n sample2_pca = pca.transform(sample2)\n scatterHist(sample1_pca[:,pc1], \n sample1_pca[:,pc2], \n sample2_pca[:,pc1], \n sample2_pca[:,pc2], \n axis1, \n axis2, \n title=\"Data before calibration\",\n name1='sample1', \n name2='sample2')\n \n # plot data after calibration\n calibrated_sample2_pca = pca.transform(calibrated_sample2)\n scatterHist(sample1_pca[:,pc1], \n sample1_pca[:,pc2], \n calibrated_sample2_pca[:,pc1], \n calibrated_sample2_pca[:,pc2], \n axis1, \n axis2, \n title=\"Data after calibration\",\n name1='sample1', \n name2='sample2')\n \n if not os.path.exists(args.save_dir):\n os.makedirs(args.save_dir)\n np.save(args.save_dir + '/sample1.csv', sample1)\n np.save(args.save_dir + '/calibrated_sample2.csv', calibrated_sample2)\n \n \nif __name__ == '__main__':\n main()","sub_path":"week5/week4.py","file_name":"week4.py","file_ext":"py","file_size_in_byte":38273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"137376236","text":"import os\nimport logging.config\n\nredis_conf = {\n\t'host' : 'localhost',\n\t'port' : 6379,\n}\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nLOGGING = {\n\t'version': 1,\n\t'disable_existing_loggers': True,\n\t'formatters': {\n\t\t'verbose': {\n\t\t\t'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n\t\t},\n\t\t'simple': {\n\t\t\t'format': '%(asctime)s %(message)s'\n\t\t},\n\t},\n\t'handlers': {\n\t\t'console':{\n\t\t\t'level':'DEBUG',\n\t\t\t'class':'logging.StreamHandler',\n\t\t\t'formatter': 'simple'\n\t\t},\n\t\t'file': {\n\t\t\t'level': 'DEBUG',\n\t\t\t'class': 'logging.FileHandler',\n\t\t\t'filename': BASE_DIR + '/records.log',\n\t\t\t'formatter': 'simple',\n\t\t},\n\t},\n\t'loggers': {\n\t\t'pattern.server': {\n\t\t\t'handlers': ['console', 'file'],\n\t\t\t'level': 'DEBUG',\n\t\t},\n\t}\n}\n\nlogging.config.dictConfig(LOGGING)","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"193764183","text":"# SCAR - Serverless Container-aware ARchitectures\n# Copyright (C) 2011 - GRyCAP - Universitat Politecnica de Valencia\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom .boto import BotoClient\nimport src.logger as logger\nfrom botocore.exceptions import ClientError\nimport src.utils as utils\nimport src.providers.aws.response as response_parser\nimport time\n\nAPI_DESCRIPTION=\"API created automatically with SCAR\"\nMAX_NUMBER_OF_RETRIES = 5\nWAIT_BETWEEN_RETIRES = 5\n\nclass APIGateway():\n \n @utils.lazy_property\n def client(self):\n client = APIGatewayClient()\n return client\n\n def __init__(self, aws_lambda):\n # Get all the log related attributes\n self.function_name = aws_lambda.get_property(\"name\")\n self.api_gateway_name = aws_lambda.get_property(\"api_gateway_name\")\n self.lambda_role = aws_lambda.get_property(\"iam\",\"role\")\n # ANY, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT\n self.default_http_method = \"ANY\"\n # NONE, AWS_IAM, CUSTOM, COGNITO_USER_POOLS\n self.default_authorization_type = \"NONE\"\n # 'HTTP'|'AWS'|'MOCK'|'HTTP_PROXY'|'AWS_PROXY'\n self.default_type = \"AWS_PROXY\"\n\n def get_api_lambda_uri(self):\n self.aws_acc_id = utils.find_expression('\\d{12}', self.lambda_role)\n api_gateway_uri = 'arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/'\n lambda_uri = 'arn:aws:lambda:us-east-1:{0}:function:{1}/invocations'.format(self.aws_acc_id, self.function_name)\n return api_gateway_uri + lambda_uri\n\n def create_api_gateway(self):\n api_info = self.client.create_rest_api(self.api_gateway_name)\n self.set_api_resources(api_info)\n resource_info = self.client.create_resource(self.api_id, self.root_resource_id, \"{proxy+}\")\n self.client.create_method(self.api_id,\n resource_info['id'],\n self.default_http_method,\n self.default_authorization_type)\n self.client.set_integration(self.api_id,\n resource_info['id'],\n self.default_http_method,\n self.default_type,\n self.get_api_lambda_uri())\n self.client.create_deployment(self.api_id, 'scar')\n self.endpoint = 'https://{0}.execute-api.{1}.amazonaws.com/scar/launch'.format(self.api_id, 'us-east-1')\n logger.info('API Gateway endpoint: {0}'.format(self.endpoint))\n return self.api_id, self.aws_acc_id\n \n def delete_api_gateway(self, api_id, output_type):\n response = self.client.delete_rest_api(api_id)\n response_parser.parse_delete_api_response(response, api_id, output_type)\n \n def set_api_resources(self, api_info):\n self.api_id = api_info['id']\n resources_info = self.client.get_resources(api_info['id'])\n for resource in resources_info['items']:\n if resource['path'] == '/':\n self.root_resource_id = resource['id']\n \nclass APIGatewayClient(BotoClient):\n '''A low-level client representing Amazon API Gateway.\n https://boto3.readthedocs.io/en/latest/reference/services/apigateway.html'''\n \n def __init__(self, region=None):\n super().__init__('apigateway', region)\n \n def create_rest_api(self, api_name, count=MAX_NUMBER_OF_RETRIES):\n ''' Default type REGIONAL, other possible type EDGE. \n More info in https://boto3.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.create_rest_api\n '''\n try: \n return self.get_client().create_rest_api(name=api_name,\n description=API_DESCRIPTION,\n endpointConfiguration={'types': ['REGIONAL']})\n except ClientError as ce:\n if (ce.response['Error']['Code'] == 'TooManyRequestsException'):\n time.sleep(WAIT_BETWEEN_RETIRES)\n return self.create_rest_api(api_name, count-1)\n error_msg = \"Error creating the '{0}' REST API\".format(api_name)\n logger.error(error_msg, error_msg + \": {0}\".format(ce))\n \n def get_resources(self, api_id):\n ''' Default type REGIONAL, other possible type EDGE. \n More info in https://boto3.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.get_resources\n '''\n try: \n return self.get_client().get_resources(restApiId=api_id)\n except ClientError as ce:\n error_msg = \"Error getting resources for the API ID '{0}'\".format(api_id)\n logger.error(error_msg, error_msg + \": {0}\".format(ce)) \n \n def create_resource(self, api_id, parent_id, path_part):\n ''' Default type REGIONAL, other possible type EDGE. \n More info in https://boto3.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.create_rest_api\n '''\n try: \n return self.get_client().create_resource(restApiId=api_id,\n parentId=parent_id,\n pathPart=path_part)\n except ClientError as ce:\n error_msg = \"Error creating the resource '{0}' in the API '{1}'\".format(path_part, api_id)\n logger.error(error_msg, error_msg + \": {0}\".format(ce))\n \n def create_method(self, api_id, resource_id, http_method, authorization_type):\n ''' Add a method to an existing Resource resource.\n More info in https://boto3.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.put_method\n '''\n try: \n return self.get_client().put_method(restApiId=api_id,\n resourceId=resource_id,\n httpMethod=http_method,\n authorizationType=authorization_type,\n requestParameters={'method.request.header.X-Amz-Invocation-Type' : False} )\n except ClientError as ce:\n error_msg = \"Error creating the method '{0}' in the API '{1}'\".format(http_method, api_id)\n logger.error(error_msg, error_msg + \": {0}\".format(ce))\n \n def set_integration(self, api_id, resource_id, http_method, aws_type, api_uri):\n ''' Sets up a method's integration.\n More info in https://boto3.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.put_integration\n Also https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html\n '''\n req_param = { 'integration.request.header.X-Amz-Invocation-Type': 'method.request.header.X-Amz-Invocation-Type' }\n try:\n return self.get_client().put_integration(restApiId=api_id,\n resourceId=resource_id,\n httpMethod=http_method,\n type=aws_type,\n integrationHttpMethod='POST',\n uri=api_uri,\n requestParameters=req_param)\n except ClientError as ce:\n error_msg = \"Error integrating the Lambda function with the API Gateway\"\n logger.error(error_msg, error_msg + \": {0}\".format(ce))\n \n def create_deployment(self, api_id, stage_name):\n ''' Creates a Deployment resource, which makes a specified RestApi callable over the internet.\n More info in https://boto3.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.create_deployment\n '''\n try:\n return self.get_client().create_deployment(restApiId=api_id, stageName=stage_name)\n except ClientError as ce:\n error_msg = \"Error creating the deployment of the API '{0}'\".format(api_id)\n logger.error(error_msg, error_msg + \": {0}\".format(ce))\n \n def delete_rest_api(self, api_id, count=MAX_NUMBER_OF_RETRIES):\n ''' Deletes the specified API.\n More info in https://boto3.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.delete_rest_api\n '''\n try:\n return self.get_client().delete_rest_api(restApiId=api_id)\n except ClientError as ce:\n if (ce.response['Error']['Code'] == 'TooManyRequestsException'):\n time.sleep(WAIT_BETWEEN_RETIRES)\n return self.delete_rest_api(api_id, count-1)\n error_msg = \"Error deleting the API '{0}'\".format(api_id)\n logger.error(error_msg, error_msg + \": {0}\".format(ce)) \n","sub_path":"src/providers/aws/client/apigateway.py","file_name":"apigateway.py","file_ext":"py","file_size_in_byte":9653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608556714","text":"#!/usr/bin/env python\n# coding: utf-8\n# ### 2. Video Features\n# \n# + `extract_vgg16_relu6.py` \n# + used to extract video features \n# + Given an image (size: 256x340), we get 5 crops (size: 224x224) at the image center and four corners. The `vgg16-relu6` features are extracted for all 5 crops and subsequently averaged to form a single feature vector (size: 4096). \n# + Given a video, we process its 25 images seuqentially. In the end, each video is represented as a feature sequence (size: 4096 x 25). \n# + written in PyTorch; supports both CPU and GPU. \n# \n# + `vgg16_relu6/` \n# + contains all the video features, EXCEPT those belonging to class 1 (`ApplyEyeMakeup`) \n# + you need to run script `extract_vgg16_relu6.py` to complete the feature extracting process \n# \n# In[4]:\n\n\n# write your codes here\nimport torch\nimport torch.nn as nn\nimport torch.utils.data as data_utils\n\nfrom torch.utils.data import DataLoader\nimport torchvision.transforms as transforms\nimport glob\nimport scipy.io\nfrom PIL import Image\nimport torchvision.models as models\nfrom torch.optim import lr_scheduler\nimport os\nimport numpy as np\nimport h5py\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.utils.data as DD\nimport torchnet as tnt\n\nimport time\n\n\n# In[2]:\n\n\nnormalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\nprep = transforms.Compose([ transforms.ToTensor(), normalize ])\n#prep(img)\n\n\n# In[3]:\n\n\nclass1_path = '../data/train/imgs/*'#'./UCF101_release/images_class1/*'\nclass1_path_new = '../data/train/imgs/' #'./UCF101_release/images_class1/'\n\nvgg_gen_mat_path = '../data/train/mat/'\nframe_names = [name[-8:] for name in glob.glob(class1_path )]\nimage_class1_paths = [name for name in glob.glob(class1_path)]\nprint(len(frame_names))\n#print(frame_names)\n#print(image_class1_paths)\n\n\n# In[5]:\n\n\nmodel_vgg16 = models.vgg16(pretrained=True) \nprint(\"------------\")\nfor param in model_vgg16.parameters():\n param.requires_grad = False\n\n## outputs contain the 1st ReLU output of the classifier layer in the VGG 16 network as given in question\n## we will outputs as vgg features to process the next steps in this problem\noutputs= list()\ndef hook(module, input, output):\n outputs.append(output)\n\nprint(model_vgg16.classifier[1])\nmodel_vgg16.classifier[1].register_forward_hook(hook) #relu\n\nprint(\"------------\")\nprint(model_vgg16.features)\nprint(model_vgg16.classifier)\n\n\n# In[6]:\n\n\ndef get_vgg_feature(img):\n #features = vgg16_FC1(img)\n features = model_vgg16(img)\n return features\n \n\ndef load_crop_extract_save(image_filename):\n newImgTnsrs = dict()\n newImgTnsrs['Feature'] = list()\n #for image_filename in glob.glob(aImgClass1Path + '/*'):\n \n print(\"Processing image .... \",image_filename)\n # for each image crop 5 areas\n img = Image.open(image_filename)\n \n height = img.size[1]\n width = img.size[0]\n \n # tuple defining the left, upper, right, and lower pixel coordinates\n # training image is 640(w) X 480(h) ; test image is 640(w) X 840(h) =>\n # Train:: ignore 32 px from top - dont need skies as features.\n top_left = img.crop((0, 32, 224, 256))\n top_right = img.crop((width - 224, 32, width, 256))\n bottom_left = img.crop((0, height - 224, 224 , height))\n bottom_right = img.crop(( width - 224, height - 224, width, height))\n center = img.crop(( (width/2) - 112, (height/2) - 112, (width/2) + 112, (height/2) + 112 ))\n \n #normalize and transform cropped images before passing to vgg \n stcked_tnsr = torch.stack((prep(top_left), prep(top_right),prep(bottom_left) ,prep(bottom_right),prep(center)) , 0 )\n #print('stcked_tnsr ',stcked_tnsr.shape)\n stcked_vgg = get_vgg_feature(stcked_tnsr)\n print(stcked_vgg.shape)\n #print('output ',len(outputs))\n \n ## find mean\n new_img_mean = torch.mean(outputs[0], 0)\n #print('new_img_mean ',new_img_mean.shape)\n newImgTnsrs['Feature'].append(new_img_mean.numpy())\n #outputs.clear() ## so that next image \n del outputs[:] #py 2.7 syntx\n \n #break ## comment out\n \n print('aImgTnsr >> ',len(newImgTnsrs['Feature']))\n last_dot_index = image_filename.rfind('.')\n last_slash_index = image_filename.rfind('/')\n mat_file_name = image_filename[last_slash_index + 1: last_dot_index] \n scipy.io.savemat(vgg_gen_mat_path +mat_file_name, newImgTnsrs)\n \n \n \n \n \n\n\n# In[2]:\n\n\n################################### UNCOMMENT THE CODE BELOW TO RUN EXTRACT VGG FEATURES (MAT FILES) ################## \n## get image features for class 1 - extract features - UNCOMMENT if you want to extract features again for class1\n##\n\n##('extracting .. ', '../data/train/imgs/2586.jpg')\n## ('Processing image .... ', '../data/train/imgs/2586.jpg')\n##\nstart_time = time.time()\n\n\nfor aClass1Img in image_class1_paths: #glob.glob(image_class1_paths + '/*'):\n print(\"extracting .. \",aClass1Img)\n\n ## check if mat file already exists, else generate it.\n last_dot_index = aClass1Img.rfind('.')\n last_slash_index = aClass1Img.rfind('/')\n mat_file_name = aClass1Img[last_slash_index + 1: last_dot_index] \n\n total_mat_path = vgg_gen_mat_path + mat_file_name+'.mat'\n print(total_mat_path)\n\n if total_mat_path not in glob.glob(vgg_gen_mat_path + '/*'):\n load_crop_extract_save(aClass1Img)\n else:\n print('mat file for %s already exists !!'%aClass1Img)\n \n #break # comment out for all \nend_time = time.time() - start_time\nprint('------------------------------------------------------------')\nprint(\"time taken to extract features for Class 1 in seconds {:.3f}\".format(end_time))\n\n","sub_path":"src/scripts/extract_vgg16_relu6.py","file_name":"extract_vgg16_relu6.py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"144869013","text":"'''\n给你一个整数数组 A,只有可以将其划分为三个和相等的非空部分时才返回 true,否则返回 false。\n\n形式上,如果可以找出索引 i+1 < j 且满足 (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1]) 就可以将数组三等分。\n\n \n\n示例 1:\n\n输出:[0,2,1,-6,6,-7,9,1,2,0,1]\n输出:true\n解释:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1\n示例 2:\n\n输入:[0,2,1,-6,6,7,9,-1,2,0,1]\n输出:false\n示例 3:\n\n输入:[3,3,6,5,-2,2,5,1,-9,4]\n输出:true\n解释:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4\n \n\n提示:\n\n3 <= A.length <= 50000\n-10^4 <= A[i] <= 10^4\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n'''\nclass Solution:\n def canThreePartsEqualSum(self, A) -> bool:\n leng = len(A)\n for i in range(1, leng):\n for j in range(i + 1, leng):\n sum1 = 0\n sum2 = 0\n sum3 = 0\n for index in range(0, i):\n sum1 += A[index]\n for index in range(i, j):\n sum2 += A[index]\n for index in range(j, leng):\n sum3 += A[index]\n if sum1 == sum2 and sum1 == sum3:\n return True\n return False\n\na = Solution().canThreePartsEqualSum([1,-1,1,-1])\nprint(a)","sub_path":"src/1013.py","file_name":"1013.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"654401763","text":"__author__ = 'Exergos'\n\n########################################################################################################################\n########################################################################################################################\n\n#########################\n# What does this file do?\n#########################\n\n# This file simulates outcomes for the Jupiler Pro League based on the SPI algorithm and the ELO algorithm\n# It uses the a Monte Carlo Simulation\n\n# Python 3.3 as Interpreter\n\n######################\n# What does it return?\n######################\n# A list of 2 things:\n# [0]: List of 2 things\n# [0][0]: Team names of all teams in Jupiler Pro League\n# [0][1]: Array of size (number of teams x 3)\n# [0][1][:,0]: SPI\n# [0][1][:,1]: Off Rating\n# [0][1][:,2]: Def Rating\n# Or, in case of ELO simulation:\n# [0][1]: Array of size (number of teams x 1)\n# [0][1][:,0]: ELO\n\n# [1]: A size (number_of_teams x number_of_teams) matrix with the percentage chance of every team to end up in every\n# possible league position\n\n########################################################################################################################\n########################################################################################################################\n\ndef montecarlo(wedstrijden_gtt,simulations = 100):\n import numpy as np\n import time\n \n # Loop over all competitions\n competitions = [\"rs\",\"poi\",\"poii_a\",\"poii_b\",\"poiii\"]\n \n # Save output\n output = dict()\n \n for competition in competitions:\n print('Starting Montecarlo Simulation for ' + competition)\n # check to see if there are games still to be played in this competition\n # if int(np.sum(wedstrijden_gtt[competition][1][:,4],0)) == len(wedstrijden_gtt[competition][1]):\n # continue\n # if int(np.sum(wedstrijden_gtt[\"rs\"][1][:,4],0)) < len(wedstrijden_gtt[\"rs\"][1]):\n # if competition is not \"rs\":\n # continue\n \n # Define some parameters to make code more readable\n # Define some parameters that will help with reading the code\n team_names = wedstrijden_gtt[competition][0][0]\n team_indices = wedstrijden_gtt[competition][0][1]\n number_of_teams = len(team_names)\n total_games = len(wedstrijden_gtt[competition][1])\n games_played = []\n for i in range(total_games):\n if wedstrijden_gtt[competition][1][i,4] == 1:\n games_played.append(i)\n \n # Initialize parameters for Monte Carlo Simulation\n simulation = 0\n simulation_matrix = np.zeros((total_games, simulations))\n \n # Monte Carlo Simulation\n # Simulate every game in a season, and this \"simulations\" times\n # This data can then be used to generate statistical output\n \n sim_start = time.time()\n while simulation < simulations:\n if simulation == 0:\n sim_start_iteration = time.time()\n for i in range(total_games): # total games\n simulation_matrix[i, simulation] = np.random.choice([0, 1, 2], p=wedstrijden_gtt[competition][1][i, 6:9])\n if simulation == 0:\n sim_end_iteration = time.time()\n print('One Montecarlo Iteration finished in ' + str(round(sim_end_iteration - sim_start_iteration,4)) + \" seconds\")\n print('Expected time for full Montecarlo simulation is ' + str(round((sim_end_iteration - sim_start_iteration)*simulations,0)) + \" seconds\") \n simulation += 1\n sim_end = time.time()\n \n print('Montecarlo Simulation finished for ' + competition + \" in \" + str(round(sim_end - sim_start,0)) + \" seconds, taking \" + str(simulations) + \" simulations\")\n \n # Adjust simulation_matrix for games already played (only if \"actual\" parameter = 1)!!\n # 0 for Home Win, 1 for Tie, 2 for Away Win\n simulation_matrix_regular = np.zeros((total_games, simulations))\n for i in range(total_games):\n if wedstrijden_gtt[competition][1][i,4] == 1: # Game already played\n if wedstrijden_gtt[competition][1][i,2] > wedstrijden_gtt[competition][1][i,3]: # Home Win\n simulation_matrix_regular[i,:] = np.matrix(np.zeros(simulations))\n if wedstrijden_gtt[competition][1][i,2] == wedstrijden_gtt[competition][1][i,3]: # Tie\n simulation_matrix_regular[i,:] = np.matrix(np.ones(simulations))\n if wedstrijden_gtt[competition][1][i,2] < wedstrijden_gtt[competition][1][i,3]: # Away Win\n simulation_matrix_regular[i,:] = np.matrix(2*np.ones(simulations))\n else:\n simulation_matrix_regular[i,:] = simulation_matrix[i,:]\n \n # Generate Output based on Monte Carlo Simulation\n # Determine number of points & league position for every team in every simulation\n \n # points is matrix of size number_of_teams x simulation\n # unsorted (teams alphabetically) points for every team in every season\n points = np.zeros((number_of_teams, simulations))\n wins = np.zeros((number_of_teams, simulations))\n \n # Fix points and wins per PO competition\n rs_ranking = wedstrijden_gtt[\"rs\"][2]\n if competition == \"poi\":\n for i in range(len(team_indices)):\n points[i,:] = np.ones((1,simulations))*np.ceil(rs_ranking[:,7]/2)[int(team_indices[i])]\n # wins[i,:] = np.ones((1,simulations))*np.ceil(rs_ranking[:,1]/2)[int(team_indices[i])]\n \n if competition == \"poiii\":\n if rs_ranking[:,8][int(team_indices[0])] < rs_ranking[:,8][int(team_indices[1])]:\n points[0,:] = np.ones((1,simulations))*3 \n else:\n points[1,:] = np.ones((1,simulations))*3 \n \n # league_ranking is matrix of size number_of_teams x simulation\n # sorted (descending) index of team on that position\n league_ranking = np.zeros((number_of_teams, simulations))\n league_ranking_distribution_po = list()\n for i in range(simulations):\n for j in range(total_games):\n for k in range(number_of_teams):\n if wedstrijden_gtt[competition][1][j, 0] == team_indices[k]: # Home Team\n if simulation_matrix_regular[j, i] == 0: # Home Team Victory\n points[k, i] += 3\n wins[k, i] += 1\n if simulation_matrix_regular[j, i] == 1: # Tie\n points[k, i] += 1\n if simulation_matrix_regular[j, i] == 2: # Away Team Victory\n points[k, i] += 0\n if wedstrijden_gtt[competition][1][j, 1] == team_indices[k]: # Away team\n if simulation_matrix_regular[j, i] == 0: # Home Team Victory\n points[k, i] += 0\n if simulation_matrix_regular[j, i] == 1: # Tie\n points[k, i] += 1\n if simulation_matrix_regular[j, i] == 2: # Away Team Victory\n points[k, i] += 3\n wins[k, i] += 1\n \n # Make ranking for this simulation\n # 1. Sort by points\n league_ranking[:, i] = np.argsort(points[:, i])[::-1] # Best Team index [0], Worst team index [number_of_teams - 1]\n \n # 2. If same amount of points, most wins\n for j in range(1,len(points)):\n if points[league_ranking[j,i],i] == points[league_ranking[j-1,i],i]:\n if wins[league_ranking[j,i],i] > wins[league_ranking[j-1,i],i]:\n league_ranking[j,i],league_ranking[j-1,i] = league_ranking[j-1,i],league_ranking[j,i]\n \n # 3. Goal difference\n \n # # Average amount of points for every team\n # # number_of_teams (ordered alphabetically) x 1 matrix\n # points_avg = np.sum(points, axis=1) / simulations\n \n # Percentage chance to end up in certain league position\n # number_of_teams (ordered alphabetically) x number_of_teams (ranking)\n league_ranking_distribution = np.zeros((number_of_teams, number_of_teams))\n # league_ranking_distribution_elo = np.zeros((number_of_teams, number_of_teams))\n for i in range(number_of_teams):\n # Some teams may not get simulated on every position\n # For example a very good team might never simulate in last place\n # For that reason we have to check this and extend array if necessary (with 0 values)\n possible_positions_i = np.unique(np.where(league_ranking == i)[0])\n amount_per_position_i = np.bincount(np.where(league_ranking == i)[0]) / simulations\n # Remove zeros from amount_per_position_i\n amount_per_position_i = amount_per_position_i[amount_per_position_i != 0]\n for j in range(len(possible_positions_i)):\n league_ranking_distribution[i, possible_positions_i[j]] = amount_per_position_i[j]\n \n # Round all numbers to 2 digits behind comma\n league_ranking_distribution = np.around(league_ranking_distribution,5)\n \n output[competition] = list([list([team_names,team_indices]), league_ranking_distribution])\n\n return output","sub_path":"app_voetbalelo/jpl_playoffs/algorithms/montecarlo.py","file_name":"montecarlo.py","file_ext":"py","file_size_in_byte":9556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"585879153","text":"from django.template.loader import get_template\nfrom django.template import Context\nfrom django.http import HttpResponse, Http404\nfrom django.shortcuts import render_to_response, render\nfrom mysite.forms import ContactForm, SimpleForm, AddPublisher\nfrom django.template import RequestContext\nfrom books.models import *\nimport datetime, csv\n\ndef hello(request):\n return HttpResponse(\"Hello World\")\n\ndef current_datetime(request):\n now = datetime.datetime.now()\n t = get_template('current_datetime.html')\n html = t.render(Context({'current_date': now}))\n return HttpResponse(html)\n\ndef current_datetime_short(request):\n now = datetime.datetime.now()\n return render_to_response('current_datetime.html', {'current_date': now})\n\ndef hours_ahead(request, offset):\n try:\n offset = int(offset)\n except:\n raise Http404()\n dt = datetime.datetime.now() + datetime.timedelta(hours=offset)\n html = \"In %s hour(s), it will be %s.\" % (offset, dt)\n return HttpResponse(html)\n\ndef use_include(request):\n title = \"My page\" # This will be used by locals()\n current_section = \"This is the Nav section\"\n\n return render_to_response('mypage.html', locals())\n\n time = datetime.datetime.now() + datetime.timedelta(hours=offset)\n html = \"The current + offset time is: %s .\" % time\n return HttpResponse(html)\n\n\ndef inheritance_version_1(request):\n title = \"This is a title\"\n version = 1\n return render_to_response('page1.html', locals())\n\n\ndef inheritance_version_2(request):\n title = \"This is another title\"\n version = 2\n return render_to_response('page2.html', locals())\n\n\ndef display_meta(request):\n values = request.META.items()\n values.sort()\n html = []\n for k, v in values:\n html.append('%s%s' % (k, v))\n return HttpResponse('%s 1:\r\n pendu()\r\nelse :\r\n pendu_cpu()\r\n","sub_path":"Pendu V1.py","file_name":"Pendu V1.py","file_ext":"py","file_size_in_byte":5118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"413529076","text":"import os\nimport ConfigParser\n\n\ndef build_session_config():\n try:\n CONF_PATH = os.path.join('config', 'core.conf')\n config = ConfigParser.SafeConfigParser()\n config.read(CONF_PATH)\n return config\n except IOError:\n raise IOError\n\n\ndef get_preference(automation_script, requested_setting):\n for section in automation_script.config.sections():\n if automation_script.config.has_option(section, requested_setting):\n return automation_script.config.get(section, requested_setting)\n raise ConfigParser.NoOptionError(option=requested_setting, section=section)\n\n\n\n","sub_path":"src/configTools.py","file_name":"configTools.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"630208566","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom conans import ConanFile, CMake, tools\nimport os\n\n\nclass GbenchmarkConan(ConanFile):\n name = \"gbenchmark\"\n version = \"1.4.1\"\n description = \"Google's C++ benchmark framework\"\n url = \"http://github.com/bincrafters/conan-gbenchmark\"\n license = \"BSD 3-Clause\"\n exports = [\"LICENSE.md\"]\n exports_sources = [\"*.patch\", \"FindGBenchmark.cmake\"]\n generators = \"cmake\"\n source_subfolder = 'source_subfolder'\n settings = \"os\", \"arch\", \"compiler\", \"build_type\"\n options = {\"shared\": [True, False], \"fPIC\": [True, False]}\n default_options = (\"shared=False\", \"fPIC=True\")\n\n def configure(self):\n if self.settings.os == \"Windows\":\n self.options.remove(\"fPIC\")\n\n def source(self):\n source_url = \"https://github.com/google/benchmark\"\n tools.get(\"{0}/archive/v{1}.tar.gz\".format(source_url, self.version))\n extracted_dir = \"benchmark-\" + self.version\n tools.patch(patch_file='werror.patch')\n os.rename(extracted_dir, self.source_subfolder)\n\n def build(self):\n cmake = CMake(self)\n if self.settings.os != \"Windows\":\n cmake.definitions[\"CMAKE_POSITION_INDEPENDENT_CODE\"] = self.options.fPIC\n\n cmake.definitions[\"BENCHMARK_ENABLE_GTEST_TESTS\"] = \"OFF\"\n cmake.definitions[\"BENCHMARK_ENABLE_TESTING\"] = \"OFF\"\n cmake.definitions['CMAKE_VERBOSE_MAKEFILE'] = \"ON\"\n\n cmake.configure(source_dir=self.source_subfolder)\n cmake.build()\n\n def package(self):\n self.copy(\"FindGBenchmark.cmake\", \".\", \".\")\n\n # Copy the license files\n self.copy(\"LICENSE\", dst=\"licenses\", src=self.source_subfolder)\n\n # Copying headers\n include_dir = os.path.join(self.source_subfolder, \"include\", \"benchmark\")\n\n self.copy(pattern=\"*.h\", dst=\"include/benchmark\", src=include_dir, keep_path=True)\n\n # Copying static and dynamic libs\n self.copy(pattern=\"*.a\", dst=\"lib\", src=\".\", keep_path=False)\n self.copy(pattern=\"*.lib\", dst=\"lib\", src=\".\", keep_path=False)\n self.copy(pattern=\"*.dll\", dst=\"bin\", src=\".\", keep_path=False)\n self.copy(pattern=\"*.so*\", dst=\"lib\", src=\".\", keep_path=False)\n self.copy(pattern=\"*.dylib*\", dst=\"lib\", src=\".\", keep_path=False)\n self.copy(pattern=\"*.pdb\", dst=\"bin\", src=\".\", keep_path=False)\n\n def package_info(self):\n self.cpp_info.libs = ['benchmark_main', 'benchmark']\n\n if self.settings.os == \"Linux\":\n self.cpp_info.libs.append(\"pthread\")\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"279150886","text":"import pytest\n\nfrom dcicutils import contribution_scripts as contribution_scripts_module\nfrom dcicutils.command_utils import ScriptFailure\nfrom dcicutils.contribution_scripts import show_contributors, show_contributors_main\nfrom unittest import mock\n\n\nclass MockContributions:\n\n def __init__(self, repo, exclude_fork=None, verbose=False):\n self.repo = repo\n self.exclude_fork = exclude_fork\n self.verbose = verbose\n\n\ndef test_show_contributors():\n with mock.patch.object(contribution_scripts_module, \"Contributions\") as mock_contributions:\n contributions_object = mock.MagicMock()\n mock_contributions.return_value = contributions_object\n\n show_contributors(repo='my-repo')\n\n assert contributions_object.save_contributor_data.call_count == 0\n\n mock_contributions.assert_called_once_with(repo='my-repo', exclude_fork=None, verbose=False)\n contributions_object.show_repo_contributors.assert_called_once_with(error_class=None)\n\n mock_contributions.reset_mock()\n contributions_object = mock.MagicMock()\n mock_contributions.return_value = contributions_object\n\n show_contributors(repo='another-repo', exclude_fork='whatever', save_contributors=True, verbose=True, test=True)\n\n mock_contributions.assert_called_once_with(repo='another-repo', exclude_fork='whatever', verbose=True)\n contributions_object.show_repo_contributors.assert_called_once_with(error_class=ScriptFailure)\n contributions_object.save_contributor_data.assert_called_once_with()\n\n\ndef test_show_contributors_main():\n\n with mock.patch.object(contribution_scripts_module, \"show_contributors\") as mock_show_contributors:\n\n with pytest.raises(SystemExit) as exc:\n\n show_contributors_main(simulated_args=['some-repo'])\n\n assert exc.value.code == 0\n\n mock_show_contributors.assert_called_once_with(repo='some-repo', exclude_fork=None, verbose=False,\n save_contributors=False, test=False)\n\n mock_show_contributors.reset_mock()\n\n with pytest.raises(SystemExit) as exc:\n\n show_contributors_main(simulated_args=['my-repo', '--exclude', 'their-repo',\n '--save-contributors', '--test', '--verbose'])\n\n assert exc.value.code == 0\n\n mock_show_contributors.assert_called_once_with(repo='my-repo', exclude_fork='their-repo',\n save_contributors=True, test=True, verbose=True)\n","sub_path":"test/test_contribution_scripts.py","file_name":"test_contribution_scripts.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445780367","text":"#Author: Niklas Melton\n#Date: 23/02/2016\n#Basic MLP neural network library\n\nimport numpy as np, math\n\nDCONST = 0.1 #constant error value to accelerate learning\n\ndef sigmoid(x):\n if x > 7:\n y = 1\n elif x < -7:\n y = 0\n else:\n y = 1/(1+math.e**(-x))\n return y\n\ndef normalize(X, Xmin,Xmax, angular = False):\n X = (X-Xmin)/(Xmax-Xmin)\n if angular == True:\n X = round((X%1), 3)\n return X\n\ndef error(X, Xgoal):\n return (X*(1-X) + DCONST)*(X-Xgoal)\n\n\n\nclass network:\n def __init__(self, shape, weights = None):\n #expects shape of network in the form of a tuple\n self.shape = shape\n self.nodes = np.zeros(len(shape), dtype = object)\n for i in range(0, len(self.shape)):\n self.nodes[i] = zeros(self.shape[i])\n if weights != None:\n self.weights = weights\n else:\n #initialize new set of weights if not given\n self.weights = np.zeros((len(self.shape)-1), dtype = object)\n for i in range(0, (len(self.shape)-1)):\n self.weights[i] = np.zeros((self.shape[i+1],self.shape[i]))\n\n\n def feedForward(X, allNodes = False):\n self.nodes[0] = X\n for i in range(0, (len(self.shape)-1)):\n #for each subsequent layer, create a set of nodes\n for j in range(0, self.shape[i+1]):\n #for each node:\n for k in range(0, self.shape[i]):\n #sum the product of the weights and previous node layer\n self.nodes[i+1][j] += self.nodes[i][k]*self.weights[k][j]\n #take sigmoid of node values\n self.nodes[i+1] = sigmoid(self.nodes[i+1])\n if allNodes == False:\n #return last node layer\n return self.nodes[(len(self.nodes)-1)]\n else:\n return self.nodes\n\n\n def backProp(error, LR = None, nodes = None):\n errorNodeDown = error\n if nodes != None:\n self.nodes = nodes\n for i in range(0, (len(self.shape)-1)):\n I = (len(self.shape)-1)-i\n #for each previous layer, create a set of errorNodes\n errorNode = np.zeros(self.shape[I-1])\n for j in range(0, self.shape[I-1]):\n #for each of these errorNodes\n errorSum = 0\n for k in range(0, self.shape[I]):\n #sum the product of the lower errors and weights\n errorSum += errorNodeDown[k]*self.weights[j][k]\n if LR != None:\n #update weights\n self.weights[j][k] -= LR*errorNodeDown[k]*self.nodes[I-1][j]\n errorNode = (self.nodes[I-1][j]*(1-self.nodes[I-1][j]) + DCONST)*errorSum\n errorNodeDown = errorNode\n #return the topmost error derivatives\n if LR != None:\n return errorNode\n \n","sub_path":"MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"361250997","text":"import pyodbc\n\ntry:\n\n conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=C:\\Users\\Bujhc\\eplan_db;')\n conn.autocommit = True\n cursor = conn.cursor()\n\n param = 'Johnson Controls'\n sql=(\"\"\"\n select partnr, purchaseprice1, salesprice1, lastchange from tblPart\n where manufacturer=?\n \"\"\")\n\n cursor.execute(sql,param)\n\n\n\n\n\n # find items in price table which have in db of eplan\n\n\n t1 = [['A99DY-200C','4444'],['MS-NAE3510-2', '44444']]\n\n\n for x in t1:\n x1= x[1]\n x2= x[0] \n sql_update_request =\"update tblPart set salesprice1=? where partnr=?\"\n conn.execute(sql_update_request,x1,x2)\n conn.commit\n\n row = cursor.fetchall()\n for i in row:\n print(i)\n\nexcept pyodbc.Error as e:\n loggin.error(e)\n print(e)\n\ncursor.close()\nconn.close()\n\n","sub_path":"clean_db.py","file_name":"clean_db.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"236011893","text":"import os\nfrom datetime import datetime\nfrom multiprocessing.util import register_after_fork\n\nfrom sqlalchemy import create_engine, MetaData, Table\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\n\nfrom psycopg2.extras import RealDictConnection, register_hstore\n\nDATABASE_URL = os.environ.get('DATABASE_URL')\n\n\nBase = declarative_base()\n\n\n_ENGINES = {}\n_SESSIONS = {}\n\n# https://github.com/celery/celery/blob/master/celery/backends/database/session.py#L27-L46\n\nclass _after_fork(object):\n registered = False\n\n def __call__(self):\n self.registered = False # child must reregister\n for engine in list(_ENGINES.values()):\n engine.dispose()\n _ENGINES.clear()\n _SESSIONS.clear()\nafter_fork = _after_fork()\n\ndef get_engine(dburi, **kwargs):\n try:\n return _ENGINES[dburi]\n except KeyError:\n engine = _ENGINES[dburi] = create_engine(dburi, **kwargs)\n after_fork.registered = True\n register_after_fork(after_fork, after_fork)\n return engine\n\n\ndef create_session(dburi, short_lived_sessions=False, **kwargs):\n engine = get_engine(dburi, **kwargs)\n if short_lived_sessions or dburi not in _SESSIONS:\n _SESSIONS[dburi] = sessionmaker(bind=engine)\n return engine, _SESSIONS[dburi]\n\nengine = create_engine(DATABASE_URL)\nmetadata = MetaData(bind=engine)\n\nsession_maker = create_session(DATABASE_URL)[1]\n\n\nclass SessionPropertyMixin(object):\n\n def save(self, session=None, commit=True, close=False):\n\n if session:\n session.add(self)\n session.commit()\n\n if close:\n session.close()\n\n\nclass Warehouse(object):\n def __init__(self, conn_str):\n self.db = RealDictConnection(conn_str)\n register_hstore(self.db)\n\n def query(self, q, params=None, fetchall=False):\n c = self.db.cursor()\n c.execute(q, params)\n\n gen = (r for r in c)\n\n if fetchall:\n return list(gen)\n else:\n return gen\n\n def query_file(self, path, params=None, fetchall=False):\n with open(path) as f:\n query = f.read()\n\n return self.query(query, params=params, fetchall=fetchall)\n","sub_path":"proto.py","file_name":"proto.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"221990221","text":"import os\nimport imageio\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom genetic_optimizer import GeneticOptimizer\nfrom functools import partial\n\n''' CONSTANTS '''\nCOLORS = ['red', 'yellow', 'green', 'purple']\n\n''' PARAMETERS '''\nparser = argparse.ArgumentParser(description='Genetic optimization of route in graph. ')\n\n# graph specific\nparser.add_argument('--n_nodes', type=int, default=100, help='number of nodes in graph')\nparser.add_argument('--x_lim', type=int, default=25, help='number of grid cells in x-direction')\nparser.add_argument('--y_lim', type=int, default=25, help='number of grid cells in y-direction')\nparser.add_argument('--lmbda', type=float, default=0.45, help='parameter for connections (low --> many connections)')\n\n# optimizer specific\nparser.add_argument('--n_generations', type=int, default=30, help='number of generations')\nparser.add_argument('--population_size', type=int, default=30, help='number of members in population')\nparser.add_argument('--p_elitism', type=float, default=0.1, help='proportion of elitist members')\nparser.add_argument('--p_crossover', type=float, default=0.3, help='proportion of crossover members')\nparser.add_argument('--p_mutate', type=float, default=0.1, help='probability to create mutated copy of member')\n\n# output\nparser.add_argument('--save_frames', type=bool, default=True, help='wether to save frames or not')\nparser.add_argument('--save_dir', type=str, default='frames', help='where to save frames')\n\nargs = parser.parse_args()\n\n\n''' FUNCTIONS '''\ndef make_edge_list(graph_matrix):\n indices = np.where(graph_matrix > 0)\n return [[indices[0][i], indices[1][i]] for i in range(len(indices[0]))]\n\nclass Environment():\n def __init__(self, n_nodes, x_lim, y_lim, lmbda):\n self.n_nodes = n_nodes\n self.x_lim = x_lim\n self.y_lim = y_lim\n self.lmbda = lmbda\n self.graph_matrix, self.node_positions, self.edge_list = self._generate_graph()\n\n def _generate_graph(self):\n # generate node positions\n node_positions = np.zeros((self.n_nodes, 2))\n for i in range(self.n_nodes):\n already_exists = True\n counter = 0\n while already_exists:\n node_position = np.array((np.random.randint(0, self.x_lim), np.random.randint(0, self.y_lim)))\n if not (node_position == node_positions).all(1).any():\n already_exists = False\n counter += 1\n if counter > 1000:\n continue\n node_positions[i] = node_position\n\n # generate node connections\n graph_matrix = np.zeros((self.n_nodes, self.n_nodes))\n for node_no, node_pos in enumerate(node_positions):\n distances = np.linalg.norm(node_positions - node_pos, axis=1)\n distances[distances == 0] = np.inf\n nearest_connection_index = np.argmin(distances)\n graph_matrix[node_no, nearest_connection_index] = np.min(distances[distances > 0])\n probability_for_connection = np.exp(-self.lmbda * distances)\n additional_connection_indices = np.where(probability_for_connection > np.random.uniform(0, 1, self.n_nodes))[0]\n for connection_index in additional_connection_indices:\n if not connection_index == node_no:\n graph_matrix[node_no, connection_index] = distances[connection_index]\n graph_matrix[connection_index, node_no] = distances[connection_index]\n\n edge_list = make_edge_list(graph_matrix)\n\n return graph_matrix, node_positions, edge_list\n\n def draw(self, color='cyan'):\n map_graph = nx.Graph()\n map_graph.add_edges_from(self.edge_list)\n nx.draw(map_graph, self.node_positions, node_color=color, with_labels=True)\n\n\ndef generate_route_segment(graph_matrix, node_start: int, node_end: int):\n route_segment = np.ones(1, dtype=int) * node_start\n i = 0\n while not route_segment[i] == node_end:\n route_segment = np.append(route_segment, np.random.choice(np.nonzero(graph_matrix[route_segment[i]])[0]))\n i += 1\n\n return route_segment\n\ndef get_distance(env, route):\n distance = 0\n for i in range(len(route) - 1):\n distance += np.linalg.norm(env.node_positions[route[i]] - env.node_positions[route[i + 1]])\n return distance\n\n\ndef mutate(env, route):\n index_start = np.random.randint(0, len(route) - 1)\n index_end = index_start + np.random.randint(0, len(route) - index_start)\n route_before = route[:index_start]\n route_after = route[index_end + 1:]\n route_intermediate = generate_route_segment(env.graph_matrix, route[index_start], route[index_end])\n mutated_route = np.concatenate([route_before, route_intermediate, route_after])\n return mutated_route\n\ndef crossover(first_route, second_route):\n intersections = np.intersect1d(first_route[1:-1], second_route[1:-1])\n if len(intersections):\n intersection = np.random.choice(intersections)\n own_snipping_location = np.random.choice(np.where(first_route[1:-1] == intersection)[0]) + 1\n other_snipping_location = np.random.choice(np.where(second_route[1:-1] == intersection)[0]) + 1\n if np.random.random() > 0.5:\n new_route = np.concatenate([first_route[:own_snipping_location], second_route[other_snipping_location:]])\n else:\n new_route = np.concatenate([second_route[:other_snipping_location], first_route[own_snipping_location:]])\n else:\n if np.random.random() > 0.5:\n new_route = first_route\n else:\n new_route = second_route\n return new_route\n\ndef draw_route(env, route, color='red'):\n edges = [[route[i], route[i + 1]] for i in range(len(route) - 1)]\n route_graph = nx.Graph()\n route_graph.add_edges_from(edges)\n nx.draw(route_graph, env.node_positions, node_color=color, with_labels=True)\n\n\ndef main():\n np.random.seed(5)\n\n # create environment\n env = Environment(args.n_nodes, args.x_lim, args.y_lim, args.lmbda)\n\n # create optimizer\n optimizer = GeneticOptimizer(create_member_fun = partial(generate_route_segment, env.graph_matrix, 0, np.shape(env.graph_matrix)[0] - 1),\n mutate_fun = partial(mutate, env),\n crossover_fun = crossover,\n evaluation_fun = partial(get_distance, env),\n p_elitism = args.p_elitism,\n p_crossover = args.p_crossover,\n p_mutate = args.p_mutate)\n\n # run evolution, plot results and extract population\n optimizer.run_evolution(args.n_generations,\n args.population_size)\n\n optimizer.plot_evaluation_history()\n\n population_history, fitness_history = optimizer.get_history()\n\n\n # visualize reesults\n if args.save_frames:\n os.makedirs(args.save_dir, exist_ok=True)\n\n plt.figure(figsize=[12, 8])\n env.draw()\n for generation_no, population in enumerate(population_history):\n plt.clf()\n for route in population[:1]:\n env.draw()\n draw_route(env, route, color=COLORS[np.mod(generation_no, len(COLORS))])\n plt.text(args.x_lim * 0.95, args.y_lim * 0.01, 'gen {}'.format(generation_no))\n plt.pause(0.2)\n if args.save_frames:\n plt.savefig(os.path.join(args.save_dir, 'gen' + str(generation_no).zfill(int(np.log10(args.n_generations)) + 1) + '.png'))\n plt.show()\n\n\nif '__main__' == __name__:\n main()","sub_path":"experiments/shortest_route.py","file_name":"shortest_route.py","file_ext":"py","file_size_in_byte":7608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"283935588","text":"from django.urls import path\nfrom . import views\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = [\n path('', views.home, name = 'home'),\n path('login/', views.user_login, name = 'login'),\n path('register/', views.register, name = 'register'),\n path('logout/', views.user_logout, name='logout'),\n path('upload/', views.upload, name='upload'),\n path('detail/', views.detail_custom, name='detail_custom'),\n path('edit/', views.edit_custom, name='edit_custom'),\n ]\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"mypage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"8643851","text":"from __future__ import print_function, absolute_import\r\nimport numpy as np\r\nimport copy\r\nfrom tqdm import tqdm\r\n\r\n\r\ndef evaluate(distmat, queryPersonIds, galleryPersonIds, maxRank=30):\r\n\tnumQuery, numGallery = distmat.shape\r\n\tif numGallery < maxRank:\r\n\t\tmaxRank = numGallery\r\n\t\tprint(\"Note: number of gallery samples is quite small, got {}\".format(numGallery))\r\n\t\r\n\tindices = np.argsort(distmat, axis=1)\r\n\tmatches = (galleryPersonIds[indices] == queryPersonIds[:, np.newaxis]).astype(np.int32)\r\n\r\n\t# compute cmc curve for each query\r\n\tall_cmc = []\r\n\tall_AP = []\r\n\tnum_valid_q = 0.\r\n\r\n\tfor queryIndex in tqdm(range(numQuery), desc=\"Computing CMC and mAP\"):\r\n\t\t# get query pid and camid\r\n\t\tq_pid = queryPersonIds[queryIndex]\r\n\t\t# remove gallery samples that have the same pid and camid with query\r\n\t\t# order = indices[queryIndex]\r\n\t\t# remove = (galleryPersonIds[order] == q_pid)\r\n\t\t# keep = np.invert(remove)\r\n\r\n\t\t# compute cmc curve\r\n\t\t# orig_cmc = matches[queryIndex][keep] # binary vector, positions with value 1 are correct matches\r\n\t\torig_cmc = matches[queryIndex]\r\n\t\t# if not np.any(orig_cmc):\r\n\t\t# # this condition is true when query identity does not appear in gallery\r\n\t\t# continue\r\n\t\tcmc = orig_cmc.cumsum()\r\n\t\tcmc[cmc > 1] = 1\r\n\t\tall_cmc.append(cmc[:maxRank])\r\n\t\tnum_valid_q += 1.\r\n\r\n\t\t# compute average precision\r\n\t\t# reference: https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision\r\n\t\tnum_rel = orig_cmc.sum()\r\n\t\ttmp_cmc = orig_cmc.cumsum()\r\n\t\ttmp_cmc = [x / (i+1.) for i, x in enumerate(tmp_cmc)]\r\n\t\ttmp_cmc = np.asarray(tmp_cmc) * orig_cmc\r\n\t\tAP = tmp_cmc.sum() / num_rel\r\n\t\tall_AP.append(AP)\r\n\r\n\tassert num_valid_q > 0, \"Error: all query identities do not appear in gallery\"\r\n\r\n\tall_cmc = np.asarray(all_cmc).astype(np.float32)\r\n\tall_cmc = all_cmc.sum(0) / num_valid_q\r\n\tmAP = np.mean(all_AP)\r\n\treturn all_cmc, mAP","sub_path":"tool/evalMetrics.py","file_name":"evalMetrics.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"224183907","text":"class ListNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.next = None\r\n\r\n\r\nclass Solution:\r\n def FindKthToTail(self, head, k):\r\n # write code here\r\n if head is None or k == 0:\r\n return None\r\n nodes = []\r\n cur_node = head\r\n while cur_node is not None:\r\n nodes.append(cur_node)\r\n cur_node = cur_node.next\r\n if len(nodes) < k:\r\n return None\r\n return nodes[len(nodes)-k]\r\n","sub_path":"Python总结/PyExamples/niuke/find_node_to_tail.py","file_name":"find_node_to_tail.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"103705548","text":"__author__ = 'RandyGuo'\n#coding=utf-8\n\"\"\"\nsplit and interactively page a string , file , or stream of text to stdout ; when run as a script,\npage stdin or file whose name is passed on cmdline ; if input is stdin,can't use it for user reply\n--use platform--specific tools or GUI;\n\n\"\"\"\n\nimport sys\n\ndef getreply():\n '''\n 读取交互式用户的回复键,即使stdin重定向到某个文件或者管道\n '''\n if sys.stdin.isatty():\n return input('?') # 如果stdin 是控制台 从stdin 读取回复行数据\n else :\n if sys.platform[:3] == 'win': # 如果stdin 重定向,不能用于询问用户\n import msvcrt\n msvcrt.putch(b'?')\n key = msvcrt.getche() # 使用windows 控制台工具 getch()方法不能回应键\n return key\n else:\n assert False,'platform not supported'\n #linux?:open(/dev/tty).readline()[:-1]\n\ndef more(text,numlines = 10):\n \"\"\"\n page multiline string to stdout\n :param text:\n :param numlines:\n :return:\n \"\"\"\n lines = text.splitlines()\n while lines:\n chunk = lines[:numlines]\n lines = lines[numlines:]\n for line in chunk:print(line)\n if lines and getreply() not in [b'y',b'Y']:break\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n more(sys.stdin.read())\n else:\n more(open(sys.argv[1].read()))\n","sub_path":"PragrammingPython/SystemTools/moreplus.py","file_name":"moreplus.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"208402875","text":"import sys\nimport numpy as np\nimport speech_detection\nimport os.path\nsys.path.insert(0,'./utils/')\n# from qsub_parallel import qsub_fun\nimport time\n\n'''\nRun command:\nC:\\1Python_Speech_detection\\speech_detection\\code\\outerLoop_speech_detection_testData.py\n'''\n\nif __name__==\"__main__\":\n\n\n\n participant = np.r_[101]\n dataPath = \"./\"\n test_fileName=\"101_TopRankFeatures_CoupleField.csv\"\n\n\n inPath = \"./model_files/\"\n opPath = \".\"\n\n model_fn = inPath + \"W2_activity_enriched_F5_CoupleLab_model.pkl\"\n weights_fn = inPath + \"W2_activity_enriched_F5_CoupleLab_weights.pkl\"\n grammer_fn = \"./speech_detection_grammar.txt\"\n\n\n model_save = 0\n if model_save==1:\n data_fn_train = \"./4_activity_enritched_W2_walk_F5_CoupleLab_data.csv\"\n LAMDA = np.r_[100,1000] # np.r_[0.01,0.1,1] # np.r_[1, 10, 100]\n speech_detection.train(grammer_fn, data_fn_train, model_fn, weights_fn, LAMDA)\n else:\n for pid in participant:\n print(pid)\n data_fn_test = dataPath + str(pid) + test_fileName\n prediction_fn = opPath + \"/\" + str(pid) + \"_pred_W1_F5_activity_ResampledModel_21_Features_coupleField.csv\"\n result = speech_detection.test(data_fn_test, model_fn, prediction_fn)\n output = np.append(pid, result)\n","sub_path":"conversation_detection/outerLoop_speech_detection_testData.py","file_name":"outerLoop_speech_detection_testData.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390164032","text":"from googleapiclient.discovery import build\nimport logging\nimport json\nimport pygame\nimport schedule\nimport time\n\n\"\"\"API section\"\"\"\n\napi_key = 'Your Youtube API_Key HERE!'\n\n# service\nyoutube = build('youtube', 'v3', developerKey = api_key)\n\n# Create request\nrequest = youtube.channels().list(part = 'statistics', id = 'UCy0YHkGM8szRMOhIkNUFwiA')\nresponse = request.execute() # Read youtube API raw data\n\n\n\"\"\"Logging Section\"\"\"\n\nlogger = logging.getLogger(__name__) # Logger obj created\n\n# Setting level\nlogger.setLevel(logging.INFO)\n\n# Formating\nformatter = logging.Formatter('%(asctime)s:%(message)s')\n\n# Creating a new Log file\nfile_handler = logging.FileHandler('SubsReport.txt')\nfile_handler.setFormatter(formatter)\n\n# Adding the file to our logger\nlogger.addHandler(file_handler)\n\n# End Logger section\n\n\"\"\"Data treatment\"\"\"\n\n# Read data from youtube API\ndata = response\n\n\"\"\"Extract subscriber from Nested Dictionary\"\"\"\ndef subscribers():\n subs = data['items'][0]['statistics']['subscriberCount']\n return (subs)\n\n\"\"\"GUI section\"\"\"\npygame.init()\npygame.display.init()\npygame.display.set_caption(\"Youtube Subscriber Counter by @iobotic\")\n\n\"\"\"Screen settings\"\"\"\nscr_width = 900\nscr_height = 600\nscreen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)\n\nblack = (0,0,0)\nmBlack = (20,20,20)\nwhite = (255,255,255)\nred = (255,0,0)\n\nscreen.fill(black)\n\n\n\"\"\"Visuals Functions\"\"\"\n\ndef checkitout():\n \"\"\"show subscribers\"\"\"\n newsubs = subscribers() # Reading YT_Subs\n \n # Show Up!\n font = pygame.font.SysFont(None, 500)\n text = font.render(newsubs, True, white)\n screen.blit(text,(scr_width/2 - text.get_rect().width/2+240, scr_height/2 - text.get_rect().height/2+100))\n pygame.display.update()\n logger.info(\"The number of suscribers = {}\".format(newsubs))\n\ndef firstView():\n \"\"\"show subscribers\"\"\"\n newsubs = subscribers() # Reading YT_Subs\n \n # Show Up!\n font = pygame.font.SysFont(None, 500)\n text = font.render(newsubs, True, white)\n screen.blit(text,(scr_width/2 - text.get_rect().width/2+240, scr_height/2 - text.get_rect().height/2+100))\n pygame.display.update()\n \ndef info():\n font = pygame.font.SysFont(None,140)\n info = font.render(\"SUSCRIPTORES\", True, red)\n screen.blit(info, (300,540))\n pygame.display.update()\n \n \n \n\"\"\"Schedule\"\"\"\n\n# every 30 minutes\nschedule.every(30).minutes.do(checkitout)\n\n\"\"\"Main code\"\"\"\nfirstView()\nexitsubs = False\n\nwhile(exitsubs == False):\n for event in pygame.event.get():\n if(event.type == pygame.KEYUP):\n if(event.key == pygame.K_e):\n exitsubs = True\n\n schedule.run_pending()\n time.sleep(0.1)\n info()\n\npygame.quit()\n \n","sub_path":"YT_API.py","file_name":"YT_API.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"344011917","text":"import requests\nfrom lxml import etree\nimport pypinyin\nimport time\nfrom xpinyin import Pinyin\nheaders = {\n 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'\n}\nnews = []\ntechnlg = []\ncar = []\nhouse = []\njob = []\nfinance = []\nlife = []\ninspire = []\nfemale = []\ntravel = []\nsport = []\ncate = []\nfun = []\nstar = []\ninfant = []\neducation = []\nstartup = []\ngovernm = []\ncompany = []\nlocal = []\n\n\ndef get_account():\n types = [news, technlg, car, house, job, finance, life, inspire, female, travel, sport, cate, fun, star, infant,\n education, startup, governm, company, local]\n\n for category in range(1,21):\n url = 'https://data.wxb.com/rank?category='+str(category)+'&page=1'\n html = requests.get(url,headers=headers)\n selector = etree.HTML(html.text)\n type = selector.xpath('//div[@class=\"rank-right\"]/div/text()')[0]\n p = Pinyin()\n print(\"==========\")\n #print(p.get_pinyin(type))\n print(\"正在爬取类别:\",type)\n print(\"==========\")\n infos = selector.xpath('//tbody[@class=\"ant-table-tbody\"]/tr')\n\n for info in infos:\n name = info.xpath('td[2]/div/div[2]/div[1]/a/text()')[0]\n #wechat_id = info.xpath('td[2]/div/div[2]/div[2]/text()')[0]\n types[category-1].append(name)\n #print(name)\n\n time.sleep(2)\n return types\n\n\n\n\nif __name__ == '__main__':\n\n #print(get_account())\n\n lisys = get_account()\n\n for list in lisys:\n print(list)\n print(\"\\n\")\n\n print('ok')","sub_path":"engine/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"248531892","text":"def letterCasePermutation(S) :\n check=[0]*len(S)\n results=[]\n def makelist(index,result):\n if index==len(S):\n results.append(result)\n return results\n print(index,result)\n\n if S[index].isdigit():\n result.append(S[index])\n makelist(index+1,result)\n else:\n if check[index] == 0:\n result.append(S[index].lower())\n check[index] = 1\n makelist(index+1,result)\n result.append(S[index].upper())\n check[index] = 0\n makelist(index+1,result)\n makelist(0,[])\n print(results)\nletterCasePermutation('a1b2')\n","sub_path":"190316-5.py","file_name":"190316-5.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"405129674","text":"from manga_py.provider import Provider\nfrom .helpers.std import Std\n\n\nclass MangaDexCom(Provider, Std):\n _links_on_page = 100\n _home_url = ''\n\n def get_archive_name(self) -> str:\n return self.normal_arc_name({\n 'vol': self.chapter['vol'],\n 'ch': [*self.chapter['ch'].split('.'), self.chapter['lng']],\n })\n\n def get_chapter_index(self) -> str:\n fmt = '{}-{}'\n if len(self.chapter['lng']) > 0:\n fmt += '-{}'\n return fmt.format(\n self.chapter['ch'].replace('.', '-'),\n self.chapter['vol'],\n self.chapter['lng'],\n )\n\n def get_main_content(self):\n url = self.get_url()\n if url.find('/title/') < 0:\n url = self.html_fromstring(url, 'a.manga-link', 0)\n url = self.http().normalize_uri(url.get('href'))\n self._home_url = self.re.search('(.+/title/\\d+/[^/])', url).group(1)\n return self.http_get(self._home_url)\n\n def get_manga_name(self) -> str:\n url = self.get_url()\n if ~url.find('/title/'):\n name = self.html_fromstring(url, '.card-header', 0).text_content()\n else:\n name = self.html_fromstring(url, '.manga-link', 0).get('title')\n return name.strip()\n\n def _all_langs(self, items):\n languages = []\n for i in items:\n languages.append(i['flag'] + '\\t--- ' + i['lng'])\n return list(set(languages))\n\n def _filter_langs(self, chapters, lng):\n if len(lng) < 1:\n return chapters\n lng = lng.split(' ')\n result = []\n for i in chapters:\n if i['flag'] == '' or i['flag'] in lng:\n result.append(i)\n return result\n\n def get_chapters(self):\n parser = self.document_fromstring(self.content)\n # https://mangadex.org/manga/153/detective-conan\n pages = parser.cssselect('.pagination li.paging a')\n items = self._get_chapters_links(parser)\n if pages:\n pages = self.re.search(r'.+/(\\d+)', pages[0].get('href')).group(1)\n for i in range(2, int(pages)+1):\n _parser = self.html_fromstring('{}/chapters/{}/)'.format(\n self._home_url, i\n ))\n items += self._get_chapters_links(_parser)\n chapters = self._parse_chapters(items)\n lng = self.quest(\n [],\n 'Available languages:\\n{}\\n\\nPlease, select your lang (empty for all, space for delimiter lang):'.format(\n '\\n'.join(self._all_langs(chapters))\n ))\n return self._filter_langs(chapters, lng)\n\n def _get_chapters_links(self, parser):\n return parser.cssselect('div.chapter-row[data-chapter]')\n\n def get_files(self):\n idx = self.re.search(r'/chapter/(\\d+)', self.chapter['link']).group(1)\n try:\n data = self.json.loads(self.http_get('{}/api/chapter/{}'.format(\n self.domain, idx\n )))\n n = self.http().normalize_uri\n items = []\n for item in data.get('page_array', []):\n items.append('{}{}/{}'.format(\n n(data.get('server', '/data/')), data.get('hash'), item\n ))\n return items\n except Exception as e:\n return []\n\n def get_cover(self) -> str:\n return self._cover_from_content('.card-body .rounded')\n\n def prepare_cookies(self):\n self._storage['cookies']['mangadex_h_toggle'] = '1'\n\n def _parse_chapters(self, items):\n n = self.http().normalize_uri\n result = []\n re = self.re.compile(r'/flags/(.+?)\\..+')\n for tr in items:\n ch = tr.cssselect('a[href*=\"/chapter/\"]')[0]\n lng = tr.cssselect('img.flag')\n _ch = {\n 'ch': tr.get('data-chapter'),\n 'vol': tr.get('data-volume'),\n 'link': n(ch.get('href')),\n }\n if lng:\n _ch['lng'] = lng[0].get('alt')\n _ch['flag'] = re.search(lng[0].get('src')).group(1)\n else:\n _ch['lng'] = ''\n _ch['flag'] = ''\n result.append(_ch)\n return result\n\n def book_meta(self) -> dict:\n # todo meta\n pass\n\n def chapter_for_json(self):\n return self.chapter['link']\n\n\nmain = MangaDexCom\n","sub_path":"manga_py/providers/mangadex_com.py","file_name":"mangadex_com.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"299626486","text":"# By submitting this assignment, I agree to the following:\n# \"Aggies do not lie, cheat, or steal, or tolerate those who do\"\n# \"I have not given or received any unauthorized aid on this assignment\"\n#\n# Name: Chase Johnson\n# Section: 413\n# Team: 23\n# Assignment: Quiz 5\n# Date: 09 October, 2019\n\n# list to contain the user's top 5 favorite acts\nacts = []\n\n# for loop to take input for all of the acts and append them to the list $acts\nfor i in range(5):\n act = input(\"What is your number \" + str(i+1) + \" artist? \")\n acts.append(act)\n\nmaxHit = 0 # variable to determine the length of the longest act for printing purposes\nbieberExists = False # boolean used to determine if the name \"bieber\" is contained in the list\n\n# for loop to iterate through the $acts list and determine if \"bieber\" exists within the list\n# for loop also changes the value of $maxHit as it goes through checking for \"bieber\"\nfor act in acts:\n if \"bieber\" in act.lower():\n bieberExists = True\n\n if len(act) > maxHit:\n maxHit = len(act) + 14\n print(\"maxHit is now: \" + str(maxHit))\n\n# determines if \"bieber\" does not exist, remove the last user entry and insert \"Justin Bieber\" to index 0\n# also ensures that maxHit is long enough, if a user entry is not longer than one with ^\nif bieberExists != True:\n acts.pop()\n acts.insert(0, 'Justin Bieber')\n\n if maxHit < 27:\n maxHit = 27\n\n# Print the \"-------------\" stuff\nprint('-' * maxHit)\n\n# print out each of the acts, in order of the list\nfor i, act in enumerate(acts):\n print(\"Number\", i + 1, \"Hit: \" + act)\n\n# Print the \"-------------\" stuff\nprint('-' * maxHit)","sub_path":"Quizzes/Quiz 5/Quiz5_Johnson.py","file_name":"Quiz5_Johnson.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455458303","text":"###############################################################################\n### This example need a card with default Masterkey\n### Than do the follow things\n### - Format card all data will be lost\n### - Create app with ID 00AE16\n### - Select app\n### - Change key 0, app masterkey\n### - Change setting key 1 need to change other keys\n### - Change key 1\n### - Auth key 1\n### - Change key 2,3,4\n### - Create file ID 0\n### - Auth key 3\n### - Write data file ID 0\n### - Auth key 4\n### - Read data file ID 0\n\nfrom __future__ import print_function\n\nimport functools\nimport logging\nimport time\nimport sys\n\nfrom smartcard.System import readers\nfrom smartcard.CardMonitoring import CardMonitor, CardObserver\nfrom smartcard.util import toHexString\nfrom smartcard.CardConnectionObserver import ConsoleCardConnectionObserver\n\nfrom Desfire.DESFire import *\nfrom Desfire.util import byte_array_to_human_readable_hex\nfrom Desfire.pcsc import PCSCDevice\n\nIGNORE_EXCEPTIONS = (KeyboardInterrupt, MemoryError,)\n\n\ndef catch_gracefully():\n \"\"\"Function decorator to show any Python exceptions occured inside a function.\n\n Use when the underlying thread main loop does not provide satisfying exception output.\n \"\"\"\n def _outer(func):\n\n @functools.wraps(func)\n def _inner(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except Exception as e:\n if isinstance(e, IGNORE_EXCEPTIONS):\n raise\n else:\n logger.error(\"Catched exception %s when running %s\", e, func)\n logger.exception(e)\n\n return _inner\n\n return _outer\n\n\nclass MyObserver(CardObserver):\n \"\"\"Observe when a card is inserted. Then try to run DESFire application listing against it.\"\"\"\n\n # We need to have our own exception handling for this as the\n # # main loop of pyscard doesn't seem to do any exception output by default\n @catch_gracefully()\n def update(self, observable, actions):\n\n (addedcards, removedcards) = actions\n\n for card in addedcards:\n logger.info(\"+ Inserted: %s\", toHexString(card.atr))\n\n connection = card.createConnection()\n connection.connect()\n\n # This will log raw card traffic to console\n connection.addObserver(ConsoleCardConnectionObserver())\n # connection object itself is CardConnectionDecorator wrapper\n # and we need to address the underlying connection object\n # directly\n logger.info(\"Opened connection %s\", connection.component)\n desfire = DESFire(PCSCDevice(connection.component))\n key_setting=desfire.getKeySetting()\n logger.info('Auth Key %d',0)\n info=desfire.getCardVersion()\n logger.info(info)\n default_key=desfire.createKeySetting('00 00 00 00 00 00 00 00',0,DESFireKeyType.DF_KEY_2K3DES,[])\n try:\n desfire.authenticate(0,default_key)\n except DESFireCommunicationError as DCE:\n key = input('Key in Hex:')\n default_key=desfire.createKeySetting(key,0,DESFireKeyType.DF_KEY_2K3DES,[])\n desfire.authenticate(0,default_key)\n logger.info('Format card')\n desfire.formatCard()\n new_picc=desfire.getKeySetting()\n default_key_1=desfire.createKeySetting('00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00',0,DESFireKeyType.DF_KEY_2K3DES,[])\n\n new_picc.setKey('01 23 45 67 89 AB CD EF 02 13 46 57 8A 9B CE DF')\n desfire.changeKey(0,new_picc,default_key_1)\n logger.info('Create application with ID 00AE16')\n desfire.createApplication(\"00 AE 16\",[DESFireKeySettings.KS_ALLOW_CHANGE_MK,DESFireKeySettings.KS_LISTING_WITHOUT_MK,DESFireKeySettings.KS_CONFIGURATION_CHANGEABLE],14,DESFireKeyType.DF_KEY_AES)\n logger.info('Select application with ID 00AE16')\n desfire.selectApplication('00 AE 16')\n default_app_key=desfire.createKeySetting('00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00',0,DESFireKeyType.DF_KEY_AES,[])\n app_key=desfire.createKeySetting('00 10 20 31 40 50 60 70 80 90 A0 B0 B0 A0 90 80',0,DESFireKeyType.DF_KEY_AES,[])\n logger.info('Auth Key %d',0)\n try:\n desfire.authenticate(0,default_app_key)\n except DESFireCommunicationError as DCE:\n key = input('Key in Hex:')\n default_app_key=desfire.createKeySetting(key,0,DESFireKeyType.DF_KEY_AES,[])\n desfire.authenticate(0,default_key)\n\n logger.info('Cange Key %d',0)\n desfire.changeKey(0,app_key,default_app_key)\n logger.info('Auth Key %d',0)\n desfire.authenticate(0,app_key)\n desfire.changeKeySettings([ DESFireKeySettings.KS_ALLOW_CHANGE_MK, DESFireKeySettings.KS_CONFIGURATION_CHANGEABLE, DESFireKeySettings.KS_CHANGE_KEY_WITH_KEY_1])\n app_key_1=desfire.createKeySetting('11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF 00',0,DESFireKeyType.DF_KEY_AES,[])\n logger.info('Cange Key %d',1)\n desfire.changeKey(1,app_key_1,default_app_key)\n logger.info('Auth Key %d',1)\n desfire.authenticate(1,app_key_1)\n app_key_2=desfire.createKeySetting('22 33 44 55 66 77 88 99 AA BB CC DD EE FF 00 11',0,DESFireKeyType.DF_KEY_AES,[])\n logger.info('Cange Key %d',2)\n desfire.changeKey(2,app_key_2,default_app_key)\n app_key_3=desfire.createKeySetting('33 44 55 66 77 88 99 AA BB CC DD EE FF 00 11 22',0,DESFireKeyType.DF_KEY_AES,[])\n logger.info('Cange Key %d',3)\n desfire.changeKey(3,app_key_3,default_app_key)\n app_key_4=desfire.createKeySetting('44 55 66 77 88 99 AA BB CC DD EE FF 00 11 22 33',0,DESFireKeyType.DF_KEY_AES,[])\n logger.info('Cange Key %d',4)\n desfire.changeKey(4,app_key_4,default_app_key)\n logger.info('Auth Key %d',0)\n desfire.authenticate(0,app_key)\n filePerm=DESFireFilePermissions()\n filePerm.setPerm(0x04,0x03,0x0F,0x02) # key 4 read, key3 write, no key read and write, key2 change permissions\n logger.info('Creat File with ID %d and %d byte',0,32)\n desfire.createStdDataFile(0,filePerm,32) # file Id 0, length 32 byte\n logger.info('Auth Key %d',3)\n desfire.authenticate(3,app_key_3)\n write='00 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20'\n logger.info('Data write %s',write)\n desfire.writeFileData(0,0,32,write)\n logger.info('Auth Key %d',4)\n desfire.authenticate(4,app_key_4)\n read=desfire.readFileData(0,0,32)\n logger.info('Data read %s',byte_array_to_human_readable_hex(read))\n\n\n\n\n\n\n\ndef main():\n global logger\n\n logging.basicConfig(level=logging.DEBUG)\n logger = logging.getLogger(__name__)\n\n logger.info(\"Insert MIFARE Desfire card to any reader to get its applications.\")\n\n available_reader = readers()\n logger.info(\"Available readers: %s\", available_reader)\n if not available_reader:\n sys.exit(\"No smartcard readers detected\")\n\n cardmonitor = CardMonitor()\n cardobserver = MyObserver()\n cardmonitor.addObserver(cardobserver)\n\n while True:\n time.sleep(1)\n\n # don't forget to remove§ observer, or the\n # monitor will poll forever...\n cardmonitor.deleteObserver(cardobserver)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"example2.py","file_name":"example2.py","file_ext":"py","file_size_in_byte":7684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"521925489","text":"import os\n\n# Common compiler options.\ncflags = '-std=c99'\ncxxflags = '-std=c++14'\n#ccflags = (\n# '-Werror -Wfatal-errors -Wpedantic -pedantic-errors -Wall -Wextra '\n# '-Wno-missing-braces -Wno-strict-overflow -Wno-sign-compare ')\n\n# Additional compiler options per build variant.\ndebug = '-O0 -g '\ndevel = '-O3 '\nrelease = '-O3 -DNDEBUG '\n\n# Get options from the command line.\nvariant = ARGUMENTS.get('variant', 'Devel')\n\n# Assemble ccflags according to the build variant.\nccflags = '-Wfatal-errors '\nif variant == 'Debug':\n ccflags += debug\nelif variant == 'Devel':\n ccflags += devel\nelif variant == 'Release':\n ccflags += release\nelse:\n print('Invalid value for option variant: ' + variant + '.')\n print(\"Valid values are: ('Debug', 'Devel', 'Release')\")\n Exit(1)\n\n\n# Set construction variables in the default environment.\nDefaultEnvironment(\n CFLAGS = cflags,\n CXXFLAGS = cxxflags,\n CCFLAGS = ccflags,\n# CPPDEFINES = cppdefines,\n CPPPATH = ['./External/RoutingKit/include/', '#', './External/routing-framework/', './External/', './External/routing-framework/'],\n LIBPATH=['./External/RoutingKit/lib/'],\n ENV = {\n 'CPLUS_INCLUDE_PATH': os.environ.get('CPLUS_INCLUDE_PATH'),\n 'LIBRARY_PATH': os.environ.get('LIBRARY_PATH'),\n 'PATH': os.environ.get('PATH')})\n\np1 = Program(source=['OsmImport/Import.cpp'], LIBS=['cairo', 'routingkit'])\np2 = Program(source=['WebServer/SkiServer.cpp', 'External/mongoose/mongoose.c'])\n\nAlias('Import', p1)\nAlias('SkiServer', p2)\n","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"521299665","text":"from flask import Blueprint,render_template,flash,redirect,url_for\n# 导入表单注册类\nfrom App.forms import Register,Login,AgainActive\nfrom App.models import User # 导入User模型类\nfrom App.email import send_mail # 导入发送邮件的函数\nfrom flask_login import login_required,login_user,logout_user,current_user\nfrom datetime import datetime\n\n\nuser = Blueprint('user',__name__)\n\n\"\"\"\n注册步骤\n1. 创建模型类\n2. 加载flask-migrate扩展库\n3. 在视图函数中导入模型类\n4. 验证用户名是否存在\n5. 获取模板前台传递过来的数据\n6. 存储\n7. 明文密码加密存储\n8. 配置发送邮件扩展库和功能\n9. 发送邮件\n10. 消息闪现(发送成功,前去激活)\n\"\"\"\n\n\n\n@user.route('/register/',methods=['GET','POST'])\ndef register():\n # 实例化注册表单类\n form = Register()\n if form.validate_on_submit():\n # 实例化注册表单数据\n u = User(username=form.username.data,password=form.userpass.data,email=form.email.data)\n u.save()\n token = u.generate_token()\n # 发送邮件激活\n send_mail('账户激活',form.email.data,username=form.username.data,token=token)\n flash('注册成功,前去邮箱进行激活')\n # 成功,去登录\n return redirect(url_for('user.login'))\n return render_template('user/register.html',form=form)\n\n# 进行账户激活的视图\n@user.route('/active/')\ndef active(token):\n if User.check_token(token):\n flash('激活成功,请前去登录')\n # 激活成功,跳转到登录\n return redirect(url_for('user.login'))\n else:\n flash('激活失败,请重新激活')\n return redirect(url_for(''))\n\n\n\n\n# class =\"media-object\" src=\"{{ url_for('static',filename='upload/s_'+p.user.icon) }}\" alt=\"...\" width=\"100px\" >\n\n\n# 再次激活的视图\n@user.route('/again_active/',methods=['GET','POST'])\ndef again_active():\n form = AgainActive()\n if form.validate_on_submit():\n u = User.query.filter(User.username == form.username.data).first()\n if not u:\n flash('请输入正确的用户名或密码')\n elif not u.check_password(form.userpass.data):\n flash('请输入正确的用户名或密码')\n elif not u.confirm:\n token = u.generate_token()\n # 发送邮件激活\n send_mail('账户激活', u.email, username=form.username.data, token=token)\n flash('激活邮件发送成功,请前往激活')\n else:\n flash('该账户已经激活,请前去登录')\n return render_template('user/again_active.html',form=form)\n\n\n\"\"\"\n登录步骤\n1. 接收表单传递过来的数据\n2. 查询用户名的对象\n3. 判断用户名密码(错误的话给出提示),激活状态\n4. 登陆成功进行处理\n5. 登陆失败给出提示\n\"\"\"\n\n\n# 登录的视图\n@user.route('/login/',methods=['GET','POST'])\ndef login():\n form = Login()\n if form.validate_on_submit():\n u = User.query.filter(User.username == form.username.data).first()\n if not u:\n flash('请输入正确的用户名和密码')\n elif not u.confirm:\n flash('还未激活该账户,请前往激活')\n return redirect(url_for('user.again_active'))\n elif not u.check_password(form.userpass.data):\n flash('请输入正确的用户名或密码')\n else:\n flash('登录成功')\n # 修改上次登录时间\n u.lastLogin = datetime.utcnow()\n u.save()\n login_user(u,remember=form.remember.data) # 使用第三方扩展卡处理登陆状态的维持\n return redirect(url_for('main.index'))\n return render_template('user/login.html',form=form)\n\n\n\n# 退出登录\n@user.route('/logout/')\ndef logout():\n logout_user()\n flash('退出成功')\n return redirect(url_for('main.index'))\n\n\n\n# 测试login_required\n@user.route('/test/')\n@login_required\ndef test():\n return '必须登录才能访问'\n\n\n\"\"\"\n登陆成功后 在跳转到上次过来的路由地址\n\"\"\"","sub_path":"python/示例代码/4.Flask 博客项目/blog/App/views/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"549074976","text":"from functools import partial\nfrom pprint import pformat\nfrom urllib.parse import unquote, urlparse\nimport json\nimport logging\n\nfrom bs4 import BeautifulSoup\nfrom flask import flash, make_response, redirect, request, url_for\nfrom flask_admin import AdminIndexView, expose\nfrom flask_admin.babel import gettext\nfrom flask_admin.contrib.sqla import ModelView\nfrom flask_admin.form import rules\nfrom flask_admin.helpers import get_redirect_target\nfrom flask_admin.model.helpers import get_mdict_item_or_list\nfrom jinja2 import Markup, contextfunction\nfrom sqlalchemy.sql.expression import desc\nfrom wtforms import fields, validators\nimport humanize\n\nfrom . import api, models, filters, forms\n\n\nlog = logging.getLogger(__name__)\n\n\ndef date_formatter(view, context, model, name):\n date_data = getattr(model, name)\n humanized_date_data = humanize.naturaltime(date_data)\n return Markup(\n '{}'.format(\n date_data, humanized_date_data\n )\n )\n\n\ndef url_formatter(view, context, model, name):\n data = getattr(model, name)\n if not data:\n return ''\n templ = '{1}'\n return Markup(templ.format(data.value, unquote(str(data.value))))\n\n\nclass HomeView(AdminIndexView):\n\n @expose('/')\n def index(self):\n form = forms.IndexForm(request.args)\n if form.search_term.data:\n session = models.db.session\n manager = models.get_plugin_manager()\n plugin_inst = manager.getPluginByName(form.mode.data, category='mode')\n plugin_model = models.get_or_create(session, models.Plugin, path=plugin_inst.path)[0]\n form.mode.data = plugin_model\n session = models.db.session\n model, created = models.get_or_create(\n session, models.SearchQuery,\n search_term=form.search_term.data,\n page=form.page.data,\n mode=plugin_model\n )\n if not created and not form.disable_cache.data:\n page_size = len(model.match_results)\n return redirect(url_for(\n 'matchresult.index_view', page_size=page_size,\n flt0_search_query_search_term_equals=model.search_term,\n flt1_search_query_page_equals=model.page\n ))\n model = models.SearchQuery.create(form, session)\n if model:\n page_size = len(model.match_results)\n return redirect(url_for(\n 'matchresult.index_view', page_size=page_size,\n flt0_search_query_search_term_equals=model.search_term,\n flt1_search_query_page_equals=model.page\n ))\n flash(gettext('Search error.'), 'error')\n return self.render('gbooru_images_download/index.html', form=form)\n\n @expose('/u/')\n def url_redirect(self):\n \"\"\"View for single image url.\"\"\"\n url = request.args.get('u', None)\n session = models.db.session\n entry, created = models.get_or_create(session, models.Url, value=url)\n if created:\n session.add(entry)\n session.commit()\n if not entry.id:\n flash(gettext('Url id error.'), 'error')\n return redirect(url_for('admin.index'))\n return redirect(url_for('url.details_view', id=entry.id))\n\n\nclass NamespaceView(ModelView):\n\n column_editable_list = ('hidden', 'alias')\n column_list = ('created_at', 'hidden', 'value', 'alias', 'tag_count')\n column_filters = [\n 'created_at',\n 'value',\n 'hidden',\n ]\n column_formatters = {'created_at': date_formatter, }\n\n\nclass MatchResultView(ModelView):\n\n def _order_by(self, query, joins, sort_joins, sort_field, sort_desc):\n try:\n res = super()._order_by(query, joins, sort_joins, sort_field, sort_desc)\n except AttributeError as e:\n if sort_field.key not in ('url', 'thumbnail_url'):\n log.error('{}'.format(e), sort_field_key=sort_field.key)\n raise e\n if sort_field is not None:\n # Handle joins\n query, joins, alias = self._apply_path_joins(\n query, joins, sort_joins, inner_join=False)\n try:\n field = getattr(self.model, sort_field.key)\n if sort_desc:\n query = query.join(models.Url, field).order_by(desc(models.Url.value))\n else:\n query = query.join(models.Url, field).order_by(models.Url.value)\n except Exception as e:\n raise e\n return query, joins\n return res\n\n def _thumbnail_formatter(self, context, model, name):\n if not model.thumbnail_url:\n return\n return Markup('
{}
'.format(\n 'style=\"max-width:100%\"',\n model.thumbnail_url.value,\n Markup('
{}
'.format(\n ''.join([\n Markup('{2}'.format(\n url_for('admin.url_redirect', u=model.url.value),\n \"btn view-details-btn btn-default\",\n \"detail\"\n )),\n Markup('{2}'.format(\n url_for('url.edit_view', id=model.id),\n \"btn btn-default\",\n \"edit\"\n )),\n ])\n ))\n ))\n\n can_view_details = True\n can_set_page_size = True\n column_default_sort = ('created_at', True)\n column_exclude_list = ('thumbnail_url', )\n column_filters = [\n 'created_at',\n 'search_queries',\n 'tags',\n 'thumbnail_url',\n 'url',\n ]\n column_formatters = {\n 'created_at': date_formatter,\n 'thumbnail_url': url_formatter,\n 'thumbnail': _thumbnail_formatter,\n 'url': url_formatter,\n }\n column_labels = {\n 'url.value.netloc': 'Netloc',\n 'url.filename': 'Filename',\n 'url.ext': 'Ext',\n 'url.width': 'W',\n 'url.height': 'H',\n }\n column_list = (\n 'created_at',\n 'thumbnail',\n 'url.value.netloc',\n 'url.filename',\n 'url.ext',\n 'url.width',\n 'url.height',\n )\n column_sortable_list = ('created_at', 'url', 'thumbnail_url')\n named_filter_urls = True\n page_size = 100\n\n def create_model(self, form):\n try:\n models.get_or_create_match_result(\n self.session, url=form.url, thumbnail_url=form.thumbnail_url)\n model = self.model()\n form.populate_obj(model)\n # plugin.get_match_results(search_term, page, session)\n assert model.mode.category == 'mode'\n pm = api.get_plugin_manager()\n plugin = pm.getPluginByName(model.mode.name, model.mode.category)\n mrs = list(set(plugin.plugin_object.get_match_results(\n model.search_term, model.page, self.session)))\n model.match_results = mrs\n self.session.add(model)\n self._on_model_change(form, model, True)\n self.session.commit()\n except Exception as ex:\n if not self.handle_view_exception(ex):\n flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error')\n log.exception('Failed to create record.')\n self.session.rollback()\n return False\n else:\n self.after_model_change(form, model, True)\n return model\n\n\nclass NetlocView(ModelView):\n can_create = False\n can_edit = False\n can_set_page_size = True\n column_editable_list = ('hidden', )\n column_formatters = {'created_at': date_formatter}\n edit_modal = True\n form_columns = ('hidden', )\n form_excluded_columns = ['created_at', ]\n page_size = 100\n\n def get_list(self, page, sort_field, sort_desc, search, filters, page_size=None):\n query = self.session.query(models.Url.value).distinct()\n for item in query:\n n_model = models.get_or_create(self.session, self.model, value=item[0].netloc)[0]\n self.session.add(n_model)\n self.session.commit()\n res = super().get_list(page, sort_field, sort_desc, search, filters, page_size=None)\n return res\n\n\nclass PluginView(ModelView):\n\n can_edit = False\n can_create = False\n can_view_details = True\n column_default_sort = ('created_at', True)\n column_filters = [\n 'category',\n 'created_at',\n 'description',\n 'name',\n 'version',\n ]\n column_formatters = {\n 'created_at': date_formatter,\n 'website': lambda v, c, m, p: Markup(\n '{0}'.format(getattr(m, p))\n ),\n 'path': lambda v, c, m, p: Markup(\n '
{0}
'.format(\n getattr(m, p),\n ' '.join([\n 'white-space: pre-wrap;',\n 'white-space: -moz-pre-wrap;',\n 'white-space: -pre-wrap;',\n 'white-space: -o-pre-wrap;',\n 'word-wrap: break-word;',\n ])\n )\n ),\n 'category': lambda v, c, m, p: Markup(\n '{}'.format(\n url_for('plugin.index_view', flt2_2=getattr(m, p)),\n getattr(m, p)\n )\n ),\n }\n column_list = ('created_at', 'name', 'version', 'category', 'description')\n details_modal = True\n list_template = 'gbooru_images_download/plugin_list.html'\n\n @expose('/update')\n def index_update_view(self):\n return_url = get_redirect_target() or self.get_url('.index_view')\n manager = api.get_plugin_manager()\n keys = [\n 'name', 'version', 'description', 'author', 'website', 'copyright',\n 'categories', 'category']\n for plugin in manager.getAllPlugins():\n with self.session.no_autoflush:\n model = models.get_or_create(self.session, self.model, path=plugin.path)[0]\n # update record\n for key in keys:\n if getattr(plugin, key):\n if key == 'version':\n setattr(model, key, str(getattr(plugin, key)))\n else:\n setattr(model, key, getattr(plugin, key))\n self.session.add(model)\n self.session.commit()\n return redirect(return_url)\n\n\nclass ResponseView(ModelView):\n\n def _text_formatter(self, context, model, name):\n data = getattr(model, name)\n soup = BeautifulSoup(data, 'html.parser')\n code_section = '
{}
'.format(\n Markup.escape(soup.prettify(formatter='minimal'))\n )\n button = ''\n if data.strip():\n button = 'view text'.format(\n url_for('.details_text_view', id=model.id)\n )\n return Markup('{}
{}'.format(button, code_section))\n\n can_edit = False\n can_view_details = True\n column_default_sort = ('created_at', True)\n column_display_pk = True\n column_filters = [\n 'created_at',\n 'final_url',\n 'status_code',\n 'text',\n 'url',\n ]\n column_formatters = {\n 'created_at': date_formatter,\n 'final_url': url_formatter,\n 'headers': lambda v, c, m, p: Markup(\n '
{0}
'.format(\n json.dumps(getattr(m, p), indent=1),\n 'class=\"language-json\"',\n ' '.join([\n 'white-space: pre-wrap;',\n 'white-space: -moz-pre-wrap;',\n 'white-space: -pre-wrap;',\n 'white-space: -o-pre-wrap;',\n 'word-wrap: break-word;',\n ])\n )),\n 'method': lambda v, c, m, p: getattr(m, p).value,\n 'text': _text_formatter,\n 'url': url_formatter,\n }\n column_list = ('created_at', 'status_code', 'method', 'url', 'content_type')\n details_template = 'gbooru_images_download/response_details.html'\n form_columns = ('method', 'kwargs_json')\n form_create_rules = ('url_input', 'method', 'kwargs_json')\n form_overrides = {\n 'url_input': fields.StringField, 'kwargs_json': fields.TextAreaField, }\n form_widget_args = {\n 'method': {'class': 'radio'},\n 'kwargs_json': {'rows': 5},\n }\n list_template = 'gbooru_images_download/response_list.html'\n\n def create_model(self, form):\n model = self.model.create(\n url=form.url_input.data, method=form.method.data, session=self.session,\n kwargs_json=form.kwargs_json.data,\n on_model_change_func=lambda x: self._on_model_change(form, x, True),\n handle_view_exception=self.handle_view_exception,\n after_model_change_func=lambda x: self.after_model_change(form, x, True)\n )\n return model\n\n @expose('/details/text_.html')\n def details_text_view(self, id):\n return_url = get_redirect_target() or self.get_url('.index_view')\n # id = get_mdict_item_or_lit(request.args, 'id')\n if id is None:\n return redirect(return_url)\n model = self.get_one([id, ])\n if model is None:\n flash(gettext('Record does not exist.'), 'error')\n return redirect(return_url)\n resp = make_response(model.text)\n resp.mimetype = '; '.join(model.content_type)\n return resp\n\n def get_create_form(self):\n form = super().get_form()\n\n def json_check(form, field):\n data = form.data.strip()\n if data:\n try:\n json.loads(form.data)\n except Exception as e:\n message = 'Json check failed: {}'.format(str(e))\n raise validators.ValidationError(message)\n\n form.kwargs_json.kwargs['validators'].append(json_check)\n # RadioField can't be created on form_overrides\n # it need choices list to at init\n form.method = fields.RadioField(\n 'Method', [validators.required()],\n choices=[('head', ' head'), ('post', 'post'), ('get', 'get')])\n form.url_input = fields.StringField(\n 'Url', [validators.required(), validators.URL()])\n return form\n\n def get_details_columns(self):\n \"\"\"\n Uses `get_column_names` to get a list of tuples with the model\n field name and formatted name for the columns in `column_details_list`\n and not in `column_details_exclude_list`. If `column_details_list`\n is not set, the columns from `scaffold_list_columns` will be used.\n \"\"\"\n try:\n only_columns = self.column_details_list or self.scaffold_list_columns()\n except NotImplementedError:\n raise Exception('Please define column_details_list')\n\n return self.get_column_names(\n only_columns=only_columns,\n excluded_columns=self.column_details_exclude_list,\n )\n\n @contextfunction\n def get_detail_value(self, context, model, name):\n \"\"\"\n Returns the value to be displayed in the detail view\n\n :param context:\n :py:class:`jinja2.runtime.Context`\n :param model:\n Model instance\n :param name:\n Field name\n \"\"\"\n return super().get_detail_value(context, model, name)\n\n @expose('/parser')\n def parser_view(self):\n return_url = get_redirect_target() or self.get_url('response.index_view')\n plugin_category = 'mode'\n id = get_mdict_item_or_list(request.args, 'id')\n if not id:\n id = get_mdict_item_or_list(request.args, 'response')\n form = forms.ResponseParserForm()\n form.response.choices = [\n (x.id, \"id:{0.id} url:{0.url.value}\".format(x))\n for x in self.session.query(self.model).all()\n ]\n form.parser.choices = [\n (x.id, x.name)\n for x in self.session.query(models.Plugin).filter_by(category=plugin_category)\n ]\n resp_tmpl = partial(\n self.render, 'gbooru_images_download/response_parser.html',\n details_column=self._details_columns,\n get_value=self.get_detail_value,\n return_url=return_url,\n )\n if id is None:\n return resp_tmpl(form=form)\n model = self.get_one(id)\n if model is None:\n flash(gettext('Response record does not exist.'), 'error')\n return resp_tmpl(form=form)\n form.response.default = model.id\n parser_model_id = get_mdict_item_or_list(request.args, 'parser')\n parser_model = self.session.query(models.Plugin).filter_by(\n id=parser_model_id, category=plugin_category).first()\n parser_result = None\n if parser_model:\n form.parser.default = parser_model.id\n form.process()\n manager = api.get_plugin_manager()\n plugin = manager.getPluginByName(parser_model.name, category=plugin_category)\n get_match_results_dict = plugin.plugin_object.get_match_results_dict\n parser_result = get_match_results_dict(\n model.text, session=self.session, url=str(model.url.value))\n return resp_tmpl(\n model=model,\n form=form,\n parser_model=parser_model,\n parser_result_text=pformat(parser_result, width=120),\n parser_result=parser_result,\n )\n\n\nclass SearchQueryView(ModelView):\n \"\"\"Custom view for SearchQuery model.\"\"\"\n\n def _search_term_formatter(self, context, model, name):\n data = getattr(model, name)\n parsed_data = urlparse(data)\n if parsed_data.netloc and parsed_data.scheme in ('http', 'https'):\n return Markup('{0}'.format(data))\n return data\n\n def _match_result_formatter(self, context, model, name):\n data = len(model.match_results)\n return Markup('{}'.format(\n url_for(\n 'matchresult.index_view', page_size=data,\n flt0_search_query_search_term_equals=model.search_term,\n flt1_search_query_page_equals=model.page\n ),\n data\n ))\n\n column_formatters = {\n 'created_at': date_formatter,\n 'match result': _match_result_formatter,\n 'search_term': _search_term_formatter,\n }\n column_list = ('created_at', 'search_term', 'page', 'match result')\n column_searchable_list = ('page', 'search_term')\n column_sortable_list = ('created_at', 'search_term', 'page')\n column_filters = ('page', 'search_term')\n form_excluded_columns = ['created_at', 'match_results']\n\n def create_model(self, form):\n res = self.model.create(\n form=form, session=self.session,\n on_model_change_func=self._on_model_change,\n handle_view_exception=self.handle_view_exception,\n after_model_change_func=self.after_model_change\n )\n return res\n\n\nclass TagView(ModelView):\n \"\"\"Custom view for Tag model.\"\"\"\n\n can_view_details = True\n column_default_sort = ('created_at', True)\n column_filters = ('value', 'namespace.value')\n column_formatters = {\n 'created_at': date_formatter,\n 'urls': lambda v, c, m, p: len(m.urls),\n 'value': lambda v, c, m, p: Markup(\n '{}'.format(m.value)\n )\n }\n column_labels = {'namespace.value': 'Namespace'}\n column_list = ('created_at', 'namespace.value', 'value', 'urls')\n column_searchable_list = ('value', 'namespace.value')\n column_sortable_list = ('value', 'namespace.value', 'created_at')\n page_size = 100\n\n\nclass UrlView(ModelView):\n \"\"\"Custom view for ImageURL model.\"\"\"\n\n def _content_type_formatter(self, context, model, name):\n data = list(getattr(model, name))\n if data:\n return ', '.join(data)\n\n can_view_details = True\n can_set_page_size = True\n column_display_pk = True\n column_filters = [\n 'created_at',\n filters.FilteredImageUrl(\n models.Url, 'Filter list', options=(('1', 'Yes'), ('0', 'No')),\n ),\n filters.TagFilter(models.Url, 'Tag')\n ]\n column_formatters = {\n 'created_at': date_formatter,\n 'value': lambda v, c, m, p: Markup('{0}'.format(\n getattr(m, p), 'id=\"source-url\"'\n )),\n 'content_type': _content_type_formatter,\n }\n column_list = ('created_at', 'id', 'value', 'content_type')\n column_searchable_list = ('value', )\n details_template = 'gbooru_images_download/url_details.html'\n form_edit_rules = [\n rules.FieldSet(('value', 'tags'), 'Url'),\n # rules.FieldSet(('value', 'hidden', 'tags'), 'Url'),\n rules.FieldSet(('match_results', 'thumbnail_match_results'), 'Match Result'),\n rules.FieldSet(('responses', 'on_final_responses'), 'Response'),\n ]\n form_excluded_columns = ['created_at', ]\n form_overrides = dict(value=fields.StringField,)\n page_size = 100\n","sub_path":"gbooru_images_download/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"509193431","text":"#!/usr/bin/python\nimport os\nimport bz2\nimport argparse\nimport re\nimport urllib2\nfrom HTMLParser import HTMLParser\n\ntitle_in_other_languages = {}\nlist_of_title_in_other_languages = []\ndef get_all_languages_titles(titles_file, languages):\n '''Translates titles from txt-file to titles in given languages.\n Function is no longer used in favor of using QIDs.'''\n\n #get titles to translate\n titles = []\n f = open(titles_file, 'r')\n for line in f:\n line = line.replace(\"\\n\", \"\")\n titles.append(line)\n\n for title in titles:\n title_in_other_languages = get_title_in_other_languages(title, \"en\", languages)\n list_of_title_in_other_languages.append(title_in_other_languages)\n return list_of_title_in_other_languages\n\ndef get_title_in_other_languages(title, title_language, other_languages):\n '''Translates Wikipedia title from the specified language(e.g. en, de, fr, it,...) to other languages.\n Uses normalized titles via:\n https://www.wikidata.org/w/api.php?action=wbgetentities&sites=enwiki&titles=WIKIPEDIA-TITLE&normalize=1\n instead of\n https://www.wikidata.org/w/api.php?action=wbgetentities&sites=enwiki&titles=WIKIPEDIA-TITLE\n as this fixes wrong initial character capitalization, underscores (and possible more) (which may occur due to changed wikipedia titles), as can be read here:\n https://stackoverflow.com/questions/37024807/how-to-get-wikidata-id-for-an-wikipedia-article-by-api\n This function is no longer used in favor of translating QIDs(not titles) via get_QID_and_lang_to_title().'''\n\n def get_html_code(title, title_language):\n '''returns html code from \"https://www.wikidata.org/w/api.php?action=wbgetentities&sites=' + title_language + 'wiki&titles=' + title + '&normalize=1\"'''\n def open_url(url):\n try:\n req = urllib2.Request(url)\n http_response_object = urllib2.urlopen(req)\n return http_response_object\n except Exception as e:\n print(\"Error with url: \" + url)\n print(e)\n print(\"\\n\")\n\n url = 'https://www.wikidata.org/w/api.php?action=wbgetentities&sites=' + title_language + 'wiki&titles=' + title + '&normalize=1'\n\n http_response_object = open_url(url)\n html_as_bytes = http_response_object.read() #type: bytes\n html = html_as_bytes.decode(\"utf8\") #type: str\n\n return html\n\n title = title.replace(\" \", \"%20\") #anything else to replace for html in this url-part?\n title = title.replace(\"\", \"\")\n title = title.replace(\"\", \"\")\n\n html = get_html_code(title, title_language)\n html = html.split(\"\\n\")\n\n language_of_title = None\n title_in_other_languages = {}\n for line in html:\n #todo: check for possible redirect(\"from:\", \"to:\") and notify user of changed title\n if '"missing"' in line:\n print(\"ERROR! title \" + title + \" from language \" + title_language + \" was not found via the Wikidata API.\")\n if ('"code"' in line) and ('"params-illegal"' in line):\n print(\"ERROR! title \" + title + \" from language \" + title_language + \" resulted in a 'params-illegal'-Errorcode.\")\n if '"descriptions"' in line: #solves the problem that multiple lines consist of '\"language\": \"en\"', but only the first occurence is followed by the title\n break\n if language_of_title != None: #current line contains the title\n title_in_other_languages[language_of_title] = re.search(\"\\>\\"\\;(.*?)\\>\\"\\;(.*?)\\"\\;\\<\\/span\\>$\", line).group(2)\n language_of_title = None\n else:\n #check for errors\n if \""language"\" in line:\n for language in other_languages:\n if \""\" + language + \""\" in line:\n if language_of_title != None:\n print(\"ERROR! Multiple languages in line. This should never appear! Maybe the API changed => you need to manually change the code!\")\n print(\"Line:\")\n print(line)\n print(\"Second(or third or...) language found: \" + language)\n print(\"Complete html code:\")\n print(html)\n language_of_title = language #next line contains the title\n\n return title_in_other_languages\n\ndef get_QID_and_lang_to_title(QIDs, languages=[]):\n '''Converts list of QIDs to a dictionary(named \"QID_and_lang_to_title\") mapping each tuple (QID, language) to it's corresponding title, for all specified languages.\n If no languages are specified, all languages available for a QID will be included.\n Titles returned will be unescaped (e.g. \"'\" becomes \"'\").\n Only gets titles for languages named \"enwiki\", \"dewiki\",...; does not match \"enwikiquote\", \"enwikibooks\",...!'''\n\n def get_html_code(QID):\n '''returns html code from \"https://www.wikidata.org/w/api.php?action=wbgetentities&format=xml&props=sitelinks&ids=\" + QID'''\n def open_url(url):\n try:\n req = urllib2.Request(url)\n http_response_object = urllib2.urlopen(req)\n return http_response_object\n except Exception as e:\n print(\"Error with url: \" + url)\n print(e)\n print(\"\\n\")\n\n url = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=xml&props=sitelinks&ids=' + QID\n\n http_response_object = open_url(url)\n html_as_bytes = http_response_object.read() #type: bytes\n html = html_as_bytes.decode(\"utf8\") #type: str\n\n #for documentation purposes\n '''if not os.path.isfile(\"get_QID_and_lang_to_title \" + QID + \".txt\"): #since get_QID_and_lang_to_title() gets called twice\n file = open(\"get_QID_and_lang_to_title \" + QID + \".txt\", \"w\")\n file.write(html_as_bytes)\n file.close()'''\n\n return html\n\n QID_and_lang_to_title = {}\n for QID in QIDs:\n #search html code and look for titles\n html = get_html_code(QID)\n html = html.split(\"\\n\")\n for line in html:\n if \"SOME-TITLE\n or\n SOME-FORMULA-BUT-NO-TITLE\n No mixed line of title and formula is allowed.'''\n\n QIDs = []\n f = open(QID_file, 'r')\n for line in f:\n if re.match(\"^Q[1-9][0-9]*$\", line) != None: #line consists of only a QID like \"Q1234\"\n line = line.replace(\"\\n\", \"\")\n QIDs.append(line)\n\n return QIDs\n\ndef get_ifiles_and_lang(args_file, args_dir):\n '''Uses user input(input files and output directory) to determine which bz2-files to process\n - already processed bz2-files(=those found in the output directory) will be skipped.\n If no input files are specified, every bz2-file in the current directory will be used as input file.\n The input files need to begin with the language code followed by \"wiki\" -> \"enwiki\", \"dewiki\",... !\n Returns a list of the input files together with a list of the language codes.\n '''\n\n bz2_files = []\n languages = []\n if args_file == '': #use all .bz2-files as input, except for the case when the result was already calculated before and saved in the given output-dir\n files_in_current_dir = None\n for root, directories, f_names in os.walk(\"./\"):\n files_in_current_dir = f_names[:]\n break\n #remove files where the result has already been calculated & saved before\n for root, directories, f_names in os.walk(args_dir):\n for filename in f_names:\n if filename in files_in_current_dir:\n files_in_current_dir.remove(filename)\n print(\"Result for \" + filename + \" has already been calculated before and thus will be reused. If you don't want this behaviour, either delete/move the file from the given output-directory or choose another output-directory!\")\n break\n #only add .bz2-files\n for filename in files_in_current_dir:\n if filename.endswith(\".bz2\"):\n bz2_files.append(filename)\n languages.append(filename.split(\"wiki\")[0])\n else: #use only given file(s) as input\n for f in args_file:\n bz2_files.append(f)\n languages.append(f.split(\"wiki\")[0])\n\n return bz2_files, languages\n\ndef get_ofiles_and_lang(args_dir):\n '''Uses all bz2-files in the given output directory to determine the result_files(=already processed output files).\n These are not necessarily the same as the input files in case we reuse already processed output files.\n Returns the result_files as well as result_languages(=language codes = beginning of the filename, followed by \"wiki\").'''\n\n result_files = [] #not necessary the same as bz2_files(=input files) in case we reused results\n result_languages = []\n for root, directories, f_names in os.walk(args_dir):\n for f_name in f_names:\n if f_name.endswith(\".bz2\"):\n result_files.append(f_name)\n result_languages.append(f_name.split(\"wiki\")[0])\n break\n\n return result_files, result_languages\n\ndef get_formulae_dict(QID_and_lang_to_title, result_files, args_tags, args_dir, args_verbosity_level):\n '''Checks which formulae occur how often for each article in all its languages (on a single site, a formula will be counted only once).\n Returns formulae_dict - mapping each tuple (QID and formula) to number-of-occurences-of-formula.'''\n\n formulae_dict = {} #mapping the tuple (QID, formula) to the number of occurrences across different sites\n tags = args_tags.split(',')\n\n current_formula = \"\"\n\n for f_name in result_files:\n language = f_name.split(\"wiki\")[0]\n file = bz2.BZ2File(os.path.join(args_dir, f_name), 'r')\n found_QIDs = [] #for non-found-QIDs the formula \"\" will be saved - some titles will not be found a) if you prefiltered the bz2-file to only contain pages with formulae (=>it is correct to choose \"\" as the formula) b) if you have an old Dump and the title changed (=>beware that you might not want \"\" as the formula in that case!)\n for line in file:\n #search for title to save corresponding QID with the formulae that are contained in the lines after the title\n if \"\" in line:\n current_title = line[line.find(\"<title>\")+7 : line.find(\"\")]\n current_QID = None\n current_tag = None\n current_formula = \"\"\n formulae_found = [] #lists all formulae for the current title => every formula will only be counted once per page (this does currently not take similar formulae into account!->change program to use e.g. formulae_are_similar()!)\n\n #get QID of found title\n for (QID, lang), title in QID_and_lang_to_title.items():\n if (lang == language) and (title == current_title.decode('utf8')):\n current_QID = QID\n found_QIDs.append(QID)\n if args_verbosity_level > 1:\n print(\"Found title for formula_dict: \", QID, lang, title)\n\n elif (line == \"\\n\") and (current_formula == \"\"): #no formula was found in the Wikipedia article, because there either is no defining formula or it did not have a formula_indicator\n #add empty formula to dict\n current_formula = \"\"\n if current_formula not in formulae_found: #delete this if-clause all 3 times in this function if you want to count a reoccurring formula on one page multiple times instead of once\n formulae_found.append(current_formula)\n if formulae_dict.get((current_QID, current_formula)) == None: #formula didn't occur yet\n formulae_dict[(current_QID, current_formula)] = 1\n else:\n formulae_dict[(current_QID, current_formula)] += 1\n\n else: #line contains formula\n for tag in tags:\n #a) formula ends in current line\n if (current_tag != None) and (tag == current_tag):\n if (line.find(\"<\"+tag+\">\") == -1) and (line.find(\"\") != -1):#split() deals with being closed as \n current_formula += line[ : line.find(\"\")]\n #add formula to dict\n if current_formula not in formulae_found: #every formula will only be counted once per page\n formulae_found.append(current_formula)\n if formulae_dict.get((current_QID, current_formula)) == None: #formula didn't occur yet\n formulae_dict[(current_QID, current_formula)] = 1\n else:\n formulae_dict[(current_QID, current_formula)] += 1\n\n current_formula = \"\"\n current_tag = None\n break\n\n else:\n for tag in tags:\n #b) formula completely contained inside the current line\n if (line.find(\"<\"+tag+\">\") != -1) and (line.find(\"\") != -1):\n current_formula = line[line.find(\"<\"+tag+\">\") + 2 + len(tag) : line.find(\"\")]\n #add formula to dict\n if current_formula not in formulae_found: #every formula will only be counted once per page\n formulae_found.append(current_formula)\n if formulae_dict.get((current_QID, current_formula)) == None: #formula didn't occur yet\n formulae_dict[(current_QID, current_formula)] = 1\n else:\n formulae_dict[(current_QID, current_formula)] += 1\n\n current_formula = \"\"\n\n #c) formula starts in current line\n elif line.rfind(\"<\"+tag+\">\") > line.rfind(\"\"): #last opening tag after last closing tag\n current_formula = line[line.rfind(\"<\"+tag+\">\") + 2 + len(tag) : ]\n current_tag = tag\n\n #d) formula continues in current & next line\n elif (current_tag != None) and (tag == current_tag):\n if (line.find(\"<\"+current_tag+\">\") == -1) and (line.find(\"\") == -1):\n current_formula += line\n\n #choose \"\" as the formula for every non-found-title\n for (QID, lang), title in QID_and_lang_to_title.items():\n if (lang == language) and (QID not in found_QIDs):\n if args_verbosity_level > 0:\n print(\"Title '\" + title.encode('utf8') + \"' of language '\" + language + \"' was not found in the output-bz2-file, thus '' will be used as the found formula. This is probably your intention (=if the page didn't contain a formula), but it might be that the title changed, because you use an old dump!\")\n current_formula = \"\"\n if formulae_dict.get((QID, current_formula)) == None: #formula didn't occur yet\n formulae_dict[(QID, current_formula)] = 1\n else:\n formulae_dict[(QID, current_formula)] += 1\n\n return formulae_dict\n\ndef extract_titles_and_formulae(filename, splitsize, dir, tags, keywords):\n ''' The function gets the filename of the xml.bz2-file as input\n and returns every formula of each page that has a title(=keyword) '''\n\n formulae_indicators = ['=', '<', '>', '\\leq', '\\geq', '\\approx', '\\equiv']#todo: consider adding more! #todo: if no formula_indicator is found, choose first \"formula\"(that is longer than a few characters, so it won't be just a variable)!\n titles_found = [] #to check for missed titles\n\n if tags != '':\n tags = tags.split(',')\n else:\n tags = []\n\n # Check and create chunk diretory\n if not os.path.exists(dir):\n os.mkdir(dir)\n # Counters\n pagecount = 0\n filecount = 1\n header = \"\"\n footer = \"\"\n title_and_formulae = \"\"\n # open chunkfile in write mode\n chunkname = os.path.join(dir, filename)\n chunkfile = bz2.BZ2File(chunkname, 'w')\n # Read line by line\n bzfile = bz2.BZ2File(filename)\n\n # the header\n for line in bzfile:\n header += line\n if '' in line:\n break\n\n # and the rest\n for line in bzfile:\n try:\n line = line.decode(\"utf8\") #probably faster to use python3 and specify encoding=utf8 in bz2.open()! the bz2 module in python3 also supports multistreaming :) Also see https://pymotw.com/3/bz2/\n except Exception as e:\n print(e)\n print(\" decoding-ERROR! This shouldn't happen as the dump is supposed to be UTF-8 encoded. The error is in line:\")\n print(line)\n\n if ' tag not found\n #doublecheck if there really is not a single tag in the current line - happens, iff closing tag is different from opening tag(as is the case with ...) or the closing tag is misspelled or consists of extra spaces(as is the case with ~10 formulae in the whole enwiki)\n tag_and_position = [] #lists first found tag of the current line and the position of its occurence -> position of the first tag determines end of formula; remember: the found tag should be a closing tag of current_tag, but might not be due to e.g. a misspelling\n for tag2 in tags:\n if line.find('</'+tag2) != -1: #closing tag found\n if tag_and_position == []:\n tag_and_position = ['</'+tag2, line.find('</'+tag2)]\n else: #already found a tag => find out, which tag occured first\n if line.find('</'+tag2) < tag_and_position[1]:\n tag_and_position = ['</'+tag2, line.find('</'+tag2)]\n\n if line.find('<'+tag2) != -1: #opening tag found\n if tag_and_position == []:\n tag_and_position = ['<'+tag2, line.find('<'+tag2)]\n else: #already found a tag => find out, which tag occured first\n if line.find('<'+tag2) < tag_and_position[1]:\n tag_and_position = ['<'+tag2, line.find('<'+tag2)]\n\n if tag_and_position == []: #there really is no closing tag in the current line\n title_and_formulae = title_and_formulae + \"\\n\" + line.replace(\"\\n\", \"\")\n else:\n if (args.verbosity_level > 0) and (current_tag != \"math chem\"): #\"\" always gets closed with \"\", so there is no need to notify the user in that case\n print(\"Unexpectedly found tag \" + tag_and_position[0] + \" (to opening tag \" + current_tag + \" ) in line \" + line + \"!\")\n title_and_formulae = title_and_formulae + \"\\n\" + line[0:tag_and_position[1]] + \"\"\n current_tag = None\n\n else: #formula ends in this line\n title_and_formulae = title_and_formulae + \"\\n\" + line.split(r'</'+tag+'>')[0] + \"\" #does not find tags with spaces / misspelled tags yet!\n current_tag = None\n\n #search for formula that lies completely inside the current line\n for tag in tags:\n if ('<' + tag + '>' in line):\n pagecount += 1\n formulae = re.findall(r'<' + tag + r'>(.*?)</' + tag + r'>', line) #\".*?\" results in nongreedy search = shortest match\n for formula in formulae:\n for indicator in formulae_indicators:\n if indicator in formula:# => it is a \"real\" formula, not just a variable\n title_and_formulae = title_and_formulae + \"\\n\" + \"<\"+tag+\">\" + formula + \"\"\n\n if check_for_multiple_line_formula == 1:\n #find formula beginning in this line, but ending in the next\n for tag in tags:\n if current_tag == None:\n if line.rfind('<'+tag+'>') > line.rfind('</'+tag+'>'): #last opening tag is after the last closing tag\n title_and_formulae = title_and_formulae + \"\\n\" + \"<\"+tag+\">\" + (line.split(r'<'+tag+'>')[-1]).replace(\"\\n\", \"\")\n current_tag = tag\n\n check_for_multiple_line_formula = 0\n\n if '' in line:\n title_and_formulae += \"\\n\"\n\n #add empty line when no formula was found\n title_and_formulae_wo_l = title_and_formulae.replace(\"\\n\", \"\") #title_and_formulae without a linebreak\n if title_and_formulae_wo_l[len(title_and_formulae_wo_l)-8:len(title_and_formulae_wo_l)] == \"\": #title_and_formulae_wo_l ends with \" no formula found\n title_and_formulae += \"\\n\"\n\n if args.verbosity_level > 1:\n try:\n print(\"No formula found for title: \" + title_and_formulae.encode('utf8'))\n except Exception as e:\n print(e)\n\n if keyword_matched == 1:\n title_and_formulae = title_and_formulae.encode(\"utf8\")\n chunkfile.write(title_and_formulae)\n\n if args.verbosity_level > 1:\n print(title_and_formulae)\n title_and_formulae = \"\"\n\n if pagecount > splitsize:\n if args.verbosity_level > 1:\n print(\"New bz2-file number \" + pagecount + \" since number of matched pages reached splitsize = \" + splitsize)\n chunkfile.close()\n pagecount = 0\n filecount += 1\n chunkfile = bz2.BZ2File(chunkname(filecount), 'w')\n chunkfile.write(header)\n try:\n chunkfile.close()\n except:\n print('File already closed.')\n\n\n #check if every title was found\n if len(titles_found) != len(keywords):\n print(\"Error! Found \" + str(len(titles_found)) + \" titles of \" + str(len(keywords)) + \". This should not happen unless you prefiltered the input-bz2-file(s) (e.g. filtered all pages with -tags) or use an old Dump!\")\n if args.verbosity_level > 1:\n print(\" Titles found: \" + str(titles_found))\n print(\" All titles: \" + str(keywords))\n #check which titles were not found\n if args.verbosity_level > 0:\n for title in keywords:\n if title not in titles_found:\n try:\n print(\" Title '\" + title.encode('utf8') + \"' was not found in the input-bz2-file.\")\n except Exception as e:\n print(e)\n\ndef formulae_are_similar(gs_formula, i_formula):\n '''Returns true if formulae are the same after deleting every space characters(e.g. whitespaces, Latex-specifix space commands like \"\\,\" or \"\\!\" and commas at the end of the formula) and ignoring different notations for single indices(=with and without curly brackets)\n Reason: Formulae from Dump and from Wikidata Query differ slightly (and both also differ from the Wikipedia html source code).\n Problems: Does not yet delete more Latex-specific spaces as well as Latex-specific commands like \"\\rm\", '''\n\n #todo: delete Latex-specific commands like \"\\rm\" in the following code line. these might appear as part of the index => \"k_{\\rm B}\" -> \"k_{\\rm {B}}\" (part of the formula of \"Einstein relation (kinetic theory)\" in the html-Code) does not work properly yet!\n\n #todo: delete \"\\n\"\n\n #todo: two formulae \"A=B=C\" and \"A=C\" should probably be considered as being similar\n\n\n #delete Latex-spaces \"\\,\" and \"\\;\" and \"\\!\" and \"\\ \", they sometimes occur at the end before a comma in the Dump, but not in the html-code/GoldStandard #test if more Latex-spaces from https://www.latex-kurs.de/kurse/Extra/Abstaende_in_Latex.pdf occur in formulae!\n gs_formula = re.sub(r\"\\\\,\", \"\", gs_formula)\n i_formula = re.sub(r\"\\\\,\", \"\", i_formula)\n gs_formula = re.sub(r\"\\\\;\", \"\", gs_formula)\n i_formula = re.sub(r\"\\\\;\", \"\", i_formula)\n gs_formula = re.sub(r\"\\\\!\", \"\", gs_formula)\n i_formula = re.sub(r\"\\\\!\", \"\", i_formula)\n gs_formula = re.sub(r\"\\\\ \", \"\", gs_formula) #lookbehind to make sure we don't have a linebreak; counting the number of backslashes would be better to account for multiple linebreaks though!\n i_formula = re.sub(r\"\\\\ \", \"\", i_formula)\n\n #ignore different notations for single indices, which can be written in two notations in Latex: \"_i\" or \"_{i}\" or \"_\\alpha\" or \"_{\\alpha}\"\n gs_formula = re.sub(r'([_^])(\\\\[a-zA-Z]+?)(\\W)', r'\\g<1>{\\g<2>}\\g<3>', gs_formula)\n gs_formula = re.sub(r'([_^])(\\w)', r'\\g<1>{\\g<2>}', gs_formula)\n i_formula = re.sub(r'([_^])(\\\\[a-zA-Z]+?)(\\W)', r'\\g<1>{\\g<2>}\\g<3>', i_formula)\n i_formula = re.sub(r'([_^])(\\w)', r'\\g<1>{\\g<2>}', i_formula)\n\n #delete comma (seen in the Dump) & dot (seen in the Dump) & semicolon at end\n gs_formula = re.sub(\";$\", \"\", gs_formula)\n gs_formula = re.sub(\",$\", \"\", gs_formula)\n gs_formula = re.sub(\"\\.$\", \"\", gs_formula)\n i_formula = re.sub(\";$\", \"\", i_formula)\n i_formula = re.sub(\",$\", \"\", i_formula)\n i_formula = re.sub(\"\\.$\", \"\", i_formula)\n\n #delete unnecessary single backslash at the end (seen in html code)\n gs_formula = re.sub(r\"(\\\\\\\\)+\\\\$\", \"\\g<1>\", gs_formula) #delete single backslash, in case there are linebreaks before it\n gs_formula = re.sub(r\"(?<=[^\\\\])\\\\$\", \"\", gs_formula) #delete single backslash without linebreak before it/that's not part of a linebreak\n i_formula = re.sub(r\"(\\\\\\\\)+\\\\$\", \"\\g<1>\", i_formula)\n i_formula = re.sub(r\"(?<=[^\\\\])\\\\$\", \"\", i_formula)\n\n #delete whitespaces\n gs_formula = \"\".join(gs_formula.split()) #deletes all whitespaces(' \\t\\n\\r\\v\\f'); this doesn't include e.g. \"\\t\" from \"\\theta\" as intended, since we have the raw formulae strings as input\n i_formula = \"\".join(i_formula.split())\n\n\n #check if formulae are now equal and thus were similar at the beginning\n if gs_formula == i_formula:\n return True\n else:\n return False\n\ndef compare_files(input_file, gold_standard_file):\n '''Compares titles(or QIDs) & formulae from the two input files. Prints formulae from gold_standard_file that are missing in input_file.\n Also prints all formulae (that share the same title) that are different in the two files, if \"-v\" is used.\n Supports file-formats bz2 and txt.'''\n\n num_of_titles = {}\n num_of_titles[input_file] = 0\n num_of_titles[gold_standard_file] = 0\n TP = 0\n FP = 0\n FN = 0\n TN = 0\n\n missing_titles = []\n different_formulae = {} #maps titles to correct(Gold Standard) & wrong(input_file) formulae\n similar_formulae = {} #maps titles to correct(Gold Standard) & similar-but-not-exactly-the-same(input_file) formulae\n gs_dict = {} #maps titles to formulae from gold_standard_file\n i_dict = {} #maps titles to formulae from input_file\n\n #add title and formula to dict\n for filename in [input_file, gold_standard_file]:\n #open files depending on file-format\n file = None\n if filename.split(\".\")[-1] == \"bz2\":\n file = bz2.BZ2File(filename, 'r')\n else:\n file = open(filename, \"r\")\n\n #check if file contains titles or QIDs -> know which regex to search for\n file_contains_titles = False\n for line in file:\n if \"\" in line:\n file_contains_titles = True\n break\n\n #reset file pointer to read file again\n file.seek(0)\n\n title = \"\"\n formula = \"\"\n for line in file:\n if (file_contains_titles == True) and (\"\" in line): #line contains either \"ABC\" or \"ABC\"\n #delete empty spaces as well as \"\" at the beginning of the line if it occurs\n if re.search(r'(.*)', line) != None:\n title = re.search(r'[\\ ]*[\\ ]*(.*)', line).group(1)\n #delete empty spaces as well as \"\" at the end of the line if it occurs\n if re.search(r'(.*)', title) != None:\n title = re.search(r'(.*)[\\ ]*[\\ ]*', title).group(1)\n num_of_titles[filename] += 1\n elif (file_contains_titles == False) and (re.search(r'^Q[1-9][0-9]*[\\ ]*[0-9]*[\\ ]*$', line) != None): #line contains QID, e.g. Q1234\n title = re.search(r'^(Q[1-9][0-9]*)[\\ ]*[0-9]*[\\ ]*$', line).group(1)\n else: #line with formula\n formula = line\n #add title & formula to respective dict\n if filename == input_file:\n if i_dict.get(title) == None: #key not found\n i_dict[title] = formula.replace(\"\\n\", \"\")\n else:\n i_dict[title] += formula.replace(\"\\n\", \"\") #append formula to dict, since the formula spans multiple lines\n else: #filename == gold_standard_file\n if gs_dict.get(title) == None: #key not found\n gs_dict[title] = formula.replace(\"\\n\", \"\")\n else: #key already exists, because the formula spans multiple lines\n gs_dict[title] += formula.replace(\"\\n\", \"\") #append formula to dict, since the formula spans multiple lines\n file.close()\n\n #compare titles & formulae from the two dictionaries\n for gs_title, gs_formula in gs_dict.items():\n num_of_title_matches = 0 #to search for missing titles in i_file, possibly due to strange characters in the title => they weren't found by wikiFilter.py or find_formula.py\n for i_title, i_formula in i_dict.items():\n if (gs_title == i_title):# or titles_are_similar(gs_formula, i_formula):\n num_of_title_matches += 1\n if num_of_title_matches == 1:\n if gs_formula == i_formula:\n if gs_formula == \"\":\n TN += 1\n else:\n TP += 1\n elif formulae_are_similar(gs_formula, i_formula):\n similar_formulae[gs_title] = [gs_formula, i_formula]\n else:\n different_formulae[gs_title] = [gs_formula, i_formula]\n elif num_of_title_matches > 1:\n print(\"ERROR! Title appeared more than once in input_file: \", gs_title)\n\n if num_of_title_matches == 0:\n missing_titles.append(gs_title)\n\n #error handling\n if num_of_titles[gold_standard_file] - num_of_titles[input_file] < len(missing_titles):\n print(\"ERROR! Number of found titles doesn't match. Some of the titles of input_file don't match with those from gold_standard_file, probably because of special characters that have been changed for regex search( '-' to '.' etc) or because the the wikipedia titles changed. It can also be that the last line(formula) of input_file.txt is empty(=no formula found) - in that case add another empty line at the end! This needs to be fixed manually in the gold_standard_file. \\n Another (unlikely) cause might be a duplicated title in the input_file. \\n It could also be that you mixed up the input file with the gold standard file.\")\n print(\"num_of_titles[gold_standard_file]\", num_of_titles[gold_standard_file])\n print(\"num_of_titles[input_file]\", num_of_titles[input_file])\n print(\"len(missing_titles)\", len(missing_titles))\n elif num_of_titles[gold_standard_file] - num_of_titles[input_file] > len(missing_titles):\n print(\"ERROR! Number of found titles doesn't match at all. This shouldn't have happened.\")\n print(\"num_of_titles[gold_standard_file]\", num_of_titles[gold_standard_file])\n print(\"num_of_titles[input_file]\", num_of_titles[input_file])\n print(\"len(missing_titles)\", len(missing_titles))\n\n #print results\n if len(similar_formulae) != 0:\n print(\"Similar formulae: \")\n for title in similar_formulae.keys():\n print(\"Title \" + str(title) + \" has similar formulae:\")\n print(\" \" + '\"' + similar_formulae[title][0] + '\"')\n print(\" \" + '\"' + similar_formulae[title][1] + '\"')\n print(\"\")\n if len(different_formulae) != 0:\n for title in different_formulae.keys():\n if (different_formulae[title][0] != \"\") and (different_formulae[title][1] == \"\"):\n FN += 1\n else: #there either is no defining formula or the wrong formula was found\n FP += 1\n if args.verbosity_level > 1:\n print(title + \" has two different formulae:\\n \" + '\"' + different_formulae[title][0] + '\"' + \" in Gold Standard,\"+ \"\\n \" + '\"' + different_formulae[title][1] + '\"' + \" in input file.\")\n print(\"\")\n print(\"Number of titles with different formulae (FP+FN) = \" + str(FP+FN) + \", FP = \" + str(FP) + \", FN = \" + str(FN))\n print(\"Number of TP(similar formulae not included) = \" + str(TP))\n print(\"Number of similar formulae = \" + str(len(similar_formulae)))\n print(\"Number of TN = \" + str(TN))\n print(str(len(missing_titles)) + \" missing titles: \" + str(missing_titles))\n\nif __name__ == '__main__': # When the script is self run\n parser = argparse.ArgumentParser(description='Extract all formulae (defined as having a formula_indicator) from the wikipages that contain the titles corresponding to the given QIDs(loaded via \"-Q\"), in all specified languages(corresponding to the beginning of the bz2-filenames, e.g. \"enwiki....bz2\"). Afterwards extracts the most common formula for a wikipedia page (in all languages specified). Formulae occuring multiple times for a wikipedia page(in a single language) are counted only once!',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-f', '--filename', help='The bz2-file(s) to be filtered. Default: Use all bz2-files in current folder.',\n default='', type=str, dest='file', nargs='*')\n parser.add_argument('-s', '--splitsize', help='The number of pages contained in each split.',\n default=1000000, type=int, dest='size')\n parser.add_argument('-d', '--outputdir', help='The output directory name.',\n default='wout', type=str, dest='dir')\n parser.add_argument('-Q', '--QID_file', help='QID-file, containing one QID (e.g. \"Q1234\") in each line(other lines without QIDs can be mixed in). They will be translated to the titles in their respective languages and \"SOME_TITLE\" will be used as keywords. The languages will be taken from the beginning of the filenames, which thus must start with \"enwiki\"/\"dewiki\"/... for english/german/... ! \"enwikibooks\", \"enwikiquote\" etc. are not allowed!!!',\n default='', type=str, dest='QID_file')\n parser.add_argument('-t', '--tagname', help='Comma separated string of the tag names to search for; no spaces allowed.',\n default='math,ce,chem,math chem', type=str, dest='tags')\n parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0, dest='verbosity_level')\n parser.add_argument('-T', '--template', help='include all templates',\n action=\"store_true\", dest='template')#default=False\n\n args = parser.parse_args()\n\n #determine input bz2-file(s) & corresponding language(s)\n bz2_files, languages = get_ifiles_and_lang(args.file, args.dir)\n print(str(len(bz2_files)) + \" Input files: \" + str(bz2_files))\n print(str(len(languages)) + \" Languages: \" + str(languages))\n\n #get QIDs\n QIDs = read_QIDs_from_file(args.QID_file)\n QID_and_lang_to_title = get_QID_and_lang_to_title(QIDs, languages)\n if args.verbosity_level > 0:\n print(\"\\n\")\n print(\"QID_and_lang_to_title (len=\" + str(len(QID_and_lang_to_title)) + \") for extracting all formulae from bz2-files :\")\n print(QID_and_lang_to_title)\n print(\"\\n\")\n\n #extract titles with all formulae from bz2-files\n for filename in bz2_files:\n language = filename.split(\"wiki\")[0]\n titles = get_titles_for_language(language, QID_and_lang_to_title)\n if args.verbosity_level > 0:\n print(\"The following titles exist in language \" + language + \":\\n\" + str(titles) + \"\\n\")\n print(str(len(titles)) + \" pages (of \" + str(len(QIDs)) + \" QIDs) exist for language \" + language + \", equaling \" + str(float(len(titles))/float(len(QIDs)) * 100) + \"%. If this percentage is too low for most of your languages, you might need to add more languages to get good results!\")\n if len(titles) == 0:\n print(\"No wikipedia pages matching the QIDs exist for language \" + language + \"! This can happen with few QIDs (here \" + str(len(QIDs)) + \" )or small wikis.\")\n\n keywords = [ \"\" + title + \"\" for title in titles]\n extract_titles_and_formulae(filename, args.size, args.dir, args.tags, keywords)\n print(\"Done with file: \" + filename)\n\n\n #find bz2-files containing the results(all formulae for each article); needed in case we reuse results\n result_files, result_languages = get_ofiles_and_lang(args.dir)\n print(\"Checking \" + str(len(result_files)) + \" files for similar formulae: \" + str(result_files))\n #calculate QID_and_lang_to_title again, in case we are reusing results\n if languages.sort() != result_languages.sort():\n QID_and_lang_to_title = get_QID_and_lang_to_title(QIDs, result_languages) #has to be called again in case we reused results <=> not all languages are already included in QID_and_lang_to_title\n if args.verbosity_level > 0:\n print(\"\\nQID_and_lang_to_title (len=\" + len(QID_and_lang_to_title) + \") to be checked for most common formula:\")\n print(QID_and_lang_to_title)\n print(\"\\n\")\n\n\n #check which formula occurs how often for each QID (on a single wikipage, a formula will be counted only once)\n formulae_dict = get_formulae_dict(QID_and_lang_to_title, result_files, args.tags, args.dir, args.verbosity_level)\n if args.verbosity_level > 1:\n print(\"\\nAll formulae (QID, formula, #occurences):\")\n print(formulae_dict)\n print(\"\\n\")\n\n #find biggest number of occurrences for each QID\n print(\"Now checking for most common formula...\")\n most_common_formula_for_QID = {} #mappes QIDs to (formula, num_of_occ), where num_of_occ is the number of occurrences for the formula that occurrs the most\n for (QID, formula), occ in formulae_dict.items():\n if most_common_formula_for_QID.get(QID) == None: #first formula for a QID will always be added\n most_common_formula_for_QID[QID] = (formula, occ)\n elif most_common_formula_for_QID[QID][1] < occ: #found a formula that occurrs more often\n most_common_formula_for_QID[QID] = (formula, occ)\n if args.verbosity_level > 0:\n print(\"Most common formulae (QID, formula, #occurences):\")\n print(most_common_formula_for_QID)\n\n #print \"QID formula occ\" to txt-file\n with open(\"results.txt\", \"w\") as file:\n output_string = \"\"\n for QID in most_common_formula_for_QID.keys():\n output_string += QID + \" \" + str(most_common_formula_for_QID[QID][1]) + \"\\n\"\n output_string += most_common_formula_for_QID[QID][0] + \"\\n\"\n file.write(output_string)\n\n #evaluate results for TP, FP, FN, TN\n compare_files(\"results.txt\", args.QID_file)\n","sub_path":"Dumps filtered for tags/filtered for 100 QIDs/find_most_common_formula.py","file_name":"find_most_common_formula.py","file_ext":"py","file_size_in_byte":43756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"540458683","text":"import re\nfrom os import path\n\nfrom webtest import TestApp, TestRequest\n\nfrom pyramid.config import Configurator\n\nfrom pyramid.interfaces import ISessionFactory, IDebugLogger\nfrom pyramid.security import (remember, Allow, Authenticated, Everyone,\n ALL_PERMISSIONS)\nfrom pyramid.testing import DummyRequest, DummyResource\nfrom pyramid import testing\nimport redis\n\nfrom eduid_userdb.db import MongoDB\nfrom eduid_userdb.dashboard import UserDBWrapper\nfrom eduiddashboard.session import SessionFactory\nfrom eduiddashboard.testing import MongoTestCase, RedisTemporaryInstance\nfrom eduiddashboard.saml2 import includeme as saml2_includeme\nfrom eduid_am.celery import celery, get_attribute_manager\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass RootFactory(object):\n __acl__ = [\n (Allow, Everyone, ALL_PERMISSIONS),\n ]\n\n def __init__(self, request):\n self.request = request\n\n\nclass ObjectFactory(object):\n __acl__ = [\n (Allow, Authenticated, ALL_PERMISSIONS),\n ]\n\n def __init__(self, request):\n self.request = request\n\n\ndef get_db(settings):\n mongodb = MongoDB(db_uri=settings['mongo_uri'])\n logger.warning(\"Using a raw MongoDB instance: {!r} (mongo_uri: {!r})\".format(mongodb, settings['mongo_uri']))\n return mongodb.get_database()\n\n\ndef saml2_main(global_config, **settings):\n \"\"\" This function returns a WSGI application.\n\n This is only useful for saml2 testing\n\n \"\"\"\n settings = dict(settings)\n\n config = Configurator(settings=settings,\n root_factory=RootFactory)\n\n factory = SessionFactory(settings)\n config.set_session_factory(factory)\n\n config.include('pyramid_jinja2')\n _userdb = UserDBWrapper(config.registry.settings['mongo_uri'])\n config.registry.settings['userdb'] = _userdb\n config.add_request_method(lambda x: x.registry.settings['userdb'], 'userdb', reify=True)\n mongodb = MongoDB(db_uri=settings['mongo_uri'])\n authninfodb = MongoDB(db_uri=settings['mongo_uri'], db_name='authninfo')\n config.registry.settings['mongodb'] = mongodb\n config.registry.settings['authninfodb'] = authninfodb\n config.registry.settings['db_conn'] = mongodb.get_connection\n config.registry.settings['db'] = mongodb.get_database('eduid_dashboard')\n config.set_request_property(lambda x: x.registry.settings['mongodb'].get_database('eduid_dashboard'), 'db', reify=True)\n\n saml2_includeme(config)\n\n config.scan(ignore=[re.compile('.*tests.*').search, '.testing'])\n return config.make_wsgi_app()\n\n\ndef dummy_groups_callback(userid, request):\n return ['']\n\n\nclass Saml2RequestTests(MongoTestCase):\n \"\"\"Base TestCase for those tests usign saml2 that need a full environment\n setup\n \"\"\"\n\n def setUp(self, settings={}):\n super(Saml2RequestTests, self).setUp(celery, get_attribute_manager, userdb_use_old_format=True)\n\n self.settings = {\n 'saml2.settings_module': path.join(path.dirname(__file__),\n 'tests/data/saml2_settings.py'),\n 'saml2.login_redirect_url': '/',\n 'saml2.logout_redirect_url': '/',\n 'saml2.strip_saml_user_suffix': '@test',\n 'auth_tk_secret': '123456',\n 'testing': True,\n 'jinja2.directories': 'eduiddashboard:saml2/templates',\n 'jinja2.undefined': 'strict',\n 'jinja2.filters': \"\"\"\n route_url = pyramid_jinja2.filters:route_url_filter\n static_url = pyramid_jinja2.filters:static_url_filter\n \"\"\",\n 'session.key': 'sessid',\n 'session.secret': '123341234',\n 'session.cookie_domain': 'localhost',\n 'session.cookie_path': '/',\n 'session.cookie_max_age': '3600',\n 'session.cookie_httponly': True,\n 'session.cookie_secure': False,\n }\n self.settings.update(settings)\n\n if not self.settings.get('groups_callback', None):\n self.settings['groups_callback'] = dummy_groups_callback\n\n self.settings['mongo_uri'] = self.mongodb_uri('')\n\n self.redis_instance = RedisTemporaryInstance.get_instance()\n self.settings['REDIS_HOST'] = 'localhost'\n self.settings['REDIS_PORT'] = self.redis_instance._port\n self.settings['REDIS_DB'] = '0'\n self.redis_conn = redis.Redis(host='localhost',\n port=self.redis_instance._port, db=0)\n\n app = saml2_main({}, **self.settings)\n self.testapp = TestApp(app)\n\n self.config = testing.setUp()\n self.config.registry.settings = self.settings\n self.config.registry.registerUtility(self, IDebugLogger)\n self.userdb = app.registry.settings['userdb']\n self.db = app.registry.settings['db']\n\n def tearDown(self):\n super(Saml2RequestTests, self).tearDown()\n for k in self.redis_conn.keys():\n self.redis_conn.delete(k)\n self.testapp.reset()\n\n def set_user_cookie(self, user_id):\n request = TestRequest.blank('', {})\n request.registry = self.testapp.app.registry\n remember_headers = remember(request, user_id)\n cookie_value = remember_headers[0][1].split('\"')[1]\n self.testapp.set_cookie('auth_tkt', cookie_value)\n return request\n\n def dummy_request(self):\n request = DummyRequest()\n request.context = DummyResource()\n request.userdb = self.userdb\n request.db = self.db\n request.registry.settings = self.settings\n return request\n\n def get_request_with_session(self):\n queryUtility = self.testapp.app.registry.queryUtility\n session_factory = queryUtility(ISessionFactory)\n\n request = self.dummy_request()\n session = session_factory(request)\n session.persist()\n self.testapp.set_cookie(self.settings['session.key'], session._session.token)\n self.pol = self.config.testing_securitypolicy(\n 'user', ('editors', ),\n permissive=False, remember_result=True)\n return request\n\n def get_fake_session_info(self, eppn=None):\n session_info = {\n 'authn_info': [\n ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', [])\n ],\n 'name_id': None,\n 'not_on_or_after': 1371671386,\n 'came_from': u'/',\n 'ava': {\n 'cn': ['John'],\n 'objectclass': ['top', 'inetOrgPerson', 'person', 'eduPerson'],\n 'userpassword': ['1234'],\n 'edupersonaffiliation': ['student'],\n 'sn': ['Smith'],\n 'mail': ['johnsmith@example.com'],\n 'eduPersonPrincipalName': ['hubba-bubba@test']\n },\n 'issuer': 'https://idp.example.com/saml/saml2/idp/metadata.php'\n }\n\n if eppn is not None:\n session_info['ava']['eduPersonPrincipalName'] = eppn\n\n return session_info\n","sub_path":"eduiddashboard/saml2/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":6985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"364076063","text":"# -*- coding: utf-8 -*-\r\n'''\r\nby 绝 2019.4.27\r\n\r\n'''\r\n\r\nfrom AirCom import *\r\n\r\nclass MDX(object):\r\n\r\n __字节流 = None\r\n __贴图数量 = 0\r\n\r\n def __init__(self, 文件):\r\n self.__file = 文件\r\n self.__打开文件()\r\n\r\n def __打开文件(self):\r\n # 二进制模式读取\r\n with open(self.__file, 'rb') as f:\r\n self.__字节流 = f.read()\r\n\r\n def 读取贴图路径(self):\r\n 字节流 = self.__字节流\r\n 出现位置 = 字节流.find(b'TEXS')\r\n 贴图数量 = 字节流[出现位置 + 4 + 1]\r\n 当前位置 = 出现位置+8\r\n 贴图路径组 = [字节流[当前位置+268*x:当前位置+268*x +\r\n 100].strip(b'\\x00').decode('utf-8', 'replace') for x in range(贴图数量)]\r\n 贴图路径组.insert(0, os.path.split(self.__file)[1])\r\n return 贴图路径组\r\n\r\n # decode('utf-8').encode('gb2312')..strip(\"\\x00\")\r\n\r\n\r\n\r\n\r\ndef 目录枚举(path, dest):\r\n files = os.listdir(path)\r\n for f in files:\r\n subpath = path + '\\\\' + f\r\n # 如果是文件\r\n if (os.path.isfile(subpath)):\r\n if os.path.splitext(subpath)[1] == \".mdx\":\r\n dest.append(subpath)\r\n # 如果是目录\r\n elif (os.path.isdir(subpath)):\r\n\r\n if (f[0] == '.'):\r\n pass\r\n else:\r\n # 递归\r\n 目录枚举(subpath, dest)\r\n\r\n # return self.__file\r\n\r\n\r\ndef 枚举所有模型路径():\r\n 路径 = r'C:\\DemoAir\\PY'\r\n 路径 = r'D:\\OneDrive\\War3\\模型\\资源\\微光战记'\r\n\r\n 路径组 = []\r\n 目录枚举(路径, 路径组)\r\n\r\n 贴图路径 = []\r\n for f in 路径组:\r\n print(f)\r\n a = MDX(f)\r\n 贴图路径.append(a.读取贴图路径())\r\n\r\n print(贴图路径)\r\n 写出文件(\"1.json\", 贴图路径)\r\n\r\n\r\nif __name__ == '__main__':\r\n 枚举所有模型路径()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n'''\r\nos.listdir 目录枚举\r\nos.path.isdir 是否目录\r\nos.path.splitext %~x0 分割文件名和后缀\r\nos.path.split %~nx0 分割路径和文件名 \r\n\r\n\r\n'''\r\n","sub_path":"mdx解析/mdx.py","file_name":"mdx.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"388742243","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom itertools import chain\n\nfrom MyHearthStone import ext\nfrom MyHearthStone.ext import Minion, Spell, Hero, HeroPower\nfrom MyHearthStone.ext import std_events\nfrom MyHearthStone.utils.game import Zone\n\n__author__ = 'fyabc'\n\n\n##############\n# Priest (5) #\n##############\n\n# Priest (4)\nclass Priest(Hero):\n data = {\n 'id': 4,\n 'klass': 5, 'hero_power': 4,\n }\n\n\nclass 次级治疗术(HeroPower):\n data = {\n 'id': 4,\n 'klass': 5, 'is_basic': True, 'cost': 2,\n 'po_tree': '$HaveTarget',\n }\n ext.add_dh_bonus_data(data, 2)\n\n def run(self, target, **kwargs):\n return [std_events.Healing(self.game, self, target, self.dh_values[0])]\n\n\n# 北郡牧师 (50000)\nclass 北郡牧师(Minion):\n data = {\n 'id': 50000,\n 'klass': 5, 'cost': 1, 'attack': 1, 'health': 3,\n }\n\n # TODO\n\n\n# 神圣惩击 (50001)\nclass 神圣惩击(Spell):\n data = {\n 'id': 50001,\n 'type': 1, 'klass': 5, 'cost': 1,\n 'po_tree': '$HaveTarget',\n }\n ext.add_dh_bonus_data(data, 2)\n\n def run(self, target, **kwargs):\n return [std_events.Damage(self.game, self, target, self.dh_values[0])]\n\n# 心灵视界 (50002)\n\n\n# 真言术:盾 (50003)\nclass 真言术_盾(Spell):\n data = {\n 'id': 50003,\n 'type': 1, 'klass': 5, 'cost': 1,\n 'po_tree': '$HaveTarget',\n }\n\n can_do_action = ext.require_minion\n check_target = ext.checker_minion\n\n def run(self, target, **kwargs):\n # TODO\n return []\n\n# 神圣之灵 (50004)\n\n\n# 心灵震爆 (50005)\nclass 心灵震爆(Spell):\n data = {\n 'id': 50005,\n 'type': 1, 'klass': 5, 'cost': 2,\n }\n ext.add_dh_bonus_data(data, 5)\n\n def run(self, target, **kwargs):\n return [std_events.Damage(self.game, self, self.game.get_hero(1 - self.player_id), self.dh_values[0])]\n\n\n# 暗言术:痛 (50006)\nclass 暗言术_痛(Spell):\n data = {\n 'id': 50006,\n 'type': 1, 'klass': 5, 'cost': 2,\n 'po_tree': '$HaveTarget',\n }\n\n can_do_action, check_target = ext.action_target_checker_factory_cond_minion(lambda target: target.attack <= 3)\n\n def run(self, target, **kwargs):\n target.to_be_destroyed = True\n return []\n\n# 暗言术:灭 (50007)\n\n# 神圣新星 (50008)\n\n\n# 精神控制 (50009)\nclass 精神控制(Spell):\n \"\"\"[NOTE]: This is a classic card of (permanent) mind control effect.\"\"\"\n data = {\n 'id': 50009,\n 'type': 1, 'klass': 5, 'cost': 10,\n 'po_tree': '$HaveTarget',\n }\n\n # TODO: Extract these condition-message pairs.\n can_do_action = ext.action_checker_factory_cond(\n (ext.have_enemy_minion, 'No enemy minions in play, and I can\\'t use it!'),\n (lambda self: not self.game.full(Zone.Play, self.player_id), 'I have too many minions, and I can\\'t use it!'),\n )\n check_target = ext.checker_enemy_minion\n\n def run(self, target, **kwargs):\n entity, status = self.game.move(target.player_id, target.zone, target, self.player_id, Zone.Play, 'last')\n return status['events']\n","sub_path":"HearthStone2/MyHearthStone/data/packages/basic/basic_priest.py","file_name":"basic_priest.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"554540874","text":"'''\nFile: testParser.py\nAuthor: Ashish Anand\nDescription: A file to test various functionality of HTML parser.\nTo check where will a tag land and how will it be handled when feed with html.\nDate: 2012-10-18 Thu 12:42 PM\n'''\nfrom html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n print(\"handle_starttag:\", tag)\n if tag.lower() == \"img\":\n for (key, val) in attrs:\n if key == \"alt\":\n print(\"Img Alt: \", val)\n if key == \"src\":\n print(\"Img Src: \", val)\n def handle_endtag(self, tag):\n print(\"handle_endtag :\", tag)\n def handle_data(self, data):\n print(\"handle_data :\", data)\n\np = MyHTMLParser(strict=False)\np.feed(\"\"\"\n Question Papers of NET \n June 2012\n \"\"\")\np.close()\ninput(\"...\")\n","sub_path":"webParsing/testParser.py","file_name":"testParser.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335895486","text":"import numpy as np\nimport os\nimport tensorflow as tf \n\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\n#Data reading and preprocessing function\ndef imgs_input_fn(path, mode, batch_size=15):\n imagepaths, imagelabels = [], []\n \n #List the directory\n classes = os.walk(path).__next__()[1]\n label = 0\n buffer_size = 0\n #List each sub-directory (the classes)\n for c in classes:\n c_dir = os.path.join(path,c)\n img_paths = os.walk(c_dir).__next__()[2]\n \n #Add each image to training set\n for image_path in img_paths:\n imagepaths.append(os.path.join(c_dir,image_path))\n imagelabels.append(label)\n buffer_size += 1\n \n label += 1\n \n imagepaths = tf.constant(imagepaths)\n imagelabels = tf.constant(imagelabels)\n \n def _parse_function(file, label):\n image_string = tf.read_file(file)\n image_decoded = tf.image.decode_jpeg(image_string)\n image_resized = tf.image.resize_images(image_decoded,[244,244])\n image_resized.set_shape([244, 244, 3])\n \n return image_resized, label\n \n def augment(image, label):\n augment_image = tf.random_crop(image, [244,244,3])\n augment_image = tf.image.random_flip_left_right(image)\n augment_image = tf.contrib.image.rotate(augment_image, 50)\n \n return augment_image, label\n \n dataset = tf.data.Dataset.from_tensor_slices((imagepaths,imagelabels))\n dataset = dataset.map(_parse_function)\n dataset = dataset.shuffle(buffer_size=buffer_size)\n \n #Create batches \n if mode == tf.estimator.ModeKeys.TRAIN:\n num_epochs = None\n dataset = dataset.map(augment)\n dataset = dataset.repeat(num_epochs).shuffle(buffer_size=buffer_size)\n else:\n num_epochs = 1\n \n dataset = dataset.repeat(num_epochs).batch(batch_size) \n iterator = dataset.make_one_shot_iterator() \n features, labels = iterator.get_next()\n labels = tf.reshape(labels,[-1, 1])\n \n return features, labels\n\ndef reset_graph(seed=42):\n tf.reset_default_graph()\n tf.set_random_seed(2)\n np.random.seed(2)\n\nreset_graph()\n\ndef cnn_model_fn(features, labels, mode):\n \n input_layer = tf.reshape(features, [-1 , 244, 244, 3])\n \n #Convolutional and Pooling layers\n conv1 = tf.layers.conv2d(input_layer, 16, 3, activation=tf.nn.relu)\n pool1 = tf.layers.max_pooling2d(conv1, 2, 2)\n\n conv2 = tf.layers.conv2d(pool1, 32, 3, activation=tf.nn.relu)\n pool2 = tf.layers.max_pooling2d(conv2, 2, 2)\n\n conv3 = tf.layers.conv2d(pool2, 64, 3, activation=tf.nn.relu)\n pool3 = tf.layers.max_pooling2d(conv3, 2, 2)\n \n #Dense layer\n flat = tf.contrib.layers.flatten(pool3)\n dense = tf.layers.dense(flat, 64, activation=tf.nn.relu)\n drop = tf.layers.dropout(dense, rate=0.3, training=mode == tf.estimator.ModeKeys.TRAIN)\n \n #Logits layer\n logits = tf.layers.dense(drop, 2)\n \n #Generate predictions\n predictions = {\"classes\": tf.argmax(input=logits, axis=1),\"probabilities\": tf.nn.softmax(logits, name=\"softmax_tensor\")}\n \n if mode == tf.estimator.ModeKeys.PREDICT:\n \n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n \n #Calculate Loss\n loss = tf.losses.sparse_softmax_cross_entropy(labels, logits)\n \n #Configure the Training Op\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.RMSPropOptimizer(learning_rate=0.001)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n \n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) \n \n #Add evaluation metrics\n eval_metric_ops = {\"accuracy\": tf.metrics.accuracy(labels=labels, predictions=predictions[\"classes\"])}\n \n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)\n\n#food_classifier = tf.keras.estimator.model_to_estimator(keras_model=model, model_dir='food_model')\neval_int = 50\n\nfood_classifier = tf.estimator.Estimator(model_fn=cnn_model_fn, model_dir='./food_model/food_notfood_trained',\n config=tf.estimator.RunConfig(save_checkpoints_secs=eval_int)) \n\ntrain_spec = tf.estimator.TrainSpec(input_fn= lambda: imgs_input_fn(\"./food_model/train\", mode=tf.estimator.ModeKeys.TRAIN), max_steps=60)\n\n#exporter = tf.estimator.LatestExporter('exporter', serving_input_fn)\n\neval_spec = tf.estimator.EvalSpec(input_fn= lambda: imgs_input_fn(\"./food_model/test\", mode=tf.estimator.ModeKeys.EVAL),\n start_delay_secs=eval_int, throttle_secs=eval_int)\n \ntf.estimator.train_and_evaluate(food_classifier, train_spec, eval_spec)\n\n\n#Pred data reading and preprocessing function\n#def img_input_fn(path):\n# imagepaths = []\n# \n# images = os.walk(path).__next__()[2]\n# for img in images:\n# img_path = os.path.join(path,img)\n# imagepaths.append(img_path)\n# \n# imagepaths = tf.constant(imagepaths)\n# \n# def _parse_function(file):\n# image_string = tf.read_file(file)\n# image_decoded = tf.image.decode_jpeg(image_string)\n# image_resized = tf.image.resize_images(image_decoded,[244,244])\n# image_resized.set_shape([244, 244, 3])\n# return image_resized\n# \n# dataset = tf.data.Dataset.from_tensor_slices(imagepaths)\n# dataset = dataset.map(_parse_function)\n# \n# iterator = dataset.make_one_shot_iterator() \n# features = iterator.get_next()\n# \n# return features\n\n#pred = food_classifier.predict(input_fn=lambda: img_input_fn(\"n\"))\n\n#for prediction in pred:\n \n# if prediction[\"classes\"] == 0:\n# print(\"Food\")\n# else:\n# print(\"Not Food\")\n\n","sub_path":"food_model/food_notfood.py","file_name":"food_notfood.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"245278822","text":"#\n# @lc app=leetcode.cn id=242 lang=python\n#\n# [242] 有效的字母异位词\n#\n# https://leetcode-cn.com/problems/valid-anagram/description/\n#\n# algorithms\n# Easy (50.29%)\n# Total Accepted: 23.9K\n# Total Submissions: 46.7K\n# Testcase Example: '\"anagram\"\\n\"nagaram\"'\n#\n# 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。\n# \n# 示例 1:\n# \n# 输入: s = \"anagram\", t = \"nagaram\"\n# 输出: true\n# \n# \n# 示例 2:\n# \n# 输入: s = \"rat\", t = \"car\"\n# 输出: false\n# \n# 说明:\n# 你可以假设字符串只包含小写字母。\n# \n# 进阶:\n# 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?\n# \n#\nclass Solution(object):\n def isAnagram(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) != len(t):\n return False\n map1 = {}\n map2 = {}\n for i in range(len(s)):\n map1[s[i]] = 1 if s[i] not in map1 else map1[s[i]] + 1\n map2[t[i]] = 1 if t[i] not in map2 else map2[t[i]] + 1\n return map1 == map2\n\n # if len(s) != len(t):\n # return False\n # for i in set(s):\n # if s.count(i) != t.count(i):\n # return False\n # return True\n\n","sub_path":"sort/242.有效的字母异位词.py","file_name":"242.有效的字母异位词.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343297809","text":"from django.db import models\r\nfrom PIL import ImageFile\r\nfrom django.utils.safestring import mark_safe\r\n# from ORDER.models import Order, TowarInOrder\r\n# from ORDER.models import TowarInOrder\r\n\r\nclass Status(models.Model):\r\n TYPES_CHOISES = (\r\n ('ready', 'доступен'),\r\n ('not_ready', 'недоступен'),\r\n ('allready', 'В разработке'),\r\n )\r\n mStatus = models.CharField(max_length=30, blank=True, null=True, default='ready', choices=TYPES_CHOISES)\r\n\r\n def __str__(self):\r\n return \"%s\" % self.mStatus\r\n\r\nclass Category_new(models.Model):\r\n\r\n TYPES_CHOISES = (\r\n ('pizza', 'Пицца'),\r\n ('sushi', 'Суши'),\r\n ('burger', 'Бургер'),\r\n ('drink', 'Напиток'),\r\n ('alcohol', 'Алкоголь')\r\n )\r\n\r\n category_key = models.CharField(max_length=30, default='pizza', blank=True, null=True, choices=TYPES_CHOISES, unique=True)\r\n is_active = models.BooleanField(default=True)\r\n # cat_type = str(category_key)\r\n\r\n def __str__(self):\r\n return \"%s\" % self.category_key\r\n\r\n class Meta:\r\n verbose_name = 'Категория товара:'\r\n verbose_name_plural = 'Категория товаров:'\r\n\r\n\r\nclass Towar(models.Model):\r\n category_new = models.ForeignKey(Category_new, blank=True, null=True, default=None, on_delete=models.CASCADE)\r\n # TYPES_CHOISES = (\r\n # ('1', 'Пицца'),\r\n # ('2', 'Суши'),\r\n # ('3', 'Бургер'),\r\n # ('4', 'Напиток'),\r\n # ('5', 'Алкоголь')\r\n # )\r\n # tovar_key = models.CharField(max_length=30, blank=True, null=True, default='1', choices=TYPES_CHOISES)\r\n name = models.CharField(max_length=30, blank=True, null=True, default='_')\r\n # created = models.BooleanField(default=True) #############################\r\n created = models.DateTimeField(auto_now_add=True, auto_now=False)\r\n updated = models.DateTimeField(auto_now_add=False, auto_now=True)\r\n is_active = models.BooleanField(default=True)\r\n is_delete = models.BooleanField(default=False)\r\n zena = models.DecimalField(max_digits=10, decimal_places=2, default=0)\r\n status = models.ForeignKey(Status, blank=True, null=True, default='ready', on_delete=models.CASCADE)\r\n # Под заказ\r\n # order = models.ForeignKey(Order_new, blank=True, null=True, default=1, on_delete=models.CASCADE)\r\n ves = models.IntegerField(default=0)\r\n description = models.TextField(max_length=300, blank=True, null=True, default=None)\r\n image = models.ImageField(blank=True, upload_to='media_true/%Y/%m/%d', help_text='150x150px', verbose_name='Ссылка картинки')\r\n\r\n def __str__(self):\r\n return \"%s\" % self.id\r\n # def save(self, *args, **kwargs):\r\n # # добавим сохранение инфы по цене и по количеству\r\n # print('SAVE')\r\n # print(self.order_new.zena)\r\n # for_one_pr = self.order_new.zena\r\n # self.for_one_price = for_one_pr\r\n # self.for_all_price = self.count * for_one_pr\r\n # print('2_SAVE_2')\r\n # super(TowarInOrder, self).save(*args, **kwargs)\r\n #\r\n # def save(self, *args, **kwargs):\r\n # # Переопределение метода сохранения\r\n # self._____ = self_____....\r\n # all_tovars = Tovars.objects.filter(___ = ___, is_active=True)\r\n #\r\n # for item in all_tovars:\r\n # ....\r\n # super(model, self).save(*args, **kwargs)\r\n\r\n\r\n\r\n # ВОТ КАК НАДО КАРТИНКУ ЗАГРУЖАТЬ\r\n def image_img(self):\r\n if self.image:\r\n return mark_safe(u''.format(self.image.url))\r\n else:\r\n return '(Нет изображения)'\r\n\r\n class Meta:\r\n verbose_name = 'Товар:'\r\n verbose_name_plural = 'Товары:'\r\n default_related_name = 'back_to_towar'\r\n\r\n image_img.short_description = 'Картинка'\r\n image_img.allow_tags = True\r\n\r\n\r\n\r\n\r\n# ВОТ КАК НАДО КАРТИНКУ ЗАГРУЖАТЬ","sub_path":"TOWARS/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"483918158","text":"import asyncpg\nfrom loguru import logger\nfrom functools import wraps\n\nfrom ..settings import settings\n\n\nasync def connect() -> asyncpg.Connection or bool:\n try:\n connection = await asyncpg.connect(\n host=settings.psql_host,\n port=settings.psql_port,\n user=settings.psql_user,\n password=settings.psql_password,\n database=settings.psql_db_name,\n timeout=60,\n )\n\n return connection\n\n except Exception as err:\n logger.error(\"Connection with DB failed\")\n logger.warning(err)\n\n return False\n\n\ndef sql_task(func):\n @wraps(func)\n async def wrapper(*args, **kwargs):\n connection = await connect()\n\n try:\n result = await func(connection, *args, **kwargs)\n except Exception as err:\n logger.error(\"SQL task could not be executed\")\n logger.warning(err)\n\n return False\n\n await connection.close()\n\n return result\n\n return wrapper\n","sub_path":"back-end/core/db/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"495999904","text":"import json\nimport pytest\nfrom app.connectors.arkiv_downloader.models import ArkivkopiRequest, ArkivkopiStatusResponse, ArkivkopiRequestBlobInfo\nfrom app.connectors.sas_generator.models import SASResponse\nfrom app.domain.models.Arkivkopi import ArkivkopiStatus, ArkivkopiRequestParameters\n\narkivkopi_id = 1\nstorage_account = \"storage_account_test\"\ncontainer = \"container_test\"\nsas_token = \"se=2020-12-05T14%3A40%3A54Z&sp=r&sv=2020-02-10&sr=c&sig=someSignature\"\nendpoint = \"localhost\"\nsource_name = \"some/random/file\"\ntarget_name_object = \"target_filename.tar\"\ntarget_name_archive = \"target_folder/\"\nstatus = ArkivkopiStatus.BESTILT\nblob_info = ArkivkopiRequestBlobInfo(source_name=source_name, target_name=target_name_archive)\n\n\n@pytest.fixture\ndef testobj_arkivkopi_request_with_blob(testobj_arkivkopi_request) -> ArkivkopiRequest:\n blob_info = ArkivkopiRequestBlobInfo(source_name=\"some/random/file\", target_name=\"target_filename.tar\")\n testobj_arkivkopi_request.blob_info = blob_info\n return testobj_arkivkopi_request\n\n\n@pytest.fixture\ndef arkivkopi_status_response():\n return ArkivkopiStatusResponse(arkivkopi_id=arkivkopi_id, status=status)\n\n\n@pytest.fixture\ndef sas_response():\n return SASResponse(storage_account, container, sas_token, endpoint)\n\n\ndef test_arkivkopirequest_equals(testobj_arkivkopi_request):\n result = ArkivkopiRequest(arkivkopi_id=arkivkopi_id, storage_account=storage_account,\n container=container, sas_token=sas_token)\n assert result == testobj_arkivkopi_request\n\n\ndef test_arkivkopirequest_not_equals(testobj_arkivkopi_request):\n arkivkopi_request_2 = ArkivkopiRequest(arkivkopi_id=arkivkopi_id + 1,\n storage_account=storage_account, container=container, sas_token=sas_token)\n assert testobj_arkivkopi_request != arkivkopi_request_2\n\n\ndef test_arkivkopirequest_from_parameters_when_archive(testobj_arkivkopi_request, sas_response):\n parameters = ArkivkopiRequestParameters(arkivkopi_id, sas_response)\n result = ArkivkopiRequest.from_parameters(parameters)\n assert testobj_arkivkopi_request == result\n\n\ndef test_arkivkopirequest_from_parameters_when_object(testobj_arkivkopi_request_with_blob, sas_response):\n parameters = ArkivkopiRequestParameters(arkivkopi_id, sas_response,\n source_name=source_name, target_name=target_name_object)\n result = ArkivkopiRequest.from_parameters(parameters)\n assert testobj_arkivkopi_request_with_blob == result\n\n\ndef test_arkivkopirequest_from_parameters_no_blob_info_when_missing_parameter(testobj_arkivkopi_request,\n sas_response):\n parameters_without_source_name = ArkivkopiRequestParameters(arkivkopi_id, sas_response,\n source_name=None, target_name=target_name_object)\n request_without_blob_info = ArkivkopiRequest.from_parameters(parameters_without_source_name)\n assert testobj_arkivkopi_request == request_without_blob_info\n\n\ndef test_arkivkopirequest_as_json(testobj_arkivkopi_request):\n result = testobj_arkivkopi_request.json()\n expected = json.dumps(testobj_arkivkopi_request.__dict__, default=lambda o: o.__dict__)\n assert expected == result\n\n\ndef test_arkivkopistatus_response_equals(arkivkopi_status_response):\n arkivkopi_status_response_2 = ArkivkopiStatusResponse(arkivkopi_id=arkivkopi_id, status=status)\n assert arkivkopi_status_response == arkivkopi_status_response_2\n\n\ndef test_arkivkopistatus_response_not_equals(arkivkopi_status_response):\n arkivkopi_status_response_2 = ArkivkopiStatusResponse(arkivkopi_id=arkivkopi_id + 1, status=status)\n assert arkivkopi_status_response != arkivkopi_status_response_2\n\n\ndef test_arkivkopistatus_response_not_equals_status(arkivkopi_status_response):\n arkivkopi_status_response_2 = ArkivkopiStatusResponse(arkivkopi_id=arkivkopi_id, status=ArkivkopiStatus.OK)\n assert arkivkopi_status_response != arkivkopi_status_response_2\n\n\ndef test_arkivkopistatus_response_from_string(arkivkopi_status_response):\n arkivkopi_status_response_str = '{\"arkivkopi_id\": ' + str(arkivkopi_id) + ', \"status\": \"' + status + '\"}'\n json_dict = json.loads(arkivkopi_status_response_str)\n arkivkopi_status_response_2 = ArkivkopiStatusResponse(**json_dict)\n assert arkivkopi_status_response == arkivkopi_status_response_2\n","sub_path":"mottak-arkiv-service/tests/connectors/arkiv_downloader/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558732023","text":"import webapp2\r\nfrom google.appengine.ext import db\r\nfrom gaesessions import get_current_session\r\n\r\nclass Movies5(db.Model):\r\n name = db.StringProperty()\r\n desc = db.TextProperty()\r\n rating = db.FloatProperty()\r\n origin = db.StringProperty()\r\n genre = db.StringProperty()\r\n typ = db.StringProperty()\r\n \r\n\r\nclass Users2(db.Model):\r\n username = db.StringProperty()\r\n password = db.StringProperty()\r\n\r\nclass Ratings(db.Model):\r\n username = db.StringProperty()\r\n name = db.StringProperty()\r\n rating = db.FloatProperty()\r\n \r\nclass Comments(db.Model):\r\n username = db.StringProperty()\r\n name = db.StringProperty()\r\n comment = db.StringProperty()\r\n\r\n \r\nclass Scomments(webapp2.RequestHandler):\r\n def get(self):\r\n session = get_current_session()\r\n usname = session.get('usname',\"\")\r\n \r\n if(len(usname)>1):\r\n name = self.request.get(\"movie\")\r\n comment = self.request.get(\"comment\")\r\n if(len(comment)>1):\r\n t = Comments(username = usname , name = name , comment = comment)\r\n t.put()\r\n ans = \"\"\r\n le = db.GqlQuery(\"SELECT * FROM Comments where name = :key\",key = name)\r\n ans += '''
\r\n \r\n \t\t\r\n'''\r\n for ch in le: \r\n ans += '''\"\r\n self.response.write(ans)\r\n else:\r\n self.response.write('Your comment seems blank')\r\n else:\r\n self.response.write(''''''+ \"Kindly login to Comment\")\r\n \r\n\r\napp = webapp2.WSGIApplication([\r\n ('/Scomments', Scomments)\r\n], debug=True)\r\n","sub_path":"Scomments.py","file_name":"Scomments.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383686910","text":"#5_GPIO_PyQt.py\nfrom gpiozero import LED, Button\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtWidgets import *\n\nled = LED(18)\nbutton = Button(24)\n\napp = QApplication([])\nwin = QMainWindow()\n\napp.setApplicationName(\"GPIO Control With GUI\")\nwin.resize(400,250)\nbar = win.statusBar()\nbar.showMessage(\"copyright(c) 2020 All rights reserved\")\n\n\nwin.resize(300,300)\nmb = win.menuBar()\nbye = QAction('EXIT',win)\nmb.addAction(bye)\n\n\nmain = QWidget()\nwin.setCentralWidget(main)\n\n\nonBtn = QPushButton(\"LED ON\")\noffBtn = QPushButton(\"LED OFF\")\nswBtn = QPushButton(\"Swtich Check\")\n#remove ; off\nbtnLayout = QHBoxLayout()\nbtnLayout.addWidget(onBtn)\nbtnLayout.addWidget(offBtn)\nbtnLayout.addWidget(swBtn)\nform = QFormLayout()\n#name = QLineEdit()\n\n#//pwform = QFormLayout()\npwname = QLineEdit()\n#pwform.addWidget(QLabel(\"pwform\"))\n\nform.addRow(btnLayout)\n\nmain.setLayout(form)\n\n \n\n\n#================\ndef onnled():\n print(\"LED ON!\")\n #================\n led.on()\n #================\n\ndef offled():\n print(\"LED OFF\")\n #================\n led.off()\n #================\n \ndef swcheck():\n if button.is_pressed:\n print(\"pressed!!!!\")\n else:\n print(\"released...\")\n\ndef byebye():\n print(\"EXIT\")\n quit()\n\n\nonBtn.clicked.connect(onnled)\noffBtn.clicked.connect(offled)\nswBtn.clicked.connect(swcheck)\n\n#menuAdd.triggered.connect(onnled)\n#menuRemove.triggered.connect(offled)\nbye.triggered.connect(byebye)\n#\n\n\nwin.show()\napp.exec()\n","sub_path":"1_example/D4/chp3_5_GPIO_PyQt.py","file_name":"chp3_5_GPIO_PyQt.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335692821","text":"import json\nimport requests\n\ndef main():\n data = {\"data1\":30, \"data2\":50}\n jsonString = json.dumps(data)\n res = requests.post(\"http://localhost:5000\",\n data={\"content\":jsonString})\n print(res)\n print(res.text)\n\nif __name__ == '__main__':\n main()\n","sub_path":"sendData.py","file_name":"sendData.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"483516775","text":"from django.views import View\r\nfrom django.shortcuts import render,redirect\r\nfrom django.shortcuts import get_object_or_404\r\nfrom onlineapp.models import *\r\nfrom django.views.generic import *\r\nfrom django import forms\r\nfrom django.urls import *\r\nfrom django.contrib.auth.mixins import LoginRequiredMixin,PermissionRequiredMixin\r\n\r\nclass CollegeView(View):\r\n def get(self,request,*args,**kargs):\r\n colleges = College.objects.all()\r\n return render(\r\n request,\r\n template_name=\"colleges.html\",\r\n context={\r\n \"jails\":colleges\r\n }\r\n )\r\n\r\nclass CollegeListView(LoginRequiredMixin,ListView):\r\n login_url = '/login/'\r\n model = College\r\n context_object_name = 'jails'\r\n template_name = \"colleges.html\"\r\n def get_context_data(self, **kwargs):\r\n context = super(CollegeListView, self).get_context_data(**kwargs)\r\n context['data'] = self.model.objects\r\n context.update({'user_permissions': self.request.user.get_all_permissions})\r\n return context\r\n\r\n\r\nclass CollegeDetailsView(DetailView):\r\n model = College\r\n template_name = \"studentdetails.html\"\r\n def get_object(self,queryset=None):\r\n return get_object_or_404(College,**self.kwargs)\r\n\r\n def get_context_data(self,**kargs):\r\n context = super(CollegeDetailsView, self).get_context_data(**kargs)\r\n college = context.get('college')\r\n\r\n students = list(college.student_set.order_by(\"-mocktest1__total\"))\r\n context.update({\r\n \"students\": students,\r\n 'user_permissions': self.request.user.get_all_permissions\r\n })\r\n return context\r\n\r\nclass AddCollege(forms.ModelForm):\r\n class Meta:\r\n model = College\r\n exclude = ['id']\r\n widgets = {\r\n 'name':forms.TextInput(),\r\n 'college':forms.TextInput(),\r\n 'location':forms.TextInput(),\r\n 'acronym':forms.TextInput(),\r\n }\r\n\r\nclass StudentForm(forms.ModelForm):\r\n class Meta:\r\n model = Student\r\n exclude = ['id','dob','college']\r\n widgets = {\r\n 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'enter'}),\r\n 'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'enter'}),\r\n 'db_folder': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'enter'}),\r\n 'dropped_out': forms.CheckboxInput(attrs={'class': 'form-control', 'placeholder': 'enter'}),\r\n }\r\n\r\nclass MockTestForm(forms.ModelForm):\r\n class Meta:\r\n model = MockTest1\r\n exclude = ['id','student','total']\r\n widgets = {\r\n 'problem1': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Score in problem 1'}),\r\n 'problem2': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Score in problem 2'}),\r\n 'problem3': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Score in problem 3'}),\r\n 'problem4': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Score in problem 4'}),\r\n }\r\n\r\nclass CreateCollegeView(CreateView):\r\n model=College\r\n form_class = AddCollege\r\n template_name =\"addcollege.html\"\r\n\r\n success_url = reverse_lazy('onlineapp:colleges_html')\r\n\r\n\r\nclass CreateStudentView(CreateView):\r\n model = Student\r\n form_class = StudentForm\r\n template_name = \"addstudent.html\"\r\n success_url = reverse_lazy('onlineapp:colleges_html')\r\n\r\n def get_context_data(self, **kwargs):\r\n context=super(CreateStudentView,self).get_context_data(**kwargs)\r\n test_form=MockTestForm()\r\n context.update(\r\n {'student_form':context.get('form'),\r\n 'test_form': test_form,\r\n })\r\n return context\r\n\r\n def post(self, request, *args, **kwargs):\r\n college = get_object_or_404(College, pk=kwargs.get('college_id'))\r\n student_form = StudentForm(request.POST)\r\n test_form = MockTestForm(request.POST)\r\n\r\n if student_form.is_valid():\r\n student = student_form.save(commit=False)\r\n student.college = college\r\n student.save()\r\n\r\n if test_form.is_valid():\r\n score = test_form.save(commit=False)\r\n score.total = sum(test_form.cleaned_data.values())\r\n score.student = student\r\n score.save()\r\n\r\n return redirect('onlineapp:studentdetails_html', college.id)\r\n\r\nclass UpdateCollegeView(UpdateView,PermissionRequiredMixin):\r\n\r\n model = College\r\n form_class = AddCollege\r\n template_name = \"addcollege.html\"\r\n success_url = reverse_lazy('onlineapp:colleges_html')\r\n def get_object(self,queryset=None):\r\n return get_object_or_404(College, **{'pk': self.kwargs.get('college_id')})\r\n\r\n def get_context_data(self, **kwargs):\r\n context = super(UpdateCollegeView, self).get_context_data(**kwargs)\r\n return context\r\n\r\nclass DeleteCollegeView(DeleteView):\r\n model = College\r\n success_url = reverse_lazy('onlineapp:colleges_html')\r\n\r\nclass UpdateStudentView(UpdateView):\r\n model = Student\r\n form_class = StudentForm\r\n template_name = 'edit_student_details.html'\r\n\r\n def get_context_data(self, **kwargs):\r\n context = super(UpdateStudentView, self).get_context_data(**kwargs)\r\n student_form = context.get('student')\r\n test_form = MockTestForm(instance=student_form.mocktest1)\r\n context.update({\r\n 'student_form': context.get('form'),\r\n 'test_form': test_form,\r\n })\r\n\r\n return context\r\n\r\n def post(self, request, *args, **kwargs):\r\n student = Student.objects.get(pk=kwargs.get('college_id'))\r\n form = StudentForm(request.POST, instance=student)\r\n test_form = MockTestForm(request.POST, instance=student.mocktest1)\r\n test = test_form.save(False)\r\n test.total = sum(test_form.cleaned_data.values())\r\n form.save()\r\n test_form.save()\r\n return redirect(\"onlineapp:studentdetails_html\", self.kwargs.get('college_id'))\r\n\r\nclass DeleteStudentView(DeleteView):\r\n model = Student\r\n #form_class = AddCollege\r\n template_name = \"deletecollege.html\"\r\n success_url = reverse_lazy('onlineapp:colleges_html')\r\n\r\n def get_object(self, queryset=None):\r\n return redirect('onlineapp:colleges_html')\r\n\r\n\r\n\r\n","sub_path":"Apps Course/onlineproject/onlineapp/views/college.py","file_name":"college.py","file_ext":"py","file_size_in_byte":6437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"220156125","text":"import sys\nimport os\nimport pathlib\nimport json\n\nfrom pprint import pprint\n\n\ndef read_text(text_file_path, dir_path):\n \n result = []\n \n with open(text_file_path, 'r', encoding='utf-8') as f:\n for line in f:\n data = line.strip().split()\n # print(data)\n \n key = data[0]\n value = \" \".join(data[1:])\n # print(\"K: {}, V: {}\".format(key, value))\n \n wav_path = os.path.join(dir_path.split('/')[1], key.split(\"_\")[1], key.split(\"_\")[0], key + \".trimmed.wav\")\n wav = str(pathlib.Path(wav_path))\n text = value\n speaker_id = key.split(\"_\")[0]\n \n sample = {\n \"wav\": wav,\n \"text\": text,\n \"speaker_id\": speaker_id\n }\n \n result.append(sample)\n \n # print(wav, text, speaker_id)\n \n # print(text_file_path, type(text_file_path))\n # print(text_file_path.relative_to('zeroth_korean/test_data_01'))\n \n return result\n \n\ndef text2json(dir_path, json_path):\n \n # 모든 하위 디렉토리 검색하여 txt 파일 목록 리스트화\n file_ext = r\"**/*.txt\"\n text_file_list = list(pathlib.Path(dir_path).glob(file_ext))\n print(\"text_list : {}\".format(text_file_list))\n print()\n \n # 모든 목록 작성 \n data_total = []\n for text_file_path in text_file_list:\n data = read_text(text_file_path, dir_path)\n data_total = data_total + data\n \n print()\n pprint(data_total)\n \n # 파일로 기록하기\n with open(json_path, 'w', encoding='utf-8') as f:\n f.write(json.dumps(data_total, indent=4, ensure_ascii=False))\n \n\n\nif __name__ == '__main__':\n \n text2json(sys.argv[1], sys.argv[2])","sub_path":"data/text2json.py","file_name":"text2json.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"378478995","text":"\"\"\"\nTimeseries\n----------\n\n`TimeSeries` is the main class in `darts`. It represents a univariate time series,\npossibly with lower and upper confidence bounds.\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom copy import deepcopy\nimport matplotlib.pyplot as plt\nfrom pandas.tseries.frequencies import to_offset\nfrom typing import Tuple, Optional, Callable, Any\n\nfrom .logging import raise_log, raise_if_not, get_logger\n\nlogger = get_logger(__name__)\n\n\nclass TimeSeries:\n def __init__(self,\n series: pd.Series,\n confidence_lo: Optional[pd.Series] = None,\n confidence_hi: Optional[pd.Series] = None,\n freq: Optional[str] = None,\n fill_missing_dates: Optional[bool] = True):\n \"\"\"\n A TimeSeries is an object representing a univariate time series, and optional confidence intervals.\n\n TimeSeries are meant to be immutable.\n\n Parameters\n ----------\n series\n The actual time series, as a pandas Series with a proper time index.\n confidence_lo\n Optionally, a Pandas Series representing lower confidence interval.\n confidence_hi\n Optionally, a Pandas Series representing upper confidence interval.\n freq\n Optionally, a string representing the frequency of the Pandas Series. When creating a TimeSeries\n instance with a length smaller than 3, this argument must be passed.\n fill_missing_dates\n Optionally, a boolean value indicating whether to fill missing dates with NaN values\n in case the frequency of `series` cannot be inferred.\n \"\"\"\n\n raise_if_not(len(series) > 0, 'Series must not be empty.', logger)\n raise_if_not(isinstance(series.index, pd.DatetimeIndex), 'Series must be indexed with a DatetimeIndex.', logger)\n raise_if_not(np.issubdtype(series.dtype, np.number), 'Series must contain numerical values.', logger)\n raise_if_not(len(series) >= 3 or freq is not None, 'Series must have at least 3 values if the \"freq\" argument'\n 'is not passed', logger)\n\n self._series = series.sort_index() # Sort by time\n\n if (len(series) < 3):\n self._freq: str = freq\n logger.info('A TimeSeries with length below 3 is being created. Please note that this can lead to'\n ' unexpected behavior.')\n else:\n if not series.index.inferred_freq:\n if fill_missing_dates:\n self._series = self._fill_missing_dates(self._series)\n else:\n raise_if_not(False, 'Could not infer frequency. Are some dates missing? '\n 'Try specifying `fill_missing_dates=True`.', logger)\n self._freq: str = self._series.index.inferred_freq # Infer frequency\n raise_if_not(freq is None or self._freq == freq, 'The inferred frequency does not match the'\n 'value of the \"freq\" argument.', logger)\n\n # TODO: are there some pandas Series where the line below causes issues?\n self._series.index.freq = self._freq # Set the inferred frequency in the Pandas series\n\n # The actual values\n self._values: np.ndarray = self._series.values\n\n # Handle confidence intervals:\n self._confidence_lo = None\n self._confidence_hi = None\n if confidence_lo is not None:\n self._confidence_lo = confidence_lo.sort_index()\n raise_if_not(len(self._confidence_lo) == len(self._series),\n 'Lower confidence interval must have same size as the main time series.', logger)\n raise_if_not((self._confidence_lo.index == self._series.index).all(),\n 'Lower confidence interval and main series must have the same time index.', logger)\n if confidence_hi is not None:\n self._confidence_hi = confidence_hi.sort_index()\n raise_if_not(len(self._confidence_hi) == len(self._series),\n 'Upper confidence interval must have same size as the main time series.', logger)\n raise_if_not((self._confidence_hi.index == self._series.index).all(),\n 'Upper confidence interval and main series must have the same time index.', logger)\n\n def pd_series(self) -> pd.Series:\n \"\"\"\n Returns\n -------\n pandas.Series\n A copy of the Pandas Series underlying this time series\n \"\"\"\n return self._series.copy()\n\n def conf_lo_pd_series(self) -> Optional[pd.Series]:\n \"\"\"\n Returns\n -------\n pandas.Series\n The underlying Pandas Series of the lower confidence interval if it exists.\n \"\"\"\n return self._confidence_lo.copy() if self._confidence_lo is not None else None\n\n def conf_hi_pd_series(self) -> Optional[pd.Series]:\n \"\"\"\n Returns\n -------\n pandas.Series\n The underlying Pandas Series of the upper confidence interval if it exists.\n \"\"\"\n return self._confidence_hi.copy() if self._confidence_hi is not None else None\n\n def start_time(self) -> pd.Timestamp:\n \"\"\"\n Returns\n -------\n pandas.Timestamp\n A timestamp containing the first time of the TimeSeries.\n \"\"\"\n return self._series.index[0]\n\n def end_time(self) -> pd.Timestamp:\n \"\"\"\n Returns\n -------\n pandas.Timestamp\n A timestamp containing the last time of the TimeSeries.\n \"\"\"\n return self._series.index[-1]\n\n def first_value(self) -> float:\n \"\"\"\n Returns\n -------\n float\n The first value of this series\n \"\"\"\n return self._values[0]\n\n def last_value(self) -> float:\n \"\"\"\n Returns\n -------\n float\n The last value of this series\n \"\"\"\n return self._values[-1]\n\n def values(self) -> np.ndarray:\n \"\"\"\n Returns\n -------\n numpy.ndarray\n A copy of the values composing the time series\n \"\"\"\n return np.copy(self._values)\n\n def time_index(self) -> pd.DatetimeIndex:\n \"\"\"\n Returns\n -------\n pandas.DatetimeIndex\n The time index of this series.\n \"\"\"\n return deepcopy(self._series.index)\n\n def freq(self) -> pd.DateOffset:\n \"\"\"\n Returns\n -------\n pandas.DateOffset\n The frequency of this series\n \"\"\"\n return to_offset(self._freq)\n\n def freq_str(self) -> str:\n \"\"\"\n Returns\n -------\n str\n A string representation of the frequency of this series\n \"\"\"\n return self._freq\n\n def duration(self) -> pd.Timedelta:\n \"\"\"\n Returns\n -------\n pandas.Timedelta\n The duration of this series.\n \"\"\"\n return self._series.index[-1] - self._series.index[0]\n\n def copy(self, deep: bool = True) -> 'TimeSeries':\n \"\"\"\n Make a copy of this time series object\n\n Parameters\n ----------\n deep\n Make a deep copy. If False, the underlying pandas Series will be the same\n\n Returns\n -------\n TimeSeries\n A copy of this time series.\n \"\"\"\n if deep:\n return TimeSeries(self.pd_series(), self.conf_lo_pd_series(), self.conf_hi_pd_series(), self.freq())\n else:\n return TimeSeries(self._series, self._confidence_lo, self._confidence_hi, self.freq())\n\n def _raise_if_not_within(self, ts: pd.Timestamp):\n if (ts < self.start_time()) or (ts > self.end_time()):\n raise_log(ValueError('Timestamp must be between {} and {}'.format(self.start_time(),\n self.end_time())), logger)\n\n def split_after(self, ts: pd.Timestamp) -> Tuple['TimeSeries', 'TimeSeries']:\n \"\"\"\n Splits the TimeSeries in two, around a provided timestamp `ts`.\n\n The timestamp may not be in the TimeSeries. If it is, the timestamp will be included in the\n first of the two TimeSeries, and not in the second.\n\n Parameters\n ----------\n ts\n The timestamp that indicates the splitting time.\n\n Returns\n -------\n Tuple[TimeSeries, TimeSeries]\n A tuple of two series. The first series is before `ts`, and the second one is after `ts`.\n \"\"\"\n self._raise_if_not_within(ts)\n ts = self.time_index()[self.time_index() <= ts][-1] # closest index before ts (new ts)\n start_second_series: pd.Timestamp = ts + self.freq() # second series does not include ts\n return self.slice(self.start_time(), ts), self.slice(start_second_series, self.end_time())\n\n def split_before(self, ts: pd.Timestamp) -> Tuple['TimeSeries', 'TimeSeries']:\n \"\"\"\n Splits a TimeSeries in two, around a provided timestamp `ts`.\n\n The timestamp may not be in the TimeSeries. If it is, the timestamp will be included in the\n second of the two TimeSeries, and not in the first.\n\n Parameters\n ----------\n ts\n The timestamp that indicates the splitting time.\n\n Returns\n -------\n Tuple[TimeSeries, TimeSeries]\n A tuple of two series. The first series is before `ts`, and the second one is after `ts`.\n \"\"\"\n self._raise_if_not_within(ts)\n ts = self.time_index()[self.time_index() >= ts][0] # closest index after ts (new ts)\n end_first_series: pd.Timestamp = ts - self.freq() # second series does not include ts\n return self.slice(self.start_time(), end_first_series), self.slice(ts, self.end_time())\n\n def drop_after(self, ts: pd.Timestamp) -> 'TimeSeries':\n \"\"\"\n Drops everything after the provided timestamp `ts`, included.\n The timestamp may not be in the TimeSeries. If it is, the timestamp will be dropped.\n\n Parameters\n ----------\n ts\n The timestamp that indicates cut-off time.\n\n Returns\n -------\n TimeSeries\n A new TimeSeries, before `ts`.\n \"\"\"\n self._raise_if_not_within(ts)\n ts = self.time_index()[self.time_index() >= ts][0] # closest index after ts (new ts)\n end_series: pd.Timestamp = ts - self.freq() # new series does not include ts\n return self.slice(self.start_time(), end_series)\n\n def drop_before(self, ts: pd.Timestamp) -> 'TimeSeries':\n \"\"\"\n Drops everything before the provided timestamp `ts`, included.\n The timestamp may not be in the TimeSeries. If it is, the timestamp will be dropped.\n\n Parameters\n ----------\n ts\n The timestamp that indicates cut-off time.\n\n Returns\n -------\n TimeSeries\n A new TimeSeries, after `ts`.\n \"\"\"\n self._raise_if_not_within(ts)\n ts = self.time_index()[self.time_index() <= ts][-1] # closest index before ts (new ts)\n start_series: pd.Timestamp = ts + self.freq() # new series does not include ts\n return self.slice(start_series, self.end_time())\n\n def slice(self, start_ts: pd.Timestamp, end_ts: pd.Timestamp) -> 'TimeSeries':\n \"\"\"\n Returns a new TimeSeries, starting later than `start_ts` and ending before `end_ts`, inclusive on both ends.\n The timestamps don't have to be in the series.\n\n Parameters\n ----------\n start_ts\n The timestamp that indicates the left cut-off.\n end_ts\n The timestamp that indicates the right cut-off.\n\n Returns\n -------\n TimeSeries\n A new series, with indices greater or equal than `start_ts` and smaller or equal than `end_ts`.\n \"\"\"\n raise_if_not(end_ts >= start_ts, 'End timestamp must be after start timestamp when slicing.', logger)\n raise_if_not(end_ts >= self.start_time(),\n 'End timestamp must be after the start of the time series when slicing.', logger)\n raise_if_not(start_ts <= self.end_time(),\n 'Start timestamp must be after the end of the time series when slicing.', logger)\n\n def _slice_not_none(s: Optional[pd.Series]) -> Optional[pd.Series]:\n if s is not None:\n s_a = s[s.index >= start_ts]\n return s_a[s_a.index <= end_ts]\n return None\n\n return TimeSeries(_slice_not_none(self._series),\n _slice_not_none(self._confidence_lo),\n _slice_not_none(self._confidence_hi),\n self.freq())\n\n def slice_n_points_after(self, start_ts: pd.Timestamp, n: int) -> 'TimeSeries':\n \"\"\"\n Returns a new TimeSeries, starting later than `start_ts` (included) and having at most `n` points.\n\n The timestamp may not be in the time series. If it is, it will be included in the new TimeSeries.\n\n Parameters\n ----------\n start_ts\n The timestamp that indicates the splitting time.\n n\n The maximal length of the new TimeSeries.\n\n Returns\n -------\n TimeSeries\n A new TimeSeries, with length at most `n` and indices greater or equal than `start_ts`.\n \"\"\"\n raise_if_not(n >= 0, 'n should be a positive integer.', logger) # TODO: logically raise if n<3, cf. init\n self._raise_if_not_within(start_ts)\n start_ts = self.time_index()[self.time_index() >= start_ts][0] # closest index after start_ts (new start_ts)\n end_ts: pd.Timestamp = start_ts + (n - 1) * self.freq() # (n-1) because slice() is inclusive on both sides\n return self.slice(start_ts, end_ts)\n\n def slice_n_points_before(self, end_ts: pd.Timestamp, n: int) -> 'TimeSeries':\n \"\"\"\n Returns a new TimeSeries, ending before `end_ts` (included) and having at most `n` points.\n\n The timestamp may not be in the TimeSeries. If it is, it will be included in the new TimeSeries.\n\n Parameters\n ----------\n end_ts\n The timestamp that indicates the splitting time.\n n\n The maximal length of the new time series.\n\n Returns\n -------\n TimeSeries\n A new TimeSeries, with length at most `n` and indices smaller or equal than `end_ts`.\n \"\"\"\n raise_if_not(n >= 0, 'n should be a positive integer.', logger)\n self._raise_if_not_within(end_ts)\n end_ts = self.time_index()[self.time_index() <= end_ts][-1]\n start_ts: pd.Timestamp = end_ts - (n - 1) * self.freq() # (n-1) because slice() is inclusive on both sides\n return self.slice(start_ts, end_ts)\n\n def slice_intersect(self, other: 'TimeSeries') -> 'TimeSeries':\n \"\"\"\n Returns a TimeSeries slice of this time series, where the time index has been intersected with the one\n provided in argument. Note that this method is in general *not* symmetric.\n\n Parameters\n ----------\n other\n the other time series\n\n Returns\n -------\n TimeSeries\n a new series, containing the values of this series, over the time-span common to both time series.\n \"\"\"\n time_index = self.time_index().intersection(other.time_index())\n return self.__getitem__(time_index)\n\n # TODO: other rescale? such as giving a ratio, or a specific position? Can be the same function\n def rescale_with_value(self, value_at_first_step: float) -> 'TimeSeries':\n \"\"\"\n Returns a new TimeSeries, which is a multiple of this TimeSeries such that\n the first value is `value_at_first_step`.\n (Note: numerical errors can appear with `value_at_first_step > 1e+24`).\n\n Parameters\n ----------\n value_at_first_step\n The new value for the first entry of the TimeSeries.\n\n Returns\n -------\n TimeSeries\n A new TimeSeries, where the first value is `value_at_first_step` and other values\n have been scaled accordingly.\n \"\"\"\n\n raise_if_not(self.values()[0] != 0, 'Cannot rescale with first value 0.', logger)\n\n coef = value_at_first_step / self.values()[0] # TODO: should the new TimeSeries have the same dtype?\n new_series = coef * self._series\n new_conf_lo = self._op_or_none(self._confidence_lo, lambda s: s * coef)\n new_conf_hi = self._op_or_none(self._confidence_hi, lambda s: s * coef)\n return TimeSeries(new_series, new_conf_lo, new_conf_hi, self.freq())\n\n def shift(self, n: int) -> 'TimeSeries':\n \"\"\"\n Shifts the time axis of this TimeSeries by `n` time steps.\n\n If :math:`n > 0`, shifts in the future. If :math:`n < 0`, shifts in the past.\n\n For example, with :math:`n=2` and `freq='M'`, March 2013 becomes May 2013.\n With :math:`n=-2`, March 2013 becomes Jan 2013.\n\n Parameters\n ----------\n n\n The signed number of time steps to shift by.\n\n Returns\n -------\n TimeSeries\n A new TimeSeries, with a shifted index.\n \"\"\"\n try:\n self.time_index()[-1] + n * self.freq()\n except pd.errors.OutOfBoundsDatetime:\n raise_log(OverflowError(\"the add operation between {} and {} will \"\n \"overflow\".format(n * self.freq(), self.time_index()[-1])), logger)\n new_time_index = self._series.index.map(lambda ts: ts + n * self.freq())\n new_series = self._series.copy()\n new_series.index = new_time_index\n new_conf_lo = None\n new_conf_hi = None\n if self._confidence_lo is not None:\n new_conf_lo = self._confidence_lo.copy()\n new_conf_lo.index = new_time_index\n if self._confidence_hi is not None:\n new_conf_hi = self._confidence_hi.copy()\n new_conf_hi.index = new_time_index\n return TimeSeries(new_series, new_conf_lo, new_conf_hi, self.freq())\n\n @staticmethod\n def from_dataframe(df: pd.DataFrame,\n time_col: Optional[str],\n value_col: str,\n conf_lo_col: str = None,\n conf_hi_col: str = None,\n freq: Optional[str] = None,\n fill_missing_dates: Optional[bool] = True) -> 'TimeSeries':\n \"\"\"\n Returns a TimeSeries built from a DataFrame.\n One column (or the DataFrame index) has to represent the time,\n and another column has to represent the values for this univariate time series.\n\n Parameters\n ----------\n df\n The DataFrame\n time_col\n The time column name (mandatory). If set to `None`, the DataFrame index will be used.\n value_col\n The value column name (mandatory).\n conf_lo_col\n The lower confidence interval column name (optional).\n conf_hi_col\n The upper confidence interval column name (optional).\n freq\n Optionally, a string representing the frequency of the Pandas Series.\n fill_missing_dates\n Optionally, a boolean value indicating whether to fill missing dates with NaN values\n in case the frequency of `series` cannot be inferred.\n\n Returns\n -------\n TimeSeries\n A TimeSeries constructed from the inputs.\n \"\"\"\n if time_col is None:\n times: pd.DatetimeIndex = pd.to_datetime(df.index, errors='raise')\n else:\n times: pd.Series = pd.to_datetime(df[time_col], errors='raise')\n series: pd.Series = pd.Series(df[value_col].values, index=times)\n\n conf_lo = pd.Series(df[conf_lo_col], index=times) if conf_lo_col is not None else None\n conf_hi = pd.Series(df[conf_hi_col], index=times) if conf_hi_col is not None else None\n\n return TimeSeries(series, conf_lo, conf_hi, freq, fill_missing_dates)\n\n @staticmethod\n def from_times_and_values(times: pd.DatetimeIndex,\n values: np.ndarray,\n confidence_lo: np.ndarray = None,\n confidence_hi: np.ndarray = None,\n freq: Optional[str] = None,\n fill_missing_dates: Optional[bool] = True) -> 'TimeSeries':\n \"\"\"\n Returns a TimeSeries built from an index and values.\n\n Parameters\n ----------\n times\n A `pandas.DateTimeIndex` representing the time axis for the time series.\n values\n An array of values for the TimeSeries.\n confidence_lo\n The lower confidence interval values (optional).\n confidence_hi\n The higher confidence interval values (optional).\n freq\n Optionally, a string representing the frequency of the Pandas Series.\n fill_missing_dates\n Optionally, a boolean value indicating whether to fill missing dates with NaN values\n in case the frequency of `series` cannot be inferred.\n\n Returns\n -------\n TimeSeries\n A TimeSeries constructed from the inputs.\n \"\"\"\n series = pd.Series(values, index=times)\n series_lo = pd.Series(confidence_lo, index=times) if confidence_lo is not None else None\n series_hi = pd.Series(confidence_hi, index=times) if confidence_hi is not None else None\n\n return TimeSeries(series, series_lo, series_hi, freq, fill_missing_dates)\n\n def plot(self,\n plot_ci: bool = True,\n new_plot: bool = False,\n *args,\n **kwargs):\n \"\"\"\n A wrapper method around `pandas.Series.plot()`.\n\n Parameters\n ----------\n plot_ci\n whether to plot the confidence intervals\n new_plot\n whether to spawn a new Figure\n args\n some positional arguments for the `plot()` method\n kwargs\n some keyword arguments for the `plot()` method\n \"\"\"\n\n fig = (plt.figure() if new_plot else (kwargs['figure'] if 'figure' in kwargs else plt.gcf()))\n kwargs['figure'] = fig\n self._series.plot(*args, **kwargs)\n x_label = self.time_index().name\n if x_label is not None and len(x_label) > 0:\n plt.xlabel(x_label)\n # TODO: use pandas plot in the future\n if plot_ci and self._confidence_lo is not None and self._confidence_hi is not None:\n plt.fill_between(self.time_index(), self._confidence_lo.values, self._confidence_hi.values, alpha=0.5)\n\n def has_same_time_as(self, other: 'TimeSeries') -> bool:\n \"\"\"\n Checks whether this TimeSeries and another one have the same index.\n\n Parameters\n ----------\n other\n the other series\n\n Returns\n -------\n bool\n True if both TimeSeries have the same index, False otherwise.\n \"\"\"\n if self.__len__() != len(other):\n return False\n return (other.time_index() == self.time_index()).all()\n\n def append(self, other: 'TimeSeries') -> 'TimeSeries':\n \"\"\"\n Appends another TimeSeries to this TimeSeries.\n\n Parameters\n ----------\n other\n A second TimeSeries.\n\n Returns\n -------\n TimeSeries\n A new TimeSeries, obtained by appending the second TimeSeries to the first.\n \"\"\"\n raise_if_not(other.start_time() == self.end_time() + self.freq(),\n 'Appended TimeSeries must start one time step after current one.', logger)\n # TODO additional check?\n raise_if_not(other.freq() == self.freq(),\n 'Appended TimeSeries must have the same frequency as the current one', logger)\n\n series = self._series.append(other.pd_series())\n conf_lo = None\n conf_hi = None\n if self._confidence_lo is not None and other.conf_lo_pd_series() is not None:\n conf_lo = self._confidence_lo.append(other.conf_lo_pd_series())\n if self._confidence_hi is not None and other.conf_hi_pd_series() is not None:\n conf_hi = self._confidence_hi.append(other.conf_hi_pd_series())\n return TimeSeries(series, conf_lo, conf_hi, self.freq())\n\n def append_values(self,\n values: np.ndarray,\n index: pd.DatetimeIndex = None,\n conf_lo: np.ndarray = None,\n conf_hi: np.ndarray = None) -> 'TimeSeries':\n \"\"\"\n Appends values to current TimeSeries, to the given indices.\n\n If no index is provided, assumes that it follows the original data.\n Does not add new confidence values if there were none first.\n Does not update value if already existing indices are provided.\n\n Parameters\n ----------\n values\n An array with the values to append.\n index\n A `pandas.DateTimeIndex` for the new values (optional)\n conf_lo\n The lower confidence interval values (optional).\n conf_hi\n The upper confidence interval values (optional).\n\n Returns\n -------\n TimeSeries\n A new TimeSeries with the new values appended\n \"\"\"\n if len(values) < 1:\n return self\n if isinstance(values, list):\n values = np.array(values)\n if index is None:\n index = pd.DatetimeIndex([self.end_time() + i * self.freq() for i in range(1, 1 + len(values))])\n raise_if_not(isinstance(index, pd.DatetimeIndex), 'Values must be indexed with a DatetimeIndex.', logger)\n raise_if_not(len(index) == len(values), 'Values and index must have same length.', logger)\n raise_if_not(self.time_index().intersection(index).empty, \"Cannot add already present time index.\", logger)\n new_indices = index.argsort()\n index = index[new_indices]\n # TODO do we really want that?\n raise_if_not(index[0] == self.end_time() + self.freq(),\n 'Appended index must start one time step after current one.', logger)\n if len(index) > 2:\n raise_if_not(index.inferred_freq == self.freq_str(),\n 'Appended index must have the same frequency as the current one.', logger)\n elif len(index) == 2:\n raise_if_not(index[-1] == index[0] + self.freq(),\n 'Appended index must have the same frequency as the current one.', logger)\n values = values[new_indices]\n new_series = pd.Series(values, index=index)\n series = self._series.append(new_series)\n if conf_lo is not None and self._confidence_lo is not None:\n raise_if_not(len(index) == len(conf_lo), 'Confidence intervals must have same length as index.', logger)\n conf_lo = conf_lo[new_indices]\n conf_lo = self._confidence_lo.append(pd.Series(conf_lo, index=index))\n if conf_hi is not None and self._confidence_hi is not None:\n raise_if_not(len(index) == len(conf_hi), 'Confidence intervals must have same length as index.', logger)\n conf_hi = conf_hi[new_indices]\n conf_hi = self._confidence_hi.append(pd.Series(conf_hi, index=index))\n\n return TimeSeries(series, conf_lo, conf_hi, self.freq())\n\n def update(self,\n index: pd.DatetimeIndex,\n values: np.ndarray = None,\n conf_lo: np.ndarray = None,\n conf_hi: np.ndarray = None,\n inplace: bool = False) -> 'TimeSeries':\n \"\"\"\n Updates the Series with the new values provided.\n If indices are not in original TimeSeries, they will be discarded.\n At least one parameter other than index must be filled.\n Use `numpy.nan` to ignore a specific index in a series.\n\n It will raise an error if try to update a missing CI series\n\n Parameters\n ----------\n index\n A `pandas.DateTimeIndex` containing the indices to replace.\n values\n An array containing the values to replace (optional).\n conf_lo\n The lower confidence interval values to change (optional).\n conf_hi\n The upper confidence interval values (optional).\n inplace\n If True, do operation inplace and return self, defaults to False.\n\n Returns\n -------\n TimeSeries\n A new TimeSeries (if `inplace = False`) or the same TimeSeries with values updated\n \"\"\"\n\n raise_if_not(not (values is None and conf_lo is None and conf_hi is None),\n \"At least one parameter must be filled other than index\", logger)\n raise_if_not(index is not None, \"Index must be filled.\")\n if (values is not None):\n raise_if_not(len(values) == len(index), \"The number of values must correspond \"\n \"to the number of indices: {} != {}\".format(len(values),\n len(index)), logger)\n if (conf_lo is not None):\n raise_if_not(len(conf_lo) == len(index), \"The number of values must correspond \"\n \"to the number of indices: \"\"{} != {}\".format(len(conf_lo),\n len(index)), logger)\n if (conf_hi is not None):\n raise_if_not(len(conf_hi) == len(index), \"The number of values must correspond \"\n \"to the number of indices: {} != {}\".format(len(conf_hi),\n len(index)), logger)\n ignored_indices = [index.get_loc(ind) for ind in (set(index) - set(self.time_index()))]\n index = index.delete(ignored_indices)\n series = values if values is None else pd.Series(np.delete(values, ignored_indices), index=index)\n conf_lo = conf_lo if conf_lo is None else pd.Series(np.delete(conf_lo, ignored_indices), index=index)\n conf_hi = conf_hi if conf_hi is None else pd.Series(np.delete(conf_hi, ignored_indices), index=index)\n raise_if_not(len(index) > 0, \"Must give at least one correct index.\", logger)\n if inplace:\n if series is not None:\n self._series.update(series)\n if conf_lo is not None:\n self._confidence_lo.update(conf_lo)\n if conf_hi is not None:\n self._confidence_hi.update(conf_hi)\n return self\n else:\n new_series = self.pd_series()\n new_lo = self.conf_lo_pd_series()\n new_hi = self.conf_hi_pd_series()\n if series is not None:\n new_series.update(series)\n if conf_lo is not None:\n new_lo.update(conf_lo)\n if conf_hi is not None:\n new_hi.update(conf_hi)\n return TimeSeries(new_series, new_lo, new_hi, self.freq())\n\n def resample(self, freq: str, method: str = 'pad') -> 'TimeSeries':\n \"\"\"\n Creates an reindexed time series with a given frequency.\n Provided method is used to fill holes in reindexed TimeSeries, by default 'pad'.\n\n Parameters\n ----------\n freq\n The new time difference between two adjacent entries in the returned TimeSeries.\n A DateOffset alias is expected.\n method:\n Method to fill holes in reindexed TimeSeries (note this does not fill NaNs that already were present):\n\n ‘pad’: propagate last valid observation forward to next valid\n\n ‘backfill’: use NEXT valid observation to fill.\n Returns\n -------\n TimeSeries\n A reindexed TimeSeries with given frequency.\n \"\"\"\n\n new_series = self.pd_series().asfreq(freq, method=method)\n new_conf_hi_series = self.conf_hi_pd_series()\n if new_conf_hi_series is not None:\n new_conf_hi_series = new_conf_hi_series.asfreq(freq, method=method)\n\n new_conf_lo_series = self.conf_lo_pd_series()\n if new_conf_lo_series is not None:\n new_conf_lo_series = new_conf_lo_series.asfreq(freq, method=method)\n return TimeSeries(new_series, new_conf_lo_series, new_conf_hi_series, freq)\n\n def is_within_range(self,\n ts: pd.Timestamp) -> bool:\n \"\"\"\n Check whether a given timestamp is withing the time interval of this time series\n\n Parameters\n ----------\n ts\n The `pandas.Timestamp` to check\n\n Returns\n -------\n bool\n Whether the timestamp is contained within the time interval of this time series.\n Note that the timestamp does not need to be *in* the time series.\n \"\"\"\n index = self.time_index()\n return index[0] <= ts <= index[-1]\n\n @staticmethod\n def _combine_or_none(series_a: Optional[pd.Series],\n series_b: Optional[pd.Series],\n combine_fn: Callable[[pd.Series, pd.Series], Any]) -> Optional[pd.Series]:\n \"\"\"\n Combines two Pandas Series `series_a and `series_b` using `combine_fn` if neither is `None`.\n\n Parameters\n ----------\n series_a\n the first series\n series_b\n the second series\n combine_fn\n An operation with input two Pandas Series and output one Pandas Series.\n\n Returns\n -------\n Optional[pandas.Series]\n A new Pandas Series, the result of [combine_fn], or None.\n \"\"\"\n if series_a is not None and series_b is not None:\n return combine_fn(series_a, series_b)\n return None\n\n @staticmethod\n def _op_or_none(series: Optional[pd.Series], op: Callable[[pd.Series], Any]):\n return op(series) if series is not None else None\n\n def _combine_from_pd_ops(self, other: 'TimeSeries',\n combine_fn: Callable[[pd.Series, pd.Series], pd.Series]) -> 'TimeSeries':\n \"\"\"\n Combines this TimeSeries with another one, using the `combine_fn` on the underlying Pandas Series.\n\n Parameters\n ----------\n other\n A second TimeSeries.\n combine_fn\n An operation with input two Pandas Series and output one Pandas Series.\n\n Returns\n -------\n TimeSeries\n A new TimeSeries, with underlying Pandas Series the series obtained with `combine_fn`.\n \"\"\"\n raise_if_not(self.has_same_time_as(other), 'The two TimeSeries must have the same time index.', logger)\n\n series = combine_fn(self._series, other.pd_series())\n conf_lo = self._combine_or_none(self._confidence_lo, other.conf_lo_pd_series(), combine_fn)\n conf_hi = self._combine_or_none(self._confidence_hi, other.conf_hi_pd_series(), combine_fn)\n return TimeSeries(series, conf_lo, conf_hi, self.freq())\n\n @staticmethod\n def _fill_missing_dates(series: pd.Series) -> pd.Series:\n \"\"\"\n Tries to fill missing dates in series with NaN.\n Method is successful only when explicit frequency can be determined from all consecutive triple timestamps.\n\n Parameters\n ----------\n series\n The actual time series, as a pandas Series with a proper time index.\n\n Returns\n -------\n pandas.Series\n A new Pandas Series without missing dates.\n \"\"\"\n date_axis = series.index\n samples_size = 3\n observed_frequencies = [\n date_axis[x:x + samples_size].inferred_freq\n for x\n in range(len(date_axis) - samples_size + 1)]\n\n observed_frequencies = set(filter(None.__ne__, observed_frequencies))\n\n raise_if_not(\n len(observed_frequencies) == 1,\n \"Could not infer explicit frequency. Observed frequencies: \"\n + ('none' if len(observed_frequencies) == 0 else str(observed_frequencies))\n + \". Is Series too short (n=2)?\",\n logger)\n\n inferred_frequency = observed_frequencies.pop()\n return series.resample(inferred_frequency).asfreq(fill_value=None)\n\n \"\"\"\n Definition of some useful statistical methods.\n These methods rely on the Pandas implementation.\n \"\"\"\n\n def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs) -> float:\n return self._series.mean(axis, skipna, level, numeric_only, **kwargs)\n\n def var(self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs) -> float:\n return self._series.var(axis, skipna, level, ddof, numeric_only, **kwargs)\n\n def std(self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs) -> float:\n return self._series.std(axis, skipna, level, ddof, numeric_only, **kwargs)\n\n def skew(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs) -> float:\n return self._series.skew(axis, skipna, level, numeric_only, **kwargs)\n\n def kurtosis(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs) -> float:\n return self._series.kurtosis(axis, skipna, level, numeric_only, **kwargs)\n\n def min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs) -> float:\n return self._series.min(axis, skipna, level, numeric_only, **kwargs)\n\n def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs) -> float:\n return self._series.max(axis, skipna, level, numeric_only, **kwargs)\n\n def sum(self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs) -> float:\n return self._series.sum(axis, skipna, level, numeric_only, min_count, **kwargs)\n\n def median(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs) -> float:\n return self._series.median(axis, skipna, level, numeric_only, **kwargs)\n\n def autocorr(self, lag=1) -> float:\n return self._series.autocorr(lag)\n\n def describe(self, percentiles=None, include=None, exclude=None) -> pd.Series:\n return self._series.describe(percentiles, include, exclude)\n\n \"\"\"\n Definition of some dunder methods\n \"\"\"\n\n def __eq__(self, other):\n if isinstance(other, TimeSeries):\n if not self._series.equals(other.pd_series()):\n return False\n for other_ci, self_ci in zip([other.conf_lo_pd_series(), other.conf_hi_pd_series()],\n [self._confidence_lo, self._confidence_hi]):\n if (other_ci is None) ^ (self_ci is None):\n # only one is None\n return False\n if self._combine_or_none(self_ci, other_ci, lambda s1, s2: s1.equals(s2)) is False:\n # Note: we check for \"False\" explicitly, because None is OK..\n return False\n return True\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __len__(self):\n return len(self._series)\n\n def __add__(self, other):\n if isinstance(other, (int, float, np.integer, np.float)):\n new_series = self._series + other\n conf_lo = self._op_or_none(self._confidence_lo, lambda s: s + other)\n conf_hi = self._op_or_none(self._confidence_hi, lambda s: s + other)\n return TimeSeries(new_series, conf_lo, conf_hi, self.freq())\n elif isinstance(other, TimeSeries):\n return self._combine_from_pd_ops(other, lambda s1, s2: s1 + s2)\n else:\n raise_log(TypeError('unsupported operand type(s) for + or add(): \\'{}\\' and \\'{}\\'.'\n .format(type(self).__name__, type(other).__name__)), logger)\n\n def __radd__(self, other):\n return self + other\n\n def __sub__(self, other):\n if isinstance(other, (int, float, np.integer, np.float)):\n new_series = self._series - other\n conf_lo = self._op_or_none(self._confidence_lo, lambda s: s - other)\n conf_hi = self._op_or_none(self._confidence_hi, lambda s: s - other)\n return TimeSeries(new_series, conf_lo, conf_hi, self.freq())\n elif isinstance(other, TimeSeries):\n return self._combine_from_pd_ops(other, lambda s1, s2: s1 - s2)\n else:\n raise_log(TypeError('unsupported operand type(s) for - or sub(): \\'{}\\' and \\'{}\\'.'\n .format(type(self).__name__, type(other).__name__)), logger)\n\n def __rsub__(self, other):\n return other + (-self)\n\n def __mul__(self, other):\n if isinstance(other, (int, float, np.integer, np.float)):\n new_series = self._series * other\n conf_lo = self._op_or_none(self._confidence_lo, lambda s: s * other)\n conf_hi = self._op_or_none(self._confidence_hi, lambda s: s * other)\n return TimeSeries(new_series, conf_lo, conf_hi, self.freq())\n elif isinstance(other, TimeSeries):\n return self._combine_from_pd_ops(other, lambda s1, s2: s1 * s2)\n else:\n raise_log(TypeError('unsupported operand type(s) for * or mul(): \\'{}\\' and \\'{}\\'.'\n .format(type(self).__name__, type(other).__name__)), logger)\n\n def __rmul__(self, other):\n return self * other\n\n def __pow__(self, n):\n if isinstance(n, (int, float, np.integer, np.float)):\n if n < 0 and not all(self.values() != 0):\n raise_log(ZeroDivisionError('Cannot divide by a TimeSeries with a value 0.'), logger)\n\n new_series = self._series ** float(n)\n conf_lo = self._op_or_none(self._confidence_lo, lambda s: s ** float(n))\n conf_hi = self._op_or_none(self._confidence_hi, lambda s: s ** float(n))\n return TimeSeries(new_series, conf_lo, conf_hi, self.freq())\n else:\n raise_log(TypeError('unsupported operand type(s) for ** or pow(): \\'{}\\' and \\'{}\\'.'\n .format(type(self).__name__, type(n).__name__)), logger)\n\n def __truediv__(self, other):\n if isinstance(other, (int, float, np.integer, np.float)):\n if (other == 0):\n raise_log(ZeroDivisionError('Cannot divide by 0.'), logger)\n\n new_series = self._series / other\n conf_lo = self._op_or_none(self._confidence_lo, lambda s: s / other)\n conf_hi = self._op_or_none(self._confidence_hi, lambda s: s / other)\n return TimeSeries(new_series, conf_lo, conf_hi)\n\n elif isinstance(other, TimeSeries):\n if (not all(other.values() != 0)):\n raise_log(ZeroDivisionError('Cannot divide by a TimeSeries with a value 0.'), logger)\n\n return self._combine_from_pd_ops(other, lambda s1, s2: s1 / s2)\n else:\n raise_log(TypeError('unsupported operand type(s) for / or truediv(): \\'{}\\' and \\'{}\\'.'\n .format(type(self).__name__, type(other).__name__)), logger)\n\n def __rtruediv__(self, n):\n return n * (self ** (-1))\n\n def __abs__(self):\n series = abs(self._series)\n conf_lo = self._op_or_none(self._confidence_lo, lambda s: abs(s))\n conf_hi = self._op_or_none(self._confidence_hi, lambda s: abs(s))\n return TimeSeries(series, conf_lo, conf_hi, self.freq())\n\n def __neg__(self):\n series = -self._series\n conf_lo = self._op_or_none(self._confidence_lo, lambda s: -s)\n conf_hi = self._op_or_none(self._confidence_hi, lambda s: -s)\n return TimeSeries(series, conf_lo, conf_hi, self.freq())\n\n def __contains__(self, ts: pd.Timestamp) -> bool:\n return ts in self._series.index\n\n def __round__(self, n=None):\n series = self._series.round(n)\n confidence_lo = self._op_or_none(self._confidence_lo, lambda s: s.round(n))\n confidence_hi = self._op_or_none(self._confidence_hi, lambda s: s.round(n))\n return TimeSeries(series, confidence_lo, confidence_hi, self.freq())\n\n # TODO: Ignoring confidence series for now\n def __lt__(self, other):\n if isinstance(other, (int, float, np.integer, np.float, np.ndarray)):\n series = self._series < other\n elif isinstance(other, TimeSeries):\n series = self._series < other.pd_series()\n else:\n raise_log(TypeError('unsupported operand type(s) for < : \\'{}\\' and \\'{}\\'.'\n .format(type(self).__name__, type(other).__name__)), logger)\n return series # TODO should we return only the ndarray, the pd series, or our timeseries?\n\n def __gt__(self, other):\n if isinstance(other, (int, float, np.integer, np.float, np.ndarray)):\n series = self._series > other\n elif isinstance(other, TimeSeries):\n series = self._series > other.pd_series()\n else:\n raise_log(TypeError('unsupported operand type(s) for > : \\'{}\\' and \\'{}\\'.'\n .format(type(self).__name__, type(other).__name__)), logger)\n return series\n\n def __le__(self, other):\n if isinstance(other, (int, float, np.integer, np.float, np.ndarray)):\n series = self._series <= other\n elif isinstance(other, TimeSeries):\n series = self._series <= other.pd_series()\n else:\n raise_log(TypeError('unsupported operand type(s) for <= : \\'{}\\' and \\'{}\\'.'\n .format(type(self).__name__, type(other).__name__)), logger)\n return series\n\n def __ge__(self, other):\n if isinstance(other, (int, float, np.integer, np.float, np.ndarray)):\n series = self._series >= other\n elif isinstance(other, TimeSeries):\n series = self._series >= other.pd_series()\n else:\n raise_log(TypeError('unsupported operand type(s) for >= : \\'{}\\' and \\'{}\\'.'\n .format(type(self).__name__, type(other).__name__)), logger)\n return series\n\n def __str__(self):\n df = pd.DataFrame({'value': self._series})\n if self._confidence_lo is not None:\n df['conf_low'] = self._confidence_lo\n if self._confidence_hi is not None:\n df['conf_high'] = self._confidence_hi\n return str(df) + '\\nFreq: {}'.format(self.freq_str())\n\n def __repr__(self):\n return self.__str__()\n\n def __copy__(self, deep: bool = True):\n return self.copy(deep=deep)\n\n def __deepcopy__(self):\n return self.copy(deep=True)\n\n # TODO: also support integer 0-D and 1-D indexing\n def __getitem__(self, item):\n # return only main series if nb of values < 3\n if isinstance(item, (int, pd.Timestamp)):\n return self._series[[item]]\n elif isinstance(item, (pd.DatetimeIndex, slice, list, np.ndarray)):\n if isinstance(item, slice):\n # if create a slice with timestamp, convert to indices\n if item.start.__class__ == pd.Timestamp or item.stop.__class__ == pd.Timestamp:\n istart = None if item.start is None else self.time_index().get_loc(item.start)\n istop = None if item.stop is None else self.time_index().get_loc(item.stop)\n item = slice(istart, istop, item.step)\n elif item.start.__class__ == str or item.stop.__class__ == str:\n istart = None if item.start is None else self.time_index().get_loc(pd.Timestamp(item.start))\n istop = None if item.stop is None else self.time_index().get_loc(pd.Timestamp(item.stop))\n item = slice(istart, istop, item.step)\n # cannot reverse order\n if item.indices(len(self))[-1] == -1:\n raise_log(IndexError(\"Cannot have a backward TimeSeries\"), logger)\n # Verify that values in item are really in index to avoid the creation of NaN values\n if isinstance(item, (np.ndarray, pd.DatetimeIndex)):\n check = np.array([elem in self.time_index() for elem in item])\n if not np.all(check):\n raise_log(IndexError(\"None of {} in the index\".format(item[~check])), logger)\n try:\n return TimeSeries(self._series[item],\n self._op_or_none(self._confidence_lo, lambda s: s[item]),\n self._op_or_none(self._confidence_hi, lambda s: s[item]),\n self.freq())\n except ValueError:\n # return only main series if nb of values < 3\n return TimeSeries(self._series[item], freq=self.freq())\n elif isinstance(item, str):\n return self._series[[pd.Timestamp(item)]]\n else:\n raise_log(IndexError(\"Input {} of class {} is not a possible key.\\n Please use integers, \"\n \"pd.DateTimeIndex, arrays or slice\".format(item, item.__class__)), logger)\n","sub_path":"darts/timeseries.py","file_name":"timeseries.py","file_ext":"py","file_size_in_byte":49560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"197868464","text":"import numpy as np\nimport os.path\n\nhbar_eVs = 6.58212E-16 # Planck's constant [eV*s]\nc = 2.998E+10 # speed of light [cm/s]\n\nclass Photothermal_Image:\n def __init__(self):\n # Obtain all the parameters\n par = []\n val = []\n with open(str(\"parameters.py\")) as file:\n for line in file:\n if \"#\" != line[0] and len(line.split()) != 0:\n par.append(line.split()[0][:-1])\n if 'theta_info' in line:\n val.append(line.split()[1:4])\n elif 'phi_info' in line:\n val.append(line.split()[1:4])\n else:\n val.append(line.split()[1])\n\n self.DS = int(val[par.index(\"DS\")])\n self.radius = int(val[par.index(\"radius\")])\n self.rt_dir = val[par.index(\"rt_dir\")]\n self.heat_dir = val[par.index(\"heat_dir\")]\n self.n_R = float(val[par.index(\"n_R\")])\n self.num_k = int(val[par.index(\"num_k\")])\n self.k_back = float(val[par.index(\"k_back\")])\n self.k_in = float(val[par.index(\"k_in\")])\n self.k_sub = float(val[par.index(\"k_sub\")])\n self.pump_um = float(val[par.index(\"pump_um\")])\n self.P_pu = float(val[par.index(\"P_pu\")])\n self.P_pu_pol = val[par.index(\"P_pu_pol\")]\n self.P_pu_offset = float(val[par.index(\"P_pu_offset\")])*self.DS*1E-7 # units of cm \n self.probe_um = float(val[par.index(\"probe_um\")])\n self.P_pr = float(val[par.index(\"P_pr\")])\n self.P_pr_pol = val[par.index(\"P_pr_pol\")]\n self.P_pr_offset = float(val[par.index(\"P_pr_offset\")])*self.DS*1E-7 # units of cm\n self.phi_info = val[par.index(\"phi_info\")]\n self.theta_info = val[par.index(\"theta_info\")]\n self.NA = float(val[par.index(\"num_app\")])\n self.n_amb_heat = float(val[par.index(\"n_ambient_heated\")])\n self.image_width = int(val[par.index(\"image_width\")])\n self.ss = int(val[par.index(\"ss\")])\n self.num_theta = (float(self.theta_info[1])-float(self.theta_info[0]))/float(self.theta_info[2])\n self.num_phi= (float(self.phi_info[1])-float(self.phi_info[0]))/float(self.phi_info[2])\n\n def waist(self,wave):\n # [nm]\n return wave * 10**3 * 0.6 / self.NA \n\n def return_params(self):\n print(self.image_width)\n print(self.ss)\n print(self.DS)\n print(self.radius)\n\n def make_ddscatpar(self, shapefile,step,):\n\t\t##### PUMP SCATTERING #####\n if step == \"pump\":\n wavelength = self.pump_um\n g_waist_DS = self.waist(self.pump_um)/self.DS\n diel_files = str(' \"') + str(self.rt_dir) + str('\" = file with metal refractive index\\n')\n ncomp = 1\n nrfld = 2\n focal_offset = self.P_pu_offset/(self.DS*1E-7) # DS\n n_back = self.n_R\n inc_pol = self.P_pu_pol\n wrsc = 0\n nplanes = 0\n\n\t\t##### HOT PROBE SCATTERING #####\n if step == \"probe_hot\":\n wavelength = self.probe_um\n g_waist_DS = self.waist(self.probe_um)/self.DS\n with open(str(\"ddscat_filler\"), 'r') as heated_material:\n diel_files = heated_material.readlines()\n ncomp = len(diel_files)\n nrfld = 0\n focal_offset = self.P_pr_offset/(self.DS*1E-7) # DS \n with open(str(\"n_T_of_temp_max\"),'r') as file:\n n_back = file.readlines()\n n_back = n_back[0]\n inc_pol = self.P_pr_pol\n wrsc = 1\n nplanes = self.num_phi + 1\n\n ##### ROOM PROBE SCATTERING #####\n if step == \"probe_room\":\n wavelength = self.probe_um\n g_waist_DS = self.waist(self.probe_um)/self.DS\n diel_files = str(' \"') + str(self.rt_dir) + str('\" = file with metal refractive index\\n')\n ncomp = 1\n nrfld = 0\n focal_offset = self.P_pr_offset/(self.DS*1E-7) # DS \n n_back = self.n_R\n inc_pol = self.P_pr_pol\n wrsc = 1\n nplanes = self.num_phi + 1\n\n\t\t#################\n\t\t# memory allocation \n x = []; y = []; z = []\n with open(shapefile) as file:\n data = file.readlines ()\n for line in data:\n line = line.split()\n if len(line) == 7 and '=' not in line:\n x.append(int(line[1]))\n y.append(int(line[2]))\n z.append(int(line[3]))\n mem_allo_x = max(x) - min(x) + 10\n mem_allo_y = max(y) - min(y) + 10\n mem_allo_z = max(z) - min(z) + 10\n\n # Effective radius\n effR = (3 * len(x) / (4 * np.pi))**(1 / 3.0) * int(self.DS) * 10**(-3)\n effR = \"{0:.4f}\".format(effR)\n\n # Make ddscat.par file \n f = open(\"ddscat.par\", \"w\")\n f.write(\" ' ========== Parameter file for v7.3 ==================='\\n\")\n f.write(\" '**** Preliminaries ****'\\n\")\n f.write(\" 'NOTORQ' = CMTORQ*6 (DOTORQ, NOTORQ) -- either do or skip torque calculations\\n\")\n f.write(\" 'PBCGS2' = CMDSOL*6 (PBCGS2, PBCGST, GPBICG, QMRCCG, PETRKP) -- CCG method\\n\")\n f.write(\" 'GPFAFT' = CMETHD*6 (GPFAFT, FFTMKL) -- FFT method\\n\")\n f.write(\" 'GKDLDR' = CALPHA*6 (GKDLDR, LATTDR, FLTRCD) -- DDA method\\n\")\n f.write(\" 'NOTBIN' = CBINFLAG (NOTBIN, ORIBIN, ALLBIN)\\n\")\n f.write(\" '**** Initial Memory Allocation ****'\\n\")\n f.write(\" %r %r %r = dimensioning allowance for target generation\\n\" % (mem_allo_x, mem_allo_y, mem_allo_z))\n f.write(\" '**** Target Geometry and Composition ****'\\n\")\n f.write(\" 'FROM_FILE' = CSHAPE*9 shape directive\\n\")\n f.write(\" no SHPAR parameters needed\\n\")\n f.write(\" %r = NCOMP = number of dielectric materials\\n\" % ncomp)\n for line in diel_files:\n f.write( line)\n f.write(\" '**** Additional Nearfield calculation? ****'\\n\")\n f.write(\" %r = NRFLD (=0 to skip nearfield calc., =1 to calculate nearfield E, =2 to calculate nearfield E and B)\\n\" % nrfld)\n f.write(\" 0.0 0.0 0.0 0.0 0.0 0.0 (fract. extens. of calc. vol. in -x,+x,-y,+y,-z,+z)\\n\")\n f.write(\" '**** Error Tolerance ****'\\n\")\n f.write(\" 1.00e-5 = TOL = MAX ALLOWED (NORM OF |G>=AC|E>-ACA|X>)/(NORM OF AC|E>)\\n\")\n f.write(\" '**** Maximum number of iterations ****'\\n\")\n f.write(\" 2370 = MXITER\\n\")\n f.write(\" '**** Integration cutoff parameter for PBC calculations ****'\\n\")\n f.write(\" 1.00e-2 = GAMMA (1e-2 is normal, 3e-3 for greater accuracy)\\n\")\n f.write(\" '**** Angular resolution for calculation of , etc. ****'\\n\")\n f.write(\" 0.5 = ETASCA (number of angles is proportional to [(3+x)/ETASCA]^2 )\\n\")\n f.write(\" '**** Vacuum wavelengths (micron) ****'\\n\")\n f.write(\" %r %r 1 'INV' = wavelengths (first,last,how many,how=LIN,INV,LOG)\\n\" % (wavelength, wavelength))\n f.write(\" '**** Gaussian beam parameters (unit = dipole spacing)'\\n\")\n f.write(\" 1 = FLGWAV: Option for wavefront: 0 -- Plane wave; 1 -- Gaussian beam\\n\")\n f.write(\" %r, 0.00, 0.00 = xyzc0, center of Gaussian beam waist, unit = dipole spacing\\n\" % focal_offset)\n f.write(\" %.4f = w0, Gaussian beam waist, unit = dipole spacing\\n\" % float(g_waist_DS))\n f.write(\" '**** Refractive index of ambient medium'\\n\")\n f.write(\" %r = NAMBIENT\\n\" % (float(n_back)))\n f.write(\" '**** Effective Radii (micron) **** '\\n\")\n f.write(\" %r %r 1 'LIN' = eff. radii (first, last, how many, how=LIN,INV,LOG)\\n\" % (float(effR), float(effR)))\n f.write(\" '**** Define Incident Polarizations ****'\\n\")\n if inc_pol == \"y\":\n f.write( \" (0,0) (1.,0.) (0.,0.) = Polarization state e01 (k along x axis)\\n\")\n elif inc_pol == \"z\":\n f.write( \" (0,0) (0.,0.) (1.,0.) = Polarization state e01 (k along x axis)\\n\")\n f.write(\" 1 = IORTH (=1 to do only pol. state e01; =2 to also do orth. pol. state)\\n\")\n f.write(\" '**** Specify which output files to write ****'\\n\")\n f.write(\" %r = IWRKSC (=0 to suppress, =1 to write \\\".sca\\\" file for each target orient.\\n\" % wrsc)\n f.write(\" '**** Specify Target Rotations ****'\\n\")\n f.write(\" 0. 0. 1 = BETAMI, BETAMX, NBETA (beta=rotation around a1)\\n\")\n f.write(\" 0. 0. 1 = THETMI, THETMX, NTHETA (theta=angle between a1 and k)\\n\")\n f.write(\" 0. 0. 1 = PHIMIN, PHIMAX, NPHI (phi=rotation angle of a1 around k)\\n\")\n f.write(\" '**** Specify first IWAV, IRAD, IORI (normally 0 0 0) ****'\\n\")\n f.write(\" 0 0 0 = first IWAV, first IRAD, first IORI (0 0 0 to begin fresh)\\n\")\n f.write(\" '**** Select Elements of S_ij Matrix to Print ****'\\n\")\n f.write(\" 6 = NSMELTS = number of elements of S_ij to print (not more than 9)\\n\")\n f.write(\" 11 12 21 22 31 41 = indices ij of elements to print\\n\")\n f.write(\" '**** Specify Scattered Directions ****'\\n\")\n f.write(\" 'LFRAME' = CMDFRM (LFRAME, TFRAME for Lab Frame or Target Frame)\\n\")\n if int(nplanes) == 0:\n f.write(\" 0 = NPLANES = number of scattering planes\\n\")\n if int(nplanes) > 0:\n f.write(\" %r = NPLANES = number of scattering planes\\n\" % int(nplanes))\n for i in range(int(nplanes)):\n phi = -180 + i * 360 / (int(nplanes) - 1)\n f.write(\" %r %r %r %r = phi, theta_min, theta_max (deg) for plane %r\\n\" % ( float(phi), float(self.theta_info[0]), float(self.theta_info[1]), float(self.theta_info[2]), i+1))\n f.close()\n\n def make_varpar(self, shapefile):\n # tDDA window\n x = []; y = []; z = []\n with open(shapefile) as file:\n data = file.readlines()\n for line in data:\n line = line.split()\n if len(line) == 7 and '=' not in line:\n x.append(int(line[1]))\n y.append(int(line[2]))\n z.append(int(line[3]))\n window = 2 # [DS] since we're not making glycerol shells, no need to extend target\n x_min = min(x) - int(window) \n x_max = max(x) + int(window) \n y_min = min(y) - int(window) \n y_max = max(y) + int(window) \n z_min = min(z) - int(window) \n z_max = max(z) + int(window) \n x_plane = int( (x_max+x_min) / 2)\n ## Convert Power to Intensity \n I_0 = float(self.P_pu) / ( np.pi * ( float(self.waist(self.pump_um)) * 10**-9)**2 )*10**-9 #units of nW/m^2, then will get converted to W/m^2 for var.par\n I_0 = \"{:.4E}\".format(I_0)\n\n f = open(\"var.par\", \"w\")\n f.write(\"num_k: 1\\n\")\n f.write(\"k_out: %r\\n\" % self.k_back)\n f.write(\"k_in: %r\\n\" % self.k_in)\n f.write(\"k_sub: %r\\n\" % self.k_sub)\n f.write(\"lambda: %r\\n\" % (self.pump_um*10**(-6)))\n f.write(\"n_m: %r\\n\" % self.n_R)\n f.write(\"I_0: %re+9\\n\" % float(I_0))\n f.write(\"unit: %r\\n\\n\" % self.DS)\n f.write(\"d: 1\\n\")\n f.write(\"x_min: %r\\n\" % int(x_min))\n f.write(\"x_max: %r\\n\" % int(x_max))\n f.write(\"y_min: %r\\n\" % int(y_min))\n f.write(\"y_max: %r\\n\" % int(y_max))\n f.write(\"z_min: %r\\n\" % int(z_min))\n f.write(\"z_max: %r\\n\\n\" % int(z_max))\n f.write(\"x_plane: %r\\n\" % int(x_plane))\n f.write(\"input_mode: 1\\n\")\n f.close()\n\n def make_makemetal(self, shapefile):\n file = open('makemetal.py', 'r')\n list_of_lines = file.readlines() \n list_of_lines[2] = str(\"nback=\")+str(self.n_R)+str(\"\\n\")\n list_of_lines[3] = str(\"diel_path='\") + str(self.heat_dir)+str(\"' \")+str(\"\\n\")\n list_of_lines[4] = str(\"shapefile=np.loadtxt('\")+str(shapefile)+str(\"', skiprows=7)\")+str(\"\\n\")\n file = open('makemetal.py', 'w')\n file.writelines(list_of_lines)\n file.close\n\n ### Collect FML functions ###\n \n def file_len(self, fname):\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\n def field_MM(self, filename,skip):\n fmlfile = np.loadtxt(filename, skiprows=skip)\n theta_fml = (fmlfile[:,0])*np.pi/180 # radians\n phi_fml = fmlfile[:,1]*np.pi/180 # radians\n weights = np.zeros(len(theta_fml))+1\n f11 = fmlfile[:, 2] + 1j*fmlfile[:, 3]\n f21 = fmlfile[:, 4] + 1j*fmlfile[:, 5]\n f12 = 0; f22 = 0\n w = 1.240/self.probe_um # probe wavelength, eV\n k = w/hbar_eVs/c\n I0_SI = self.P_pr / ( np.pi * (self.waist(self.probe_um) * 2 * 10**-9)**2 ) # W/m^2 ## COME BACK TO HERE\n I0 = I0_SI*10**3 # g^1/2 / ( cm^1/2 s)\n E0 = np.sqrt(I0*8*np.pi/(c*self.n_R))\n\n magr = 1 # cm\n magk = np.linalg.norm(k)\n expon = np.exp(1j*magk*magr)\n E_theta = expon/(magk*magr) * ( f11 ) * E0\n E_phi = expon/(magk*magr) * ( f21 ) * E0\n E_r = 0\n Ex = np.zeros(len(theta_fml),dtype=complex)\n Ey = np.zeros(len(theta_fml),dtype=complex)\n Ez = np.zeros(len(theta_fml),dtype=complex)\n for i in range(0, len(theta_fml)):\n theta = theta_fml[i]\n phi = phi_fml[i]\n Ex[i] = E_r*np.cos(theta) - E_theta[i]*np.sin(theta)\n Ey[i] = E_r*np.sin(theta)*np.cos(phi) + E_theta[i]*np.cos(theta)*np.cos(phi) - E_phi[i]*np.sin(phi)\n Ez[i] = E_r*np.sin(theta)*np.sin(phi) + E_theta[i]*np.cos(theta)*np.sin(phi) + E_phi[i]*np.cos(phi)\n x = magr*np.cos(theta_fml)\n y = magr*np.sin(theta_fml)*np.cos(phi_fml)\n z = magr*np.sin(theta_fml)*np.sin(phi_fml)\n\n idx_thetamin = np.where(theta_fml*180/np.pi == float(self.theta_info[0]))\n idx_thetamax = np.where(theta_fml*180/np.pi == float(self.theta_info[1]))\n idx_phimin = np.where(phi_fml*180/np.pi == float(self.phi_info[0]))\n idx_phimax = np.where(phi_fml*180/np.pi == float(self.phi_info[1]))\n weights[idx_thetamin] = 0.5\n weights[idx_thetamax] = 0.5\n weights[idx_phimin] = 0.5\n weights[idx_phimax] = 0.5\n\n ### Convert theta_fml to theta \n theta = np.arccos(z/magr)\n phi = np.arctan2(y, x)\n\n return np.array([Ex, Ey, Ez]), weights, theta, phi, theta_fml, phi_fml\n\n def E_gaussian(self,filename,skip):\n # for one beam position, calculate the field on the partial hemi\n fmlfile = np.loadtxt(filename, skiprows=skip)\n theta_fml = (fmlfile[:,0])*np.pi/180 # radians\n phi_fml = fmlfile[:,1]*np.pi/180 # radians\n magr = 1 # cm\n w = 1.240/self.probe_um # probe wavelength\n k = w*self.n_R/hbar_eVs/c\n waist_cm = self.waist(self.probe_um) * 1E-7 # [cm] beam waist radius\n ## position dependence \n x_fml = magr*np.cos(theta_fml)\n y_fml = magr*np.sin(theta_fml)*np.cos(phi_fml)\n z_fml = magr*np.sin(theta_fml)*np.sin(phi_fml)\n x = x_fml-self.P_pr_offset # axial distance from beam's focus / waist \n xR = np.pi*waist_cm**2*self.n_R/(self.probe_um*1E-4) # Rayleigh range, at distance xR, width of beam = np.sqrt(2) times larger than it is at beam waist\n wx = waist_cm*np.sqrt(1+(x/xR)**2) # radius at which field amp. falls to 1/e of their axial values\n Rx = x*(1 + (xR/x)**2) # radius of curvature\n phi_gouy = np.arctan(x/xR) # Gouy phase\n r = np.sqrt(y_fml**2 + z_fml**2) # radial distance from center of beam \n Emag = waist_cm/wx*np.exp(-r**2/wx**2)*np.exp(-1j*(k*x+k*r**2/(2*Rx)-phi_gouy))\n return np.array([np.zeros(len(Emag)), Emag, np.zeros(len(Emag))])\n\n def calculated_IPT(self):\n IPT_TOT_HMR = np.zeros((int(self.image_width*2/(self.ss)+1), int(self.image_width*2/(self.ss)+1)))\n IPT_TOT_INT = np.zeros(IPT_TOT_HMR.shape)\n IPT_R = np.zeros(IPT_TOT_HMR.shape)\n IPT_one = np.zeros(IPT_TOT_HMR.shape)\n ycoords = np.zeros(IPT_TOT_HMR.shape)\n zcoords = np.zeros(IPT_TOT_HMR.shape)\n for valy in range(-self.image_width,self.image_width+self.ss,self.ss):\n for valz in range(-self.image_width,self.image_width+self.ss,self.ss):\n print(valy, valz)\n base_file = str('raster_data/x0_y')+str(int(valy))+str('_z')+str(int(valz)) + \\\n str('/fml_x0y')+str(int(valy))+str('z')+str(int(valz))+str('_')\n lines_H = self.file_len(base_file+str('H'))\n lines_R = self.file_len(base_file+str('R'))\n base = 29; ndiff = lines_H-lines_R\n E_H, weights, theta, phi, theta_fml, phi_fml = self.field_MM(filename=str(base_file+str('H')),skip=base+ndiff) \n E_R, _, _, _,_,_ = self.field_MM(filename=str(base_file+str('R')),skip=base)\n E_p = self.E_gaussian(filename=str(base_file+str('R')),skip=base)\n hot_minus_room = np.zeros(E_p.shape[1])\n interf_term = np.zeros(E_p.shape[1])\n one_term = np.zeros(E_p.shape[1])+1\n\n modEH_sqrd = np.sum(E_H.real**2 + E_H.imag**2, axis=0)\n modER_sqrd = np.sum(E_R.real**2 + E_R.imag**2, axis=0)\n hot_minus_room = modEH_sqrd - modER_sqrd\n interf_term = 2*np.real( np.sum(E_p*np.conj(E_H - E_R),axis=0))\n\n yi = int((valy + self.image_width)/self.ss)\n zi = int((valz + self.image_width)/self.ss)\n ycoords[yi, zi] = valy\n zcoords[yi, zi] = valz\n\n dtheta = float(self.theta_info[2])*np.pi/180 \n dphi = float(self.phi_info[2])*np.pi/180\n\n # Integrate \n IPT_TOT_HMR[yi, zi] = c*self.n_R/(8*np.pi)*( np.sum(hot_minus_room*np.sin(theta_fml)*dtheta*dphi*weights ) )\n IPT_TOT_INT[yi, zi] = c*self.n_R/(8*np.pi)*( np.sum(interf_term*np.sin(theta_fml)*dtheta*dphi*weights ) )\n IPT_one[yi, zi] = np.sum(np.abs(one_term)*np.sin(theta_fml)*dtheta*dphi*weights)\n return ycoords, zcoords, IPT_TOT_HMR, IPT_TOT_INT, IPT_one\n\n def collect_fml(self):\n ycoords, zcoords, IPT_HMR, IPT_INT, IPT_one = self.calculated_IPT()\n ywrite = np.ravel(ycoords); zwrite = np.ravel(zcoords)\n IPT_HMR_write = np.ravel(IPT_HMR)\n IPT_INT_write = np.ravel(IPT_INT)\n IPT_one_write = np.ravel(IPT_one)\n file = open(str('pt_signal.txt'),'w')\n file.write(str('y') + '\\t' + str('z') + '\\t' + str('H-R') + '\\t' + str('INT') + '\\n')\n for i in range(0, len(ywrite)):\n file.write(\"%d \\t %d \\t %2.4e \\t %2.4e \\t %2.4e \\n\" % (ywrite[i], zwrite[i], IPT_HMR_write[i], IPT_INT_write[i], IPT_one_write[i]))\n\n\n\n\n\n","sub_path":"pipeline/my_inputgen.py","file_name":"my_inputgen.py","file_ext":"py","file_size_in_byte":21629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"282042317","text":"\r\nclass Solution(object):\r\n \"\"\"\r\n One way to serialize a binary tree is to use pre-oder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.\r\n\r\n _9_\r\n / \\\r\n 3 2\r\n / \\ / \\\r\n 4 1 # 6\r\n / \\ / \\ / \\\r\n # # # # # #\r\n\r\n For example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\", where # represents a null node.\r\n\r\n Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.\r\n\r\n Each comma separated value in the string must be either an integer or a character '#' representing null pointer.\r\n\r\n You may assume that the input format is always valid, for example it could never contain two consecutive commas such as \"1,,3\".\r\n\r\n Example 1:\r\n \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\r\n Return true\r\n\r\n Example 2:\r\n \"1,#\"\r\n Return false\r\n\r\n Example 3:\r\n \"9,#,#,1\"\r\n Return false\r\n \"\"\"\r\n def isValidSerialization(self, preorder):\r\n \"\"\"\r\n :type preorder: str\r\n :rtype: bool\r\n\r\n for \"1,#\" return false, I think that means all the leaf should be \"#\"\r\n \"\"\"\r\n def preorderTraversal(s):\r\n if s:\r\n n = s.pop(0)\r\n if n != \"#\":\r\n preorderTraversal(s)\r\n return preorderTraversal(s)\r\n else:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n print(preorder)\r\n s = preorder.split(\",\")\r\n if len(s) <= 3 or s[-1] != \"#\" or s[-2] != \"#\":\r\n return False\r\n\r\n ret = preorderTraversal(s)\r\n\r\n if not s and ret:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef buildTestData(dc=5):\r\n from random import randint\r\n ret = []\r\n for i in range(dc):\r\n c = randint(5,20)\r\n v = [\"1\",\"2\"]+[\"#\"] * c\r\n for x in range(randint(1,c)):\r\n v[randint(2,c-1)] = str(randint(1,c))\r\n v += [\"#\", \"#\"]\r\n ret.append(\",\".join(v))\r\n return ret\r\n\r\nif __name__ == \"__main__\":\r\n a = Solution()\r\n for x in buildTestData():\r\n print(a.isValidSerialization(x))\r\n #~ d1 = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\r\n #~ print(a.isValidSerialization(d1))\r\n #~ d2 = \"1,#\"\r\n #~ print(a.isValidSerialization(d2))\r\n #~ d3 = \"9,#,#,1\"\r\n #~ print(a.isValidSerialization(d3))\r\n #~ d4 = \"1,2,7,#,#,6,6,4,#,#,#,#\"\r\n #~ print(a.isValidSerialization(d4))\r\n #~ d5 = \"1,2,11,#,12,16,#,#,11,16,#,13,#,#,10,9,6,#,#,#,#,#,#\"\r\n #~ print(a.isValidSerialization(d5))\r\n","sub_path":"leet/331.VerifyPreorderSerializationOfABinaryTree.py","file_name":"331.VerifyPreorderSerializationOfABinaryTree.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"246554999","text":"import numpy as np\nimport sys\nsys.path.append('../../')\nimport estimate_L\n\nA = np.array([\n [1.5, 0],\n [0, 0.1]\n])\nB = np.array([\n [1],\n [0]\n])\n\ndef F(x,u):\n return A @ x.reshape(-1, 1) + B @ u.reshape(-1, 1)\n\ndef K(x):\n \"\"\" compute state-dependent control variable u \"\"\"\n u = -1*x[0] + np.random.randn()\n return u.reshape(-1, 1)\n\n# def phi(x):\n# \"\"\" Identity for DMD \"\"\"\n# return x\n\n# def psi(u):\n# \"\"\" Identity for DMD \"\"\"\n# return u\n\ndef phi(x):\n \"\"\" Quadratic dictionary \"\"\"\n return np.array([1, x[0], x[1], x[0]**2, x[1]**2, x[0]*x[1]])\n\ndef psi(u):\n \"\"\" Quadratic dictionary \"\"\"\n return np.array([float(1), float(u), float(u**2)])\n\n# simulate system to generate data matrices\nm = 1000 # number of sample steps from the system.\nn = 2 # dimensionality of state space\nq = 1 # dimensionality of control space\n\n# State snapshotting\nx0 = np.array([\n [4],\n [7]\n])\nsnapshots = np.empty((n, m))\nsnapshots[:, 0] = np.squeeze(x0)\n\n# Control snapshotting\nU = np.empty((q, m-1))\n# sys = UnstableSystem1(x0)\nfor k in range(m-1):\n u_k = K(snapshots[:, k])\n y = F(snapshots[:, k], u_k[0])\n snapshots[:, k+1] = np.squeeze(y)\n U[:, k] = u_k\n\nX = snapshots[:, :m-1]\nY = snapshots[:, 1:m]\n\n#%% Build Phi and Psi matrices\nd_phi = 6\nd_psi = 3\nN = m-1\n\nPhi_X = np.empty((d_phi, N))\nfor i,x in enumerate(X.T):\n Phi_X[:,i] = phi(x)\n\nPhi_Y = np.empty((d_phi, N))\nfor i,y in enumerate(Y.T):\n Phi_Y[:,i] = phi(y)\n\nPsi_U = np.empty((d_psi, N))\nfor i,u in enumerate(U.T):\n Psi_U[:,i] = psi(u)\n\n#%% Build kronMatrix\nkronMatrix = np.empty((d_psi * d_phi, N))\nfor i in range(N):\n kronMatrix[:,i] = np.kron(Psi_U[:,i], Phi_X[:,i])\n\n#%% Estimate M\nM = estimate_L.ols(kronMatrix.T, Phi_Y.T).T\n\n#%% Reshape M into K tensor\nK = np.empty((d_phi, d_phi, d_psi))\nfor i in range(d_phi):\n K[i] = M[i].reshape((d_phi,d_psi), order='F')\n\ndef K_u(K, u):\n return np.einsum('ijz,z->ij', K, psi(u))\n\n#%% Training error\ndef l2_norm(true_state, predicted_state):\n error = true_state - predicted_state\n squaredError = np.power(error, 2)\n return np.sum(squaredError)\n\nnorms = []\nfor i in range(N):\n true_phi_x_prime = Phi_Y[:,i]\n predicted_phi_x_prime = K_u(K, U[:,i]) @ Phi_X[:,i]\n norms.append(l2_norm(true_phi_x_prime, predicted_phi_x_prime))\nnorms = np.array(norms)\n\nprint(\"Mean norm on training data:\", norms.mean())\n\n\n\n\n\n# A_approx, B_approx, Phi = dmdc(X, Y, U)\n# print(\"\\nApproximation of A\")\n# print(\"True\")\n# pprint(sys.A)\n# print(\"Predicted\")\n# pprint(A_approx)\n\n# print(\"\\nApproximation of B\")\n# print(\"True\")\n# pprint(sys.B)\n# print(\"Predicted\")\n# pprint(B_approx)","sub_path":"koopman-tensor/system-dynamics/dmdc.py","file_name":"dmdc.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"512544621","text":"import random\nimport glob\nimport os\n\nclass SecretWord:\n os.chdir(r'cse210-student-jumper')\n myFiles = glob.glob('*.txt')\n os.chdir(r'jumper')\n myFiles2 = glob.glob('*.txt')\n os.chdir(r'game')\n myFiles3 = glob.glob('*.txt')\n\n index = random.randint(0,844)\n file = open('words.txt', 'r')\n l = file.readlines()\n selected_word = l[index].strip('\\n')\n\n print(selected_word)","sub_path":"jumper/game/get_word.py","file_name":"get_word.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"152178161","text":"class ViewService:\n def __init__(self):\n self.error_message = ''\n self.page_title = ''\n\n def _get_header(self):\n print(\"Work Log ({})\\n\".format(self.page_title))\n\n def _get_error_message(self):\n if self.error_message:\n print(\"Error: {}\".format(self.error_message))\n print(\"Please try again:\\n\")\n\n def clear_error_message(self):\n self.error_message = ''\n\n def get_menu_page(self, menu_items, page_type):\n self._get_header()\n\n if page_type == 'main':\n print(\"Please select an item from menu\\n\")\n elif page_type == 'search_page':\n print(\"Please select one of the following options\\n\")\n\n for index, item in enumerate(menu_items):\n if index != len(menu_items) - 1:\n print(\"{0}. {1}\".format(chr(index+97), item))\n else:\n print(\"{0}. {1}\\n\".format(chr(index+97), item))\n\n self._get_error_message()\n\n def get_add_page(self, prompt_phrase):\n self._get_header()\n\n print(\"Please enter value to the following\\n\")\n\n print(\"{}:\\n\".format(prompt_phrase))\n\n self._get_error_message()\n\n def _get_title_search_by_page(self, search_type):\n output = ''\n\n if search_type == 'date':\n output = \"Please enter full date (yyyy-MM-dd):\\n\"\n elif search_type == 'task_name':\n output = \"Please enter name of task:\\n\"\n elif search_type == 'time_spent':\n output = \"Please enter amount of time (Non-negative integer):\\n\"\n elif search_type == 'employee_name':\n output = \"Please enter employee name:\\n\"\n elif search_type == 'task_name_and_notes':\n output = \"Please enter search term:\\n\"\n\n return output\n\n def get_search_by_page(self, search_type):\n self._get_header()\n\n title = self._get_title_search_by_page(search_type)\n\n print(title)\n\n print(\"[R] Return to Search Page\\n\")\n\n self._get_error_message()\n\n def _get_options_display_page(self, path, items, index):\n output = ''\n\n if path == 'search_page':\n if len(items) == 1:\n output = \"[R] Return to Search Page\\n\"\n elif index == 0:\n output = \"[N] Next Item [R] Return to Search Page\\n\"\n elif index > 0 and index < len(items) - 1:\n output = (\n \"[N] Next Item [P] Previous Item [R] Return to \"\n \"Search Page\\n\")\n else:\n output = \"[P] Previous Item [R] Return to Search Page\\n\"\n else:\n output = \"[R] Return to Main Page\\n\"\n\n return output\n\n def get_display_page(self, path, items, index):\n self._get_header()\n item = items[index]\n\n print(\"Employee Name: {}\".format(item.employee_name))\n print(\"Task Name: {}\".format(item.task_name))\n print(\"Created Date: {}\".format(item.date.strftime('%Y-%m-%d')))\n print(\"Time Spent: {}\".format(item.time_amt))\n print(\"Notes: {}\\n\".format(item.notes))\n\n title_submenu = self._get_options_display_page(path, items, index)\n\n if path == 'search_page':\n print(\"Displaying Item ({} of {})\\n\".format(index+1, len(items)))\n\n print(title_submenu)\n\n self._get_error_message()\n\n","sub_path":"view_service.py","file_name":"view_service.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"652027775","text":"import pandas as pd\r\nimport random\r\n\r\ndef replace_only_str(x, that, by):\r\n if type(x)==str:\r\n x = x.replace(that, by)\r\n\r\n return x\r\n\r\ndef comma_to_dot(df):\r\n for col in df.columns:\r\n df[col] = df[col].apply(lambda x : replace_only_str(x, ',', \".\"))\r\n\r\n return df\r\n\r\ndef clean_col_names(df):\r\n for col in df.columns:\r\n if 'Unnamed:' in col:\r\n new_col_name = col[9:]\r\n df[new_col_name]=df[col]\r\n df.drop(columns=[col], inplace=True)\r\n return df\r\n\r\np = 0.37 #% in bxl from bxl / in bxl from every where\r\n\r\nall_hh = pd.read_csv('all_hh_child_Reallocated.csv')\r\nall_hh.drop(columns=[\"Unnamed: 0\"], inplace=True)\r\nprint(all_hh)\r\n\r\nsectors_names_correspondance = pd.read_csv(\"sector_stat.csv\", sep=\";\")\r\nsectors_names_correspondance.drop(columns=[\"Name\"], inplace=True)\r\nsectors_names_correspondance.drop_duplicates(inplace=True)\r\nprint(sectors_names_correspondance)\r\n\r\n\r\nall_hh = all_hh.merge(sectors_names_correspondance, left_on=\"SectorStatID\", right_on=\"Code\")\r\nprint(all_hh)\r\n\r\ncommunes = all_hh['Commune']\r\ncommunes.drop_duplicates(inplace=True)\r\nprint(communes)\r\n\r\n\r\nsectors = all_hh['SectorStatID']\r\nsectors.drop_duplicates(inplace=True)\r\nprint(sectors)\r\n\r\nadultes = all_hh[(all_hh.Age > 20) & (all_hh.Age < 65)]\r\nadultes_not_collectif = adultes[adultes.HouseholdTypeID != 6]\r\n\r\n\r\n#etudiant from bxl to bxl fr\r\ncampus = pd.read_csv(\"sup_campus_bxl_fr_with_ss_v2.csv\")\r\n\r\nprint(campus.columns)\r\n\r\nss = pd.DataFrame()\r\nss['SectorStat'] = campus.sector_stat\r\n#ss.drop_duplicates(inplace=True)\r\nprint(ss)\r\n\r\nsectors_names_correspondance = pd.read_csv('sector_stat.csv', sep=';')\r\n#sectors_names_correspondance.set_index(\"Code\", inplace=True, drop=True)\r\nprint(sectors_names_correspondance)\r\n\r\n\r\nss = ss.merge(sectors_names_correspondance, left_on=\"SectorStat\", right_on=\"Code\", how='inner')\r\nss.drop(columns=[\"Code\"], inplace=True)\r\nprint(ss)\r\nss.to_csv('campus_fr_ss_commune.csv')\r\ncommunes = ss.Commune\r\ncommunes.drop_duplicates(inplace=True)\r\nsectors_names_correspondance.set_index(\"Code\", inplace=True, drop=True)\r\ndic = dict()\r\nfor com in communes:\r\n list_ss = ss[ss.Commune == com].SectorStat.tolist()\r\n dic[com]=list_ss #len(ss[ss.Commune==com])\r\n \r\nprint(dic)\r\n\r\ncolnames = adultes_not_collectif.columns.tolist()\r\ncolnames.extend([\"WorkerID\", \"WorkerType\", \"WorkSectorStatID\", \"WorkSectorStatName\"])\r\nadulte_students = pd.DataFrame(columns=colnames)\r\n\r\nage_min = 21\r\nage_max = 64\r\nunif_fr = pd.read_csv(\"unif_fr_bxl_to_bxl.csv\", sep=';')\r\nprint(unif_fr)\r\ni=0\r\nfor ind in unif_fr.index:\r\n print(\"ind\", ind)\r\n if unif_fr.loc[ind, \"Sexe\"] == \"Femme\":\r\n sex = 1\r\n elif unif_fr.loc[ind, \"Sexe\"] == \"Homme\":\r\n sex = 0\r\n else:\r\n errorsex\r\n \r\n age = unif_fr.loc[ind, \"Age\"]\r\n if age >= age_min and age<= age_max:\r\n possible = adultes_not_collectif[(adultes_not_collectif.GenderID == sex) & (adultes_not_collectif.Age == age) &\r\n (adultes_not_collectif.Commune == unif_fr.loc[ind, \"Commune_from\"])]\r\n nb = unif_fr.loc[ind, \"Sum of Compte\"]\r\n \r\n com_to = unif_fr.loc[ind, \"Commune_to\"]\r\n list_ss_to = dic[com_to]\r\n\r\n if com_to == \"Bruxelles\":\r\n nb_per_ss = max(round(nb/len(list_ss_to)), 0)\r\n nb_per_ss = max(round((nb*(1-650*p/8634-200*p/8634-2783*p/8634-16407*p/8634))/len(list_ss_to-4)), 0)\r\n reste = (nb*(1-650*p/8634-200*p/8634-2783*p/8634-16407*p/8634))%len(list_ss_to-4)\r\n elif com_to == 'Anderlecht':\r\n nb_per_ss = max(round((nb*(1-200*p/3520-4707*p/3520))/len(list_ss_to-2)), 0)\r\n reste = (nb*(1-200*p/3520-4707*p/3520))%len(list_ss_to-2)\r\n elif com_to == 'Ixelles':\r\n nb_per_ss = max(round((nb*(1-1050*p/2022-2476*p/2022))/len(list_ss_to-2)), 0)\r\n reste = (nb*(1-1050*p/2022-2476*p/2022))%len(list_ss_to-2)\r\n elif com_to == 'Woluwe Saint-Pierre':\r\n nb_per_ss = max(round((nb(1-2000*p/2453))/len(list_ss_to-1)), 0)\r\n reste = (nb(1-2000*p/2453))%len(list_ss_to-1)\r\n elif com_to == 'Woluwe Saint-Lambert':\r\n nb_per_ss = max(round((nb*(1-7006*p/9213))/len(list_ss_to-1)), 0)\r\n reste = (nb*(1-7006*p/9213))%len(list_ss_to-1)\r\n else:\r\n nb_per_ss = max(round(nb/len(list_ss_to)), 0)\r\n reste = (nb)%len(list_ss_to)\r\n\r\n first_ss = True\r\n \r\n for ss in list_ss_to:\r\n print(\"ss\", ss)\r\n if ss == '21004C642':\r\n nb_per_ss_tmp = round(nb*650*p/8634)\r\n elif ss == '21004A3MJ':\r\n nb_per_ss_tmp = round(nb*200*p/8634)\r\n elif ss == '21001B25-':\r\n nb_per_ss_tmp = round(nb*200*p/3520)\r\n elif ss == \"21004A32-\":\r\n nb_per_ss_tmp = round(nb*2783*p/8634)\r\n elif ss == '21004C61-':\r\n nb_per_ss_tmp = round(nb*16407*p/8634)\r\n elif ss == '21001C522':\r\n nb_per_ss_tmp = round(nb*(4707*p + 2*nb_per_ss))/3\r\n elif ss == '21009A602':\r\n nb_per_ss_tmp = round(nb*1050*p/2022)\r\n elif ss == '21009A2MJ':\r\n nb_per_ss_tmp = round(nb*2476*p/2022)\r\n elif ss == '21019A52-':\r\n nb_per_ss_tmp = round(nb*2000*p/2453)\r\n elif ss == '21018A87-':\r\n nb_per_ss_tmp = round(nb*7006*p/9213 + 7+nb_per_ss)/8\r\n\r\n\r\n elif first_ss:\r\n nb_per_ss_tmp = nb_per_ss + reste\r\n first_ss = False\r\n else:\r\n nb_per_ss_tmp = nb_per_ss\r\n \r\n while nb_per_ss_tmp > 0 and len(possible) > 0:\r\n print(\"i ss\", i)\r\n elu = random.randrange(0, len(possible), 1)\r\n ind_elu = possible.index[elu]\r\n \r\n el = possible.loc[ind_elu].tolist()\r\n \r\n hh_type_id = possible.loc[ind_elu, \"HouseholdTypeID\"]\r\n \r\n if hh_type_id == 3 or hh_type_id == 5:\r\n ss_home = possible.loc[ind_elu, \"SectorStatID\"]\r\n \r\n if ss_home == ss:\r\n work_id = 4\r\n work_type = \"Unif on campus\"\r\n else:\r\n work_id = 5\r\n work_type = \"Unif off campus\"\r\n else:\r\n work_id = 5\r\n work_type = \"Unif off campus\" \r\n \r\n work_ss_name = sectors_names_correspondance.loc[ss]\r\n el.extend([work_id, work_type, ss, work_ss_name])\r\n adulte_students.loc[i]=el\r\n \r\n possible.drop([ind_elu], inplace=True)\r\n adultes_not_collectif.drop([ind_elu], inplace = True)\r\n \r\n nb_per_ss_tmp -=1\r\n i+=1\r\n\r\nprint(adulte_students)\r\nadulte_students.to_csv(\"student_fr_bxl_bxl_adultes_workplace_v2.csv\") \r\n \r\nclosest_peri = pd.read_csv(\"closest_ss_peri_v2.csv\")\r\nclosest_peri.set_index('SectorStatID', inplace=True, drop=True)\r\nprint(closest_peri) #TODO check unnamed and index (should be ss id)\r\n\r\n\r\n#etudiants from bxl to out bxl fr\r\nsup_fr_trajets_hors_bxl = pd.read_csv('sup_fr_trajets_to_hors_bxl.csv', sep=';')\r\n\r\nfor age in range(21, 65):\r\n print(\"age bxl out bxl fr\", age)\r\n sup_fr_trajets_hors_bxl_age = sup_fr_trajets_hors_bxl[sup_fr_trajets_hors_bxl.Age == age]\r\n\r\n sup_fr_trajets_hors_bxl_age_fe = sup_fr_trajets_hors_bxl_age[sup_fr_trajets_hors_bxl_age.Sexe == \"Femme\"]\r\n sup_fr_trajets_hors_bxl_age_ho = sup_fr_trajets_hors_bxl_age[sup_fr_trajets_hors_bxl_age.Sexe == \"Homme\"]\r\n\r\n for com in communes:\r\n if com == 'Saint-Josse-ten-Noode':\r\n com = 'Saint-Josse-Ten-Noode'\r\n print(\"com\", com)\r\n nb_to_allocate_fe = sup_fr_trajets_hors_bxl_age_fe[sup_fr_trajets_hors_bxl_age_fe[\"Commune_from\"]==com]\r\n nb_to_allocate_fe.reset_index(inplace=True)\r\n \r\n if not nb_to_allocate_fe.empty:\r\n \r\n nb_to_allocate_fe= nb_to_allocate_fe.loc[0,\"Sum of Compte\"]\r\n print(nb_to_allocate_fe) #TODO verifier not null because of majuscules\r\n possible_fe = adultes_not_collectif[(adultes_not_collectif.GenderID == 1) & (adultes_not_collectif.Commune == com) & (adultes_not_collectif.Age == age)]\r\n print(possible_fe) #TODO verifier not null because of majuscules\r\n \r\n \r\n while nb_to_allocate_fe > 0 and len(possible_fe)>0:\r\n print(\"i com bxl out bxl fr\", i)\r\n elu = random.randrange(0, len(possible_fe), 1)\r\n ind_elu = possible_fe.index[elu]\r\n \r\n work_ss_id = closest_peri.loc[adultes_not_collectif.loc[ind_elu, \"SectorStatID\"]][\"Closest_Peri\"]\r\n work_ss_name = sectors_names_correspondance.loc[work_ss_id, \"Name\"]\r\n \r\n el = possible_fe.loc[ind_elu].tolist()\r\n el.extend([5, \"Unif off campus\", work_ss_id, work_ss_name])\r\n adulte_students.loc[i] = el\r\n \r\n possible_fe.drop([ind_elu], inplace=True)\r\n adultes_not_collectif.drop([ind_elu], inplace=True)\r\n \r\n nb_to_allocate_fe-=1\r\n i+=1\r\n\r\n nb_to_allocate_ho = sup_fr_trajets_hors_bxl_age_ho[sup_fr_trajets_hors_bxl_age_ho[\"Commune_from\"]==com]\r\n nb_to_allocate_ho.reset_index(inplace=True)\r\n if not nb_to_allocate_ho.empty:\r\n \r\n nb_to_allocate_ho= nb_to_allocate_ho.loc[0,\"Sum of Compte\"]\r\n print(nb_to_allocate_ho) #TODO verifier not null because of majuscules\r\n possible_ho = adultes_not_collectif[(adultes_not_collectif.GenderID == 0) & (adultes_not_collectif.Commune == com) & (adultes_not_collectif.Age == age)]\r\n \r\n while nb_to_allocate_ho > 0 and len(possible_ho)>0:\r\n print(\"i com bxl out bxl fr g\", i)\r\n elu = random.randrange(0, len(possible_ho), 1)\r\n ind_elu = possible_ho.index[elu]\r\n \r\n work_ss_id = closest_peri.loc[adultes_not_collectif.loc[ind_elu, \"SectorStatID\"]][\"Closest_Peri\"]\r\n work_ss_name = sectors_names_correspondance.loc[work_ss_id, \"Name\"]\r\n \r\n el = possible_ho.loc[ind_elu].tolist()\r\n el.extend([5, \"Unif off campus\", work_ss_id, work_ss_name])\r\n adulte_students.loc[i] = el\r\n \r\n possible_ho.drop([ind_elu], inplace=True)\r\n adultes_not_collectif.drop([ind_elu], inplace=True)\r\n \r\n nb_to_allocate_ho-=1\r\n i+=1\r\n\r\nprint(adulte_students)\r\nadulte_students.to_csv(\"students_adultes_unif_workplace_v2.csv\")\r\n\r\n#Etudiants from bxl to bxl nl\r\nnb_student_nl = pd.read_csv(\"sup_nl_bxl_to_bxl.csv\", sep=\";\")\r\nprint(nb_student_nl)\r\n\r\ncolnames = [\"SectorStatID\", \"SectorStatName\", \"PersID\", \"Age\", \"GenderID\", \"GenderName\", \"ChildOrParent\",\r\n \"HouseholdID\", \"HouseholdTypeID\", \"HouseholdTypeName\", \"Code\", \"Commune\", \"WorkerID\", \r\n \"WorkerType\"]\r\nstudents_nl = pd.DataFrame(columns=colnames)\r\nstudents_nl_off_or_on_campus_to_check = pd.DataFrame(columns=colnames)\r\n\r\ni = 0\r\nfor age in range(18, 21):\r\n print(\"age\", age)\r\n nb_student_nl_age = nb_student_nl[nb_student_nl.Age == age]\r\n\r\n nb_student_nl_age_fe = int(nb_student_nl_age.loc[:, \"Fe\"])\r\n nb_student_nl_age_ho = int(nb_student_nl_age.loc[:, \"Ho\"])\r\n\r\n possible_fe = adultes_not_collectif[(adultes_not_collectif.Age == age) & (adultes_not_collectif.GenderID == 1)]\r\n possible_ho = adultes_not_collectif[(adultes_not_collectif.Age == age) & (adultes_not_collectif.GenderID == 0)]\r\n\r\n while nb_student_nl_age_fe > 0 and len(possible_fe) > 0:\r\n print(\"age i\", i)\r\n elu = random.randrange(0, len(possible_fe), 1)\r\n ind_elu = possible_fe.index[elu]\r\n\r\n hh_id = adultes_not_collectif.loc[ind_elu, \"HouseholdTypeID\"]\r\n \r\n el = possible_fe.loc[ind_elu].tolist()\r\n\r\n if hh_id == 1 or hh_id == 2 or hh_id == 3 or hh_id == 4:\r\n el.extend([5, \"Unif off campus\"])\r\n students_nl.loc[i] = el\r\n\r\n elif hh_id == 5:\r\n el.extend([\"4 or 5\", \"Unif on or off campus\"])\r\n students_nl_off_or_on_campus_to_check.loc[i] = el #jeune_student.loc[ind_elu],\"4 or 5\", \"Unif on or off campus\"]\r\n #TODO check whether same ss unif and logement\r\n else:\r\n error\r\n\r\n possible_fe.drop([ind_elu], inplace=True)\r\n adultes_not_collectif.drop([ind_elu], inplace=True)\r\n\r\n nb_student_nl_age_fe-=1\r\n i+=1\r\n\r\n while nb_student_nl_age_ho > 0 and len(possible_fe) > 0:\r\n print(\"age i g\", i)\r\n elu = random.randrange(0, len(possible_ho), 1)\r\n ind_elu = possible_ho.index[elu]\r\n\r\n hh_id = adultes_not_collectif.loc[ind_elu, \"HouseholdTypeID\"]\r\n \r\n el = possible_ho.loc[ind_elu].tolist()\r\n\r\n if hh_id == 1 or hh_id == 2 or hh_id == 3 or hh_id == 4:\r\n el.extend([5, \"Unif off campus\"])\r\n students_nl.loc[i] = el\r\n\r\n elif hh_id == 5:\r\n el.extend([\"4 or 5\", \"Unif on or off campus\"])\r\n students_nl_off_or_on_campus_to_check.loc[i] = el\r\n #TODO check whether same ss unif and logement\r\n else:\r\n error\r\n\r\n possible_ho.drop([ind_elu], inplace=True)\r\n adultes_not_collectif.drop([ind_elu], inplace=True)\r\n\r\n nb_student_nl_age_ho-=1\r\n i+=1\r\n\r\nprint(students_nl)\r\nstudents_nl.to_csv(\"student_adultes_nl_workid_v2.csv\")\r\n\r\nprint(students_nl_off_or_on_campus_to_check)\r\nstudents_nl_off_or_on_campus_to_check.to_csv(\"student_adultes_nl_workid_4_or_5_to_check_v2.csv\")\r\n\r\n\r\n#Etudiants from bxl to out bxl nl\r\nnb_student_nl_out = pd.read_csv(\"sup_nl_bxl_to_out_bxl.csv\", sep=\";\")\r\nprint(nb_student_nl_out)\r\n\r\n\r\nsectors_names_correspondance = pd.read_csv(\"sector_stat.csv\", sep=\";\")\r\n#sectors_names_correspondance.drop(columns=[\"Name\"], inplace=True)\r\nsectors_names_correspondance.drop_duplicates(inplace=True)\r\nprint(sectors_names_correspondance)\r\n\r\ncommunes = sectors_names_correspondance.Commune\r\ncommunes.drop_duplicates(inplace=True)\r\nprint(communes)\r\n\r\nadultes_not_collectif = adultes_not_collectif.merge(sectors_names_correspondance, how='inner', left_on='SectorStatID', right_on='Code')\r\nprint(adultes_not_collectif)\r\n\r\nsectors_names_correspondance.set_index(\"Code\", inplace=True, drop=True)\r\n\r\ncolnames = adultes_not_collectif.columns.tolist()\r\ncolnames.extend([\"WorkerID\", \"WorkerType\", \"WorkSectorStatID\", \"WorkSectorStatName\"])\r\nstudents_nl_out = pd.DataFrame(columns=colnames)\r\n\r\ni = 0\r\nfor age in range(21, 65):\r\n print(\"age g bxl out bxl\", age)\r\n nb_student_nl_out_age = nb_student_nl_out[nb_student_nl_out.Age == age]\r\n\r\n nb_student_nl_out_age_fe = int(nb_student_nl_out_age.loc[:, \"Fe\"])\r\n nb_student_nl_out_age_ho = int(nb_student_nl_out_age.loc[:, \"Ho\"])\r\n\r\n possible_fe = adultes_not_collectif[(adultes_not_collectif.Age == age) & (adultes_not_collectif.GenderID == 1)]\r\n possible_ho = adultes_not_collectif[(adultes_not_collectif.Age == age) & (adultes_not_collectif.GenderID == 0)]\r\n\r\n while nb_student_nl_out_age_fe > 0 and len(possible_fe) > 0:\r\n print(\"i g bxl out bxl\", i)\r\n elu = random.randrange(0, len(possible_fe), 1)\r\n ind_elu = possible_fe.index[elu]\r\n \r\n el = possible_fe.loc[ind_elu].tolist()\r\n\r\n work_ss_id = closest_peri.loc[adultes_not_collectif.loc[ind_elu, \"SectorStatID\"]][\"Closest_Peri\"]\r\n work_ss_name = sectors_names_correspondance.loc[work_ss_id, \"Name\"]\r\n \r\n el.extend([ 5, \"Unif off campus\", work_ss_id, work_ss_name])\r\n students_nl_out.loc[i] = el\r\n\r\n possible_fe.drop([ind_elu], inplace=True)\r\n adultes_not_collectif.drop([ind_elu], inplace=True)\r\n\r\n nb_student_nl_out_age_fe-=1\r\n i+=1\r\n\r\n while nb_student_nl_out_age_ho > 0 and len(possible_ho) > 0:\r\n print(\"i g bxl out bxl g\", i)\r\n elu = random.randrange(0, len(possible_ho), 1)\r\n ind_elu = possible_ho.index[elu]\r\n\r\n el = possible_ho.loc[ind_elu].tolist()\r\n \r\n work_ss_id = closest_peri.loc[adultes_not_collectif.loc[ind_elu, \"SectorStatID\"]][\"Closest_Peri\"]\r\n work_ss_name = sectors_names_correspondance.loc[work_ss_id, \"Name\"]\r\n \r\n el.extend([ 5, \"Unif off campus\", work_ss_id, work_ss_name])\r\n students_nl_out.loc[i] = el\r\n\r\n possible_ho.drop([ind_elu], inplace=True)\r\n adultes_not_collectif.drop([ind_elu], inplace=True)\r\n\r\n nb_student_nl_out_age_ho-=1\r\n i+=1\r\n\r\nprint(students_nl_out)\r\nstudents_nl_out.to_csv(\"student_adultes_nl_to_out_workplace_v2.csv\")\r\n\r\n\r\n\r\n#Adultes at home\r\ncolnames = adultes_not_collectif.columns.tolist()\r\ncolnames.extend([\"WorkerID\", \"WorkerType\"])\r\nadultes_at_home = pd.DataFrame(columns=colnames)\r\n\r\nadultes_not_collectif_fe = adultes_not_collectif[adultes_not_collectif.GenderID == 1]\r\n\r\nact_home_fe = pd.read_csv(\"activite_home_fe.csv\", sep=';')\r\nprint(act_home_fe)\r\n\r\nsectors = all_hh['SectorStatID']\r\n\r\nact_home_fe.set_index(\"Code\", inplace=True, drop=True)\r\ni = 0\r\nfor age in range(21, 65):\r\n print(\"age fin\", age)\r\n act_home_fe_age= act_home_fe[str(age)+\",00\"]\r\n\r\n for ss in sectors:\r\n print(\"ss fin\", ss)\r\n nb_act_home_fe = act_home_fe_age.loc[ss]\r\n if type(nb_act_home_fe)==str:\r\n nb_act_home_fe = nb_act_home_fe.replace(\",\", \".\")\r\n nb_act_home_fe = float(nb_act_home_fe)\r\n nb_act_home_fe = round(nb_act_home_fe)\r\n \r\n possible_act_home_fe = adultes_not_collectif_fe[adultes_not_collectif_fe.SectorStatID == ss]\r\n\r\n while nb_act_home_fe > 0:\r\n print(\"i fin\", i)\r\n elu = random.randrange(0, len(possible_act_home_fe), 1)\r\n ind_elu = possible_act_home_fe.index[elu]\r\n \r\n el = possible_act_home_fe.loc[ind_elu].tolist()\r\n el.extend([7, \"StayHome\"])\r\n \r\n adultes_at_home.loc[i] = el\r\n\r\n possible_act_home_fe.drop([ind_elu], inplace=True)\r\n adultes_not_collectif.drop([ind_elu], inplace=True)\r\n\r\n nb_act_home_fe-=1\r\n i+=1\r\n\r\nadultes_not_collectif_ho = adultes_not_collectif[adultes_not_collectif.GenderID == 0]\r\n\r\nact_home_ho = pd.read_csv(\"activite_home_ho.csv\", sep=';')\r\nprint(act_home_ho)\r\n\r\nact_home_ho.set_index(\"Code\", inplace=True, drop=True)\r\n\r\nfor age in range(21, 65):\r\n print(\"age fin g\", age)\r\n act_home_ho_age= act_home_ho[str(age)+\",00\"]\r\n\r\n for ss in sectors:\r\n print(\"ss fin g\", ss)\r\n nb_act_home_ho = act_home_ho_age.loc[ss]\r\n if type(nb_act_home_ho)==str:\r\n nb_act_home_ho = nb_act_home_ho.replace(\",\", \".\")\r\n nb_act_home_ho = float(nb_act_home_ho)\r\n nb_act_home_ho= round(nb_act_home_ho)\r\n \r\n possible_act_home_ho = adultes_not_collectif_ho[adultes_not_collectif_ho.SectorStatID == ss]\r\n\r\n while nb_act_home_ho > 0:\r\n print(\"i fin g\", i)\r\n elu = random.randrange(0, len(possible_act_home_ho), 1)\r\n ind_elu = possible_act_home_ho.index[elu]\r\n\r\n el = possible_act_home_ho.loc[ind_elu].tolist()\r\n el.extend([7, \"StayHome\"])\r\n \r\n adultes_at_home.loc[i] = el\r\n \r\n possible_act_home_ho.drop([ind_elu], inplace=True)\r\n adultes_not_collectif.drop([ind_elu], inplace=True)\r\n\r\n nb_act_home_ho-=1\r\n i+=1\r\n\r\n\r\nprint(adultes_at_home)\r\nadultes_at_home.to_csv(\"adultes_home_workid.csv\")\r\n\r\nadultes_not_collectif[\"WorkerID\"]=6\r\nadultes_not_collectif[\"WorkerName\"]=\"Worker\"\r\n\r\nprint(adultes_not_collectif)\r\nadultes_not_collectif.to_csv(\"adultes_worker.csv\")\r\n\r\nadultes_collectif = adultes[adultes.HouseholdTypeID == 6]\r\nprint(adultes_collectif)\r\nadultes_collectif.to_csv(\"adultes_collectif.csv\")\r\n\r\n#TODO hopital ou prison ?","sub_path":"code/workid_adultes_v2.py","file_name":"workid_adultes_v2.py","file_ext":"py","file_size_in_byte":20110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"225113041","text":"import json\nimport socket\nimport threading\nimport logging\nimport requests\nfrom wsgiref.simple_server import make_server\nlogger = logging.getLogger(__name__)\n\n\ndef find_free_port():\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.bind(('0.0.0.0', 0))\n port = sock.getsockname()[1]\n sock.close()\n return port\n\n\ndef make_app(consume):\n def app(environ, start_response):\n status = '200 OK'\n headers = [('Content-type', 'application/json; charset=utf-8')]\n start_response(status, headers)\n wsgi_input = environ[\"wsgi.input\"]\n content_length = int(environ[\"CONTENT_LENGTH\"])\n\n val = json.loads(wsgi_input.read(content_length))\n\n class args:\n input = [val]\n\n result = list(consume(args))\n assert len(result) == 2\n return [json.dumps(result[1]).encode(\"utf-8\")]\n\n return app\n\n\ndef main():\n import logging\n logging.basicConfig(level=logging.INFO)\n\n import magicalimport\n handler_main = magicalimport.import_symbol(\"./05handler_cli.py:main\")\n app = make_app(handler_main)\n\n port = find_free_port()\n httpd = make_server('', port, app)\n\n th = threading.Thread(target=httpd.serve_forever, daemon=True)\n logger.info(\"Serving on port %s...\", port)\n th.start()\n\n rows = [10, 20, 30, 40, 50]\n for row in rows:\n payload = row\n response = requests.post(f\"http://localhost:{port}\", json=payload)\n data = response.json()\n logger.info(\"response status=%s, data=%s\", response.status_code, data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"daily/20180703/example_resumable/05runner_cli.py","file_name":"05runner_cli.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"47853625","text":"\"\"\"\nType annotations for route53 service client.\n\n[Open documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html)\n\nUsage::\n\n ```python\n import boto3\n from mypy_boto3_route53 import Route53Client\n\n client: Route53Client = boto3.client(\"route53\")\n ```\n\"\"\"\nimport sys\nfrom typing import Any, Dict, List, Type, overload\n\nfrom botocore.client import BaseClient, ClientMeta\n\nfrom .literals import (\n AccountLimitTypeType,\n HealthCheckRegionType,\n HostedZoneLimitTypeType,\n InsufficientDataHealthStatusType,\n ResettableElementNameType,\n RRTypeType,\n TagResourceTypeType,\n VPCRegionType,\n)\nfrom .paginator import (\n ListCidrBlocksPaginator,\n ListCidrCollectionsPaginator,\n ListCidrLocationsPaginator,\n ListHealthChecksPaginator,\n ListHostedZonesPaginator,\n ListQueryLoggingConfigsPaginator,\n ListResourceRecordSetsPaginator,\n ListVPCAssociationAuthorizationsPaginator,\n)\nfrom .type_defs import (\n ActivateKeySigningKeyResponseTypeDef,\n AlarmIdentifierTypeDef,\n AssociateVPCWithHostedZoneResponseTypeDef,\n ChangeBatchTypeDef,\n ChangeCidrCollectionResponseTypeDef,\n ChangeResourceRecordSetsResponseTypeDef,\n CidrCollectionChangeTypeDef,\n CreateCidrCollectionResponseTypeDef,\n CreateHealthCheckResponseTypeDef,\n CreateHostedZoneResponseTypeDef,\n CreateKeySigningKeyResponseTypeDef,\n CreateQueryLoggingConfigResponseTypeDef,\n CreateReusableDelegationSetResponseTypeDef,\n CreateTrafficPolicyInstanceResponseTypeDef,\n CreateTrafficPolicyResponseTypeDef,\n CreateTrafficPolicyVersionResponseTypeDef,\n CreateVPCAssociationAuthorizationResponseTypeDef,\n DeactivateKeySigningKeyResponseTypeDef,\n DeleteHostedZoneResponseTypeDef,\n DeleteKeySigningKeyResponseTypeDef,\n DisableHostedZoneDNSSECResponseTypeDef,\n DisassociateVPCFromHostedZoneResponseTypeDef,\n EnableHostedZoneDNSSECResponseTypeDef,\n GetAccountLimitResponseTypeDef,\n GetChangeResponseTypeDef,\n GetCheckerIpRangesResponseTypeDef,\n GetDNSSECResponseTypeDef,\n GetGeoLocationResponseTypeDef,\n GetHealthCheckCountResponseTypeDef,\n GetHealthCheckLastFailureReasonResponseTypeDef,\n GetHealthCheckResponseTypeDef,\n GetHealthCheckStatusResponseTypeDef,\n GetHostedZoneCountResponseTypeDef,\n GetHostedZoneLimitResponseTypeDef,\n GetHostedZoneResponseTypeDef,\n GetQueryLoggingConfigResponseTypeDef,\n GetReusableDelegationSetLimitResponseTypeDef,\n GetReusableDelegationSetResponseTypeDef,\n GetTrafficPolicyInstanceCountResponseTypeDef,\n GetTrafficPolicyInstanceResponseTypeDef,\n GetTrafficPolicyResponseTypeDef,\n HealthCheckConfigTypeDef,\n HostedZoneConfigTypeDef,\n ListCidrBlocksResponseTypeDef,\n ListCidrCollectionsResponseTypeDef,\n ListCidrLocationsResponseTypeDef,\n ListGeoLocationsResponseTypeDef,\n ListHealthChecksResponseTypeDef,\n ListHostedZonesByNameResponseTypeDef,\n ListHostedZonesByVPCResponseTypeDef,\n ListHostedZonesResponseTypeDef,\n ListQueryLoggingConfigsResponseTypeDef,\n ListResourceRecordSetsResponseTypeDef,\n ListReusableDelegationSetsResponseTypeDef,\n ListTagsForResourceResponseTypeDef,\n ListTagsForResourcesResponseTypeDef,\n ListTrafficPoliciesResponseTypeDef,\n ListTrafficPolicyInstancesByHostedZoneResponseTypeDef,\n ListTrafficPolicyInstancesByPolicyResponseTypeDef,\n ListTrafficPolicyInstancesResponseTypeDef,\n ListTrafficPolicyVersionsResponseTypeDef,\n ListVPCAssociationAuthorizationsResponseTypeDef,\n TagTypeDef,\n TestDNSAnswerResponseTypeDef,\n UpdateHealthCheckResponseTypeDef,\n UpdateHostedZoneCommentResponseTypeDef,\n UpdateTrafficPolicyCommentResponseTypeDef,\n UpdateTrafficPolicyInstanceResponseTypeDef,\n VPCTypeDef,\n)\nfrom .waiter import ResourceRecordSetsChangedWaiter\n\nif sys.version_info >= (3, 8):\n from typing import Literal\nelse:\n from typing_extensions import Literal\n\n__all__ = (\"Route53Client\",)\n\nclass BotocoreClientError(BaseException):\n MSG_TEMPLATE: str\n\n def __init__(self, error_response: Dict[str, Any], operation_name: str) -> None:\n self.response: Dict[str, Any]\n self.operation_name: str\n\nclass Exceptions:\n CidrBlockInUseException: Type[BotocoreClientError]\n CidrCollectionAlreadyExistsException: Type[BotocoreClientError]\n CidrCollectionInUseException: Type[BotocoreClientError]\n CidrCollectionVersionMismatchException: Type[BotocoreClientError]\n ClientError: Type[BotocoreClientError]\n ConcurrentModification: Type[BotocoreClientError]\n ConflictingDomainExists: Type[BotocoreClientError]\n ConflictingTypes: Type[BotocoreClientError]\n DNSSECNotFound: Type[BotocoreClientError]\n DelegationSetAlreadyCreated: Type[BotocoreClientError]\n DelegationSetAlreadyReusable: Type[BotocoreClientError]\n DelegationSetInUse: Type[BotocoreClientError]\n DelegationSetNotAvailable: Type[BotocoreClientError]\n DelegationSetNotReusable: Type[BotocoreClientError]\n HealthCheckAlreadyExists: Type[BotocoreClientError]\n HealthCheckInUse: Type[BotocoreClientError]\n HealthCheckVersionMismatch: Type[BotocoreClientError]\n HostedZoneAlreadyExists: Type[BotocoreClientError]\n HostedZoneNotEmpty: Type[BotocoreClientError]\n HostedZoneNotFound: Type[BotocoreClientError]\n HostedZoneNotPrivate: Type[BotocoreClientError]\n HostedZonePartiallyDelegated: Type[BotocoreClientError]\n IncompatibleVersion: Type[BotocoreClientError]\n InsufficientCloudWatchLogsResourcePolicy: Type[BotocoreClientError]\n InvalidArgument: Type[BotocoreClientError]\n InvalidChangeBatch: Type[BotocoreClientError]\n InvalidDomainName: Type[BotocoreClientError]\n InvalidInput: Type[BotocoreClientError]\n InvalidKMSArn: Type[BotocoreClientError]\n InvalidKeySigningKeyName: Type[BotocoreClientError]\n InvalidKeySigningKeyStatus: Type[BotocoreClientError]\n InvalidPaginationToken: Type[BotocoreClientError]\n InvalidSigningStatus: Type[BotocoreClientError]\n InvalidTrafficPolicyDocument: Type[BotocoreClientError]\n InvalidVPCId: Type[BotocoreClientError]\n KeySigningKeyAlreadyExists: Type[BotocoreClientError]\n KeySigningKeyInParentDSRecord: Type[BotocoreClientError]\n KeySigningKeyInUse: Type[BotocoreClientError]\n KeySigningKeyWithActiveStatusNotFound: Type[BotocoreClientError]\n LastVPCAssociation: Type[BotocoreClientError]\n LimitsExceeded: Type[BotocoreClientError]\n NoSuchChange: Type[BotocoreClientError]\n NoSuchCidrCollectionException: Type[BotocoreClientError]\n NoSuchCidrLocationException: Type[BotocoreClientError]\n NoSuchCloudWatchLogsLogGroup: Type[BotocoreClientError]\n NoSuchDelegationSet: Type[BotocoreClientError]\n NoSuchGeoLocation: Type[BotocoreClientError]\n NoSuchHealthCheck: Type[BotocoreClientError]\n NoSuchHostedZone: Type[BotocoreClientError]\n NoSuchKeySigningKey: Type[BotocoreClientError]\n NoSuchQueryLoggingConfig: Type[BotocoreClientError]\n NoSuchTrafficPolicy: Type[BotocoreClientError]\n NoSuchTrafficPolicyInstance: Type[BotocoreClientError]\n NotAuthorizedException: Type[BotocoreClientError]\n PriorRequestNotComplete: Type[BotocoreClientError]\n PublicZoneVPCAssociation: Type[BotocoreClientError]\n QueryLoggingConfigAlreadyExists: Type[BotocoreClientError]\n ThrottlingException: Type[BotocoreClientError]\n TooManyHealthChecks: Type[BotocoreClientError]\n TooManyHostedZones: Type[BotocoreClientError]\n TooManyKeySigningKeys: Type[BotocoreClientError]\n TooManyTrafficPolicies: Type[BotocoreClientError]\n TooManyTrafficPolicyInstances: Type[BotocoreClientError]\n TooManyTrafficPolicyVersionsForCurrentPolicy: Type[BotocoreClientError]\n TooManyVPCAssociationAuthorizations: Type[BotocoreClientError]\n TrafficPolicyAlreadyExists: Type[BotocoreClientError]\n TrafficPolicyInUse: Type[BotocoreClientError]\n TrafficPolicyInstanceAlreadyExists: Type[BotocoreClientError]\n VPCAssociationAuthorizationNotFound: Type[BotocoreClientError]\n VPCAssociationNotFound: Type[BotocoreClientError]\n\nclass Route53Client(BaseClient):\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html)\n \"\"\"\n\n meta: ClientMeta\n\n @property\n def exceptions(self) -> Exceptions:\n \"\"\"\n Route53Client exceptions.\n \"\"\"\n def activate_key_signing_key(\n self, *, HostedZoneId: str, Name: str\n ) -> ActivateKeySigningKeyResponseTypeDef:\n \"\"\"\n Activates a key-signing key (KSK) so that it can be used for signing by DNSSEC.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.activate_key_signing_key)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#activate_key_signing_key)\n \"\"\"\n def associate_vpc_with_hosted_zone(\n self, *, HostedZoneId: str, VPC: \"VPCTypeDef\", Comment: str = None\n ) -> AssociateVPCWithHostedZoneResponseTypeDef:\n \"\"\"\n Associates an Amazon VPC with a private hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.associate_vpc_with_hosted_zone)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#associate_vpc_with_hosted_zone)\n \"\"\"\n def can_paginate(self, operation_name: str) -> bool:\n \"\"\"\n Check if an operation can be paginated.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.can_paginate)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#can_paginate)\n \"\"\"\n def change_cidr_collection(\n self,\n *,\n Id: str,\n Changes: List[\"CidrCollectionChangeTypeDef\"],\n CollectionVersion: int = None\n ) -> ChangeCidrCollectionResponseTypeDef:\n \"\"\"\n Creates, changes, or deletes CIDR blocks within a collection.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.change_cidr_collection)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#change_cidr_collection)\n \"\"\"\n def change_resource_record_sets(\n self, *, HostedZoneId: str, ChangeBatch: \"ChangeBatchTypeDef\"\n ) -> ChangeResourceRecordSetsResponseTypeDef:\n \"\"\"\n Creates, changes, or deletes a resource record set, which contains authoritative\n DNS information for a specified domain name or subdomain name.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.change_resource_record_sets)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#change_resource_record_sets)\n \"\"\"\n def change_tags_for_resource(\n self,\n *,\n ResourceType: TagResourceTypeType,\n ResourceId: str,\n AddTags: List[\"TagTypeDef\"] = None,\n RemoveTagKeys: List[str] = None\n ) -> Dict[str, Any]:\n \"\"\"\n Adds, edits, or deletes tags for a health check or a hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.change_tags_for_resource)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#change_tags_for_resource)\n \"\"\"\n def close(self) -> None:\n \"\"\"\n Closes underlying endpoint connections.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.close)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#close)\n \"\"\"\n def create_cidr_collection(\n self, *, Name: str, CallerReference: str\n ) -> CreateCidrCollectionResponseTypeDef:\n \"\"\"\n Creates a CIDR collection in the current Amazon Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_cidr_collection)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_cidr_collection)\n \"\"\"\n def create_health_check(\n self, *, CallerReference: str, HealthCheckConfig: \"HealthCheckConfigTypeDef\"\n ) -> CreateHealthCheckResponseTypeDef:\n \"\"\"\n Creates a new health check.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_health_check)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_health_check)\n \"\"\"\n def create_hosted_zone(\n self,\n *,\n Name: str,\n CallerReference: str,\n VPC: \"VPCTypeDef\" = None,\n HostedZoneConfig: \"HostedZoneConfigTypeDef\" = None,\n DelegationSetId: str = None\n ) -> CreateHostedZoneResponseTypeDef:\n \"\"\"\n Creates a new public or private hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_hosted_zone)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_hosted_zone)\n \"\"\"\n def create_key_signing_key(\n self,\n *,\n CallerReference: str,\n HostedZoneId: str,\n KeyManagementServiceArn: str,\n Name: str,\n Status: str\n ) -> CreateKeySigningKeyResponseTypeDef:\n \"\"\"\n Creates a new key-signing key (KSK) associated with a hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_key_signing_key)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_key_signing_key)\n \"\"\"\n def create_query_logging_config(\n self, *, HostedZoneId: str, CloudWatchLogsLogGroupArn: str\n ) -> CreateQueryLoggingConfigResponseTypeDef:\n \"\"\"\n Creates a configuration for DNS query logging.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_query_logging_config)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_query_logging_config)\n \"\"\"\n def create_reusable_delegation_set(\n self, *, CallerReference: str, HostedZoneId: str = None\n ) -> CreateReusableDelegationSetResponseTypeDef:\n \"\"\"\n Creates a delegation set (a group of four name servers) that can be reused by\n multiple hosted zones that were created by the same Amazon Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_reusable_delegation_set)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_reusable_delegation_set)\n \"\"\"\n def create_traffic_policy(\n self, *, Name: str, Document: str, Comment: str = None\n ) -> CreateTrafficPolicyResponseTypeDef:\n \"\"\"\n Creates a traffic policy, which you use to create multiple DNS resource record\n sets for one domain name (such as example.com) or one subdomain name (such as\n www.example.com).\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_traffic_policy)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_traffic_policy)\n \"\"\"\n def create_traffic_policy_instance(\n self,\n *,\n HostedZoneId: str,\n Name: str,\n TTL: int,\n TrafficPolicyId: str,\n TrafficPolicyVersion: int\n ) -> CreateTrafficPolicyInstanceResponseTypeDef:\n \"\"\"\n Creates resource record sets in a specified hosted zone based on the settings in\n a specified traffic policy version.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_traffic_policy_instance)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_traffic_policy_instance)\n \"\"\"\n def create_traffic_policy_version(\n self, *, Id: str, Document: str, Comment: str = None\n ) -> CreateTrafficPolicyVersionResponseTypeDef:\n \"\"\"\n Creates a new version of an existing traffic policy.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_traffic_policy_version)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_traffic_policy_version)\n \"\"\"\n def create_vpc_association_authorization(\n self, *, HostedZoneId: str, VPC: \"VPCTypeDef\"\n ) -> CreateVPCAssociationAuthorizationResponseTypeDef:\n \"\"\"\n Authorizes the Amazon Web Services account that created a specified VPC to\n submit an `AssociateVPCWithHostedZone` request to associate the VPC with a\n specified hosted zone that was created by a different account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.create_vpc_association_authorization)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#create_vpc_association_authorization)\n \"\"\"\n def deactivate_key_signing_key(\n self, *, HostedZoneId: str, Name: str\n ) -> DeactivateKeySigningKeyResponseTypeDef:\n \"\"\"\n Deactivates a key-signing key (KSK) so that it will not be used for signing by\n DNSSEC.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.deactivate_key_signing_key)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#deactivate_key_signing_key)\n \"\"\"\n def delete_cidr_collection(self, *, Id: str) -> Dict[str, Any]:\n \"\"\"\n Deletes a CIDR collection in the current Amazon Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.delete_cidr_collection)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#delete_cidr_collection)\n \"\"\"\n def delete_health_check(self, *, HealthCheckId: str) -> Dict[str, Any]:\n \"\"\"\n Deletes a health check.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.delete_health_check)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#delete_health_check)\n \"\"\"\n def delete_hosted_zone(self, *, Id: str) -> DeleteHostedZoneResponseTypeDef:\n \"\"\"\n Deletes a hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.delete_hosted_zone)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#delete_hosted_zone)\n \"\"\"\n def delete_key_signing_key(\n self, *, HostedZoneId: str, Name: str\n ) -> DeleteKeySigningKeyResponseTypeDef:\n \"\"\"\n Deletes a key-signing key (KSK).\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.delete_key_signing_key)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#delete_key_signing_key)\n \"\"\"\n def delete_query_logging_config(self, *, Id: str) -> Dict[str, Any]:\n \"\"\"\n Deletes a configuration for DNS query logging.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.delete_query_logging_config)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#delete_query_logging_config)\n \"\"\"\n def delete_reusable_delegation_set(self, *, Id: str) -> Dict[str, Any]:\n \"\"\"\n Deletes a reusable delegation set.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.delete_reusable_delegation_set)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#delete_reusable_delegation_set)\n \"\"\"\n def delete_traffic_policy(self, *, Id: str, Version: int) -> Dict[str, Any]:\n \"\"\"\n Deletes a traffic policy.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.delete_traffic_policy)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#delete_traffic_policy)\n \"\"\"\n def delete_traffic_policy_instance(self, *, Id: str) -> Dict[str, Any]:\n \"\"\"\n Deletes a traffic policy instance and all of the resource record sets that\n Amazon Route 53 created when you created the instance.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.delete_traffic_policy_instance)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#delete_traffic_policy_instance)\n \"\"\"\n def delete_vpc_association_authorization(\n self, *, HostedZoneId: str, VPC: \"VPCTypeDef\"\n ) -> Dict[str, Any]:\n \"\"\"\n Removes authorization to submit an `AssociateVPCWithHostedZone` request to\n associate a specified VPC with a hosted zone that was created by a different\n account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.delete_vpc_association_authorization)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#delete_vpc_association_authorization)\n \"\"\"\n def disable_hosted_zone_dnssec(\n self, *, HostedZoneId: str\n ) -> DisableHostedZoneDNSSECResponseTypeDef:\n \"\"\"\n Disables DNSSEC signing in a specific hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.disable_hosted_zone_dnssec)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#disable_hosted_zone_dnssec)\n \"\"\"\n def disassociate_vpc_from_hosted_zone(\n self, *, HostedZoneId: str, VPC: \"VPCTypeDef\", Comment: str = None\n ) -> DisassociateVPCFromHostedZoneResponseTypeDef:\n \"\"\"\n Disassociates an Amazon Virtual Private Cloud (Amazon VPC) from an Amazon Route\n 53 private hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.disassociate_vpc_from_hosted_zone)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#disassociate_vpc_from_hosted_zone)\n \"\"\"\n def enable_hosted_zone_dnssec(\n self, *, HostedZoneId: str\n ) -> EnableHostedZoneDNSSECResponseTypeDef:\n \"\"\"\n Enables DNSSEC signing in a specific hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.enable_hosted_zone_dnssec)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#enable_hosted_zone_dnssec)\n \"\"\"\n def generate_presigned_url(\n self,\n ClientMethod: str,\n Params: Dict[str, Any] = None,\n ExpiresIn: int = 3600,\n HttpMethod: str = None,\n ) -> str:\n \"\"\"\n Generate a presigned url given a client, its method, and arguments.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.generate_presigned_url)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#generate_presigned_url)\n \"\"\"\n def get_account_limit(self, *, Type: AccountLimitTypeType) -> GetAccountLimitResponseTypeDef:\n \"\"\"\n Gets the specified limit for the current account, for example, the maximum\n number of health checks that you can create using the account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_account_limit)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_account_limit)\n \"\"\"\n def get_change(self, *, Id: str) -> GetChangeResponseTypeDef:\n \"\"\"\n Returns the current status of a change batch request.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_change)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_change)\n \"\"\"\n def get_checker_ip_ranges(self) -> GetCheckerIpRangesResponseTypeDef:\n \"\"\"\n Route 53 does not perform authorization for this API because it retrieves\n information that is already available to the public.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_checker_ip_ranges)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_checker_ip_ranges)\n \"\"\"\n def get_dnssec(self, *, HostedZoneId: str) -> GetDNSSECResponseTypeDef:\n \"\"\"\n Returns information about DNSSEC for a specific hosted zone, including the key-\n signing keys (KSKs) in the hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_dnssec)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_dnssec)\n \"\"\"\n def get_geo_location(\n self, *, ContinentCode: str = None, CountryCode: str = None, SubdivisionCode: str = None\n ) -> GetGeoLocationResponseTypeDef:\n \"\"\"\n Gets information about whether a specified geographic location is supported for\n Amazon Route 53 geolocation resource record sets.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_geo_location)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_geo_location)\n \"\"\"\n def get_health_check(self, *, HealthCheckId: str) -> GetHealthCheckResponseTypeDef:\n \"\"\"\n Gets information about a specified health check.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_health_check)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_health_check)\n \"\"\"\n def get_health_check_count(self) -> GetHealthCheckCountResponseTypeDef:\n \"\"\"\n Retrieves the number of health checks that are associated with the current\n Amazon Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_health_check_count)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_health_check_count)\n \"\"\"\n def get_health_check_last_failure_reason(\n self, *, HealthCheckId: str\n ) -> GetHealthCheckLastFailureReasonResponseTypeDef:\n \"\"\"\n Gets the reason that a specified health check failed most recently.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_health_check_last_failure_reason)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_health_check_last_failure_reason)\n \"\"\"\n def get_health_check_status(self, *, HealthCheckId: str) -> GetHealthCheckStatusResponseTypeDef:\n \"\"\"\n Gets status of a specified health check.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_health_check_status)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_health_check_status)\n \"\"\"\n def get_hosted_zone(self, *, Id: str) -> GetHostedZoneResponseTypeDef:\n \"\"\"\n Gets information about a specified hosted zone including the four name servers\n assigned to the hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_hosted_zone)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_hosted_zone)\n \"\"\"\n def get_hosted_zone_count(self) -> GetHostedZoneCountResponseTypeDef:\n \"\"\"\n Retrieves the number of hosted zones that are associated with the current Amazon\n Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_hosted_zone_count)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_hosted_zone_count)\n \"\"\"\n def get_hosted_zone_limit(\n self, *, Type: HostedZoneLimitTypeType, HostedZoneId: str\n ) -> GetHostedZoneLimitResponseTypeDef:\n \"\"\"\n Gets the specified limit for a specified hosted zone, for example, the maximum\n number of records that you can create in the hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_hosted_zone_limit)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_hosted_zone_limit)\n \"\"\"\n def get_query_logging_config(self, *, Id: str) -> GetQueryLoggingConfigResponseTypeDef:\n \"\"\"\n Gets information about a specified configuration for DNS query logging.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_query_logging_config)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_query_logging_config)\n \"\"\"\n def get_reusable_delegation_set(self, *, Id: str) -> GetReusableDelegationSetResponseTypeDef:\n \"\"\"\n Retrieves information about a specified reusable delegation set, including the\n four name servers that are assigned to the delegation set.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_reusable_delegation_set)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_reusable_delegation_set)\n \"\"\"\n def get_reusable_delegation_set_limit(\n self, *, Type: Literal[\"MAX_ZONES_BY_REUSABLE_DELEGATION_SET\"], DelegationSetId: str\n ) -> GetReusableDelegationSetLimitResponseTypeDef:\n \"\"\"\n Gets the maximum number of hosted zones that you can associate with the\n specified reusable delegation set.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_reusable_delegation_set_limit)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_reusable_delegation_set_limit)\n \"\"\"\n def get_traffic_policy(self, *, Id: str, Version: int) -> GetTrafficPolicyResponseTypeDef:\n \"\"\"\n Gets information about a specific traffic policy version.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_traffic_policy)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_traffic_policy)\n \"\"\"\n def get_traffic_policy_instance(self, *, Id: str) -> GetTrafficPolicyInstanceResponseTypeDef:\n \"\"\"\n Gets information about a specified traffic policy instance.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_traffic_policy_instance)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_traffic_policy_instance)\n \"\"\"\n def get_traffic_policy_instance_count(self) -> GetTrafficPolicyInstanceCountResponseTypeDef:\n \"\"\"\n Gets the number of traffic policy instances that are associated with the current\n Amazon Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.get_traffic_policy_instance_count)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#get_traffic_policy_instance_count)\n \"\"\"\n def list_cidr_blocks(\n self,\n *,\n CollectionId: str,\n LocationName: str = None,\n NextToken: str = None,\n MaxResults: str = None\n ) -> ListCidrBlocksResponseTypeDef:\n \"\"\"\n Returns a paginated list of location objects and their CIDR blocks.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_cidr_blocks)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_cidr_blocks)\n \"\"\"\n def list_cidr_collections(\n self, *, NextToken: str = None, MaxResults: str = None\n ) -> ListCidrCollectionsResponseTypeDef:\n \"\"\"\n Returns a paginated list of CIDR collections in the Amazon Web Services account\n (metadata only).\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_cidr_collections)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_cidr_collections)\n \"\"\"\n def list_cidr_locations(\n self, *, CollectionId: str, NextToken: str = None, MaxResults: str = None\n ) -> ListCidrLocationsResponseTypeDef:\n \"\"\"\n Returns a paginated list of CIDR locations for the given collection (metadata\n only, does not include CIDR blocks).\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_cidr_locations)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_cidr_locations)\n \"\"\"\n def list_geo_locations(\n self,\n *,\n StartContinentCode: str = None,\n StartCountryCode: str = None,\n StartSubdivisionCode: str = None,\n MaxItems: str = None\n ) -> ListGeoLocationsResponseTypeDef:\n \"\"\"\n Retrieves a list of supported geographic locations.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_geo_locations)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_geo_locations)\n \"\"\"\n def list_health_checks(\n self, *, Marker: str = None, MaxItems: str = None\n ) -> ListHealthChecksResponseTypeDef:\n \"\"\"\n Retrieve a list of the health checks that are associated with the current Amazon\n Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_health_checks)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_health_checks)\n \"\"\"\n def list_hosted_zones(\n self, *, Marker: str = None, MaxItems: str = None, DelegationSetId: str = None\n ) -> ListHostedZonesResponseTypeDef:\n \"\"\"\n Retrieves a list of the public and private hosted zones that are associated with\n the current Amazon Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_hosted_zones)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_hosted_zones)\n \"\"\"\n def list_hosted_zones_by_name(\n self, *, DNSName: str = None, HostedZoneId: str = None, MaxItems: str = None\n ) -> ListHostedZonesByNameResponseTypeDef:\n \"\"\"\n Retrieves a list of your hosted zones in lexicographic order.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_hosted_zones_by_name)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_hosted_zones_by_name)\n \"\"\"\n def list_hosted_zones_by_vpc(\n self, *, VPCId: str, VPCRegion: VPCRegionType, MaxItems: str = None, NextToken: str = None\n ) -> ListHostedZonesByVPCResponseTypeDef:\n \"\"\"\n Lists all the private hosted zones that a specified VPC is associated with,\n regardless of which Amazon Web Services account or Amazon Web Services service\n owns the hosted zones.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_hosted_zones_by_vpc)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_hosted_zones_by_vpc)\n \"\"\"\n def list_query_logging_configs(\n self, *, HostedZoneId: str = None, NextToken: str = None, MaxResults: str = None\n ) -> ListQueryLoggingConfigsResponseTypeDef:\n \"\"\"\n Lists the configurations for DNS query logging that are associated with the\n current Amazon Web Services account or the configuration that is associated with\n a specified hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_query_logging_configs)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_query_logging_configs)\n \"\"\"\n def list_resource_record_sets(\n self,\n *,\n HostedZoneId: str,\n StartRecordName: str = None,\n StartRecordType: RRTypeType = None,\n StartRecordIdentifier: str = None,\n MaxItems: str = None\n ) -> ListResourceRecordSetsResponseTypeDef:\n \"\"\"\n Lists the resource record sets in a specified hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_resource_record_sets)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_resource_record_sets)\n \"\"\"\n def list_reusable_delegation_sets(\n self, *, Marker: str = None, MaxItems: str = None\n ) -> ListReusableDelegationSetsResponseTypeDef:\n \"\"\"\n Retrieves a list of the reusable delegation sets that are associated with the\n current Amazon Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_reusable_delegation_sets)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_reusable_delegation_sets)\n \"\"\"\n def list_tags_for_resource(\n self, *, ResourceType: TagResourceTypeType, ResourceId: str\n ) -> ListTagsForResourceResponseTypeDef:\n \"\"\"\n Lists tags for one health check or hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_tags_for_resource)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_tags_for_resource)\n \"\"\"\n def list_tags_for_resources(\n self, *, ResourceType: TagResourceTypeType, ResourceIds: List[str]\n ) -> ListTagsForResourcesResponseTypeDef:\n \"\"\"\n Lists tags for up to 10 health checks or hosted zones.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_tags_for_resources)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_tags_for_resources)\n \"\"\"\n def list_traffic_policies(\n self, *, TrafficPolicyIdMarker: str = None, MaxItems: str = None\n ) -> ListTrafficPoliciesResponseTypeDef:\n \"\"\"\n Gets information about the latest version for every traffic policy that is\n associated with the current Amazon Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_traffic_policies)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_traffic_policies)\n \"\"\"\n def list_traffic_policy_instances(\n self,\n *,\n HostedZoneIdMarker: str = None,\n TrafficPolicyInstanceNameMarker: str = None,\n TrafficPolicyInstanceTypeMarker: RRTypeType = None,\n MaxItems: str = None\n ) -> ListTrafficPolicyInstancesResponseTypeDef:\n \"\"\"\n Gets information about the traffic policy instances that you created by using\n the current Amazon Web Services account.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_traffic_policy_instances)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_traffic_policy_instances)\n \"\"\"\n def list_traffic_policy_instances_by_hosted_zone(\n self,\n *,\n HostedZoneId: str,\n TrafficPolicyInstanceNameMarker: str = None,\n TrafficPolicyInstanceTypeMarker: RRTypeType = None,\n MaxItems: str = None\n ) -> ListTrafficPolicyInstancesByHostedZoneResponseTypeDef:\n \"\"\"\n Gets information about the traffic policy instances that you created in a\n specified hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_traffic_policy_instances_by_hosted_zone)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_traffic_policy_instances_by_hosted_zone)\n \"\"\"\n def list_traffic_policy_instances_by_policy(\n self,\n *,\n TrafficPolicyId: str,\n TrafficPolicyVersion: int,\n HostedZoneIdMarker: str = None,\n TrafficPolicyInstanceNameMarker: str = None,\n TrafficPolicyInstanceTypeMarker: RRTypeType = None,\n MaxItems: str = None\n ) -> ListTrafficPolicyInstancesByPolicyResponseTypeDef:\n \"\"\"\n Gets information about the traffic policy instances that you created by using a\n specify traffic policy version.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_traffic_policy_instances_by_policy)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_traffic_policy_instances_by_policy)\n \"\"\"\n def list_traffic_policy_versions(\n self, *, Id: str, TrafficPolicyVersionMarker: str = None, MaxItems: str = None\n ) -> ListTrafficPolicyVersionsResponseTypeDef:\n \"\"\"\n Gets information about all of the versions for a specified traffic policy.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_traffic_policy_versions)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_traffic_policy_versions)\n \"\"\"\n def list_vpc_association_authorizations(\n self, *, HostedZoneId: str, NextToken: str = None, MaxResults: str = None\n ) -> ListVPCAssociationAuthorizationsResponseTypeDef:\n \"\"\"\n Gets a list of the VPCs that were created by other accounts and that can be\n associated with a specified hosted zone because you've submitted one or more\n `CreateVPCAssociationAuthorization` requests.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.list_vpc_association_authorizations)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#list_vpc_association_authorizations)\n \"\"\"\n def test_dns_answer(\n self,\n *,\n HostedZoneId: str,\n RecordName: str,\n RecordType: RRTypeType,\n ResolverIP: str = None,\n EDNS0ClientSubnetIP: str = None,\n EDNS0ClientSubnetMask: str = None\n ) -> TestDNSAnswerResponseTypeDef:\n \"\"\"\n Gets the value that Amazon Route 53 returns in response to a DNS request for a\n specified record name and type.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.test_dns_answer)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#test_dns_answer)\n \"\"\"\n def update_health_check(\n self,\n *,\n HealthCheckId: str,\n HealthCheckVersion: int = None,\n IPAddress: str = None,\n Port: int = None,\n ResourcePath: str = None,\n FullyQualifiedDomainName: str = None,\n SearchString: str = None,\n FailureThreshold: int = None,\n Inverted: bool = None,\n Disabled: bool = None,\n HealthThreshold: int = None,\n ChildHealthChecks: List[str] = None,\n EnableSNI: bool = None,\n Regions: List[HealthCheckRegionType] = None,\n AlarmIdentifier: \"AlarmIdentifierTypeDef\" = None,\n InsufficientDataHealthStatus: InsufficientDataHealthStatusType = None,\n ResetElements: List[ResettableElementNameType] = None\n ) -> UpdateHealthCheckResponseTypeDef:\n \"\"\"\n Updates an existing health check.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.update_health_check)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#update_health_check)\n \"\"\"\n def update_hosted_zone_comment(\n self, *, Id: str, Comment: str = None\n ) -> UpdateHostedZoneCommentResponseTypeDef:\n \"\"\"\n Updates the comment for a specified hosted zone.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.update_hosted_zone_comment)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#update_hosted_zone_comment)\n \"\"\"\n def update_traffic_policy_comment(\n self, *, Id: str, Version: int, Comment: str\n ) -> UpdateTrafficPolicyCommentResponseTypeDef:\n \"\"\"\n Updates the comment for a specified traffic policy version.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.update_traffic_policy_comment)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#update_traffic_policy_comment)\n \"\"\"\n def update_traffic_policy_instance(\n self, *, Id: str, TTL: int, TrafficPolicyId: str, TrafficPolicyVersion: int\n ) -> UpdateTrafficPolicyInstanceResponseTypeDef:\n \"\"\"\n Updates the resource record sets in a specified hosted zone that were created\n based on the settings in a specified traffic policy version.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Client.update_traffic_policy_instance)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/client.html#update_traffic_policy_instance)\n \"\"\"\n @overload\n def get_paginator(self, operation_name: Literal[\"list_cidr_blocks\"]) -> ListCidrBlocksPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Paginator.ListCidrBlocks)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/paginators.html#listcidrblockspaginator)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_cidr_collections\"]\n ) -> ListCidrCollectionsPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Paginator.ListCidrCollections)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/paginators.html#listcidrcollectionspaginator)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_cidr_locations\"]\n ) -> ListCidrLocationsPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Paginator.ListCidrLocations)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/paginators.html#listcidrlocationspaginator)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_health_checks\"]\n ) -> ListHealthChecksPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Paginator.ListHealthChecks)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/paginators.html#listhealthcheckspaginator)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_hosted_zones\"]\n ) -> ListHostedZonesPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Paginator.ListHostedZones)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/paginators.html#listhostedzonespaginator)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_query_logging_configs\"]\n ) -> ListQueryLoggingConfigsPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Paginator.ListQueryLoggingConfigs)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/paginators.html#listqueryloggingconfigspaginator)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_resource_record_sets\"]\n ) -> ListResourceRecordSetsPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Paginator.ListResourceRecordSets)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/paginators.html#listresourcerecordsetspaginator)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_vpc_association_authorizations\"]\n ) -> ListVPCAssociationAuthorizationsPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Paginator.ListVPCAssociationAuthorizations)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/paginators.html#listvpcassociationauthorizationspaginator)\n \"\"\"\n def get_waiter(\n self, waiter_name: Literal[\"resource_record_sets_changed\"]\n ) -> ResourceRecordSetsChangedWaiter:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/route53.html#Route53.Waiter.ResourceRecordSetsChanged)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_route53/waiters.html#resourcerecordsetschangedwaiter)\n \"\"\"\n","sub_path":"typings/mypy_boto3_route53/client.pyi","file_name":"client.pyi","file_ext":"pyi","file_size_in_byte":55608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274980340","text":"import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import pyqtSlot\n\nclass App(QWidget):\n\n def __init__(self):\n super().__init__()\n self.title = 'Test'\n self.left = 0\n self.top = 0\n self.width = 1100\n self.height = 400\n\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n self.createTable()\n\n # Add box layout, add table to box layout and add box layout to widget\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.tableWidget)\n self.setLayout(self.layout)\n\n # Show window widget\n self.show()\n\n def createTable(self):\n # Create table\n self.tableWidget = QTableWidget()\n\n # Make this less hardcoded\n wifi_networks = [\n [\"The Pit Of Dispair\", \"52:6e:de:5c:58:25\", 6, -64, \"{WPA2/PSK}\"],\n [\"The Pit Of Despair\", \"84:a0:6e:f0:7f:46\", 11, -49, \"{WPA2/PSK}\"],\n [\"DirtyBirdy\", \"50:c7:bf:31:60:96\", 10, -88, \"{WPA/PSK, WPA2/PSK}\"],\n [\"hello there\", \"a8:6a:bb:e6:8f:0e\", 1, -89, \"{WEP}\"],\n [\"Lalonde\", \"10:be:f5:26:11:c8\", 11, -91, \"{WPA/PSK, WPA2/PSK}\"],\n [\"COGECO-ABB00\", \"84:0b:7c:8a:bb:08\", 11, -88, \"{WPA2/PSK}\"]]\n\n # Values based on wifi_networks list\n numRows = len(wifi_networks)\n numCols = len(wifi_networks[0])\n\n # Set table size based on wifi_networks list\n self.tableWidget.setColumnCount(numCols)\n self.tableWidget.setRowCount(numRows)\n\n # Added appropriate headers\n self.tableWidget.setHorizontalHeaderLabels(('SSID', 'BSSID', 'Channel','Signal dBm','Security'))\n self.tableWidget.verticalHeader().setVisible(False)\n\n # Populate the table\n for row in range(numRows):\n for column in range(numCols):\n # Set numbers to strings?\n # if isinstance(wifi_networks[row][column],type(num)):\n #\n # else:\n self.tableWidget.setItem(row, column, QTableWidgetItem((wifi_networks[row][column])))\n\n # Rebecca u can remove this chunk, it served as our first attempt to populate the table\n # self.tableWidget.setItem(0,0, QTableWidgetItem(\"The Pit Of Dispair\"))\n # self.tableWidget.setItem(0,1, QTableWidgetItem(\"52:6e:de:5c:58:25\"))\n # self.tableWidget.setItem(0,2, QTableWidgetItem('6'))\n # self.tableWidget.setItem(0,3, QTableWidgetItem('-64'))\n # self.tableWidget.setItem(0,4, QTableWidgetItem(\"{WPA2/PSK}\"))\n #\n # self.tableWidget.setItem(1,0, QTableWidgetItem(\"DirtyBirdy\"))\n # self.tableWidget.setItem(1,1, QTableWidgetItem(\"50:c7:bf:31:60:96\"))\n # self.tableWidget.setItem(1,2, QTableWidgetItem('10'))\n # self.tableWidget.setItem(1,3, QTableWidgetItem('-84'))\n # self.tableWidget.setItem(1,4, QTableWidgetItem(\"{WPA/PSK, WPA2/PSK}\"))\n\n\n #Table will fit the screen horizontally\n self.tableWidget.horizontalHeader().setStretchLastSection(True)\n self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = App()\n sys.exit(app.exec_())\n","sub_path":"tablewidget.py","file_name":"tablewidget.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234847076","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 2 12:35:54 2021\n\n@author: danielpazing\n\nwww.logsis.com.ar\n\nRealiza graficos de velas de un dtaframe de precios de un ticker\nque tenga el formato OCLHV\nsin necesidad de ninguna libreria adicional a matplotlib\n\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n########## GRAFICADORES\n\ndef graf_velas(data):\n \"\"\"\n Construye un grafico de velas directamente desde matplotlib\n Input: grafico formato open.close.high.low\n \"\"\"\n\n data[\"Vardia\"] = abs(data[\"Open\"] - data[\"Close\"])\n data[\"Rango\"] =data[\"High\"]-data[\"Low\"]\n data[\"Pmedio\"]=(data[\"High\"]+data[\"Low\"]+data[\"Open\"]+data[\"Close\"])/4\n data[\"Base\"] = np.where(data[\"Open\"]data[\"Close\"]]\n \n plt.grid(color=\"lightgray\",linestyle='-')\n plt.bar(data.index, data[\"Rango\"], bottom=data[\"Low\"],width=0.1,color=\"black\" )\n plt.bar(data.index, data[\"Vardia\"], bottom=data[\"Base\"],width= 1,color=data.Color )\n plt.plot(data.index, data[\"Pmedio\"],color=\"black\", linestyle=\"--\",linewidth=1)\n \n return data[\"Pmedio\"]","sub_path":"Funcion_grafico_velas.py","file_name":"Funcion_grafico_velas.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335596396","text":"from django.urls import path, re_path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"wiki/\", views.entryPage, name=\"entry_page\"),\n path(\"search\", views.search, name=\"search\"),\n path(\"create_new_page\", views.createNewPage, name=\"create_new_page\"),\n path(\"edit_page/\", views.editPage, name=\"edit_page\"),\n path(\"random_page\", views.randomPage, name=\"random_page\")\n]\n","sub_path":"encyclopedia/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"412066276","text":"from flask import Flask, redirect, url_for, render_template, request\nfrom characters import Character, skeleton, wraith\nimport random\nimport csv\nimport json\n\napp = Flask(__name__)\n\nenemy = skeleton\nhero = Character(0,\"Empty\", 1, True, 1, 1, 1, 1, 1, 1, 1, 1, \"Empty\")\nuserid = 0\nuserid += 1\nlvldict = {\"lvl0\": 0, \"lvl1\":1, 'lvl2': 300, 'lvl3': 1000, 'lvl4':2000, 'lvl5':5000,'lvl6':8000,'lvl7':12000}\n\n\n\n\n\ndef write_to_file(data):\n with open('database.txt', mode='r+') as database:\n global userid\n userid += len(database.readlines())\n data['userid'] = userid\n username = data[\"warriorname\"]\n password = data[\"password\"]\n charactername = data[\"username\"]\n userage = data['age']\n data['useralive'] = True\n data['userhp'] = 30\n data['userac'] = 6\n data['userxp'] = 1\n data['userlvl'] = 1\n data['userammo'] = 6\n data['userstr'] =(random.randint(3, 18))\n data['userdex'] = (random.randint(3, 18))\n data['usercon'] = (random.randint(3, 18))\n data['userofd'] = data['objectOfDesire']\n file = database.write(json.dumps(data))\n file = database.write('\\n')\n userid -= 1\n\n\ndef write_to_csv(data):\n with open('database.csv', newline='',mode='r+') as database2:\n global userid\n userid += len(database2.readlines())\n username = data[\"warriorname\"]\n password = data[\"password\"]\n charactername = data[\"username\"]\n userage = data['age']\n useralive = True\n userhp = 30\n userac = 6\n userxp = 1\n userlvl = 1\n userammo = 6\n userstr = (random.randint(3, 18))\n userdex = (random.randint(3, 18))\n usercon = (random.randint(3, 18))\n userofd = data['objectOfDesire']\n csv_writer = csv.writer(database2,delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n csv_writer.writerow([userid,username,password,charactername,userage,useralive,userhp,userac,userxp,userlvl,userammo,userstr,userdex,usercon,userofd])\n\ndef checkregistry(data):\n with open('database.txt', mode='r') as database:\n if data[\"warriorname\"] and data[\"password\"] in database:\n print('already exists')\n return redirect(\"/signin.html\")\n else:\n write_to_file(data)\n write_to_csv(data)\n global userid\n userid += len(database.readlines())\n username = data[\"warriorname\"]\n password = data[\"password\"]\n charactername = data[\"username\"]\n userage = data['age']\n useralive = True\n userhp = 30\n userac = 6\n userxp = 1\n userlvl = 1\n userammo = 6\n userstr = (random.randint(3, 18))\n userdex = (random.randint(3, 18))\n usercon = (random.randint(3, 18))\n userofd = data['objectOfDesire']\n print('wrote to file')\n global hero\n hero = Character(userid,charactername, userage, useralive, userhp, userac, userxp, userlvl, userammo, userstr, userdex, usercon, userofd)\n print(hero.name)\n\n\ndef signinfunc(data):\n with open('database.txt', mode='r') as database:\n for line in database.readlines():\n hgrab = json.loads(line)\n if data[\"warriorname\"] == hgrab[\"warriorname\"] and data[\"password\"] == hgrab[\"password\"]:\n print('character found')\n global hero\n hero = Character(hgrab[\"userid\"],hgrab[\"username\"],hgrab[\"age\"],hgrab[\"useralive\"],hgrab[\"userhp\"],hgrab[\"userac\"],hgrab[\"userxp\"],hgrab[\"userlvl\"],hgrab[\"userammo\"],hgrab[\"userstr\"],hgrab[\"userdex\"],hgrab[\"usercon\"],hgrab[\"userofd\"])\n else:\n print('character not found')\n\n\n\n@app.route(\"/\", methods=[\"POST\", \"GET\"])\ndef signin():\n return render_template(\"signin.html\")\n\n@app.route('/characternotfound', methods=[\"POST\",\"GET\"])\ndef characternotfound():\n return render_template(\"characternotfound.html\")\n\n@app.route(\"/register\", methods=[\"POST\", \"GET\"])\ndef register():\n if request.method == 'POST':\n data = request.form.to_dict()\n print(data)\n checkregistry(data)\n return render_template('character.html', name=hero.name, obj=hero.ofd, hero=hero)\n else:\n return 'something went wrong'\n\n@app.route(\"/signcheck\", methods=[\"POST\", \"GET\"])\ndef signcheck():\n if request.method == 'POST':\n global data\n data = request.form.to_dict()\n signinfunc(data)\n return render_template('character.html', name=hero.name, obj=hero.ofd, hero=hero)\n else:\n return 'something went wrong'\n\n\n\n\n\n@app.route(\"/index\", methods=[\"POST\", \"GET\"])\ndef home():\n return render_template(\"index.html\")\n\n@app.route(\"/character\", methods=[\"POST\", \"GET\"])\ndef character():\n return render_template(\"character.html\", name = username, obj= userofd, hero=hero)\n\n@app.route('/arena', methods=[\"POST\", \"GET\"])\ndef arena():\n while enemy.alive == True and hero.alive == True:\n # enemyattack\n strike = (random.randint(1, 20))\n if strike < hero.ac:\n combatmessage = \"The beast slashes with it's claws but barely misses!\"\n break\n else:\n e1damage = (random.randint(1, 8))\n hero.hp -= e1damage\n combatmessage = (f\"\\nThe beast's claws rip into your flesh for {e1damage} damage! \")\n if hero.hp <= 0:\n hero.alive = False\n return render_template(\"dead.html\")\n break\n else:\n break\n if enemy.name == 'Wraith':\n if enemy.alive == False:\n return render_template(\"gameover.html\")\n else:\n pass\n\n return render_template(\"arena.html\", enemy= enemy, hero=hero, combatmessage=combatmessage)\n\n@app.route('/wraith', methods=[\"POST\", \"GET\"])\ndef wraithfight():\n global enemy\n enemy = wraith\n while enemy.alive == True and hero.alive == True:\n attacktyperoll = (random.randint(1, 10))\n if attacktyperoll <= 5:\n strike = (random.randint(1, 20))\n if strike < hero.ac:\n combatmessage = \"The beast slashes with it's claws but barely misses!\"\n break\n else:\n e1damage = (random.randint(1, 8))\n hero.hp -= e1damage\n combatmessage = (f\"\\nThe beast's claws rip into your flesh for {e1damage} damage! \")\n if hero.hp <= 0:\n hero.alive = False\n return render_template(\"dead.html\", combatmessage = combatmessage)\n break\n else:\n break\n else:\n agestrike = (random.randint(1, 23))\n if agestrike < hero.con:\n combatmessage = \"It's eyes probe deep but you look away just in time!\"\n break\n else:\n e1damage = (random.randint(1, 10))\n ageint = int(hero.age)\n ageint -= e1damage\n combatmessage = (f\"\\nThe Wraith's eyes probe deep in your soul and take away {e1damage} years! \")\n if hero.age <= 0:\n hero.alive = False\n return render_template(\"dead.html\", combatmessage=combatmessage)\n break\n else:\n break\n\n if enemy.name == 'Wraith':\n if enemy.alive == False:\n return render_template(\"gameover.html\")\n else:\n pass\n\n return render_template(\"wraith.html\", enemy= enemy, hero=hero, combatmessage=combatmessage)\n\n@app.route('/arenadagger', methods=[\"POST\", \"GET\"])\ndef arenadagger():\n # my attack\n while enemy.alive == True and hero.alive == True:\n ha = (random.randint(1, 18))\n if ha < enemy.ac:\n heromessage = \"You missed!\"\n break\n else:\n dagger_damage = (random.randint(1, 8))\n enemy.hp -= dagger_damage\n heromessage = (f\"You slash into the beast for {dagger_damage} damage!\")\n if enemy.hp < 0:\n enemy.alive = False\n hero.xp += enemy.xp\n if hero.xp >= lvldict[f\"lvl{hero.lvl + 1}\"]:\n hero.lvlup()\n heromessage = (f\"\\nYour dagger slashs deep and the bastard falls to the dust. The crowd chants the\\nname of their champion: {hero.name}!\"\n f\"\\nYou've leveled up! You are now level {hero.lvl}\".upper())\n else:\n heromessage = (f\"\\nYour dagger slashs deep and the bastard falls to the dust. The crowd chants the\\nname of their champion: {hero.name}!\".upper())\n pass\n heromessage= (f\"\\nYour dagger slashs deep and the bastard falls to the dust. The crowd chants the\\nname of their champion: {hero.name}!\".upper())\n return render_template(\"enemydead.html\", heromessage=heromessage, enemy= enemy, hero=hero)\n else:\n break\n return render_template(\"arenadagger.html\", heromessage=heromessage, enemy= enemy, hero=hero)\n\n@app.route('/arenastone', methods=[\"POST\", \"GET\"])\ndef arenastone():\n while enemy.alive == True and hero.alive == True:\n if hero.ammo<=0:\n heromessage = (\"You are out of stones!\")\n break\n else:\n ha = (random.randint(1,19))\n hero.ammo -= 1\n ammomessage = (f\"\\nYou now have {hero.ammo} stones left!\")\n if ha < enemy.ac:\n heromessage = \"You missed!\"\n break\n else:\n stone_damage = (random.randint(1,8))\n enemy.hp -= stone_damage\n heromessage = (f\"\\nYour stone sails true for {stone_damage} damage!\")\n if enemy.hp < 0:\n enemy.alive = False\n hero.xp += enemy.xp\n if hero.xp >= lvldict[f\"lvl{hero.lvl + 1}\"]:\n hero.lvlup()\n heromessage = (f\"\\nThe stone lands with a sickening thud and the bastard falls to the dust. The crowd chants the\\nname of their champion: {hero.name}!\"\n f\"\\nYou've leveled up! You are now level {hero.lvl}\".upper())\n\n else:\n heromessage = (f\"\\nThe stone lands with a sickening thud and the bastard falls to the dust. The crowd chants the\\nname of their champion: {hero.name}!\".upper())\n pass\n return render_template(\"enemydead.html\", heromessage=heromessage, enemy= enemy, hero=hero)\n else:\n break\n\n return render_template(\"arenastone.html\" ,heromessage=heromessage, enemy= enemy, hero=hero, ammomessage=ammomessage )\n\n@app.route(\"/arenapotion\", methods=[\"POST\",\"GET\"])\ndef drinkpotion():\n potion = (random.randint(1, 10))\n hero.hp += potion\n heromessage = (f\"\\nYou drink deeply of the healing vial and recieve {potion} hit points!\")\n return render_template(\"arenapotion.html\", heromessage=heromessage, hero=hero, enemy=enemy)\n\n\n@app.route(\"/enemydead\", methods=[\"POST\",\"GET\"])\ndef enemydead():\n return render_template(\"enemydead.html\",heromessage = heromessage, enemy = enemy, hero = hero, ammomessage=ammomessage)\n\n@app.route(\"/gameover\", methods=[\"POST\",\"GET\"])\ndef gameover():\n return render_template(\"gameover.html\",heromessage = heromessage, enemy = enemy, hero = hero )\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"407579908","text":"import bellman, csv\n\nwhile(True):\n cmd = input().split(\" \")\n if(cmd[0]==\"help\"):\n print(\"How to use graphator : 'command' 'file' 'algorithm' 'arguments'\\n\")\n elif(cmd[0]==\"solve\"):\n matrix = []\n results = []\n with open (cmd[1], newline='') as matrix_file:\n matrix_reader = csv.reader(matrix_file, delimiter=',')\n for row in matrix_reader :\n matrix.append(row)\n for index in range(0, len(matrix)):\n matrix[index] = list(map(float,matrix[index]))\n if(cmd[2]==\"bellman_min\"):\n results = bellman.bellman_min(matrix, int(cmd[3]))\n elif(cmd[2]==\"bellman_max\"):\n results = bellman.bellman_max(matrix, int(cmd[3]))\n elif(cmd[2]==\"bellman_ford_kalaba\"):\n results = bellman.bellman_ford_kalaba(matrix, int(cmd[3]))\n print(\"Results : {}\".format(results))\n elif(cmd[0]==\"exit\"):\n break\n\n","sub_path":"Graphator/graphator.py","file_name":"graphator.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"523701947","text":"import itertools\nimport pickle\nimport time\nfrom enum import Enum\nfrom functools import wraps\nfrom inspect import currentframe\nfrom pathlib import Path\nimport concurrent.futures\nimport functools\n\nimport cv2\nimport matplotlib as mpl\nimport matplotlib.gridspec as gridspec\nimport matplotlib.patches as patches\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport openslide \nfrom PIL import Image\nfrom probreg import cpd\nfrom probreg import transformation as tf\nfrom sklearn.neighbors import LocalOutlierFactor\n\n\nclass NodeOrientation(Enum):\n \"\"\"[summary]\n Quad-Tree node orientation\n Args:\n Enum ([type]): [description]\n \"\"\"\n TOP = 0\n NORTH_WEST = 1\n NORTH_EAST = 2\n SOUTH_WEST = 3\n SOUTH_EAST = 4\n\n\nclass Point:\n \"\"\"A point located at (x,y) in 2D space.\n\n Each Point object may be associated with a payload object.\n\n \"\"\"\n\n def __init__(self, x, y, payload=None):\n self.x, self.y = x, y\n self.payload = payload\n\n def __repr__(self):\n return '{}: {}'.format(str((self.x, self.y)), repr(self.payload))\n def __str__(self):\n return 'P({:.2f}, {:.2f})'.format(self.x, self.y)\n\n def distance_to(self, other):\n try:\n other_x, other_y = other.x, other.y\n except AttributeError:\n other_x, other_y = other\n return np.hypot(self.x - other_x, self.y - other_y)\n\nclass Rect:\n \"\"\"A rectangle centred at (cx, cy) with width w and height h.\"\"\"\n\n def __init__(self, cx, cy, w, h):\n self.cx, self.cy = cx, cy\n self.w, self.h = w, h\n self.west_edge, self.east_edge = cx - w/2, cx + w/2\n self.north_edge, self.south_edge = cy - h/2, cy + h/2\n\n def __repr__(self):\n return str((self.west_edge, self.east_edge, self.north_edge,\n self.south_edge))\n\n def __str__(self):\n return '({:.2f}, {:.2f}, {:.2f}, {:.2f})'.format(self.west_edge,\n self.north_edge, self.east_edge, self.south_edge)\n\n def create(cls, x, y, w, h):\n\n cx, cy = x + w // 2, y + h // 2\n\n return cls(cx, cy, w, h)\n\n def is_valid(self):\n return self.w > 0 and self.h > 0\n\n\n def contains(self, point):\n \"\"\"Is point (a Point object or (x,y) tuple) inside this Rect?\"\"\"\n\n try:\n point_x, point_y = point.x, point.y\n except AttributeError:\n point_x, point_y = point\n\n return (point_x >= self.west_edge and\n point_x < self.east_edge and\n point_y >= self.north_edge and\n point_y < self.south_edge)\n\n def intersects(self, other):\n \"\"\"Does Rect object other interesect this Rect?\"\"\"\n return not (other.west_edge > self.east_edge or\n other.east_edge < self.west_edge or\n other.north_edge > self.south_edge or\n other.south_edge < self.north_edge)\n\n def draw(self, ax, c='k', lw=1, **kwargs):\n x1, y1 = self.west_edge, self.north_edge\n x2, y2 = self.east_edge, self.south_edge\n ax.plot([x1,x2,x2,x1,x1],[y1,y1,y2,y2,y1], c=c, lw=lw, **kwargs)\n\nclass RegistrationQuadTree:\n \"\"\"[summary]\n\n A class implementing the registration quadtree.\n\n \"\"\"\n\n def __init__(self, source_slide_path:Path, target_slide_path:Path, source_boundary:Rect=None, target_boundary:Rect=None,\n depth=0, target_depth=1, thumbnail_size=(2048, 2048),\n run_async=False, node_orientation:NodeOrientation = NodeOrientation.TOP,\n parent=None, homography:bool=True, filter_outliner:bool=False, num_workers:int=2, **kwargs):\n \"\"\"[summary]\n Init the current quadtree level\n\n Args:\n source_slide_path ([Path]): [source slide path as Path object]\n target_slide_path ([Path]): [target slide path as Path object]\n source_boundary ([Rect]): [source wsi region of interest]\n target_boundary ([Rect]): [target wsi region of interest]\n depth (int, optional): [current depth]. Defaults to 0.\n target_depth (int, optional): [maximal number of qt levels]. Defaults to 4.\n thumbnail_size (tuple, optional): [size of the thumbnail to extract keypoints from]. Defaults to (2048, 2048).\n run_async (bool, optional): [generate the quad-tree in a parallel maner]. Defaults to False.\n node_orientation (NodeOrientation, optional): [defines the four note orientations]. Defaults to NodeOrientation.TOP.\n parent ([RegistrationQuadTree], optional): [parent quad-tree]. Defaults to None.\n homography (bool, optional): [use cv.findHomography or a probReg]. Defaults to True.\n filter_outliner (bool, optional): [description]. Defaults to False.\n num_workers (int, optional): [current depth]. Defaults to 2.\n \"\"\"\n\n\n kwargs.update({\"run_async\":run_async, \"thumbnail_size\":thumbnail_size, \"homography\":homography, \n \"filter_outliner\":filter_outliner, \"target_depth\":target_depth, \"num_workers\": num_workers})\n \n self.kwargs = kwargs\n self.parent = parent\n self.node_orientation = node_orientation\n self.run_async = run_async\n self.thumbnail_size = thumbnail_size\n self.depth = depth\n self.target_depth = target_depth \n self.num_workers = num_workers\n self.source_slide_path = source_slide_path if isinstance(source_slide_path, Path) else Path(source_slide_path)\n self.target_slide_path = target_slide_path if isinstance(target_slide_path, Path) else Path(target_slide_path)\n\n self._target_slide_dimensions = None\n self._source_slide_dimensions = None \n\n self.source_boundary = source_boundary\n self.target_boundary = target_boundary \n \n if self.source_boundary == None: \n source_slide = openslide.open_slide(str(source_slide_path))\n self._source_slide_dimensions = source_slide.dimensions\n self.source_boundary = Rect.create(Rect, 0, 0, source_slide.dimensions[0], source_slide.dimensions[1])\n\n if self.target_boundary == None: \n target_slide = openslide.open_slide(str(target_slide_path)) \n self._target_slide_dimensions = target_slide.dimensions\n self.target_boundary = Rect.create(Rect, 0, 0, target_slide.dimensions[0], target_slide.dimensions[1])\n\n # start timer\n tic = time.perf_counter()\n\n if True: #self.run_async\n with concurrent.futures.ThreadPoolExecutor() as executor: # ProcessPoolExecutor ThreadPoolExecutor\n source_func = functools.partial(RegistrationQuadTree.get_region_thumbnail, slide_path=self.source_slide_path, boundary=self.source_boundary, depth=self.depth + 1, size=self.thumbnail_size)\n target_func = functools.partial(RegistrationQuadTree.get_region_thumbnail, slide_path=self.target_slide_path, boundary=self.target_boundary, depth=self.depth + 1, size=self.thumbnail_size)\n\n submitted = {executor.submit(func) : area for func, area in zip([source_func, target_func], [\"source\", \"target\"])}\n for future in concurrent.futures.as_completed(submitted):\n try:\n if submitted[future] == \"source\":\n self.source_thumbnail, self.source_scale = future.result()\n else:\n self.target_thumbnail, self.target_scale = future.result()\n except Exception as exc:\n print('%r generated an exception: %s' % (submitted[future], exc))\n else:\n self.source_thumbnail, self.source_scale = RegistrationQuadTree.get_region_thumbnail(slide_path=self.source_slide_path, boundary=self.source_boundary, depth=self.depth + 1, size=self.thumbnail_size)\n self.target_thumbnail, self.target_scale = RegistrationQuadTree.get_region_thumbnail(slide_path=self.target_slide_path, boundary=self.target_boundary, depth=self.depth + 1, size=self.thumbnail_size)\n \n self.ptsA, self.ptsB, self.matchedVis = self.extract_matching_points(self.source_thumbnail, self.target_thumbnail, source_scale=self.source_scale, target_scale=self.target_scale, **kwargs)\n\n if filter_outliner:\n self.ptsA, self.ptsB, self.scale_factors = self.filter_outliner(self.ptsA, self.ptsB)\n \n if homography:\n self.mean_reg_error, self.sigma2, self.q, self.tf_param = self._get_min_reg_error_hom(self.ptsA, self.ptsB)\n else:\n self.tf_param, self.sigma2, self.q = cpd.registration_cpd(self.ptsA, self.ptsB, 'affine')\n self.mean_reg_error = np.linalg.norm(self.tf_param.transform(self.ptsA)-self.ptsB, axis=1).mean()\n\n mean_reg_error, _, _, tf_param = self._get_min_reg_error_hom(self.ptsA, self.ptsB)\n\n if self.mean_reg_error > mean_reg_error:\n self.mean_reg_error = self.mean_reg_error\n self.tf_param = tf_param\n\n\n self.b = self.tf_param.b\n self.t = self.tf_param.t\n self.mpp_x_scale = self.tf_param.b[0][0]\n self.mpp_y_scale = self.tf_param.b[1][1]\n\n self.max_points = len(self.ptsA)\n self.points = self.ptsA\n # A flag to indicate whether this node has divided (branched) or not.\n self.divided = False\n\n self.nw, self.ne, self.se, self.sw = None, None, None, None\n if depth < target_depth:\n self.divide()\n\n # done stop timer\n toc = time.perf_counter()\n self.run_time = toc - tic\n\n\n def _get_min_reg_error_hom(self, ptsA, ptsB):\n mean_reg_error = 99999999\n\n tf_param = None\n for outline_filter in [0, cv2.RANSAC, cv2.RHO, cv2.LMEDS]:\n homography, mask = cv2.findHomography(self.ptsA, self.ptsB, outline_filter) \n temp_tf_param = tf.AffineTransformation(homography[:2, :2], homography[:2, 2:].reshape(-1))\n\n temp_mean_reg_error = np.linalg.norm(temp_tf_param.transform(ptsA)-ptsB, axis=1).mean()\n if temp_mean_reg_error < mean_reg_error:\n mean_reg_error = temp_mean_reg_error\n sigma2, q, tf_param = -1, -1, temp_tf_param\n\n return mean_reg_error, sigma2, q, tf_param\n\n @property\n def source_thumbnail(self):\n\n if self._source_thumbnail is None:\n self.source_thumbnail, self.source_scale = self.get_region_thumbnail(self.source_slide, self.source_boundary, self.thumbnail_size)\n\n return self._source_thumbnail\n\n @source_thumbnail.setter \n def source_thumbnail(self, thumbnail):\n self._source_thumbnail = thumbnail\n\n @property\n def target_thumbnail(self):\n\n if self._target_thumbnail is None:\n self._target_thumbnail, self.target_scale = self.get_region_thumbnail(self.target_slide, self.target_boundary, self.thumbnail_size)\n\n return self._target_thumbnail\n\n @target_thumbnail.setter \n def target_thumbnail(self, thumbnail):\n self._target_thumbnail = thumbnail\n\n\n @property\n def source_slide_dimensions(self):\n\n if self._source_slide_dimensions is None:\n self.source_slide_dimensions = openslide.open_slide(str(self.source_slide_path)).dimensions\n \n return self._source_slide_dimensions\n\n @source_slide_dimensions.setter \n def source_slide_dimensions(self, dimensions):\n\n self._source_slide_dimensions = dimensions\n\n if self.nw is not None: self.nw.source_slide_dimensions = dimensions\n if self.ne is not None: self.ne.source_slide_dimensions = dimensions\n if self.se is not None: self.se.source_slide_dimensions = dimensions\n if self.sw is not None: self.sw.source_slide_dimensions = dimensions\n\n\n @property\n def target_slide_dimensions(self):\n\n if self._target_slide_dimensions is None:\n self._target_slide_dimensions = openslide.open_slide(str(self.target_slide_path)).dimensions\n \n return self._target_slide_dimensions\n\n @target_slide_dimensions.setter \n def target_slide_dimensions(self, dimensions):\n\n self._target_slide_dimensions = dimensions\n\n if self.nw is not None: self.nw.target_slide_dimensions = dimensions\n if self.ne is not None: self.ne.target_slide_dimensions = dimensions\n if self.se is not None: self.se.target_slide_dimensions = dimensions\n if self.sw is not None: self.sw.target_slide_dimensions = dimensions\n\n @property\n def source_path(self):\n return self.source_slide_path\n \n @property\n def target_path(self):\n return self.target_slide_path\n\n @property\n def source_name(self):\n return self.source_slide_path.stem\n \n @property\n def target_name(self):\n return self.target_slide_path.stem\n \n def __str__(self):\n \"\"\"Return a string representation of this node, suitably formatted.\"\"\"\n sp = ' ' * self.depth * 2\n \n s = \"\"\n if self.depth == 0:\n s += f\"Source: {self.source_name} \\n\"\n s += f\"Target: {self.target_name} \\n\"\n \n s += f\"Source: {self.source_boundary} Target: {self.target_boundary}\" + '\\n' \n s += sp + f'x: [{self.tf_param.b[0][0]:4.3f}, {self.tf_param.b[0][1]:4.3f}, {self.tf_param.t[0]:4.3f}], y: [{self.tf_param.b[1][0]:4.3f}, {self.tf_param.b[1][1]:4.3f}, {self.tf_param.t[1]:4.3f}]] error: {self.mean_reg_error:4.3f}'\n if not self.divided:\n return s\n return s + '\\n' + '\\n'.join([\n sp + 'nw: ' + str(self.nw), sp + 'ne: ' + str(self.ne),\n sp + 'se: ' + str(self.se), sp + 'sw: ' + str(self.sw)])\n\n def divide(self):\n \"\"\"Divide (branch) this node by spawning four children nodes.\"\"\"\n\n source_cx, source_cy = self.source_boundary.cx, self.source_boundary.cy\n source_w, source_h = self.source_boundary.w / 2, self.source_boundary.h / 2\n\n # transform target bounding box\n\n new_xmin, new_ymin = self.transform_boxes([(self.source_boundary.west_edge, self.source_boundary.north_edge, 50, 50)])[0][:2]\n new_xmax, new_ymax = self.transform_boxes([(self.source_boundary.east_edge, self.source_boundary.south_edge, 50, 50)])[0][:2]\n\n # set new box coordinates withhin old limits\n new_ymin, new_xmin = max(new_ymin, 0), max(new_xmin, 0)\n new_ymax, new_xmax = min(new_ymax, self.target_slide_dimensions[1]), min(new_xmax, self.target_slide_dimensions[0])\n\n # transform target center\n target_cx, target_cy = self.transform_boxes([(self.source_boundary.cx, self.source_boundary.cy, 50, 50)])[0][:2]\n\n # create target boxes\n target_nw = Rect.create(Rect, new_xmin, new_ymin, target_cx - new_xmin, target_cy - new_ymin)\n target_sw = Rect.create(Rect, new_xmin, target_cy, target_cx - new_xmin, new_ymax - target_cy)\n\n target_ne = Rect.create(Rect, target_cx, new_ymin, new_xmax - target_cx, target_cy - new_ymin)\n target_se = Rect.create(Rect, target_cx, target_cy, new_xmax - target_cx, new_ymax - target_cy)\n\n\n # create target boxes\n source_nw = Rect(source_cx - source_w/2, source_cy - source_h/2, source_w, source_h)\n source_sw = Rect(source_cx - source_w/2, source_cy + source_h/2, source_w, source_h)\n\n source_ne = Rect(source_cx + source_w/2, source_cy - source_h/2, source_w, source_h)\n source_se = Rect(source_cx + source_w/2, source_cy + source_h/2, source_w, source_h)\n\n\n # The boundaries of the four children nodes are \"northwest\",\n # \"northeast\", \"southeast\" and \"southwest\" quadrants within the\n # boundary of the current node.\n\n qt_functions = {}\n \n if source_nw.is_valid() and target_nw.is_valid():\n qt_functions[NodeOrientation.NORTH_WEST] = functools.partial(RegistrationQuadTree, source_slide_path=self.source_slide_path, target_slide_path=self.target_slide_path, source_boundary=source_nw, target_boundary=target_nw, depth=self.depth + 1, node_orientation=NodeOrientation.NORTH_WEST, parent=self, **self.kwargs)\n\n if source_ne.is_valid() and target_ne.is_valid():\n qt_functions[NodeOrientation.NORTH_EAST] = functools.partial(RegistrationQuadTree, source_slide_path=self.source_slide_path, target_slide_path=self.target_slide_path, source_boundary=source_ne, target_boundary=target_ne, depth=self.depth + 1, node_orientation=NodeOrientation.NORTH_EAST, parent=self, **self.kwargs)\n\n if source_se.is_valid() and target_se.is_valid():\n qt_functions[NodeOrientation.SOUTH_EAST] = functools.partial(RegistrationQuadTree, source_slide_path=self.source_slide_path, target_slide_path=self.target_slide_path, source_boundary=source_se, target_boundary=target_se, depth=self.depth + 1, node_orientation=NodeOrientation.SOUTH_EAST, parent=self, **self.kwargs)\n\n if source_sw.is_valid() and target_sw.is_valid():\n qt_functions[NodeOrientation.SOUTH_WEST] = functools.partial(RegistrationQuadTree, source_slide_path=self.source_slide_path, target_slide_path=self.target_slide_path, source_boundary=source_sw, target_boundary=target_sw, depth=self.depth + 1, node_orientation=NodeOrientation.SOUTH_WEST, parent=self, **self.kwargs)\n\n if self.run_async == True:\n with concurrent.futures.ThreadPoolExecutor(max_workers=self.num_workers) as executor: # ProcessPoolExecutor ThreadPoolExecutor\n\n submitted = {executor.submit(func) : area for area, func in qt_functions.items()}\n for future in concurrent.futures.as_completed(submitted):\n try:\n if submitted[future] == NodeOrientation.NORTH_WEST:\n self.nw = future.result()\n elif submitted[future] == NodeOrientation.NORTH_EAST:\n self.ne = future.result()\n elif submitted[future] == NodeOrientation.SOUTH_EAST:\n self.se = future.result()\n elif submitted[future] == NodeOrientation.SOUTH_WEST:\n self.sw = future.result()\n\n self.divided = True\n except Exception as exc:\n print('%r generated an exception: %s' % (submitted[future], exc))\n else:\n for area, func in qt_functions.items():\n try:\n if area == NodeOrientation.NORTH_WEST:\n self.nw = func()\n elif area == NodeOrientation.NORTH_EAST:\n self.ne = func()\n elif area == NodeOrientation.SOUTH_EAST:\n self.se = func()\n elif area == NodeOrientation.SOUTH_WEST:\n self.sw = func()\n\n self.divided = True\n\n except Exception as exc:\n print('%r generated an exception: %s' % (submitted[future], exc))\n\n def draw_feature_points(self, num_sub_pic:int=5, figsize=(16, 16)):\n \n fig = plt.figure(constrained_layout=True, figsize=figsize)\n fig.suptitle(f'{self.source_name} --> {self.target_name}')\n gs = fig.add_gridspec(5, num_sub_pic)\n\n f_ax_match = fig.add_subplot(gs[:2, :])\n f_ax_match.imshow(self.matchedVis)\n\n source_slide = openslide.open_slide(str(self.source_slide_path))\n target_slide = openslide.open_slide(str(self.target_slide_path))\n\n tf_temp = tf.AffineTransformation(self.tf_param.b, self.tf_param.t)\n \n for idx, (pA, pB) in enumerate(zip(self.ptsA[:num_sub_pic].copy(), self.ptsB[:num_sub_pic].copy())):\n size = 512\n\n transformed = pA.copy()\n pA = (pA + (self.source_boundary.west_edge, self.source_boundary.north_edge)).astype(int)\n pB = (pB + (self.target_boundary.west_edge, self.target_boundary.north_edge)).astype(int)\n\n transformed = (tf_temp.transform(transformed) + (self.target_boundary.west_edge, self.target_boundary.north_edge)).astype(int)\n pA = pA.astype(int)\n\n size_target_x, size_target_y = int(size * self.mpp_x_scale), int(size * self.mpp_y_scale)\n\n image_source, image_target, image_target_trans = np.zeros(shape=(1,1)), np.zeros(shape=(1,1)), np.zeros(shape=(1,1))\n\n pA_location = pA.astype(int) - (size // 2, size // 2)\n if size > 0:\n image_source = source_slide.read_region(location=pA_location, level=0, size=(size, size))\n\n pB_location = pB.astype(int) - (size_target_x // 2, size_target_y // 2)\n if size_target_x > 0 and size_target_y > 0:\n image_target = target_slide.read_region(location=pB_location, level=0, size=(size_target_x, size_target_y))\n\n trans_location = transformed - (size_target_x // 2, size_target_y // 2)\n if size_target_x > 0 and size_target_y > 0:\n image_target_trans = target_slide.read_region(location=trans_location, level=0, size=(size_target_x, size_target_y))\n\n ax = fig.add_subplot(gs[2, idx])\n ax.set_title(f'Source: {pA}')\n ax.imshow(image_source)\n\n ax = fig.add_subplot(gs[3, idx])\n ax.set_title(f'Trans: {transformed}')\n ax.imshow(image_target_trans)\n\n ax = fig.add_subplot(gs[4, idx])\n ax.set_title(f'GT: {pB}')\n ax.imshow(image_target)\n \n if self.divided:\n sub_draws = []\n if self.nw is not None: sub_draws.append(self.nw.draw_feature_points(num_sub_pic, figsize))\n if self.ne is not None: sub_draws.append(self.ne.draw_feature_points(num_sub_pic, figsize))\n if self.se is not None: sub_draws.append(self.se.draw_feature_points(num_sub_pic, figsize))\n if self.sw is not None: sub_draws.append(self.sw.draw_feature_points(num_sub_pic, figsize))\n\n return fig, sub_draws\n else:\n return fig, None\n\n\n def filter_boxes(self, boxes):\n \"\"\"[summary]\n Filter boxes that are not visibile in the quadtree level \n Args:\n boxes ([type]): [Array of boxes: [xc, cy, w, h]]\n\n Returns:\n [type]: [description]\n \"\"\"\n\n boxes = boxes[((boxes[:, 0] > self.source_boundary.west_edge) & (boxes[:, 0] < self.source_boundary.east_edge))]\n boxes = boxes[((boxes[:, 1] > self.source_boundary.north_edge) & (boxes[:, 1] < self.source_boundary.south_edge))]\n\n return boxes\n\n def transform_boxes(self, boxes, max_depth=100):\n \"\"\"[summary]\n Transform box coordinages from the soure to the target domain coordinate system\n Args:\n boxes ([type]): [Array of boxes: [xc, cy, w, h]]\n\n Returns:\n [type]: [description]\n \"\"\"\n\n tf_temp = tf.AffineTransformation(self.tf_param.b, self.tf_param.t)\n\n result_boxes = []\n for box in boxes:\n box = np.array(box)\n point = Point(box[0], box[1])\n \n #if self.nw is not None and self.nw.mean_reg_error <= self.mean_reg_error and self.nw.source_boundary.contains(point) and self.nw.depth <= max_depth: #q\n if self.nw is not None and self.nw.source_boundary.contains(point) and self.nw.depth <= max_depth:\n box = self.nw.transform_boxes([box], max_depth)[0] \n #elif self.ne is not None and self.ne.mean_reg_error <= self.mean_reg_error and self.ne.source_boundary.contains(point) and self.ne.depth <= max_depth:\n elif self.ne is not None and self.ne.source_boundary.contains(point) and self.ne.depth <= max_depth:\n box = self.ne.transform_boxes([box], max_depth)[0] \n #elif self.se is not None and self.se.mean_reg_error <= self.mean_reg_error and self.se.source_boundary.contains(point) and self.se.depth <= max_depth:\n elif self.se is not None and self.se.source_boundary.contains(point) and self.se.depth <= max_depth:\n box = self.se.transform_boxes([box], max_depth)[0] \n #elif self.sw is not None and self.sw.mean_reg_error <= self.mean_reg_error and self.sw.source_boundary.contains(point) and self.sw.depth <= max_depth:\n elif self.sw is not None and self.sw.source_boundary.contains(point) and self.sw.depth <= max_depth:\n box = self.sw.transform_boxes([box], max_depth)[0] \n else:\n\n source_boxes = box[:2] - (self.source_boundary.west_edge, self.source_boundary.north_edge) \n transformed_xy = tf_temp.transform(source_boxes) + (self.target_boundary.west_edge, self.target_boundary.north_edge)\n transformed_wh = box[2:] * np.array([self.mpp_x_scale, self.mpp_y_scale])\n\n box = np.hstack([transformed_xy, transformed_wh])\n\n result_boxes.append(box)\n\n #if self.depth == 0:\n #result_boxes = np.array(list(itertools.chain(*result_boxes)))\n\n return result_boxes\n \n def draw_annotations(self, boxes, figsize=(16, 16), num_sub_pic:int=5):\n \"\"\"[summary]\n Draw annotations on patches from the source and target slide\n Args:\n boxes ([type]): Array of boxes: [xc, cy, w, h]]\n figsize (tuple, optional): description. Defaults to (16, 16).\n num_sub_pic (int, optional): description. Defaults to 5.\n\n Returns:\n [type]: Array of figures for each level\n \"\"\"\n\n source_boxes = boxes.copy()\n source_boxes = self.filter_boxes(source_boxes)\n target_boxes = self.transform_boxes(source_boxes)\n \n fig = plt.figure(constrained_layout=True, figsize=figsize)\n fig.suptitle(f'{self.source_name} --> {self.target_name}')\n gs = fig.add_gridspec(4, num_sub_pic)\n\n f_ax_match = fig.add_subplot(gs[:2, :])\n f_ax_match.imshow(self.matchedVis)\n\n source_slide = openslide.open_slide(str(self.source_slide_path))\n target_slide = openslide.open_slide(str(self.target_slide_path))\n \n for idx, (source_box, target_box) in enumerate(zip(source_boxes[:num_sub_pic], target_boxes[:num_sub_pic])):\n size = 512\n\n pA = np.array(source_box[:2]).astype(int)\n source_anno_width, source_anno_height = source_box[2:4]\n source_x1, source_y1 = (size / 2) - source_anno_width / 2, (size / 2) - source_anno_height / 2\n \n \n transformed = target_box[:2].astype(int)\n size_target_x, size_target_y = abs(int(size * self.mpp_x_scale)), abs(int(size * self.mpp_y_scale))\n \n target_anno_width, target_anno_height = int(source_anno_width * self.mpp_x_scale), int(source_anno_height * self.mpp_y_scale)\n target_x1, target_y1 = (size_target_x / 2) - target_anno_width / 2, (size_target_y / 2) - target_anno_height / 2\n \n\n image_source, image_target_trans = np.zeros(shape=(1,1)), np.zeros(shape=(1,1))\n\n pA_location = pA.astype(int) - (size // 2, size // 2)\n if size > 0:\n image_source = source_slide.read_region(location=pA_location, level=0, size=(size, size))\n\n trans_location = transformed - (size_target_x // 2, size_target_y // 2)\n if size_target_x > 0 and size_target_y > 0:\n image_target_trans = target_slide.read_region(trans_location, level=0, size=(size_target_x, size_target_y))\n\n\n ax = fig.add_subplot(gs[2, idx])\n ax.set_title(f'Source: {pA}')\n ax.imshow(image_source) \n rect = patches.Rectangle((source_x1, source_y1), source_anno_width, source_anno_height, \n linewidth=3, edgecolor='m', facecolor='none')\n ax.add_patch(rect)\n \n\n ax = fig.add_subplot(gs[3, idx])\n ax.set_title(f'Trans: {transformed}')\n ax.imshow(image_target_trans)\n rect = patches.Rectangle((target_x1, target_y1), target_anno_width, target_anno_height, \n linewidth=3, edgecolor='m', facecolor='none')\n ax.add_patch(rect)\n\n \n if self.divided:\n sub_draws = []\n if self.nw is not None: sub_draws.append(self.nw.draw_annotations(boxes, figsize, num_sub_pic))\n if self.ne is not None: sub_draws.append(self.ne.draw_annotations(boxes, figsize, num_sub_pic))\n if self.se is not None: sub_draws.append(self.se.draw_annotations(boxes, figsize, num_sub_pic))\n if self.sw is not None: sub_draws.append(self.sw.draw_annotations(boxes, figsize, num_sub_pic))\n\n return fig, sub_draws\n else:\n return fig, None\n\n def draw(self, ax):\n \"\"\"Draw a representation of the quadtree on Matplotlib Axes ax.\"\"\"\n\n self.source_boundary.draw(ax)\n if self.divided:\n self.nw.draw(ax)\n self.ne.draw(ax)\n self.se.draw(ax)\n self.sw.draw(ax)\n \n def filter_outliner(self, ptsA, ptsB):\n \n scales = ptsA / ptsB\n \n #if self.parent is None:\n inliners = LocalOutlierFactor(n_neighbors=int(len(scales) * 0.25)).fit_predict(scales) == 1\n #else:\n # inliners = scales[:, 0] > min(self.parent.scale_factors[:, 0]) & scales[:, 0] < max(self.parent.scale_factors[:, 0]) & scales[:, 1] > min(self.parent.scale_factors[:, 1]) & scales[:, 1] < max(self.parent.scale_factors[:, 1])\n\n return ptsA[inliners], ptsB[inliners], ptsA[inliners] / ptsB[inliners]\n\n def _get_detector_matcher(self, point_extractor=\"orb\", maxFeatures:int=500, crossCheck:bool=False, flann:bool=False, **kwargs):\n\n kwargs.update({\"point_extractor\":point_extractor, \"maxFeatures\":maxFeatures, \"crossCheck\":crossCheck, \"flann\":flann})\n \n if point_extractor == \"orb\":\n detector = cv2.ORB_create(maxFeatures)\n norm = cv2.NORM_HAMMING\n elif point_extractor == \"sift\":\n detector = cv2.SIFT_create() # maxFeatures\n norm = cv2.NORM_L2\n elif point_extractor == \"kaze\":\n detector = cv2.KAZE_create()\n norm = cv2.NORM_L2\n elif point_extractor == \"brisk\":\n detector = cv2.BRISK_create()\n norm = cv2.NORM_HAMMING\n else:\n return None, None\n \n if flann:\n if norm == cv2.NORM_L2:\n flann_params = dict(algorithm = 1, trees = 5)\n else:\n flann_params= dict(algorithm = 6,\n table_number = 6, # 12\n key_size = 12, # 20\n multi_probe_level = 1) #2\n matcher = cv2.FlannBasedMatcher(flann_params, {}) # bug : need to pass empty dict (#1329)\n else:\n matcher = cv2.BFMatcher(norm, crossCheck)\n return detector, matcher\n\n def _filter_matches(self, kp1, kp2, matches, ratio = 0.75, **kwargs):\n kwargs.update({\"ratio\":ratio})\n\n mkp1, mkp2, good = [], [], []\n for match in matches:\n if len(match) < 2:\n break\n \n m, n = match\n if m.distance < n.distance * ratio:\n good.append([m])\n mkp1.append(np.array(kp1[m.queryIdx].pt))\n mkp2.append(np.array(kp2[m.trainIdx].pt))\n\n return mkp1, mkp2, good \n\n def extract_matching_points(self, source_image, target_image, \n debug=False, \n source_scale:[tuple]=[(1,1)], \n target_scale:[tuple]=[(1,1)],\n point_extractor:callable=\"orb\",\n use_gray:bool=False, \n **kwargs\n ):\n kwargs.update({\"debug\":debug, \"point_extractor\":point_extractor, \"use_gray\":use_gray})\n\n source_scale = np.array(source_scale)\n target_scale = np.array(target_scale)\n\n source_image = np.array(source_image) if type(source_image) == Image.Image else source_image\n target_image = np.array(target_image) if type(target_image) == Image.Image else target_image\n \n if callable(point_extractor):\n kpsA_ori, descsA, kpsB, descsB, matches = point_extractor(source_image, target_image)\n else:\n detector, matcher = self._get_detector_matcher(**kwargs)\n\n kpsA_ori, descsA = detector.detectAndCompute(source_image, None) if use_gray == False else detector.detectAndCompute(cv2.cvtColor(source_image, cv2.COLOR_BGR2GRAY), None)\n kpsB_ori, descsB = detector.detectAndCompute(target_image, None) if use_gray == False else detector.detectAndCompute(cv2.cvtColor(target_image, cv2.COLOR_BGR2GRAY), None)\n\n matches = matcher.knnMatch(descsA, descsB, k=2)\n kpsA, kpsB, matches = self._filter_matches(kpsA_ori, kpsB_ori, matches, **kwargs)\n\n # check to see if we should visualize the matched keypoints\n matchedVis = None\n if debug:\n #matchedVis = cv2.drawMatches(source_image, kpsA, target_image, kpsB, matches, None)\n matchedVis = cv2.drawMatchesKnn(source_image, kpsA_ori, target_image, kpsB_ori, matches, \n None,flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)\n \n ptsA, ptsB = [], []\n\n for ptA, ptB in zip(kpsA, kpsB):\n # scale points \n for s_scale, t_scale in zip(source_scale, target_scale):\n ptA *= s_scale \n ptB *= t_scale \n\n ptsA.append(ptA)\n ptsB.append(ptB)\n\n return np.array(ptsA), np.array(ptsB), matchedVis\n\n\n @staticmethod\n def get_region_thumbnail(slide_path:Path, boundary:Rect, depth:int=0, size=(2048, 2048)):\n\n scale = []\n\n slide = openslide.open_slide(str(slide_path))\n downsample = max(*[dim / thumb for dim, thumb in zip((boundary.w, boundary.h), (size[0] * depth, size[1] * depth))]) \n level = slide.get_best_level_for_downsample(downsample)\n\n downsample = slide.level_downsamples[level]\n\n x, y, w, h = int(boundary.west_edge), int(boundary.north_edge), int(boundary.w / downsample), int(boundary.h / downsample)\n scale.append(np.array((boundary.w, boundary.h)) / (w, h))\n\n tile = slide.read_region((x, y), level, (w, h))\n\n thumb = Image.new('RGB', tile.size, '#ffffff')\n thumb.paste(tile, None, tile)\n thumb.thumbnail(size, Image.ANTIALIAS)\n scale.append(np.array([w, h]) / thumb.size)\n\n return thumb, scale\n\n def __getstate__(self):\n\n attributes = self.__dict__.copy()\n\n attributes[\"source_slide_path\"] = str(self.source_slide_path)\n attributes[\"target_slide_path\"] = str(self.target_slide_path)\n\n del attributes['matchedVis']\n del attributes['_source_thumbnail']\n del attributes['_target_thumbnail']\n del attributes['tf_param']\n return attributes\n\n def __setstate__(self, state):\n\n self.__dict__ = state\n\n self._source_thumbnail = None\n self._target_thumbnail = None\n self.matchedVis = None\n\n self.source_slide_path = Path(self.__dict__[\"source_slide_path\"])\n self.target_slide_path = Path(self.__dict__[\"target_slide_path\"])\n\n self.tf_param = tf.AffineTransformation(self.__dict__[\"b\"], self.__dict__[\"t\"])\n\n\n","sub_path":"qt_wsi_reg/registration_tree.py","file_name":"registration_tree.py","file_ext":"py","file_size_in_byte":35624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"263468993","text":"import sys\nfrom collections import deque\nread = sys.stdin.readline\n\ndef bfs(cur) :\n q = deque()\n q.append(cur)\n e,v = 0,0\n while q :\n here = q.popleft()\n if visited[here] == 1 : continue\n\n v += 1\n visited[here] = 1\n for n in adjs[here] :\n e += 1\n q.append(n)\n\n if e / 2 == v - 1 : return True\n else : return False\n \nn,m = -1,-1\ncase = 0\nwhile(1) :\n n,m = map(int,read().split())\n if n == 0 and m == 0 : break\n\n adjs = [[] for _ in range(n+1)]\n visited = [0 for _ in range(n+1)]\n for _ in range(m) :\n x,y = map(int, read().split())\n adjs[x].append(y)\n adjs[y].append(x)\n\n tree = 0\n for i in range(1,n+1) :\n if visited[i] == 1 : continue\n if bfs(i) : \n tree += 1\n\n case += 1\n if tree == 0 :\n print(\"Case {}: No trees.\".format(case))\n elif tree == 1 :\n print(\"Case {}: There is one tree.\".format(case))\n else :\n print(\"Case {}: A forest of {} trees.\".format(case,tree))\n\n ","sub_path":"BOJ/28_트리/4803_트리.py","file_name":"4803_트리.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"70402768","text":"'''\nCreated on Jan 19, 2016\n\n@author: tim\n'''\nimport logging\nfrom tim.metadataExtractor.ImportFilter import ImportFilterEmail\nfrom tim.swift.SwiftBackend import SwiftBackend\nimport swiftclient.multithreading\nimport concurrent.futures\n#from tim.metadataExtractor.ContentTypeIdentifier import ContentTypeIdentifier\n\n\nclass Extractor(object):\n\t'''\n\tclassdocs\n\t'''\n\tmapping = dict()\n\tmapping[ImportFilterEmail.myContentType] = ImportFilterEmail\n\n\tdef __init__(self, containerName):\n\t\t'''\n\t\tConstructor\n\t\t'''\n\t\tself.log = logging.getLogger()\n\t\tself.containerName = containerName\n\t\tself.log.info('initializing...')\n\t\tself.sb = SwiftBackend()\n\t\t\n\tdef getFilterForObjType(self, objType):\n\t\treturn self.mapping[objType]()\n\t\n\t\n\t\n\tdef getDataAndIdentifyContentType(self, conn, objType, objName):\n\t\tthisObjBlob = self.sb.getObjBlob(conn, self.containerName, objName)\n\t\tctype = ContentTypeIdentifier().identifyContentType(thisObjBlob)\n\t\tif objType == ctype:\n\t\t\treturn \"same same...\"\n\t\treturn self.sb.updateObjContentType(conn, containerName=self.containerName, objName=objName, newContentType=ctype)\n\t\t\n\t\t\n\t\t\n\tdef getDataAndRunFilter(self, conn, objType, objName):\n\t\tthisObjBlob = self.sb.getObjBlob(conn, self.containerName, objName)\n\t\ttry:\n\t\t\tthisFilter = self.getFilterForObjType(objType)\n\t\texcept:\n\t\t\traise TypeError(\"No Filter for type {}\".format(objType))\n\t\tr = thisFilter.extractMetaData(thisObjBlob)\n\t\treturn self.sb.writeObjMetaData(conn=conn, containerName=self.containerName, objName=objName, metaDict=r)\n\t\t\t\n\t\t\t\n\t\t\t\n\tdef runForWholeContainer(self, functionOnObject):\n\t\twith swiftclient.multithreading.ConnectionThreadPoolExecutor(self.sb._getConnection, max_workers=20) as executor:\n\t\t\tobjs = self.sb.get_object_list(self.containerName)\n\t\t\tfuture_results = []\n\t\t\t\n\t\t\t# first go through all objs in the container and spawn a thread to run the filter\n\t\t\tfor thisObj in objs:\n\t\t\t\tthisObjType = thisObj['content_type']\n\t\t\t\tthisObjName = thisObj['name']\n\t\t\t\t\n\t\t\t\tself.log.info('running {} for type : {} on obj: {}'.format(functionOnObject.__name__, thisObjType, thisObjName))\n\t\t\t\tfuture_results.append(executor.submit(functionOnObject, thisObjType, thisObjName))\n\t\t\t\n\t\t\tsuccess = 0\n\t\t\tfailure = 0\n\t\t\t# try to get the individual results from the filters\n\t\t\tfor future in concurrent.futures.as_completed(future_results):\n\t\t\t\ttry:\n\t\t\t\t\tdata = future.result()\n\t\t\t\texcept Exception as exc:\n\t\t\t\t\tself.log.error('worker failed with exception: {}'.format(exc))\n\t\t\t\t\tfailure += 1\n\t\t\t\telse:\n\t\t\t\t\tself.log.info('worker succeeded on obj: {}'.format(data))\n\t\t\t\t\tsuccess += 1\n\t\t\t\n\t\t\tsuccessPerc = success/(success+failure)\t\n\t\t\tfailurePerc = failure/(success+failure)\n\t\t\tself.log.info('{} workers were successful ({} success rate!) and {} workers has been failed({} failure rate!!!)'.format(success,successPerc,failure,failurePerc))\n\t\n\t\n\tdef runFilterForWholeContainer(self):\n\t\t\tself.runForWholeContainer(functionOnObject=self.getDataAndRunFilter)\n\t\t\t\n\t\t\t\n\t\t\t\n\tdef runIdentifierForWholeContainer(self):\n\t\t\tself.runForWholeContainer(functionOnObject=self.getDataAndIdentifyContentType)\n\t\t\t\n\t\t\t\n","sub_path":"tim/metadataExtractor/Extractor.py","file_name":"Extractor.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"148108274","text":"\"\"\"\nHelpers to log tornado request information.\n\"\"\"\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\ndef log_request(handler):\n \"\"\"Log the request information with extra context for use w/ Graylog-enabled apps.\"\"\"\n\n response_status = handler.get_status()\n request_time = 1000.0 * handler.request.request_time()\n request_summary = handler._request_summary()\n\n if response_status < 400:\n log_method = logger.info\n elif response_status < 500:\n log_method = logger.warning\n else:\n log_method = logger.error\n\n log_method(\"%d %s %.2fms\", response_status, request_summary, request_time,\n extra={\"request_method\": handler.request.method,\n \"request_path\": handler.request.path,\n \"request_query\": handler.request.query,\n \"response_status\": response_status,\n \"request_duration\": request_time,\n \"request_remote_ip\": handler.request.remote_ip,\n \"request_summary\": request_summary})\n","sub_path":"muselog/tornado.py","file_name":"tornado.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"291315523","text":"import re\n\n\nclass TaggedInfoExtractor:\n known_speakers = set()\n known_locations = set()\n\n def __init__(self, email_files):\n seminar_emails = [file.read() for file in email_files] # read all email files to an array\n\n for e in seminar_emails:\n self.known_speakers = self.extract_from_tags(\"speaker\", e, self.known_speakers) # all known speakers\n self.known_locations = self.extract_from_tags(\"location\", e, self.known_locations) # all known locations\n\n @staticmethod\n def extract_from_tags(tag_name, text, known_set):\n between_tag_regex = r'<{0}>[ \\t]*((?:.|\\s)+?)[ \\t]*'.format(tag_name)\n regex = re.compile(between_tag_regex)\n tag_content = regex.findall(text)\n\n for extracted_info in tag_content:\n known_set.add(TaggedInfoExtractor.clean_extracted_info(extracted_info))\n\n return known_set\n\n @staticmethod\n def clean_extracted_info(text):\n cleanr = re.compile('<.*?>') # tag regex\n clean_text = re.sub(cleanr, '', text) # removes tags from the info\n\n clean_text = re.sub(r'\\W+', '', clean_text)\n clean_text = clean_text.lower()\n\n return clean_text\n","sub_path":"tagger/extract_tagged_info.py","file_name":"extract_tagged_info.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"113563554","text":"from Stream import StreamModel\nimport webapp2\nimport re\nfrom ViewHandler import View\n\nimport os\nimport jinja2\nimport json\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nclass Search(webapp2.RequestHandler):\n def get(self):\n View.more = True\n template = JINJA_ENVIRONMENT.get_template('templates/search.html')\n self.response.write(template.render())\n\nclass SearchResult(webapp2.RequestHandler):\n def get(self):\n View.more = True\n template = JINJA_ENVIRONMENT.get_template('templates/searchresult.html')\n pattern = self.request.get(\"searchPattern\")\n found_in_tag = False\n Name = []\n streams = StreamModel.query().fetch()\n for st in streams:\n Name.append(st.name)\n num = 0\n infos = []\n for name in Name:\n fi = re.findall(pattern, name)\n stream = StreamModel.query(StreamModel.name==name).fetch()[0]\n for tag in stream.tag:\n if len(re.findall(pattern,tag))>0:\n found_in_tag = True\n if len(fi)>0 or found_in_tag==True:\n infos.append((stream.name, stream.coverpageURL, stream.url, num))\n if num==3:\n num = 0\n else:\n num += 1\n template_values = {\n 'infos': infos\n }\n self.response.write(template.render(template_values))\n\nclass AutoAPI(webapp2.RequestHandler):\n def get(self):\n # patten = self.request.get('term')\n # print patten\n streams = StreamModel.query().fetch()\n namelist = list()\n for stream in streams:\n # if patten in stream.name:\n namelist.append(stream.name)\n for tag in stream.tag:\n # if (patten in tag) and (tag != \"\"):\n namelist.append(tag)\n\n namelist.sort()\n list_json = {\"namelist\": namelist}\n\n self.response.headers['Content-Type'] = 'application/json'\n list_json = json.dumps(list_json)\n self.response.write(list_json)\n\n\napp = webapp2.WSGIApplication([\n ('/search', Search),\n ('/searchresult', SearchResult),\n ('/autoapi.*', AutoAPI),\n], debug=True)\n","sub_path":"backend/SearchHandler.py","file_name":"SearchHandler.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333111770","text":"'''\nCreated on February 13, 2016\n\n@author: Nicholas Falco\n'''\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport unittest\n\nfrom obspy import UTCDateTime\nfrom obspy.clients import fdsn\n\n\nDATASELECT = 'http://service.iris.edu/ph5wsbeta/dataselect/1'\nSTATION = 'http://service.iris.edu/ph5wsbeta/station/1'\n\n\nclass TestObspyClients(unittest.TestCase):\n\n def test_dataselect(self):\n \"\"\"\n Uses ObsPy to run various dataselect requests against the PH5\n Dataselect web service. Confirms that the requested waveforms are\n returned and parsed.\n \"\"\"\n c = fdsn.client.Client('http://service.iris.edu',\n service_mappings={\n 'dataselect': DATASELECT\n },\n debug=True\n )\n # example valid requests\n stream = c.get_waveforms('ZI', '100?,1100,1200,0000,0001',\n '--,10',\n 'DPZ,BHZ',\n UTCDateTime('2015-06-29T04:55:00.0'),\n UTCDateTime('2015-06-29T05:00:00.0'))\n # assert that 10 traces are returned\n self.assertEqual(len(stream.traces), 10)\n for trace in stream.traces:\n self.assertEqual(trace.stats.network, 'ZI')\n self.assertIn(trace.stats.station, ['1002', '1003', '1004', '1005',\n '1006', '1007', '1008', '1009',\n '1100', '1200'])\n self.assertNotIn(trace.stats.station, ['0000', '0001', '1001'])\n self.assertEqual(trace.stats.location, '')\n self.assertEqual(trace.stats.channel, 'DPZ')\n self.assertEqual(trace.stats.sampling_rate, 250.0)\n self.assertEqual(UTCDateTime('2015-06-29T04:55:00.0'),\n trace.stats.starttime)\n self.assertEqual(UTCDateTime('2015-06-29T04:59:59.996000'),\n trace.stats.endtime)\n stream = c.get_waveforms('ZI', '10*', '*', 'DP?',\n UTCDateTime('2015-06-29T04:55:00'),\n UTCDateTime('2015-06-29T05:00:00'))\n self.assertEquals(len(stream.traces), 98)\n\n def test_station(self):\n \"\"\"\n Uses ObsPy to run various requests against the PH5 Station\n web service. Confirms that the requested stationxml is valid and\n accurate.\n \"\"\"\n c = fdsn.client.Client('http://service.iris.edu',\n service_mappings={\n 'station': STATION\n },\n debug=True\n )\n inv = c.get_stations(network=\"ZI\", station=\"100?\", channel='DPZ',\n starttime='2015-06-29T04:55:00',\n endtime='2015-06-29T05:00:00')\n self.assertEqual(len(inv.networks), 1)\n for net in inv.networks:\n self.assertEqual(len(net.stations), 8)\n self.assertEqual(net._code, 'ZI')\n for sta in inv.networks[0].stations:\n self.assertIn(sta._code, ['1002', '1003', '1004', '1005',\n '1006', '1007', '1008', '1009'])\n for cha in sta:\n self.assertEqual(len(sta.channels), 8)\n self.assertEqual(cha._code, 'DPZ')\n # Test against multiple networks\n inv = c.get_stations(network=\"ZI,4C\",\n station=\"100?,DAN,IVY,LGC\",\n channel='DPZ',\n starttime='2015-06-29T04:55:00',\n endtime='2015-08-05T19:30:00')\n self.assertEqual(len(inv.networks), 2)\n for net in inv.networks:\n self.assertIn(len(net.stations), [8, 3])\n self.assertIn(net._code, ['ZI', '4C'])\n for sta in inv.networks[0].stations:\n self.assertIn(sta._code, ['1002', '1003', '1004', '1005',\n '1006', '1007', '1008', '1009',\n 'DAN', 'IVY', 'LGC'])\n for cha in sta:\n self.assertIn(len(sta.channels), [8, 3])\n self.assertEqual(cha._code, 'DPZ')\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"PH5WebService/common/tests/test_with_obspy_client.py","file_name":"test_with_obspy_client.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"130812780","text":"from django.utils.translation import gettext as _\n\n\nUI_NO_TRANSACTIONS_AVAILABLE = _('There is no transactions yet')\nUI_NO_SERVICE_AVAILABLE = _('No service available')\n\n# CATEGORIES STRINGS\nUI_CATEGORY_EDUCATION = _('Education')\nUI_CATEGORY_ELECTRICITY = _('Electricity')\nUI_CATEGORY_HEALTH = _('Health')\nUI_CATEGORY_WATER = _('Water')\nUI_CATEGORY_TRAVEL = _('Travel')\nUI_CATEGORY_ENTERTAINMENT = _('Entertainment')\nUI_CATEGORY_BUSINESS = _('Business')\nUI_CATEGORY_ONLINE_SHOPPING = _('Online Shopping')\n\n# TRANSACTIONS\nUI_MAKE_TRANSFER_LABEL = _('Send money')\nUI_MAKE_PAYMENT_LABEL = _('Make payment')\nUI_MAKE_RECHARGE_LABEL = _('Recharge')\nUI_CURRENT_BALANCE_LABEL = _('Current balance')\nUI_STATISTICS_LABEL = _('Statistics')\n\nUI_TRANSACTIONS_LABEL = _('Transactions')\nUI_AVAILABLE_SERVICES_LABEL = _('Available Services')\nUI_CATEGORIES_LABEL = _('Categories')\nUI_TRANSACTIONS_VERIFICATION_LABEL = _('Transactions verification')\nUI_RECIPIENT_LABEL = _('Recipient')\nUI_SELLER_LABEL = _('Seller')\nUI_AMOUNT_LABEL = _('Amount')\nUI_DESCRIPTION_LABEL = _('Description')\nUI_VOUCHER_CODE_LABLE = _('Voucher Code')\n","sub_path":"payments/resources/ui_strings.py","file_name":"ui_strings.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"651201354","text":"from pymongo import MongoClient\n\nuri = \"mongodb+srv://admin:789852@tk-c4e26-ldifb.mongodb.net/test?retryWrites=true\"\n\nclient = MongoClient(uri)\n\ndb = client.test\n\ninfuser_collection = db[\"infuser\"]\n\ndef infuser(imagebase64,cvtitle,fullname,nominee,dateofbirth,sex,numberphone,addressemail,address,website,awareness,hobby,schoolname,startschool,endschool,majors,describe,companyname,startcompany,endcompany,locationcompany,jobdescription,prize,timeprize,softskill,namecertificate,typecertificate,diffirent,_id_user):\n new_infuser = {\n \"image\": imagebase64,\n \"cvtitle\":cvtitle,\n \"fullname\":fullname,\n \"nominee\":nominee,\n \"dateofbirth\":dateofbirth,\n \"sex\":sex,\n \"numberphone\":numberphone,\n \"addressemail\":addressemail,\n \"address\":address,\n \"website\":website,\n \"awareness\":awareness,\n \"hobby\":hobby,\n \"schoolname\":schoolname,\n \"startschool\":startschool,\n \"endschool\":endschool,\n \"majors\":majors,\n \"describe\":describe,\n \"companyname\":companyname,\n \"startcompany\":startcompany,\n \"endcompany\":endcompany,\n \"locationcompany\":locationcompany,\n \"jobdescription\":jobdescription,\n \"prize\":prize,\n \"timeprize\":timeprize,\n \"softskill\":softskill,\n \"namecertificate\":namecertificate,\n \"typecertificate\":typecertificate,\n \"diffirent\":diffirent,\n \"_id_user\":_id_user,\n }\n infuser_collection.insert_one(new_infuser)\n return new_infuser\ndef search_image(imagebase64):\n image = infuser_collection.find_one({'image': imagebase64})\n return image\ndef close():\n client.close()\n","sub_path":"CV online (html, python, css)/20190405-CV/00. CV/dbuser.py","file_name":"dbuser.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"229516996","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\BitBucket\\djmicrosip_apps\\django_msp_controldeacceso\\django_msp_controldeacceso\\urls.py\n# Compiled at: 2016-02-15 12:30:53\nfrom django.conf.urls import patterns, url\nfrom .views import index, cliente_search, UpdateDatabaseTable, ClienteListView, ClienteManageView, PreferenciasManageView, play_sound, log_view, ImagenManageView, ImagenListView, eliminarimagen\nurlpatterns = patterns('', (\n '^$', index), (\n '^search/$', cliente_search), (\n '^initialize/$', UpdateDatabaseTable), (\n '^clientes/$', ClienteListView.as_view()), (\n '^cliente/(?P\\\\d+)/', ClienteManageView), (\n '^preferencias/$', PreferenciasManageView), (\n '^play_sound/$', play_sound), (\n '^bitacora/$', log_view), (\n '^imagenes/$', ImagenListView.as_view()), (\n '^imagen/$', ImagenManageView), (\n '^imagen/(?P\\\\d+)/', ImagenManageView), (\n '^eliminarimagen/(?P\\\\d+)/', eliminarimagen))","sub_path":"pycfiles/django_msp_controldeacceso-1.1.0/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"403051914","text":"#!/usr/bin/env python3\n\n# 练习1:写一个程序,info.py\n# 要求:\n# $ ./info.py Bob 25 如果输入参数个数不正确则正常退出程序 # 用到sys模块中的方法\n# 执行结果输出:\n# { '姓名:' : 'Bob' ,'年龄:' : 25 } \nimport sys\nif len(sys.argv) < 3:\n sys.exit()\nelse:\n v = sys.argv\n d = {'姓名': v[1], '年龄': v[2]}\n print(d)","sub_path":"pbase/day13/chenlian/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"154428302","text":"\"\"\"\nThis module test 'Extension tester tool'(ovirt-engine-extensions-tool) and\nit's aaa module with login action.\n\npolarion:\n RHEVM3/wiki/System/Extension tester tool\n\"\"\"\nimport logging\nimport pytest\nfrom os import path, listdir\n\nfrom rhevmtests.coresystem.helpers import EngineCLI\nfrom art.test_handler.tools import polarion\nfrom art.unittest_lib import (\n tier1,\n)\nfrom art.unittest_lib import CoreSystemTest as TestCase, testflow\n\nfrom rhevmtests.coresystem.aaa.ldap import config, common\n\nCERT_BASE = '/tmp/my_crt'\nTEST_USER = 'user1'\nTEST_USER_PASSWORD = 'pass:123456'\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(autouse=True, scope=\"module\")\ndef setup_module(request):\n def finalize():\n testflow.teardown(\"Cleaning extension directories\")\n common.cleanExtDirectory(config.ENGINE_EXTENSIONS_DIR)\n common.cleanExtDirectory(config.AAA_DIR)\n\n request.addfinalizer(finalize)\n\n testflow.setup(\"Setting up module %s\", __name__)\n dir_name = path.join(\n path.dirname(path.abspath(__file__)),\n '../answerfiles',\n )\n testflow.setup(\"Setting up LDAP\")\n for answerfile in listdir(dir_name):\n assert common.setup_ldap(\n host=config.ENGINE_HOST,\n conf_file=path.join(dir_name, answerfile),\n )\n\n\n@tier1\nclass ExttoolAAALogin(TestCase):\n \"\"\" Test login action with generic provider \"\"\"\n profile = None\n extended_properties = {}\n\n @classmethod\n @pytest.fixture(autouse=True, scope=\"class\")\n def setup_class(cls, request):\n def finalize():\n testflow.teardown(\"Tearing down class %s\", cls.__name__)\n with cls.executor.session() as ss:\n ss.run_cmd(['mv', '%s.tmp' % cls.ext_file, cls.ext_file])\n ss.run_cmd(['rm', '-f', '%s.jks' % CERT_BASE])\n ss.run_cmd(['rm', '-f', '%s.pem' % CERT_BASE])\n\n request.addfinalizer(finalize)\n\n testflow.setup(\"Setting up class %s\", cls.__name__)\n cls.executor = config.ENGINE_HOST.executor()\n authz = '/etc/ovirt-engine/extensions.d/%s-authz.properties' % (\n cls.profile\n )\n authn = '/etc/ovirt-engine/extensions.d/%s-authn.properties' % (\n cls.profile\n )\n testflow.setup(\"Setting up AAA module\")\n cls.cli = EngineCLI(\n config.TOOL,\n cls.executor.session(),\n '--log-level=WARNING',\n '--extension-file=%s' % authn,\n '--extension-file=%s' % authz,\n ).setup_module(\n module='aaa',\n )\n\n cls.ext_file = '/etc/ovirt-engine/aaa/%s.properties' % cls.profile\n with cls.executor.session() as ss:\n testflow.setup(\n \"Getting properties from extension file %s\", cls.ext_file\n )\n with ss.open_file(cls.ext_file, 'r') as f:\n for line in f:\n if line.find('=') > 0:\n key, val = line.split('=', 1)\n else:\n key = line\n val = ''\n cls.extended_properties[key.strip()] = val.strip()\n\n testflow.setup(\"Backing up\")\n assert not ss.run_cmd(\n ['mv', cls.ext_file, '%s.tmp' % cls.ext_file]\n )[0], \"Failed to backup '%s'\" % cls.ext_file\n\n testflow.setup(\"Downloading cert files\")\n if cls.cert_url:\n assert not ss.run_cmd(\n ['wget', cls.cert_url, '-O', '%s.pem' % CERT_BASE]\n )[0], \"Failed to download cert '%s'\" % cls.cert_url\n assert not common.importCertificateToTrustStore(\n session=ss,\n filename='%s.pem' % CERT_BASE,\n truststore='%s.jks' % CERT_BASE,\n password='changeit',\n )[0], \"Failed to create trustore '%s.jks'\" % CERT_BASE\n\n def login(self, user_name=TEST_USER, password=TEST_USER_PASSWORD):\n testflow.step(\"Login as user %s\", user_name)\n assert self.cli.run(\n 'login-user',\n user_name=user_name,\n profile=self.profile,\n password=password,\n )[0], \"Failed to run login-user action\"\n\n\nclass TestExttoolAAALoginAD(ExttoolAAALogin):\n \"\"\" Test login action with Active Directory \"\"\"\n profile = 'ad-w2k12r2'\n cert_url = 'http://ad-w2k12r2.rhev.lab.eng.brq.redhat.com/w2k12r2.cer'\n\n @polarion('RHEVM3-14526')\n @common.extend(\n properties={\n 'pool.default.ssl.startTLS': 'true',\n 'pool.default.ssl.truststore.file': '%s.jks' % CERT_BASE\n }\n )\n def test_login_startTLS(self):\n \"\"\" test login \"\"\"\n testflow.step(\"Login with startTLS\")\n self.login(password='pass:Heslo123')\n\n @polarion('RHEVM3-14527')\n @common.extend(\n properties={\n 'pool.default.ssl.startTLS': 'true',\n 'pool.default.ssl.insecure': 'true',\n }\n )\n def test_login_startTLS_insecure(self):\n \"\"\" test login startl insecure \"\"\"\n testflow.step(\"Login with startTLS insecure\")\n self.login(password='pass:Heslo123')\n\n\nclass TestExttoolAAALoginOpenLDAP(ExttoolAAALogin):\n \"\"\" Test login action with OpenLDAP \"\"\"\n profile = 'openldap'\n cert_url = 'http://brq-openldap.rhev.lab.eng.brq.redhat.com/cacert.pem'\n bz = {'1313516': {}}\n\n @polarion('RHEVM3-14525')\n @common.extend(\n properties={\n 'pool.default.ssl.startTLS': 'true',\n 'pool.default.ssl.truststore.file': '%s.jks' % CERT_BASE\n }\n )\n def test_login_startTLS(self):\n \"\"\" test login startl \"\"\"\n testflow.step(\"Login with startTLS\")\n self.login()\n\n @polarion('RHEVM3-14528')\n @common.extend(\n properties={\n 'pool.default.ssl.startTLS': 'true',\n 'pool.default.ssl.insecure': 'true',\n }\n )\n def test_login_startTLS_insecure(self):\n \"\"\" test login startl insecure \"\"\"\n testflow.step(\"Login with startTLS insecure\")\n self.login()\n","sub_path":"art/tests/rhevmtests/coresystem/aaa/ldap/exttool/test_aaa_login.py","file_name":"test_aaa_login.py","file_ext":"py","file_size_in_byte":6089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"640316039","text":"#!/usr/bin/env python\n#\n# Copyright 2013 Simone Campagna\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n__author__ = 'Simone Campagna'\n\nfrom .base_editor import BaseEditor\nfrom .ascii_editor import AsciiEditor\n\nfrom ..utils.application import UiType, load_default_ui_type\nfrom ..utils.debug import LOGGER\n\n\ntry:\n from .qt_editor import QtEditor\n HAS_QT = True\nexcept ImportError as e:\n LOGGER.warning(\"cannot load module qt_editor: {0}\".format(e))\n #import traceback\n #traceback.print_exc()\n HAS_QT = False\n\nUI_CLASS = {UiType.Ascii: AsciiEditor}\n\nDEFAULT_UI_TYPE = load_default_ui_type()\nif HAS_QT:\n UI_CLASS[UiType.Qt] = QtEditor\n\nif DEFAULT_UI_TYPE is None:\n if HAS_QT:\n DEFAULT_UI_TYPE = UiType.Qt\n else:\n DEFAULT_UI_TYPE = UiType.Ascii\n\nclass Editor(BaseEditor):\n def __init__(self, ui_type=DEFAULT_UI_TYPE):\n if isinstance(ui_type, UiType):\n if not ui_type in UI_CLASS:\n raise ValueError(\"invalid UI type {0}\".format(ui_type.label))\n self.ui_class = UI_CLASS[ui_type]\n elif isinstance(ui_type, BaseEditor):\n self.ui_class = ui_type\n else:\n raise TypeError(\"invalid init value {0!r} of type {1} for {2}\".format(ui_type, type(ui_type).__name__, self.__class__.__name__))\n self.ui_editor = self.ui_class()\n\n def edit(self, field, output_filename=None):\n return self.ui_editor.edit(field, output_filename=output_filename)\n","sub_path":"structparser/editor/editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"240074617","text":"\"\"\"\n This module contains the whole processing of Open Food Facts data,\n from the download to the upload in the database.\n They are closely linked w. the management/commands modules of this app.\n It is organized around the types of datat:\n - Stores,\n - Categories,\n - Products.\n\n Classes:\n ProcessStore\n\n ProcessCategory\n\n ProcessProduct\n\n Exceptions:\n NIL\n\n Functions:\n NIL\n\"\"\"\n\nimport requests\nfrom datetime import datetime\nfrom food_items.openfoodfacts.shared_methods import DataCleaning\nfrom food_items.openfoodfacts.config import OpenFoodFactsParams\nfrom food_items.openfoodfacts.queries import UploadQueries, UpdateQueries\nfrom food_items.models import Product\n\n\nclass ProcessStore(DataCleaning, OpenFoodFactsParams, UploadQueries):\n def _download_stores(self):\n response = requests.get(self.URL_STORES)\n return response.json()\n\n def _upload_stores(self, stores):\n self.query_upload_stores(stores)\n\n def store_full_process(self):\n self.stores = self._download_stores()\n # Here is room for optimization along category_full_process (DRY)\n self.stores = self.from_data_to_list(self.stores,\n \"tags\", \"name\", \"products\", 1000)\n self._upload_stores(self.stores)\n\n\nclass ProcessCategory(DataCleaning, OpenFoodFactsParams, UploadQueries):\n def _download_categories(self):\n response = requests.get(self.URL_CATEGORIES)\n return response.json()\n\n def _upload_categories(self, categories):\n self.query_upload_categories(categories)\n\n def category_full_process(self):\n self.categories = self._download_categories()\n self.categories = self.from_data_to_list(self.categories,\n \"tags\", \"name\",\n \"products\", 10000)\n self._upload_categories(self.categories)\n\n\nclass ProcessProduct(DataCleaning, OpenFoodFactsParams, UploadQueries):\n\n def _configure_request_payload(self, page_number):\n # Product data in OFF DB are organized in pages, up to 1000 items.\n # Increment the page numbers allow larger downloads.\n self.payload.update({\"tag_0\": self.CATEGORY})\n self.payload.update({\"page\": page_number})\n return self.payload\n\n def _download_products(self):\n response = requests.get(self.URL, headers=self.HEADERS, params=self.payload)\n return response.json()\n\n\n def _sort_out_product_data(self, product_data):\n \"\"\"\n The Open Food Facts database may look somehow messy.\n Therefore products have to be checked and cleaned before import.\n\n Arguments:\n product_data: is under a JSON format\n\n Returns:\n products_list: each product is organized as a tuple.\n All the products to be uploaded are organized into a list.\n \"\"\"\n products_list = list()\n for product in product_data[\"products\"]:\n # Need to discard the data where the nutrition grade is empty.\n if product.get('nutrition_grade_fr') is not None\\\n and product.get('stores') is not None:\n brand = product.get('brands')\n name = product.get('product_name')\n code = product.get('code')\n nutrition_score = product.get('nutrition_grade_fr')\n # Stores and categories are stores as strings in OFF.\n stores = self.from_string_into_list(product.get('stores'))\n categories = self.from_string_into_list(\n product.get('categories'))\n # In order to avoid an overloading of the DB,\n # keeps only 1 category per product\n category = categories[0]\n image_url = self.assign_url(product.get('image_url'))\n last_modified = product.get('last_modified_t')\n products_list.append((brand, name, code, nutrition_score,\n stores, category, image_url,\n last_modified))\n return products_list\n\n def _product_treatment(self):\n product_data = self._download_products()\n product_list = self._sort_out_product_data(product_data)\n return product_list\n\n def _product_full_process(self, page_number):\n self._configure_request_payload(page_number)\n product_list = self._product_treatment()\n self.query_upload_products(product_list)\n\n def manage_full_set_products(self, number_of_pages):\n # Room for optimization to choose other categories and more pages\n for page in range(1, number_of_pages + 1):\n self._product_full_process(page)\n number_recorded_products = self.query_count_products()\n return number_recorded_products\n\n def product_upload_outcome(self, number_recorded_products):\n print(f\"Number of food items: {number_recorded_products}\")\n\n\nclass UpdateProducts(ProcessProduct, UpdateQueries):\n\n def _store_comparrison(self, product_to_update_stores, current_stores):\n if sorted(product_to_update_stores) != sorted(current_stores):\n return product_to_update_stores\n else:\n return current_stores\n\n def _product_comparrison(self, stored_products, products_for_update):\n products_to_update = list()\n products_to_create = list()\n for product in products_for_update:\n if product[2] in stored_products:\n product_details = stored_products[product[2]]\n if int(product[7]) > int(datetime.timestamp(product_details[0])):\n stores_to_check = [store.name for store in product_details[1]]\n checked_stores = self._store_comparrison(product[4], stores_to_check)\n product = list(product)\n product[4] = checked_stores\n product = tuple(product)\n products_to_update.append(product)\n else:\n products_to_create.append(product)\n return products_to_update, products_to_create\n\n def _download_products_for_update(self, page):\n self._configure_request_payload(page)\n products_for_update = self._product_treatment()\n return products_for_update\n\n def _fetch_all_stored_products(self):\n return self.query_fetch_all_stored_products()\n\n def _compare_products(self, stored_products, page=1):\n products_for_update = self._download_products_for_update(page)\n products_to_update, products_to_create = self._product_comparrison(stored_products, products_for_update)\n return products_to_update, products_to_create\n\n def update_products_in_db(self, number_of_pages):\n stored_products = self._fetch_all_stored_products()\n existing_stores = self.query_fetch_existing_stores()\n update_counter = 0\n for page in range(1, number_of_pages):\n products_to_update, products_to_create = self._compare_products(stored_products, page)\n self.query_upload_products(products_to_create)\n for product in products_to_update:\n self.query_update_product(product, existing_stores)\n update_counter += 1\n return self.query_count_products(), update_counter\n\n def print_update_outcome(self, product_count, update_counter):\n print(f\"Number of updated products: {update_counter}\")\n print(f\"Number of food items in DB: {product_count}\")\n","sub_path":"food_items/openfoodfacts/off_data_process.py","file_name":"off_data_process.py","file_ext":"py","file_size_in_byte":7618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649619523","text":"#!/usr/bin/env python\n\n\"\"\"\n.. module:: convert\n :synopsis: used to create info.txt and the .txt files.\n\n\"\"\"\nimport sys\nimport os\nimport argparse\nimport types\n\nargparser = argparse.ArgumentParser(description = \n'create info.txt, txname.txt, twiki.txt and sms.py')\nargparser.add_argument ('-utilsPath', '--utilsPath', \nhelp = 'path to the package smodels_utils',\\\ntype = str)\nargparser.add_argument ('-smodelsPath', '--smodelsPath', \nhelp = 'path to the package smodels_utils',\\\ntype = str)\nargs = argparser.parse_args()\n\nif args.utilsPath:\n utilsPath = args.utilsPath\nelse:\n databaseRoot = '../../../'\n sys.path.append(os.path.abspath(databaseRoot))\n from utilsPath import utilsPath\n utilsPath = databaseRoot + utilsPath\nif args.smodelsPath:\n sys.path.append(os.path.abspath(args.smodelsPath))\n\nsys.path.append(os.path.abspath(utilsPath))\nfrom smodels_utils.dataPreparation.inputObjects import MetaInfoInput,DataSetInput\nfrom smodels_utils.dataPreparation.databaseCreation import databaseCreator\nfrom smodels_utils.dataPreparation.massPlaneObjects import x, y, z\n\n\n\n#+++++++ global info block ++++++++++++++\ninfo = MetaInfoInput('CMS-SUS-13-007')\ninfo.url ='https://twiki.cern.ch/twiki/bin/view/CMSPublic/PhysicsResultsSUS13007'\ninfo.sqrts = 8\ninfo.lumi = 19.3\ninfo.prettyName = '1 lepton + >= 2 b-jets + Etmiss'\ninfo.private = False\ninfo.arxiv = 'http://arxiv.org/abs/arXiv:1311.4937'\ninfo.contact ='Loukas Gouskos , Markus Stoye '\ninfo.publication = 'http://www.sciencedirect.com/science/article/pii/S037026931400255X'\ninfo.comment = 'Only two mass planes for T5tttt; implemented Delta Phi method'\ninfo.supersedes =''\ninfo.implementedBy = 'Federico Ambrogi'\n\n\n#+++++++ dataset block ++++++++++++++\ndataset = DataSetInput('data')\ndataset.setInfo(dataType = 'upperLimit', dataId = None)\n\n#+++++++ next txName block ++++++++++++++\nT1tttt = dataset.addTxName('T1tttt')\nT1tttt.constraint = \"[[['t','t']],[['t','t']]]\"\nT1tttt.conditionDescription = None\nT1tttt.condition = None\nT1tttt.massConstraint = None\nT1tttt.source = 'CMS'\nT1ttttoff = dataset.addTxName('T1ttttoff')\nT1ttttoff.constraint =\"[[['b','W','b','W']],[['b','W','b','W']]]\"\nT1ttttoff.conditionDescription = None\nT1ttttoff.condition = None\nT1ttttoff.massConstraint = [['dm <= 338.0'], ['dm <= 338.0']]\nT1ttttoff.source = 'CMS'\n#+++++++ next mass plane block ++++++++++++++\nT1tttt_1 = T1tttt.addMassPlane(2*[[x, y]])\nT1tttt_1.figure = 'combLimit_T1tttt_b.pdf'\nT1tttt_1.figureUrl = 'https://twiki.cern.ch/twiki/pub/CMSPublic/PhysicsResultsSUS13007/combLimit_T1tttt_b.pdf'\nT1tttt_1.dataUrl = 'https://twiki.cern.ch/twiki/pub/CMSPublic/PhysicsResultsSUS13007/limits_model_A.txt'\nT1tttt_1.setSources(dataLabels= ['obsExclusion', 'upperLimits'],\n dataFiles= ['./orig/T1tttt_excl.txt', './orig/T1tttt.txt'],\n dataFormats= ['txt', 'txt'],objectNames= [None, 'None'],units= [None, 'fb'])\nT1ttttoff.addMassPlane(T1tttt_1)\n\n#+++++++ next txName block ++++++++++++++\nT5tttt = dataset.addTxName('T5tttt')\nT5tttt.constraint = \"[[['t'],['t']],[['t'],['t']]]\"\nT5tttt.conditionDescription = None\nT5tttt.condition = None\nT5tttt.massConstraint = None\nT5tttt.source = 'CMS'\nT5ttttoff = dataset.addTxName('T5ttttoff')\nT5ttttoff.constraint = \"[[['b','W'],['b','W']],[['b','W'],['b','W']]]\"\nT5ttttoff.conditionDescription = None\nT5ttttoff.condition = None\nT5ttttoff.massConstraint = [['dm <= 169.0', 'dm <= 169.0'], ['dm <= 169.0', 'dm <= 169.0']]\nT5ttttoff.source = 'CMS'\n#+++++++ next mass plane block ++++++++++++++\nT5tttt_1 = T5tttt.addMassPlane(2*[[1000., x, y]])\nT5tttt_1.figure = 'combLimit_T1t1t_b.pdf'\nT5tttt_1.figureUrl ='https://twiki.cern.ch/twiki/pub/CMSPublic/PhysicsResultsSUS13007/combLimit_T1t1t_b.png'\nT5tttt_1.dataUrl = 'https://twiki.cern.ch/twiki/pub/CMSPublic/PhysicsResultsSUS13007/limits_model_B.txt'\nT5tttt_1.setSources(dataLabels= ['obsExclusion', 'upperLimits'],\n dataFiles= ['./orig/T5tttt_mg1TeV_excl.txt', './orig/T5tttt_mg1TeV.txt'],\n dataFormats= ['txt', 'txt'],objectNames= [None, 'None'],units= [None, 'fb'])\nT5ttttoff.addMassPlane(T5tttt_1)\n#+++++++ next mass plane block ++++++++++++++\nT5tttt_2 = T5tttt.addMassPlane(2*[[x, y, 50.]])\nT5tttt_2.figure = 'combLimit_T5tttt_b.pdf'\nT5tttt_2.figureUrl = 'https://twiki.cern.ch/twiki/pub/CMSPublic/PhysicsResultsSUS13007/combLimit_T5tttt_b.png'\nT5tttt_2.dataUrl = 'https://twiki.cern.ch/twiki/pub/CMSPublic/PhysicsResultsSUS13007/limits_model_C.txt'\nT5tttt_2.setSources(dataLabels= ['obsExclusion', 'upperLimits'],\n dataFiles= ['./orig/T5tttt_mLSP50GeV_excl.txt', './orig/T5tttt_mLSP50GeV.txt'],\n dataFormats= ['txt', 'txt'],objectNames= [None, 'None'],units= [None, 'fb'])\nT5ttttoff.addMassPlane(T5tttt_2)\n\n\n\ndatabaseCreator.create()\n","sub_path":"smodels-database/8TeV/CMS/CMS-SUS-13-007/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316277825","text":"import numpy\nfrom CmpCV import CmpCVUtils\n\n\nclass CmpClusterNode(object):\n \n id_cluster = 0\n \n list_vector = []\n indices_match = []\n list_distance = []\n \n sum_vector = []\n num_node = 0\n mean_vector = []\n mean_angle = 0\n \n child_l = None\n child_r = None\n current_distance = 0\n \n def __init__(self, child_l=None, child_r=None, distance=0, id_cluster=0):\n if child_l is None or child_r is None:\n return\n self.id_cluster = id_cluster\n self.child_l = child_l\n self.child_r = child_r\n self.list_vector = numpy.concatenate((child_l.list_vector, child_r.list_vector))\n self.indices_match = numpy.concatenate((child_l.indices_match, child_r.indices_match))\n self.sum_vector = child_l.sum_vector + child_r.sum_vector\n self.calculate_mean_vector()\n # self.mean_angle = CmpCVUtils.angle_clockwise_from_horizon(self.mean_vector)\n self.list_distance += [distance]\n self.current_distance = distance\n \n def calculate_mean_vector(self):\n if self.list_vector.shape[0] == 1:\n self.mean_vector = self.list_vector[0].copy()\n else:\n num_data = self.list_vector.shape[0]\n self.mean_vector = self.sum_vector/num_data\n \n def __lt__(self, other):\n return self.mean_angle < other.mean_angle\n \n @classmethod\n def from_vector(cls, list_vector, index_match, id_cluster=0):\n temp_obj = CmpClusterNode()\n temp_obj.id_cluster = id_cluster\n temp_obj.list_vector = numpy.array([list_vector], numpy.float32)\n temp_obj.list_distance = []\n temp_obj.current_distance = 0\n temp_obj.indices_match = numpy.array([index_match])\n temp_obj.sum_vector = numpy.array(list_vector, numpy.float32)\n temp_obj.calculate_mean_vector()\n # temp_obj.mean_angle = CmpCVUtils.angle_clockwise_from_horizon(temp_obj.mean_vector)\n return temp_obj\n \n \n\n","sub_path":"CmpClustering/CmpClusterNode.py","file_name":"CmpClusterNode.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"469782943","text":"import numpy as np\r\nclass Kernels():\r\n \r\n \"\"\" Robert\r\n \r\n This class contains three flavours of kernel desnity estimators.\r\n Functionally, these attempt to estimate a distribution function \r\n for a data set (at this stage, only able to work in 1D but could\r\n be extended to N dimensions {in theory}).\r\n \r\n Essentially, these take a given data point and assign it a weight\r\n at each point on a pre-defined grid. This weight is determined by the\r\n type of function used and the proximity of the data point to the position \r\n on the pre-defined grid.\r\n \r\n As this code is developed, it is likely that each of these functions will\r\n take additional arguments to determine the cut-off and the desnity of\r\n grid points.\r\n \r\n Note that given the way in which these functions are created and designed, \r\n are already normalised.\r\n \r\n Note that additional kernels are likely to be implemented into this module\r\n in the fullnes of time as and when I get around to developing and testing them.\r\n However; at the moment, these three below appear to be sufficient in efficiency\r\n and accuracy for the task at hand. But variety IS the spice of life.\r\n \"\"\"\r\n \r\n def __init__(self, Space, Density):\r\n self.Space = Space\r\n self.Density = Density\r\n\r\n\r\n\r\n def Gauss(Data,Band):\r\n \r\n \"\"\" Robert\r\n \r\n Data: At this stage, this expects the input of a 1D vector containing\r\n the data to be iterated over. This is expected to be the output of one\r\n of the functions from the \"Distances.py\" module. Although, in theory,\r\n this could be an arbitrary vector of data.\r\n \r\n Band: The bandwidth assigned to this kernel. Increasing the bandwidth results \r\n in a smoother looking distribution although runs the risk of missing important\r\n features of the true distribution. Decreasing it tends towards the behaviour\r\n of each data point being a dirac-delta peak at its precise location in the limit\r\n of Band tends to zero.\r\n This would have the effect of re-paramterising the raw data.\r\n Good results have come from using band ~ 0.125 for estimating a PDDF. Although,\r\n one may wish to tune this parameter depending on how they wish to present their\r\n data.\r\n \r\n This particular function assigns the weight according to an underlying\r\n Gaussian distribution. I.e., the weight that a given data point has is \r\n Gaussian distributed about the position on the grid under consideration.\r\n \"\"\"\r\n \r\n Number = '5'\r\n \r\n Space=np.linspace(0,8.0,400);Density=[]\r\n for i in Space:\r\n P=0\r\n for j in range(len(Data)):\r\n X = (Data[j]-i)/Band\r\n Gauss = (1/np.sqrt(2*np.pi))*np.exp(-(X**2)/2)\r\n P+=Gauss\r\n Density.append(P/(len(Data)*Band))\r\n return Space, Density\r\n\r\n\r\n def Uniform(Data,Band):\r\n \r\n \"\"\" Robert\r\n \r\n Data: At this stage, this expects the input of a 1D vector containing\r\n the data to be iterated over. This is expected to be the output of one\r\n of the functions from the \"Distances.py\" module. Although, in theory,\r\n this could be an arbitrary vector of data.\r\n \r\n Band: The bandwidth assigned to this kernel. Increasing the bandwidth results \r\n in a smoother looking distribution although runs the risk of missing important\r\n features of the true distribution. Decreasing it tends towards the behaviour\r\n of each data point being a dirac-delta peak at its precise location in the limit\r\n of Band tends to zero.\r\n This would have the effect of re-paramterising the raw data.\r\n \r\n This assigns a uniform weight to a data point if it exists within an interval\r\n centred on the grid point under consideration. The weight and interval width are\r\n intrinsically linked for the purposes of distribution normalisation.\r\n \r\n Fine details of PDDFs (including peak splitting) has been best observed with \r\n a bandwidth of ~ 0.25.\r\n \"\"\"\r\n \r\n Number = '6'\r\n \r\n \r\n Space=np.linspace(0,8.0,400);Density=[]\r\n for i in Space:\r\n P=0\r\n for j in range(len(Data)):\r\n X = (Data[j]-i)/Band\r\n if -0.5*Band <= X <= 0.5*Band:\r\n P+=1.0/Band\r\n else:\r\n P+=0\r\n \r\n Density.append(P/(len(Data)*Band))\r\n return Space, Density\r\n \r\n \r\n def Epan(Data,Band):\r\n \r\n \r\n \"\"\" Robert\r\n \r\n Data: At this stage, this expects the input of a 1D vector containing\r\n the data to be iterated over. This is expected to be the output of one\r\n of the functions from the \"Distances.py\" module. Although, in theory,\r\n this could be an arbitrary vector of data.\r\n \r\n Band: The bandwidth assigned to this kernel. Increasing the bandwidth results \r\n in a smoother looking distribution although runs the risk of missing important\r\n features of the true distribution. Decreasing it tends towards the behaviour\r\n of each data point being a dirac-delta peak at its precise location in the limit\r\n of Band tends to zero.\r\n This would have the effect of re-paramterising the raw data.\r\n \r\n This particular function utilises the Epanechnikov convention for assigning weights\r\n to each data point. In essence, this creates a small semi-circle of weight around \r\n each grid point to weight the surroudning data points by.\r\n \r\n Testing has had good results for a bandwidth of 0.25 when analysing PDDFs.\r\n \"\"\"\r\n \r\n Number = '7'\r\n \r\n \r\n Space=np.linspace(0,8.0,400);Density=[]\r\n for i in Space:\r\n P=0\r\n for j in range(len(Data)):\r\n X = (Data[j]-i)/Band\r\n P+=0.75*max(1-X**2,0)\r\n \r\n Density.append(P/(len(Data)*Band))\r\n return Space, Density\r\n\r\n \r\n \r\n \r\ndef KB_Dist(P,Q):\r\n \r\n \"\"\" Robert\r\n Calculates the Kullback-Liebler divergence between two distributions.\r\n \r\n P: The \"initial\" distribution against which one wishes to measure the mutual\r\n entropy of the distribution\r\n \r\n Q:\r\n \r\n At the moment, there is no actual provision to protect against zero division errors.\r\n One possible solution could be to define a local varaible, epsilon, which is added to \r\n every point in P and prevents it from being zero at any point. \r\n \r\n Note that these two distributions must have identical dimensions or the script\r\n will not run. \r\n \r\n A reasonable work-around is to define both from an identical linspace.\r\n \"\"\"\r\n \r\n \r\n K=0\r\n Epsilon=0.000001\r\n Q+=Epsilon\r\n P+=Epsilon\r\n for x in range(len(Q)):\r\n K-=P[x]*np.log(Q[x]/P[x])\r\n return K\r\n\r\ndef JSD(P,Q):\r\n\r\n K=0\r\n Epsilon=0.000001\r\n Q+=Epsilon\r\n P+=Epsilon\r\n for x in range(len(Q)):\r\n K-=0.5*(P[x]*np.log(2*Q[x]/(Q[x]+P[x]))+Q[x]*np.log(2*P[x]/(P[x]+Q[x])))\r\n return np.sqrt(K)\r\n\r\n\r\nif __name__ == '__main__':\r\n import Movie_Read as Read\r\n import Distances as Dist\r\n\r\n Energy, Trajectory, Elements=Read.Manual_Input()\r\n Positions=[];Distances=[];PDDF=[]\r\n\r\n for x in range(10):\r\n Positions.append(np.column_stack((Elements[x],Trajectory[x])))\r\n Distances.append(Dist.Distance.Euc_Dist(Positions[x])) #All possible pairings\r\n PDDF.append(Kernels.KDE_Uniform(Distances[x],0.25))","sub_path":"LoDiS_CC/Kernels.py","file_name":"Kernels.py","file_ext":"py","file_size_in_byte":7774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"277571729","text":"from collections import defaultdict\nimport time\n\nimport random\nimport numpy as np\nimport sympy\nimport scipy.optimize\n\nimport cirq\n\nfrom statistics import mean, stdev\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nrcParams.update({'figure.autolayout': True})\n\ndm_smp_time_dict = {}\nkc_smp_time_dict = {}\n\ncirq_max = 16\n\ndef main():\n\n for max_length in range(4,5):\n for steps in range(1,2):\n\n grid_points_cirq = []\n grid_points_all = []\n\n for length in range(2,max_length):\n\n if length*length<=cirq_max:\n grid_points_cirq.append(length*length)\n grid_points_all.append(length*length)\n\n dm_smp_time_dict[length*length] = []\n kc_smp_time_dict[length*length] = []\n\n for _ in range(2):\n trial(length=length,steps=steps,repetitions=1000)\n\n dm_smp_time_mean = []\n kc_smp_time_mean = []\n\n dm_smp_time_stdev = []\n kc_smp_time_stdev = []\n\n for grid_point in grid_points_all:\n\n if grid_point<=cirq_max:\n dm_smp_time_mean.append(mean(dm_smp_time_dict[grid_point]))\n dm_smp_time_stdev.append(stdev(dm_smp_time_dict[grid_point]))\n\n kc_smp_time_mean.append(mean(kc_smp_time_dict[grid_point]))\n kc_smp_time_stdev.append(stdev(kc_smp_time_dict[grid_point]))\n\n fig = plt.figure(figsize=(6,3))\n # plt.subplots_adjust(left=.2)\n ax = fig.add_subplot(1, 1, 1)\n\n ax.set_title('Noisy VQE simulation time vs. qubits (iterations={})'.format(steps))\n ax.set_xlabel('Qubits, representing 2D Ising model grid points')\n ax.set_ylabel('Time (s)')\n ax.set_yscale('log')\n ax.grid(linestyle=\"--\", linewidth=0.25, color='.125', zorder=-10)\n ax.errorbar(grid_points_cirq, dm_smp_time_mean, yerr=dm_smp_time_stdev, color='gray', marker='2', label='density matrix sampling')\n ax.errorbar(grid_points_all, kc_smp_time_mean, yerr=kc_smp_time_stdev, color='purple', marker='o', label='knowledge compilation sampling')\n ax.legend(loc='upper left', frameon=False)\n ax.spines['right'].set_visible(True)\n ax.spines['top'].set_visible(True)\n\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n plt.savefig(fname=timestr+'.pdf', format='pdf')\n\n# define the length of the grid.\ndef trial(length=2, steps=1, repetitions=1000, maxiter=2):\n\n h, jr, jc = random_instance(length)\n print('transverse fields: {}'.format(h))\n print('row j fields: {}'.format(jr))\n print('column j fields: {}'.format(jc))\n # prints something like\n # transverse fields: [[-1, 1, -1], [1, -1, -1], [-1, 1, -1]]\n # row j fields: [[1, 1, -1], [1, -1, 1]]\n # column j fields: [[1, -1], [-1, 1], [-1, 1]]\n\n # define qubits on the grid.\n # [cirq.GridQubit(i, j) for i in range(length) for j in range(length)]\n qubits = cirq.LineQubit.range(length*length)\n print(qubits)\n # prints\n # [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), cirq.GridQubit(0, 2), cirq.GridQubit(1, 0), cirq.GridQubit(1, 1), cirq.GridQubit(1, 2), cirq.GridQubit(2, 0), cirq.GridQubit(2, 1), cirq.GridQubit(2, 2)]\n\n cirq_circuit = cirq.Circuit()\n alpha = sympy.Symbol('alpha')\n beta = sympy.Symbol('beta')\n gamma = sympy.Symbol('gamma')\n for _ in range(steps):\n cirq_circuit.append(one_step(h, jr, jc, alpha, beta, gamma))\n\n # noise = cirq.ConstantQubitNoiseModel(cirq.asymmetric_depolarize(0.005,0.005,0.005)) # mixture: size four noise not implemented\n noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.005)) # mixture: size four noise not implemented\n # noise = cirq.ConstantQubitNoiseModel(cirq.phase_flip(0.01)) # mixture: works well\n # noise = cirq.ConstantQubitNoiseModel(cirq.bit_flip(0.01)) # mixture: works well\n\n cirq_circuit = cirq.Circuit(cirq.NoiseModel.from_noise_model_like(noise).noisy_moments(cirq_circuit, sorted(cirq_circuit.all_qubits())))\n meas_circuit = cirq.Circuit( cirq_circuit, cirq.measure(*qubits, key='x') )\n print(meas_circuit)\n\n # Initialize simulators\n dm_sim = cirq.DensityMatrixSimulator()\n # kc_sim = cirq.KnowledgeCompilationSimulator(cirq_circuit, initial_state=0)\n kc_smp = cirq.KnowledgeCompilationSimulator(meas_circuit, initial_state=0)\n\n\n # eval_iter = 0\n def f(x):\n param_resolver = cirq.ParamResolver({ 'alpha':x[0], 'beta':x[1], 'gamma':x[2] })\n\n # VALIDATE DENSITY MATRIX SIMULATION\n\n # dm_sim_start = time.time()\n # dm_sim_result = dm_sim.simulate(cirq_circuit, param_resolver=param_resolver)\n # dm_sim_time = time.time() - dm_sim_start\n\n # kc_sim_start = time.time()\n # kc_sim_result = kc_sim.simulate(cirq_circuit, param_resolver=param_resolver)\n # kc_sim_time = time.time() - kc_sim_start\n\n # print(\"dm_sim_result.final_density_matrix=\")\n # print(dm_sim_result.final_density_matrix)\n # print(\"kc_sim_result.final_density_matrix=\")\n # print(kc_sim_result.final_density_matrix)\n\n # np.testing.assert_almost_equal(\n # dm_sim_result.final_density_matrix,\n # kc_sim_result.final_density_matrix,\n # decimal=6\n # )\n\n # VALIDATE SAMPLING HISTOGRAMS\n\n # Sample bitstrings from circuit\n if length*length<=cirq_max:\n dm_smp_start = time.time()\n dm_smp_result = dm_sim.run(meas_circuit, param_resolver=param_resolver, repetitions=repetitions)\n dm_smp_time = time.time() - dm_smp_start\n dm_smp_time_dict[length*length].append(dm_smp_time)\n\n # Process histogram\n dm_bitstrings = dm_smp_result.measurements['x']\n dm_histogram = defaultdict(int)\n for bitstring in dm_bitstrings:\n integer = 0\n for pos, bit in enumerate(reversed(bitstring)):\n integer += bit< conditioned on the jr and jc fields.\"\"\"\n gate = cirq.CZPowGate(exponent=half_turns)\n for i, jr_row in enumerate(jr):\n for j, jr_ij in enumerate(jr_row):\n if jr_ij == -1:\n yield cirq.X(cirq.LineQubit(i*length+j))\n yield cirq.X(cirq.LineQubit((i+1)*length+j))\n yield gate(cirq.LineQubit(i*length+j),\n cirq.LineQubit((i+1)*length+j))\n if jr_ij == -1:\n yield cirq.X(cirq.LineQubit(i*length+j))\n yield cirq.X(cirq.LineQubit((i+1)*length+j))\n\n for i, jc_row in enumerate(jc):\n for j, jc_ij in enumerate(jc_row):\n if jc_ij == -1:\n yield cirq.X(cirq.LineQubit(i*length+j))\n yield cirq.X(cirq.LineQubit(i*length+j+1))\n yield gate(cirq.LineQubit(i*length+j),\n cirq.LineQubit(i*length+j+1))\n if jc_ij == -1:\n yield cirq.X(cirq.LineQubit(i*length+j))\n yield cirq.X(cirq.LineQubit(i*length+j+1))\n\ndef one_step(h, jr, jc, x_half_turns, h_half_turns, j_half_turns):\n length = len(h)\n yield rot_x_layer(length, x_half_turns)\n yield rot_z_layer(h, h_half_turns)\n yield rot_11_layer(length, jr, jc, j_half_turns)\n\nif __name__ == '__main__':\n main()\n","sub_path":"kc_examples/kc_noise_vqe/kc_noise_vqe.py","file_name":"kc_noise_vqe.py","file_ext":"py","file_size_in_byte":12082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"195572209","text":"from Stages.stage import Stage\nfrom GameObjects.stageList import StageList\nfrom Singletons.inputManager import InputManager\nfrom Singletons.displayManager import DisplayManager\nimport pygame\n\n\nclass MenuStage(Stage):\n def runStage(self):\n stages = StageList()\n black = (0, 0, 0)\n\n while not InputManager().quitGame:\n DisplayManager().gameDisplay.fill(black)\n\n events = pygame.event.get()\n InputManager().update(events)\n\n stages.update()\n stages.render()\n pygame.display.update()\n\n DisplayManager().gameDisplay.fill(black)\n pygame.display.update()\n pygame.quit()\n","sub_path":"GameFolder/Stages/menuStage.py","file_name":"menuStage.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169276212","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (C) 2012 Yahoo! Inc. 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\n# See http://yum.baseurl.org/api/yum-3.2.26/yum-module.html\nfrom yum import YumBase\n\nfrom yum.packages import PackageObject\n\n\nclass Requirement(object):\n def __init__(self, name, version):\n self.name = str(name)\n self.version = version\n\n def __str__(self):\n name = self.name\n if self.version is not None:\n name += \"-%s\" % (self.version)\n return name\n\n @property\n def package(self):\n # Form a 'fake' rpm package that\n # can be used to compare against\n # other rpm packages using the\n # standard rpm routines\n my_pkg = PackageObject()\n my_pkg.name = self.name\n if self.version is not None:\n my_pkg.version = str(self.version)\n return my_pkg\n\n\nclass Helper(object):\n # Cache of yumbase object\n _yum_base = None\n\n @staticmethod\n def _get_yum_base():\n if Helper._yum_base is None:\n _yum_base = YumBase()\n _yum_base.setCacheDir(force=True)\n Helper._yum_base = _yum_base\n return Helper._yum_base\n\n def is_installed(self, name):\n if len(self.get_installed(name)):\n return True\n else:\n return False\n\n def get_available(self):\n base = Helper._get_yum_base()\n pkgs = base.doPackageLists(showdups=True)\n avail = list(pkgs.available)\n avail.extend(pkgs.installed)\n return avail\n\n def get_installed(self, name):\n base = Helper._get_yum_base()\n pkgs = base.doPackageLists(pkgnarrow='installed',\n ignore_case=True, patterns=[name])\n if pkgs.installed:\n whats_installed = list(pkgs.installed)\n else:\n whats_installed = []\n return whats_installed\n","sub_path":"anvil/packaging/helpers/yum_helper.py","file_name":"yum_helper.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"585100106","text":"\"\"\"Test for the cfg Python extension module.\"\"\"\n\nfrom pytype.pytd import cfg\nimport unittest\n\n\nclass CFGTest(unittest.TestCase):\n \"\"\"Test control flow graph creation.\"\"\"\n\n def testSimpleGraph(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"foo\")\n n2 = n1.ConnectNew()\n n3 = n1.ConnectNew()\n n4 = n3.ConnectNew()\n self.assertEquals(\"<0>foo\", n1.Label())\n self.assertEquals(len(n1.outgoing), 2)\n self.assertEquals(len(n2.outgoing), 0)\n self.assertEquals(len(n3.outgoing), 1)\n self.assertEquals(len(n2.incoming), 1)\n self.assertEquals(len(n3.incoming), 1)\n self.assertEquals(len(n4.incoming), 1)\n self.assertIn(n2, n1.outgoing)\n self.assertIn(n3, n1.outgoing)\n self.assertIn(n1, n2.incoming)\n self.assertIn(n1, n3.incoming)\n self.assertIn(n3, n4.incoming)\n\n def testBindingBinding(self):\n p = cfg.Program()\n node = p.NewCFGNode()\n u = p.NewVariable(\"v\")\n v1 = u.AddBinding(None, source_set=[], where=node)\n v2 = u.AddBinding(u\"data\", source_set=[], where=node)\n v3 = u.AddBinding({1: 2}, source_set=[], where=node)\n self.assertEquals(v1.data, None)\n self.assertEquals(v2.data, u\"data\")\n self.assertEquals(v3.data, {1: 2})\n self.assertEquals(\"\" % id(v3.data),\n str(v3))\n\n def testGetAttro(self):\n p = cfg.Program()\n node = p.NewCFGNode()\n u = p.NewVariable(\"foo\")\n data = [1, 2, 3]\n a = u.AddBinding(data, source_set=[], where=node)\n self.assertEquals(a.variable.name, \"foo\")\n self.assertEquals(a.variable.bindings, [a])\n origin, = a.origins # we expect exactly one origin\n self.assertEquals(origin.where, node)\n self.assertEquals(len(origin.source_sets), 1)\n source_set, = origin.source_sets\n self.assertEquals(list(source_set), [])\n self.assertEquals(a.data, data)\n\n def testGetOrigins(self):\n p = cfg.Program()\n node = p.NewCFGNode()\n u = p.NewVariable(\"foo\")\n a = u.AddBinding(1, source_set=[], where=node)\n b = u.AddBinding(2, source_set=[a], where=node)\n c = u.AddBinding(3, source_set=[a, b], where=node)\n expected_source_sets = [[], [a], [a, b]]\n for binding, expected_source_set in zip([a, b, c], expected_source_sets):\n origin, = binding.origins\n self.assertEquals(origin.where, node)\n source_set, = origin.source_sets\n self.assertItemsEqual(list(source_set), expected_source_set)\n\n def testBindingName(self):\n p = cfg.Program()\n u = p.NewVariable(\"foo\")\n self.assertEquals(u.name, \"foo\")\n u.name = \"bar\"\n self.assertEquals(u.name, \"bar\")\n\n def _Freeze(self, program, entrypoint):\n program.entrypoint = entrypoint\n program.Freeze()\n\n def testVariableSet(self):\n p = cfg.Program()\n node1 = p.NewCFGNode()\n node2 = node1.ConnectNew()\n d = p.NewVariable(\"d\")\n d.AddBinding(\"v1\", source_set=[], where=node1)\n d.AddBinding(\"v2\", source_set=[], where=node2)\n self.assertEquals(len(d.bindings), 2)\n\n def testAsciiTree(self):\n p = cfg.Program()\n node1 = p.NewCFGNode()\n node2 = node1.ConnectNew()\n node3 = node2.ConnectNew()\n _ = node3.ConnectNew()\n # Just check sanity. Actual verification of the drawing algorithm is\n # done in utils_test.py.\n self.assertIsInstance(node1.AsciiTree(), str)\n self.assertIsInstance(node1.AsciiTree(forward=True), str)\n\n def testHasSource(self):\n p = cfg.Program()\n n0, n1, n2 = p.NewCFGNode(\"n0\"), p.NewCFGNode(\"n1\"), p.NewCFGNode(\"n2\")\n u = p.NewVariable(\"u\")\n u1 = u.AddBinding(0, source_set=[], where=n0)\n v = p.NewVariable(\"v\")\n v1 = v.AddBinding(1, source_set=[], where=n1)\n v2 = v.AddBinding(2, source_set=[u1], where=n1)\n v3a = v.AddBinding(3, source_set=[], where=n1)\n v3b = v.AddBinding(3, source_set=[u1], where=n2)\n self.assertEquals(v3a, v3b)\n v3 = v3a\n self.assertTrue(v1.HasSource(v1))\n self.assertTrue(v2.HasSource(v2))\n self.assertTrue(v3.HasSource(v3))\n self.assertFalse(v1.HasSource(u1))\n self.assertTrue(v2.HasSource(u1))\n self.assertTrue(v3.HasSource(u1))\n\n def testMergeZeroVariables(self):\n p = cfg.Program()\n n0 = p.NewCFGNode(\"n0\")\n self.assertIsInstance(p.MergeVariables(n0, \"u\", []), cfg.Variable)\n\n def testMergeOneVariable(self):\n p = cfg.Program()\n n0 = p.NewCFGNode(\"n0\")\n u = p.NewVariable(\"u\", [0], [], n0)\n self.assertIs(p.MergeVariables(n0, \"u\", [u]), u)\n self.assertIs(p.MergeVariables(n0, \"u\", [u, u]), u)\n self.assertIs(p.MergeVariables(n0, \"u\", [u, u, u]), u)\n\n def testMergeVariables(self):\n p = cfg.Program()\n n0, n1, n2 = p.NewCFGNode(\"n0\"), p.NewCFGNode(\"n1\"), p.NewCFGNode(\"n2\")\n u = p.NewVariable(\"u\")\n u1 = u.AddBinding(0, source_set=[], where=n0)\n v = p.NewVariable(\"v\")\n v1 = v.AddBinding(1, source_set=[], where=n1)\n v2 = v.AddBinding(2, source_set=[], where=n1)\n w = p.NewVariable(\"w\")\n w1 = w.AddBinding(1, source_set=[u1], where=n1)\n w2 = w.AddBinding(3, source_set=[], where=n1)\n vw = p.MergeVariables(n2, \"vw\", [v, w])\n self.assertItemsEqual(vw.data, [1, 2, 3])\n val1, = [v for v in vw.bindings if v.data == 1]\n self.assertTrue(val1.HasSource(u1))\n\n def testFilter1(self):\n # x.ab = A()\n # ,---+------------.\n # | n3 |\n # x = X() | x.ab = B() |\n # +------------+---+------------+------------+\n # n1 n2 n4 n5 n6\n p = cfg.Program()\n n1 = p.NewCFGNode()\n n2 = n1.ConnectNew()\n n3 = n2.ConnectNew()\n n4 = n2.ConnectNew()\n n5 = n3.ConnectNew()\n n4.ConnectTo(n5)\n n6 = n5.ConnectNew()\n n5.ConnectTo(n6)\n\n all_x = p.NewVariable(\"x\")\n x = all_x.AddBinding({}, source_set=[], where=n1)\n ab = p.NewVariable(\"x.ab\")\n x.data[\"ab\"] = ab\n a = ab.AddBinding(\"A\", source_set=[], where=n3)\n b = ab.AddBinding(\"B\", source_set=[], where=n4)\n\n self._Freeze(p, entrypoint=n1)\n self.assertFalse(a.IsVisible(n1) or b.IsVisible(n1))\n self.assertFalse(a.IsVisible(n2) or b.IsVisible(n2))\n self.assertTrue(a.IsVisible(n3))\n self.assertTrue(b.IsVisible(n4))\n self.assertEquals(ab.Filter(n1), [])\n self.assertEquals(ab.Filter(n2), [])\n self.assertEquals(ab.FilteredData(n3), [\"A\"])\n self.assertEquals(ab.FilteredData(n4), [\"B\"])\n self.assertSameElements([\"A\", \"B\"], ab.FilteredData(n5))\n self.assertSameElements([\"A\", \"B\"], ab.FilteredData(n6))\n\n def testCanHaveCombination(self):\n p = cfg.Program()\n n1 = p.NewCFGNode()\n n2 = n1.ConnectNew()\n n3 = n1.ConnectNew()\n n4 = p.NewCFGNode()\n n2.ConnectTo(n4)\n n3.ConnectTo(n4)\n x = p.NewVariable(\"x\")\n y = p.NewVariable(\"y\")\n x1 = x.AddBinding(\"1\", source_set=[], where=n2)\n y2 = y.AddBinding(\"2\", source_set=[], where=n3)\n self.assertTrue(n4.CanHaveCombination([x1, y2]))\n self.assertTrue(n4.CanHaveCombination([x1]))\n self.assertTrue(n4.CanHaveCombination([y2]))\n self.assertTrue(n3.CanHaveCombination([y2]))\n self.assertTrue(n2.CanHaveCombination([x1]))\n self.assertTrue(n1.CanHaveCombination([]))\n self.assertFalse(n1.CanHaveCombination([x1]))\n self.assertFalse(n1.CanHaveCombination([y2]))\n self.assertFalse(n2.CanHaveCombination([x1, y2]))\n self.assertFalse(n3.CanHaveCombination([x1, y2]))\n\n def testCombinations(self):\n # n1------->n2\n # | |\n # v v\n # n3------->n4\n # [n2] x = a; y = a\n # [n3] x = b; y = b\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew(\"n2\")\n n3 = n1.ConnectNew(\"n3\")\n n4 = n2.ConnectNew(\"n4\")\n n3.ConnectTo(n4)\n x = p.NewVariable(\"x\")\n y = p.NewVariable(\"y\")\n xa = x.AddBinding(\"a\", source_set=[], where=n2)\n ya = y.AddBinding(\"a\", source_set=[], where=n2)\n xb = x.AddBinding(\"b\", source_set=[], where=n3)\n yb = y.AddBinding(\"b\", source_set=[], where=n3)\n self._Freeze(p, entrypoint=n1)\n self.assertTrue(n4.HasCombination([xa, ya]))\n self.assertTrue(n4.HasCombination([xb, yb]))\n self.assertFalse(n4.HasCombination([xa, yb]))\n self.assertFalse(n4.HasCombination([xb, ya]))\n\n def testConflicting(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n x = p.NewVariable(\"x\")\n a = x.AddBinding(\"a\", source_set=[], where=n1)\n b = x.AddBinding(\"b\", source_set=[], where=n1)\n self._Freeze(p, entrypoint=n1)\n # At n1, x can either be a or b, but not both.\n self.assertTrue(n1.HasCombination([a]))\n self.assertTrue(n1.HasCombination([b]))\n self.assertFalse(n1.HasCombination([a, b]))\n\n def testOneStepSimultaneous(self):\n # Like testSimultaneous, but woven through an additional node\n # n1->n2->n3\n # [n1] x = a or b\n # [n2] y = x\n # [n2] z = x\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew(\"n2\")\n x = p.NewVariable(\"x\")\n y = p.NewVariable(\"y\")\n z = p.NewVariable(\"z\")\n a = x.AddBinding(\"a\", source_set=[], where=n1)\n b = x.AddBinding(\"b\", source_set=[], where=n1)\n ya = y.AddBinding(\"ya\", source_set=[a], where=n2)\n yb = y.AddBinding(\"yb\", source_set=[b], where=n2)\n za = z.AddBinding(\"za\", source_set=[a], where=n2)\n zb = z.AddBinding(\"zb\", source_set=[b], where=n2)\n self._Freeze(p, entrypoint=n1)\n self.assertTrue(n2.HasCombination([ya, za]))\n self.assertTrue(n2.HasCombination([yb, zb]))\n self.assertFalse(n2.HasCombination([ya, zb]))\n self.assertFalse(n2.HasCombination([yb, za]))\n\n def testConflictingBindings(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew(\"n2\")\n x = p.NewVariable(\"x\")\n x_a = x.AddBinding(\"a\", source_set=[], where=n1)\n x_b = x.AddBinding(\"b\", source_set=[], where=n1)\n self._Freeze(p, entrypoint=n1)\n self.assertTrue(n1.HasCombination([x_a]))\n self.assertTrue(n1.HasCombination([x_b]))\n self.assertFalse(n1.HasCombination([x_a, x_b]))\n self.assertFalse(n2.HasCombination([x_a, x_b]))\n\n def testSameNodeOrigin(self):\n # [n1] x = a or b; y = x\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n x = p.NewVariable(\"x\")\n y = p.NewVariable(\"y\")\n xa = x.AddBinding(\"xa\", source_set=[], where=n1)\n xb = x.AddBinding(\"xb\", source_set=[], where=n1)\n ya = y.AddBinding(\"ya\", source_set=[xa], where=n1)\n yb = y.AddBinding(\"yb\", source_set=[xb], where=n1)\n self._Freeze(p, entrypoint=n1)\n self.assertTrue(n1.HasCombination([xa]))\n self.assertTrue(n1.HasCombination([xb]))\n self.assertTrue(n1.HasCombination([xa, ya]))\n self.assertTrue(n1.HasCombination([xb, yb]))\n # We don't check the other two combinations, because within one CFG node,\n # bindings are treated as having any order, so the other combinations\n # are possible, too:\n # n1.HasCombination([xa, yb]) == True (because x = b; y = x; x = a)\n # n1.HasCombination([xb, ya]) == True (because x = a; y = x; x = b)\n\n def testNewVariable(self):\n p = cfg.Program()\n n1 = p.NewCFGNode()\n n2 = p.NewCFGNode()\n x, y, z = \"x\", \"y\", \"z\"\n variable = p.NewVariable(\"xyz\",\n bindings=[x, y],\n source_set=[],\n where=n1)\n variable.AddBinding(z, source_set=variable.bindings, where=n2)\n self.assertSameElements([x, y, z], [v.data for v in variable.bindings])\n self.assertTrue(any(len(e.origins) for e in variable.bindings))\n\n def testNodeBindings(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"node1\")\n n2 = n1.ConnectNew(\"node2\")\n self.assertEquals(n1.name, \"node1\")\n self.assertEquals(n2.name, \"node2\")\n u = p.NewVariable(\"var\")\n a1 = u.AddBinding(1, source_set=[], where=n1)\n a2 = u.AddBinding(2, source_set=[], where=n1)\n a3 = u.AddBinding(3, source_set=[], where=n1)\n a4 = u.AddBinding(4, source_set=[], where=n1)\n self.assertSameElements([a1, a2, a3, a4], n1.bindings)\n\n def testProgram(self):\n p = cfg.Program()\n n1 = p.NewCFGNode()\n n2 = n1.ConnectNew()\n u1 = p.NewVariable(\"var1\")\n u2 = p.NewVariable(\"var2\")\n self.assertEquals(u1.name, \"var1\")\n self.assertEquals(u2.name, \"var2\")\n a11 = u1.AddBinding(11, source_set=[], where=n1)\n a12 = u1.AddBinding(12, source_set=[], where=n2)\n a21 = u2.AddBinding(21, source_set=[], where=n1)\n a22 = u2.AddBinding(22, source_set=[], where=n2)\n self.assertSameElements([n1, n2], p.cfg_nodes)\n self.assertSameElements([u1, u2], p.variables)\n self.assertSameElements([a11, a21], n1.bindings)\n self.assertSameElements([a12, a22], n2.bindings)\n\n def testDisconnected(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = p.NewCFGNode(\"n2\")\n self.assertRaises(AssertionError, self._Freeze, p, entrypoint=n1)\n self.assertRaises(AssertionError, self._Freeze, p, entrypoint=n2)\n\n def testEntryPoint(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew(\"n2\")\n x = p.NewVariable(\"x\")\n a = x.AddBinding(\"a\", source_set=[], where=n1)\n a = x.AddBinding(\"b\", source_set=[], where=n2)\n self._Freeze(p, entrypoint=n1)\n self.assertTrue(n2.HasCombination([a]))\n\n def testNonFrozenSolving(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew(\"n2\")\n x = p.NewVariable(\"x\")\n a = x.AddBinding(\"a\", source_set=[], where=n1)\n a = x.AddBinding(\"b\", source_set=[], where=n2)\n p.entrypoint = n1\n self.assertTrue(n2.HasCombination([a]))\n\n def testFilter2(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = p.NewCFGNode(\"n2\")\n n1.ConnectTo(n2)\n x = p.NewVariable(\"x\")\n a = x.AddBinding(\"a\", source_set=[], where=n2)\n self._Freeze(p, entrypoint=n1)\n self.assertEquals(x.Filter(n1), [])\n self.assertEquals(x.Filter(n2), [a])\n\n def testHiddenConflict1(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew(\"n2\")\n n3 = n1.ConnectNew(\"n3\")\n x = p.NewVariable(\"x\")\n y = p.NewVariable(\"y\")\n z = p.NewVariable(\"z\")\n x_a = x.AddBinding(\"a\", source_set=[], where=n1)\n x_b = x.AddBinding(\"b\", source_set=[], where=n1)\n y_a = y.AddBinding(\"a\", source_set=[x_a], where=n1)\n y_b = y.AddBinding(\"b\", source_set=[x_b], where=n2)\n z_ab1 = z.AddBinding(\"ab1\", source_set=[x_a, x_b], where=n3)\n z_ab2 = z.AddBinding(\"ab2\", source_set=[y_a, x_b], where=n3)\n z_ab3 = z.AddBinding(\"ab3\", source_set=[y_b, x_a], where=n3)\n z_ab4 = z.AddBinding(\"ab4\", source_set=[y_a, y_b], where=n3)\n self._Freeze(p, entrypoint=n1)\n self.assertFalse(n2.HasCombination([y_a, x_b]))\n self.assertFalse(n2.HasCombination([y_b, x_a]))\n self.assertFalse(n3.HasCombination([z_ab1]))\n self.assertFalse(n3.HasCombination([z_ab2]))\n self.assertFalse(n3.HasCombination([z_ab3]))\n self.assertFalse(n3.HasCombination([z_ab4]))\n\n def testHiddenConflict2(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew(\"n2\")\n x = p.NewVariable(\"x\")\n y = p.NewVariable(\"y\")\n x_a = x.AddBinding(\"a\", source_set=[], where=n1)\n x_b = x.AddBinding(\"b\", source_set=[], where=n1)\n y_b = y.AddBinding(\"b\", source_set=[x_b], where=n1)\n self._Freeze(p, entrypoint=n1)\n self.assertFalse(n2.HasCombination([y_b, x_a]))\n\n def testEmptyBinding(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew()\n x = p.NewVariable(\"x\")\n a = x.AddBinding(\"a\")\n self._Freeze(p, entrypoint=n1)\n self.assertEquals(x.Filter(n1), [])\n self.assertEquals(x.Filter(n2), [])\n a.AddOrigin(n2, [])\n self._Freeze(p, entrypoint=n1)\n self.assertEquals(x.Filter(n1), [])\n self.assertEquals(x.Filter(n2), [a])\n a.AddOrigin(n1, [a])\n self._Freeze(p, entrypoint=n1)\n self.assertEquals(x.Filter(n1), [a])\n self.assertEquals(x.Filter(n2), [a])\n\n def testAssignToNew(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew()\n n3 = n2.ConnectNew()\n x = p.NewVariable(\"x\")\n ax = x.AddBinding(\"a\", source_set=[], where=n1)\n y = ax.AssignToNewVariable(\"y\", n2)\n ay, = y.bindings\n z = y.AssignToNewVariable(\"x\", n3)\n az, = z.bindings\n self.assertEquals([v.data for v in y.bindings], [\"a\"])\n self.assertEquals([v.data for v in z.bindings], [\"a\"])\n self._Freeze(p, entrypoint=n1)\n self.assertTrue(n1.HasCombination([ax]))\n self.assertTrue(n2.HasCombination([ax, ay]))\n self.assertTrue(n3.HasCombination([ax, ay, az]))\n self.assertFalse(n1.HasCombination([ax, ay]))\n self.assertFalse(n2.HasCombination([ax, ay, az]))\n\n def testPasteVariable(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew()\n x = p.NewVariable(\"x\")\n ax = x.AddBinding(\"a\", source_set=[], where=n1)\n bx = x.AddBinding(\"b\", source_set=[], where=n1)\n y = p.NewVariable(\"y\")\n y.PasteVariable(x, n2)\n ay, by = y.bindings\n self.assertEquals([v.data for v in x.bindings], [\"a\", \"b\"])\n self.assertEquals([v.data for v in y.bindings], [\"a\", \"b\"])\n self._Freeze(p, entrypoint=n1)\n self.assertTrue(n1.HasCombination([ax]))\n self.assertTrue(n1.HasCombination([bx]))\n self.assertFalse(n1.HasCombination([ay]))\n self.assertFalse(n1.HasCombination([by]))\n self.assertTrue(n2.HasCombination([ay]))\n self.assertTrue(n2.HasCombination([by]))\n\n def testPasteAtSameNode(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n x = p.NewVariable(\"x\")\n x.AddBinding(\"a\", source_set=[], where=n1)\n x.AddBinding(\"b\", source_set=[], where=n1)\n y = p.NewVariable(\"y\")\n y.PasteVariable(x, n1)\n ay, _ = y.bindings\n self.assertEquals([v.data for v in x.bindings], [\"a\", \"b\"])\n self.assertEquals([v.data for v in y.bindings], [\"a\", \"b\"])\n o, = ay.origins\n self.assertItemsEqual([cfg.SourceSet([])], o.source_sets)\n o, = ay.origins\n self.assertItemsEqual([cfg.SourceSet([])], o.source_sets)\n\n def testId(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = p.NewCFGNode(\"n2\")\n x = p.NewVariable(\"x\")\n y = p.NewVariable(\"y\")\n self.assertIsInstance(x.id, int)\n self.assertIsInstance(y.id, int)\n self.assertLess(x.id, y.id)\n self.assertIsInstance(n1.id, int)\n self.assertIsInstance(n2.id, int)\n self.assertLess(n1.id, n2.id)\n\n def testPrune(self):\n p = cfg.Program()\n n1 = p.NewCFGNode(\"n1\")\n n2 = n1.ConnectNew(\"n2\")\n n3 = n2.ConnectNew(\"n3\")\n n4 = n3.ConnectNew(\"n4\")\n n1.ConnectTo(n4)\n x = p.NewVariable(\"x\")\n x.AddBinding(1, [], n1)\n x.AddBinding(2, [], n2)\n x.AddBinding(3, [], n3)\n self.assertSameElements([1], [v.data for v in x.Bindings(n1)])\n self.assertSameElements([2], [v.data for v in x.Bindings(n2)])\n self.assertSameElements([3], [v.data for v in x.Bindings(n3)])\n self.assertSameElements([1, 3], [v.data for v in x.Bindings(n4)])\n self.assertSameElements([1], x.Data(n1))\n self.assertSameElements([2], x.Data(n2))\n self.assertSameElements([3], x.Data(n3))\n self.assertSameElements([1, 3], x.Data(n4))\n\n def testProgramFreeze(self):\n p = cfg.Program()\n n = p.NewCFGNode(\"n\")\n self._Freeze(p, entrypoint=n)\n self.assertRaises(AssertionError, p.NewCFGNode)\n self.assertRaises(AssertionError, p.NewCFGNode, \"named\")\n self.assertRaises(AssertionError, p.NewCFGNode, name=\"named\")\n\n def testVariableCallback(self):\n counters = [0, 0]\n def callback1():\n counters[0] += 1\n def callback2():\n counters[1] += 1\n p = cfg.Program()\n x = p.NewVariable(\"x\")\n x.RegisterChangeListener(callback1)\n x.AddBinding(\"a\")\n self.assertListEqual(counters, [1, 0])\n x.RegisterChangeListener(callback2)\n x.AddBinding(\"b\")\n self.assertListEqual(counters, [2, 1])\n x.AddBinding(\"a\") # Duplicate binding; callbacks should not be triggered\n self.assertListEqual(counters, [2, 1])\n x.UnregisterChangeListener(callback1)\n x.AddBinding(\"c\")\n self.assertListEqual(counters, [2, 2])\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"pytype/pytd/cfg_test.py","file_name":"cfg_test.py","file_ext":"py","file_size_in_byte":19805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"117474387","text":"#!/usr/bin/env python\n\nfrom kazoo.client import KazooClient\nfrom urlparse import urljoin\nimport json\nimport requests\n\n\nzk = KazooClient(hosts='192.168.1.111:2181')\nzk.start()\nAPI = json.loads(zk.get('/shipyard/api')[0])\nURL = API['url']\nKEY = API['key']\n\n\ndef get(key):\n url = urljoin(URL, '/api/%s' % key)\n obj = requests.get(url, headers={'X-Service-Key': KEY}).json()\n return obj\n\n\ndef put(key, obj):\n zk.delete('/shipyard/%s' % key, recursive=True)\n zk.ensure_path('/shipyard/%s' % key)\n for i in obj:\n zk.create('/shipyard/%s/%s' % (key, i['id']), json.dumps(i))\n\n\nif __name__ == '__main__':\n for key in ['accounts', 'engines', 'containers']:\n put(key, get(key))\n\n","sub_path":"zk/monitor/discard/zksync.py","file_name":"zksync.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"520302949","text":"run = True\r\nimport random\r\nwhile run == True:\r\n tests = int(input(\"How many loops? Enter 0 to end.\"))\r\n if tests == 0:\r\n run = False\r\n else:\r\n finalScore = []\r\n while tests > 0:\r\n score = 1\r\n cards = [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,13,13]\r\n correct = True\r\n cardNumber = len(cards) - 1\r\n card = cards.pop(random.randint(0,cardNumber))\r\n #print(\"Drawn a \" + str(card))\r\n while correct == True:\r\n drawn = False\r\n while drawn == False:\r\n if card <= 7:\r\n guess = \"H\"\r\n elif card >= 8:\r\n guess = \"L\"\r\n #print(\"Player guesses \" + str(guess))\r\n cardNumber = len(cards) - 1\r\n #print(\"Current size of deck is \" + str(len(cards)))\r\n newCard = cards.pop(random.randint(0,cardNumber))\r\n #print(\"Drawn a \" + str(newCard))\r\n if score == 52:\r\n drawn = True\r\n elif newCard != card:\r\n drawn = True\r\n else:\r\n cards.append(newCard)\r\n #print(\"Returning card to deck\")\r\n if score == 52:\r\n correct = False\r\n elif guess == \"L\":\r\n if newCard < card:\r\n #print(\"Guessed lower correctly!\")\r\n score = score + 1\r\n card = newCard\r\n else:\r\n #print(\"Guessed(H) incorrectly!\")\r\n correct = False\r\n elif guess == \"H\":\r\n if newCard > card:\r\n #print(\"Guessed higher correctly!\")\r\n score = score + 1\r\n card = newCard\r\n else:\r\n #print(\"Guessed(L) incorrectly!\")\r\n correct = False\r\n finalScore.append(score)\r\n print(\"Test ended with a score of \" + str(score) + \", \" + str(tests) + \" tests left!\")\r\n tests = tests - 1\r\n print(\"List of scores \" + str(finalScore))\r\n print(\"Average score of all the tested games \" + str(sum(finalScore)/len(finalScore)))\r\n \r\n \r\n","sub_path":"HighLow Simulator - Minimal.py","file_name":"HighLow Simulator - Minimal.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"133063121","text":"from flask import Flask, request\nimport json\nimport pyCiscoSpark\nimport sys\n\napp = Flask(__name__)\norder = \"\"\n\n@app.route('/',methods=['GET', 'POST'])\ndef foo():\n\tdata = request.get_json()\n\tglobal order\n\torder = str(data['result']['action'])\n\tif order == \"PlaceSingleOrder\":\n\t\tif str(data[\"result\"][\"parameters\"][\"Drink\"]) != \"\":\n\t\t\torder2 = \"\"\n\t\t\torder2 = order2 + str(data[\"result\"][\"parameters\"][\"number\"]) + \" \" + str(data[\"result\"][\"parameters\"][\"Drink\"])\n\n\t\telif \"Snack\" in data[\"result\"][\"parameters\"] != \"\":\n\t\t\torder2 = \"\"\n\t\t\torder2 = order2 + str(data[\"result\"][\"parameters\"][\"number\"]) + \" \" + str(data[\"result\"][\"parameters\"][\"Snack\"])\n\tprint (order2)\n\t\t\t\n\t#elif order == \"PlaceDoubleOrder\":\n\t\t#do for single order\n\tprint (\"I'm here\")\n\t\n\tif [\"result\"][\"action\"] != \"FinalizeOrder\":\n\t\trequest2()\n\telse:\n\t\tprint (\"Nothing else to be done\")\t\n\t\ndef request2():\t\n\tdata2 = request.get_json()\n\tprint (\"Part 2 homie\")\n\ttnum = int(data2[\"result\"][\"paramater\"][\"TableNumber\"])\n\tprint (tnum)\n\t\n\tspark(order2, tnum)\n\ndef search (values, searchFor):\n for k in values[\"items\"]:\n print (k[\"title\"])\n if (k[\"title\"] == searchFor) : return k[\"id\"]\n return None\n \n\n\t\n\n\t\n\ndef spark(order, tableno):\n\taccesstoken=\"Bearer ZTZlNDdmOGUtOGE4MC00NzdmLWE3YmYtOGNlZjc2NTMxYzVkYjA3NTVjMmUtMmIw\"\n\n\n\trooms_dict=pyCiscoSpark.get_rooms(accesstoken)\n\n\troomid = search (rooms_dict, \"Table \" + tableno)\n\n\tprint (roomid)\n\t\n\tresp_dict = pyCiscoSpark.post_message(accesstoken,roomid,order)\n\n\tprint (resp_dict)\n \n\nif __name__ == '__main__':\n app.run()","sub_path":"SparkBackup copy 2.py","file_name":"SparkBackup copy 2.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"598451627","text":"import cPickle\nimport os.path\nimport sys\n\nimport numpy as np\nfrom keras.models import model_from_json\nfrom scipy import hanning\n\nsys.setrecursionlimit(50000)\n\n\ndef load_model(modelPath):\n\n defFilePath = modelPath+\"/definition.json\"\n weightFilePath = modelPath+\"/weights.h5\"\n dumpFilePath = modelPath+\"/cache.dump\"\n\n # check for a memory dump of the model\n if os.path.isfile(dumpFilePath):\n # return the saved model\n m = cPickle.load(open(dumpFilePath, \"rb\"))\n return m\n\n model = model_from_json(open(defFilePath).read())\n model.load_weights(weightFilePath)\n\n # cache the model by dumping it into a file\n cPickle.dump(model, open(dumpFilePath, \"wb\"), protocol=cPickle.HIGHEST_PROTOCOL)\n\n return model\n\n\ndef stft(x, fs, framesz, hop):\n \"\"\"\n rolling/hopping hamming window FFT\n x .. data - 1D numpy array\n fs .. data rate of x in samples per sec\n framesz .. frame size in seconds\n hop .. sampling resoltuion in seconds\n \"\"\"\n framesamp = int(framesz * fs)\n hopsamp = int(hop * fs)\n xlen = len(x)\n newsamps = np.int(np.ceil((np.float(xlen) - np.float(framesamp)) / hopsamp))\n win = hanning(framesamp)\n X = np.empty((framesamp, newsamps), dtype=complex)\n freqs = np.fft.fftfreq(framesamp) * fs\n for n in range(newsamps):\n i = n * hopsamp\n X[:, n] = np.fft.fft(win * x[i:i + framesamp])\n\n fceil = int(np.ceil(np.float(X.shape[0]) / 2)) + 1\n X = np.abs(X[0:fceil, :])\n\n return X, freqs\n\n\ndef stack_stft(x):\n y, f = stft(x, 8000, np.float32(512) / 22050, np.float32(64) / 22050)\n\n T = 688\n F = 94\n nFrame = y.shape[1]\n nWindows = np.int(np.floor(float(nFrame) / T))\n windowStack = np.zeros((nWindows, 1, F, T), dtype='float32')\n\n for j in range(nWindows):\n windowStack[j, 0, :, :] = y[:, j * T:(j + 1) * T]\n\n return windowStack\n\n\ndef predict(x, model):\n y = stack_stft(x)\n\n prob = model.predict_proba(y, batch_size=128, verbose=0)\n\n return prob\n","sub_path":"cnn_predict_spec.py","file_name":"cnn_predict_spec.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"354862692","text":"l = [1, 2, [2, 4, [[7, 8], 4, 6]]]\n\ndef recurs(l, sum = 0):\n\n if not l:\n return\n\n else: \n\n for elem in l:\n try:\n sum +=elem\n except:\n sum += recurs(elem)\n return sum\n\nprint('sum of elements:', recurs(l))","sub_path":"Tasks/AlexanderTarasov/homework_5/hw5.py","file_name":"hw5.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"193009689","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# native\nfrom docopt import docopt\nimport os, sys\nimport re\n\n# local\nsys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib'))\nsys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'src-helpers'))\nfrom helpers import *\nfrom vecsim import VecSim\n\n# docopt help\ndoc = \"\"\"Compute vector similarity\n\nUsage: \n %(name)s KV_DICT [ PAIR_LIST ] [options]\n\nArguments:\n KV_DICT Dictionary with Key-Value(s) tuples to compare\n PAIR_LIST Dictionary with tab-separated Molecule pairs\n\nOptions:\n -m --metric ARRAY Similarity metric\n -H --header STRING First line of input file is a header\nOutput:\n -o --out STRINGF Print results to STDOUT in the specified string format\n --count INT Print results up to the specified amount [default: -1]\n -r --repeat Enable to include repeat pairs when a pair-list is not provided\n -v --verbose Print debug messages to STDERR\n\nMisc:\n -h --help Show this message.\n --opts Print options debug info\n\n\"\"\" % { 'name': os.path.basename(__file__) } \n\n\n# ========== MAIN\n\ndef initialize_component(options):\n \n vector_dict = input_to_rdict(data = options['KV_DICT'], sep = \"\\t\", header = options['--header'], ssep = ',')\n vector_dict = { vid: vector[0] for vid,vector in vector_dict.viewitems() }\n pair_list = input_to_n_list(options['PAIR_LIST'], \"\\t\") if options['PAIR_LIST'] else None\n\n # init class\n vsim = VecSim(vector_dict, pair_list)\n\n # compute similarity\n for metric in options['--metric']:\n if metric == 'cosine':\n vsim.cosine()\n if metric == 'forbes':\n vsim.forbes()\n if metric == 'geometric':\n vsim.geometric()\n if metric == 'hgeometric':\n vsim.hypergeometric()\n if metric == 'jaccard':\n vsim.jaccard()\n if metric == 'pcc':\n vsim.pcc()\n if metric == 'simpson':\n vsim.simpson()\n\n # print results\n if options['--out']:\n vsim.print_result(replace_literals(options['--out']), int(options['--count']))\n\n# ========== AUXILIARY\n\ndef verify_options(options):\n \"\"\"Validates supported optional arguments\n\n :options: docopt options dictionary\n\n \"\"\"\n \n log = []\n\n # metrics\n metrics = [ 'cosine', 'forbes', 'geometric', 'hgeometric', 'jaccard', 'pcc', 'simpson' ]\n if not options['--metric'] in metrics:\n log.append('ERROR: metric not supported: %s' % options['--metric'])\n\n if log:\n for error in log:\n print_error(error)\n\n\n# ========== INITIALIZE\n\nif __name__ == '__main__':\n options = docopt(doc)\n\n if options['--header']:\n options['--header'] = 'I'\n options['--metric'] = options['--metric'].split(',')\n options['--count'] = int(options['--count'])\n\n if options['--opts']:\n verify_options(options)\n print_error(options)\n exit()\n initialize_component(options)\n","sub_path":"bin/voppler.py","file_name":"voppler.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383620704","text":"#!/usr/bin/env python\n\"\"\"\n\nExamples:\n\t%s -m 1 -u yh -n /tmp/genomeRBDictTaxID60711.pickle -c\n\t\n\t%s \nDescription:\n\t2012.5.2\n\tprogram to find the context (nearby genes) of a locus. It fills results into db table locus_context.\n\tIt also annotates structural variation or SNPs (syn, non-syn, intron, etc.) db table locus_annotation.\n\t\n\n\"\"\"\nimport sys, os, math\n__doc__ = __doc__%(sys.argv[0], sys.argv[0])\n\nsys.path.insert(0, os.path.expanduser('~/lib/python'))\nsys.path.insert(0, os.path.join(os.path.expanduser('~/script')))\n\nimport time, csv, getopt\nimport warnings, traceback\nfrom pymodule import ProcessOptions, PassingData, GenomeDB\nfrom pymodule.db import formReadmeObj\nfrom pymodule.CNV import CNVCompare, CNVSegmentBinarySearchTreeKey, get_overlap_ratio\nfrom pymodule.RBTree import RBDict\nfrom vervet.src.mapper.AbstractVervetMapper import AbstractVervetMapper\nfrom vervet.src import VervetDB\nfrom Bio.Seq import Seq\t#translate cds sequence, decide whether synonymous/non SNP\nfrom Bio.Alphabet import IUPAC\nfrom pymodule.SNP import nt2complement\t#to complement single nucleotide\n\nclass FindLocusContext(AbstractVervetMapper):\n\t__doc__ = __doc__\n\toption_default_dict = AbstractVervetMapper.option_default_dict.copy()\n\toption_default_dict.pop(('inputFname', 0, ))\n\toption_default_dict.pop(('outputFname', 0, ))\n\toption_default_dict.pop(('outputFnamePrefix', 0, ))\n\toption_default_dict.update({\n\t\t\t\t\t\t\t('genome_db_schema', 1, ): ['genome', 'g', 1, 'genome schema name within db (postgresql)', ],\\\n\t\t\t\t\t\t\t('locus_type_id', 1, int): [None, 'm', 1, 'construct contexts for loci from this locus_type_id'],\\\n\t\t\t\t\t\t\t('genomeRBDictPickleFname', 1, ): ['', 'n', 1, 'The file to contain pickled genomeRBDict.'],\\\n\t\t\t\t\t\t\t('max_distance', 0, int): [20000, 'x', 1, \"maximum distance allowed between a CNV and a gene\"],\\\n\t\t\t\t\t\t\t('tax_id', 0, int): [60711, 'a', 1, 'Taxonomy ID to get gene position and coordinates.'],\\\n\t\t\t\t\t\t\t('commit', 0, int):[0, 'c', 0, 'commit db transaction'],\\\n\t\t\t\t\t\t\t('debug', 0, int):[0, 'b', 0, 'toggle debug mode'],\\\n\t\t\t\t\t\t\t('report', 0, int):[0, 'r', 0, 'toggle report, more verbose stdout/stderr.']\n\t\t\t\t\t\t\t})\n\t\n\tdef __init__(self, **keywords):\n\t\t\"\"\"\n\t\t2012.5.05\n\t\t\"\"\"\n\t\t\n\t\tinputFnameLs = []\n\t\tAbstractVervetMapper.__init__(self, inputFnameLs, **keywords)\n\t\n\tdef getLocusAnnotationShortName2dbEntry(self, db_vervet):\n\t\t\"\"\"\n\t\t2012.5.14\n\t\t\"\"\"\n\t\tsys.stderr.write(\"Getting locus_annotation_short_name2db_entry ...\")\n\t\tlocus_annotation_short_name2db_entry = {}\n\t\trows = VervetDB.LocusAnnotationType.query.all()\n\t\tfor row in rows:\n\t\t\tlocus_annotation_short_name2db_entry[row.short_name] = row\n\t\tsys.stderr.write(\"Done.\\n\")\n\t\treturn locus_annotation_short_name2db_entry\n\t\n\tdef _constructSNPAnnotation(self, db_vervet, locus=None, oneGeneData=None, locus_context=None, locus_annotation_short_name2db_entry=None,\\\n\t\t\t\t\t\t\tgeneCommentaryRBDict=None, geneSegmentKey = None, compareIns=None, param_obj=None):\n\t\t\"\"\"\n\t\t2012.5.18\n\t\t\tadd which_codon into the db_vervet.getLocusAnnotation()\n\t\t2012.5.14\n\t\t\tadapted from variation/src/ConstructSNPAnnotation.py\n\t\t\t\n\t\t\tlocus is of type VervetDB.Locus\n\t\t\toneGeneData = PassingData(strand = row.strand, gene_id = row.id, gene_start = row.start, \\\n\t\t\t\t\t\t\t\t\t\tgene_stop = row.stop, geneCommentaryRBDictLs=[],\\\n\t\t\t\t\t\t\t\t\t\tncbi_gene_id=row.ncbi_gene_id)\n\t\t2009-2-5\n\t\t\tbug fixed. when adding a box as UTR, make sure after the forloop above, the current box is still the UTR.\n\t\t2009-1-5\n\t\t\"\"\"\n\t\tsys.stderr.write(\"Constructing LocusAnnotation for SNP ...\\n\")\n\t\t#standard_translator = Translate.unambiguous_dna_by_id[1]\t#2012.5.23 Translate is to be deprecated.\n\t\tcounter = 0\n\t\treal_counter = 0\n\t\tcounter += 1\n\t\tchr=locus.chromosome\n\t\tpos = locus.start\n\t\tallele1 = locus.ref_seq.sequence.encode('ascii')\t#2012.5.17 unicode is not accepted by cds_seq.tomutable()\n\t\tallele2 = locus.alt_seq.sequence.encode('ascii')\n\t\tsnp_annotation_type_short_name_ls = []\t#each element is (snp_annotation_type_short_name, gene_id, gene_commentary_id, \n\t\t\t\t# which_exon_or_intron, pos_within_codon)\n\t\tdisp_pos = locus_context.disp_pos\n\t\tgene_id = locus_context.gene_id\n\t\t#gene_box_node_ls = []\n\t\t#geneCommentaryRBDict.findNodes(segmentKey, node_ls=gene_box_node_ls, compareIns=compareIns)\n\t\tgene_commentary_id = geneCommentaryRBDict.gene_commentary_id\n\t\tbox_ls = geneCommentaryRBDict.box_ls\n\t\tprotein_box_ls = geneCommentaryRBDict.protein_box_ls\n\t\t#gene_commentary = GeneCommentary.get(gene_commentary_id)\n\t\t#box_ls = gene_commentary.construct_annotated_box()\n\t\tcds_sequence = geneCommentaryRBDict.cds_sequence\n\t\tgeneCommentaryRBDict.gene_commentary_type_name\n\t\tCDS_5_end_pos = geneCommentaryRBDict.CDS_5_end_pos\n\t\tno_of_introns = geneCommentaryRBDict.no_of_introns\n\t\t\n\t\tdetailed_box_type = geneSegmentKey.label\n\t\tis_translated = geneSegmentKey.is_translated\n\t\twhich_intron = geneSegmentKey.intron_number\t#which intron the SNP resides, starting from 1\n\t\twhich_coding_exon = geneSegmentKey.cds_number\t#which exon the SNP resides in terms of the CDS sequence, starting from 1\n\t\tcumulativeWithinCDSUTRAndIntronLen = geneSegmentKey.cumulativeWithinCDSUTRAndIntronLen\n\t\tgene_segment_id = geneSegmentKey.gene_segment_id\n\t\t\n\t\tif protein_box_ls:\t#this is a protein coding gene\n\t\t\tif detailed_box_type.find('UTR')>=0 and detailed_box_type=='exon' and is_translated==0:\t#it's UTR. bug fixed. make sure after the forloop above, \n\t\t\t\t\t# the current box is still the UTR.\n\t\t\t\tsnp_annotation_type_short_name_ls.append((detailed_box_type, gene_id, gene_commentary_id, None , None, None))\n\t\t\telse:\n\t\t\t\tif oneGeneData.strand=='-1':\t#reverse the order of exon/intron\n\t\t\t\t\tno_of_coding_exons = len(protein_box_ls)\n\t\t\t\t\t#no_of_introns = len(gene_commentary.mrna_box_ls)-no_of_coding_exons\t#not right\n\t\t\t\t\twhich_coding_exon = no_of_coding_exons-which_coding_exon+1\n\t\t\t\t\twhich_intron = no_of_introns-which_intron + 1\n\t\t\t\tif detailed_box_type=='intron':\n\t\t\t\t\tsnp_annotation_type_short_name_ls.append(('intron', gene_id, gene_commentary_id, which_intron, None, None))\n\t\t\t\t\tif pos-geneSegmentKey.start<=1:\t#within the donor/acceptor two-nucleotide\n\t\t\t\t\t\tif oneGeneData.strand=='-1':\n\t\t\t\t\t\t\tsnp_annotation_type_short_name = 'splice-acceptor'\t#on the 3' of this intron\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsnp_annotation_type_short_name = 'splice-donor'\t#on the 5' of this intron\n\t\t\t\t\t\tsnp_annotation_type_short_name_ls.append((snp_annotation_type_short_name, gene_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgene_commentary_id, which_intron, None, None))\n\t\t\t\t\telif geneSegmentKey.stop-pos<=1:\n\t\t\t\t\t\tif oneGeneData.strand=='-1':\n\t\t\t\t\t\t\tsnp_annotation_type_short_name = 'splice-donor'\t#on the 5' of this intron\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsnp_annotation_type_short_name = 'splice-acceptor'\t#on the 3' of this intron\n\t\t\t\t\t\tsnp_annotation_type_short_name_ls.append((snp_annotation_type_short_name, gene_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgene_commentary_id, which_intron, None, None))\n\t\t\t\telif detailed_box_type=='CDS':\t#must be translated\n\t\t\t\t\tSNP_index_in_CDS = pos - CDS_5_end_pos - cumulativeWithinCDSUTRAndIntronLen\n\t\t\t\t\tif oneGeneData.strand=='-1':\t#reverse\n\t\t\t\t\t\tSNP_index_in_CDS = len(cds_sequence)-SNP_index_in_CDS-1\t#-1 because SNP_index_in_CDS starts from 0\n\t\t\t\t\t\tgene_allele1 = nt2complement[allele1]\n\t\t\t\t\t\tgene_allele2 = nt2complement[allele2]\n\t\t\t\t\telse:\n\t\t\t\t\t\tgene_allele1 = allele1\n\t\t\t\t\t\tgene_allele2 = allele2\n\t\t\t\t\tSNP_index_in_CDS = int(SNP_index_in_CDS)\t\n\t\t\t\t\t# SNP_index_in_CDS is type long. without int(), cds_seq[SNP_index_in_CDS] returns a Bio.Seq with one nucleotide, \n\t\t\t\t\t# rather than a single-char string\n\t\t\t\t\tSNP_index_in_peptide = SNP_index_in_CDS/3\n\t\t\t\t\t\n\t\t\t\t\tSNP_index_in_peptide = int(SNP_index_in_peptide)\t#ditto as int(SNP_index_in_CDS), not necessary\n\t\t\t\t\t\n\t\t\t\t\tpos_within_codon = SNP_index_in_CDS%3+1\t#pos_within_codon starts from 1\n\t\t\t\t\tcds_seq = Seq(cds_sequence, IUPAC.unambiguous_dna)\n\t\t\t\t\tif SNP_index_in_CDS>=len(cds_seq):\n\t\t\t\t\t\tsys.stderr.write(\"Error: SNP (%s, %s), SNP_index_in_CDS=%s, is beyond any of the boxes from gene %s (chr=%s, %s-%s), \\\n\t\t\t\t\t\t\t\tgene_commentary_id %s (%s-%s), box_ls=%s, cds-length=%s. counted as intergenic.\\n\"%\\\n\t\t\t\t\t\t\t\t(chr, pos, SNP_index_in_CDS, gene_id, oneGeneData.chromosome, oneGeneData.gene_start, oneGeneData.gene_stop, \\\n\t\t\t\t\t\t\t\tgene_commentary_id, geneCommentaryRBDict.start, geneCommentaryRBDict.stop, repr(box_ls), \\\n\t\t\t\t\t\t\t\tlen(cds_seq)))\n\t\t\t\t\t\tsys.exit(3)\n\t\t\t\t\t\tsnp_annotation_type_short_name_ls.append(['intergenic'])\n\t\t\t\t\tif cds_seq[SNP_index_in_CDS]!=gene_allele1 and cds_seq[SNP_index_in_CDS]!=gene_allele2:\n\t\t\t\t\t\tsys.stderr.write(\"Error: Neither allele (%s, %s) from SNP (%s,%s) matches the nucleotide, %s, from the cds seq of gene %s \\\n\t\t\t\t\t\t\t(gene_commentary_id=%s).\\n\"%\\\n\t\t\t\t\t\t\t(gene_allele1, gene_allele2, chr, pos, cds_seq[SNP_index_in_CDS], gene_id, gene_commentary_id))\n\t\t\t\t\t\tsys.exit(3)\n\t\t\t\t\tcds_mut_ar = cds_seq.tomutable()\n\t\t\t\t\tcds_mut_ar[SNP_index_in_CDS] = gene_allele1\n\t\t\t\t\tpeptide = cds_mut_ar.toseq().translate()\t#2012.5.23 no more translator. table=1\n\t\t\t\t\t\n\t\t\t\t\talt_cds_mut_ar = cds_seq.tomutable()\n\t\t\t\t\talt_cds_mut_ar[SNP_index_in_CDS] = gene_allele2\n\t\t\t\t\talt_peptide = alt_cds_mut_ar.toseq().translate()\n\t\t\t\t\taa = peptide[SNP_index_in_peptide]\n\t\t\t\t\talt_aa = alt_peptide[SNP_index_in_peptide]\n\t\t\t\t\tif aa != alt_aa:\n\t\t\t\t\t\tsnp_annotation_type_short_name = 'non-synonymous'\n\t\t\t\t\t\tcomment = '%s->%s'%(aa, alt_aa)\n\t\t\t\t\telse:\n\t\t\t\t\t\tsnp_annotation_type_short_name = 'synonymous'\n\t\t\t\t\t\tcomment = None\n\t\t\t\t\tsnp_annotation_type_short_name_ls.append((snp_annotation_type_short_name, gene_id, gene_commentary_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhich_coding_exon, pos_within_codon, comment, SNP_index_in_peptide))\n\t\t\t\t\t\n\t\t\t\t\tif aa != alt_aa:\n\t\t\t\t\t\tif aa=='*' or alt_aa=='*':\n\t\t\t\t\t\t\tsnp_annotation_type_short_name = 'premature-stop-codon'\t#could also be the last stop codon changing to something else \n\t\t\t\t\t\t\t# and thereby extending the cds\n\t\t\t\t\t\t\tsnp_annotation_type_short_name_ls.append((snp_annotation_type_short_name, gene_id, gene_commentary_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhich_coding_exon, pos_within_codon, comment, SNP_index_in_peptide))\n\t\t\t\t\t\tif SNP_index_in_peptide==0:\n\t\t\t\t\t\t\tsnp_annotation_type_short_name = 'init-Met'\n\t\t\t\t\t\t\tsnp_annotation_type_short_name_ls.append((snp_annotation_type_short_name, gene_id, gene_commentary_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhich_coding_exon, pos_within_codon, comment, SNP_index_in_peptide))\n\t\t\t\t\t\"\"\"\n\t\t\t\t\texcept:\n\t\t\t\t\t\ttraceback.print_exc()\n\t\t\t\t\t\tsys.stderr.write('%s.\\n'%repr(sys.exc_info()))\n\t\t\t\t\t\tsys.stderr.write(\"Except encountered for SNP (%s, %s), gene %s (chr=%s, %s-%s), gene_commentary_id %s (%s-%s), box_ls=%s.\\n\"%\\\n\t\t\t\t\t\t\t(chr, pos, gene_id, locus.chromosome, oneGeneData.start, oneGeneData.stop, \\\n\t\t\t\t\t\t\tgene_commentary_id, geneCommentaryRBDict.start, geneCommentaryRBDict.stop, repr(box_ls)))\n\t\t\t\t\t\"\"\"\n\t\telse:\n\t\t\tif oneGeneData.type_of_gene=='pseudo':\n\t\t\t\tsnp_annotation_type_short_name = oneGeneData.type_of_gene\n\t\t\telse:\n\t\t\t\tsnp_annotation_type_short_name = geneCommentaryRBDict.gene_commentary_type_name\n\t\t\tsnp_annotation_type_short_name_ls.append((snp_annotation_type_short_name, gene_id, gene_commentary_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tNone, None, None))\n\t\t#else:\t#integenic\n\t\t#\tsnp_annotation_type_short_name_ls.append(['intergenic'])\n\t\t\t\n\t\t#now save everything into db\n\t\tlocus_annotation_ls = []\n\t\tfor snp_annotation_type_tup in snp_annotation_type_short_name_ls:\n\t\t\tsnp_annotation_type_short_name = snp_annotation_type_tup[0]\n\t\t\tif snp_annotation_type_short_name not in locus_annotation_short_name2db_entry:\n\t\t\t\tty = db_vervet.getLocusAnnotationType(locus_annotation_type_short_name=snp_annotation_type_short_name)\n\t\t\t\tlocus_annotation_short_name2db_entry[snp_annotation_type_short_name] = ty\n\t\t\tif len(snp_annotation_type_tup)>=3:\n\t\t\t\tgene_id = snp_annotation_type_tup[1]\n\t\t\t\tgene_commentary_id = snp_annotation_type_tup[2]\n\t\t\telse:\n\t\t\t\tgene_id = None\n\t\t\t\tgene_commentary_id = None\n\t\t\tif len(snp_annotation_type_tup)>=4:\n\t\t\t\twhich_exon_or_intron = snp_annotation_type_tup[3]\n\t\t\telse:\n\t\t\t\twhich_exon_or_intron = None\n\t\t\tif len(snp_annotation_type_tup)>=5:\n\t\t\t\tpos_within_codon = snp_annotation_type_tup[4]\n\t\t\telse:\n\t\t\t\tpos_within_codon = None\n\t\t\tif len(snp_annotation_type_tup)>=6:\n\t\t\t\tcomment = snp_annotation_type_tup[5]\n\t\t\telse:\n\t\t\t\tcomment = None\n\t\t\tif len(snp_annotation_type_tup)>=7:\n\t\t\t\twhich_codon = snp_annotation_type_tup[6] +1\t#[6] is the SNP_index_in_peptide\n\t\t\telse:\n\t\t\t\twhich_codon = None\n\t\t\tlocus_annotation_type = locus_annotation_short_name2db_entry.get(snp_annotation_type_short_name)\n\t\t\t\n\t\t\tlocus_annotation = db_vervet.getLocusAnnotation(locus_id=locus.id, locus_context_id=locus_context.id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tlocus_context=locus_context, gene_id=gene_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tgene_commentary_id=gene_commentary_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tgene_segment_id=gene_segment_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tlocus_annotation_type=locus_annotation_type, locus_annotation_type_id=locus_annotation_type.id,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\twhich_exon_or_intron=which_exon_or_intron, pos_within_codon=pos_within_codon, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\twhich_codon=which_codon, label=geneSegmentKey.label, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tutr_number=geneSegmentKey.utr_number, cds_number=geneSegmentKey.cds_number, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tintron_number=geneSegmentKey.intron_number,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\texon_number=geneSegmentKey.exon_number, overlap_length=None, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\toverlap_fraction_in_locus=None, overlap_fraction_in_gene=None,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\tcomment=comment)\n\t\t\tif locus_annotation:\n\t\t\t\tparam_obj.no_of_locus_annotations_already_in_db += 1\n\t\t\telse:\n\t\t\t\tparam_obj.no_of_into_db += 1\n\t\t\tparam_obj.no_of_total_annotations += 1\n\t\t\tlocus_annotation_ls.append(locus_annotation)\n\t\t\treal_counter += 1\n\t\t\"\"\"\n\t\tif self.report and counter%2000==0:\n\t\t\tsys.stderr.write(\"%s%s\\t%s\"%('\\x08'*40, counter, real_counter))\n\t\t\tsession.flush()\n\t\tif self.report:\n\t\t\tsys.stderr.write(\"%s%s\\t%s\\n\"%('\\x08'*40, counter, real_counter))\n\t\t\"\"\"\n\t\tsys.stderr.write(\"Done.\\n\")\n\t\treturn locus_annotation_ls\n\t\n\t\n\tdef findLocusContext(self, db_vervet=None, genomeRBDict=None, locus_type_id=None, compareIns=None, max_distance=50000, debug=0,\n\t\t\t\t\tparam_obj=None, locus_annotation_short_name2db_entry=None):\n\t\t\"\"\"\n\t\t2012.5.14\n\t\t2011-3-25\n\t\t\tcast row.chromosome (from db) into str type.\n\t\t2010-10-3\n\t\t\tbug fixed: (chr, start, stop) is not unique. There are genes with the same coordinates.\n\t\t2010-8-18\n\t\t\"\"\"\n\t\tsys.stderr.write(\"Finding Locus context ... \\n\")\n\t\tsession = db_vervet.session\n\t\tTableClass = VervetDB.Locus\n\t\tquery = TableClass.query.filter_by(locus_type_id=locus_type_id)\n\t\tfor row in query:\n\t\t\tsegmentKey = CNVSegmentBinarySearchTreeKey(chromosome=str(row.chromosome), \\\n\t\t\t\t\t\t\tspan_ls=[row.start, row.stop], \\\n\t\t\t\t\t\t\tmin_reciprocal_overlap=0.0000001, )\t#min_reciprocal_overlap doesn't matter here.\n\t\t\t\t# it's decided by compareIns.\n\t\t\tnode_ls = []\n\t\t\tgenomeRBDict.findNodes(segmentKey, node_ls=node_ls, compareIns=compareIns)\n\t\t\tfor node in node_ls:\n\t\t\t\tgeneSegKey = node.key\n\t\t\t\tfor oneGeneData in node.value:\n\t\t\t\t\t# geneSegKey.span_ls expands 20kb upstream or downstream of the gene.\n\t\t\t\t\toverlapData = get_overlap_ratio(segmentKey.span_ls, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t[oneGeneData.gene_start, oneGeneData.gene_stop])\n\t\t\t\t\toverlapFraction1 = overlapData.overlapFraction1\n\t\t\t\t\toverlapFraction2 = overlapData.overlapFraction2\n\t\t\t\t\toverlap_length = overlapData.overlap_length\n\t\t\t\t\toverlap_start_pos = overlapData.overlap_start_pos\n\t\t\t\t\toverlap_stop_pos = overlapData.overlap_stop_pos \n\t\t\t\t\tif overlap_length>0:\t#use fraction of length as coordinates.\n\t\t\t\t\t\tgene_length = oneGeneData.gene_stop - oneGeneData.gene_start + 1\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tif oneGeneData.strand == '+1':\n\t\t\t\t\t\t\t\tterm5_disp_pos = abs(overlap_start_pos - oneGeneData.gene_start)/float(gene_length)\n\t\t\t\t\t\t\t\tterm3_disp_pos = abs(overlap_stop_pos - oneGeneData.gene_start + 1)/float(gene_length)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tterm5_disp_pos = abs(oneGeneData.gene_stop - overlap_stop_pos)/float(gene_length)\n\t\t\t\t\t\t\t\tterm3_disp_pos = abs(oneGeneData.gene_stop - overlap_start_pos + 1)/float(gene_length)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\timport pdb\n\t\t\t\t\t\t\tpdb.set_trace()\n\t\t\t\t\telse:\t#no overlap at the gene itself, but within the neighborhood (<=max_distance)\n\t\t\t\t\t\tterm3_disp_pos = None\n\t\t\t\t\t\tif oneGeneData.strand == '+1':\n\t\t\t\t\t\t\tif row.stop<=oneGeneData.gene_start:\t#upstream\n\t\t\t\t\t\t\t\tterm5_disp_pos = row.stop - oneGeneData.gene_start\n\t\t\t\t\t\t\telif row.start>=oneGeneData.gene_stop:\t# downstream\n\t\t\t\t\t\t\t\tterm5_disp_pos = row.start - oneGeneData.gene_stop\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif row.stop<=oneGeneData.gene_start:\t#downstream\n\t\t\t\t\t\t\t\tterm5_disp_pos = oneGeneData.gene_start - row.stop\n\t\t\t\t\t\t\telif row.start>=oneGeneData.gene_stop:\t# upstream\n\t\t\t\t\t\t\t\tterm5_disp_pos = oneGeneData.gene_stop - row.start\n\t\t\t\t\tlocus_context = db_vervet.getLocusContext(locus_id=row.id, gene_id=oneGeneData.gene_id, \\\n\t\t\t\t\t\t\t\t\t\t\tgene_strand=oneGeneData.strand, disp_pos=term5_disp_pos, \\\n\t\t\t\t\t\t\t\t\t\t\toverlap_length=overlap_length,\\\n\t\t\t\t\t\t\t\t\t\t\toverlap_fraction_in_locus=overlapFraction1, overlap_fraction_in_gene=overlapFraction2)\n\t\t\t\t\tif locus_context.id:\n\t\t\t\t\t\tparam_obj.no_of_locus_contexts_already_in_db += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tparam_obj.no_of_into_db += 1\n\t\t\t\t\tparam_obj.no_of_total_contexts += 1\n\t\t\t\t\t\n\t\t\t\t\tfor geneCommentaryRBDict in oneGeneData.geneCommentaryRBDictLs:\n\t\t\t\t\t\tgene_box_node_ls = []\n\t\t\t\t\t\tgeneCommentaryRBDict.findNodes(segmentKey, node_ls=gene_box_node_ls, compareIns=compareIns)\n\t\t\t\t\t\tfor geneSegmentNode in gene_box_node_ls:\n\t\t\t\t\t\t\tgeneSegmentKey = geneSegmentNode.key\n\t\t\t\t\t\t\tif row.stop!=row.start: \t#2012.5.14 structural variation, not single-base locus \n\t\t\t\t\t\t\t\toverlapData = get_overlap_ratio(segmentKey.span_ls, geneSegmentKey.span_ls)\n\t\t\t\t\t\t\t\toverlapFraction1 = overlapData.overlapFraction1\n\t\t\t\t\t\t\t\toverlapFraction2 = overlapData.overlapFraction2\n\t\t\t\t\t\t\t\toverlap_length = overlapData.overlap_length\n\t\t\t\t\t\t\t\toverlap_start_pos = overlapData.overlap_start_pos\n\t\t\t\t\t\t\t\toverlap_stop_pos = overlapData.overlap_stop_pos\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tlocus_annotation = db_vervet.getLocusAnnotation(locus_id=row.id, locus_context_id=locus_context.id, locus_context=locus_context, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tgene_id=oneGeneData.gene_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tgene_commentary_id=geneCommentaryRBDict.gene_commentary_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tgene_segment_id=geneSegmentKey.gene_segment_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlocus_annotation_type =None, locus_annotation_type_id=None,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twhich_exon_or_intron = None, pos_within_codon=None, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlabel=geneSegmentKey.label, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tutr_number=geneSegmentKey.utr_number, cds_number=geneSegmentKey.cds_number, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintron_number=geneSegmentKey.intron_number,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\texon_number=geneSegmentKey.exon_number, overlap_length=overlap_length, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\toverlap_fraction_in_locus=overlapFraction1, overlap_fraction_in_gene=overlapFraction2,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcomment=None)\n\t\t\t\t\t\t\t\tif locus_annotation:\n\t\t\t\t\t\t\t\t\tparam_obj.no_of_locus_annotations_already_in_db += 1\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tparam_obj.no_of_into_db += 1\n\t\t\t\t\t\t\t\tparam_obj.no_of_total_annotations += 1\n\t\t\t\t\t\t\telse:\t#single-nucleotide \n\t\t\t\t\t\t\t\tself._constructSNPAnnotation(db_vervet, locus=row, locus_context=locus_context, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\toneGeneData=oneGeneData, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tgeneCommentaryRBDict=geneCommentaryRBDict, geneSegmentKey=geneSegmentKey,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\tlocus_annotation_short_name2db_entry=locus_annotation_short_name2db_entry, param_obj=param_obj)\n\t\t\t\t\t\t\t\n\t\t\t\t\tif param_obj.no_of_into_db>2000:\n\t\t\t\t\t\tsession.flush()\n\t\t\t\t\t\tparam_obj.no_of_into_db = 0\n\t\t\t\t\t\tsys.stderr.write(\"\\t %s/%s LocusContext(s) & %s/%s LocusAnnotation(s) already in db.\\n\"%(\\\n\t\t\t\t\t\t\t\t\tparam_obj.no_of_locus_contexts_already_in_db, param_obj.no_of_total_contexts, \\\n\t\t\t\t\t\t\t\t\tparam_obj.no_of_locus_annotations_already_in_db, param_obj.no_of_total_annotations))\n\t\tsession.flush()\n\t\tsession.expunge_all()\n\t\tsys.stderr.write(\"\\t %s/%s LocusContext(s) & %s/%s LocusAnnotation(s) already in db.\\n\"%(\\\n\t\t\t\t\t\t\t\tparam_obj.no_of_locus_contexts_already_in_db, param_obj.no_of_total_contexts, \\\n\t\t\t\t\t\t\t\tparam_obj.no_of_locus_annotations_already_in_db, param_obj.no_of_total_annotations))\n\t\n\t\t\n\tdef connectDB(self):\n\t\t\"\"\"\n\t\t2012.5.14\n\t\t2012.4.29\n\t\t\tsplit out of __init__() so that derived classes could overwrite this function\n\t\t\"\"\"\n\t\tAbstractVervetMapper.connectDB(self)\n\t\t\n\t\tdb_genome = GenomeDB.GenomeDatabase(drivername=self.drivername, db_user=self.db_user,\n\t\t\t\t\t\tdb_passwd=self.db_passwd, hostname=self.hostname, dbname=self.dbname, \\\n\t\t\t\t\t\tschema=self.genome_db_schema, port=self.port)\n\t\tdb_genome.setup(create_tables=False)\t#do the setup() after both db have been instantiated.\n\t\tself.db_genome = db_genome\n\t\n\tdef run(self):\n\t\t\"\"\"\n\t\t2012.5.14\n\t\t\t\n\t\t\"\"\"\n\t\tif self.debug:\n\t\t\timport pdb\n\t\t\tpdb.set_trace()\n\t\t\t\n\t\t\n\t\t#self.db_genome.session.begin()\n\t\t#self.db_genome.metadata.bind.execute('set search_path to %s'%(self.genome_db_schema))\n\t\t\n\t\tgenomeRBDict = self.db_genome.dealWithGenomeRBDict(self.genomeRBDictPickleFname, tax_id=self.tax_id, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tmax_distance=self.max_distance, debug=self.debug)\n\t\t\n\t\tself.db_vervet.session.begin()\n\t\tparam_obj = PassingData(no_of_total_annotations=0, session=self.db_vervet.session, \\\n\t\t\t\t\tlocus_type_id=self.locus_type_id, no_of_total_contexts=0, no_of_into_db=0, report=self.report,\\\n\t\t\t\t\tno_of_locus_contexts_already_in_db=0, no_of_locus_annotations_already_in_db=0)\n\t\tcompareIns = CNVCompare(min_reciprocal_overlap=0.0000001)\t#any overlap is an overlap\n\t\t\n\t\tlocus_annotation_short_name2db_entry = self.getLocusAnnotationShortName2dbEntry(self.db_vervet)\n\t\t\n\t\tself.findLocusContext(self.db_vervet, genomeRBDict, locus_type_id=self.locus_type_id, compareIns=compareIns, \\\n\t\t\t\t\tmax_distance=self.max_distance, debug=self.debug, param_obj=param_obj, \\\n\t\t\t\t\tlocus_annotation_short_name2db_entry=locus_annotation_short_name2db_entry)\n\t\tif self.commit:\n\t\t\tself.db_vervet.session.flush()\n\t\t\tself.db_vervet.session.commit()\n\t\telse:\n\t\t\tself.db_vervet.session.rollback()\n\t\t\nif __name__ == '__main__':\n\tfrom pymodule import ProcessOptions\n\tmain_class = FindLocusContext\n\tpo = ProcessOptions(sys.argv, main_class.option_default_dict, error_doc=main_class.__doc__)\n\t\n\tinstance = main_class(**po.long_option2value)\n\tinstance.run()\n","sub_path":"src/db/FindLocusContext.py","file_name":"FindLocusContext.py","file_ext":"py","file_size_in_byte":21900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"317943959","text":"name = input('Как Вас зовут?:')\nage = int(input('Введите сколько Вам лет:'))\nweight = int(input('Введите сколько киллогр��м составляет Ваша масса тела:'))\nif age <= 30 and 50 < weight < 120:\n print(name, age,'год', 'вес', weight,'-хорошее состояние')\nelif 40 > age >= 30 and (weight > 120 or weight < 50):\n print('требудется заняться собой')\nelif age >= 40 and (weight > 120 or weight < 50):\n print(name, age,'год', 'вес', weight,'-требуется врачебный осмотр')\nelse:\n print(name, age,'год', 'вес', weight,'Поздравляю, Вы абсолютно здоровы')","sub_path":"pythonProject2/2.3.py","file_name":"2.3.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"31030724","text":"# Code inspired by the github : https://github.com/nitarshan/bayes-by-backprop/blob/master/Weight%20Uncertainty%20in%20Neural%20Networks.ipynb\n\nimport math\nimport numpy as np\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.autograd as autograd \n\n# Params to set the priors in the Bayesian Linear\nSIGMA = torch.FloatTensor([0.2])\nVariable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs)\n\n\nclass Gaussian(object):\n def __init__(self, mu, rho, device):\n super().__init__()\n self.mu = mu\n self.rho = rho\n self.device = device\n self.normal = torch.distributions.Normal(0,1)\n # self.sigma = torch.FloatTensor([0.01])\n \n @property\n def sigma(self):\n return torch.log1p(torch.exp(self.rho))\n \n def sample(self):\n epsilon = self.normal.sample(self.rho.size()).to(self.device)\n return self.mu + self.sigma * epsilon\n \n def log_prob(self, input):\n return (-math.log(math.sqrt(2 * math.pi))\n - torch.log(self.sigma)\n - ((input - self.mu) ** 2) / (2 * self.sigma ** 2)).sum()\n\nclass ScaleMixtureGaussian(object):\n def __init__(self, sigma):\n super().__init__()\n self.sigma = sigma\n self.gaussian = torch.distributions.Normal(0,sigma)\n \n def log_prob(self, input):\n prob = torch.exp(self.gaussian.log_prob(input))\n return torch.log(prob).sum()\n\nclass BayesianLinear(nn.Module):\n def __init__(self, in_features, out_features, device, sigma):\n super().__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.device = device\n # Weight parameters\n self.weight_mu = nn.Parameter(torch.Tensor(out_features, in_features).uniform_(-0.1, 0.1))\n self.weight_rho = nn.Parameter(torch.Tensor(out_features, in_features).uniform_(-3 + np.log10(2), -2 + np.log10(2)))\n self.weight = Gaussian(self.weight_mu, self.weight_rho, self.device)\n # Bias parameters\n self.bias_mu = nn.Parameter(torch.Tensor(out_features).uniform_(-0.1, 0.1))\n self.bias_rho = nn.Parameter(torch.Tensor(out_features).uniform_(-3 + np.log10(2), -2 + np.log10(2)))\n self.bias = Gaussian(self.bias_mu, self.bias_rho, self.device)\n # Prior distributions\n self.weight_prior = ScaleMixtureGaussian(sigma)\n self.bias_prior = ScaleMixtureGaussian(sigma)\n self.log_prior = 0\n self.log_variational_posterior = 0\n\n def forward(self, input, sample=False, calculate_log_probs=False):\n if self.training or sample:\n weight = self.weight.sample()\n bias = self.bias.sample()\n else:\n weight = self.weight.mu\n bias = self.bias.mu\n if self.training or calculate_log_probs:\n self.log_prior = self.weight_prior.log_prob(weight) + self.bias_prior.log_prob(bias)\n self.log_variational_posterior = self.weight.log_prob(weight) + self.bias.log_prob(bias)\n else:\n self.log_prior, self.log_variational_posterior = 0, 0\n\n return F.linear(input, weight, bias)\n\n\nclass BayesianNetwork(nn.Module):\n def __init__(self, n_features, device, sigma=0.1, l2_reg=1):\n super().__init__()\n self.n_features = n_features\n self.device = device\n self.l1 = BayesianLinear(self.n_features, 100, self.device, sigma)\n self.l2 = BayesianLinear(100, 100, self.device, sigma)\n self.l3 = BayesianLinear(100, 2, self.device, sigma)\n self.l2_reg = l2_reg\n self.sigma = sigma\n\n def forward(self, x, sample=False):\n x = x.view(-1, self.n_features)\n x = F.relu(self.l1(x, sample))\n x = F.relu(self.l2(x, sample))\n x = self.l3(x, sample)\n return x\n \n def log_prior(self):\n return self.l1.log_prior \\\n + self.l2.log_prior \\\n + self.l3.log_prior\n \n def log_variational_posterior(self):\n return self.l1.log_variational_posterior \\\n + self.l2.log_variational_posterior \\\n + self.l3.log_variational_posterior\n \n def sample_elbo(self, X, action, reward, n_samples, batch_size, samples):\n action = action.unsqueeze(1)\n outputs = torch.zeros(samples, batch_size).to(self.device)\n log_priors = torch.zeros(samples).to(self.device)\n log_variational_posteriors = torch.zeros(samples).to(self.device)\n for i in range(samples):\n output = self(X, sample=True)\n outputs[i] = output.gather(1, action).squeeze(1)\n log_priors[i] = self.log_prior()\n log_variational_posteriors[i] = self.log_variational_posterior()\n log_prior = log_priors.mean()\n log_variational_posterior = log_variational_posteriors.mean()\n negative_log_likelihood = F.mse_loss(outputs.mean(0), reward, reduction='sum')\n loss = self.l2_reg * (log_variational_posterior - log_prior) / n_samples + negative_log_likelihood\n return loss, log_prior, log_variational_posterior, negative_log_likelihood\n\ndef act(net, X, samples):\n outputs = [net(X.float(), sample=True) for i in range(samples * 10)]\n outputs = torch.stack(outputs).squeeze().detach()\n mean = outputs.mean(0)\n uncertainty = outputs.std(0)\n Q = [np.random.normal(loc=mean[k].item(), scale=i.abs().item()) for k,i in enumerate(uncertainty)]\n Q = torch.tensor(Q)\n _, a_star = torch.max(Q, 0)\n return a_star.item(), uncertainty.detach()\n\n\ndef train_step(net, optimizer, X, action, reward, n_samples, samples):\n net.train()\n \n net.zero_grad()\n loss, log_prior, log_variational_posterior, negative_log_likelihood = net.sample_elbo(X,\n action,\n reward,\n n_samples= n_samples,\n batch_size = X.size(0),\n samples=samples)\n loss.backward()\n optimizer.step()\n\n return loss, log_prior, log_variational_posterior, negative_log_likelihood\n\n\ndef compute_loss(net, optimizer, replay_buffer, n_samples, samples, batch_size, verbose=False):\n for i in range(100):\n if len(replay_buffer.buffer) < batch_size:\n X, action, reward = replay_buffer.sample_all()\n\n else:\n X, action, reward = replay_buffer.sample_batch(batch_size)\n\n\n X = Variable(torch.FloatTensor(np.float32(X)))\n action = Variable(torch.LongTensor(action))\n reward = torch.FloatTensor(reward)\n\n loss, log_prior, log_variational_posterior, negative_log_likelihood = train_step(net, optimizer, X, action, reward, n_samples, samples)\n if verbose:\n print(\"Loss: {}\".format(loss))","sub_path":"Archive/main/Bandits/functions/bayes_by_backprop_functions.py","file_name":"bayes_by_backprop_functions.py","file_ext":"py","file_size_in_byte":7122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"563880114","text":"from django.conf.urls import patterns, url\nfrom django.conf import settings\n\nfrom pico import views\n\nurlpatterns = [\n url(r'^$', views.Index.as_view()),\n url(r'^(?P[\\w-]+)/$', views.EntryView.as_view()),\n]\n\nurlpatterns += [\n url(r'^media/(?P.*)$', 'django.views.static.serve', {\n 'document_root': settings.MEDIA_ROOT}),\n]\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"184670112","text":"import math\nimport ConfigParser\n\nfrom Layers import Layer\nfrom Nodes import Node, CopyNode, BiasNode, Connection\nfrom Nodes import NODE_OUTPUT, NODE_HIDDEN, NODE_INPUT, NODE_COPY\nfrom Nodes import NODE_BIAS\nfrom collections import deque \n\nclass NeuralNet(object):\n \"\"\"\n This class implements a standard multi-layered perceptron (MLP).\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Because there are a number of parameters to specify, there are\n no specific variables that are initialized within __init__.\n \"\"\"\n\n self._learnrate = None\n self._random_constraint = 1.0\n self._epochs =None\n self._init_copy_input=[]\n self._init_copy_target=[]\n self._output_order=[]\n self._input_order=[]\n self.accum_mse_valid=[]\n self.layers = []\n self._data_range = {'learning': [None, None],\n 'validation': [None, None],\n 'test': [None, None]}\n\n self._allinputs = []\n self._alltargets = []\n \n # This is where the test results are stored.\n self._allresults = []\n # This holds the mean squared error for the test.\n self.mse = []\n\n # This holds the accumulated mean squared errors for each epoch\n # tested\n self.accum_mse = []\n self.validation_targets_activations = []\n self.test_targets_activations = []\n\n self._halt_on_extremes = False\n\n self.input_layer = None\n self.output_layer = None\n \n\n def init_layers(self, input_nodes, total_hidden_nodes_list,\n output_nodes, recurrent_mod):\n \"\"\"\n This function initializes the layers.\n The variables:\n\n * input_nodes: the number of nodes in the input layer\n * total_hidden_nodes_list: a list of numbers of nodes in the\n hidden layer. For example, [5, 3]\n * output_nodes: the number of nodes in the output layer\n\n The initial network is created, and then a series of modifications can\n be made to enable recurrent features. recurrent_mods are\n configurations for modifications to the neural network that is created\n within init_layers.\n\n \"\"\"\n\n self.layers = []\n\n # Input layer\n layer = Layer(len(self.layers), NODE_INPUT)\n layer.add_nodes(input_nodes, NODE_INPUT)\n for item in range(input_nodes):\n self._init_copy_input.append(deque())\n layer.add_node(BiasNode())\n\n self.layers.append(layer)\n self.input_layer = layer\n \n # hidden layers \n for hid in total_hidden_nodes_list:\n layer = Layer(len(self.layers), NODE_HIDDEN)\n layer.add_nodes(hid, NODE_HIDDEN)\n\n layer.add_node(BiasNode())\n\n self.layers.append(layer)\n \n #Output layer\n layer = Layer(len(self.layers), NODE_OUTPUT)\n layer.add_nodes(output_nodes, NODE_OUTPUT)\n for item in range(output_nodes):\n self._init_copy_target.append(deque())\n \n \n \n self.layers.append(layer)\n self.output_layer = layer\n \n self._init_connections()\n recurrent_mod.apply_config(self)\n self._output_order=recurrent_mod.output_values[0]\n self._input_order=recurrent_mod.input_values[0]\n\n \n def set_halt_on_extremes(self, halt):\n \"\"\"\n This function sets the flag as to whether the program should halt when\n experiencing extremely positive or negative numbers. This can happen\n when using linear functions and data that may not be normalized. Such\n things as nan and inf can be experienced otherwise. Not halting\n instead, simply scales back the values to LARGEVALUE_LIMIT and\n NEGVALUE_LIMIT. A satisfactory output from the network may be in doubt,\n but at least it gives it the possibility.\n\n \"\"\"\n\n err_msg = \"Halt: %s -- Must be True or False\" % (halt)\n if not isinstance(halt, bool):\n raise ValueError(err_msg)\n else:\n self._halt_on_extremes = halt\n\n def get_halt_on_extremes(self):\n \"\"\"\n This function returns the True/False flag for halting on extremes.\n\n \"\"\"\n\n return self._halt_on_extremes\n\n def set_random_constraint(self, constraint):\n \"\"\"\n This fuction sets a value between 0 and 1 for limiting the random\n weights upon initialization. For example, .8 would limit weights to\n -.8 through .8.\n\n \"\"\"\n\n err_msg = \"\"\"The constraint, %s, must be a float between 0.0 and 1.0\n \"\"\" % (constraint)\n if not isinstance(constraint, float):\n raise ValueError(err_msg)\n elif 0.0 < constraint <= 1.0:\n self._random_constraint = constraint\n else:\n raise ValueError(err_msg)\n\n def get_random_constraint(self):\n \"\"\"\n This function gets the random constraint used in weights\n initialization.s\n\n \"\"\"\n\n return self._random_constraint\n\n def set_epochs(self, epochs):\n \"\"\"\n This function sets the number of epochs or cycles through the learning\n data.\n\n \"\"\"\n err_msg = \"\"\"The epochs, %s, must be an int \"\"\" % (epochs)\n if not isinstance(epochs, int):\n raise ValueError(err_msg)\n elif epochs <= 0:\n raise ValueError(err_msg)\n else:\n self._epochs = epochs\n\n def get_epochs(self):\n \"\"\"\n This function gets the number of epochs that will run during learning.\n\n \"\"\"\n\n return self._epochs\n\n \n\n def set_all_inputs(self, allinputs):\n \"\"\"\n This function sets the inputs. Inputs are basically treated as a\n list.\n\n \"\"\"\n\n self._allinputs = allinputs\n\n def set_all_targets(self, alltargets):\n \"\"\"\n This function sets the targets.\n\n \"\"\"\n self._alltargets = alltargets\n\n def set_learnrate(self, learnrate):\n \"\"\"\n This function sets the learn rate for the modeling. It is used to\n determine how much weight to associate with an error when learning.\n\n \"\"\"\n\n err_msg = \"\"\"The learnrate, %s, must be a float between 0.0 and 1.0\n \"\"\" % (learnrate)\n \n if not isinstance(learnrate, float):\n raise ValueError(err_msg)\n elif 0.0 < learnrate <= 1.0:\n self._learnrate = learnrate\n else:\n raise ValueError(err_msg)\n\n def get_learnrate(self):\n \"\"\"\n This function gets the learn rate for the modeling. It is used to\n determine how much weight to associate with an error when learning.\n\n \"\"\"\n\n return self._learnrate\n\n def _set_data_range(self, data_type, start_position, end_position):\n \"\"\"\n This function sets the data positions by type\n\n \"\"\"\n\n err_msg = \"The %s, %s, must be an int value\"\n if not isinstance(start_position, int):\n raise ValueError(err_msg % ('start_position', start_position))\n\n if not isinstance(end_position, int):\n raise ValueError(err_msg % ('end_position', end_position))\n \n self._data_range[data_type] = (start_position, end_position)\n if data_type=='test':\n print(self._data_range[data_type])\n def set_learn_range(self, start_position, end_position):\n \"\"\"\n This function sets the range within the data that is to used for\n learning.\n\n \"\"\"\n\n self._set_data_range('learning', start_position, end_position)\n\n def get_learn_range(self):\n \"\"\"\n This function gets the range within the data that is to used for\n learning.\n\n \"\"\"\n return self._data_range['learning']\n\n \n def get_learn_data(self):\n \"\"\" \n This function is a generator for learning data. It is assumed that in\n many cases, this function will be over-written with a situation\n specific function.\n\n \"\"\"\n\n start_position, end_position = self._data_range['learning']\n self._check_positions(start_position, end_position)\n for inputs, targets in self._get_data(start_position,end_position):\n yield (inputs, targets)\n\n def get_validation_data(self):\n \n \"\"\"\n This function is a generator for validation data. It is assumed that\n in many cases, this function will be over-written with a situation\n specific function.\n \"\"\"\n start_position, end_position = self._data_range['validation']\n self._check_positions(start_position, end_position)\n\n for inputs, targets in self._get_data(start_position,\n end_position):\n yield (inputs, targets)\n\n def get_test_data(self):\n \"\"\"\n This function is a generator for testing data. It is assumed that in\n many cases, this function will be over-written with a situation\n specific function.\n\n \"\"\"\n\n start_position, end_position = self._data_range['test']\n self._check_positions(start_position, end_position)\n\n for inputs, targets in self._get_data(start_position,\n end_position):\n yield (inputs, targets)\n\n def _get_data(self, start_position, end_position):\n \"\"\"\n This function gets an input from the list of all inputs.\n\n \"\"\"\n\n i = start_position\n if end_position > len(self._allinputs) - 1:\n raise ValueError(\n \"end_position %s is past end of ._allinputs, %s\" % (\n end_position, len(self._allinputs)))\n while i < end_position:\n inputs = self._allinputs[i]\n targets = self._alltargets[i]\n yield (inputs, targets)\n i += 1\n\n\n def _check_positions(self, start_position, end_position):\n \"\"\"\n This function evaluates validates, somewhat, start and end positions\n for data ranges.\n\n \"\"\"\n\n if start_position is None:\n raise ValueError(\n \"Start position is not defined.\")\n if end_position is None:\n raise ValueError(\n \"End position data is not defined.\")\n if start_position > end_position:\n raise ValueError(\"\"\"\n Start position, %s, cannot be greater than\n end position %s\"\"\" % (start_position, end_position))\n\n\n def set_validation_range(self, start_position, end_position):\n \"\"\"\n This function sets the start position and ending position for the\n validation range. The first test period is often used to test the\n current weights against data that is not within the learning period\n after each epoch run.\n\n \"\"\"\n self._set_data_range('validation', start_position, end_position)\n\n def get_validation_range(self):\n \"\"\"\n This function gets the start position and ending position for the\n validation range. The first test period is often used to test the\n current weights against data that is not within the learning period\n after each epoch run.\n\n \"\"\"\n\n return self._data_range['validation']\n\n def set_test_range(self, start_position, end_position):\n \"\"\"\n This function sets the start position and ending position for\n the out-of-sample range.\n\n \"\"\"\n\n self._set_data_range('test', start_position, end_position)\n\n def get_test_range(self):\n \"\"\"\n This function gets the start position and ending position for\n the out-of-sample range.\n\n \"\"\"\n\n return self._data_range['test']\n\n def _init_connections(self):\n \"\"\"\n Init connections sets up the linkages between layers.\n\n This function connects all nodes, which is typically desirable\n However, note that by substituting in a different process, a\n sparse network can be achieved. And, there is no restriction\n to connecting layers in a non-traditional fashion such as skip-layer\n connections.\n\n \"\"\"\n \n for layer in self.layers[1:]:\n self._connect_layer(layer)\n\n def _connect_layer(self, layer):\n \"\"\"\n Generates connections to the lower layer.\n\n If it is the input layer, then it's skipped\n It could raise an error, but it seems pointless.\n\n \"\"\"\n lower_layer_no = layer.layer_no - 1\n if lower_layer_no >= 0:\n lower_layer = self.layers[lower_layer_no]\n layer.connect_layer(lower_layer)\n\n def randomize_network(self):\n \"\"\"\n This function randomizes the weights in all of the connections.\n\n \"\"\"\n\n for layer in self.layers:\n if layer.layer_type != NODE_INPUT:\n layer.randomize(self._random_constraint)\n\n def learn_and_validate(self, epochs=None, show_epoch_results=True):\n \n if epochs is not None:\n self.set_epochs(epochs)\n\n self.accum_mse = []\n mse=0\n initial_mse_valid=self.validate()\n mse_valid=0\n epoch=0\n stop=False\n while(stop==False and epoch100):\n stop=True\n self.adjust_old_weight()\n \n if show_epoch_results:\n # Convert this over to logging\n print (\"epoch: %s MSE: %s MSE_validation: %s\" % (epoch, mse ,mse_valid))\n\n self.accum_mse.append(mse)\n self.accum_mse_valid.append(mse_valid)\n \n def learn(self, epochs=None):\n \n if epochs is not None:\n self.set_epochs(epochs)\n epoch=0 \n while(epoch 0:\n if count % show_sample_interval == 0:\n # Convert to logging at some point\n print(\"sample: %s errors: %s\",\n count, summed_errors)\n\n self.mse = self.calc_mse(summed_errors, count)\n return self.mse\n \n \n @staticmethod\n def calc_mse(total_summed_errors, count):\n \"\"\"\n This function calculates mean squared errors.\n \"\"\"\n\n mse = total_summed_errors / float(count) / 2.0\n\n if math.isnan(mse):\n raise ValueError(\"Mean squared error is Nan\")\n\n return mse\n \n\n def process_sample(self, inputs, targets,learn=False ):\n \"\"\"\n Accepts inputs and targets, then forward and back propagations. A\n comparison is then made of the generated output with the target values.\n\n Note that this is for an incremental learn, not the full set of inputs\n and examples.\n\n \"\"\"\n self.input_layer.load_inputs(inputs)\n\n if targets:\n # Must be either learn or testing mode\n self.output_layer.load_targets(targets)\n\n self._feed_forward()\n\n if targets and learn:\n \n self._back_propagate()\n elif targets:\n self._update_error(toponly=True)\n\n self._copy_levels()\n\n def _feed_forward(self):\n \"\"\"\n This function starts with the first hidden layer and\n gathers the values from the lower layer, applies the\n connection weightings to those values, and activates the\n nodes. Then, the next layer up is selected and the process\n is repeated; resulting in output values in the upper-most\n layer.\n\n \"\"\"\n\n for layer in self.layers[1:]:\n layer.feed_forward()\n\n def _back_propagate(self):\n \"\"\"\n Backpropagate the error through the network. Aside from the\n initial compution of error at the output layer, the process takes the\n top hidden layer, looks at the output connections reaching up to the\n next layer, and carries the results down through each layer back to the\n input layer.\n\n \"\"\"\n\n self._update_error(toponly=False)\n self._adjust_weights()\n\n def _update_error(self, toponly):\n \"\"\"\n This function goes through layers starting with the top hidden layer\n and working its way down to the input layer.\n\n At each layer, the errors are updated in the nodes from the errors and\n weights in connections to nodes in the upper layer.\n\n \"\"\"\n if toponly is False:\n self._zero_errors()\n\n if toponly:\n self.output_layer.update_error(self.get_halt_on_extremes())\n else:\n for layer_no in range(len(self.layers) - 1, -1, -1):\n self.layers[layer_no].update_error(self.get_halt_on_extremes())\n \n \n def _zero_errors(self):\n \"\"\"\n This function sets the node errors to zero in preparation for back\n propagation.\n\n \"\"\"\n\n for layer in self.layers:\n for node in layer.nodes:\n node.error = 0.0\n node.error_second=0.0\n \n def adjust_old_weight(self):\n \"\"\"\n This function goes through layers starting with the top hidden layer\n and working its way down to the input layer.\n\n At each layer, the weights are adjusted based upon old weights.\n \"\"\"\n for layer_no in range(len(self.layers) - 1, 0, -1):\n layer = self.layers[layer_no]\n layer.adjust_old_weights()\n \n \n def _adjust_weights(self):\n \"\"\"\n This function goes through layers starting with the top hidden layer\n and working its way down to the input layer.\n\n At each layer, the weights are adjusted based upon the errors.\n\n \"\"\"\n for layer_no in range(len(self.layers) - 1, 0, -1):\n layer = self.layers[layer_no]\n layer.adjust_weights(self._learnrate, self.get_halt_on_extremes())\n \n\n def calc_sample_error(self):\n \"\"\"\n The mean squared error (MSE) is a measure of how well the outputs\n compared to the target values.\n\n \"\"\"\n\n total = 0.0\n for node in self.output_layer.nodes:\n total += pow(node.error, 2.0)\n\n return total\n\n def _copy_levels(self):\n \"\"\"\n This function advances the copy node values, transferring the values\n from the source node to the copy node. In order to avoid stomping on\n the values that are to be copies, it goes from highest node number to\n lowest.\n\n No provision is made at this point to exhaustively check precedence.\n\n \"\"\"\n\n for layer in self.layers:\n for i in range(layer.total_nodes() - 1, -1, -1):\n node = layer.nodes[i]\n if isinstance(node, CopyNode):\n #print(node._copy_type,node._copy_order,node._copy_type)\n node.load_source_value()\n\n \n def _parse_inputfile_layer(self, config, layer_no):\n \"\"\"\n This function loads a layer and nodes from the input file. Note that\n it does not load the connections for those nodes here, waiting\n until all the nodes are fully instantiated. This is because\n the connection objects have nodes as part of the object.\n\n \"\"\"\n\n layer_id = 'layer %s' % (layer_no)\n layer_nodes = config.get(layer_id, 'nodes').split(\" \")\n layer_type = config.get(layer_id, 'layer_type')\n layer = Layer(layer_no, layer_type)\n\n for node_id in layer_nodes:\n node = self._parse_inputfile_node(config, node_id)\n layer.add_node(node)\n\n self.layers.append(layer)\n\n @staticmethod\n def _parse_inputfile_node(config, node_id):\n \"\"\"\n This function receives a node id, parses it, and returns the node in\n the network to which it pertains. It implies that the network\n structure must already be in place for it to be functional.\n\n \"\"\"\n\n activation_type = config.get(node_id, 'activation_type')\n\n node_type = config.get(node_id, 'node_type')\n\n if node_type == NODE_BIAS:\n node = BiasNode()\n elif node_type == NODE_COPY:\n node = CopyNode()\n node._incoming_weight = float(config.get(node_id,\n 'incoming_weight'))\n\n node.set_activation_type(activation_type)\n else:\n node = Node()\n node.set_activation_type(activation_type)\n\n node.node_type = node_type\n\n return node\n\n def _parse_inputfile_conn(self, conn_strs, node):\n \"\"\"\n This function instantiates a connection based upon the\n string loaded from the input file.\n Ex. node-1:0, 0.166366874487\n \"\"\"\n\n node_id, weight = conn_strs.split(',')\n weight = float(weight)\n layer_no, node_no = self._parse_node_id(node_id)\n lower_node = self.layers[layer_no].get_node(node_no)\n\n return Connection(lower_node, node, weight)\n\n def _parse_inputfile_copy(self, source_str):\n \"\"\"\n This function instantiates a source node.\n\n \"\"\"\n\n layer_no, node_no = self._parse_node_id(source_str)\n return self.layers[layer_no].get_node(node_no)\n\n @staticmethod\n def _parse_node_id(node_id):\n \"\"\"\n This function parses the node_id received from the input file.\n Format of node id: 'node-%s:%s' % (layer_no, node_no)\n\n Returns layer_no and node_no\n \"\"\"\n\n components = [i for i in node_id.split(\":\")]\n layer_no = int(components[0].split('-')[1])\n node_no = int(components[1])\n return (layer_no, node_no)\n\n def load(self, filename):\n \"\"\"\n This function loads a file that has been saved by save funtion. It is\n designed to be used when implementing a run-time version of the neural\n network.\n\n \"\"\"\n\n config = ConfigParser.ConfigParser()\n config.readfp(open(filename))\n\n hidden_neurons = config.get('net', 'hidden_neurons').split(\",\")\n \n hidden_neurons = [int(item) for item in hidden_neurons]\n\n # Load layer/nodes framework\n self.set_learnrate(float(config.get('net', 'learnrate')))\n self.set_epochs(int(config.get('net', 'epochs')))\n\n flag = config.get('net', 'halt_on_extremes').title()\n if flag == \"True\":\n self.set_halt_on_extremes(True)\n elif flag == \"False\":\n self.set_halt_on_extremes(False)\n else:\n raise ValueError(\"Invalid halt on extremes flag\")\n\n self.set_random_constraint(\n float(config.get('net', 'random_constraint')))\n total_layers = 1 + len(hidden_neurons) + 1\n for layer_no in range(total_layers):\n self._parse_inputfile_layer(config, layer_no)\n self.input_layer = self.layers[0]\n self.output_layer = self.layers[-1]\n\n # Attempt load of connections now that all nodes instantiated\n for layer_no in range(total_layers):\n layer = self.layers[layer_no]\n for node in layer.nodes:\n node_id = self._node_id(node)\n\n connections = config.get(node_id, 'connections').split('\\n')\n for conn_str in connections:\n if conn_str:\n conn = self._parse_inputfile_conn(conn_str, node)\n node.add_input_connection(conn)\n\n if isinstance(node, CopyNode):\n # load source node\n source_str = config.get(node_id, 'source_node')\n node.set_source_node(self._parse_inputfile_copy(\n source_str))\n node.set_copy_order(int(config.get(node_id, 'copy_order')))\n node.set_copy_type(config.get(node_id, 'copy_type'))\n node.set_copy_number(int(config.get(node_id, 'copy_number')))\n\n for layer_no in range(total_layers):\n layer = self.layers[layer_no]\n\n def output_values(self):\n \"\"\"\n This function outputs the values of the network. It is meant to be\n sufficiently complete that, once saved to a file, it could be loaded\n back from that file completely to function.\n\n To accommodate configparser, which is used as the file format, there is\n a form of [category],\n label = value\n\n Since there are also no sub-categories possible, so the naming\n structure is designed to take that into account. This accommodation\n also leads to a couple design choices: Each layer is given a separate\n category and a list of nodes follows. Then each node has a separate\n category identifying it by layer number and node number. This can't be\n inferred from just knowing the number of nodes in the layer and\n sequentially reading, because if a sparse network is used, then the\n node numbers may be out of sync with the position of the node within of\n the layer.\n \"\"\"\n\n output = ''\n # Overall parameters\n output += '[net]\\n'\n\n # Overall layer structure\n output += 'input_neurons = %s\\n' % (\n self.input_layer.total_nodes(NODE_INPUT))\n output += 'hidden_neurons = %s\\n' % (', '.join(\n [str(layer.total_nodes()) for layer in self.layers[1:-1]]))\n output += 'output_neurons = %s\\n' % (\n self.output_layer.total_nodes(NODE_OUTPUT))\n\n # Note: this line will change if backpropagation through time (BPTT)\n # is implemented\n if self.layers[1].total_nodes(NODE_HIDDEN) > 0:\n copy_levels = self.input_layer.total_nodes(NODE_COPY) / \\\n self.layers[1].total_nodes(NODE_HIDDEN)\n output += 'copy_levels = %s\\n' % (copy_levels)\n output += 'learnrate = %s\\n' % (self._learnrate)\n output += 'epochs = %s\\n' % (self._epochs)\n output += 'halt_on_extremes = %s\\n' % (self._halt_on_extremes)\n output += 'random_constraint = %s\\n' % (self._random_constraint)\n output += '\\n\\n'\n\n # Layers\n for layer in self.layers:\n output += '[layer %s]\\n' % (layer.layer_no)\n output += 'layer_type = %s\\n' % (layer.layer_type)\n # Nodes\n output += 'nodes = '\n for node in layer.nodes:\n output += 'node-%s:%s ' % (layer.layer_no, node.node_no)\n\n output = output[:-1] + '\\n'\n output += '\\n\\n'\n\n for node in layer.nodes:\n output += '[node-%s:%s]\\n' % (layer.layer_no, node.node_no)\n output += 'node_type = %s\\n' % (node.node_type)\n\n if isinstance(node, CopyNode):\n snode = node.get_source_node()\n output += 'source_node = %s\\n' % (self._node_id(snode))\n output += 'copy_type = %s\\n' %(node.get_copy_type())\n output += 'copy_number = %s\\n' % (node.get_copy_number())\n output += 'copy_order = %s\\n' % (node.get_copy_order())\n output += 'incoming_weight = %s\\n' % (\n node.get_incoming_weight())\n output += 'activation_type = %s\\n' % (\n node.get_activation_type())\n else:\n output += 'activation_type = %s\\n' % (\n node.get_activation_type())\n\n # Connections\n output += 'connections = \\n '\n for conn in node.input_connections:\n lower_node = conn.lower_node\n node_id = self._node_id(lower_node)\n output += '%s, %s\\n ' % (node_id, conn.get_weight())\n output += '\\n'\n output += '\\n'\n\n return output\n\n @staticmethod\n def _node_id(node):\n \"\"\"\n This function receives a node, and returns an text based id that\n uniquely identifies it within the network.\n \"\"\"\n return 'node-%s:%s' % (node.layer.layer_no, node.node_no)\n\n def save(self, filename):\n \"\"\"\n This function saves the network structure to a file.\n \"\"\"\n\n try:\n fobj = open(filename, \"w\")\n except:\n raise ValueError(\"Invalid filename\")\n\n fobj.write(self.output_values())\n fobj.close()\n","sub_path":"Neuralnet.py","file_name":"Neuralnet.py","file_ext":"py","file_size_in_byte":35240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558859185","text":"# Automatic Sebastian game player\n# B551 Fall 2020\n# Code by bgoginen-surgudla-tsadey\n#\n# Based on skeleton code by D. Crandall\n#\n#\n# This is the file you should modify to create your new smart player.\n# The main program calls this program three times for each turn.\n# 1. First it calls first_roll, passing in a Dice object which records the\n# result of the first roll (state of 5 dice) and current Scorecard.\n# You should implement this method so that it returns a (0-based) list\n# of dice indices that should be re-rolled.\n#\n# 2. It then re-rolls the specified dice, and calls second_roll, with\n# the new state of the dice and scorecard. This method should also return\n# a list of dice indices that should be re-rolled.\n#\n# 3. Finally it calls third_roll, with the final state of the dice.\n# This function should return the name of a scorecard category that\n# this roll should be recorded under. The names of the scorecard entries\n# are given in Scorecard.Categories.\n#\n\nfrom SebastianState import Scorecard\nimport random\n\n\nclass SebastianAutoPlayer:\n\n def __init__(self):\n self.cat_auto = []\n\n # Returns score for the die combinations for the category passed as a parameter\n def calculate_score(self, dice1, category):\n score = {}\n counts = [dice1.count(i) for i in range(1, 7)]\n if category in Scorecard.Numbers:\n score = counts[Scorecard.Numbers[category] - 1] * Scorecard.Numbers[category]\n elif category == \"company\":\n score = 40 if sorted(dice1) == [1, 2, 3, 4, 5] or sorted(dice1) == [2, 3, 4, 5, 6] else 0\n elif category == \"prattle\":\n score = 30 if (len({1, 2, 3, 4} - set(dice1)) == 0 or len({2, 3, 4, 5} - set(dice1)) == 0 or len(\n {3, 4, 5, 6} - set(dice1)) == 0) else 0\n elif category == \"squadron\":\n score = 25 if (2 in counts) and (3 in counts) else 0\n elif category == \"triplex\":\n score = sum(dice1) if max(counts) >= 3 else 0\n elif category == \"quadrupla\":\n score = sum(dice1) if max(counts) >= 4 else 0\n elif category == \"quintuplicatam\":\n score = 50 if max(counts) == 5 else 0\n elif category == \"pandemonium\":\n score = sum(dice1)\n return score\n\n # Returns indices to be rolled for first re-roll\n def first_roll(self, dice, scorecard):\n best_re_roll, category = self.max_layer(dice, scorecard)\n best_re_roll = list(best_re_roll)\n best_re_roll1 = []\n for i in range(0, len(best_re_roll)):\n if best_re_roll[i]:\n best_re_roll1.append(i)\n return best_re_roll1\n\n # Returns indices to be rolled for second re-roll\n def second_roll(self, dice, scorecard):\n best_re_roll, category = self.max_layer(dice, scorecard)\n best_re_roll = list(best_re_roll)\n best_re_roll1 = []\n for i in range(0, len(best_re_roll)):\n if best_re_roll[i]:\n best_re_roll1.append(i)\n return best_re_roll1\n\n # Assigns best category for the given die combination and returns it\n def third_roll(self, dice, scorecard):\n dice = list(str(dice))\n dice = [ele for ele in dice if ele != ' ']\n dice = [int(ele) for ele in dice]\n categories = {}\n # Checks for unassigned list of categories\n for category in list(set(Scorecard.Categories) - set(scorecard.scorecard.keys())):\n categories[category] = self.calculate_score(dice, category)\n cat = next(iter(sorted(categories, key=categories.get, reverse=True)))\n self.cat_auto.append(cat)\n return cat\n\n # Checks for best re-roll indices\n def max_layer(self, roll1, scorecard):\n max_so_far = (0, 0)\n # consider all possible combinations\n for roll_a in (True, False):\n for roll_b in (True, False):\n for roll_c in (True, False):\n for roll_d in (True, False):\n for roll_e in (True, False):\n exp_score, category = self.expectation_of_re_roll(roll1,\n (roll_a, roll_b, roll_c, roll_d, roll_e),\n scorecard)\n if exp_score > max_so_far[1]:\n max_so_far = (roll_a, roll_b, roll_c, roll_d, roll_e)\n return max_so_far, category\n\n # Calculates expectation for each die combination\n def expectation_of_re_roll(self, roll, re_roll, scorecard):\n roll1 = list(str(roll))\n roll2 = [ele for ele in roll1 if ele != ' ']\n roll2 = [int(ele) for ele in roll2]\n outcomes = []\n for out_a in ((roll2[0],) if not (re_roll[0]) else range(1, 7)):\n for out_b in ((roll2[1],) if not (re_roll[1]) else range(1, 7)):\n for out_c in ((roll2[2],) if not (re_roll[2]) else range(1, 7)):\n for out_d in ((roll2[3],) if not (re_roll[3]) else range(1, 7)):\n for out_e in ((roll2[4],) if not (re_roll[4]) else range(1, 7)):\n o = (out_a, out_b, out_c, out_d, out_e)\n outcomes.append(o)\n outcomes1 = []\n value = {}\n # removes duplicate outcomes by sorting the outcomes\n for o in outcomes:\n outcomes1.append(tuple(sorted(o)))\n outcomes2 = list(set(outcomes1))\n for category in list(set(Scorecard.Categories) - set(scorecard.scorecard.keys())):\n for o in outcomes2:\n value[category] = 0\n value[category] += self.calculate_score(o, category)\n value[category] /= len(outcomes2)\n exp = next(iter(sorted(value, key=value.get, reverse=True)))\n return value[exp], exp\n","sub_path":"Dice and Luck/SebastianAutoPlayer.py","file_name":"SebastianAutoPlayer.py","file_ext":"py","file_size_in_byte":5912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76741829","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index_page():\n \"\"\"Show an index page.\"\"\"\n\n return render_template(\"index.html\")\n\n\n@app.route(\"/application-form\")\ndef apply():\n \"\"\"Present a form for application.\"\"\"\n\n return render_template(\"application-form.html\")\n\n\n@app.route(\"/application\", methods=[\"POST\"])\ndef confirm_application():\n \"\"\"Process data from and display confirmation of application inputs.\"\"\"\n\n firstname = request.form.get(\"firstname\")\n lastname = request.form.get(\"lastname\")\n position = request.form.get(\"position\")\n salary = request.form.get(\"salary\")\n\n # Clean up text inputs in case the have whitespace, or salary has commas\n firstname = firstname.strip()\n lastname = lastname.strip()\n salary = salary.strip()\n while salary.find(',') >= 0:\n idx = salary.find(',')\n salary = salary[:idx] + salary[idx+1:]\n\n # Clean up salary number input, use float conversion in case decimals, but.\n # store as int becuase that level of precision is not needed\n salary = int(float(salary))\n\n return render_template(\"application-response.html\",\n firstname=firstname,\n lastname=lastname,\n position=position,\n salary=salary\n )\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"skills-flask/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"254570930","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom pprint import pprint as pp\nimport numpy as np\n\n\"\"\"\ndata dictionary:\n\nFILM - film name\nRT_user_norm - average user rating from Rotten Tomatoes, normalized to a 1 to 5 point scale\nMetacritic_user_nom - average user rating from Metacritc, normalized to a 1 to 5 point scale\nIMDB_norm - average user rating from IMDB, normalized to a 1 to 5 point scale\nFandango_Ratingvalue - average user rating from Fandango, normalized to a 1 to 5 point scale\nFandango_Stars - the rating displayed on the Fandango website (rounded to nearest star, 1 to 5 point scale)\n\"\"\"\n\n\n\nfn='fandango_scores.csv'\ndat=pd.read_csv(fn)\npp(dat.info())\npp(dat.head(3))\ncols = [\n'FILM',\n'RT_user_norm',\n'Metacritic_user_nom',\n'IMDB_norm',\n'Fandango_Ratingvalue',\n'Fandango_Stars']\n\nnorm_reviews = dat[cols]\n\npp(norm_reviews.head(3))\n\npp(norm_reviews.describe())\n\n#4\nnum_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']\nbar_heights = norm_reviews[num_cols].iloc[0].values\nbar_positions = np.arange(5) + 0.75\n\nfig, ax = plt.subplots()\nax.bar(bar_positions, bar_heights, 0.5)\nplt.show()\n\n\n#5\nnum_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']\nbar_heights = norm_reviews[num_cols].iloc[0].values\nbar_positions = np.arange(5) + 0.75\ntick_positions = range(1,6)\n\nfig, ax = plt.subplots()\n\nax.bar(bar_positions, bar_heights, 0.5)\n#settinng x-ticks\nax.set_xticks(tick_positions)\nax.set_xticklabels(num_cols, rotation=90)\n\n#setting labels\nax.set_xlabel('Rating Source')\nax.set_ylabel('Average Rating')\nax.set_title('Average User Rating For Avengers: Age of Ultron (2015)')\nplt.show()\n\n#6 vertial bar\n\nnum_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']\n\nbar_widths = norm_reviews[num_cols].iloc[0].values\nbar_positions = np.arange(5) + 0.75\ntick_positions = range(1,6)\n\nfig, ax = plt.subplots()\nax.barh(bar_positions, bar_widths, 0.5) #horizontal bar\n\n#now setting y-ticks\nax.set_yticks(tick_positions)\nax.set_yticklabels(num_cols)\n\nax.set_ylabel('Rating Source')\nax.set_xlabel('Average Rating')\nax.set_title('Average User Rating For Avengers: Age of Ultron (2015)')\nplt.show()\n\n#7 scatter plots\nfig, ax = plt.subplots()\nax.scatter( norm_reviews.Fandango_Ratingvalue.values,\n norm_reviews.RT_user_norm.values )\nax.set_xlabel('Fandango')\nax.set_ylabel('Rotten Tomatoes')\nplt.show()\n\n#8\nfig = plt.figure(figsize=(5,10))\nax1 = fig.add_subplot(2,1,1)\nax2 = fig.add_subplot(2,1,2)\nax1.scatter( norm_reviews.Fandango_Ratingvalue.values,\n norm_reviews.RT_user_norm.values )\n\nax2.scatter(norm_reviews.RT_user_norm.values,\n norm_reviews.Fandango_Ratingvalue.values)\n\nax1.set_xlabel('Fandango')\nax1.set_ylabel('Rotten Tomatoes')\n\nax2.set_xlabel('Rotten Tomatoes')\nax2.set_ylabel('Fandango')\nplt.show()\n\n##9\nfig = plt.figure(figsize=(5,10))\nax1 = fig.add_subplot(3,1,1)\nax2 = fig.add_subplot(3,1,2)\nax3 = fig.add_subplot(3,1,3)\nax1.scatter(norm_reviews['Fandango_Ratingvalue'], norm_reviews['RT_user_norm'])\nax1.set_xlabel('Fandango')\nax1.set_ylabel('Rotten Tomatoes')\nax1.set_xlim(2.5, 5) #hard setting limits\nax1.set_ylim(0, 5)\n\nax2.scatter(norm_reviews['Fandango_Ratingvalue'], norm_reviews['Metacritic_user_nom'])\nax2.set_xlabel('Fandango')\nax2.set_ylabel('Metacritic')\nax2.set_xlim(2.5, 5)\nax2.set_ylim(0, 5)\n\nax3.scatter(norm_reviews['Fandango_Ratingvalue'], norm_reviews['IMDB_norm'])\nax3.set_xlabel('Fandango')\nax3.set_ylabel('IMDB')\nax3.set_xlim(2.5, 5)\nax3.set_ylim(0, 5)\n\nplt.show()\n","sub_path":"dataquest/trds/s2/223_barscatter.py","file_name":"223_barscatter.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"431842215","text":"import sys\nimport platform\nfrom cyanodbc import Connection\nfrom typing import List, Optional, Callable\nfrom logging import getLogger\nfrom asyncio import get_event_loop\nfrom threading import Thread, Lock\nfrom prompt_toolkit.layout.containers import HSplit, Window, ScrollOffsets, ConditionalContainer, Container\nfrom prompt_toolkit.formatted_text.base import StyleAndTextTuples\nfrom prompt_toolkit.formatted_text import fragment_list_width\nfrom prompt_toolkit.layout.controls import FormattedTextControl, BufferControl, UIContent\nfrom prompt_toolkit.layout.dimension import Dimension\nfrom prompt_toolkit.buffer import Buffer\nfrom prompt_toolkit.document import Document\nfrom prompt_toolkit.filters import is_done, renderer_height_is_known\nfrom prompt_toolkit.layout.margins import ScrollbarMargin\nfrom prompt_toolkit.mouse_events import MouseEvent\nfrom prompt_toolkit.lexers import Lexer\nfrom prompt_toolkit.widgets import SearchToolbar\nfrom prompt_toolkit.filters import Condition\nfrom .conn import sqlConnection\nfrom .filters import ShowSidebar\nfrom .utils import if_mousedown\nfrom .__init__ import __version__\n\nclass myDBObject:\n def __init__(\n self,\n my_app: \"sqlApp\",\n conn: sqlConnection,\n name: str,\n otype: str,\n level: Optional[int] = 0,\n children: Optional[List[\"myDBObject\"]] = None,\n parent: Optional[\"myDBObject\"] = None,\n next_object: Optional[\"myDBObject\"] = None\n ) -> None:\n\n self.my_app = my_app\n self.conn = conn\n self.children = children\n self.parent = parent\n self.next_object = next_object\n # Held while modifying children, parent, next_object\n # As some of thes operatins (expand) happen asynchronously\n self._lock = Lock()\n self.name = name\n self.otype = otype\n self.level = level\n self.selected: bool = False\n\n def _expand_internal(self) -> None:\n \"\"\"\n Populates children and sets parent for children nodes\n \"\"\"\n raise NotImplementedError()\n\n def expand(self) -> None:\n \"\"\"\n Populates children and sets parent for children nodes\n \"\"\"\n if self.children is not None:\n return None\n\n loop = get_event_loop()\n self.my_app.show_expanding_object = True\n self.my_app.application.invalidate()\n def _redraw_after_io():\n \"\"\" Callback, scheduled after threaded I/O\n completes \"\"\"\n self.my_app.show_expanding_object = False\n self.my_app.obj_list_changed = True\n self.my_app.application.invalidate()\n\n def _run():\n \"\"\" Executes in a thread \"\"\"\n self._expand_internal() # Blocking I/O\n loop.call_soon_threadsafe(_redraw_after_io)\n\n # (Don't use 'run_in_executor', because daemon is ideal here.\n t = Thread(target = _run, daemon = True)\n t.start()\n\n def collapse(self) -> None:\n \"\"\"\n Populates children and sets parent for children nodes\n Note, we don't have to blow up the children; just redirect\n next_object. This way we re-query the database / force re-fresh\n which may be suboptimal. TODO: Codify not/refresh path\n \"\"\"\n if self is not self.my_app.selected_object:\n return\n if self.children is not None:\n obj = self.children[len(self.children) - 1].next_object\n while obj.level > self.level:\n obj = obj.next_object\n with self._lock:\n self.next_object = obj\n self.children = None\n elif self.parent is not None:\n self.my_app.selected_object = self.parent\n self.parent.collapse()\n\n self.my_app.obj_list_changed = True\n\n def add_children(self, list_obj: List[\"myDBObject\"]) -> None:\n lst = list(filter(lambda x: x.name != \"\", list_obj))\n if len(lst):\n with self._lock:\n self.children = lst\n for i in range(len(self.children) - 1):\n self.children[i].next_object = self.children[i + 1]\n self.children[len(self.children) - 1].next_object = self.next_object\n self.next_object = self.children[0]\n\nclass myDBColumn(myDBObject):\n def _expand_internal(self) -> None:\n return None\n\nclass myDBFunction(myDBObject):\n def _expand_internal(self) -> None:\n cat = \"%\"\n schema = \"%\"\n # https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlprocedurecolumns-function?view=sql-server-ver15\n # CatalogName cannot contain a string search pattern\n\n if self.parent is not None:\n if type(self.parent).__name__ == \"myDBSchema\":\n schema = self.conn.sanitize_search_string(self.parent.name)\n elif type(self.parent).__name__ == \"myDBCatalog\":\n cat = self.parent.name\n if self.parent.parent is not None:\n if type(self.parent.parent).__name__ == \"myDBCatalog\":\n cat = self.parent.parent.name\n\n res = self.conn.find_procedure_columns(\n catalog = cat,\n schema = schema,\n procedure = self.conn.sanitize_search_string(self.name),\n column = \"%\")\n\n lst = [myDBColumn(\n my_app = self.my_app,\n conn = self.conn,\n name = col.column,\n otype = col.type_name,\n parent = self,\n level = self.level + 1) for col in res]\n\n self.add_children(list_obj = lst)\n return None\n\nclass myDBTable(myDBObject):\n def _expand_internal(self) -> None:\n cat = \"%\"\n schema = \"%\"\n # https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlcolumns-function?view=sql-server-ver15\n # CatalogName cannot contain a string search pattern\n\n if self.parent is not None:\n if type(self.parent).__name__ == \"myDBSchema\":\n schema = self.conn.sanitize_search_string(self.parent.name)\n elif type(self.parent).__name__ == \"myDBCatalog\":\n cat = self.parent.name\n if self.parent.parent is not None:\n if type(self.parent.parent).__name__ == \"myDBCatalog\":\n cat = self.parent.parent.name\n\n res = self.conn.find_columns(\n catalog = cat,\n schema = schema,\n table = self.name,\n column = \"%\")\n\n lst = [myDBColumn(\n my_app = self.my_app,\n conn = self.conn,\n name = col.column,\n otype = col.type_name,\n parent = self,\n level = self.level + 1) for col in res]\n\n self.add_children(list_obj = lst)\n return None\n\nclass myDBSchema(myDBObject):\n def _expand_internal(self) -> None:\n\n cat = self.conn.sanitize_search_string(self.parent.name) if self.parent is not None else \"%\"\n res = self.conn.find_tables(\n catalog = cat,\n schema = self.conn.sanitize_search_string(self.name),\n table = \"\",\n type = \"\")\n resf = self.conn.find_procedures(\n catalog = cat,\n schema = self.conn.sanitize_search_string(self.name),\n procedure = \"\")\n tables = []\n views = []\n functions = []\n lst = []\n for table in res:\n if table.type.lower() == 'table':\n tables.append(table.name)\n if table.type.lower() == 'view':\n views.append(table.name)\n lst.append(myDBTable(\n my_app = self.my_app,\n conn = self.conn,\n name = table.name,\n otype = table.type.lower(),\n parent = self,\n level = self.level + 1))\n for func in resf:\n functions.append(func.name)\n lst.append(myDBFunction(\n my_app = self.my_app,\n conn = self.conn,\n name = func.name,\n otype = \"function\",\n parent = self,\n level = self.level + 1))\n\n self.conn.dbmetadata.extend_objects(\n catalog = self.conn.escape_name(self.parent.name) if self.parent else \"\",\n schema = self.conn.escape_name(self.name),\n names = self.conn.escape_names(tables),\n obj_type = \"table\")\n self.conn.dbmetadata.extend_objects(\n catalog = self.conn.escape_name(self.parent.name) if self.parent else \"\",\n schema = self.conn.escape_name(self.name),\n names = self.conn.escape_names(views),\n obj_type = \"view\")\n self.conn.dbmetadata.extend_objects(\n catalog = self.conn.escape_name(self.parent.name) if self.parent else \"\",\n schema = self.conn.escape_name(self.name),\n names = self.conn.escape_names(functions),\n obj_type = \"function\")\n self.add_children(list_obj = lst)\n return None\n\nclass myDBCatalog(myDBObject):\n def _expand_internal(self) -> None:\n schemas = lst = []\n schemas = self.conn.list_schemas(\n catalog = self.conn.sanitize_search_string(self.name))\n\n if len(schemas) < 1 or all([s == \"\" for s in schemas]):\n res = self.conn.find_tables(\n catalog = self.conn.sanitize_search_string(self.name),\n schema = \"\",\n table = \"\",\n type = \"\")\n schemas = [r.schema for r in res]\n\n self.conn.dbmetadata.extend_schemas(\n catalog = self.conn.escape_name(self.name),\n names = self.conn.escape_names(schemas))\n\n if not all([s == \"\" for s in schemas]):\n # Schemas were found either having called list_schemas\n # or via the find_tables call\n lst = [myDBSchema(\n my_app = self.my_app,\n conn = self.conn,\n name = schema,\n otype = \"schema\",\n parent = self,\n level = self.level + 1) for schema in sorted(set(schemas))]\n elif len(schemas):\n # No schemas found; but if there are tables then these are direct\n # descendents, i.e. MySQL\n tables = []\n views = []\n lst = []\n for table in res:\n if table.type.lower() == 'table':\n tables.append(table.name)\n if table.type.lower() == 'view':\n views.append(table.name)\n lst.append(myDBTable(\n my_app = self.my_app,\n conn = self.conn,\n name = table.name,\n otype = table.type.lower(),\n parent = self,\n level = self.level + 1))\n self.conn.dbmetadata.extend_objects(\n catalog = self.conn.escape_name(self.name),\n schema = \"\", names = self.conn.escape_names(tables),\n obj_type = \"table\")\n self.conn.dbmetadata.extend_objects(\n catalog = self.conn.escape_name(self.name),\n schema = \"\", names = self.conn.escape_names(views),\n obj_type = \"view\")\n\n self.add_children(list_obj = lst)\n return None\n\n\nclass myDBConn(myDBObject):\n def _expand_internal(self) -> None:\n if not self.conn.connected():\n return None\n\n lst = []\n cat_support = self.conn.catalog_support()\n if cat_support:\n rows = self.conn.list_catalogs()\n if len(rows):\n lst = [myDBCatalog(\n my_app = self.my_app,\n conn = self.conn,\n name = row,\n otype = \"catalog\",\n parent = self,\n level = self.level + 1) for row in rows]\n self.conn.dbmetadata.extend_catalogs(\n self.conn.escape_names(rows))\n else:\n res = self.conn.find_tables(\n catalog = \"%\",\n schema = \"\",\n table = \"\",\n type = \"\")\n schemas = [r.schema for r in res]\n self.conn.dbmetadata.extend_schemas(catalog = \"\",\n names = self.conn.escape_names(schemas))\n if not all([s == \"\" for s in schemas]):\n lst = [myDBSchema(\n my_app = self.my_app,\n conn = self.conn,\n name = schema,\n otype = \"schema\",\n parent = self,\n level = self.level + 1) for schema in sorted(set(schemas))]\n elif len(schemas):\n tables = []\n views = []\n lst = []\n for table in res:\n if table.type.lower() == 'table':\n tables.append(table.name)\n if table.type.lower() == 'view':\n views.append(table.name)\n lst.append(myDBTable(\n my_app = self.my_app,\n conn = self.conn,\n name = table.name,\n otype = table.type.lower(),\n parent = self,\n level = self.level + 1))\n self.conn.dbmetadata.extend_objects(catalog = \"\",\n schema = \"\", names = self.conn.escape_names(tables),\n obj_type = \"table\")\n self.conn.dbmetadata.extend_objects(catalog = \"\",\n schema = \"\", names = self.conn.escape_names(views),\n obj_type = \"view\")\n self.add_children(list_obj = lst)\n return None\n\ndef sql_sidebar_help(my_app: \"sqlApp\"):\n \"\"\"\n Create the `Layout` for the help text for the current item in the sidebar.\n \"\"\"\n token = \"class:sidebar.helptext\"\n\n def get_current_description():\n \"\"\"\n Return the description of the selected option.\n \"\"\"\n obj = my_app.selected_object\n if obj is not None:\n return obj.name\n return \"\"\n\n def get_help_text():\n return [(token, get_current_description())]\n\n return ConditionalContainer(\n content=Window(\n FormattedTextControl(get_help_text), style=token, height=Dimension(min=3)\n ),\n filter = ~is_done\n & ShowSidebar(my_app)\n & Condition(\n lambda: not my_app.show_exit_confirmation\n ))\n\ndef expanding_object_notification(my_app: \"sqlApp\"):\n \"\"\"\n Create the `Layout` for the 'Expanding object' notification.\n \"\"\"\n\n def get_text_fragments():\n # Show navigation info.\n return [(\"fg:red\", \"Expanding object ...\")]\n\n return ConditionalContainer(\n content = Window(\n FormattedTextControl(get_text_fragments),\n style = \"class:sidebar\",\n width=Dimension.exact( 45 ),\n height=Dimension(max = 1),\n ),\n filter = ~is_done\n & ShowSidebar(my_app)\n & Condition(\n lambda: my_app.show_expanding_object\n ))\n\ndef sql_sidebar_navigation():\n \"\"\"\n Create the `Layout` showing the navigation information for the sidebar.\n \"\"\"\n\n def get_text_fragments():\n # Show navigation info.\n return [\n (\"class:sidebar.navigation\", \" \"),\n (\"class:sidebar.navigation.key\", \"[Up/Dn]\"),\n (\"class:sidebar.navigation\", \" \"),\n (\"class:sidebar.navigation.description\", \"Navigate\"),\n (\"class:sidebar.navigation\", \" \"),\n (\"class:sidebar.navigation.key\", \"[L/R]\"),\n (\"class:sidebar.navigation\", \" \"),\n (\"class:sidebar.navigation.description\", \"Expand/Collapse\"),\n (\"class:sidebar.navigation\", \"\\n \"),\n (\"class:sidebar.navigation.key\", \"[Enter]\"),\n (\"class:sidebar.navigation\", \" \"),\n (\"class:sidebar.navigation.description\", \"Connect/Preview\"),\n ]\n\n return Window(\n FormattedTextControl(get_text_fragments),\n style = \"class:sidebar.navigation\",\n width=Dimension.exact( 45 ),\n height=Dimension(max = 2),\n )\n\ndef show_sidebar_button_info(my_app: \"sqlApp\") -> Container:\n \"\"\"\n Create `Layout` for the information in the right-bottom corner.\n (The right part of the status bar.)\n \"\"\"\n\n @if_mousedown\n def toggle_sidebar(mouse_event: MouseEvent) -> None:\n \" Click handler for the menu. \"\n my_app.show_sidebar = not my_app.show_sidebar\n\n # TO DO: app version rather than python\n version = sys.version_info\n tokens: StyleAndTextTuples = [\n (\"class:status-toolbar.key\", \"[C-t]\", toggle_sidebar),\n (\"class:status-toolbar\", \" Object Browser\", toggle_sidebar),\n (\"class:status-toolbar\", \" - \"),\n (\"class:status-toolbar.cli-version\", \"odbcli %s\" % __version__),\n (\"class:status-toolbar\", \" \"),\n ]\n width = fragment_list_width(tokens)\n\n def get_text_fragments() -> StyleAndTextTuples:\n # Python version\n return tokens\n\n return ConditionalContainer(\n content=Window(\n FormattedTextControl(get_text_fragments),\n style=\"class:status-toolbar\",\n height=Dimension.exact(1),\n width=Dimension.exact(width),\n ),\n filter=~is_done\n & Condition(\n lambda: not my_app.show_exit_confirmation\n )\n & renderer_height_is_known\n )\n\ndef sql_sidebar(my_app: \"sqlApp\") -> Window:\n \"\"\"\n Create the `Layout` for the sidebar with the configurable objects.\n \"\"\"\n\n @if_mousedown\n def expand_item(obj: \"myDBObject\") -> None:\n obj.expand()\n\n def tokenize_obj(obj: \"myDBObject\") -> StyleAndTextTuples:\n \" Recursively build the token list \"\n tokens: StyleAndTextTuples = []\n selected = obj is my_app.selected_object\n expanded = obj.children is not None\n connected = obj.otype == \"Connection\" and obj.conn.connected()\n active = my_app.active_conn is not None and my_app.active_conn is obj.conn and obj.level == 0\n\n act = \",active\" if active else \"\"\n sel = \",selected\" if selected else \"\"\n if len(obj.name) > 24 - 2 * obj.level:\n name_trim = obj.name[:24 - 2 * obj.level - 3] + \"...\"\n else:\n name_trim = (\"%-\" + str(24 - 2 * obj.level) + \"s\") % obj.name\n\n tokens.append((\"class:sidebar.label\" + sel + act, \" >\" if connected else \" \"))\n tokens.append(\n (\"class:sidebar.label\" + sel, \" \" * 2 * obj.level, expand_item)\n )\n tokens.append(\n (\"class:sidebar.label\" + sel + act,\n name_trim,\n expand_item)\n )\n tokens.append((\"class:sidebar.status\" + sel + act, \" \", expand_item))\n tokens.append((\"class:sidebar.status\" + sel + act, \"%+12s\" % obj.otype, expand_item))\n\n if selected:\n tokens.append((\"[SetCursorPosition]\", \"\"))\n\n if expanded:\n tokens.append((\"class:sidebar.status\" + sel + act, \"\\/\"))\n else:\n tokens.append((\"class:sidebar.status\" + sel + act, \" <\" if selected else \" \"))\n\n # Expand past the edge of the visible buffer to get an even panel\n tokens.append((\"class:sidebar.status\" + sel + act, \" \" * 10))\n return tokens\n\n search_buffer = Buffer(name = \"sidebarsearchbuffer\")\n search_field = SearchToolbar(\n search_buffer = search_buffer,\n ignore_case = True\n )\n def _buffer_pos_changed(buff):\n \"\"\" This callback gets executed after cursor position changes. Most\n of the time we register a key-press (up / down), we change the\n selected object and as a result of that the cursor changes. By that\n time we don't need to updat the selected object (cursor changed as\n a result of the selected object being updated). The one exception\n is when searching the sidebar buffer. When this happens the cursor\n moves ahead of the selected object. When that happens, here we\n update the selected object to follow suit.\n \"\"\"\n if buff.document.cursor_position_row != my_app.selected_object_idx[0]:\n my_app.select(buff.document.cursor_position_row)\n\n sidebar_buffer = Buffer(\n name = \"sidebarbuffer\",\n read_only = True,\n on_cursor_position_changed = _buffer_pos_changed\n )\n\n class myLexer(Lexer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._obj_list = []\n\n def add_objects(self, objects: List):\n self._obj_list = objects\n\n def lex_document(self, document: Document) -> Callable[[int], StyleAndTextTuples]:\n def get_line(lineno: int) -> StyleAndTextTuples:\n # TODO: raise out-of-range exception\n return tokenize_obj(self._obj_list[lineno])\n return get_line\n\n\n sidebar_lexer = myLexer()\n\n class myControl(BufferControl):\n\n def move_cursor_down(self):\n my_app.select_next()\n # Need to figure out what do do here\n # AFAICT these are only called for the mouse handler\n # when events are otherwise not handled\n def move_cursor_up(self):\n my_app.select_previous()\n\n def mouse_handler(self, mouse_event: MouseEvent) -> \"NotImplementedOrNone\":\n \"\"\"\n There is an intricate relationship between the cursor position\n in the sidebar document and which object is market as 'selected'\n in the linked list. Let's not muck that up by allowing the user\n to change the cursor position in the sidebar document with the mouse.\n \"\"\"\n return NotImplemented\n\n def create_content(self, width: int, height: Optional[int]) -> UIContent:\n # Only traverse the obj_list if it has been expanded / collapsed\n if not my_app.obj_list_changed:\n self.buffer.cursor_position = my_app.selected_object_idx[1]\n return super().create_content(width, height)\n\n res = []\n obj = my_app.obj_list[0]\n res.append(obj)\n while obj.next_object is not my_app.obj_list[0]:\n res.append(obj.next_object)\n obj = obj.next_object\n\n self.lexer.add_objects(res)\n self.buffer.set_document(Document(\n text = \"\\n\".join([a.name for a in res]), cursor_position = my_app.selected_object_idx[1]), True)\n # Reset obj_list_changed flag, now that we have had a chance to\n # regenerate the sidebar document content\n my_app.obj_list_changed = False\n return super().create_content(width, height)\n\n\n\n sidebar_control = myControl(\n buffer = sidebar_buffer,\n lexer = sidebar_lexer,\n search_buffer_control = search_field.control,\n focusable = True,\n )\n\n return HSplit([\n search_field,\n Window(\n sidebar_control,\n right_margins = [ScrollbarMargin(display_arrows = True)],\n style = \"class:sidebar\",\n width = Dimension.exact( 45 ),\n height = Dimension(min = 7, preferred = 33),\n scroll_offsets = ScrollOffsets(top = 1, bottom = 1)),\n Window(\n height = Dimension.exact(1),\n char = \"\\u2500\",\n style = \"class:sidebar,separator\",\n ),\n expanding_object_notification(my_app),\n sql_sidebar_navigation()])\n","sub_path":"odbcli/sidebar.py","file_name":"sidebar.py","file_ext":"py","file_size_in_byte":23951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"28719072","text":"import cv2\nimport glob\nimport numpy as np\n#from sift import Sift\n#from PIL import Image, ImageChops\n#from random import randrange\n#import matplotlib.pyplot as plt\n\nprint (cv2. __version__ )\n\nX_data = []\nY_data = []\nfiles = glob.glob (\"/Users/klee22/Desktop/save/New_Vid_copy/*.png\")\nfiles2 = glob.glob (\"/users/klee22/Desktop/save/New_vid_copy2/*.png\")\nfiles.sort()\nfiles2.sort()\n\n#Reads the Files as cv2\nfor myFile in files: \n #enumerated constants\n image = cv2.imread(myFile, cv2.IMREAD_COLOR) \n X_data.append (image)\n\nprint(np.sum(X_data[0]))\n\nfor myFile2 in files2:\n image2 = cv2.imread(myFile2, cv2.IMREAD_COLOR)\n Y_data.append (image2)\n\n# create multi-dim array by providing shape\nprint('X_data shape:', np.array(X_data).shape) \nprint('Y_data shape:', np.array(Y_data).shape) \n\n\nnumpic_x = len(X_data)\nnumpic_y = len(Y_data)\nprint(numpic_y)\nprint(numpic_x)\n#create an empty grid that has space for the data from the for loop\ncomparison_data = np.zeros(shape=(numpic_x, numpic_y)) \n\nx = 0\nfor ref_image in X_data:\n y = 0\n for new_image in Y_data:\n # if X_data[x].shape == Y_data[y].shape:\n # print(\"The images have same size and channels\")\n # difference = cv2.subtract(X_data[x], Y_data[y])\n # b, g, r = cv2.split(difference)\n # if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:\n # print(\"The images are completely Equal\")\n # comparison_data[x][y] = 1\n # else:\n # print(\"The images are NOT equal\")\n #SSIM\n orb = cv2.ORB_create()\n kp_1, desc_1 = orb.detectAndCompute(X_data[x], None)\n kp_2, desc_2 = orb.detectAndCompute(Y_data[y], None)\n\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n matches = bf.match(des1, des2)\n matches = sorted(matches, key = lambda x:x.distance)\n\n index_params = dict(algorithm=0, trees=5)\n search_params = dict()\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n\n matches = flann.knnMatch(desc_1, desc_2, k=2)\n\n good_points = []\n\n for m, n in matches:\n if m.distance < 0.6*n.distance:\n good_points.append(m)\n\n # Define how similar they are\n number_keypoints = 0\n if len(kp_1) <= len(kp_2):\n number_keypoints = len(kp_1)\n else:\n number_keypoints = len(kp_2)\n\n\n print(\"Keypoints 1ST Image: \" + str(len(kp_1)))\n print(\"Keypoints 2ND Image: \" + str(len(kp_2)))\n print(\"GOOD Matches:\", len(good_points))\n print(\"How good it's the match: \", len(good_points) / number_keypoints * 100)\n\n good_match = len(good_points) / number_keypoints * 100\n comparison_data[x][y] = good_match\n\n #result = cv2.drawMatches(X_data[x], kp_1, Y_data[y], kp_2, good_points, None)\n #cv2.imshow(\"result\", cv2.resize(result, None, fx=0.4, fy=0.4))\n #cv2.imwrite(\"feature_matching.jpg\", result)\n #print(comparison_data)\n y += 1\n x += 1\n\nprint(comparison_data)\n\nbest_comparison_points = []\n\nfor i in comparison_data:\n best_comparison_points.append(max(i))\n\noffset = []\noffset_values = []\n#for i in range(0,5): #len(x)\nfor y in range(0, numpic_y):\n big_value = 0\n big_index = 0\n for i in range(0, numpic_x):\n if big_value < comparison_data[y][i]:\n big_value = comparison_data[y][i]\n big_index = i \n offset.append((big_index) % (numpic_x))\n #offset.append((big_index-y) % (numpic_x))\n offset_values.append(big_value)\n\n#shows the biggest number and how the largest offset it does take; 4+1 4+2 = 5 6%6 offset + rownum % numpic\nprint(offset)\nprint(offset_values)\n\nalignment_data = []\ncomparison_data = np.zeros(shape=(numpic_x, numpic_y)) #values should have photos\n\n#creating orb\nnew_orb = Orb(offset, X_data, Y_data)\nnew_orb.create_orb()\n\n#new_sift = Sift(offset, X_data, Y_data)\n#new_sift.create_sift()\n\n\n\n","sub_path":"5-6SIFT.py","file_name":"5-6SIFT.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"249507214","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport sys\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import *\r\nfrom os import listdir, rename\r\nfrom shutil import *\r\nfrom datetime import *\r\nimport time\r\nfrom threading import *\r\n\r\nSymbol_For_Path = \"\\ \"\r\n\r\nnow_time = datetime.now()\r\ncur_year = now_time.year\r\ncur_month = now_time.month\r\ncur_day = now_time.day\r\ncur_hour = now_time.hour\r\ncur_minute = now_time.minute\r\ncur_seconds = now_time.second\r\n\r\n\r\nclass SecondThread(Thread):\r\n def __init__(self, name):\r\n Thread.__init__(self, name=name)\r\n\r\n self.times = 0\r\n self.cycle = 0\r\n\r\n db_1 = open(r\"Paths.txt\", \"r\")\r\n db_1_readlines = db_1.readlines()\r\n self_seconds = db_1_readlines[3]\r\n self.seconds = int(self_seconds[0:-1])\r\n db_1.close()\r\n\r\n def run(self):\r\n\r\n print(\"Script start\")\r\n\r\n while self.cycle == 0:\r\n while self.times == 0:\r\n\r\n db_1 = open(r\"Paths.txt\", \"r\")\r\n db_1_readlines = db_1.readlines()\r\n dwn_path = db_1_readlines[0]\r\n Downloaded_SWF_Path = dwn_path[0:-1]\r\n ori_path = db_1_readlines[1]\r\n Original_SWF_Path = ori_path[0:-1]\r\n bck_path = db_1_readlines[2]\r\n Backup_Path = bck_path[0:-1]\r\n db_1.close()\r\n\r\n db_2 = open(r\"Paths.txt\", \"r\")\r\n db_2_readlines = db_2.readlines()\r\n self_2_seconds = db_2_readlines[3]\r\n self.seconds = int(self_2_seconds[0:-1])\r\n db_2.close()\r\n\r\n try:\r\n Files_Search = listdir(Downloaded_SWF_Path)\r\n Filter = list(filter(lambda x: x.endswith('.swf'), Files_Search))\r\n Get_File_Name = Filter[0]\r\n Files_Search_2 = listdir(Original_SWF_Path)\r\n Filter_2 = list(filter(lambda x: x.endswith(Get_File_Name), Files_Search_2))\r\n rename(Original_SWF_Path +\r\n str(Symbol_For_Path[0]) +\r\n str(Get_File_Name),\r\n \"{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}\".format(Backup_Path,\r\n str(Symbol_For_Path[0]),\r\n str(Get_File_Name.replace(\".swf\",\r\n \"\")),\r\n str(\"-\"), str(cur_year),\r\n str(\"-\"), str(cur_month),\r\n str(\"-\"), str(cur_day),\r\n str(\"-\"), str(cur_hour),\r\n str(\"-\"), str(cur_minute),\r\n str(\".swf\")))\r\n print(Get_File_Name + str(\" was backup\"))\r\n Go_To_Original = move(\"{0}{1}{2}\".format(Downloaded_SWF_Path,\r\n str(Symbol_For_Path[0]),\r\n str(Get_File_Name)),\r\n Original_SWF_Path)\r\n except IndexError:\r\n print(\"No match files in \" + str(Downloaded_SWF_Path))\r\n print(\"Script waiting \" + str(self.seconds) + str(\" seconds\"))\r\n time.sleep(self.seconds)\r\n continue\r\n except FileNotFoundError:\r\n print(\"No match files in \" +\r\n str(Original_SWF_Path +\r\n \"\\nor\\n\" +\r\n \"Folder does not exist: \" +\r\n str(Downloaded_SWF_Path)))\r\n print(\"Script waiting \" + str(self.seconds) + str(\" seconds\"))\r\n time.sleep(self.seconds)\r\n continue\r\n except BaseException as e:\r\n print(e)\r\n print(\"Script waiting \" + str(self.seconds) + str(\" seconds\"))\r\n time.sleep(self.seconds)\r\n continue\r\n\r\n def stops_to_work(self):\r\n self.times = 1\r\n print(\"Script stop\")\r\n\r\n def start_again(self):\r\n self.times = 0\r\n print(\"Script start\")\r\n\r\n def stop_self_cycle(self):\r\n self.cycle = 1\r\n self.times = 1\r\n\r\n\r\nclass Stream(QObject):\r\n textWritten = pyqtSignal(str)\r\n\r\n def write(self, text):\r\n self.textWritten.emit(str(text))\r\n\r\n\r\nclass Button(QPushButton):\r\n\r\n def __init__(self, title, parent):\r\n\r\n super().__init__(title, parent)\r\n\r\n self.a = 0\r\n self.b = 0\r\n\r\n def hide_self(self):\r\n\r\n self.a = 1\r\n\r\n if self.a == 1:\r\n self.hide()\r\n pass\r\n\r\n def show_self(self):\r\n\r\n self.a = 0\r\n\r\n if self.a == 0:\r\n self.show()\r\n pass\r\n\r\n def disabled(self):\r\n\r\n self.b = 1\r\n\r\n if self.b == 1:\r\n self.setDisabled(True)\r\n pass\r\n\r\n def enabled(self):\r\n\r\n self.b = 0\r\n\r\n if self.b == 0:\r\n self.setDisabled(False)\r\n pass\r\n\r\n\r\nht = SecondThread('SecondThread')\r\n\r\n\r\nclass SWF_Copy_Manager(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n ##Задаем объекты размещаемые в нашем окне\r\n self.tray_icon = QSystemTrayIcon(self)\r\n self.le = QLineEdit(self)\r\n self.le2 = QLineEdit(self)\r\n self.le3 = QLineEdit(self)\r\n self.le4 = QLineEdit(self)\r\n self.te = QTextEdit(self)\r\n self.initUI()\r\n\r\n sys.stdout = Stream(textWritten=self.onUpdateText)\r\n sys.stderr = Stream(textWritten=self.onUpdateText)\r\n\r\n def onUpdateText(self, text):\r\n cursor = self.te.textCursor()\r\n cursor.movePosition(QTextCursor.End)\r\n cursor.insertText(text)\r\n self.te.setTextCursor(cursor)\r\n self.te.ensureCursorVisible()\r\n\r\n write_logs = open(r\"Logs.txt\", \"a+\")\r\n write_logs.write(text)\r\n write_logs.close()\r\n\r\n def initUI(self):\r\n\r\n ##Работа с файлами\r\n db_1 = open(r\"Paths.txt\", \"r\")\r\n db_1_readlines = db_1.readlines()\r\n dwn_path = db_1_readlines[0]\r\n Downloaded_SWF_Path = dwn_path[0:-1]\r\n ori_path = db_1_readlines[1]\r\n Original_SWF_Path = ori_path[0:-1]\r\n bck_path = db_1_readlines[2]\r\n Backup_Path = bck_path[0:-1]\r\n timer_line = db_1_readlines[3]\r\n timer_txt = timer_line[0:-1]\r\n db_1.close()\r\n\r\n ##Задаем дефолтные значения для полей ввода текста\r\n self.le.move(110, 10)\r\n self.le.setText(str(Downloaded_SWF_Path))\r\n self.le.setFixedSize(200, 29)\r\n self.le.setReadOnly(True)\r\n\r\n self.le2.move(110, 45)\r\n self.le2.setText(str(Original_SWF_Path))\r\n self.le2.setFixedSize(200, 29)\r\n self.le2.setReadOnly(True)\r\n\r\n self.le3.move(110, 80)\r\n self.le3.setText(str(Backup_Path))\r\n self.le3.setFixedSize(200, 29)\r\n self.le3.setReadOnly(True)\r\n\r\n self.le4.move(110, 115)\r\n self.le4.setText(str(timer_txt))\r\n self.le4.setFixedSize(30, 29)\r\n self.le4.setReadOnly(True)\r\n\r\n ##Задаем параметры поля ввода\r\n self.te.move(320, 10)\r\n self.te.setFixedSize(270, 230)\r\n self.te.setReadOnly(True)\r\n self.te.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)\r\n\r\n ##Задаем параметры окна\r\n self.statusBar().showMessage('Ready for fight')\r\n self.setFixedSize(600, 250)\r\n self.setWindowTitle('SWF Copy & Backup Manager')\r\n self.setWindowIcon(QIcon('75.png'))\r\n self.center()\r\n\r\n ##Заводим кнопки с действиями для трей менюшки\r\n show_action = QAction(\"Show\", self)\r\n hide_action = QAction(\"Hide\", self)\r\n quit_action = QAction(\"Exit\", self)\r\n\r\n ##Создаем менюшку\r\n tray_menu = QMenu()\r\n tray_menu.addAction(show_action)\r\n tray_menu.addAction(quit_action)\r\n\r\n ##Добавляем в трей менюшку и меняем иконку\r\n self.tray_icon.activated.connect(self.tray_icon_activated)\r\n self.tray_icon.setContextMenu(tray_menu)\r\n self.tray_icon.setIcon(QIcon('75.png'))\r\n\r\n ##Задаем шрифт тултипов и задаем тултипы под поля ввода\r\n QToolTip.setFont(QFont(\"SansSerif\", 10))\r\n self.le.setToolTip('Folder with downloads *.swf files')\r\n self.le2.setToolTip('Folder with Original *.swf files')\r\n self.le3.setToolTip('Folder with backups *.swf files')\r\n self.le4.setToolTip('This is the delay of the script')\r\n self.te.setToolTip('This is \"Log Space\"')\r\n\r\n ##Создаем кнопочки\r\n dw_btn = QPushButton('Download Folder', self)\r\n or_btn = QPushButton('Original Folder', self)\r\n bck_btn = QPushButton('Backup Folder', self)\r\n set_btn = QPushButton('Set Delay', self)\r\n ps_btn = Button('Start', self)\r\n lch_btn = Button('Start', self)\r\n stp_btn = Button('Stop', self)\r\n\r\n ##Присваиваем кнопочкам действия и другие атрибуты\r\n dw_btn.setToolTip(\"Set folder with downloads *.swf files\")\r\n dw_btn.move(5, 10)\r\n dw_btn.setFixedSize(100, 30)\r\n dw_btn.clicked.connect(self.showDialog)\r\n\r\n or_btn.setToolTip(\"Set folder with Original *.swf files\")\r\n or_btn.move(5, 45)\r\n or_btn.setFixedSize(100, 30)\r\n or_btn.clicked.connect(self.showDialog2)\r\n\r\n bck_btn.setToolTip(\"Set folder with backups *.swf files\")\r\n bck_btn.move(5, 80)\r\n bck_btn.setFixedSize(100, 30)\r\n bck_btn.clicked.connect(self.showDialog3)\r\n\r\n set_btn.setToolTip(\"Set the delay for script work\")\r\n set_btn.move(5, 115)\r\n set_btn.setFixedSize(100, 30)\r\n set_btn.clicked.connect(self.showDialog4)\r\n\r\n ps_btn.setToolTip(\"This button will start script to work\")\r\n ps_btn.hide()\r\n ps_btn.setDisabled(True)\r\n ps_btn.move(20, 180)\r\n ps_btn.clicked.connect(ht.start_again)\r\n ps_btn.clicked.connect(stp_btn.enabled)\r\n ps_btn.clicked.connect(ps_btn.disabled)\r\n ps_btn.clicked.connect(self.status_bar_lch)\r\n\r\n lch_btn.setToolTip(\"This button will start script to work\")\r\n lch_btn.move(20, 180)\r\n lch_btn.clicked.connect(ht.start)\r\n lch_btn.clicked.connect(lch_btn.hide_self)\r\n lch_btn.clicked.connect(ps_btn.show_self)\r\n lch_btn.clicked.connect(stp_btn.enabled)\r\n lch_btn.clicked.connect(self.status_bar_lch)\r\n\r\n stp_btn.setToolTip('This button will stop script to work')\r\n stp_btn.move(150, 180)\r\n stp_btn.setDisabled(True)\r\n stp_btn.clicked.connect(ht.stops_to_work)\r\n stp_btn.clicked.connect(ps_btn.enabled)\r\n stp_btn.clicked.connect(stp_btn.disabled)\r\n stp_btn.clicked.connect(self.status_bar_stp)\r\n\r\n ##Задаем экшен для кнопок в трей менюшке\r\n show_action.triggered.connect(self.show)\r\n show_action.triggered.connect(self.tray_icon_hide_show)\r\n show_action.triggered.connect(self.show_app)\r\n\r\n hide_action.triggered.connect(self.hide)\r\n\r\n quit_action.triggered.connect(qApp.quit)\r\n quit_action.triggered.connect(ht.stop_self_cycle)\r\n quit_action.triggered.connect(self.tray_exit_hide)\r\n\r\n def showDialog(self):\r\n self.statusBar().showMessage('Input path')\r\n text, ok = QInputDialog.getText(self, \"Set path\",\r\n \"Enter path for Download folder:\")\r\n if ok:\r\n self.statusBar().showMessage('Path changed')\r\n self.le.setText(str(text))\r\n\r\n db_1 = open(r\"Paths.txt\", \"r\")\r\n db_1_readlines = db_1.readlines()\r\n db_1.close()\r\n\r\n db_1_readlines[0] = str(text) + \"\\n\"\r\n\r\n db_1 = open(r\"Paths.txt\", \"w\")\r\n db_1.writelines(db_1_readlines)\r\n db_1.close()\r\n\r\n def showDialog2(self):\r\n self.statusBar().showMessage('Input path')\r\n text, ok = QInputDialog.getText(self, \"Set path\",\r\n \"Enter path for Download folder:\")\r\n if ok:\r\n self.statusBar().showMessage('Path changed')\r\n self.le2.setText(str(text))\r\n\r\n db_1 = open(r\"Paths.txt\", \"r\")\r\n db_1_readlines = db_1.readlines()\r\n db_1.close()\r\n\r\n db_1_readlines[1] = str(text) + \"\\n\"\r\n\r\n db_1 = open(r\"Paths.txt\", \"w\")\r\n db_1.writelines(db_1_readlines)\r\n db_1.close()\r\n\r\n def showDialog3(self):\r\n self.statusBar().showMessage('Input path')\r\n text, ok = QInputDialog.getText(self, \"Set path\",\r\n \"Enter path for Download folder:\")\r\n if ok:\r\n self.statusBar().showMessage('Path changed')\r\n self.le3.setText(str(text))\r\n\r\n db_1 = open(r\"Paths.txt\", \"r\")\r\n db_1_readlines = db_1.readlines()\r\n db_1.close()\r\n\r\n db_1_readlines[2] = str(text) + \"\\n\"\r\n\r\n db_1 = open(r\"Paths.txt\", \"w\")\r\n db_1.writelines(db_1_readlines)\r\n db_1.close()\r\n\r\n def showDialog4(self):\r\n self.statusBar().showMessage('Input delay')\r\n text, ok = QInputDialog.\\\r\n getInt(self, \"Set delay\", \"Enter delay for script work:\")\r\n if ok:\r\n self.statusBar().showMessage('Delay changed')\r\n self.le4.setText(str(text))\r\n\r\n db_1 = open(r\"Paths.txt\", \"r\")\r\n db_1_readlines = db_1.readlines()\r\n db_1.close()\r\n\r\n db_1_readlines[3] = str(text) + \"\\n\"\r\n\r\n db_1 = open(r\"Paths.txt\", \"w\")\r\n db_1.writelines(db_1_readlines)\r\n db_1.close()\r\n\r\n def status_bar_lch(self):\r\n self.statusBar().showMessage('I am Fighting...')\r\n\r\n def status_bar_stp(self):\r\n self.statusBar().showMessage('I am stopped...')\r\n\r\n def closeEvent(self, event):\r\n\r\n reply = QMessageBox.question(self,\r\n 'Exit',\r\n \"Do you really want to leave?\",\r\n QMessageBox.Yes | QMessageBox.No,\r\n QMessageBox.No)\r\n if reply == QMessageBox.Yes:\r\n ht.stop_self_cycle()\r\n event.accept()\r\n else:\r\n event.ignore()\r\n\r\n def tray_icon_hide_show(self):\r\n if self.isHidden():\r\n self.tray_icon.show()\r\n else:\r\n self.tray_icon.hide()\r\n\r\n def tray_exit_hide(self):\r\n self.tray_icon.hide()\r\n\r\n def changeEvent(self, event):\r\n if event.type() == QEvent.WindowStateChange:\r\n if self.windowState() & Qt.WindowMinimized:\r\n event.ignore()\r\n self.hide()\r\n self.tray_icon.show()\r\n return\r\n\r\n def tray_icon_activated(self, reason):\r\n if reason == QSystemTrayIcon.DoubleClick:\r\n if self.isHidden():\r\n self.showMaximized()\r\n self.center()\r\n ##Вызвать окно поверх остальных(не закрепить)\r\n self.raise_()\r\n ##Сделать окно активным для ввода\r\n self.activateWindow()\r\n self.tray_icon.hide()\r\n else:\r\n self.hide()\r\n\r\n def show_app(self):\r\n self.showMaximized()\r\n self.center()\r\n self.raise_()\r\n self.activateWindow()\r\n\r\n def center(self):\r\n\r\n qr = self.frameGeometry()\r\n cp = QDesktopWidget().availableGeometry().center()\r\n qr.moveCenter(cp)\r\n self.move(qr.topLeft())\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n ex = SWF_Copy_Manager()\r\n ex.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"swf_manager.py","file_name":"swf_manager.py","file_ext":"py","file_size_in_byte":16753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333786089","text":"\"\"\"\nCreated on Tue Mar 27 21:51:57 2018\n\n@author: plesueur\n\"\"\"\n\nimport unittest\nimport vdc_impacts as ip\nimport pandas as pd\n\nclass TestVDCImpacts(unittest.TestCase):\n '''\n Basic test class\n '''\n \n def test_probOfDamage(self):\n s = pd.Series(data = [0.64,0.95], index=['sigma','x50']) \n res = ip.probabilityOfDamage(0.3,s)\n self.assertAlmostEqual(res, 0.0358465750872893)\n res = ip.probabilityOfDamage(500,s)\n self.assertGreaterEqual(res, 0)\n self.assertLessEqual(res, 1)\n res = ip.probabilityOfDamage(-500,s)\n self.assertGreaterEqual(res, 0)\n self.assertLessEqual(res, 1)\n res = ip.probabilityOfDamage('garbage',s)\n self.assertEqual(res, 0)\n \n def test_buildingRate(self):\n vdc_data = ip.getVdcData('Atarpur')\n res = ip.buildingRate('wdn',vdc_data)\n self.assertAlmostEqual(res, 0.0021551724137931)\n res = ip.buildingRate('sm',vdc_data)\n self.assertAlmostEqual(res, 0.976293103448276)\n \n def test_buildingPop(self):\n vdc_data = ip.getVdcData('Atarpur')\n res = ip.buildingPop(vdc_data, 'wdn')\n self.assertAlmostEqual(res, 4.70258620689655)\n \n \n \nif __name__ == '__main__':\n unittest.main()","sub_path":"vdc_impact_test.py","file_name":"vdc_impact_test.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56320636","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author:joel\n# time:2019/3/14 13:05\n\nimport math\nimport pymysql\nimport requests\nimport re\nfrom lxml import etree\n\n\n\"\"\"\n北京 成交二手房 790980 小区个数 11638 在售二手房... 实际小区找到个数 5502\n上海 成交二手房 164075 小区个数 31205 在售二手房... 实际小区找到个数 6175\n广州 成交二手房 27028 小区个数 8732 在售二手房... 实际小区找到个数 5141\n深圳 成交二手房 78324 小区个数 6517 在售二手房... 实际小区找到个数 3796\n杭州 成交二手房 30423 小区个数 5936 在售二手房... 实际小区找到个数 3980\n\n目前只能遍历出最多 3000 个小区\n\"\"\"\n\n\nclass LianJia():\n def __init__(self):\n # self.village_area = {'bj': '北京', 'sh': '上海', 'gz': '广州', 'sz': '深圳', 'hz': '杭州'}\n self.village_area = {'sh': '上海', 'gz': '广州', 'sz': '深圳', 'hz': '杭州'}\n self.cj_list = []\n # 11633 个小区 388页 一页30个\n self.xiaoqu_list = \"https://{}.lianjia.com/xiaoqu/pg{}/\" # 2993 默认排序\n self.xiaoqu_list_cro11 = \"https://{}.lianjia.com/xiaoqu/pg{}cro11/\" # 按成交量\n self.xiaoqu_list_cro21 = \"https://{}.lianjia.com/xiaoqu/pg{}cro21/\" # 小区均价\n self.xq_list_search_ways = [self.xiaoqu_list, self.xiaoqu_list_cro11, self.xiaoqu_list_cro21]\n # 遍历以上三个链接,100页之后都一样\n self.xiaoqu_cj_list = \"https://bj.lianjia.com/chengjiao/pg{}c{}\"\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '\n '(KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'\n }\n\n def get_xiaoqu_url(self):\n s = requests.session()\n for area in self.village_area.keys():\n for way in self.xq_list_search_ways:\n for xq_page in range(1, 102):\n print(xq_page)\n r1 = s.get(way.format(area, xq_page), headers=self.headers)\n # print(r1.text)\n xq_url_list = re.findall(r'
  • '\n r'.*?.*?.*?
  • ', r1.text, re.S)\n for xq in xq_url_list:\n xq_url = xq[0]\n xq_id = re.sub('https://{}\\.lianjia\\.com/xiaoqu/|/'.format(area), '', xq_url)\n xq_name = xq[1]\n xq_cj_url = xq[2]\n xq_place = self.village_area[area]\n print(xq_id, xq_url, xq_name, xq_cj_url)\n self.insert(xq_id, xq_url, xq_name, xq_cj_url, xq_place)\n # break\n\n def w_cj(self):\n with open(\"D:\\\\pyprogram\\\\LianJia\\\\cj_urls.txt\", 'w') as fw:\n for cjurl in self.cj_list:\n fw.writelines(cjurl + '\\n')\n\n def insert(self, xq_id, xq_url, xq_name, xq_cj_url, xq_place):\n conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='lianjia')\n cursor = conn.cursor()\n\n insert_sql = \"insert into `xq_copy` (`xq_id`, `xq_url`, `xq_name`, `xq_cj_url`, `xq_place`)values\" \\\n \"('%s','%s','%s','%s','%s')\" % (xq_id, xq_url, xq_name, xq_cj_url, xq_place)\n select_sql = \"select `xq_id` from `xq_copy` where `xq_id`='%s'\" % xq_id\n\n try:\n response = cursor.execute(select_sql)\n conn.commit()\n if response == 1:\n print(u'该小区已存在...')\n else:\n try:\n cursor.execute(insert_sql)\n conn.commit()\n print(u'插入成功...')\n except Exception as e:\n print(u'插入错误...', e)\n conn.rollback()\n except Exception as e:\n print(u'查询错误...', e)\n conn.rollback()\n finally:\n cursor.close()\n conn.close()\n\n def get_cj_urls(self):\n conn_sel = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='lianjia')\n cursor = conn_sel.cursor()\n select_sql = \"select `xq_cj_url` from xq\"\n try:\n cursor.execute(select_sql)\n row = cursor.fetchall()\n for r in row:\n # print(r[0])\n self.cj_list.append(r[0])\n conn_sel.commit()\n except Exception as e:\n print('error1', e)\n conn_sel.rollback()\n finally:\n cursor.close()\n conn_sel.close()\n\n\nif __name__ == '__main__':\n lianjia = LianJia()\n lianjia.get_xiaoqu_url()\n\n","sub_path":"LianJia/LianJia/spiders/lianjia_village.py","file_name":"lianjia_village.py","file_ext":"py","file_size_in_byte":4887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"322347467","text":"import sys\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\n\nclass Conv2Net(nn.Module):\n def __init__(self, input_channels, middle_channels, output_channels, kernel_size, stride, padding):\n \"\"\"\n In the constructor we instantiate two nn.Linear modules and assign them as\n member variables.\n \"\"\"\n super(Conv2Net, self).__init__()\n self.layer1 = nn.Conv2d(in_channels=input_channels, out_channels=middle_channels, kernel_size=kernel_size, stride=stride, padding=padding)\n self.layer2 = nn.Conv2d(in_channels=middle_channels, out_channels=output_channels, kernel_size=kernel_size, stride=stride, padding=padding)\n def forward(self, x):\n \"\"\"\n In the forward function we accept a Tensor of input data and we must return\n a Tensor of output data. We can use Modules defined in the constructor as\n well as arbitrary (differentiable) operations on Tensors.\n \"\"\"\n x = self.layer1(x)\n x = self.layer2(x)\n return x\n@profile\ndef main():\n\n if (len(sys.argv) < 10):\n print(\"usage: conv.py \")\n return\n\n input_size = int(sys.argv[1])\n input_channels = int(sys.argv[2])\n padding = int(sys.argv[3])\n batch_size = int(sys.argv[4])\n kernel_size = int(sys.argv[5])\n output_channels = int(sys.argv[6])\n stride = int(sys.argv[7])\n opt_algo = sys.argv[8]\n middle_channels = int(sys.argv[9])\n\n\n print(\"Running: \", sys.argv[0])\n print(\"Input size: \", input_size)\n print(\"Input channels: \", input_channels)\n print(\"Padding: \", padding)\n print(\"Batch size: \", batch_size)\n print(\"Kernel size: \", kernel_size)\n print(\"Output channels: \", output_channels)\n print(\"Stride: \", stride)\n print(\"Opt algo: \", opt_algo)\n print(\"Middle channels: \", middle_channels)\n\n\n# N is batch size; D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\n\n# Create random Tensors to hold inputs and outputs\n x = Variable(torch.randn(batch_size, input_channels, input_size, input_size))\n\n middle_size = (input_size - kernel_size + 2*padding)/(stride) + 1\n output_size = (middle_size - kernel_size + 2*padding)/(stride) + 1\n y = Variable(torch.randn(batch_size, output_channels, output_size, output_size))\n\n# Construct our model by instantiating the class defined above.\n myConv = Conv2Net(input_channels, middle_channels, output_channels, kernel_size, stride, padding)\n\n# Construct our loss function and an Optimizer. The call to model.parameters()\n# in the SGD constructor will contain the learnable parameters of the two\n# nn.Linear modules which are members of the model.\n loss_fn = nn.MSELoss(size_average=False)\n if(opt_algo == \"SGD\"):\n optimizer = optim.SGD(myConv.parameters(), lr=1e-4)\n elif(opt_algo == \"Adam\"):\n optimizer = optim.Adam(myConv.parameters(), lr=0.001)\n\n# training part to be implemented\n myConv.train()\n optimizer.zero_grad()\n y1 = myConv(x)\n loss = loss_fn(y1, y)\n loss.backward()\n optimizer.step()\n\n\n\n# inference part\n myConv.eval()\n y1 = myConv(x)\n\nif __name__ == '__main__':\n main()","sub_path":"conv2.py","file_name":"conv2.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"379579297","text":"\"\"\"Importing an Entire Module\"\"\"\r\nimport car\r\n\r\nmy_beetle = car.Car(\"volkswagen\", \"beetle\", 2016)\r\nprint(my_beetle.get_descriptive_name())\r\n\r\nmy_tesla = car.ElectricCar(\"tesla\", \"roadster\", 2016)\r\nprint(my_tesla.get_descriptive_name())\r\n\r\n\"\"\"Importing All Classes from a Module\r\nYou can import every class from a module using the following syntax:\r\nfrom module_name import *\r\nfrom Car import *\"\"\"\r\n\"\"\"\"This method is not recommended for two reasons. First, it’s helpful\r\nto be able to read the import statements at the top of a file and get a clear\r\nsense of which classes a program uses. With this approach it’s unclear which\r\nclasses you’re using from the module. This approach can also lead to confusion\r\nwith names in the file. If you accidentally import a class with the same\r\nname as something else in your program file, you can create errors that are\r\nhard to diagnose. I show this here because even though it’s not a recommended\r\napproach, you’re likely to see it in other people’s code.\r\nIf you need to import many classes from a module, you’re better off\r\nimporting the entire module and using the module_name.class_name syntax.\"\"\"","sub_path":"my_cars.py","file_name":"my_cars.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"547763747","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Oct 21 19:08:30 2017\r\n\r\n@author: juzheng\r\n\"\"\"\r\n\r\n\r\nfrom proxy import proxy_crawl #返回一个代理列表,参数为n,代理数量为n*100\r\nimport urllib.request\r\nimport http.cookiejar\r\nimport re\r\nimport time\r\nfrom pandas import DataFrame\r\nimport pandas as pd\r\n\r\nproxylist=proxy_crawl(20)\r\np=10\r\nproxy_addr=proxylist[p]\r\nnoprice=[]\r\nbaseurl='https://book.douban.com/subject/'\r\nheaders={\"Host\": \"book.douban.com\",\r\n\"Connection\":\"keep-alive\",\r\n\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\",\r\n\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\r\n\"Accept-Language\": \"zh-CN,zh;q=0.8\",\r\n\"Referer\":\"https://book.douban.com/tag/%E7%BB%8F%E6%B5%8E%E5%AD%A6\"\r\n}\r\nheaderall=[]\r\nfor (key,value) in headers.items():\r\n item=(key,value)\r\n headerall.append(item)\r\n\r\nop=pd.read_csv('D:\\\\booksfinal(noindex)bian.csv')\r\nopid=op['idlist']\r\nIDlist=list(opid)\r\n\r\nwhole={}\r\ndef price_crawl(idnum,proxy_addr):\r\n proxy=urllib.request.ProxyHandler({'http':proxy_addr})\r\n cjar=http.cookiejar.CookieJar()\r\n opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler(),urllib.request.HTTPCookieProcessor(cjar))\r\n opener.addheaders=headerall\r\n urllib.request.install_opener(opener)\r\n url=baseurl+str(idnum)+'/'\r\n html=urllib.request.urlopen(url).read().decode('utf-8')\r\n html=str(html)\r\n pattern1='在哪儿买这本书(.+?)
    '\r\n pricepart=re.findall(pattern1,html,re.S) \r\n if pricepart==[]:\r\n pattern2='其他版本有售(.+?)
    '\r\n pricepart=re.findall(pattern2,html,re.S)\r\n if pricepart!=[]:\r\n pricepart=pricepart[0]\r\n \r\n web_pattern=r'\\s+?(\\w+?)\\s+?'\r\n price_pattern=r'\\s+?\\s+?(\\d+?\\.\\d+?) 元'\r\n web=re.findall(web_pattern,pricepart)\r\n price=re.findall(price_pattern,pricepart)\r\n for i in range(len(web)):\r\n wp[web[i]]=str(price[i])\r\n whole[idnum]=wp\r\n else:\r\n print('no other price')\r\n print(str(idnum))\r\n noprice.append(idnum)\r\n else:\r\n pricepart=pricepart[0]\r\n web_pattern=r'\\s+?(.+?)'\r\n price_pattern=r'\\s+?\\s+?(\\d+?\\.\\d+?) 元\\s+?'\r\n web=re.findall(web_pattern,pricepart)\r\n price=re.findall(price_pattern,pricepart) \r\n for i in range(len(web)):\r\n wp[web[i]]=str(price[i])\r\n whole[idnum]=wp\r\n \r\n time.sleep(5)\r\n \r\nfor i in range(len(IDlist)):\r\n wp={}\r\n try:\r\n price_crawl(IDlist[i],proxy_addr)\r\n except urllib.error.URLError as e:\r\n if hasattr(e,\"code\"):\r\n print(e.code)\r\n if hasattr(e,\"reason\"):\r\n print(e.reason)\r\n p+=1\r\n proxy_addr=proxylist[p]\r\n\r\n\r\n \r\nidlist=whole.keys()\r\npricelist=whole.values()\r\nidlist=list(idlist)\r\npricelist=list(pricelist)\r\nframe=DataFrame({'id':idlist,\r\n 'otherprice':pricelist\r\n })\r\nframe.to_csv('D:\\\\otherprice.csv')\r\n \r\n\r\n \r\n \r\n\r\n \r\n \r\n","sub_path":"otherprice.py","file_name":"otherprice.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242768747","text":"#!/usr/bin/python\n\nfrom subprocess import call\n\ndef main():\n call('cp -p /etc/inputrc /etc/inputrc.bak'.split(' '))\n to_append = open('/etc/inputrc', 'a')\n to_append.write('\\nset completion-ignore-case on\\n')\n to_append.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"unixFiles/scripts/case_blind_tab_complete.py","file_name":"case_blind_tab_complete.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"299771737","text":"#! /usr/bin/python\n\nimport lof_gfx_pygame as gfx\nimport lof_game as game\nimport lof_bindings as bindings\nimport lof_actionparse as parser\nimport lof_fs as fs\n\nr = gfx.renderer()\n\ninstate = game.input_state()\ngamestate = {\n \"renderer\": r,\n \"fs\": fs.fs (\"lof_data\"),\n \"defaults\": [ \"teamname red\",\n \"editor false\", \n \"direction up\", \n \"piecetype unit\", \n \"unittype triangle\", \n \"autolayer\",\n \"tiletype goal\",\n \"pos 0 0\" ],\n \"eachframe\": [ \"drawcursor\",\n \"refresh\",\n \"clearcursor\" ]\n }\ngamestate[\"fs\"].add_resource_type (\"scenario\", \"scenarios\", \"lof\")\nfor action in gamestate[\"defaults\"]+[\"filename std\", \"openmap\"]:\n cmd, args = parser.parse_statement(action)\n game.run_cmd (gamestate, cmd, args)\n\nbindings.game_add_buttons(gamestate)\n\nwhile True:\n r.update_inputstate (instate)\n actions = bindings.game_transform_controls(instate, gamestate)\n \n for action in actions:\n cmd, args = parser.parse_statement (action)\n game.run_cmd (gamestate, cmd, args)\n \n for action in gamestate[\"eachframe\"]:\n cmd, args = parser.parse_statement (action)\n game.run_cmd (gamestate, cmd, args)\n \n\n","sub_path":"lof_main.py","file_name":"lof_main.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"40278443","text":"from typing import TypeVar, Sequence, Optional, Generic, T\n\nfrom ._ipywidgets import ipywidgets\n\nfrom descarteslabs.common.proto.widgets import widgets_pb2\n\nfrom ...types import Int, Float, Str\nfrom ...types.widget import Widget\n\n\nFORMAT_TO_WIDGET = {\n \"dropdown\": ipywidgets.Dropdown,\n \"radio\": ipywidgets.RadioButtons,\n \"slider\": ipywidgets.SelectionSlider,\n}\n\n\nclass Select(Widget, Generic[T]):\n def __init__(\n self, name: str, options: Sequence[T], format: str, default: T, label=\"\"\n ):\n super().__init__(name, default, label)\n\n if len(options) == 0:\n raise ValueError(\"Must give at least one option\")\n\n format = format.lower()\n self._options = options\n self._format = format\n\n try:\n widget_type = FORMAT_TO_WIDGET[format]\n except KeyError:\n raise ValueError(\n f\"Unsupported format {format!r}. Must be one of: {tuple(FORMAT_TO_WIDGET)}.\"\n ) from None\n\n self.widget = widget_type(options=options, value=default)\n self.widget._label = label\n\n def _to_proto_set_widget_msg(self, widget_msg: widgets_pb2.StringSelect):\n widget_msg.default = self._default\n widget_msg.format = widgets_pb2.SelectFormat.Value(self._format.upper())\n widget_msg.options[:] = self._options\n\n @classmethod\n def _from_proto_init_from_widget_msg(\n cls, name: str, label: str, widget_msg: widgets_pb2.StringSelect\n ):\n return cls(\n name=name,\n options=list(widget_msg.options),\n format=widgets_pb2.SelectFormat.Name(widget_msg.format).lower(),\n default=widget_msg.default,\n label=label,\n )\n\n\nclass StringSelect(Select[str], Str):\n _proto_type = widgets_pb2.StringSelect\n\n\nclass IntSelect(Select[int], Int):\n _proto_type = widgets_pb2.IntSelect\n\n\nclass FloatSelect(Select[float], Float):\n _proto_type = widgets_pb2.FloatSelect\n\n\nTYPES = {str: StringSelect, int: IntSelect, float: FloatSelect}\nPrimitiveType = TypeVar(\"Primitive\", *TYPES)\n\n\ndef select(\n name: str,\n options: Sequence[PrimitiveType],\n format: str = \"dropdown\",\n default: Optional[PrimitiveType] = None,\n label: str = \"\",\n):\n \"\"\"\n A widget (dropdown, radio buttons, etc.) to select a value from a list of options.\n\n Depending on the types of the values you pass for ``options``, the widget will act as\n a `.Str`, an `.Int`, or a `.Float` parameter.\n\n Example\n -------\n >>> import descarteslabs.workflows as wf\n >>> wf.widgets.select(\n ... \"param_name\",\n ... [\"one\", \"two\", \"three\"],\n ... format=\"radio\",\n ... default=\"two\",\n ... label=\"A select parameter\",\n ... ) # doctest: +SKIP\n\n >>> s2 = wf.ImageCollection.from_id(\"sentinel-2:L1C\", \"2018-01-01\", \"2018-04-01\")\n >>> s2_bands = s2.pick_bands(\n ... wf.widgets.select(\n ... \"band_combo\",\n ... [\"red green blue\", \"nir red green\", \"swir1 nir blue\"],\n ... format=\"radio\",\n ... label=\"Band combination\"\n ... )\n ... )\n >>> s2_bands.visualize(\"Sentinel-2\", scales=[[0, 0.4], [0, 0.4], [0, 0.4]]) # doctest: +SKIP\n >>> # ^ when you call .visualize, the `select` widget will automatically show up below\n\n Selecting a band combination from the radio buttons will update the map.\n (If you haven't already, run ``wf.map`` in another notebook cell to see your layer.)\n\n You may want to display user-friendly terms for your options, rather than the actual values.\n A typical way to do this is to make a `.Dict` mapping the user-friendly terms to their values,\n then use the dict's keys as ``options``:\n\n >>> band_combos = {\n ... \"Natural color\": \"red green blue\",\n ... \"Vegetation\": \"nir red green\",\n ... \"Agriculture\": \"swir1 nir blue\"\n ... }\n >>> band_combo_name = wf.widgets.select(\n ... \"band_combo\",\n ... options=band_combos.keys(),\n ... format=\"radio\",\n ... label=\"Band combination\",\n ... )\n >>> band_combos_wf = wf.Dict[wf.Str, wf.Str](band_combos)\n >>> s2_bands = s2.pick_bands(band_combos_wf[band_combo_name])\n >>> s2_bands.visualize(\"Sentinel-2\", scales=[[0, 0.4], [0, 0.4], [0, 0.4]]) # doctest: +SKIP\n\n Parameters\n ----------\n name: str\n The name of the parameter.\n options: Sequence[str, int, or float]\n The available options to display. All values in the sequence must be the same type.\n format: str, default \"dropdown\"\n Which sort of widget to display. Options are:\n\n * \"dropdown\" (default): a dropdown selector\n * \"radio\": radio buttons\n * \"slider\": a slider to pick between the ``options`` in the order they're given.\n Displays the currently-selected option on the right side.\n default: str, int, float, optional, default None\n The default value to have selected. If None (default), picks the first value in ``options``.\n If not None, the value must be in the ``options`` list.\n label: str, default \"\"\n The longform label to display next to the widget.\n If not given, the widget will display as ``name``.\n\n Returns\n -------\n widget: Union[StringSelect, IntSelect, FloatSelect]\n A Widget object that acts just like a Workflows `.Str`, `.Int`, or `.Float`, and displays as a selector widget.\n \"\"\"\n\n first, *rest = options\n if not isinstance(first, tuple(TYPES)):\n raise TypeError(\n f\"Only primitive Python values ({tuple(TYPES)}) can be used as options for `select`, \"\n f\"not {first!r}.\"\n )\n\n pytype = type(first)\n for x in options:\n if not isinstance(x, pytype):\n raise TypeError(\n f\"All options must be the same type. Expected all {pytype}, but got {x!r}\"\n )\n\n if default is None:\n default = first\n elif default not in options:\n raise ValueError(f\"The default {default!r} is not in the options list.\")\n\n return TYPES[pytype](\n name=name, options=options, format=format, default=default, label=label\n )\n","sub_path":"descarteslabs/workflows/interactive/widgets/select.py","file_name":"select.py","file_ext":"py","file_size_in_byte":6138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"570221374","text":"from tensorflow import python as tf\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nimport pandas as pd\r\n\r\n\r\ntrain_datagen = ImageDataGenerator(rescale=1./255,\r\n shear_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=False)\r\n\r\ntest_datagen = ImageDataGenerator(rescale=1./255)\r\n\r\n\r\n\r\ntraining_set = train_datagen.flow_from_directory('data2/masked_rotated_h_train/small vehicle/',\r\n target_size=(30, 75),\r\n batch_size=32,\r\n class_mode='categorical')\r\n\r\ntest_set = test_datagen.flow_from_directory('data2/masked_rotated_h_test/small vehicle/',\r\n target_size=(30, 75),\r\n batch_size=32,\r\n class_mode='categorical')\r\n\r\n# Initialising\r\ncnn_classifier = tf.keras.models.Sequential()\r\n\r\n# 1st conv. layer\r\ncnn_classifier.add(tf.keras.layers.Conv2D(64, (3, 3), input_shape=(30, 75, 3), activation='relu'))\r\ncnn_classifier.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\r\n\r\n# 2nd conv. layer\r\ncnn_classifier.add(tf.keras.layers.Conv2D(128, (3, 3), activation='relu'))\r\ncnn_classifier.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\r\n\r\n# 3nd conv. layer\r\ncnn_classifier.add(tf.keras.layers.Conv2D(256, (3, 3), activation='relu'))\r\ncnn_classifier.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\r\n\r\n# Flattening\r\ncnn_classifier.add(tf.keras.layers.Flatten())\r\n\r\n\r\n# Full connection\r\ncnn_classifier.add(tf.keras.layers.Dense(units=256, activation='relu'))\r\ncnn_classifier.add(tf.keras.layers.Dropout(0.5))\r\ncnn_classifier.add(tf.keras.layers.Dense(units=6, activation='sigmoid'))\r\n\r\ncnn_classifier.summary()\r\n# Compiling the CNN\r\ncnn_classifier.compile(optimizer='adam',\r\n loss='categorical_crossentropy',\r\n metrics=['accuracy'])\r\n\r\ncnn_classifier.fit_generator(training_set,\r\n steps_per_epoch=6406,\r\n epochs=10,\r\n validation_data=test_set,\r\n validation_steps=903)\r\n\r\n# saving model and weights\r\ncnn_classifier.save_weights('data2/vehicle_classification_weights_dropout.h5')\r\ncnn_classifier.save('data2/vehicle_classification_model_dropout.h5')\r\n","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"377099420","text":"from googleads import adwords\nimport config_GoogleAdWords as gadc\nimport pandas as pd\n\nadwords_client = adwords.AdWordsClient(\n gadc.developer_token,\n gadc.oauth2_client,\n client_customer_id=gadc.client_customer_id\n)\n\nreport_name = 'AD_PERFORMANCE_REPORT'\n\n\n# # print the fields in the report and datatypes\ndef get_fields_in_report(client, report_type):\n # Initialize appropriate service.\n report_definition_service = client.GetService(\n 'ReportDefinitionService', version='v201802')\n\n # Get report fields.\n fields = report_definition_service.getReportFields(report_type)\n\n # Display results.\n print('Report type \"%s\" contains the following fields:' % report_type)\n for field in fields:\n print(' - %s (%s)' % (field['fieldName'], field['fieldType']))\n if 'enumValues' in field:\n print(' := [%s]' % ', '.join(field['enumValues']))\n\n\nif __name__ == '__main__':\n get_fields_in_report(adwords_client, report_name)\n","sub_path":"GoogleAdwords_GetReportFields.py","file_name":"GoogleAdwords_GetReportFields.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"391209710","text":"import tensorflow as tf\nimport numpy as np\n# #### Defining Variables\n\n\ng1 = tf.Graph()\n\nwith g1.as_default():\n w = tf.Variable(np.array([[1, 2, 3, 4],\n [5, 6, 7, 8]]), name='w')\n print(w)\n\n# #### Initializing variables\n\n\n\n## initialize w and evaluate it\nwith tf.compat.v1.Session(graph=g1) as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n print(sess.run(w))\n\n\n\n\n## add the init_op to the graph\nwith g1.as_default():\n init_op = tf.compat.v1.global_variables_initializer()\n \n## initialize w with init_op and evaluate it\nwith tf.compat.v1.Session(graph=g1) as sess:\n sess.run(init_op)\n print(sess.run(w))\n\n\n\n\ng2 = tf.Graph()\n\nwith g2.as_default():\n w1 = tf.Variable(1, name='w1')\n init_op = tf.compat.v1.global_variables_initializer()\n w2 = tf.Variable(2, name='w2')\n\n\n\n\nwith tf.compat.v1.Session(graph=g2) as sess:\n sess.run(init_op)\n print('w1:', sess.run(w1))\n\n\n# Error if a variable is not initialized:\n\n\n\nwith tf.compat.v1.Session(graph=g2) as sess:\n \n try:\n sess.run(init_op)\n print('w2:', sess.run(w2))\n except tf.errors.FailedPreconditionError as e:\n print(e)\n\n\n","sub_path":"ch14/variable.py","file_name":"variable.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"121836845","text":"n = int(input('Enter a number: '))\ntotal1 = 0\ntotal2 = 1\nlength = 0\nwhile n > 0:\n if length % 2 != 0: \n total1 += (n % 10)\n else:\n total2 *= (n % 10)\n n //= 10\n length += 1\nprint('Answer:', (total1 + total2))\n","sub_path":"problem10.py","file_name":"problem10.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90984068","text":"from django.http import JsonResponse\nfrom django.http.response import HttpResponse\nfrom django.template.loader import render_to_string\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom viberbot import Api\nfrom viberbot.api.messages import KeyboardMessage\nfrom viberbot.api.messages.text_message import TextMessage\nfrom viberbot.api.bot_configuration import BotConfiguration\nfrom viberbot.api.viber_requests import ViberMessageRequest\nfrom viberbot.api.messages.sticker_message import StickerMessage\n\nimport datetime\nfrom decouple import config\n\nfrom .keyboard import *\nfrom .subscribe import Subscriber\nfrom .middleware import Middleware\nfrom .back_button import BackButton\nfrom .db_request import DatabaseRequest\nfrom .show_schedule import show, show_for_subscriber\n\n\nbot_configuration = BotConfiguration(\n name='Робот',\n avatar='http://brstu.ru/docs/faculties/feiu/feiu-logo.jpg',\n auth_token=config('TOKEN')\n)\nviber = Api(bot_configuration)\n\nmiddleware = Middleware()\ndb_request = DatabaseRequest()\nback_button = BackButton()\nsubscriber = Subscriber()\n\n\n@csrf_exempt\ndef index(request):\n req = request.body\n viber_request = viber.parse_request(req.decode('utf-8'))\n\n if isinstance(viber_request, ViberMessageRequest):\n username = viber_request.sender.name\n chat_id = viber_request.sender.id\n request_text = viber_request.message.text\n\n if request_text == \"Меню\":\n viber.send_messages(chat_id, [TextMessage(text='Выберите пункт меню')])\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=MAIN_MENU)])\n\n elif request_text == \"Получить расписание по подписке\":\n success_adding = middleware.add_subscribe(username, chat_id, 'get_subscribe', 'Viber')\n if success_adding:\n schedule = db_request.get_subscribers_schedule(chat_id)\n if schedule:\n today_sch, tomorrow_sch = show_for_subscriber(schedule)\n try:\n today_date = datetime.datetime.today().strftime('%d.%m')\n viber.send_messages(chat_id, [TextMessage(text=\"Расписание на сегодня (\" + today_date + \"):\\n\\n\" + today_sch)])\n except:\n viber.send_messages(chat_id, [TextMessage(text=\"Запрос не удалось обработать, попробуйте позже\")])\n\n try:\n tomorrow_date = (datetime.datetime.today() + datetime.timedelta(days=1)).strftime('%d.%m')\n viber.send_messages(chat_id, [TextMessage(text=\"Расписание на завтра (\" + tomorrow_date + \"):\\n\\n\" + tomorrow_sch)])\n except:\n viber.send_messages(chat_id, [TextMessage(text=\"Запрос не удалось обработать, попробуйте позже\")])\n else:\n viber.send_messages(chat_id, [TextMessage(text=\"Запрос не выполнен\")])\n else:\n viber.send_messages(chat_id, [TextMessage(text=\"Вы еще не подписаны на расписание\")])\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=MAIN_MENU)])\n\n elif request_text == \"Время пар\":\n middleware.add_time(username, chat_id, \"Viber\")\n viber.send_messages(chat_id, [TextMessage(text=render_to_string('time.md'))])\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=MAIN_MENU)])\n\n elif request_text == \"Получить расписание\":\n # добавляем пользователя в статистику, курс, специальность и дата запроса - empty\n middleware.get_user(username, chat_id, \"Viber\")\n viber.send_messages(chat_id, [TextMessage(text=\"Выберите специальность\")])\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=SELECT_GROUP)])\n\n elif request_text == \"ПИЭ\" or request_text == \"УП\" or\\\n request_text == \"ГМУ\" or request_text == \"ИМ\" or\\\n request_text == \"УИ\" or request_text == \"ФиК\" or\\\n request_text == \"ПМ\" or request_text == \"К\":\n middleware.update_group(chat_id, request_text)\n viber.send_messages(chat_id, [TextMessage(text=\"Выберите курс\")])\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=SELECT_COURSE)])\n\n elif request_text == \"1 курс\" or request_text == \"2 курс\" \\\n or request_text == \"3 курс\" or request_text == \"4 курс\":\n middleware.update_course(chat_id, request_text)\n viber.send_messages(chat_id, [TextMessage(text=\"Выберите время\")])\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=FINAL_MENU)])\n\n # todo На сегодня и на завтра похожи, мб функция?\n elif request_text == \"На сегодня\":\n data = middleware.get_full_info(chat_id)\n course = data[3]\n group = data[4]\n # запрос расписания, курс берем только цифру\n schedule = db_request.get_today_schedule(course[0], group)\n try:\n viber.send_messages(chat_id, [TextMessage(text=show(schedule))])\n except:\n viber.send_messages(chat_id, [TextMessage(text=\"Запрос не удалось обработать, попробуйте позже\")])\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=MAIN_MENU)])\n\n elif request_text == \"На завтра\":\n data = middleware.get_full_info(chat_id)\n course = data[3]\n group = data[4]\n schedule = db_request.get_tomorrow_schedule(course[0], group)\n try:\n viber.send_messages(chat_id, [TextMessage(text=show(schedule))])\n except:\n viber.send_messages(chat_id, [TextMessage(text=\"Запрос не удалось обработать, попробуйте позже\")])\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=MAIN_MENU)])\n\n elif request_text == \"На главную\":\n back_button.cancel_operation(chat_id, 0)\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=MAIN_MENU)])\n\n elif request_text == \"Вернуться назад\":\n empty_count = db_request.select_backbutton(chat_id)\n if empty_count == 1:\n back_button.cancel_operation(chat_id, 1)\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=SELECT_COURSE)])\n elif empty_count == 2:\n back_button.cancel_operation(chat_id, 2)\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=SELECT_GROUP)])\n elif empty_count == 3:\n back_button.cancel_operation(chat_id, 0)\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=MAIN_MENU)])\n\n elif request_text == \"Подписаться на это расписание\":\n data = middleware.get_full_info(chat_id)\n response = subscriber.add_subscriber(data)\n viber.send_messages(chat_id, [TextMessage(text=response)])\n viber.send_messages(chat_id, [KeyboardMessage(keyboard=MAIN_MENU)])\n else:\n viber.send_messages(viber_request.sender.id, [StickerMessage(sticker_id=40133)])\n viber.send_messages(viber_request.sender.id, [TextMessage(text=\"Что-то не так, попробуйте еще раз\")])\n return JsonResponse({}, status=200)\n\n\n\n\n\n#Пример запроса\n\"\"\"\nViberMessageRequest\n[event_type=message,\ntimestamp=1498799862283,\nmessage_token=5061443159342451146,\nsender=UserProfile[name=Роман Саблин, avatar=https://media-direct.cdn.viber.com/download_photo?dlid=0lmYu0BW8EnttzNGSiHnww_XAnU_9PkaIx90Dgkdc6VKhOuEi6jp4fKPIxpG2WH7O1goyiLdETrSR0A1q1ihBTqhloL5p34PgxVc4tjldbmguMQ5_n5bgKV36lMnFJriHtKXOQ&fltp=jpg&imsz=0000,\n id=nT7x1IzZ3XbEpRjBs7pY+g==, country=RU, language=ru, api_version=2, message=TextMessage [tracking_data=None, keyboard=None, min_api_version=None, text=A], chat_id=None, reply_type=None, silent=False]\n\"\"\"","sub_path":"vbot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445987354","text":"import os\nimport math\n\ndef integral(a, b, n):\n \n if n % 2 == 1:\n n += 1\n print(n)\n\n h = (b - a) / n\n\n suma = f(a) + f(b)\n\n for i in range(1,n,2):\n suma += 4 * f(a + (i * h))\n\n for i in range(2,n,2):\n suma += 2 * f(a + (i * h)) \n\n return suma * (h/3)\n\ndef f(x): #Esta sera la funcion a integrar\n\n y = x**3; #En este ejemplo se tiene la funcion y = cos(x)\n\n return y\n\n\nprint(integral(1,10,4))","sub_path":"PY/CTerm/IntegralSimpson.py","file_name":"IntegralSimpson.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"387277060","text":"import os, enum, shutil\n\nIMAGE_EXTENSIONS = 'jpg', 'jpeg', 'png'\nVIDEO_EXTENSIONS = ('mpg', 'mod', 'mmv', 'tod', 'wmv', 'asf', \n 'avi', 'divx', 'mov', 'm4v', '3gp', '3g2', \n 'mp4', 'm2t', 'm2ts', 'mts', 'and', 'mkv')\npictures_copied = 0\n\ndef get_ext(file: str) -> str:\n '''\n Return the file extension of a file\n\n :param file: A path to a file\n :return: The file extension. If there isn't one, an empty string is returned\n '''\n split = file.split('.')\n if len(split) == 1:\n return ''\n else:\n return file.split('.')[-1].lower()\n\ndef is_media(file: str) -> bool:\n '''\n Checks whether a file is a media file. \n A media file is a file with one of the \n IMAGE_EXTENSIONS or VIDEO_EXTENSIONS\n\n :param file: A path to a file\n :return: True if the file is a media file, False if it's not\n '''\n ext = get_ext(file)\n return ext in IMAGE_EXTENSIONS + VIDEO_EXTENSIONS\n\ndef extract_media(top: str, dest: str, exc_ext: list = None) -> int:\n '''\n Extract pictures from a directory tree.\n Pictures (image files) are searched for throughout \n the entire drectory tree recursively in subdirectories\n \n :param top: The top of the directory tree\n :param dest: The destination directory to copy the pictures to. \n Every picture that is qualified as such and is not marked to be \n excluded from the search is copied over to this diretory\n :param exc_ext: A list of image extensions to excldue from the operation. \n Any file with one of these extensions is skipped. \n If this is None (default), no picture file is skipped\n :return: The number of extracted pictures\n '''\n global pictures_copied\n if top == dest: \n print(f'\\nTop and destination directories are the same, they must be different!') \n return 0\n try:\n items = os.scandir(top)\n except FileNotFoundError:\n print(f'\\nTop directory {top!r} not found! Try again.')\n return 0\n for item in items:\n if not item.name.startswith('.'):\n if item.is_file(follow_symlinks=False) and is_media(item.name) and get_ext(item.name) not in exc_ext:\n if not os.path.exists(dest):\n os.mkdir(dest)\n shutil.copy(item.path, dest)\n pictures_copied += 1\n elif item.is_dir():\n extract_media(item.path, dest, exc_ext)\n else:\n return pictures_copied\n\ndef interact(repeat: bool = True):\n '''\n Perform an interaction with the program\n\n :param repeat: Indicates whether to continue\n the iteraction process after some \n actions are performed or to exit the program\n '''\n global pictures_copied\n pictures_copied = 0\n print()\n top = input('Choose a top directory for media extraction: ')\n if top == 'exit': os._exit(0)\n dest = input('Choose a destination directory to hold the extracted media files: ')\n if dest == 'exit': os._exit(0)\n exc_ext = input('Excluded file extensions (optional). Separate these with commas: ').split(',')\n if exc_ext == 'exit': os._exit(0)\n extract_media(top, dest, exc_ext)\n if repeat: interact()\n else: return","sub_path":"extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"513865297","text":"import math, microbit, random\n\nadjust=lambda x: int(math.floor(x))\n\nmicrobit.display.scroll(\">>>\", delay=100)\nfirebase=[5+random.randrange(4) for i in range(5)]\n\ndef fire():\n\n global firebase\n newbase=[]\n for i in firebase:\n if random.choice([0,1]): a=abs(i+math.floor(random.randrange(2)))\n else: a=abs(i-math.floor(random.randrange(2)))\n a=9 if a>9 else 0 if a<0 else a\n newbase.append(a)\n previousline=newbase\n firebase=newbase\n\n for i in range(5):\n actualline=[]\n for j in range(5):\n lvl=adjust((previousline[j]+previousline[j+1])/3)-1 if j==0 else adjust((previousline[j]+previousline[j-1])/3)-1 if j==4 else adjust((previousline[j-1]+previousline[j]+previousline[j+1])/3)-1\n if lvl<0:lvl=0\n actualline.append(lvl)\n microbit.display.set_pixel(j,4-i,lvl)\n previousline=actualline\n\nwhile 1:\n fire()\n microbit.sleep(50)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"136600724","text":"import logging\nimport os\n\nlogger = logging.getLogger('spotipy.frontends.mpris')\n\nimport dbus\nimport dbus.mainloop.glib\nimport dbus.service\n\nfrom pykka.registry import ActorRegistry\n\nimport spotipy\nfrom spotipy import settings\nimport time\n\n# Must be done before dbus.SessionBus() is called\ndbus.mainloop.glib.threads_init()\ndbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\nBUS_NAME = 'org.mpris.MediaPlayer2.spotipy'\nOBJECT_PATH = '/org/mpris/MediaPlayer2'\nROOT_IFACE = 'org.mpris.MediaPlayer2'\nPLAYER_IFACE = 'org.mpris.MediaPlayer2.Player'\n\nclass MprisObject(dbus.service.Object):\n \"\"\"Implements http://www.mpris.org/2.1/spec/\"\"\"\n\n properties = None\n\n def __init__(self):\n self._backend = None\n #self._mixer = None\n self.properties = {\n ROOT_IFACE: self._get_root_iface_properties(),\n PLAYER_IFACE: self._get_player_iface_properties(),\n }\n bus_name = self._connect_to_dbus()\n super(MprisObject, self).__init__(bus_name, OBJECT_PATH)\n\n # init key handling\n logger.debug (u'Finding Spotipy...')\n session_bus = dbus.SessionBus();\n spotipy_bus = session_bus.get_object(\"org.mpris.MediaPlayer2.spotipy\", \"/org/mpris/MediaPlayer2\")\n self.spotipy = dbus.Interface(session_bus, \"org.mpris.MediaPlayer2.Player\")\n\n logger.debug (u'Connect to MediaKeys...')\n bus = session_bus.get_object(\"org.gnome.SettingsDaemon\", \"/org/gnome/SettingsDaemon/MediaKeys\")\n bus.connect_to_signal(\"MediaPlayerKeyPressed\", self.key_pressed)\n self.mediakeys = dbus.Interface(bus, \"org.gnome.SettingsDaemon.MediaKeys\")\n self.mediakeys.GrabMediaPlayerKeys(\"spotipy\", time.time())\n\n def key_pressed(self, *keys):\n if self.spotipy:\n for key in keys:\n if key == \"\":\n pass\n\n elif key == \"Play\":\n self.PlayPause()\n \n elif key == \"Pause\":\n self.PlayPause()\n\n elif key == \"Stop\":\n self.Stop()\n\n elif key == \"Next\":\n self.Next()\n\n elif key == \"Previous\":\n self.Previous()\n\n def _get_root_iface_properties(self):\n return {\n 'CanQuit': (True, None),\n 'CanRaise': (True, None),\n # NOTE Change if adding optional track list support\n 'HasTrackList': (False, None),\n 'Identity': ('SpotiPy', None),\n 'DesktopEntry': (self.get_DesktopEntry, None),\n 'SupportedUriSchemes': (dbus.Array([], signature='s'), None),\n #'SupportedUriSchemes': (self.get_SupportedUriSchemes, None),\n # NOTE Return MIME types supported by local backend if support for\n # reporting supported MIME types is added\n 'SupportedMimeTypes': (dbus.Array([], signature='s'), None),\n }\n\n def _get_player_iface_properties(self):\n return {\n 'PlaybackStatus': (self.get_PlaybackStatus, None),\n 'LoopStatus': (self.get_LoopStatus, self.set_LoopStatus),\n 'Rate': (1.0, self.set_Rate),\n 'Shuffle': (self.get_Shuffle, self.set_Shuffle),\n #'Metadata': (self.get_Metadata, None),\n #'Volume': (self.get_Volume, self.set_Volume),\n #'Position': (self.get_Position, None),\n 'MinimumRate': (1.0, None),\n 'MaximumRate': (1.0, None),\n 'CanGoNext': (self.get_CanGoNext, None),\n 'CanGoPrevious': (self.get_CanGoPrevious, None),\n 'CanPlay': (self.get_CanPlay, None),\n 'CanPause': (self.get_CanPause, None),\n #'CanSeek': (self.get_CanSeek, None),\n 'CanControl': (self.get_CanControl, None),\n }\n\n def _connect_to_dbus(self):\n logger.debug(u'Connecting to D-Bus...')\n bus_name = dbus.service.BusName(BUS_NAME, dbus.SessionBus())\n logger.info(u'Connected to D-Bus')\n return bus_name\n\n @property\n def backend(self):\n if self._backend is None:\n #backend_refs = ActorRegistry.get_by_class(Backend)\n #assert len(backend_refs) == 1, \\\n # 'Expected exactly one running backend.'\n #self._backend = backend_refs[0].proxy()\n self._backend = spotipy.settings._PLAYER\n return self._backend\n\n #@property\n #def mixer(self):\n # if self._mixer is None:\n # mixer_refs = ActorRegistry.get_by_class(BaseMixer)\n # assert len(mixer_refs) == 1, 'Expected exactly one running mixer.'\n # self._mixer = mixer_refs[0].proxy()\n # return self._mixer\n\n def _get_track_id(self, cp_track):\n return '/com/spotipy/track/%d' % cp_track.cpid\n\n def _get_cpid(self, track_id):\n assert track_id.startswith('/com/spotipy/track/')\n return track_id.split('/')[-1]\n\n ### Properties interface\n\n @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE,\n in_signature='ss', out_signature='v')\n def Get(self, interface, prop):\n logger.debug(u'%s.Get(%s, %s) called',\n dbus.PROPERTIES_IFACE, repr(interface), repr(prop))\n (getter, setter) = self.properties[interface][prop]\n if callable(getter):\n return getter()\n else:\n return getter\n\n @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE,\n in_signature='s', out_signature='a{sv}')\n def GetAll(self, interface):\n logger.debug(u'%s.GetAll(%s) called',\n dbus.PROPERTIES_IFACE, repr(interface))\n getters = {}\n for key, (getter, setter) in self.properties[interface].iteritems():\n getters[key] = getter() if callable(getter) else getter\n return getters\n\n @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE,\n in_signature='ssv', out_signature='')\n def Set(self, interface, prop, value):\n logger.debug(u'%s.Set(%s, %s, %s) called',\n dbus.PROPERTIES_IFACE, repr(interface), repr(prop), repr(value))\n getter, setter = self.properties[interface][prop]\n if setter is not None:\n setter(value)\n self.PropertiesChanged(interface,\n {prop: self.Get(interface, prop)}, [])\n\n @dbus.service.signal(dbus_interface=dbus.PROPERTIES_IFACE,\n signature='sa{sv}as')\n def PropertiesChanged(self, interface, changed_properties,\n invalidated_properties):\n logger.debug(u'%s.PropertiesChanged(%s, %s, %s) signaled',\n dbus.PROPERTIES_IFACE, interface, changed_properties,\n invalidated_properties)\n\n\n ### Root interface methods\n\n @dbus.service.method(dbus_interface=ROOT_IFACE)\n def Raise(self):\n logger.debug(u'%s.Raise called', ROOT_IFACE)\n self.backend.show()\n # Do nothing, as we do not have a GUI\n\n @dbus.service.method(dbus_interface=ROOT_IFACE)\n def Quit(self):\n logger.debug(u'%s.Quit called', ROOT_IFACE)\n self.backend.quit(None)\n #exit_process()\n\n\n ### Root interface properties\n\n def get_DesktopEntry(self):\n return os.path.splitext(os.path.basename(settings.DESKTOP_FILE))[0]\n\n def get_SupportedUriSchemes(self):\n return dbus.Array(self.backend.uri_schemes.get(), signature='s')\n\n\n ### Player interface methods\n\n @dbus.service.method(dbus_interface=PLAYER_IFACE)\n def Next(self):\n logger.debug(u'%s.Next called', PLAYER_IFACE)\n if not self.get_CanGoNext():\n logger.debug(u'%s.Next not allowed', PLAYER_IFACE)\n return\n self.backend.next()\n\n @dbus.service.method(dbus_interface=PLAYER_IFACE)\n def Previous(self):\n logger.debug(u'%s.Previous called', PLAYER_IFACE)\n if not self.get_CanGoPrevious():\n logger.debug(u'%s.Previous not allowed', PLAYER_IFACE)\n return\n self.backend.prev()\n\n @dbus.service.method(dbus_interface=PLAYER_IFACE)\n def Pause(self):\n logger.debug(u'%s.Pause called', PLAYER_IFACE)\n self.backend.playpause()\n\n @dbus.service.method(dbus_interface=PLAYER_IFACE)\n def PlayPause(self):\n logger.debug(u'%s.PlayPause called', PLAYER_IFACE)\n self.backend.playpause()\n\n @dbus.service.method(dbus_interface=PLAYER_IFACE)\n def Stop(self):\n logger.debug(u'%s.Stop called', PLAYER_IFACE)\n if not self.get_CanControl():\n logger.debug(u'%s.Stop not allowed', PLAYER_IFACE)\n return\n self.backend.stop()\n\n @dbus.service.method(dbus_interface=PLAYER_IFACE)\n def Play(self):\n logger.debug(u'%s.Play called', PLAYER_IFACE)\n if not self.get_CanPlay():\n logger.debug(u'%s.Play not allowed', PLAYER_IFACE)\n return\n #state = self.backend.playback.state.get()\n #if state == PlaybackController.PAUSED:\n # self.backend.playback.resume().get()\n #else:\n # self.backend.playback.play().get()\n\n @dbus.service.method(dbus_interface=PLAYER_IFACE)\n def Seek(self, offset):\n logger.debug(u'%s.Seek called', PLAYER_IFACE)\n if not self.get_CanSeek():\n logger.debug(u'%s.Seek not allowed', PLAYER_IFACE)\n return\n #offset_in_milliseconds = offset // 1000\n #current_position = self.backend.playback.time_position.get()\n #new_position = current_position + offset_in_milliseconds\n #self.backend.seek(new_position)\n\n @dbus.service.method(dbus_interface=PLAYER_IFACE)\n def SetPosition(self, track_id, position):\n logger.debug(u'%s.SetPosition called', PLAYER_IFACE)\n if not self.get_CanSeek():\n logger.debug(u'%s.SetPosition not allowed', PLAYER_IFACE)\n return\n position = position // 1000\n #current_cp_track = self.backend.playback.current_cp_track.get()\n #if current_cp_track is None:\n # return\n #if track_id != self._get_track_id(current_cp_track):\n # return\n #if position < 0:\n # return\n #if current_cp_track.track.length < position:\n # return\n #self.backend.playback.seek(position)\n\n @dbus.service.method(dbus_interface=PLAYER_IFACE)\n def OpenUri(self, uri):\n logger.debug(u'%s.OpenUri called', PLAYER_IFACE)\n if not self.get_CanPlay():\n # NOTE The spec does not explictly require this check, but guarding\n # the other methods doesn't help much if OpenUri is open for use.\n logger.debug(u'%s.Play not allowed', PLAYER_IFACE)\n return\n ## NOTE Check if URI has MIME type known to the backend, if MIME support\n ## is added to the backend.\n #uri_schemes = self.backend.uri_schemes.get()\n #if not any([uri.startswith(uri_scheme) for uri_scheme in uri_schemes]):\n # return\n #track = self.backend.library.lookup(uri).get()\n #if track is not None:\n # cp_track = self.backend.current_playlist.add(track).get()\n # self.backend.playback.play(cp_track)\n #else:\n # logger.debug(u'Track with URI \"%s\" not found in library.', uri)\n\n\n ### Player interface signals\n\n @dbus.service.signal(dbus_interface=PLAYER_IFACE, signature='x')\n def Seeked(self, position):\n logger.debug(u'%s.Seeked signaled', PLAYER_IFACE)\n # Do nothing, as just calling the method is enough to emit the signal.\n\n\n ### Player interface properties\n\n def get_PlaybackStatus(self):\n state = self.backend.playback.state.get()\n if state == PlaybackController.PLAYING:\n return 'Playing'\n elif state == PlaybackController.PAUSED:\n return 'Paused'\n elif state == PlaybackController.STOPPED:\n return 'Stopped'\n\n def get_LoopStatus(self):\n #repeat = self.backend.playback.repeat.get()\n #single = self.backend.playback.single.get()\n #if not repeat:\n # return 'None'\n #else:\n # if single:\n # return 'Track'\n # else:\n # return 'Playlist'\n return 'None'\n\n def set_LoopStatus(self, value):\n if not self.get_CanControl():\n logger.debug(u'Setting %s.LoopStatus not allowed', PLAYER_IFACE)\n return\n #if value == 'None':\n # self.backend.playback.repeat = False\n # self.backend.playback.single = False\n #elif value == 'Track':\n # self.backend.playback.repeat = True\n # self.backend.playback.single = True\n #elif value == 'Playlist':\n # self.backend.playback.repeat = True\n # self.backend.playback.single = False\n\n def set_Rate(self, value):\n if not self.get_CanControl():\n # NOTE The spec does not explictly require this check, but it was\n # added to be consistent with all the other property setters.\n logger.debug(u'Setting %s.Rate not allowed', PLAYER_IFACE)\n return\n if value == 0:\n self.Pause()\n\n def get_Shuffle(self):\n return self.backend.get_shuffle()\n\n def set_Shuffle(self, value):\n #if not self.get_CanControl():\n # logger.debug(u'Setting %s.Shuffle not allowed', PLAYER_IFACE)\n # return\n #if value:\n # self.backend.playback.random = True\n #else:\n # self.backend.playback.random = False\n self.backend.set_shuffle(value)\n\n def get_Metadata(self):\n current_cp_track = self.backend.playback.current_cp_track.get()\n if current_cp_track is None:\n return {'mpris:trackid': ''}\n else:\n (cpid, track) = current_cp_track\n metadata = {'mpris:trackid': self._get_track_id(current_cp_track)}\n if track.length:\n metadata['mpris:length'] = track.length * 1000\n if track.uri:\n metadata['xesam:url'] = track.uri\n if track.name:\n metadata['xesam:title'] = track.name\n if track.artists:\n artists = list(track.artists)\n artists.sort(key=lambda a: a.name)\n metadata['xesam:artist'] = dbus.Array(\n [a.name for a in artists if a.name], signature='s')\n if track.album and track.album.name:\n metadata['xesam:album'] = track.album.name\n if track.album and track.album.artists:\n artists = list(track.album.artists)\n artists.sort(key=lambda a: a.name)\n metadata['xesam:albumArtist'] = dbus.Array(\n [a.name for a in artists if a.name], signature='s')\n if track.track_no:\n metadata['xesam:trackNumber'] = track.track_no\n return dbus.Dictionary(metadata, signature='sv')\n\n #def get_Volume(self):\n # volume = self.mixer.volume.get()\n # if volume is not None:\n # return volume / 100.0\n\n #def set_Volume(self, value):\n # if not self.get_CanControl():\n # logger.debug(u'Setting %s.Volume not allowed', PLAYER_IFACE)\n # return\n # if value is None:\n # return\n # elif value < 0:\n # self.mixer.volume = 0\n # elif value > 1:\n # self.mixer.volume = 100\n # elif 0 <= value <= 1:\n # self.mixer.volume = int(value * 100)\n\n def get_Position(self):\n #return self.backend.playback.time_position.get() * 1000\n return 0\n\n def get_CanGoNext(self):\n return True\n #if not self.get_CanControl():\n # return False\n #return (self.backend.playback.cp_track_at_next.get() !=\n # self.backend.playback.current_cp_track.get())\n\n def get_CanGoPrevious(self):\n return True\n #if not self.get_CanControl():\n # return False\n #return (self.backend.playback.cp_track_at_previous.get() !=\n # self.backend.playback.current_cp_track.get())\n\n def get_CanPlay(self):\n return True\n #if not self.get_CanControl():\n # return False\n #return (self.backend.playback.current_track.get() is not None\n # or self.backend.playback.track_at_next.get() is not None)\n\n def get_CanPause(self):\n #if not self.get_CanControl():\n # return False\n # NOTE Should be changed to vary based on capabilities of the current\n # track if SpotiPy starts supporting non-seekable media, like streams.\n return True\n\n def get_CanSeek(self):\n #if not self.get_CanControl():\n # return False\n # NOTE Should be changed to vary based on capabilities of the current\n # track if SpotiPy starts supporting non-seekable media, like streams.\n return False\n\n def get_CanControl(self):\n # NOTE This could be a setting for the end user to change.\n return True\n","sub_path":"spotipy/frontends/mpris/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":16907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"357734756","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2015 Red Hat\n# Licensed under The MIT License (MIT)\n# http://opensource.org/licenses/MIT\n#\nfrom pdc_client.test_helpers import CLITestCase\nfrom pdc_client.runner import Runner\n\n\nclass RpmTestCase(CLITestCase):\n def setUp(self):\n self.runner = Runner()\n self.runner.setup()\n\n def test_list_without_filters(self, api):\n with self.expect_failure():\n self.runner.run(['rpm', 'list'])\n\n def _setup_list(self, api):\n api.add_endpoint('rpms', 'GET', [\n {'id': x,\n 'name': 'bash',\n 'epoch': 0,\n 'version': '4.3.42',\n 'release': x,\n 'arch': 'x86_64'}\n for x in range(1, 30)\n ])\n\n def test_list(self, api):\n self._setup_list(api)\n with self.expect_output('list.txt'):\n self.runner.run(['rpm', 'list', '--name', 'bash'])\n self.assertEqual(api.calls['rpms'],\n [('GET', {'page': 1, 'name': 'bash'}),\n ('GET', {'page': 2, 'name': 'bash'})])\n\n def test_list_json(self, api):\n self._setup_list(api)\n with self.expect_output('list.json', parse_json=True):\n self.runner.run(['--json', 'rpm', 'list', '--name', 'bash'])\n self.assertEqual(api.calls['rpms'],\n [('GET', {'page': 1, 'name': 'bash'}),\n ('GET', {'page': 2, 'name': 'bash'})])\n\n def _setup_detail(self, api):\n obj = {\n 'id': 1,\n 'name': 'bash',\n 'epoch': 0,\n 'version': '4.3.42',\n 'release': 1,\n 'arch': 'x86_64',\n 'srpm_name': 'bash',\n 'srpm_nevra': 'bash-4.3.42-1.src',\n 'filename': 'bash-0:4.3.42-1.x86_64.rpm',\n 'linked_composes': ['compose-1'],\n 'linked_releases': ['release-1'],\n 'dependencies': {\n 'requires': ['glibc > 0'],\n 'obsoletes': [],\n 'recommends': [],\n 'suggests': [],\n 'conflicts': [],\n 'provides': [],\n }\n }\n api.add_endpoint('rpms/1', 'GET', obj)\n api.add_endpoint('rpms/1', 'PATCH', obj)\n api.add_endpoint('rpms', 'POST', obj)\n\n def test_info(self, api):\n self._setup_detail(api)\n with self.expect_output('info.txt'):\n self.runner.run(['rpm', 'info', '1'])\n self.assertEqual(api.calls['rpms/1'], [('GET', {})])\n\n def test_info_json(self, api):\n self._setup_detail(api)\n with self.expect_output('info.json', parse_json=True):\n self.runner.run(['--json', 'rpm', 'info', '1'])\n self.assertEqual(api.calls['rpms/1'], [('GET', {})])\n\n def test_create(self, api):\n self._setup_detail(api)\n with self.expect_output('info.txt'):\n self.runner.run(['rpm', 'create',\n '--name', 'bash',\n '--srpm-name', 'bash',\n '--epoch', '0',\n '--version', '4.3.42',\n '--arch', 'x86_64',\n '--release', '1'])\n self.assertEqual(api.calls['rpms'],\n [('POST', {'name': 'bash', 'srpm_name': 'bash', 'arch': 'x86_64',\n 'epoch': 0, 'version': '4.3.42', 'release': '1'})])\n self.assertEqual(api.calls['rpms/1'],\n [('GET', {})])\n\n def test_update(self, api):\n self._setup_detail(api)\n with self.expect_output('info.txt'):\n self.runner.run(['rpm', 'update', '1',\n '--name', 'bash',\n '--srpm-name', 'bash',\n '--epoch', '0',\n '--version', '4.3.42',\n '--release', '1'])\n self.assertEqual(api.calls['rpms/1'],\n [('PATCH', {'name': 'bash', 'srpm_name': 'bash',\n 'epoch': 0, 'version': '4.3.42', 'release': '1'}),\n ('GET', {})])\n","sub_path":"tests/rpm/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"52982553","text":"#!/usr/bin/env python3\n'''\nTake from snakemake documentation\nhttps://snakemake.readthedocs.io/en/stable/tutorial/additional_features.html#using-cluster-status\n\n'''\nimport sys\nimport subprocess\nif len(sys.argv) < 5:\n print(\"failed\")\nelse:\n jobid = sys.argv[4]\n\n cmd = \"sacct -j %s --format State --noheader | head -1 | awk '{print $1}'\" % jobid\n output = str(subprocess.check_output(cmd, shell=True).strip())\n\n running_status=[\"PENDING\", \"CONFIGURING\", \"COMPLETING\", \"RUNNING\", \"SUSPENDED\"]\n failed_status=[\"FAILED\", \"OUT_OF_MEMORY\", \"TIMEOUT\", \"CANCELLED\", \"BOOT_FAIL\", \"DEADLINE\", \"NODE_FAIL\", \"PREEMPTED\"]\n if \"COMPLETED\" in output:\n print(\"success\")\n elif any(r in output for r in failed_status):\n print(\"failed\")\n else:\n print(\"running\")\n","sub_path":"odybcl2fastq/profiles/rc_slurm/cluster_status.py","file_name":"cluster_status.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"171979811","text":"import boto3\nsns = boto3.client('sns')\n# Publish a simple message to the specified SNS topic\nresponse = sns.publish(\n TopicArn='arn:aws:sns:us-east-2:101048863733:alerts',\n Message='Hello World', \n)\n\n# Print out the response\nprint(response)","sub_path":"aws-spark/aws-spark/snspublish.py","file_name":"snspublish.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"35174915","text":"import logging\nimport textwrap\nimport typing as t\nfrom datetime import datetime\n\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom bot import constants\nfrom bot.bot import Bot\nfrom bot.converters import Expiry, InfractionSearchQuery, allowed_strings, proxy_user\nfrom bot.pagination import LinePaginator\nfrom bot.utils import time\nfrom bot.utils.checks import in_whitelist_check, with_role_check\nfrom . import utils\nfrom .infractions import Infractions\nfrom .modlog import ModLog\n\nlog = logging.getLogger(__name__)\n\n\nclass ModManagement(commands.Cog):\n \"\"\"Management of infractions.\"\"\"\n\n category = \"Moderation\"\n\n def __init__(self, bot: Bot):\n self.bot = bot\n\n @property\n def mod_log(self) -> ModLog:\n \"\"\"Get currently loaded ModLog cog instance.\"\"\"\n return self.bot.get_cog(\"ModLog\")\n\n @property\n def infractions_cog(self) -> Infractions:\n \"\"\"Get currently loaded Infractions cog instance.\"\"\"\n return self.bot.get_cog(\"Infractions\")\n\n # region: Edit infraction commands\n\n @commands.group(name='infraction', aliases=('infr', 'infractions', 'inf'), invoke_without_command=True)\n async def infraction_group(self, ctx: Context) -> None:\n \"\"\"Infraction manipulation commands.\"\"\"\n await ctx.send_help(ctx.command)\n\n @infraction_group.command(name='edit')\n async def infraction_edit(\n self,\n ctx: Context,\n infraction_id: t.Union[int, allowed_strings(\"l\", \"last\", \"recent\")], # noqa: F821\n duration: t.Union[Expiry, allowed_strings(\"p\", \"permanent\"), None], # noqa: F821\n *,\n reason: str = None\n ) -> None:\n \"\"\"\n Edit the duration and/or the reason of an infraction.\n\n Durations are relative to the time of updating and should be appended with a unit of time.\n Units (∗case-sensitive):\n \\u2003`y` - years\n \\u2003`m` - months∗\n \\u2003`w` - weeks\n \\u2003`d` - days\n \\u2003`h` - hours\n \\u2003`M` - minutes∗\n \\u2003`s` - seconds\n\n Use \"l\", \"last\", or \"recent\" as the infraction ID to specify that the most recent infraction\n authored by the command invoker should be edited.\n\n Use \"p\" or \"permanent\" to mark the infraction as permanent. Alternatively, an ISO 8601\n timestamp can be provided for the duration.\n \"\"\"\n if duration is None and reason is None:\n # Unlike UserInputError, the error handler will show a specified message for BadArgument\n raise commands.BadArgument(\"Neither a new expiry nor a new reason was specified.\")\n\n # Retrieve the previous infraction for its information.\n if isinstance(infraction_id, str):\n params = {\n \"actor__id\": ctx.author.id,\n \"ordering\": \"-inserted_at\"\n }\n infractions = await self.bot.api_client.get(\"bot/infractions\", params=params)\n\n if infractions:\n old_infraction = infractions[0]\n infraction_id = old_infraction[\"id\"]\n else:\n await ctx.send(\n \":x: Couldn't find most recent infraction; you have never given an infraction.\"\n )\n return\n else:\n old_infraction = await self.bot.api_client.get(f\"bot/infractions/{infraction_id}\")\n\n request_data = {}\n confirm_messages = []\n log_text = \"\"\n\n if duration is not None and not old_infraction['active']:\n if reason is None:\n await ctx.send(\":x: Cannot edit the expiration of an expired infraction.\")\n return\n confirm_messages.append(\"expiry unchanged (infraction already expired)\")\n elif isinstance(duration, str):\n request_data['expires_at'] = None\n confirm_messages.append(\"marked as permanent\")\n elif duration is not None:\n request_data['expires_at'] = duration.isoformat()\n expiry = time.format_infraction_with_duration(request_data['expires_at'])\n confirm_messages.append(f\"set to expire on {expiry}\")\n else:\n confirm_messages.append(\"expiry unchanged\")\n\n if reason:\n request_data['reason'] = reason\n confirm_messages.append(\"set a new reason\")\n log_text += f\"\"\"\n Previous reason: {old_infraction['reason']}\n New reason: {reason}\n \"\"\".rstrip()\n else:\n confirm_messages.append(\"reason unchanged\")\n\n # Update the infraction\n new_infraction = await self.bot.api_client.patch(\n f'bot/infractions/{infraction_id}',\n json=request_data,\n )\n\n # Re-schedule infraction if the expiration has been updated\n if 'expires_at' in request_data:\n # A scheduled task should only exist if the old infraction wasn't permanent\n if old_infraction['expires_at']:\n self.infractions_cog.cancel_task(new_infraction['id'])\n\n # If the infraction was not marked as permanent, schedule a new expiration task\n if request_data['expires_at']:\n self.infractions_cog.schedule_task(new_infraction['id'], new_infraction)\n\n log_text += f\"\"\"\n Previous expiry: {old_infraction['expires_at'] or \"Permanent\"}\n New expiry: {new_infraction['expires_at'] or \"Permanent\"}\n \"\"\".rstrip()\n\n changes = ' & '.join(confirm_messages)\n await ctx.send(f\":ok_hand: Updated infraction #{infraction_id}: {changes}\")\n\n # Get information about the infraction's user\n user_id = new_infraction['user']\n user = ctx.guild.get_member(user_id)\n\n if user:\n user_text = f\"{user.mention} (`{user.id}`)\"\n thumbnail = user.avatar_url_as(static_format=\"png\")\n else:\n user_text = f\"`{user_id}`\"\n thumbnail = None\n\n # The infraction's actor\n actor_id = new_infraction['actor']\n actor = ctx.guild.get_member(actor_id) or f\"`{actor_id}`\"\n\n await self.mod_log.send_log_message(\n icon_url=constants.Icons.pencil,\n colour=discord.Colour.blurple(),\n title=\"Infraction edited\",\n thumbnail=thumbnail,\n text=textwrap.dedent(f\"\"\"\n Member: {user_text}\n Actor: {actor}\n Edited by: {ctx.message.author}{log_text}\n \"\"\")\n )\n\n # endregion\n # region: Search infractions\n\n @infraction_group.group(name=\"search\", invoke_without_command=True)\n async def infraction_search_group(self, ctx: Context, query: InfractionSearchQuery) -> None:\n \"\"\"Searches for infractions in the database.\"\"\"\n if isinstance(query, discord.User):\n await ctx.invoke(self.search_user, query)\n else:\n await ctx.invoke(self.search_reason, query)\n\n @infraction_search_group.command(name=\"user\", aliases=(\"member\", \"id\"))\n async def search_user(self, ctx: Context, user: t.Union[discord.User, proxy_user]) -> None:\n \"\"\"Search for infractions by member.\"\"\"\n infraction_list = await self.bot.api_client.get(\n 'bot/infractions',\n params={'user__id': str(user.id)}\n )\n embed = discord.Embed(\n title=f\"Infractions for {user} ({len(infraction_list)} total)\",\n colour=discord.Colour.orange()\n )\n await self.send_infraction_list(ctx, embed, infraction_list)\n\n @infraction_search_group.command(name=\"reason\", aliases=(\"match\", \"regex\", \"re\"))\n async def search_reason(self, ctx: Context, reason: str) -> None:\n \"\"\"Search for infractions by their reason. Use Re2 for matching.\"\"\"\n infraction_list = await self.bot.api_client.get(\n 'bot/infractions',\n params={'search': reason}\n )\n embed = discord.Embed(\n title=f\"Infractions matching `{reason}` ({len(infraction_list)} total)\",\n colour=discord.Colour.orange()\n )\n await self.send_infraction_list(ctx, embed, infraction_list)\n\n # endregion\n # region: Utility functions\n\n async def send_infraction_list(\n self,\n ctx: Context,\n embed: discord.Embed,\n infractions: t.Iterable[utils.Infraction]\n ) -> None:\n \"\"\"Send a paginated embed of infractions for the specified user.\"\"\"\n if not infractions:\n await ctx.send(\":warning: No infractions could be found for that query.\")\n return\n\n lines = tuple(\n self.infraction_to_string(infraction)\n for infraction in infractions\n )\n\n await LinePaginator.paginate(\n lines,\n ctx=ctx,\n embed=embed,\n empty=True,\n max_lines=3,\n max_size=1000\n )\n\n def infraction_to_string(self, infraction: utils.Infraction) -> str:\n \"\"\"Convert the infraction object to a string representation.\"\"\"\n actor_id = infraction[\"actor\"]\n guild = self.bot.get_guild(constants.Guild.id)\n actor = guild.get_member(actor_id)\n active = infraction[\"active\"]\n user_id = infraction[\"user\"]\n hidden = infraction[\"hidden\"]\n created = time.format_infraction(infraction[\"inserted_at\"])\n\n if active:\n remaining = time.until_expiration(infraction[\"expires_at\"]) or \"Expired\"\n else:\n remaining = \"Inactive\"\n\n if infraction[\"expires_at\"] is None:\n expires = \"*Permanent*\"\n else:\n date_from = datetime.strptime(created, time.INFRACTION_FORMAT)\n expires = time.format_infraction_with_duration(infraction[\"expires_at\"], date_from)\n\n lines = textwrap.dedent(f\"\"\"\n {\"**===============**\" if active else \"===============\"}\n Status: {\"__**Active**__\" if active else \"Inactive\"}\n User: {self.bot.get_user(user_id)} (`{user_id}`)\n Type: **{infraction[\"type\"]}**\n Shadow: {hidden}\n Reason: {infraction[\"reason\"] or \"*None*\"}\n Created: {created}\n Expires: {expires}\n Remaining: {remaining}\n Actor: {actor.mention if actor else actor_id}\n ID: `{infraction[\"id\"]}`\n {\"**===============**\" if active else \"===============\"}\n \"\"\")\n\n return lines.strip()\n\n # endregion\n\n # This cannot be static (must have a __func__ attribute).\n def cog_check(self, ctx: Context) -> bool:\n \"\"\"Only allow moderators inside moderator channels to invoke the commands in this cog.\"\"\"\n checks = [\n with_role_check(ctx, *constants.MODERATION_ROLES),\n in_whitelist_check(\n ctx,\n channels=constants.MODERATION_CHANNELS,\n categories=[constants.Categories.modmail],\n redirect=None,\n fail_silently=True,\n )\n ]\n return all(checks)\n\n # This cannot be static (must have a __func__ attribute).\n async def cog_command_error(self, ctx: Context, error: Exception) -> None:\n \"\"\"Send a notification to the invoking context on a Union failure.\"\"\"\n if isinstance(error, commands.BadUnionArgument):\n if discord.User in error.converters:\n await ctx.send(str(error.errors[0]))\n error.handled = True\n","sub_path":"bot/cogs/moderation/management.py","file_name":"management.py","file_ext":"py","file_size_in_byte":11482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"450569093","text":"# coding:utf-8\n\"\"\"\nAPI 解读过程\n1. 首先发现全国的URL列表存在位置在\n - https://static.122.gov.cn/V1.18.4/static/js/funcDistrict.js\n2. 针对单个zf机构的列表查询,我们可以发现。这里有一个列表和时间的查询。\n - https://{city_short}.122.gov.cn/m/viopub/getVioPubList\n - NOTE: city_short 对应的就是之前的bj、tj等(省市的缩写)\n3. 获取详情\n - NOTE: 针对每一个列表查看详情后, 可以得到一个详情介绍的Json(页面上渲染出的内容)\n - https://{city_short}.122.gov.cn/m/viopub/getVioPubDetail POST\n\"\"\"\nimport os\n\nimport json\nfrom requests.api import request\ntry:\n from .logger import Log\n logging = Log(log_flag='spyder_running_status')\nexcept:\n import logging\n\ntry:\n from .config import DUMP_DATA_DIR as dump_data_dir\nexcept:\n # TODO 如果本地并没有存储的相关配置,那么默认指定这个。\n dump_data_dir = 'd://results//'\n\n\nfrom .config import firefox_request\nrequest_headers = {x['name']: x['value'] for x in firefox_request['headers']}\nrequest_cookies = {x['name']: x['value'] for x in firefox_request['cookies']}\n\n\nclass ViopubSpyderApiManager():\n\n def __init__(self, city_short=None, vpid=None):\n self.city_short = city_short\n self.vpid = vpid\n\n @staticmethod\n def write_to_local(json_data, path):\n _txt = json_data\n if type(json_data) == dict:\n _txt = json.dumps(json_data)\n if not os.path.exists(os.path.dirname(path)):\n os.makedirs(os.path.dirname(path))\n with open(path, 'w+', encoding='utf-8') as f:\n f.write(_txt)\n f.close()\n\n @staticmethod\n def get_parse_header():\n from .request_tool import ParseReqHeader\n from .config import DEFAULT_HEADER_FILE_PATH\n return ParseReqHeader.parse1(file_path=DEFAULT_HEADER_FILE_PATH)\n\n @staticmethod\n def fetch_url(url, method='post', data=None,\n headers=request_headers, cookies=request_cookies, **kwargs):\n response = request(method=method, url=url,\n headers=headers, cookies=cookies,\n data=data, timeout=10, )\n status_code = response.status_code\n logging.warn('Prepare to Patch URL: {}'.format(url))\n if status_code != 200:\n logging.error('Headers Error [{code}] for Server. \\n{text}'.format(\n code=str(status_code), text=response.text))\n return None\n _res = json.loads(response.text)\n _status = _res.get('code')\n if _status != 200:\n logging.error('payload Error. {}'.format(response.text))\n return None\n return _res\n\n def get_list(self, page=2, save_local=True):\n _list_url = \"https://{city_short}.122.gov.cn/m/viopub/getVioPubList\".format(city_short=self.city_short)\n data = {\"page\": page, \"size\": 20, \"startTime\": \"&\", \"endTime\": \"&\", \"gsyw\": \"01\"}\n res_data = ViopubSpyderApiManager.fetch_url(url=_list_url, data=data)\n if not res_data:\n logging.error('REQUEST_DATA_ERROR: {}'.format(_list_url))\n return None\n if save_local:\n data_dump_dir = os.path.join(dump_data_dir, self.city_short, 'lists')\n _saved_path = os.path.join(data_dump_dir, 'list_page_{}.txt'.format(str(page)))\n ViopubSpyderApiManager.write_to_local(json_data=res_data, path=_saved_path)\n return res_data\n\n def get_detail(self, save_local=True):\n _detail_url = \"https://{city_short}.122.gov.cn/m/viopub/getVioPubDetail\".format(city_short=self.city_short)\n data = {'id': self.vpid}\n res_data = ViopubSpyderApiManager.fetch_url(url=_detail_url, data=data,\n headers={\"User-Agent\": \"Local Test\"},\n cookies=None)\n if not res_data:\n logging.error('REQUEST_DATA_ERROR: {}'.format(_detail_url))\n return None\n if save_local:\n data_dump_dir = os.path.join(dump_data_dir, self.city_short, 'details')\n _saved_path = os.path.join(data_dump_dir, '{}.txt'.format(str(self.vpid)))\n ViopubSpyderApiManager.write_to_local(json_data=res_data, path=_saved_path)\n return res_data\n\n\n# if __name__ == '__main__':\n# logging.warning('---------------------')\n# # _test = ViopubSpyderApiManager(city_short='hb', vpid='42000210000000373477').get_detail()\n# _test = ViopubSpyderApiManager(city_short='hb', vpid='42000210000000373477').get_list()\n# logging.warning(_test)","sub_path":"auxi/spy_utils/spyder.py","file_name":"spyder.py","file_ext":"py","file_size_in_byte":4631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"355102218","text":"# -*- encoding: utf-8 -*-\n#\n# Author: Endre Karlson \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.\nfrom pecan import expose, request\nimport wsme\nimport wsmeext.pecan as wsme_pecan\n\n\nfrom billingstack.api.base import Query, _query_to_criterion, RestController\nfrom billingstack.api.v2 import models\nfrom billingstack.central.rpcapi import central_api\n\n\nclass SubscriptionController(RestController):\n def __init__(self, id_):\n self.id_ = id_\n request.context['subscription_id'] = id_\n\n @wsme_pecan.wsexpose(models.Subscription)\n def get_all(self):\n row = central_api.get_subscription(request.ctxt, self.id_)\n\n return models.Subscription.from_db(row)\n\n @wsme.validate(models.Subscription)\n @wsme_pecan.wsexpose(models.Subscription, body=models.Subscription)\n def patch(self, body):\n row = central_api.update_subscription(request.ctxt, self.id_,\n body.to_db())\n\n return models.Subscription.from_db(row)\n\n @wsme_pecan.wsexpose(None, status_code=204)\n def delete(self):\n central_api.delete_subscription(request.ctxt, self.id_)\n\n\nclass SubscriptionsController(RestController):\n @expose()\n def _lookup(self, subscription_id, *remainder):\n return SubscriptionController(subscription_id), remainder\n\n @wsme.validate(models.Subscription)\n @wsme_pecan.wsexpose(models.Subscription, body=models.Subscription,\n status_code=202)\n def post(self, body):\n row = central_api.create_subscription(\n request.ctxt,\n request.context['merchant_id'],\n body.to_db())\n\n return models.Subscription.from_db(row)\n\n @wsme_pecan.wsexpose([models.Subscription], [Query])\n def get_all(self, q=[]):\n criterion = _query_to_criterion(\n q,\n merchant_id=request.context['merchant_id'])\n\n rows = central_api.list_subscriptions(\n request.ctxt, criterion=criterion)\n\n return map(models.Subscription.from_db, rows)\n","sub_path":"billingstack/api/v2/controllers/subscription.py","file_name":"subscription.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"441446263","text":"\"\"\"\ncollection of utility routines for use with other SOLPS modules\n\nSeveral routines that used to be here have simpler/more robust duplicates in common libraries\nI've left those routines below but commented them out and given a good replacement option\n\nA. Sontag, R.S. Wilcox 2019\n\"\"\"\n\nfrom os import path, system\nimport numpy as np\n\n\n# ----------------------------------------------------------------------------------------\n\ndef calcTanhMulti(c, x, param=None):\n \"\"\"\n tanh function with cubic or quartic inner and linear to quadratic outer extensions\n and derivative = 0 at param\n \n 0.5*(c[2]-c[3])*(pz1*exp(z)-pz2*exp(-z))/(exp(z)+exp(-z))+0.5*(c[2]+c[3])\n where z=2*(c[0]-x)/c[1]\n \n if param=None:\n pz1=1+c[4]*z+c[5]*z*z+c[6]*z*z*z\n else:\n pz1=1+cder*z+c[4]*z*z+c[5]*z*z*z+c[6]*z*z*z*z\n where cder=-(2.0*c[4]*z0+3.0*c[5]*z0*z0+4.0*c[6]*z0*z0*z0\n and z0=2.0*(c[0]-param)/c[1]\n \n pz2=1+(c[7]*z+c[8]*z*z) depending on whether there are 7, 8 or 9 coefs\n \n c0 = SYMMETRY POINT\n c1 = FULL WIDTH\n c2 = HEIGHT\n c3 = OFFSET\n c4 = SLOPE OR QUADRATIC (IF ZERO DERIV) INNER\n c5 = QUADRATIC OR CUBIC (IF ZERO DERIV) INNER\n c6 = CUBIC OR QUARTIC (IF ZERO DERIV) INNER\n c7 = SLOPE OF OUTER\n c8 = QUADRATIC OUTER\n \n ** translated from IDL by A. Sontag 4-4-18\n \"\"\"\n\n z = 2 * (c[0] - x) / c[1]\n out = np.zeros(len(z))\n\n if len(c) == 5:\n for i in range(0, len(z)):\n out[i] = 0.5 * (c[2] - c[3]) * ((1 + c[4] * z[i]) * np.exp(z[i]) - np.exp(-z[i])) / \\\n (np.exp(z[i]) + np.exp(-z[i])) + 0.5 * (c[2] + c[3])\n elif len(c) == 6:\n # pz1 = np.zeros(len(z))\n if param:\n z0 = 2 * (c[0] - param) / c[1]\n cder = -(2 * c[3] * z0 + 3 * c[4] * z0**2 + 4 * c[5] * z0**3)\n pz1 = 1 + cder * z + c[3] * z**2 + c[4] * z**3 + c[5] * z**4\n else:\n pz1 = 1 + c[3] * z + c[4] * z**2 + c[5] * z**3\n for i in range(0, len(z)):\n out[i] = 0.5*c[2]*(pz1[i]*np.exp(z[i]) - np.exp(-z[i])) / \\\n (np.exp(z[i]) + np.exp(-z[i])) + 0.5*c[2]\n else:\n # pz1 = np.zeros(len(z))\n if param:\n z0 = 2 * (c[0] - param) / c[1]\n cder = -(2 * c[4] * z0 + 3 * c[5] * z0**2 + 4 * c[6] * z0**3)\n pz1 = 1 + cder * z + c[4] * z**2 + c[5] * z**3 + c[6] * z**4\n else:\n pz1 = 1 + c[4] * z + c[5] * z**2 + c[6] * z**3\n\n pz2 = np.ones(len(z))\n if len(c) > 7: pz2 += c[7] * z\n if len(c) > 8: pz2 += c[8] * z**2\n\n for i in range(0, len(z)):\n out[i] = 0.5 * (c[2] - c[3]) * (pz1[i] * np.exp(z[i]) - pz2[i] * np.exp(-z[i])) / \\\n (np.exp(z[i]) + np.exp(-z[i])) + 0.5 * (c[2] + c[3])\n\n return out\n\n\n# ---------------------------------------------------------------------------------------- \n\ndef loadMDS(tree, tag, shot, quiet=True):\n import MDSplus\n\n c = MDSplus.Connection('atlas.gat.com')\n c.openTree(tree, shot)\n\n try:\n y = c.get(tag).data()\n except:\n print('invalid data for ' + tag)\n y = None\n\n try:\n x = c.get('DIM_OF(' + tag + ')').data()\n except:\n x = None\n\n try:\n yerr = c.get('ERROR_OF(' + tag + ')').data()\n except:\n yerr = None\n\n try:\n xerr = c.get('ERROR_OF(DIM_OF(' + tag + '))').data()\n except:\n xerr = None\n\n out = dict(x=x, y=y, xerr=xerr, yerr=yerr)\n\n if not quiet: print('done with ' + tag)\n\n return out\n\n\n# ----------------------------------------------------------------------------------------\n\ndef B2pl(cmds, wdir='.', debug=False):\n \"\"\"\n runs B2plot with the commands used in the call and reads contents of the resulting\n b2plot.write file into two lists\n \n ** Make sure you've sourced the setup script first, or this won't work! **\n ** Make sure B2PLOT_DEV is set to 'ps'\n \"\"\"\n\n if debug:\n cmdstr = 'echo \"' + cmds + '\" | b2plot'\n print(cmdstr)\n else:\n cmdstr = 'echo \"' + cmds + '\" | b2plot >&/dev/null'\n system(cmdstr)\n\n fname = path.join(wdir, 'b2pl.exe.dir', 'b2plot.write')\n x, y = [], []\n with open(fname) as f:\n lines = f.readlines()\n for line in lines:\n elements = line.split()\n if elements[0] == '#':\n pass\n else:\n x.append(float(elements[0]))\n y.append(float(elements[1]))\n x = x[0:(len(x) / 2)] # used to be: x=x[0:(len(x)/2)-1], chopped final value\n y = y[0:(len(y) / 2)]\n\n return x, y\n\n\n# ----------------------------------------------------------------------------------------\n\ndef readProf(fname, wdir='.'):\n \"\"\"\n reads contents of text file into two lists, returns them as numpy arrays\n \"\"\"\n\n fname = path.join(wdir, fname)\n x, y = [], []\n\n with open(fname) as f:\n lines = f.readlines()\n\n for line in lines:\n elements = line.split()\n\n if elements[0] == '#':\n pass\n else:\n x.append(float(elements[0]))\n y.append(float(elements[1]))\n\n return x, y\n\n\n# ----------------------------------------------------------------------------------------\n\ndef loadg(filename):\n infile = open(filename, 'r')\n lines = infile.readlines()\n\n # read first line for case string and grid size\n line = lines[0]\n words = line.split()\n\n nw = int(words[-2])\n nh = int(words[-1])\n psi = np.linspace(0, 1, nw)\n\n # read in scalar parameters\n # note: word size of 16 characters each is assumed for all of the data to be read\n\n # line 1\n line = lines[1]\n rdim = float(line[0:16])\n zdim = float(line[16:32])\n rcentr = float(line[32:48])\n rleft = float(line[48:64])\n zmid = float(line[64:80])\n\n # line 2\n line = lines[2]\n rmaxis = float(line[0:16])\n zmaxis = float(line[16:32])\n simag = float(line[32:48])\n sibry = float(line[48:64])\n bcentr = float(line[64:80])\n\n # line 3\n line = lines[3]\n current = float(line[0:16])\n\n # read in profiles\n # start by reading entire file into single list then split into individual profiles\n # first block has 5 profiles of length nw and one array of length nh*nw\n\n temp = []\n count = 0\n lnum = 5\n terms = 5 * nw + nw * nh\n while count < terms:\n line = lines[lnum]\n numchar = len(line)\n nwords = numchar / 16\n count1 = 0\n while count1 < nwords:\n i1 = count1 * 16\n i2 = i1 + 16\n temp.append(float(line[i1:i2]))\n count1 += 1\n count += 1\n lnum += 1\n\n fpol = temp[0:nw]\n pres = temp[nw:2 * nw]\n ffprime = temp[2 * nw:3 * nw]\n pprime = temp[3 * nw:4 * nw]\n psirz_temp = temp[4 * nw:(4 + nh) * nw]\n qpsi = temp[(4 + nh) * nw:]\n\n # split psirz up into 2D matrix\n count = 0\n psirz = []\n while count < nh:\n ind1 = count * nw\n ind2 = ind1 + nw\n psirz.append(psirz_temp[ind1:ind2])\n count += 1\n\n # scalars for length of boundary and limiter arrays\n line = lines[lnum]\n words = line.split()\n nbbbs = int(words[0])\n limitr = int(words[1])\n\n # read boundary and limiter points into temp array\n\n temp = []\n count = 0\n terms = 2 * (nbbbs + limitr)\n lnum += 1\n while count < terms:\n line = lines[lnum]\n numchar = len(line)\n nwords = numchar / 16\n count1 = 0\n while count1 < nwords:\n i1 = count1 * 16\n i2 = i1 + 16\n temp.append(float(line[i1:i2]))\n count1 += 1\n count += 1\n lnum += 1\n bdry_temp = temp[0:(2 * nbbbs)]\n limit_temp = temp[(2 * nbbbs):]\n\n # split boundary into (R,Z) pairs\n count = 0\n rbdry = []\n zbdry = []\n while count < len(bdry_temp) - 1:\n rbdry.append(bdry_temp[count])\n zbdry.append(bdry_temp[count + 1])\n count += 2\n\n # split limiter into (R,Z) pairs\n count = 0\n rlim = []\n zlim = []\n while count < len(limit_temp) - 1:\n rlim.append(limit_temp[count])\n zlim.append(limit_temp[count + 1])\n count += 2\n\n g = dict(nw=nw, nh=nh, rdim=rdim, zdim=zdim, rcentr=rcentr, rleft=rleft, zmid=zmid,\n rmaxis=rmaxis, zmaxis=zmaxis, simag=simag, sibry=sibry, current=current,\n fpol=np.array(fpol),\n ffprime=np.array(ffprime), pprime=np.array(pprime), psirz=np.array(psirz),\n qpsi=np.array(qpsi), nbbbs=nbbbs, bcentr=bcentr,\n pres=np.array(pres), limitr=limitr, rbdry=np.array(rbdry),\n zbdry=np.array(zbdry), rlim=np.array(rlim), zlim=np.array(zlim))\n\n return g\n\n\n# ----------------------------------------------------------------------------------------\n\ndef list2H5(data, pathname, outname):\n import h5py\n\n outname += '.h5'\n out = h5py.File(path.join(pathname, outname), 'w')\n\n var = data.keys()\n\n for v in var:\n vals = data[v]\n try:\n dset = out.create_dataset(v, np.shape(vals), 'f', compression='gzip', shuffle='true')\n dset[...] = vals\n except:\n pass\n\n out.close()\n\n\n# ----------------------------------------------------------------------------------------\n\n\ndef getProfDBPedFit(shotnum, timeid, runid, write_to_file=None):\n \"\"\"\n Loads saved data from Tom's tools MDSplus server\n 'XXdatpsi' : Raw data\n \n write_to_file: Give file name\n \"\"\"\n\n tree = 'profdb_ped'\n\n tagList = ['nedatpsi', 'tedatpsi', 'tidatpsi', 'netanhpsi', 'ttst',\n 'netanhpsi:fit_coef', 'tetanhpsi:fit_coef', 'titanhpsi:fit_coef',\n 'tisplpsi', 'ptotsplpsi', 'zfz1datpsi', 'zfz1splpsi']\n\n # tagList=['nedatpsi','tedatpsi','tidatpsi','netanhpsi','fzdatpsi','zfz1datpsi',\n # 'vtordatpsi','ttst','netnh0psi:fit_coef','netanhpsi:fit_coef','tetnh0psi:fit_coef',\n # 'tetanhpsi:fit_coef','titanhpsi:fit_coef','tisplpsi','ptotsplpsi','vtorsplpsi',\n # 'fzsplpsi','zfz1splpsi']\n\n profile_fits = {}\n tstr = ':p' + str(timeid) + '_' + runid + ':'\n for t in tagList:\n tag = tstr + t\n val = loadMDS(tree, tag, shotnum)\n if t[-9:] == ':fit_coef': t = t[:-9]\n profile_fits[t] = val\n\n if write_to_file is not None:\n import pickle\n\n with open(write_to_file, 'wb') as f:\n pickle.dump(profile_fits, f, pickle.HIGHEST_PROTOCOL)\n\n return profile_fits\n\n\n# ----------------------------------------------------------------------------------------\n\n\ndef read_pfile(pfile_loc):\n \"\"\"\n Read in the kinetic profiles from a p file to be used as inputs (successfully tested 2018/1/3)\n\n Returns a dictionary with a non-intuitive set of keys (units are included)\n \n ** Note: pfiles don't go into the SOL **\n \"\"\"\n with open(pfile_loc, mode='r') as pfile:\n lines = pfile.readlines()\n\n profiles = {}\n nprofs = 0 # counter for total number of profiles so far\n linestart = 0 # counter for which line to start at for each profile\n nlines_tot = len(lines)\n\n while True:\n # Read the header line for each profile first\n lin1 = lines[linestart].split()\n npts_prof = int(lin1[0])\n\n xname = lin1[1]\n yname = lin1[2]\n dyname = ''.join(lin1[3:])[:-1]\n\n # Generate and populate the profile arrays\n x = np.zeros(npts_prof)\n y = np.zeros(npts_prof)\n dy = np.zeros(npts_prof)\n for i in range(npts_prof):\n split_line = lines[linestart + i + 1].split()\n x[i] = float(split_line[0])\n y[i] = float(split_line[1])\n dy[i] = float(split_line[2][:-1])\n\n # profiles[xname + '_' + yname] = x # psinorm\n profiles[xname] = x\n profiles[yname] = y\n profiles[dyname] = dy\n\n nprofs += 1\n linestart += 1 + npts_prof\n\n if linestart >= nlines_tot:\n break\n\n # Check if all psinorms are the same, consolidate if so (they are, don't bother separating)\n\n # condense = True\n # psinorm = None\n # for k in profiles.keys():\n # if k is None or k=='':\n # continue\n #\n # if k[:4] == 'psin':\n # if psinorm is None:\n # psinorm = profiles[k]\n #\n # if max(abs(profiles[k] - psinorm)) > 1e-5:\n # condense = False\n # break\n\n # if condense:\n # profiles = {key: value for key, value in profiles.items()\n # if key[:4] != 'psin' or key is None or key==''}\n # profiles['psinorm'] = psinorm\n\n return profiles\n\n# ----------------------------------------------------------------------------------------\n\n\ndef read_b2_transport_inputfile(infileloc, carbon=True):\n \"\"\"\n Reads b2.transport.inputfile, outputs basic quantities as a dictionary\n \n All carbon species are assumed to have the same transport coefficients\n (this could be fixed easily if you want)\n \n !!!WARNING!!!\n This was only written to read inputfiles written using SOLPSxport.py,\n and therefore may not work properly if your file is formatted differently.\n \"\"\"\n with open(infileloc, 'r') as f:\n lines = f.readlines()\n\n ndata = int(\n lines[1].strip().split()[5]) # This is the same for every array in our write routine\n\n rn = np.zeros(ndata)\n dn = np.zeros(ndata)\n ke = np.zeros(ndata)\n ki = np.zeros(ndata)\n if carbon:\n vrc = np.zeros(ndata)\n dc = np.zeros(ndata)\n\n for line_full in lines[2:]:\n line = line_full.strip().split()\n if len(line) < 4: continue\n\n if line[2][0] == '1' and line[3][0] == '1':\n rn[int(line[1][:-1]) - 1] = np.float(line[5])\n dn[int(line[1][:-1]) - 1] = np.float(line[-2])\n\n elif line[2][0] == '3' and line[3][0] == '1':\n ki[int(line[1][:-1]) - 1] = np.float(line[-2])\n\n elif line[2][0] == '4' and line[3][0] == '1':\n ke[int(line[1][:-1]) - 1] = np.float(line[-2])\n\n elif carbon:\n\n if line[2][0] == '1' and line[3][0] == '4':\n dc[int(line[1][:-1]) - 1] = np.float(line[-2])\n\n elif line[2][0] == '6' and line[3][0] == '3':\n vrc[int(line[1][:-1]) - 1] = np.float(line[-2])\n\n if carbon:\n return {'rn': rn, 'dn': dn, 'ki': ki, 'ke': ke, 'dc': dc, 'vrc': vrc}\n else:\n return {'rn': rn, 'dn': dn, 'ki': ki, 'ke': ke}\n\n# ----------------------------------------------------------------------------------------\n\n\ndef read_b2fgmtry(fileloc):\n \"\"\"\n Modified from omfit_solps.py\n \"\"\"\n\n with open(fileloc, 'r') as f:\n tmp = f.read()\n tmp = tmp.replace('\\n', ' ')\n tmp = tmp.split(\"*c\")\n tmp = [[f for f in x.split(' ') if f] for x in tmp]\n\n m = {'int': int, 'real': float, 'char': str}\n\n b2fgmtry = {}\n\n for line in tmp[1:]:\n if len(line) > 4:\n b2fgmtry[line[3]] = np.array(list(map(m[line[1]], line[4:])))\n else:\n b2fgmtry[line[3]] = None\n\n return b2fgmtry\n\n# ----------------------------------------------------------------------------------------\n\n\ndef read_b2fstat(fileloc):\n \"\"\"\n Modified from omfit_solps.py\n \"\"\"\n with open(fileloc, 'r') as f:\n lines = f.readlines()\n\n b2fstat = {'__notes__': [], '__unhandled__': []}\n\n # Initialize\n data = np.array([])\n\n translations = {'real': 'float', 'char': 'str'}\n\n b2fstat['nx'], b2fstat['ny'], b2fstat['ns'] = 0, 0, 0\n\n def close_field():\n # Handle previous field\n if n > 0:\n print('Finishing previous field; dat_type = \"{}\", n = {}, ' +\n 'names = {}, len(names) = {}'.format(dat_type, n, names, len(names)))\n if len(names) == 1:\n # 2D arrays: X Y\n if n == (b2fstat['nx'] + 2) * (b2fstat['ny'] + 2):\n # This is an X by Y spatial array with guard cells\n b2fstat[names[0]] = data.reshape(-1, b2fstat['nx'] + 2)\n elif n == b2fstat['nx'] * b2fstat['ny']:\n # This is an X by Y spatial array with no guard cells\n b2fstat[names[0]] = data.reshape(-1, b2fstat['nx'])\n\n # 3D arrays - X Y S\n elif n == (b2fstat['nx'] + 2) * (b2fstat['ny'] + 2) * b2fstat['ns']:\n # This is an X by Y by species array with guard cells\n b2fstat[names[0]] = data.reshape(b2fstat['ns'], -1, b2fstat['nx'] + 2)\n elif n == (b2fstat['nx']) * (b2fstat['ny']) * b2fstat['ns']:\n # This is an X by Y by species array with no guard cells\n b2fstat[names[0]] = data.reshape(b2fstat['ns'], -1, b2fstat['nx'])\n\n # 3D arrays - X Y v\n # Page 183 of the 2015 Feb 27 SOLPS manual mentions \"fhe - (-1:nx, -1:ny, 0:1) real*8 array\n # I think there's a row major vs. column major difference going on or something, but anyway,\n # python gets the array out correctly if nx corresponds to the last axis when 2D, which is\n # the opposite of the documentation, so the v axis with length 2 should be the first axis in\n # python.\n elif n == (b2fstat['nx'] + 2) * (b2fstat['ny'] + 2) * 2:\n # This is an X by Y by 2 (probably poloidal & radial components) array w/ guard cells.\n b2fstat[names[0]] = data.reshape(2, -1, b2fstat['nx'] + 2)\n elif n == b2fstat['nx'] * b2fstat['ny'] * 2:\n # This is an X by Y by 2 (probably poloidal & radial components) array w/o guard cells.\n b2fstat[names[0]] = data.reshape(2, -1, b2fstat['nx'])\n\n # 4D arrays - X Y S v\n # Manual calls fna X Y v S, so it should be S v Y X here.\n elif n == (b2fstat['nx'] + 2) * (b2fstat['ny'] + 2) * b2fstat['ns'] * 2:\n # This is an X by Y by species by 2 array w/ guard cells.\n b2fstat[names[0]] = data.reshape(b2fstat['ns'], 2, -1, b2fstat['nx'] + 2)\n elif n == (b2fstat['nx']) * (b2fstat['ny']) * b2fstat['ns'] * 2:\n # This is an X by Y by species by 2 array w/o guard cells.\n b2fstat[names[0]] = data.reshape(b2fstat['ns'], 2, -1, b2fstat['nx'])\n\n else:\n # Can't identify higher dims of this or it is just 1D, so don't mess with it\n b2fstat[names[0]] = data\n elif len(names) == n:\n for ii, name in enumerate(names):\n b2fstat[name] = data[ii]\n else:\n print('WARNING! Problem parsing b2fstate or b2fstati in omfit_solps class: ' +\n 'Cannot handle more than one name unless length of names matches length' +\n ' of data!')\n b2fstat['__unhandled__'] += [{'names': names, 'data': data}]\n\n cflines = []\n for i, line in enumerate(lines):\n if line.startswith('*cf:'):\n cflines += [i]\n\n cflines += [len(lines)]\n\n if cflines[0] > 0:\n print(' Found header line(s), adding to notes: {}'.format(lines[: cflines[0]]))\n b2fstat['__notes__'] += [line.split('\\n')[0] for line in lines[: cflines[0]]]\n\n for i in range(len(cflines) - 1):\n print('Setting up field: {}'.format(lines[cflines[i]].split('\\n')[0]))\n dat_type_string = lines[cflines[i]].split()[1].strip()\n dat_type_string = translations.get(dat_type_string, dat_type_string)\n dat_type = eval(dat_type_string)\n n = int(lines[cflines[i]].split()[2])\n names = lines[cflines[i]].split()[3].split(',')\n print(' dat_type = \"{}\" / \"{}\", n = {}, names = {}, len(names) = {}'.format(\n dat_type_string, dat_type, n, names, len(names)),)\n\n raw = lines[cflines[i] + 1: cflines[i + 1]]\n if dat_type_string != 'char':\n data = np.array(' '.join(raw).split()).astype(dat_type)\n else:\n data = lines[cflines[i] + 1].split('\\n')[0][1:]\n close_field()\n\n return b2fstat\n\n\n# ----------------------------------------------------------------------------------------\n# def shift(arr,ns):\n# \"\"\"\n# Use np.roll for this instead ('append' doesn't work for numpy arrays)\n# 2nd argument needs to be opposite for np.roll (2 --> -2)\n# \"\"\"\n# print(\"Use np.roll instead of this custom 'shift' routine\")\n# new_arr=arr[ns:]\n# for e in arr[:ns]:\n# new_arr.append(e)\n#\n# return new_arr\n#\n# ----------------------------------------------------------------------------------------\n# def deriv(x,y):\n# \"\"\"\n# This function duplicates the deriv finite differencing function from IDL\n#\n# Use np.gradient(y) / np.gradient(x) instead of this, it handles end indeces properly\n# \"\"\"\n#\n# xx = np.array(x)\n# y = np.array(y)\n#\n# x12 = xx - np.roll(xx,1)\n# x01 = np.roll(xx,-1) - xx\n# x02 = np.roll(xx,-1) - np.roll(xx,1)\n#\n# d = np.roll(y,-1)*(x12/(x01*x02))+y*(1/x12-1/x01)-np.roll(y,1)*(x01/(x02*x12))\n#\n# # x12 = xx - shift(xx,-1)\n# # x01 = shift(xx,1) - xx\n# # x02 = shift(xx,1) - shift(xx,-1)\n#\n# # d = shift(y,1)*(x12/(x01*x02))+y*(1/x12-1/x01)-shift(y,-1)*(x01/(x02*x12))\n# d[0]=y[0]*(x01[1]+x02[1])/(x01[1]*x02[1])-y[1]*x02[1]/(x01[1]*x12[1])+y[2]*x01[1]/(x02[1]*x12[1])\n# d[-1]=y[-3]*x12[-2]/(x01[-2]*x02[-2])+y[-2]*x02[-2]/(x01[-2]*x12[-2])-y[-1]*(x02[-2]+x12[-2])/(x02[-2]*x12[-2])\n#\n# return d\n","sub_path":"SOLPSutils.py","file_name":"SOLPSutils.py","file_ext":"py","file_size_in_byte":21577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577482357","text":"import argparse\nimport os\nimport sys\n\nimport loguru\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\nfrom path import Path\n\nfrom pdf_white_cut import miner\n\nlogger = loguru.logger\nlogger.remove()\nlogger.add(sys.stderr, level=\"INFO\")\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", help=\"input file\", action=\"store\",\n default='', type=str, dest=\"input\")\n parser.add_argument(\"-o\", help=\"output file\", action=\"store\",\n default='', type=str, dest=\"output\")\n parser.add_argument(\"-id\", help=\"input directory\", action=\"store\",\n default='', type=str, dest=\"indir\")\n parser.add_argument(\"-od\", help=\"output directory\", action=\"store\",\n default='', type=str, dest=\"outdir\")\n parser.add_argument(\"-t\", \"--test\", help=\"run test\",\n action=\"store_true\", dest=\"test\")\n parser.add_argument(\"--ignore\", help=\"ignore global\",\n action=\"store\", type=int, default=0, dest=\"ignore\")\n parser.add_argument(\"--verbose\", help=\"choose verbose (DEBUG)\",\n action=\"store_true\", default=False, dest=\"verbose\")\n # parser.add_argument(nargs=argparse.REMAINDER, dest=\"value\")\n args = parser.parse_args()\n return args\n\n\ndef edit_box(page, useful_area):\n \"\"\"\n cut the box by setting new position (relative position)\n \"\"\"\n box = page.mediaBox\n # MENTION: media box is a visible area of the pdf page\n logger.info('media box: {}', page.mediaBox)\n logger.debug(page.trimBox)\n logger.debug(page.artBox)\n logger.debug(page.cropBox)\n logger.debug(page.bleedBox)\n\n # must translate relative position to absolute position\n # box position\n bx1, by1 = box.getLowerLeft()\n bx1, by1 = float(bx1), float(by1)\n bx2, by2 = box.getUpperRight()\n bx2, by2 = float(bx2), float(by2)\n\n # visible area\n (x1, y1, x2, y2) = useful_area\n\n # MENTION: all of the box is relative position, so we need to fix the position, choose the smaller area\n logger.info(\"origin box: {}\", box)\n\n box.lowerLeft = (\n max(bx1, x1 + bx1),\n max(by1, y1 + by1)\n )\n box.upperRight = (\n min(bx2, x2 + bx1),\n min(by2, y2 + by1)\n )\n\n logger.info(\"fixed box: {}\", box)\n\n\ndef cut_white(source, target: str = None, ignore=0):\n \"\"\"\n cut the white slide of the input pdf file, and output a new pdf file.\n \"\"\"\n if target is None:\n target = 'output.pdf'\n\n if source == target:\n raise Exception('input and output can not be the same!')\n\n try:\n with open(source, 'rb') as infd:\n logger.info('process file: {}', source)\n inpdf = PdfFileReader(infd)\n\n # MENTION: never move and change the sequence, since file IO\n # get the visible area of the page, aka the box scale. res=[(x1,y1,x2,y2)]\n page_box_list = miner.mine_area(source, ignore=ignore)\n outpdf = PdfFileWriter()\n\n for idx in range(inpdf.getNumPages()):\n # scale is the max box of the page\n scale = page_box_list[idx]\n logger.info('origin scale: {}', scale)\n\n page = inpdf.getPage(idx)\n edit_box(page, scale)\n outpdf.addPage(page)\n\n with open(target, 'wb') as outfd:\n outpdf.write(outfd)\n logger.info('output file: {}', target)\n\n except UnicodeEncodeError as ue:\n logger.exception('UnicodeEncodeError while processing file:{}', source)\n logger.exception(ue)\n except Exception as e:\n logger.exception('Some other Error while processing file:{}', source)\n logger.exception(e)\n\n\ndef scan_files(folder, glob=\"\"):\n \"\"\"\n scan files under the dir with spec prefix and postfix\n \"\"\"\n files = []\n for item in Path(folder).listdir(glob):\n item: 'Path'\n files.append(item.abspath())\n return files\n\n\ndef batch(sources, targets, ignore=0):\n if sources == targets:\n raise Exception('input and output can not be the same!')\n\n files = scan_files(sources, glob='*.pdf')\n logger.info(files)\n\n if not os.path.exists(sources):\n os.mkdir(sources)\n\n for item in files:\n source = os.path.join(sources, item)\n target = os.path.join(targets, item)\n cut_white(source, target, ignore=ignore)\n","sub_path":"pdf_white_cut/cutwhite.py","file_name":"cutwhite.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"324547609","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom statsmodels.nonparametric.smoothers_lowess import lowess\nimport matplotlib.colors as colors\nimport matplotlib.cm as cmx\nfrom matplotlib.collections import LineCollection\nimport matplotlib.patheffects as pe\nimport eagle3 as E\n\ndef multiline(xs, ys, c, ax=None, **kwargs):\n \"\"\"Plot lines with different colorings\n\n Parameters\n ----------\n xs : iterable container of x coordinates\n ys : iterable container of y coordinates\n c : iterable container of numbers mapped to colormap\n ax (optional): Axes to plot on.\n kwargs (optional): passed to LineCollection\n\n Notes:\n len(xs) == len(ys) == len(c) is the number of line segments\n len(xs[i]) == len(ys[i]) is the number of points for each line (indexed by i)\n\n Returns\n -------\n lc : LineCollection instance.\n \"\"\"\n\n # find axes\n ax = plt.gca() if ax is None else ax\n\n # create LineCollection\n segments = [np.column_stack([x, y]) for x, y in zip(xs, ys)]\n lc = LineCollection(segments, **kwargs)\n\n # set coloring of line segments\n # Note: I get an error if I pass c as a list here... not sure why.\n lc.set_array(np.asarray(c))\n\n # add lines to axes and rescale \n # Note: adding a collection doesn't autoscalee xlim/ylim\n ax.add_collection(lc)\n ax.autoscale()\n return lc\n\ndef lowess_error(x,y,frac=0.5,it=2,frac_error=0.1):\n print('Processing lowess')\n ys=lowess(y,x,frac=frac,it=2)\n sort=np.argsort(x)\n x=x[sort]\n y=y[sort]\n\n ys_samp=ys[0::int(1/frac_error)]\n\n x_samp=x[0::int(1/frac_error)]\n y_samp=y[0::int(1/frac_error)]\n\n error=np.empty(len(ys_samp[:,0]))\n mean_error=np.empty(len(ys_samp[:,0]))\n num=int(len(ys[:,0])*frac)\n for i in range(len(ys_samp[:,0])):\n dist=np.abs(ys_samp[i,0]-ys[:,0])\n sort_id=np.argsort(dist)\n width=dist[sort_id][num-1]\n weight=(1-(dist[sort_id][0:num-1]/width)**2)**2\n weight=np.ones(len(weight))\n val=y[sort_id][0:num-1]\n \n error[i]=(np.sum((ys_samp[i,1]-val)**2)/np.sum(weight))**0.5\n mean_error[i]=error[i]/np.sum(weight)**0.5\n return(ys,ys_samp,error,mean_error)\n\nnsims=2\ncross_sections=['CDM_low_norm_bins','CDM_low_high_bins']\ncross_sections2=['z0','z0_high']\ncolors=['#1f77b4','#ff7f0e']#,'#2ca02c','#d62728']\n\nwrite_loc='/hpcdata4/arisbrow/simulations/L100N256_WMAP9/Processed_data/Entropy_CDM_bin_test/'\nwrite_loc2='/hpcdata4/arisbrow/simulations/L100N256_WMAP9/Processed_data/Entropy_CDM_redshifts/'\nm=[]; params=[]; profile=[]; rad=[]; density=[]; vel_disp=[];\nfor i in range(nsims):\n m.append(np.load(write_loc+'Entropy_CDM_mass_'+cross_sections[i]+'.npy'))\n params.append(np.load(write_loc+'Entropy_CDM_fit_params_'+cross_sections[i]+'.npy'))\n profile.append(np.load(write_loc+'Entropy_CDM_profile_'+cross_sections[i]+'.npy'))\n rad.append(np.load(write_loc+'Rad_CDM_profile_'+cross_sections[i]+'.npy'))\n density.append(np.load(write_loc+'Entropy_CDM_density_'+cross_sections[i]+'.npy'))\n vel_disp.append(np.load(write_loc+'Entropy_CDM_vel_disp_'+cross_sections[i]+'.npy'))\nm2=[]; params2=[]; profile2=[]; rad2=[]; density2=[]; vel_disp2=[];\nfor i in range(nsims):\n m2.append(np.load(write_loc2+'Entropy_CDM_mass_'+cross_sections2[i]+'.npy'))\n params2.append(np.load(write_loc2+'Entropy_CDM_fit_params_'+cross_sections2[i]+'.npy'))\n profile2.append(np.load(write_loc2+'Entropy_CDM_profile_'+cross_sections2[i]+'.npy'))\n rad2.append(np.load(write_loc2+'Rad_CDM_profile_'+cross_sections2[i]+'.npy'))\n density2.append(np.load(write_loc2+'Entropy_CDM_density_'+cross_sections2[i]+'.npy'))\n vel_disp2.append(np.load(write_loc2+'Entropy_CDM_vel_disp_'+cross_sections2[i]+'.npy'))\n\n#identifying 'good' and 'bad' halos\ndiff=[]\n\nfor i in range(nsims):\n mass_cut=10**13\n diff_cut=15\n r=rad[i][m[i]>mass_cut].flatten()\n s=profile[i][m[i]>mass_cut].flatten()\n alpha,A=np.polyfit(np.log(r),np.log(s),1)\n\n pow_prof=np.exp(A)*rad[i]**alpha\n\n diff.append(np.sum(profile[i]-pow_prof,axis=1))\n\ndiff2=[]\nfor i in range(nsims):\n mass_cut=10**13\n diff_cut=15\n r=rad2[i][m2[i]>mass_cut].flatten()\n s=profile[i][m[i]>mass_cut].flatten()\n alpha,A=np.polyfit(np.log(r),np.log(s),1)\n\n pow_prof=np.exp(A)*rad2[i]**alpha\n\n diff2.append(np.sum(profile2[i]-pow_prof,axis=1))\n\nplt.figure()\nax=plt.subplot(111)\nplt.scatter(m[1],diff[1],s=2)#,c=np.log(subhalo_mass_ratio),alpha=0.7)\nplt.text(0.65,0.05,'Normal bins',transform=ax.transAxes,fontsize=14)\nprint(len(diff[1][diff[1]>500])/len(diff[1]))\n#plt.colorbar()\nplt.xscale('log')\n#plt.yscale('log')\nplt.xlabel('M200',fontsize=14)\nplt.ylabel('S-S_fit',fontsize=14)\nplt.xlim(10**9.5,10**14)\nplt.ylim(-50,2000)\n\nplt.figure()\nax=plt.subplot(111)\nplt.scatter(m2[1],diff2[1],s=2)#,c=np.log(subhalo_mass_ratio),alpha=0.7)\nplt.text(0.65,0.05,'Gaussian kernel',transform=ax.transAxes,fontsize=14)\nprint(len(diff[1][diff[1]>500])/len(diff[1]))\n#plt.colorbar()\nplt.xscale('log')\n#plt.yscale('log')\nplt.xlabel('M200',fontsize=14)\nplt.ylabel('S-S_fit',fontsize=14)\nplt.xlim(10**9.5,10**14)\nplt.ylim(-50,2000)\n\n\n\nfig=plt.figure()\nax=fig.add_subplot(111)\n\nlc=multiline(rad[1],profile[1],np.log10(m[1]),cmap='viridis',lw=0.5,alpha=0.5)\ncb=fig.colorbar(lc)\nplt.xscale('log')\nplt.yscale('log')\nplt.xlim(10**-2.5,10**0)\nplt.ylim(10**-3,10**3)\nplt.xlabel('r/R200',fontsize=12)\nplt.ylabel('$\\\\rho$',fontsize=12)\ncb.set_label('log(M200)')\nplt.text(0.65,0.05,'Normal bins',transform=ax.transAxes,fontsize=14)\n\n\nfig=plt.figure()\nax=fig.add_subplot(111)\n\nlc=multiline(rad2[1],profile2[1],np.log10(m2[1]),cmap='viridis',lw=0.5,alpha=0.5)\ncb=fig.colorbar(lc)\nplt.xscale('log')\nplt.yscale('log')\nplt.xlim(10**-2.5,10**0)\nplt.ylim(10**-3,10**3)\nplt.xlabel('r/R200',fontsize=12)\nplt.ylabel('$\\\\sigma$',fontsize=12)\ncb.set_label('log(M200)')\nplt.text(0.65,0.05,'Gaussian kernel',transform=ax.transAxes,fontsize=14)\n\nplt.show()\nexit()\n#calculating the tidal forces on a halo\n# sim='/hpcdata4/sam/PhD/Investigating_Running/RUNS/DMONLY/L025N1024/run_0/data'\n# tag='033'\n# M200 = E.readArray(\"SUBFIND_GROUP\", sim, tag, \"FOF/Group_M_Crit200\",noH=False); M200*=10**10\n# R200 = E.readArray(\"SUBFIND_GROUP\", sim, tag, \"FOF/Group_R_Crit200\",noH=False)\n# loc=E.readArray(\"SUBFIND_GROUP\", sim, tag, \"FOF/GroupCentreOfPotential\",noH=False)\n\n# num_sub = E.readArray(\"SUBFIND_GROUP\", sim, tag, \"FOF/NumOfSubhalos\",noH=False);\n# sub_id = E.readArray(\"SUBFIND_GROUP\", sim, tag, \"FOF/FirstSubhaloID\",noH=False);\n\n# sub_mass = E.readArray(\"SUBFIND\",sim,tag,\"Subhalo/Mass\",noH=False); \n# sub_loc = E.readArray(\"SUBFIND\",sim,tag,\"/Subhalo/CentreOfPotential\"); \n\n# sub_rad = E.readArray(\"SUBFIND\",sim,tag,\"/Subhalo/HalfMassRad\",noH=False)[:,1]; \n\n# sort=np.argsort(M200)\n# M200=M200[sort]\n# R200=R200[sort]\n# loc=loc[sort]\n# num_sub=num_sub[sort]\n# sub_id=sub_id[sort]\n\n# mas_cut=10**9\n# cut=np.where(M200>mas_cut)[0]\n# M200=M200[cut]\n# R200=R200[cut]\n# loc=loc[cut]\n# num_sub=num_sub[cut]\n# sub_id=sub_id[cut]\n\n\n# cut=np.where(m[1]>mas_cut)[0]\n# m[1]=m[1][cut]\n# params[1]=params[1][cut]\n# profile[1]=profile[1][cut]\n# rad[1]=rad[1][cut]\n\n\n# summed_mass=np.empty(len(num_sub))\n\n# for i in range(len(num_sub)):\n# if num_sub[i]==1:\n# summed_mass[i]=-1\n# continue\n# mass=sub_mass[sub_id[i]:sub_id[i]+num_sub[i]]\n\n# rat=mass[1:]/mass[0]\n# summed_mass[i]=np.sum(mass[1:])/mass[0]\n\n\n# tid_force=np.empty(len(M200))\n# for i in range(len(M200)):\n# dist=((loc[i,0]-loc[:,0])**2+(loc[i,1]-loc[:,1])**2+(loc[i,2]-loc[:,2])**2)**0.5\n# dist[dist==0]=100\n# rat=M200/M200[i]*R200[i]**2/dist**2\n# tid_force[i]=np.max(rat)\n\n# subhalo_mass_ratio=np.empty(len(M200))\n# print(np.sum(num_sub==0))\n\n# for i in range(len(M200)):\n# if num_sub[i]==0:\n# subhalo_mass_ratio[i]=-1.0\n# continue\n# elif num_sub[i]==1:\n# subhalo_mass_ratio[i]=0.0\n# continue\n# rad_host = sub_rad[sub_id[i]]\n# mass=sub_mass[sub_id[i]:sub_id[i]+num_sub[i]]\n# loc=sub_loc[sub_id[i]:sub_id[i]+num_sub[i]]\n\n# mass_host=mass[0]\n# mass_sub=mass[1:]\n \n# loc_host=loc[0]\n# loc_sub=loc[1:]\n# dist=((loc_sub[:,0]-loc_host[0])**2+(loc_sub[:,1]-loc_host[1])**2+(loc_sub[:,2]-loc_host[2])**2)**0.5\n\n# tid_forc_rat=4*mass_sub/mass_host*dist*rad_host**3/((dist+rad_host)**2*(dist-rad_host)**2)\n \n# subhalo_mass_ratio[i]=np.max(tid_forc_rat)\n# #calculating residuals from a power law fit of the most massive haloes\n# mass_cut=10**13\n# r=rad[1][m[1]>mass_cut].flatten()\n# s=profile[1][m[1]>mass_cut].flatten()\n# alpha,A=np.polyfit(np.log(r),np.log(s),1)\n\n# pow_prof=np.exp(A)*rad[1]**alpha\n\n# diff=np.sum(profile[1]-pow_prof,axis=1)\n\n# plt.figure()\n# plt.scatter(M200,diff,s=2)#,c=np.log(subhalo_mass_ratio),alpha=0.7)\n\n# print(len(diff[(M200<2.3*10**10) & (diff>500)])/len(diff[M200<2.3*10**10]))\n# #plt.colorbar()\n# plt.xscale('log')\n# #plt.yscale('log')\n# plt.xlabel('M200',fontsize=14)\n# plt.ylabel('S-S_fit',fontsize=14)\n\n# bad_halos=np.where(diff>1000)\n# good_halos=np.where(diff<1000)\n\n# print(np.max(summed_mass))\n# plt.figure()\n# plt.plot(M200[good_halos],R200[good_halos],'k.')\n# plt.plot(M200[bad_halos],R200[bad_halos],'b.')\n# plt.xscale('log')\n# plt.yscale('log')\n# plt.show()","sub_path":"phase_space_analysis/Entropy_CDM_plots_norm_bins.py","file_name":"Entropy_CDM_plots_norm_bins.py","file_ext":"py","file_size_in_byte":9247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"207137901","text":"#app course_admin views.py\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom .models import Course, Description\n# This will handle /\ndef index(request):\n\tcourses = Course.objects.all()\n\treturn render(request,'course_admin/index.html', {'courses': courses})\n\n#This will handle POST to /new/\ndef new(request):\n\tif request.method == \"POST\":\n\t\terrors = Course.objects.basic_validator(request.POST)\n\t\tif len(errors):\n\t\t\tfor tag, error in errors.iteritems():\n\t\t\t\tmessages.error(request, error, extra_tags=tag)\n\t\t\tprint(request.POST['description'])\n\t\t\tcourses = Course.objects.all()\n\t\t\treturn render(request,'course_admin/index.html', {'courses': courses,\"name\":request.POST['name'],\"description\":request.POST['description']})\n\t\telse:\n\t\t\tcourse = Course.objects.create(name=request.POST['name'])\n\t\t\tdesc = Description.objects.create(desc=request.POST['description'], course=course)\n\telse:\n\t\t#Should never happen\n\t\tprint(\"new --- Unexpected request method received:\", request.method)\n\treturn redirect(reverse('course_admin_index'))\n\n#This will handle /destroy// and POST to /destroy/\ndef destroy(request, id=''):\n\ttry:\n\t\tif request.method == \"POST\":\n\t\t\tif 'yes' in request.POST:\n\t\t\t\tcourse = Course.objects.get(id=request.POST['id'])\n\t\t\t\tprint(\"deleting\")\n\t\t\t\tcourse.delete()\n\t\telse:\n\t\t\tcourse = Course.objects.get(id=id)\n\t\t\treturn render(request,'course_admin/destroy.html', {'course': course})\n\texcept Exception as e:\n\t\t\t#Should not get here. Print error and redirect home.\n\t\t\tprint('%s (%s)' % (e.message, type(e)))\n\treturn redirect(reverse('course_admin_index'))","sub_path":"apps/course_admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"37208986","text":"# Code derived from tensorflow/tensorflow/models/image/imagenet/classify_image.py\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os.path\nimport sys\nimport tarfile\n\nimport sys\nsys.path.insert(0, '/data/whyjay/NIPS2017')\nimport numpy as np\nfrom six.moves import urllib\nimport tensorflow as tf\nimport glob\nimport scipy.misc\nimport math\nimport sys\nslim = tf.contrib.slim\n\nMODEL_DIR = 'checkpoints'\nsoftmax = None\nx = None\n\n# Call this function with list of images. Each of elements should be a\n# numpy array with values ranging from 0 to 255.\ndef get_inception_score(images, splits=10):\n assert(type(images) == list)\n assert(type(images[0]) == np.ndarray)\n assert(len(images[0].shape) == 3)\n assert(np.min(images[0]) >= 0.0)\n inps = []\n\n for img in images:\n img = img.astype(np.float32)\n inps.append(np.expand_dims(img, 0))\n\n bs = 100\n with tf.Session() as sess:\n ckpt = tf.train.get_checkpoint_state(MODEL_DIR)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n saver = tf.train.Saver()\n saver.restore(sess, os.path.join(MODEL_DIR, ckpt_name))\n\n preds = []\n n_batches = int(math.ceil(float(len(inps)) / float(bs)))\n\n for i in range(n_batches):\n sys.stdout.write(\".\")\n sys.stdout.flush()\n inp = inps[(i * bs):min((i + 1) * bs, len(inps))]\n inp = np.concatenate(inp, 0)\n pred = sess.run(softmax, {x: inp})\n preds.append(pred)\n\n preds = np.concatenate(preds, 0)\n scores = []\n\n for i in range(splits):\n part = preds[(i * preds.shape[0] // splits):((i + 1) * preds.shape[0] // splits), :]\n kl = part * (np.log(part) - np.log(np.expand_dims(np.mean(part, 0), 0)))\n kl = np.mean(np.sum(kl, 1))\n scores.append(np.exp(kl))\n\n return np.mean(scores), np.std(scores), preds\n\n# This function is called automatically.\ndef _init_model():\n global softmax\n global x\n if not os.path.exists(MODEL_DIR):\n os.makedirs(MODEL_DIR)\n\n # Works with an arbitrary minibatch size.\n x = tf.placeholder(tf.float32, shape=[None, 28, 28, 1])\n\n h = slim.conv2d(x, 32, 3, 1, activation_fn=tf.nn.relu, normalizer_fn=None)\n h = tf.nn.max_pool(h, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n h = slim.conv2d(h, 64, 3, 1, activation_fn=tf.nn.relu, normalizer_fn=None)\n h = tf.nn.max_pool(h, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n h = tf.reshape(h, [-1, 7*7*64])\n h = slim.fully_connected(h, 1024, activation_fn=None, normalizer_fn=None)\n h = tf.nn.dropout(h, 1.0)\n logits = slim.fully_connected(h, 10, activation_fn=None, normalizer_fn=None)\n softmax = tf.nn.softmax(logits)\n\nif softmax is None or x is None:\n _init_model()\n","sub_path":"inception_score/model_mnist.py","file_name":"model_mnist.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"83169843","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom nets import vgg\nfrom drop_net import dropped_vgg\nimport random\nimport numpy as np\nimport argparse\n\nslim = tf.contrib.slim\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--drop_layer', action=\"store\", dest='drop_layer',default=None, type=int)\n parser.add_argument('--drop_num', action=\"store\", dest='drop_num',default=None, type=int)\n parser.add_argument('--exp_num', action=\"store\", dest='exp_num',default=None, type=int)\n FLAGS = parser.parse_args()\n\n sess = tf.Session()\n # create dropped model\n infer_in = tf.placeholder(tf.float32, shape=(1,224,224,3))\n drop_num = [0]*16\n drop_num[FLAGS.drop_layer] = FLAGS.drop_num\n drop_array=np.array(drop_num)\n\n with slim.arg_scope(vgg.vgg_arg_scope()):\n dropped_logits, _ = dropped_vgg(infer_in, num_classes=1000, is_training=False,drop_num=drop_num)\n\n #variable list of the dropped model\n dv=[]\n for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope='dropped_vgg'):\n dv.append(v)\n\n # create original VGG 19 model\n with slim.arg_scope(vgg.vgg_arg_scope()):\n logits, _ = vgg.vgg_19(infer_in, num_classes=1000, is_training=False)\n\n #variable list of the complete model\n cv=[]\n for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope='vgg_19'):\n cv.append(v)\n\n # restore parameters of the complete model\n # and assign related parameters to the dropped model\n init_fn = slim.assign_from_checkpoint_fn(\n './vgg_19.ckpt',\n slim.get_model_variables('vgg_19'))\n\n init_fn(sess)\n\n fm_list=[]\n for c,d in zip(cv,dv):\n if c.shape != d.shape:\n nptmp=sess.run(c)\n #initialize fm list when it's empty\n if not fm_list:\n fm_list=list(range(c.shape.dims[3]))\n drop_list=random.sample(fm_list,drop_array[np.nonzero(drop_array)][0])\n for item in drop_list:\n fm_list.remove(item)\n\n if c.shape.ndims == 1:\n 'assign dropped bias'\n sess.run(d.assign(tf.constant(nptmp[fm_list])))\n else:\n 'assign dropped weights'\n if c.shape.dims[2] != d.shape.dims[2]:\n sess.run(d.assign(tf.constant(nptmp[:,:,fm_list,:])))\n elif c.shape.dims[3] != d.shape.dims[3]:\n sess.run(d.assign(tf.constant(nptmp[:,:,:,fm_list])))\n else:\n sess.run(d.assign(c))\n\n # export checkpoint of dropped vgg\n\n global_step=tf.get_variable('global_step',initializer=tf.constant(0,dtype=tf.int64))\n sess.run(global_step.initializer)\n dv.insert(0,global_step)\n mean_rgb=tf.get_variable('dropped_vgg/mean_rgb',initializer=tf.constant([123.68, 116.78, 103.94]))\n sess.run(mean_rgb.initializer)\n dv.append(mean_rgb)\n\n saver = tf.train.Saver(write_version=tf.train.SaverDef.V1,var_list=dv)\n ckpt_name = str(FLAGS.drop_layer)+'_'+str(FLAGS.drop_num)+'_'+str(FLAGS.exp_num)\n saver.save(sess, './drop_ckpt/'+ckpt_name)\n np.savetxt('./eval_results/'+ckpt_name+'.drop_list',drop_list,fmt='%i')\n tf.reset_default_graph()\n\nif __name__ == '__main__':\n main()\n","sub_path":"save_dropped_ckpt.py","file_name":"save_dropped_ckpt.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"489366938","text":"import sys\nimport os\nfrom room import Room\nfrom player import Player\nfrom item import Item\n\nrock = Item(\"Rock\", \"a small rock than can be thrown\")\nstick = Item(\"Stick\", \"a piece of wood stick, easy to break\")\ncrystal = Item(\"Crystal\", \"shiny crystal\")\nempty_backpack = Item(\"Backpack\", \"empty backpack from earlier adventurers\")\nsword = Item(\"Sword\", \"rusty sword\")\ncoins = Item(\"Coins\", \"unknown coins\")\n\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\", [rock, stick]),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\", [rock, stick, empty_backpack]),\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.\"\"\", [rock, crystal]),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\", [rock, coins]),\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.\"\"\", [sword]),\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#\n# Main\n#\n# os.system('cls')\npossible_directions = ['n', 's', 'e', 'w', 'i']\n# Make a new player object that is currently in the 'outside' room.\nplayer = Player(input(\"Please enter your name:\"), room['outside'])\n# os.system('cls')\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\nplayer_command = None\n\nwhile True:\n\n print(f\"Your location: {player.current_room}\\n\")\n\n def command():\n global player_command\n print(\"***Enter a command to continue***\\\n \\n q: quit\\\n \\n i: show your items\\\n \\n n: go North\\\n \\n s: go South\\\n \\n e: go East\\\n \\n w: go West\\\n \\n g [item]: get item\\\n \\n d [item]: drop item\")\n player_command = input(\">> \")\n\n command()\n\n if player_command == 'q':\n print(\"See you back soon\")\n sys.exit(1)\n\n elif player_command == 'i':\n player.show_items()\n\n elif player_command[0] == 'g':\n player.get_item(player_command[2:].lower())\n\n elif player_command[0] == 'd':\n player.drop_item(player_command[2:].lower())\n \n elif player_command in possible_directions:\n player.try_direction(player_command)\n \n else:\n print(\"I don't understand your command. Try again\\n\")\n","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93660524","text":"import os\nfrom PIL import Image\nimport numpy as np\nimport csv\n\nos.chdir('FullIJCNN2013')\n\nimage_dir = \"images\"\nannotations_dir = \"annotations\"\nif not os.path.exists(image_dir):\n os.mkdir(image_dir)\nif not os.path.exists(annotations_dir):\n os.mkdir(annotations_dir)\nclasses = []\nwith open(\"gt.txt\") as csv_file:\n gt = csv.reader(csv_file, delimiter=';')\n for row in gt:\n im_name, x1, y1, x2, y2, c = row\n x1 = int(x1)\n y1 = int(y1)\n x2 = int(x2)\n y2 = int(y2)\n basename = os.path.splitext(im_name)[0]\n classes.append(int(c))\n im = Image.open(im_name)\n\n gt_im_path = os.path.join(annotations_dir, basename + '.png')\n if os.path.exists(gt_im_path):\n gt_im = np.array(Image.open(gt_im_path))\n else:\n gt_im = np.full(np.array(im).shape[:2], 43, dtype=np.uint8) #Set background to max class + 1\n gt_im[y1:y2+1, x1:x2+1] = c\n gt_im = Image.fromarray(gt_im)\n \n im.save(os.path.join(image_dir, basename + \".png\"))\n gt_im.save(gt_im_path)\n","sub_path":"dataset_preprocess.py","file_name":"dataset_preprocess.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"523520263","text":"import ast\nimport json\n\nimport requests\nfrom django.http import JsonResponse\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic.base import View\n\nfrom ConfigureCenter.CommonConfigure import nginx_ip_port\nfrom ConfigureCenter.ManagerCenterConfigure import floor_limit\nfrom ManagerCenter.views import executor\n\n\n@method_decorator(csrf_exempt, 'dispatch')\nclass GenerateTasks(View):\n def post(self, request):\n task_data = request.body.decode('utf-8')\n try:\n try:\n data = ast.literal_eval(task_data)\n except Exception as e:\n data = json.loads(task_data)\n executor.submit(self.process_data, data)\n except Exception as e:\n print(\"StorageCenter->ResultStorage: analysis json data fail:{}\\n that's json data is {}\".format(e,\n task_data))\n return JsonResponse(\n {\"status\": 1,\n \"title\": \"StorageCenter->ResultStorage: analysis json fail, json is all right? please make sure\"})\n return JsonResponse({\"status\": 0, \"title\": \"StorageCenter->ResultStorage: had received UnduplicateCenter data\"})\n\n def process_data(self, data):\n result_urls = data.get(\"result_urls\")\n task_url = data.get(\"task_url\")\n if result_urls is None:\n return\n if data.get(\"page_source\"):\n del data['page_source']\n del data['page_status_code']\n del data['result_urls']\n current_floor = int(data.get(\"current_floor\"))\n if current_floor > floor_limit:\n pass\n task_id = data.get(\"task_id\")\n executor.submit(self.post_tasks_to_taskcenter, task_id)\n for url in result_urls:\n data['task_url'] = url\n data['current_floor'] = str(current_floor + 1)\n data['task_url_pre'] = task_url\n executor.submit(self.post_tasks_to_download, data)\n\n def post_tasks_to_download(self, data):\n try:\n r = requests.post(nginx_ip_port + reverse('DownloadCenter:receive_task'), json=data)\n # print(\"ManagerCenter->GenerateTasks:receive DownloadCenter->receive_task return data:{}\".format(r.text))\n except Exception as e:\n print(\"ManagerCenter->GenerateTasks: send task to DownloadCenter fail:{}\".format(e))\n\n def post_tasks_to_taskcenter(self, task_id):\n r = requests.post(nginx_ip_port + reverse('TaskCenter:shut_down_task'), data={\"task_id\": task_id})\n # print(\"ManagerCenter->GenerateTasks: receive return data: {}\".format(r.text))\n","sub_path":"ManagerCenter/views/GenerateTasks.py","file_name":"GenerateTasks.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"131609787","text":"import csv\nfhand = open(\"/sas/vidhya/CompoundDb4jV2/USPTO/data/PubPatAppUSPTO.csv\",\"w\")\nfName = \"/sas/vidhya/CompoundDb4jV2/USPTO/data/ALLPatents.csv\"\nlines = open(fName)\nlines = lines.read()\nlines = lines.split(\"\\n\")\nnum = 0\nskip = []\nfor x in range(0,len(lines)-1):\n\trow = lines[x].rstrip().split(\"|\")\n\tif (len(row) != 9):\n\t\tskip.append(x+1)\n\tif x not in skip:\n\t\tappD = row[0]\n\t\tappNo = row[1]\n\t\tpubNo = row[3]\n\t\tpatNo = row[5]\n\t\trecord = pubNo + \"|\" + patNo + \"|\" + appNo + \"|\" + appD + \"\\n\"\n\t\tfhand.write(record)\n\t\tnum += 1\t\n\t\tif (num%2000000 ==0):\n\t\t\tprint(num)\n\nprint(\"No of lines:\" + str(len(lines)))\nprint(\"last line\"+lines[len(lines)-1])\nprint(\"skip\" + str(len(skip)))\nprint(\"No Of Rows writtern to new file:\" , num)\n\t\nfhand.close()\n","sub_path":"ExtractNumUSPTO.py","file_name":"ExtractNumUSPTO.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"412678564","text":"# %% imports\nimport scipy\nimport scipy.io\nimport scipy.stats\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom data.data_fetchers import get_joyride_data\nfrom filters import pda, imm, ekf\nfrom utils import measurementmodels, dynamicmodels\n\n# %% plot config check and style setup\n\n\n# to see your plot config\nprint(f\"matplotlib backend: {matplotlib.get_backend()}\")\nprint(f\"matplotlib config file: {matplotlib.matplotlib_fname()}\")\nprint(f\"matplotlib config dir: {matplotlib.get_configdir()}\")\nplt.close(\"all\")\n\n# try to set separate window ploting\nif \"inline\" in matplotlib.get_backend():\n print(\"Plotting is set to inline at the moment:\", end=\" \")\n\n if \"ipykernel\" in matplotlib.get_backend():\n print(\"backend is ipykernel (IPython?)\")\n print(\"Trying to set backend to separate window:\", end=\" \")\n import IPython\n\n IPython.get_ipython().run_line_magic(\"matplotlib\", \"\")\n else:\n print(\"unknown inline backend\")\n\nprint(\"continuing with this plotting backend\", end=\"\\n\\n\\n\")\n\n\n# set styles\ntry:\n # installed with \"pip install SciencePLots\" (https://github.com/garrettj403/SciencePlots.git)\n # gives quite nice plots\n plt_styles = [\"science\", \"grid\", \"bright\", \"no-latex\"]\n plt.style.use(plt_styles)\n print(f\"pyplot using style set {plt_styles}\")\nexcept Exception as e:\n print(e)\n print(\"setting grid and only grid and legend manually\")\n plt.rcParams.update(\n {\n # setgrid\n \"axes.grid\": True,\n \"grid.linestyle\": \":\",\n \"grid.color\": \"k\",\n \"grid.alpha\": 0.5,\n \"grid.linewidth\": 0.5,\n # Legend\n \"legend.frameon\": True,\n \"legend.framealpha\": 1.0,\n \"legend.fancybox\": True,\n \"legend.numpoints\": 1,\n }\n )\n\n\n# %% load data and plot\nK, Ts, T, Xgt, Z = get_joyride_data()\n\n# plot measurements close to the trajectory\nfig1, ax1 = plt.subplots(num=1, clear=True)\n\nZ_plot_data = np.empty((0, 2), dtype=float)\nplot_measurement_distance = 45\nfor Zk, xgtk in zip(Z, Xgt):\n to_plot = np.linalg.norm(Zk - xgtk[None:2], axis=1) <= plot_measurement_distance\n Z_plot_data = np.append(Z_plot_data, Zk[to_plot], axis=0)\n\nax1.scatter(*Z_plot_data.T, color=\"C1\")\nax1.plot(*Xgt.T[:2], color=\"C0\", linewidth=1.5)\nax1.set_title(\"True trajectory and the nearby measurements\")\nplt.show(block=False)\n\n# %% play measurement movie. Remember that you can cross out the window\nplay_movie = True\nplay_slice = slice(0, K)\nif play_movie:\n if \"inline\" in matplotlib.get_backend():\n print(\"the movie might not play with inline plots\")\n fig2, ax2 = plt.subplots(num=2, clear=True)\n sh = ax2.scatter(np.nan, np.nan)\n th = ax2.set_title(f\"measurements at step 0\")\n mins = np.vstack(Z).min(axis=0)\n maxes = np.vstack(Z).max(axis=0)\n ax2.axis([mins[0], maxes[0], mins[1], maxes[1]])\n plotpause = 0.1\n # sets a pause in between time steps if it goes to fast\n for k, Zk in enumerate(Z[play_slice]):\n sh.set_offsets(Zk)\n th.set_text(f\"measurements at step {k}\")\n fig2.canvas.draw_idle()\n plt.show(block=False)\n plt.pause(plotpause)\n\n# %% setup and track\n\n\n","sub_path":"projects/graded_assignment1/run_joyride.py","file_name":"run_joyride.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"72928679","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 10 16:06:18 2021\r\n\r\n@author: Alexis\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport ResolutionSystTriSup\r\n\r\ndef ReductionGaussChoixPivotTotal(A):\r\n Aaug = np.concatenate((A,B), axis=1)\r\n n,m = np.shape(Aaug)\r\n \r\n for i in range(n):\r\n for j in range(0,n-i):\r\n if abs(Aaug[j,j]) < abs(Aaug[i+j,j]) :\r\n i_max = Aaug[i,:].copy()\r\n Aaug[i,:] = Aaug[i+j,:]\r\n Aaug[i+j,:] = i_max\r\n if abs(Aaug[j,j]) < abs(Aaug[j,i+j]) :\r\n J_max = Aaug[:,i].copy()\r\n Aaug[:,i] = Aaug[:,i+j]\r\n Aaug[:,i+j] = J_max\r\n for k in range(i+1,n):\r\n g = Aaug[k,i]/Aaug[i,i]\r\n Aaug[k,:] = Aaug[k,:] - g * Aaug[i,:]\r\n return Aaug\r\n\r\n\r\ndef GaussChoixPivotTotal(A,B):\r\n Aaug = np.concatenate((A,B), axis=1)\r\n \r\n Taug = ReductionGaussChoixPivotTotal(Aaug)\r\n solution= ResolutionSystTriSup.ResolutionSystTriSup(Taug)\r\n \r\n return solution\r\n\r\nA = np.array([[2 , 5 , 0],[4 , 11 , 9],[-2 , -8 , 7]])\r\nB = np.array([[7], [12] , [3]])\r\n\r\nprint(GaussChoixPivotTotal(A,B))\r\n\r\n","sub_path":"GaussChoixPivotTotal.py","file_name":"GaussChoixPivotTotal.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"461532249","text":"import cv2 as cv\r\nimport numpy as np\r\nimport os\r\nimport math\r\nfrom pynput.mouse import Button, Controller\r\n\r\ndef nothing(x):\r\n pass\r\n\r\ndef histogram(firstFrame, r, h, c, w):\r\n #roi = firstFrame[r:r+h, c:c+w]\r\n hsv_roi = cv.cvtColor(firstFrame, cv.COLOR_BGR2HSV)\r\n hl, hu, sl, su, vl, vu = setMask()\r\n low = np.array([hl, sl, vl])\r\n up = np.array([hu, su, vu]) \r\n mask = cv.inRange(hsv_roi, low, up)\r\n hist = cv.calcHist([hsv_roi], [0], mask, [180], [0,180])\r\n cv.normalize(hist, hist, 0, 255, cv.NORM_MINMAX)\r\n\r\n return [hist]\r\n\r\ndef setMask():\r\n cv.namedWindow(\"Settings\")\r\n cv.resizeWindow(\"Settings\", 640, 250)\r\n\r\n cv.createTrackbar(\"H Low\", \"Settings\", 0, 180, nothing)\r\n cv.createTrackbar(\"H Up\", \"Settings\", 0, 180, nothing)\r\n cv.createTrackbar(\"S Low\", \"Settings\", 0, 255, nothing)\r\n cv.createTrackbar(\"S Up\", \"Settings\", 0, 255, nothing)\r\n cv.createTrackbar(\"V Low\", \"Settings\", 0, 255, nothing)\r\n cv.createTrackbar(\"V Up\", \"Settings\", 0, 255, nothing)\r\n\r\n cv.setTrackbarPos(\"H Low\", \"Settings\", 0)\r\n cv.setTrackbarPos(\"H Up\", \"Settings\", 180)\r\n cv.setTrackbarPos(\"S Low\", \"Settings\", 0)\r\n cv.setTrackbarPos(\"S Up\", \"Settings\", 255)\r\n cv.setTrackbarPos(\"V Low\", \"Settings\", 0)\r\n cv.setTrackbarPos(\"V Up\", \"Settings\", 255)\r\n\r\n while (1):\r\n _,frame = cap.read()\r\n frame = cv.flip(frame, 1)\r\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\r\n\r\n hl = cv.getTrackbarPos(\"H Low\", \"Settings\")\r\n hu = cv.getTrackbarPos(\"H Up\", \"Settings\")\r\n sl = cv.getTrackbarPos(\"S Low\", \"Settings\")\r\n su = cv.getTrackbarPos(\"S Up\", \"Settings\")\r\n vl = cv.getTrackbarPos(\"V Low\", \"Settings\")\r\n vu = cv.getTrackbarPos(\"V Up\", \"Settings\")\r\n \r\n low = np.array([hl, sl, vl])\r\n up = np.array([hu, su, vu])\r\n\r\n mask = cv.inRange(hsv, low, up)\r\n ker = np.ones((5, 5), np.uint8)\r\n\r\n mask = cv.morphologyEx(mask, cv.MORPH_CLOSE, ker)\r\n mask = cv.dilate(mask, ker, iterations = 1)\r\n mask = cv.morphologyEx(mask, cv.MORPH_OPEN, ker)\r\n mask = cv.medianBlur(mask, 15)\r\n res = cv.bitwise_and(frame, frame, mask = mask)\r\n \r\n cv.imshow(\"Original\", frame)\r\n cv.imshow(\"Filter\", res)\r\n\r\n k = cv.waitKey(1)\r\n if k & 0xFF == ord(\"s\"):\r\n break\r\n \r\n cv.destroyAllWindows()\r\n \r\n return hl, hu, sl, su, vl, vu\r\n\r\ndef subtractBg(frame):\r\n fgMask = bgCap.apply(frame, learningRate = 0)\r\n ker = np.ones((3,3), np.uint8)\r\n fgMask = cv.erode(fgMask, ker, iterations = 1)\r\n res = cv.bitwise_and(frame, frame, mask = fgMask)\r\n \r\n return res\r\n\r\ndef findMaxContour(rThresh):\r\n _,con,_ = cv.findContours(rThresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\r\n max_i = 0\r\n max_area = 0\r\n for i in range(len(con)):\r\n hand = con[i]\r\n area_hand = cv.contourArea(hand)\r\n if area_hand > max_area:\r\n max_area = area_hand\r\n max_i = i\r\n try:\r\n max_con = con[max_i]\r\n except:\r\n con = [0]\r\n max_con = con[0]\r\n \r\n return con, max_con\r\n\r\ndef findFingers(res, max_con):\r\n try:\r\n hull = cv.convexHull(max_con, returnPoints = False)\r\n defects = cv.convexityDefects(max_con, hull)\r\n if defects is None:\r\n defects = [0]\r\n num_def = 0\r\n else:\r\n num_def = 0\r\n for i in range(defects.shape[0]):\r\n s,e,f,d = defects[i,0]\r\n start = tuple(max_con[s][0])\r\n end = tuple(max_con[e][0])\r\n far = tuple(max_con[f][0])\r\n \r\n a = math.sqrt((end[0] - start[0])**2 + (end[1] - start[1])**2)\r\n b = math.sqrt((far[0] - start[0])**2 + (far[1] - start[1])**2)\r\n c = math.sqrt((end[0] - far[0])**2 + (end[1] - far[1])**2)\r\n s = (a+b+c)/2\r\n ar = math.sqrt(s*(s-a)*(s-b)*(s-c))\r\n \r\n d = (2*ar)/a\r\n \r\n angle = math.acos((b**2 + c**2 - a**2) / (2*b*c)) * 57\r\n \r\n if angle <= 90 and d > 30:\r\n num_def += 1\r\n cv.circle(res, far, 3, (255,0,0), -1)\r\n \r\n cv.line(res, start, end, (0,0,255), 2)\r\n \r\n return defects, num_def\r\n \r\n except:\r\n defects = [0]\r\n num_def = 0\r\n \r\n return defects, num_def\r\n\r\ndef centroid(max_con):\r\n moment = cv.moments(max_con)\r\n if moment is None:\r\n cx = 0\r\n cy = 0\r\n \r\n return cx, cy\r\n \r\n else:\r\n cx = 0\r\n cy = 0\r\n if moment[\"m00\"] != 0:\r\n cx = int(moment[\"m10\"] / moment[\"m00\"])\r\n cy = int(moment[\"m01\"] / moment[\"m00\"])\r\n\r\n return cx, cy\r\n \r\ndef findFarPoint(res, cx, cy, defects, max_con):\r\n try:\r\n s = defects[:,0][:,0]\r\n\r\n x = np.array(max_con[s][:,0][:,0], dtype = np.float)\r\n y = np.array(max_con[s][:,0][:,1], dtype = np.float)\r\n\r\n xp = cv.pow(cv.subtract(x, cx), 2)\r\n yp = cv.pow(cv.subtract(y, cy), 2)\r\n \r\n dist = cv.sqrt(cv.add(xp, yp))\r\n dist_max_i = np.argmax(dist)\r\n\r\n if dist_max_i < len(s):\r\n farthest_defect = s[dist_max_i]\r\n farthest_point = tuple(max_con[farthest_defect][0])\r\n\r\n cv.line(res, (cx,cy), farthest_point, (0,255,255), 2)\r\n \r\n return farthest_point\r\n \r\n except:\r\n farthest_point = 0\r\n \r\n return farthest_point\r\n\r\ndef recognizeGestures(frame, num_def, count, farthest_point):\r\n try:\r\n if num_def == 1:\r\n cv.putText(frame, \"2\", (0,50), cv.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 3, cv.LINE_AA)\r\n if count == 0:\r\n mouse.release(Button.left)\r\n mouse.position = (341, 82)\r\n mouse.press(Button.left)\r\n mouse.release(Button.left)\r\n mouse.position = farthest_point\r\n count = 1\r\n \r\n elif num_def == 2:\r\n cv.putText(frame, \"3\", (0,50), cv.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 3, cv.LINE_AA)\r\n if count == 0:\r\n mouse.release(Button.left)\r\n mouse.position = (254, 106)\r\n mouse.press(Button.left)\r\n mouse.release(Button.left)\r\n mouse.position = farthest_point\r\n count = 1\r\n \r\n elif num_def == 3:\r\n cv.putText(frame, \"4\", (0,50), cv.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 3, cv.LINE_AA)\r\n if count == 0:\r\n mouse.release(Button.left)\r\n mouse.position = (837, 69)\r\n mouse.press(Button.left)\r\n mouse.release(Button.left)\r\n mouse.position = farthest_point\r\n count = 1\r\n \r\n elif num_def == 4:\r\n cv.putText(frame, \"5\", (0,50), cv.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 3, cv.LINE_AA)\r\n if count == 0:\r\n mouse.release(Button.left)\r\n mouse.position = (772, 69)\r\n mouse.press(Button.left)\r\n mouse.release(Button.left)\r\n mouse.position = farthest_point\r\n count = 1\r\n \r\n else:\r\n cv.putText(frame, \"1\", (0,50), cv.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 3, cv.LINE_AA)\r\n mouse.position = farthest_point\r\n mouse.press(Button.left)\r\n count = 0\r\n\r\n except:\r\n print(\"You moved the hand too fast or take it out of range of vision of the camera\")\r\n\r\ncap = cv.VideoCapture(1)\r\n\r\n_,firstFrame = cap.read()\r\nfirstFrame = cv.flip(firstFrame, 1)\r\nr,h,c,w = 0,240,0,640\r\ntrack_window = (c,r,w,h)\r\n[hist] = histogram(firstFrame, r, h, c, w)\r\nterm_crit = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1)\r\n\r\nbgCaptured = False\r\ncv.namedWindow(\"Value\")\r\ncv.resizeWindow(\"Value\", 300, 25)\r\ncv.createTrackbar(\"Value\", \"Value\", 0, 255, nothing)\r\ncv.setTrackbarPos(\"Value\", \"Value\", 20)\r\n\r\nmouse = Controller()\r\ncount = 0\r\nex = 0\r\n\r\ntrigger = False\r\nos.startfile(\"C:\\Windows\\system32\\mspaint.exe\")\r\n\r\nwhile (1):\r\n ret,frame = cap.read()\r\n frame = cv.flip(frame, 1)\r\n\r\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\r\n dst = cv.calcBackProject([hsv], [0], hist, [0,180], 1)\r\n ret,track_window = cv.CamShift(dst, track_window, term_crit)\r\n pts = cv.boxPoints(ret)\r\n pts = np.int0(pts)\r\n\r\n if bgCaptured is True:\r\n mask = subtractBg(frame)\r\n\r\n vThresh = cv.getTrackbarPos(\"Value\", \"Value\")\r\n \r\n ker = np.ones((5,5), np.uint8)\r\n\r\n img = np.zeros(frame.shape, np.uint8)\r\n chanCount = mask.shape[2]\r\n ignoreColor = (255,) * chanCount\r\n cv.fillConvexPoly(img, pts, ignoreColor)\r\n res = cv.bitwise_and(mask, img)\r\n\r\n resMask = cv.dilate(res, ker, iterations = 1)\r\n resMask = cv.morphologyEx(resMask, cv.MORPH_OPEN, ker)\r\n resMask = cv.medianBlur(resMask, 15)\r\n resMask = cv.cvtColor(resMask, cv.COLOR_BGR2GRAY)\r\n _,rThresh = cv.threshold(resMask, vThresh, 255, cv.THRESH_BINARY)\r\n \r\n con, max_con = findMaxContour(rThresh)\r\n \r\n defects, num_def = findFingers(res, max_con)\r\n \r\n cx, cy = centroid(max_con)\r\n if np.all(con[0] > 0):\r\n cv.circle(res, (cx,cy), 5, (0,255,0), 2)\r\n else:\r\n pass\r\n \r\n farthest_point = findFarPoint(res, cx, cy, defects, max_con)\r\n\r\n if trigger is True:\r\n recognizeGestures(frame, num_def, count, farthest_point)\r\n\r\n cv.imshow(\"Live\", frame)\r\n cv.imshow(\"Result\", res)\r\n cv.imshow(\"Threshold\", rThresh)\r\n cv.imshow(\"Mask\", mask)\r\n #cv.imshow(\"test\", )\r\n\r\n k = cv.waitKey(1) \r\n if k & 0xFF == 27:\r\n break\r\n elif k == ord(\"c\"):\r\n bgCap = cv.createBackgroundSubtractorMOG2(0,50)\r\n bgCaptured = True\r\n elif k == ord(\"a\"):\r\n trigger = True\r\n \r\ncv.destroyAllWindows()\r\nos.system(\"TASKKILL /F /IM mspaint.exe\")\r\ncap.release()\r\n","sub_path":"Prototype.py","file_name":"Prototype.py","file_ext":"py","file_size_in_byte":10214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497417810","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 4 17:22:12 2019\n\nObjective: Load and clean League of Legends game data to identify important \n game features that contribute and predict game outcome. This is important \n because the goal of many players is to identify aspects of the game to improve\n on and the analyses outlined below is generalizable to all skill-based games\n and sports.\n \nData from: https://github.com/DoransLab/data/tree/master/champion_clustering\n\n@author: Zhe Charles Zhou\n\"\"\"\n\n#### Import toolboxes\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# use riotAPI_matchInfo for individual match info; riotAPI_avgMatchInfo to take avg across all matches for each sample\nfrom riotAPI_avgMatchInfo import dfPlayer, dataYPlayer # IMPORTANT: separate script to pull data from RiotAPI for specific player data\n\n\nfrom skopt import BayesSearchCV\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.model_selection import GridSearchCV,train_test_split,cross_val_score\nfrom sklearn.metrics import classification_report,confusion_matrix\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_curve, roc_auc_score\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#### Load data\n\ndata=pd.read_csv(\"C:\\\\Users\\\\The Iron Maiden\\\\Documents\\\\DataScienceProjects\\\\totalSup.csv\")\n\n# make the column names reference-friendly\ndata.columns = data.columns.str.strip().str.lower().str.replace(' ', '_')\nprint(data.columns)\n\n# separate category and feature data\ndataX_all=data.drop('win',axis=1)\ndataY=data['win']\n\n# define columns to analyze\ncolumns2Keep = ['champion_name','match_rank_score','max_time','gold_earned','wards_placed','damage_dealt_to_objectives','damage_dealt_to_turrets','kda','total_damage_dealt_to_champions', 'total_damage_taken', 'total_minions_killed']\ndataX = dataX_all[columns2Keep]\n\n# append player data for on hot encoding and scaling\nnumPlayerSamps = dfPlayer.shape[0]\n\n###### Logistic regression Data Preprocessing\n\n# Define which columns should be encoded vs scaled\ncolumns_to_encode = ['champion_name']\ncolumns_to_scale = columns2Keep[1:]\n# we're going to encode the categorical data together (dataX + player) since we might find new champions in the player data\ndataToEncode_plusPlayer = dataX[columns_to_encode].append(dfPlayer[columns_to_encode])\n\n# Instantiate encoder/scaler\nscaler = StandardScaler()\nohe = OneHotEncoder(sparse=False)\n# Scale and Encode the continuous and categorical data separately\nscaled_columnsX = scaler.fit_transform(dataX[columns_to_scale]) \nencoded_columns = ohe.fit_transform(dataToEncode_plusPlayer)\n\nscaled_columns_player = scaler.transform(dfPlayer[columns_to_scale]) \n\n# IMPORTANT: split appended player data off after one hot encoding \nencodedColumnsX = encoded_columns[:-numPlayerSamps,:]\nencodedColumns_Player = encoded_columns[-numPlayerSamps:,:]\n\n# Concatenate (Column-Bind) Processed Columns Back Together\nprocessedX = np.concatenate([scaled_columnsX, encodedColumnsX], axis=1)\nprocessedPlayerX = np.concatenate([scaled_columns_player, encodedColumns_Player], axis=1)\n\n\n# from scikitlearn: split data into test and training sets\nxTrain,xTest,yTrain,yTest=train_test_split(processedX,dataY,test_size=0.2,random_state=42)\n\n###### Logistic regression\n\nparams_lrc=[\n{\n 'penalty':['l1','l2'],\n 'C':[ 0.01, 0.1,1, 10],\n 'random_state':[0]\n },\n]\n\n\nlrc=LogisticRegression()\n\ngs_model = GridSearchCV(lrc, params_lrc, cv= 5, scoring='accuracy') \ngs_model.fit(xTrain, yTrain)\nprint('Best parameters set:')\nprint(gs_model.best_params_)\n\npred = gs_model.predict(xTest)\n\nfrom sklearn.metrics import accuracy_score\nprint('Optimized logistic regression performance: ',\n round(accuracy_score(yTest,pred),5)*100,'%')\n\n# save the model to disk\n#filename = 'final_logRegLoL.sav'\n#pickle.dump(gs_model, open(filename, 'wb'))\n#gs_model = pickle.load(open(filename, 'rb'))\n\n#### examine contribution of variables to win\n\nnumVars = len(columns_to_scale)\n\nbestLR=LogisticRegression(C=1,penalty='l1',random_state=0)\nbestLR.fit(xTrain, yTrain)\n\nlogCoefs = bestLR.coef_\n\nx_labels = ['Rank','MaxTime','Gold','Wards','ObjDmg','TurretDmg','KDA','ChampDmg', 'dmgTaken', 'minion#','percDmgTaken']\nplt.bar(columns_to_scale[0:numVars],logCoefs[0,0:numVars])\nplt.ylabel('Coef Score')\nplt.xticks(np.arange(numVars), x_labels, rotation = 45, fontsize=13 )\nplt.title('Log Reg Coef Scores')\n\n# plot absolute value of coeff and sort by highest coeff\n\nlogCoefs_abs = abs(bestLR.coef_)\nlogCoefs_absSort = sorted(logCoefs_abs[0,0:numVars],reverse=True)\nsortedInds = np.argsort(-logCoefs_abs[0,0:numVars])\n\nplt.figure(figsize=(10,5))\nplt.bar(columns_to_scale[0:numVars],logCoefs_absSort)\nplt.ylabel('Coefficient Score (Impact)', fontsize=25)\nplt.xticks(np.arange(numVars), [x_labels[i] for i in sortedInds], rotation = 45, fontsize=17 ) # need to reorder x labels according to sorting of coeffs\nplt.yticks(fontsize=20)\nplt.title('Player Metrics Sorted by Impact on Win/Loss', fontsize=27)\n\n#### calculate model performance for test data\n\n## calculate predicted probability\n#prob = gs_model.predict_proba(xTest)[:,1]\n## calculate true and false pos \n#falsePos,truePos,thresh = roc_curve(yTest,prob)\n##Calculate area under the curve\n#AUCscore = roc_auc_score(yTest,prob)\n#\n## ROC plot\n#sns.set_style('whitegrid')\n#plt.figure(figsize=(8,5))\n#\n#plt.plot(falsePos,truePos)\n#plt.plot([0,1],ls='--')\n#plt.plot([0,0],[1,0],c='.5')\n#plt.plot([1,1],c='.5')\n#\n#plt.title('ROC Curve; AUC = ' + str(round(AUCscore,5)) + '; Model Test Accuracy = ' + str(round(accuracy_score(yTest,pred),3)*100) + '%')\n#plt.ylabel('True positive rate')\n#plt.xlabel('False positive rate')\n#plt.show()\n\n#### Now predict game outcome for player data pulled from riot API\n\npred = gs_model.predict(processedPlayerX)\n\nprint('Optimized logistic regression performance: ',\n round(accuracy_score(dataYPlayer,pred),5)*100,'%')\n\n# calculate predicted probability\nprob = gs_model.predict_proba(processedPlayerX)[:,1]\n# calculate true and false pos \nfalsePos,truePos,thresh = roc_curve(dataYPlayer,prob)\n#Calculate area under the curve\nAUCscore = roc_auc_score(dataYPlayer,prob)\n\n# ROC plot\nsns.set_style('whitegrid')\nplt.figure(figsize=(8,5))\n\nplt.plot(falsePos,truePos)\nplt.plot([0,1],ls='--')\nplt.plot([0,0],[1,0],c='.5')\nplt.plot([1,1],c='.5')\n\nplt.title('ROC Curve; AUC = ' + str(round(AUCscore,5)) + '; Model Test Accuracy = ' + str(round(accuracy_score(dataYPlayer,pred),3)*100) + '%',fontsize = 20)\nplt.ylabel('True positive rate',fontsize = 20)\nplt.xlabel('False positive rate',fontsize = 20)\nplt.yticks(fontsize=20)\nplt.xticks(fontsize=20)\nplt.show()\n\n######\n\ntmpDf = pd.DataFrame(np.array([[1,10], [2,100],[3,50] ]),columns = ['var1','var2'])\ntmpNormDf=( df_2norm-df_2norm.min() )/( df_2norm.max()-df_2norm.min() )\n\nimport plotly.graph_objects as go\n\n# append column for data group\ntmpData = dataX.drop('champion_name',axis=1).assign(Group='data')\ntmpDataPlayer = dfPlayer.drop('champion_name',axis=1).assign(Group='player')\nallDataWithPlayer = tmpData.append(tmpDataPlayer, ignore_index=True)\n\n# normalize (0-1) ccontinuous data and add back on group\ndf_2norm = allDataWithPlayer.iloc[:,1:-1]\nnormalized_df=( df_2norm-df_2norm.min() )/( df_2norm.max()-df_2norm.min() )\nnormalized_df['Group']=allDataWithPlayer['Group']\n\ncol2Group = columns2Keep[1:-1]\njustDataData = normalized_df.loc[normalized_df['Group'] == 'data']\nnorm_dataMean = justDataData[0:1000].mean(axis=0)\nnorm_playerMean = normalized_df.loc[normalized_df['Group'] == 'player'].mean(axis=0)\n\n#################\n\ncategories = columns2Keep[1:-1]\n\nfig = go.Figure()\n\nfig.add_trace(go.Scatterpolar(\n r=norm_dataMean,\n theta=categories,\n fill='toself',\n name='Average Player Performance'\n))\n\nfig.add_trace(go.Scatterpolar(\n r=norm_playerMean,\n theta=categories,\n fill='toself',\n name='Your Performance'\n))\n\nfig.update_layout(\n polar=dict(\n radialaxis=dict(\n visible=True,\n \n )),\n showlegend=True\n)\n# fig.show()\nplot(fig, auto_open=True)\n\n\n\n","sub_path":"League_Classifier_riotAPI.py","file_name":"League_Classifier_riotAPI.py","file_ext":"py","file_size_in_byte":8093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"69003751","text":"\"\"\"\nRuffus pipeline to benchmark varying different datasets\n\n\"\"\"\n\nimport networkx as nx\nimport pysubiso\nimport tarfile\nfrom pysubiso import util\nimport os\nimport numpy as np\nimport time\nimport pickle\n\nfrom tqdm import tqdm\nimport pandas as pd\nfrom ruffus import *\n\n\n\nEXPERIMENTS = {'debug_100' : {'files' : ['/tmp/slow_graphs.00000000.tar.gz'],\n 'matchers' : ['ri', 'lemon'],\n 'timeout' : 10.0,\n 'num' : 100},\n \n 'allgraphs_4000' : {'files' : ['all_graphs.00000000.tar.gz',\n 'all_graphs.00000001.tar.gz',\n 'all_graphs.00000002.tar.gz',\n 'all_graphs.00000003.tar.gz', ],\n 'matchers' : ['ri', 'lemon'],\n 'timeout' : 1.0, \n 'num' : 1000}, \n 'riperf5' : {'files' : ['all_graphs.00000000.tar.gz',\n 'all_graphs.00000001.tar.gz',\n 'all_graphs.00000002.tar.gz',\n 'all_graphs.00000003.tar.gz', ],\n 'matchers' : ['ri'],\n 'timeout' : 1.0, \n 'num' : 100}, \n # 'debug_400' : {'files' : ['/tmp/slow_graphs.00000000.tar.gz'],\n # 'matchers' : ['ri', 'lemon'],\n # 'num' : 400}\n\n 'benchmark_newnew_100' : {'files' : ['all_graphs.00000000.tar.gz',\n \n ],\n 'matchers' : ['ri', 'lemon'],\n 'timeout' : 1.0, \n 'num' : 100}, \n\n 'allgraphs_4000_faster' : {'files' : ['all_graphs.00000000.tar.gz',\n 'all_graphs.00000001.tar.gz',\n 'all_graphs.00000002.tar.gz',\n 'all_graphs.00000003.tar.gz', ],\n 'matchers' : ['ri', 'lemon'],\n 'timeout' : 1.0, \n 'num' : 1000},\n\n 'allgraphs_4000_with_next_edges' : {'files' : ['all_graphs.00000000.tar.gz',\n 'all_graphs.00000001.tar.gz',\n 'all_graphs.00000002.tar.gz',\n 'all_graphs.00000003.tar.gz', ],\n 'matchers' : ['ri', 'lemon'],\n 'timeout' : 1.0, \n 'num' : 1000},\n 'slow_200' : {'files' : ['/tmp/slow_graphs.00000000.tar.gz'],\n 'matchers' : ['ri', 'lemon'],\n 'timeout' : 10.0,\n 'num' : 200}, \n}\n\ndef params():\n for exp_name, ec in EXPERIMENTS.items():\n infiles = ec['files']\n for matcher in ec['matchers']:\n \n outfiles = f\"results.{exp_name}.{matcher}.pickle\"\n yield infiles, outfiles, exp_name, ec, matcher, ec['num'], ec['timeout']\n\n@files(params)\ndef run_exp(infiles, outfile, exp_name, ec, matcher, num, TIMEOUT):\n\n m = pysubiso.create_match(matcher)\n\n log = []\n\n possible_edges = np.array([1, 2, 3, 4], dtype=np.int32)\n for filename in infiles:\n tf_load = tarfile.open(filename, mode='r:gz') \n n = tf_load.getnames()[:num]\n\n pairs = [os.path.dirname(s) for s in n]\n for p in tqdm(pairs):\n main = tf_load.extractfile(p + \"/main.graphml\").read()\n sub = tf_load.extractfile(p + \"/sub.graphml\").read()\n g_main = nx.parse_graphml(main, node_type=int)\n g_sub = nx.parse_graphml(sub, node_type=int)\n\n g_adj, g_color = util.nx_to_adj(g_main)\n\n g_sub_adj, g_sub_color = util.nx_to_adj(g_sub)\n\n\n t1 = time.time()\n timeout = False\n try:\n candidate_edges = pysubiso.gen_possible_next_edges(g_sub_adj, possible_edges)\n\n valid_indsubiso = m.edge_add_indsubiso(g_sub_adj, g_sub_color,\n g_adj, g_color,\n candidate_edges, TIMEOUT)\n except pysubiso.TimeoutError as e:\n timeout = True\n\n t2 = time.time()\n\n log.append({\"id\" : p,\n \"runtime\" : t2-t1,\n 'timed_out' : timeout,\n 'timeout' : TIMEOUT, \n 'matcher' : matcher,\n 'filename' : filename, \n \"g_main_nodes\" : len(g_main.nodes),\n \"g_sub_nodes\" : len(g_sub.nodes)})\n\n df = pd.DataFrame(log)\n pickle.dump(df, open(outfile, 'wb'))\n\n\n\nif __name__ == \"__main__\":\n pipeline_run([run_exp])\n","sub_path":"benchmark/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":5264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"305210595","text":"# client.py \nimport tkinter as tk\nimport tkinter.scrolledtext as tkst\nimport tkinter.messagebox as tkmb\nimport socket\nimport threading\nfrom threading import Thread\nimport _thread\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n tk.Frame.__init__(self, master)\n self.pack()\n self.createWidgets()\n t = threading.Thread(target=self.listener)\n t.daemon = True # thread dies when main thread (only non-daemon thread) exits.\n t.start()\n\n def createWidgets(self):\n self.text_box = tkst.ScrolledText(self, height = 20, width = 50)\n self.text_box.pack(side=\"top\")\n \n self.hi_there = tk.Button(self)\n self.hi_there[\"text\"] = \"Send\"\n self.hi_there[\"command\"] = self.say_hi\n self.hi_there.pack(side=\"right\")\n\n self.message = tk.Text(self, height = 3, width = 30)\n self.message.pack(side=\"bottom\")\n\n def say_hi(self):\n print(\"hi there, everyone!\")\n send_text = \"Jake: \" + self.message.get('1.0', tk.END)\n s.send(send_text.encode())\n self.message.delete('1.0', tk.END)\n\n def listener(self):\n print(\"Back in again\")\n try:\n while True:\n tm = s.recv(1024)\n if tm:\n print(\"Something to do\")\n self.text_box.insert(tk.END, tm.decode('ascii'))\n self.text_box.mark_set(tk.INSERT, '1.0')\n self.text_box.focus()\n else:\n print(\"Nothing to do\")\n finally:\n print(\"It broke\")\n\n# create a socket object\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n\n# get local machine name\nhost = socket.gethostname() \nprint(\"test1\")\nport = 9999\n\n# connection to hostname on the port.\ns.connect((host, port)) \nprint(\"test2\")\n# Receive no more than 1024 bytes \n\n#print(\"The time got from the server is %s\" % tm.decode('ascii'))\n\nroot = tk.Tk()\napp = Application(master=root)\napp.mainloop()\n\ns.close()","sub_path":"GUIclient.py","file_name":"GUIclient.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"456172397","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os, sys\nimport random\nimport re\nimport threading\n\nimport librosa\nimport pretty_midi\nimport numpy as np\nimport tensorflow as tf\n\nsys.path.append(os.path.join(os.getcwd(), os.pardir))\nfrom utils import find_files, roll_encode, roll_decode, get_roll_index\n\n\ndef randomize_files(files):\n for file in files:\n file_index = random.randint(0, (len(files) - 1))\n yield files[file_index]\n\n\ndef load_piece_data(directory,\n audio_sr,\n velocity,\n fac,\n valid=True):\n '''Loader that reads tune from directory and yields audio\n waveform and encoded piano roll as tuple of 3 arrays:\n (W, T, I). If more audio files represent single midi file,\n one is chosen randomly.\n '''\n\n midi_files = find_files(directory, '*.mid')\n randomized_midi_files = randomize_files(midi_files)\n\n for midi_filename in randomized_midi_files if valid else midi_files:\n # load piano roll from midi file\n proll = pretty_midi.PrettyMIDI(\n midi_filename).get_piano_roll(fs=int(audio_sr/fac))\n proll /= 127 # velocity to <0;1>\n if not velocity:\n proll[proll > 0] = 1\n # encode piano roll\n table, indices = roll_encode(proll, fac)\n # add 0-roll if not present (we will need it later for padding)\n if get_roll_index(table, np.zeros(128)).shape[0] == 0:\n table = np.concatenate((table, np.zeros(shape=(1, 128))))\n # get respective audio file names and choose 1 randomly\n base = midi_filename.rsplit('/', 1)[-1]\n base = re.sub(r'(.*)%s$' % re.escape('.mid'), r'\\1', base)\n audio_files = find_files(directory, base+'*.wav')\n if not audio_files:\n raise ValueError('No files found for \\'{}\\'.'.format(base+'*.wav'))\n audio_filename = random.choice(audio_files)\n # load audio waveform\n audio, _ = librosa.load(audio_filename, sr=audio_sr, mono=True)\n yield audio, table, indices\n\n\ndef sequence_samples(audio, table, indices, reader):\n '''Generator that yields batch samples as a tuple\n of numpy arrays (wave, roll) with shapes:\n wave.shape = (sample_size + receptive_field - 1, 1)\n roll.shape = (sample_size, 128)\n where sample_size is length of slice to which piece\n is cut. Last slice of a tune may have shape with\n length < sample_size.\n '''\n\n left = np.ceil((reader.receptive_field - 1) / 2).astype(int)\n right = np.floor((reader.receptive_field - 1) / 2).astype(int)\n # Ensure len(audio) == len(indices)\n if (audio.shape[0] < indices.shape[0]):\n # Cut piano roll down to length of audio sequence\n indices = indices[:audio.shape[0]]\n else:\n # Pad piano roll up to length of audio sequence, since this is\n # usually longer due to sustain of last notes\n indices = np.pad(indices,\n [0, audio.shape[0] - indices.shape[0]],\n 'constant',\n constant_values=get_roll_index(table, np.zeros(128))[0])\n # Pad audio sequence from left and right to provide context\n # to each estimate, receptive field is therefore centered\n # to time sample being calculated\n audio = np.pad(audio,\n [left, right],\n 'constant').reshape(-1, 1)\n\n if reader.sample_size:\n # Cut tune into sequences of size sample_size +\n # receptive_field - 1 with overlap = receptive_field - 1\n while len(audio) > reader.receptive_field:\n wave = audio[:(left + reader.sample_size + right), :]\n roll = roll_decode(table, indices[:reader.sample_size])\n yield wave, roll\n\n audio = audio[reader.sample_size:, :]\n indices = indices[reader.sample_size:]\n else:\n yield audio, roll_decode(table, indices)\n\n\nclass WavMidReader(object):\n '''Generic background music data reader that preprocesses audio files\n and enqueues them into a TensorFlow queue.\n '''\n\n def __init__(self,\n data_dir,\n coord,\n audio_sample_rate,\n receptive_field,\n velocity,\n sample_size,\n queues_size,\n compress_fac=10):\n self.data_dir = data_dir\n self.audio_sample_rate = audio_sample_rate\n self.compress_fac = compress_fac\n self.coord = coord\n self.receptive_field = receptive_field\n self.velocity = velocity\n self.sample_size = sample_size\n self.threads = []\n\n # Init queues and placeholders.\n self.queues = {'tune': {}, 'batch': {}}\n self.audio_placeholder = tf.placeholder(dtype=tf.float32, shape=(None,))\n self.table_placeholder = tf.placeholder(dtype=tf.float32, shape=(None,\n 128))\n self.indices_placeholder = tf.placeholder(dtype=tf.int32, shape=(None,))\n self.queues['tune']['Q'] = tf.FIFOQueue(queues_size[0],\n ['float32', 'float32', 'int32'])\n self.queues['tune']['enQ'] = self.queues['tune']['Q'].enqueue(\n [self.audio_placeholder,\n self.table_placeholder,\n self.indices_placeholder])\n self.wave_placeholder = tf.placeholder(dtype=tf.float32,\n shape=(None, 1))\n self.roll_placeholder = tf.placeholder(dtype=tf.float32,\n shape=(None, 128))\n self.queues['batch']['Q'] = tf.PaddingFIFOQueue(\n queues_size[1], ['float32', 'float32'],\n shapes=[(None, 1), (None, 128)])\n self.queues['batch']['enQ'] = self.queues['batch']['Q'].enqueue(\n [self.wave_placeholder, self.roll_placeholder])\n\n self.file_counter = tf.Variable(0, trainable=True)\n self.increment_file_counter = tf.assign(\n self.file_counter, self.file_counter+1)\n\n files = find_files(data_dir, '*.mid')\n if not files:\n raise ValueError('No midi files found in \\'{}\\'.'.format(data_dir))\n\n def dequeue(self, num_elements):\n output = self.queues['batch']['Q'].dequeue_many(num_elements)\n return output\n\n def thread_loader(self, sess):\n stop = False\n # Count tune data files\n n_midi_files = len(find_files(self.data_dir, '*.mid'))\n if n_midi_files == 0:\n raise ValueError('No files found for \\'{}\\'.'.format(\n directory+'/*.mid'))\n one_percent = int(np.ceil(n_midi_files/100))\n print('files length: {}'.format(n_midi_files))\n # Go through the dataset repeatedly until stopped\n while not stop:\n # Randomly iterate over files and fetch tune data\n file_iterator = load_piece_data(self.data_dir,\n self.audio_sample_rate,\n self.velocity,\n self.compress_fac)\n for audio, table, indices in file_iterator:\n sess.run(self.queues['tune']['enQ'],\n feed_dict={self.audio_placeholder: audio,\n self.table_placeholder: table,\n self.indices_placeholder: indices})\n # Track and report progress\n sess.run(self.increment_file_counter)\n file_counter = sess.run(self.file_counter)\n if file_counter % one_percent == 0:\n print('Training progress: {:.02f} epochs '\n '(file {} of {})'.format(file_counter/n_midi_files,\n file_counter, n_midi_files))\n if self.coord.should_stop():\n stop = True\n break\n\n def thread_generator(self, sess):\n stop = False\n # Go through the dataset repeatedly until stopped\n while not stop:\n # Dequeue tune data\n audio, table, indices = sess.run(self.queues['tune']['Q'].dequeue())\n # Fetch samples from the tune\n sample_iterator = sequence_samples(audio, table, indices, self)\n for wave, roll in sample_iterator:\n sess.run(self.queues['batch']['enQ'],\n feed_dict={self.wave_placeholder: wave,\n self.roll_placeholder: roll})\n if self.coord.should_stop():\n stop = True\n break\n\n def single_pass(self, sess, data_dir):\n for audio, table, indices in load_piece_data(data_dir,\n self.audio_sample_rate,\n self.velocity,\n self.compress_fac,\n valid=False):\n if self.coord.should_stop():\n break\n for wave, roll in sequence_samples(audio,\n table,\n indices,\n self):\n if self.coord.should_stop():\n break\n wave = np.expand_dims(wave, axis=0)\n yield wave, roll\n\n def start_threads(self, sess, n_threads=1):\n def _add_daemon_thread(reader, thread_func, sess):\n thread = threading.Thread(target=thread_func, args=(sess,))\n thread.daemon = True # Thread will close when parent quits.\n reader.threads.append(thread)\n\n # Single loader will suffice to possibly multiple generators\n _add_daemon_thread(self, self.thread_loader, sess)\n for _ in range(n_threads):\n _add_daemon_thread(self, self.thread_generator, sess)\n\n for thread in self.threads:\n thread.start()\n return self.threads\n","sub_path":"readers/wavmid_reader.py","file_name":"wavmid_reader.py","file_ext":"py","file_size_in_byte":10218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"44777410","text":"import psutil\n\n\ndef stats():\n cpu = (100 - (\n psutil\n .cpu_times_percent()\n .idle\n ))\n memory = (\n psutil\n .virtual_memory()\n .percent\n )\n users = sorted({user.name for user in psutil.users()})\n disk = (\n psutil\n .disk_usage('/')\n .percent\n )\n return '''\\\n CPU: {cpu:.0f}%\n Mem: {memory:.0f}%\n Disk: {disk:.0f}%\n Users: {users}\n '''.format(**locals())\n","sub_path":"healthchecker/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"382074998","text":"import pandas as pd\nimport numpy as np\n\ndef GetDM(api):\n dms = api.list_direct_messages(500)\n msg = []\n sender_id = []\n reciever_id = []\n timestamp = []\n for dm in dms:\n timestamp.append(dm._json['created_timestamp'])\n sender_id.append(dm._json['message_create']['sender_id'])\n reciever_id.append(dm._json['message_create']['target']['recipient_id'])\n msg.append(dm._json['message_create']['message_data']['text'])\n data_df = pd.DataFrame({\"timestamp\":timestamp,\"sender_id\":sender_id,\"reciever_id\":reciever_id,\"text\":msg},columns=['timestamp','sender_id','reciever_id','text'])\n data_df['timestamp'] = data_df['timestamp'].astype(float)\n data_df.sort_values(\"timestamp\",ascending=False,inplace=True)\n\n uid = api.me().id_str\n\n s_data = [api.get_user(sid)._json for sid in data_df[data_df['sender_id'] != uid]['sender_id']]\n s_data = list({s['id_str']:s for s in s_data}.values())\n\n\n return data_df,s_data","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"287012468","text":"import pytest\nfrom mixer.backend.django import mixer\nfrom graphql_relay.node.node import to_global_id\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.test import RequestFactory\n\n\nfrom .. import schema\n\n\npytestmark = pytest.mark.django_db\n\n\n'''\nTest for Model returns\n'''\n\n\ndef test_client_type():\n instance = schema.ClientType()\n assert instance\n\n\ndef test_product_type():\n instance = schema.ProductType()\n assert instance\n\n\ndef test_edge_type():\n instance = schema.EdgeType()\n assert instance\n\n\ndef test_node_type():\n instance = schema.NodeType()\n assert instance\n\n\ndef test_pallet_type():\n instance = schema.ProductBundleType()\n assert instance\n\n\ndef test_productbundle_type():\n instance = schema.ProductBundleType()\n assert instance\n\n\ndef test_movement_type():\n instance = schema.MovementType()\n assert instance\n\n\n'''\nTest for Queries\n'''\n\n\ndef test_resolve_all_clients():\n mixer.blend('inventory.Client')\n mixer.blend('inventory.Client')\n q = schema.Query()\n res = q.resolve_all_clients(None, None, None)\n assert res.count() == 2, 'Should return all clients'\n\n\ndef test_resolve_client():\n client = mixer.blend('inventory.Client')\n q = schema.Query()\n clientID = to_global_id('ClientType', client.pk)\n res = q.resolve_client({'id': clientID}, None, None)\n assert res == client, 'Should return the requested client'\n\n# Other tests needs to be defined\n\n'''\nMutation Tests\n'''\n\n\ndef test_create_message_mutation():\n user = mixer.blend('auth.User')\n mut = schema.CreateMessageMutation()\n\n data = {'message': 'Test'}\n req = RequestFactory().get('/')\n req.user = AnonymousUser()\n res = mut.mutate(None, data, req, None)\n assert res.status == 403, 'Should return 403 if user is not logged in'\n\n req.user = user\n res = mut.mutate(None, {}, req, None)\n assert res.status == 400, 'Should return 400 if there are form errors'\n assert 'message' in res.formErrors, (\n 'Should have form error for message field')\n\n res = mut.mutate(None, data, req, None)\n assert res.status == 200, 'Should return 200 if mutation is successful'\n assert res.message.pk == 1, 'Should create new message'","sub_path":"backend/inventory/tests/test_schema.py","file_name":"test_schema.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"84583016","text":"from keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy\n\n#fix random seed for reproducibility\n#numpy.random.seed(7)\n\n\n# 1 load pima indians dataset\ndataset = numpy.loadtxt(\"pima-indians-diabetes.csv\", delimiter=\",\")\n# split into input (X) and output (Y) variables\nX = dataset[:,0:8]\nY = dataset[:,8]\n\n# 2 create model\nmodel = Sequential()\n\n# it defines the input layer having 8 inputs\n# it defines a hidden layer with 12 neurons, connected to the input\n# using relu activation function\n# It initializes all weights using a sample of uniform random numbers.\nmodel.add(Dense(12, input_dim=8, activation='relu'))\n\nmodel.add(Dense(8, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\n\n\n# 3 compile\n# binary classification -> loss=binary crossentropy\n# adam optimizeer -> stochastic optimization\n# Finally, because it is a classification problem, \n# we will collect and report the classification accuracy as the metric.\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n# 4 fit the model\nmodel.fit(X, Y, epochs=150, batch_size=10)\n\n# 5 evaluate\nscores = model.evaluate(X,Y)\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n\n# calculate predictions\nprint(X)\npredictions = model.predict(X)\n# round predictions\nrounded = [round(x[0]) for x in predictions]\nprint(rounded)","sub_path":"sample_scripts/keras_sample.py","file_name":"keras_sample.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234200552","text":"from generator import Generator\n\nclass Kreator(Generator):\n\n def __init__(self, diagram, slave):\n self.diagram = Generator(diagram['states'], diagram['transitions'], diagram['form_to'])\n self.slave = Generator(slave['states'], slave['transitions'], slave['form_to'])\n\n self.curr_state = self.diagram.states[0]\n self.allowed_trans = self.diagram.allowed_transitions\n self.to_run = self.diagram\n\n self.state_master_to_slave = self.diagram.states[2]\n self.states_slave_to_master = [self.slave.states[1], self.slave.states[2]]\n\n self.trans_slave_to_master = [self.diagram.transitions[3], self.diagram.transitions[2]]\n\n def refresh(self):\n if self.to_run.current_state == self.state_master_to_slave:\n self.to_run = self.slave\n elif self.to_run.current_state in self.states_slave_to_master:\n self.to_run = self.diagram\n if self.slave.current_state == self.states_slave_to_master[0]:\n self.trans_slave_to_master[0]._run(self.to_run)\n elif self.slave.current_state == self.states_slave_to_master[1]:\n self.trans_slave_to_master[1]._run(self.to_run)\n self.reset_slave()\n\n self.curr_state = self.to_run.current_state\n self.allowed_trans = self.to_run.allowed_transitions\n\n def reset_slave(self):\n self.slave.current_state = self.slave.states[0]\n\n @staticmethod\n def identifier_to_index(to_run, transition):\n\n for ind, tran in enumerate(to_run.transitions):\n if tran.identifier == transition:\n return ind\n\n def run(self, transition):\n\n tran_index = self.identifier_to_index(self.to_run, transition)\n\n self.to_run.transitions[tran_index]._run(self.to_run)\n","sub_path":"scripts/kreator.py","file_name":"kreator.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"552046570","text":"from django.shortcuts import render,redirect, get_object_or_404\nfrom .models import Blog, Comment\n\n# Create your views here.\ndef main(request):\n blog = Blog.objects.all().order_by('-id')\n return render(request, 'main.html', {'blog':blog})\n\ndef detail(request, blog_id):\n blog = get_object_or_404(Blog, pk=blog_id)\n comment=Comment.objects.filter(post=blog.id)\n return render(request, 'detail.html', {'blog':blog, 'comment':comment})\n\ndef new(request):\n return render(request, 'new.html')\n\ndef create(request):\n blog = Blog()\n blog.user = request.user\n blog.title = request.GET['title']\n blog.body = request.GET['body']\n blog.save()\n return redirect('/detail/'+str(blog.id))\n\ndef renew(request, blog_id):\n blog = get_object_or_404(Blog, pk = blog_id)\n return render(request, 'renew.html', {'blog':blog})\n\ndef update(request, blog_id):\n blog = get_object_or_404(Blog, pk=blog_id)\n blog.title = request.GET['title']\n blog.body = request.GET['body']\n blog.save()\n return redirect('/detail/'+ str(blog.id))\n\ndef delete(request, blog_id):\n blog = get_object_or_404(Blog, pk=blog_id)\n blog.delete()\n return redirect('/')\n\ndef comment_create(request, blog_id):\n if request.method=='POST':\n comment = Comment()\n comment.user = request.user\n comment.post = Blog.objects.get(id=blog_id)\n comment.content = request.POST['comment']\n anonymous = request.POST.get('anonymous', True)\n if anonymous==\"y\":\n comment.anonymous=False\n comment.save()\n return redirect('/detail/'+str(blog_id))\n\ndef delete_comment(request, blog_id, comment_id):\n comment = Comment.objects.get(id=comment_id)\n comment.delete()\n return redirect('/detail/'+str(blog_id))","sub_path":"blogapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"421705191","text":"#coding=utf-8\n\n#Author: Jiangtian\n#Create Date:2018/08/03\n#Last Edited:2018/08/04\n\n#从刀区精华区的帖子列表中获取精品贴,并生成供版头使用的文本。因泥潭未登录时访问页面会经跳转,还是使用selenium实现\n\nfrom selenium import webdriver\nimport poster\n\ndef removetags(text): #去掉tag\n while text.find('[') != -1:\n bra = text.find('[')\n ket = text.find(']')\n text = text[:bra] + text[(ket+1):]\n if text[0] == ' ':\n text = text[1:]\n return text\n\n\ndef watchdog(bs): #判断精品贴的内容是否发生变化。如果精品贴的内容不变,返回0;否则返回变化后的文本,\n #并分别存入essence.txt、farmdepartment.txt、reddit.txt\n bs.get('http://bbs.ngacn.cc/thread.php?&recommend=1&fid=321&order_by=postdatedesc')\n\n \n with open ('lastpost.txt', 'r', encoding='utf-8') as f:\n lastpost = f.read()\n elements = bs.find_elements_by_class_name('topic')\n\n if elements[0].text == lastpost: #如果第一项没有变化,则直接返回0,退出函数\n return 0\n \n #如果否的话再更新内容\n with open ('essence.txt', 'r', encoding='utf-8') as f:\n jingpin = f.read().split('split')\n with open ('farmdepartment.txt', 'r', encoding='utf-8') as f:\n famubu = f.read().split('split')\n with open ('reddit.txt', 'r', encoding='utf-8') as f:\n hongdiwang = f.read().split('split')\n\n topic = []\n for i in elements:\n topic.append([i.text, i.get_attribute('href')]) #将帖子标题和url赋到list topic里\n\n #寻找lastpost在topic中的位置,来裁剪topic;然后再把topic的第一项赋给lastpost.txt\n lpplace = -1\n for i in range(len(topic)):\n if topic[i][0] == lastpost:\n lpplace = i\n break\n topic = topic[:lpplace]\n with open ('lastpost.txt', 'w', encoding='utf-8') as f:\n f.write(topic[0][0])\n\n #然后将topic倒序,从旧往新开始更新内容\n #先初始化开关和内容\n switch1 = 0\n switch2 = 0\n switch3 = 0\n text1 = ''\n text2 = ''\n text3 = ''\n topic.reverse()\n for i in topic:\n if (i[0].find('reddit周报') != -1) | (i[0].find('Reddit周报') != -1): #如果是红迪网周报\n processedurl = i[1].split('http://bbs.ngacn.cc')[1]\n processedcon = i[0][(i[0].find('eddit周报')+12):(i[0].find('eddit周报')+14)] #期数为两位数,在100期之后会发生问题……管他的,100期之后这玩意还有没有用都说不定了呢\n addtext = '[url={}][b]第{}期[/b][/url]'.format(processedurl, processedcon)\n hongdiwang.insert(0, addtext)\n hongdiwang.pop(-1)\n switch1 = 1\n elif i[0].find('阀木部') != -1: #如果是阀木部相关帖子\n processedurl = i[1].split('http://bbs.ngacn.cc')[1]\n processedcon = removetags(i[0])\n addtext = '[url={}][b]{}[/b][/url]'.format(processedurl, processedcon)\n famubu.insert(0, addtext)\n famubu.pop(-1)\n switch2 = 1\n else: #如果是一般的精品贴\n processedurl = i[1].split('http://bbs.ngacn.cc')[1]\n processedcon = removetags(i[0])\n addtext = '[url={}][b]{}[/b][/url]'.format(processedurl, processedcon)\n jingpin.insert(0, addtext)\n jingpin.pop(-1)\n switch3 = 1\n\n if switch1 == 1:#自动更新标记放在[size=140%][color=red][b]NEW![/b][/color][/size]后面\n text1 = '[size=120%]{st1}[/size]\\n[size=110%]{nd2}[/size]\\n[size=100%]{rd3}[/size]\\n[/align][align=center]{th4} {th5} {th6} {th7} {th8} {th9} {th10}[/align]'.format(st1=hongdiwang[0], nd2=hongdiwang[1], rd3=hongdiwang[2], th4=hongdiwang[3], th5=hongdiwang[4], th6=hongdiwang[5], th7=hongdiwang[6], th8=hongdiwang[7], th9=hongdiwang[8], th10=hongdiwang[9])\n #和[align=right][pid=265787209][b]更多节奏盘点[/b][/pid][/align][/td]前面\n with open ('reddit.txt', 'w', encoding='utf-8') as f:\n f.write('split'.join(hongdiwang))\n\n if switch2 == 1:#标记放在[l]后面和[/l]前面\n text2 = '[list]\\n[*]{st1}[color=red]~new~[/color]\\n[*]{st2}[color=red]~new~[/color]\\n[*]{st3}[color=red]~new~[/color]\\n[*]{st4}\\n[*]{st5}\\n[*]{st6}\\n[*]{st7}\\n[/list]'.format(st1=famubu[0], st2=famubu[1], st3=famubu[2], st4=famubu[3], st5=famubu[4], st6=famubu[5], st7=famubu[6])\n with open ('farmdepartment.txt', 'w', encoding='utf-8') as f:\n f.write('split'.join(famubu))\n\n if switch3 == 1:#标记放在[/h]后面和[/td]前面\n text3 = '[list]\\n[*]{st1}\\n[*]{st2}\\n[*]{st3}\\n[*]{st4}\\n[*]{st5}\\n[*]{st6}\\n[*]{st7}\\n[/list]'.format(st1=jingpin[0], st2=jingpin[1], st3=jingpin[2], st4=jingpin[3], st5=jingpin[4], st6=jingpin[5], st7=jingpin[6])\n with open ('essence.txt', 'w', encoding='utf-8') as f:\n f.write('split'.join(jingpin))\n \n return [text1, text2, text3]\n \n","sub_path":"project1/essence_old.py","file_name":"essence_old.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"467970409","text":"#!/usr/bin/env python3\n\n\"\"\"beeflow.\n\nThis script manages the startup of the BEE daemons and supporting services.\nIf no arguments are given this script will start the BEEWorkflowManager,\nBEETaskManager, and all required supporting services. If any combination of\nservices is specified using the appropriate flag(s) then ONLY those services\nwill be started.\n\"\"\"\nimport os\nimport signal\nimport subprocess\nimport socket\nimport sys\nimport shutil\nimport time\nimport importlib.metadata\n\nimport daemon\nimport typer\n\nfrom beeflow.common.config_driver import BeeConfig as bc\nfrom beeflow.common import cli_connection\nfrom beeflow.common import paths\n\n\nbc.init()\n# Max number of times a component can be restarted\nMAX_RESTARTS = bc.get('DEFAULT', 'max_restarts')\n\n\nclass ComponentManager:\n \"\"\"Component manager class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct the component manager.\"\"\"\n self.components = {}\n self.procs = {}\n\n def component(self, name, deps=None):\n \"\"\"Return a decorator function to be called.\"\"\"\n\n def wrap(fn):\n \"\"\"Add the component to the list.\"\"\"\n self.components[name] = {\n 'fn': fn,\n 'deps': deps,\n 'restart_count': 0,\n 'failed': False,\n }\n\n return wrap\n\n def _validate(self, base_components):\n \"\"\"Make sure that the components all exist and have valid deps.\"\"\"\n missing = [name for name in base_components if name not in self.components]\n for component in self.components.values():\n if component['deps'] is None:\n continue\n for dep in component['deps']:\n if dep not in self.components:\n missing.append(dep)\n if missing:\n raise RuntimeError(f'Missing/unknown component(s): {\",\".join(missing)}')\n\n def _find_order(self, base_components):\n \"\"\"Find the order of the dependencies to launch.\"\"\"\n s = base_components[:]\n levels = {name: 0 for name in self.components}\n while len(s) > 0:\n name = s.pop()\n if self.components[name]['deps'] is None:\n continue\n for dep in self.components[name]['deps']:\n levels[dep] = max(levels[name] + 1, levels[dep])\n # Detect a possible cycle\n if levels[dep] > len(self.components):\n raise RuntimeError(f'There may be a cycle for the \"{dep}\" component')\n s.append(dep)\n levels = list(levels.items())\n levels.sort(key=lambda t: t[1], reverse=True)\n return [name for name, level in levels]\n\n def run(self, base_components):\n \"\"\"Start and run everything.\"\"\"\n # Determine if there are any missing components listed\n self._validate(base_components)\n # Determine the order to launch components in (note: this should just ignore cycles)\n order = self._find_order(base_components)\n print(f'Launching components in order: {order}')\n # Now launch the components\n for name in order:\n component = self.components[name]\n self.procs[name] = component['fn']()\n\n def poll(self):\n \"\"\"Poll each process to check for errors, restart failed processes.\"\"\"\n for name in self.procs: # noqa no need to iterate with items() since self.procs may be set\n component = self.components[name]\n if component['failed']:\n continue\n returncode = self.procs[name].poll()\n if returncode is not None:\n log = paths.log_fname(name)\n print(f'Component \"{name}\" failed, check log \"{log}\"')\n if component['restart_count'] >= MAX_RESTARTS:\n print(f'Component \"{name}\" has been restarted {MAX_RESTARTS} '\n 'times, not restarting again')\n component['failed'] = True\n else:\n restart_count = component['restart_count']\n print(f'Attempting restart {restart_count} of \"{name}\"...')\n self.procs[name] = component['fn']()\n component['restart_count'] += 1\n\n def status(self):\n \"\"\"Return the statuses for each process in a dict.\"\"\"\n return {\n name: 'RUNNING' if proc.poll() is None else 'FAILED'\n for name, proc in self.procs.items()\n }\n\n def kill(self):\n \"\"\"Kill all components.\"\"\"\n for name, proc in self.procs.items():\n print(f'Killing {name}')\n proc.terminate()\n\n\nMGR = ComponentManager()\n\n\ndef warn(*pargs):\n \"\"\"Print a red warning message.\"\"\"\n typer.secho(' '.join(pargs), fg=typer.colors.RED, file=sys.stderr)\n\n\ndef launch_with_gunicorn(module, sock_path, *args, **kwargs):\n \"\"\"Launch a component with Gunicorn.\"\"\"\n # Setting the timeout to infinite, since sometimes the gdb can take too long\n return subprocess.Popen(['gunicorn', module, '--timeout', '0', '-b', f'unix:{sock_path}'],\n *args, **kwargs)\n\n\ndef open_log(component):\n \"\"\"Determine the log for the component, open and return it.\"\"\"\n log = paths.log_fname(component)\n return open(log, 'a', encoding='utf-8')\n\n\n# Slurmrestd will be started only if we're running with Slurm and\n# slurm::use_commands is not True\nNEED_SLURMRESTD = (bc.get('DEFAULT', 'workload_scheduler') == 'Slurm'\n and not bc.get('slurm', 'use_commands'))\n\n\n@MGR.component('wf_manager', ('scheduler',))\ndef start_wfm():\n \"\"\"Start the WFM.\"\"\"\n fp = open_log('wf_manager')\n return launch_with_gunicorn('beeflow.wf_manager.wf_manager:create_app()',\n paths.wfm_socket(), stdout=fp, stderr=fp)\n\n\nTM_DEPS = []\nif NEED_SLURMRESTD:\n TM_DEPS.append('slurmrestd')\n\n\n@MGR.component('task_manager', TM_DEPS)\ndef start_task_manager():\n \"\"\"Start the TM.\"\"\"\n fp = open_log('task_manager')\n return launch_with_gunicorn('beeflow.task_manager:flask_app', paths.tm_socket(),\n stdout=fp, stderr=fp)\n\n\n@MGR.component('scheduler', ())\ndef start_scheduler():\n \"\"\"Start the scheduler.\"\"\"\n fp = open_log('scheduler')\n # Using a function here because of the funny way that the scheduler's written\n return launch_with_gunicorn('beeflow.scheduler.scheduler:create_app()',\n paths.sched_socket(), stdout=fp, stderr=fp)\n\n\n# Workflow manager and task manager need to be opened with PIPE for their stdout/stderr\nif NEED_SLURMRESTD:\n @MGR.component('slurmrestd')\n def start_slurm_restd():\n \"\"\"Start BEESlurmRestD. Returns a Popen process object.\"\"\"\n bee_workdir = bc.get('DEFAULT', 'bee_workdir')\n slurmrestd_log = '/'.join([bee_workdir, 'logs', 'restd.log'])\n openapi_version = bc.get('slurm', 'openapi_version')\n slurm_args = f'-s openapi/{openapi_version}'\n slurm_socket = paths.slurm_socket()\n subprocess.run(['rm', '-f', slurm_socket], check=True)\n # log.info(\"Attempting to open socket: {}\".format(slurm_socket))\n fp = open(slurmrestd_log, 'w', encoding='utf-8') # noqa\n cmd = ['slurmrestd']\n cmd.extend(slurm_args.split())\n cmd.append(f'unix:{slurm_socket}')\n return subprocess.Popen(cmd, stdout=fp, stderr=fp)\n\n\ndef handle_terminate(signum, stack): # noqa\n \"\"\"Handle a terminate signal.\"\"\"\n # Kill all subprocesses\n MGR.kill()\n sys.exit(1)\n\n\nMIN_CHARLIECLOUD_VERSION = (0, 32)\n\n\ndef version_str(version):\n \"\"\"Convert a version tuple to a string.\"\"\"\n return '.'.join([str(part) for part in version])\n\n\ndef check_dependencies():\n \"\"\"Check for various dependencies in the environment.\"\"\"\n print('Checking dependencies...')\n # Check for Charliecloud and it's version\n if not shutil.which('ch-run'):\n warn('Charliecloud is not loaded. Please ensure that it is accessible on your path.')\n sys.exit(1)\n cproc = subprocess.run(['ch-run', '-V'], capture_output=True, text=True,\n check=True)\n version = cproc.stdout if cproc.stdout else cproc.stderr\n version = version.strip()\n version = tuple(int(part) for part in version.split('.'))\n print(f'Found Charliecloud {version_str(version)}')\n if version < MIN_CHARLIECLOUD_VERSION:\n warn('This version of Charliecloud is too old, please upgrade to at '\n f'least version {version_str(MIN_CHARLIECLOUD_VERSION)}')\n sys.exit(1)\n # Check for the flux API\n if bc.get('DEFAULT', 'workload_scheduler') == 'Flux':\n try:\n import flux # noqa needed to check whether flux api is actually installed\n except ModuleNotFoundError:\n warn('Failed to import flux Python API. Please make sure you can '\n 'use flux in your environment.')\n sys.exit(1)\n\n\nclass Beeflow:\n \"\"\"Beeflow class for handling the main loop.\"\"\"\n\n def __init__(self, mgr, base_components):\n \"\"\"Create the Beeflow class.\"\"\"\n self.mgr = mgr\n self.base_components = base_components\n self.quit = False\n\n def loop(self):\n \"\"\"Run the main loop.\"\"\"\n print(f'Running on {socket.gethostname()}')\n self.mgr.run(self.base_components)\n with cli_connection.server(paths.beeflow_socket()) as server:\n while not self.quit:\n # Handle a message from the client, if there is one\n self.handle_client(server)\n # Poll the components\n self.mgr.poll()\n time.sleep(1)\n # Kill everything, if possible\n self.mgr.kill()\n\n def handle_client(self, server):\n \"\"\"Handle a message from the client.\"\"\"\n try:\n client = server.accept()\n if client is None:\n return\n msg = client.get()\n resp = None\n if msg['type'] == 'status':\n resp = {\n 'components': self.mgr.status(),\n }\n print('Returned status info.')\n elif msg['type'] == 'quit':\n self.quit = True\n resp = 'shutting down'\n print('Shutting down.')\n client.put(resp)\n except cli_connection.BeeflowConnectionError as err:\n print(f'connection failed: {err}')\n\n\ndef daemonize(base_components):\n \"\"\"Start beeflow as a daemon, monitoring all processes.\"\"\"\n # Now set signal handling, the log and finally daemonize\n signal_map = {\n signal.SIGINT: handle_terminate,\n signal.SIGTERM: handle_terminate,\n }\n fp = open_log('beeflow')\n with daemon.DaemonContext(signal_map=signal_map, stdout=fp, stderr=fp, stdin=fp,\n umask=0o002):\n Beeflow(MGR, base_components).loop()\n\n\napp = typer.Typer(no_args_is_help=True)\n\n\n@app.command()\ndef start(foreground: bool = typer.Option(False, '--foreground', '-F',\n help='run in the foreground')):\n \"\"\"Attempt to daemonize if not in debug and start all BEE components.\"\"\"\n beeflow_log = paths.log_fname('beeflow')\n check_dependencies()\n sock_path = paths.beeflow_socket()\n if bc.get('DEFAULT', 'workload_scheduler') == 'Slurm' and not NEED_SLURMRESTD:\n warn('Not using slurmrestd. Command-line interface will be used.')\n # Note: there is a possible race condition here, however unlikely\n if os.path.exists(sock_path):\n # Try to contact for a status\n try:\n resp = cli_connection.send(sock_path, {'type': 'status'})\n except (ConnectionResetError, ConnectionRefusedError):\n resp = None\n if resp is None:\n # Must be dead, so remove the socket path\n try:\n os.remove(sock_path)\n except FileNotFoundError:\n pass\n else:\n # It's already running, so print an error and exit\n warn(f'Beeflow appears to be running. Check the beeflow log: \"{beeflow_log}\"')\n sys.exit(1)\n print('Starting beeflow...')\n if not foreground:\n print(f'Check \"{beeflow_log}\" or run `beeflow status` for more information.')\n # Create the log path if it doesn't exist yet\n path = paths.log_path()\n os.makedirs(path, exist_ok=True)\n base_components = ['wf_manager', 'task_manager', 'scheduler']\n if foreground:\n try:\n Beeflow(MGR, base_components).loop()\n except KeyboardInterrupt:\n MGR.kill()\n else:\n daemonize(base_components)\n\n\n@app.command()\ndef status():\n \"\"\"Check the status of beeflow and the components.\"\"\"\n resp = cli_connection.send(paths.beeflow_socket(), {'type': 'status'})\n if resp is None:\n beeflow_log = paths.log_fname('beeflow')\n warn('Cannot connect to the beeflow daemon, is it running? Check the '\n f'log at \"{beeflow_log}\".')\n sys.exit(1)\n print('beeflow components:')\n for comp, stat in resp['components'].items():\n print(f'{comp} ... {stat}')\n\n\n@app.command()\ndef stop():\n \"\"\"Stop the current running beeflow daemon.\"\"\"\n stop_msg = (\"\\n** Please ensure all workflows are complete before stopping beeflow. **\"\n + \"\\n** Check the status of workflows by running 'beeclient listall'. **\"\n + \"\\nAre you sure you want to kill beeflow components? [y/n] \")\n ans = input(stop_msg)\n if ans.lower() != 'y':\n return\n resp = cli_connection.send(paths.beeflow_socket(), {'type': 'quit'})\n if resp is None:\n beeflow_log = paths.log_fname('beeflow')\n warn('Error: beeflow is not running on this system. It could be '\n 'running on a different front end.\\n'\n f' Check the beeflow log: \"{beeflow_log}\".')\n sys.exit(1)\n # As long as it returned something, we should be good\n beeflow_log = paths.log_fname('beeflow')\n print(f'Beeflow has stopped. Check the log at \"{beeflow_log}\".')\n\n\n@app.command()\ndef restart(foreground: bool = typer.Option(False, '--foreground', '-F',\n help='run in the foreground')):\n \"\"\"Attempt to stop and restart the beeflow daemon.\"\"\"\n stop()\n start(foreground)\n\n\n@app.callback(invoke_without_command=True)\ndef version_callback(version: bool = False):\n \"\"\"Beeflow.\"\"\"\n # Print out the current version of the app, and then exit\n # Note above docstring gets used in the help menu\n if version:\n version = importlib.metadata.version(\"hpc-beeflow\")\n print(version)\n\n\ndef main():\n \"\"\"Start the beeflow app.\"\"\"\n app()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"beeflow/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":14670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"345604532","text":"#!/usr/bin/python\n\nimport os\nfrom flask import Flask\nfrom flask import request,render_template,abort,url_for,send_from_directory\nimport utils\n\nIMAGE_PATH = '/path/to/images/or/videos'\napp = Flask(__name__)\n\n@app.route('/images/')\ndef images(filepath):\n return send_from_directory(IMAGE_PATH, filepath)\n\n@app.route('/')\n@app.route('//')\ndef index(filepath=None):\n fullpath = os.path.join(IMAGE_PATH, filepath) if filepath else IMAGE_PATH\n if not utils.valid_path(fullpath, IMAGE_PATH):\n abort(404)\n if not os.path.exists(fullpath):\n abort(404)\n urlparts = utils.split_url(filepath) if filepath else []\n dirs, files = utils.ls(fullpath, filepath)\n images = utils.filter(files, 'jpg')\n videos = utils.filter(files, 'mp4', 'ogg')\n videos = utils.add_mimetype(videos)\n return render_template('index.html',urlparts=urlparts, dirs=dirs,\n images=images,videos=videos)\n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n\n","sub_path":"simplegallery.py","file_name":"simplegallery.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"143889085","text":"import numpy as np\r\nimport random\r\n# from ENV import LOW_MID_Y_kernel, MID_X_kernel, ground_y, LITE, EXPAND_KERNEL_DEF_DEPTH\r\n\r\n\r\n\r\ndef get_possible_action(m, PM, ENV, sp): # maybe also ground_y shoudl be used\r\n\r\n if sp is m.root: # just go straight up\r\n # only gives one try for these nodes, after this they can't expand\r\n if ENV.LITE == '25_40':\r\n hardcoded_firsts = [[2, 2], [3, 0]] # first one is both left and right. [y, x]\r\n elif ENV.LITE == '250_400':\r\n hardcoded_firsts = [[5, 8], [10, 0]]\r\n elif ENV.LITE == 'fin':\r\n hardcoded_firsts = [[5, 8], [10, 0]] # first one is both left and right\r\n\r\n ac = None # actionCoords\r\n if len(m.root.children) < 1:\r\n ac = [m.root.coords[0] - hardcoded_firsts[0][0], m.root.coords[1] - hardcoded_firsts[0][1]]\r\n elif len(m.root.children) < 2:\r\n ac = [m.root.coords[0] - hardcoded_firsts[1][0], m.root.coords[1]]\r\n elif len(m.root.children) < 3:\r\n ac = [m.root.coords[0] - hardcoded_firsts[0][0], m.root.coords[1] + hardcoded_firsts[0][1]]\r\n else:\r\n ac = [m.root.coords[0] - random.randint(5, 8), m.root.coords[1] + random.randint(-5, 5)]\r\n return ac, 'root_exp'\r\n\r\n\r\n kernel_type = 'right_up' # default\r\n diff_x = sp.coords[1] - sp.parent.coords[1] # if sp is to the right of sp.parent this is positive. if so do left move\r\n diff_x_g = sp.coords[1] - m.root.coords[1]\r\n if diff_x < 0: # sp to the left: i.e. movement is right\r\n kernel_type = 'left_up'\r\n if sp.d < PM.EXPAND_KERNEL_DEF_DEPTH or abs(diff_x_g) < PM.MID_X_kernel*2: # if it's centrally located\r\n kernel_type = 'default_up' #\r\n elif sp.d > PM.EXPAND_KERNEL_DEF_DEPTH and random.random() < 0.4:\r\n kernel_type = 'default' #\r\n\r\n hardcoded_area = check_hardcoded_area(sp.coords[0], sp.coords[1])\r\n if hardcoded_area == 'down':\r\n kernel_type = 'down'\r\n\r\n MULT_Y = 1\r\n MULT_X = 1 # epilogue. 3\r\n\r\n y_up = None\r\n y_do = None\r\n x_le = None\r\n x_ri = None\r\n\r\n if kernel_type == 'default_up': # UBE!!! will have to chagne for downward dir CHECK SIGN!\r\n y_up = -PM.LOW_MID_Y_kernel*MULT_Y # 16\r\n y_do = 0 # UBE\r\n x_le = -PM.MID_X_kernel\r\n x_ri = PM.MID_X_kernel + 1 + 1 # + 1 since this is positive, +1 UBE\r\n elif kernel_type == 'left_up':\r\n y_up = -PM.LOW_MID_Y_kernel\r\n y_do = 0 # UBE\r\n x_le = -PM.MID_X_kernel*MULT_X\r\n x_ri = 1\r\n elif kernel_type == 'right_up':\r\n y_up = -PM.LOW_MID_Y_kernel\r\n y_do = 0 # UBE\r\n x_le = 1\r\n x_ri = PM.MID_X_kernel*MULT_X + 1\r\n elif kernel_type == 'default':\r\n y_up = -PM.LOW_MID_Y_kernel * MULT_Y # 16\r\n y_do = PM.LOW_MID_Y_kernel * MULT_Y # UBE\r\n x_le = -PM.MID_X_kernel\r\n x_ri = PM.MID_X_kernel + 1 + 1 # + 1 since this is positive, +1 UBE\r\n elif kernel_type == 'down':\r\n y_up = -PM.LOW_MID_Y_kernel // 2\r\n y_do = PM.LOW_MID_Y_kernel * MULT_Y\r\n x_le = -PM.MID_X_kernel\r\n x_ri = PM.MID_X_kernel + 1 + 1 # + 1 since this is positive, +1 UBE\r\n\r\n pnc = ENV.e_o[(sp.coords[0] + y_up):min((sp.coords[0] + y_do), ENV.ground_y), (sp.coords[1] + x_le):(sp.coords[1] + x_ri)] # possibleNewCoords\r\n sun_c = ENV.e_s[(sp.coords[0] + y_up):min((sp.coords[0] + y_do), ENV.ground_y), (sp.coords[1] + x_le):(sp.coords[1] + x_ri)]\r\n tp_c = ENV.e_tp[(sp.coords[0] + y_up):min((sp.coords[0] + y_do), ENV.ground_y), (sp.coords[1] + x_le):(sp.coords[1] + x_ri)] # if tree_pic is gona be incorporated here\r\n\r\n pnc_li = np.argwhere(pnc == False) # OBS this is from the perspective of sp\r\n\r\n if len(pnc_li) < 1: # early exit; # nowhere to place child\r\n # sp.can_expand = False THIS IS HANDLED OUTSIDE\r\n # print(\"state \" + sp.id + \" is now not expandable\")\r\n return None, 'could_not_find_free_coords'\r\n\r\n # SELECT BEST VALUE WITHIN PNC -----------------\r\n free_sun_c_vals_ss = sun_c[pnc_li[:, 0], pnc_li[:, 1]] # these are organized as flattened array from the 2D one\r\n free_sun_c_vals = tp_c[pnc_li[:, 0], pnc_li[:, 1]] # these are organized as flattened array from the 2D one\r\n free_sun_c_vals_tp = free_sun_c_vals_ss * free_sun_c_vals\r\n if np.amax(free_sun_c_vals_tp) < 0.001 and random.random() < PM.TP_C: # the more TP_C, the more punishment\r\n return None, 'could_not_find_free_coords'\r\n # if random.random() < 0.99:\r\n best_c = np.argwhere(free_sun_c_vals_tp == np.amax(free_sun_c_vals_tp))[0][0]\r\n # else:\r\n # best_c = np.where(free_sun_c_vals == np.amax(free_sun_c_vals))[0][0]\r\n if random.random() < PM.EXPANSION_BIAS_P:\r\n pnc_coords = pnc_li[best_c]\r\n else:\r\n pnc_coords = random.choice(pnc_li)\r\n\r\n # 1. the kernel is placed on the env 2. ac starts at top left on the env-kernel. 3. ac is aligned.\r\n ac_start = [sp.coords[0] + y_up, sp.coords[1] + x_le] #\r\n ac = [ac_start[0] + pnc_coords[0], ac_start[1] + pnc_coords[1]]\r\n\r\n if ac[0] < 0 or ac[1] < 0 or ac[0] > ENV.ground_y:\r\n raise Exception(\"joException tree growing too large\")\r\n # logging\r\n if kernel_type == 'default_up':\r\n m.num_default_up_exp += 1\r\n elif kernel_type == 'left_up':\r\n m.num_left_up_exp += 1\r\n elif kernel_type == 'right_up':\r\n m.num_right_up_exp += 1\r\n elif kernel_type == 'default':\r\n m.num_default_exp += 1\r\n elif kernel_type == 'down':\r\n m.num_down_exp += 1\r\n\r\n return ac, 'sucess'\r\n\r\n\r\ndef get_pnc_li(m, sp, G_POINT):\r\n pnc = None\r\n kernel_type = 'right'\r\n diff_x = sp.coords[1] - G_POINT[1] # if sp is to the right of G this is positive\r\n if diff_x < 0: # sp to the left\r\n kernel_type = 'left'\r\n\r\n if kernel_type == 'right':\r\n pnc = m.e_o[(sp.coords[0] - LOW_MID_Y_kernel):sp.coords[0], (sp.coords[1] - MID_X_kernel):(\r\n sp.coords[1] + MID_X_kernel + 1)] # UBE!!! will have to chagne for downward dir CHECK SIGN!\r\n\r\n pnc_li = np.argwhere(pnc == False) # OBS this is from the perspective of sp\r\n\r\n return None\r\n\r\n\r\ndef check_hardcoded_area(y, x):\r\n ha = {'down': [[(563, 700), (748, 787)]]}\r\n ha = ha['down'][0]\r\n if (y > ha[0][0] and y < ha[0][1]) and (x > ha[1][0] and x < ha[1][1]):\r\n return 'down'\r\n else:\r\n return False\r\n\r\n\r\n","sub_path":"backup/MCTS_proj/utils_model.py","file_name":"utils_model.py","file_ext":"py","file_size_in_byte":6377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"819617","text":"import pytest\n\nfrom currency_service.extensions.fake.backends.catalog import (\n FakeCatalogBackend)\nfrom currency_service.product.models import Product\n\n\nclass TestFakeCatalogBackend:\n\n @pytest.fixture\n def backend(self):\n return FakeCatalogBackend()\n\n def test_get_should_return_an_product_object(self, backend):\n sku = 'jkqrm3214'\n seller = 'centauro'\n product = backend.get_product(sku=sku, seller=seller)\n assert isinstance(product, Product)\n assert product.sku == sku\n assert product.seller == seller\n","sub_path":"django/currency_service/extensions/fake/tests/backends/test_catalog.py","file_name":"test_catalog.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"267457376","text":"#! /bin/usr/python3\n#tablePrinter.py - prints list of lists of strings and displays it\n#in a well-organized table with each column right-justified\n\ndef printTable(data):\n lenWidths = [0] * len(data) # assign list for values of lengths of each line\n lines = [''] * len(data) # and lines themselves\n \n for i in range(len(data)): # converts each list to a line\n lines[i] = ' '.join(data[i])\n\n for i in range(len(lines)): # gets values of lengths of each line created\n lenWidths[i] += len(lines[i])\n \n maximumLen = 0\n for lenWidth in lenWidths: # finds the widest line\n if lenWidth > maximumLen:\n maximumLen = lenWidth\n \n for line in lines: #prints well-organized table\n print(line.rjust(maximumLen))\n\ntableData = [['apples', 'oranges', 'cherries', 'banana'],\n ['Alice', 'Bob', 'Carol', 'David'],\n ['dogs', 'cats', 'moose', 'goose']]\n\nprintTable(tableData)\n","sub_path":"tablePrinter.py","file_name":"tablePrinter.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"569726503","text":"import cv2\nimport os\nimport datetime\nimport time\n\nfrom src.cv.calib.camera_utils import Camera\nfrom src.cv.detect.detect_utils import DetectUtils\n# from src.cv.detect.detect_utils import filter_confidence_dets\nfrom src.cv.draw.draw_utils import DrawUtils\nfrom src.cv.track.track_utils import TrackUtils\nfrom src.analyze.roi_utils import RoiUtils\nfrom utils.common import logger\n\nfrom utils.constant import TRACKER, DETECTOR, SKIP1, SKIP2, \\\n B_SAVE_VIDEO, B_SHOW_VIDEO, PREFIX_SAVED_VIDEO, PREFIX_RESULT_VIDEO, SCALE_FACTOR\n\n\nclass DriveThru:\n def __init__(self):\n\n self.cap = None\n\n self.cam = Camera(overwrite=False)\n\n self.detector = DetectUtils(det_mode=DETECTOR, score_threshold=0.1).detector\n\n self.tracker = TrackUtils(trk_type=TRACKER)\n\n self.drawer = DrawUtils(b_log=False)\n\n self.roi = None\n\n self.fourcc = cv2.VideoWriter_fourcc(*'XVID')\n self.saver = None\n\n self.scale_factor = SCALE_FACTOR\n\n def run(self, video_path):\n # ---------------- initialize -------------------------------------------------\n self.cap = cv2.VideoCapture(video_path)\n\n fps = self.cap.get(cv2.CAP_PROP_FPS)\n width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH) * self.scale_factor\n height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) * self.scale_factor\n num_frames = self.cap.get(cv2.CAP_PROP_FRAME_COUNT)\n logger.info(\"video infos:\\n\" +\n \"\\tfps: {}\\n\".format(fps) +\n \"\\twidth: {}\\n\".format(width) +\n \"\\theight: {}\\n\".format(height) +\n \"\\tnum_frames: {}\\n\".format(num_frames))\n\n self.roi = RoiUtils(img_sz=[height, width], b_log=True)\n\n output_path = video_path.replace(PREFIX_SAVED_VIDEO, PREFIX_RESULT_VIDEO)\n self.saver = cv2.VideoWriter(output_path, self.fourcc, fps, (int(width), int(height)))\n\n # ---------------- validate --------------------------------------------------\n # model_h, model_w = self.cam.distort.get_map_sz()\n # if model_h != height or model_w != width:\n # logger.info(\n # \"input frame size {}x{} should be matched with camera model {}x{}\".format(width, height, model_w,\n # model_h))\n # return\n # ----------------------------------------------------------------------------\n\n vehicles = {}\n current_id = 0\n log_history = []\n logger.info(\"start analyzing...\")\n frm_cnt = -1\n is_first_frame = True\n\n __last_fps_t = 0\n\n while True:\n frm_cnt += 1\n ret, raw_frame = self.cap.read()\n\n if not ret:\n break\n\n # if frm_cnt == (fps * 300):\n # break\n\n if frm_cnt % int(fps * 600) == 0:\n print(\"{} / {}\".format(frm_cnt, num_frames))\n __dur = time.time() - __last_fps_t\n __fps = (fps * 600) / __dur\n print(\"fps: {}\".format(round(__fps, 2)))\n __last_fps_t = time.time()\n\n # print(\"time pos: {}\".format(round(frm_cnt / fps, 2)))\n\n # skip1\n if frm_cnt % SKIP1 != 0:\n continue\n\n # -------------------- pre-processing (undistorting) -------------------------------------------------------\n frame = cv2.resize(raw_frame, None, fx=self.scale_factor, fy=self.scale_factor)\n crop = self.roi.crop_area(img=frame)\n\n # -------------------- detect and tracking -----------------------------------------------------------------\n if frm_cnt % SKIP2 == 0: # detect the object\n\n # detect the object ----------------------------------------------------\n dets = self.detector.detect(img=crop)\n\n # confidence_dets = filter_confidence_dets(dets, car_thresh=0.1, truck_thresh=0.35) # no need in yolov3\n\n # only in roi(tracking area) -------------------------------------------\n dets_in_roi = self.roi.filter_objects_in_roi(objects=dets, crop_sz=crop.shape[:2])\n\n # update trackers ------------------------------------------------------\n if is_first_frame:\n is_first_frame = False\n cv2.imwrite(\"first_frame.jpg\", frame)\n\n # remain_dets = dets_in_roi.copy()\n remain_dets = list(dets_in_roi)\n\n for det in remain_dets:\n current_id += 1\n vehicles[current_id] = self.tracker.create_tracker(trk_img=crop, det=det, frame_pos=frm_cnt)\n else:\n remain_dets = self.tracker.upgrade_trackers(dets=dets_in_roi, trk_img=crop, trackers=vehicles)\n\n remain_dets_img = self.drawer.show_objects(img=crop, objects=dets_in_roi)\n remain_dets_img = self.drawer.show_roi(img=remain_dets_img, roi_objs=self.roi.cropped_roi_objs)\n cv2.imshow(\"remain_dets_img\", remain_dets_img)\n cv2.waitKey(1)\n\n for det in remain_dets:\n if self.roi.is_det_located_by_crossline(det=det, crop_sz=crop.shape[:2]):\n current_id += 1\n vehicles[current_id] = self.tracker.create_tracker(trk_img=crop, det=det, frame_pos=frm_cnt)\n\n else:\n # keep trackers --------------------------------------------------------\n self.tracker.keep_trackers(trk_img=crop, trackers=vehicles)\n\n # -------------------- show the frame ----------------------------------------------------------------------\n # recover the cropped trackers\n show_img = self.drawer.show_roi(img=frame, roi_objs=self.roi.roi_objs)\n show_img = self.drawer.show_trackers(trk_img=show_img, trackers=vehicles, mode=\"rect\", fps=fps,\n offset=self.roi.crop_to_detect[:2])\n if B_SHOW_VIDEO:\n # showing the result\n cv2.imshow(\"result\", cv2.resize(show_img, None, fx=0.7, fy=0.7))\n key = cv2.waitKey(1)\n if key == ord('q'):\n break\n elif key == ord('n'): # next\n pos = self.cap.get(cv2.CAP_PROP_POS_FRAMES)\n pos += 100\n frm_cnt += 100\n self.cap.set(cv2.CAP_PROP_POS_FRAMES, pos)\n print(frm_cnt)\n elif key == ord('p'): # prev\n pos = self.cap.get(cv2.CAP_PROP_POS_FRAMES)\n pos -= max(0, pos - 100)\n frm_cnt -= 100\n self.cap.set(cv2.CAP_PROP_POS_FRAMES, pos)\n print(frm_cnt)\n\n # -------------------- check roi events --------------------------------------------------------------------\n event_hist = self.roi.check_roi_events(trackers=vehicles, fps=fps, crop_sz=crop.shape[:2])\n if len(event_hist) > 0:\n log_history.append(event_hist)\n print(\"new event at {}\".format(round(frm_cnt / fps, 2)))\n\n if B_SAVE_VIDEO: # rename\n self.saver.write(show_img)\n\n self.export_to_csv(video_path=video_path, history=log_history)\n self.release()\n\n if not B_SAVE_VIDEO: # rename\n new_path = video_path.replace(PREFIX_SAVED_VIDEO, PREFIX_RESULT_VIDEO)\n try:\n os.rename(video_path, new_path)\n except Exception as e:\n print(e)\n os.remove(new_path)\n os.rename(video_path, new_path)\n time.sleep(1)\n\n return frm_cnt\n\n def release(self):\n if self.saver is not None:\n self.saver.release()\n if self.cap is not None:\n self.cap.release()\n\n def export_to_csv(self, video_path, history):\n s_time = self.get_time_from_fn(file_path=video_path)\n s_time = s_time.timestamp()\n\n csv_path = os.path.join(os.path.splitext(video_path)[0] + \".csv\")\n\n lines = \"ID, AppearanceTime (sec), TimeToOrderPoint1 (sec), TimeAtOrderPoint1 (sec), \" \\\n \"Exist Vehicle in Front (T/F), TimeToOrderPoint2 (sec), TimeAtOrderPoint2 (sec) \\n\"\n for events in history:\n for event in events:\n tid, time_appearance, time_to_order_1, time_at_order_1, front_flag, \\\n time_to_order_2, time_at_order_2 = event\n\n # 2007-04-05T14:30:20 | ISO8601 standard\n epoch_t_appearance = s_time + time_appearance\n time_appearance = datetime.datetime.fromtimestamp(epoch_t_appearance).strftime('%Y-%m-%d %H:%M:%S')\n\n line = \"{}, {}, {}, {}, {}, {}, {}\\n\".format(\n tid,\n time_appearance,\n round(time_to_order_1, 2),\n round(time_at_order_1, 2),\n front_flag,\n round(time_to_order_2, 2),\n round(time_at_order_2, 2)\n )\n\n lines += line\n # save the csv file\n with open(csv_path, 'w') as fp:\n fp.write(lines)\n\n @staticmethod\n def get_time_from_fn(file_path):\n try:\n _, fn = os.path.split(file_path)\n base, ext = os.path.splitext(fn)\n base = base.replace(PREFIX_RESULT_VIDEO, '').replace(PREFIX_SAVED_VIDEO, '')\n t_obj = datetime.datetime.strptime(base, '%Y-%m-%d_%H-%M-%S')\n except Exception as e:\n logger.warn(\"{}\".format(e))\n t_obj = datetime.datetime.utcnow()\n return t_obj\n\n\nif __name__ == '__main__':\n dt = DriveThru()\n\n from utils.constant import SAVE_DIR, VIDEO_EXT\n\n paths = [os.path.join(SAVE_DIR, fn) for fn in os.listdir(SAVE_DIR) if\n os.path.splitext(fn)[1] == VIDEO_EXT and fn.find(PREFIX_SAVED_VIDEO) != -1]\n paths.sort()\n for path in paths:\n logger.info(os.path.split(path)[1])\n s_t = time.time()\n frames = dt.run(video_path=path)\n e_t = time.time()\n print(e_t - s_t)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243355340","text":"# -*- encoding: utf-8 -*-\n#\n# Copyright © 2012 New Dream Network, LLC (DreamHost)\n#\n# Author: Julien Danjou \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\"\"\"Common code for working with images\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport itertools\nimport glanceclient\n\nfrom ceilometer import counter\nfrom ceilometer.openstack.common import timeutils\nfrom ceilometer import plugin\n\n\nclass _Base(plugin.PollsterBase):\n\n @staticmethod\n def get_glance_client(ksclient):\n endpoint = ksclient.service_catalog.url_for(\n service_type='image',\n endpoint_type='internalURL')\n\n # hard-code v1 glance API version selection while v2 API matures\n return glanceclient.Client('1', endpoint,\n token=ksclient.auth_token)\n\n def iter_images(self, ksclient):\n \"\"\"Iterate over all images.\"\"\"\n client = self.get_glance_client(ksclient)\n #TODO(eglynn): use pagination to protect against unbounded\n # memory usage\n return itertools.chain(\n client.images.list(filters={\"is_public\": True}),\n #TODO(eglynn): extend glance API with all_tenants logic to\n # avoid second call to retrieve private images\n client.images.list(filters={\"is_public\": False}))\n\n @staticmethod\n def extract_image_metadata(image):\n return dict((k, getattr(image, k))\n for k in\n [\n \"status\",\n \"is_public\",\n \"name\",\n \"deleted\",\n \"container_format\",\n \"created_at\",\n \"disk_format\",\n \"updated_at\",\n \"properties\",\n \"min_disk\",\n \"protected\",\n \"checksum\",\n \"deleted_at\",\n \"min_ram\",\n \"size\",\n ])\n\n\nclass ImagePollster(_Base):\n\n @staticmethod\n def get_counter_names():\n return ['image', 'image.size']\n\n def get_counters(self, manager):\n for image in self.iter_images(manager.keystone):\n yield counter.Counter(\n name='image',\n type=counter.TYPE_GAUGE,\n unit='image',\n volume=1,\n user_id=None,\n project_id=image.owner,\n resource_id=image.id,\n timestamp=timeutils.isotime(),\n resource_metadata=self.extract_image_metadata(image),\n )\n yield counter.Counter(\n name='image.size',\n type=counter.TYPE_GAUGE,\n unit='B',\n volume=image.size,\n user_id=None,\n project_id=image.owner,\n resource_id=image.id,\n timestamp=timeutils.isotime(),\n resource_metadata=self.extract_image_metadata(image),\n )\n","sub_path":"ceilometer/image/glance.py","file_name":"glance.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"57343313","text":"'''\nWrite a Program that prints frequency of a digit from a number,\nwhere user provides number & digit both.\nInput:\nNumber: 1231234\nDigit to check Frequency: 3\nOutput: The Frequency of 3 in number 1231234 is 2.\n\n'''\n\nn=int(input(\"Input:\"))\nd=int(input(\"digit to check frequency:\"))\nc=0\ntemp=n\nwhile(n>0):\n\tif(n%10==d):\n\t\tc+=1\n\t\t\n\tn=int(n/10)\n\t\nprint(\"The Frequency of\",d,\"in number\",str(temp),\"is\",c)\n","sub_path":"Python/DailyFlash/22feb2020/MySolutions/program5.py","file_name":"program5.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"414042987","text":"\r\nimport sys, os\r\n\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\r\nos.environ['FOUNDATION_RUN_MODE'] = 'jupyter'\r\n# os.environ['FOUNDATION_SAVE_DIR'] = '/is/ei/fleeb/workspace/chome/trained_nets'\r\n# os.environ['FOUNDATION_DATA_DIR'] = '/is/ei/fleeb/workspace/local_data'\r\n# %load_ext autoreload\r\n# %autoreload 2\r\nimport torch\r\nimport numpy as np\r\nimport h5py as hf\r\n# %matplotlib notebook\r\n# %matplotlib tk\r\n#plt.switch_backend('Qt5Agg') #('Qt5Agg')\r\n#from foundation.util import replicate, Cloner\r\n\r\ndef print_info(f):\r\n\tprint(list(f.keys()), list(f.attrs.keys()))\r\n\tfor k in f.keys():\r\n\t\tprint('{}: {} {}'.format(k, f[k].dtype, f[k].shape))\r\n\r\ndef main(argv=None):\r\n\t\r\n\tif argv is None:\r\n\t\targv = sys.argv\r\n\t\r\n\tprint(argv)\r\n\t\r\n\tcat = argv[-1]\r\n\t\r\n\tdataroot = os.environ['FOUNDATION_DATA_DIR']\r\n\tdataset_name = 'mpi3d'\r\n\t\r\n\tN = 1036800\r\n\t\r\n\tindices = torch.arange(N).long()\r\n\t\r\n\t# cat = 'real'\r\n\t\r\n\tsrc_name = f'{dataset_name}_{cat}.npz'\r\n\t\r\n\tpath = os.path.join(dataroot, dataset_name, src_name)\r\n\t\r\n\tprint(f'{cat} {dataset_name} {path}')\r\n\t\r\n\tdata = np.load(path)\r\n\t\r\n\timages = data['images']\r\n\r\n\tprint(f'Data loaded: {images.shape}')\r\n\t\r\n\ttarget_path = f'{dataset_name}_{cat}_full.h5'\r\n\t\r\n\tprint('Dest: {}'.format(target_path))\r\n\tprint('Name: {}, Size: {}'.format(os.path.basename(target_path), len(indices)))\r\n\twith hf.File(target_path, 'w') as tgt:\r\n\t\ttgt.create_dataset('indices', data=indices)\r\n\t\ttgt.create_dataset('images', data=images)\r\n\t\tprint_info(tgt)\r\n\t\r\n\tprint('done')\r\n\t\r\n\tpass\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n\r\n\r\n\r\n\r\n","sub_path":"load_mpi.py","file_name":"load_mpi.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558542968","text":"class Student:\n def __init__(self, name, surname, gender):\n self.name = name\n self.surname = surname\n self.gender = gender\n self.finished_courses = []\n self.courses_in_progress = []\n self.grades = {}\n\n def rate_hw(self, lecture, course, grade):\n if isinstance(lecture, Lecturer) and course in lecture.courses_attached and course in self.courses_in_progress:\n if course in lecture.grades:\n lecture.grades[course] += [grade]\n else:\n lecture.grades[course] = [grade]\n else:\n return 'Ошибка'\n\n\nclass Mentor:\n def __init__(self, name, surname):\n self.name = name\n self.surname = surname\n self.courses_attached = []\n\n\nclass Lecturer(Mentor):\n def __init__(self, name, surname):\n super().__init__(name, surname)\n self.grades = {}\n\n\nclass Reviewer(Mentor):\n def rate_hw(self, student, course, grade):\n if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress:\n if course in student.grades:\n student.grades[course] += [grade]\n else:\n student.grades[course] = [grade]\n else:\n return 'Ошибка'\n\n\nbest_student = Student('Ruoy', 'Eman', 'your_gender')\nbest_student.courses_in_progress += ['Python', 'java']\n\ncool_reviewer = Reviewer('Some', 'Buddy')\ncool_reviewer.courses_attached += ['Python']\n\nbest_lecturer = Lecturer(\"Pavel\", \"Pavlovich\")\nbest_lecturer.courses_attached += ['java']\n\ncool_reviewer.rate_hw(best_student, 'Python', 10)\ncool_reviewer.rate_hw(best_student, 'Python', 10)\ncool_reviewer.rate_hw(best_student, 'Python', 10)\n\nbest_student.rate_hw(best_lecturer, 'java', 10)\nbest_student.rate_hw(best_lecturer, 'java', 9)\nbest_student.rate_hw(best_lecturer, 'java', 5)\n\nprint(best_student.grades)\nprint(best_lecturer.grades)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"99534075","text":"from PySide.QtCore import QSettings\n\nfrom inselect.lib.inselect_error import InselectError\nfrom inselect.lib.utils import debug_print\n\ntry:\n import gouda\n from gouda.engines import InliteEngine, LibDMTXEngine, ZbarEngine\n from gouda.strategies.roi.roi import roi\n from gouda.strategies.resize import resize\nexcept ImportError:\n gouda = InliteEngine = LibDMTXEngine = ZbarEngine = roi = resize = None\n\n\ndef inlite_available():\n \"Returns True if the Inlite engine is available\"\n return InliteEngine is not None and InliteEngine.available()\n\n\ndef libdmtx_available():\n \"Returns True if the libdmtx engine is available\"\n return LibDMTXEngine is not None and LibDMTXEngine.available()\n\n\ndef zbar_available():\n \"Returns True if the zbar engine is available\"\n return ZbarEngine is not None and ZbarEngine.available()\n\n\ndef current_settings():\n \"\"\"Returns a dict of the current settings:\n {\n \"engine\": one of ('libdmtx', 'zbar', 'inlite'),\n \"inlite-format\": one of ('1d', 'datamatrix', 'pdf417', 'qrcode'),\n }\n \"\"\"\n s = QSettings()\n return {\n 'engine': s.value('barcode/engine', 'libdmtx'),\n 'inlite-format': s.value('barcode/inlite-format', 'datamatrix')\n }\n\n\ndef update_settings(new_settings):\n \"\"\"Updates settings. new_settings should be a dict:\n {\n \"engine\": one of ('libdmtx', 'zbar', 'inlite'),\n \"inlite-format\": one of ('1d', 'datamatrix', 'pdf417', 'qrcode'),\n }\n \"\"\"\n debug_print('New barcode settings', new_settings)\n s = QSettings()\n s.setValue('barcode/engine', new_settings['engine'])\n s.setValue('barcode/inlite-format', new_settings['inlite-format'])\n\n\ndef load_engine():\n \"\"\"Returns an instance of the user's choice of barcode reading engine\n \"\"\"\n if gouda:\n settings = current_settings()\n engine = settings['engine']\n if 'libdmtx' == engine:\n return LibDMTXEngine()\n elif 'zbar' == engine:\n return ZbarEngine()\n elif 'inlite' == engine:\n return InliteEngine(settings['inlite-format'])\n else:\n raise ValueError('Unrecognised barcode reader [{0}]'.format(engine))\n else:\n raise InselectError('Barcode decoding is not available')\n","sub_path":"inselect/gui/plugins/barcode_settings.py","file_name":"barcode_settings.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"380205915","text":"# -*- coding: utf-8 -*-\n\nfrom typing import Tuple\n\nimport decimal\nfrom .Decimal import *\n\nHUNDRED = Dec('100')\n\nimport pandas as pd\n\nclass Wallet(object):\n def __init__(self,\n instrument: decimal.Decimal = ZERO,\n base: decimal.Decimal = ONE,\n base_limit: decimal.Decimal = ONE,\n fee: decimal.Decimal = Dec('0.1'),\n accumulate_excess: bool = True,\n ):\n self.instrument = Dec(instrument)\n self.base = Dec(base)\n self.base_limit = Dec(base_limit)\n self.fee = Dec(fee)\n self.accumulate_excess = bool(accumulate_excess)\n self.excess = ZERO\n\n self.history_ts = []\n self.history_base = []\n self.history_excess = []\n self.history_instrument = []\n\n\n def __repr__(self):\n return ''.format(self.base, self.instrument, self.excess)\n\n def buy(self, price: decimal.Decimal, fraction: decimal.Decimal, ts: int):\n price = Dec(price)\n fraction = min(Dec(fraction), ONE)\n ts = int(ts)\n\n # selling currency\n if self.accumulate_excess:\n to_sell = min(self.base_limit, self.base) * fraction\n else:\n to_sell = self.base * fraction\n\n sold = (to_sell / price) / (ONE + self.fee / HUNDRED)\n self.instrument += sold\n self.base -= to_sell\n\n self.history_ts.append(ts)\n self.history_base.append(self.base)\n self.history_excess.append(self.excess)\n self.history_instrument.append(self.instrument)\n\n\n def sell(self, price: decimal.Decimal, fraction: decimal.Decimal, ts: int):\n price = Dec(price)\n fraction = min(Dec(fraction), ONE)\n ts = int(ts)\n\n # selling instrument\n to_sell = self.instrument * fraction\n sold = to_sell * price / (ONE + self.fee / HUNDRED)\n self.instrument -= to_sell\n self.base += sold\n if self.accumulate_excess and self.base > self.base_limit:\n self.excess += self.base - self.base_limit\n self.base = self.base_limit\n\n self.history_ts.append(ts)\n self.history_base.append(self.base)\n self.history_excess.append(self.excess)\n self.history_instrument.append(self.instrument)\n\n\n @property\n def history(self) -> pd.DataFrame:\n rv = pd.DataFrame.from_dict(\n {\n 'ts': self.history_ts,\n 'base': self.history_base,\n 'excess': self.history_excess,\n 'instrument': self.history_instrument,\n }\n ).set_index('ts')\n return rv\n\n\n @property\n def balance(self) -> Tuple:\n return self.instrument, self.base, self.excess\n","sub_path":"generic_strategy_optimization/generic_strategy_optimization/wallet.py","file_name":"wallet.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"62063176","text":"# Contributor: Maya Ramsey\r\n# Description: Contents: date2040.py - Challenge V: Recieves ISO 8601 datestamp \r\n# and interval in seconds from API. Returns sum of datestamp and interval ISO 8601 format.\r\n# ------------------------------------------------------------\r\n\r\nimport json\r\nimport requests\r\nimport datetime\r\nimport dateutil.parser\r\nimport iso8601\r\n\r\n# accessing endpoint\r\npayload1 = {'token' : '26200b75083ca3fdb0381b8815534373'}\r\nurl = 'http://challenge.code2040.org/api/dating'\r\nurlValid = 'http://challenge.code2040.org/api/dating/validate'\r\nresponse = requests.post(url, json=payload1)\r\n\r\nresponse.status_code\r\n\r\n# convert information\r\nprint(response.text)\r\ndata = json.loads(response.text)\r\ndatestamp = data['datestamp']\r\ninterval = data['interval']\r\n\r\n# Turn datestamp into datetime, increment and then turn back into iso 8601 format\r\noldDate = iso8601.parse_date(datestamp)\r\nnewDate = oldDate + datetime.timedelta(0, interval)\r\nfinalDate = newDate.isoformat()\r\nreturnDate = finalDate[:-6]\r\nreturnDate += 'Z'\r\nprint(returnDate)\r\n\r\n# post updated date\r\npayload2 = {\"token\" : '26200b75083ca3fdb0381b8815534373', \"datestamp\" : returnDate}\r\nr = requests.post(urlValid, json=payload2)\r\nprint(r.text)\r\n","sub_path":"date2040.py","file_name":"date2040.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"100830390","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 26 14:12:29 2018\n\n@author: Nakanishi\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom neurowang2 import Neuron\n\n\n\ndef main():\n \n neu = Neuron(0.02, 5000, 1, -60, 0.58)\n \n M = np.zeros(int(neu.simtime / neu.dt))\n \n for i in range(0, int(neu.cycle)-1):\n neu.propagation()\n \n M[i] = neu.ca[0, i] * 50\n \n t = np.arange(0, neu.simtime, neu.dt)\n \n plt.plot(t, neu.vin[0])\n plt.plot(t, neu.vde[0])\n '''\n plt.plot(t, M)\n '''\n plt.show()\n \nif __name__=='__main__':\n main()","sub_path":"wang/mainwang.py","file_name":"mainwang.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497100156","text":"from argparse import ArgumentParser\nimport json\nimport pandas as pd\nimport numpy as np\nfrom prettify_json import read_json\nfrom tqdm import tqdm\nimport os\nimport re\nfrom collections import Counter\nimport random\n\n\nSPELLING_CORRECTION_DICT = {}\n\n\ndef argParse():\n argparser = ArgumentParser(description='Select json file')\n argparser.add_argument('-f', '--file', type=str, required=True, help='Path to csv file.')\n argparser.add_argument('-a', '--attribute_mapping', type=str, required=True, help='Path to attribute mapping (profile) json file')\n argparser.add_argument('-t', '--translation_mapping', type=str, required=True, help='Path to translation mapping json file')\n argparser.add_argument('-p', '--predicting', action='store_true', help='If it is making prediction without label')\n\n A = argparser.parse_args()\n return A\n\n\ndef concat_title_translate(df):\n \"\"\" concat title and translate in one col, return new_col of concated str \"\"\"\n print(\"Creating concatenated col ...\")\n new_col = df[['title', 'translated']].fillna('').apply(lambda x: ' '.join(x), axis=1)\n return new_col\n\n\ndef spelling_correction(content, spelling_correction_dict):\n for word, corrected in spelling_correction_dict.items():\n if word in content:\n content.replace(word, corrected)\n return content\n\n\ndef language_correction(content, language_correction_dict):\n for word_id, word_en in language_correction_dict.items():\n if word_id in content:\n content = content.replace(word_id, word_en)\n return content\n\n\ndef cleaning(col, language_correction_dict, spelling_correction_dict=SPELLING_CORRECTION_DICT):\n \"\"\" clean the column with spelling and language correction \"\"\"\n print(\"Cleaning concatenated col ... \")\n\n with tqdm(total=len(col)) as pbar:\n for i, content in enumerate(col):\n content = spelling_correction(content, spelling_correction_dict)\n content = language_correction(content, language_correction_dict)\n col[i] = content\n # print(col[i])\n pbar.update(1)\n\n return col\n\n\ndef find_exact_model(src, attr_dict):\n \"\"\" src: a title (one row)\n attr_dict: corrected attrs:num dictionary for a single attr\n return matching_result (name) and matching_num_result (coded number) as list\n \"\"\"\n concat_src = src.replace(' ', '')\n matching_result = set()\n matching_num_result = set()\n for attr, num in attr_dict.items():\n if attr.replace(' ', '') in concat_src:\n matching_result.add(attr)\n matching_num_result.add(int(num))\n return list(matching_result), list(matching_num_result)\n\n\ndef find_exact(src, attr_dict):\n \"\"\" src: a title (one row)\n attr_dict: corrected attrs:num dictionary for a single attr\n return matching_result (in coded number) as list\n \"\"\"\n matching_result = set()\n for attr, num in attr_dict.items():\n if attr in src:\n matching_result.add(int(num))\n return list(matching_result)\n\n\ndef predict(cleaned_col, attribute_mapping, df, predicting=False):\n total_row = len(cleaned_col)\n\n predictions = dict()\n for attr in attribute_mapping.keys():\n predictions[attr] = []\n attr_dict = attribute_mapping[attr]\n print(\"Predicting {} ... \".format(attr))\n with tqdm(total=total_row) as pbar:\n for item in cleaned_col:\n predictions[attr].append(find_exact(item, attr_dict))\n pbar.update(1)\n\n # if < 2 prediction, use NN model output\n if predicting:\n predictions = add_nn_output(predictions, df)\n\n return predictions\n\n\ndef add_nn_output(prediction, nn_output):\n\n def internal_add_nn_output(pred, nn_pred):\n # print(pred, nn_pred)\n nn_pred = list(map(int, nn_pred.split()))\n if len(pred) == 0:\n pred = nn_pred\n elif len(pred) == 1:\n for p in nn_pred:\n if p not in pred:\n pred.append(p)\n break\n else:\n new_pred = []\n for p in nn_pred:\n if p in pred:\n new_pred.append(p)\n while len(new_pred) < 2:\n for p in nn_pred:\n if p not in pred:\n new_pred.append(p)\n\n pred = new_pred\n if len(pred) == 1:\n pred.append(pred[0])\n return pred\n\n print(\"Adding output from NN model ... \")\n total_row = nn_output.shape[0]\n with tqdm(total=total_row) as pbar:\n for i in range(total_row):\n for attr, pred in prediction.items():\n prediction[attr][i] = internal_add_nn_output(pred[i], nn_output.ix[i, attr])\n\n # print('final:', prediction[attr][i])\n # if len(prediction[attr][i]) < 2:\n # print(attr, i, prediction[attr][i], pred[i], nn_output.ix[i, attr])\n # input()\n # there should be exactly two predictions\n \n assert len(prediction[attr][i]) == 2\n pbar.update(1)\n return prediction\n\n\ndef post_process(predicted_brand, predicted_model, other_predictions, branddict, modeldict):\n\n print('Post processing using brand and phone model ... ')\n with tqdm(total=len(predicted_brand)) as pbar:\n for i in range(len(predicted_brand)):\n round2 = False\n # if phone model is not null, use it, otherwise, use brand\n if len(predicted_model[i]) > 0:\n for attr in other_predictions.keys():\n other_predictions[attr][i] = cross_reference(other_predictions[attr][i], attr, predicted_model[i], modeldict)\n round2 = True\n if len(predicted_brand[i]) > 0:\n for attr in other_predictions.keys():\n other_predictions[attr][i] = cross_reference(other_predictions[attr][i], attr, predicted_brand[i], branddict, round2)\n\n pbar.update(1)\n\n return other_predictions\n\n\ndef sort_model(model):\n # if more than 1 phone model, take the longest and second longest\n if len(model) > 1:\n model.sort(key=len)\n model.reverse()\n model = model[:2]\n return model\n\n\ndef cross_reference(attr, attr_name, model, modeldict, round2=False):\n\n # if model is not null, use the longest matched model to cross reference brand\n if len(model) > 0:\n longest_model = model[0]\n longest_model_dict = modeldict[str(longest_model)]\n counter = Counter(longest_model_dict[attr_name])\n most_likely_two = counter.most_common()\n\n # if no brand, get the most common brand\n if len(attr) == 0:\n try:\n attr.append(int(float(most_likely_two[0][0])))\n attr.append(int(float(most_likely_two[1][0])))\n except IndexError:\n pass\n\n elif len(attr) == 1:\n try:\n if attr[0] == int(float(most_likely_two[0][0])):\n attr.append(int(float(most_likely_two[1][0])))\n else:\n attr.append(int(float(most_likely_two[0][0])))\n except IndexError:\n pass\n\n elif len(attr) > 1 and round2 is False:\n updated_attr = []\n for i in range(len(most_likely_two)):\n if int(float(most_likely_two[i][0])) in attr:\n updated_attr.append(int(float(most_likely_two[i][0])))\n attr.remove(int(float(most_likely_two[i][0])))\n\n while len(updated_attr) < 2 and len(attr) > 0:\n # randomly select one from the brand and add in hahahahaha\n chosen = random.choice(attr)\n updated_attr.append(int(float(chosen)))\n attr.remove(int(float(chosen)))\n\n attr = updated_attr\n\n return attr\n\n\ndef main():\n A = argParse()\n\n df = pd.read_csv(A.file)\n # df = df[:20]\n translation_mapping = read_json(A.translation_mapping)\n attribute_mapping = read_json(A.attribute_mapping)\n\n ## 1. cleaning for beauty attribute mapping\n\n ## 2. concate and clean title\n concat_col = concat_title_translate(df)\n cleaned_col = cleaning(concat_col, translation_mapping)\n df['clean_title'] = cleaned_col\n\n ## 3. make prediction\n prediction = predict(cleaned_col, attribute_mapping, df, A.predicting)\n\n ## 4. write prediction to df\n new_file_name = '../data/beauty_test_keywords.csv'\n new_keys = []\n for k, v in prediction.items():\n # if A.predicting is True:\n # new_key = k\n # else:\n # new_key = \"Keyword \" + k\n\n new_key = \"Keyword \" + k\n new_keys.append(new_key)\n df[new_key] = [' '.join(list(map(str, lst))) for lst in v]\n\n new_keys += [\"itemid\", \"clean_title\", \"image_path\", \"title\", \"translated\"]\n df = df[new_keys]\n df.to_csv(new_file_name, index=False)\n\nif __name__ == '__main__':\n main()\n","sub_path":"keyword_extraction/predict_beauty.py","file_name":"predict_beauty.py","file_ext":"py","file_size_in_byte":8989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"165634617","text":"#!/usr/bin/env python3\n\"\"\"\nCreated on Tue Apr 24 15:48:52 2020\n@author: Jesse Haviland\n\"\"\"\n\nimport sys\nfrom os.path import splitext\nimport numpy as np\n# import spatialmath as sp\nfrom spatialmath import SE3\nfrom spatialmath.base.argcheck import getvector, verifymatrix\nfrom roboticstoolbox.robot.ELink import ELink, ETS\n# from roboticstoolbox.backends.PyPlot.functions import \\\n# _plot, _teach, _fellipse, _vellipse, _plot_ellipse, \\\n# _plot2, _teach2\nfrom roboticstoolbox.tools import xacro\nfrom roboticstoolbox.tools import URDF\nfrom roboticstoolbox.robot.Robot import Robot\nfrom roboticstoolbox.robot.Gripper import Gripper\nfrom pathlib import PurePath, PurePosixPath\nfrom ansitable import ANSITable, Column\nfrom spatialmath import SpatialAcceleration, SpatialVelocity, \\\n SpatialInertia, SpatialForce\n\n\nclass ERobot(Robot):\n \"\"\"\n The ERobot. A superclass which represents the\n kinematics of a serial-link manipulator\n\n :param et_list: List of elementary transforms which represent the robot\n kinematics\n :type et_list: ET list\n :param name: Name of the robot\n :type name: str, optional\n :param manufacturer: Manufacturer of the robot\n :type manufacturer: str, optional\n :param base: Location of the base is the world frame\n :type base: SE3, optional\n :param tool: Offset of the flange of the robot to the end-effector\n :type tool: SE3, optional\n :param gravity: The gravity vector\n :type n: ndarray(3)\n\n :references:\n - Kinematic Derivatives using the Elementary Transform Sequence,\n J. Haviland and P. Corke\n \"\"\"\n\n # TODO do we need tool and base as well?\n\n def __init__(\n self,\n elinks,\n base_link=None,\n gripper_links=None,\n **kwargs\n ):\n\n self._ets = []\n self._linkdict = {}\n self._n = 0\n self._ee_links = []\n self._base_link = None\n\n # Ordered links, we reorder the input elinks to be in depth first\n # search order\n orlinks = []\n\n if isinstance(elinks, ETS):\n # were passed an ETS string\n ets = elinks\n elinks = []\n\n # chop it up into segments, a link frame after every joint\n start = 0\n for j, k in enumerate(ets.joints()):\n ets_j = ets[start:k+1]\n start = k + 1\n if j == 0:\n parent = None\n else:\n parent = elinks[-1]\n elink = ELink(ets_j, parent=parent, name=f\"link{j:d}\")\n elinks.append(elink)\n\n n = len(ets.joints())\n\n tool = ets[start:]\n if len(tool) > 0:\n elinks.append(ELink(tool, parent=elinks[-1], name=\"ee\"))\n elif isinstance(elinks, list):\n # were passed a list of ELinks\n\n # check all the incoming ELink objects\n n = 0\n for link in elinks:\n if isinstance(link, ELink):\n self._linkdict[link.name] = link\n else:\n raise TypeError(\"Input can be only ELink\")\n if link.isjoint:\n n += 1\n else:\n raise TypeError('elinks must be a list of ELinks or an ETS')\n\n self._n = n\n\n # scan for base\n for link in elinks:\n # is this a base link?\n if link._parent is None:\n if self._base_link is not None:\n raise ValueError('Multiple base links')\n self._base_link = link\n else:\n # no, update children of this link's parent\n link._parent._child.append(link)\n\n # Set up the gripper, make a list containing the root of all\n # grippers\n if gripper_links is not None:\n if isinstance(gripper_links, ELink):\n gripper_links = [gripper_links]\n else:\n gripper_links = []\n\n # An empty list to hold all grippers\n self.grippers = []\n\n # Make a gripper object for each gripper\n for link in gripper_links:\n g_links = self.dfs_links(link)\n\n # Remove gripper links from the robot\n for g_link in g_links:\n elinks.remove(g_link)\n\n # Save the gripper object\n self.grippers.append(Gripper(g_links))\n\n # Subtract the n of the grippers from the n of the robot\n for gripper in self.grippers:\n self._n -= gripper.n\n\n # Set the ee links\n self.ee_links = []\n if len(gripper_links) == 0:\n for link in elinks:\n # is this a leaf node? and do we not have any grippers\n if len(link.child) == 0:\n # no children, must be an end-effector\n self.ee_links.append(link)\n else:\n for link in gripper_links:\n # use the passed in value\n self.ee_links.append(link.parent)\n\n # assign the joint indices\n if all([link.jindex is None for link in elinks]):\n\n jindex = [0] # \"mutable integer\" hack\n\n def visit_link(link, jindex):\n # if it's a joint, assign it a jindex and increment it\n if link.isjoint and link in elinks:\n link.jindex = jindex[0]\n jindex[0] += 1\n\n if link in elinks:\n orlinks.append(link)\n\n # visit all links in DFS order\n self.dfs_links(\n self.base_link, lambda link: visit_link(link, jindex))\n\n elif all([link.jindex is not None for link in elinks]):\n # jindex set on all, check they are unique and sequential\n jset = set(range(self._n))\n for link in elinks:\n if link.jindex not in jset:\n raise ValueError(\n 'joint index {link.jindex} was '\n 'repeated or out of range')\n jset -= set([link.jindex])\n if len(jset) > 0: # pragma nocover # is impossible\n raise ValueError('joints {jset} were not assigned')\n else:\n # must be a mixture of ELinks with/without jindex\n raise ValueError(\n 'all links must have a jindex, or none have a jindex')\n\n # Current joint angles of the robot\n # TODO should go to Robot class?\n self.q = np.zeros(self.n)\n self.qd = np.zeros(self.n)\n self.qdd = np.zeros(self.n)\n self.control_type = 'v'\n\n super().__init__(orlinks, **kwargs)\n\n def dfs_links(self, start, func=None):\n \"\"\"\n Visit all links from start in depth-first order and will apply\n func to each visited link\n\n :param start: the link to start at\n :type start: ELink\n :param func: An optional function to apply to each link as it is found\n :type func: function\n\n :returns: A list of links\n :rtype: list of ELink\n \"\"\"\n visited = []\n\n def vis_children(link):\n visited.append(link)\n if func is not None:\n func(link)\n\n for li in link.child:\n if li not in visited:\n vis_children(li)\n\n vis_children(start)\n\n return visited\n\n # def dfs_path(self, l1, l2):\n # path = []\n # visited = [l1]\n\n # def vis_children(link):\n # visited.append(link)\n\n # for li in link.child:\n # if li not in visited:\n\n # if li == l2 or vis_children(li):\n # path.append(li)\n # return True\n # vis_children(l1)\n # path.append(l1)\n # path.reverse()\n # return path\n\n def to_dict(self):\n ob = {\n 'links': [],\n 'name': self.name,\n 'n': self.n\n }\n\n self.fkine_all()\n\n for link in self.links:\n li = {\n 'axis': [],\n 'eta': [],\n 'geometry': [],\n 'collision': []\n }\n\n for et in link.ets():\n li['axis'].append(et.axis)\n li['eta'].append(et.eta)\n\n if link.v is not None:\n li['axis'].append(link.v.axis)\n li['eta'].append(link.v.eta)\n\n for gi in link.geometry:\n li['geometry'].append(gi.to_dict())\n\n for gi in link.collision:\n li['collision'].append(gi.to_dict())\n\n ob['links'].append(li)\n\n # Do the grippers now\n for gripper in self.grippers:\n for link in gripper.links:\n li = {\n 'axis': [],\n 'eta': [],\n 'geometry': [],\n 'collision': []\n }\n\n for et in link.ets():\n li['axis'].append(et.axis)\n li['eta'].append(et.eta)\n\n if link.v is not None:\n li['axis'].append(link.v.axis)\n li['eta'].append(link.v.eta)\n\n for gi in link.geometry:\n li['geometry'].append(gi.to_dict())\n\n for gi in link.collision:\n li['collision'].append(gi.to_dict())\n\n ob['links'].append(li)\n\n return ob\n\n def fk_dict(self):\n ob = {\n 'links': []\n }\n\n self.fkine_all()\n\n # Do the robot\n for link in self.links:\n\n li = {\n 'geometry': [],\n 'collision': []\n }\n\n for gi in link.geometry:\n li['geometry'].append(gi.fk_dict())\n\n for gi in link.collision:\n li['collision'].append(gi.fk_dict())\n\n ob['links'].append(li)\n\n # Do the grippers now\n for gripper in self.grippers:\n for link in gripper.links:\n li = {\n 'geometry': [],\n 'collision': []\n }\n\n for gi in link.geometry:\n li['geometry'].append(gi.fk_dict())\n\n for gi in link.collision:\n li['collision'].append(gi.fk_dict())\n\n ob['links'].append(li)\n\n return ob\n\n # @classmethod\n # def urdf_to_ets(cls, file_path):\n # name, ext = splitext(file_path)\n\n # if ext == '.xacro':\n # urdf_string = xacro.main(file_path)\n # urdf = URDF.loadstr(urdf_string, file_path)\n\n # return ERobot(\n # urdf.elinks,\n # name=urdf.name\n # )\n\n def urdf_to_ets_args(self, file_path, tld=None):\n \"\"\"\n [summary]\n\n :param file_path: File path relative to the xacro folder\n :type file_path: str, in Posix file path fprmat\n :param tld: top-level directory, defaults to None\n :type tld: str, optional\n :return: Links and robot name\n :rtype: tuple(ELink list, str)\n \"\"\"\n\n # get the path to the class that defines the robot\n classpath = sys.modules[self.__module__].__file__\n # add on relative path to get to the URDF or xacro file\n base_path = PurePath(classpath).parent.parent / 'URDF' / 'xacro'\n file_path = base_path / PurePosixPath(file_path)\n name, ext = splitext(file_path)\n\n if ext == '.xacro':\n # it's a xacro file, preprocess it\n if tld is not None:\n tld = base_path / PurePosixPath(tld)\n urdf_string = xacro.main(file_path, tld)\n urdf = URDF.loadstr(urdf_string, file_path)\n else: # pragma nocover\n urdf = URDF.loadstr(open(file_path).read(), file_path)\n\n return urdf.elinks, urdf.name\n\n # @classmethod\n # def dh_to_ets(cls, robot):\n # \"\"\"\n # Converts a robot modelled with standard or modified DH parameters to\n # an ERobot representation\n\n # :param robot: The robot model to be converted\n # :type robot: SerialLink\n # :return: List of returned :class:`bluepy.btle.Characteristic` objects\n # :rtype: ets class\n # \"\"\"\n # ets = []\n # q_idx = []\n # M = 0\n\n # for j in range(robot.n):\n # L = robot.links[j]\n\n # # Method for modified DH parameters\n # if robot.mdh:\n\n # # Append Tx(a)\n # if L.a != 0:\n # ets.append(ET.Ttx(L.a))\n # M += 1\n\n # # Append Rx(alpha)\n # if L.alpha != 0:\n # ets.append(ET.TRx(L.alpha))\n # M += 1\n\n # if L.is_revolute:\n # # Append Tz(d)\n # if L.d != 0:\n # ets.append(ET.Ttz(L.d))\n # M += 1\n\n # # Append Rz(q)\n # ets.append(ET.TRz(joint=j+1))\n # q_idx.append(M)\n # M += 1\n\n # else:\n # # Append Tz(q)\n # ets.append(ET.Ttz(joint=j+1))\n # q_idx.append(M)\n # M += 1\n\n # # Append Rz(theta)\n # if L.theta != 0:\n # ets.append(ET.TRz(L.alpha))\n # M += 1\n\n # return cls(\n # ets,\n # q_idx,\n # robot.name,\n # robot.manuf,\n # robot.base,\n # robot.tool)\n\n @property\n def qlim(self):\n v = np.zeros((2, self.n))\n j = 0\n\n for i in range(len(self.links)):\n if self.links[i].isjoint:\n v[:, j] = self.links[i].qlim\n j += 1\n\n return v\n\n # @property\n # def qdlim(self):\n # return self.qdlim\n\n# --------------------------------------------------------------------- #\n\n @property\n def n(self):\n return self._n\n# --------------------------------------------------------------------- #\n\n @property\n def elinks(self):\n # return self._linkdict\n return self._links\n# --------------------------------------------------------------------- #\n\n @property\n def link_dict(self):\n return self._linkdict\n# --------------------------------------------------------------------- #\n\n @property\n def base_link(self):\n return self._base_link\n\n @base_link.setter\n def base_link(self, link):\n if isinstance(link, ELink):\n self._base_link = link\n else:\n # self._base_link = self.links[link]\n raise TypeError('Must be an ELink')\n # self._reset_fk_path()\n# --------------------------------------------------------------------- #\n # TODO get configuration string\n\n @property\n def ee_links(self):\n return self._ee_links\n\n # def add_ee(self, link):\n # if isinstance(link, ELink):\n # self._ee_link.append(link)\n # else:\n # raise ValueError('must be an ELink')\n # self._reset_fk_path()\n\n @ee_links.setter\n def ee_links(self, link):\n if isinstance(link, ELink):\n self._ee_links = [link]\n elif isinstance(link, list) and \\\n all([isinstance(x, ELink) for x in link]):\n self._ee_links = link\n else:\n raise TypeError('expecting an ELink or list of ELinks')\n # self._reset_fk_path()\n\n @property\n def reach(self):\n r\"\"\"\n Reach of the robot\n\n :return: Maximum reach of the robot\n :rtype: float\n\n A conservative estimate of the reach of the robot. It is computed as\n the sum of the translational ETs that define the link transform.\n\n .. note:: \n \n - Probably an overestimate of reach\n - Used by numerical inverse kinematics to scale translational\n error.\n - For a prismatic joint, uses ``qlim`` if it is set\n\n .. warning:: Computed on the first access. If kinematic parameters \n subsequently change this will not be reflected.\n \"\"\"\n if self._reach is None:\n d = 0\n for link in self:\n for et in link.ets():\n if et.isprismatic:\n d += abs(et.eta)\n if link.isprismatic and link.qlim is not None:\n d += link.qlim[1]\n self._reach = d\n return self._reach\n\n# --------------------------------------------------------------------- #\n\n # @property\n # def ets(self):\n # return self._ets\n\n# --------------------------------------------------------------------- #\n\n # @property\n # def M(self):\n # return self._M\n\n# --------------------------------------------------------------------- #\n\n # @property\n # def q_idx(self):\n # return self._q_idx\n\n# --------------------------------------------------------------------- #\n\n def ets(self, ee=None):\n if ee is None:\n if len(self.ee_links) == 1:\n link = self.ee_links[0]\n else:\n raise ValueError(\n 'robot has multiple end-effectors, specify one')\n # elif isinstance(ee, str) and ee in self._linkdict:\n # ee = self._linkdict[ee]\n elif isinstance(ee, ELink) and ee in self._links:\n link = ee\n else:\n raise ValueError('end-effector is not valid')\n\n ets = ETS()\n\n # build the ETS string from ee back to root\n while link is not None:\n ets = link.ets() * ets\n link = link.parent\n\n return ets\n\n def config(self):\n s = ''\n for link in self.links:\n if link.v is not None:\n if link.v.isprismatic:\n s += 'P'\n elif link.v.isrevolute:\n s += 'R'\n return s\n\n# --------------------------------------------------------------------- #\n\n def fkine(self, q=None, from_link=None, to_link=None):\n '''\n Forward kinematics\n\n :param q: Joint coordinates\n :type q: ndarray(n) or ndarray(m,n)\n :return: The transformation matrix representing the pose of the\n end-effector\n :rtype: SE3 instance\n\n - ``T = robot.fkine(q)`` evaluates forward kinematics for the robot at joint\n configuration ``q``.\n\n - ``T = robot.fkine(q, start=link1, end=link2)``\n\n **Trajectory operation**:\n\n If ``q`` has multiple rows (mxn), it is considered a trajectory and the\n result is an ``SE3`` instance with ``m`` values.\n\n .. note::\n\n - The robot's base or tool transform, if present, are incorporated\n into the result.\n\n :references:\n - Kinematic Derivatives using the Elementary Transform\n Sequence, J. Haviland and P. Corke\n\n '''\n\n if from_link is None:\n from_link = self.base_link\n\n if to_link is None:\n to_link = self.ee_links[0]\n\n trajn = 1\n\n if q is None:\n q = self.q\n\n path, n = self.get_path(from_link, to_link)\n\n use_jindex = True\n\n try:\n q = getvector(q, self.n, 'col')\n\n except ValueError:\n try:\n q = getvector(q, n, 'col')\n use_jindex = False\n j = 0\n except ValueError:\n trajn = q.shape[1]\n verifymatrix(q, (self.n, trajn))\n\n for i in range(trajn):\n tr = self.base.A\n for link in path:\n if link.isjoint:\n if use_jindex:\n T = link.A(q[link.jindex, i], fast=True)\n else:\n T = link.A(q[j, i], fast=True)\n j += 1\n else:\n T = link.A(fast=True)\n\n tr = tr @ T\n\n if i == 0:\n t = SE3(tr)\n else:\n t.append(SE3(tr))\n\n return t\n\n def fkine_all(self, q=None):\n '''\n Tall = robot.fkine_all(q) evaluates fkine for each joint within a robot and\n returns a trajecotry of poses.\n\n Tall = fkine_all() as above except uses the stored q value of the\n robot object.\n\n :param q: The joint angles/configuration of the robot (Optional,\n if not supplied will use the stored q values).\n :type q: float ndarray(n)\n\n :return T: Homogeneous transformation trajectory\n :rtype T: SE3 list\n\n .. note::\n\n - The robot's base transform, if present, are incorporated\n into the result.\n\n :references:\n - Kinematic Derivatives using the Elementary Transform\n Sequence, J. Haviland and P. Corke\n\n '''\n\n if q is None:\n q = np.copy(self.q)\n else:\n q = getvector(q, self.n)\n\n for link in self.elinks:\n if link.isjoint:\n t = link.A(q[link.jindex])\n else:\n t = link.A()\n\n if link.parent is None:\n link._fk = self.base * t\n else:\n link._fk = link.parent._fk * t\n\n # Update the collision objects transform as well\n for col in link.collision:\n col.wT = link._fk\n\n for gi in link.geometry:\n gi.wT = link._fk\n\n # Do the grippers now\n for gripper in self.grippers:\n for link in gripper.links:\n # print(link.jindex)\n if link.isjoint:\n t = link.A(gripper.q[link.jindex])\n else:\n t = link.A()\n\n link._fk = link.parent._fk * t\n\n # Update the collision objects transform as well\n for col in link.collision:\n col.wT = link._fk\n\n for gi in link.geometry:\n gi.wT = link._fk\n\n # def jacob0(self, q=None):\n # \"\"\"\n # J0 = jacob0(q) is the manipulator Jacobian matrix which maps joint\n # velocity to end-effector spatial velocity. v = J0*qd in the\n # base frame.\n\n # J0 = jacob0() as above except uses the stored q value of the\n # robot object.\n\n # :param q: The joint angles/configuration of the robot (Optional,\n # if not supplied will use the stored q values).\n # :type q: float ndarray(n)\n\n # :return J: The manipulator Jacobian in ee frame\n # :rtype: float ndarray(6,n)\n\n # :references:\n # - Kinematic Derivatives using the Elementary Transform\n # Sequence, J. Haviland and P. Corke\n # \"\"\"\n\n # if q is None:\n # q = np.copy(self.q)\n # else:\n # q = getvector(q, self.n)\n\n # T = (self.base.inv() * self.fkine(q)).A\n # U = np.eye(4)\n # j = 0\n # J = np.zeros((6, self.n))\n\n # for link in self._fkpath:\n\n # for k in range(link.M):\n\n # if k != link.q_idx:\n # U = U @ link.ets[k].T().A\n # else:\n # # self._jacoblink(link, k, T)\n # U = U @ link.ets[k].T(q[j]).A\n # Tu = np.linalg.inv(U) @ T\n # n = U[:3, 0]\n # o = U[:3, 1]\n # a = U[:3, 2]\n # x = Tu[0, 3]\n # y = Tu[1, 3]\n # z = Tu[2, 3]\n\n # if link.ets[k].axis == 'Rz':\n # J[:3, j] = (o * x) - (n * y)\n # J[3:, j] = a\n\n # elif link.ets[k].axis == 'Ry':\n # J[:3, j] = (n * z) - (a * x)\n # J[3:, j] = o\n\n # elif link.ets[k].axis == 'Rx':\n # J[:3, j] = (a * y) - (o * z)\n # J[3:, j] = n\n\n # elif link.ets[k].axis == 'tx':\n # J[:3, j] = n\n # J[3:, j] = np.array([0, 0, 0])\n\n # elif link.ets[k].axis == 'ty':\n # J[:3, j] = o\n # J[3:, j] = np.array([0, 0, 0])\n\n # elif link.ets[k].axis == 'tz':\n # J[:3, j] = a\n # J[3:, j] = np.array([0, 0, 0])\n\n # j += 1\n\n # return J\n\n def get_path(self, from_link, to_link):\n path = []\n n = 0\n link = to_link\n\n path.append(link)\n if link.isjoint:\n n += 1\n\n while link != from_link:\n link = link.parent\n path.append(link)\n if link.isjoint:\n n += 1\n\n path.reverse()\n\n return path, n\n\n def jacob0(self, q=None, from_link=None, to_link=None, offset=None, T=None):\n \"\"\"\n [summary]\n\n :param q: Joint coordinate vector\n :type q: ndarray(n)\n :param from_link: [description], defaults to None\n :type from_link: [type], optional\n :param to_link: [description], defaults to None\n :type to_link: [type], optional\n :param offset: [description], defaults to None\n :type offset: [type], optional\n :param T: [description], defaults to None\n :type T: [type], optional\n :return J: Manipulator Jacobian in the base frame\n :rtype: ndarray(6,n)\n\n - ``robot.jacobo(q)`` is the manipulator Jacobian matrix which maps\n joint velocity to end-effector spatial velocity expressed in the\n end-effector frame.\n\n End-effector spatial velocity :math:`\\nu = (v_x, v_y, v_z, \\omega_x, \\omega_y, \\omega_z)^T`\n is related to joint velocity by :math:`{}^{E}\\!\\nu = \\mathbf{J}_m(q) \\dot{q}`.\n\n Example:\n\n .. runblock:: pycon\n\n >>> import roboticstoolbox as rtb\n >>> puma = rtb.models.ETS.Puma560()\n >>> puma.jacobe([0, 0, 0, 0, 0, 0])\n\n .. note:: This is the geometric Jacobian as described in texts by\n Corke, Spong etal., Siciliano etal. The end-effector velocity is\n described in terms of translational and angular velocity, not a \n velocity twist as per the text by Lynch & Park.\n \"\"\"\n if from_link is None:\n from_link = self.base_link\n\n if to_link is None:\n to_link = self.ee_links[0]\n\n if offset is None:\n offset = SE3()\n\n path, n = self.get_path(from_link, to_link)\n\n if q is None:\n q = np.copy(self.q)\n else:\n try:\n q = getvector(q, n)\n except ValueError:\n q = getvector(q, self.n)\n\n if T is None:\n T = (self.base.inv()\n * self.fkine(q, from_link=from_link, to_link=to_link)\n * offset)\n\n T = T.A\n U = np.eye(4)\n j = 0\n J = np.zeros((6, n))\n\n for link in path:\n\n if link.isjoint:\n U = U @ link.A(q[j], fast=True)\n\n if link == to_link:\n U = U @ offset.A\n\n Tu = np.linalg.inv(U) @ T\n n = U[:3, 0]\n o = U[:3, 1]\n a = U[:3, 2]\n x = Tu[0, 3]\n y = Tu[1, 3]\n z = Tu[2, 3]\n\n if link.v.axis == 'Rz':\n J[:3, j] = (o * x) - (n * y)\n J[3:, j] = a\n\n elif link.v.axis == 'Ry':\n J[:3, j] = (n * z) - (a * x)\n J[3:, j] = o\n\n elif link.v.axis == 'Rx':\n J[:3, j] = (a * y) - (o * z)\n J[3:, j] = n\n\n elif link.v.axis == 'tx':\n J[:3, j] = n\n J[3:, j] = np.array([0, 0, 0])\n\n elif link.v.axis == 'ty':\n J[:3, j] = o\n J[3:, j] = np.array([0, 0, 0])\n\n elif link.v.axis == 'tz':\n J[:3, j] = a\n J[3:, j] = np.array([0, 0, 0])\n\n j += 1\n else:\n U = U @ link.A(fast=True)\n\n return J\n\n def jacobe(self, q=None, from_link=None, to_link=None, offset=None):\n \"\"\"\n :param q: Joint coordinate vector\n :type q: ndarray(n)\n :return J: Manipulator Jacobian in the end-effector frame\n :rtype: ndarray(6,n)\n\n - ``robot.jacobe(q)`` is the manipulator Jacobian matrix which maps\n joint velocity to end-effector spatial velocity expressed in the\n end-effector frame.\n\n End-effector spatial velocity :math:`\\nu = (v_x, v_y, v_z, \\omega_x, \\omega_y, \\omega_z)^T`\n is related to joint velocity by :math:`{}^{E}\\!\\nu = \\mathbf{J}_m(q) \\dot{q}`.\n\n Example:\n\n .. runblock:: pycon\n\n >>> import roboticstoolbox as rtb\n >>> puma = rtb.models.ETS.Puma560()\n >>> puma.jacobe([0, 0, 0, 0, 0, 0])\n\n .. note:: This is the **geometric Jacobian** as described in texts by\n Corke, Spong etal., Siciliano etal. The end-effector velocity is\n described in terms of translational and angular velocity, not a \n velocity twist as per the text by Lynch & Park.\n \"\"\"\n\n if from_link is None:\n from_link = self.base_link\n\n if to_link is None:\n to_link = self.ee_links[0]\n\n if offset is None:\n offset = SE3()\n\n if q is None:\n q = np.copy(self.q)\n # else:\n # q = getvector(q, n)\n\n T = (self.base.inv()\n * self.fkine(q, from_link=from_link, to_link=to_link)\n * offset)\n\n J0 = self.jacob0(q, from_link, to_link, offset, T)\n Je = self.jacobev(q, from_link, to_link, offset, T) @ J0\n return Je\n\n def hessian0(self, q=None, J0=None, from_link=None, to_link=None):\n \"\"\"\n The manipulator Hessian tensor maps joint acceleration to end-effector\n spatial acceleration, expressed in the world-coordinate frame. This\n function calulcates this based on the ETS of the robot. One of J0 or q\n is required. Supply J0 if already calculated to save computation time\n\n :param q: The joint angles/configuration of the robot (Optional,\n if not supplied will use the stored q values).\n :type q: float ndarray(n)\n :param J0: The manipulator Jacobian in the 0 frame\n :type J0: float ndarray(6,n)\n :return: The manipulator Hessian in 0 frame\n :rtype: float ndarray(6,n,n)\n\n :references:\n - Kinematic Derivatives using the Elementary Transform\n Sequence, J. Haviland and P. Corke\n \"\"\"\n\n if from_link is None:\n from_link = self.base_link\n\n if to_link is None:\n to_link = self.ee_links[0]\n\n path, n = self.get_path(from_link, to_link)\n\n if J0 is None:\n if q is None:\n q = np.copy(self.q)\n else:\n q = getvector(q, n)\n\n J0 = self.jacob0(q, from_link, to_link)\n else:\n verifymatrix(J0, (6, n))\n\n H = np.zeros((6, n, n))\n\n for j in range(n):\n for i in range(j, n):\n\n H[:3, i, j] = np.cross(J0[3:, j], J0[:3, i])\n H[3:, i, j] = np.cross(J0[3:, j], J0[3:, i])\n\n if i != j:\n H[:3, j, i] = H[:3, i, j]\n\n return H\n\n def manipulability(self, q=None, J=None, from_link=None, to_link=None):\n \"\"\"\n Calculates the manipulability index (scalar) robot at the joint\n configuration q. It indicates dexterity, that is, how isotropic the\n robot's motion is with respect to the 6 degrees of Cartesian motion.\n The measure is high when the manipulator is capable of equal motion\n in all directions and low when the manipulator is close to a\n singularity. One of J or q is required. Supply J if already\n calculated to save computation time\n\n :param q: The joint angles/configuration of the robot (Optional,\n if not supplied will use the stored q values).\n :type q: float ndarray(n)\n :param J: The manipulator Jacobian in any frame\n :type J: float ndarray(6,n)\n :return: The manipulability index\n :rtype: float\n\n :references:\n - Analysis and control of robot manipulators with redundancy,\n T. Yoshikawa,\n - Robotics Research: The First International Symposium (M. Brady\n and R. Paul, eds.), pp. 735-747, The MIT press, 1984.\n\n \"\"\"\n\n if from_link is None:\n from_link = self.base_link\n\n if to_link is None:\n to_link = self.ee_links[0]\n\n path, n = self.get_path(from_link, to_link)\n\n if J is None:\n if q is None:\n q = np.copy(self.q)\n else:\n q = getvector(q, n)\n\n J = self.jacob0(q, from_link, to_link)\n else:\n verifymatrix(J, (6, n))\n\n return np.sqrt(np.linalg.det(J @ np.transpose(J)))\n\n def jacobm(self, q=None, J=None, H=None, from_link=None, to_link=None):\n \"\"\"\n Calculates the manipulability Jacobian. This measure relates the rate\n of change of the manipulability to the joint velocities of the robot.\n One of J or q is required. Supply J and H if already calculated to\n save computation time\n\n :param q: The joint angles/configuration of the robot (Optional,\n if not supplied will use the stored q values).\n :type q: float ndarray(n)\n :param J: The manipulator Jacobian in any frame\n :type J: float ndarray(6,n)\n :param H: The manipulator Hessian in any frame\n :type H: float ndarray(6,n,n)\n :return: The manipulability Jacobian\n :rtype: float ndarray(n)\n\n :references:\n - Kinematic Derivatives using the Elementary Transform\n Sequence, J. Haviland and P. Corke\n \"\"\"\n\n if from_link is None:\n from_link = self.base_link\n\n if to_link is None:\n to_link = self.ee_links[0]\n\n path, n = self.get_path(from_link, to_link)\n\n if J is None:\n if q is None:\n q = np.copy(self.q)\n else:\n q = getvector(q, n)\n\n J = self.jacob0(q, from_link, to_link)\n else:\n verifymatrix(J, (6, n))\n\n if H is None:\n H = self.hessian0(J0=J, from_link=from_link, to_link=to_link)\n else:\n verifymatrix(H, (6, n, n))\n\n manipulability = self.manipulability(\n J=J, from_link=from_link, to_link=to_link)\n b = np.linalg.inv(J @ np.transpose(J))\n Jm = np.zeros((n, 1))\n\n for i in range(n):\n c = J @ np.transpose(H[:, :, i])\n Jm[i, 0] = manipulability * \\\n np.transpose(c.flatten('F')) @ b.flatten('F')\n\n return Jm\n\n def __str__(self):\n \"\"\"\n Pretty prints the ETS Model of the robot. Will output angles in\n degrees\n\n :return: Pretty print of the robot model\n :rtype: str\n\n Constant links are shown in blue.\n End-effector links are prefixed with an @\n \"\"\"\n table = ANSITable(\n Column(\"id\", headalign=\"^\"),\n Column(\"link\", headalign=\"^\"),\n Column(\"parent\", headalign=\"^\"),\n Column(\"joint\", headalign=\"^\"),\n Column(\"ETS\", headalign=\"^\", colalign=\">\"),\n border=\"thin\")\n for k, link in enumerate(self):\n color = \"\" if link.isjoint else \"<>\"\n ee = \"@\" if link in self.ee_links else \"\"\n ets = link.ets()\n table.row(\n k,\n color + ee + link.name,\n link.parent.name if link.parent is not None else \"-\",\n link._joint_name if link.parent is not None else \"\",\n ets.__str__(f\"q{link._jindex}\"))\n\n s = str(table)\n s += self.configurations_str()\n\n return s\n\n def hierarchy(self):\n \"\"\"\n Pretty print the robot link hierachy\n\n :return: Pretty print of the robot model\n :rtype: str\n\n Example:\n\n .. runblock:: pycon\n\n import roboticstoolbox as rtb\n robot = rtb.models.URDF.Panda()\n robot.hierarchy()\n\n \"\"\"\n\n # link = self.base_link\n\n def recurse(link, indent=0):\n print(' ' * indent * 2, link.name)\n for child in link.child:\n recurse(child, indent+1)\n\n recurse(self.base_link)\n\n def jacobev(\n self, q=None, from_link=None, to_link=None,\n offset=None, T=None):\n \"\"\"\n Jv = jacobev(q) is the spatial velocity Jacobian, at joint\n configuration q, which relates the velocity in the base frame to the\n velocity in the end-effector frame.\n\n Jv = jacobev() as above except uses the stored q value of the\n robot object.\n\n :param q: The joint angles/configuration of the robot (Optional,\n if not supplied will use the stored q values).\n :type q: float ndarray(n)\n\n :returns J: The velocity Jacobian in ee frame\n :rtype J: float ndarray(6,6)\n\n \"\"\"\n\n if from_link is None:\n from_link = self.base_link\n\n if to_link is None:\n to_link = self.ee_links[0]\n\n if offset is None:\n offset = SE3()\n\n if T is None:\n r = (self.base.inv() * self.fkine(\n q, from_link, to_link) * offset).R\n r = np.linalg.inv(r)\n else:\n r = np.linalg.inv(T.R)\n\n Jv = np.zeros((6, 6))\n Jv[:3, :3] = r\n Jv[3:, 3:] = r\n\n return Jv\n\n def jacob0v(self, q=None):\n \"\"\"\n Jv = jacob0v(q) is the spatial velocity Jacobian, at joint\n configuration q, which relates the velocity in the end-effector frame\n to velocity in the base frame\n\n Jv = jacob0v() as above except uses the stored q value of the\n robot object.\n\n :param q: The joint angles/configuration of the robot (Optional,\n if not supplied will use the stored q values).\n :type q: float ndarray(n)\n\n :returns J: The velocity Jacobian in 0 frame\n :rtype J: float ndarray(6,6)\n\n \"\"\"\n\n r = (self.base.inv() * self.fkine(q)).R\n\n Jv = np.zeros((6, 6))\n Jv[:3, :3] = r\n Jv[3:, 3:] = r\n\n return Jv\n\n def joint_velocity_damper(self, ps=0.05, pi=0.1, n=None, gain=1.0):\n '''\n Formulates an inequality contraint which, when optimised for will\n make it impossible for the robot to run into joint limits. Requires\n the joint limits of the robot to be specified. See examples/mmc.py\n for use case\n\n :param ps: The minimum angle (in radians) in which the joint is\n allowed to approach to its limit\n :type ps: float\n :param pi: The influence angle (in radians) in which the velocity\n damper becomes active\n :type pi: float\n :param n: The number of joints to consider. Defaults to all joints\n :type n: int\n :param gain: The gain for the velocity damper\n :type gain: float\n\n :returns: Ain, Bin as the inequality contraints for an optisator\n :rtype: ndarray(6), ndarray(6)\n '''\n\n if n is None:\n n = self.n\n\n Ain = np.zeros((n, n))\n Bin = np.zeros(n)\n\n for i in range(n):\n if self.q[i] - self.qlim[0, i] <= pi:\n Bin[i] = -gain * (\n ((self.qlim[0, i] - self.q[i]) + ps) / (pi - ps))\n Ain[i, i] = -1\n if self.qlim[1, i] - self.q[i] <= pi:\n Bin[i] = gain * (\n (self.qlim[1, i] - self.q[i]) - ps) / (pi - ps)\n Ain[i, i] = 1\n\n return Ain, Bin\n\n def link_collision_damper(\n self, shape, q=None, di=0.3, ds=0.05, xi=1.0,\n from_link=None, to_link=None):\n '''\n Formulates an inequality contraint which, when optimised for will\n make it impossible for the robot to run into a collision. Requires\n See examples/neo.py for use case\n\n :param ds: The minimum distance in which a joint is allowed to\n approach the collision object shape\n :type ds: float\n :param di: The influence distance in which the velocity\n damper becomes active\n :type di: float\n :param xi: The gain for the velocity damper\n :type xi: float\n :param from_link: The first link to consider, defaults to the base\n link\n :type from_link: ELink\n :param to_link: The last link to consider, will consider all links\n between from_link and to_link in the robot, defaults to the\n end-effector link\n :type to_link: ELink\n\n :returns: Ain, Bin as the inequality contraints for an omptimisor\n :rtype: ndarray(6), ndarray(6)\n '''\n\n if from_link is None:\n from_link = self.base_link\n\n if to_link is None:\n to_link = self.ee_link\n\n links, n = self.get_path(from_link, to_link)\n\n if q is None:\n q = np.copy(self.q)\n else:\n q = getvector(q, n)\n\n j = 0\n Ain = None\n bin = None\n\n def indiv_calculation(link, link_col, q):\n d, wTlp, wTcp = link_col.closest_point(shape, di)\n\n if d is not None:\n lpTcp = wTlp.inv() * wTcp\n norm = lpTcp.t / d\n norm_h = np.expand_dims(np.r_[norm, 0, 0, 0], axis=0)\n\n Je = self.jacobe(\n q, from_link=self.base_link, to_link=link,\n offset=link_col.base)\n n_dim = Je.shape[1]\n dp = norm_h @ shape.v\n l_Ain = np.zeros((1, n))\n l_Ain[0, :n_dim] = norm_h @ Je\n l_bin = (xi * (d - ds) / (di - ds)) + dp\n else:\n l_Ain = None\n l_bin = None\n\n return l_Ain, l_bin, d, wTcp\n\n for link in links:\n if link.isjoint:\n j += 1\n\n for link_col in link.collision:\n l_Ain, l_bin, d, wTcp = indiv_calculation(\n link, link_col, q[:j])\n\n if l_Ain is not None and l_bin is not None:\n if Ain is None:\n Ain = l_Ain\n else:\n Ain = np.r_[Ain, l_Ain]\n\n if bin is None:\n bin = np.array(l_bin)\n else:\n bin = np.r_[bin, l_bin]\n\n return Ain, bin\n\n # inverse dynamics (recursive Newton-Euler) using spatial vector notation\n def rne(robot, q, qd, qdd, gravity=None):\n\n n = robot.n\n\n # allocate intermediate variables\n Xup = SE3.Alloc(n)\n Xtree = SE3.Alloc(n)\n\n v = SpatialVelocity.Alloc(n)\n a = SpatialAcceleration.Alloc(n)\n f = SpatialForce.Alloc(n)\n I = SpatialInertia.Alloc(n) # noqa\n s = [None for i in range(n)] # joint motion subspace\n Q = np.zeros((n,)) # joint torque/force\n\n # initialize intermediate variables\n for j, link in enumerate(robot):\n I[j] = SpatialInertia(m=link.m, r=link.r)\n Xtree[j] = link.Ts\n s[j] = link.v.s\n\n if gravity is None:\n a_grav = SpatialAcceleration(robot.gravity)\n else:\n a_grav = SpatialAcceleration(gravity)\n\n # forward recursion\n for j in range(0, n):\n vJ = SpatialVelocity(s[j] * qd[j])\n\n # transform from parent(j) to j\n Xup[j] = robot[j].A(q[j]).inv()\n\n if robot[j].parent is None:\n v[j] = vJ\n a[j] = Xup[j] * a_grav + SpatialAcceleration(s[j] * qdd[j])\n else:\n jp = robot[j].parent.jindex\n v[j] = Xup[j] * v[jp] + vJ\n a[j] = Xup[j] * a[jp] \\\n + SpatialAcceleration(s[j] * qdd[j]) \\\n + v[j] @ vJ\n\n f[j] = I[j] * a[j] + v[j] @ (I[j] * v[j])\n\n # backward recursion\n for j in reversed(range(0, n)):\n Q[j] = f[j].dot(s[j])\n\n if robot[j].parent is not None:\n jp = robot[j].parent.jindex\n f[jp] = f[jp] + Xup[j] * f[j]\n\n return Q\n\n\nif __name__ == \"__main__\": # pragma nocover\n\n import roboticstoolbox as rtb\n np.set_printoptions(precision=4, suppress=True)\n\n p = rtb.models.URDF.Panda()\n print(p[1].m)\n\n # robot = rtb.models.ETS.Panda()\n # print(robot)\n # print(robot.base, robot.tool)\n # print(robot.ee_links)\n # ets = robot.ets()\n # print(ets)\n # print('n', ets.n)\n # ets2 = ets.compile()\n # print(ets2)\n\n # q = np.random.rand(7)\n # # print(ets.eval(q))\n # # print(ets2.eval(q))\n\n # J1 = robot.jacob0(q)\n # J2 = ets2.jacob0(q)\n # print(J1-J2)\n\n # print(robot[2].v, robot[2].v.jindex)\n # print(robot[2].Ts)\n","sub_path":"roboticstoolbox/robot/ERobot.py","file_name":"ERobot.py","file_ext":"py","file_size_in_byte":45626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"92868557","text":"from Fila import Fila\r\nfrom time import sleep\r\n\r\nFila_Hosp = Fila()\r\ncont_num = 0\r\n\r\nwhile True:\r\n # ========= introdução ======== #\r\n\r\n print('\\n\\\r\n MENU DE OPÇÕES: \\n\\\r\n 1) Acrescentar na Fila \\n\\\r\n 2) Pesquisar Fixa \\n\\\r\n 3) Listar Fila \\n\\\r\n 4) Chamar Paciente \\n\\\r\n 0) Sair do programa \\n\\\r\n ')\r\n\r\n escolha = input('Digite sua escolha: ')\r\n\r\n # ========= condições ======== #\r\n\r\n if escolha == '1':\r\n\r\n nome = input('Digite o nome do paciente: ').title()\r\n cont_num += 1\r\n \r\n Fila_Hosp.insere([nome, f'T00{cont_num}'])\r\n sleep(1)\r\n\r\n print('\\n --- Paciente inserido com sucesso ---\\n')\r\n print(f'Tamanho da fila: {Fila_Hosp.size()}')\r\n sleep(1)\r\n\r\n elif escolha == '2':\r\n\r\n nome = input('Digite o paciente a ser pesquisado: ').title()\r\n Fila_Hosp.pesq_pac(nome)\r\n\r\n elif escolha == '3':\r\n\r\n print('\\n --- Pacientes na Fila ---\\n')\r\n Fila_Hosp.listar()\r\n print('\\n')\r\n print(f'Tamanho da fila: {Fila_Hosp.size()}\\n')\r\n sleep(2)\r\n\r\n elif escolha == '4':\r\n lista = Fila_Hosp.indice(0)\r\n print(f'\\n Paciente para Entrar \\n - {lista}')\r\n\r\n Fila_Hosp.remove()\r\n sleep(3)\r\n\r\n elif escolha == '0': \r\n escolha = input('Tem certeza que deseja sair? (Y/N)').title()\r\n\r\n if escolha == 'N':\r\n pass\r\n else:\r\n print('# ------ FIM DE PROGRAMA ------- #\\n')\r\n break\r\n\r\n else: print('\\n --- Digite um número Válido ---\\n')\r\n\r\n","sub_path":"Lista_Pilha_Fila/Implant_Fila.py","file_name":"Implant_Fila.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"427610394","text":"#!/usr/bin/env python\n# coding: utf-8\n'''\nFile Name: meanScore_UsGe.py\nEdit Time: 20180421 1840\n\nContent:\n get mean score of genres rated by one user\n \nVersion:\n 1.0\n'''\n\nimport pdb # debug module\nfrom numpy import mean\nfrom time import gmtime, strftime\n\ndef main():\n \n dataDir = '/home/z/Documents/python/EE627_project/data/data_in_matrixForm/'\n file_in = dataDir + 'user_genre.txt'\n t = strftime('%Y%m%d%H%M', gmtime())\n title = 'di_UsID_geSc_mean'+t+'.txt'\n output_file = dataDir + title\n\n f_in = open(file_in, 'r')\n f_out = open(output_file, 'w')\n \n line = f_in.readline()\n arr_in = line.strip().split('|')\n lastUserID = arr_in[0]\n buff = [float(arr_in[2])]\n\n for line in f_in:\n arr_in = line.strip().split('|')\n userID = arr_in[0]\n\n if lastUserID != userID:\n outStr = str(lastUserID)+'|'+str(mean(buff))+'\\n'\n f_out.write(outStr)\n buff = []\n buff.append(float(arr_in[2]))\n lastUserID = userID\n\n outStr = str(lastUserID)+'|'+str(mean(buff))+'\\n'\n f_out.write(outStr)\n\n f_in.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"meanScore_UsGe.py","file_name":"meanScore_UsGe.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"181558995","text":"\"\"\"\r\n\n\nWrite a **recursive** function that will return the longest word in a\nsentence. In cases where more than one word is found, return the first one.\n\n### Examples\n\n find_longest(\"I will and ever will be gratefully and perpetually loving you Tesh!\") ➞ \"perpetually\"\n \n find_longest(\"A thing of beauty is a joy forever.\") ➞ \"forever\"\n \n find_longest(\"Forgetfulness is by all means powerless!\") ➞ \"forgetfulness\"\n \n find_longest(\"\\\"Strengths\\\" is the longest and most commonly used word that contains only a single vowel.\") ➞ \"strengths\"\n\n### Notes\n\n * Special characters and symbols _don't count_ as part of the word.\n * Return the longest word found in **lowercase** letters.\n * You are expected to solve this challenge via a **recursive** approach.\n * An **iterative** versions of this challenge can be found via these links ([1](https://edabit.com/challenge/Z6kRGLpYgSuFQJ7Rx) and [2](https://edabit.com/challenge/Aw2QK8vHY7Xk8Keto)).\n\n\"\"\"\r\n\nimport re\ndef find_longest(sentence, words='', big='', size=0):\n if words == '':\n pattern = re.compile('[^A-Za-z0-9]+')\n sentence = re.sub(pattern,' ',sentence)\n sentence = sentence.lower()\n words = sentence.split(' ')\n if len(words) == 0:\n return big\n word = words.pop()\n if len(word) >= size:\n big = word\n size = len(word)\n return find_longest(sentence, words, big, size)\n\n","sub_path":"LyzKTyYdKF4oDf5bG_22.py","file_name":"LyzKTyYdKF4oDf5bG_22.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"494843147","text":"\"\"\"\n twtxt.twhttp\n ~~~~~~~~~~~~\n\n This module handles HTTP requests via aiohttp/asyncio.\n\n :copyright: (c) 2016 by buckket.\n :license: MIT, see LICENSE for more details.\n\"\"\"\nimport re\nimport asyncio\nimport logging\nimport click\nimport aiohttp\nimport sys\nimport ssl\nfrom twtxt.models import Source\nfrom twtxt.cache import Cache\nfrom twtxt.helper import generate_user_agent\nfrom twtxt.parser import parse_tweets\n\nfrom twtxt.config import Config\nlogger = logging.getLogger(__name__)\n\n\n@asyncio.coroutine\ndef retrieve_status(client, source):\n status = None\n try:\n response = yield from client.head(source.url)\n status = response.status\n yield from response.release()\n except Exception as e:\n logger.debug(e)\n #comp490\n if e==ssl.CertificateError:\n\n click.echo(\"Warning unable to validate the source: \"+source.nick+\"ssl certificate \")\n elif e==aiohttp.errors.ClientOSError:\n errorString=str(e)\n if \"[[SSL: CERTIFICATE_VERIFY_FAILED\" in str(e):\n click.echo(\"Warning the source: \"+source.nick+\" is unsafe: The ssl certificate has expired\")\n return []\n elif \"[SSL: EXCESSIVE_MESSAGE_SIZE]\" in str(e):\n click.echo(\"Warpning the source: \"+source.nick+\" is unsafe: source has sent an invalid response\")\n #COMP490\n finally:\n return source, status\n\n\n@asyncio.coroutine\ndef retrieve_file(client, source, limit, cache):\n is_cached = cache.is_cached(source.url) if cache else None\n headers = {\"If-Modified-Since\": cache.last_modified(source.url)} if is_cached else {}\n\n try:\n response = yield from client.request(\"get\",source.url, headers=headers,allow_redirects=False)\n content = yield from response.text()\n except Exception as e:\n if is_cached:\n logger.debug(\"{}: {} - using cached content\".format(source.url, e))\n return cache.get_tweets(source.url, limit)\n #comp490\n elif e==ssl.CertificateError:\n\n click.echo(\"Warning the source: \"+source.nick+\" is unsafe: Hostname does not match name on SSL certificate\")\n return []\n elif e==aiohttp.errors.ClientOSError:\n\n if \"[[SSL: CERTIFICATE_VERIFY_FAILED\" in str(e):\n click.echo(\"Warning the source: \"+source.nick+\" is unsafe: The ssl certificate has expired\")\n return []\n elif \"[SSL: EXCESSIVE_MESSAGE_SIZE]\" in str(e):\n click.echo(\"Warning the source: \"+source.nick+\" is unsafe: source has sent an invalid response\")\n #COMP490\n else:\n logger.debug(e)\n return []\n\n if response.status == 200:\n tweets = parse_tweets(content.splitlines(), source)\n\n if cache:\n last_modified_header = response.headers.get(\"Last-Modified\")\n if last_modified_header:\n logger.debug(\"{} returned 200 and Last-Modified header - adding content to cache\".format(source.url))\n cache.add_tweets(source.url, last_modified_header, tweets)\n else:\n logger.debug(\"{} returned 200 but no Last-Modified header - can’t cache content\".format(source.url))\n else:\n logger.debug(\"{} returned 200\".format(source.url))\n\n return sorted(tweets, reverse=True)[:limit]\n#comp490\n elif response.status==301:\n cache = Cache.discover()\n conf=Config.discover()\n tweets=cache.get_tweets(source.url)\n\n conf.remove_source_by_nick(source.nick)\n url=response.headers[\"Location\"]\n conf.add_source(Source(source.nick,url))\n for tweet in tweets:\n cache.add_tweet(url,0,tweet)\n#comp490\n elif response.status == 410 and is_cached:\n # 410 Gone:\n # The resource requested is no longer available,\n # and will not be available again.\n logger.debug(\"{} returned 410 - deleting cached content\".format(source.url))\n cache.remove_tweets(source.url)\n return []\n\n elif is_cached:\n logger.debug(\"{} returned {} - using cached content\".format(source.url, response.status))\n return cache.get_tweets(source.url, limit)\n\n else:\n logger.debug(\"{} returned {}\".format(source.url, response.status))\n return []\n\n\n@asyncio.coroutine\ndef process_sources_for_status(client, sources,):\n g_status = []\n coroutines = [retrieve_status(client, source) for source in sources]\n for coroutine in asyncio.as_completed(coroutines):\n status = yield from coroutine\n g_status.append(status)\n return sorted(g_status, key=lambda x: x[0].nick)\n\n\n@asyncio.coroutine\ndef process_sources_for_file(client, sources, limit, cache=None):\n g_tweets = []\n coroutines = [retrieve_file(client, source, limit, cache) for source in sources]\n for coroutine in asyncio.as_completed(coroutines):\n tweets = yield from coroutine\n g_tweets.extend(tweets)\n return sorted(g_tweets, reverse=True)[:limit]\n\n#comp490\ndef backup_get_tweets(client,sources,limit):\n alltweets=[]\n for source in sources:\n try:\n tweets=process_sources_for_file(client,sources,limit)\n alltweets.extend(tweets)\n except ValueError:\n click.echo(\"warning encountered unreadable character when getting data from source \"+ source.nick+\"To preven further problems please update python and all the dependiencies of this program\")\n continue\n return alltweets\n\ndef get_remote_tweets(sources, limit=None, timeout=5.0, use_cache=True):\n conn = aiohttp.TCPConnector(conn_timeout=timeout, use_dns_cache=True)\n headers = generate_user_agent()\n\n with aiohttp.ClientSession(connector=conn, headers=headers) as client:\n loop = asyncio.get_event_loop()\n\n def start_loop(client, sources, limit, cache=None):\n return loop.run_until_complete(process_sources_for_file(client, sources, limit, cache))\n\n if use_cache:\n try:\n with Cache.discover() as cache:\n tweets = start_loop(client, sources, limit, cache)\n except OSError as e:\n logger.debug(e)\n tweets = start_loop(client, sources, limit)\n #comp490\n else:\n tweets = start_loop(client, sources, limit)\n #comp490\n if tweets is None:\n return backup_get_tweets(client,sources,limit)\n else:\n return tweets\n\n\n\n\ndef get_remote_status(sources, timeout=5.0):\n conn = aiohttp.TCPConnector(conn_timeout=timeout, use_dns_cache=True)\n headers = generate_user_agent()\n with aiohttp.ClientSession(connector=conn, headers=headers) as client:\n loop = asyncio.get_event_loop()\n result = loop.run_until_complete(process_sources_for_status(client, sources))\n return result\n","sub_path":"twtxt/twhttp.py","file_name":"twhttp.py","file_ext":"py","file_size_in_byte":6809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"238044001","text":"from funciones import *\r\n\r\ndef juego():\r\n userP = 0 # puntaje Partidas ganadas jugador\r\n maqP = 0 # puntaje Partidas ganadas jugador\r\n jugar = \"si\" # variable para iniciar juego\r\n while jugar == \"si\":\r\n numTur = 1 # Numero de turnos jugados\r\n numU = 0 # puntaje de las cartas usuario\r\n numC = 0 # puntaje de las cartas maquina\r\n while True:\r\n \r\n if numTur == 1: \r\n print(\"-----------||------------\")\r\n print(\"Turno \"+ nombre + \" : Turno MAQUINA: \")\r\n print(\"Cartas \"+ nombre + \": \" + str(turno(\"user\")) +\" Cartas MAQUINA: [\" + str(turno(\"maquina\")[0]) + \", --]\")\r\n numU += suma(0, 0, \"user\")\r\n print(\"Resultado \"+ nombre + \" es: \" +str(numU))\r\n print(\"-----------||------------||||---------------||----------------\")\r\n print(\"-----------||------------||||---------------||----------------\")\r\n \r\n numC += suma(0, 0, \"maquina\")\r\n numTur +=1\r\n \r\n else:\r\n print(\"Turno No\"+ str(numTur)+\" \"+ nombre + \": \")\r\n numTur +=1\r\n des = input(\"Desea otra carta si o no? : \")\r\n if des == \"si\":\r\n print(\"-----------||------------\")\r\n print (turno(\"user\"))\r\n numU = suma(numU, len(user())-1, \"user\")\r\n numA = 0\r\n if (\"Ad\" in user() or \"Ap\" in user() or \"At\" in user() or \"Ac\" in user()) and numU > 21:\r\n \r\n for i in range(0, len(user())):\r\n if \"A\" in user()[i][0]:\r\n numA += 1\r\n \r\n numU-=numA*10\r\n print (\"Se pudo restar \" + str(numU))\r\n \r\n print(\"Resultado \"+ nombre + \" es: \" +str(numU))\r\n print(\"-----------||------------\")\r\n if numU >21:\r\n print(\"----pass-------| EL JUGADOR \"+ nombre + \" SE HA PLANTADO |------------\")\r\n break\r\n \r\n des2 = input(\"Deseas plantar tu juego si o no? : \")\r\n if des2 == \"si\":\r\n print(\"-----------| EL JUGADOR \"+ nombre + \" SE HA PLANTADO |------------\")\r\n break\r\n \r\n while True:\r\n if numC == 21 or numC > 21 or numU > 21 and numC <= 21 or numC >= numU and numC < 21:\r\n print(\"-----------||------------\")\r\n print(\"Cartas MAQUINA: \" + str(pc()))\r\n print(\"Resultado MAQUINA es: \" +str(numC))\r\n print(\"-----------| LA MAQUINA SE HA PLANTADO |------------\")\r\n break\r\n\r\n else:\r\n print(\"-----------||------------\")\r\n print(\"otra carta para MAQUINA\")\r\n print(\"-----------||------------\")\r\n print(turno(\"maquina\"))\r\n numC = suma(numC, len(pc())-1, \"maquina\")\r\n \r\n userP, maqP = validarGanador(numU, numC, userP, maqP)\r\n print(\"El puntaje es: \" + nombre + \" con \"+ str(userP) + \"----||--- MAQUINA con \" + str(maqP))\r\n jugar = input(\"Desea jugar de nuevo si o no ?\")\r\nprint (juego())\r\n\r\n","sub_path":"Juego_21/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"547274810","text":"import pygame\nimport simulator\nimport constant\nimport parameter\n\n#Setting up pygame\n\npygame.init()\n\nclock = pygame.time.Clock()\n\nsimulationDisplay = pygame.display.set_mode((parameter.displayWidth, parameter.displayHeight))\npygame.display.set_caption(\"ApplePy Simulation\")\n\nicon = pygame.image.load('planet.png')\npygame.display.set_icon(icon)\n\npygame.display.update()\n\n#Simulation screen\n\nclass SimulationScreen:\n def __init__ (self, width, height):\n self.width = width\n self.height = height\n (self.dx, self.dy) = (0, 0)\n (self.mx, self.my) = (0, 0)\n self.magnification = 1.0\n\n def scroll(self, dx=0, dy=0):\n self.dx += dx * parameter.displayWidth / (self.magnification*10)\n self.dy += dy * parameter.displayHeight / (self.magnification*10)\n\n def zoom(self, zoom):\n self.magnification *= zoom\n self.mx = (1-self.magnification) * self.width/2\n self.my = (1-self.magnification) * self.height/2\n\n def reset(self):\n (self.dx, self.dy) = (0, 0)\n (self.mx, self.my) = (0, 0)\n self.magnification = 1.0\n\n#Initialize a simulation screen object\n\nsimulationScreen = SimulationScreen(parameter.displayWidth,parameter.displayHeight)\n\n#Dictionary of possible input values\n\nfunctionKeys = {\n pygame.K_LEFT: (lambda x: x.scroll(dx = 1)),\n pygame.K_RIGHT: (lambda x: x.scroll(dx = -1)),\n pygame.K_DOWN: (lambda x: x.scroll(dy = -1)),\n pygame.K_UP: (lambda x: x.scroll(dy = 1)),\n pygame.K_EQUALS: (lambda x: x.zoom(2)),\n pygame.K_MINUS: (lambda x: x.zoom(0.5)),\n pygame.K_z: (lambda x: x.reset())}\n\n#Diplay number of days passed\n\ndef daysPassed(count):\n font = pygame.font.SysFont(None, 25)\n text = font.render(\"Day \"+str(count), True, constant.white)\n simulationDisplay.blit(text,(0,0))\n\n#Reset simulation function\n\ndef resetSimulation():\n simulationDisplay.fill(constant.black)\n simulator.particleList = []\n simulator.generateParticles(parameter.particleNumber,\"moon\")\n for particle in simulator.particleList:\n x = int(simulationScreen.mx + (simulationScreen.dx + particle.px) * simulationScreen.magnification)\n y = int(simulationScreen.my + (simulationScreen.dy + particle.py) * simulationScreen.magnification)\n\n size = int(simulationScreen.magnification)\n\n if size < 2:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),1,1)\n else:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),size,0)\n\n pygame.display.update()\n clock.tick(15)\n\n#Pause function\n\ndef pause(count):\n paused = True\n\n pygame.display.update()\n\n while paused:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n paused = False\n if event.key == pygame.K_r:\n resetSimulation()\n count = 0\n if event.key == pygame.K_q:\n pygame.quit()\n quit()\n if event.key in functionKeys:\n functionKeys[event.key](simulationScreen)\n\n simulationDisplay.fill(constant.black)\n daysPassed(count)\n\n messageFunction(\"Press space bar to continue simulation\",parameter.displayWidth/2,parameter.displayHeight/2)\n\n for particle in simulator.particleList:\n x = int(simulationScreen.mx + (simulationScreen.dx + particle.px) * simulationScreen.magnification)\n y = int(simulationScreen.my + (simulationScreen.dy + particle.py) * simulationScreen.magnification)\n\n size = int(simulationScreen.magnification)\n\n if size < 2:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),1,1)\n else:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),size,0)\n\n pygame.display.update()\n clock.tick(5)\n\n#Message to screen function\n\ndef textObjects(text, font):\n textSurface = font.render(text, True, constant.white)\n return textSurface, textSurface.get_rect()\n\ndef messageFunction(text,x,y):\n largeText = pygame.font.Font('freesansbold.ttf',30)\n textSurf, textRect = textObjects(text, largeText)\n textRect.center = ((x), (y))\n simulationDisplay.blit(textSurf, textRect)\n #pygame.display.update()\n\n#Button function\n\ndef button(text,x,y,buttonWidth,buttonHeight,inactiveColor,activeColor,action=None):\n\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n if x + buttonWidth/2 > mouse[0] > x - buttonWidth/2 and y + buttonHeight/2 > mouse[1] > y - buttonHeight/2:\n pygame.draw.rect(simulationDisplay, activeColor,(x-(buttonWidth/2),y-(buttonHeight/2),buttonWidth,buttonHeight))\n if click[0] == 1 and action != None:\n action()\n else:\n pygame.draw.rect(simulationDisplay, inactiveColor,(x-(buttonWidth/2),y-(buttonHeight/2),buttonWidth,buttonHeight))\n\n smallText = pygame.font.Font(\"freesansbold.ttf\",20)\n textSurf, textRect = textObjects(text, smallText)\n textRect.center = ( (x), (y))\n simulationDisplay.blit(textSurf, textRect)\n\n#Simulation start screen\n\ndef simulationIntro():\n\n intro = True\n\n while intro:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n intro = False\n if event.key == pygame.K_r:\n resetSimulation()\n if event.key == pygame.K_q:\n pygame.quit()\n quit()\n if event.key in functionKeys:\n functionKeys[event.key](simulationScreen)\n\n simulationDisplay.fill(constant.black)\n\n #Draw initial particles\n for particle in simulator.particleList:\n\n x = int(simulationScreen.mx + (simulationScreen.dx + particle.px) * simulationScreen.magnification)\n y = int(simulationScreen.my + (simulationScreen.dy + particle.py) * simulationScreen.magnification)\n\n size = int(simulationScreen.magnification)\n\n if size < 2:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),1,1)\n else:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),size,0)\n\n #Start menu\n\n messageFunction(\"ApplePy\",parameter.displayWidth/2,parameter.displayHeight/8)\n\n messageFunction(\"n-body simulator\",parameter.displayWidth/2,parameter.displayHeight/8 + 50)\n\n button(\"Start!\", parameter.displayWidth/2,parameter.displayHeight/2 - 150,100,50, constant.green,constant.darkGreen,simulationLoop)\n\n button(\"Help\", parameter.displayWidth/2,parameter.displayHeight/2 - 75,100,50, constant.green,constant.darkGreen,helpScreen)\n\n button(\"About\", parameter.displayWidth/2,parameter.displayHeight/2,100,50, constant.green,constant.darkGreen,aboutScreen)\n\n pygame.display.update()\n clock.tick(30)\n\n#Simulation loop\n\n#Initial conditions\nsimulator.generateParticles(parameter.particleNumber,\"moon\")\n\ndef simulationLoop():\n\n count = 0\n\n simulationExit = False\n\n while not simulationExit:\n for event in pygame.event.get():\n\n #Handling quit events\n\n if event.type == pygame.QUIT:\n simulationExit = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n resetSimulation()\n count = 0\n elif event.key == pygame.K_SPACE:\n pause(count)\n elif event.key in functionKeys:\n functionKeys[event.key](simulationScreen)\n\n simulationDisplay.fill(constant.black)\n\n #Update particle positions\n simulator.updatePositions(simulator.particleList,\"euler\")\n\n #Draw particles\n for particle in simulator.particleList:\n\n x = int(simulationScreen.mx + (simulationScreen.dx + particle.px) * simulationScreen.magnification)\n y = int(simulationScreen.my + (simulationScreen.dy + particle.py) * simulationScreen.magnification)\n\n size = int(simulationScreen.magnification)\n\n if size < 2:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),1,1)\n else:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),size,0)\n\n count += 1\n daysPassed(count)\n\n pygame.display.update()\n\n clock.tick(30)\n\n pygame.quit()\n quit()\n\n#Simulation help screen\ndef helpScreen():\n\n intro = True\n\n while intro:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n intro = False\n if event.key == pygame.K_r:\n resetSimulation()\n if event.key == pygame.K_q:\n pygame.quit()\n quit()\n if event.key in functionKeys:\n functionKeys[event.key](simulationScreen)\n\n simulationDisplay.fill(constant.black)\n\n #Draw initial particles\n for particle in simulator.particleList:\n\n x = int(simulationScreen.mx + (simulationScreen.dx + particle.px) * simulationScreen.magnification)\n y = int(simulationScreen.my + (simulationScreen.dy + particle.py) * simulationScreen.magnification)\n\n size = int(simulationScreen.magnification)\n\n if size < 2:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),1,1)\n else:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),size,0)\n\n #Start menu\n\n messageFunction(\"ApplePy\",parameter.displayWidth/2,parameter.displayHeight/8)\n\n messageFunction(\"n-body simulator\",parameter.displayWidth/2,parameter.displayHeight/8 + 50)\n\n messageFunction(\"Press spacebar to pause\",parameter.displayWidth/2,parameter.displayHeight/8 + 150)\n\n messageFunction(\"Use arrow keys to move around and +/- to zoom\",parameter.displayWidth/2,parameter.displayHeight/8 + 200)\n\n messageFunction(\"Press r to reset simulation and q to quit\",parameter.displayWidth/2,parameter.displayHeight/8 + 250)\n\n button(\"Back\", parameter.displayWidth/2,parameter.displayHeight/8 + 350,100,50, constant.green,constant.darkGreen,simulationIntro)\n\n pygame.display.update()\n clock.tick(30)\n\n#Simulation about screen\ndef aboutScreen():\n\n intro = True\n\n while intro:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n intro = False\n if event.key == pygame.K_r:\n resetSimulation()\n if event.key == pygame.K_q:\n pygame.quit()\n quit()\n if event.key in functionKeys:\n functionKeys[event.key](simulationScreen)\n\n simulationDisplay.fill(constant.black)\n\n #Draw initial particles\n for particle in simulator.particleList:\n\n x = int(simulationScreen.mx + (simulationScreen.dx + particle.px) * simulationScreen.magnification)\n y = int(simulationScreen.my + (simulationScreen.dy + particle.py) * simulationScreen.magnification)\n\n size = int(simulationScreen.magnification)\n\n if size < 2:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),1,1)\n else:\n pygame.draw.circle(simulationDisplay,constant.white,(x,y),size,0)\n\n #Start menu\n\n messageFunction(\"ApplePy\",parameter.displayWidth/2,parameter.displayHeight/8)\n\n messageFunction(\"n-body simulator\",parameter.displayWidth/2,parameter.displayHeight/8 + 50)\n\n messageFunction(\"This physics simulation uses euler integration to solve\",parameter.displayWidth/2,parameter.displayHeight/8 + 150)\n\n messageFunction(\"for the motion of particles under the influence of gravity.\",parameter.displayWidth/2,parameter.displayHeight/8 + 200)\n\n messageFunction(\"Built by Paul Le\",parameter.displayWidth/2,parameter.displayHeight/8 + 250)\n\n button(\"Back\", parameter.displayWidth/2,parameter.displayHeight/8 + 350,100,50, constant.green,constant.darkGreen,simulationIntro)\n\n pygame.display.update()\n clock.tick(30)\n\n\n#Calling simulation program functions\n\nsimulationIntro()\nsimulationLoop()\n","sub_path":"apple.py","file_name":"apple.py","file_ext":"py","file_size_in_byte":12877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"539909814","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.5.2\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # Prepare Reference DEMS \n\nimport hsfm\n\ndata_dir = '/home/elilouis/hsfm-geomorph/data'\n\n# ## Prepare High Res Reference DEM\n#\n# We start with a WA DNR dataset from 2007.\n\ndem_highres_file = f'{data_dir}/reference_dem_highres/2007_final.tif'\ndem_highres_file_meters = f'{data_dir}/reference_dem_highres/reference_dem_m.tif'\ndem_highres_file_meters_warped = f'{data_dir}/reference_dem_highres/reference_dem_m_epsg32610.tif'\ndem_highres_file_final = f'{data_dir}/reference_dem_highres/reference_dem_final-adj.tif'\n\nhsfm.plot.plot_dem_from_file(dem_highres_file)\n\n# ### Convert from feet to meters using gdal_calc\n\n# !gdal_calc.py --co COMPRESS=LZW --co TILED=YES --co BIGTIFF=IF_SAFER --NoDataValue=-9999 --calc 'A*0.3048' -A $reference_dem_high_res_file --outfile $reference_dem_high_res_file_in_meters\n\n# !gdalinfo $reference_dem_high_res_file_in_meters | head -5 | tail -1\n\nhsfm.plot.plot_dem_from_file(reference_dem_high_res_file_in_meters)\n\n# ### Convert from 26710 (NAD27 UTM 10N) -> 32610 (WGS84 UTM 10N) using gdalwarp\n#\n# ### **LAST I TRIED THIS, I HAD TO DO IT THROUGH QGIS TO GET IT WORK...**\n\n# !gdalwarp -t_srs EPSG:32610 -r near -of GTiff $reference_dem_high_res_file_in_meters $dem_highres_file_meters_warped\n\nhsfm.plot.plot_dem_from_file(dem_highres_file_meters_warped)\n\n# ### Adjust the geoid\n\n# !dem_geoid --reverse-adjustment $dem_highres_file_meters_warped -o $dem_highres_file_final_prefix\n\n# + jupyter={\"outputs_hidden\": true}\nhsfm.plot.plot_dem_from_file(dem_highres_file_final)\n# -\n\n# ## Preare Low Res SRTM Reference DEM\n\n# Get corner coordinates from a high resolution LIDAR DEM that is cropped to Mt. Rainier so I can download a coarse SRTM reference DEM\n\n# !gdalinfo $dem_highres_file_final | grep \"Corner Coord\" --after 5\n\n# Convert using this tool https://www.rapidtables.com/convert/number/degrees-minutes-seconds-to-degrees.html\n\n# ## Download coarse SRTM reference DEM\n\nLLLON = -121.948\nLLLAT = 46.74643\nURLON = -121.6145\nURLAT = 47.00322\n\nreference_dem = hsfm.utils.download_srtm(LLLON,\n LLLAT,\n URLON,\n URLAT,\n output_directory='input_data/reference_dem/',\n verbose=False)\n\nhsfm.plot.plot_dem_from_file(reference_dem)\n\n","sub_path":"create_dems/create_dem_nisqually_1977/prepare-reference-dems.py","file_name":"prepare-reference-dems.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"322340942","text":"\"\"\"Prepare PTX dataset\"\"\"\nimport os\nimport torch\nimport numpy as np\nimport random\n\nfrom PIL import Image\nfrom .segbase import SegmentationDataset\n\n\nclass PTXSegmentation(SegmentationDataset):\n \"\"\"ADE20K Semantic Segmentation Dataset.\n\n Parameters\n ----------\n root : string\n Path to ADE20K folder. Default is './datasets/ade'\n split: string\n 'train', 'val' or 'test'\n transform : callable, optional\n A function that transforms the image\n Examples\n --------\n >>> from torchvision import transforms\n >>> import torch.utils.data as data\n >>> # Transforms for Normalization\n >>> input_transform = transforms.Compose([\n >>> transforms.ToTensor(),\n >>> transforms.Normalize((.485, .456, .406), (.229, .224, .225)),\n >>> ])\n >>> # Create Dataset\n >>> trainset = ADE20KSegmentation(split='train', transform=input_transform)\n >>> # Create Training Loader\n >>> train_data = data.DataLoader(\n >>> trainset, 4, shuffle=True,\n >>> num_workers=4)\n \"\"\"\n BASE_DIR = 'input'\n NUM_CLASS = 2\n\n def __init__(self, root, split='test', mode=None, transform=None, **kwargs):\n super(PTXSegmentation, self).__init__(root, split, mode, transform, **kwargs)\n root = os.path.join(root, self.BASE_DIR)\n #assert os.path.exists(root), \"Please setup the dataset using ../datasets/ade20k.py\"\n if mode == 'test':\n self.images = _get_ptx_pairs(root, split)\n else:\n self.images, self.masks = _get_ptx_pairs(root, split)\n assert (len(self.images) == len(self.masks))\n if len(self.images) == 0:\n raise RuntimeError(\"Found 0 images in subfolders of:\" + root + \"\\n\")\n print('Found {} images in the folder {}'.format(len(self.images), root))\n\n def __getitem__(self, index):\n img = Image.open(self.images[index]).convert('RGB')\n # img = Image.open(self.images[index])\n\n if self.mode == 'test':\n img = self._img_transform(img)\n if self.transform is not None:\n img = self.transform(img)\n return img, os.path.basename(self.images[index])\n\n #mask = Image.open(random.choice(self.masks[index]))\n mask = Image.open(self.masks[index])\n # synchrosized transform\n if self.mode == 'train':\n img, mask = self._sync_transform(img, mask)\n elif self.mode == 'val':\n img, mask = self._val_sync_transform(img, mask)\n else:\n assert self.mode == 'testval'\n img, mask = self._img_transform(img), self._mask_transform(mask)\n # general resize, normalize and to Tensor\n if self.transform is not None:\n img = self.transform(img)\n return img, mask, os.path.basename(self.images[index])\n\n def _mask_transform(self, mask):\n return torch.LongTensor(np.array(mask).astype('int32'))\n\n def __len__(self):\n return len(self.images)\n\n @property\n def pred_offset(self):\n return 1\n\n @property\n def classes(self):\n \"\"\"Category names.\"\"\"\n return (\"Background\", \"Pneumothorax\")\n\n\n\nIMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm',\\\n '.PPM', '.bmp', '.BMP', '.nii.gz', '.tif', '.tiff', '.svs',\\\n '.mrxs', '.nii']\n\n####################\n# Files & IO\n####################\n\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\n\ndef get_image_paths(data_path):\n images = []\n if type(data_path) == list:\n for dpath in data_path:\n assert os.path.isdir(dpath), '{:s} is not a valid directory'.format(dpath)\n for dir_path, _, fnames in sorted(os.walk(dpath)):\n for fname in sorted(fnames):\n if is_image_file(fname):\n #if 'mask' not in fname:\n img_path = os.path.join(dir_path, fname)\n images.append(img_path)\n else:\n assert os.path.isdir(data_path), '{:s} is not a valid directory'.format(data_path)\n for dir_path, _, fnames in sorted(os.walk(data_path)):\n for fname in sorted(fnames):\n if is_image_file(fname):\n #f 'mask' not in fname:\n img_path = os.path.join(dir_path, fname)\n images.append(img_path)\n assert images, '{:s} has no valid image file'.format(data_path)\n return sorted(images)\n\n\ndef _get_ptx_pairs(folder, mode='train'):\n import csv\n import cv2\n if mode != 'test':\n # Ordnerstruktur und/oder File in -> List[Image]\n data_list = get_image_paths(r'E:\\repos\\PTXSegmentationForReal\\stage2_dataset\\segData')\n imgID_dict = {}\n imgID_withMask = []\n # filter img without PTX\n with open(r'E:\\repos\\PTXSegmentationForReal\\stage2_dataset\\stage_2_train.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count > 0:\n if int(row[1].strip().split(' ')[0]) != -1:\n imgID_withMask.append(row[0])\n line_count += 1\n\n # extract imgID from path\n neg_counter = 0\n debugging = False\n for d in data_list:\n if 'mask' in d:\n imgID = os.path.basename(d).split('_mask.png')[0]\n else:\n imgID = os.path.basename(d).split('.png')[0]\n # imgID = d.split('images_dcm')[1]\n # imgID = imgID.split('/')[1]\n if imgID.split('_')[-1] not in imgID_withMask:\n neg_counter += 1\n if neg_counter >= len(imgID_withMask) + len(imgID_withMask) * (1/3) and not imgID in imgID_dict.keys():\n #if neg_counter >= 0 and not imgID in imgID_dict.keys():\n continue\n\n # imgID = imgID.split('case_')[1]\n if imgID.split('_')[-1] in imgID_withMask:\n if not imgID in imgID_dict.keys():\n imgID_dict[imgID] = {}\n imgID_dict[imgID]['patID'] = imgID\n if 'mask' not in [d][0]:\n\n if os.path.isfile(d):\n imgID_dict[imgID]['imageFilepath'] = d\n else:\n print(d)\n elif 'mask' in [d][0]:\n # correct maks to 0,1\n #img = cv2.imread(d, 0)\n #if np.max(img) == 255:\n # img = img / 255\n # cv2.imwrite(d, img)\n\n if os.path.isfile(d):\n imgID_dict[imgID]['segmentationFilepath'] = d\n else:\n print(d)\n elif True:\n if not imgID in imgID_dict.keys():\n imgID_dict[imgID] = {}\n imgID_dict[imgID]['patID'] = imgID\n if 'mask' not in [d][0]:\n\n if os.path.isfile(d):\n imgID_dict[imgID]['imageFilepath'] = d\n else:\n print(d)\n elif 'mask' in [d][0]:\n if os.path.isfile(d):\n imgID_dict[imgID]['segmentationFilepath'] = d\n else:\n print(d)\n # if mode != 'test':\n # root_folder = os.path.join(folder, r'train\\images_dcm')\n # data_list = get_image_paths(root_folder)\n # imgID_withMask = []\n # # filter img without PTX\n # with open(r'E:\\repos\\PTXSegmentation\\input\\train-rle.csv') as csv_file:\n # csv_reader = csv.reader(csv_file, delimiter=',')\n # line_count = 0\n # for row in csv_reader:\n # if line_count > 0:\n # if int(row[1].strip().split(' ')[0]) != -1:\n # imgID_withMask.append(row[0])\n # line_count += 1\n # # extract imgID from path\n # neg_counter = 0\n # debugging = False\n # for d in data_list:\n # if 'mask' in d:\n # imgID = os.path.basename(d).split('_mask.png')[0]\n # else:\n # imgID = os.path.basename(d).split('.png')[0]\n # # imgID = d.split('images_dcm')[1]\n # # imgID = imgID.split('/')[1]\n # if imgID.split('_')[-1] not in imgID_withMask:\n # neg_counter += 1\n # # if neg_counter >= len(imgID_withMask) + len(imgID_withMask) * (1/3) and not imgID in imgID_dict.keys():\n # if neg_counter >= 0 and not imgID in imgID_dict.keys():\n # continue\n #\n # if imgID.split('_')[-1] in imgID_withMask:\n # if not imgID in imgID_dict.keys():\n # imgID_dict[imgID] = {}\n # imgID_dict[imgID]['patID'] = imgID\n # if 'mask' not in [d][0]:\n #\n # if os.path.isfile(d):\n # imgID_dict[imgID]['imageFilepath'] = d\n # else:\n # print(d)\n # elif 'mask' in [d][0]:\n # # correct maks to 0,1\n # img = cv2.imread(d, 0)\n # if np.max(img) == 255:\n # img = img / 255\n # cv2.imwrite(d, img)\n #\n # if os.path.isfile(d):\n # imgID_dict[imgID]['segmentationFilepath'] = d\n # else:\n # print(d)\n # elif True:\n # if not imgID in imgID_dict.keys():\n # imgID_dict[imgID] = {}\n # imgID_dict[imgID]['patID'] = imgID\n # if 'mask' not in [d][0]:\n #\n # if os.path.isfile(d):\n # imgID_dict[imgID]['imageFilepath'] = d\n # else:\n # print(d)\n # elif 'mask' in [d][0]:\n # if os.path.isfile(d):\n # imgID_dict[imgID]['segmentationFilepath'] = d\n # else:\n # print(d)\n # data_list_tmp = []\n # for d in data_list:\n # imgID = d.split('images_dcm')[1]\n # imgID = imgID.split('\\\\')[1]\n # if imgID in imgID_withMask:\n # data_list_tmp.append(d)\n # data_list = data_list_tmp\n # #split data_list\n # train_len = int(np.ceil(len(data_list) * 0.8))\n # img_paths = []\n # mask_paths = []\n # if mode == 'train':\n # data_list = data_list[:train_len]\n # else:\n # data_list = data_list[train_len:]\n #\n # for d in data_list:\n # # finding masks\n # mask_name = os.path.join(os.path.dirname(d), 'mask_{}_0.png'.format(os.path.basename(d).split('.pn')[0]))\n # mask_names = []\n # counter = 1\n # while os.path.isfile(mask_name):\n # mask_names.append(mask_name)\n # mask_name = os.path.join(os.path.dirname(d), 'mask_{}_{}.png'.format(os.path.basename(d).split('.pn')[0], counter))\n # counter += 1\n # if os.path.isfile(d):\n # img_paths.append(d)\n # mask_paths.append(mask_names)\n # else:\n # print(d, mask_name)\n #convert dict to list:\n img_paths = list()\n mask_paths = list()\n for k in imgID_dict.keys():\n img_paths.append(imgID_dict[k]['imageFilepath'])\n mask_paths.append(imgID_dict[k]['segmentationFilepath'])\n train_len = int(np.ceil(len(img_paths) * 0.85))\n if mode == 'train':\n img_paths = img_paths[:train_len]\n mask_paths = mask_paths[:train_len]\n else:\n img_paths = img_paths[train_len:]\n mask_paths = mask_paths[train_len:]\n return img_paths, mask_paths\n else:\n root_folder = os.path.join(r'E:\\repos\\PTXSegmentationForReal\\stage2_dataset\\testing_preFullSize')\n data_list = get_image_paths(root_folder)\n img_paths = []\n for d in data_list:\n img_paths.append(d)\n return img_paths\n\n\nif __name__ == '__main__':\n train_dataset = PTXSegmentation()\n","sub_path":"core/data/dataloader/ptx.py","file_name":"ptx.py","file_ext":"py","file_size_in_byte":12428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560148413","text":"def add(p, q):\n px, py = p\n qx, qy = q\n return px + qx, py + qy\n\n\ndef dot(p, q):\n px, py = p\n qx, qy = q\n return px * qx + py * qy\n\n\ndef main():\n x = 48, 6\n v = 0, 0\n\n target_velocity = 8\n target_height = 48\n\n cost = 0\n for turn in range(256):\n px, py = x\n print(\"turn {}: {}, {}\".format(turn, px, py))\n if max(abs(px), abs(py)) > 128:\n print(\"went outer space on turn {}\".format(turn))\n return\n if max(abs(px), abs(py)) < 16:\n print(\"crashed on planet surface {}\".format(turn))\n return\n gx, gy = 0, 0\n if px >= 0 and px >= abs(py):\n gx -= 1\n if px <= 0 and px <= -abs(py):\n gx += 1\n if py >= 0 and py >= abs(px):\n gy -= 1\n if py <= 0 and py <= -abs(px):\n gy += 1\n g = gx, gy\n nv = add(v, g)\n\n xnorm = dot(x, x) ** 0.5\n nx, ny = px / xnorm, py / xnorm\n rx, ry = ny, -nx\n r = rx, ry\n\n r_v = dot(nv, r) / (dot(r, r) ** 0.5)\n\n cur_height = xnorm\n\n cur_diff = abs(r_v - target_velocity)\n action = -9999, (-5, -5)\n for ctx in range(-1, 2):\n for cty in range(-1, 2):\n ct = ctx, cty\n cv = add(nv, ct)\n cr_v = dot(cv, r) / (dot(r, r) ** 0.5)\n cx = add(x, cv)\n cand_height = dot(cx, cx) ** 0.5\n improve = (cur_diff - abs(cr_v - target_velocity))\n improve += (abs(cur_height - target_height) - abs(cand_height - target_height))\n cand_action = improve, ct\n if cand_action > action:\n action = cand_action\n tx, ty = action[1]\n\n t = tx, ty\n if tx != 0 or ty != 0:\n cost += 1\n v = add(add(v, g), t)\n x = add(x, v)\n print(\"survived 256 turns with cost {}\".format(cost))\n\n\nif __name__ == '__main__':\n main()","sub_path":"manarimo/misc/orbit.py","file_name":"orbit.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"319342610","text":"import pygame, RCcarFunctions\npygame.init()\nRCcarFunctions.init()\ntry:\n while True:\n #RCcarFunctions.forward()\n keypressed = pygame.key.get_pressed()\n #for event in pygame.event.get():\n # if event.type == pygame.KEYDOWN:\n if keypressed[pygame.K_w]:\n RCcarFunctions.forward()\n elif keypressed[pygame.K_a]:\n RCcarFunctions.spinleft()\n elif keypressed[pygame.K_s]:\n RCcarFunctions.reverse()\n elif keypressed[pygame.K_d]:\n RCcarFunctions.spinright()\n else: \n RCcarFunctions.stop()\n pygame.event.pump()\nexcept KeyboardInterrupt:\n print (\"\\ncleaning up\")\n RCcarFunctions.cleanup()\n","sub_path":"RaspberryPi/RCcar.py","file_name":"RCcar.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"542439371","text":"import tkinter as tk\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.pack()\n self.create_widgets()\n\n def create_widgets(self):\n self.hi_there = tk.Button(self)\n self.hi_there[\"text\"] = \"metronome\"\n self.hi_there[\"font\"] = ('Helvetica', '20')\n self.hi_there[\"command\"] = self.say_hi\n self.hi_there.pack(side=\"top\", ipadx=40, ipady=20, padx=80, pady=80)\n\n self.bpm = tk.Label(self)\n self.bpm[\"text\"] = str(tempo)\n self.bpm[\"font\"] = ('Helvetica', '20')\n self.bpm.pack(side=\"top\", ipadx=40, ipady=20, padx=80, pady=80)\n \n self.fasterbut = tk.Button(self)\n self.fasterbut[\"text\"] = \"+\"\n self.fasterbut[\"font\"] = ('Helvetica', '40')\n self.fasterbut[\"command\"] = self.faster\n self.fasterbut.pack(side=\"left\", ipadx=40, ipady=20, padx=80, pady=80)\n\n self.slowerbut = tk.Button(self)\n self.slowerbut[\"text\"] = \"-\"\n self.slowerbut[\"font\"] = ('Helvetica', '40')\n self.slowerbut[\"command\"] = self.slower\n self.slowerbut.pack(side=\"right\", ipadx=40, ipady=20, padx=80, pady=80)\n \n self.quit = tk.Button(self, text=\"QUIT\", fg=\"Blue\",\n command=root.destroy)\n self.quit.pack(side=\"bottom\", ipadx=80, ipady=80, padx=80, pady=80)\n\n def say_hi(self):\n print(\"hi there, everyone!\")\n \n def faster(self):\n global tempo\n tempo = tempo + 1\n self.bpm.configure(text=tempo)\n print(\"metronome goes faster \" + str(tempo))\n\n def slower(self):\n global tempo\n tempo = tempo - 1\n self.bpm.configure(text=tempo)\n print(\"metronome goes slower \" + str(tempo))\n \n \n \n\ntempo = 120 \nroot = tk.Tk()\napp = Application(master=root)\napp.mainloop()\n","sub_path":"metronome_01.py","file_name":"metronome_01.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"28672749","text":"import itertools\nimport types\nimport functools\n\nfrom paka import funcreg\n\nfrom . import astlib\nfrom .utils import A\n\n\nNODE_CLASSES = (astlib.BaseNode, astlib.Name)\n_PREREGISTERED_NODE_CLASSES_ATTR_NAME = \"_layer_prereg_nodes_clss\"\n_INTERNAL_REGISTRY_ATTR_NAME = \"_registry\"\n\n\ndef register(*node_classes):\n def _wrapper(func):\n setattr(\n func, _PREREGISTERED_NODE_CLASSES_ATTR_NAME,\n node_classes)\n return func\n return _wrapper\n\n\nclass LayerMeta(type):\n\n def __new__(cls, name, bases, attrs):\n # Layer does not have bases, so we filter it out this way.\n if bases:\n registry = funcreg.TypeRegistry()\n for value in attrs.values():\n if isinstance(value, types.FunctionType):\n for node_class in getattr(\n value,\n _PREREGISTERED_NODE_CLASSES_ATTR_NAME, ()):\n registry.register(value, node_class)\n attrs[_INTERNAL_REGISTRY_ATTR_NAME] = registry\n return type.__new__(cls, name, bases, attrs)\n\n\nclass Layer(metaclass=LayerMeta):\n\n def get_registry(self):\n reg = funcreg.TypeRegistry()\n for node_class, func in getattr(\n self, _INTERNAL_REGISTRY_ATTR_NAME).items():\n reg.register(functools.partial(func, self), node_class)\n return reg\n\n\ndef transform_node(node, *, registry):\n node_type = type(node)\n if node in A(astlib.Annotated):\n node_type = type(node.node)\n node_func = registry.get(node_type)\n if node_func:\n yield from node_func(node)\n else:\n yield node\n\n\ndef transform_ast(ast_, *, registry):\n for node in ast_:\n yield from transform_node(node, registry=registry)\n\n\ndef expand_ast(ast_, *, registry):\n yield from registry.get(astlib.AST)(ast_, registry)\n\n\ndef proceed(ast_, *, registry):\n for node in ast_:\n node_func = registry.get(type(node))\n if node_func:\n node_func(node)\n return None\n\n\ndef b(layer, **kwords):\n def helper(body):\n reg = layer(**kwords).get_registry()\n return list(itertools.chain.from_iterable(\n map(lambda stmt: list(\n transform_node(stmt, registry=reg)\n ), body)\n ))\n return helper\n\n\ndef b_proceed(layer, **kwords):\n def helper(body):\n proceed(body, registry=layer(**kwords).get_registry())\n return helper\n","sub_path":"solyanka/solyanka/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"229593473","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 2 12:27:11 2019\n\n@author: natewagner\n\"\"\"\n\nimport plotly.graph_objects as go\nfrom plotly.offline import plot\nimport psycopg2\nimport sys\nconn = psycopg2.connect(\"dbname=LEGOS user=nwagner\")\ncur = conn.cursor()\n\n\n\n\n# function to clean the results from a query:\ndef clean(i):\n holder = []\n for x in range(0, len(i) ):\n holder.append(i[x][0])\n return holder\n\n# returns cleaned SQL output \ndef printdata(sets, names, percents):\n for x in range(0, len(sets)):\n print(str(sets[x]) + ' ' + str(names[x]) + ' ' + str(percents[x]))\n\n\ndef findOtherSets(setnums):\n ''' \n Function takes in lego set-numbers and outputs an interactive chart showing\n the percent of parts you have needed to build other lego sets\n\n '''\n \n # User will input the set_nums from sets that they have\n #setnums = input(\"Please enter the set_num associated with the set you have, seperated by a comma: \")\n #setnums = \"0013-1, 0013-10, 0055-1, 00222-1, 0009995-1\"\n \n \n # clean the user input\n setnums = setnums.split(\",\")\n setnums = [x.replace(' ', '') for x in setnums]\n \n \n # initiate query to obtain inventory_id's form the corresponding set_nums\n InventoryID = \"select inventory_id from inventories where set_num = \" + \"'\" + setnums[0] + \"'\"\n \n # create query:\n # this adds the \" or set_num = \" to end of the query depending on how many sets the user has\n for i in range(1, len(setnums)):\n whereStatement = \" or set_num = \" + \"'\" + setnums[i] + \"'\" \n if len(setnums) == 1:\n InventoryID = \"select inventory_id from inventories where set_num = \" + \"'\" + setnums + \"'\" \n else:\n InventoryID = InventoryID + whereStatement\n \n # finalize query:\n InventoryID = InventoryID + \";\"\n \n # execute SQL command:\n cur.execute(InventoryID)\n InventoryIDS = cur.fetchall()\n \n \n \n \n IDs = clean(InventoryIDS)\n \n # intialize query to get the associated parts and how many:\n PartsList = \"select part_num from inventory_parts where inventory_id = \" + str(IDs[0])\n \n # create query:\n # this adds the additional inventory_ids to end of query:\n for i in range(1, len(IDs)):\n whereStatement = \" or inventory_id = \" + str(IDs[i])\n if len(IDs) == 1:\n PartsList = \"select part_num from inventory_parts where inventory_id = \" + str(IDs) \n else:\n PartsList = PartsList + whereStatement\n \n # finalize query:\n PartsList = PartsList + \";\"\n \n # execute in SQL\n cur.execute(PartsList)\n ALLPartsList = cur.fetchall()\n \n \n \n \n # clean parts\n ALLPartsList = clean(ALLPartsList)\n \n \n # initialize query to get quantity of parts we have\n GetParts = \"select inventory_id, part_num, quantity from inventory_parts where part_num = \" + \"'\" + ALLPartsList[0] + \"'\" \n \n \n # create query:\n # this adds the additional part_nums to end of query:\n for i in range(1, len(ALLPartsList)):\n whereStatement = \" or part_num = \" + \"'\" + str(ALLPartsList[i]) + \"'\" \n if len(ALLPartsList) == 1:\n GetParts = \"select inventory_id, part_num, quantity from inventory_parts where inventory_id = \" + \"'\" + str(ALLPartsList) + \"'\" \n else:\n GetParts = GetParts + whereStatement\n \n\n \n cur.execute(\"select set_num, set_name, sum/num_parts::float*100 as percentParts from (select a.set_num, a.sum, b.set_name, b.num_parts from (select a.set_num, b.sum from inventories a, (select inventory_id, sum(quantity) from (\" + GetParts + \") hold group by hold.inventory_id order by sum desc) b where a.inventory_id = b.inventory_id) a, sets b where a.set_num = b.set_num) a order by percentParts desc limit 20;\")\n InventoryID_SumParts = cur.fetchall()\n #print(InventoryID_SumParts)\n \n sets = []\n names = []\n percents = [] \n for x in InventoryID_SumParts:\n sets.append(x[0])\n names.append(x[1])\n percents.append(x[2])\n\n# # If user wants to see how many complete sets they can build:\n# if numFull == True:\n# cur.execute(\"select count(*) from (select set_num, set_name, sum/num_parts::float*100 as percentParts from (select a.set_num, a.sum, b.set_name, b.num_parts from (select a.set_num, b.sum from inventories a, (select inventory_id, sum(quantity) from (\" + GetParts + \") hold group by hold.inventory_id order by sum desc) b where a.inventory_id = b.inventory_id) a, sets b where a.set_num = b.set_num) a order by percentParts desc) b where percentparts >= 100 ;\")\n# numberOfCompletes = cur.fetchall()\n# print(\"You can build \" + str(clean(numberOfCompletes)[0]) + \" complete sets.\")\n# else:\n# pass\n \n #printdata(sets, names, percents)\n \n #make setnum pretty:\n numss = []\n for x in sets:\n numss.append(\"Set Number: \" + x)\n\n\n\n\n # plot chart:\n data = [go.Bar(\n x=names,\n y=percents,\n text = numss\n )]\n\n plot(data)\n \n return ALLPartsList, setnums\n\n \n \n \n\nfindOtherSets(str(sys.argv[1]))\n\n\n\n","sub_path":"findOtherSets.py","file_name":"findOtherSets.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"30854368","text":"import numpy as np\nimport matplotlib.pyplot as pl\nimport astropy.constants as au\nimport astropy.units as au\nimport sys\nimport os\nfrom matplotlib import rc\nrc('font',**{'family':'serif'}) # This is for Latex writing\n\nTm_T0 = lambda a: a**(-2.0)\nTr_T0 = lambda a: a**(-1.0)\n\nn = 1000\na = np.logspace(-4,0,n)\n\npl.figure(); pl.hold(True); pl.grid(True)\npl.title(\"Time evolution of temperature\")\npl.xlabel(r\"relative scalefactor $\\frac{a(t)}{a_0}$\")\npl.ylabel(r\"relative temperature $\\frac{T(a)}{T_0}$\")\npl.plot(a,Tm_T0(a), label=r\"$T_m$\")\npl.plot(a,Tr_T0(a), label=r\"$T_r$\")\npl.legend(loc=\"best\", fontsize=11)\npl.savefig(\"temperature_rad_mat_ex3.png\")\n\npl.xscale(\"log\")\npl.savefig(\"temperature_rad_mat_xlog_ex3.png\")\n\npl.xscale(\"linear\")\npl.yscale(\"log\")\npl.savefig(\"temperature_rad_mat_ylog_ex3.png\")\n\npl.xscale(\"log\")\npl.savefig(\"temperature_rad_mat_xylog_ex3.png\")\n","sub_path":"assignment1/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"25774735","text":"import discord\nfrom discord.ext import commands\n\nclass Meta:\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name=\"help\")\n async def help(self, ctx):\n emb1 = discord.Embed(description=\"**Reaction Poll**\\nCreate a reaction poll by typing 'poll: *your message*’. Poll Bot will automatically add the reactions 👍, 👎, and 🤷.\\nCreate a reaction poll with multiple options by typing `poll: {title} [Option1] [Option2] [Option3]`.\\n\\n**Strawpoll**\\nCreate a strawpoll by typing '+strawpoll {title} [Option1] [Option2] [Option 3]', with up to 30 options.\\n\\n**Other Commands**\\n+updates, +invite\\n\\n**Still Have Questions?**\\nJoin our Dscord server: \" + \"\\n\" + \"Ask us on Twitter: \" + \"\\n\\n **Duration polls are currently under maintenance and will be back up soon.**\", colour=0x83bae3)\n try:\n await ctx.author.send(embed=emb1)\n await ctx.message.channel.send('Check your DMs!')\n except discord.HTTPException:\n await ctx.message.channel.send(embed=emb1)\n\n @commands.command(name=\"invite\")\n async def invite(self, ctx):\n emb1 = discord.Embed(description=\"Invite Poll Bot to your server: \", colour=0x83bae3)\n await ctx.message.channel.send(embed=emb1)\n\n @commands.command(name=\"updates\")\n async def updates(self, ctx):\n emb1 = discord.Embed(description=\"**Please join the Poll Bot server and see #announcements to see the latest updates! **\")\n await ctx.message.channel.send(embed=emb1)\n\ndef setup(bot):\n bot.add_cog(Meta(bot))\n","sub_path":"cogs/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"315799162","text":"\"\"\"\n1058. Minimize Rounding Error to Meet Target (Medium)\n\nGiven an array of prices [p1,p2...,pn] and a target, round each price pi to Roundi(pi) so that the rounded array [Round1(p1),Round2(p2)...,Roundn(pn)] sums to the given target. Each operation Roundi(pi) could be either Floor(pi) or Ceil(pi).\n\nReturn the string \"-1\" if the rounded array is impossible to sum to target. Otherwise, return the smallest rounding error, which is defined as Σ |Roundi(pi) - (pi)| for i from 1 to n, as a string with three places after the decimal.\n\nExample 1:\n\nInput: prices = [\"0.700\",\"2.800\",\"4.900\"], target = 8\nOutput: \"1.000\"\nExplanation: \nUse Floor, Ceil and Ceil operations to get (0.7 - 0) + (3 - 2.8) + (5 - 4.9) = 0.7 + 0.2 + 0.1 = 1.0 .\nExample 2:\n\nInput: prices = [\"1.500\",\"2.500\",\"3.500\"], target = 10\nOutput: \"-1\"\nExplanation: \nIt is impossible to meet the target.\n\nNote:\n\n1 <= prices.length <= 500.\nEach string of prices prices[i] represents a real number which is between 0 and 1000 and has exactly 3 decimal places.\ntarget is between 0 and 1000000.\n\"\"\"\n\n\nclass Solution(object):\n def minimizeError(self, prices, target):\n \"\"\"\n :type prices: List[str]\n :type target: int\n :rtype: str\n \"\"\"\n prices = [float(item) for item in prices]\n t_round = sum([round(item) for item in prices])\n res = sum([abs(round(item) - item) for item in prices])\n if t_round == target:\n # just round\n return str(\"%.3f\" % res)\n elif t_round < target:\n # should round up\n tmp = [item - round(item) for item in prices if round(item) < item]\n diff = target - t_round\n if diff > len(tmp):\n return \"-1\"\n tmp.sort(reverse=True)\n tmp = tmp[:diff]\n res2 = sum([1.0 - 2 * item for item in tmp])\n return str(\"%.3f\" % (res + res2))\n else: # t_round > target\n # should round down\n tmp = [round(item) - item for item in prices if round(item) > item]\n diff = t_round - target\n if diff > len(tmp):\n return \"-1\"\n tmp.sort(reverse=True)\n tmp = tmp[:diff]\n res2 = sum([1.0 - 2 * item for item in tmp])\n return str(\"%.3f\" % (res + res2))\n\n\nif __name__ == \"__main__\":\n a = Solution()\n print(a.minimizeError([\"0.700\", \"2.800\", \"4.900\"], 8))\n","sub_path":"python/leetcode/math/1058_minimize_rounding_error.py","file_name":"1058_minimize_rounding_error.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"87284063","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('menu', '0024_auto_20150714_2016'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='comment',\n name='pub_date',\n ),\n migrations.AddField(\n model_name='comment',\n name='publishDate',\n field=models.DateTimeField(default=datetime.datetime(2015, 7, 15, 1, 29, 11, 230653, tzinfo=utc), verbose_name=b'date published'),\n ),\n ]\n","sub_path":"menu/migrations/0025_auto_20150714_2029.py","file_name":"0025_auto_20150714_2029.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"211274580","text":"import socket\nimport glob, os,sys\nimport httplib\nimport json\nimport ConfigParser\nimport numpy as np\nimport pandas as pd\n#from XMLParse import XMLParser\nconfig = ConfigParser.ConfigParser()\ncwd = os.getcwd()\nconfpath=cwd+\"/DevKit/Etc/config.properties\"\nconfig.read(confpath)\ntenantIDIP = config.get(\"myvars\", \"tenantIDIP\")\nroot_path = config.get(\"myvars\", \"root_path\")\nport = config.get(\"myvars\", \"port\")\nprint(port,tenantIDIP)\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nclass client:\n\tdef run(self):\n\t\theaders = {'Content-type': 'application/json'}\n\t\ttest = httplib.HTTPConnection(tenantIDIP,port)\n\t\t\n\t\tdatafile=\"dataset1\"\n\t\t\n\t\tresponse=test.request('POST', '/markdown',datafile,headers)\n\t\tr1 = test.getresponse()\n\t\tprint(\"r1\",r1)\n\t\tdata = r1.read()\n\t\tresp=data.splitlines()\n\t\t\n\t\treturn resp;\n\nEdge=client()\nresponse=Edge.run()\nprint(\"Succesfuly completed Predictions\")\na=eval(response[5])\nprint(dict(pd.Series(a).value_counts()))\n\n\n\t\n\n","sub_path":"Pangea/PMML/packagefor_Edison_DTC/DevKit/Bin/Services/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"189781589","text":"import pandas as pd\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.feature_selection import RFE\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom yellowbrick.classifier import ClassPredictionError\nfrom yellowbrick.classifier import ROCAUC\nimport matplotlib.pyplot as plt\n\nfeat_df = pd.read_csv('/home/fahad/DATA/ML-project/ml-project/data/WorkingData/features_new.csv')\n\n# Separating inputs and outputs\nX = feat_df.iloc[:, :-1].values\ny = feat_df.iloc[:, -1].values\npca = PCA(n_components=3)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)\nclf = ExtraTreesClassifier()\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint(clf.feature_importances_)\ndict_feat = {0: 'RMS', 1: 'Mean', 2: 'Var', 3: 'Skew', 4: 'Kurt',\n 5: ' CrestFactor', 6: 'ImpulseFactor', 7: 'ShapeFactor',\n 8: 'Median', 9: 'Range'}\n\n\nfeat_df1 = pd.Series(dict_feat)\n\nimportance = clf.feature_importances_\nimport_df = pd.Series(importance)\ndf = pd.concat([feat_df1, import_df], axis=1)\nsort_df = df.sort_values(by=[1], ascending=False)\nRMS_Norm = feat_df[feat_df['FaultType'] == 'Normal_0']['RMS']\nVar_Norm = feat_df[feat_df['FaultType'] == 'Normal_0']['Var']\nRMS_B7 = feat_df[feat_df['FaultType'] == 'B007_0']['RMS']\nVar_B7 = feat_df[feat_df['FaultType'] == 'B007_0']['Var']\nRMS_B14 = feat_df[feat_df['FaultType'] == 'B014_0']['RMS']\nVar_B14 = feat_df[feat_df['FaultType'] == 'B014_0']['Var']\nRMS_B21 = feat_df[feat_df['FaultType'] == 'B021_0']['RMS']\nVar_B21 = feat_df[feat_df['FaultType'] == 'B021_0']['Var']\nRMS_B28 = feat_df[feat_df['FaultType'] == 'B028_0']['RMS']\nVar_B28 = feat_df[feat_df['FaultType'] == 'B028_0']['Var']\nRMS_IR7 = feat_df[feat_df['FaultType'] == 'IR007_0']['RMS']\nVar_IR7 = feat_df[feat_df['FaultType'] == 'IR007_0']['Var']\nRMS_IR14 = feat_df[feat_df['FaultType'] == 'IR014_0']['RMS']\nVar_IR14 = feat_df[feat_df['FaultType'] == 'IR014_0']['Var']\nRMS_IR21 = feat_df[feat_df['FaultType'] == 'IR021_0']['RMS']\nVar_IR21 = feat_df[feat_df['FaultType'] == 'IR021_0']['Var']\nRMS_IR28 = feat_df[feat_df['FaultType'] == 'IR028_0']['RMS']\nVar_IR28 = feat_df[feat_df['FaultType'] == 'IR028_0']['Var']\n\ndata = ((RMS_Norm, Var_Norm), (RMS_B7, Var_B7), (RMS_B14, Var_B14), (RMS_B21, Var_B21), (RMS_B28, Var_B28),\n (RMS_IR7, Var_IR7), (RMS_IR14, Var_IR14), (RMS_IR21, Var_IR21), (RMS_IR28, Var_IR28))\ncolors = (\"red\", \"green\", \"blue\", \"yellow\", \"orange\", \"black\", \"pink\", \"purple\", \"brown\", \"gray\")\ngroups = (\"Normal\", \"B007\", \"B014\", \"B021\", \"B028\", \"IR007\", \"IR014\", \"IR021\", \"IR028\")\nmarkers = ()\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\nfor data, color, group in zip(data, colors, groups):\n x, y = data\n ax.scatter(x, y, c=color, edgecolors='none', label=group)\n\nplt.title('Matplot scatter plot')\nplt.legend(loc=2)\nplt.show()\n\n\nplt.scatter(RMS_Norm, Var_Norm, 'ro',\n RMS_B7, Var_B7, 'bs',\n RMS_B14, Var_B14, 'go',\n RMS_B21, Var_B21, 'r-',\n RMS_B28, Var_B28, 'yo')\n\nplt.legend()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nplt.bar(sort_df[0], sort_df[1])\nplt.title(\"Feature Importance VS feature\")\nplt.xticks(rotation=70)\nplt.savefig('/home/fahad/DATA/ML-project/ml-project/Plots/Feature_imp_with_Ext_Tree_classifier.png')\n\n\n# --------------------------------FOLDER NAMES GO HERE ---------------------------------------------------------------\nclasses = ['Normal_0', 'B007_0', 'B014_0',\n 'B021_0', 'B028_0', 'IR007_0',\n 'IR014_0', 'IR021_0', 'IR028_0']\n\n\n\nvisualizer = ROCAUC(clf, classes=classes)\n\nvisualizer.fit(X_train, y_train) # Fit the training data to the visualizer\nvisualizer.score(X_test, y_test) # Evaluate the model on the test data\ng = visualizer.poof('/home/fahad/DATA/ML-project/ml-project/Plots/DE_plots/ROC_with_NaiveBayes_Gaussian.png') # Draw/show/poof the data\n\n\n# clf.fit(X_train, y_train)\n# print(clf.feature_importances_)\nvisualizer.fit(X_train, y_train)\nvisualizer.score(X_test, y_test)\n\n# Draw visualization\ng = visualizer.poof()\n\ny_pred = clf.predict(X_test)\nacc = accuracy_score(y_pred, y_test)\n\nfrom yellowbrick.features import ParallelCoordinates\n\nvisualizer = ParallelCoordinates()\nvisualizer.fit_transform(X_train, y_train)\nvisualizer.poof()\n\n","sub_path":"src/ml-project-work/PCA.py","file_name":"PCA.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"472338621","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 6 13:03:28 2020\n\n@author: Jacky\n\"\"\"\n\nfrom __future__ import print_function\nimport cv2 as cv\nimport argparse\nfrom datetime import datetime\nfrom backend_service import AlertClient\n\nparser = argparse.ArgumentParser(description='This program shows how to use background subtraction methods provided by \\\n OpenCV. You can process both videos and images.')\nparser.add_argument('--input', type=str, help='Path to a video or a sequence of image.', default='vtest.avi')\nparser.add_argument('--algo', type=str, help='Background subtraction method (KNN, MOG2).', default='MOG2')\nargs = parser.parse_args()\nif args.algo == 'MOG2':\n backSub = cv.createBackgroundSubtractorMOG2()\nelse:\n backSub = cv.createBackgroundSubtractorKNN()\ncapture = cv.VideoCapture(int(args.input))\nif not capture.isOpened:\n print('Unable to open: ' + args.input)\n exit(0)\n\n\nlastTriggerTime = datetime.now()\nwhile True:\n ret, frame = capture.read()\n if frame is None:\n break\n \n fgMask = backSub.apply(frame)\n valueDict = {}\n for i in range(len(fgMask)):\n for j in range(len(fgMask[i])):\n # print(\"type:\", type(fgMask[i][j]))\n x = valueDict.get(fgMask[i][j])\n if x == None:\n valueDict[fgMask[i][j]] = 1\n else:\n valueDict[fgMask[i][j]] = valueDict[fgMask[i][j]] + 1\n \n #print(\"valueDict:\", valueDict)\n\n if valueDict.get(0) is not None:\n if valueDict[0] / fgMask.size < 0.98:\n # print(\"trigger========================\", datetime.now())\n currentTime = datetime.now()\n timeDiff = currentTime - lastTriggerTime\n if timeDiff.seconds > 1:\n lastTriggerTime = datetime.now()\n AlertClient.inform_intruder_status(True)\n #else:\n # print(\"trigger ignored since it is within 1s compare to last one\", timeDiff.microseconds)\n\n #cv.rectangle(frame, (10, 2), (100,20), (255,255,255), -1)\n cv.rectangle(frame, None, None, (255, 255, 255), -1)\n\n #cv.putText(frame, str(capture.get(cv.CAP_PROP_POS_FRAMES)), (15, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5 , (0,0,0))\n\n # fgmask = fgbg.apply(frame)\n # erosion and dilation\n # fgmask = cv.morphologyEx(fgmask, cv.MORPH_OPEN, kernel)\n\n # cv.imshow('Frame', frame)\n cv.imshow('FG Mask', fgMask)\n\n #print(\"fgMask:\", fgMask)\n \n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n","sub_path":"bk/intruderDetection/IntruderDetection.py","file_name":"IntruderDetection.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"28919111","text":"import os, sys\nfrom datetime import datetime,timedelta\nimport shutil\nfrom filecmp import cmp\nimport sched\nimport time\nimport hashlib\nimport logger\n\nlogger = logger.logger(tofile=True)\n\n#File compare\ndef hash_bytestr_iter(bytesiter, hasher, ashexstr=False):\n for block in bytesiter:\n hasher.update(block)\n # print('here')\n return (hasher.hexdigest() if ashexstr else hasher.digest())\n\ndef file_as_blockiter(afile, blocksize=65536):\n with afile:\n block = afile.read(blocksize)\n while len(block) > 0:\n yield block\n block = afile.read(blocksize)\n\ndef copyfile():\n base = \"/nfs-volume/volume6/BB/1mtcSouth\"\n path = base+\"/live\"\n\n #Begin logging\n #tlog = datetime.now().isoformat()\n #log = open('copylog_'+'_'.join(base.split('/')[-2:])+'_'+tlog+'.log', 'w')\n\n for f in os.listdir(path):\n #Generate new directory path\n file = os.path.join(path, f)\n if os.path.isfile(file):\n #Get Modification time\n time = datetime.fromtimestamp(os.stat(file).st_mtime)\n npath = base + \"/%d/%02d/%02d/%02d\"%(time.year,time.month,time.day,time.hour)\n nfile = os.path.join(npath, f)\n logger.debug('check '+file+'\\n')\n\n #Create the directory if not exist\n if not os.path.exists(npath):\n logger.info('create dir: '+npath+'\\n')\n os.makedirs(npath)\n\n if not os.path.exists(nfile):\n #Copy the file\n shutil.copy2(file, npath)\n logger.debug('Copy to '+npath+'\\n')\n #Compare the file\n hashfile = hash_bytestr_iter(file_as_blockiter(open(file, 'rb')), hashlib.sha256())\n hashnfile = hash_bytestr_iter(file_as_blockiter(open(nfile, 'rb')), hashlib.sha256())\n if hashfile==hashnfile:\n logger.info('Removing file because it was copied successfully: '+str(file))\n os.remove(file)\n else:\n logger.debug('Already exists: '+nfile+'\\n')\n logger.info('Removing file because it has already been moved: '+str(file))\n os.remove(file)\n #log.close()\n\nclass PeriodicScheduler(object):\n def __init__(self):\n self.scheduler = sched.scheduler(time.time, time.sleep)\n\n def setup(self, interval, action, actionargs=()):\n action(*actionargs)\n self.scheduler.enter(interval, 1, self.setup,\n (interval, action, actionargs))\n\n def run(self):\n self.scheduler.run()\n\ntry:\n INTERVAL = 60*15 # every 15 minutes\n periodic_scheduler = PeriodicScheduler()\n periodic_scheduler.setup(INTERVAL, copyfile) # it executes the event just once\n periodic_scheduler.run() # it starts the scheduler\nexcept KeyboardInterrupt:\n sys.exit()\n","sub_path":"utils/copyfiles_BB_South.py","file_name":"copyfiles_BB_South.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"84537369","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom django.contrib.auth import logout\nfrom django.views.generic import TemplateView, FormView\nfrom django.views import View\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.contrib import messages\nimport json\nimport requests\nfrom allauth.socialaccount.models import SocialToken\nfrom users.models import *\nfrom etc.models import *\nfrom django.utils import timezone\n\n\ndef _getNotifications(kyprofile):\n notifications = Notifications.objects.filter(users=kyprofile.caprofile,\n recieved_date__lte=timezone.now())\n context = {\n 'notifications': notifications.order_by('recieved_date'),\n 'count': notifications.count(),\n }\n return context\n\nclass IndexView(TemplateView):\n template_name = 'index.html'\n\n\n@login_required(login_url=\"/login\")\ndef CaFormView(request):#ca-form\n template_name='ca-form.html'\n kyprofile = request.user\n if request.method == 'POST':\n post = request.POST\n collegeName = post.get('college', None)\n year = post.get('year', None)\n whatsapp_number = post.get('whatsapp_number', None)\n postal_address = post.get('postal_address', None)\n pincode = post.get('pincode', None)\n mobile_number = post.get('mobile_number', None)\n if collegeName and whatsapp_number and mobile_number and \\\n postal_address and pincode and year:\n\n ca, created = CAProfile.objects.get_or_create(kyprofile=kyprofile)\n if created:\n ca.whatsapp_number=whatsapp_number,\n ca.postal_address=postal_address,\n ca.pincode=pincode\n ca.save()\n\n welcome_note = Notifications.objects.all().order_by('id')[0]\n welcome_note.users.add(ca)\n welcome_note.save()\n college, created = College.objects.get_or_create(\n collegeName=collegeName)\n\n kyprofile.mobile_number = mobile_number\n kyprofile.college = college\n kyprofile.year = year\n kyprofile.has_ca_profile = True\n kyprofile.save()\n return redirect('/dashboard')\n else:\n return HttpResponse(\"Invalid form submission\")#sth to be done\n else:\n context = {\n 'email': kyprofile.email,\n 'full_name': kyprofile.full_name,\n 'all_colleges': College.objects.all(),\n }\n return render(request, template_name, context)\n\n@receiver(post_save,sender=CAProfile)\ndef AddCaToSheet(sender,instance,**kwargs):\n if instance.ca_id:\n data = {'id': instance.kyprofile.ky_id,\n 'name': instance.kyprofile.full_name,\n 'email': instance.kyprofile.email,\n 'college': instance.kyprofile.college,\n 'refCode': instance.ca_id,\n 'year': instance.kyprofile.year,\n 'sex': instance.kyprofile.gender,\n 'mobileNumber': instance.kyprofile.mobile_number}\n\n url = 'https://script.google.com/macros/s/AKfycbxUUHoa81jigbSdGtSl91qTdCJ0J__JA1HdqNq-VFAfuTtq4o01/exec'\n\n return requests.post(url, data=data)\n\n\n\n\n@login_required(login_url=\"/login\")\ndef DashboardView(request):\n kyprofile = request.user\n if kyprofile.has_ca_profile:\n template_name = 'ca-dashboard/dashboard.html'\n context = _getNotifications(kyprofile)\n context['posts'] = Post.objects.all().order_by('-id')[:9]\n\n return render(request, template_name, context)\n else:\n return redirect('/ca-form')\n\n\n@login_required(login_url=\"/login\")\ndef CAProfileUpdateView(request):\n kyprofile = request.user\n ca_profile_object = CAProfile.objects.get(kyprofile=kyprofile)\n\n if request.method == 'POST':\n post = request.POST\n kyprofile.mobile_number = post.get('mobile_number', None)\n kyprofile.save()\n ca_profile_object.whatsapp_number = post.get('whatsapp_number', None)\n ca_profile_object.postal_address = post.get('address', None)\n ca_profile_object.pincode = post.get('pincode', None)\n ca_profile_object.save()\n\n context = {\n \"email\": kyprofile.email,\n \"fullname\": kyprofile.full_name,\n \"year\": kyprofile.year,\n \"gender\": kyprofile.gender,\n \"mobile_number\": kyprofile.mobile_number,\n \"college\": kyprofile.college,\n \"whatsapp_number\": ca_profile_object.whatsapp_number,\n \"pincode\": ca_profile_object.pincode,\n \"address\": ca_profile_object.postal_address,\n\n }\n\n if kyprofile.has_ca_profile:\n template_name = 'ca-dashboard/user.html'\n notices = _getNotifications(kyprofile)\n #new_context = context + notices\n new_context = context.copy()\n new_context.update(notices)\n return render(request, template_name, new_context)\n else:\n return redirect('/ca-form')\n\n@login_required(login_url=\"/login\")\ndef LeaderBoardView(request):\n kyprofile = request.user\n print(kyprofile)\n if kyprofile.has_ca_profile:\n template_name = 'ca-dashboard/leaderboard.html'\n context = _getNotifications(kyprofile)\n return render(request, template_name, context)\n else:\n return redirect('/ca-form')\n\n\n@login_required(login_url=\"/login\")\ndef NotificationsView(request):\n kyprofile = request.user\n print(kyprofile)\n if kyprofile.has_ca_profile:\n template_name = 'ca-dashboard/notifications.html'\n context = _getNotifications(kyprofile)\n return render(request, template_name, context)\n else:\n return redirect('/ca-form')\n\ndef PrivacyPolicyView(request):\n template_name = 'privacy_policy.html'\n return render(request, template_name, {})\n\ndef LogoutView(request):\n logout(request)\n return redirect('/')\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"149053310","text":"from .task_base import Task\nfrom sqlalchemy import Column, ForeignKey, Integer\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.orm.collections import attribute_mapped_collection\n\n\n__all__ = ['MethodList']\n\n\nclass MethodList(Task):\n __tablename__ = 'method_list'\n\n id = Column(Integer, ForeignKey('task.id'), primary_key=True)\n\n methods = relationship('Method',\n collection_class=attribute_mapped_collection('name'),\n cascade='all, delete-orphan')\n\n method_list = relationship('Method', order_by='Method.index')\n\n __mapper_args__ = {\n 'polymorphic_identity': 'MethodList',\n }\n\n def attach_subclass_transitions(self, transitions, start_place):\n last_failure_place = start_place\n success_places = []\n for method in self.method_list:\n success_place, failure_place = method.attach_transitions(\n transitions, last_failure_place)\n last_failure_place = failure_place\n success_places.append(success_place)\n\n for sp in success_places:\n transitions.append({\n 'inputs': [sp],\n 'outputs': [self._pn('success')],\n })\n\n return self._pn('success'), last_failure_place\n\n def create_input_sources(self, session, parallel_depths):\n super(MethodList, self).create_input_sources(session, parallel_depths)\n for method in self.method_list:\n method.create_input_sources(session, parallel_depths)\n\n def as_dict(self, detailed):\n result = {\n 'methods': [m.as_dict(detailed=detailed)\n for m in self.method_list],\n }\n if self.parallel_by is not None:\n result['parallelBy'] = self.parallel_by\n webhooks = self.get_webhooks()\n if webhooks:\n result['webhooks'] = webhooks\n\n if detailed:\n result['executions'] = {\n color: execution.as_dict(detailed=detailed)\n for color, execution in self.executions.iteritems()}\n return result\n\n def as_skeleton_dict(self):\n result = {\n 'id': self.id,\n 'methods': [m.as_skeleton_dict() for m in self.method_list],\n 'topologicalIndex': self.topological_index,\n }\n if self.parallel_by is not None:\n result['parallelBy'] = self.parallel_by\n return result\n","sub_path":"ptero_workflow/implementation/models/task/method_list.py","file_name":"method_list.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"13832156","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python2.7/site-packages/nsnitro/nsresources/nscsvserverstat.py\n# Compiled at: 2015-12-01 16:20:42\nfrom nsbaseresource import NSBaseResource\n\nclass NSCSVServerStat(NSBaseResource):\n\n def __init__(self, json_data=None):\n super(NSCSVServerStat, self).__init__()\n self.options = {'name': '', \n 'clearstats': '', \n 'establishedconn': '', \n 'primaryipaddress': '', \n 'primaryport': '', \n 'type': '', \n 'state': '', \n 'tothits': '', \n 'hitsrate': '', \n 'totalrequests': '', \n 'requestsrate': '', \n 'totalresponses': '', \n 'responsesrate': '', \n 'totalrequestbytes': '', \n 'requestbytesrate': '', \n 'totalresponsebytes': '', \n 'responsebytesrate': '', \n 'totalpktsrecvd': '', \n 'pktsrecvdrate': '', \n 'totalpktssent': '', \n 'pktssentrate': '', \n 'curclntconnections': '', \n 'cursrvrconnections': '', \n 'sothreshold': '', \n 'totspillovers': '', \n 'labelledconn': '', \n 'pushlabel': '', \n 'deferredreq': '', \n 'deferredreqrate': '', \n 'invalidrequestresponse': '', \n 'invalidrequestresponsedropped': ''}\n self.resourcetype = NSCSVServerStat.get_resourcetype()\n if json_data is not None:\n for key in json_data.keys():\n if self.options.has_key(key):\n self.options[key] = json_data[key]\n\n return\n\n @staticmethod\n def get_resourcetype():\n return 'csvserver'\n\n def set_name(self, name):\n self.options['name'] = name\n\n def get_name(self):\n return self.options['name']\n\n def get_state(self):\n return self.options['state']\n\n def get_primaryipaddress(self):\n return self.options['primaryipaddress']\n\n @staticmethod\n def get(nitro, csvserver):\n __csvs = NSCSVServerStat()\n __csvs.set_name(csvserver.get_name())\n __csvs.get_resource(nitro, urltype='stat')\n return __csvs\n\n @staticmethod\n def get_all(nitro):\n __url = nitro.get_url('stat') + NSCSVServerStat.get_resourcetype()\n __json_csvs = nitro.get(__url).get_response_field(NSCSVServerStat.get_resourcetype())\n __csvs = []\n for __json_vs in __json_csvs:\n __csvs.append(NSCSVServerStat(__json_vs))\n\n return __csvs","sub_path":"pycfiles/nsnitro-1.0.35.macosx-10.10-x86_64.tar/nscsvserverstat.py","file_name":"nscsvserverstat.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"452717501","text":"\"\"\"Remove OCCAS Installations\"\"\"\n\nimport logging\nimport functions\nfrom rda_base import cluster\nfrom rda_base import util\nimport activate\nimport adminserver\nimport managedserver\n\n\ndef deactivate_standalone(dp):\n \"\"\"function\"\"\"\n adminserver.stop([dp])\n\n server = activate.define_standalone(dp)\n server.deactivate()\n\n\ndef deactivate_adminserver(dp, clean):\n \"\"\"function\"\"\"\n functions.uninstall_adminserver_service()\n adminserver.stop()\n if clean:\n pass\n\n server = activate.define_adminserver(dp)\n server.deactivate()\n\n\ndef deactivate_managedserver(dp, clean):\n \"\"\"function\"\"\"\n managedserver.stop()\n if clean:\n pass\n\n server = activate.define_managedserver(dp)\n if clean:\n server.deactivate_and_clean()\n else:\n server.deactivate()\n\n\nif __name__ == '__main__':\n functions.check_user_is_occas()\n (verbose, server_type, dp_name, _, option_clean) = activate.parse_options()\n if verbose:\n util.init_log(filename='/var/log/occas/occas_config.log',\n format_in_console='[%(levelname)s] [%(funcName)s] %(message)s',\n level_in_console=logging.DEBUG)\n else:\n util.init_log(filename='/var/log/occas/occas_config.log',\n format_in_console='[%(levelname)s] %(message)s',\n level_in_console=logging.INFO)\n current_nodename = cluster.current_nodename()\n logging.info('Deactivate OCCAS {0} on node {1}'.format(server_type, current_nodename))\n\n if server_type == 'standalone':\n deactivate_standalone(dp_name)\n elif server_type == 'clusteradmin':\n deactivate_adminserver(dp_name, option_clean)\n elif server_type == 'clustermanaged':\n deactivate_managedserver(dp_name, option_clean)\n else:\n raise RuntimeError('unknown server type: {0}'.format(server_type))\n\n logging.info('Deactivate OCCAS {0} on node {1} succeed!'.format(server_type, current_nodename))\n","sub_path":"occas-config/src/main/python/deactivate.py","file_name":"deactivate.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41787181","text":"from toee import *\nfrom utilities import *\nfrom combat_standard_routines import *\n\n\ndef san_insert_item( attachee, triggerer ):\n\tdone = attachee.obj_get_int( obj_f_weapon_pad_i_1 )\n\tif (triggerer.type == obj_t_pc or triggerer.type == obj_t_npc) and (triggerer.has_feat(feat_far_shot)):\n\t\tif done == 1:\n\t\t\treturn RUN_DEFAULT\n\t\telse:\n\t\t\tcurr = attachee.obj_get_int( obj_f_weapon_range )\n\t\t\tcurr = curr * 1.5\n\t\t\tattachee.obj_set_int( obj_f_weapon_range, curr )\n\t\t\tattachee.obj_set_int( obj_f_weapon_pad_i_1, 1 )\n\t\t\tgame.sound(3013,1)\n\telse:\n\t\tif done == 1:\n\t\t\tcurr = attachee.obj_get_int( obj_f_weapon_range )\n\t\t\tcurr = curr * 2/3\n\t\t\tattachee.obj_set_int( obj_f_weapon_range, curr )\n\t\t\tattachee.obj_set_int( obj_f_weapon_pad_i_1, 0 )\n\t\t\tgame.sound(3013,1)\n\treturn RUN_DEFAULT\n\n## done = 0 when in the hands of someone without far_shot, 1 when in the hands of someone with the feat","sub_path":"tpdatasrc/co8fixes/scr/py00282Ranged_Ammo.py","file_name":"py00282Ranged_Ammo.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"647538407","text":"# credit: the code below is modified from https://github.com/m-hahn/tabula-rasa-rnns\nimport logging\n\nimport torch\n\ncuda = torch.cuda.is_available()\n\n# define vocabulary\nthai_chars = 'กขฃคฅฆงจฉชซฌญฐฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืุูเแโใไๅๆ็่้๊๋์ํ'\nchars = thai_chars + \".\"\nitos = [''] + [''] + [''] + list(chars)\nstoi = {v: k for k, v in enumerate(itos)}\n\n\n# create batches\ndef _prepareDatasetChunks(args, data):\n count = 0\n logging.info(\"Prepare chunks\")\n numerified = []\n for chunk in data:\n for char in chunk:\n if char == \" \" or char == \"\":\n continue\n count += 1\n numerified.append(stoi[char] if char in stoi else 2)\n\n cutoff = int(len(numerified) / (args.batchSize * args.sequence_length)) \\\n * (args.batchSize * args.sequence_length)\n\n numerifiedCurrent = numerified[:cutoff]\n numerified = numerified[cutoff:]\n if cuda:\n numerifiedCurrent = torch.LongTensor(numerifiedCurrent) \\\n .view(args.batchSize, -1, args.sequence_length) \\\n .transpose(0, 1).transpose(1, 2).cuda()\n else:\n numerifiedCurrent = torch.LongTensor(numerifiedCurrent) \\\n .view(args.batchSize, -1, args.sequence_length) \\\n .transpose(0, 1).transpose(1, 2)\n\n numberOfSequences = numerifiedCurrent.size()[0]\n for i in range(numberOfSequences):\n yield numerifiedCurrent[i]\n","sub_path":"lmcut/data_LM.py","file_name":"data_LM.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274422342","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nclass Card:\n numberOfCards = 0\n def __init__(self, rank=None, suit=None):\n if not suit or rank == None:\n raise ValueError(\"error: suit and rank are needed\")\n self._suit = suit\n # possible ranks [0,1,2,3,4,5,6,7,8,9, 10,11,12]\n # ---> repr [A,2,3,4,5,6,7,8,9,10, J, Q, K]\n self._rank = rank\n self._rank_names = [\"A\",2,3,4,5,6,7,8,9,10,\"J\",\"Q\",\"K\",\"A\"]\n Card.numberOfCards += 1\n def __del__(self):\n Card.numberOfCards -= 1\n def get_rank(self):\n return self._rank\n def get_suit(self):\n return self._suit\n def _less_than(self, c1, c2):\n rc1 = c1.get_rank()\n rc2 = c2.get_rank()\n # zero is the Ace\n if rc1 == 0:\n print(\"is an ace\")\n rc1 = 13\n if rc2 == 0:\n rc2 = 13\n# if type(rc1) == str and rc1 in \"JQKA\":\n# rc1 = 9 + \"JQKA\".index(rc1)\n# if type(rc2) == str and rc2 in \"JQKA\":\n# rc2 = 9 + \"JQKA\".index(rc2)\n return rc1 < rc2\n def __repr__(self):\n return str(self._suit) + str(self._rank_names[self._rank])\n def __lt__(self, c2):\n return self._less_than(self,c2)\n def __gt__(self, c2):\n return self._less_than(c2, self)\n def __eq__(self, c2):\n return self._rank == c2.get_rank()\n def __ne__(self, c2):\n return self._rank != c2.get_rank()\n def __mod__(self, c2):\n return self._suit == c2.get_suit()\n def __neg__(self):\n r = self._rank\n if r == 0:\n r = 13\n return -r\n\n\n# In[2]:\n\n\nclass Hand:\n def __init__(self, cards):\n self.cards = cards\n\n\n# In[3]:\n\n\nclass PokerHand(Hand):\n def __gt__(self, other_hand):\n if len(self.cards) != len(other_hand.cards):\n raise ValueError(\"Hands need to have same number of cards!\")\n if max(self.cards) > max(other_hand.cards):\n return True\n elif max(self.cards) == max(other_hand.cards):\n h1 = sorted(self.cards)\n h2 = sorted(other_hand.cards)\n h1_max = False\n for card1, card2 in zip(h1, h2):\n if card1 > card2:\n h1_max = True\n break\n elif card1 == card2:\n continue\n else: # card1 < card2:\n h1_max = False\n break\n return h1_max\n else:\n return False\n def __eq__(self, other_hand):\n pass\n\n\n# In[4]:\n\n\nclass Deck:\n \"\"\"standard French Deck (52 cards)\"\"\"\n def __init__(self):\n self.suits = [\"H\" , \"S\" , \"D\", \"C\"]\n self.ranks = [x for x in range(0,13)] #[\"A\",2,3,4,5,6,7,8,9,10,\"J\",\"C\",\"Q\",\"K\"]\n self.cards = [Card(r,s) for s in self.suits for r in self.ranks]\n\n\n# In[5]:\n\n\n\nd = Deck()\nprint(len(d.cards))\nprint(d.cards[-5:])\n\n\n# In[6]:\n\n\nc1 = Card(3,\"H\")\nc2 = Card(3,\"H\")\nc2 > c1\n\n\n# In[7]:\n\n\nc2 == c1\n\n\n# In[8]:\n\n\nh1 = PokerHand([Card(0,\"H\"), Card(10,\"H\")])\nh2= PokerHand([Card(3,\"C\"), Card(4,\"C\")])\n\n\n# In[9]:\n\n\nh1 > h2\n\n\n# In[10]:\n\n\nh2 > h1\n\n\n# In[11]:\n\n\nc1.numberOfCards\n\n\n# In[12]:\n\n\nsorted(h1.cards,key=lambda x: -x)\n\n\n# In[13]:\n\n\nh1.cards[0]._rank\n\n\n# In[14]:\n\n\nfrom random import shuffle\nshuffle(d.cards)\nprint(d.cards)\n\n\n# In[29]:\n\n\n# abgeleitet von Card\nclass FancyCard(Card):\n def __init__(self, rank = None, suit= None):\n super().__init__(rank=rank, suit=suit)\n def __repr__(self):\n spades = '🂡🂢🂣🂤🂥🂦🂧🂨🂩🂪🂫🂭🂮'\n hearts = '🂱🂲🂳🂴🂵🂶🂷🂸🂹🂺🂻🂽🂾'\n diamonds = '🃁🃂🃃🃄🃅🃆🃇🃈🃉🃊🃋🃍🃎'\n clubs = '🃑🃒🃓🃔🃕🃖🃗🃘🃙🃚🃛🃝🃞'\n cards = {'S': spades, 'H': hearts, 'C': clubs, 'D': diamonds}\n return cards[self._suit][self._rank]\n def __del__(self):\n print(\"bye bye\")\n\n\n# In[30]:\n\n\nc = FancyCard(rank=0, suit='H')\n\n\n# In[31]:\n\n\nc\n\n\n# In[61]:\n\n\nclass FancyDeck(Deck):\n \"\"\"fancy French Deck (52 cards)\"\"\"\n def __init__(self):\n super().__init__()\n self.cards = [FancyCard(r,s) for s in self.suits for r in self.ranks]\n\n\n# In[62]:\n\n\nfd = FancyDeck()\n\n\n# In[63]:\n\n\nshuffle(fd.cards)\n\n\n# In[64]:\n\n\nprint(fd.cards)\n\n","sub_path":"bsp/06/Cards_fixed.py","file_name":"Cards_fixed.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"202742178","text":"from __future__ import unicode_literals\n\nimport logging\n\nfrom api.exceptions import (\n BadPickException,\n DuplicateMemberException,\n InvalidMemberException,\n TooFewMembersException,\n TooManyMembersException,\n)\nfrom datetime import datetime\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save\nfrom random import shuffle\nfrom rest_framework.authtoken.models import Token\n\nlogger = logging.getLogger('nba-logger')\n\nSUPPORTED_POOL_SIZES = (2, 3, 5, 6)\n\n\n# This code is triggered whenever a new user has been created and saved to the database\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n\n\nclass Pool(models.Model):\n \"\"\"\n `Pool` has many `User`s through `Membership`. User is part of many `Pool`s\n through the `Membership`.\n \"\"\"\n name = models.CharField(max_length=128)\n max_size = models.PositiveSmallIntegerField(default=5)\n members = models.ManyToManyField(User, through='Membership')\n\n def add_member(self, user):\n \"\"\"\n Adds a new member to the Pool. If, after adding the new member, we're at\n `self.max_size`, then kicks off the Pool.\n \"\"\"\n # 0. Verify that we can add another unique member.\n original_pool_size = len(self.members.all())\n if original_pool_size >= self.max_size:\n raise TooManyMembersException(\"Cannot add any more members to the Pool.\")\n\n if user in self.members.all():\n raise DuplicateMemberException(\"Cannot add the same member to the Pool twice.\")\n\n # 1. Add the new member to the Pool.\n curr_time = datetime.now()\n Membership.objects.create(pool=self, user=user, date_joined=curr_time)\n\n # 2. If we now have enough members in the pool to begin, compute the\n # draft order and draft status.\n new_members = self.members.all()\n assert len(new_members) == original_pool_size + 1\n if len(new_members) == self.max_size:\n self.begin_draft()\n\n return self\n\n def remove_member(self, user):\n \"\"\"\n Removes the user from the membership list of the Pool\n \"\"\"\n if user not in self.members.all():\n raise InvalidMemberException(\"Cannot remove a member that isn't part of the pool\")\n\n m = Membership.objects.get(user=user, pool=self)\n m.delete()\n\n @staticmethod\n def compute_draft_order(user_ids):\n \"\"\"\n Given a list of `user_ids`, randomly shuffles the `user_ids` and returns\n them in a draft order.\n\n Args:\n user_ids(iterable): A list of `user_ids` of the members of the pool.\n\n Returns:\n user_ids_by_draft_order(dict): Map from draft_order -> user_id.\n E.g. {pick_1-> user_1234}\n\n Raises:\n AssertionError: If `user_ids` is the incorrect length.\n \"\"\"\n # 0. De-dupe the user_ids and sanity check.\n pool_size = len(set(user_ids))\n assert pool_size in SUPPORTED_POOL_SIZES\n\n # 1. Shuffle the user_ids randomly.\n random_user_ids = list(set(user_ids))\n shuffle(random_user_ids)\n\n logger.info('random user_ids: %s' % random_user_ids)\n\n # 2. Map from size of pool to the order.\n draft_order_by_pool_size = {\n 2: [1, 2, 2, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 2, 1],\n 3: [1, 2, 3, 3, 2, 1, 2, 1, 3, 3, 2, 1, 1, 2, 3, 3, 2, 1, 1, 2, 3, 3, 2, 1, 2, 1, 3, 3, 2, 1],\n 5: [1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 1, 2, 3, 5, 4, 5, 4, 3, 2, 1, 4, 2, 3, 1, 5, 5, 4, 3, 2, 1],\n 6: [1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1, 5, 2, 4, 3, 6, 1, 5, 6, 4, 2, 3, 1, 6, 5, 4, 3, 2, 1],\n }\n\n # 3. Grab the relevant draft order and populate the dict.\n draft_order = draft_order_by_pool_size[pool_size]\n logger.info('draft order: %s' % draft_order)\n user_ids_by_draft_order = {}\n for pick_index, user_index in enumerate(draft_order):\n user_ids_by_draft_order[pick_index + 1] = random_user_ids[user_index - 1]\n\n logger.info('user_ids_by_draft_order: %s' % user_ids_by_draft_order)\n\n return user_ids_by_draft_order\n\n def begin_draft(self):\n \"\"\"\n Verifies that we have enough members to start the pool and then creates\n empty DraftPicks for each member of the Pool.\n\n Returns:\n Nothing but creates a series of DraftPicks for each member.\n\n Raises:\n AssertionError: If we cannot begin the draft yet.\n \"\"\"\n members = self.members.all()\n if len(members) != self.max_size:\n raise TooFewMembersException(\"Not enough members to start the pool!\")\n\n users_by_id = {member.id: member for member in members}\n user_ids_by_draft_order = Pool.compute_draft_order(users_by_id.keys())\n\n logger.info('user_ids_by_draft_order: %s' % user_ids_by_draft_order)\n for (pick, user_id) in user_ids_by_draft_order.iteritems():\n user = users_by_id[user_id]\n DraftPick.objects.create(pool=self, user=user, draft_pick_number=pick)\n\n def make_draft_pick(self, user, team):\n # 0. Ensure that only the next user up can make a pick.\n pick = DraftPick.objects.filter(pool=self, team=None).order_by('draft_pick_number')[0]\n if pick.user != user:\n raise BadPickException(\"Not user: %s's turn to pick!\" % user.username)\n\n # 1. Ensure that the user doesn't try to pick a team that has already been\n # chosen.\n dps = DraftPick.objects.filter(pool=self).exclude(team__isnull=True).order_by('draft_pick_number')\n teams_picked = [dp.team for dp in dps]\n if team in teams_picked:\n raise BadPickException(\"Can't pick a team %s that has already been chosen\" % team.team_full_name)\n\n pick.team = team\n pick.save()\n\n return self\n\n def __unicode__(self):\n return '' % (self.name, self.max_size)\n\n\nclass Membership(models.Model):\n \"\"\"\n `Membership` defines the relation between `User` and `Pool`.\n A `User` joins a `Pool` through their membership.\n \"\"\"\n pool = models.ForeignKey(Pool, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n date_joined = models.DateField()\n\n\nclass Team(models.Model):\n \"\"\"\n Autopopulated from `nba_teams.yaml`.\n \"\"\"\n league_short_code = models.CharField(max_length=256)\n league_full_name = models.CharField(max_length=256)\n\n team_short_code = models.CharField(max_length=256)\n team_full_name = models.CharField(max_length=256)\n\n def __unicode__(self):\n return '' % (self.league_short_code, self.team_full_name)\n\n\nclass DraftPick(models.Model):\n pool = models.ForeignKey(Pool, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True, null=True)\n draft_pick_number = models.IntegerField(default=1)\n","sub_path":"api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"75157717","text":"# encoding: UTF-8\n\nimport pygame\n\n# Dimensiones de la pantalla\nANCHO = 600\nALTO = 600\n# Colores\nBLANCO = (255,255,255) # R,G,B en el rango [0,255]\nVERDE_BANDERA = (0, 122, 0)\nROJO = (255, 0, 0)\nNEGRO=(0,0,0)\n\ndef interpretar(archivo,ventana):\n for linea in open(archivo):\n datos=linea.lower().split()\n if datos[0]==\"r\":\n x=int(datos[1])\n y=int(datos[2])\n ancho=int(datos[3])\n alto=int(datos[4])\n pygame.draw.rect(ventana, NEGRO,(x,y,ancho,alto),1)\n elif datos[0]==\"c\":\n x=int(datos[1])\n y=int(datos[2])\n r=int(datos[3])\n pygame.draw.circle(ventana,NEGRO,(x,y),r,1)\n\n\ndef dibujar(archivo):\n # Ejemplo del uso de pygame\n pygame.init() # Inicializa pygame\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana de dibujo\n reloj = pygame.time.Clock() # Para limitar los fps\n termina = False # Bandera para saber si termina la ejecución\n\n while not termina:\n # Procesa los eventos que recibe\n for evento in pygame.event.get():\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\n termina = True\n\n # Borrar pantalla\n ventana.fill(BLANCO)\n\n interpretar(archivo,ventana)\n\n pygame.display.flip() # Actualiza trazos\n reloj.tick(40) # 40 fps\n\n pygame.quit() # termina pygame\n\n\ndef main():\n archivoMain=\"prueba.pic\"\n dibujar(archivoMain)\n\nmain()\n","sub_path":"pygameArchivos.py","file_name":"pygameArchivos.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"619137056","text":"\"\"\"\nUtils class for handling file uploads, time and other miscellaneous tasks.\n\"\"\"\n\nimport os\n\nimport ffmpeg_streaming\nfrom ffmpeg_streaming import Formats\nfrom werkzeug.utils import secure_filename\n\nimport constants\n\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'mp4'}\n\n\"\"\"\nVerifies for allowed extensions.\n\"\"\"\n\n\ndef allowed_file(filename):\n return '.' in filename and get_file_extension(filename=filename) in ALLOWED_EXTENSIONS\n\n\ndef get_file_extension(filename):\n return filename.rsplit('.', 1)[1].lower()\n\"\"\"\nUpload file to specific path. For videos, it's /uploads/videos//file.mp4.\nFor images, it's /uploads/images//image.jpg.\n\"\"\"\n\n\ndef upload_file(news, file, upload_type):\n if file is None:\n return ''\n if file and allowed_file(filename=file.filename):\n path = 'uploads/{}/{}/'.format(upload_type, news.id)\n filename = secure_filename(file.filename)\n if not os.path.exists(path):\n os.makedirs(path)\n file_path = os.path.join(path, filename)\n file.save(file_path)\n if get_file_extension(filename=file.filename) == 'mp4':\n video = ffmpeg_streaming.input(file_path)\n dash = video.dash(Formats.h264())\n dash.auto_generate_representations()\n video_name_with_ext = '{}.{}'.format(file.filename.rsplit('.', 1)[0], 'mpd')\n dash.output(path + '/{}'.format(video_name_with_ext))\n os.remove(path=file_path)\n return 'https://thewitness.wielabs.com/uploads/{}/{}/{}'.format(upload_type, news.id, video_name_with_ext)\n return 'https://thewitness.wielabs.com/uploads/{}/{}/{}'.format(upload_type, news.id, filename)\n return ''\n\n\n\"\"\"\nGet formatted time of current instant. \nEx. 25 Dec, 2020 • 09:00 AM\n\"\"\"\n\n\ndef get_formatted_time():\n from datetime import datetime\n timestamp = datetime.now()\n return '{} {}, {} • {}:{} {}'.format(timestamp.strftime(\"%d\"), timestamp.strftime(\"%b\"), timestamp.strftime(\"%Y\"),\n timestamp.strftime(\"%I\"), timestamp.strftime(\"%M\"), timestamp.strftime(\"%p\"))\n\n\ndef get_flag_url(region):\n return constants.BASE_FLAG_URL.format(region.lower())\n","sub_path":"api/TheWitnessAPI/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80668008","text":"'''\n스파이들은 매일 다른 옷을 조합하여 입어 자신을 위장합니다.\n\n예를 들어 스파이가 가진 옷이 아래와 같고\n오늘 스파이가 동그란 안경, 긴 코트, 파란색 티셔츠를 입었다면\n다음날은 청바지를 추가로 입거나 동그란 안경 대신 검정 선글라스를 착용하거나 해야 합니다.\n\n\n종류\t이름\n얼굴\t동그란 안경, 검정 선글라스\n상의\t파란색 티셔츠\n하의\t청바지\n겉옷\t긴 코트\n스파이가 가진 의상들이 담긴 2차원 배열 clothes가 주어질 때 서로 다른 옷의 조합의 수를 return 하도록 solution 함수를 작성해주세요.\n\n제한사항\nclothes의 각 행은 [의상의 이름, 의상의 종류]로 이루어져 있습니다.\n스파이가 가진 의상의 수는 1개 이상 30개 이하입니다.\n같은 이름을 가진 의상은 존재하지 않습니다.\nclothes의 모든 원소는 문자열로 이루어져 있습니다.\n모든 문자열의 길이는 1 이상 20 이하인 자연수이고 알파벳 소문자 또는 '_' 로만 이루어져 있습니다.\n스파이는 하루에 최소 한 개의 의상은 입습니다.\n\nhttps://programmers.co.kr/learn/courses/30/lessons/42578\n\n'''\n\n\n'''\n종류별 갯수 파악.\n그리고 경우의 수 계산\n-각자1\n-조합()\n\n'''\n\nt1 = [[\"yellow_hat\", \"headgear\"], [\"blue_sunglasses\", \"eyewear\"], [\"green_turban\", \"headgear\"]] #return 5\nt2 = [[\"crow_mask\", \"face\"], [\"blue_sunglasses\", \"face\"], [\"smoky_makeup\", \"face\"]] # 3\n\ndef solution(clothes):\n ### 종류별로 갯수 계\n D = {}\n for c in clothes:\n if c[1] in D:\n D[c[1]] += 1\n else:\n D[c[1]] = 1\n c = 1\n for d in D.values():\n c *=d+1 # 종류별로 안 입는 것도 갯수\n return c - 1 # 전부다 안 입는 건 안됨.\n\n\nr1 = solution(t1) #5\nr2 = solution(t2)\nprint(r1) # 5\nprint(r2) # 3\n\n","sub_path":"FLIP-CODING/03-HASH/Q3.py","file_name":"Q3.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191220785","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n def __str__(self):\n result = \"({})\".format(self.val)\n if self.left != None :\n result += \"-L[{}]\".format(self.left)\n if self.right != None :\n result += \"-R[{}]\".format(self.right)\n return result\n\nclass Solution:\n \n def searchBST(self, root: TreeNode, val: int) -> TreeNode:\n if root.val == val :\n return root\n if root.left != None :\n result = self.searchBST(root.left, val)\n if result != None :\n return result\n if root.right != None :\n result = self.searchBST(root.right, val)\n if result != None :\n return result\n return None\n\nif __name__ == \"__main__\":\n sol = Solution()\n root = TreeNode(18)\n \n root.left = TreeNode(2)\n root.right = TreeNode(22)\n root.right.right = TreeNode(63)\n root.right.right.right = TreeNode(84)\n\n # [18,2,22,null,null,null,63,null,84,null,null]\n\n print(sol.searchBST(root, 63))","sub_path":"python/search_in_bst.py","file_name":"search_in_bst.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"561919494","text":"# encoding: utf-8\n\n\"\"\"\n@version: 1.0\n@author: LeungJain\n@time: 2018/2/26 14:50\n\"\"\"\nimport threading\nimport time\nimport datetime as dt\nimport json\nimport re\nfrom timeit import timeit\nimport pandas as pd\nimport pytz\nfrom Calf import project_dir\nfrom Calf.exception import ExceptionInfo, WarningMessage\nfrom Calf.utils import trading, fontcolor, sound_notice\nfrom Calf import KlineData as kd\nfrom Calf import CalfDateTime\nfrom Calf import ModelAction\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom apscheduler.schedulers.background import BackgroundScheduler\n# from Calf.sys_config import config as cf\n\n\nclass ModelRun:\n \"\"\"\n 实时任务的运行是由两个类型的事件驱动的:\n\n 1.由使用Calf模型的开发者指定时间点的集合,时钟走到相应的时点就运行客服函数。\n\n 2.由K线数据更新这一事件引起的,这种类型的任务我们要求开发者在ModelAction的\n 子类申明klines,并将一个list赋给klines,这个list是一个形如\n ['kline_min30','kline_min60']的列表,这意味着当kline_min30或kline_60\n 这两个表的数据发生了更新将会驱动ModelRun去执行ModelAction的real函数,\n 这里所谓的表的数据发生更新通常是指这种情况:比如在中国A股对于30分钟这一周期来说,\n 上午10点钟到了,所有股票10点钟kline_min30的那更K线便产生了,这可能对那些\n 依赖于kline_min30的模型而言,就需要去计算新的信号了。其他周期也是相同的道理。\n 当然你也可以有其他的定义,总之是因为k线数据发生了更新,这种更新被记录到了\n 相应的表中,ModelRun读到这种更新记录后就会执行ModelAction的real函数。\n 有关K线更新的日志的相关信息你可以在KlineData中找到.\n \"\"\"\n @classmethod\n def open_kline_update_log(cls):\n try:\n with open(project_dir + '/Calf/kline_update_log.json', encoding='utf-8') as file:\n content = json.load(file)\n return content\n except Exception as e:\n ExceptionInfo(e)\n return {}\n\n @classmethod\n def set_kline_update_log(cls, self, **kw):\n try:\n keys = self.keys()\n for k, v in zip(kw.keys(), kw.values()):\n if k in keys:\n self[k] = v\n else:\n print(WarningMessage('not find this key in original file'))\n self['datetime'] = dt.datetime.strftime(dt.datetime.today(), '%Y-%m-%d %H:%M:%S')\n with open(project_dir + '/Calf/kline_update_log.json', 'w') as file:\n file.write(json.dumps(self))\n return self\n except Exception as e:\n ExceptionInfo(e)\n return self\n\n @classmethod\n def KScheduler(cls, action, tz=None, deep_sleep=list()):\n \"\"\"\n 适用于A股的信号采集实时任务,适用于跨时区任务\n :param deep_sleep:\n :param action: 模型的运行管理对象\n :return:\n \"\"\"\n if not isinstance(action, type(ModelAction)):\n raise TypeError('Object action must be a subclass of ModelAction')\n if tz is not None:\n if tz not in pytz.all_timezones:\n raise ValueError('this tz: %s not in pytz time zones' % tz)\n else:\n tz = pytz.timezone(tz)\n profit_probe_period = dt.timedelta(minutes=1)\n profit_probe_next = dt.datetime.now() if tz is None else dt.datetime.now(tz=tz).replace(tzinfo=None)\n _f = False # 记录当天是否收盘\n klines = action.klines # 需要跟踪的bar周期\n _id = cls.open_kline_update_log() # 记录bar更新\n while 1:\n try:\n crt = dt.datetime.now() if tz is None else dt.datetime.now(tz=tz).replace(tzinfo=None)\n if not action.is_trade_day(dt.datetime(crt.year, crt.month, crt.day)):\n print('{0} today is not in business'.format(crt))\n time.sleep(60 * 60 * 2) # sleep two hours\n continue\n if action.trade_day_end(crt) and _f:\n print(fontcolor.F_GREEN + '-' * 80)\n print('# %s Today Overview #' % action.name)\n print('Signal:')\n action.signals_summary()\n print('Order:')\n action.orders_summary()\n print(fontcolor.F_GREEN + '-' * 80 + fontcolor.END)\n sound_notice('close.wav').start()\n _f = False\n # open_am <= crt <= close_am or open_pm <= crt < close_pm\n if action.trade_date(crt):\n # 交易日盘中\n s_d = crt - dt.timedelta(minutes=3)\n e_d = crt + dt.timedelta(minutes=3)\n log = kd.read_log(start_date=s_d, end_date=e_d, status=200)\n if len(log):\n log['_id'] = log['_id'].astype('str')\n for i, r in log.iterrows():\n if r.kline in klines and r['_id'] != _id[r.kline]:\n print('this kline %s find update' % r.kline)\n action.real(r.kline)\n print(r.kline + ' id update:' + _id[r.kline] + '-->' + r['_id'])\n _id[r.kline] = r['_id']\n cls.set_kline_update_log(_id)\n\n if profit_probe_next <= crt:\n print('profit probing date:{0}'.format(crt))\n action.probing()\n profit_probe_next += profit_probe_period\n _f = True\n time.sleep(5)\n else:\n print('{0} this datetime is not in business'.format(crt))\n profit_probe_next = crt\n _f = False\n sleep = 60 * 5 if crt.hour in deep_sleep else 60 * 30\n time.sleep(sleep)\n\n except Exception as e:\n ExceptionInfo(e)\n\n @classmethod\n def forexrun(cls, drive_fun, real_fun, klines):\n \"\"\"\n 适用于外汇市场的实时任务。由于外汇交易是24小时全体候交易,但周末\n 一般会休市,以及其他的特殊日期。在中国外汇程序化交易必须通过做市商\n 的交易平台进行。Calf裁剪了一些对外汇的功能支持,包括实时收益监控,\n 收盘报告。forexrun仅提供了模型信号实时计算的功能。\n forexrun提供了基于K线跟踪的实时信号的采集驱动,包括min5、min15、\n min30、min60、d1\n :param klines:\n :param real_fun: 实时任务\n :param drive_fun: 一个用于判断是否为交易日的函数,\n :return:\n \"\"\"\n period_m5 = dt.timedelta(minutes=5)\n period_m15 = dt.timedelta(minutes=15)\n period_m30 = dt.timedelta(minutes=30)\n period_h1 = dt.timedelta(hours=1)\n period_d1 = dt.timedelta(days=1)\n now = dt.datetime.now()\n next_m5 = now\n next_m15 = now\n next_m30 = now\n next_h1 = now\n next_d1 = now\n sup_klines = ['forex_min5', 'forex_min15', 'forex_min30', 'forex_min60', 'forex_day1']\n if set(klines) <= set(sup_klines):\n pass\n else:\n raise Exception('The invalid kernel element')\n '''控制在恰当的时间进入系统'''\n tdy = dt.datetime(now.year, now.month, now.day)\n for k in klines:\n if k == 'forex_min5':\n ntm = (now.minute // 5) * 5 + 6\n next_m5 = tdy + dt.timedelta(hours=now.hour, minutes=ntm, seconds=30)\n elif k == 'forex_min15':\n ntm = (now.minute // 15) * 15 + 16\n next_m15 = tdy + dt.timedelta(hours=now.hour, minutes=ntm, seconds=30)\n elif k == 'forex_min30':\n ntm = (now.minute // 30) * 30 + 31\n next_m30 = tdy + dt.timedelta(hours=now.hour, minutes=ntm, seconds=30)\n elif k == 'forex_min60':\n next_h1 = now if now.minute <= 1 else tdy + dt.timedelta(hours=now.hour + 1, minutes=1, seconds=30)\n elif k == 'forex_day1':\n next_d1 = tdy if now.minute <= 1 else tdy + dt.timedelta(days=1, minutes=1, seconds=30)\n else:\n raise Exception('The invalid kernel element')\n print(fontcolor.F_GREEN + '-' * 80 + fontcolor.END)\n print(fontcolor.F_GREEN + 'Calf:Successful entry forex real task', fontcolor.END)\n print(fontcolor.F_GREEN + '-' * 80 + fontcolor.END)\n while 1:\n try:\n current = dt.datetime.now()\n if drive_fun():\n if next_m5 <= current and 'forex_min5' in klines:\n # print('min5:', next_m5)\n real_fun('forex_min5')\n next_m5 += period_m5\n print('Task for forex_min5 have completed on {0} and next start up will be {1}'\n .format(current, next_m5))\n if next_m15 <= current and 'forex_min15' in klines:\n # print('min5:', next_m15)\n real_fun('forex_min15')\n next_m15 += period_m15\n print('Task for forex_min15 have completed on {0} and next start up will be {1}'\n .format(current, next_m15))\n if next_m30 < current and 'forex_min30' in klines:\n print('min30:', next_m30)\n real_fun('forex_min30')\n next_m30 += period_m30\n print('Task for forex_min30 have completed on {0} and next start up will be {1}'\n .format(current, next_m30))\n if next_h1 < current and 'forex_min60' in klines:\n print('h1:', next_h1)\n real_fun('forex_min60')\n next_h1 += period_h1\n print('Task for forex_min60 have completed on {0} and next start up will be {1}'\n .format(current, next_h1))\n if next_d1 < current and 'forex_day1' in klines:\n real_fun('forex_day1')\n next_d1 += period_d1\n print('Task for forex_day1 have completed on {0} and next start up will be {1}'\n .format(current, next_d1))\n time.sleep(60)\n else:\n print(fontcolor.F_RED + '-' * 80 + fontcolor.END)\n print(fontcolor.F_RED + 'Note:Non-transaction time;Date:' + str(current), fontcolor.END)\n print(fontcolor.F_RED + '-' * 80 + fontcolor.END)\n time.sleep(60 * 60)\n except Exception as e:\n ExceptionInfo(e)\n\n @classmethod\n def timing(cls, func, times):\n \"\"\"\n 定时任务.\n 在交易日执行定时任务\n :param times:\n :param func:形如[[10, 0], [10, 30], [11, 0], [11, 30], [13, 30], [14, 0], [14, 30], [15, 0]]\n 这会使得func在每个交易日的10点、10点30分···执行\n :return:\n \"\"\"\n try:\n def merge(h, m):\n return pd.Timedelta(hours=h, minutes=m)\n\n times['time'] = times.apply(lambda r: merge(r['hour'], r['minute']), axis=1)\n times['log'] = pd.datetime(2018, 1, 1)\n\n def tim(tms):\n while 1:\n try:\n crt = dt.datetime.now()\n if not trading.is_trade_day(crt):\n print('{0} today is not in business'.format(crt))\n time.sleep(60 * 60 * 2) # sleep two hours\n continue\n tms['date'] = pd.datetime(crt.year, crt.month, crt.day) + tms.time\n tm = tms[tms.hour == crt.hour]\n if len(tm):\n for i, r in tm.iterrows():\n if crt >= r.date != r.log:\n print('timing task run', r.date, r.log)\n func()\n tms.at[i, 'log'] = r.date\n pass\n time.sleep(60)\n else:\n time.sleep(60 * 60)\n pass\n except Exception as ep:\n ExceptionInfo(ep)\n\n t = threading.Thread(target=tim, args=(times,))\n t.start()\n except Exception as e:\n ExceptionInfo(e)\n\n @classmethod\n def rerun(cls, action, deep_sleep=list(), offset=None):\n \"\"\"\n 复盘演示\n :param action:\n :param deep_sleep:\n :param offset:\n :return:\n \"\"\"\n profit_probe_period = dt.timedelta(minutes=1)\n profit_probe_next = CalfDateTime.now(offset=offset)\n _f = False # 记录当天是否收盘\n klines = action.klines # 需要跟踪的bar周期\n _id = cls.open_kline_update_log() # 记录bar更新\n while 1:\n try:\n crt = CalfDateTime.now(offset=offset)\n if not trading.is_trade_day(dt.datetime(crt.year, crt.month, crt.day)):\n print('{0} today is not in business'.format(crt))\n time.sleep(60 * 60 * 2) # sleep two hours\n continue\n if action.trade_day_end(crt) and _f:\n print(fontcolor.F_GREEN + '-' * 80)\n print('# %s Today Overview #' % action.name)\n print('Signal:')\n action.signals_summary()\n print('Order:')\n action.orders_summary()\n print(fontcolor.F_GREEN + '-' * 80 + fontcolor.END)\n sound_notice('close.wav').start()\n _f = False\n # open_am <= crt <= close_am or open_pm <= crt < close_pm\n if action.trade_date(crt):\n # 交易日盘中\n s_d = crt - dt.timedelta(minutes=3)\n e_d = crt + dt.timedelta(minutes=3)\n log = kd.read_log(start_date=s_d, end_date=e_d, status=200)\n if len(log):\n log['_id'] = log['_id'].astype('str')\n for i, r in log.iterrows():\n if r.kline in klines and r['_id'] != _id[r.kline]:\n print('this kline %s find update' % r.kline)\n action.real(r.kline, start_time=crt)\n print(r.kline + ' id update:' + _id[r.kline] + '-->' + r['_id'])\n _id[r.kline] = r['_id']\n cls.set_kline_update_log(_id)\n\n if profit_probe_next <= crt:\n print('profit probing date:{0}'.format(crt))\n # action.probing()\n profit_probe_next += profit_probe_period\n _f = True\n time.sleep(5)\n else:\n print('{0} this datetime is not in business'.format(crt))\n profit_probe_next = crt\n _f = False\n # sleep = 60 * 30\n # if crt.hour == 9 or crt.hour == 12:\n # sleep = 60 * 5\n sleep = 60 * 5 if crt.hour in deep_sleep else 60 * 30\n time.sleep(sleep)\n\n except Exception as e:\n ExceptionInfo(e)\n\n @classmethod\n def DScheduler(cls, action, start_date=None, execute_date=None, end_date=None,\n execute_interval=3, tz=None, **kwargs):\n \"\"\"\n 一个依托于时间驱动的实时任务,action所���载的任务由相应的时间驱动,\n 这跟run方法由K线更新驱动不一样,时区功能未起作用\n :param action:\n :param start_date:like '09:30:00'\n :param execute_date:like '09:30:00-11:30:00' or '09:30:00-11:30:00 13:00:00-15:00:00'\n :param end_date:like '15:00:00'\n :param execute_interval:连续任务的执行时间间隔,以秒计\n :param tz:时区\n :return:\n \"\"\"\n fmt = '%Y-%m-%d %H:%M:%S'\n if start_date is not None:\n try:\n sdt = dt.datetime.strptime('2000-01-01 ' + start_date, fmt)\n except Exception:\n raise TypeError('this start_date param like a \"09:30:00\" string')\n if execute_date is not None:\n try:\n xdt = []\n dts = execute_date.split(' ')\n for et in dts:\n t = et.split('-')\n s = dt.datetime.strptime('2000-01-01 ' + t[0], fmt)\n e = dt.datetime.strptime('2000-01-01 ' + t[1], fmt)\n # if s > e:\n # 如果execute的start大于end说明是当天的end到第二天的start\n # raise TypeError('execute start datetime must less than end')\n xdt.append([s, e])\n del s, e, t\n del dts\n except Exception:\n raise TypeError('this start_date param like a \"09:30:00-11:30:00\" or'\n ' \"09:30:00-11:30:00 13:00:00-15:00:00\"')\n if end_date is not None:\n try:\n edt = dt.datetime.strptime('2000-01-01 ' + end_date, fmt)\n except Exception:\n raise TypeError('this start_date param like a \"15:30:00\" string')\n if tz is not None:\n if tz not in pytz.all_timezones:\n raise ValueError('Only timezones from the pytz library are supported')\n else:\n tz = pytz.timezone(tz)\n from apscheduler.triggers.date import DateTrigger\n from apscheduler.triggers.interval import IntervalTrigger\n from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor\n while 1:\n # scheduler = BlockingScheduler(daemonic=False)\n # crt = CalfDateTime.now(tz, offset)\n crt = dt.datetime.now() if tz is None else dt.datetime.now(tz=tz).replace(tzinfo=None)\n tdy = dt.datetime(crt.year, crt.month, crt.day)\n # 非交易日\n if not action.is_trade_day(tdy):\n print(fontcolor.F_RED + '-' * 80)\n print('Note:Non-transaction date;Datetime:' + str(crt))\n print('-' * 80 + fontcolor.END)\n delta = (tdy + dt.timedelta(days=1) - crt).seconds\n delta = 1 if delta < 1 else delta\n time.sleep(delta) # sleep to next day\n continue\n # 交易日\n else:\n try:\n from pytz import FixedOffset, utc\n nsds = list()\n executors = {'default': ThreadPoolExecutor(4),\n 'processpool': ProcessPoolExecutor(4)}\n job_defaults = {'coalesce': True,'max_instances': 1}\n scheduler = BackgroundScheduler(executors=executors,\n job_defaults=job_defaults,\n daemonic=False,\n timezone=tz)\n if start_date is not None:\n d = tdy + dt.timedelta(hours=sdt.hour, minutes=sdt.minute,\n seconds=sdt.second)\n nsds.append(d + dt.timedelta(days=1))\n def action_start(args):\n print(fontcolor.F_GREEN + '-' * 80)\n print('Calf-Note:start task running on ', dt.datetime.now(tz=tz))\n print('-' * 80 + fontcolor.END)\n try:\n action.start(args=args)\n except Exception as ep:\n ExceptionInfo(ep)\n scheduler.add_job(func=action_start, trigger=DateTrigger(d),\n id='action_start', args=[kwargs])\n if execute_date is not None:\n def action_execute(args):\n print(fontcolor.F_GREEN + '-' * 80)\n print('Calf-Note:execute task running on ', dt.datetime.now(tz=tz))\n print('-' * 80 + fontcolor.END)\n try:\n action.execute(args=args)\n except Exception as ep:\n ExceptionInfo(ep)\n for x in xdt:\n sd = tdy + dt.timedelta(hours=x[0].hour, minutes=x[0].minute,\n seconds=x[0].second)\n ed = tdy + dt.timedelta(hours=x[1].hour, minutes=x[1].minute,\n seconds=x[1].second)\n if sd > ed:\n # 当出现了‘21:30:00-04:00:00’这种类型的格式,表示任务执行时间应该\n # 从当天的21:30到第二天的04:00\n ed = ed + dt.timedelta(days=1)\n else:\n pass\n scheduler.add_job(func=action_execute,\n trigger=IntervalTrigger(seconds=execute_interval,\n start_date=sd,\n end_date=ed), args=[kwargs])\n nsds.append(sd + dt.timedelta(days=1))\n\n if end_date is not None:\n def action_end(args):\n print(fontcolor.F_GREEN + '-' * 80)\n print('Calf-Note:end task running on ', dt.datetime.now(tz=tz))\n print('-' * 80 + fontcolor.END)\n try:\n action.end(args=args)\n except Exception as ep:\n ExceptionInfo(ep)\n d = tdy + dt.timedelta(hours=edt.hour, minutes=edt.minute, seconds=edt.second)\n nsds.append(d + dt.timedelta(days=1))\n scheduler.add_job(func=action_end, trigger=DateTrigger(d), id='action_end',timezone=tz, \n args=[kwargs])\n print(fontcolor.F_GREEN + '-' * 80)\n print('Note:enter Calf real task and mount these tasks:')\n scheduler.print_jobs()\n print('Datetime:' + str(crt))\n print('-' * 80 + fontcolor.END)\n scheduler.start()\n # 计算距离下一次启动应该休眠多久\n if len(nsds) == 0:\n break\n # ed = CalfDateTime.now(tz, offset)\n nd = dt.datetime.now() if tz is None else dt.datetime.now(tz=tz).replace(tzinfo=None)\n delta = (min(nsds) - nd)\n delta = delta.seconds + delta.days * 86400\n print(fontcolor.F_YELLOW + '-' * 80)\n print('Note:Calf will sleep {0} seconds and restart on {1}:'.format(delta, min(nsds)))\n print('Datetime:' , str(crt))\n print('-' * 80 + fontcolor.END)\n delta = 1 if delta < 1 else delta\n time.sleep(delta)\n scheduler.shutdown(wait=False)\n del scheduler\n except Exception as e:\n ExceptionInfo(e)\n pass\n\n\n\n\n","sub_path":"Visual_Tools/Calf/modelrun.py","file_name":"modelrun.py","file_ext":"py","file_size_in_byte":24504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"451287184","text":"from django import forms\n\n\nclass IndexForm(forms.Form):\n query = forms.CharField(label=\"Query\", widget=forms.TextInput(\n attrs={'placeholder': 'What we will search in books?',\n 'class': 'form-control'}))\n email = forms.EmailField(label=\"Email\", widget=forms.TextInput(\n attrs={'placeholder': 'Your email for search results.',\n 'class': 'form-control'}))\n time_limit = forms.IntegerField(label='Limit query', required=False,\n widget=forms.NumberInput(\n attrs={'placeholder': 'Seconds',\n 'class': 'form-control'}))\n","sub_path":"books/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390523661","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\"\"\n def iterateA(head):\n if head:\n node_map[head] = 0\n iterateA(head.next)\n\n def iterateB(head):\n if head:\n try:\n a = node_map[head]\n return head\n except:\n return iterateB(head.next)\n node_map = {}\n iterateA(headA)\n return iterateB(headB)\n\n\na = ListNode(1)\nb = ListNode(2)\nc = ListNode(3)\nd = ListNode(4)\ne = ListNode(5)\na.next = b\nb.next = c\nc.next = d\ne.next = c\nprint(Solution().getIntersectionNode(a, e).val)\n\n\n# 优秀解答 两个游标分别遍历AB和BA\n# class Solution(object):\n# def getIntersectionNode(self, headA, headB):\n# \"\"\"\n# :type head1, head1: ListNode\n# :rtype: ListNode\n# \"\"\"\n# p1, p2 = headA, headB\n# while(p1 != p2):\n# p1 = headB if p1 == None else p1.next\n# p2 = headA if p2 == None else p2.next\n# return p1","sub_path":"leet_code/160#intersection_of_two_linked_lists.py","file_name":"160#intersection_of_two_linked_lists.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"391489863","text":"# -*- coding: utf-8 -*-\n\n\"\"\"A setuptools based setup module.\nSee:\nhttps://packaging.python.org/en/latest/distributing.html\nhttps://github.com/pypa/sampleproject\n\"\"\"\n\n# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\n# To use a consistent encoding\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n readme = f.read()\n\nwith open(path.join(here,'LICENSE'), encoding='utf-8') as f:\n license = f.read()\n\nsetup(\n name='lockss-stf',\n version='1.0.0',\n url='https://github.com/lockss/lockss-stf.git',\n license=license,\n author='LOCKSS-DLSS, Stanford University',\n author_email='clairetg@stanford.edu',\n description='The LOCKSS Stochastic Testing Framework',\n long_description=readme,\n long_description_content_type='text/markdown',\n packages=find_packages(exclude=['docs', 'bin']),\n python_requires='>=2.7'\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"636913448","text":"from typing import List\nfrom pprint import pprint\n\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n dp = [0xffffffff for _ in range(amount + 1)]\n dp[0] = 0\n for coin in coins:\n for j in range(coin, amount + 1):\n if dp[j - coin] != 0xffffffff:\n dp[j] = min(dp[j - coin] + 1, dp[j])\n return dp[-1] if dp[-1] != 0xffffffff else -1\n\nif __name__ == '__main__':\n sol = Solution()\n amount = 0\n coins = [1]\n print(sol.coinChange(coins, amount))","sub_path":"source code/322. Coin Change.py","file_name":"322. Coin Change.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"73215891","text":"from Colors import Colors\nimport curses\nfrom SuperWin import SuperWin\nfrom StatusWindow import StatusWindow\nfrom PauseWin import PauseWin\n\n\nclass MineWindow(SuperWin):\n\n def __init__(self, scr, context, manager):\n self.scr = scr\n self.manager = manager\n self.context = context\n self.logic = self.context.logic\n self.status = StatusWindow(self.manager.s_win, self.context)\n self.pause_win = PauseWin(self.manager.p_win, self.manager, self.context)\n self.max_y, self.max_x = self.scr.getmaxyx()\n self.curs_y, self.curs_x = (self.max_y // 2 - 1, 2)\n self.color = Colors()\n self.x_index = self.curs_x // 2\n self.closed_field = '*'\n self.flag_field = '?'\n self.explode_field = 'x'\n\n def draw(self):\n for y in range(self.max_y):\n for x in range(int(self.max_x/2)):\n self.scr.addstr(y, x*2, self.closed_field)\n self.curs_x = self.x_start()\n self.scr.box()\n self.scr.addstr(self.curs_y, self.curs_x, self.closed_field, curses.A_REVERSE)\n self.logic.render_list.add(self.logic.field_matrix[self.curs_y][self.x_index])\n\n def render_mine_win(self):\n if self.logic.loose:\n self.end_game()\n else:\n for cur_field in self.logic.render_list:\n cur_y, cur_x = cur_field.get_foordinate()\n if not (cur_y, cur_x) == (self.curs_y, self.curs_x):\n style = curses.A_NORMAL\n else:\n style = curses.A_REVERSE\n if cur_field.get_open():\n if cur_field.get_number() == 0:\n self.scr.addstr(cur_y, cur_x, ' ', style)\n else:\n self.scr.addstr(cur_y, cur_x, str(cur_field.get_number()),\n curses.color_pair(cur_field.get_number()) | style)\n else:\n if cur_field.get_flag():\n self.scr.addstr(cur_y, cur_x, self.flag_field, curses.color_pair(6) | style)\n else:\n self.scr.addstr(cur_y, cur_x, self.closed_field, style)\n self.scr.box()\n self.logic.render_list.clear()\n self.logic.check_win()\n\n if self.logic.win:\n if not self.logic.cheat:\n self.scr.addstr(0, int(self.max_x/2 - 4), ' win ^.^ ')\n else:\n self.scr.addstr(0, int(self.max_x/2 - 6), ' cheater >.> ')\n\n def end_game(self):\n for y in self.logic.field_matrix:\n for x in y:\n cur_y, cur_x = x.get_foordinate()\n if (cur_y, cur_x) in self.logic.rim_list:\n continue\n if x.get_number() == 0:\n self.scr.addstr(cur_y, cur_x, ' ')\n elif x.get_flag():\n if x.get_mine():\n self.scr.addstr(cur_y, cur_x, self.flag_field, curses.color_pair(6))\n else:\n self.scr.addstr(cur_y, cur_x, self.flag_field, curses.color_pair(11))\n elif x.get_number() == 9:\n self.scr.addstr(cur_y, cur_x, self.closed_field, curses.color_pair(10))\n else:\n self.scr.addstr(cur_y, cur_x, str(x.get_number()), curses.color_pair(x.get_number()))\n curs_field = self.logic.tuple_in_matrix((self.curs_y, self.curs_x))\n if curs_field.get_mine():\n self.scr.addstr(self.curs_y, self.curs_x, self.explode_field, curses.color_pair(9))\n else:\n self.scr.addstr(self.curs_y, self.curs_x, str(curs_field.get_number()), curses.color_pair(10))\n self.scr.refresh()\n self.scr.box()\n\n def reset_render(self):\n for y in self.logic.field_matrix:\n for x in y:\n cur_y, cur_x = x.get_foordinate()\n if (cur_y, cur_x) in self.logic.rim_list:\n continue\n if x.get_open():\n if x.get_number() == 0:\n self.scr.addstr(cur_y, cur_x, ' ')\n else:\n self.scr.addstr(cur_y, cur_x, str(x.get_number()),\n curses.color_pair(x.get_number()))\n else:\n if x.get_flag():\n self.scr.addstr(cur_y, cur_x, self.flag_field, curses.color_pair(6))\n else:\n self.scr.addstr(cur_y, cur_x, self.closed_field)\n self.scr.box()\n self.scr.move(self.curs_y, self.curs_x)\n\n def x_start(self):\n x_start = int(self.max_x * 0.36)\n if x_start % 2 != 0:\n return x_start - 1\n return x_start\n\n def render(self):\n self.render_mine_win()\n self.status.render()\n\n def update_index(self):\n self.x_index = int(self.curs_x / 2)\n \n def pre_input_action(self):\n self.update_index()\n self.logic.render_list.add(self.logic.field_matrix[self.curs_y][self.x_index])\n if not self.logic.loose:\n self.logic.previous_matrix = self.logic.field_matrix\n \n def after_input_action(self):\n after_index = int(self.curs_x/2)\n self.logic.render_list.add(self.logic.field_matrix[self.curs_y][after_index])\n\n def up_input(self):\n if not (self.logic.loose or self.logic.win):\n self.pre_input_action()\n if self.curs_y > 1:\n self.curs_y -= 1\n self.after_input_action()\n\n def left_input(self):\n if not (self.logic.loose or self.logic.win):\n self.pre_input_action()\n if self.curs_x > 2:\n self.curs_x -= 2\n self.pre_input_action()\n\n def right_input(self):\n if not (self.logic.loose or self.logic.win):\n self.pre_input_action()\n if self.curs_x < self.max_x - 3:\n self.curs_x += 2\n self.pre_input_action()\n\n def down_input(self):\n if not (self.logic.loose or self.logic.win):\n self.pre_input_action()\n if self.curs_y < self.max_y - 2:\n self.curs_y += 1\n self.pre_input_action()\n\n def click_input(self):\n if not (self.logic.loose or self.logic.win):\n self.pre_input_action()\n if self.logic.first:\n self.logic.distribute_mines(self.curs_y, self.curs_x)\n self.logic.click_field(self.curs_y, self.curs_x)\n else:\n if not self.logic.field_matrix[self.curs_y][self.x_index].get_open():\n self.logic.click_field(self.curs_y, self.curs_x)\n else:\n self.logic.quality_of_life_click(self.curs_y, self.curs_x)\n\n def flag_input(self):\n if not (self.logic.loose or self.logic.win):\n self.pre_input_action()\n if not self.logic.loose:\n self.logic.flag_field(self.curs_y, self.x_index)\n\n def reset_input(self):\n self.pre_input_action()\n if self.logic.loose:\n self.logic.loose = False\n self.logic.cheat = True\n self.logic.field_matrix = self.logic.previous_matrix\n self.reset_render()\n self.logic.cheat_count += 1\n\n def exit_input(self):\n self.logic.pause = True\n self.manager.push_win_stack(self.manager.p_win, self.pause_win)\n","sub_path":"src/MineWindow.py","file_name":"MineWindow.py","file_ext":"py","file_size_in_byte":7499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"291535954","text":"import math\r\nimport datetime\r\nimport pickle\r\nfrom Domains.Manager import Manager\r\nfrom Domains.Staff import Staff\r\nfrom Domains.Employee import Employee\r\nfrom Domains.Salary import Salary\r\n\r\ndef check_Date(DoB):\r\n #\r\n # Check:\r\n # if _DoB_ is in form DD/MM/YYYY\r\n # return _DoB_\r\n\r\n error = True\r\n while error == True:\r\n try:\r\n temp = DoB.split(\"/\" , 2)\r\n x = datetime.datetime(int(temp[2]), int(temp[1]), int(temp[0]))\r\n DoB = (datetime.date.strftime(x, \"%d/%m/%Y\"))\r\n error = False\r\n except:\r\n DoB = input(\"\\tTry again (DD/MM/YYYY) : \")\r\n error = True\r\n return DoB\r\n\r\n\r\ndef check_Gender(gender):\r\n # \r\n # Check:\r\n # if _gender_ is valid, \"Male\" or \"Female\"\r\n # return _gender_\r\n\r\n while True:\r\n if gender == \"Male\" or gender == \"Female\":\r\n break\r\n else:\r\n gender = input(\"\\tTry again (Male/Female) : \")\r\n return gender\r\n\r\ndef prevent_Duplicate(id, list):\r\n #\r\n # Prevent having same ID in the list\r\n # return id\r\n\r\n while True:\r\n if any(obj.id == id for obj in list):\r\n id = input(\"ID already existed. Try again : \")\r\n else:\r\n break\r\n return id \r\n\r\n\r\ndef employee_Count():\r\n #\r\n # Count employee\r\n # input number of employees as e_count\r\n #\r\n # If e_count < 11\r\n # return an Integer\r\n\r\n e_count = input(\"Enter the number of employees (smaller than 11) : \")\r\n while True:\r\n try: \r\n if int(e_count) < 11:\r\n e_count = int(e_count)\r\n break\r\n else:\r\n e_count = input(\"Try again (smaller than 11) : \")\r\n\r\n except:\r\n e_count = input(\"Integer only (smaller than 11) : \") \r\n return e_count\r\n\r\n\r\ndef update_Employee(e_count, office):\r\n # \r\n # Create a new list of e_count people\r\n # return e_list\r\n\r\n e_list = []\r\n for i in range(e_count):\r\n print(\"Employee : \", i + 1)\r\n\r\n # ID ----------------------------------------------------------------\r\n id = input(\"\\tEmployee ID : \")\r\n id = prevent_Duplicate(id, e_list)\r\n\r\n # Name --------------------------------------------------------------\r\n name = input(\"\\tEmployee Name : \")\r\n\r\n # Gender ------------------------------------------------------------\r\n gender = input(\"\\tEmployee Gender (Male/Female): \")\r\n gender = check_Gender(gender)\r\n\r\n # Date of Birth -----------------------------------------------------\r\n DoB = input(\"\\tEmployee Date of Birth (DD/MM/YYYY) : \")\r\n DoB = check_Date(DoB)\r\n\r\n e_list.append(Employee(id, name, gender, DoB, office))\r\n print()\r\n\r\n e_list = sorted(e_list, key = lambda x: x.id)\r\n return e_list\r\n\r\n\r\ndef show_Employee(e_list):\r\n #\r\n # Show employee list as e_list\r\n # \r\n\r\n print()\r\n print(\"Employee Information\")\r\n print(\"ID\\t\\tName\\t\\t\\t\\tGender\\t\\tDoB\\t\\tOffice\")\r\n\r\n for i in range(len(e_list)):\r\n e_list[i].display()\r\n\r\n\r\ndef salary(e_list, office):\r\n #\r\n # Create a new list of salary base on e_list\r\n # Payment list (Employee salary) as p_list\r\n #\r\n # return p_list\r\n\r\n show_Employee(e_list)\r\n print()\r\n print(\"Choose employee 'ID' from the list to update salary \")\r\n print()\r\n\r\n p_list = []\r\n for i in range(len(e_list)):\r\n # ID ---------------------------------------------------------------\r\n id = input(\"Employee ID : \")\r\n while True:\r\n id = prevent_Duplicate(id, p_list)\r\n if not any(employee.id == id for employee in e_list):\r\n id = input(\"\\tNo ID found. Try again : \")\r\n else:\r\n break\r\n for j in range(len(e_list)):\r\n if e_list[j].id == id:\r\n name = e_list[j].name\r\n\r\n # Working hours -----------------------------------------------------\r\n working_hour = input(\"\\tWorking Hours (total hour/month) : \")\r\n while True:\r\n try: \r\n if float(working_hour) < 201.0:\r\n working_hour = float(working_hour)\r\n break\r\n else:\r\n working_hour = input(\"Try again (smaller than 201h) : \")\r\n except:\r\n working_hour = input(\"Number only (smaller than 201h) : \")\r\n \r\n # wage --------------------------------------------------------------\r\n wage = input(\"\\tWage/Hour (smaller than 9999$) : \")\r\n while True:\r\n try: \r\n if float(wage) < 9999.0:\r\n wage = float(wage)\r\n break\r\n else:\r\n wage = input(\"Try again (smaller than 9999$) : \")\r\n except:\r\n wage = input(\"Number only (smaller than 9999$) : \")\r\n \r\n total = wage * working_hour\r\n total = math.floor(total)\r\n \r\n p_list.append(Salary(id, name, office, working_hour, wage, total))\r\n print()\r\n \r\n p_list = sorted(p_list, key = lambda x: x.id)\r\n return p_list\r\n\r\n\r\ndef show_Salary(p_list):\r\n # \r\n # Show p_list\r\n\r\n print()\r\n print(\"Salary\")\r\n print(\"ID\\t\\tName\\t\\t\\t\\tOffice\\t\\tWorking Hours\\tWage\\t\\tTotal\")\r\n \r\n for i in range(len(p_list)):\r\n p_list[i].display()\r\n\r\n\r\ndef insert_Salary(p_list):\r\n #\r\n # Dump p_list into Databse using pickle\r\n\r\n f = open(\"C:\\\\Users\\\\FLOS IGNIS\\\\OneDrive\\\\Máy tính\\\\Human Resource\\\\Database\\\\Salary{}.pickle\".format(p_list[0].office), \"wb\")\r\n pickle.dump(p_list, f)\r\n f.close()\r\n\r\n\r\ndef read_Salary(office):\r\n #\r\n # Read p_list of the office from Database\r\n # return p_list\r\n\r\n f = open(\"C:\\\\Users\\\\FLOS IGNIS\\\\OneDrive\\\\Máy tính\\\\Human Resource\\\\Database\\\\Salary{}.pickle\".format(office), \"rb\")\r\n p_list = pickle.load(f)\r\n f.close() \r\n return p_list\r\n\r\n\r\ndef add_Salary(e_list, p_list, office):\r\n # \r\n # Add new salary info of the office\r\n # return p_list\r\n\r\n print()\r\n show_Salary(p_list)\r\n\r\n # ID ----------------------------------------------------------------\r\n id = input(\"Employee ID : \")\r\n while True:\r\n id = prevent_Duplicate(id, p_list)\r\n if not any(employee.id == id for employee in e_list):\r\n id = input(\"\\tNo ID found. Try again : \")\r\n else:\r\n break\r\n for j in range(len(e_list)):\r\n if e_list[j].id == id:\r\n name = e_list[j].name\r\n\r\n # Working hours -------------------------------------------------------\r\n working_hour = input(\"\\tWorking Hours (total hour/month) : \")\r\n while True:\r\n try: \r\n if float(working_hour) < 201.0:\r\n working_hour = float(working_hour)\r\n break\r\n else:\r\n working_hour = input(\"Try again (smaller than 201h) : \")\r\n except:\r\n working_hour = input(\"Number only (smaller than 201h) : \")\r\n \r\n # wage ----------------------------------------------------------------\r\n wage = input(\"\\tWage/Hour (smaller than 9999$) : \")\r\n while True:\r\n try: \r\n if float(wage) < 9999.0:\r\n wage = float(wage)\r\n break\r\n else:\r\n wage = input(\"Try again (smaller than 9999$) : \")\r\n except:\r\n wage = input(\"Number only (smaller than 9999$) : \")\r\n \r\n total = wage * working_hour\r\n total = math.floor(total)\r\n \r\n p_list.append(Salary(id, name, office, working_hour, wage, total))\r\n print()\r\n \r\n p_list = sorted(p_list, key = lambda x: x.id)\r\n return p_list\r\n\r\n\r\ndef del_Salary(p_list):\r\n #\r\n # Delete an salary info\r\n # return p_list\r\n\r\n print()\r\n show_Salary(p_list)\r\n\r\n id = input(\"Choose employee 'ID' from the list to delete infomation : \")\r\n while True:\r\n if not any(salary.id == id for salary in p_list):\r\n id = input(\"\\tNo ID found. Try again : \")\r\n else:\r\n break\r\n\r\n for i in range(len(p_list)):\r\n if p_list[i].id == id:\r\n del(p_list[i])\r\n\r\n p_list = sorted(p_list, key = lambda x: x.id)\r\n return p_list\r\n \r\ndef insert_Employee(e_list):\r\n #\r\n # Dump e_list into Databse using pickle\r\n\r\n f = open(\"C:\\\\Users\\\\FLOS IGNIS\\\\OneDrive\\\\Máy tính\\\\Human Resource\\\\Database\\\\Employee{}.pickle\".format(e_list[0].office), \"wb\")\r\n pickle.dump(e_list, f)\r\n f.close()\r\n\r\n\r\ndef read_Employee(office):\r\n # \r\n # Read e_list of the office from Database\r\n # return e_list\r\n\r\n f = open(\"C:\\\\Users\\\\FLOS IGNIS\\\\OneDrive\\\\Máy tính\\\\Human Resource\\\\Database\\\\Employee{}.pickle\".format(office), \"rb\")\r\n e_list = pickle.load(f)\r\n f.close() \r\n return e_list\r\n\r\n\r\ndef add_Employee(e_list, office):\r\n #\r\n # Add new employee info of the office\r\n # return e_list\r\n\r\n print()\r\n while True:\r\n e_count = input(\"Add how many people : \")\r\n while True:\r\n try: \r\n e_count = int(e_count)\r\n break\r\n except:\r\n e_count = input(\"Integer only : \")\r\n\r\n if len(e_list) + e_count > 10:\r\n print(\"No more than 10 people in an office\")\r\n else:\r\n break\r\n\r\n for i in range(e_count):\r\n print(\"Employee : \", i + len(e_list) + 1)\r\n id = input(\"\\tEmployee ID : \")\r\n id = prevent_Duplicate(id, e_list)\r\n\r\n name = input(\"\\tEmployee Name : \")\r\n\r\n gender = input(\"\\tEmployee Gender (Male/Female): \")\r\n gender = check_Gender(gender)\r\n\r\n DoB = input(\"\\tEmployee Date of Birth (DD/MM/YYYY) : \")\r\n DoB = check_Date(DoB)\r\n\r\n e_list.append(Employee(id, name, gender, DoB, office))\r\n print()\r\n\r\n e_list = sorted(e_list, key = lambda x: x.id)\r\n return e_list\r\n\r\n\r\ndef del_Employee(e_list):\r\n #\r\n # Delete an employee info\r\n # return e_list\r\n\r\n print()\r\n show_Employee(e_list)\r\n \r\n id = input(\"Choose employee 'ID' from the list to delete infomation : \")\r\n while True:\r\n if not any(employee.id == id for employee in e_list):\r\n id = input(\"\\tNo ID found. Try again : \")\r\n else:\r\n break\r\n \r\n for i in range(len(e_list)):\r\n if e_list[i].id == id:\r\n del(e_list[i])\r\n \r\n e_list = sorted(e_list, key = lambda x: x.id)\r\n return e_list \r\n\r\n\r\ndef your_Info(office):\r\n #\r\n # Show informations of the staff who manage the office\r\n\r\n f = open(\"C:\\\\Users\\\\FLOS IGNIS\\\\OneDrive\\\\Máy tính\\\\Human Resource\\\\Database\\\\Staff{}.pickle\".format(office), \"rb\")\r\n staff = pickle.load(f)\r\n f.close() \r\n staff.display2() \r\n\r\n\r\ndef main(office):\r\n #\r\n # running when input Username and Password of a staff\r\n\r\n print(\"OFFICE : {}\".format(office))\r\n try:\r\n print(\"Getting Employee info.......\", end = \"\")\r\n e_list = read_Employee(office)\r\n print(\"Done\")\r\n except:\r\n print(\"No Employee info. Please update Employee info !\")\r\n try:\r\n print(\"Getting Salary info.......\", end = \"\")\r\n p_list = read_Salary(office)\r\n print(\"Done\")\r\n except:\r\n print(\"No Salary info. Please update Salary info !\")\r\n print()\r\n while True:\r\n print(\"'A' : Update employee info\", end = \"\\t\\t\")\r\n print(\"'B' : Show employee info\")\r\n print(\"'C' : Update salary\", end = \"\\t\\t\\t\")\r\n print(\"'D' : Show salary\")\r\n print(\"'X' : Show your information\")\r\n print(\"'Z' : Exit\")\r\n answer = input(\"Choose your action : \")\r\n if answer == \"A\":\r\n print(\"\\n\\n\")\r\n print(\"Updating employee info.......\")\r\n print()\r\n while True:\r\n print(\"'1' : Create new employee info\")\r\n print(\"'2' : Add new employee info\")\r\n print(\"'3' : Del employee info\")\r\n print(\"'4' : Cancel\")\r\n answer = input(\"Choose your action : \")\r\n if answer == \"1\":\r\n print()\r\n e_count = employee_Count()\r\n print()\r\n e_list = update_Employee(e_count, office)\r\n insert_Employee(e_list)\r\n print()\r\n elif answer == \"2\":\r\n try:\r\n e_list = add_Employee(e_list, office)\r\n insert_Employee(e_list)\r\n print()\r\n except:\r\n print(\"No employee info. Please update employee info first\")\r\n print()\r\n elif answer == \"3\":\r\n try:\r\n e_list = (e_list)\r\n insert_Employee(e_list)\r\n print()\r\n except:\r\n print(\"No employee info. Please update employee info first\")\r\n print()\r\n elif answer == \"4\":\r\n print()\r\n break\r\n else:\r\n print()\r\n print(\"Action not recognized\")\r\n print()\r\n elif answer == \"B\":\r\n try:\r\n show_Employee(e_list)\r\n except:\r\n print(\"Need updating.......\")\r\n print()\r\n elif answer == \"C\":\r\n print(\"\\n\\n\")\r\n print(\"Updating salary info.......\")\r\n try:\r\n print()\r\n while True:\r\n print(\"'1' : Create new salary info\")\r\n print(\"'2' : Add salary info\")\r\n print(\"'3' : Del salary info\")\r\n print(\"'4' : Cancel\")\r\n answer = input(\"Choose your action : \")\r\n if answer == \"1\":\r\n print()\r\n p_list = salary(e_list, office)\r\n (p_list)\r\n print()\r\n elif answer == \"2\":\r\n try:\r\n p_list = add_Salary(e_list, p_list, office)\r\n (p_list)\r\n print()\r\n except:\r\n print(\"No salary info. Please update salary info first\")\r\n print()\r\n elif answer == \"3\":\r\n try:\r\n p_list = del_Salary(p_list)\r\n (p_list)\r\n print()\r\n except:\r\n print(\"No salary info. Please update salary info first\")\r\n print()\r\n elif answer == \"4\":\r\n print()\r\n break\r\n else:\r\n print()\r\n print(\"Action not recognized\")\r\n print()\r\n except:\r\n print(\"No employee info. Please update employee info first\")\r\n elif answer == \"D\":\r\n try:\r\n show_Salary(p_list)\r\n except:\r\n print(\"Need updating.......\")\r\n print()\r\n elif answer == \"X\":\r\n your_Info(office)\r\n print()\r\n elif answer == \"Z\":\r\n print(\"Bravo Six, we're going dark !.... \")\r\n break\r\n else:\r\n print()\r\n print(\"Action not recognized\")\r\n print()\r\n continue\r\n\r\n\r\n \r\n ","sub_path":"ProjectMid/Human Resource/staff.py","file_name":"staff.py","file_ext":"py","file_size_in_byte":15738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33423644","text":"#from typing import List, Set, Dict, Tuple, Optional\r\n\r\n\r\n\r\nimport grille\r\n\r\n\r\n\r\nclass Voyageur :\r\n\r\n \"\"\" cree et determine un voyageur ; attributs : une couleur (tuple de 3 entiers) et une liste trajet contenant les\r\n\r\n differentes etapes pour arriver a la porte finale (tuple de portes) ; cette liste est mise a jour au fur et a mesure\r\n\r\n que les etapes sont franchies ; lorsqu'elle est vide, le voyageur a atteint son but. Ce voyageur appartient a une grille\r\n\r\n (dictionnaire) \"\"\"\r\n\r\n \r\n\r\n def __init__(self, couleur,trajet, grille):\r\n\r\n self.couleur = couleur\r\n\r\n self.trajet = trajet\r\n\r\n self.grille = grille\r\n\r\n \r\n\r\n def autourVoyageur(self,position):\r\n\r\n \"\"\"determine le contenu des cases autour du voyageur (soit un autre voyageur, soit un obstacle, soit une porte) ;\r\n\r\n en entree : les coordonnees du voyageur (tuple d'entiers) ; en sortie : la liste des coordonnees des cases accessibles (tuples d'entiers)\r\n\r\n et avec leur contenu (porte ou vide) \"\"\"\r\n\r\n casespossibles=[]\r\n\r\n x_voy=position[0]\r\n\r\n y_voy=position[1]\r\n\r\n for coord in [(x_voy-1, y_voy-1), (x_voy-1, y_voy), (x_voy-1, y_voy+1), (x_voy, y_voy-1), (x_voy, y_voy+1), (x_voy+1, y_voy-1),(x_voy+1, y_voy), (x_voy+1, y_voy+1)]:\r\n\r\n contenu = self.grille.getContenuCase(coord)\r\n\r\n if contenu[0]==None and contenu[1]==None: # case accessible\r\n\r\n casespossibles.append((coord, contenu[2])) \r\n\r\n return casespossibles\r\n\r\n \r\n\r\n \r\n\r\n def seDeplacer(self):\r\n\r\n \"\"\" deplacement d'un voyageur. Sortie : nouvelle position du voyageur (tuple d'entiers).\r\n\r\n Le voyageur commence par observer les cases alentour et etablit ainsi une liste de possibilites.\r\n\r\n Si une des cases accessibles est une des etapes de son trajet, il y va. Sinon, on choisit celle le devie le moins possible de son trajet\r\n\r\n (produit scalaire de deux vecteurs) \"\"\"\r\n\r\n maposition=self.grille.getPosition(self)\r\n\r\n# ATT : manque un self\r\n casespossibles=self.autourVoyageur(maposition) \r\n\r\n if casespossibles==[] : return(maposition) # aucune case accessible, le voyageur ne bouge pas\r\n\r\n else :\r\n\r\n maxi = -1\r\n\r\n for case in casespossibles: #on parcourt la liste des cases accessibles\r\n \r\n# ATT ; si la case est la 1ere porte du trajet du voyageur : if (case[1]))self.trajet[0]\r\n if case[1] == self.trajet[0] : # la case est une porte du trajet du voyageur\r\n\r\n self.trajet.pop(case[1]) # suppression de l'etape\r\n \r\n# ATT : ajout self. devant grille\r\n if self.trajet ==[] : self.grille.deleteVoyageur(self) # le voyageur est arrive ; on le supprime de la grille\r\n\r\n# QUESTION : dans ce cas la valeur de retour va-t-elle traitee ?\r\n return case[0]\r\n\r\n else :\r\n\r\n coord_etape=self.grille.getPosition(self.trajet[0]) # on recupere les coordonnees de la porte a atteindre \r\n\r\n vecteur1=(coord_etape[0] - maposition[0], coord_etape[1] - maposition[1])\r\n\r\n# ATT : A quoi correspond coord dans vecteur2 ? coord[0] par case[0][0]\r\n vecteur2=(case[0][0] - maposition[0], case[0][1] - maposition[1])\r\n# ATT : ajout de la biblio Math pour sqrt\r\n cosinus = (vecteur1[0]*vecteur2[0] + vecteur1[1]*vecteur2[1])/(sqrt(vecteur1[0]**2 + vecteur1[1]**2)*sqrt(vecteur2[0]**2 + vecteur2[1]**2))\r\n\r\n if cosinus >= maxi :\r\n\r\n maxi = cosinus\r\n# ATT : idem ci dessus : coord par case[0] \r\n new_pos=coord\r\n\r\n if maxi < 0 : return(maposition) # le voyageur est dans une situation ou il devrait reculer. Il ne bouge pas.\r\n\r\n return new_pos\r\n\r\n \r\n\r\n \r\n\r\nclass Obstacle:\r\n\r\n def __init__(self, couleur, grille):\r\n\r\n self.couleur = couleur\r\n\r\n self.grille = grille\r\n\r\n\r\n\r\nclass Porte:\r\n\r\n def __init__(self, couleur, grille):\r\n\r\n self.couleur = couleur\r\n\r\n self.grille = grille\r\n\r\n \r\n\r\n","sub_path":"MouvementFoule/classevoyageur avec Remarques pascal.py","file_name":"classevoyageur avec Remarques pascal.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"352332029","text":"import os, sys\nfrom subprocess import call, check_output\nimport pylab as pl\nfrom environ import syten_envi\n\ndef make_tmp (fname,N,symm='su2'):\n '''\n if os.path.isfile (fname):\n f = open (fname)\n lines = f.readlines()\n f.close()\n if len(lines) == N+1: return\n '''\n if symm == 'su2': s_op = 's'\n elif symm == 'u1': s_op = 'sz'\n\n f = open (fname, 'w')\n f.write ('site n '+s_op+'\\n')\n for i in xrange(N):\n f.write (str(i)+' { n '+str(i)+' @ } { '+s_op+' '+str(i)+' @ }\\n')\n f.close()\n\ndef get_N (sytendir, lat):\n command = sytendir+'/bin/syten-info '+lat\n lines = check_output(command, shell=True)\n lines = lines.rstrip().split('\\n')\n for line in lines:\n if 'Number of sites' in line:\n return int(line.split()[-1])\n\ndef get_lxy (sytendir, lat):\n command = sytendir+'/bin/syten-info '+lat\n lines = check_output(command, shell=True)\n lines = lines.rstrip().split('\\n')\n for line in lines:\n if 'lattice' in line and 'dimension' in line:\n tmp = line.split()\n ind = tmp.index('dimension')\n tmp = tmp[ind+1].split('\\xc3\\x97')\n return int(tmp[0]),int(tmp[1])\n\ndef plot_hsz (lx,ly,fname):\n def toxy (i,lx,ly):\n return i/ly+1, i%ly+1\n\n f = open (fname)\n for line in f:\n if 'site' in line and 'n' in line and 'sz' in line:\n break\n h_dict, sz_dict = dict(), dict()\n for line in f:\n tmp = line.split()\n if len(tmp) != 3: break\n i,h,sz = int(tmp[0]),1-float(tmp[1]),float(tmp[2])\n\n x,y = toxy (i,lx,ly)\n h_dict[x,y] = h\n sz_dict[x,y] = sz\n\n xs = range(1,lx+1)\n for y in xrange(1,ly+1):\n hx = []\n for x in xs:\n hx.append (h_dict[x,y])\n pl.plot (xs, hx, 'o-')\n pl.xlabel('x',fontsize=18)\n pl.ylabel('hole density',fontsize=18)\n\ndef do_hsz (sytendir, lat, psi, out='',symm='su2',cpus_dense=1,cpus_tensor=1,cpus_super=1,writeM=1048576,overwrite=False):\n tmp = 'mea.temp'\n if os.path.isfile (out) and overwrite: os.system ('rm '+out)\n commands = []\n if not os.path.isfile (out):\n N = get_N (sytendir, lat)\n make_tmp (tmp,N,symm)\n\n flag = ' --cache --cache-threshold '+str(writeM)+' '\n flag += ' --threads-dense '+str(cpus_dense)+' '\n flag += ' --threads-tensor '+str(cpus_tensor)+' '\n flag += ' --threads-super '+str(cpus_super)+' '\n to_file = ''\n if out != '': to_file = ' 1>>'+out+' 2>&1'\n command = sytendir+'/bin/syten-expectation '+flag+' --template-file '+tmp+' -l '+lat+' '+psi+' -r'+to_file\n\n commands += ['echo '+command]\n commands += [command]\n return commands\n\nif __name__ == '__main__':\n syten_envi (sys.argv)\n sytendir = os.environ['SYTENDIR']\n\n lat = sys.argv[1]\n psi_files = ''\n plot = False\n for f in sys.argv[2:]: psi_files += ' '+f+' '\n psi_files = check_output('ls '+psi_files, shell=True).split()\n\n if '-plt' in sys.argv: plot = True\n\n for psi in psi_files:\n out = ''\n if plot: out = psi.replace('.hsz','')+'.hsz'\n commands = do_hsz (sytendir, lat, psi, out, symm='u1')\n for command in commands:\n os.system (command)\n\n if plot:\n lx,ly = get_lxy (sytendir, lat)\n plot_hsz (lx,ly,out)\n pl.title (psi)\n pl.show()\n","sub_path":"hsz.py","file_name":"hsz.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"483665443","text":"#PLEASE DO NOT CHANGE ANYTHING UNLESS THE COMMENTS STATE OTHERWISE!!!\n#====================================================================\n\nimport os\nimport cv2\nfrom cv2 import aruco\nimport numpy as np\n\n# 1) Corners contains an array of vectors, each of which describes the \n# locations of the corners of one marker in the frame\n# 2) Strategy is to find the marker closest to the center of the frame, \n# seperate it from corners, and estimate its pose using \n# estimatePoseSingleMarkers\n# 3) EstimatePoseSingleMarkers will return rvec, tvec, which describe the \n# rotation and translation vectors from the marker to the camera\n# - The marker coordinate system that is assumed by this function \n# is placed at the center of the marker with the Z axis pointing \n# out\n# 4) Using the relationship between the pose of the camera and the base_link\n# frame of the walker, as well as the known pose of that specific marker\n# (as identified by the id) in the map of the room, we can easily calculate \n# the walkers pose in the room map\n# 5) The walkers pose can be returned and then used to determine its navigation\n# goal\n\n#Initialization (should not have to do every time)\nmarker_length = 0.165 #Any unit. Pose estimation will have the same unit\n#cal_file = \"webcam_calibration.xml\"\n#calibrationParams = cv2.FileStorage(cal_file, cv2.FILE_STORAGE_READ)\n##camera_matrix = calibrationParams.getNode(\"cameraMatrix\").mat()\n##dist_coeffs = calibrationParams.getNode(\"distCoeffs\").mat()\naruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)\n\nwebcam_cals = np.load('calib.npz')\ncamera_matrix = webcam_cals['mtx']\ndist_coeffs = webcam_cals['dist']\n\n##print(camera_matrix)\n##print(dist_coeffs)\n\nNUM_MARKERS = 20 #You are allowed to change this (breaks if you go higher than 20 with size 40 atm)\nARUCO_SIZE = 40 #You are allowed to change this\nWIN_WIDTH = 480\nWIN_LENGTH = 640\nSPACING = 5\n\nids = []\n\nblank = np.ones((WIN_WIDTH,WIN_LENGTH),np.uint8)*255\n\ni = 0\n##while i < NUM_MARKERS:\n## ids.append(cv2.aruco.drawMarker(aruco_dict, i, ARUCO_SIZE, 1))\n## xstart = i*(ARUCO_SIZE + SPACING) + SPACING\n## ystart = i*(ARUCO_SIZE + SPACING) + SPACING\n## \n## if xstart > (WIN_WIDTH - ARUCO_SIZE):\n## xstart -= (WIN_WIDTH - ARUCO_SIZE)\n##\n## if ystart > (WIN_LENGTH - ARUCO_SIZE):\n## ystart -= (WIN_LENGTH - ARUCO_SIZE)\n## \n## xend = xstart + ARUCO_SIZE\n## #print(xstart,xend)\n## yend = ystart + ARUCO_SIZE\n## #print(ystart,yend)\n## \n## blank[xstart:xend,ystart:yend] = ids[i]\n## \n## i += 1\n\n\ncap = cv2.VideoCapture(1)\n\nwhile (cv2.waitKey(1) & 0xFF != ord('q')):\n _, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n#Read in color image, 'image_color', here\n#image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY)\n corners, ids, rejected = aruco.detectMarkers(gray, aruco_dict)\n\n aruco.drawDetectedMarkers(frame, corners, ids, (120,120,120))\n\n if not(ids is None): #Markers were detected\n print('Markers detected')\n \n rvec, tvec = aruco.estimatePoseSingleMarkers(corners, marker_length, camera_matrix, dist_coeffs)\n aruco.drawAxis(frame, camera_matrix, dist_coeffs, rvec, tvec, marker_length)\n print ('rvec = %s\\ntvec = %s' % (rvec, tvec))\n else:\n print('No markers detected\\n')\n\n#cv2.imshow('blank', blank)\n cv2.imshow('frame', frame)\n\ncap.release()\ncv2.destroyAllWindows()\n\n\n\n","sub_path":"camera_calibrations/Webcam/marker_detect_webcam_edit.py","file_name":"marker_detect_webcam_edit.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"192989937","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 9 15:09:02 2020\n\n@author: adamepstein\n\"\"\"\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.utils import to_categorical\nimport os\n\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n#%%\ndata_dir = '/Users/adamepstein/Downloads/digit-recognizer'\n\ntrain_df = pd.read_csv(data_dir + '/train.csv')\ntest_df = pd.read_csv(data_dir + '/test.csv')\n#%%\nY_train = train_df[\"label\"]\nY_train = to_categorical(Y_train)\nX_train = train_df.loc[0:train_df.shape[0], \"pixel0\":\"pixel783\"]\nX_test = test_df\n\nnumval = 8000\nX_val = X_train[0:numval]\nY_val = Y_train[0:numval]\nX_partial_train = X_train[numval:]\nY_partial_train = Y_train[numval:]\n#%%\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Dense(32, activation = 'relu', input_shape = (784,)),\n tf.keras.layers.Dense(10, activation = 'softmax')\n ])\n\n#%%\n# model = tf.keras.models.Sequential([\n# tf.keras.layers.Conv2D(6, (3,3), activation = 'relu', input_shape = (28,28,1)),\n# tf.keras.layers.MaxPooling2D((2,2)),\n# tf.keras.layers.Conv2D(14,(3,3), activation = 'relu'),\n# tf.keras.layers.MaxPooling2D((2,2)),\n# tf.keras.layers.Flatten(),\n# tf.keras.layers.Dense(64, activation = 'relu'),\n# tf.keras.layers.Dense(10, activation = 'softmax')\n# ])\n\n\n#%%\nmodel.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy',\\\n metrics = ['accuracy'])\n\nhistory = model.fit(X_partial_train, Y_partial_train , \\\n epochs = 100, batch_size = 64, \\\n validation_data = (X_val, Y_val))\n\n#%%\nmodel.summary() \n#%% \n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nplt.plot(acc, 'bo')\nplt.plot(val_acc, 'b')\n#%%\nY_predicted = model.predict(X_test)\n#%%\npredictions = np.zeros(28000)\n\nfor i in range(28000):\n predictions[i] = np.argmax(Y_predicted[i])\n\n\n#%% \n# kaggleSubmission = pd.DataFrame(predictions)\nkaggleSubmission = pd.DataFrame()\nkaggleSubmission['ImageId'] = np.arange(1,28001)\n\n\n# kaggleSubmission = test_df[['']]\nkaggleSubmission['Label'] = np.uint8(predictions)\nkaggleSubmission.to_csv('/Users/adamepstein/Downloads/digit-recognizer/Kaggle_submission.csv', index = False)\n\n \n#I got a kaggle score of 0.94871 \n \n ","sub_path":"kaggleMNIST_tensorflow.py","file_name":"kaggleMNIST_tensorflow.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"516746045","text":"# -*- coding: utf-8 -*-\nfrom django import template\nfrom pages.models import Page\n\nregister = template.Library()\n\n\n@register.inclusion_tag('pages/tags/content.html')\ndef pages_page_full(slug):\n try:\n page = Page.objects.get(slug=slug, is_show=True)\n except Page.DoesNotExist:\n page = None\n return {'page': page}\n\n\n@register.inclusion_tag('pages/tags/t_tag_inline.html')\ndef pages_page_body(slug):\n try:\n page = Page.objects.get(slug=slug)\n except Page.DoesNotExist:\n page = None\n return {'page': page}\n\n\n@register.inclusion_tag('pages/t_tag_short.html')\ndef pages_page_short(slug):\n try:\n page = Page.objects.get(slug=slug, is_show=True)\n except Page.DoesNotExist:\n page = None\n return {'page': page}\n","sub_path":"src/apps/pages/templatetags/pages_tags.py","file_name":"pages_tags.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"361860803","text":"\nimport turtle\ndef draw_shape():\n\twindow=turtle.Screen()\n\twindow.bgcolor(\"yellow\")\n\tflower=turtle.Turtle()\n\tflower.shape(\"turtle\")\n\tflower.color(\"green\")\n\tflower.speed(50)\n\tflower.right(45)\n\tfor i in range(1,100):\n\t\tfor j in range(6):\n\t\t\tdraw_circle(flower,i)\n\t\t\tflower.left(45)\n\tflower.right(45)\n\tflower.forward(200)\n\twindow.exitonclick()\n\ndef draw_circle(circle,radius):\n\tcircle.circle(radius)\n\ndraw_shape()\n","sub_path":"flower.py","file_name":"flower.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80544876","text":"import os\nimport sys\nimport random\nimport math\nimport numpy as np\nimport skimage.io\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nsys.path.append('./maskrcnn')\nsys.path.append('./dataset')\n\nimport maskrcnn.utils as utils\nimport model as modellib\nimport visualize\nimport config\n\nimport mark_dataset\nimport sc_utils\nimport position as pos\n\nROOT_DIR = os.path.abspath(\".\")\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\nmodel_path = os.path.join(ROOT_DIR, \"adjusted_frame_alignment_20.h5\")\nclassnames = ['BG', 'mark']\n\ndef get_inference_model():\n ''' Loads weights and returns an inference model '''\n inference_config = mark_dataset.InferenceConfig()\n model = modellib.MaskRCNN(mode=\"inference\", \n config=inference_config,\n model_dir=MODEL_DIR)\n print(\"Loading weights from \", model_path)\n model.load_weights(model_path, by_name=True)\n return model\n\ndef convert_to_mrcnn_format(image):\n image = np.ceil(image / 255) # convert down to 8-bit\n image = image.astype('uint8')\n new_im = np.zeros((image.shape[0], image.shape[1], 3))\n for ix, iy in np.ndindex(image.shape):\n new_im[ix,iy] = [image[ix,iy],image[ix,iy],image[ix,iy]]\n new_im = new_im.astype('uint8')\n new_im = new_im * 16\n return new_im\n\ndef get_mark_center(rois):\n centroids = np.stack([\n rois[1] + ((rois[3] - rois[1]) / 2.0),\n rois[0] + ((rois[2] - rois[0]) / 2.0),\n ], -1)\n return centroids\n\ndef get_frame():\n cam = sc_utils.start_cam()\n # frame = cam.get_frame(exp_time=1).reshape(cam.sensor_size[::-1])\n frame = cam.get_frame(exp_time=1)\n sc_utils.close_cam(cam)\n print(frame.shape)\n return frame\n\ndef find_alignment_mark(model):\n orig_frame = get_frame()\n frame = convert_to_mrcnn_format(orig_frame)\n \n results = model.detect([frame], verbose=1)\n r = results[0]\n print ('ran detect')\n centroids = get_mark_center(r['rois'][0])\n return centroids, orig_frame, frame, r\n\ndef move_to_center(mmc, center):\n currx = mmc.getXPosition()\n curry = mmc.getYPosition()\n\n x = center[0]\n y = center[1]\n \n x_change = (x-1344)*0.45\n y_change = (y-1100)*0.45\n \n new_x = currx-x_change\n new_y = curry-y_change\n \n pos.set_pos(mmc, x=new_x, y=new_y)\n\n","sub_path":"python/source/alignment.py","file_name":"alignment.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"420534195","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\n# Hive Budy\r\n# Copyright (c) 2008-2020 Hive Solutions Lda.\r\n#\r\n# This file is part of Hive Budy.\r\n#\r\n# Hive Budy is free software: you can redistribute it and/or modify\r\n# it under the terms of the Apache License as published by the Apache\r\n# Foundation, either version 2.0 of the License, or (at your option) any\r\n# later version.\r\n#\r\n# Hive Budy 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# Apache License for more details.\r\n#\r\n# You should have received a copy of the Apache License along with\r\n# Hive Budy. If not, see .\r\n\r\n__author__ = \"João Magalhães \"\r\n\"\"\" The author(s) of the module \"\"\"\r\n\r\n__version__ = \"1.0.0\"\r\n\"\"\" The version of the module \"\"\"\r\n\r\n__revision__ = \"$LastChangedRevision$\"\r\n\"\"\" The revision number of the module \"\"\"\r\n\r\n__date__ = \"$LastChangedDate$\"\r\n\"\"\" The last change date of the module \"\"\"\r\n\r\n__copyright__ = \"Copyright (c) 2008-2020 Hive Solutions Lda.\"\r\n\"\"\" The copyright for the module \"\"\"\r\n\r\n__license__ = \"Apache License, Version 2.0\"\r\n\"\"\" The license for the module \"\"\"\r\n\r\nimport appier\r\n\r\nimport budy\r\n\r\nfrom . import root\r\n\r\nclass CurrencyAPIController(root.RootAPIController):\r\n\r\n @appier.route(\"/api/currencies\", \"GET\", json = True)\r\n def list(self):\r\n object = appier.get_object(alias = True, find = True)\r\n currencies = budy.Currency.find(\r\n find_i = True,\r\n find_t = \"right\",\r\n map = True,\r\n **object\r\n )\r\n return currencies\r\n\r\n @appier.route(\"/api/currencies/simple.csv\", \"GET\")\r\n @appier.ensure(token = \"admin\")\r\n def simple_csv(self):\r\n object = appier.get_object(\r\n alias = True,\r\n find = True,\r\n limit = 0\r\n )\r\n currencies = budy.Currency.find(**object)\r\n\r\n currencies_s = [(\"iso\", \"decimal_places\")]\r\n for currency in currencies:\r\n currency_s = (currency.iso, currency.decimal_places)\r\n currencies_s.append(currency_s)\r\n\r\n result = appier.serialize_csv(currencies_s, delimiter = \",\")\r\n self.content_type(\"text/csv\")\r\n return result\r\n","sub_path":"src/budy/controllers/api/currency.py","file_name":"currency.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"344726342","text":"import json\nimport re\nfrom datetime import datetime\nfrom urllib.parse import urlencode\n\nfrom scrapy import Request\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom ..items import VansItem\n\n\nclass Mixin:\n retailer = \"vans-fr\"\n market = \"FR\"\n\n pagniation_req_url_t = \"https://fsm-vfc.attraqt.com/zones-js.aspx?{0}\"\n\n\nclass VansCrawler(CrawlSpider, Mixin):\n name = Mixin.retailer + \"-crawler\"\n listings_css = [\".topnav-main-item\"]\n product_css = [\".product-block-figure\"]\n deny_re = [\".html\"]\n PAGE_SIZE = 48\n\n custom_settings = {\n \"ITEM_PIPELINES\": {\n \"skuscraper.pipelines.NormalizePricePipeline\": 300\n }\n }\n\n rules = (\n Rule(LinkExtractor(restrict_css=listings_css, deny=deny_re), callback=\"parse_pagination\"),\n )\n\n def category_zones(self, response):\n css = \".body-container div::attr(lmzone)\"\n return response.css(css).extract()\n\n def site_id(self, response):\n script_re = \"WCS_CONFIG.ATTRAQT = (.+?);\"\n raw_site_id = json.loads(re.findall(script_re, response.body.decode(\"utf-8\").replace(\"\\n\", \"\"))[0])\n return re.findall(\"zones/(.*).min\", raw_site_id[\"MAINJS\"])[0]\n\n def config_categorytree(self, response):\n return re.findall('categorytree : \"(.*)\"', response.body.decode(\"utf-8\"))[0]\n\n def config_language(self, response):\n css = \"meta[name='locale']::attr(content)\"\n return response.css(css).extract_first()\n\n def parse_pagination(self, response):\n pages = self.page_count(response)\n cat_zones = self.category_zones(response)\n lang = self.config_language(response)\n\n parameters = {\n \"zone0\": cat_zones[0], \"zone1\": cat_zones[1], \"mergehash\": \"true\",\n \"config_categorytree\": self.config_categorytree(response),\n \"siteId\": self.site_id(response), \"config_language\": lang,\n \"language\": lang, \"config_country\": self.market}\n\n for page in range(0, pages + self.PAGE_SIZE, self.PAGE_SIZE):\n parameters[\"pageurl\"] = f\"{response.url}#esp_pg={page//self.PAGE_SIZE}\"\n url = self.pagniation_req_url_t.format(urlencode(parameters))\n\n yield Request(url, callback=self.parse_raw_content, dont_filter=True)\n\n def parse_raw_content(self, response):\n script_re = \"LM.buildZone\\((.*)\\)\"\n raw_html = json.loads(re.findall(script_re, response.body.decode(\"utf-8\"))[0])\n new_response = response.replace(body=raw_html[\"html\"])\n\n return [Request(url, callback=self.parse_product) for url in self.product_urls(new_response)]\n\n def product_urls(self, response):\n css = \".product-block-pdp-url::attr(href)\"\n urls = response.css(css).extract()\n return [f\"https://www.vans.fr/{url}\" for url in urls]\n\n def page_count(self, response):\n css = \".header-result-counter ::text\"\n return int(response.css(css).re_first(\"\\d+\") or '0')\n\n # Parser\n\n def parse_product(self, response):\n item = VansItem()\n item[\"uuid\"] = self.product_id(response)\n item[\"name\"] = self.product_name(response)\n item[\"gender\"] = self.get_gender(response)\n item[\"market\"] = self.market\n item[\"retailer\"] = self.retailer\n item[\"retailer_sku\"] = self.retailer_sku(response)\n item[\"description\"] = self.product_description(response)\n item[\"care\"] = self.product_care(response)\n item[\"category\"] = self.product_category(response)\n item[\"crawl_id\"] = self.get_crawl_id()\n item[\"spider_name\"] = Mixin.retailer\n item[\"date\"] = datetime.now().strftime(\"%Y-%m-%d\")\n item[\"crawl_start_time\"] = datetime.now().isoformat()\n item[\"url_orignal\"] = response.url\n item[\"skus\"] = self.skus(response)\n item[\"image_urls\"] = self.image_urls(response)\n\n return [item] + self.color_requests(response)\n\n def skus(self, response):\n color_css = \".attr-selected-color-js::text\"\n skus = []\n\n sku = self.product_pricing(response)\n sku[\"color\"] = response.css(color_css).extract_first()\n\n sizes = self.product_sizes(response)\n for size in sizes:\n sku[\"size\"] = size\n sku[\"sku_id\"] = f\"{sku['color']}_{size}\"\n skus.append(sku)\n\n return skus\n\n def product_id(self, response):\n css = \".step-container::attr(data-product-id)\"\n return response.css(css).extract_first()\n\n def retailer_sku(self, response):\n css = \"input[name='productCode']::attr(value)\"\n return response.css(css).extract_first()\n\n def product_name(self, response):\n css = \"h1.product-info-js::text\"\n return response.css(css).extract_first()\n\n def product_price(self, response):\n css = \"meta[property='og:price:amount']::attr(content)\"\n return int(float(response.css(css).extract_first()) * 100)\n\n def previous_price(self, response):\n script_re = \"var itemPrices = (.+?);\\n\"\n price_details = json.loads(re.findall(script_re, response.body.decode(\"utf-8\"))[0])\n raw_price = price_details[self.product_id(response)][\"pricing\"]\n\n return int(float(raw_price[\"default\"][\"lowListPriceNumeric\"]) * 100)\n\n def product_description(self, response):\n css = \".desc-container ::text\"\n return response.css(css).extract_first()\n\n def product_care(self, response):\n css = \".desc-container ::text\"\n return response.css(css).extract()[-1] if response.css(css).extract() else []\n\n def product_category(self, response):\n css = \"#product-attr-form::attr(data-seo-category)\"\n return response.css(css).extract()\n\n def product_sizes(self, response):\n css = \".swatches .attr-box::attr(data-attribute-value)\"\n return response.css(css).extract()\n\n def get_gender(self, response):\n css = \"#product-attr-form::attr(data-master-category-identifier)\"\n return response.css(css).extract_first()\n\n def get_crawl_id(self):\n return f\"vans-us-{datetime.now().strftime('%Y%m%d-%H%M%s')}-axuj\"\n\n def currency_type(self, response):\n css = \"meta[property='og:price:currency']::attr(content)\"\n return response.css(css).extract_first()\n\n def product_pricing(self, response):\n pricing_details = {\n \"price\": self.product_price(response),\n \"currency\": self.currency_type(response)}\n\n prev_price = self.previous_price(response)\n if prev_price != pricing_details[\"price\"]:\n pricing_details[\"previous_price\"] = prev_price\n\n return pricing_details\n\n def image_urls(self, response):\n css = \".vfdp-s7-viewer-preload-image::attr(src)\"\n urls = response.css(css).extract()\n return [response.urljoin(url) for url in urls]\n\n def color_requests(self, response):\n urls = response.css(\"button img::attr(data-product-url)\").extract()\n return [Request(url, callback=self.parse_product) for url in urls]\n\n def clean(self, dirty_strs):\n return [re.sub(':\\s+', ' ', text).strip() for text in dirty_strs.split(\";\")]\n","sub_path":"frontera-spiders/skuscraper/spiders/vans_spider.py","file_name":"vans_spider.py","file_ext":"py","file_size_in_byte":7143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"487308274","text":"from fastapi import FastAPI, Request, Response\nfrom fastapi.openapi.utils import get_openapi\nfrom starlette.middleware.cors import CORSMiddleware\nfrom .generic import v1 as generic_v1\nfrom .market import v1 as market_v1\nfrom .database import SessionLocal\nfrom .settings import settings\nfrom .git import Git\n\napp = FastAPI()\nGit.clone()\n\n\ndef custom_openapi():\n if app.openapi_schema:\n return app.openapi_schema\n openapi_schema = get_openapi(\n title=\"Bewerkdemarkten-api\",\n version=\"0.8.1\",\n description=\"This is the API for Bewerkdemarkten\",\n routes=app.routes,\n )\n app.openapi_schema = openapi_schema\n return app.openapi_schema\n\n\n@app.middleware(\"http\")\nasync def db_session_middleware(request: Request, call_next):\n response = Response(\"Internal server error\", status_code=500)\n try:\n request.state.db = SessionLocal()\n response = await call_next(request)\n finally:\n request.state.db.close()\n return response\n\n\n# Dependency\ndef get_db(request: Request):\n return request.state.db\n\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=settings.BACKEND_CORS_ORIGINS_CSV.split(','),\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n# Routers moved to individual files in the ./routers folder\napp.include_router(generic_v1.router)\napp.include_router(market_v1.router)\napp.openapi = custom_openapi","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"199726220","text":"import json\nimport os\nimport re\nfrom collections import namedtuple\nfrom datetime import datetime\nfrom typing import List\n\nfrom compress import compress_file_with_lzma, decompress_file_with_lzma\nfrom lanzou.api import LanZouCloud\nfrom lanzou.api.types import FileInFolder, FolderDetail\nfrom log import logger, color\nfrom util import make_sure_dir_exists, with_cache, human_readable_size, cache_name_download\n\nFolder = namedtuple('Folder', ['name', 'id', 'url', 'password'])\n\n\n# 参考文档可见:https://github.com/zaxtyson/LanZouCloud-API/wiki\n\n# 如果日后蓝奏云仍出现多次问题,可以考虑增加一个fallback选项\n# 在gitee新建一个仓库,通过git add操作更新文件,通过访问raw链接来下载文件\n# 如:https://gitee.com/fzls/djc_helper/raw/master/CHANGELOG.MD\n\nclass Uploader:\n default_sub_domain = \"fzls\"\n default_main_domain = \"lanzoui\"\n default_domain = f\"{default_sub_domain}.{default_main_domain}.com\"\n\n folder_dnf_calc = Folder(\"魔改计算器\", \"1810329\", f\"https://{default_domain}/s/dnf-calc\", \"\")\n folder_djc_helper = Folder(\"蚊子腿小助手\", \"2290618\", f\"https://{default_domain}/s/djc-helper\", \"\")\n folder_history_files = Folder(\"历史版本\", \"2303716\", f\"https://{default_domain}/b01bp17zg\", \"\")\n folder_djc_helper_tools = Folder(\"蚊子腿小助手相关工具\", \"2291287\", f\"https://{default_domain}/s/djc-tools\", \"\")\n folder_online_files = Folder(\"在线文��存储\", \"2866929\", f\"https://{default_domain}/s/myfiles\", \"6tnk\")\n folder_online_files_history_files = Folder(\"历史版本\", \"2867307\", f\"https://{default_domain}/b01c143ah\", \"5r75\")\n\n history_version_prefix = \"DNF蚊子腿小助手_v\"\n history_patches_prefix = \"DNF蚊子腿小助手_增量更新文件_\"\n history_dlc_version_prefix = \"auto_updater.exe\"\n\n regex_version = r'DNF蚊子腿小助手_v(.+)_by风之凌殇.7z'\n regex_patches = r'DNF蚊子腿小助手_增量更新文件_v(.+)_to_v(.+).7z'\n\n # 保存购买了自动更新工具的用户信息\n buy_auto_updater_users_filename = \"buy_auto_updater_users.txt\"\n\n # 保存用户的付费信息\n user_monthly_pay_info_filename = \"user_monthly_pay_info.txt\"\n\n # 卡密操作的付费信息\n cs_used_card_secrets = \"_used_card_secrets.txt\"\n cs_buy_auto_updater_users_filename = \"cs_buy_auto_updater_users.txt\"\n cs_user_monthly_pay_info_filename = \"cs_user_monthly_pay_info.txt\"\n\n # 压缩版本的前后缀\n compressed_version_prefix = \"compressed_\"\n compressed_version_suffix = \".7z\"\n\n def __init__(self):\n self.lzy = LanZouCloud()\n self.login_ok = False\n\n def login(self, cookie):\n # 仅上传需要登录\n self.login_ok = self.lzy.login_by_cookie(cookie) == LanZouCloud.SUCCESS\n\n def upload_to_lanzouyun(self, filepath: str, target_folder: Folder, history_file_prefix=\"\", also_upload_compressed_version=False, only_upload_compressed_version=False) -> bool:\n if not self.login_ok:\n logger.info(\"未登录,不能上传文件\")\n return False\n\n if history_file_prefix == \"\":\n # 未设置历史文件前缀,默认为当前文件名\n history_file_prefix = os.path.basename(filepath)\n\n if not only_upload_compressed_version:\n ok = self._upload_to_lanzouyun(filepath, target_folder, history_file_prefix)\n if not ok:\n return False\n\n if also_upload_compressed_version:\n make_sure_dir_exists('.cached')\n filename = os.path.basename(filepath)\n compressed_filepath = os.path.join('.cached', self.get_compressed_version_filename(filename))\n compressed_history_file_prefix = f\"{self.compressed_version_prefix}{history_file_prefix}\"\n\n logger.info(color(\"bold_green\") + f\"创建压缩版本并上传 {compressed_filepath}\")\n # 创建压缩版本\n compress_file_with_lzma(filepath, compressed_filepath)\n # 上传\n return self._upload_to_lanzouyun(compressed_filepath, target_folder, compressed_history_file_prefix)\n\n return True\n\n def _upload_to_lanzouyun(self, filepath: str, target_folder: Folder, history_file_prefix) -> bool:\n if history_file_prefix == \"\":\n logger.error(\"未设置history_file_prefix\")\n return False\n\n filename = os.path.basename(filepath)\n logger.warning(f\"开始上传 {filename} 到 {target_folder.name}\")\n run_start_time = datetime.now()\n\n def on_uploaded(fid, is_file):\n if not is_file:\n return\n\n logger.info(f\"上传完成,fid={fid}\")\n\n folder_history_files = self.folder_history_files\n if target_folder.id == self.folder_online_files.id:\n folder_history_files = self.folder_online_files_history_files\n\n files = self.lzy.get_file_list(target_folder.id)\n for file in files:\n if file.name.startswith(history_file_prefix):\n self.lzy.move_file(file.id, folder_history_files.id)\n logger.info(f\"将{file.name}移动到目录({folder_history_files.name})\")\n\n logger.info(f\"将文件移到目录({target_folder.name})中\")\n self.lzy.move_file(fid, target_folder.id)\n\n # 上传到指定的文件夹中\n retCode = self.lzy.upload_file(filepath, -1, callback=self.show_progress, uploaded_handler=on_uploaded)\n if retCode != LanZouCloud.SUCCESS:\n logger.error(f\"上传失败,retCode={retCode}\")\n return False\n\n filesize = os.path.getsize(filepath)\n logger.warning(color(\"bold_yellow\") + f\"上传文件 {filename}({human_readable_size(filesize)}) 总计耗时{datetime.now() - run_start_time}\")\n\n return True\n\n def get_compressed_version_filename(self, filename: str) -> str:\n return f\"{self.compressed_version_prefix}{filename}{self.compressed_version_suffix}\"\n\n def latest_version(self) -> str:\n \"\"\"\n 返回形如\"1.0.0\"的最新版本信息\n \"\"\"\n latest_version_file = self.find_latest_version()\n\n return self.parse_version_from_djc_helper_file_name(latest_version_file.name)\n\n def parse_version_from_djc_helper_file_name(self, filename: str) -> str:\n \"\"\"\n 从小助手压缩包文件名中提取版���信息\n DNF蚊子腿小助手_v4.6.6_by风之凌殇.7z => v4.6.6\n \"\"\"\n match = re.search(self.regex_version, filename)\n if match is None:\n # 保底返回1.0.0\n return \"1.0.0\"\n\n return match.group(1)\n\n def download_latest_version(self, download_dir) -> str:\n \"\"\"\n 下载最新版本压缩包到指定目录,并返回最终压缩包的完整路径\n \"\"\"\n return self.download_file(self.find_latest_version(), download_dir)\n\n def find_latest_version(self) -> FileInFolder:\n \"\"\"\n 查找最新版本,如找到,返回lanzouyun提供的file信息,否则抛出异常\n \"\"\"\n folder_info = self.get_folder_info_by_url(self.folder_djc_helper.url)\n for file in folder_info.files:\n if file.name.startswith(self.history_version_prefix):\n return file\n\n raise FileNotFoundError(\"latest version not found\")\n\n def latest_patches_range(self):\n \"\"\"\n 返回形如(\"1.0.0\", \"1.1.2\")的补丁范围\n \"\"\"\n latest_patches_file = self.find_latest_patches()\n # DNF蚊子腿小助手_增量更新文件_v4.6.5_to_v4.6.6.7z\n match = re.search(self.regex_patches, latest_patches_file.name)\n if match is not None:\n version_left, version_right = match.group(1), match.group(2)\n return (version_left, version_right)\n\n # 保底返回\n return (\"1.0.0\", \"1.0.0\")\n\n def download_latest_patches(self, download_dir) -> str:\n \"\"\"\n 下载最新版本压缩包到指定目录,并返回最终压缩包的完整路径\n \"\"\"\n return self.download_file(self.find_latest_patches(), download_dir)\n\n def find_latest_patches(self) -> FileInFolder:\n \"\"\"\n 查找最新版本的补丁,如找到,返回lanzouyun提供的file信息,否则抛出异常\n \"\"\"\n folder_info = self.get_folder_info_by_url(self.folder_djc_helper.url)\n for file in folder_info.files:\n if file.name.startswith(self.history_patches_prefix):\n return file\n\n raise FileNotFoundError(\"latest patches not found\")\n\n def download_latest_dlc_version(self, download_dir) -> str:\n \"\"\"\n 下载最新版本dlc压缩包到指定目录,并返回最终压缩包的完整路径\n \"\"\"\n return self.download_file(self.find_latest_dlc_version(), download_dir)\n\n def find_latest_dlc_version(self) -> FileInFolder:\n \"\"\"\n 查找最新版本dlc,如找到,返回lanzouyun提供的file信息,否则抛出异常\n \"\"\"\n folder_info = self.get_folder_info_by_url(self.folder_djc_helper.url)\n for file in folder_info.files:\n if file.name.startswith(self.history_dlc_version_prefix):\n return file\n\n raise FileNotFoundError(\"latest version not found\")\n\n def download_file_in_folder(self, folder: Folder, name: str, download_dir: str, overwrite=True, show_log=True, try_compressed_version_first=False, cache_max_seconds=600) -> str:\n \"\"\"\n 下载网盘指定文件夹的指定文件到本地指定目录,并返回最终本地文件的完整路径\n \"\"\"\n\n def _download(fname: str) -> str:\n return with_cache(cache_name_download, os.path.join(folder.name, fname), cache_max_seconds=cache_max_seconds,\n cache_miss_func=lambda: self.download_file(self.find_file(folder, fname), download_dir, overwrite=overwrite, show_log=show_log),\n cache_validate_func=lambda target_path: os.path.isfile(target_path),\n )\n\n if try_compressed_version_first:\n # 先尝试获取压缩版本\n compressed_filename = self.get_compressed_version_filename(name)\n try:\n if show_log: logger.info(color(\"bold_green\") + f\"尝试优先下载压缩版本 {compressed_filename}\")\n # 下载压缩版本\n compressed_filepath = _download(compressed_filename)\n\n # 解压缩\n dirname = os.path.dirname(compressed_filepath)\n target_path = os.path.join(dirname, name)\n decompress_file_with_lzma(compressed_filepath, target_path)\n # 返回解压缩的文件路径\n return target_path\n except Exception as e:\n if show_log: logger.error(f\"下载压缩版本 {compressed_filename} 失败,将尝试普通版本~\", exc_info=e)\n\n # 下载普通版本\n return _download(name)\n\n def find_file(self, folder, name) -> FileInFolder:\n \"\"\"\n 在对应目录查找指定名称的文件,如找到,返回lanzouyun提供的file信息,否则抛出异常\n \"\"\"\n folder_info = self.get_folder_info_by_url(folder.url, folder.password)\n for file in folder_info.files:\n if file.name == name:\n return file\n\n raise FileNotFoundError(f\"file={name} not found in folder={folder.name}\")\n\n def download_file(self, fileinfo: FileInFolder, download_dir: str, overwrite=True, show_log=True) -> str:\n \"\"\"\n 下载最新版本压缩包到指定目录,并返回最终压缩包的完整路径\n \"\"\"\n if not os.path.isdir(download_dir):\n os.mkdir(download_dir)\n\n download_dir = os.path.realpath(download_dir)\n target_path = os.path.join(download_dir, fileinfo.name)\n\n def after_downloaded(file_name):\n \"\"\"下载完成后的回调函数\"\"\"\n target_path = file_name\n if show_log: logger.info(f\"最终下载文件路径为 {file_name}\")\n\n if show_log: logger.info(f\"即将开始下载 {target_path}\")\n callback = None\n if show_log: callback = self.show_progress\n retCode = self.down_file_by_url(fileinfo.url, \"\", download_dir, callback=callback, downloaded_handler=after_downloaded, overwrite=overwrite)\n if retCode != LanZouCloud.SUCCESS:\n if show_log: logger.error(f\"下载失败,retCode={retCode}\")\n if retCode == LanZouCloud.NETWORK_ERROR:\n if show_log: logger.warning(color(\"bold_yellow\") + (\n \"蓝奏云api返回网络错误,这很可能是由于dns的问题导致的\\n\"\n \"分别尝试在浏览器中访问下列两个网页,是否一个打的开一个打不开?\\n\"\n \"https://fzls.lanzoux.com/s/djc-helper\\n\"\n \"https://fzls.lanzous.com/s/djc-helper\\n\"\n \"\\n\"\n \"如果是这样,请按照下面这个链接,修改本机的dns,使用阿里、腾讯、百度、谷歌dns中的任意一个应该都可以解决。\\n\"\n \"https://www.ypojie.com/9830.html\\n\"\n \"\\n\"\n \"如果两个都打不开,大概率是蓝奏云挂了-。-可选择忽略后面的弹框,继续运行旧版本,或者手动去QQ群或github下载最新版本\"\n ))\n raise Exception(\"下载失败\")\n\n return target_path\n\n def show_progress(self, file_name, total_size, now_size):\n \"\"\"显示进度的回调函数\"\"\"\n percent = now_size / total_size\n bar_len = 40 # 进度条长总度\n bar_str = '>' * round(bar_len * percent) + '=' * round(bar_len * (1 - percent))\n show_percent = percent * 100\n now_mb = now_size / 1048576\n total_mb = total_size / 1048576\n print(f'\\r{show_percent:.2f}%\\t[{bar_str}] {now_mb:.2f}/{total_mb:.2f}MB | {file_name} ', end='')\n if total_size == now_size:\n print('') # 下载完成换行\n\n def get_folder_info_by_url(self, share_url, dir_pwd='', get_this_page=0) -> FolderDetail:\n for possiable_url in self.all_possiable_urls(share_url):\n folder_info = self.lzy.get_folder_info_by_url(possiable_url, dir_pwd, get_this_page=get_this_page)\n if folder_info.code != LanZouCloud.SUCCESS:\n logger.debug(f\"请求{possiable_url}失败,将尝试下一个\")\n continue\n\n return folder_info\n\n return FolderDetail(LanZouCloud.FAILED)\n\n def down_file_by_url(self, share_url, pwd='', save_path='./Download', *, callback=None, overwrite=False,\n downloaded_handler=None) -> int:\n for possiable_url in self.all_possiable_urls(share_url):\n retCode = self.lzy.down_file_by_url(possiable_url, pwd, save_path, callback=callback, overwrite=overwrite, downloaded_handler=downloaded_handler)\n if retCode != LanZouCloud.SUCCESS:\n logger.debug(f\"请求{possiable_url}失败,将尝试下一个\")\n continue\n\n return retCode\n\n return LanZouCloud.FAILED\n\n def all_possiable_urls(self, lanzouyun_url: str) -> List[str]:\n if self.default_main_domain not in lanzouyun_url:\n return [lanzouyun_url]\n\n return [\n # 目前网盘默认分享链接是这个,后面可以根据经验,哪个最靠谱,调整先后顺序\n # 可以使用下面这个网站测试各个域名的全国连通性\n # https://www.ping.cn/\n lanzouyun_url.replace(self.default_main_domain, 'lanzoui'),\n lanzouyun_url.replace(self.default_main_domain, 'lanzoux'),\n lanzouyun_url.replace(self.default_main_domain, 'lanzous'),\n ]\n\n\nif __name__ == '__main__':\n uploader = Uploader()\n\n # 不需要登录的接口\n logger.info(f\"最新版本为{uploader.latest_version()}\")\n # uploader.download_latest_version(\".cached\")\n\n logger.info(f\"最新增量补丁范围为{uploader.latest_patches_range()}\")\n logger.info(f\"最新增量补丁为{uploader.find_latest_patches()}\")\n uploader.download_latest_patches(\".cached\")\n\n uploader.download_file_in_folder(uploader.folder_online_files, uploader.cs_user_monthly_pay_info_filename, \".cached\", try_compressed_version_first=True)\n\n # 需要登录才能使用的接口\n test_login_functions = False\n if test_login_functions:\n with open(\"upload_cookie.json\") as fp:\n cookie = json.load(fp)\n uploader.login(cookie)\n if uploader.login_ok:\n # file = r\"D:\\_codes\\Python\\djc_helper_public\\utils\\bandizip_portable\\bz.exe\"\n # uploader.upload_to_lanzouyun(file, uploader.folder_djc_helper)\n # uploader.upload_to_lanzouyun(file, uploader.folder_dnf_calc)\n pass\n else:\n logger.error(\"登录失败\")\n","sub_path":"upload_lanzouyun.py","file_name":"upload_lanzouyun.py","file_ext":"py","file_size_in_byte":17005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"501082476","text":"#!/usr/bin/env python3\n\"\"\"\nCreated: Jan 19 2022\nAuthor: JustinTan (Python 3.4) & Yubo Su\n\nDescription: Work on related work https://arxiv.org/pdf/1402.1907.pdf\n\"\"\"\nfrom multiprocessing import Pool\nimport numpy as np\nimport matplotlib.pyplot as plt\n# YS: here are some matplotlib config options I like to use. They let you:\n# use latex in labels, larger font size, axis ticks face inwards on both\n# left/right/top/bottom\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif', size=20)\nplt.rc('xtick', direction='in', top=True, bottom=True)\nplt.rc('ytick', direction='in', left=True, right=True)\n\nfrom scipy.integrate import solve_ivp\nfrom scipy.interpolate import interp1d\nimport scipy.optimize as opt\nimport os, pickle, lzma\nfrom utils import *\n\n# YS: can just use pi from numpy, saves you an import\nPi = np.pi\nTAU = 1 #Myrs\ntf_mults = np.array([10]) # integration time (units of TAU)\nw_s = 0.1\nw_sd0 = 48.6 * 2 * Pi\n\nL_dS0_mass = 244\nL_pS0 = 0.5184\nL_b = np.array([0,0,1])\n\nNTHREADS = (os.cpu_count() // 3) * 2\n# tol = 1e-12\ntol = 1e-6\n# tol = 1e-9\n\n# YS: I personally prefer helper functions defined elsewhere in the code, so\n# they are easier to find (especially if they're used in multiple places), and\n# so that they don't clutter the flow of the code\ndef magnitude(A):\n return (A[0]**2+A[1]**2+A[2]**2)**0.5\ndef angle(A,B):\n normA = A/np.linalg.norm(A)\n normB = B/np.linalg.norm(B)\n dot = np.dot(normA,normB)\n return np.arccos(dot)\n# YS: a quick helper function to sort out the \"invalid arccos\" warning that\n# keeps popping up when calculating np.arccos(0/0)\ndef calcPhi(v):\n if v[0] == 0 and v[1] == 0: # phi isn't really defined, just return 0\n return 0\n return np.arccos(v[0]/(v[0]**2+v[1]**2)**(1/2))\n# YS: another quick helper function to suppress warnings because of floating\n# point errors if np.dot(S, L) is something like 1.000000000000000001\ndef regularized_dot(a, b):\n # coerce the dot product to be between -1 and 1\n return max(min(np.dot(a, b), 1), -1)\ndef get_thetaleftcrit(mp, ab, rin, ap, mult=1, etac=1, Mstar=1):\n '''\n calcs min theta where enough vertical angular momentum to tilt S\n\n mult = (1 - cos(qsbf)), typically ~1 unless qsbf is small\n '''\n w_db = 4.91 * 2 * Pi / (ab/300)**3 * (Mstar / 1)**(1/2)\n w_pb = 1 / 36 * 2 * Pi * ap**1.5/(ab/300)**3 * (Mstar / 1)**(1/2)\n w_sp = 0.0668 * 2 * Pi * (w_s/0.1)*mp/ap**3 / (Mstar / 1)**(1/2)\n L_pS = L_pS0*mp*ap**0.5/(w_s/0.1) / (Mstar / 1)\n L_dS0 = L_dS0_mass / (Mstar / 1)\n def eta_minus1(m):\n ''' returns eta - 1 '''\n w_sd = w_sd0 * m/0.1*(w_s/0.1)/rin**2 * (Mstar / 1)**(1/2)\n\n L_dS = L_dS0 * (m/0.1)/(w_s/0.1)\n\n SL = 1/(L_dS+L_pS)\n L_dL = L_dS * SL\n L_pL = L_pS * SL\n\n return (w_db * L_dL + w_pb * L_pL) / (w_sd + w_sp) - etac\n try:\n md_crit = opt.brenth(eta_minus1, 0, 0.1)\n L_dS = L_dS0 * (md_crit/0.1)/(w_s/0.1)\n SL = 1/(L_dS0 * (md_crit/0.1)/(w_s/0.1) + L_pS0*mp*ap**0.5/(w_s/0.1))\n return np.degrees(np.arccos(1 - SL * mult))\n except:\n return 0\n\ndef run_single(tLB, tSB, ntime,\n tau_disk=TAU, mp=1, ab=300, rin=1, ap=5, Mstar=1,\n return_full=False):\n # initial S and L(d) align, then try different angles, 5, 10, 20, etc.\n # final(disc gone) angle between D and B, S and B\n # note: vectors are unit vectors\n w_db = 4.91 * 2 * Pi / (ab/300)**3\n w_pb = 1 / 36 * 2 * Pi * ap**1.5/(ab/300)**3\n w_sp = 0.0668 * 2 * Pi * (w_s/0.1)*mp/ap**3\n L_pS = L_pS0*mp*ap**0.5/(w_s/0.1)\n\n def ode(t, Y):\n S = Y[ :3]\n L = Y[3: ]\n\n m = 0.1*np.exp(-t/tau_disk)\n w_sd = w_sd0 * m/0.1*(w_s/0.1)/rin**2\n\n L_dS = L_dS0_mass * (m/0.1)/(w_s/0.1) / (Mstar / 1)\n\n SL = 1/(L_dS+L_pS)\n L_dL = L_dS * SL\n L_pL = L_pS * SL\n\n dSdt = -(w_sd + w_sp) * np.dot(S,L) * np.cross(L,S)\n dLdt = (\n -(w_db * L_dL + w_pb * L_pL) * (np.dot(L,L_b) * np.cross(L_b,L))\n + (w_sd + w_sp) * SL * np.dot(S,L) * np.cross(L,S)\n )\n\n return np.concatenate((dSdt, dLdt))\n\n\n #initial conditions\n IC = [0.0,np.sin(tSB),np.cos(tSB),0.0,np.sin(tLB),np.cos(tLB)]\n #SOLVE\n all_tol = 1e-12\n ret = solve_ivp(ode, (0, ntime), IC,\n method='DOP853', atol=all_tol, rtol=all_tol)\n\n #post processing\n Sf = ret.y[ :3, -1]\n Lf = ret.y[3: , -1]\n\n if return_full:\n return ret\n\n # store final angle\n angleSL = np.degrees(np.arccos(regularized_dot(Sf, Lf)))\n angleSB = np.degrees(np.arccos(regularized_dot(Sf, L_b)))\n angleLB = np.degrees(np.arccos(regularized_dot(Lf, L_b)))\n phiL = calcPhi(Lf)\n phiS = calcPhi(Sf)\n if Sf[1] < 0:\n phiS = 2*Pi - phiS\n phiSL = (phiS - phiL)*180/Pi\n if phiSL < 0:\n phiSL = 360 + phiSL\n return angleSL, angleSB, angleLB, phiSL\n\n# YS: save the zoomed-in angles, so that it's easy to edit later\ndef run_for_case(plot=True, folder='tau1plots', tau_disk=TAU, npts=200,\n zoom_left=85, zoom_right=95, mp=1, ab=300, rin=1, ap=5,\n Mstar=1, point_sel='zoom', times=None, bg=None):\n if times is None:\n times = tf_mults * tau_disk\n os.makedirs(folder, exist_ok=True)\n npts_qt = npts // 4\n for ntime in times:\n # YS: calculate the final distributions for both zoomed-in and not-zoomed-in\n # case at the same time\n if point_sel == 'zoom':\n angles = np.sort(np.concatenate((\n np.linspace(0, 180, 2 * npts_qt),\n # YS: more points near 90, including 90 exactly once\n # -np.linspace(np.sqrt(90 - zoom_left), 0, npts_qt, endpoint=False)**2 + 90,\n # np.linspace(0, np.sqrt(zoom_right - 90), npts_qt + 1)**2 + 90,\n )))\n elif point_sel == 'cos':\n angles = np.degrees(np.arccos(np.linspace(-1, 1, npts)))\n else:\n raise ValueError('Unsupported point_sel %s' % point_sel)\n\n # YS: the `zeros_like` (and `ones_like` and `full_like`) functions are\n # helpful for creating similarly-sized arrays\n anglesSLx = np.zeros_like(angles)\n anglesSB = np.zeros_like(angles)\n anglesLB = np.zeros_like(angles)\n anglesSL = np.zeros_like(angles)\n\n # YS: I like to save the simulation data, so I don't have to re-integrate\n # each time I run the file. Here, we happen to want to use the raw values\n # anyway, so let's just use the existence of the text file to skip\n # simulations\n data_fn = '%s/time_%d.txt' % (folder, ntime)\n if not os.path.exists(data_fn):\n # YS: this trick is called \"string formatting\", where you insert a value\n # into a string without doing a bunch of stuff like\n # `\"string \" + str(1) + \" rest of string\"`\n # there are a few ways to do this in python, I use this one below out of\n # habit but I think everybody has their preference!\n print('Running for time %d' % ntime)\n args = [(tLB, tLB, ntime, tau_disk, mp, ab, rin, ap, Mstar) for tLB in np.radians(angles)]\n all_angles = []\n # for arg in args:\n # all_angles.append(run_single(*arg))\n with Pool(NTHREADS) as p:\n all_angles = p.starmap(run_single, args)\n anglesSL, anglesSB, anglesLB, anglesSLx = np.array(all_angles).T\n anglesSLx = np.unwrap(anglesSLx, period=360)\n\n # YS: write the data into the text file (using 7 digits)\n # note that I save `angles` as well, even though it's technically not\n # changed. I've found this to be convenient, e.g. if I change the\n # `angles` list in a way that is incompatible with the existing pkl\n # file, but this is personal preference\n np.savetxt(data_fn,\n (angles, anglesSL, anglesSB, anglesLB, anglesSLx),\n fmt='%.7f',\n header='rows are: theta_sb0, theta_slf, theta_sbf, theta_lbf, phi_slf, phi_sbf')\n\n # YS: for convenience, it is easier to plot all the times on a single plot. This\n # makes loading the data a bit of a pain; it is easy to imagine saving the data\n # more smartly (e.g. all in a single text file). But there may be some merit in\n # keeping the data for different dissipation times in different txt files, e.g.\n # to share to others!\n angles_by_time = []\n anglesSL_by_time = []\n anglesSB_by_time = []\n anglesLB_by_time = []\n anglesSLx_by_time = []\n for ntime in times:\n data_fn = '%s/time_%d.txt' % (folder, ntime)\n assert os.path.exists(data_fn), 'Data file %s not found' % data_fn\n\n print('Loading for time %d' % ntime)\n angles, anglesSL, anglesSB, anglesLB, anglesSLx = np.loadtxt(data_fn)\n angles_by_time.append(angles)\n anglesSL_by_time.append(anglesSL)\n anglesSB_by_time.append(anglesSB)\n anglesLB_by_time.append(anglesLB)\n anglesSLx_by_time.append(anglesSLx)\n\n # YS: for plots, I like to save them as png files instead of just\n # \"plt.show()\" since they're easier to use / reference down the line. I've\n # also added axis labels etc.\n # YS: also, it's easiest to define variables to store your plotting options\n # so that it's easy to change them all at once. The variable names I choose\n # are also accepted by plt.plot (e.g. plt.plot(..., linewidth=1) is the same\n # as plt.plot(..., lw=1)\n if plot == True:\n lw = 0.7\n marker = 'o'\n ms = 2\n fs = 14\n dpi = 400\n alpha = 0.7\n ls = '-'\n legfs = 14\n xticks = [0, 45, 90, 135, 180]\n xticklabels = [str(t) for t in xticks]\n yticks = [0, 90, 180]\n yticklabels = [str(t) for t in yticks]\n # YS: useful indicies for plotting the zoomed-in plots\n idx_left = np.searchsorted(angles, zoom_left)\n idx_right = np.searchsorted(angles, zoom_right)\n angles_left = angles[np.where(angles <= 90)[0]]\n angles_right = angles[np.where(angles >= 90)[0]]\n\n theta_leftcrit0 = get_thetaleftcrit(mp, ab, rin, ap, mult=0.5,\n Mstar=Mstar)\n theta_leftcrit90 = get_thetaleftcrit(mp, ab, rin, ap, etac=0.6,\n Mstar=Mstar)\n\n w_db = 4.91 * 2 * Pi / (ab/300)**3\n w_pb = 1 / 36 * 2 * Pi * ap**1.5/(ab/300)**3\n w_sp = 0.0668 * 2 * Pi * (w_s/0.1)*mp/ap**3\n L_pS = L_pS0*mp*ap**0.5/(w_s/0.1)\n w_sd = w_sd0 *(w_s/0.1)/rin**2\n L_dS = L_dS0_mass/(w_s/0.1)\n SL = 1/(L_dS+L_pS)\n L_dL = L_dS * SL\n L_pL = L_pS * SL\n etai = (w_db * L_dL + w_pb * L_pL) / (w_sd + w_sp)\n etaf = (w_pb) / (w_sp)\n I0ds = np.linspace(0.1, 89.9, 200)\n I0ds_right = 180 - I0ds\n I0s = np.radians(I0ds)\n mfs, Ifs, qsbfs = get_analsol(I0s, etai, SL)\n qsbf_ds = np.degrees(qsbfs)\n I_crit = 90 - theta_leftcrit90\n\n theta_vert = 90 - theta_leftcrit90 / np.sqrt(2)\n\n fig, (ax1, ax2, ax3) = plt.subplots(\n 3, 1,\n figsize=(7, 10),\n sharex=True)\n colors = ['tab:%s' % s for s in ['red', 'purple', 'green']]\n for ntime, anglesLB, anglesSB, anglesSL, c in zip(\n times, anglesLB_by_time, anglesSB_by_time, anglesSL_by_time, colors):\n if len(times) > 1:\n label = '%d Myr' % ntime\n else:\n label = 'Sim'\n ax1.plot(angles, anglesSB,\n linewidth=lw, marker=marker, markersize=ms, linestyle=ls,\n label=label, alpha=alpha, c=c)\n ax2.plot(angles,anglesLB,\n linewidth=lw, marker=marker, markersize=ms, linestyle=ls,\n label=label, alpha=alpha, c=c)\n if npts < 2000:\n ax3.plot(angles, anglesSL,\n linewidth=lw, marker=marker, markersize=ms,\n linestyle=ls, label=label, alpha=alpha, c=c)\n else:\n ax3.plot(angles, anglesSL,\n linewidth=0.7, linestyle=ls, label=label, alpha=alpha,\n c=c)\n\n # vert labels & labels\n for ax in [ax1, ax2, ax3]:\n # ax.axvline(theta_leftcrit0, c='g', ls=':')\n # ax.axvline(180 - theta_leftcrit0, c='g', ls=':')\n ax.set_yticks(xticks)\n ax.set_yticklabels(xticklabels)\n ax.set_ylim(0, 180)\n\n ax1.set_ylabel(r'$\\theta_{\\rm sb, f}$ [Deg]')\n # ax2.set_ylabel(r'$\\theta_{\\rm lb, f}$ [Deg]')\n ax2.set_ylabel(r'$I$ [Deg]')\n ax3.set_ylabel(r'$\\theta_{\\rm sl, f}$ [Deg]')\n ax3.set_xlabel(r'$I_0$ [Deg]')\n ax3.set_xticks(xticks)\n ax3.set_xticklabels(xticklabels)\n ax3.set_xlim(0, 180)\n\n # theory lines (ward)\n ward_left = np.degrees(np.arccos(\n 2 / (1 + np.tan(np.radians(angles_left))**(2/3))**(3/2) - 1))\n ward_right = np.degrees(np.arccos(\n 1 - 2 / (1 + np.tan(np.radians(180 - angles_right))**(2/3))**(3/2)))\n ax1.plot(angles_left, ward_left, 'k--', label='Th (simple)')\n ax1.plot(angles_right, ward_right, 'k--')\n ax2.plot(angles, angles, 'k--')\n ax3.plot(angles_left, np.abs(ward_left - angles_left), 'k--')\n ax3.plot(angles_right, np.abs(ward_right - angles_right), 'k--')\n ax3.plot(angles_left, np.minimum(\n ward_left + angles_left,\n 360 - (ward_left + angles_left)\n ), 'k--')\n ax3.plot(angles_right, np.minimum(\n ward_right + angles_right,\n 360 - (ward_right + angles_right)\n ), 'k--')\n # theory lines (improved)\n ax1.plot(I0ds, qsbf_ds, 'b', lw=2, label='Th. (L budget)')\n ax1.plot(I0ds_right, 180 - qsbf_ds, 'b', lw=2)\n ax2.plot(I0ds, np.degrees(Ifs), 'b', lw=2, label='Th. (L budget)')\n ax2.plot(I0ds_right, 180 - np.degrees(Ifs), 'b', lw=2)\n qsbf_d_rights = 180 - qsbf_ds\n ax3.plot(I0ds, np.abs(qsbf_ds - I0ds), 'b')\n ax3.plot(I0ds_right, np.abs(qsbf_d_rights - I0ds_right), 'b')\n ax3.plot(I0ds, np.minimum(\n qsbf_ds + I0ds,\n 360 - (qsbf_ds + I0ds)\n ), 'b')\n ax3.plot(I0ds_right, np.minimum(\n qsbf_d_rights + I0ds_right,\n 360 - (qsbf_d_rights + I0ds_right)\n ), 'b')\n\n ax1.legend(fontsize=fs, loc='lower left',\n bbox_to_anchor=(theta_leftcrit0, 0),\n bbox_transform=ax1.transData)\n plt.tight_layout()\n fig.subplots_adjust(hspace=0.08)\n plt.savefig('%s/YS_composite' % folder, dpi=dpi)\n plt.close()\n\n FC = bg\n fig = plt.figure(figsize=(8, 4), facecolor=FC)\n ax = plt.axes()\n ax.set_facecolor(FC)\n nbins = 30\n fig, axs = plt.subplots(\n len(times), 1,\n figsize=(8, 3 * len(times) + 3),\n sharex=True)\n if len(times) == 1:\n axs = [axs]\n for ntime, ax, anglesSL in zip(times, axs, anglesSL_by_time):\n n, bin_edges = np.histogram(np.cos(np.radians(anglesSL)), bins=nbins)\n bins = (bin_edges[ :-1] + bin_edges[1: ]) / 2\n ax.bar(bins, (n / npts) * nbins / 2, width=2 / nbins,\n color='tab:orange', label='Sim')\n ax.set_title('%d Myr' % ntime)\n ## compute analytic histograms\n # I < 90\n def cosd(q):\n return np.cos(np.radians(q))\n def arccosd(x):\n return np.degrees(np.arccos(x))\n qsl_ys_bot_i = interp1d(I0ds, np.abs(qsbf_ds - I0ds))\n qsl_ys_top_i = interp1d(I0ds, np.minimum(\n qsbf_ds + I0ds,\n 360 - (qsbf_ds + I0ds)\n ))\n qsl_ward_bot_i = interp1d(angles_left, np.abs(ward_left - angles_left))\n qsl_ward_top_i = interp1d(angles_left, np.minimum(\n ward_left + angles_left,\n 360 - (ward_left + angles_left)\n ))\n # choose a list of I values, uniformly spaced in cos(I) that can be\n # plugged into the interps above. For each I, choose n_t_vals equally\n # spaced in angle over the predicted cos(obliquity) interval, and add\n # to buckets weighted by the probability dist\n n_Ivals = 5000\n n_tvals = 1000\n n_obl_buckets = 5000\n obl_counts = np.zeros(n_obl_buckets)\n Ivals_an_hist = np.linspace(\n max(cosd(I0ds.max()), cosd(angles_left.max())),\n min(cosd(I0ds.min()), cosd(angles_left.min())), n_Ivals)\n all_cosI_vals_ys = np.zeros(n_Ivals * n_tvals)\n all_weights_ys = np.zeros(n_Ivals * n_tvals)\n all_cosI_vals_ward = np.zeros(n_Ivals * n_tvals)\n all_weights_ward = np.zeros(n_Ivals * n_tvals)\n for idx, I_an_hist in enumerate(Ivals_an_hist):\n cosI_bot_ys = cosd(qsl_ys_top_i(arccosd(I_an_hist)))\n cosI_top_ys = cosd(qsl_ys_bot_i(arccosd(I_an_hist)))\n cosI_bot_ward = cosd(qsl_ward_top_i(arccosd(I_an_hist)))\n cosI_top_ward = cosd(qsl_ward_bot_i(arccosd(I_an_hist)))\n cosI_vals_ys = np.linspace(\n cosI_bot_ys, cosI_top_ys, 2 * n_tvals + 1)[1::2]\n cosI_vals_ward = np.linspace(\n cosI_bot_ward, cosI_top_ward, 2 * n_tvals + 1)[1::2]\n # just need the unnormalized pdf, ~((xmin - x)(xmax - x))^(-1/2)\n weights_ys = (\n -(cosI_bot_ys - cosI_vals_ys) *\n (cosI_top_ys - cosI_vals_ys))**(-1/2)\n weights_ward = (\n -(cosI_bot_ward - cosI_vals_ward) *\n (cosI_top_ward - cosI_vals_ward))**(-1/2)\n weights_ys /= weights_ys.sum()\n weights_ward /= weights_ward.sum()\n all_cosI_vals_ys[idx * n_tvals:(idx + 1) * n_tvals] = cosI_vals_ys\n all_weights_ys[idx * n_tvals:(idx + 1) * n_tvals] = weights_ys\n all_cosI_vals_ward[idx * n_tvals:(idx + 1) * n_tvals] = cosI_vals_ward\n all_weights_ward[idx * n_tvals:(idx + 1) * n_tvals] = weights_ward\n bins_th = int(np.sqrt(len(all_weights_ys)) / 10)\n counts_ys, edges_ys = np.histogram(all_cosI_vals_ys,\n weights=all_weights_ys, bins=bins_th)\n counts_ward, edges_ward = np.histogram(all_cosI_vals_ward,\n weights=all_weights_ward,\n bins=bins_th)\n counts_ys *= 1 / counts_ys.max() # bins_th / (2 * np.sum(counts_ys))\n counts_ward *= 1 / counts_ward.max() # bins_th / (2 * np.sum(counts_ward))\n def etoc(e): # centers from edges\n return (e[1: ] + e[ :-1]) / 2\n for ax in axs:\n ax.plot(etoc(edges_ward), counts_ward, 'k--', label='Th (simple)')\n ax.plot(etoc(edges_ys), counts_ys, 'b', label='Th (L budget)')\n\n coslims = (1.05, -1.05)\n ax.set_xlim(*coslims)\n costicks = [1, 0.5, 0, -0.5, -1]\n costicklabels = ['%s' % str(x) for x in costicks]\n degticks = np.round(np.degrees(np.arccos(costicks)) / 10) * 10\n degticklabels = [r'$%d^\\circ$' % x for x in degticks]\n ax.set_xticks(costicks)\n ax.set_xticklabels(costicklabels)\n axs[0].set_ylabel('Prob')\n axs[0].legend()\n axs[-1].set_xlabel(r'$\\cos(\\theta_{\\rm sl})$')\n ax2 = axs[0].twiny()\n ax2.set_xticks(costicks)\n ax2.set_xticklabels(degticklabels)\n ax2.set_xlim(*coslims)\n ax2.set_xlabel(r'Obliquity [Deg]')\n\n plt.tight_layout()\n plt.savefig('%s/YS_hist' % folder, dpi=dpi)\n plt.close()\n\n if bg is None:\n plt.figure(figsize=(8, 6))\n else:\n plt.figure(figsize=(8, 5), facecolor=bg)\n I_crit = 90 - theta_leftcrit90\n\n for ntime, anglesSLx in zip(times, anglesSLx_by_time):\n plt.plot(angles, np.unwrap(anglesSLx,period=360),\n linewidth=lw, marker=marker, markersize=ms, linestyle=ls,\n label=label)\n plt.xlabel(r'$I_{\\rm i}$ [Deg]')\n plt.ylabel(r'$\\phi_{\\rm sl, f}$ [Deg]')\n if bg is None:\n if len(times) > 1:\n plt.legend(fontsize=legfs)\n plt.title(r'$\\tau_{\\rm d} = %d$ Myr' % tau_disk)\n plt.axvline(I_crit, c='k')\n plt.axvline(180 - I_crit, c='k')\n plt.tight_layout()\n if bg is None:\n plt.savefig('%s/phisl' % folder, dpi=dpi)\n else:\n plt.savefig('%s/phisl' % folder, dpi=dpi, facecolor=bg,\n transparent=True)\n plt.clf() # clear figure, but reuse it for later\n # YS: replot the zoomed-in figure\n for ntime, anglesSLx in zip(times, anglesSLx_by_time):\n plt.plot(angles[idx_left:idx_right],\n anglesSLx[idx_left:idx_right],\n marker=marker, markersize=ms,\n linestyle='', label=label)\n plt.xlabel(r'$I_{\\rm i}$ [Deg]')\n plt.ylabel(r'$\\phi_{\\rm sl, f}$ [Deg]')\n if bg is None:\n if len(times) > 1:\n plt.legend(fontsize=legfs)\n plt.title(r'$\\tau_{\\rm d} = %d$ Myr' % tau_disk)\n plt.tight_layout()\n if bg is None:\n plt.savefig('%s/phisl_zoom' % folder, dpi=dpi)\n else:\n plt.savefig('%s/phisl_zoom' % folder, dpi=dpi, facecolor=bg,\n transparent=True)\n plt.clf() # clear figure, but reuse it for later\n\n for ntime, anglesLB in zip(times, anglesLB_by_time):\n plt.plot(angles,anglesLB,\n linewidth=lw, marker=marker, markersize=ms, linestyle=ls,\n label=label)\n plt.plot(I0ds, np.degrees(Ifs), 'b', lw=2)\n plt.plot(I0ds_right, 180 - np.degrees(Ifs), 'b', lw=2)\n plt.plot(angles, angles, 'k--')\n plt.xlabel(r'$I_{\\rm i}$ [Deg]')\n plt.ylabel(r'$I_{\\rm f}$ [Deg]')\n # plt.axvline(theta_leftcrit0, c='g', ls='--')\n plt.xticks(xticks, labels=xticklabels)\n if bg is None:\n if len(times) > 1:\n plt.legend(fontsize=legfs)\n plt.title(r'$\\tau_{\\rm d} = %d$ Myr' % tau_disk)\n plt.axvline(I_crit, c='k')\n plt.axvline(180 - I_crit, c='k')\n plt.tight_layout()\n if bg is None:\n plt.savefig('%s/thetalb' % folder, dpi=dpi)\n else:\n plt.savefig('%s/thetalb' % folder, dpi=dpi, facecolor=bg,\n transparent=True)\n plt.clf()\n for ntime, anglesLB in zip(times, anglesLB_by_time):\n plt.plot(angles[idx_left:idx_right],anglesLB[idx_left:idx_right],\n linewidth=lw, marker=marker, markersize=ms, linestyle=ls,\n label=label)\n idx_I0_left = np.searchsorted(I0ds, zoom_left)\n plt.plot(I0ds[idx_I0_left:],\n np.degrees(Ifs)[idx_I0_left:], 'b', lw=2)\n plt.plot(I0ds_right[idx_I0_left:], 180 - np.degrees(Ifs)[idx_I0_left:],\n 'b', lw=2)\n plt.xlabel(r'$I_{\\rm i}$ [Deg]')\n plt.ylabel(r'$I_{\\rm f}$ [Deg]')\n if bg is None:\n if len(times) > 1:\n plt.legend(fontsize=legfs)\n plt.title(r'$\\tau_{\\rm d} = %d$ Myr' % tau_disk)\n plt.axhline(theta_vert, c='g', ls='--')\n plt.axhline(180 - theta_vert, c='g', ls='--')\n plt.tight_layout()\n if bg is None:\n plt.savefig('%s/thetalb_zoom' % folder, dpi=dpi)\n else:\n plt.savefig('%s/thetalb_zoom' % folder, dpi=dpi, facecolor=bg,\n transparent=True)\n plt.clf()\n\n for ntime, anglesSB in zip(times, anglesSB_by_time):\n plt.plot(angles,anglesSB, linewidth=lw, marker=marker,\n markersize=ms, linestyle=ls, label=label)\n # YS: plot analytic function\n plt.plot(\n angles_left,\n ward_left,\n 'k--')\n plt.plot(\n angles_right,\n ward_right,\n 'k--')\n plt.plot(I0ds, qsbf_ds, 'b', lw=2)\n plt.plot(I0ds_right, 180 - qsbf_ds, 'b', lw=2)\n # one more theory line, theta_cs2, i\n qcs2s = []\n for I0d in I0ds:\n qcs2s.append(find_cs(SL, etai, np.radians(I0d), 0, np.pi / 2))\n # plt.plot(I0ds, np.degrees(qcs2s), c='c')\n plt.xlabel(r'$I_{\\rm i}$ [Deg]')\n plt.ylabel(r'$\\theta_{\\rm sb, f}$ [Deg]')\n if bg is None:\n if len(times) > 1:\n plt.legend(fontsize=legfs)\n plt.title(r'$\\tau_{\\rm d} = %d$ Myr' % tau_disk)\n # plt.axvline(theta_leftcrit90, c='g', ls='--')\n # plt.axvline(theta_leftcrit90, c='g', ls=':')\n plt.xticks(xticks, labels=xticklabels)\n plt.axvline(I_crit, c='k')\n plt.axvline(180 - I_crit, c='k')\n plt.tight_layout()\n if bg is None:\n plt.savefig('%s/thetasb' % folder, dpi=dpi)\n else:\n plt.savefig('%s/thetasb' % folder, dpi=dpi, facecolor=bg,\n transparent=True)\n plt.clf()\n for ntime, anglesSB in zip(times, anglesSB_by_time):\n plt.plot(angles[idx_left:idx_right],anglesSB[idx_left:idx_right],\n linewidth=lw, marker=marker, markersize=ms,\n linestyle=ls, label=label)\n plt.xlabel(r'$I_{\\rm i}$ [Deg]')\n plt.ylabel(r'$\\theta_{\\rm sb, f}$ [Deg]')\n if bg is None:\n if len(times) > 1:\n plt.legend(fontsize=legfs)\n plt.title(r'$\\tau_{\\rm d} = %d$ Myr' % tau_disk)\n plt.tight_layout()\n if bg is None:\n plt.savefig('%s/thetasb_zoom' % folder, dpi=dpi)\n else:\n plt.savefig('%s/thetasb_zoom' % folder, dpi=dpi, facecolor=bg,\n transparent=True)\n plt.clf()\n\n for ntime, anglesSL in zip(times, anglesSL_by_time):\n plt.plot(angles,anglesSL, linewidth=lw, marker=marker,\n markersize=ms, linestyle=ls, label=label)\n plt.xlabel(r'$I_{\\rm i}$ [Deg]')\n plt.ylabel(r'$\\theta_{\\rm sl, f}$ [Deg]')\n if bg is None:\n if len(times) > 1:\n plt.legend(fontsize=legfs)\n plt.title(r'$\\tau_{\\rm d} = %d$ Myr' % tau_disk)\n # plt.axvline(theta_leftcrit90, c='g', ls='--')\n # plt.axvline(theta_leftcrit90, c='g', ls=':')\n plt.xticks(xticks, labels=xticklabels)\n plt.yticks(yticks, labels=yticklabels)\n # plt.axvline(I_crit, c='k')\n # plt.axvline(180 - I_crit, c='k')\n\n # plot anal ward\n # plt.plot(angles_left, np.abs(ward_left - angles_left), 'k--')\n # plt.plot(angles_right, np.abs(ward_right - angles_right), 'k--')\n # plt.plot(angles_left, np.minimum(\n # ward_left + angles_left,\n # 360 - (ward_left + angles_left)\n # ), 'k--')\n # plt.plot(angles_right, np.minimum(\n # ward_right + angles_right,\n # 360 - (ward_right + angles_right)\n # ), 'k--')\n\n # plot anal me\n qsbf_d_rights = 180 - qsbf_ds\n plt.plot(I0ds, np.abs(qsbf_ds - I0ds), 'g--')\n plt.plot(I0ds_right, np.abs(qsbf_d_rights - I0ds_right), 'g--')\n plt.plot(I0ds, np.minimum(\n qsbf_ds + I0ds,\n 360 - (qsbf_ds + I0ds)\n ), 'g--')\n plt.plot(I0ds_right, np.minimum(\n qsbf_d_rights + I0ds_right,\n 360 - (qsbf_d_rights + I0ds_right)\n ), 'g--')\n\n plt.xlim(0, 180)\n plt.ylim(0, 180)\n plt.xlabel(r'Disk-Binary Inclination [Deg]')\n # plt.xlabel(r'$I_0$ [Deg]')\n plt.ylabel(r'Obliquity [Deg]')\n # plt.ylabel(r'$\\theta_{\\rm sl, f}$ [Deg]')\n plt.tight_layout()\n if bg is None:\n plt.savefig('%s/thetasl' % folder, dpi=dpi)\n else:\n plt.savefig('%s/thetasl' % folder, dpi=dpi, facecolor=bg,\n transparent=True)\n plt.clf()\n for ntime, anglesSL in zip(times, anglesSL_by_time):\n plt.plot(angles[idx_left:idx_right],anglesSL[idx_left:idx_right],\n linewidth=lw, marker=marker, markersize=ms,\n linestyle=ls, label=label)\n if bg is None:\n if len(times) > 1:\n plt.legend(fontsize=legfs)\n plt.title(r'$\\tau_{\\rm d} = %d$ Myr' % tau_disk)\n plt.tight_layout()\n if bg is None:\n plt.savefig('%s/thetasl_zoom' % folder, dpi=dpi)\n else:\n plt.savefig('%s/thetasl_zoom' % folder, dpi=dpi, facecolor=bg,\n transparent=True)\n plt.clf()\n\ndef plot_single(basefn='sample0', rin=1, ab=300, mp=1, ap=5, Mstar=1,\n tau_disk=1, qlbi_d=30, tf=15, bg=(1, 1, 1),\n qlb_label=r'$\\theta_{\\rm lb}$', extra_vert=None):\n fn = '1sampleplots/' + basefn\n qlbi = np.radians(qlbi_d)\n ret = run_single(qlbi, qlbi, tf,\n rin=rin, ab=ab, mp=mp, tau_disk=tau_disk, ap=ap,\n Mstar=Mstar, return_full=True)\n anglesSB = []\n anglesLB = []\n anglesSL = []\n phisSL = []\n for idx in range(len(ret.t)):\n S = ret.y[ :3, idx]\n L = ret.y[3: , idx]\n anglesSB.append(np.degrees(np.arccos(regularized_dot(S, L_b))))\n anglesLB.append(np.degrees(np.arccos(regularized_dot(L, L_b))))\n anglesSL.append(np.degrees(np.arccos(regularized_dot(S, L))))\n\n phiL = calcPhi(L)\n phiS = calcPhi(S)\n phiSL = (phiS - phiL)*180/Pi\n phiSL = ((phiSL + 180) % 360) - 180\n phisSL.append(phiSL)\n\n m = 0.1 * np.exp(-ret.t / tau_disk)\n\n w_db = 4.91 * 2 * Pi / (ab/300)**3\n w_pb = 1 / 36 * 2 * Pi * ap**1.5/(ab/300)**3\n w_sp = 0.0668 * 2 * Pi * (w_s/0.1)*mp/ap**3\n L_pS = L_pS0*mp*ap**0.5/(w_s/0.1)\n\n w_sd = w_sd0 * m/0.1*(w_s/0.1)/rin**2\n\n L_dS = L_dS0_mass * (m/0.1)/(w_s/0.1) / (Mstar / 1)\n\n SL = 1/(L_dS+L_pS)\n L_dL = L_dS * SL\n L_pL = L_pS * SL\n\n wlb = w_db * L_dL + w_pb * L_pL\n wsl = w_sd + w_sp\n eta0 = wlb / wsl\n eta = eta0 * np.cos(np.radians(anglesLB))\n\n # fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(\n # 3, 2,\n # figsize=(11, 8))\n # t = ret.t / tau_disk\n # ax1.plot(t, anglesSB)\n # ax2.plot(t, anglesLB)\n # ax3.semilogy(t, SL)\n # ax4.semilogy(t, eta)\n # ax1.set_ylabel(r'$\\theta_{\\rm sb}$')\n # ax2.set_ylabel(r'$\\theta_{\\rm lb}$')\n # ax3.set_ylabel(r'$S / L$')\n # ax4.set_ylabel(r'$\\eta = \\eta_0 \\cos \\theta_{\\rm lb}$')\n\n # # ax1.set_xlabel(r'$t / \\tau_{\\rm d}$')\n # # ax2.set_xlabel(r'$t / \\tau_{\\rm d}$')\n # ax3.set_xlabel(r'$t / \\tau_{\\rm d}$')\n # ax4.set_xlabel(r'$t / \\tau_{\\rm d}$')\n\n # ax5.semilogy(t, w_db * L_dL)\n # ax5.semilogy(t, w_pb * L_pL)\n # # ax6.semilogy(t, w_sd)\n # # ax6.semilogy(t, np.full_like(t, w_sp))\n\n # # ax5.loglog(SL, eta)\n # # ax5.set_xlabel(r'$S / L$')\n # # ax5.set_ylabel(r'$\\eta$')\n # ax6.plot(t, anglesSL)\n # ax6.set_ylabel(r'$\\theta_{\\rm sl}$')\n\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(\n 4, 1,\n figsize=(6, 10),\n gridspec_kw={'height_ratios': [2, 1, 1, 1]},\n sharex=True)\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(\n 4, 1,\n figsize=(6, 10),\n gridspec_kw={'height_ratios': [2, 1, 1, 1]},\n sharex=True)\n t = ret.t\n ax1.plot(t, anglesLB, c='tab:orange', label=qlb_label)\n ax1.plot(t, anglesSB, c='tab:green', label=r'$\\theta_{\\rm sb}$')\n ax1.plot(t, anglesSL, c='tab:blue', label=r'$\\theta_{\\rm sl}$')\n\n # np.savetxt('/tmp/save.txt',\n # (t, anglesLB, anglesSB, anglesSL),\n # fmt='%.7f',\n # header='t, thetaLB, thetaSB, thetaSL')\n ax1.set_ylabel(r'Deg')\n yticks = [0, 45, 90, 135, 180]\n yticklabels = [str(t) for t in yticks]\n ax1.set_yticks(yticks)\n ax1.set_yticklabels(yticklabels)\n ax1.legend(fontsize=14, ncol=2, loc='upper right')\n ax1.set_ylim(0, 180)\n\n ax2.plot(t, phisSL, c='k')\n ax2.set_ylabel(r'$\\phi_{\\rm sl}$')\n eject_idx = np.where(np.abs(np.unwrap(phisSL, discont=180)) > 30)[0][0]\n ax2.set_ylim(-180, 180)\n ticks4 = [-180, -90, 0, 90, 180]\n ticks4labels = ['%d' % t for t in ticks4]\n ax2.set_yticks(ticks4)\n ax2.set_yticklabels(ticks4labels)\n\n eta = wlb / wsl * np.cos(np.radians(anglesLB))\n ax3.semilogy(t, SL, 'k', label=r'$S / L$')\n ax3.semilogy(t, eta, 'tab:blue', label=r'$\\eta$')\n ax3.legend(fontsize=14)\n ax3.set_ylim(1e-2 / 4, 4e2)\n ax3.set_yticks([1e-2, 1, 1e2])\n ax3.set_yticklabels([r'$10^{-2}$', r'$10^0$', r'$10^2$'])\n\n ax4.semilogy(t, wsl, c='tab:blue', label=r'$\\omega_{\\rm sl}$')\n ax4.semilogy(t, wlb, c='tab:orange', label=r'$\\omega_{\\rm lb}$')\n ax4.set_ylabel(r'Freq [Myr$^{-1}$]')\n ax4.legend(fontsize=14)\n\n xticks = [0, 5, 10, 15]\n xticklabels = [str(t) for t in xticks]\n ax4.set_xticks(xticks)\n ax4.set_xticklabels(xticklabels)\n ax4.set_xlim(0, tf)\n ax4.set_xlabel(r'$t$ [Myr]')\n ax4.set_ylim(1e-3, 1e3)\n for ax in [ax1, ax2, ax3, ax4]:\n ylims = ax.get_ylim()\n ax.fill_betweenx([ylims[0] - 100, ylims[1] + 100],\n [0] * 2,\n [t[eject_idx]] * 2,\n color='k', alpha=0.1)\n ax.set_ylim(ylims)\n\n # if extra_vert is not None:\n # ax1.axvline(extra_vert, c='k', ls='--')\n # ax2.axvline(extra_vert, c='k', ls='--')\n # ax3.axvline(extra_vert, c='k', ls='--')\n\n # ax1.set_facecolor(bg)\n\n plt.tight_layout()\n fig.subplots_adjust(hspace=0.13)\n plt.savefig(fn, facecolor=bg, dpi=400)\n plt.close()\n\nif __name__ == '__main__':\n # run_for_case(zoom_left=87, zoom_right=93, tau_disk=3,\n # folder='tau3plots', npts=1000)\n # run_for_case(zoom_left=87, zoom_right=93, npts=1000)\n # run_for_case(zoom_left=87, zoom_right=93, npts=1000, Mstar=1.4,\n # folder='fdwarf')\n # run_for_case(zoom_left=87, zoom_right=93, ab=150, npts=1000, Mstar=1.4,\n # folder='fdwarf150')\n # run_for_case(zoom_left=87, zoom_right=93, npts=1000, ab=150,\n # folder='tau150plots')\n # run_for_case(zoom_left=87, zoom_right=93, tau_disk=3,\n # folder='tau3plots', npts=1000)\n # run_for_case(zoom_left=87, zoom_right=93, tau_disk=3,\n # folder='tau3plots', npts=1000)\n # run_for_case(zoom_left=87, zoom_right=93, tau_disk=6,\n # folder='tau6plots', npts=1000)\n # run_for_case(zoom_left=87, zoom_right=93, tau_disk=3,\n # folder='tau3plots_smallab', npts=1000, ab=250)\n # run_for_case(zoom_left=87, zoom_right=93, tau_disk=3,\n # folder='tau3plots_smallerab', npts=1000, ab=200)\n # run_for_case(zoom_left=87, zoom_right=93, tau_disk=3,\n # folder='tau3plots_biggerrin', npts=1000, rin=1.2)\n run_for_case(zoom_left=87, zoom_right=93, npts=20000, point_sel='cos',\n folder='tau_uniform', times=[8, 10, 15], bg='#ffffff')\n\n # os.makedirs('1sampleplots/', exist_ok=True)\n # plot_single(basefn='sample', qlbi_d=20, qlb_label=r'$I$')\n # plot_single(basefn='sample_dda', tau_disk=3)\n # plot_single(basefn='sample_biggerrin', rin=1.2)\n # plot_single(basefn='sample_smallab', ab=250)\n # plot_single(basefn='sample_smallerab', ab=200)\n # plot_single(basefn='sample_ab150', ab=150, qlbi_d=50)\n # plot_single(basefn='sample_ab300_mid', ab=300, qlbi_d=50)\n # plot_single(basefn='YS_sample', Mstar=1.4, tf=10, qlbi_d=100)\n\n # run_for_case(zoom_left=80, zoom_right=100, npts=1000,\n # ap=0.1, mp=0.0064, folder='tautesto',\n # tau_disk=3, times=[30, 45])\n # plot_single(basefn='sample_testo', ap=0.1, mp=0.0064,\n # qlbi_d=10, tau_disk=1, tf=30)\n # plot_single(basefn='sample_testo50', ap=0.1, mp=0.0064,\n # qlbi_d=50, tau_disk=1, tf=30)\n # run_for_case(zoom_left=80, zoom_right=100, npts=1000, ab=500,\n # folder='tau500plots', times=[10])\n","sub_path":"scripts/justin_code/1justincode.py","file_name":"1justincode.py","file_ext":"py","file_size_in_byte":36249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"382295017","text":"# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n\t# @return a list of tree node\n\tdef generateTrees(self, n):\n\t\treturn self.generate(1, n)\n\n\tdef generate(self, start, end):\n\t\troots = []\n\t\tif start > end:\n\t\t\troots.append(None)\n\t\t\treturn roots\n\n\t\tfor i in range(start, end + 1):\n\t\t\tleft = self.generate(start, i - 1)\n\t\t\tright = self.generate(i + 1, end)\n\t\t\tfor l in left:\n\t\t\t\tfor r in right:\n\t\t\t\t\troot = TreeNode(i)\n\t\t\t\t\troot.left = l\n\t\t\t\t\troot.right = r\n\t\t\t\t\troots.append(root)\n\n\t\treturn roots \n","sub_path":"src/main/python/lc/unique_bst_2.py","file_name":"unique_bst_2.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"624798447","text":"import random\nimport math\nfrom player import Player\nfrom monster import Monster\nfrom d20 import D20\n\nclass Combat:\n enemyTypes = [\"skeleton\", \"orc\"]\n\n def getEnemy():\n return random.choice(Combat.enemyTypes)\n\n def fightEnemy():\n rnd = random.randrange(1000)\n enemy = Combat.getEnemy()\n if enemy == \"skeleton\":\n enemy = Monster.Skeleton()\n print(\"\\nYou encounter a Skeleton!\")\n elif enemy == \"orc\":\n enemy = Monster.Orc()\n print(\"\\nYou encounter an Orc!\")\n turn = Combat.getInitiative(enemy)\n while Player.currentHealth >= 1 and enemy.hp >= 1:\n if turn == \"Monster\":\n enemyDamage = D20.roll20(enemy.damage[0],enemy.damage[1]) + enemy.damage[2]\n print(enemy.name, \"hits you for\", enemyDamage, \"damage!\")\n Player.currentHealth = Player.currentHealth - enemyDamage\n turn = \"Player\"\n if Player.currentHealth <= 0:\n Player.isAlive = False\n elif turn == \"Player\":\n playerDamage = D20.roll20(Player.Inventory.rightArm.damage[0],Player.Inventory.rightArm.damage[1]) + Player.Inventory.rightArm.damage[2] + Player.strength_modifier\n print(\"You hit\", enemy.name, \"for\", playerDamage, \"damage!\")\n enemy.hp = enemy.hp - playerDamage\n turn = \"Monster\"\n if enemy.hp <= 0:\n Player.xp = int(Player.xp) + int(enemy.xp_value)\n print(\"You defeated the\", enemy.name, \"and gained\", enemy.xp_value, \"xp!\")\n if rnd >= 900:\n Player.hasKey = True\n print(\"You found a Key!\")\n\n def getInitiative(enemy):\n PI = D20.roll20(1,20) + Player.dexterity_modifier\n MI = D20.roll20(1,20) + math.floor((int(enemy.dexterity) / 2)) - 5\n if PI > MI:\n return \"Player\"\n else:\n return \"Monster\"\n","sub_path":"combat.py","file_name":"combat.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129678104","text":"import random\nclass Library:\n def __init__(self):\n self.available = {}\n self.patrons = {}\n\n def addBook(self, name):\n self.available[name] = \"Available\"\n\n def addPatron(self, name):\n patronExists = False\n for key in self.patrons:\n if patrons[key] == name:\n patronExists = True\n if (patronExists == False):\n keyGen = genActNum()\n while keyGen in self.patrons:\n keyGen = genActNum()\n self.patrons[keyGen] = name\n print(\"Account created for: \" + name)\n\n else:\n print(\"Patron already has an account\")\n\n def checkOut(self, name):\n if name in self.patrons:\n if(self.available[name] == \"Available\"):\n self.available[name] = \"Unavailable\"\n else:\n print(name + \"is currently unavailable for check-out\")\n else:\n print(\"The account does not exist\")\n\ndef genActNum(self, patrons):\n number = random.randint((10 ** 4), ((10 ** 4) - 1))\n return number\n\nclass Patron:\n def __init__(self, name):\n self.name = name\n self.booklist = []\n\n\n\n\n\ndef main():\n response = \"\"\n while (response != \"4\"):\n response = input(\"1. create account\\n2. checkout\\n3. Return book\\n4. quit\")\n if(response == \"1\"):\n name = input(\"Enter a name: \")\n Library.addPatron(name)\n elif(response ==\"2\"):\n title = input(\"Enter the title of the book: \")\n Library.checkOut(title)\n elif(response == \"3\"):\n title = input(\"Enter the title of the book: \")\n Library.addBook(title)\n else:\n print(\"Invalid Response\")\nmain()","sub_path":"1114 labs/lab13/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"607054913","text":"\"\"\"Rules and rule parsing for the failure simulator\n\nRValue: Base class for referencable values\nRValueProperty: Referencable value from the managers name table\nRValueLiteral: Referencable literal (float, or string)\nTrigger: Base class for triggers of a rule\nTriggerTrue: Trigger that always triggers\nTriggerSimpleComparison: Trigger for a single comparison (e.g.: tick <= 4 )\nTriggerNot: Trigger negating an incorporated trigger\nTriggerParen: Trigger that has been parsen within parenthesis\nTriggerAnd: Trigger that triggers only if all incorporated triggers trigger\nTriggerOr: Trigger that triggers only if any incorporated trigger triggers\nRuleOptions: Options of a rule\nAction: Base class for actions that can be triggered by rules\nSimpleAction: Single action (with 0, ..., n or without parameters)\nRuleParser: Parsing of rules, triggers, options, and actions\nRule: Single rule\n\"\"\"\n\nimport signal\nimport traceback\nimport token\nimport tokenize\nimport StringIO\nimport fs_logging\n\n\n\n# RValues ------------------------------------------------------------------------\n\n\n\nclass RValue():\n\n\t\"\"\"Value that can be arbirarily complex to compute, but cannot get assigned to\n\n\tRValues are the basic building blocks of triggers for rules,\n\tand can be used as arguments for actions.\n\t\"\"\"\n\n\tdef __init__( self ):\n\t\t\"\"\"Common initialization for all RValues\"\"\"\n\t\tpass\n\n\tdef get_value( self, manager ):\n\t\t\"\"\"Evaluation of the RValue to a value usable in python.\n\n\t\tSo typically an integer, float, string is returned.\n\n\t\tmanager: The failure simulation manager that should be\n\t\t used for evaluation\n\t\t\"\"\"\n\t\traise RuntimeError( \"unimplemented\" )\n\n\tdef get_names( self ):\n\t\t\"\"\"This function returns a frozenset of property names\n\t\tthat this RValue depends on.\n\n\t\tIf self models\n\t\t'(tickerA < tunnel.connection_0.alive) and (tickerA > 6)'\n\t\tthis function would return\n\t\tfrozenset([ \"tickerA\", \"tunnel.connection_0.alive\" ]).\n\t\t\"\"\"\n\t\treturn frozenset()\n\n\tdef __str__( self ):\n\t\t\"\"\"Conversion of the RValue to a string\"\"\"\n\t\traise RuntimeError( \"unimplemented\" )\n\n\n\nclass RValueProperty( RValue ):\n\n\t\"\"\"Class for RValues representing properties of the manager\"\"\"\n\n\tdef __init__( self, name ):\n\t\tRValue.__init__( self )\n\t\tself._name = name\n\n\tdef get_value( self, manager ):\n\t\treturn manager.get_value( self._name )\n\n\tdef get_names( self ):\n\t\treturn frozenset( [ self._name ] )\n\n\tdef __str__( self ):\n\t\treturn str( self._name )\n\n\n\nclass RValueLiteral( RValue ):\n\n\t\"\"\"Class for literal RValues\"\"\"\n\n\tdef __init__( self, value ):\n\t\tRValue.__init__( self )\n\t\tself._value = value\n\n\tdef get_value( self, manager ):\n\t\treturn self._value\n\n\tdef __str__( self ):\n\t\treturn str( self._value )\n\n\n\n# Trigger ------------------------------------------------------------------------\n\n\n\nclass Trigger():\n\n\t\"\"\"Base class for triggers as used in rules\"\"\"\n\n\tdef __init__( self ):\n\t\t\"\"\"Common initialization for all triggers\"\"\"\n\t\tpass\n\n\tdef get_names( self ):\n\t\t\"\"\"This function returns a frozenset of property names\n\t\tthat this RValue depends on.\n\n\t\tIf self models\n\t\t'(tickerA < tunnel.connection_0.alive) and (tickerA > 6)'\n\t\tthis function would return\n\t\tfrozenset([ \"tickerA\", \"tunnel.connection_0.alive\" ]).\n\t\t\"\"\"\n\t\treturn frozenset()\n\n\tdef matches( self, manager ):\n\t\t\"\"\"This function yields true if the trigger is fulfilled\n\n\t\tmanager: The manager of the failure simulation that\n\t\t should be used when evaluating used RValues\n\t\t\"\"\"\n\t\traise RuntimeError( \"unimplemented\" )\n\n\n\nclass TriggerTrue( Trigger ):\n\n\t\"\"\"Trigger that always fires\"\"\"\n\n\tdef matches( self, manager ):\n\t\treturn True\n\n\tdef __str__( self ):\n\t\treturn \"\"\n\n\n\nclass TriggerSimpleComparison( Trigger ):\n\n\t\"\"\"Trigger modelling a simple comparison\"\"\"\n\n\tdef __init__( self, lhs, rel, rhs ):\n\t\t\"\"\"Initialization.\n\n\t\tlhs: RValue holding the left-hand side of the comparison.\n\t\trel: The comparison operator as string. One of '<',\n\t\t '<=', '==', '!=', '>=', '>' with the usual semantics.\n\t\trhs: RValue holding the right-hand side of the comparison.\n\t\t\"\"\"\n\t\tTrigger.__init__( self )\n\t\tself._lhs = lhs\n\t\tself._rel_str = rel\n\t\tif rel == '<':\n\t\t\tself._rel = 0\n\t\telif rel == '<=':\n\t\t\tself._rel = 1\n\t\telif rel == '==':\n\t\t\tself._rel = 2\n\t\telif rel == '!=':\n\t\t\tself._rel = 3\n\t\telif rel == '>=':\n\t\t\tself._rel = 4\n\t\telif rel == '>':\n\t\t\tself._rel = 5\n\t\telse:\n\t\t\traise RuntimeError( \"No supported operator passed\" )\n\t\tself._rhs = rhs\n\n\tdef get_names( self ):\n\t\treturn self._lhs.get_names().union( self._rhs.get_names() )\n\n\tdef matches( self, manager ):\n\t\tlhs = self._lhs.get_value( manager )\n\t\trhs = self._rhs.get_value( manager )\n\n\t\t# If one argument is a string, and the other is not,\n\t\t# the string probably should be interpreted as number\n\t\t# as well\n\t\tif type( lhs ).__name__ == \"str\" and type( rhs ).__name__ != \"str\" and rhs is not None:\n\t\t\tlhs = float( lhs )\n\t\tif type( lhs ).__name__ != \"str\" and type( rhs ).__name__ == \"str\" and lhs is not None:\n\t\t\trhs = float( rhs )\n\n\t\tif self._rel == 0:\n\t\t\treturn lhs < rhs\n\t\telif self._rel == 1:\n\t\t\treturn lhs <= rhs\n\t\telif self._rel == 2:\n\t\t\treturn lhs == rhs\n\t\telif self._rel == 3:\n\t\t\treturn lhs != rhs\n\t\telif self._rel == 4:\n\t\t\treturn lhs >= rhs\n\t\telif self._rel == 5:\n\t\t\treturn lhs > rhs\n\t\traise RuntimeError( \"Unsupported setting of relational operator\" )\n\n\tdef __str__( self ):\n\t\treturn \"%s %s %s\" % ( self._lhs, self._rel_str, self._rhs)\n\n\n\nclass TriggerNot( Trigger ):\n\n\t\"\"\"Trigger modelling a negation of another Trigger\"\"\"\n\n\tdef __init__( self, subtrigger ):\n\t\t\"\"\"Initialization.\n\n\t\tsubtrigger: The trigger that gets negated\n\t\t\"\"\"\n\t\tTrigger.__init__( self )\n\t\tself._subtrigger = subtrigger\n\n\tdef get_names( self ):\n\t\treturn self._subtrigger.get_names()\n\n\tdef matches( self, manager ):\n\t\treturn not self._subtrigger.matches( manager )\n\n\tdef __str__( self ):\n\t\treturn \"not \" + str(self._subtrigger)\n\n\n\nclass TriggerParen( Trigger ):\n\n\t\"\"\"Trigger modelling parenthesis around a Trigger\n\n\tThis trigger not necessary for grouping, but is solely used to\n\trender parentheses around the wrapped trigger for textual\n\toutput.\n\t\"\"\"\n\n\tdef __init__( self, subtrigger ):\n\t\t\"\"\"Initialization.\n\n\t\tsubtrigger: The trigger that gets wrapped in parentheses\n\t\t\"\"\"\n\t\tTrigger.__init__( self )\n\t\tself._subtrigger = subtrigger\n\n\tdef get_names( self ):\n\t\treturn self._subtrigger.get_names()\n\n\tdef matches( self, manager ):\n\t\treturn self._subtrigger.matches( manager )\n\n\tdef __str__( self ):\n\t\treturn \"( \" + str(self._subtrigger) + \" )\"\n\n\n\nclass TriggerAnd( Trigger ):\n\n\t\"\"\"Conjunction of arbitrarily many triggers\n\n\tThe conjunction of the empty set of triggers always fires.\n\t\"\"\"\n\n\tdef __init__( self, subtriggers ):\n\t\t\"\"\"Initialization.\n\n\t\tsubtriggers: The list of triggers over which the\n\t\t conjunction shall govern\n\t\t\"\"\"\n\t\tTrigger.__init__( self )\n\t\tself._subtriggers = subtriggers\n\n\tdef get_names( self ):\n\t\tret = set()\n\t\tfor subtrigger in self._subtriggers:\n\t\t\tret |= subtrigger.get_names()\n\t\treturn frozenset( ret )\n\n\tdef matches( self, manager ):\n\t\tfor subtrigger in self._subtriggers:\n\t\t\tif not subtrigger.matches( manager ):\n\t\t\t\treturn False\n\t\treturn True\n\n\tdef __str__( self ):\n\t\treturn \" and \".join( map( str, self._subtriggers ) )\n\n\n\nclass TriggerOr( Trigger ):\n\n\t\"\"\"Disjunction of arbitrarily many triggers\n\n\tThe Disjunction of the empty set of triggers never fires.\n\t\"\"\"\n\n\tdef __init__( self, subtriggers ):\n\t\t\"\"\"Initialization.\n\n\t\tsubtriggers: The list of triggers over which the\n\t\t disjunction shall govern\n\t\t\"\"\"\n\t\tTrigger.__init__( self )\n\t\tself._subtriggers = subtriggers\n\n\tdef get_names( self ):\n\t\tret = set()\n\t\tfor subtrigger in self._subtriggers:\n\t\t\tret |= subtrigger.get_names()\n\t\treturn frozenset( ret )\n\n\tdef matches( self, manager ):\n\t\tfor subtrigger in self._subtriggers:\n\t\t\tif subtrigger.matches( manager ):\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef __str__( self ):\n\t\treturn \" or \".join( map( str, self._subtriggers ) )\n\n\n\n# Options for rules --------------------------------------------------------------\n\n\n\nclass RuleOptions():\n\n\t\"\"\"Options that can be set/reset for a rule.\n\n\tCurrently, there is only the 'multiple' option.\n\n\tmultiple: (default:False) If False, the rule's trigger can\n\t fire only once. If True, the rule can very arbitrarily many\n\t times.\n\t\"\"\"\n\n\tdef __init__( self ):\n\t\t\"\"\"Initialization\"\"\"\n\t\tself._multiple = False\n\n\tdef get_multiple( self ):\n\t\t\"\"\"Getter for the 'multiple' option\"\"\"\n\t\treturn self._multiple\n\n\tdef set_multiple( self, multiple = True ):\n\t\t\"\"\"Setter for the 'multiple' option\"\"\"\n\t\tself._multiple = multiple\n\n\tdef __str__( self ):\n\t\t\"\"\"Conversion to string\"\"\"\n\t\treturn \"multiple\" if self._multiple else \"\"\n\n\n\n# Actions ------------------------------------------------------------------------\n\n\n\nclass Action():\n\n\t\"\"\"Base class for actions that should be executed, once a\n\trule's trigger fires.\n\t\"\"\"\n\n\tdef __init__( self ):\n\t\t\"\"\"Common initialization for all actions\"\"\"\n\t\tpass\n\n\tdef execute( self, manager ):\n\t\t\"\"\"This function performs the action.\n\n\t\tThis function is called if the action shall do it's\n\t\tduty. Override it to implement a new kind of action.\n\n\t\tmanager: The failure simulation manager that should be\n\t\t used for evaluation\n\t\t\"\"\"\n\t\traise RuntimeError( \"unimplemented\" )\n\n\n\nclass SimpleAction( Action ):\n\n\t\"\"\"Single, simple, plain action to be triggered, if a rule's\n\ttrigger fires.\n\t\"\"\"\n\n\tdef __init__( self, name, parameters = None ):\n\t\t\"\"\"Initialization.\n\n\t\tname: A string holding the name of the action that\n\t\t shall be called (e.g.: 'tickerA.start'). This name\n\t\t will get mapped to a Python function by the manager.\n\t\tparameters: None, or a (possibly empty) list of\n\t\t RValue's whose evaluation gets passed as parameters\n\t\t to the action specified in the 'name' parameter.\n\t\t\"\"\"\n\t\tAction.__init__( self )\n\t\tself._name=name\n\t\tself._parameters=parameters\n\n\tdef execute( self, manager ):\n\t\tparameters = None\n\n\t\tif self._parameters is None:\n\t\t\tparameters = None # We already did this above. But to have a same\n\t\t\t# if cascade (while still not omittig above fallback initialization),\n\t\t\t#we repeat it\n\t\telse:\n\t\t\tparameters = [ parameter.get_value( manager ) for parameter in self._parameters ]\n\n\t\tmanager.execute_simple_action( self._name, parameters )\n\n\tdef __str__( self ):\n\t\tret = self._name\n\t\tif not ( self._parameters is None ):\n\t\t\tret += \"(\"\n\t\t\tif len( self._parameters ) > 0:\n\t\t\t\tret += \" \" + \",\".join( map( str, self._parameters ) ) + \" \"\n\t\t\tret += \")\"\n\t\treturn ret\n\n\n\n# Parsing ------------------------------------------------------------------------\n\n\n\nclass RuleParser():\n\n\t\"\"\"Parser for Rules, Actions, RValues etc\"\"\"\n\n\tdef __init__( self, str ):\n\t\t\"\"\"Initialization\n\n\t\tstr: The string that shall be parsed by this instance\n\t\t\"\"\"\n\t\tself._init_tokens( str )\n\t\tpass\n\n\tdef parse_rule( self ):\n\t\t\"\"\"Parsing a rule from the remaining tokens.\n\n\t\tThe token stream shall meet the pattern\n\n\t\t [TRIGGER:[RULE_OPTION:]]ACTION\n\n\t\twhere TRIGGER can be parsed to a trigger, RULE_OPTION\n\t\tcan be parsed to rule options, and ACTION to an\n\t\taction.\n\n\t\tThis function returns a Rule instance.\n\t\t\"\"\"\n\t\tstr_split = self._str.split( ':', 3 )\n\t\tif len( str_split ) == 0:\n\t\t\ttrigger = ''\n\t\t\toptions = ''\n\t\t\taction = ''\n\t\telif len( str_split ) == 1:\n\t\t\taction, = str_split\n\t\t\ttrigger = ''\n\t\t\toptions = ''\n\t\telif len( str_split ) == 2:\n\t\t\ttrigger, action = str_split\n\t\t\toptions = ''\n\t\telif len( str_split ) == 3:\n\t\t\ttrigger, options, action = str_split\n\t\telse:\n\t\t\tassert False, \"Unhandled case for splitting rule string\"\n\n\t\t# Trigger\n\t\tparser = RuleParser( trigger )\n\t\ttrigger_obj = parser._parse_trigger_allow_empty()\n\t\tparser._assert_end_token()\n\n\t\t# RuleOptions\n\t\tparser = RuleParser( options )\n\t\toptions_obj = parser._parse_options()\n\t\tparser._assert_end_token()\n\n\t\t# Action\n\t\tparser = RuleParser( action )\n\t\taction_obj = parser._parse_action()\n\t\tparser._assert_end_token()\n\n\t\treturn Rule( trigger_obj, options_obj, action_obj )\n\n\t# Handling of tokenizer .....................................\n\n\tdef _init_tokens( self, str ):\n\t\t\"\"\"Setup of the tokenizer and read the first token\n\n\t\tstr: The string to initialize the tokenizer from\n\t\t\"\"\"\n\t\tself._str = str\n\t\tself._tokens = tokenize.generate_tokens( StringIO.StringIO( str ).readline)\n\t\tself._next_token()\n\n\tdef _next_token( self ):\n\t\t\"\"\"Reading of the next token\"\"\"\n\t\tself._tok_type, self._tok_string, _, _, _ = self._tokens.next()\n\n\tdef _dump_current_token( self ):\n\t\t\"\"\"Printing the current token\n\n\t\tThis is mainly used when implementing new parsing functions\n\t\t\"\"\"\n\t\tprint( \"%s - %s\" % (self._tok_type, self._tok_string ) )\n\n\tdef _assert_end_token( self ):\n\t\t\"\"\"Assertion that the end of the token stream has been reached\"\"\"\n\t\tif self._tok_type != token.ENDMARKER:\n\t\t\traise RuntimeError( \"End of tokenizer expected\" )\n\n\t# Low lewel parsing .........................................\n\n\tdef _parse_name( self ):\n\t\t\"\"\"Parsing of tokens of the form\n\n\t\t name { \".\" name }\n\n\t\tThis function returns the parsed token as string\n\t\t\"\"\"\n\t\tif self._tok_type != token.NAME:\n\t\t\traise RuntimeError( \"Name expected\" )\n\n\t\tname = [ self._tok_string ]\n\t\tself._next_token()\n\n\t\twhile self._tok_type == token.OP and self._tok_string == '.':\n\t\t\tself._next_token()\n\t\t\tif ( self._tok_type == token.NAME ):\n\t\t\t\tname.append( self._tok_string )\n\t\t\telse:\n\t\t\t\traise RuntimeError( \"Name expected\" )\n\t\t\tself._next_token()\n\t\treturn '.'.join( name )\n\n\n\tdef _parse_rvalue( self ):\n\t\t\"\"\"Parsing of an RValue\n\n\t\tThis function returns either\n\t\t * a name (as parsed by _parse_name),\n\t\t * a number literal, or\n\t\t * a string literal\n\t\tas RValue instance.\n\t\t\"\"\"\n\t\tif self._tok_type == token.NAME:\n\t\t\treturn RValueProperty( self._parse_name() )\n\t\tif self._tok_type == token.NUMBER:\n\t\t\tstr = self._tok_string\n\t\t\tself._next_token()\n\t\t\treturn RValueLiteral( float( str ) )\n\t\tif self._tok_type == token.STRING:\n\t\t\tstr = self._tok_string\n\n\t\t\t# For the first three letters in the alphabet,\n # the string will be either \"abc\", or 'abc'\n # not simply abc. We have to strip the string\n # delimiters from start and end of the string\n\t\t\tif len( str ) < 2:\n\t\t\t\traise RuntimeError( \"Too short string in RValue parsing\" )\n\t\t\tif str[0] != str[len(str)-1]:\n\t\t\t\traise RuntimeError( \"First and last character in string literal do not match\" )\n\t\t\tif str[0] not in [ \"'\", '\"' ]:\n\t\t\t\traise RuntimeError( \"Unknown string delimiter\" )\n\n\t\t\t# All senity chikes passed, so strip 'em!\n\t\t\tstr = str[1:len(str)-1]\n\n\t\t\tself._next_token()\n\t\t\treturn RValueLiteral( str )\n\t\traise RuntimeError( \"RValue expected\" )\n\n\t# Parsing of triggers .......................................\n\n\t# For parsing of triggers, the function names resemble the\n\t# non-terminal symbol names of the Python grammar on purpose,\n # as we stick their precendence / formulation\n\n\tdef _parse_trigger_paren( self ):\n\t\t\"\"\"Parsing of a trigger that is optionally wrapped in parentheses.\n\n\t\tIf you want to parse an arbitrary trigger, use\n\t\t self._parse_trigger( self ), or\n\t\t self._parse_trigger_allow_empty( self, str )\n\t\tas they are the corrept high level entrance points\n\t\t\"\"\"\n\n\t\t# \"(\"\n\t\tif self._tok_type != token.OP or self._tok_string != \"(\":\n\t\t\traise RuntimeError( \"'(' expected\" )\n\t\tself._next_token()\n\n\t\t# trigger\n\t\tret = self._parse_trigger();\n\n\t\t# \")\"\n\t\tif self._tok_type != token.OP or self._tok_string != \")\":\n\t\t\traise RuntimeError( \"')' expected\" )\n\t\tself._next_token()\n\n\t\t# Done.\n\t\treturn TriggerParen( ret );\n\n\tdef _parse_trigger_comparison( self ):\n\t\t\"\"\"Parsing of a simple comparison\"\"\"\n\n\t\t# We are in the parsing function for strongest\n\t\t# binding, so we inject parentheses handling.\n\t\t#\n\t\t# ! Be sure to put this part again into the parsing !\n\t\t# ! function of strongest binding, when refining !\n\t\t# ! trigger parsing !\n\t\tif self._tok_type == token.OP and self._tok_string == \"(\":\n\t\t\treturn self._parse_trigger_paren()\n\n\t\t# Left-hand side\n\t\tlhs = self._parse_rvalue()\n\n\t\t# operator\n\t\tif ( self._tok_type == token.OP ):\n\t\t\tif ( self._tok_string in [ '<', '<=', '==', '!=', '>=', '>' ] ):\n\t\t\t\trel = self._tok_string\n\t\t\t\tself._next_token()\n\t\t\telse:\n\t\t\t\traise RuntimeError( \"One of the operators %s expected\" % [ '<', '<=', '==', '!=', '>=', '>' ] )\n\t\telse:\n\t\t\traise RuntimeError( \"Operator expected\" )\n\n\t\t# Right-hand side\n\t\trhs = self._parse_rvalue()\n\n\t\t# Done.\n\t\treturn TriggerSimpleComparison( lhs, rel, rhs )\n\n\n\tdef _parse_trigger_not_test( self ):\n\t\t\"\"\"Parsing of negation\"\"\"\n\t\tif self._tok_type == token.NAME and self._tok_string == \"not\":\n\t\t\tself._next_token()\n\t\t\treturn TriggerNot( self._parse_trigger_not_test() )\n\t\treturn self._parse_trigger_comparison()\n\n\tdef _parse_trigger_and_test( self ):\n\t\t\"\"\"Parsing of conjunction\"\"\"\n\t\tsubtriggers = [ self._parse_trigger_not_test() ]\n\n\t\twhile self._tok_type == token.NAME and self._tok_string == \"and\":\n\t\t\tself._next_token()\n\t\t\tsubtriggers.append( self._parse_trigger_not_test() )\n\n\t\tif len( subtriggers ) == 1:\n\t\t\treturn subtriggers[0]\n\t\treturn TriggerAnd( subtriggers )\n\n\tdef _parse_trigger_or_test( self ):\n\t\t\"\"\"Parsing of disjunction\"\"\"\n\t\tsubtriggers = [ self._parse_trigger_and_test() ]\n\n\t\twhile self._tok_type == token.NAME and self._tok_string == \"or\":\n\t\t\tself._next_token()\n\t\t\tsubtriggers.append( self._parse_trigger_and_test() )\n\n\t\tif len( subtriggers ) == 1:\n\t\t\treturn subtriggers[0]\n\t\treturn TriggerOr( subtriggers )\n\n\tdef _parse_trigger( self ):\n\t\t\"\"\"Parsing of a trigger\"\"\"\n\t\t# Just a call to the highest level parsing function\n # for triggers to ease refinements\n\t\treturn self._parse_trigger_or_test()\n\n\tdef _parse_trigger_allow_empty( self ):\n\t\t\"\"\"Parsing of a trigger, where the empty tokenstream\n\t\tis allowed and yields a True trigger\n\t\t\"\"\"\n\t\tif self._tok_type == token.ENDMARKER:\n\t\t\tret = TriggerTrue()\n\t\telse:\n\t\t\tret = self._parse_trigger();\n\n\t\treturn ret\n\n\t# Parsing of options ........................................\n\n\tdef _parse_options_single( self, options ):\n\t\t\"\"\"Parsing of a single option\"\"\"\n\t\tif self._tok_type != token.NAME:\n\t\t\traise RuntimeError( \"Name expected\" )\n\n\t\tif self._tok_string == \"multiple\":\n\t\t\toptions.set_multiple()\n\t\telse:\n\t\t\traise RuntimeError( \"Unknown rule option '%s'\" % self._tok_string )\n\t\tself._next_token()\n\n\tdef _parse_options( self ):\n\t\t\"\"\"Parsing of rule options.\n\n\t\tThe token stream shall meet the pattern\n\n\t\t [ option { \",\" option } ]\n\n\t\twhere option is any of the rule options.\n\t\t\"\"\"\n\t\toptions = RuleOptions()\n\n\t\twhile self._tok_type != token.ENDMARKER:\n\t\t\tself._parse_options_single( options )\n\n\t\t\tif self._tok_type != token.ENDMARKER:\n\t\t\t\tif self._tok_type == token.OP and self._tok_string == \",\":\n\t\t\t\t\tself._next_token()\n\t\t\t\t\tif self._tok_type == token.ENDMARKER:\n\t\t\t\t\t\traise RuntimeError( \"Expected another name\" )\n\t\t\t\telse:\n\t\t\t\t\traise RuntimeError( \"Either ',' or end of tokenizer expected\" )\n\n\t\treturn options\n\n\t# Parsing of actions ........................................\n\n\tdef _parse_action( self ):\n\t\t\"\"\"Parsing of an action\n\n\t\tThe token stream shall meet the pattern\n\n\t\t name ( | \"(\" [ rvalue { \",\" rvalue } ] \")\" )\n\n\t\t\"\"\"\n\t\tname = None\n\t\tparameters = None\n\n\t\t# action name\n\t\tif ( self._tok_type == token.NAME ):\n\t\t\tname = self._parse_name()\n\t\telse:\n\t\t\traise RuntimeError( \"Name expected\" )\n\n\t\t# parameters\n\t\tif self._tok_type == token.OP and self._tok_string == '(':\n\t\t\tself._next_token()\n\t\t\tparameters = []\n\n\t\t\twhile self._tok_type != token.OP or self._tok_string != \")\":\n\n\t\t\t\tparameters.append( self._parse_rvalue() )\n\n\t\t\t\tif self._tok_type != token.OP or self._tok_string != \")\":\n\t\t\t\t\tif self._tok_type == token.OP and self._tok_string == ',':\n\t\t\t\t\t\tself._next_token()\n\t\t\t\t\t\tif not ( self._tok_type != token.OP or self._tok_string != \")\" ):\n\t\t\t\t\t\t\traise RuntimeError( \"Another RValue expected\" )\n\t\t\t\t\telse:\n\t\t\t\t\t\traise RuntimeError( \"',' or ')' expected\" )\n\n\t\t\tself._next_token()\n\n\t\treturn SimpleAction( name, parameters )\n\n\n\n# Rules --------------------------------------------------------------------------\n\n\n\nclass Rule():\n\n\t\"\"\"Rule as used within the failure simulator manager.\n\n\tEach rule has a trigger, options, and an action.\n\n\tUpon rule evaluation, if the trigger fires, the action is\n\texecuted.\n\t\"\"\"\n\tdef __init__( self, trigger, options, action ):\n\t\t\"\"\"Initialization\n\n\t\ttrigger: An instance of Trigger\n\t\toptions: An instance of RuleOptions\n\t\taction: An instance of Action\n\t\t\"\"\"\n\t\tself._trigger = trigger\n\t\tself._options = options\n\t\tself._action = action\n\t\tself._matched = False\n\n\tdef __str__( self ):\n\t\t\"\"\"Conversion to string\"\"\"\n\t\treturn str( self._trigger ) + \":\" + str( self._options ) + \":\" + str( self._action )\n\n\tdef depends_on( self ):\n\t\t\"\"\"This function returns a frozenset of property names\n\t\tthat this Rule depends on.\n\n\t\tIf any of the names in this frozenset change their\n\t\tvalue, the manager shall reevaluate the rule.\n\t\t\"\"\"\n\t\treturn self._trigger.get_names()\n\n\tdef evaluate( self, manager ):\n\t\t\"\"\"Evaluation of the trigger, and execution of the action if appropriate\n\n\t\tmanager: The manager that shall be used for name evaluation.\n\n\t\tThis function yields True, if the action was\n\t\texecuted. Otherwise, the function returns False.\n\t\t\"\"\"\n\t\tif ( not self._matched or self._options.get_multiple() ) and self._trigger.matches( manager ):\n\t\t\tself._matched = True\n\t\t\tself._action.execute( manager )\n\t\t\treturn True\n\t\treturn False\n","sub_path":"failure_simulation/fs_rules.py","file_name":"fs_rules.py","file_ext":"py","file_size_in_byte":21079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"504484988","text":"from __future__ import print_function\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import zip\nfrom builtins import str\nfrom builtins import range\nfrom _ctypes import Array\nfrom numpy import array\nfrom builtins import open\nimport numpy as np\n\nfrom lsst.afw.image import makeImageFromArray\nfrom time import sleep\nfrom matplotlib.pyplot import ylim\nimport pylab as plt\n\nimport shutil\nimport os\nimport filecmp\n# import pyfits as pf\nimport sys\nimport glob\nimport functions as fn\n# fn = reload(fn)\n\nintrinsic_offset = -75\n\n\ndef GetMdSetFromVisitList(butler, visits, mdKey):\n \"\"\"Return the unique values of a given registry key for a list of visits.\"\"\"\n mdSet = []\n failed = 0\n for vis in visits:\n try:\n md = butler.queryMetadata('raw', [mdKey], dataId={'visit': vis})\n mdSet.append(md[0])\n except:\n failed += 1\n if failed:\n print(\"Failed to find expTimes for %s of %s\"%(failed, len(visits)))\n return set(mdSet)\n\n# def TimepixToExposure(filename):\n# from lsst.afw.image import makeImageFromArray\n# import numpy as np\n# \n# data = np.loadtxt(filename)\n# x = data[:, 0] \n# y = data[:, 1] \n# t = data[:, 2]\n# \n# my_array = np.zeros((256,256), dtype = np.int32)\n# \n# for pointnum in range(len(x)):\n# my_array[x[pointnum],y[pointnum]] = t[pointnum]\n# \n# my_image = makeImageFromArray(my_array)\n# return my_image\n\n\n# def TimepixToExposure_binary(filename, xmin, xmax, ymin, ymax):\n# import numpy as np\n# from lsst.afw.image import makeImageFromArray\n# \n# data = np.loadtxt(filename)\n# \n# my_array = np.zeros((256,256), dtype = np.int32)\n# \n# if data.shape == (0,):\n# my_image = makeImageFromArray(my_array)\n# \n# elif data.shape == (3,):\n# x = data[0] \n# y = data[1] \n# t = data[2]\n# \n# if x >= xmin and x <= xmax and y >= ymin and y <= ymax:\n# my_array[y,x] = 1\n# \n# my_image = makeImageFromArray(my_array)\n# \n# else: \n# x = data[:, 0] \n# y = data[:, 1] \n# t = data[:, 2]\n# \n# for pointnum in range(len(x)):\n# if x[pointnum] >= xmin and x[pointnum] <= xmax and y[pointnum] >= ymin and y[pointnum] <= ymax:\n# my_array[y[pointnum],x[pointnum]] = 1\n# \n# my_image = makeImageFromArray(my_array)\n# \n# return my_image\n\n\ndef SafeCopy(src, dest):\n if os.path.exists(dest):\n print('warning, tried to overwrite %s with %s'%(dest, src))\n if filecmp.cmp(src, dest):\n print('but it\\'s OK, the files were the same anyway')\n else:\n print('DISASTER - the files were different!\\n\\n\\n')\n else:\n shutil.copy(src,dest)\n \ndef SafeMove(src, dest):\n if os.path.exists(dest):\n print('warning, tried to overwrite %s with %s'%(dest, src))\n if filecmp.cmp(src, dest):\n print('but it\\'s OK, the files were the same anyway')\n else:\n print('DISASTER - the files were different!\\n\\n\\n')\n else:\n shutil.move(src,dest) \n \ndef ReverseDictionary(input_dict):\n return dict((v,k) for k,v in input_dict.items())\n\ndef GetFilename(filename_or_path):\n return str(filename_or_path).split('/')[-1]\n\ndef SafeCopyDir(src_dir, dest_dir, prepend_date=True, skip_eko_files=True):\n files = [_ for _ in os.listdir(src_dir) if os.path.isfile(os.path.join(src_dir,_))] #grab files, reject directories\n for fname in files:\n if skip_eko_files:\n if fname.find('eko')!=-1: continue\n source_filename = os.path.join(src_dir, fname)\n if prepend_date:\n try:\n d_file = pf.open(source_filename)\n primaryHeader = d_file[0].header\n date = primaryHeader['DATE-OBS'].split('T')[0]\n d_file.close()\n except Exception as e:\n print(repr(e))\n print('no date found for prepending in %s'%source_filename)\n date = ''\n \n dest_filename = os.path.join(dest_dir, date + fname)\n if os.path.exists(dest_filename):\n print('warning: tried to overwrite %s with %s'%(dest_filename, source_filename))\n if filecmp.cmp(source_filename, dest_filename):\n print('but it\\'s OK, the files were the same anyway')\n else:\n print('\\n\\n *** DISASTER - the files were different!*** \\n\\n\\n')\n else:\n shutil.copy(source_filename,dest_filename)\n\ndef ShowExp(exp, percentile=0.5, saveAs=None, dontShow=False):\n data = exp.getMaskedImage().getImage().getArray()\n plt.figure(figsize=(10,10))\n plt.imshow(data, cmap='gray', vmin=np.percentile(data, percentile), vmax=np.percentile(data, 100-percentile), origin='bl')\n if not dontShow:\n plt.show()\n if saveAs:\n plt.savefig(saveAs)\n\ndef BoxcarAverage1DArray(data, length):\n return np.convolve(data, np.ones((length,))/length,mode='valid')\n\n\ndef TranslatePImMSToTimepix(in_file, run_num, out_path):\n data = np.loadtxt(in_file)\n x = data[:,0] \n y = data[:,1] \n t = data[:,2]\n shot = data[:,3]-1 #pimms shot number is 1-based, we want to fix that\n \n n_shots = int(shot[-1])\n for i in range(n_shots):\n indices = np.where(shot == i)\n lines = []\n for index in indices[0]:\n lines.append(str(int(x[index])) + '\\t'+ str(int(y[index])) + '\\t'+ str(int(t[index]))+ '\\n')\n \n file = open(out_path + str(run_num).rjust(2,'0') +'_'+ str(i+1).rjust(4,'0')+'.txt','w')\n file.writelines(lines)\n file.close()\n \n \n\ndef TimepixToExposure_binary(filename, xmin, xmax, ymin, ymax, mask_pixels=np.ones((1), dtype = np.float64)):\n from lsst.afw.image import makeImageFromArray\n \n data = np.loadtxt(filename)\n\n my_array = np.zeros((256,256), dtype = np.int32)\n \n if data.shape == (0,):\n my_image = makeImageFromArray(my_array)\n \n elif data.shape == (3,):\n x = data[0] \n y = data[1] \n t = data[2]\n if x >= xmin and x <= xmax and y >= ymin and y <= ymax:\n my_array[y,x] = 1\n my_image = makeImageFromArray(my_array*mask_pixels.transpose())\n return_npix = (my_array*mask_pixels.transpose()).sum() #apply the mask, *then* sum!\n \n else: \n x = data[:, 0] \n y = data[:, 1] \n t = data[:, 2]\n for pointnum in range(len(x)):\n if x[pointnum] >= xmin and x[pointnum] <= xmax and y[pointnum] >= ymin and y[pointnum] <= ymax:\n my_array[y[pointnum],x[pointnum]] = 1\n \n my_image = makeImageFromArray(my_array*mask_pixels.transpose())\n return_npix = (my_array*mask_pixels.transpose()).sum() #apply the mask, *then* sum!\n \n return my_image, return_npix\n\n\n\ndef MakeMaskArray(mask_list):\n import numpy as np\n mask_array = np.ones((256,256), dtype = np.int32)\n \n for i in range(len(mask_list[0])):\n y = mask_list[0][i]\n x = mask_list[1][i]\n mask_array[y][x] = 0\n return mask_array\n\n\ndef MaskBadPixels(data_array, mask_list):\n mask_array = MakeMaskArray(mask_list)\n data_array *= mask_array\n \n \ndef GeneratePixelMaskListFromFileset(path, noise_threshold = 0.03, xmin = 0, xmax = 255, ymin = 0, ymax = 255, file_limit = 1e6):\n import numpy as np\n import os\n# intensity_array = MakeCompositeImage_Timepix(path, 0, 255, 0, 255, 0, 9999, -99999, 99999, return_raw_array=True)\n intensity_array = MakeCompositeImage_Timepix(path, xmin, xmax, ymin, ymax, 0, file_limit, -99999, 99999, return_raw_array=True)\n nfiles = len(os.listdir(path))\n mask_pixels = np.where(intensity_array >= noise_threshold*(nfiles))\n\n return mask_pixels\n \n\ndef ViewMaskInDs9(mask_array):\n import lsst.afw.display.ds9 as ds9\n ds9.mtv(makeImageFromArray(mask_array))\n \n\ndef ViewIntensityArrayInDs9(intensity_array, savefile = None):\n import lsst.afw.display.ds9 as ds9\n ds9.mtv(makeImageFromArray(100*intensity_array/float(intensity_array.max())))\n if savefile is not None:\n arg = 'saveimage jpeg ' + str(savefile) + ' 100'\n ds9.ds9Cmd(arg)\n\n\n\n\n\ndef TimepixToExposure(filename, xmin, xmax, ymin, ymax):\n import numpy as np\n from lsst.afw.image import makeImageFromArray\n\n data = np.loadtxt(filename)\n\n my_array = np.zeros((256,256), dtype = np.int32)\n \n if data.shape == (0,):\n my_image = makeImageFromArray(my_array)\n \n elif data.shape == (3,):\n x = data[0] \n y = data[1] \n t = data[2]\n \n if x >= xmin and x <= xmax and y >= ymin and y <= ymax:\n my_array[y,x] = t\n \n my_image = makeImageFromArray(my_array)\n \n else: \n x = data[:, 0] \n y = data[:, 1] \n t = data[:, 2]\n \n for pointnum in range(len(x)):\n if x[pointnum] >= xmin and x[pointnum] <= xmax and y[pointnum] >= ymin and y[pointnum] <= ymax:\n my_array[y[pointnum],x[pointnum]] = t[pointnum]\n \n my_image = makeImageFromArray(my_array)\n \n return my_image\n\n\n\n\ndef XYI_array_to_exposure(xs, ys, i_s):\n from lsst.afw.image import makeImageFromArray\n import numpy as np\n\n my_array = np.zeros((256,256), dtype = np.int32)\n\n for pointnum in range(len(xs)):\n my_array[xs[pointnum],ys[pointnum]] = i_s[pointnum]\n \n my_image = makeImageFromArray(my_array)\n return my_image\n\n\n\ndef GetTimecodes_SingleFile(filename, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, offset_us = 0):\n import string\n \n timecodes = []\n datafile = open(filename)\n \n for line in datafile.readlines():\n x,y,timecode = string.split(str(line),'\\t')\n x = int(x)\n y = int(y)\n timecode = int(timecode)\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n actual_offset_us = intrinsic_offset - offset_us\n time_s = (11810. - timecode) * 20e-9\n time_us = (time_s *1e6)- actual_offset_us\n timecodes.append(time_us)\n \n return timecodes\n\ndef ReadTektronixWaveform(filename):\n import pylab as pl\n data = pl.loadtxt(filename, delimiter = ',', skiprows = 18, usecols = [3,4])\n xs = data[:,0]\n ys = data[:,1]\n return xs, ys\n \ndef ReadBNL_PMTWaveform(filename):\n import pylab as pl\n data = pl.loadtxt(filename, skiprows = 7)\n# pl.loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin)\n xs = data[:,0]\n ys = data[:,1]\n return xs, ys\n \ndef GetRawTimecodes_SingleFile(filename, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999,tmin=-9999999,tmax=9999999, offset_us = 0):\n import string\n \n timecodes = []\n datafile = open(filename)\n \n for line in datafile.readlines():\n x,y,timecode = string.split(str(line),'\\t')\n x = int(x)\n y = int(y)\n timecode = int(timecode)\n if x >= winow_xmin and x <= winow_xmax and y >= winow_ymin and y <= winow_ymax: \n if (timecode <= tmax) and (timecode >= tmin):\n timecodes.append(timecode) \n\n return timecodes\n\ndef GetTimecodes_AllFilesInDir(path, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, offset_us = 0, translate_to_us = False, glitch_threshold = 20000, checkerboard_phase = None, noise_mask = None):\n import string, os\n \n timecodes = []\n files = []\n \n for filename in os.listdir(path):\n files.append(path + filename)\n \n\n nfiles = 0\n for filename in files:\n if str(filename).find('.DS')!=-1:continue\n \n datafile = open(filename)\n nfiles += 1\n if len(files)>500 and (nfiles % 500 == 0): print('Loaded %s of %s files'%(nfiles, len(files)))\n lines = datafile.readlines()\n \n if len(lines) > glitch_threshold: continue #skip files which glitched (most pixels hit - parameter may need tuning)\n for line in lines:\n x,y,timecode = string.split(str(line),'\\t')\n x = int(x)\n y = int(y)\n \n if noise_mask is not None:\n if noise_mask[x][y] == 0: continue\n \n timecode = int(timecode)\n if timecode == 11810: continue #discard overflows\n if timecode == 1: continue #discard noise hits\n \n if checkerboard_phase is not None:\n if (x+y)%2 == checkerboard_phase:\n timecode -= 1 \n \n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n if translate_to_us == True:\n actual_offset_us = 250 - offset_us\n time_s = (11810. - timecode) * 20e-9\n time_us = (time_s *1e6)- actual_offset_us\n timecodes.append(time_us)\n else:\n timecodes.append(timecode)\n\n print(\"Loaded data from %s files\"%nfiles)\n return timecodes\n\n\ndef GetMaxClusterTimecodes_AllFilesInDir(path, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, checkerboard_phase = None, npix_min = 1):\n import os\n all_timecodes = []\n \n files = os.listdir(path)\n nfiles = len(files)\n for i,filename in enumerate(files):\n if i%500 == 0: print('Centroided %s of %s files'%(i,nfiles))\n codes = Clusterfind_max_timecode_one_file(path + filename, winow_xmin=winow_xmin, winow_xmax=winow_xmax, winow_ymin=winow_ymin, winow_ymax=winow_ymax, checkerboard_phase=checkerboard_phase, npix_min=npix_min)\n all_timecodes.extend(codes)\n \n return all_timecodes\n\ndef Clusterfind_max_timecode_one_file(filename, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, glitch_threshold = 20000, checkerboard_phase = None, npix_min = 1):\n if str(filename).find('.DS')!=-1:return\n \n import lsst.afw.detection as afwDetect\n import string, os\n \n cluster_sizes = []\n timecodes = []\n files = []\n \n thresholdValue = 1\n npixMin = npix_min\n grow = 0\n isotropic = False\n \n image = TimepixToExposure(filename, winow_xmin, winow_xmax, winow_ymin, winow_ymax)\n \n threshold = afwDetect.Threshold(thresholdValue)\n footPrintSet = afwDetect.FootprintSet(image, threshold, npixMin)\n footPrintSet = afwDetect.FootprintSet(footPrintSet, grow, isotropic)\n footPrints = footPrintSet.getFootprints()\n \n for footprintnum, footprint in enumerate(footPrints):\n npix = afwDetect.Footprint.getNpix(footprint)\n cluster_sizes.append(npix)\n \n# if npix >= 4:\n box = footprint.getBBox()\n bbox_xmin = box.getMinX()\n bbox_xmax = box.getMaxX() + 1\n bbox_ymin = box.getMinY()\n bbox_ymax = box.getMaxY() + 1\n \n data = image.getArray()[bbox_ymin:bbox_ymax,bbox_xmin:bbox_xmax] \n# x,y,t,chisq = CentroidTimepixCluster(data, fit_function = 'gaus')\n# timecodes.append(t)\n\n## centroid_x, centroid_y = footprint.getCentroid()\n## x += bbox_xmin\n## y += bbox_ymin\n\n if checkerboard_phase is not None:\n print('WARNING - Not yet implemented')\n exit()\n if (bbox_xmin+bbox_ymin)%2 == checkerboard_phase:\n timecode -= 1 \n\n timecodes.append(GetMaxClusterTimecode(data))\n\n return timecodes\n\n\n\ndef GetXYTarray_AllFilesInDir(path, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, offset_us = 0, tmin_us = -1000, tmax_us = 999999, maxfiles = None):\n import string, os\n import pylab as pl\n \n files = []\n for filename in os.listdir(path):\n files.append(path + filename)\n\n xs, ys, ts = [], [], []\n\n num = 0\n for filename in files:\n data = pl.loadtxt(filename, usecols = (0,1,2))\n num +=1\n if (num % 10 == 0): print('loaded %s files'%num)\n \n #handle problem with the way loadtxt reads single line data files\n if data.shape == (3,): \n x = int(data[0])\n y = int(data[1])\n timecode = int(data[2])\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n actual_offset_us = intrinsic_offset - offset_us\n time_s = (11810. - timecode) * 20e-9\n time_us = (time_s *1e6)- actual_offset_us\n if time_us>=tmin_us and time_us<= tmax_us:\n xs.append(x)\n ys.append(y)\n ts.append(time_us)\n continue\n \n #extract data for multiline files\n if len(data) > 10000: continue #skip glitch files\n for i in range(len(data)):\n x = int(data[i,0])\n y = int(data[i,1])\n timecode = int(data[i,2])\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n actual_offset_us = intrinsic_offset - offset_us\n time_s = (11810. - timecode) * 20e-9\n time_us = (time_s *1e6)- actual_offset_us\n# print time_us\n# exit()\n if time_us>=tmin_us and time_us<= tmax_us:\n xs.append(x)\n ys.append(y)\n ts.append(time_us)\n \n if maxfiles != None and num == maxfiles:\n return xs, ys, ts\n\n# if return_as_ndarray:\n# return \n\n return xs, ys, ts \n\n\n\ndef ShowRawToF_whole_dir(path, invert = False, logy = False):\n import pylab as pl\n raw_codes = GetTimecodes_AllFilesInDir(path, 0, 256, 0, 256, 0, checkerboard_phase = None)\n\n fig = pl.figure(figsize=(14,10))\n \n if invert:\n n_codes, bins, patches = pl.hist([11810-i for i in raw_codes], bins = 11810, range = [0,11810])\n else:\n n_codes, bins, patches = pl.hist(raw_codes, bins = 11810, range = [0,11810])\n \n if logy: pl.yscale('log', nonposy='clip')\n\n \n pl.show()\n\ndef MakeCompositeImage_Medipix(path, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, offset_us = 0, maxfiles = None):\n from lsst.afw.image import makeImageFromArray\n import string, os\n import numpy as np\n import pylab as pl\n \n my_array = np.zeros((256,256), dtype = np.int32)\n\n files = []\n for filename in os.listdir(path):\n files.append(path + filename)\n\n num = 0\n for filename in files:\n data = pl.loadtxt(filename, usecols = (0,1,2))\n num +=1\n if (num % 10 == 0): print('loaded %s files'%num)\n \n for i in range(len(data)):\n x = int(data[i,0])\n y = int(data[i,1])\n intensity = int(data[i,2])\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n my_array[x,y] += intensity\n \n \n if maxfiles != None and num == maxfiles:\n my_image = makeImageFromArray(my_array)\n return my_image\n \n my_image = makeImageFromArray(my_array)\n return my_image\n\n\ndef MakeCompositeImage_Timepix(path, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, offset_us = 0, maxfiles = None, t_min = -9999, t_max = 9999, return_raw_array = False):\n from lsst.afw.image import makeImageFromArray\n import string, os\n import numpy as np\n import pylab as pl\n \n my_array = np.zeros((256,256), dtype = np.int32)\n\n files = []\n for filename in os.listdir(path):\n files.append(path + filename)\n\n for filenum, filename in enumerate(files):\n if filenum % 500 ==0: print(\"Compiled %s files\"%filenum)\n \n xs, ys, ts = GetXYTarray_SingleFile(filename, winow_xmin, winow_xmax, winow_ymin, winow_ymax)\n# if len(xs) > 5000: continue # skip glitch files\n \n for i in range(len(xs)):\n x = xs[i]\n y = ys[i]\n t = ts[i]\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n if t>=t_min and t<=t_max:\n my_array[x,y] += 1\n \n \n if maxfiles != None and filenum >= maxfiles:\n if return_raw_array: return my_array\n my_image = makeImageFromArray(my_array)\n return my_image\n \n my_image = makeImageFromArray(my_array)\n if return_raw_array: return my_array\n return my_image\n\n\n\ndef MakeCompositeImage_PImMS(path, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, offset_us = 0, maxfiles = None, t_min = -9999, t_max = 9999, return_raw_array = False):\n from lsst.afw.image import makeImageFromArray\n import string, os\n import numpy as np\n import pylab as pl\n \n my_array = np.zeros((72,72), dtype = np.int32)\n\n files = []\n for filename in os.listdir(path):\n files.append(path + filename)\n\n for filenum, filename in enumerate(files):\n if filenum % 500 ==0: print(\"Compiled %s files\"%filenum)\n \n xs, ys, ts = GetXYTarray_SingleFile(filename, winow_xmin, winow_xmax, winow_ymin, winow_ymax)\n# if len(xs) > 5000: continue # skip glitch files\n \n for i in range(len(xs)):\n x = xs[i]\n y = ys[i]\n t = ts[i]\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n if t>=t_min and t<=t_max:\n my_array[x,y] += 1\n \n \n if maxfiles != None and filenum >= maxfiles:\n if return_raw_array: return my_array\n my_image = makeImageFromArray(my_array)\n return my_image\n \n my_image = makeImageFromArray(my_array)\n if return_raw_array: return my_array\n return my_image\n\n\n\ndef TimecodeTo_us(timecode):\n return (11810. - timecode) * 0.02 # 20e-9 * 1e6\n\n\ndef OpenTimepixInDS9(filename, binary = False):\n import lsst.afw.display.ds9 as ds9\n if binary:\n image,dummy = TimepixToExposure_binary(filename, 0,255,0,255)\n else:\n image = TimepixToExposure(filename, 0,255,0,255)\n\n try:\n ds9.initDS9(False)\n except ds9.Ds9Error:\n print('DS9 launch bug error thrown away (probably)')\n\n ds9.mtv(image)\n \n \ndef OpenImageInDS9(image):\n import lsst.afw.display.ds9 as ds9\n\n try:\n ds9.initDS9(False)\n except ds9.Ds9Error:\n print('DS9 launch bug error thrown away (probably)')\n\n ds9.mtv(image)\n \ndef BuildMosaic(filename, gutter = 0, background = 0):\n import lsst.afw.display.utils as Util\n import lsst.afw.image as afwImg\n \n m = Util.Mosaic()\n m.setGutter(gutter)\n m.setBackground(background)\n \n images = []\n for i in range(2,18):\n m.append(afwImg.ImageF(filename,i), str(i))\n \n \n# mosaic = m.makeMosaic()\n\n return m\n\n\ndef GetXYTarray_SingleFile(filename, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999):\n import pylab as pl\n \n xs, ys, ts = [], [], []\n\n data = pl.loadtxt(filename, usecols = (0,1,2))\n \n #handle problem with the way loadtxt reads single line data files\n if data.shape == (3,): \n x = int(data[0])\n y = int(data[1])\n timecode = int(data[2])\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n xs.append(x)\n ys.append(y)\n ts.append(timecode)\n return xs, ys, ts \n \n \n #extract data for multiline files\n for i in range(len(data)):\n x = int(data[i,0])\n y = int(data[i,1])\n timecode = int(data[i,2])\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n xs.append(x)\n ys.append(y)\n ts.append(timecode)\n \n return xs, ys, ts\n\n\ndef Timepix_ToT_to_lego(datafile, center_x, center_y, boxsize_over_2, savefile = '', mask_above = 999999, print_RMS = False, fix_zmax = '', nfiles_for_camera_tricks = '', filenum_for_camera_trick = ''):\n from ROOT import TH2F, TCanvas\n from root_functions import CANVAS_HEIGHT, CANVAS_WIDTH\n c1 = TCanvas( 'canvas', 'canvas', CANVAS_WIDTH/2,CANVAS_HEIGHT/2)\n\n xs, ys, ts = GetXYTarray_SingleFile(datafile, center_x - boxsize_over_2, center_x + boxsize_over_2, center_y - boxsize_over_2, center_y + boxsize_over_2)\n \n nx,ny = 256,256\n image_hist = TH2F('', '',nx,0,255,ny, 0, 255)\n \n for i in range(len(xs)):\n value = float(ts[i])/50\n if value > mask_above: value = 0\n image_hist.Fill(float(xs[i]),float(ys[i]),value)\n\n image_hist.GetXaxis().SetTitle('x')\n image_hist.GetYaxis().SetTitle('y')\n image_hist.GetZaxis().SetTitle('ToT (us)')\n \n image_hist.GetXaxis().SetRangeUser(center_x - boxsize_over_2, center_x + boxsize_over_2)\n image_hist.GetYaxis().SetRangeUser(center_y - boxsize_over_2, center_y + boxsize_over_2)\n if fix_zmax != '':\n image_hist.GetZaxis().SetRangeUser(0,fix_zmax)\n \n image_hist.GetXaxis().SetTitleOffset(1.2)\n image_hist.GetYaxis().SetTitleOffset(1.4)\n image_hist.GetZaxis().SetTitleOffset(1.2)\n \n image_hist.Draw(\"same lego2 0 z\") #box, lego, colz, lego2 0\n image_hist.SetStats(False)\n \n if savefile != '':\n if nfiles_for_camera_tricks != '' and filenum_for_camera_trick != '':\n c1.SetPhi(180 * filenum_for_camera_trick / nfiles_for_camera_tricks)\n else:\n c1.SetPhi(41.57391)\n\n c1.SetTheta(41.57391)\n# c1.SetPhi(-132.4635)\n #c1.SetTheta(35)#theta sets inclination, phi sets rotation\n# c1.SetPhi(45)#around z axis\n \n if print_RMS:\n from ROOT import TPaveText\n textbox = TPaveText(0.0,1.0,0.2,0.8,\"NDC\")\n textbox.AddText('RMS = ' + str(image_hist.GetRMS()))\n textbox.SetFillColor(0)\n textbox.Draw(\"same\")\n c1.SaveAs(savefile)\n \n del c1 \n \n return image_hist\n \n\ndef TimepixDirToPImMMSDatafile(path, outfile_name, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, offset_us = 0, tmin_us = -1000, tmax_us = 999999, maxfiles = None):\n import string, os\n import pylab as pl\n \n files = []\n for filename in os.listdir(path):\n files.append(path + filename)\n\n output_file = open(outfile_name, 'w')\n\n for filenum, filename in enumerate(files):\n data = pl.loadtxt(filename, usecols = (0,1,2))\n if (filenum % 100 == 0): print('loaded %s files'%filenum)\n \n #handle problem with the way loadtxt reads single line data files\n if data.shape == (3,): \n x = int(data[0])\n y = int(data[1])\n timecode = int(data[2])\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n actual_offset_us = intrinsic_offset - offset_us\n# time_s = (11810. - timecode) * 20e-9\n# time_us = (time_s *1e6)- actual_offset_us\n reflected_timecode = 11810 - timecode\n# if time_us>=tmin_us and time_us<= tmax_us:\n line = str(x) + '\\t' + str(y) + '\\t' + str(reflected_timecode) + '\\t' + str(filenum) + '\\t' + '1\\n'\n output_file.write(line)\n continue\n \n #extract data for multiline files\n if len(data) > 50: continue #skip glitch files\n for i in range(len(data)):\n x = int(data[i,0])\n y = int(data[i,1])\n timecode = int(data[i,2])\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n actual_offset_us = intrinsic_offset - offset_us\n# time_s = (11810. - timecode) * 20e-9\n# time_us = (time_s *1e6)- actual_offset_us\n reflected_timecode = 11810 - timecode\n# if time_us>=tmin_us and time_us<= tmax_us:\n line = str(x) + '\\t' + str(y) + '\\t' + str(reflected_timecode) + '\\t' + str(filenum) + '\\t' + '1\\n'\n output_file.write(line)\n# xs.append(x)\n# ys.append(y)\n# ts.append(time_us)\n\n if maxfiles != None and num == maxfiles:\n output_file.close()\n return\n\n output_file.close()\n return\n \ndef MakeTimeSlices(inpath, slicelist, outpath):\n from lsst.afw.image import makeImageFromArray\n import string, os\n import numpy as np\n from TrackViewer import TrackToFile_ROOT_2D_3D\n \n image_array = []\n for i in slicelist:\n image_array.append(np.zeros((256,256), dtype = np.int32)) \n \n xs, ys, ts = GetXYTarray_AllFilesInDir_Raw_Timecodes(inpath)\n \n for slicenum,slice in enumerate(slicelist):\n t_min = slice[0]\n try:\n t_max = slice[1]\n except:\n t_max = t_min\n \n try: #NB try/except blocks do need to be separate here\n prefix = slice[2]\n except:\n prefix = ''\n \n\n \n for i in range(len(xs)):\n t = ts[i]\n if t>=t_min and t<=t_max:\n image_array[slicenum][xs[i],ys[i]] += 1\n \n \n for i in range(1,3):\n if t_min == t_max:\n outname = outpath + str(t_min) + '_boxcar_' + str(i) + '.png'\n else:\n outname = outpath + prefix + 'range_' + str(t_min) + '_' + str(t_max) + '_boxcar_' + str(i) + '.png'\n \n avergaged_array = BoxcarAverage2DArray(image_array[slicenum], i)\n TrackToFile_ROOT_2D_3D(avergaged_array, outname, plot_opt='surf1', zmax_supress_ratio = 0.6, log_z = False, force_aspect= True, fitline = None)\n \n# TrackToFile_ROOT_2D_3D(image_array[slicenum], outname, plot_opt='surf1', zmax_supress_ratio = 0.5, log_z = False, force_aspect= True, fitline = None)\n \n \n return\n\n\ndef BoxcarAverage2DArray(array, boxcar_size):\n import numpy as np\n xsize, ysize = array.shape\n if boxcar_size == 1:\n return array\n if boxcar_size < 1:\n print(\"Error - Boxcar size cannot be less than 1\")\n exit()\n \n ret = np.zeros((xsize - (boxcar_size - 1),ysize - (boxcar_size - 1)), dtype = np.float32)\n for x in range(xsize - boxcar_size + 1):\n for y in range(ysize - boxcar_size + 1):\n av = np.average(array[x:x+boxcar_size,y:y+boxcar_size])\n ret[x,y] = av \n return ret \n\ndef GetXYTarray_AllFilesInDir_Raw_Timecodes(path, winow_xmin = 0, winow_xmax = 999, winow_ymin = 0, winow_ymax = 999, offset_us = 0, maxfiles = None):\n import string, os\n import pylab as pl\n \n files = []\n for filename in os.listdir(path):\n files.append(path + filename)\n\n xs, ys, ts = [], [], []\n\n num = 0\n for filename in files:\n data = pl.loadtxt(filename, usecols = (0,1,2))\n num +=1\n if (num % 100 == 0): print('loaded %s files'%num)\n \n #handle problem with the way loadtxt reads single line data files\n if data.shape == (3,): \n x = int(data[0])\n y = int(data[1])\n timecode = int(data[2])\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n xs.append(x)\n ys.append(y)\n ts.append(timecode)\n continue\n \n #extract data for multiline files\n if len(data) > 10000: continue #skip glitch files\n for i in range(len(data)):\n x = int(data[i,0])\n y = int(data[i,1])\n timecode = int(data[i,2])\n if x>=winow_xmin and x<=winow_xmax and y>=winow_ymin and y<=winow_ymax:\n xs.append(x)\n ys.append(y)\n ts.append(timecode)\n \n if maxfiles != None and num == maxfiles:\n return xs, ys, ts\n\n return xs, ys, ts \n\n\n\ndef MakeToFSpectrum(input_path, save_path, xmin=0, xmax=255, ymin=0, ymax=255, translate_to_us = True, time_zoom_region = [0,11810]):\n import pylab as pl\n \n timecodes = GetTimecodes_AllFilesInDir(input_path, xmin, xmax, ymin, ymax, 110, translate_to_us)\n print('Total number of timecodes read in = %s' %len(timecodes))\n \n if translate_to_us:\n tmin = 5\n tmax = 25\n bins = (((tmax-tmin))*50) - 1 #1 timecode per bin\n else:\n tmin = 0 # full range\n tmax = 11810 # full range\n bins = (tmax-tmin) +1 \n \n fig = pl.figure()\n \n vals, bins, pathches = pl.hist(timecodes, bins = bins, range = [tmin,tmax]) #make the histogram of the timecodes\n \n# pl.ylim([0,2000]) #for clipping the y-axis\n \n if translate_to_us:\n pl.xlabel('ToF (us)', horizontalalignment = 'right' )\n else:\n pl.xlabel('Timecodes', horizontalalignment = 'right' )\n \n pl.title('Timepix ToF Spectrum')\n fig.savefig(save_path + '_ToF_Full.png')\n\n tmin, tmax = time_zoom_region\n ylim = max(vals[tmin:tmax])\n ylim *= 1.2\n pl.ylim([0,ylim]) #for clipping the x-axis\n pl.xlim([tmin,tmax]) #for clipping the x-axis\n fig.savefig(save_path + '_ToF_ROI.png')\n print('Finished making ToF')\n \n \ndef CentroidTimepixCluster(data, save_path = None, fit_function = None):\n import numpy as np\n # from ROOT import *\n from ROOT import TH2F, TCanvas, TBrowser, TF2\n import ROOT\n gROOT.SetBatch(1) #don't show drawing on the screen along the way \n \n nbinsx = xmax = max(data.shape[0], data.shape[1])\n nbinsy = ymax = max(data.shape[0], data.shape[1])\n \n xlow = 0\n ylow = 0\n \n tmin = np.amin(data[np.where(data >= 1)])\n \n if save_path!= None: \n c1 = TCanvas( 'canvas', 'canvas', 1200,1000) #create canvas\n \n image_hist = TH2F('', '',nbinsx,xlow,xmax,nbinsy, ylow, ymax)\n for x in range(data.shape[0]):\n for y in range(data.shape[1]):\n value = data[x,y]\n if value != 0:\n image_hist.Fill(float(x),float(y),float(value-tmin))\n \n \n if fit_function == 'gaus':\n fit_func = TF2(\"f2\",\"[0]*TMath::Gaus(x,[1],[2])*TMath::Gaus(y,[3],[4])\",0,xmax,0,ymax)\n fit_func.SetParameters(10,3,3,3,3)\n elif fit_function == 'p2':\n fit_func = TF2(\"f2\",'[0]*(x-[1])^2 + [2]*(y-[3])^2 + [4]',0,xmax, 0, ymax)\n fit_func.SetParameters(10,3,3,3,3)\n elif fit_function == 'p4':\n fit_func = TF2(\"f2\",'[0]*(x-[1])^4 + [2]*(y-[3])^4 + [4]',0,xmax, 0, ymax)\n fit_func.SetParameters(-0.002,10,-0.002,8,15)\n elif fit_function == None:\n print('Warning - not fitting clusters')\n else:\n print('Error - unknown fit function')\n exit()\n \n if fit_function != None:\n image_hist.Fit(fit_func, 'MEQ')\n true_xmax = fit_func.GetParameter(1)\n true_ymax = fit_func.GetParameter(3)\n true_tmax = fit_func.Eval(true_xmax, true_ymax) + tmin\n chisq = fit_func.GetChisquare()\n NDF = fit_func.GetNDF()\n try:\n chisqred = chisq/NDF\n except:\n chisqred = 999999\n\n \n if save_path!= None:\n if fit_function == None:\n image_hist.Draw('lego20z')\n image_hist.GetZaxis().SetRangeUser(0,np.ceil(data.max() - tmin))\n image_hist.SetStats(False)\n c1.SaveAs(save_path)\n else:\n fit_func.SetNpx(1000)\n image_hist.Draw('lego20')\n fit_func.Draw(\"same\")\n zrange = np.ceil(true_tmax - tmin)\n zrange = max(zrange,10, np.ceil(data.max() - tmin))\n image_hist.GetZaxis().SetRangeUser(0,zrange)\n image_hist.SetStats(False)\n c1.SaveAs(save_path)\n del c1\n \n if fit_function != None: return true_xmax, true_ymax, true_tmax, chisqred\n return 0, 0, 0, 0\n \ndef GetMaxClusterTimecode(data):\n return np.amax(data[np.where(data >= 1)])\n\n# def GetMinClusterTimecode(data):\n# return np.amin(data[np.where(data >= 1)])\n \ndef GetAllTimecodesInCluster(data):\n timecodes = []\n for x in range(data.shape[0]):\n for y in range(data.shape[1]):\n value = data[x,y]\n if value != 0:\n timecodes.append(value)\n \n return timecodes\n \ndef Combine_and_pickle_dir(path, output_pickle):\n import pickle as pickle\n import os\n import pylab as pl\n \n files = []\n for filename in os.listdir(path):\n files.append(path + filename)\n\n xs, ys, ts = [], [], []\n\n for filenum, filename in enumerate(files):\n data = pl.loadtxt(filename, usecols = (0,1,2))\n if (filenum % 500 == 0): print('loaded %s of %s files'%(filenum, len(files)))\n \n #handle problem with the way loadtxt reads single line data files\n if data.shape == (3,): \n xs.append(int(data[0]))\n ys.append(int(data[1]))\n ts.append(int(data[2]))\n \n #extract data for multiline files\n if len(data) > 10000: continue #skip glitch files\n for i in range(len(data)):\n xs.append(int(data[i,0]))\n ys.append(int(data[i,1]))\n ts.append(int(data[i,2]))\n \n x_array = np.asarray(xs, dtype = np.int16)\n y_array = np.asarray(ys, dtype = np.int16)\n t_array = np.asarray(ts, dtype = np.int16)\n\n data_array = np.ndarray([len(x_array),3], dtype = np.int16)\n data_array[:,0] = x_array\n data_array[:,1] = y_array\n data_array[:,2] = t_array\n \n pickle.dump(data_array, open(output_pickle,'wb'), pickle.HIGHEST_PROTOCOL)\n \ndef Load_XYT_pickle(filename):\n import pickle as pickle\n return pickle.load(open(filename, 'rb'))\n \ndef XYT_to_image(xyt_array, display = False):\n import numpy as np\n from lsst.afw.image import makeImageFromArray\n if display:\n import lsst.afw.display.ds9 as ds9\n try:\n ds9.initDS9(False)\n except ds9.Ds9Error:\n print()\n\n my_array = np.zeros((256,256), dtype = np.int32)\n \n xs = xyt_array[:, 0] \n ys = xyt_array[:, 1] \n \n# for x,y in zip(xs,ys):\n# my_array[y,x] += 1\n \n n_counts = 0\n for x,y in zip(xs,ys):\n if n_counts >= 1000000: break\n n_counts += 1\n my_array[y,x] += 1\n \n my_image = makeImageFromArray(my_array)\n if display: ds9.mtv(my_image)\n \n return my_image\n \n \ndef Make3DScatter(xs, ys, ts, tmin = -9999999, tmax = 9999999, xminmax = [0,255], yminmax = [0,255], savefile = ''):\n import pylab as pl\n import numpy as np\n \n fig = pl.figure()\n ax = fig.add_subplot(111, projection='3d')\n \n w = np.where(ts >= tmin and ts <= tmax)\n ax.scatter(xs[w], ys[w], ts[w])\n pl.xlim(xminmax)\n pl.ylim(yminmax)\n if savefile != '':\n fig.savefig(savefile)\n else:\n pl.show()\n","sub_path":"old/my_functions.py","file_name":"my_functions.py","file_ext":"py","file_size_in_byte":38833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"506400041","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 5 09:25:55 2021\r\n\r\n@author: amol\r\n\"\"\"\r\nimport time\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom .error_manager import ErrorManager\r\n\r\nclass PCDNNV2ExperimentExecutor:\r\n def __init__(self):\r\n self.dm = None\r\n self.modelType = None\r\n self.model = None\r\n self.df_experimentTracker = None\r\n self.fit_time = None\r\n self.pred_time = None\r\n self.err = None\r\n self.df_err = None \r\n self.predicitions = None\r\n self.errManager = ErrorManager()\r\n self.modelFactory = None\r\n self.min_mae = 0\r\n \r\n def setModel(self,model):\r\n self.model = model\r\n \r\n def setModelFactory(self,modelFactory):\r\n self.modelFactory = modelFactory \r\n \r\n def getPredicitons(self):\r\n return self.predicitions\r\n\r\n \r\n def executeSingleExperiment(self,noOfInputNeurons,dataSetMethod,dataType,inputType,ZmixPresent,noOfCpv,concatenateZmix,kernel_constraint,kernel_regularizer,activity_regularizer):\r\n\r\n \r\n print(\"--------------------self.build_and_compile_pcdnn_v2_model----------------------\")\r\n \r\n self.model = self.modelFactory.build_and_compile_model(noOfInputNeurons,noOfCpv,concatenateZmix,kernel_constraint,kernel_regularizer,activity_regularizer)\r\n \r\n self.model.summary()\r\n\r\n # dataSetMethod,noOfCpvs, ipscaler, opscaler\r\n ipscaler = \"MinMaxScaler\"\r\n opscaler = \"MinMaxScaler\"\r\n self.dm.createTrainTestData(dataSetMethod,noOfCpv, ipscaler, opscaler)\r\n\r\n self.modelFactory.experimentSettings = {\"dataSetMethod\": dataSetMethod,\"ipscaler\":ipscaler, \"opscaler\":opscaler, \"noOfCpv\": noOfCpv, \"ZmixPresent\": ZmixPresent, \"concatenateZmix\": concatenateZmix,\"kernel_constraint\":kernel_constraint,\"kernel_regularizer\":kernel_regularizer,\"activity_regularizer\":activity_regularizer }\r\n\r\n X_train, X_test, Y_train, Y_test, rom_train, rom_test, zmix_train, zmix_test = self.dm.getTrainTestData() \r\n \r\n self.fitModelAndCalcErr(X_train, Y_train, X_test, Y_test,None, None, zmix_train, zmix_test, self.dm.outputScaler, concatenateZmix,kernel_constraint,kernel_regularizer,activity_regularizer)\r\n\r\n #['Model','Dataset','Cpv Type','#Cpv',\"ZmixExists\",'MAE','TAE','MSE','TSE','#Pts','FitTime','PredTime','MAX-MAE','MAX-TAE','MAX-MSE','MAX-TSE','MIN-MAE','MIN-TAE','MIN-MSE','MIN-TSE']\r\n\r\n experimentResults = [self.modelType, dataType,inputType,str(noOfCpv), ZmixPresent,kernel_constraint,kernel_regularizer,activity_regularizer,str(self.df_err['MAE'].mean()),str(self.df_err['TAE'].mean()),str(self.df_err['MSE'].mean()),str(self.df_err['TSE'].mean()),str(self.df_err['#Pts'].mean()),str(self.fit_time),str(self.pred_time),str(self.df_err['MAE'].max()),str(self.df_err['TAE'].max()),str(self.df_err['MSE'].max()),str(self.df_err['TSE'].max()),str(self.df_err['MAE'].min()),str(self.df_err['TAE'].min()),str(self.df_err['MSE'].min()),str(self.df_err['TSE'].min())]\r\n\r\n self.df_experimentTracker.loc[len(self.df_experimentTracker)] = experimentResults \r\n\r\n printStr = \"self.modelType: \"+ self.modelType+ \" dataType: \" + dataType+ \" inputType:\"+inputType+ \" noOfCpv:\"+str(noOfCpv)+ \" ZmixPresent:\" + ZmixPresent + \" MAE:\" +str(self.df_err['MAE'].min())\r\n\r\n print(printStr)\r\n\r\n printStr = \"\\t\"\r\n\r\n printStr = printStr.join(experimentResults)\r\n\r\n\r\n\r\n def fitModelAndCalcErr(self,X_train, Y_train, X_test, Y_test, rom_train = None, rom_test = None, zmix_train = None, zmix_test = None, Y_scaler = None, concatenateZmix = 'N',kernel_constraint = 'Y',kernel_regularizer = 'Y',activity_regularizer = 'Y'):\r\n\r\n fit_times = []\r\n \r\n pred_times = []\r\n \r\n errs = []\r\n \r\n \r\n #TODO:uncomment \r\n #for itr in range(1,11):\r\n \r\n #TODO:comment \r\n for itr in range(1,2): \r\n \r\n t = time.process_time()\r\n\r\n if concatenateZmix == 'Y':\r\n history = self.model.fit({\"species_input\":X_train, \"zmix\":zmix_train}, {\"prediction\":Y_train},validation_split=0.2,verbose=0,epochs=100)\r\n #history = self.model.fit([X_train, zmix_train], Y_train,validation_split=0.2,verbose=0,epochs=100)\r\n else:\r\n history = self.model.fit({\"species_input\":X_train}, {\"prediction\":Y_train},validation_split=0.2,verbose=0,epochs=100)\r\n \r\n #self.plot_loss_physics_and_regression(history)\r\n \r\n fit_times.append(time.process_time() - t)\r\n \r\n t = time.process_time()\r\n\r\n if concatenateZmix == 'Y':\r\n predictions = self.model.predict({\"species_input\":X_test, \"zmix\":zmix_test})\r\n else:\r\n predictions = self.model.predict({\"species_input\":X_test})\r\n \r\n pred_times.append(time.process_time() - t)\r\n \r\n self.predicitions = predictions\r\n \r\n Y_pred = predictions\r\n \r\n\r\n if Y_scaler is not None:\r\n Y_pred = Y_scaler.inverse_transform(Y_pred)\r\n \r\n \r\n #sns.residplot(Y_pred.flatten(), getResiduals(Y_test,Y_pred))\r\n\r\n curr_errs = self.errManager.computeError (Y_pred, Y_test)\r\n \r\n if (len(errs) == 0) or ((len(errs) > 0) and (curr_errs[2] < self.min_mae)) :\r\n self.min_mae = curr_errs[2]#MAE\r\n self.modelFactory.saveCurrModelAsBestModel()\r\n \r\n errs.append(curr_errs)\r\n \r\n \r\n \r\n \r\n self.fit_time = sum(fit_times)/len(fit_times)\r\n \r\n self.pred_time = sum(pred_times)/len(pred_times)\r\n \r\n #computeAndPrintError(Y_pred, Y_test)\r\n\r\n self.df_err = pd.DataFrame(errs, columns = ['TAE', 'TSE', 'MAE', 'MSE', 'MAPE', '#Pts'])\r\n \r\n return \r\n\r\n def executeExperiments(self,dataManager, modelType, df_experimentTracker):\r\n self.dm = dataManager\r\n self.modelType = modelType\r\n self.df_experimentTracker = df_experimentTracker\r\n \r\n #Experiments \r\n \r\n #TODO:uncomment\r\n #dataTypes = [\"randomequaltraintestsplit\",\"frameworkincludedtrainexcludedtest\"]\r\n #inputTypes = [\"AllSpecies\",\"AllSpeciesAndZmix\"]\r\n \r\n\r\n #TODO:comment\r\n dataTypes = [\"randomequaltraintestsplit\"]\r\n inputTypes = [\"AllSpeciesAndZmix\"]\r\n \r\n \r\n \r\n concatenateZmix = 'N'\r\n \r\n #TODO:uncomment\r\n #kernel_constraints = ['Y','N']\r\n #kernel_regularizers = ['Y','N']\r\n #activity_regularizers = ['Y','N'] \r\n \r\n #TODO:comment\r\n kernel_constraints = ['Y']\r\n kernel_regularizers = ['Y']\r\n activity_regularizers = ['Y'] \r\n \r\n for dataType in dataTypes:\r\n print('=================== ' + dataType + ' ===================')\r\n \r\n for inputType in inputTypes:\r\n \r\n print('------------------ ' + inputType + ' ------------------')\r\n \r\n #ZmixCpv_randomequaltraintestsplit\r\n dataSetMethod = inputType + '_' + dataType\r\n \r\n self.modelFactory.setDataSetMethod(dataSetMethod)\r\n \r\n noOfNeurons = 53\r\n\r\n if inputType.find('Zmix') != -1:\r\n ZmixPresent = 'Y'\r\n concatenateZmix = 'Y'\r\n else:\r\n ZmixPresent = 'N'\r\n concatenateZmix = 'N'\r\n \r\n #TODO:uncomment \r\n #noOfCpvs = [item for item in range(2, 6)]\r\n\r\n #TODO:comment \r\n noOfCpvs = [item for item in range(2, 3)]\r\n\r\n for noOfCpv in noOfCpvs:\r\n for kernel_constraint in kernel_constraints:\r\n for kernel_regularizer in kernel_regularizers:\r\n for activity_regularizer in activity_regularizers:\r\n \r\n self.executeSingleExperiment(noOfNeurons,dataSetMethod,dataType,inputType,ZmixPresent,noOfCpv,concatenateZmix,kernel_constraint,kernel_regularizer,activity_regularizer)\r\n \r\n \r\n def plot_loss_physics_and_regression(self,history):\r\n \r\n f = plt.figure(figsize=(10,3))\r\n ax = f.add_subplot(121)\r\n ax2 = f.add_subplot(122)\r\n\r\n ax.plot(history.history['prediction_loss'], label='loss')\r\n ax.plot(history.history['val_prediction_loss'], label='val_loss')\r\n ax.set_title('Souener Prediction Loss')\r\n ax.set(xlabel='Epoch', ylabel='Souener Error')\r\n ax.legend()\r\n\r\n ax2.plot(history.history['physics_loss'], label='loss')\r\n ax2.plot(history.history['val_physics_loss'], label='val_loss')\r\n ax2.set_title('Physics Loss')\r\n ax2.set(xlabel='Epoch', ylabel='Physics Error')\r\n ax2.legend() \r\n \r\n","sub_path":"src/experiment_executor/pcdnn_v2_experiment_executor.py","file_name":"pcdnn_v2_experiment_executor.py","file_ext":"py","file_size_in_byte":9221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"471853449","text":"#!/usr/bin/python3\n#- Note python 3.6 or later now required!\nfrom termcolor import cprint\nfrom os import path\nfrom importlib import reload\nimport devices\nimport settings\nimport traceback\nimport datetime\nimport threading\nimport configparser\nimport sys\nimport getopt\nimport time\nimport netaddr\nimport signal\nimport socket\nimport errno\nimport json\nimport macros\nimport re\nimport collections\nimport platform\nimport pdb\nimport socketserver\nimport http.server\nimport mimetypes\n\nfrom plugins import device_broadlink\nfrom plugins import device_url\nfrom plugins import device_gpio\nfrom plugins import device_scheduler\nfrom plugins import device_virtual\n\ndef reloadAll():\n reload(devices)\n reload(device_broadlink)\n reload(device_url)\n reload(device_gpio)\n reload(device_scheduler)\n reload(device_virtual)\n reload(settings)\n\nTHROTTLE = 4 #- spawn per second\n\n\nclass Thread(threading.Thread):\n def __init__(self, i, sock, addr, timeout):\n threading.Thread.__init__(self)\n self.i = i\n self.sock = sock\n self.addr = addr\n self.timeout = timeout\n self.daemon = True\n time.sleep(self.i/THROTTLE)\n self.start()\n\n def run(self):\n httpd = http.server.HTTPServer(self.addr, Handler, False)\n\n # Prevent the HTTP server from re-binding every handler.\n # https://stackoverflow.com/questions/46210672/\n httpd.socket = self.sock\n httpd.server_bind = self.server_close = lambda self: None\n while not InterruptRequested.is_set():\n timer = min(self.timeout,macros.eventList.nextEvent())\n while timer < 1:\n event = macros.eventList.pop()\n cprint (\"EVENT (%s) %s/%s\" % (datetime.datetime.now().strftime(\"%I:%M:%S\"),event.params['device'],event.name),\"blue\")\n if event.name.startswith(\"POLL_\"):\n (POLL,devicename,argname) = event.name.split('_',2)\n value = devices.Dev[devicename][\"pollCallback\"](devicename,argname,event.command,event.params)\n if value is not False:\n if value is not None and value != '':\n setStatus(argname,str(value),event.params)\n sendCommand(event.command,event.params)\n else:\n sendCommand(event.command,event.params)\n print ('')\n timer = min(self.timeout,macros.eventList.nextEvent())\n httpd.timeout = timer\n httpd.handle_request()\n\n\nclass Handler(http.server.BaseHTTPRequestHandler):\n Parameters = collections.defaultdict(lambda : ' ')\n def _set_headers(self,path):\n self.send_response(200)\n filetype = 'application/json'\n (guesstype,encoding) = mimetypes.guess_type(path,False)\n if guesstype is not None:\n filetype = guesstype\n if encoding is not None:\n self.send_header('Content-Encoding', encoding)\n self.send_header('Content-Type', filetype)\n self.send_header('Access-Control-Allow-Origin','*')\n self.end_headers()\n\n def client_ip(self):\n remote_ip = self.headers.get('X-Forwarded-For', self.headers.get('X-Real-Ip', self.client_address[0]))\n return remote_ip\n\n def log_message(self, format, *args):\n sys.stderr.write(\"%s - - [%s] %s\\n\" %\n (self.client_ip(),self.log_date_time_string(),format%args))\n\n def do_GET(self):\n try:\n if GlobalPassword:\n try:\n if RestrictAccess and self.client_ip() not in RestrictAccess:\n return self.access_denied()\n return self.messageHandler()\n except NameError as e:\n cprint (\"Error: %s\" % e,\"yellow\")\n traceback.print_exc()\n self.password_required()\n except NameError: #- No security specified\n self.messageHandler()\n\n def do_POST(self):\n password = ''\n try:\n content_len = int(self.headers.get('content-length', 0))\n self.Parameters.update(json.loads(self.rfile.read(content_len).decode(\"utf-8\")))\n password = self.Parameters['password'];\n except:\n traceback.print_exc()\n pass\n try:\n if GlobalPassword and GlobalPassword == password:\n return self.messageHandler()\n else:\n cprint ('''POST Password Wrong: \"%s\"''' % password,\"red\")\n except NameError:\n return self.password_required()\n self.password_required()\n\n def password_required(self):\n response = \"POST Password required from %s\" % self.client_ip()\n self.wfile.write(bytes('''{ \"error\": \"%s\" }''' % response,'utf-8'))\n cprint (response,\"red\")\n self.close_connection = 1\n return False\n\n def access_denied(self):\n response = \"Client %s is not allowed to use GET!\" % self.client_ip()\n self.wfile.write(bytes('''{ \"error\": \"%s\" }''' % response,'utf-8'))\n cprint (response,\"red\")\n self.close_connection = 1\n return False\n\n def messageHandler(self):\n if 'favicon' in self.path:\n return False\n\n if '..' in self.path:\n return False\n\n self._set_headers(self.path)\n if '?' in self.path:\n (self.path,query) = self.path.split('?')\n params = re.split('[&=]+',query)\n for index in range(0,len(params),2):\n self.Parameters[params[index]] = params[index+1]\n paths = re.split('[//=]+',self.path)\n if 'learnCommand' in self.path:\n try:\n if self.client_ip() not in LearnFrom:\n cprint (\"Won't learn commands from %s. Access Denied!\" % self.client_ip(),\"red\",attrs=['bold'])\n return False\n except NameError:\n pass\n\n if paths[2] == 'learnCommand':\n deviceName = paths[1]\n commandName = paths[3]\n else:\n commandName = paths[2]\n deviceName = devices.Dev['default']\n self.Parameters[\"device\"] = deviceName\n result = learnCommand(commandName,self.Parameters)\n if result == False:\n response = \"Failed: No command learned\"\n else:\n response = \"Learned: %s\" % commandName\n\n elif 'sendCommand' in self.path:\n if paths[2] == 'sendCommand':\n deviceName = paths[1]\n commandName = paths[3]\n else:\n commandName = paths[2]\n deviceName = devices.Dev['default']\n self.Parameters[\"device\"] = deviceName\n result = sendCommand(commandName, self.Parameters)\n if result == False:\n response = \"Failed: Unknown command - %s\" % commandName\n elif result == True:\n response = commandName\n else:\n response = result\n\n elif 'getStatus' in self.path:\n if paths[2] == 'getStatus':\n commandName = paths[3]\n deviceName = paths[1]\n else:\n commandName = paths[2]\n deviceName = devices.Dev['default']\n self.Parameters[\"device\"] = deviceName\n status = getStatus(commandName,self.Parameters)\n if (status):\n response = '''{ \"%s\": \"%s\" }''' % (commandName,status)\n else:\n response = \"Failed: Unknown command - %s\" % commandName\n\n elif 'setStatus' in self.path:\n if paths[2] == 'setStatus':\n commandName = paths[3]\n deviceName = paths[1]\n status = paths[4]\n else:\n commandName = paths[2]\n deviceName = devices.Dev['default']\n status = paths[3]\n self.Parameters[\"device\"] = deviceName\n result = setStatus(commandName, status, self.Parameters)\n if (result):\n response = '''{ \"%s\": \"%s\" }''' % (commandName, result)\n else:\n response = \"Failed: Unknown command - %s\" % commandName\n\n elif 'toggleStatus' in self.path:\n if paths[2] == 'toggleStatus':\n commandName = paths[3]\n deviceName = paths[1]\n else:\n commandName = paths[2]\n deviceName = devices.Dev['default']\n self.Parameters[\"device\"] = deviceName\n status = toggleStatus(commandName, self.Parameters)\n if (status):\n response = '''{ \"%s\": \"%s\" }''' % (commandName, status)\n else:\n response = \"Failed: Unknown command - %s\" % commandName\n\n #- Should UI based commands really be local only?\n elif 'listEvents' in self.path:\n if RestrictAccess and self.client_ip() not in RestrictAccess:\n return self.access_denied()\n response = macros.eventList.dump()\n\n elif 'listDevices' in self.path:\n if RestrictAccess and self.client_ip() not in RestrictAccess:\n return self.access_denied()\n response = devices.dumpDevices()\n\n elif 'listRooms' in self.path:\n if RestrictAccess and self.client_ip() not in RestrictAccess:\n return self.access_denied()\n response = devices.dumpRooms()\n\n elif 'listStatus' in self.path:\n if RestrictAccess and self.client_ip() not in RestrictAccess:\n return self.access_denied()\n if paths[2] == 'listStatus':\n section = paths[1] + \" Status\"\n else:\n section = \"Status\"\n response = '''{\\n\\t\"ok\": \"%s\"\\n''' % section\n for var in settingsFile.options(section):\n response += '''\\t\"%s\": \"%s\"\\n''' % (var,settingsFile.get(section,var))\n response += '''}'''\n\n elif 'deleteEvent' in self.path:\n if paths[2] == 'deleteEvent':\n event = paths[3]\n else:\n event = paths[2]\n retval = macros.eventList.delete(event)\n if retval is not None:\n response = '''{ \"ok\": \"%s deleted\" }''' % retval.name\n else:\n response = \"Failed - no such event: %s\" % event\n\n elif '/ui/' in self.path:\n path = \"ui/\" + settings.DefaultUI + '/' + self.path.split('/ui/',1)[1]\n socket = self.connection\n with open(path,'rb') as f:\n socket.sendfile(f,0)\n cprint(\"\\t%s\\n\" % path)\n return\n\n elif 'getSensor' in self.path:\n if paths[2] == 'getSensor':\n sensor = paths[3]\n deviceName = paths[1]\n else:\n sensor = paths[2]\n deviceName = devices.Dev['default']\n self.Parameters[\"device\"] = deviceName\n result = getSensor(sensor, self.Parameters)\n if result == False:\n response = \"Failed to get data\"\n else:\n response = '''{ \"%s\": \"%s\" }''' % (sensor, result)\n else:\n response = \"Failed\"\n if \"Failed\" in response or \"error\" in response:\n self.wfile.write(bytes('''{ \"error\": \"%s\" }\\n''' % response,'utf-8'))\n elif response.startswith('{'):\n self.wfile.write(bytes(response+\"\\n\",'utf-8'))\n else:\n self.wfile.write(bytes('''{ \"ok\": \"%s\" }\\n''' % response,'utf-8'))\n cprint (\"\\t\"+response,\"white\")\n print(\"\")\n\n\ndef sendCommand(commandName,params):\n if commandName.startswith('.') or commandName.startswith('MACRO'):\n return macros.checkMacros(commandName,params)\n if '/' in commandName:\n (deviceName,commandName) = commandName.split('/',1)\n params = params.copy()\n params['device'] = deviceName\n if commandName == \"on\" or commandName == \"off\" or commandName == \"dim\" or commandName == \"bright\":\n commandName = (deviceName + commandName).lower()\n else:\n deviceName = params['device']\n if deviceName in devices.DeviceByName:\n device = devices.DeviceByName[deviceName]\n serviceName = deviceName + ' Commands'\n else:\n return \"Failed: No such device, %s\" % deviceName\n if \"deviceDelay\" not in params:\n params[\"deviceDelay\"] = device.delay\n if params[\"deviceDelay\"] == None:\n params[\"deviceDelay\"] = 0.2\n params[\"command\"] = commandName #- VERY IMPORTANT!\n\n if commandName is None or commandName is False or type(commandName) is bool:\n cprint (\"Check your setting.ini for invalid syntax!!\",\"yellow\")\n traceback.print_exc()\n return False\n if commandName.strip() != '':\n result = macros.checkConditionals(commandName,params)\n if result:\n return result\n command = newCommandName = False\n isRepeat = False\n if 'PRINT' not in commandName and 'MACRO' not in commandName and '.' not in commandName:\n if commandName.endswith(\"on\"):\n newCommandName = commandName[:-2]\n params[commandName + ' side-effect'] = True\n if setStatus(newCommandName, '1', params) == \"1\":\n isRepeat = True\n elif commandName.endswith(\"off\"):\n newCommandName = commandName[:-3]\n params[commandName + ' side-effect'] = True\n if setStatus(newCommandName, '0', params) == \"0\":\n isRepeat = True\n\n if settingsFile.has_option(serviceName, commandName):\n command = settingsFile.get(serviceName, commandName)\n elif settingsFile.has_option('Commands', commandName):\n command = settingsFile.get('Commands', commandName)\n if command is False and isRepeat is False:\n if settingsFile.has_option(serviceName, newCommandName):\n command = settingsFile.get(serviceName, newCommandName)\n params['command'] = newCommandName\n elif settingsFile.has_option('Commands', newCommandName):\n command = settingsFile.get('Commands', newCommandName)\n params['command'] = newCommandName\n elif command is False and isRepeat is True:\n #- If we have a defined \"toggle\", ignore it.\n #- Otherwise, it's not a toggle and send it through\n if settingsFile.has_option('Commands', newCommandName):\n return \"fail: %s was ignored\" % commandName\n if command is False:\n result = macros.checkMacros(commandName,params)\n else:\n result = macros.checkMacros(command,params)\n if result:\n return result\n\n with devices.Dev[deviceName]['Lock']:\n send = devices.Dev[deviceName]['sendCommand']\n if send is not None:\n result = send(command,device,deviceName,params)\n if result:\n return commandName\n return False\n\ndef learnCommand(commandName, params):\n deviceName = params[\"device\"]\n try:\n if deviceName in devices.DeviceByName:\n device = devices.DeviceByName[deviceName];\n sectionName = deviceName + ' Commands'\n else:\n cprint (\"Failed: No such device, %s\" % deviceName,\"yellow\")\n return False\n if OverwriteProtected and settingsFile.has_option(sectionName,commandName):\n cprint (\"Command %s alreadyExists and changes are protected!\" % commandName,\"yellow\")\n return False\n except Exception as e:\n traceback.print_exc()\n\n with devices.Dev[deviceName]['Lock']:\n cprint (\"Waiting %d seconds to capture command\" % GlobalTimeout,\"magenta\")\n\n decodedCommand = devices.Dev[deviceName]['learnCommand'](deviceName,device,params)\n with devices.SettingsLock:\n settings.backupSettings()\n try:\n ControlIniFile = open(path.join(settings.applicationDir, 'settings.ini'), 'w')\n if not settingsFile.has_section(sectionName):\n settingsFile.add_section(sectionName)\n settingsFile.set(sectionName, commandName, str(decodedCommand,'utf8'))\n settingsFile.write(ControlIniFile)\n ControlIniFile.close()\n return commandName\n except Exception as e:\n cprint(\"Error writing settings file: %s\" % e,\"yellow\")\n traceback.print_exc()\n settings.restoreSettings()\n return False\n\n\n#- The setStatus command is not designed to perform actions, use sendCommand\n#- instead with on/off appended or pass a parameter. Use setStatus for\n#- setting variables.\ndef setStatus(commandName, status, params):\n if '/' in commandName:\n (deviceName,commandName) = commandName.split('/')\n params = params.copy()\n params['device'] = deviceName\n else:\n deviceName = params[\"device\"]\n if 'globalVariable' not in params or params['globalVariable'] != commandName:\n sectionName = deviceName + \" Status\"\n else:\n sectionName = 'Status' #- Where the variables are stored\n\n #print (\"setStatus command = %s status = %s devicename = %s section = %s\" % (commandName, status, deviceName, sectionName))\n settings.backupSettings()\n oldvalue = getStatus(commandName,params)\n section = \"TRIGGER \" + commandName #- Where trigger commands are stored\n if oldvalue == status:\n default= \"Value of %s/%s not changed: %s\" % (deviceName,commandName, status)\n if settingsFile.has_option(section, \"nop\"):\n rawcommand = settingsFile.get(section,\"nop\")\n else:\n rawcommand = \".PRINT %s\" % default\n macros.eventList.add(\"%s-NOP\" % commandName,0,rawcommand,params)\n params[commandName+' side-effect'] = True\n return oldvalue\n func = devices.Dev[deviceName][\"setStatus\"]\n if func is not None:\n retval = func(deviceName,commandName,params,oldvalue,status)\n try:\n with devices.SettingsLock:\n if not settingsFile.has_section(sectionName):\n settingsFile.add_section(sectionName)\n ControlIniFile = open(path.join(settings.applicationDir, 'settings.ini'), 'w')\n settingsFile.set(sectionName, commandName, str(status))\n settingsFile.write(ControlIniFile)\n ControlIniFile.close()\n except Exception as e:\n cprint (\"Error writing settings file: %s\" % e,\"yellow\")\n traceback.print_exc()\n settings.restoreSettings()\n return oldvalue\n if settingsFile.has_section(section):\n params['value'] = status\n params['oldvalue'] = oldvalue\n if settingsFile.has_option(section, \"command\"):\n rawcommand = settingsFile.get(section, \"command\")\n params[commandName+' side-effect'] = True\n macros.eventList.add(\"%s-TRIGGER\" % commandName,0,rawcommand,params)\n else:\n try:\n if status == \"1\":\n rawcommand = settingsFile.get(section,\"on\")\n else:\n rawcommand = settingsFile.get(section,\"off\")\n if rawcommand is not None:\n params[commandName+' side-effect'] = True\n macros.eventList.add(\"%s-TRIGGER\" % commandName,0,rawcommand,params)\n except Exception as e:\n cprint(\"TRIGGER %s: A command or on/off pair is required\" % commandName, \"yellow\")\n cprint (\"ERROR was %s\" % e,\"yellow\")\n elif settingsFile.has_section(\"LOGIC \"+commandName):\n params[commandName+' side-effect'] = True\n macros.eventList.add(\"%s-LOGIC\" % commandName,0,commandName,params)\n cprint (\"Queued LOGIC branch: %s\" % commandName,\"cyan\")\n return oldvalue\n\n#- Use getStatus to read variables, either from the settings file or device\ndef getStatus(commandName, params):\n if '/' in commandName:\n (deviceName,commandName) = commandName.split('/')\n params = params.copy()\n params['device'] = deviceName\n else:\n deviceName = params[\"device\"]\n sectionName = deviceName + \" Status\"\n\n device = devices.DeviceByName[deviceName]\n func = devices.Dev[deviceName][\"getStatus\"]\n if func is not None:\n #print (\"getStatus func(%s) is %s\" % (type(func),func))\n retval = func(device,deviceName,commandName,params)\n if retval is not False:\n if 'REDIRECT' in retval:\n (command,deviceName) = retval.split(' ',2)\n sectionName = deviceName + \" Status\"\n else:\n return retval\n if settingsFile.has_option(sectionName,commandName):\n status = settingsFile.get(sectionName, commandName)\n return status\n if settingsFile.has_option('Status',commandName):\n status = settingsFile.get('Status', commandName)\n params[\"globalVariable\"] = commandName\n if status:\n return status\n print (\"Can't find %s %s\" % (sectionName, commandName))\n return \"0\"\n\n\ndef toggleStatus(commandName, params):\n status = getStatus(commandName,params)\n # print (\"Status = %s\" % status)\n try:\n if status == \"0\":\n setStatus(commandName,\"1\",params)\n else:\n setStatus(commandName,\"0\",params)\n except:\n pass\n return getStatus(commandName,params)\n\n\ndef getSensor(sensorName,params):\n if '/' in sensorName:\n (deviceName,sensorName) = sensorName.split('/')\n params = params.copy()\n params['device'] = deviceName\n else:\n deviceName = params['device']\n with devices.Dev[deviceName]['Lock']:\n func = devices.Dev[deviceName][\"getSensor\"]\n if func is not None:\n return func(sensorName,params)\n return False\n\n\ndef start(handler_class=Handler, threads=8, port=8080, listen='0.0.0.0', timeout=20):\n addr = (listen,port)\n if settings.Hostname == \"localhost\":\n name=''\n else:\n name = settings.Hostname + \" \"\n cprint ('\\nStarting RestHome server %son %s:%s ...\\n' % (name,listen,port),\"yellow\")\n sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(addr)\n sock.listen(5)\n\n [Thread(i,sock,addr,timeout) for i in range(threads)]\n while not InterruptRequested.is_set():\n InterruptRequested.wait(timeout)\n cprint(\"Closing Server ...\", \"green\")\n sock.close()\n\n\n\ndef readSettingsFile(settingsFile):\n global RestrictAccess\n global LearnFrom\n global OverwriteProtected\n global GlobalPassword\n global GlobalTimeout\n\n # A few defaults\n serverPort = 8080\n Autodetect = False\n OverwriteProtected = True\n listen_address = '0.0.0.0'\n broadcast_address = '255.255.255.255'\n\n settingsFile.optionxform = str\n with devices.SettingsLock:\n settingsFile.read(settings.settingsINI)\n\n GlobalTimeout = settings.GlobalTimeout\n DiscoverTimeout = settings.DiscoverTimeout\n\n # Override them\n if settingsFile.has_option('General', 'Password'):\n GlobalPassword = settingsFile.get('General', 'Password').strip()\n\n if settingsFile.has_option('General', 'ServerPort'):\n serverPort = int(settingsFile.get('General', 'ServerPort'))\n\n if settingsFile.has_option('General','ServerAddress'):\n listen_address = settingsFile.get('General', 'ServerAddress')\n if listen_address.strip() == '':\n listen_address = '0.0.0.0'\n\n if settingsFile.has_option('General', 'RestrictAccess'):\n RestrictAccess = settingsFile.get('General', 'RestrictAccess').strip()\n\n if settingsFile.has_option('General', 'MaxThreads'):\n MaxThreads = settingsFile.get('General','MaxThreads')\n else:\n MaxThreads = 8\n if settingsFile.has_option('General', 'LearnFrom'):\n LearnFrom = settingsFile.get('General', 'LearnFrom').strip();\n\n if settingsFile.has_option('General', 'AllowOverwrite'):\n OverwriteProtected = False\n\n if settingsFile.has_option('General','BroadcastAddress'):\n broadcast = settingsFile.get('General', 'BroadcastAddress')\n if broadcast_address.strip() == '':\n broadcast_address = '255.255.255.255'\n\n if settingsFile.has_option('General', 'Autodetect'):\n try:\n DiscoverTimeout = int(settingsFile.get('General', 'Autodetect').strip())\n except:\n DiscoverTimeout = 5\n Autodetect = True\n settingsFile.remove_option('General','Autodetect')\n\n # Device list\n if not devices.DevList:\n Autodetect = True\n\n if Autodetect == True:\n cprint (\"Beginning device auto-detection ... \",\"cyan\")\n # Try to support multi-homed broadcast better\n devices.discover(settingsFile,DiscoverTimeout,listen_address,broadcast_address)\n print()\n reloadAll()\n return None\n\n if devices.DevList:\n for devname in devices.DevList:\n devices.Dev[devname]['BaseType'] = 'unknown'\n device = devices.readSettings(settingsFile,devname)\n if devices.Dev[devname]['BaseType'] != 'virtual':\n devtype = devices.Dev[devname]['Type']\n devices.Dev[devname]['Lock'] = threading.RLock()\n else:\n devtype = device.real\n\n if 'Comment' in devices.Dev[devname]:\n comment = ' (' + devices.Dev[devname]['Comment'].strip()+')'\n else:\n comment = ''\n print(\"Configured %s%s as %s/%s\" % (devname,comment,devices.Dev[devname]['BaseType'],devtype))\n if not devname in devices.DeviceByName:\n devices.DeviceByName[devname] = device\n #device.hostname = devname\n if hasattr(device, 'auth'):\n device.auth()\n if devices.Dev[devname]['StartupCommand'] != None:\n commandName = devices.Dev[devname]['StartupCommand']\n query = {}\n query[\"device\"] = devname\n macros.eventList.add(\"Startup \"+devname,1,commandName,query)\n\n return { \"port\": serverPort, \"listen\": listen_address, \"threads\": MaxThreads, \"timeout\": GlobalTimeout }\n\n\ndef SigUsr1(signum, frame):\n cprint (\"\\nReload requested ... (this will take awhile)\",\"cyan\")\n InterruptRequested.set()\n\n\ndef SigInt(signum, frame):\n cprint (\"\\nShuting down server ...\",\"cyan\")\n ShutdownRequested.set()\n InterruptRequested.set()\n\n\nif __name__ == \"__main__\":\n ShutdownRequested = threading.Event()\n InterruptRequested = threading.Event()\n\n if platform.system() != \"Windows\":\n signal.signal(signal.SIGUSR1,SigUsr1)\n signal.signal(signal.SIGINT,SigInt)\n while not ShutdownRequested.is_set():\n InterruptRequested.clear()\n settingsFile = configparser.ConfigParser()\n serverParams = None\n while serverParams is None:\n serverParams = readSettingsFile(settingsFile)\n macros.init_callbacks(settingsFile,sendCommand,getStatus,setStatus,toggleStatus)\n devices.startUp(setStatus,getStatus,sendCommand)\n start(**serverParams)\n cprint(\"\\nShutting down devices ...\")\n for devname in devices.DeviceByName:\n if devices.Dev[devname]['ShutdownCommand'] != None:\n commandName = devices.Dev[devname]['ShutdownCommand']\n query = {}\n query[\"device\"] = devname\n query[\"command\"] = commandName\n query['serialize'] = True\n if 'Delay' in devices.Dev[devname]:\n query['deviceDelay'] = float(devices.Dev[devname]['Delay'])\n else:\n query['deviceDelay'] = 0.2\n sendCommand(commandName,query)\n if not ShutdownRequested.is_set():\n time.sleep(20)\n cprint (\"Reloading configuration ...\\n\",\"cyan\")\n reloadAll()\n devices.shutDown(setStatus,getStatus)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":28151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"95896366","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\n\nprint(\"Loading System! Please wait.....\")\n\nscores = pd.read_csv(r'./ml-latest/genome-scores.csv') # Reading datasets\nmvnames = pd.read_csv(r'./ml-latest/movies.csv')\n\n# Data processing. We are rejecting the tags for which mean relevance is less than threshold descried by quantile(0.4)\ng_new = scores.groupby(['tagId']).agg({\"relevance\": [\"mean\", \"std\"]})\n\nqt = g_new.relevance.quantile(0.4) # Threshold for tag rejection\n\ntag_list =[] # Filtering the tags\nfor i in range(1,1128):\n if g_new['relevance']['mean'].iloc[i-1] > qt[0]:\n tag_list.append(i)\n\ndataf_tags = pd.DataFrame(tag_list,columns=['tagId'])\ntags_array = np.asarray(dataf_tags).ravel()\n\n\nscor = pd.merge(scores, dataf_tags, on=['tagId'], how='inner') # Join with main dataset based on reduced tags criteria\n\nscorar = np.asarray(scor)\n\nres = np.reshape(scorar,[677,13176,3])\n\ntrans=np.transpose(res)\n\nfeature_mat = trans[2] # Creating a numpy matrix with row as objects and columns as 677 features\n\nmovieids = np.transpose(trans[0])[0] # List of movieids in final cleaned dataset\nmovieids = list(movieids)\n\nneigh = NearestNeighbors(n_neighbors=4,algorithm='ball_tree').fit(feature_mat) # Nearest neighbor algorithm to get similar movies based on distance in feature space\n\nmvframes = pd.DataFrame(movieids,columns=['movieId'])\nmovienames = pd.merge(mvnames, mvframes, on=['movieId'], how='inner')\n\nemotion_labels = ['joy', 'fear', 'anger', 'sadness', 'disgust', 'shame', 'guilt'] # List of possible input emotions\n\nemotion_dict = {}\n\nfor i in range(len(emotion_labels)): #Mapping between emotion and number which will be used to index in lists \n emotion_dict[emotion_labels[i]] = i\n\nbuckets = [] # List of emotion buckets\nfor i in emotion_labels:\n buckets.append([]) # Each bucket is a list of movies for that emotion\n\n# Pre filled lists with our recommendations\nhappylist = [movienames.iloc[46],movienames.iloc[50],movienames.iloc[52]]\nsadlist = [movienames.iloc[4],movienames.iloc[18],movienames.iloc[19]]\nfearlist = [movienames.iloc[68],movienames.iloc[89],movienames.iloc[90]]\nangerlist = [movienames.iloc[91],movienames.iloc[103],movienames.iloc[111]]\ndisgustlist = [movienames.iloc[141],movienames.iloc[145],movienames.iloc[151]]\nshamelist = [movienames.iloc[154],movienames.iloc[156],movienames.iloc[165]]\nguiltlist = [movienames.iloc[462],movienames.iloc[473],movienames.iloc[487]]\n\nbuckets[emotion_dict['joy']] = happylist\nbuckets[emotion_dict['sadness']] = sadlist\nbuckets[emotion_dict['fear']] = fearlist\nbuckets[emotion_dict['anger']] = angerlist\nbuckets[emotion_dict['disgust']] = disgustlist\nbuckets[emotion_dict['shame']] = shamelist\nbuckets[emotion_dict['guilt']] = guiltlist\n\nbucket_index = np.zeros((7,), dtype=int)\n\nuser_input = 1\n\n# Takes user's mood on terminal for demo purpose only. Actually emotion input comes from Naive Bayes' model 3rd party code that extracts\n# emotion based on sentiment analysis of textual input data\nwhile(user_input != -1): \n\temotion = input(\"\\n\\nHow are you feeling?\\nChoose from this:\\n joy\\n sadness\\n fear\\n anger\\n disgust\\n shame\\n guilt\\n\\nEnter here: \")\n\trecommendations = []\n\tfor i in buckets[emotion_dict[emotion]]:\n\t dist,indices = neigh.kneighbors(np.reshape(feature_mat[movieids.index(i['movieId'])],[1,677])) #Movies similar to that in bucket\n\t for j in range(1,len(indices[0])):\n \trecommendations.append(movienames[movienames.movieId==movieids[indices[0][j]]])\n\tprint(\"Our recommendations for you: \\n\\n\") \n\tprint(recommendations)\n\n\n\tuser_input = int(input(\"\\n\\nSelect which movieId did you see?(Enter -1 to exit!): \\t\")) # Movie that user actually watches\n\tif user_input != -1:\n\t\tprint(movienames.iloc[movieids.index(user_input)])\n\t\tchange = True\n\t\tfor movies in buckets[emotion_dict[emotion]]:\n\t\t if movies.movieId == user_input:\n\t\t change = False\n\n\t\t# Replaces bucket with movie actually watched by user for that emotion hence tuning model according to user's preferences.\n\t\tif change:\n\t\t buckets[emotion_dict[emotion]][bucket_index[emotion_dict[emotion]]] = movienames.iloc[movieids.index(user_input)]\n\t\t bucket_index[emotion_dict[emotion]] = (bucket_index[emotion_dict[emotion]] +1)%3","sub_path":"sentiment_based_movie_recomendation.py","file_name":"sentiment_based_movie_recomendation.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"368628626","text":"# print array in spiral form\n# arr is 2d array, m- rows,, n= columns\ndef print_matrix_spiral_form(arr):\n m= len(arr)\n n= len(arr[0])\n top = 0\n bottom = m-1\n left = 0\n right = n-1\n dir = 0\n\n while top<=bottom and left<=right:\n if dir ==0:\n #print from left to right\n for i in range(left,right+1):\n print(arr[top][i],end=\" \")\n top +=1\n elif dir ==1:\n for i in range(top,bottom+1):\n print(arr[i][right],end=\" \")\n right -=1\n elif dir==2:\n for k in range(right, left - 1, -1):\n print(arr[bottom][k],end=\" \")\n bottom -=1\n elif dir ==3:\n for i in range(bottom, top -1, -1):\n print(arr[i][left],end=\" \")\n left +=1\n dir=(dir+1)%4\n\ndef print_matrix(arr):\n row = len(arr)\n col = len(arr[0])\n for i in range(row):\n for j in range(col):\n print(arr[i][j],end=\" \")\n\ndef print_diagonal_matrix(arr):\n row = len(arr)\n col = len(arr[0])\n for i in range(row):\n for j in range(col):\n if i==j:\n print(arr[i][j],end=\" \")\n\n\ndef print_zig_zag_matrix(arr):\n row = len(arr)\n col = len(arr[0])\n evenRow = 0\n oddRow = 1\n # even rows should be printed straight\n # odd rows should be printed in reverse way\n while evenRow < row:\n for i in range(col):\n print(arr[evenRow][i],end=\" \")\n evenRow += 2\n\n if oddRow < row:\n for i in range(col - 1, -1, -1):\n print(arr[oddRow][i],end=\" \")\n oddRow += 2\n\ndef print_max_row_ones(arr):\n rows= len(arr)\n col= len(arr[0])\n max_index_row = -1\n ones_count =0\n\n for i in range(0,rows):\n ones= col-BS_find_first_occurance(arr[i],1)\n if ones>ones_count:\n ones_count=ones\n max_index_row = i\n\n print(f'Max index counted row is {max_index_row+1} with {ones_count} ones')\n\n\ndef BS_find_first_occurance(arr, x):\n start=0\n end= len(arr)-1\n result =-1\n while(start<=end):\n mid = (start + end) // 2\n if arr[mid]==x:\n result=mid\n end=mid-1\n elif arr[mid] 1e4 else False,\n max_iter=1, n_init=n_init, random_state=0)\n centroid = centroid.astype(np.float32)\n init_proto = torch.from_numpy(centroid)\n if samples.is_cuda:\n init_proto = init_proto.cuda()\n\n #init wc\n if not concat:\n y = torch.zeros(n_proto, 1).long()\n for c in range(n_proto):\n idx = [i for i, l in enumerate(label) if l==c]\n y_proto = y_data[idx]\n y[c] = torch.unique(y_proto, sorted=True)[-1].long()\n init_wc = torch.FloatTensor(n_proto, n_class)\n init_wc.zero_()\n nn.init.xavier_normal_(init_wc)\n\n init_wc.scatter_(1,y,1)\n init_wc = init_wc.transpose(0,1)\n else:\n # sample from input samples to initialize protos and wc\n init_proto = []\n for i in range(n_classes):\n perm = torch.randperm(n_samples)\n idx = perm[:n_proto_per_class]\n init_proto.append(samples.view(n_class,n_samples, -1)[i, idx, :])\n init_proto = torch.stack(init_proto, dim=0).view(n_class*n_proto_per_class, -1)\n init_proto += nn.init.xavier_normal_(torch.zeros_like(init_proto))\n # initialize wc\n if not concat:\n init_wc = torch.FloatTensor(n_proto, n_class)\n init_wc.zero_()\n y = torch.arange(0, n_class).view(n_class, 1, 1).expand(n_class, n_proto_per_class, 1).reshape(n_class*n_proto_per_class,1).long()\n nn.init.xavier_normal_(init_wc)\n init_wc.scatter_(1,y,1)\n init_wc = init_wc.transpose(0,1)\n\n # add hidden layer\n if use_hidden:\n self.hidden = nn.Linear(n_dim, n_dim)\n init_hidden = nn.init.xavier_normal_(torch.zeros_like(self.hidden.weight))\n init_hidden += torch.eye(n_dim, n_dim)\n self.hidden.weight = nn.Parameter(init_hidden)\n else:\n self.hidden = None\n\n # then prototype coordinates\n # shape n_protos x n_dim\n self.prototypes = nn.Parameter(init_proto)\n\n if concat:\n self.output = nn.Linear(n_dim*2, n_classes, bias=False)\n nn.init.xavier_normal_(self.output.weight)\n else:\n self.output = nn.Linear(n_proto, n_classes, bias=False)\n self.output.weight = nn.Parameter(init_wc)\n\n def transform(self, samples, flat=False):\n if flat:\n samples = F.relu(self.hidden(samples))\n else:\n n_class = samples.size(0)\n n_samples = samples.size(1)\n\n samples = F.relu(self.hidden(samples.view(n_class*n_samples, -1)).view(n_class, n_samples, -1))\n return samples\n\n def forward(self, samples):\n n_class = samples.size(0)\n n_samples = samples.size(1)\n if samples.ndimension() != 3:\n samples = samples.view(n_class, n_samples, -1)\n\n if self.hidden is not None:\n samples = self.transform(samples)\n\n dists = euclidean_dist(samples.view(n_class*n_samples, -1), self.prototypes)\n\n qj = F.softmax(-dists/self.temperature, dim=1)\n\n if self.concat:\n # x tilde = qj * pj\n x_tilde = torch.mm(qj, self.prototypes)\n x = samples.view(n_class*n_samples, -1)\n cj = self.output(torch.cat((x, x_tilde), dim=-1))\n else:\n cj = self.output(qj)\n return cj\n\n def proto_proba(self):\n return self.predict_proba(self.prototypes.view(self.n_classes,\n self.n_proto_per_class, -1)).reshape(self.n_proto,-1)\n\n def proto_class(self):\n return self.predict(self.prototypes.view(self.n_classes,\n self.n_proto_per_class, -1)).reshape(-1)\n\n def predict_log_proba(self, samples):\n n_class = samples.size(0)\n n_samples = samples.size(1)\n\n cj = self.forward(samples)\n\n log_p_y = F.log_softmax(cj, dim=1).view(n_class, n_samples, -1)\n return log_p_y\n\n def predict(self, samples):\n n_class = samples.size(0)\n n_samples = samples.size(1)\n\n cj = self.forward(samples)\n\n log_p_y = F.log_softmax(cj, dim=1).view(n_class, n_samples, -1)\n _, y_hat = log_p_y.max(2)\n return y_hat\n\n def predict_proba(self, samples):\n n_class = samples.size(0)\n n_samples = samples.size(1)\n\n cj = self.forward(samples)\n\n p_y = F.softmax(cj, dim=1).view(n_class, n_samples, -1)\n return p_y\n\n def score(self, samples):\n n_class = samples.size(0)\n n_samples = samples.size(1)\n\n target_inds = torch.arange(0, n_class).view(n_class, 1, 1).expand(n_class, n_samples, 1).long()\n target_inds = Variable(target_inds, requires_grad=False)\n if samples.is_cuda:\n target_inds = target_inds.cuda()\n\n y_hat = self.predict(samples)\n acc_val = torch.eq(y_hat, target_inds.squeeze()).float().mean()\n return acc_val\n\n def loss(self, samples):\n n_class = samples.size(0)\n n_samples = samples.size(1)\n\n target_inds = torch.arange(0, n_class).view(n_class, 1, 1).expand(n_class, n_samples, 1).long()\n target_inds = Variable(target_inds, requires_grad=False)\n\n if samples.is_cuda:\n target_inds = target_inds.cuda()\n\n log_p_y = self.predict_log_proba(samples)\n\n loss_val = -log_p_y.gather(2, target_inds).squeeze().view(-1).mean()\n\n return loss_val\n\n def fit(self, samples, lr=1e-1, max_epochs=1000):\n optimizer = torch.optim.Adam(\n self.parameters(), lr=lr, weight_decay=1e-4)\n #scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer)\n for e in range (0, max_epochs):\n optimizer.zero_grad()\n loss = self.loss(samples)\n loss.backward(retain_graph=True)\n optimizer.step()\n #scheduler.step(loss)\n return self\n\n\nclass Protonet(nn.Module):\n def __init__(self, encoder, multiproto=True, concat=True):\n super(Protonet, self).__init__()\n\n self.encoder = encoder\n self.multiproto = multiproto\n self.concat = concat\n\n\n def loss(self, sample):\n xs = Variable(sample['xs']) # support\n xq = Variable(sample['xq']) # query\n\n n_class = xs.size(0)\n assert xq.size(0) == n_class\n n_support = xs.size(1)\n n_query = xq.size(1)\n\n target_inds = torch.arange(0, n_class).view(n_class, 1, 1).expand(n_class, n_query, 1).long()\n target_inds = Variable(target_inds, requires_grad=False)\n\n if xq.is_cuda:\n target_inds = target_inds.cuda()\n\n x = torch.cat([xs.view(n_class * n_support, *xs.size()[2:]),\n xq.view(n_class * n_query, *xq.size()[2:])], 0)\n\n z = self.encoder.forward(x)\n z_dim = z.size(-1)\n\n zs = z[:n_class*n_support].view(n_class, n_support, z_dim)\n zq = z[n_class*n_support:]\n\n if self.multiproto:\n n_proto=2*n_class\n support_model = Multiproto(zs,\n z_dim, n_proto, n_class,\n concat=self.concat,\n init='random')\n if zs.is_cuda:\n support_model = support_model.cuda()\n support_model.fit(zs, lr=1e-1,\n max_epochs=200)\n zq = zq.view(n_class, n_query, z_dim)\n log_p_y = support_model.predict_log_proba(zq)\n else:\n z_proto = zs.mean(1)\n\n dists = euclidean_dist(zq, z_proto)\n\n log_p_y = F.log_softmax(-dists, dim=1).view(n_class, n_query, -1)\n\n loss_val = -log_p_y.gather(2, target_inds).squeeze().view(-1).mean()\n\n _, y_hat = log_p_y.max(2)\n acc_val = torch.eq(y_hat, target_inds.squeeze()).float().mean()\n\n return loss_val, {\n 'loss': loss_val.item(),\n 'acc': acc_val.item()\n }\n\n@register_model('protonet_conv')\ndef load_protonet_conv(**kwargs):\n x_dim = kwargs['x_dim']\n hid_dim = kwargs['hid_dim']\n z_dim = kwargs['z_dim']\n\n def conv_block(in_channels, out_channels):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n nn.MaxPool2d(2)\n )\n\n encoder = nn.Sequential(\n conv_block(x_dim[0], hid_dim),\n conv_block(hid_dim, hid_dim),\n conv_block(hid_dim, hid_dim),\n conv_block(hid_dim, z_dim),\n Flatten()\n )\n\n return Protonet(encoder, kwargs['multiproto'], kwargs['concat'])\n","sub_path":"protonets/models/few_shot.py","file_name":"few_shot.py","file_ext":"py","file_size_in_byte":10339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"4283219","text":"\"\"\"Machine Learning Time-Series Platform (cesium)\n\nSee http://cesium.mlfor more information.\n\"\"\"\n\nfrom .version import version as __version__\n\n\ndef install():\n \"\"\"Install cesium config file and create data folders.\n\n Copies cesium.yaml.example to ~/.config/cesium/cesium.yaml and creates data\n directories as described in `cesium.config.cfg['paths']`\n \"\"\"\n import os\n import shutil\n from distutils.dir_util import copy_tree\n\n data_src = os.path.join(os.path.dirname(__file__), \"data\")\n data_dst = os.path.expanduser('~/.local/cesium/')\n copy_tree(data_src, data_dst, update=1)\n print(\"Created data directory at {} and copied sample data.\".format(\n os.path.expanduser('~/.local/cesium/')))\n\n cfg = os.path.expanduser('~/.config/cesium/cesium.yaml')\n cfg_dir = os.path.dirname(cfg)\n\n if os.path.exists(cfg):\n print('Existing configuration at {} -- not overwriting.'.format(cfg))\n return\n\n if not os.path.exists(cfg_dir):\n os.makedirs(cfg_dir)\n\n shutil.copyfile(os.path.join(os.path.dirname(__file__),\n 'cesium.yaml.example'),\n cfg)\n\n print('Installed {}'.format(cfg))\n print('Please customize this file with authentication tokens, etc.')\n","sub_path":"cesium/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"127060975","text":"import os\nos.chdir(\"C://Users/김용진/Documents/Git\")\n\nwith open(\"rosalind_lexf.txt\") as f:\n lines=f.readlines()\n\nsample=lines[0].strip().split(\" \")\n\nlength=lines[1].strip()\nlength=int(length)\n\nimport itertools\n\nwith open(\"outFile.txt\",\"w\") as f:\n for i in list(itertools.product(sample,repeat=length)):\n result=\"\".join(list(i))\n f.write(result)\n f.write(\"\\n\")","sub_path":"rosalind_lexf.py","file_name":"rosalind_lexf.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"182867625","text":"# inside twilio is a folder called rest and inside that folder there's a class called TwilioRestClient\nfrom twilio.rest import TwilioRestClient\n\n# Find these values at https://twilio.com/user/account\naccount_sid = \"AC4d3f95c750171540fd08d585636cc043\"\nauth_token = \"ecdc2590f798adf83aab9ef54fc339d9\"\nclient = TwilioRestClient(account_sid, auth_token)\n\nmessage = client.messages.create(\n to=\"+18329045678\",\n from_=\"+16606754209\",\n body=\"Here's limaBEAN\")\n","sub_path":"send_txt.py","file_name":"send_txt.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"187868725","text":"__author__ = 'Pawel'\n\n#To covert nearly any number into a palindromic number you operate by reversing the digits and adding and then\n# repeating the steps until you get a palindromic number. Some require many steps.\n\n#e.g. 24 gets palindromic after 1 steps: 66 -> 24 + 42 = 66\n#while 28 gets palindromic after 2 steps: 121 -> 28 + 82 = 110, so 110 + 11 (110 reversed) = 121.\n\n#Note that, as an example, 196 never gets palindromic (at least according to researchers,\n# at least never in reasonable time). Several numbers never appear to approach being palindromic.\n\ndef rev_number(n):\n return int(str(n)[::-1])\n\nnumber = []\nfor i in range(3):\n num = int(input(\"podaj liczbę: \"))\n number.append(num)\nfor j in range(3):\n n = number[j]\n steps = 0\n while True:\n r = rev_number(n)\n if n == r:\n print(\"%s gets palindromic after %s steps: %s\" % (number[j], steps, n))\n break\n n += r\n steps += 1","sub_path":"#218 [E] Palindromic numbers.py","file_name":"#218 [E] Palindromic numbers.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"248508270","text":"# Solution to Project Euler problem 2\n# Copyright (c) Project Keaton Rowley. All rights reserved.\n# https://github.com/KeatonRowley/ProjectEuler\n\n# Get the sum of all the Fibonacci sequence whose values don't exceed 4\n# million.\ndef get_first_sum_even_num(limit):\n a = 1\n b = 2\n sum = 2 # Include the first of the 2 terms.\n\n while b < limit:\n next = a + b # calculate and swap terms.\n a = b\n b = next\n \n if next % 2 == 0: # add all even integers.\n sum += next\n \n return sum\n \n \n \nprint(get_first_sum_even_num(4000000))\n\n\n\n","sub_path":"EvenFibonacci.py","file_name":"EvenFibonacci.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"317282679","text":"\nimport collections\n\nItem = collections.namedtuple('Item', ['weight', 'value'])\n\ndef max_value(knapsack_max_weight, items):\n lookup_table = [0] * (knapsack_max_weight + 1)\n\n for item in items:\n for capacity in reversed(range(knapsack_max_weight + 1)):\n if item.weight <= capacity:\n lookup_table[capacity] = max(lookup_table[capacity], lookup_table[capacity - item.weight] + item.value) # Note [YC] This is okay and you don't need to worry about repeated element because you are counting backwards, the value of lookup_table[capacity - item.weight] was still not updated, so it's from the last row, just like my solution. \n\n return lookup_table[-1]\n\n\n\ntests = [\n {\n 'correct_output': 14,\n 'input':\n {\n 'knapsack_max_weight': 15,\n 'items': [Item(10, 7), Item(9, 8), Item(5, 6)]}},\n {\n 'correct_output': 13,\n 'input':\n {\n 'knapsack_max_weight': 25,\n 'items': [Item(10, 2), Item(29, 10), Item(5, 7), Item(5, 3), Item(5, 1), Item(24, 12)]}}\n]\n\nfor test in tests:\n assert test['correct_output'] == max_value(**test['input'])","sub_path":"advanced_algorithms/knapsack_problem_solution.py","file_name":"knapsack_problem_solution.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"62424711","text":"from __future__ import print_function\nimport random\nimport time\n\nimport requests\n\n\nclass exceptions(object):\n\n def __init__(self, retries=10, delay=random.randint(0,10)):\n self.delay = delay\n self.retries = 0\n self.retry_limit = retries\n\n def __call__(self, method):\n def wrapper(*args, **kwargs):\n try:\n return method(*args, **kwargs)\n except Exception as e:\n return self.retry(method, args, kwargs)\n return wrapper\n\n def retry(self, method, args, kwargs):\n try:\n self.retries += 1\n if self.retries <= self.retry_limit:\n return method(*args, **kwargs)\n except Exception as e:\n if self.retries < self.retry_limit:\n return self.retry(method, args, kwargs)\n else:\n print('Exceeded retry limit')\n self.retries = 0\n\n\nclass Example(object):\n\n def __init__(self, name):\n self.name = name\n\n @exceptions(retries=5, delay=2)\n def make_request(self, client):\n http_statuses = [200, 303, 401, 403, 404, 429, 500, 503, 504]\n base = 'http://httpbin.org/status/{}'\n url = base.format(random.choice(http_statuses))\n print('Tried: ', url)\n response = client.get(url)\n response.raise_for_status()\n return response\n\n\nif __name__ == '__main__':\n example = Example('Handled HTTP Exceptions')\n client = requests\n response = example.make_request(client)\n print('Response: ', response)\n","sub_path":"patterns/decorator/classes/class_decorator_class_with_args.py","file_name":"class_decorator_class_with_args.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"422652893","text":"import spacy\nfrom spacy import displacy\n\ntext = \"\"\"But Google is starting from behind. The company made a late push\ninto hardware in Nigeria, and Apple's Siri, available on iPhones, and Amazon's Alexa\nsoftware, which runs on its Echo and Dot devices, have clear leads in\nconsumer adoption.\"\"\"\n\nnlp = spacy.load('en_core_web_sm')\ndoc = nlp(text)\n\nfor ent in doc.ents:\n print(ent.text, ent.start_char, ent.end_char, ent.label_)","sub_path":"samples/text-analysis.py","file_name":"text-analysis.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"320687836","text":"import telebot\r\nfrom telebot import types\r\n\r\nfrom time import sleep\r\n\r\n\r\nfrom config import token\r\nfrom keybord import base, courses, citys, start_key\r\nfrom pars_course import show_money\r\nfrom pars_weather import city_name, wheather_now, hourly_weather\r\nfrom pars_films import get_films\r\n\r\n\r\nbot = telebot.TeleBot(token)\r\n\r\n\r\n@bot.message_handler(commands=['start'])\r\ndef start_message(message):\r\n bot.send_message(message.chat.id, 'Привет)\\nЧем могу помочь?)', reply_markup=base())\r\n\r\n\r\n@bot.message_handler(content_types=['text'])\r\ndef sent_text(message):\r\n chat_id = message.chat.id\r\n if message.text == 'Привет':\r\n bot.send_message(chat_id, 'Привет)')\r\n elif message.text == '$Курсы валют':\r\n text = \"↓Выберите валюту\"\r\n bot.send_message(chat_id, text, reply_markup=courses())\r\n elif message.text == '☀Погода':\r\n bot.send_message(chat_id, f\"Погода в {city_name.capitalize()} сейчас:\\n{wheather_now('Минск')}\", reply_markup=citys())\r\n elif message.text == '✌Афиша tut.by':\r\n films = get_films()\r\n for i in films.keys():\r\n bot.send_message(chat_id, f\"{i}\\n{films[i]}\", reply_markup=base())\r\n else:\r\n bot.send_message(message.chat.id, 'Пока не понимаю.\\nМеня ещё не доделали :c')\r\n\r\n\r\n@bot.callback_query_handler(func=lambda message:True)\r\ndef ans(message):\r\n chat_id = message.message.chat.id\r\n money = show_money()\r\n if \"courses_currency\" in message.data:\r\n mes = message.data.split('_').pop()\r\n bot.send_message(chat_id, f\"{mes} сейчас равен {money[mes]} BYN\")\r\n if message.data == \"return\":\r\n bot.send_message(chat_id, '''\\n\\n☑Вы в главном меню\\n\\n''', reply_markup=base())\r\n if message.data == \"change_city_name\":\r\n mes = bot.send_message(chat_id, \"Какой город интересует?\")\r\n bot.register_next_step_handler(mes, weather)\r\n\r\n\r\n@bot.message_handler(content_types=['locals'])\r\ndef get_locals(message):\r\n mes = message.locals\r\n chat_id = message.chat.id\r\n return mes\r\n\r\n\r\ndef weather(message):\r\n try:\r\n city_name = message.text\r\n chat_id = message.chat.id\r\n bot.send_message(chat_id, f\"Погода в {city_name.capitalize()} сейчас:\\n{wheather_now(city_name)}\", reply_markup=citys())\r\n except:\r\n mes = bot.send_message(chat_id, \"ooops:c\\nЧто-то не так, попробуй ещё\")\r\n bot.register_next_step_handler(mes, weather)\r\n\r\n\r\n\r\n\r\nbot.polling(none_stop=True)\r\n\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"319565838","text":"# -*- coding: UTF-8 -*-\n# Copyright © 2015, Michał Przybyś \n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted\n# provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of\n# conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n# conditions and the following disclaimer in the documentation and/or other materials provided\n# with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# 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\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Setuptools-Autometa's setup script.\n\n**NOTE:** Do not use this setup script as an example, as it works around the fact that\nSetuptools-Autometa is not yet installed!\n\"\"\"\nimport os\nimport setuptools\nimport sys\n\n\nsys.path.insert(0, os.path.realpath(os.path.dirname(__file__)))\nimport setuptools_autometa\n\n\n# Please note, that this is not the way Setuptools-Autometa is intended to be used.\nmeta = setuptools_autometa._autometa('setuptools_autometa', os.path.dirname(__file__))\n\nsetuptools.setup(\n name='Setuptools-Autometa',\n version=meta['version'],\n license='BSD',\n description=meta['description'],\n long_description=meta['long_description'],\n author='Michał Przybyś',\n author_email='michal@przybys.eu',\n url='https://przybys.eu/software/setuptools-autometa',\n classifiers=(\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Plugins',\n 'Framework :: Setuptools Plugin',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Other Audience',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Topic :: Software Development'\n ),\n keywords=(\n 'automatic',\n 'description',\n 'setuptools',\n 'version'\n ),\n py_modules=(\n 'setuptools_autometa',\n ),\n entry_points={\n 'distutils.setup_keywords': (\n 'autometa = setuptools_autometa:autometa_keyword',\n 'autometa_fields = setuptools_autometa:autometa_fields_keyword'\n )\n },\n zip_safe=True,\n use_2to3=True\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"524032302","text":"# 322. Coin Change\n# Medium\n\n# You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.\n\n# Example 1:\n\n# Input: coins = [1, 2, 5], amount = 11\n# Output: 3 \n# Explanation: 11 = 5 + 5 + 1\n# Example 2:\n\n# Input: coins = [2], amount = 3\n# Output: -1\n# Note:\n# You may assume that you have an infinite number of each kind of coin.\n\nclass Solution(object):\n def coinChange(self, coins, amount):\n \"\"\"\n :type coins: List[int]\n :type amount: int\n :rtype: int\n \"\"\"\n # Initialize 1D array of size amount\n # Every value in the dp table represents:\n # table[i] = min number of coins to make amount i\n table = [float('+inf')]*(amount+1)\n \n # Base Cases\n table[0] = 0\n \n # Tabulation\n for i in range(1, amount+1):\n minval = float('+inf')\n for c in coins:\n if i - c >= 0:\n minval = min(table[i-c], minval)\n table[i] = minval + 1\n \n return table[-1] if table[-1] != float('+inf') else -1","sub_path":"DP/coin-change.py","file_name":"coin-change.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"582526502","text":"from bs4 import BeautifulSoup as bsoup\nimport os\nfrom os import path\nimport re\nfrom modules.tools import commons as cms\nfrom modules import definitions as dfs\n\nclass DateTime:\n def __init__(self, year, month, day, hour, minute):\n self.year = year\n self.month = month\n self.day = day\n self.hour = hour\n self.minute = minute\n\n def compare(self, odt):\n tA = [self.year, self.month, self.day, self.hour, self.minute]\n tB = [odt.year, odt.month, odt.day, odt.hour, odt.minute]\n for i in range(len(tA)):\n if tA[i] != tB[i]:\n return 1 if tA[i] > tB[i] else -1\n return 0\n\nclass Incident:\n def __init__(self, incident_id='', incident_type='', report_time=None, occur_time=None, location='', status=''):\n self.incident_id = incident_id\n self.incident_type = incident_type\n self.report_time = report_time\n self.occur_time = occur_time\n self.location = location\n self.status = status\n\nC_INCIDENT_PATTERN = '[0-9]{2}-[0-9]{6}'\n\ndef parse_incident_data(_id, dtdata, incident_descs):\n incident = Incident(incident_id=_id)\n dt_tuples = [(dtdata[i], dtdata[i+1]) for i in range(0, len(dtdata), 2)]\n dt1 = re.sub('[^0-9]', '', ''.join(dt_tuples[0]))\n dt2 = re.sub('[^0-9]', '', ''.join(dt_tuples[1])) if len(dt_tuples) > 1 else None\n dt_sorted = [DateTime(dt[:2], dt[2:4], dt[4:6], dt[6:8], dt[8:]) if dt else None for dt in [dt1, dt2]]\n dt_sorted = dt_sorted if (not dt_sorted[0]) or (not dt_sorted[1]) or dt_sorted[0].compare(dt_sorted[1]) == 1 else [dt_sorted[1], dt_sorted[0]]\n incident.report_time = dt_sorted[0]\n incident.occur_time = dt_sorted[1]\n for text in incident_descs:\n for status in dfs.STATUSES:\n if status in text:\n incident.status = status\n if not incident.status or incident.status.strip() == '':\n incident.incident_type = text\n return incident\n\ndef parse_incident_with_id(_id):\n def parse_incident_fn(dtdata, incident_descs):\n return parse_incident_data(_id, dtdata, incident_descs)\n return parse_incident_fn\n\ndef extrapolate_row_data(row_data):\n datePattern = re.compile('^[0-9]{2}/[0-9]{2}/[0-9]{2}.*')\n timePattern = re.compile('.*[0-9]{4}(hrs|Hrs).*')\n idPattern = re.compile(C_INCIDENT_PATTERN)\n id_ = []\n for d in row_data:\n if idPattern.search(d):\n id_ += d.split('\\n')\n del row_data[row_data.index('\\n'.join(id_))]\n incident_count = len(id_)\n incident = []\n incident_parser = parse_incident_with_id(id_[0])\n if incident_count > 1: # processes 1-to-many\n datagroups = [[] for i in range(len(id_))]\n for rd in row_data:\n print(\"ROWDATA\", row_data)\n rds = rd.split('\\n')\n rd_split = [(i, d) for i in range(len(rds)) for d in rds]\n for ind, data in rd_split:\n print(\"INDDATA\", ind, data)\n datagroups[ind].append(data)\n print()\n elif incident_count == 1: # processes 1-to-1\n data = cms.flatten([rd.split(' ') for rd in row_data])\n dtdata, texts = cms.categorize(data, lambda n: datePattern.search(n) or timePattern.search(n))\n dtdata = cms.flatten(dtdata)\n incident.append(incident_parser(dtdata, texts))\n '''\n for c in incident:\n print(c.__dict__)\n print()'''\n return None\n\ndef parse_html(html_dir, html_file):\n html_path = path.join(html_dir, html_file)\n print(\"Parsing %s\" % html_path)\n soup = bsoup(open(html_path), 'html.parser')\n incident_ids = map(lambda n: n.parent.parent, soup(text=re.compile(C_INCIDENT_PATTERN)))\n id_styles = dict()\n find_midpt = lambda t, h: t+int(h/2)\n is_inline = lambda target, t, h: target >= t and target <= (t+h)\n for id_ in incident_ids:\n elem_style = id_['style']\n style_list = filter(lambda n: len(n) > 0, map(lambda part: part.strip().split(':'), id_['style'].split(';')))\n id_styles[id_.text.strip().split('\\n')[0]] = [n for n in style_list if n[0] == 'top'][0]\n rows = dict((top[1], id_) for id_, top in id_styles.items())\n row_data = {}\n styled_divs = soup.findAll('div', {'style': re.compile(r'.*top.*')})\n for div in styled_divs:\n if 'top' in div['style']:\n style_parts = [n for n in div['style'].split(';') if ('top' in n or 'height' in n)] # extracting the top style value\n th_vals = dict([(x,int(re.sub('[^0-9]', '', y))) for x,y in [s.split(\":\") for s in style_parts]])\n print(th_vals)\n '''\n try:\n id_ = rows[top_attr] # get the incident id for that row\n if id_ not in row_data: # if incident id not in row_data, add it\n row_data[id_] = []\n row_data[id_].append(div.text.strip()) # add the div to map\n except KeyError:\n pass'''\n for rd in row_data:\n print(rd, row_data[rd])\n print()\n return None\n return dict(((id_, extrapolate_row_data(row)) for id_, row in row_data.items()))\n \ndef parse_dir(html_dir):\n for f in os.listdir(html_dir):\n print(\"FILE\", f)\n if '.html' in f:\n parse_html(html_dir, f)\n","sub_path":"modules/tools/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"185426305","text":"# https://www.acmicpc.net/problem/1697\n\nfrom collections import deque\nfrom sys import stdin\ninput = stdin.readline\n\ndef BFS(start, target):\n\tvisited = [False]*(100001)\n\tvisited[start] = True\n\tq = deque([(start,0)])\n\twhile q :\n\t\tcur, cnt = q.popleft()\n\t\tif cur == target :\n\t\t\treturn cnt\n\t\tnext_curs = [cur-1,cur+1,cur*2]\n\t\tfor next_cur in next_curs:\n\t\t\tif 0 <= next_cur <= 100000 and not visited[next_cur]:\n\t\t\t\tq.append([next_cur, cnt+1])\n\t\t\t\tvisited[next_cur] = True\nN, K = map(int, input().split())\nif N < K :\n\tprint(BFS(N,K))\nelif N > K :\n\tprint(N-K)\nelse :\n\tprint(0)","sub_path":"dojinyou/code_8week/13_1697.py","file_name":"13_1697.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"365781004","text":"class Solution(object):\n def firstMissingPositive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n for i, v in enumerate(nums):\n while v != i+1 and 0 < v <= len(nums): # v's range: 0 < v <= len(nums)\n if nums[i] == nums[v-1]: break # when there are duplicates, do not need to xchange\n nums[i], nums[v-1] = nums[v-1], nums[i]\n v = nums[i]\n for i, v in enumerate(nums):\n if v != i+1:\n return i+1\n return len(nums)+1","sub_path":"first_missing_positive/prac1.py","file_name":"prac1.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559382319","text":"#수능특강 독서 과학기술 11번 지문 (데이터 마이닝) 설명 프로그램\r\n#제작: 윤수민, 이정진, 2020년 7월 31일\r\n\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nimport statistics\r\n\r\nprint('수능특강 독서 과학기술 11번 지문 (데이터 마이닝) 설명 프로그램')\r\nprint('제작: 윤수민, 이정진, 2020년 7월 31일\\n')\r\n\r\nFirstX=[]\r\nFirstY=[]\r\nSecondX=[]\r\nSecondY=[]\r\nAllX=[]\r\nAllY=[]\r\n\r\nFirstCenter=float(input('1번째 집단의 중심 좌표 (기본값 (10, 10)): ') or 10)\r\nSecondCenter=float(input('2번째 집단의 중심 좌표 (기본값 (-10, -10)): ') or -10)\r\nFirstDotNum=int(input('1번째 집단 점 개수 (기본값 30개): ') or 30)\r\nSecondDotNum=int(input('2번째 집단 점 개수 (기본값 30개): ') or 30)\r\nFirstSigma=float(input('1번째 집단 표준편차 (기본값 5): ') or 5)\r\nSecondSigma=float(input('2번째 집단 표준편차 (기본값 5): ') or 5)\r\nImprovisationNum=int(input('보정 횟수 (기본값 1000번): ') or 1000)\r\nGroupingNum=int(input('1회 보정 시 선택되는 점 개수 (기본값 15): ') or 15)\r\n\r\nfor i in range(FirstDotNum):\r\n x=random.gauss(FirstCenter, FirstSigma)\r\n y=random.gauss(FirstCenter, FirstSigma)\r\n FirstX.append(x)\r\n FirstY.append(y)\r\n AllX.append(x)\r\n AllY.append(y)\r\n plt.plot(x, y, \"bo\")\r\n\r\nfor i in range(SecondDotNum):\r\n x=random.gauss(SecondCenter, SecondSigma)\r\n y=random.gauss(SecondCenter, SecondSigma)\r\n SecondX.append(x)\r\n SecondY.append(y)\r\n AllX.append(x)\r\n AllY.append(y)\r\n plt.plot(x, y, \"bo\")\r\n\r\nFirstXLocalAverage=statistics.mean(random.sample(population=FirstX, k=GroupingNum))\r\nFirstYLocalAverage=statistics.mean(random.sample(population=FirstY, k=GroupingNum))\r\nfor i in range(ImprovisationNum):\r\n FirstXTempAverage=statistics.mean(random.sample(population=FirstX, k=GroupingNum))\r\n if abs(FirstXLocalAverage-FirstCenter)>=abs(FirstXTempAverage-FirstCenter):\r\n FirstXTempAverage=FirstXLocalAverage\r\n elif abs(FirstXLocalAverage-FirstCenter)=abs(FirstYTempAverage-FirstCenter):\r\n FirstYTempAverage=FirstYLocalAverage\r\n elif abs(FirstYLocalAverage-FirstCenter)=abs(SecondXTempAverage-SecondCenter):\r\n SecondXTempAverage=SecondXLocalAverage\r\n elif abs(SecondXLocalAverage-SecondCenter)=abs(SecondYTempAverage-SecondCenter):\r\n SecondYTempAverage=SecondYLocalAverage\r\n elif abs(SecondYLocalAverage-SecondCenter)=abs(AllXTempAverage-(((FirstCenter)+(SecondCenter))/2)):\r\n AllXTempAverage=AllXLocalAverage\r\n elif abs(AllXLocalAverage-(((FirstCenter)+(SecondCenter))/2))=abs(AllYTempAverage-(((FirstCenter)+(SecondCenter))/2)):\r\n AllYTempAverage=AllYLocalAverage\r\n elif abs(AllYLocalAverage-(((FirstCenter)+(SecondCenter))/2)) 2 -> (3&4) -> 5\n#\n# Random numbers to determine when to start new steps, and whether a step\n# succeeded or failed, for the sake of demonstration.\n\n# The stages each step goes through are as follows:\n# depend -> require -> run -> n x Progress -> done\n#\n# There is also an extra stage called \"hint\" that allows you to send\n# back some text about what is going on. This is printed in the pipeline viewer.\n\n# To define the stages in a step:\n#\n# Only define the 'stages' you must - everything else will work automatically.\n#\n# STAGE INSTRUCTIONS\n#\n# hint return any string you want. This is called when the pipeline is first instantiated.\n#\n# depend return a list of [ { depend1: True|False, depend2: True|False } ]\n#\n# require return { ram: a, cpu: b } to indicate your expected resource consumption\n#\n# run return { programName: prog, arguments: { arg1: value1, arg2: value2 } }\n#\n# progress allows you to do something as your pipeline progresses. Typically left unhandled.\n#\n# done return { state: true|false, restart: true|false, message: anyMessageYouLike }\n# - state of 'True' means the step succeeded, and 'False' means it failed.\n# - restart of 'True' directs the pipline manager to re-try that step\n# - message can be any hint about why it succeeded or failed.\n#\n\ndef randOk():\n\treturn random.randrange(0,100) < 20\n\n\ndef demo_initiator(pipeline):\n\t# print 'Test:'+str(pipeline.numActive())\n\tgotRand = random.randrange(0,100) < 5\n\ttooFew = pipeline.numActive() < 5\n\tif gotRand or tooFew:\n\t\t# print \"Initiate: \"+str(gotRand)+' '+str(tooFew)\n\t\treturn { 'id': 'sample'+str(random.randrange(1000, 9999)) }\n\treturn False\n\n\ndef demo_advisor_step1( query ):\n\tif query=='require':\n\t\treturn { 'ram': 100*1024, 'cpu': 1 }\n\tif query=='hint':\n\t\treturn 'mouth'\n\tif query=='run':\n\t\treturn { \n\t\t\t'programName': 'demo_pipedemo_step1.py',\n\t\t\t'ram': 100*1024, \n\t\t\t'cpu': 1\n\t\t}\n\tif query=='done':\n\t\treturn True\n\ndef demo_advisor_step2( query ):\n\tif query=='require':\n\t\treturn { 'ram': 100*1024, 'cpu': 1 }\n\tif query=='depend':\n\t\treturn ['step1']\n\tif query=='hint':\n\t\treturn 'nose'\n\tif query=='run':\n\t\treturn { \n\t\t\t'programName': 'demo_pipedemo_step2.py',\n\t\t\t'ram': 100*1024, \n\t\t\t'cpu': 1\n\t\t}\n\tif query=='done':\n\t\tok = random.randrange(0,100) < 50\n\t\tif random.randrange(0,100) < 50:\n\t\t\t# Test what happens when a simple result is returned\n\t\t\treturn ok\n\t\trestart = not ok and random.randrange(0,100) < 50\n\t\treturn { 'state': ok, 'restart': restart, 'message': 'my result was '+str(ok)+' and restart was '+str(restart) }\n\ndef demo_advisor_step3( query ):\n\tif query=='require':\n\t\treturn { 'ram': 100*1024, 'cpu': 1 }\n\tif query=='depend':\n\t\treturn ['step2']\n\tif query=='hint':\n\t\treturn 'left eye'\n\tif query=='run':\n\t\treturn {\n\t\t\t'arguments': {\n\t\t\t\t'part': 'left eye'\n\t\t\t},\n\t\t\t'programName': 'demo_pipedemo_step3n5.py',\n\t\t\t'ram': 100*1024, \n\t\t\t'cpu': 1\n\t\t}\n\tif query=='done':\n\t\treturn True\n\ndef demo_advisor_step4( query ):\n\tif query=='require':\n\t\treturn { 'ram': 100*1024, 'cpu': 1 }\n\tif query=='depend':\n\t\treturn ['step2']\n\tif query=='hint':\n\t\treturn 'right eye'\n\tif query=='run':\n\t\treturn {\n\t\t\t'arguments': {\n\t\t\t\t'part': 'right eye'\n\t\t\t},\n\t\t\t'programName': 'demo_pipedemo_step4.py',\n\t\t\t'ram': 100*1024, \n\t\t\t'cpu': 1\n\t\t}\n\n\tif query=='done':\n\t\treturn True\n\n\ndef demo_advisor_step5( query ):\n\tif query=='require':\n\t\treturn \n\tif query=='depend':\n\t\treturn ['step3','step4']\n\tif query=='hint':\n\t\treturn 'whole face'\n\tif query=='run':\n\t\treturn {\n\t\t\t'arguments': {\n\t\t\t\t'part': 'whole face'\n\t\t\t},\n\t\t\t'programName': 'demo_pipedemo_step3n5.py',\n\t\t\t'ram': 100*1024, \n\t\t\t'cpu': 1\n\t\t}\n\tif query=='done':\n\t\treturn { 'link': 'whole face' }\n\npipeline = Pipeline( 'kentest3' )\n\npipeline.cluster_set( { 'group': 'common', 'nodes': 1 } )\n#pipeline.initiatorAdd( demo_initiator )\npipeline.add_step( 'step1', demo_advisor_step1 )\npipeline.add_step( 'step2', demo_advisor_step2 )\npipeline.add_step( 'step3', demo_advisor_step3 )\npipeline.add_step( 'step4', demo_advisor_step4 )\npipeline.add_step( 'step5', demo_advisor_step5 )\npipeline.run()\n","sub_path":"programs/demo_pipedemo.py","file_name":"demo_pipedemo.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"308395434","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nimport os\nfrom test_sina.items import TestSinaItem\n\n\nclass Sina2Spider(CrawlSpider):\n name = 'sina2'\n allowed_domains = ['sina.com.cn']\n start_urls = ['http://news.sina.com.cn/guide/']\n # v国内\n # < a\n # href = \"http://news.sina.com.cn/c/gat/2018-05-18/doc-ihaturfs2883813.shtml\"\n\n\n rules = (\n # Rule(LinkExtractor(allow=r'.*.sina.com.cn/.*'), callback='parse_item', follow=True),\n Rule(LinkExtractor(allow=r'.*.sina.com.cn/.*shtml'), callback='detail_parse', follow=True),\n\n )\n\n\n # def parse(self, response):\n #\n # parent_titles = response.xpath('//div[@id=\"tab01\"]/div/h3/a/text()').extract()\n # parent_urls = response.xpath('//div[@id=\"tab01\"]/div/h3/a/@href').extract()\n # son_titles = response.xpath('//div[@id=\"tab01\"]/div/ul/li/a/text()').extract()\n # son_urls = response.xpath('//div[@id=\"tab01\"]/div/ul/li/a/@href').extract()\n #\n # self.items = []\n # for i in range(len(parent_titles)):\n # parent_title = \"./Data/\" + parent_titles[i]\n # parent_url = parent_urls[i]\n # for j in range(len(son_titles)):\n # son_title = son_titles[j]\n # son_url = son_urls[j]\n #\n # if son_url.startswith(parent_url):\n # parent_son_path = parent_title + \"/\" + son_title\n # if not os.path.exists(parent_son_path):\n # os.makedirs(parent_son_path)\n #\n # item = TestSinaItem()\n # item[\"parent_title\"] = parent_title\n # item[\"parent_url\"] = parent_url\n # item[\"son_title\"] = son_title\n # item[\"son_url\"] = son_url\n # item[\"parent_son_path\"] = parent_son_path\n # self.items.append(item)\n\n def parse_item(self, response):\n print('2'*200)\n meta_item = self.meta[\"meta_item\"]\n url_list = response.xpath('//a/@href').extract()\n items = []\n for url in url_list:\n parent_url = meta_item[\"parent_url\"]\n if url.startswith(parent_url) and url.endswith(\".shtml\"):\n grandson_url = url\n item = TestSinaItem()\n item[\"parent_title\"] = meta_item[\"parent_title\"]\n item[\"parent_url\"] = meta_item[\"parent_url\"]\n item[\"son_title\"] = meta_item[\"son_title\"]\n item[\"son_url\"] = meta_item[\"son_url\"]\n item[\"parent_son_path\"] = meta_item[\"parent_son_path\"]\n item[\"grandson_url\"] = grandson_url\n items.append(item)\n\n\n\n def detail_parse(self, response):\n print('3'*200)\n item = response.meta[\"meta_item2\"]\n grandson_title = response.xpath('//h1[@id=\"artibodyTitle\"]/text()|//h1[@class=\"main-title\"]/text()').extract()\n grandson_title = ''.join(grandson_title)\n grandson_content = response.xpath('//div[@id=\"article\"]/p[position()>1]/text()|//div[@id=\"artibody\"]/p/text()').extract()\n grandson_content = \"\".join(grandson_content)\n item[\"grandson_title\"] = grandson_title\n item[\"grandson_content\"] = grandson_content\n print(item)\n","sub_path":"爬虫/day10_0519/works/test_sina/test_sina/spiders/sina2.py","file_name":"sina2.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"306006771","text":"#!/usr/bin/env python3\n# Makes the robot balance\n# Based on: https://github.com/mcdeoliveira/pyctrl/raw/master/examples/rc_mip_balance.py\nimport math\nimport time\nimport warnings\nimport numpy as np\nimport sys, tty, termios\nimport threading\n\nimport pyctrl\n\ndef brief_warning(message, category, filename, lineno, line=None):\n return \"*{}\\n\".format(message)\n\nwarnings.formatwarning = brief_warning\n\n# read key stuff\n\nARROW_UP = \"\\033[A\"\nARROW_DOWN = \"\\033[B\"\nARROW_RIGHT = \"\\033[C\"\nARROW_LEFT = \"\\033[D\"\nDEL = \".\"\nEND = \"/\"\nSPACE = \" \"\n\ndef read_key():\n\n key = sys.stdin.read(1)\n if ord(key) == 27:\n key = key + sys.stdin.read(2)\n elif ord(key) == 3:\n raise KeyboardInterrupt \n\n return key\n\ndef get_arrows(mip, fd):\n\n phi_dot_reference = 0\n steer_reference = 180/360\n \n tty.setcbreak(fd)\n while mip.get_state() != pyctrl.EXITING:\n \n print('\\rvelocity = {:+4.0f} '\n ' steering = {:+4.2f} deg'\n .format(100*phi_dot_reference,\n 360*(steer_reference-180/360)),\n end='')\n \n key = read_key()\n if key == ARROW_LEFT:\n steer_reference = max(steer_reference - 20/360, 0)\n mip.set_signal('steer_reference', steer_reference)\n elif key == ARROW_RIGHT:\n steer_reference = min(steer_reference + 20/360, 1)\n mip.set_signal('steer_reference', steer_reference)\n elif key == ARROW_UP:\n phi_dot_reference = phi_dot_reference + 0.1\n mip.set_signal('phi_dot_reference', - phi_dot_reference)\n elif key == ARROW_DOWN:\n phi_dot_reference = phi_dot_reference - 0.1\n mip.set_signal('phi_dot_reference', - phi_dot_reference)\n elif key == SPACE:\n phi_dot_reference = 0\n mip.set_signal('phi_dot_reference', - phi_dot_reference)\n steer_reference = 180/360\n mip.set_signal('steer_reference', steer_reference)\n elif key == DEL:\n steer_reference = 180/360\n mip.set_signal('steer_reference', steer_reference)\n elif key == END: \n phi_dot_reference = 0\n mip.set_signal('phi_dot_reference', - phi_dot_reference)\n\ndef main():\n\n # import blocks and controller\n from pyctrl.rc.mip import Controller\n from pyctrl.block.system import System, Subtract, Differentiator, Sum, Gain\n from pyctrl.block.nl import ControlledCombination\n from pyctrl.block import Logger, ShortCircuit\n from pyctrl.block.logic import CompareAbs\n from pyctrl.system.ss import DTSS\n\n # create mip\n mip = Controller()\n\n # phi is the average of the encoders\n mip.add_signal('phi')\n mip.add_filter('phi',\n Sum(gain=0.5),\n ['encoder1','encoder2'],\n ['phi'])\n\n # phi dot\n mip.add_signal('phi_dot')\n mip.add_filter('phi_dot',\n Differentiator(),\n ['clock','phi'],\n ['phi_dot'])\n\n # phi dot reference\n mip.add_signal('phi_dot_reference')\n\n # state-space matrices\n A = np.array([[0.913134, 0.0363383],[-0.0692862, 0.994003]])\n B = np.array([[0.00284353, -0.000539063], [0.00162443, -0.00128745]])\n C = np.array([[-383.009, 303.07]])\n D = np.array([[-1.22015, 0]])\n\n B = 2*np.pi*(100/7.4)*np.hstack((-B, B[:,1:]))\n D = 2*np.pi*(100/7.4)*np.hstack((-D, D[:,1:]))\n\n ssctrl = DTSS(A,B,C,D)\n\n # state-space controller\n mip.add_signals('pwm')\n mip.add_filter('controller',\n System(model = ssctrl),\n ['theta_dot','phi_dot','phi_dot_reference'],\n ['pwm'])\n \n # steering biasing\n mip.add_signal('steer_reference')\n mip.add_filter('steer',\n ControlledCombination(),\n ['steer_reference', 'pwm','pwm'],\n ['pwm1','pwm2'])\n\n # set references\n mip.set_signal('phi_dot_reference',0)\n mip.set_signal('steer_reference',0.5)\n\n # add kill switch\n mip.add_filter('kill',\n CompareAbs(threshold = 0.2),\n ['theta'],\n ['is_running'])\n \n # print controller\n print(mip.info('all'))\n\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n\n print(\"\"\"\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n* M I P B A L A N C E *\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n\"\"\")\n\n input('Hold your MIP upright and hit to start balancing')\n\n print(\"\"\"\nUse your keyboard to control the mip:\n\n* UP and DOWN arrows move forward and back\n* LEFT and RIGHT arrows steer\n* / stops forward motion\n* . stops steering\n* SPACE resets forward motion and steering\n\n\"\"\")\n \n # reset everything\n mip.set_source('clock',reset=True)\n mip.set_source('encoder1',reset=True)\n mip.set_source('encoder2',reset=True)\n mip.set_filter('controller',reset=True)\n mip.set_source('inclinometer',reset=True)\n\n # start the controller\n mip.start()\n\n print(\"Press Ctrl-C to exit\")\n\n # fire thread to update velocities\n thread = threading.Thread(target = get_arrows,\n args = (mip, fd))\n thread.daemon = True\n thread.start()\n \n # and wait until controller dies\n mip.join()\n \n except KeyboardInterrupt:\n\n print(\"> Balancing aborted\")\n mip.set_state(pyctrl.EXITING)\n\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n \nif __name__ == \"__main__\":\n main()\n\n","sub_path":"BeagleBone/Blue/EduMIP/python/balance.py","file_name":"balance.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"377590896","text":"import math\r\ndef isPrime(n):\r\n if n > 2 and n % 2 == 0:\r\n return False\r\n else:\r\n for i in range(3, int(math.sqrt(n)) + 1, 2):\r\n if n % i == 0:\r\n return False\r\n return True\r\n\r\ndef getSum(limit):\r\n sum = 0\r\n for i in range(2, limit):\r\n if isPrime(i):\r\n sum += i\r\n \r\n return sum\r\n\r\nprint(getSum(2000000))\r\n","sub_path":"old_repo/Project Euler/Euler10.py","file_name":"Euler10.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"321731378","text":"import tensorflow as tf\nimport numpy as np\nfrom tensorlayer.layers import *\n\n# --------------------\n#ARCHITECTURE INFO\nIMAGE_SIZE = 448,256,3\nCONVOLUTIONS = [-32, -64] #Convolutional Layers, negative means downsampling\nHIDDEN_SIZE = 100\nNUM_CLASSES = 1\n# ---------------------\n#TRAINING INFO\nLEARNING_RATE = 1e-3\nMOMENTUM = .5 #For Adam Optimizer\nKEEP_PROB = .5 #For dropout\nBATCH_SIZE = 12\nTEST_BATCH_SIZE = 250\n# ----------------------\n#FILEPATH INFO\nFILEPATH = '/Data/PersonTracking/'\nTRAIN_INPUT = FILEPATH + 'train/'+ 'train_images'\nTEST_INPUT = FILEPATH + 'test/' + 'test_images'\nTRAIN_LABEL = FILEPATH + 'train/'+ 'train_labels'\nTEST_LABEL = FILEPATH + 'test/' + 'test_labels'\nPERM_MODEL_FILEPATH = '/Models/PersonTracking/model.ckpt' #filepaths to model and summaries\nSUMMARY_FILEPATH ='/Models/PersonTracking/Summaries/'\n# ----------------------\n#MISC INFO\nRESTORE = False\nWHEN_DISP = 50 #How often to visualize images\nWHEN_TEST = 50 # How often to run on test set\nNUM_OUTPUTS = 10 #Image viewing\nWHEN_SAVE = 500 #How often to save the model\nITERATIONS = 25000 #How long to trian max\nNUM_EXAMPLES = 3500 #~total amount of data\n\ndef decode_image(image):\n '''Convert from Binary and Normalize from [0, 255] to [0.0, 1.0]'''\n image = tf.decode_raw(image, tf.uint8)\n image = tf.cast(image, tf.float32)\n image = tf.reshape(image, [IMAGE_SIZE[0], IMAGE_SIZE[1], IMAGE_SIZE[2]])\n return image / 255.0\n\ndef decode_label(label):\n '''Decode labels from binary file'''\n label = tf.decode_raw(label, tf.int32)\n label = tf.reshape(label, [1])\n return label\n\ndef return_datatset_train():\n '''Load the training dataset from a Binary File'''\n images = tf.data.FixedLengthRecordDataset(\n TRAIN_INPUT, IMAGE_SIZE[0] * IMAGE_SIZE[1] * IMAGE_SIZE[2]).map(decode_image)\n labels = tf.data.FixedLengthRecordDataset(\n TRAIN_LABEL, 1* 4).map(decode_label)\n return tf.data.Dataset.zip((images, labels))\n\ndef return_datatset_test():\n '''Load the testing dataset from a binary file'''\n images = tf.data.FixedLengthRecordDataset(\n TEST_INPUT, IMAGE_SIZE[0] * IMAGE_SIZE[1] * IMAGE_SIZE[2]).map(decode_image)\n labels = tf.data.FixedLengthRecordDataset(\n TEST_LABEL, 1* 4).map(decode_label)\n return tf.data.Dataset.zip((images, labels))\n\ndef create_main_model(x_image, reuse = False, is_train = None):\n '''Create a discrimator, note the convolutions may be negative to represent\n downsampling\n reuse --> Whether or not to reuse variables\n is_train --> Whether to use dropout'''\n if is_train is None:\n is_train = not reuse\n with tf.variable_scope(\"main_model\") as scope:\n if reuse: #get previous variable if we are reusing the discriminator but with fake images\n scope.reuse_variables()\n xs, ys = IMAGE_SIZE[0],IMAGE_SIZE[1]\n inputs = InputLayer(x_image, name= 'inputs')\n convVals = inputs # Convals represents the input to a layer\n for i,v in enumerate(CONVOLUTIONS):\n '''Similarly tile for constant reference to class'''\n if v < 0:\n v *= -1\n convVals = Conv2d(convVals,v, (3, 3), act=tf.nn.relu,strides =(2,2),name='conv_%i'%(i))\n else:\n convVals = Conv2d(convVals,v, (3, 3), act=tf.nn.relu,strides =(1,1),name='conv_%i'%(i))\n flat3 = FlattenLayer(convVals, name ='flatten')\n hid3 = DenseLayer(flat3, HIDDEN_SIZE,act = tf.nn.relu, name ='fcl')\n hid3 = DropoutLayer(hid3, keep=KEEP_PROB,is_train=is_train, is_fix=True, name='drop1')\n y_conv = DenseLayer(hid3, 2, name = 'output').outputs\n importance_map = tf.nn.tanh(convVals.outputs)\n return y_conv,importance_map\n\ndef build_model(x, og_classes, reuse = False):\n '''Build a model for training and testing'''\n classes = tf.squeeze(og_classes, 1)\n classes_one =tf.one_hot(classes, 2)\n if not reuse:\n prefix = 'train_'\n else:\n prefix = 'test_'\n main_outputs,_ = create_main_model(x,reuse=reuse)#create model\n with tf.variable_scope('logistics') as scope:\n image_summary = tf.summary.image(prefix + \"inputs\", x,max_outputs = NUM_OUTPUTS)#get some example images\n cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=classes_one, logits=main_outputs))#get cost\n cross_entropy_summary = tf.summary.scalar(prefix + 'loss',cross_entropy)#get summary of cost for tensorboard\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(main_outputs,-1,output_type=tf.int32),classes), tf.float32))#determine accuracy\n accuracy_summary = tf.summary.scalar(prefix + 'accuracy',accuracy) #get summary of accuracy for tensorboard\n if not reuse: #if we're training use an atom optimizer\n train_step = tf.train.AdamOptimizer(LEARNING_RATE,beta1=MOMENTUM).minimize(cross_entropy)\n else:\n train_step = None\n scalar_summary = tf.summary.merge([cross_entropy_summary,accuracy_summary]) #compile summaries\n return scalar_summary, image_summary, train_step\n\ndef train_model():\n '''Start training a model'''\n sess = tf.Session()#start the session\n ##############GET DATA###############\n train_ship = return_datatset_train().repeat().batch(BATCH_SIZE)\n train_iterator = train_ship.make_initializable_iterator()\n train_input, train_label = train_iterator.get_next()\n\n test_ship = return_datatset_test().repeat().batch(TEST_BATCH_SIZE)\n test_iterator = test_ship.make_initializable_iterator()\n test_input, test_label = test_iterator.get_next()\n\n sess.run([train_iterator.initializer,test_iterator.initializer])\n ####################DEFINE MODEL############################################\n scalar_summary, image_summary, train_step = build_model(train_input, train_label)\n test_scalar_summary, test_image_summary, _ = build_model(test_input, test_label, reuse = True)\n ####################LOAD MODEL AND SUMMARY#########################################\n sess.run(tf.global_variables_initializer())\n saver_perm = tf.train.Saver()\n if PERM_MODEL_FILEPATH is not None and RESTORE: #if we load a model\n saver_perm.restore(sess, PERM_MODEL_FILEPATH)\n else:\n print('SAVE')\n saver_perm.save(sess, PERM_MODEL_FILEPATH)\n train_writer = tf.summary.FileWriter(SUMMARY_FILEPATH,\n sess.graph)\n #####################TRAIN##############################################\n for i in range(ITERATIONS):\n if not i % WHEN_DISP: #Whether to save some example images\n input_summary_ex, image_summary_ex,_= sess.run([scalar_summary, image_summary, train_step])\n train_writer.add_summary(image_summary_ex, i)\n else:\n input_summary_ex, _= sess.run([scalar_summary, train_step])\n train_writer.add_summary(input_summary_ex, i)\n\n if not i % WHEN_TEST: #whether to test on the test set\n input_summary_ex, image_summary_ex= sess.run([test_scalar_summary, test_image_summary])\n train_writer.add_summary(image_summary_ex, i)\n train_writer.add_summary(input_summary_ex, i)\n\n if not i % WHEN_SAVE: #whether to save the model\n print('SAVE')\n saver_perm.save(sess, PERM_MODEL_FILEPATH)\n\n if not i % (NUM_EXAMPLES // BATCH_SIZE): #rough estimate of number of epochs\n #Get a vague idea of probability of overfitting\n print('EPOCH:' , i / (NUM_EXAMPLES // BATCH_SIZE))\n\ndef build_model_inference():\n '''Build a model for live use'''\n sess = tf.Session()#start the session\n #define a placeholder (empty box) where we're going to put our data\n x = tf.placeholder(dtype=tf.float32, shape=(1,IMAGE_SIZE[0],IMAGE_SIZE[1],IMAGE_SIZE[2]))\n x_rev = tf.reverse(x,axis=[3])/255.0 #If we're using the neato, convert from BGR to RGB and to [0,1] range\n main_outputs, importance_map = create_main_model(x_rev,is_train=False) #Build model\n sess.run(tf.global_variables_initializer())\n saver_perm = tf.train.Saver()\n saver_perm.restore(sess, PERM_MODEL_FILEPATH)#Restore model\n return sess, x, main_outputs,importance_map\n\nif __name__ == '__main__':\n sess, x,binary_output = build_model_inference()\n","sub_path":"face_prediction/trainFaces.py","file_name":"trainFaces.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"550356576","text":"# TO-DO: Complete the selection_sort() function below \ndef selection_sort( arr ):\n # loop through n-1 elements\n for i in range(0, len(arr) - 1):\n sorted_index = i\n smallest_index = i\n for j in range(sorted_index+1, len(arr)):\n current_index = j\n if arr[smallest_index] > arr[current_index]: \n arr[smallest_index], arr[current_index] = arr[current_index], arr[smallest_index]\n\n return arr\n\n\n# TO-DO: implement the Bubble Sort function below\ndef bubble_sort( arr ):\n while True:\n sorted_round=False\n for i in range(0, len(arr)-1):\n if arr[i] > arr[i+1]:\n arr[i], arr[i+1] = arr[i+1], arr[i]\n sorted_round = True\n if not sorted_round:\n break\n\n return arr\n\n\n# STRETCH: implement the Count Sort function below\ndef count_sort( arr, maximum=-1 ):\n\n return arr","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"5026191","text":"# clc() ##command창에 표시된 코드들 사라지게해\n#-*- encoding: utf8 -*-\nimport os\nimport numpy as np\nimport struct\n# clear(mstring('all'))\n# close(mstring('all'))\n\n# This code save already computed C3D features into 32 (video features) segments.\n# We assume that C3D features for a video are already computed. We use\n# default settings for computing C3D features, i.e., we compute C3D features for\n# every 16 frames and obtain the features from fc6.\n\nimport struct\n\ndef read_bin(input_file):\n# input_file = open(r'.\\normal_video_001\\000032.fc6-1','rb')\n input_file = open(input_file,'rb')\n try:\n sizes = [struct.unpack('i',input_file.read(4))[0] for i in range(5)]\n m = np.prod(sizes)\n data = [struct.unpack('f',input_file.read(4))[0] for i in range(m)]\n finally:\n input_file\n feature_vector = np.array(data)\n\n return feature_vector, feature_vector.shape\n\nC3D_Path = r'C:\\Users\\seong\\Desktop\\32segment\\normal_output'\nC3D_Path_Seg = r'C:\\Users\\seong\\Desktop\\32segment\\output'\n\nif not os.path.isdir(C3D_Path_Seg):\n os.mkdir(C3D_Path_Seg)\n\nprint('DONE')\n\nAll_Folder = os.listdir(C3D_Path)\n# All_Folder = All_Folder[3:end]\nsubcript = '_C.txt'\n\nfor ifolder in All_Folder:\n #% START 1 LOOP WITH 1 FC FOLDER, ex: Abuse028 has N=1392 frames\n\n Folder_Path = str(C3D_Path) + \"\\\\\" + str(ifolder)\n #Folder_Path is path of a folder which contains C3D features (for every 16 frames) for a paricular video.\n # N=1392 frames --> it has [1392/16] = 88 fc6-1 files\n\n AllFiles = os.listdir(Folder_Path) ##\"/.fc6-1 확장자 파일 싹다 리스트로 반환\"\n # fc6-1 files in feature directory, each file = a clip in video\n # one clip = 16 frames\n\n if len(AllFiles) == 0:\n print(\"no fc6-1 file in path\")\n continue\n \n feature_vector = np.zeros((len(AllFiles), 4096))\n # each fc6-1 = 1 clips 16 frames = 4096-d ==> Total is [N/16]=88 clips like that\n #% Iterate each fc6-1 file (16 frames each)\n for ifile in range(0,len(AllFiles)):\n FilePath =Folder_Path + '\\\\' + AllFiles[ifile]\n\n data,_ = read_bin(FilePath)\n _,s = read_bin(FilePath)\n feature_vector[ifile]=data #% 1 column 4096-d in 88x4096 is assign by 1 clip feature (4096)\n\n # clear(mstring('data')) # clear라는 변수를 매트랩 내에서 삭제\n\n #% At this point, Feature vector is filled with all actual data from\n # all 16-frame clips in video, each clip is 4096-d, therefore 88x4096\n # is now filled with actual data\n # if sum(sum(feature_vector, [])) == 0: ## 고쳐야됨 : 각 열의 합인 한 행짜리 행렬로\n # print('error1')\n\n # Write C3D features in text file to load in\n # Training_AnomalyDetector_public ( You can directly use .mat format if you want).\n txt_file_name = C3D_Path_Seg + '/' + ifolder +subcript\n # feature txt name i.e Abuse028_x264_C.txt\n\n # if exist(txt_file_name, 'file'):\n # continue\n\n fid1 = open(txt_file_name, 'w')\n ## sum(x,1) = sum vertically (column)\n ## sum(x,2) = sum horizontally (row)\n # if not isempty(find(sum(Feature_vect, 2) == 0)): # sum row --> 88x4096 results in 88 rows\n # # k = find(X,n)은 X의 0이 아닌 요소에 대응하는 처음 n개의 인덱스를 반환합니다\n # print('error2')\n\n\n # if not isempty(find(isnan(Feature_vect(mslice[:])))):\n # print('error3')\n\n # if not isempty(find(Feature_vect(mslice[:]) == Inf)):\n # print('error4')\n\n #% 32 Segments\n\n Segments_Features = np.zeros((32, 4096)) #32 row, 4096 column\n thirty2_shots = np.linspace(1, len(AllFiles), 33).round(0)\n # thirty2shots = divide 88 frames to 33 segment, start from 1 to 88\n # SO: thirty2shots = [1 , 4, 6, 10, ..... 83, 85, 88], total elements\n # is 33, vector 1x33\n count = -1\n #% WRITE 88x4096 TO 32x4096\n for ishots in range(0,len(thirty2_shots) - 1): # ishorts starts from 1 to 32\n ss = int(thirty2_shots[ishots] ) # start clip index in 88x4096\n ee = int(thirty2_shots[ishots + 1] - 1) # end clip index in 88x4096\n \n # print(ss,ee,'llllll')\n if ishots == len(thirty2_shots):\n ee = int(thirty2_shots[ishots + 1])\n #% THIS IS A FEATURE FOR 1 SEGMENT\n #ALL BELOW CASE, temp_vect is always 4096-d based on value of start ss and end ee index\n if ss == ee:\n temp_vect = feature_vector[ss] ##ss번째 행 벡터 추출 # ss==ee --> get 1 vector 4096-d from 88x4096\n\n elif ee < ss:\n temp_vect = feature_vector[ss] # ee < ss --> get 1 vector 4096-d from 88x4096\n\n else:\n temp_vect = feature_vector[ss:ee].mean(axis=0) ##각 열의 평균값을 가진 1*4096행 추출\n # for i in range(ss,ee):\n # feature_vector\n # ss < ee --> get all clip vectors from ss to ee (ex: 3 vectors) from 88x4096\n # origin feature, than take mean value of all (i.e 3 vectors) that vectors to\n # get a new one has 4096-d (shape of result is shape of row when get mean a\n # matrix)\n #mean a vector = mean of each column = sum column/total row -->\n #shape = number of row (=4096) after this mean operation\n # print(temp_vect.shape)\n #% AFTER HAS 1 SEGMENT FEATURE, CALCULATE NORM-2 (L2)\n temp_vect = temp_vect / np.linalg.norm(temp_vect)\n # temp_vect = temp_vect / np.norm(temp_vect) #% divide by norm-2 (L2) of vector (Euclidean norm)=cumsum(sqrt(x[i]^2)) # divide by norm-2 (L2) of vector (Euclidean norm)=cumsum(sqrt(x[i]^2))\n\n # if np.linalg.norm(temp_vect) == 0:\n # print('error5')\n\n count = count + 1 # next segment (max=32)\n Segments_Features[count]= temp_vect # push each segment feature to final 32 video segments feature\n\n#verify\n\n # if not isempty(find(sum(Segments_Features, 2) == 0)):\n # print('error6')\n\n # if not isempty(find(isnan(Segments_Features(mslice[:])))):\n # print('error7')\n\n\n # if not isempty(find(Segments_Features(mslice[:]) == Inf)):\n # print('error8')\n\n\n # save 32 segment features in text file ( You can directly save and load .mat file in python as well).\n print(Segments_Features)\n print(Segments_Features.shape)\n\n for i in range(0,Segments_Features.shape[0]):\n feat_text = str(Segments_Features[i].tolist())\n fid1.write(feat_text)\n fid1.write('\\n')\n\n fid1.close()\n\n","sub_path":"Codes/etc/[Prep]_ch_05_Save_C3DFeatures_32Segments.py","file_name":"[Prep]_ch_05_Save_C3DFeatures_32Segments.py","file_ext":"py","file_size_in_byte":6625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"543607074","text":"#! python3\n# renameDates.py - renames filenames with American MM-DD-YYYY date format to Eruopean DD-MM-YYYY\n\nimport re\nimport os\nimport shutil\n\ndateRegex = re.compile(r'''\n^(.*?) #?作用为非贪婪匹配\n([01]?\\d)-\n([0-3]?\\d)-\n(\\d{4})\n(.*?)$\n''', re.VERBOSE)\n\nos.chdir('C:\\\\Users\\\\daize\\\\Desktop\\\\pythontest\\\\autopython\\\\act9\\\\date')\n# for filename in os.listdir():\n# findDate = dateRegex.findall(filename)\n# print(findDate)\n# day = findDate[0][2]\n# mouth = findDate[0][1]\n# newFile = findDate[0][0] + day + '-' + mouth + '-' + findDate[0][3] + findDate[0][4]\n# shutil.move(filename, newFile)\n\nfor filename in os.listdir():\n findDate = dateRegex.search(filename)\n if findDate == None:\n continue\n beforePart = findDate.group(1)\n monthPart = findDate.group(2)\n dayPart = findDate.group(3)\n yearPart = findDate.group(4)\n afterPart = findDate.group(5)\n euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart\n\n #get the full ,absolute file paths\n absWorkingDir = os.path.abspath('.')\n filename = os.path.join(absWorkingDir, filename)\n euroFilename = os.path.join(absWorkingDir, euroFilename)\n\n #rename the files\n print('renameing \"%s\" to \"%s\"' % (filename, euroFilename))\n # shutil.move(filename, euroFilename)","sub_path":"act9/renameDates.py","file_name":"renameDates.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"179331005","text":"# -- coding: utf-8 -- \n#=====================================================================\nfrom PIL import Image\nimport os\nroot = './'\nfor i in os.listdir(root):\n\tif os.path.isfile(os.path.join(root,i)):\n\t\tim = Image.open(i)\n\t\tout = im.resize((160,60),Image.ANTIALIAS) #改变图片大小为160*60\n\t\tout.save(i)\n\t\t#print \"Resize \" + str(i)\n","sub_path":"CNN/tools/ImgResize.py","file_name":"ImgResize.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"596774344","text":"import numpy as np\nimport re\nfrom variables import*\nfrom sklearn.utils import shuffle\nimport string\n\ndef load_data():\n id2line = {}\n for line in open(movie_lines_path, encoding='utf-8', errors='ignore'):\n line = line.split('\\n')[0]\n line = line.split(' +++$+++ ')\n if len(line) == 5:\n line_id = line[0]\n line_text = line[-1]\n id2line[line_id] = line_text\n\n conversation_ids = []\n for line in open(movie_conversations_path, encoding='utf-8', errors='ignore'):\n line = line.split('\\n')[0]\n line = line.split(' +++$+++ ')\n id_list = eval(line[-1])\n conversation_ids.append(id_list)\n\n return id2line, conversation_ids\n\n\t\n\t\ndef clean_text(text):\n text = text.lower()\n text = re.sub(r\"i'm\", \"i am\", text)\n text = re.sub(r\"he's\", \"he is\", text)\n text = re.sub(r\"she's\", \"she is\", text)\n text = re.sub(r\"that's\", \"that is\", text)\n text = re.sub(r\"what's\", \"what is\", text)\n text = re.sub(r\"where's\", \"where is\", text)\n text = re.sub(r\"how's\", \"how is\", text)\n text = re.sub(r\"\\'ll\", \" will\", text)\n text = re.sub(r\"\\'ve\", \" have\", text)\n text = re.sub(r\"\\'re\", \" are\", text)\n text = re.sub(r\"\\'d\", \" would\", text)\n text = re.sub(r\"n't\", \" not\", text)\n text = re.sub(r\"won't\", \"will not\", text)\n text = re.sub(r\"can't\", \"cannot\", text)\n text = re.sub(r\"[-()\\\"#/@;:<>{}`+=~|.!?,]\", \"\", text)\n return text\n\t\n\t\n\ndef get_Q_A():\n id2line, conversation_ids = load_data()\n questions = []\n answers = []\n for conversation_id in conversation_ids:\n for i in range(len(conversation_id)-1):\n question = clean_text(id2line[conversation_id[i]])\n answer = clean_text(id2line[conversation_id[i+1]])\n questions.append(question)\n answers.append(answer)\n return questions, answers\n\t\n\t\n\ndef get_data():\n questions, answers = get_Q_A()\n questions, answers = shuffle(questions, answers)\n questions, answers = np.array(questions), np.array(answers)\n ids = np.array([i for i in range(len(questions)) if (len(questions[i].split()) <= 8) and (len(answers[i].split()) <= 8)])\n idxs = np.random.choice(ids, num_samples, replace=False)\n questions, answers = questions[idxs], answers[idxs]\n\n inputs = []\n target_inputs = []\n targets = []\n\n for i in range(len(answers)):\n input_seq = questions[i]\n output_seq = answers[i]\n target_input_seq = ' ' + output_seq\n target_seq = output_seq + ' '\n\n inputs.append(input_seq)\n target_inputs.append(target_input_seq)\n targets.append(target_seq)\n\n return inputs, target_inputs, targets","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"314160224","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models, _\n\nclass PurchaseOrder(models.Model):\n\n\t_inherit = 'purchase.order'\n\n\tshipping_address_id = fields.Many2one('res.partner',string='Address')\n\n\t@api.onchange('partner_id')\n\tdef onchange_partner(self):\n\t\t#onchange of partner will set the shipping address default.\n\t\tpartner_id = self.env['res.partner'].search([('parent_id','=',self.company_id.partner_id.id),('type','=','delivery')])\n\t\tif partner_id:\n\t\t\tself.shipping_address_id = partner_id.id\n\t\telse:\n\t\t\tself.shipping_address_id = False\n\t\nclass PurchaseOrderLine(models.Model):\n\n\t_inherit = \"purchase.order.line\"\n\n\tvendor_product_code = fields.Char('Vendor Product Code',compute='return_vendor_product_code')\n\n\t@api.depends('product_id')\n\tdef return_vendor_product_code(self):\n\t\tfor line in self:\n\t\t\tproduct_supplier_info_id = self.env['product.supplierinfo'].search([('name','=',line.order_id.partner_id.id),('product_tmpl_id','=',line.product_id.product_tmpl_id.id),('product_code','!=',False)],limit=1)\n\t\t\tif product_supplier_info_id:\n\t\t\t\tline.vendor_product_code = product_supplier_info_id.product_code\n\t\t\t\tif line.product_id.default_code and line.product_id.name:\n\t\t\t\t\tline.name = str(\"[\" + line.product_id.default_code + \"]\"+ \" \" + line.product_id.name)\n\t\t\t\telif line.product_id.default_code and not line.product_id.name:\n\t\t\t\t\tline.name = str(line.product_id.default_code)\n\t\t\t\telif line.product_id.name and not line.product_id.default_code:\n\t\t\t\t\tline.name = str(line.product_id.name)\n\t\t\telse:\n\t\t\t\tline.vendor_product_code = False","sub_path":"wibtec_purchase/models/purchase_order.py","file_name":"purchase_order.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"143121199","text":"#\r\n# @lc app=leetcode.cn id=1343 lang=python3\r\n#\r\n# [1343] 大小为 K 且平均值大于等于阈值的子数组数目\r\n#\r\n# https://leetcode-cn.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/description/\r\n#\r\n# algorithms\r\n# Medium (57.52%)\r\n# Likes: 4\r\n# Dislikes: 0\r\n# Total Accepted: 1K\r\n# Total Submissions: 1.8K\r\n# Testcase Example: '[2,2,2,2,5,5,5,8]\\n3\\n4'\r\n#\r\n# 给你一个整数数组 arr 和两个整数 k 和 threshold 。\r\n#\r\n# 请你返回长度为 k 且平均值大于等于 threshold 的子数组数目。\r\n#\r\n#\r\n#\r\n# 示例 1:\r\n#\r\n# 输入:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4\r\n# 输出:3\r\n# 解释:子数组 [2,5,5],[5,5,5] 和 [5,5,8] 的平均值分别为 4,5 和 6 。其他长度为 3 的子数组的平均值都小于 4\r\n# (threshold 的值)。\r\n#\r\n#\r\n# 示例 2:\r\n#\r\n# 输入:arr = [1,1,1,1,1], k = 1, threshold = 0\r\n# 输出:5\r\n#\r\n#\r\n# 示例 3:\r\n#\r\n# 输入:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5\r\n# 输出:6\r\n# 解释:前 6 个长度为 3 的子数组平均值都大于 5 。注意平均值不是整数。\r\n#\r\n#\r\n# 示例 4:\r\n#\r\n# 输入:arr = [7,7,7,7,7,7,7], k = 7, threshold = 7\r\n# 输出:1\r\n#\r\n#\r\n# 示例 5:\r\n#\r\n# 输入:arr = [4,4,4,4], k = 4, threshold = 1\r\n# 输出:1\r\n#\r\n#\r\n#\r\n#\r\n# 提示:\r\n#\r\n#\r\n# 1 <= arr.length <= 10^5\r\n# 1 <= arr[i] <= 10^4\r\n# 1 <= k <= arr.length\r\n# 0 <= threshold <= 10^4\r\n#\r\n#\r\n#\r\n\r\n\r\n# @lc code=start\r\nclass Solution:\r\n def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:\r\n # 从左向右依次判断, 滑动区间, 维护大小为k的子数组和\r\n if not arr or k == 0:\r\n return 0\r\n sm = sum(arr[0:k])\r\n res = 1 if sm / k >= threshold else 0\r\n for i in range(k, len(arr)):\r\n sm += arr[i] - arr[i - k]\r\n if sm / k >= threshold:\r\n res += 1\r\n return res\r\n\r\n\r\n# @lc code=end\r\n","sub_path":"Medium/1343.大小为-k-且平均值大于等于阈值的子数组数目.py","file_name":"1343.大小为-k-且平均值大于等于阈值的子数组数目.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558213113","text":"#-*- coding: UTF-8 -*-\n\"\"\"\ntelegram-quote-bot\nDaily Quote Subscription Service Telegram Chatbot\n\"\"\"\nimport logging\nimport sys\nfrom os import path, environ\nimport telebot\nfrom core.non_text_deco import NonTextDeco, PhotoDeco, VideoDeco, VoiceDeco, AudioDeco, LocationDeco, \\\n StickerDeco, VideoNoteDeco\nfrom core.text_deco import TextDeco\n\nif __package__ is None:\n sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )\nelse:\n sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\n\nfrom tele.tele_polling_bot import TelePollingBot\nfrom tele.tele_dialogue import TeleDialogue\nlogger = telebot.logger\ntelebot.logger.setLevel(logging.INFO) # Outputs INFO/DEBUG messages to console.\nfrom tele.tele_utils import send_sticker, tele_get_user\n\ntoken = environ['TELE_TOKEN']\nbot = TelePollingBot(token)\n\n\n@bot.message_handler(content_types = ['text', 'photo', 'audio', 'voice', 'video', 'video_note'])\ndef handle_command(message):\n \"\"\"Handle messages.\"\"\"\n user = tele_get_user(message)\n dia = TeleDialogue(message.chat.id, message.from_user.id, message.text, user, message.chat.type, None)\n\n if message.text is not None:\n dia.InMsg = TextDeco(dia.InMsg)\n elif message.photo is not None:\n dia.InMsg = PhotoDeco(dia.InMsg, message.photo[len(message.photo) - 1].file_id)\n elif message.audio is not None:\n dia.InMsg = AudioDeco(dia.InMsg, message.audio.file_id)\n elif message.voice is not None:\n dia.InMsg = VoiceDeco(dia.InMsg, message.voice.file_id)\n elif message.video is not None:\n dia.InMsg = VideoDeco(dia.InMsg, message.video.file_id)\n elif message.video_note is not None:\n dia.InMsg = VideoNoteDeco(dia.InMsg, message.video_note.file_id)\n\n dia.InMsg.process_input(dia)\n dia.process_output()\n\n if 'photo' in dia.OutMsg.tele_kwargs.keys():\n bot.send_photo(**dia.OutMsg.tele_kwargs)\n dia.OutMsg = PhotoDeco(dia.OutMsg)\n elif 'audio' in dia.OutMsg.tele_kwargs.keys():\n bot.send_audio(**dia.OutMsg.tele_kwargs)\n dia.OutMsg = AudioDeco(dia.OutMsg)\n elif 'voice' in dia.OutMsg.tele_kwargs.keys():\n bot.send_voice(**dia.OutMsg.tele_kwargs)\n dia.OutMsg = VoiceDeco(dia.OutMsg)\n elif 'data' in dia.OutMsg.tele_kwargs.keys() and dia.OutMsg.item == 'video':\n bot.send_video(**dia.OutMsg.tele_kwargs)\n dia.OutMsg = VideoDeco(dia.OutMsg)\n elif 'data' in dia.OutMsg.tele_kwargs.keys() and dia.OutMsg.item == 'videonote':\n bot.send_video_note(**dia.OutMsg.tele_kwargs)\n dia.OutMsg = VideoNoteDeco(dia.OutMsg)\n elif dia.is_valid_kwargs():\n bot.send_message(**dia.OutMsg.tele_kwargs)\n dia.OutMsg = TextDeco(dia.OutMsg)\n else:\n dia.InMsg.print_in_msg(dia)\n return\n\n dia.InMsg.print_in_msg(dia)\n dia.OutMsg.print_out_msg()\n\n\n@bot.message_handler(content_types = ['document'])\ndef handle_command(message):\n user = tele_get_user(message)\n dia = TeleDialogue(message.chat.id, message.from_user.id, message.text, user, message.chat.type)\n dia.InMsg = NonTextDeco(dia.InMsg)\n dia.InMsg.item = 'Document'\n dia.InMsg.print_in_msg(dia)\n\n\n@bot.message_handler(content_types = ['location'])\ndef handle_command(message):\n dia = TeleDialogue(message.chat.id, message.from_user.id, message.text, message.chat.first_name + message.chat.last_name, message.chat.type)\n dia.InMsg = LocationDeco(dia.InMsg)\n dia.InMsg.print_in_msg(dia)\n\n\n@bot.message_handler(content_types = ['sticker'])\ndef handle_command(message):\n user = tele_get_user(message)\n dia = TeleDialogue(message.chat.id, message.from_user.id, message.text, user, message.chat.type)\n dia.InMsg = StickerDeco(dia.InMsg)\n dia.InMsg.print_in_msg(dia)\n dia.stop_awaiting_incoming_quote()\n\n\nif __name__ == \"__main__\":\n bot.polling(none_stop = True, interval = 0, timeout = 3)\n","sub_path":"tele/telegram_quote_bot.py","file_name":"telegram_quote_bot.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618402755","text":"from cmath import *\nfrom random import *\nfrom sys import *\nfrom os import *\nfrom math import *\n\ndef cbrt(number, min_of_test_range, max_of_range): #guesses and checks for a cube root\n n_1 = number\n __min__ = min_of_test_range\n m_a_x = max_of_range\n m_m_l = 0\n for x in range (__min__,m_a_x):\n #this does the guess 'n check part\n if x**3 == n_1:\n return x\n else:\n m_m_l = m_m_l + 1\n\n if m_m_l == (m_a_x-__min__):\n return 'the number\\'s cube root is not in the range you have given me or it could be irrational'\n\ndef selfexpont(number): #this : exponts :: multiplication : addition\n n_2 = number\n return (n_2**n_2)\n\ndef add (number1 , number2): #it adds numbers what else would it do?!?\n return (number1+number2)\n\ndef add_ (number1 , number2): #hahaha it 'adds' numbers\n return float((str(number1) + str(number2)))\n\n\ndef cbrtmulti(number_min , number_max , minrange , maxrange):\n max_ = maxrange\n min_ = minrange\n med = (min_+max_)/2\n if med * 2 % 2 != 0:\n med = med + 1\n else:\n pass\n for x in range (number_min , number_max):\n #here it does the multiple cube roots\n for y in range (min_ , (med-1)):\n for z in range (med , max_):\n print (cbrt(x , y , z))\n\ndef sqrtmulti(number_min , number_max , minrange , maxrange):\n max_ = maxrange\n min_ = minrange\n med = (min_+max_)/2\n for x in range (number_min , number_max):\n #here it does the multiple square roots\n for y in range (min_ , (med-1)):\n for z in range (med , max_):\n print (sqrt(x))\n\ndef substrnum(string , number):\n len_ = len(string)-1\n newstring = ''\n for x in range (0, len_):\n newstring = newstring + string[x]\n if x == len_ - number:\n return (newstring)\n else:\n pass\n\ndef divstr(string , number):\n len_ = len(string)+1\n f=0\n for x in range (0,len_):\n if x % number == 0:\n print (string[f:x])\n f = x\n\ndef prime(number):\n if number == 1 or number == 0:\n raise ValueError(\"1 and 0 are neither prime nor composite\")\n for x in range (2,number-1):\n if number % x == 0:\n return False\n else:\n pass\n return True\n\ndef composite(number):\n return not prime(number)\n\ndef anyrt(exponint,base):\n e=exponint\n b=base\n n=b**(1/e)\n return n\n\ndef anymulti(exponint , number_min , number_max):\n for x in range (number_min , number_max):\n #here it does the multiple roots\n print (anyrt(exponint,x))\n\ndef eRr0r (type_, txt):\n typ = lower(type_)\n if txt == None:\n raise RuntimeError('must have some text!!!')\n if typ == 'value':\n raise ValueError(txt)\n elif typ == 'overflow' or typ == 'over':\n raise OverflowError(txt)\n elif typ == 'run' or typ == 'time' or typ == 'runtime':\n raise RuntimeError(txt)\n else:\n raise RuntimeError(txt + 'is not a error or it is not in my database or it is not a error')\n\ndef prime_generator():\n from random import randint\n prime_ = randint(6,10000)*6\n if prime_ % 2 == 0:\n prime_ = prime_+1\n else:\n prime_ = prime_-1\n if prime(prime_) == True:\n return prime_\n else:\n prime_ = randint(6,10000)*6\n if prime_ % 2 == 0:\n prime_ = prime_+1\n else:\n prime_ = prime_-1\n if prime(prime_):\n return prime_\n else:\n prime_ = randint(6,10000)*6\n if prime_ % 2 == 0:\n prime_ = prime_+1\n else:\n prime_ = prime_-1\n if prime(prime_):\n return prime_\n else:\n raise RuntimeError('try again')\n\ndef prime(number):\n if number == 1 or number == 0:\n return False\n for x in range (2,number-1):\n if number % x == 0:\n return False\n else:\n pass\n return True\n\ndef prime_generator(least):\n from random import randint\n prime_ = randint(least,((100*least+5)%19)+least)*6\n if prime_ % 2 == 0:\n prime_ = prime_+1\n else:\n prime_ = prime_-1\n if prime(prime_) == True:\n return prime_\n else:\n prime_ = randint(6,10000)*6\n if prime_ % 2 == 0:\n prime_ = prime_+1\n else:\n prime_ = prime_-1\n if prime(prime_):\n return prime_\n else:\n prime_ = randint(6,10000)*6\n if prime_ % 2 == 0:\n prime_ = prime_+1\n else:\n prime_ = prime_-1\n if prime(prime_):\n return prime_\n else:\n prime_generator(least+1)\n\ndef prime_to(n):\n x = []\n for y in range(n):\n if prime(y):\n x.append(x)\n else:\n continue\n return x\n\ndef count(start,stop,step):\n for x in range(start, stop):\n yield (x)\n\ndef substrstr(str1 , str2):\n new = ''\n li = []\n il = []\n for x in str1:\n li.append(x)\n for x in str2:\n il.append(x)\n for x in li:\n for y in il:\n if y != x:\n new += y\n break\n else:\n continue\n return new\n\ndef area_of_sphere(radius):\n 4*pi*radius**2\n\ndef premution (a,b):\n w = 0\n x = 1\n while w < b:\n x *= a-w\n w += 1\n return w\n\np = premution\n\ndef combination(x,y):\n ansewr = p(x,y)/p(y,y)\n return ansewr\n\nc = combination\n\ndef fact(n):\n r = 1\n while n > 0:\n r *= n\n n -= 1\n return r\n\ndef info():\n return ('made by Scott Whalen Blair on 7/10/2013 with Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] more math v1.2')\n","sub_path":"docs/math.py","file_name":"math.py","file_ext":"py","file_size_in_byte":5797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"206533357","text":"with open('data', 'r') as f:\r\n l = [[int(num) for num in line.split(',')] for line in f]\r\n\r\ni =0\r\nfor element in l:\r\n l[i][2] = element[2]/100\r\n l[i][4] = element[4]/100\r\n i+=1;\r\n\r\nresultMaxMin = []\r\nresult = []\r\ndef calculate( data =[[]]):\r\n for element in data :\r\n temparray =[]\r\n temparray.append(element[0]+element[1]*element[5])\r\n temparray.append(element[0]+element[3]*element[5])\r\n resultMaxMin.append(temparray)\r\n result.append(temparray[0]*element[2]+temparray[1]*element[4])\r\n\r\ncalculate(l)\r\n\r\ndef printresult(text ,data):\r\n print(text)\r\n for element in data:\r\n print(element)\r\n print()\r\ntext1 =' M1 D1 P1 D2 P2 Y'\r\ntext2 =' Max Min'\r\ntext3 ='Профіт'\r\ntext4 ='Максимальний профіт\\n'\r\n\r\nprintresult(text1,l)\r\nprintresult(text2, resultMaxMin)\r\nprintresult(text3, result)\r\nprint(text4,max(result))\r\n\r\n","sub_path":"Lab2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"257980831","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------\n# \n# C/C++ template generator\n#\n# File: ctemplate.py\n# Author: Peter Malmberg \n# Date: 2016-02-19\n# Version: 0.2\n# Python: >=3\n# Licence: MIT\n# \n# -----------------------------------------------------------------------\n# History\n#\n# Todo \n#\n# Imports -------------------------------------------------------------------\n\nimport sys\nimport os \nimport traceback\nimport logging\nimport argparse\nfrom datetime import datetime, date, time\n\n# Settings ------------------------------------------------------------------\n\nAppName = \"ctemplate\"\nAppVersion = \"0.2\"\nAppLicence = \"MIT\"\nAppAuthor = \"Peter Malmberg \"\n\n# Uncomment to use logfile\n#LogFile = \"pyplate.log\"\n\n# Code ----------------------------------------------------------------------\n\n \ndef addHeader(file, fileName, brief, date, author, license):\n header = headerExample\n \n header = header.replace(\"__FILENAME__\", fileName )\n header = header.replace(\"__BRIEF__\", brief )\n header = header.replace(\"__DATE__\", date )\n header = header.replace(\"__AUTHOR__\", author )\n header = header.replace(\"__LICENSE__\", license )\n \n file.write(header)\n\n \ndef addSection(file, desc):\n line = '-' * (71 - len(desc))\n file.write(\"// \" + desc + \" \" + line + \"\\n\\n\")\n \ndef addSection2(file, desc):\n file.write( \\\n \"/**\\n\" \\\n \" * \"+desc+\"\\n\" \\\n \" *------------------------------------------------------------------\\n\" \\\n \" */\\n\\n\") \n \ndef addSentinelBegin(file, sentinel):\n file.write( \\\n \"#ifndef \"+sentinel+\"_H\\n\" \\\n \"#define \"+sentinel+\"_H\\n\\n\") \n \ndef addSentinelEnd(file):\n file.write(\"#endif\\n\\n\")\n\ndef addCppSentinel(file):\n file.write( \\\n \"#ifdef __cplusplus\\n\" \\\n \"extern \\\"C\\\" {\\n\" \\\n \"#endif\\n\\n\")\n \ndef addCppSentinelEnd(file): \n file.write( \\\n \"#ifdef __cplusplus\\n\" \\\n \"} //end brace for extern \\\"C\\\"\\n\" \\\n \"#endif\\n\")\n \ndef addMethod(file, className, methodName): \n file.write(className+\"::\"+methodName+\"() {\\n\")\n file.write(\"\\n}\\n\\n\")\n\ndef addClass(file, className):\n file.write(\"class \"+className+\" {\\n\")\n file.write(\" public:\\n\") \n file.write(\" \"+className+\"();\\n\")\n file.write(\"}\\n\")\n\ndef addInclude(file, includeFile): \n file.write(\"#include <\"+includeFile+\">\\n\") \n \ndef addCIncludes(file):\n addInclude(file, \"stdio.h\")\n addInclude(file, \"stdlib.h\")\n addInclude(file, \"sys/types.h\")\n addInclude(file, \"unistd.h\")\n addInclude(file, \"signal.h\")\n addInclude(file, \"string.h\")\n addInclude(file, \"errno.h\")\n \ndef addGTKIncludes(file):\n addInclude(file, \"gtk/gtk.h\")\n \ndef addQtIncludes(file):\n addInclude(file, \"QApplication\")\n addInclude(file, \"QCoreApplication\")\n addInclude(file, \"QDebug\")\n addInclude(file, \"QMainWindow\")\n addInclude(file, \"QPushbutton\")\n addInclude(file, \"QLabel\")\n \ndef addMain(file):\n file.write(\"int main(int argc, char *argv[]) {\\n\\n\")\n file.write(\" return 0;\\n\") \n file.write(\"}\\n\")\n \n\ndef newFile(dir, fileName):\n # Open files to be generated\n try:\n file = open(dir+\"/\"+fileName, 'w')\n return file\n except IOError:\n logging.debug(\"Could not open template file %s\" % (fileName))\n exit()\n\n\ndef askInfo(module):\n print(\"Creating new \"+module)\n fName = input(\"Enter \"+module+\" name(no extention:>\")\n brief = input(\"Enter brief description:> \")\n \n date = datetime.now().strftime(\"%Y-%m-%d\") \n return fName, brief, date\n \ndef newCModule(dir, author, licence):\n newModule(dir, author, licence, \"c\")\n\ndef newCppModule(dir, author, licence):\n newModule(dir, author, licence, \"cpp\")\n\ndef newModule(dir, author, licence, lan):\n \n # ask for some information\n fName, brief, date = askInfo(\"C module\")\n\n main = query_yn(\"Add main() function\", \"no\")\n\n \n if main and lan==\"c\":\n gtkMain = query_yn(\"GTK project\", \"no\")\n else:\n gtkMain = 0\n\n if main and lan==\"cpp\": \n qtMain = query_yn(\"Qt project\", \"no\")\n else:\n qtMain = 0\n \n \n fileNameC = fName + \".\"+lan\n fileNameH = fName + \".h\"\n\n # Open files to be generated\n fileC = newFile(dir, fileNameC)\n fileH = newFile(dir, fileNameH)\n\n # Populate C file\n addHeader(fileC, fileNameC, brief, date, author, licence)\n\n addSection(fileC, \"Includes\")\n \n if (main):\n addCIncludes(fileC)\n \n fileC.write(\"#include \\\"\"+fileNameH+\"\\\"\\n\\n\");\n \n addSection(fileC, \"Macros\")\n addSection(fileC, \"Variables\")\n addSection(fileC, \"Prototypes\")\n addSection(fileC, \"Code\") \n \n if (gtkMain):\n fileC.write(gtkMainExample)\n else:\n if (main):\n fileC.write(mainExample)\n \n\n # Populate H file\n addHeader(fileH, fileNameH, brief, date, author, licence)\n addSentinelBegin(fileH, fName.upper())\n addCppSentinel(fileH)\n addSection(fileH, \"Includes\")\n addSection(fileH, \"Macros\")\n addSection(fileH, \"Typedefs\")\n addSection(fileH, \"Variables\")\n addSection(fileH, \"Prototypes\")\n addCppSentinelEnd(fileH)\n addSentinelEnd(fileH)\n \n # Close down files\n fileC.close()\n fileH.close()\n \ndef newClass(dir, author, licence):\n\n # ask for some information\n fName, brief, date = askInfo(\"C++ Class\")\n\n fileNameC = fName + \".cpp\"\n fileNameH = fName + \".h\"\n\n # Open files to be generated\n fileC = newFile(dir, fileNameC)\n fileH = newFile(dir, fileNameH)\n\n # Populate C++ file\n addHeader(fileC, fileNameC, brief, date, author, licence)\n addSection(fileC, \"Includes\")\n fileC.write(\"#include \\\"\"+fileNameH+\"\\\"\\n\\n\");\n \n addSection(fileC, \"Macros\")\n addSection(fileC, \"Variables\")\n addSection(fileC, \"Prototypes\")\n addSection(fileC, \"Code\") \n \n addMethod(fileC, fName, fName)\n \n # Populate H file\n addHeader(fileH, fileNameH, brief, date, author, licence)\n\n addSentinelBegin(fileH, fName.upper()) \n addSection(fileH, \"Includes\")\n addSection(fileH, \"Macros\")\n addSection(fileH, \"Typedefs\")\n addSection(fileH, \"Variables\")\n \n addClass(fileH, fName)\n \n addSentinelEnd(fileH)\n \n # Close down files\n fileC.close()\n fileH.close()\n\ndef printInfo():\n print(\"Script name \" + AppName)\n print(\"Script version \" + AppVersion)\n print(\"Script path \" + os.path.realpath(__file__))\n\n\n \ndef newProject(dir, author, license):\n print(scriptPath)\n print(mpPath)\n \n# projName = input(\"Enter project name:> \")\n# subDir = query_yn(\"Create subdirectory?\", \"yes\")\n \n lan = query_list(\"Enter language\", [ \"C\", \"C++\" ], \"C\")\n return \n if subDir:\n os.mkdir(projName)\n \n \n# Absolute path to script itself \nscriptPath = os.path.abspath(os.path.dirname(sys.argv[0]))\nmpPath = scriptPath+\"/..\" \n\ndef main():\n logging.basicConfig(level=logging.DEBUG)\n \n # options parsing\n parser = argparse.ArgumentParser(description=\"Makeplate C/C++ template generator\")\n parser.add_argument(\"--newc\", action=\"store_true\", help=\"Create a new C and H file set\")\n parser.add_argument(\"--newcpp\", action=\"store_true\", help=\"Create a new C++ and H file set\")\n parser.add_argument(\"--newclass\", action=\"store_true\", help=\"Create a new C++ class\")\n parser.add_argument(\"--newQt\", action=\"store_true\", help=\"Create a new Qt project\")\n parser.add_argument(\"--newgtk\", action=\"store_true\", help=\"Create a new GTK project\")\n parser.add_argument(\"--newproj\", action=\"store_true\", help=\"Create a new Makeplate project\")\n parser.add_argument(\"--license\", type=str, help=\"License of new file\", default=\"\")\n parser.add_argument(\"--author\", type=str, help=\"Author of file\", default=\"\")\n parser.add_argument(\"--dir\", type=str, help=\"Directory where to store file\", default=\".\")\n \n args = parser.parse_args()\n\n if args.newc:\n newCModule(args.dir, args.author, args.license)\n exit(0)\n \n if args.newclass:\n newClass(args.dir, args.author, args.license)\n exit(0)\n \n if args.newcpp:\n newCppModule(args.dir, args.author, args.license)\n exit(0)\n\n if args.newgtk:\n newCppModule(args.dir, args.author, args.license)\n exit(0)\n\n if args.newQt:\n newCppModule(args.dir, args.author, args.license)\n exit(0)\n\n if args.newproj:\n newProject(args.dir, args.author, args.license)\n exit(0)\n \n \n exit(0) \n\n \ndef query_list(question, db, default=\"yes\"):\n prompt = \" >\"\n\n #print(db)\n while 1:\n sys.stdout.write(question + prompt)\n choice = input().lower()\n print(choice)\n for x in db:\n if (x.lower()==choice):\n return x\n \n print(\"\\nPlease resplond with: \")\n for c in db:\n print(\" \"+c)\n \n \ndef query_yn(question, default=\"yes\"):\n valid = {\"yes\": True, \"y\": True, \"ye\": True, \"no\": False, \"n\": False}\n if default is None:\n prompt = \" [y/n] \"\n elif default == \"yes\":\n prompt = \" [Y/n] \"\n elif default == \"no\":\n prompt = \" [y/N] \"\n else:\n raise ValueError(\"invalid default answer: '%s'\" % default)\n \n while True:\n sys.stdout.write(question + prompt)\n choice = input().lower()\n if default is not None and choice == '':\n return valid[default]\n elif choice in valid:\n return valid[choice]\n else:\n sys.stdout.write(\"Please respond with 'yes' or 'no' (or 'y' or 'n').\\n\")\n \n \nheaderExample=\"\"\"/**\n *---------------------------------------------------------------------------\n * @brief __BRIEF__\n *\n * @file __FILENAME__\n * @author __AUTHOR__\n * @date __DATE__\n * @license __LICENSE__\n *\n *---------------------------------------------------------------------------\n *\n *\n */\n\"\"\" \n \ngtkMainExample=\"\"\"\n\nint main(int argc, char *argv[]) {\n \n signal(SIGINT, sigInt);\n signal(SIGHUP, sigHup);\n\n\n// GTK Glade --------------------------------------------------------------------\n\n gtk_init(&argc, &argv);\n\n builder = gtk_builder_new();\n gtk_builder_add_from_file (builder, \"gtkTest.glade\", NULL);\n\n window = GTK_WIDGET(gtk_builder_get_object(builder, \"window2\"));\n gtk_builder_connect_signals(builder, NULL);\n\n //g_object_unref(builder);\n\n GtkWidget *w;\n GtkTextIter iter;\n w = gtk_builder_get_object(builder, \"textview2\");\n //gtk_text_view_set_buffer(w, buf);\n buf = gtk_text_view_get_buffer(w);\n gtk_text_buffer_get_iter_at_offset(buf, &iter, 0);\n gtk_text_buffer_insert(buf, &iter, \"Kalle\", -1);\n \n return 0;\n}\n\"\"\"\n\nmainExample=\"\"\"\nint main(int argc, char *argv[]) {\n \n return 0;\n}\n\"\"\"\n\nqtCoreMainExample=\"\"\"\nint main(int argc, char *argv[]) {\n \n QCoreApplication app(argc, argv);\n \n return app.exec();\n}\n\"\"\"\n\nqtMainExample=\"\"\"\nint main(int argc, char *argv[]) {\n \n QApplication app(argc, argv);\n// MainWindow w;\n// w.show();\n \n return app.exec();\n}\n\"\"\"\n \n \nif __name__ == \"__main__\":\n try:\n main()\n sys.exit(0)\n except KeyboardInterrupt as e: # Ctrl-C\n raise e\n except SystemExit as e: # sys.exit()\n raise e\n except Exception as e:\n print('ERROR, UNEXPECTED EXCEPTION')\n print(str(e))\n traceback.print_exc()\n os._exit(1)\n\n \n","sub_path":"c/conflog/tools/ctemplate.py","file_name":"ctemplate.py","file_ext":"py","file_size_in_byte":11724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343618795","text":"# ---------------------------------- #\n# Crawler for www.1101.com/iimatugai #\n# ---------------------------------- #\n\n# Author: S. Komatsu (i15323@kagawa.kosen-ac.jp)\n# Repository: https://github.com/i15323/iimatugai\n\n# モジュールの追加\nimport urllib.request\nimport re\nimport os\nimport csv\nfrom collections import Counter\nfrom bs4 import BeautifulSoup\n\n# グローバル変数\nURL_LIST = \"\"\nWRITE_FILE_NAME = \"\"\n\n\ndef main():\n # URL Listを読み込む\n ul = []\n for row in open(URL_LIST, \"r\", encoding=\"UTF-8\"):\n # コメント行の処理\n if row.find(\"#\") == -1:\n ul.append(row)\n\n print(\"=== 終了したURL ===\")\n\n # 全URLに対してクローリングを実行\n for url in ul:\n # 言い間違い例の全文を取得\n ft = getFullText(url)\n # 言い間違い例の部分を取得\n iimatigai = getIimatugai(url)\n \n # 言い間違いの分類を実行\n cl = classify(ft, url)\n\n # CSV形式で結果を保存\n writeFile(ft, iimatigai, cl, url)\n\n # 進行状況の表示\n print(url, end='')\n\n\ndef getFullText(url):\n # HTMLオブジェクト取得,テキスト変換\n with urllib.request.urlopen(url) as response:\n html = response.read().decode(\"shift-jis\")\n\n # HTMLのパース,スクレイピング\n soup = BeautifulSoup(html, \"html.parser\")\n\n # 条件付きTableタグの取得\n table = soup.findAll(\"table\", attrs={'border': '0', 'cellspacing': '10', 'cellpadding' :'0'})\n\n # 詳細条件の設定,タグ除去\n f = []\n for e in table[2:-4]:\n e1 = e.findAll(\"td\", attrs={'align': 'left', 'valign': 'top'})\n f.append(e1)\n\n pattern = re.compile(\"<.*?>\")\n l = []\n for e in f:\n # 無駄な文字の削除\n e1 = pattern.sub(\"\", str(e))\n e1 = e1.replace(',', '')\n e1 = e1.replace('[', '')\n e1 = e1.replace(']', '')\n e1 = e1.replace('\\t', '')\n e1 = e1.replace(' ', '')\n # 改行コード変換(CRLF=>LF)\n e1 = e1.replace('\\r\\n', '\\n')\n\n if e1 != '':\n l.append(e1)\n\n return l\n\ndef getIimatugai(url):\n # HTMLオブジェクト取得,テキスト変換\n with urllib.request.urlopen(url) as response:\n html = response.read().decode('shift_jis')\n\n # HTMLのパース,スクレイピング\n soup = BeautifulSoup(html, \"html.parser\")\n\n # futojiタグの取得\n futoji = soup.find_all(\"span\", class_=\"futoji\")\n\n # 不要なタグの除去\n l = []\n pattern = re.compile(\"<.*?>\")\n for e in futoji:\n e1 = pattern.sub(\"\", str(e))\n l.append(e1)\n\n return l\n\n\ndef writeFile(f, i, c, url):\n # 書き込みファイル名の調整\n url = url.split(\"/\")\n url = url[4]\n url = url.split(\".\")\n url = url[0]\n writeFileStream = open(WRITE_FILE_NAME + str(url) + \"_\" + str(c) + \".csv\", \"w\", encoding=\"Shift-JIS\")\n # writeFileStream = open(WRITE_FILE_NAME, \"a\", encoding=\"UTF-8\")\n\n # 書き込み実行\n size = len(f)\n for c in range(size):\n try:\n writeFileStream.write('\"' + f[c] + '\",' + i[c])\n writeFileStream.write(\"\\n\")\n except UnicodeEncodeError:\n print(\"Oh..UnicodeEncodeError\")\n\ndef classify(fullText, url):\n ''' 言い間違いの分類 '''\n # html ソース\n with urllib.request.urlopen(url) as response:\n html = response.read().decode('shift_jis')\n \n fullText = str(html)\n \n # 使用CSVで言い間違いタイプを判別\n css_dict = {\n \"css/yellow2009.css\": \"まつがい\",\n \"css/pink2009.css\": \"R指定\",\n \"css/black2009.css\": \"暗黒\"\n }\n # 検索実行\n for k, v in css_dict.items():\n if fullText.find(k) != -1:\n return v\n\n # 本文中の用語で間違いタイプを判定\n class_list = [\n \"書きまつがい\",\n \"元祖\",\n \"まつがい電話\",\n \"固有名詞\",\n \"聞きまつがい\",\n \"珍解答\",\n \"誤メール\",\n \"子供\",\n \"かみ合わない\",\n ]\n\n for cl in class_list:\n if fullText.find(cl) != -1:\n return cl\n\n return \"その他\"\n\n\nif __name__ == \"__main__\":\n print(\"Start crawling...\")\n # ディレクトリごと一括処理\n# ld = os.listdir(\"urllist_archive\")\n# for f in ld:\n# URL_LIST = \"./urllist_archive/\" + f\n# WRITE_FILE_NAME = \"./csv2/result_\" + f\n URL_LIST = \"urllist_archive/urllist\"\n WRITE_FILE_NAME = \"csv3/urllist\"\n main()\n","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":4716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"331751897","text":"import random\n\n\nclass EventProvider:\n \"\"\"\n An EventProvider is an abstract class that provides events. An event is a\n string that describes the event.\n \"\"\"\n\n def get_next_event(self):\n \"\"\" (EventProvider) -> None or str\n Return the next event or None if there are no more events.\n\n \"\"\"\n raise NotImplementedError('Abstract method')\n\n def has_next_event(self):\n \"\"\" (EventProvider) -> bool\n Return True iff there is a next event.\n\n \"\"\"\n raise NotImplementedError('Abstract method')\n\n\nclass EventFile(EventProvider):\n \"\"\"\n An EventFile is an EventProvider that uses a file as a source for the events\n that it provides. Each event is a line in that file.\n \"\"\"\n def __init__(self, file):\n self.file = open(file)\n line = self.file.readline()\n if line == \"\":\n file.close()\n\n def has_next_event(self):\n if self.file.close() == True:\n return True\n\n def get_next_event(self):\n if self.file.close() == True:\n return None\n else:\n for lines in self.file:\n line = self.file.readline()\n if line == \"\":\n self.file.close()\n\nclass EventUser(EventProvider):\n \"\"\"\n An EventUser is an EventProvider that uses interactive input from the\n user as a source for the events that it provides.\n \"\"\"\n\n # Your code here\n\n\nclass RandomEventProvider(EventProvider):\n \"\"\"\n A RandomEventProvider is an EventProvider that provides random events.\n\n The RandomEventProvider is rather simple in the way that it provides events:\n each type of event is equally likely to be provided.\n \"\"\"\n\n # Your code here\n\n\nif __name__ == '__main__':\n # Task 1\n provider = EventFile(\"events.txt\")\n #provider = EventUser('Enter an event: ')\n #provider = RandomEventProvider(15)\n\n i = 1\n while provider.has_next_event():\n print('{}: {}'.format(i, provider.get_next_event()))\n i += 1\n\n # Task 2\n events = EventUser('Enter an event: ')\n while events.has_next_event():\n event = events.get_next_event()\n tokens = event.split()\n print('{} {}'.format(int(tokens[0]), tokens[1]))\n","sub_path":"July 14/event_provider.py","file_name":"event_provider.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"154138234","text":"from django.shortcuts import render\nfrom . import models\nfrom course.models import Course,UserCourse\nfrom account.models import User\nfrom django.contrib.auth.decorators import permission_required\nfrom django.contrib import messages\nfrom django.http import JsonResponse,HttpResponse,HttpResponseRedirect\nimport base64\nimport json\nfrom django.core.files.base import ContentFile\nimport boto3\nimport requests\nfrom wsgiref.util import FileWrapper\nfrom django.http import Http404, HttpResponse\nfrom django.conf import settings\n\n# Create your views here.\n# create a new group\n@permission_required('course.can_access', raise_exception = True )\ndef new(request,course_id):\n # creating\n if request.method == \"POST\":\n try:\n members = request.POST.getlist('members')\n teacher = User.objects.get(email=request.user.email) \n course = Course.objects.get(course_id=course_id)\n course_group = models.Group.objects.filter(course=course)\n group_num = 1\n if course_group.count() > 0:\n group_num = (course_group.count())+1\n\n new_group = models.Group.objects.create(\n teacher=teacher,\n course=course,\n group_num=group_num,\n )\n new_group.save()\n for member_id in members:\n new_group.member.add(int(member_id))\n\n messages.add_message(request, messages.INFO, '建立成功!')\n return HttpResponseRedirect('/group/'+str(course_id))\n except Exception as e:\n messages.add_message(request, messages.ERROR, '建立失敗!')\n\n \n\n #showing creating page\n course = Course.objects.get(course_id=course_id)\n user_courses = UserCourse.objects.filter(course = course)\n groups = models.Group.objects.all()\n all_users = User.objects.exclude(id=request.user.id )\n all_users = all_users.filter(id__in=[user_course.user.id for user_course in user_courses])\n return render(request, 'new-group.html',locals())\n\n@permission_required('course.can_access', raise_exception = True )\ndef edit(request,group_id):\n group = models.Group.objects.get(id=group_id)\n if request.method == \"POST\":\n try:\n members = request.POST.getlist('members')\n \n group.member.clear()\n for member_id in members:\n group.member.add(int(member_id))\n\n messages.add_message(request, messages.INFO, '編輯成功!')\n return HttpResponseRedirect('/group/'+str(group.course.course_id))\n except Exception as e:\n messages.add_message(request, messages.ERROR, '編輯失敗!')\n group_members = group.member.all()\n #showing edit page\n course = Course.objects.get(course_id=group.course.course_id)\n user_courses = UserCourse.objects.filter(course = course)\n other_users = User.objects.exclude(id__in=group_members).exclude(id=request.user.id ).filter(id__in=[user_course.user.id for user_course in user_courses])\n return render(request, 'edit-group.html',locals())\n\n@permission_required('course.can_access', raise_exception = True )\ndef delete(request,group_id):\n try:\n group = models.Group.objects.get(id=group_id)\n group.delete()\n messages.add_message(request, messages.INFO, '刪除成功!')\n except Exception as e:\n messages.add_message(request, messages.ERROR, '刪除失敗!')\n return HttpResponseRedirect('/group/'+str(group.course.course_id))\n\n@permission_required('course.can_access', raise_exception = True )\ndef admin(request,course_id):\n teacher = User.objects.get(email=request.user.email)\n course = Course.objects.get(course_id=course_id)\n groups = models.Group.objects.filter(course=course).order_by('-created_at')\n return render(request, 'group-admin.html',locals())\n\ndef forum(request,group_id):\n group_id=group_id\n group = models.Group.objects.get(id=group_id)\n posts = models.GroupPost.objects.filter(group=group_id)\n\n return render(request, 'group-forum.html',locals())\n\ndef mygroup(request,course_id):\n course = Course.objects.get(course_id=course_id)\n course_group = models.Group.objects.filter(course=course)\n mygroup = course_group.filter(member__email=request.user.email)\n\n return render(request, 'mygroup.html',locals())\n\ndef new_post(request,group_id):\n # creating\n if request.method == \"POST\":\n #try:\n title = request.POST['title']\n content = request.POST['text-editor']\n creator_id = request.user.id\n\n model_post = models.GroupPost.objects.create(\n title=title,\n content=content,\n creator_id=creator_id,\n group_id=group_id,\n )\n model_post.save()\n\n messages.add_message(request, messages.INFO, '新增成功!')\n return HttpResponseRedirect('/group/forum/'+str(group_id) )\n #except Exception as e:\n #messages.add_message(request, messages.ERROR, '新增失敗!')\n\n #showing creating page\n return render(request, 'edit-post.html',locals())\n\ndef edit_post(request,post_id):\n post = models.GroupPost.objects.get(id=post_id)\n # creating\n if request.method == \"POST\":\n try:\n title = request.POST['title']\n content = request.POST['text-editor']\n\n post.title = title\n post.content = content\n post.save()\n\n messages.add_message(request, messages.INFO, '編輯成功!')\n return HttpResponseRedirect('/group/post/{{ post_id }}')\n except Exception as e:\n messages.add_message(request, messages.ERROR, '編輯失敗!')\n\n #showing creating page\n return render(request, 'edit-post.html',locals())\n\ndef delete_post(request,post_id):\n try:\n post = models.GroupPost.objects.get(id=post_id)\n post.delete()\n messages.add_message(request, messages.INFO, '刪除成功!')\n except Exception as e:\n messages.add_message(request, messages.ERROR, '刪除失敗!')\n return HttpResponseRedirect('/group/forum/{{ group_id }}')\n\ndef post(request,post_id):\n post = models.GroupPost.objects.get(id=post_id)\n group_id = post.group.id\n group_num = post.group.group_num\n comments = models.GroupComment.objects.filter(post_id=post_id)\n\n return render(request, 'post.html',locals())\n\ndef comment(request):\n if request.method == 'POST':\n comment = request.POST['comment']\n post_id = request.POST['post_id']\n\n model_comment = models.GroupComment.objects.create(\n post_id=post_id,\n content=comment,\n creator=request.user,\n )\n\n model_comment.save()\n\n\n comments = models.GroupComment.objects.filter(post=post_id).order_by('-created_at').values('id', 'creator__name',\n 'content','created_at','creator__pic') \n\n data = list(comments) \n return JsonResponse(data, safe=False) \n\ndef upload_project(request):\n try:\n project = request.POST['file']\n group_id = request.POST['group_id']\n project_url = request.POST['project_url']\n\n group = models.Group.objects.get(id=group_id)\n if project != '':\n arr_json = json.loads(project)\n file_data = arr_json['data']\n file_name = arr_json['name']\n file_data = ContentFile(base64.b64decode(file_data)) \n\n group.project.save(file_name, file_data, save=True)\n group.save()\n\n group.project_url = project_url\n group.save()\n\n data = {}\n return JsonResponse(data,safe=False)\n except Exception as e:\n pass\n\ndef download_project(request):\n group_id = request.GET['id']\n group = models.Group.objects.get(id=group_id)\n\n s3= boto3.client('s3', \n aws_access_key_id=settings.AWS_ACCESS_KEY_ID, \n aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, \n region_name=settings.AWS_S3_REGION_NAME\n )\n bucket_name = settings.AWS_STORAGE_BUCKET_NAME\n url = s3.generate_presigned_url('get_object', Params = {'Bucket': bucket_name, 'Key': group.project.name}, ExpiresIn = 100)\n\n\n\n request = requests.get(url, stream=True)\n\n # Was the request OK?\n if request.status_code != requests.codes.ok:\n return HttpResponse(status=400)\n\n wrapper = FileWrapper(request.raw)\n content_type = request.headers['content-type']\n content_len = request.headers['content-length']\n\n response = HttpResponse(wrapper, content_type=content_type)\n response['Content-Length'] = content_len\n response['Content-Disposition'] = \"attachment; filename=\"+group.project.name\n return response \n","sub_path":"group/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":"12"} +{"seq_id":"132293876","text":"\nimport math\nimport numpy as np\nimport parameters as par\nfrom ExcessZ import fhigh\nfrom ExcessZ import flow\nfrom Excesspl import Rpkpcfunc\nfrom err_HFhigh import errHFhi\nfrom err_HFlow import errHFlo\nfrom galpyMWRfo import MWRfo\n\ndef calja(bdeg, sigb, ldeg, sigl, dkpc, sigd, Har): \n global excpl,exz \n b = bdeg*par.degtorad\n l = ldeg*par.degtorad\n zkpc = dkpc*math.sin(b)\n if zkpc<0.0:\n zkpcm = -zkpc\n else:\n zkpcm = zkpc\n\n\n azbchfh = fhigh(zkpc)*math.sin(b)*1.08100761142e-19 #s^-1\n azbchfl = flow(zkpc)*math.sin(b)*1.08100761142e-19 #s^-1\n errhi = errHFhi(bdeg, sigb, dkpc, sigd) #s^-1\n errlo = errHFlo(bdeg, sigb, dkpc, sigd) #s^-1\n\n ExcRforce = MWRfo(bdeg,ldeg,dkpc) #s^-1 \n\n\n if zkpcm<=1.5:\n print (\"Excess_parallel(galpy-Rforce,without BH), Excess_z_HF04fit = \", ExcRforce,\", \", azbchfl)\n excpl = ExcRforce\n exz = azbchfl\n else:\n print (\"Excess_parallel(galpy-Rforce,without BH), Excess_z_HF04fit = \", ExcRforce,\", \", azbchfh)\n excpl = ExcRforce\n exz = azbchfh\n\n return None;\n\n\ndef Explja():\n return excpl;\n\ndef Exzja():\n return exz;\n","sub_path":"modelJa.py","file_name":"modelJa.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259303463","text":"import sqlite3\n\nclass DataBase(object):\n\t\"\"\"\n\tA class to simplify database interactions\n\n\tVariables:\n\t\tdatabase_name \n\n\tMethods:\n\t\tconnect () establishes a sqlite connection to the database passed in through init\n\t\tclose () closes the connection\n\t\texecute() runs sqlite execute on the command string passed in, the tuple increases security \n\t\t by not passing in variables directly\n\t\tfetch_one_execute() runs like execute but returns a fetch one command on any select statement commands\n\t\tfetch_all_execute() runs like execute but returns a fetch all command on any select statement commands\n\n\t\"\"\"\n\n\tdef __init__(self, database_name = \"database.db\"):\n\n\t\tself.database_name = database_name\n\t\tself.connect()\n\n\tdef connect(self):\n\t\t\"\"\"\n\t\tUses sqlite to establish a connection with a database defined in the init\n\n\t\tOutput:\n\t\t\tConnection established\n\t\t\"\"\"\n\n\t\tself.connection = sqlite3.connect(self.database_name, check_same_thread = False)\n\t\tself.cursor = self.connection.cursor()\n\t\tself.connected = True\n\n\tdef close(self):\n\t\t\"\"\"\n\t\tUses sqlite to close the connection\n\n\t\tOutput:\n\t\t\tConnection closed\n\t\t\"\"\"\n\n\t\tself.connection.commit()\n\t\tself.connection.close()\n\t\tself.connected = False\n\n\n\tdef execute(self, commands, tupleParameter = ()):\n\t\t\"\"\"\n\t\tA very simple execute method that takes in a list of commands and executes \n\t\t them, the tuple is used to pass in variables\n\t\t Error handling and bad commands TBD\n\n\t\tInput:\n\t\t\tcommands [str]\n\t\t\ttupleParameter (str)\n\n\t\tOutput:\n\t\t\tExecutes on database\n\t\t\"\"\"\n\n\t\tclose = False\n\t\tif not self.connected:\n\t\t\t# Open a previously closed connection if closed\n\t\t\tself.connect()\n\t\t\t# Mark the connection to be closed once complete\n\t\t\tclose = True\n\n\t\tif type(commands) == str:\n\t\t\t# All commands are dealt with in a list\n\t\t\tcommands = [commands]\n\n\t\tfor command in commands:\n\n\t\t\tself.cursor.execute(command, tupleParameter)\n\n\t\t# Commits after all commands have been executed\n\t\tself.connection.commit()\n\n\t\tif close:\n\t\t\tself.close()\n\n\tdef fetch_one_execute(self, commands, tupleParameter = ()):\n\t\t\"\"\"\n\t\tA very simple execute method that takes in a list of commands and executes \n\t\t them, the tuple is used to pass in variables\n\t\t Error handling and bad commands TBD\n\n\t\tInput:\n\t\t\tcommands [str]\n\t\t\ttupleParameter (str)\n\n\t\tOutput:\n\t\t\tExecutes on database\n\t\t\treturn fetchone \n\t\t\"\"\"\n\n\t\tclose = False\n\t\tif not self.connected:\n\t\t\t# Open a previously closed connection\n\t\t\tself.connect()\n\t\t\t# Mark the connection to be closed once complete\n\t\t\tclose = True\n\n\t\tif type(commands) == str:\n\t\t\t# All commands are dealt with in a list\n\t\t\tcommands = [commands]\n\n\t\tfor command in commands:\n\n\t\t\tself.cursor.execute(command, tupleParameter)\n\t\t\t\n\n\t\t# Commits after all commands have been executed\n\t\tself.connection.commit()\n\n\t\tif close:\n\t\t\tself.close()\n\n\t\treturn self.cursor.fetchone()\n\n\tdef fetch_all_execute(self, commands, tupleParameter = ()):\n\t\t\"\"\"\n\t\tA very simple execute method that takes in a list of commands and executes \n\t\t them, the tuple is used to pass in variables\n\t\t Error handling and bad commands TBD\n\n\t\tInput:\n\t\t\tcommands [str]\n\t\t\ttupleParameter (str)\n\n\t\tOutput:\n\t\t\tExecutes on database\n\t\t\treturn fetchall []\n\n\n\t\tElements can be accessed in the following form\n\t\tRecipes = [dict(ID=row[0],\n\t\t\t\t\tTitle=row[1],\n\t\t\t\t\tPicture=row[2],\n\t\t\t\t\tRating=row[3]) for row in cur.fetchall()]\n\t\tGives a list element for each row where the elements are dictionaries\n\t\tand the key is ID, Title, Picture, Rating (the columns), and the values\n\t\tare the associated values in the database\n\n\t\tIf we then want to access this in the html is would look like:\n\t\t{% for recipe in Recipes %}\n\t\t\tID: {{ recipe.ID }}
    \n\t\t\tTitle: {{ recipe.Title }}
    \n\t\t\tPicture: {{ recipe.Picture }}
    \n\t\t\tRating: {{ recipe.Rating }}
    \n\t\t{% endfor %}\n\t\t\"\"\"\n\t\tclose = False\n\t\tif not self.connected:\n\t\t\t# Open a previously closed connection\n\t\t\tself.connect()\n\t\t\t# Mark the connection to be closed once complete\n\t\t\tclose = True\n\n\t\tif type(commands) == str:\n\t\t\t# All commands are dealt with in a list\n\t\t\tcommands = [commands]\n\n\t\tfor command in commands:\n\t\t\tself.cursor.execute(command, tupleParameter)\n\t\t\t\n\n\t\tself.connection.commit()\n\n\t\tif close:\n\t\t\tself.close()\n\n\t\treturn self.cursor.fetchall()","sub_path":"adventure_submit/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":4261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"92976842","text":"import torch\nimport torch.nn as nn\n\nfrom lib.utils.spatial_transforms import (\n Compose, Normalize, Scale, ToTensor)\nfrom lib.utils.temporal_transforms import LoopPadding\n\nfrom lib.utils.net_utils import adjust_learning_rate\n\nfrom lib.utils.create_video_id import get_vid_dict\nfrom lib.dataloaders.video_dataset import video_names\nfrom lib.models.model import Model\nfrom lib.utils.resize_rpn import resize_tube\n\n# torch.backends.cudnn.benchnark=True \n\n\ndef validate_model(model, val_data, val_data_loader):\n\n ###\n max_dim = 1\n\n correct = 0\n\n true_pos = torch.zeros(1).long().cuda()\n false_neg = torch.zeros(1).long().cuda()\n\n true_pos_xy = torch.zeros(1).long().cuda()\n false_neg_xy = torch.zeros(1).long().cuda()\n\n true_pos_t = torch.zeros(1).long().cuda()\n false_neg_t = torch.zeros(1).long().cuda()\n\n n_preds = torch.zeros(1).long().to(device)\n preds = torch.zeros(1).long().to(device)\n ## 2 rois : 1450\n\n for step, data in enumerate(val_data_loader):\n\n if step == 2:\n break\n \n vid_id, boxes, n_frames, n_actions = data\n \n mode = 'test'\n boxes_ = boxes.cuda()\n vid_id_ = vid_id.cuda()\n n_frames_ = n_frames.cuda()\n n_actions_ = n_actions.cuda()\n\n ## create video tube\n video_tubes = create_video_tube(boxes.type_as(clips_))\n video_tubes_r = resize_tube(video_tubes.unsqueeze(0), h_,w_,self.sample_size)\n\n tubes, bbox_pred, \\\n prob_out, rpn_loss_cls, \\\n rpn_loss_bbox, act_loss_bbox, cls_loss = model(n_devs, dataset_folder, \\\n vid_names, vid_id_, spatial_transform, \\\n temporal_transform, boxes_, \\\n mode, cls2idx, n_actions_,n_frames_)\n\n\n # _, cls = torch.max(prob_out,1)\n\n # if cls == target :\n # correct += 1\n\n print(' ------------------- ')\n print('| In {: >6} steps |'.format(step))\n print('| |')\n print('| Correct : {: >6} |'.format(correct))\n print(' ------------------- ')\n\nif __name__ == '__main__':\n \n #################################\n # UCF data inits #\n #################################\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(\"Device being used:\", device)\n\n dataset_folder = '../UCF-101-frames'\n boxes_file = '../pyannot.pkl'\n spt_path = '../UCF101_Action_detection_splits/'\n\n sample_size = 112\n sample_duration = 16 # len(images)\n\n batch_size = 1\n\n # # get mean\n mean = [112.07945832, 112.87372333, 106.90993363] # ucf-101 24 classes\n\n # generate model\n actions = ['__background__', 'Basketball','BasketballDunk','Biking','CliffDiving','CricketBowling',\n 'Diving','Fencing','FloorGymnastics','GolfSwing','HorseRiding','IceDancing',\n 'LongJump','PoleVault','RopeClimbing','SalsaSpin','SkateBoarding','Skiing',\n 'Skijet','SoccerJuggling','Surfing','TennisSwing','TrampolineJumping',\n 'VolleyballSpiking','WalkingWithDog']\n\n cls2idx = {actions[i]: i for i in range(0, len(actions))}\n\n ### get videos id\n vid2idx,vid_names = get_vid_dict(dataset_folder)\n\n spatial_transform = Compose([Scale(sample_size), # [Resize(sample_size),\n ToTensor(),\n Normalize(mean, [1, 1, 1])])\n temporal_transform = LoopPadding(sample_duration)\n\n n_classes = len(actions)\n\n\n ##########################################\n # Model Initialization #\n ##########################################\n\n model = Model(actions, sample_duration, sample_size)\n model.create_architecture()\n model.deactivate_action_net_grad()\n # if torch.cuda.device_count() > 1:\n\n # print('Using {} GPUs!'.format(torch.cuda.device_count()))\n # model = nn.DataParallel(model)\n\n model.to(device)\n\n lr = 0.1\n lr_decay_step = 5\n lr_decay_gamma = 0.1\n\n params = []\n for key, value in dict(model.named_parameters()).items():\n # print(key, value.requires_grad)\n if value.requires_grad:\n print('key :',key)\n if 'bias' in key:\n params += [{'params':[value],'lr':lr*(True + 1), \\\n 'weight_decay': False and 0.0005 or 0}]\n else:\n params += [{'params':[value],'lr':lr, 'weight_decay': 0.0005}]\n\n lr = lr * 0.1\n optimizer = torch.optim.Adam(params)\n # optimizer = optim.SGD(tcn_net.parameters(), lr = lr)\n\n #######################################\n # Train starts here #\n #######################################\n\n vid_name_loader = video_names(dataset_folder, spt_path, boxes_file, vid2idx, mode='train')\n data_loader = torch.utils.data.DataLoader(vid_name_loader, batch_size=batch_size,\n shuffle=True)\n\n # epochs = 40\n epochs = 5\n\n n_devs = torch.cuda.device_count()\n if torch.cuda.device_count() > 1:\n\n print('Using {} GPUs!'.format(torch.cuda.device_count()))\n model.act_net = nn.DataParallel(model.act_net)\n\n model.act_net = model.act_net.cuda()\n\n # if torch.cuda.device_count() > 1:\n\n # print('Using {} GPUs!'.format(torch.cuda.device_count()))\n # model.module.act_net = nn.DataParallel(model.module.act_net)\n\n # model.module.act_net = model.module.act_net.cuda()\n\n\n for ep in range(epochs):\n\n model.train()\n loss_temp = 0\n\n # start = time.time()\n if (ep +1) % (lr_decay_step ) == 0:\n print('time to reduce learning rate ')\n adjust_learning_rate(optimizer, lr_decay_gamma)\n lr *= lr_decay_gamma\n\n\n print(' ============\\n| Epoch {:0>2}/{:0>2} |\\n ============'.format(ep+1, epochs))\n for step, data in enumerate(data_loader):\n\n # if step == 2:\n # break\n print('step :',step)\n vid_id, boxes, n_frames, n_actions, h, w = data\n \n ###################################\n # Function here #\n ###################################\n\n mode = 'train'\n # boxes_ = boxes.to(device)\n vid_id_ = vid_id.to(device)\n n_frames_ = n_frames.to(device)\n n_actions_ = n_actions.to(device)\n h_ = h.to(device)\n w_ = w.to(device)\n tubes, bbox_pred, \\\n prob_out, rpn_loss_cls, \\\n rpn_loss_bbox, act_loss_bbox, cls_loss = model(n_devs, dataset_folder, \\\n vid_names, vid_id_, spatial_transform, \\\n temporal_transform, boxes, \\\n mode, cls2idx, n_actions_,n_frames_, h_, w_)\n\n loss = rpn_loss_cls.mean() + rpn_loss_bbox.mean() + act_loss_bbox.mean() + cls_loss.mean()\n\n # backw\\ard\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n loss_temp += loss.item()\n\n print('Train Epoch: {} \\tLoss: {:.6f}\\t lr : {:.6f}'.format(\n ep+1,loss_temp/step, lr))\n \n if ( ep + 1 ) % 5 == 0: # validation time\n val_name_loader = video_names(dataset_folder, spt_path, boxes_file, vid2idx, mode='test')\n val_loader = torch.utils.data.DataLoader(val_name_loader, batch_size=batch_size,\n shuffle=True)\n\n validate_model(model, val_name_loader, val_loader)\n # if ( ep + 1 ) % 5 == 0:\n torch.save(model.state_dict(), \"model.pwf\")\n # torch.save(model.state_dict(), \"model.pwf\")\n\n\n","sub_path":"train_val_code/train_ucf.py","file_name":"train_ucf.py","file_ext":"py","file_size_in_byte":7897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68734767","text":"# Convolutional Neural Network\n\n# Installing Theano\n# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git\n\n# Installing Tensorflow\n# pip install tensorflow\n\n# Installing Keras\n# pip install --upgrade keras\n\n# Part 1 - Building the CNN\n\n# Importing the Keras libraries and packages\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\n\nimport numpy as np\nimport os\nfrom keras.preprocessing import image\nimport autokeras as ak\n\n#list of training times for autokeras\nTRAINING_TIMES = [\n\t\t60 * 60,\t\t# 1 hour\n\t\t60 * 60 * 2,\t# 2 hours\n\t\t60 * 60 * 4,\t# 4 hours\n\t\t60 * 60 * 8,\t# 8 hours\n\t\t60 * 60 * 12,\t# 12 hours\n\t\t60 * 60 * 24,\t# 24 hours\n\t]\n# Initialising the CNN\nclassifier = Sequential()\n\n# Step 1 - Convolution\nclassifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))\n\n# Step 2 - Pooling\nclassifier.add(MaxPooling2D(pool_size = (2, 2)))\n\n# Adding a second convolutional layer\nclassifier.add(Conv2D(32, (3, 3), activation = 'relu'))\nclassifier.add(MaxPooling2D(pool_size = (2, 2)))\n\n# Step 3 - Flattening\nclassifier.add(Flatten())\n\n# Step 4 - Full connection\nclassifier.add(Dense(units = 128, activation = 'relu'))\nclassifier.add(Dense(units = 1, activation = 'sigmoid'))\n\n# Compiling the CNN\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Part 2 - Fitting the CNN to the images\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale = 1./255,\n shear_range = 0.2,\n zoom_range = 0.2,\n horizontal_flip = True)\n\ntest_datagen = ImageDataGenerator(rescale = 1./255)\n\ntraining_set = train_datagen.flow_from_directory('/Users/stevengong/Desktop/Deep-Learning-course/Volume 1 - Supervised Deep Learning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/dataset/training_set',\n target_size = (64, 64),\n batch_size = 32,\n class_mode = 'binary')\n\ntest_set = test_datagen.flow_from_directory('/Users/stevengong/Desktop/Deep-Learning-course/Volume 1 - Supervised Deep Learning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/dataset/test_set',\n target_size = (64, 64),\n batch_size = 32,\n class_mode = 'binary')\n\nclassifier.fit_generator(training_set,\n steps_per_epoch = 8000,\n epochs = 25,\n validation_data = test_set,\n validation_steps = 2000)\n\n\ntest_image = image.load_img('Volume 1 - Supervised Deep Learning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64,64))\ntest_image = image.img_to_array(test_image)\ntest_image = np.expand_dims(test_image, axis = 0) # this line of code transforms our 3-dimensional array into a 4 dimensional one, axis is 0 since it is in the first position, index = 0\nresult = classifier.predict(test_image)\n\ntraining_set.class_indices #this line allows us to determine if cat is 0 or 1, since the prediction gives us a binary number, not a string\n\nif result[0][0] == 1:\n prediction = 'dog'\nelse:\n prediction = 'cat'\n","sub_path":"Volume 1 - Supervised Deep Learning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"96089670","text":"from pico2d import *\nimport random\nimport time\nimport game_framework\nimport title_state\nimport Data_Manager\nimport Game_End_state\n\nBG_WIDTH, BG_HEIGHT = 1066, 600\n\nname = \"MainState\"\n\n# 프레임에 따른 속도 조절\n# 적 유닛들 , 배경에다가 적용해둠\nPIXEL_PER_METER = (10.0 / 0.3)\nRUN_SPEED_KMPH = 15.0\nRUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.0)\nRUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0)\nRUN_SPEED_PPS = (RUN_SPEED_MPS * PIXEL_PER_METER)\n\n# =================================================\n# 프레임에 따른 애니메이션 조절\n# 애니메이션 들어가 있는 모든 거에 해당\nTIME_PER_ACTION = 0.5\nACTION_PER_TIME = 1.0 / TIME_PER_ACTION\nFRAMES_PER_ACTION = 8\n\n\n# 키 중 종료 이벤트 관련\ndef handle_events():\n global mario_run, mario_jump, mario_duck, onQuit # 마리오가 달리기 시작.\n events = get_events()\n for event in events:\n if event.type == SDL_QUIT:\n onQuit = True\n game_framework.quit()\n elif event.type == SDL_KEYDOWN and event.key == SDLK_d: # 달리기\n mario_run = True # 마리오가 달린다.\n elif event.type == SDL_KEYDOWN and event.key == SDLK_w: # 점프\n if not mario_jump:\n mario_jump = True\n mario.SetJump(mario_jump)\n elif event.type == SDL_KEYDOWN and event.key == SDLK_s:\n if not mario_duck:\n mario_duck = True\n mario.SetDuking(mario_duck)\n elif event.type == SDL_KEYUP and event.key == SDLK_s:\n if mario_duck:\n mario_duck = False\n mario.SetDuking(mario_duck)\n elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE:\n onQuit = True\n game_framework.quit()\n\n\nclass Mario:\n def __init__(self):\n self.image = load_image(\"Image/mario_sheet.png\")\n self.Idle_frame = 205 # 서있는 자세\n self.Died_frame = 385 # 서있는 자세\n self.Jump_frame = 355 # 점프 자세\n self.run_frame = 295 # 뛰기시작\n self.duck_frame = 385 # 앉는 자세\n self.timer = 0\n self.check_frame = 0\n self.Mario_x = 140\n self.Mario_y = 120\n self.Mario_jump = False\n self.Mario_duck = False\n self.max_jump = False\n self.Mario_jump_speed = 160\n self.UI_start = load_font('Font/ENCR10B.TTF', 30)\n # 사운드 한번 재생을 위한 boolean 변수\n self.game_start_for_BGM = False\n self.start_jump_BGM = False\n self.start_died_BGM = False\n\n def draw_Idle(self):\n self.UI_start.draw(self.Mario_x - 50, self.Mario_y + 100, 'Press D', (255, 255, 255))\n self.image.clip_draw(self.Idle_frame, 100, 20, 35, self.Mario_x, self.Mario_y, 100, 100)\n\n def draw_Movement(self):\n global Is_Died, BGM_Sound\n if Is_Died:\n self.image.clip_draw(self.Died_frame, 150, 20, 35, self.Mario_x, self.Mario_y + 20, 120, 200)\n\n else:\n if not self.game_start_for_BGM: # 한번만 재생하기 위해\n BGM_Sound.repeat_play()\n self.game_start_for_BGM = True\n\n if self.Mario_jump: # 점프 시, 애니메이션 바꿔주기\n self.image.clip_draw(self.Jump_frame, 100, 20, 35, self.Mario_x, self.Mario_y, 100, 100)\n elif self.Mario_duck: # duck 시, 애니메이션 바꿔주기\n self.image.clip_draw(self.duck_frame, 100, 20, 35, self.Mario_x, self.Mario_y - 15, 100, 100)\n else: # 달리고 있는 애니메이션\n self.image.clip_draw(self.run_frame, 100, 20, 35, self.Mario_x, self.Mario_y, 100, 100)\n\n def Update(self):\n global Is_Died, Is_Game_End, jump_Sound, Died_Sound\n\n if self.timer < 0.1:\n self.timer += game_framework.frame_time\n else:\n self.timer = 0\n # if self.Mario_died: # 마리오가 죽었을 시\n if Is_Died:\n if self.Mario_y <= 120:\n if self.Mario_y > - 400:\n self.Mario_y -= (0.01 + RUN_SPEED_PPS) * game_framework.frame_time\n if not self.start_died_BGM:\n Died_Sound.play()\n self.start_died_BGM = True\n else:\n Is_Game_End = True\n else:\n if self.Mario_y > - 150:\n self.Mario_y -= (0.01 + RUN_SPEED_PPS) * game_framework.frame_time\n if not self.start_died_BGM:\n Died_Sound.play()\n self.start_died_BGM = True\n else:\n Is_Game_End = True\n else:\n if not self.Mario_jump:\n # 뛰는 애니메이션 부분\n if self.timer == 0:\n if self.run_frame > 235:\n self.run_frame -= int(30 + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time)\n else:\n self.run_frame = 295\n # ============================\n else:\n if self.Mario_y >= 300:\n self.max_jump = True\n\n if not self.max_jump:\n if not self.start_jump_BGM:\n jump_Sound.play()\n self.start_jump_BGM = True\n self.Mario_y += (self.Mario_jump_speed + RUN_SPEED_PPS) * game_framework.frame_time\n else:\n if self.Mario_y <= 120:\n self.max_jump = False\n self.Mario_jump = False\n self.start_jump_BGM = False\n return self.Mario_jump\n self.Mario_y -= (self.Mario_jump_speed + RUN_SPEED_PPS) * game_framework.frame_time\n\n def SetJump(self, Is_jump): # 점프 키가 눌렸는지를 받아준다. Key w\n self.Mario_jump = Is_jump\n\n def SetDuking(self, Is_duck): # Duck 키가 눌렸는지를 받아준다. Key s\n self.Mario_duck = Is_duck\n\n def get_bb(self):\n if self.Mario_duck:\n return mario.Mario_x - 20, mario.Mario_x + 40, mario.Mario_y - 50, mario.Mario_y + 20\n else:\n return mario.Mario_x - 20, mario.Mario_x + 40, mario.Mario_y - 50, mario.Mario_y + 50\n\n def set_speed(self, level):\n self.Mario_jump_speed += level * 10\n\n\nclass Ground_Enemy:\n Ground_Enemy_image = None\n check_x = None\n\n def __init__(self):\n if Ground_Enemy.Ground_Enemy_image is None:\n Ground_Enemy.Ground_Enemy_image = load_image(\"Image/enemy.png\")\n self.frame = 0\n self.moving_calcu_x = 0\n if Ground_Enemy.check_x is None:\n self.random_start_enemy_x = BG_WIDTH + 0 # 초기 시작 위치 랜덤하게 돌릴 예정\n Ground_Enemy.check_x = self.random_start_enemy_x\n else:\n self.random_start_enemy_x = Ground_Enemy.check_x + random.randint(400, 600)\n Ground_Enemy.check_x = None\n self.timer = 0\n self.enemy_x = 0\n self.enemy_y = 125\n self.bb_left_x = 0\n self.bb_right_x = 0\n self.bb_up_y = 0\n self.bb_down_y = 0\n self.speed = 1\n self.distance = 0\n\n def Enemy_Draw_movement(self): # 지상 적 유닛 ( 장애물 ) 움직임 구현\n global difficulty_level\n self.enemy_x = self.random_start_enemy_x - self.moving_calcu_x\n Ground_Enemy.Ground_Enemy_image.clip_draw(self.frame, 240, 25, 25, self.enemy_x, self.enemy_y, 100, 100)\n if not Is_Died:\n if self.enemy_x >= 0:\n self.moving_calcu_x += (self.speed + RUN_SPEED_PPS) * game_framework.frame_time + (\n difficulty_level * 0.3) # 계속 이동\n else: # 화면에 보이지 않으면\n return 1\n\n self.bb_left_x = self.enemy_x - 50\n self.bb_right_x = self.enemy_x + 10\n self.bb_down_y = self.enemy_y - 50\n self.bb_up_y = self.enemy_y + 30\n\n return 0\n\n def get_bb(self):\n return self.bb_left_x, self.bb_right_x, self.bb_down_y, self.bb_up_y\n\n def Update(self):\n if self.timer == 0:\n if self.frame == 0:\n self.frame += int(30 + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time)\n else:\n self.frame = 0\n if self.timer < 2:\n self.timer += game_framework.frame_time * 10\n else:\n self.timer = 0\n\n def set_starting_point(self, num):\n self.random_start_enemy_x = num\n\n def set_speed(self, level):\n self.speed += level\n\n\nclass Sky_Enemy:\n Sky_Enemy_image = None\n check_x = None\n\n def __init__(self):\n if Sky_Enemy.Sky_Enemy_image is None:\n Sky_Enemy.Sky_Enemy_image = load_image(\"Image/enemy.png\")\n self.frame = 90\n self.moving_calcu_x = 0\n self.enemy_x = 0\n self.enemy_y = 200\n if Sky_Enemy.check_x is None:\n self.random_start_enemy_x = BG_WIDTH + 1300 # 초기 시작 위치 랜덤하게 돌릴 예정\n Sky_Enemy.check_x = self.random_start_enemy_x\n else:\n self.random_start_enemy_x = Sky_Enemy.check_x + 400\n Sky_Enemy.check_x = None\n self.timer = 0\n self.bb_left_x = 0\n self.bb_right_x = 0\n self.bb_up_y = 0\n self.bb_down_y = 0\n self.speed = 1\n\n def Enemy_Draw_movement(self): # 공중 적 유닛 ( 장애물 ) 움직임 구현\n global difficulty_level\n self.enemy_x = self.random_start_enemy_x - self.moving_calcu_x\n Sky_Enemy.Sky_Enemy_image.clip_draw(self.frame, 240, 25, 25, self.enemy_x, self.enemy_y, 100, 100)\n if not Is_Died:\n if (self.random_start_enemy_x - self.moving_calcu_x) >= 0: # 적이 화면에 보이면\n self.moving_calcu_x += (self.speed + RUN_SPEED_PPS) * game_framework.frame_time + (\n difficulty_level * 0.3) # 계속 이동\n else: # 화면에 보이지 않으면\n return 1\n\n self.bb_left_x = self.enemy_x - 50\n self.bb_right_x = self.enemy_x + 10\n self.bb_down_y = self.enemy_y - 50\n self.bb_up_y = self.enemy_y + 30\n\n return 0\n\n def get_bb(self):\n return self.bb_left_x, self.bb_right_x, self.bb_down_y, self.bb_up_y\n\n def Update(self):\n if self.timer == 0:\n if self.frame == 90:\n self.frame += int(30 + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time)\n else:\n self.frame = 90\n if self.timer < 2:\n self.timer += game_framework.frame_time * 10\n else:\n self.timer = 0\n\n def set_starting_point(self, num):\n self.random_start_enemy_x = num\n\n def set_speed(self, level):\n self.speed += level\n\n\ndef enter():\n global G_enemys, S_enemys, mario, backgrounds, real_time, high_score, enemy_list, BGM_Sound, Level_Sound, Died_Sound, jump_Sound, level_up\n close_canvas()\n open_canvas(BG_WIDTH, BG_HEIGHT, sync=True) # 게임사이즈 재 조정때문에 넣어줌.\n\n # 객체 생성\n mario = Mario()\n\n G_enemys = [Ground_Enemy() for i in range(100)]\n S_enemys = [Sky_Enemy() for i in range(100)]\n backgrounds = [BackGround() for i in range(100)]\n\n enemy_list = G_enemys + S_enemys\n random.shuffle(enemy_list)\n\n level_up = True\n x = 0\n for enemy in enemy_list:\n enemy.set_starting_point(BG_WIDTH + x)\n x += random.randint(300, 450)\n\n bg_x = BG_WIDTH // 2\n for bg in backgrounds:\n bg.set_x(bg_x)\n bg_x += BG_WIDTH - 5\n\n # ==================================\n high_score = Data_Manager.load_data()\n real_time = get_time()\n\n # Sound 부분\n BGM_Sound = load_music('Sound/Main_BGM.mp3')\n Died_Sound = load_music('Sound/Died_BGM.mp3')\n Level_Sound = load_wav('Sound/level.wav')\n jump_Sound = load_wav('Sound/jump.wav')\n # ================== 왜 안될까 ==================\n\n BGM_Sound.set_volume(100)\n Died_Sound.set_volume(100)\n Level_Sound.set_volume(100)\n jump_Sound.set_volume(100)\n # ============================\n\n\ndef exit():\n global G_enemys, S_enemys, mario, Is_Died, first_start, timer, difficulty_level, Is_Game_End, mario_run, mario_jump, \\\n mario_duck, onQuit, BGM_Sound, Level_Sound, Died_Sound, jump_Sound, level_up, enemy_list, backgrounds, player_score, high_score, real_time\n\n\n Ground_Enemy.Ground_Enemy_image = None\n Sky_Enemy.Sky_Enemy_image = None\n BackGround.Image = None\n\n\n del mario\n for Genemy in G_enemys:\n del Genemy\n for Senemy in S_enemys:\n del Senemy\n for enemy in enemy_list:\n del enemy\n\n for back in backgrounds:\n del back\n\n # 초기 설정으로 전체 수정\n first_start = True\n timer = 0\n difficulty_level = 0\n Is_Game_End = False\n Is_Died = False\n player_score = 0\n real_time = 0\n mario_run = False\n mario_jump = False\n mario_duck = False\n\n del Level_Sound\n Level_Sound = None\n del Died_Sound\n Died_Sound = None\n del jump_Sound\n jump_Sound = None\n del level_up\n level_up = None\n # =========================\n if not onQuit: # x눌러서 그냥 끄면 창 안뜨고 바로 꺼지게 작동\n close_canvas()\n open_canvas(800, 600) # 게임사이즈 재 조정때문에 넣어줌.\n else:\n close_canvas()\n onQuit = False\n\n\ndef pause():\n pass\n\n\ndef resume():\n pass\n\n\n# 적을 20마리 이상 넘겼을 때마다 점수 level 곱해서 증가\ndef score():\n global UI_score, player_score, real_time, difficulty_level, high_score, Level_Sound, enemy_list, level_up, enemy_list\n UI_score = load_font('Font/ENCR10B.TTF', 30) # 게임 시작하면서, 스코어 ( 진행 시간 )를 표시할 UI 세팅\n\n # 스코어 표시\n if not Is_Died and mario_run:\n player_score = get_time() - real_time # 죽지 않은 상태면 스코어를 계속해서 측정\n if high_score <= player_score: # 기록 갱신 시, 기록 수정\n high_score = player_score\n\n UI_score.draw(BG_WIDTH // 2 - 500, BG_HEIGHT - 30, 'Score : %3.1f' % (player_score), (255, 255, 255))\n if len(enemy_list) % 10 == 0:\n if level_up:\n if difficulty_level < 5:\n difficulty_level += 1\n if difficulty_level is not 1:\n Level_Sound.play()\n for enemy in enemy_list:\n enemy.set_speed(difficulty_level)\n mario.set_speed(difficulty_level)\n level_up = False\n else:\n level_up = True\n\n UI_score.draw(BG_WIDTH // 2 - 100, BG_HEIGHT - 30, 'Level : %d' % difficulty_level, (255, 255, 255))\n else: # 죽게되면 스코어는 멈추게 된다.\n UI_score.draw(BG_WIDTH // 2 - 500, BG_HEIGHT - 30, 'Score : %3.1f' % player_score, (255, 255, 255))\n\n if high_score <= player_score:\n Data_Manager.save_data(player_score)\n\n # 하이스코어 관리\n UI_score.draw(BG_WIDTH // 2 + 200, BG_HEIGHT - 30, 'High Score : %3.1f' % high_score, (255, 255, 255))\n\n\ndef collide(m, e):\n Mario_bb_left, Mario_bb_right, Mario_bb_bottom, Mario_bb_top = m.get_bb()\n\n E_left, E_right, E_bottom, E_top = e.get_bb()\n\n # draw_rectangle(Mario_bb_left, Mario_bb_bottom, Mario_bb_right, Mario_bb_top)\n # draw_rectangle(E_left, E_bottom, E_right, E_top)\n\n if Mario_bb_left > E_right: return False\n if Mario_bb_right < E_left: return False\n if Mario_bb_top < E_bottom: return False\n if Mario_bb_bottom > E_top: return False\n\n return True\n\n\ndef update():\n global mario_jump, enemy_list, backgrounds, Is_Died\n\n if len(backgrounds) <= 2:\n extra = [BackGround() for i in range(100)]\n bg_x = BG_WIDTH // 2\n for bg in extra:\n bg.set_x(bg_x)\n bg_x += BG_WIDTH - 5\n backgrounds += extra\n\n if len(enemy_list) <= 1:\n enemy_list.clear()\n G_enemys = [Ground_Enemy() for i in range(100)]\n S_enemys = [Sky_Enemy() for i in range(100)]\n enemy_list = G_enemys + S_enemys\n random.shuffle(enemy_list)\n x = 0\n for enemy in enemy_list:\n enemy.set_starting_point(BG_WIDTH + x)\n x += random.randint(300, 450)\n # ===========Update 부분=========\n if mario_run:\n if not Is_Died:\n for bg in range(len(backgrounds)-1):\n if backgrounds[bg].update() == 1:\n del backgrounds[bg]\n else:\n backgrounds[bg].update()\n\n for enemy in enemy_list:\n enemy.Update()\n\n mario_jump = mario.Update()\n\n if Is_Game_End:\n game_framework.change_state(Game_End_state)\n\n\ndef draw():\n global Is_Died, Enemy_num, first_start, enemy_list, backgrounds\n # 게임 랜더링\n clear_canvas()\n # ===============================\n # ===========움직임 Draw 부분=========\n if mario_run:\n for bm in backgrounds:\n bm.draw()\n for enemy in range(len(enemy_list) - 1):\n if enemy_list[enemy].Enemy_Draw_movement() == 1:\n del enemy_list[enemy]\n else:\n enemy_list[enemy].Enemy_Draw_movement()\n\n mario.draw_Movement()\n\n if not Is_Died: # 죽으면 충돌검사를 멈춘다.\n for enemy in enemy_list:\n if not Is_Died:\n Is_Died = collide(mario, enemy)\n else:\n break\n else:\n backgrounds[0].draw()\n backgrounds[1].draw()\n mario.draw_Idle()\n # ===============================\n score()\n update_canvas()\n handle_events()\n\n\n# 완성된 함수 라인 건드릴 필요 없음.\n# 뒷 배경 이미지 계속 이동 -> 캐릭이 앞으로 가는 듯한 효과 발생\nclass BackGround:\n Image = None\n index_x = None\n\n def __init__(self):\n if BackGround.Image is None:\n BackGround.Image = load_image('Image/Background.png')\n self.x = 0\n\n def draw(self):\n BackGround.Image.draw(self.x, 300)\n\n def update(self):\n self.x -= (40 + RUN_SPEED_PPS) * game_framework.frame_time # 속도 조절\n if self.x <= -BG_WIDTH // 2 + 20:\n return 1\n else:\n return 0\n\n def set_x(self, num):\n self.x = num\n\n\n# open_canvas(BG_WIDTH, BG_HEIGHT)\n# Global 변수라인\nmario_run = False\nmario_jump = False\nmario_duck = False\nonQuit = False\nUI_score, UI_highscore, player_score = None, None, 0\nfirst_start = True\ntimer = 0\nreal_time = None\ndifficulty_level = 0\nIs_Game_End = False\nenemy_list = []\nBGM_Sound = None\nLevel_Sound = None\nDied_Sound = None\njump_Sound = None\nlevel_up = None\nhigh_score = 0\n# 이미지 Load Global 변수\n# 그냥 변수\nIs_Died = False\n","sub_path":"Script/Game_state.py","file_name":"Game_state.py","file_ext":"py","file_size_in_byte":18966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"546379003","text":"import discord\nimport json\n\nfrom discord.ext import commands\nfrom .voice import VoiceState, VoiceEntry\nfrom utils import extract, checks, role_check, search, str_split, get_lyrics\n\nif not discord.opus.is_loaded():\n discord.opus.load_opus('opus')\n\nINIT0 = '205346839082303488'\n\n\nclass Music:\n\n def __init__(self, bot):\n self.bot = bot\n self.voice_states = {}\n\n def get_voice_state(self, server):\n state = self.voice_states.get(server.id)\n if state is None:\n state = VoiceState(server, self.bot, self)\n self.voice_states[server.id] = state\n\n return state\n\n async def create_voice_client(self, channel):\n state = self.get_voice_state(channel.server)\n voice = await self.bot.join_voice_channel(channel)\n state.voice = voice\n\n def __unload(self):\n for state in self.voice_states.values():\n try:\n state.audio_player.cancel()\n if state.voice:\n self.bot.loop.create_task(state.voice.disconnect())\n except:\n pass\n\n async def summon(self, ctx):\n '''Summons the bot to join your voice channel.'''\n state = self.get_voice_state(ctx.message.server)\n if state.voice is None:\n try:\n state.voice = await self.bot.join_voice_channel(ctx.message.author.voice_channel)\n except discord.ClientException:\n await self.bot.voice_client_in(ctx.message.server).disconnect()\n state.voice = await self.bot.join_voice_channel(ctx.message.author.voice_channel)\n else:\n await state.voice.move_to(ctx.message.author.voice_channel)\n\n @commands.command(pass_context=True)\n @checks()\n async def playlistadd(self, ctx, *, server_id):\n _id = server_id if server_id is not None else ctx.message.server.id\n log = self.bot.log\n if _id not in log['playlist_servers']:\n log['playlist_servers'].append(_id)\n else:\n await self.bot.say('this server is already in the list')\n return\n with open('log.json', 'w') as file:\n json.dump(log, file, indent=4)\n await self.bot.say('adding %s to playlist servers' % (ctx.message.server.name if server_id is None else _id))\n\n @commands.command(pass_context=True, no_pm=True)\n @role_check()\n async def play(self, ctx, *, song: str):\n state = self.get_voice_state(ctx.message.server)\n shuffle = False\n in_playlist = ctx.message.server.id in self.bot.log['playlist_servers'] or ctx.message.author.id == INIT0\n if 'shuffle' in song.split()[0]:\n shuffle = True\n song = song[8:]\n if 'init0' in song:\n song = 'https://www.youtube.com/playlist?list=PLzME6COik-H9hSsEuvAf26uQAN228ESck&disable_polymer=true'\n in_playlist = True\n try:\n summoned_channel = ctx.message.author.voice_channel\n if summoned_channel is None:\n await self.bot.say('You are not in a voice channel.')\n return\n ##\n entry = await extract(song, self.bot.loop, in_playlist, shuffle, self.bot.thread_pool)\n ##\n if entry == 1:\n await self.bot.say('your server has not been registered to play playlists')\n return\n if entry == 'ew it\\'s an arab server':\n await self.bot.leave_server(ctx.message.server)\n await state.disconnect()\n return\n if entry[1]:\n await self.bot.say('some songs have been omitted due to duration, the omitted titles are')\n await self.bot.say('\\n'.join(entry[1]))\n if len(entry[0]) < 1:\n return\n except Exception as e:\n fmt = 'An error occurred while processing this request: ```py\\n{}: {}\\n```'\n await self.bot.send_message(ctx.message.channel, fmt.format(e.__class__.__name__, e))\n raise e\n\n else:\n if state.voice is None or not state.is_playing():\n try:\n await self.summon(ctx)\n except Exception as e:\n await self.bot.say('Error: {}, {}'.format(e.__class__.__name__, e))\n raise Exception\n duration = 0\n ventry = None\n for i in entry[0]:\n duration += i.duration\n ventry = VoiceEntry(ctx.message, i)\n state.songlist.add_entry(ventry)\n if len(entry[0]) > 1:\n entry_msg = 'Enqueued {0} songs with a running time of {1[0]}m {1[1]}s'.format(len(entry[0]), divmod(duration, 60))\n else:\n entry_msg = 'Enqueued '+str(ventry)\n await self.bot.say(entry_msg)\n state.start()\n\n @commands.command(pass_context=True, no_pm=True)\n @role_check()\n async def pause(self, ctx):\n state = self.get_voice_state(ctx.message.server)\n if state.is_playing():\n player = state.player\n player.pause()\n else:\n await self.bot.say('not playing anything')\n return\n await self.bot.say('paused current song')\n\n @commands.command(pass_context=True, no_pm=True)\n async def resume(self, ctx):\n state = self.get_voice_state(ctx.message.server)\n if state.is_playing():\n player = state.player\n player.resume()\n else:\n await self.bot.say('not playing anything')\n return\n await self.bot.say('resumed current song')\n\n @commands.command(pass_context=True, no_pm=True)\n @commands.cooldown(1, 5, commands.BucketType.server)\n @role_check()\n async def stop(self, ctx):\n server = ctx.message.server\n state = self.voice_states[server.id] if server.id in self.voice_states.keys() else None\n\n if state is None:\n await self.bot.say('not playing anything')\n return\n\n if state.current.requester.id == INIT0 and ctx.message.author.id != INIT0:\n await self.bot.say('nah this song is good')\n return\n\n if ctx.message.author.server_permissions.mute_members or 'himebot_music' in [i.name for i in\n ctx.message.author.roles] or ctx.message.author.id == INIT0:\n state.stop = True\n try:\n await state.disconnect()\n except:\n pass\n if server.id in self.voice_states.keys():\n self.voice_states[server.id].voice.disconnect()\n del self.voice_states[server.id]\n elif self.bot.voice_client_in(server) is not None:\n await self.bot.voice_client_in(server).disconnect()\n await self.bot.say('stopped the current player')\n else:\n await self.bot.say('not enuff perms')\n\n @commands.command(pass_context=True, no_pm=True)\n @role_check()\n async def skip(self, ctx, count=0):\n\n if count < 0:\n await self.bot.say('skip count needs to be greater than, or 0')\n return\n\n state = self.get_voice_state(ctx.message.server)\n if not state.is_playing():\n await self.bot.say('Not playing any music right now...')\n return\n\n voter = ctx.message.author\n if voter not in state.voice.channel.voice_members and voter.id != INIT0:\n await self.bot.say('you are not in the current playing voice channel')\n return\n\n if state.current.requester.id == INIT0 and voter.id != INIT0:\n await self.bot.say('nah this song is good')\n return\n\n if count not in state.skip_votes.keys():\n state.skip_votes[count] = []\n if voter.id not in state.skip_votes[count]:\n state.skip_votes[count].append(voter.id)\n total_votes = len(state.skip_votes[count])\n if count == 0:\n if voter == state.current.requester or voter.id == INIT0:\n await self.bot.say('Requester requested skipping song...')\n await state.skip(count)\n return\n elif total_votes >= state.votes_needed:\n await self.bot.say('Skip vote passed, skipping song...')\n await state.skip(count)\n else:\n await self.bot.say('Skip vote added, currently at {}/{}'.format(total_votes, state.votes_needed))\n else:\n upcoming = [i for i in state.songs[:count] if i.requester != voter]\n if len(upcoming) == 0 or voter.id == INIT0:\n await self.bot.say('Requester requested skipping over %s song(s)...' % count)\n await state.skip(count)\n return\n elif total_votes >= state.votes_needed:\n await self.bot.say('Skip vote passed, skipping over %s song(s)' % count)\n await state.skip(count)\n else:\n await self.bot.say(\n 'Skip vote added for skipping {} songs, currently at {}/{}'.format(count, total_votes,\n state.votes_needed))\n else:\n await self.bot.say('You have already voted to skip this song.')\n\n @commands.command(pass_context=True, no_pm=True)\n async def current(self, ctx):\n state = self.get_voice_state(ctx.message.server)\n if state.current is None:\n await self.bot.say('Not playing anything.')\n else:\n skip_count = len(state.skip_votes[0])\n data = state.current.embed().add_field(\n name='Skip count', value='{}/{}'.format(skip_count, state.votes_needed))\n try:\n await self.bot.say(embed=data)\n except discord.HTTPException:\n await self.bot.say('I need to be able to send embedded links')\n\n @commands.command(pass_context=True, no_pm=True)\n async def lyrics(self, ctx, *, song=None):\n if song is None:\n state = self.get_voice_state(ctx.message.server)\n if state.voice is not None:\n response = await self.bot.loop.run_in_executor(self.bot.thread_pool, search, state.current.player.title)\n else:\n await self.bot.say('not playing anything currently, please specify a song')\n return\n else:\n response = await self.bot.loop.run_in_executor(self.bot.thread_pool, search, song)\n\n if 'lyrics' not in response and type(response) is not str:\n data = discord.Embed(\n color=discord.Color(value='16727871'),\n description='Select a song from below to get the lyrics for'\n )\n count = 0\n for i in response:\n count += 1\n data.add_field(name='{}. {}'.format(count, i['primaryartist_name']), value=i['title'], inline=False)\n try:\n await self.bot.say(embed=data)\n except discord.HTTPException:\n await self.bot.say('I need to be able to send embedded links')\n user_resp = await self.bot.wait_for_message(author=ctx.message.author, channel=ctx.message.channel)\n try:\n response = response[int(user_resp.content)-1]\n lyrics = await self.bot.loop.run_in_executor(self.bot.thread_pool, get_lyrics, response['url'])\n except:\n await self.bot.say('please select a number between 1 and '+str(count))\n else:\n data = discord.Embed(\n color=discord.Color(value='16727871'),\n )\n data.set_thumbnail(url=response['thumbnail'])\n data.set_author(name='Lyrics for '+response['title'])\n data.set_footer(text='Lyrics from genius.com')\n if len(lyrics) < 1200:\n data.add_field(name='Lyrics', value=lyrics)\n else:\n lyrics = str_split(lyrics)\n try:\n await self.bot.say(embed=data)\n except discord.HTTPException:\n await self.bot.say('I need to be able to send embedded links')\n for i in lyrics:\n await self.bot.say(i.replace('`', ''))\n return\n try:\n await self.bot.say(embed=data)\n except discord.HTTPException:\n await self.bot.say('I need to be able to send embedded links')\n\n elif 'lyrics' in response:\n lyrics = response['lyrics']\n data = discord.Embed(\n color=discord.Color(value='16727871'),\n )\n data.set_thumbnail(url=response['thumbnail'])\n data.set_author(name='Lyrics for ' + response['title'])\n data.set_footer(text='Lyrics from genius.com')\n if len(lyrics) < 1200:\n data.add_field(name='Lyrics', value=lyrics)\n else:\n lyrics = str_split(lyrics)\n try:\n await self.bot.say(embed=data)\n except discord.HTTPException:\n await self.bot.say('I need to be able to send embedded links')\n for i in lyrics:\n await self.bot.say(i.replace('`', ''))\n return\n try:\n await self.bot.say(embed=data)\n except discord.HTTPException:\n await self.bot.say('I need to be able to send embedded links')\n else:\n await self.bot.say(response)\n\n @commands.command(pass_context=True, no_pm=True)\n async def songlist(self, ctx):\n state = self.get_voice_state(ctx.message.server)\n data = discord.Embed(\n color=discord.Color(value='16727871'),\n title='Songs up next'\n )\n if len(state.songs) < 1:\n await self.bot.say('nothing is in the queue currently')\n return\n for i in state.songs:\n data.add_field(name='{}. {}'.format(state.songs.index(\n i) + 1, i.player.title), value='Duration: {}'.format(i.player.fmt_duration), inline=False)\n try:\n await self.bot.say(embed=data)\n except discord.HTTPException:\n await self.bot.say('I need to be able to send embedded links')\n\n @commands.command()\n async def volume(self):\n await self.bot.say('disabled due to resource use, right click on hime in a voice channel and change her volume there instead')\n\n\ndef setup(bot):\n bot.add_cog(Music(bot))\n","sub_path":"commands/music/music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":14808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"361660270","text":"'''\n\nMeasure fake rates in trimuon events.\n\nWe measure in Z + jets\n\nThe layout of output is:\n\n region/denom_tag/var1\n region/denom_tag/var2\n region/denom_tag/num_tag/var1\n region/denom_tag/num_tag/var2\n\nAuthor: Evan K. Friis, UW\n\n'''\n\nimport array\nimport MuMuMuTree\nfrom FinalStateAnalysis.PlotTools.MegaBase import MegaBase\nimport os\nimport ROOT\n\ndef control_region(row):\n # Figure out what control region we are in.\n if row.m1RelPFIsoDB < 0.25 and row.m2RelPFIsoDB < 0.25 \\\n and row.m1_m2_Zcompat < 20 and row.type1_pfMetEt < 25\\\n and row.m3MtToMET < 20:\n return 'zmm'\n else:\n return None\n\nclass FakeRatesMMM(MegaBase):\n tree = 'mmm/final/Ntuple'\n def __init__(self, tree, outfile, **kwargs):\n super(FakeRatesMMM, self).__init__(tree, outfile, **kwargs)\n # Use the cython wrapper\n self.tree = MuMuMuTree.MuMuMuTree(tree)\n self.out = outfile\n # Histograms for each category\n self.histograms = {}\n self.is7TeV = '7TeV' in os.environ['jobid']\n\n def begin(self):\n for region in ['zmm']:\n for denom in ['pt10', 'pt20']:\n denom_key = (region, denom)\n denom_histos = {}\n self.histograms[denom_key] = denom_histos\n\n for numerator in ['pfid', 'iso03', 'pfidiso03',\n 'pfidiso02', 'pfidiso01']:\n num_key = (region, denom, numerator)\n num_histos = {}\n self.histograms[num_key] = num_histos\n\n def book_histo(name, *args, **kwargs):\n # Helper to book a histogram\n if name not in denom_histos:\n denom_histos[name] = self.book(os.path.join(\n region, denom), name, *args, **kwargs)\n num_histos[name] = self.book(os.path.join(\n region, denom, numerator), name, *args, **kwargs)\n\n #pt_bins = array.array('d', [10, 12.5, 15, 17.5, 20, 30, 50, 100])\n\n #book_histo('muonPt', 'Muon Pt', 100, 0, 100)\n book_histo('muonPt', 'Muon Pt', 16, 10, 50)\n #book_histo('muonPt', 'Muon Pt', len(pt_bins)-1, pt_bins)\n book_histo('muonJetPt', 'Muon Jet Pt', 100, 0, 100)\n book_histo('muonAbsEta', 'Muon Abs Eta', 100, -2.5, 2.5)\n #book_histo('metSignificance', 'MET sig.', 100, 0, 10)\n book_histo('m1MtToMET', 'Muon 1 MT', 100, 0, 200)\n book_histo('m3MtToMET', 'Muon 3 MT', 100, 0, 200)\n \n book_histo('m3JetptD', \"\", 200, 0, 1)\n book_histo('m3Jetmult', \"\", 50, 0, 50)\n\n book_histo('m3Jetmultvsm3JetPt', '', 200, 0, 200, 50, 0, 50,type=ROOT.TH2F)\n book_histo('m3JetptDvsm3JetPt', '' , 200, 0, 200, 200, 0, 1,type=ROOT.TH2F)\n\n\n def process(self):\n\n def preselection(row):\n if row.m1_m2_SS: return False\n if not row.doubleMuPass: return False\n if not row.m1Pt > 20: return False\n if not row.m1PFIDTight: return False\n if not row.m2Pt > 10: return False\n if not row.m3Pt > 10: return False\n if row.m1Pt < row.m2Pt: return False\n if not row.m1AbsEta < 2.4: return False\n if not row.m2AbsEta < 2.4: return False\n if not row.m2JetBtag < 3.3: return False\n if not row.m3JetBtag < 3.3: return False\n if not row.m3PixHits: return False\n if not row.m3AbsEta < 2.4: return False\n if row.muVetoPt5: return False\n if row.bjetCSVVeto: return False\n if row.tauVetoPt20: return False\n if not abs(row.m1DZ) < 0.2: return False\n if not abs(row.m2DZ) < 0.2: return False\n if not abs(row.m3DZ) < 0.2: return False\n return True\n\n def trigger_match(row):\n if row.m3DiMuonL3p5PreFiltered8 > 0 or \\\n row.m3DiMuonL3PreFiltered7 > 0 or \\\n row.m3SingleMu13L3Filtered13 > 0 or \\\n row.m3SingleMu13L3Filtered17 > 0 or \\\n row.m3DiMuonMu17Mu8DzFiltered0p2 > 0:\n return True\n\n def fill(the_histos, row):\n # Get PU weight - FIXME\n weight = 1\n the_histos['muonPt'].Fill(row.m3Pt, weight)\n the_histos['muonJetPt'].Fill(max(row.m3JetPt, row.m3Pt), weight)\n the_histos['muonAbsEta'].Fill(row.m3AbsEta, weight)\n #the_histos['metSignificance'].Fill(row.metSignificance, weight)\n the_histos['m1MtToMET'].Fill(row.m1MtToMET, weight)\n the_histos['m3MtToMET'].Fill(row.m3MtToMET, weight)\n\n the_histos['m3JetptD'].Fill(row.m3JetptD)\n the_histos['m3Jetmult'].Fill(row.m3Jetmult)\n \n the_histos['m3Jetmultvsm3JetPt'].Fill(max(row.m3JetPt, row.m3Pt),row.m3Jetmult)\n the_histos['m3JetptDvsm3JetPt'].Fill(max(row.m3JetPt, row.m3Pt),row.m3JetptD) \n\n\n histos = self.histograms\n for row in self.tree:\n if not preselection(row):\n continue\n #if not trigger_match(row):\n #continue\n region = control_region(row)\n if region is None:\n continue\n # This is a QCD or Wjets\n fill(histos[(region, 'pt10')], row)\n\n if row.m3PFIDTight:\n fill(histos[(region, 'pt10', 'pfid')], row)\n\n if row.m3RelPFIsoDB < 0.3:\n fill(histos[(region, 'pt10', 'iso03')], row)\n\n if row.m3PFIDTight and row.m3RelPFIsoDB < 0.3:\n fill(histos[(region, 'pt10', 'pfidiso03')], row)\n\n if row.m3PFIDTight and row.m3RelPFIsoDB < 0.2:\n fill(histos[(region, 'pt10', 'pfidiso02')], row)\n\n if row.m3PFIDTight and row.m3RelPFIsoDB < 0.1:\n fill(histos[(region, 'pt10', 'pfidiso01')], row)\n\n if row.m3Pt > 20:\n fill(histos[(region, 'pt20')], row)\n if row.m3PFIDTight:\n fill(histos[(region, 'pt20', 'pfid')], row)\n\n if row.m3RelPFIsoDB < 0.3:\n fill(histos[(region, 'pt20', 'iso03')], row)\n\n if row.m3PFIDTight and row.m3RelPFIsoDB < 0.3:\n fill(histos[(region, 'pt20', 'pfidiso03')], row)\n\n if row.m3PFIDTight and row.m3RelPFIsoDB < 0.2:\n fill(histos[(region, 'pt20', 'pfidiso02')], row)\n\n if row.m3PFIDTight and row.m3RelPFIsoDB < 0.1:\n fill(histos[(region, 'pt20', 'pfidiso01')], row)\n\n def finish(self):\n self.write_histos()\n","sub_path":"wh/FakeRatesMMM.py","file_name":"FakeRatesMMM.py","file_ext":"py","file_size_in_byte":6823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"407828289","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: longshuicui\n@date : 2021/03/24\n@function:\n\n给定一个二维坐标中的点的集合,points-list,\npoints-list=[(x0,y0),(x1,y1),...(xn,yn)]\n返回这个列表中斜率为k的两个点\n\n题解:该题是149题的变种题,两个点在同一条直线上,所以说y-kx的值相同,也就是说找到截距相同的两个点\n\"\"\"\n\ndef findPoints(points, k):\n counts={}\n for point in points:\n b=point[1]-k*point[0]\n if b in counts:\n return counts[b], point\n counts[b]=point\n return -1\n\n\n\npoints=[[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\nk=2\nres=findPoints(points, k)\nprint(res)","sub_path":"08.数据结构/哈希表(字典)/求斜率为k的两个点.py","file_name":"求斜率为k的两个点.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"287701499","text":"# Copyright (c) 2010 Aldo Cortesi\n# Copyright (c) 2010, 2014 dequis\n# Copyright (c) 2012 Randall Ma\n# Copyright (c) 2012-2014 Tycho Andersen\n# Copyright (c) 2012 Craig Barnes\n# Copyright (c) 2013 horsik\n# Copyright (c) 2013 Tao Sauvage\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom typing import List # noqa: F401\nfrom libqtile import bar, layout, widget, hook\nfrom libqtile.config import Click, Drag, Group, Key, Screen\nfrom libqtile.lazy import lazy\nfrom libqtile.utils import guess_terminal\n\nimport os, subprocess\n\nhome = os.path.expanduser('~')\n@hook.subscribe.startup_once\ndef autostart():\n subprocess.call([home + '/.config/qtile/autostart.sh'])\n\n\nmod = \"mod4\"\nterminal = guess_terminal()\n\nkeys = [\n Key([mod], \"h\",\n lazy.layout.left()),\n \n Key([mod], \"j\",\n lazy.layout.down()),\n \n Key([mod], \"k\",\n lazy.layout.up()),\n \n Key([mod], \"l\",\n lazy.layout.right()),\n\n \n Key([mod, \"shift\"], \"j\",\n lazy.layout.shuffle_down()),\n \n Key([mod, \"shift\"], \"k\",\n lazy.layout.shuffle_up()),\n\n \n Key([mod], \"t\",\n lazy.window.toggle_floating()),\n \n Key([mod], \"f\",\n lazy.window.toggle_fullscreen()),\n\n \n Key([mod], \"space\",\n lazy.layout.next(),\n desc=\"Switch window focus to other pane(s) of stack\"),\n\n Key([mod], \"Return\",\n lazy.spawn(terminal),\n desc=\"Launch terminal\"),\n\n Key([mod], \"Tab\",\n lazy.next_layout(),\n desc=\"Toggle between layouts\"),\n\n Key([mod], \"w\",\n lazy.window.kill(),\n desc=\"Kill focused window\"),\n\n Key([mod, \"control\"], \"r\",\n lazy.restart(),\n desc=\"Restart qtile\"),\n\n Key([mod, \"control\"], \"q\",\n lazy.shutdown(),\n desc=\"Shutdown qtile\"),\n\n Key([mod], \"r\", # lazy.spawncmd(),\n lazy.spawn(\"rofi -show drun\"),\n desc=\"Spawn a command using a prompt widget\"),\n\n\n Key([], \"XF86AudioMute\",\n lazy.spawn(\"amixer -q set Master toggle\")),\n\n Key([], \"XF86AudioLowerVolume\",\n lazy.spawn(\"amixer -c 0 sset Master 1- unmute\")),\n\n Key([], \"XF86AudioRaiseVolume\",\n lazy.spawn(\"amixer -c 0 sset Master 1+ unmute\")),\n\n Key([], \"XF86MonBrightnessUp\",\n lazy.spawn(\"brightnessctl s +5%\")),\n\n Key([], \"XF86MonBrightnessDown\",\n lazy.spawn(\"brightnessctl s 5%-\")),\n\n Key([], \"Print\",\n lazy.spawn(\"scrot \"+home+\"/Pictures/'shot_%Y_%m_%d_%H_%M_%S.png'\"),\n lazy.spawn(\"notify-send SCREEN_SHOT\")),\n\n\n ## MONAD LAYOUT\n Key([mod, \"shift\"], \"space\",\n lazy.layout.flip()),\n \n Key([mod], \"i\",\n lazy.layout.grow()),\n \n Key([mod], \"d\",\n lazy.layout.shrink()),\n \n Key([mod], \"m\",\n lazy.layout.maximize()),\n \n Key([mod], \"n\",\n lazy.layout.normalize()),\n\n \n ## TILE LAYOUT\n Key([mod, \"shift\"], \"h\",\n lazy.layout.decrease_ratio()),\n \n Key([mod, \"shift\"], \"l\",\n lazy.layout.increase_ratio()),\n \n Key([mod], \"equal\",\n lazy.layout.increase_nmaster()),\n \n Key([mod], \"minus\",\n lazy.layout.decrease_nmaster()),\n]\n\ngroups = [Group(i) for i in \"123456789\"]\n\nfor i in groups:\n keys.extend([\n Key([mod], i.name,\n lazy.group[i.name].toscreen(),\n desc=\"Switch to group {}\".format(i.name)),\n\n Key([mod, \"shift\"], i.name,\n lazy.window.togroup(i.name, switch_group=True),\n desc=\"Switch to & move focused window to group {}\".format(i.name)),\n ])\n\n\nkwargs = {\n \"margin\": 5\n}\n\nlayouts = [\n layout.Tile(shift_windows=True,\n ratio=0.51,\n **kwargs),\n layout.MonadWide(**kwargs),\n layout.Max(),\n # layout.MonadTall(),\n # layout.Stack(),\n # layout.Bsp(),\n # layout.Columns(),\n # layout.Matrix(),\n # layout.RatioTile(),\n # layout.TreeTab(),\n # layout.VerticalTile(),\n # layout.Zoomy(),\n]\n\nwidget_defaults = dict(\n font='sans',\n fontsize=15,\n padding=3,\n)\nextension_defaults = widget_defaults.copy()\n\nscreens = [\n Screen(\n top=bar.Bar(\n [\n widget.CurrentLayoutIcon(),\n widget.CurrentLayout(),\n widget.GroupBox(),\n widget.Prompt(),\n widget.WindowName(),\n widget.Clipboard(\n fmt='  {} ',\n ),\n widget.Cmus(),\n widget.Systray(),\n widget.CapsNumLockIndicator(),\n widget.Volume(\n fmt='  {} ',\n ),\n #widget.Wlan( # requires iwlib\n # interface='wlp4s0',\n # format='{essid}',\n # fmt='  {} ',\n #),\n widget.Battery(\n charge_char=' ',\n discharge_char='',\n format='{char}{percent:2.0%}',\n fmt='  {} ',\n ),\n widget.ThermalSensor(\n fmt='  {} ',\n update_interval=10,\n ),\n widget.Clock(\n format='%a %I:%M %p ',\n fmt='  {} ',\n update_interval=10,\n ),\n #widget.Wallpaper(\n # directory='/usr/share/backgrounds/',\n # random_selection=True,\n # fmt='  ',\n #),\n widget.QuickExit(\n countdown_start=1,\n fmt='  ',\n ),\n\n ],\n 30,\n ),\n ),\n]\n\n# Drag floating layouts.\nmouse = [\n Drag([mod], \"Button1\",\n lazy.window.set_position_floating(),\n start=lazy.window.get_position()),\n \n Drag([mod], \"Button3\",\n lazy.window.set_size_floating(),\n start=lazy.window.get_size()),\n\n Click([mod], \"Button2\",\n lazy.window.bring_to_front())\n]\n\ndgroups_key_binder = None\ndgroups_app_rules = [] # type: List\nfollow_mouse_focus = False\nbring_front_click = False\ncursor_warp = False\nfloating_layout = layout.Floating(float_rules=[\n {'wmclass': 'confirm'},\n {'wmclass': 'dialog'},\n {'wmclass': 'download'},\n {'wmclass': 'error'},\n {'wmclass': 'file_progress'},\n {'wmclass': 'notification'},\n {'wmclass': 'splash'},\n {'wmclass': 'toolbar'},\n {'wmclass': 'confirmreset'}, # gitk\n {'wmclass': 'makebranch'}, # gitk\n {'wmclass': 'maketag'}, # gitk\n {'wname': 'branchdialog'}, # gitk\n {'wname': 'pinentry'}, # GPG key password entry\n {'wmclass': 'ssh-askpass'}, # ssh-askpass\n])\nauto_fullscreen = True\nfocus_on_window_activation = \"smart\"\n\nwmname = \"LG3D\"\n","sub_path":"qtile/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56423375","text":"# -*- coding: utf-8 -*-\nfrom twisted.test import proto_helpers\nfrom twisted.internet import reactor\nfrom twisted.internet.defer import (\n inlineCallbacks, gatherResults, Deferred, returnValue, succeed)\nfrom twisted.internet.error import ConnectionDone\nfrom twisted.internet.task import Clock\n\n\nfrom vumi.tests.helpers import VumiTestCase, PersistenceHelper\nfrom vumi.transports.smpp.smpp_transport import SmppTransceiverTransport\nfrom vumi.transports.smpp.protocol import (\n EsmeTransceiver, EsmeTransceiverFactory,\n EsmeTransmitterFactory, EsmeReceiverFactory)\nfrom vumi.transports.smpp.processors import DeliverShortMessageProcessor\nfrom vumi.transports.smpp.pdu_utils import (\n seq_no, command_status, command_id, chop_pdu_stream, short_message)\nfrom vumi.transports.smpp.smpp_utils import unpacked_pdu_opts\nfrom vumi.transports.smpp.sequence import RedisSequence\nfrom vumi.transports.tests.helpers import TransportHelper\n\nfrom smpp.pdu import unpack_pdu\nfrom smpp.pdu_builder import (\n Unbind, UnbindResp,\n BindTransceiver, BindTransceiverResp,\n BindTransmitter, BindTransmitterResp,\n BindReceiver, BindReceiverResp,\n SubmitSMResp,\n DeliverSM,\n EnquireLink, EnquireLinkResp)\n\n\ndef connect_transport(protocol, system_id='', password='', system_type=''):\n transport = proto_helpers.StringTransport()\n protocol.makeConnection(transport)\n d = protocol.bind(system_id=system_id, password=password,\n system_type=system_type)\n d.addCallback(lambda _: transport)\n return d\n\n\n@inlineCallbacks\ndef bind_protocol(transport, protocol, clear=True, bind_pdu=None):\n if bind_pdu is None:\n [bind_pdu] = yield wait_for_pdus(transport, 1)\n resp_pdu_class = {\n BindTransceiver: BindTransceiverResp,\n BindReceiver: BindReceiverResp,\n BindTransmitter: BindTransmitterResp,\n }.get(protocol.bind_pdu)\n protocol.dataReceived(\n resp_pdu_class(seq_no(bind_pdu)).get_bin())\n [enquire_link] = yield wait_for_pdus(transport, 1)\n protocol.dataReceived(\n EnquireLinkResp(seq_no(enquire_link)).get_bin())\n if clear:\n transport.clear()\n returnValue(bind_pdu)\n\n\ndef wait_for_pdus(transport, count):\n d = Deferred()\n\n def cb(pdus):\n data_stream = transport.value()\n pdu_found = chop_pdu_stream(data_stream)\n if pdu_found is not None:\n pdu_data, remainder = pdu_found\n pdu = unpack_pdu(pdu_data)\n pdus.append(pdu)\n transport.clear()\n transport.write(remainder)\n\n if len(pdus) == count:\n d.callback(pdus)\n else:\n reactor.callLater(0, cb, pdus)\n\n cb([])\n\n return d\n\n\nclass ForwardableRedisSequence(RedisSequence):\n\n def advance(self, seq_nr):\n d = self.redis.set('smpp_last_sequence_number', seq_nr)\n d.addCallback(lambda _: seq_nr)\n return d\n\n\nclass DummySmppTransport(SmppTransceiverTransport):\n\n sequence_class = ForwardableRedisSequence\n\n\nclass EsmeTestCase(VumiTestCase):\n\n @inlineCallbacks\n def setUp(self):\n self.tx_helper = self.add_helper(TransportHelper(DummySmppTransport))\n self.persistence_helper = self.add_helper(PersistenceHelper())\n self.redis = yield self.persistence_helper.get_redis_manager()\n self.clock = Clock()\n self.patch(EsmeTransceiver, 'clock', self.clock)\n\n @inlineCallbacks\n def get_protocol(self, config={},\n deliver_sm_processor=None, dr_processor=None,\n factory_class=None):\n\n factory_class = factory_class or EsmeTransceiverFactory\n\n default_config = {\n 'transport_name': 'sphex_transport',\n 'twisted_endpoint': 'tcp:host=127.0.0.1:port=0',\n 'system_id': 'system_id',\n 'password': 'password',\n 'smpp_bind_timeout': 30,\n }\n\n if deliver_sm_processor:\n default_config['deliver_short_message_processor'] = (\n deliver_sm_processor)\n\n if dr_processor:\n default_config['delivery_report_processor'] = (\n dr_processor)\n\n default_config.update(config)\n\n smpp_transport = yield self.tx_helper.get_transport(default_config)\n\n factory = factory_class(smpp_transport)\n proto = factory.buildProtocol(('127.0.0.1', 0))\n self.add_cleanup(proto.connectionLost, reason=ConnectionDone)\n returnValue(proto)\n\n def assertCommand(self, pdu, cmd_id, sequence_number=None,\n status=None, params={}):\n self.assertEqual(command_id(pdu), cmd_id)\n if sequence_number is not None:\n self.assertEqual(seq_no(pdu), sequence_number)\n if status is not None:\n self.assertEqual(command_status(pdu), status)\n\n pdu_params = {}\n if params:\n if 'body' not in pdu:\n raise Exception('Body does not have parameters.')\n\n mandatory_parameters = pdu['body']['mandatory_parameters']\n for key in params:\n if key in mandatory_parameters:\n pdu_params[key] = mandatory_parameters[key]\n\n self.assertEqual(params, pdu_params)\n\n @inlineCallbacks\n def setup_bind(self, config={}, clear=True, factory_class=None):\n protocol = yield self.get_protocol(config, factory_class=factory_class)\n transport = yield connect_transport(protocol)\n yield bind_protocol(transport, protocol, clear=clear)\n returnValue((transport, protocol))\n\n def lookup_message_ids(self, protocol, seq_nums):\n message_stash = protocol.vumi_transport.message_stash\n lookup_func = message_stash.get_sequence_number_message_id\n return gatherResults([lookup_func(seq_num) for seq_num in seq_nums])\n\n @inlineCallbacks\n def test_on_connection_made(self):\n protocol = yield self.get_protocol()\n self.assertEqual(protocol.state, EsmeTransceiver.CLOSED_STATE)\n transport = yield connect_transport(\n protocol, system_id='system_id', password='password')\n self.assertEqual(protocol.state, EsmeTransceiver.OPEN_STATE)\n [bind_pdu] = yield wait_for_pdus(transport, 1)\n self.assertCommand(\n bind_pdu,\n 'bind_transceiver',\n sequence_number=1,\n params={\n 'system_id': 'system_id',\n 'password': 'password',\n })\n\n @inlineCallbacks\n def test_drop_link(self):\n protocol = yield self.get_protocol()\n transport = yield connect_transport(protocol)\n [bind_pdu] = yield wait_for_pdus(transport, 1)\n self.assertCommand(bind_pdu, 'bind_transceiver')\n self.assertFalse(protocol.is_bound())\n self.assertEqual(protocol.state, EsmeTransceiver.OPEN_STATE)\n self.assertFalse(transport.disconnecting)\n self.clock.advance(protocol.config.smpp_bind_timeout + 1)\n [unbind_pdu] = yield wait_for_pdus(transport, 1)\n self.assertCommand(unbind_pdu, 'unbind')\n unbind_resp_pdu = UnbindResp(sequence_number=seq_no(unbind_pdu))\n yield protocol.on_pdu(unpack_pdu(unbind_resp_pdu.get_bin()))\n self.assertTrue(transport.disconnecting)\n\n @inlineCallbacks\n def test_on_smpp_bind(self):\n protocol = yield self.get_protocol()\n transport = yield connect_transport(protocol)\n yield bind_protocol(transport, protocol)\n self.assertEqual(protocol.state, EsmeTransceiver.BOUND_STATE_TRX)\n self.assertTrue(protocol.is_bound())\n self.assertTrue(protocol.enquire_link_call.running)\n\n @inlineCallbacks\n def test_handle_unbind(self):\n transport, protocol = yield self.setup_bind()\n protocol.dataReceived(Unbind(sequence_number=0).get_bin())\n [pdu] = yield wait_for_pdus(transport, 1)\n self.assertCommand(pdu, 'unbind_resp',\n sequence_number=0, status='ESME_ROK')\n\n @inlineCallbacks\n def test_on_submit_sm_resp(self):\n calls = []\n self.patch(EsmeTransceiver, 'on_submit_sm_resp',\n lambda p, *a: calls.append(a))\n transport, protocol = yield self.setup_bind()\n pdu = SubmitSMResp(sequence_number=0, message_id='foo')\n protocol.dataReceived(pdu.get_bin())\n self.assertEqual(calls, [(0, 'foo', 'ESME_ROK')])\n\n @inlineCallbacks\n def test_deliver_sm(self):\n calls = []\n self.patch(EsmeTransceiver, 'handle_deliver_sm',\n lambda p, pdu: succeed(calls.append(pdu)))\n transport, protocol = yield self.setup_bind()\n pdu = DeliverSM(\n sequence_number=0, message_id='foo', short_message='bar')\n protocol.dataReceived(pdu.get_bin())\n [deliver_sm] = calls\n self.assertCommand(deliver_sm, 'deliver_sm', sequence_number=0)\n\n @inlineCallbacks\n def test_deliver_sm_fail(self):\n transport, protocol = yield self.setup_bind()\n pdu = DeliverSM(\n sequence_number=0, message_id='foo', data_coding=4,\n short_message='string with unknown data coding')\n protocol.dataReceived(pdu.get_bin())\n [deliver_sm_resp] = yield wait_for_pdus(transport, 1)\n self.assertCommand(\n deliver_sm_resp, 'deliver_sm_resp', sequence_number=0,\n status='ESME_RDELIVERYFAILURE')\n\n @inlineCallbacks\n def test_deliver_sm_fail_with_custom_error(self):\n transport, protocol = yield self.setup_bind(config={\n \"deliver_sm_decoding_error\": \"ESME_RSYSERR\"\n })\n pdu = DeliverSM(\n sequence_number=0, message_id='foo', data_coding=4,\n short_message='string with unknown data coding')\n protocol.dataReceived(pdu.get_bin())\n [deliver_sm_resp] = yield wait_for_pdus(transport, 1)\n self.assertCommand(\n deliver_sm_resp, 'deliver_sm_resp', sequence_number=0,\n status='ESME_RSYSERR')\n\n @inlineCallbacks\n def test_on_enquire_link(self):\n transport, protocol = yield self.setup_bind()\n pdu = EnquireLink(sequence_number=0)\n protocol.dataReceived(pdu.get_bin())\n [enquire_link_resp] = yield wait_for_pdus(transport, 1)\n self.assertCommand(\n enquire_link_resp, 'enquire_link_resp', sequence_number=0,\n status='ESME_ROK')\n\n @inlineCallbacks\n def test_on_enquire_link_resp(self):\n calls = []\n self.patch(EsmeTransceiver, 'handle_enquire_link_resp',\n lambda p, pdu: calls.append(pdu))\n transport, protocol = yield self.setup_bind()\n [pdu] = calls\n # bind_transceiver is sequence_number 1\n self.assertEqual(seq_no(pdu), 2)\n self.assertEqual(command_id(pdu), 'enquire_link_resp')\n\n @inlineCallbacks\n def test_enquire_link_no_response(self):\n transport, protocol = yield self.setup_bind(clear=False)\n protocol.clock.advance(protocol.idle_timeout)\n [unbind_pdu] = yield wait_for_pdus(transport, 1)\n self.assertCommand(unbind_pdu, 'unbind')\n self.clock.advance(protocol.unbind_timeout)\n self.assertTrue(transport.disconnecting)\n\n @inlineCallbacks\n def test_enquire_link_looping(self):\n transport, protocol = yield self.setup_bind(clear=False)\n enquire_link_resp = EnquireLinkResp(1)\n\n protocol.clock.advance(protocol.idle_timeout - 1)\n protocol.dataReceived(enquire_link_resp.get_bin())\n\n protocol.clock.advance(protocol.idle_timeout - 1)\n self.assertFalse(transport.disconnecting)\n protocol.clock.advance(1)\n\n [unbind_pdu] = yield wait_for_pdus(transport, 1)\n self.assertCommand(unbind_pdu, 'unbind')\n unbind_resp_pdu = UnbindResp(sequence_number=seq_no(unbind_pdu))\n yield protocol.on_pdu(unpack_pdu(unbind_resp_pdu.get_bin()))\n self.assertTrue(transport.disconnecting)\n\n @inlineCallbacks\n def test_submit_sm(self):\n transport, protocol = yield self.setup_bind()\n seq_nums = yield protocol.submit_sm(\n 'abc123', 'dest_addr', short_message='foo')\n [submit_sm] = yield wait_for_pdus(transport, 1)\n self.assertCommand(submit_sm, 'submit_sm', params={\n 'short_message': 'foo',\n })\n stored_ids = yield self.lookup_message_ids(protocol, seq_nums)\n self.assertEqual(['abc123'], stored_ids)\n\n @inlineCallbacks\n def test_submit_sm_configured_parameters(self):\n transport, protocol = yield self.setup_bind({\n 'service_type': 'stype',\n 'source_addr_ton': 2,\n 'source_addr_npi': 2,\n 'dest_addr_ton': 2,\n 'dest_addr_npi': 2,\n 'registered_delivery': 0,\n })\n seq_nums = yield protocol.submit_sm(\n 'abc123', 'dest_addr', short_message='foo')\n [submit_sm] = yield wait_for_pdus(transport, 1)\n self.assertCommand(submit_sm, 'submit_sm', params={\n 'short_message': 'foo',\n 'service_type': 'stype',\n 'source_addr_ton': 'national', # replaced by unpack_pdu()\n 'source_addr_npi': 2,\n 'dest_addr_ton': 'national', # replaced by unpack_pdu()\n 'dest_addr_npi': 2,\n 'registered_delivery': 0,\n })\n stored_ids = yield self.lookup_message_ids(protocol, seq_nums)\n self.assertEqual(['abc123'], stored_ids)\n\n @inlineCallbacks\n def test_submit_sm_long(self):\n transport, protocol = yield self.setup_bind()\n long_message = 'This is a long message.' * 20\n seq_nums = yield protocol.submit_sm_long(\n 'abc123', 'dest_addr', long_message)\n [submit_sm] = yield wait_for_pdus(transport, 1)\n pdu_opts = unpacked_pdu_opts(submit_sm)\n\n self.assertEqual('submit_sm', submit_sm['header']['command_id'])\n self.assertEqual(\n None, submit_sm['body']['mandatory_parameters']['short_message'])\n self.assertEqual(''.join('%02x' % ord(c) for c in long_message),\n pdu_opts['message_payload'])\n stored_ids = yield self.lookup_message_ids(protocol, seq_nums)\n self.assertEqual(['abc123'], stored_ids)\n\n @inlineCallbacks\n def test_submit_sm_multipart_udh(self):\n transport, protocol = yield self.setup_bind(config={\n 'send_multipart_udh': True,\n })\n long_message = 'This is a long message.' * 20\n seq_numbers = yield protocol.submit_csm_udh(\n 'abc123', 'dest_addr', short_message=long_message)\n pdus = yield wait_for_pdus(transport, 4)\n self.assertEqual(len(seq_numbers), 4)\n\n msg_parts = []\n msg_refs = []\n\n for i, sm in enumerate(pdus):\n mandatory_parameters = sm['body']['mandatory_parameters']\n self.assertEqual('submit_sm', sm['header']['command_id'])\n msg = mandatory_parameters['short_message']\n\n udh_hlen, udh_tag, udh_len, udh_ref, udh_tot, udh_seq = [\n ord(octet) for octet in msg[:6]]\n self.assertEqual(5, udh_hlen)\n self.assertEqual(0, udh_tag)\n self.assertEqual(3, udh_len)\n msg_refs.append(udh_ref)\n self.assertEqual(4, udh_tot)\n self.assertEqual(i + 1, udh_seq)\n self.assertTrue(len(msg) <= 136)\n msg_parts.append(msg[6:])\n self.assertEqual(0x40, mandatory_parameters['esm_class'])\n\n self.assertEqual(long_message, ''.join(msg_parts))\n self.assertEqual(1, len(set(msg_refs)))\n\n stored_ids = yield self.lookup_message_ids(protocol, seq_numbers)\n self.assertEqual(['abc123'] * len(seq_numbers), stored_ids)\n\n @inlineCallbacks\n def test_udh_ref_num_limit(self):\n transport, protocol = yield self.setup_bind(config={\n 'send_multipart_udh': True,\n })\n\n # forward until we go past 0xFF\n yield protocol.sequence_generator.advance(0xFF)\n\n long_message = 'This is a long message.' * 20\n seq_numbers = yield protocol.submit_csm_udh(\n 'abc123', 'dest_addr', short_message=long_message)\n pdus = yield wait_for_pdus(transport, 4)\n\n self.assertEqual(len(seq_numbers), 4)\n self.assertTrue(all([sn > 0xFF for sn in seq_numbers]))\n\n msg_refs = []\n\n for pdu in pdus:\n msg = short_message(pdu)\n _, _, _, udh_ref, _, _ = [ord(octet) for octet in msg[:6]]\n msg_refs.append(udh_ref)\n\n self.assertEqual(1, len(set(msg_refs)))\n self.assertTrue(all([msg_ref < 0xFF for msg_ref in msg_refs]))\n\n @inlineCallbacks\n def test_submit_sm_multipart_sar(self):\n transport, protocol = yield self.setup_bind(config={\n 'send_multipart_sar': True,\n })\n long_message = 'This is a long message.' * 20\n seq_nums = yield protocol.submit_csm_sar(\n 'abc123', 'dest_addr', short_message=long_message)\n pdus = yield wait_for_pdus(transport, 4)\n # seq no 1 == bind_transceiver, 2 == enquire_link, 3 == sar_msg_ref_num\n self.assertEqual([4, 5, 6, 7], seq_nums)\n msg_parts = []\n msg_refs = []\n\n for i, sm in enumerate(pdus):\n pdu_opts = unpacked_pdu_opts(sm)\n mandatory_parameters = sm['body']['mandatory_parameters']\n\n self.assertEqual('submit_sm', sm['header']['command_id'])\n msg_parts.append(mandatory_parameters['short_message'])\n self.assertTrue(len(mandatory_parameters['short_message']) <= 130)\n msg_refs.append(pdu_opts['sar_msg_ref_num'])\n self.assertEqual(i + 1, pdu_opts['sar_segment_seqnum'])\n self.assertEqual(4, pdu_opts['sar_total_segments'])\n\n self.assertEqual(long_message, ''.join(msg_parts))\n self.assertEqual([3, 3, 3, 3], msg_refs)\n\n stored_ids = yield self.lookup_message_ids(protocol, seq_nums)\n self.assertEqual(['abc123'] * len(seq_nums), stored_ids)\n\n @inlineCallbacks\n def test_sar_ref_num_limit(self):\n transport, protocol = yield self.setup_bind(config={\n 'send_multipart_udh': True,\n })\n\n # forward until we go past 0xFFFF\n yield protocol.sequence_generator.advance(0xFFFF)\n\n long_message = 'This is a long message.' * 20\n seq_numbers = yield protocol.submit_csm_udh(\n 'abc123', 'dest_addr', short_message=long_message)\n pdus = yield wait_for_pdus(transport, 4)\n\n self.assertEqual(len(seq_numbers), 4)\n self.assertTrue(all([sn > 0xFF for sn in seq_numbers]))\n\n msg_refs = []\n\n for pdu in pdus:\n msg = short_message(pdu)\n _, _, _, udh_ref, _, _ = [ord(octet) for octet in msg[:6]]\n msg_refs.append(udh_ref)\n\n self.assertEqual(1, len(set(msg_refs)))\n self.assertTrue(all([msg_ref < 0xFFFF for msg_ref in msg_refs]))\n\n @inlineCallbacks\n def test_query_sm(self):\n transport, protocol = yield self.setup_bind()\n yield protocol.query_sm('foo', source_addr='bar')\n [query_sm] = yield wait_for_pdus(transport, 1)\n self.assertCommand(query_sm, 'query_sm', params={\n 'message_id': 'foo',\n 'source_addr': 'bar',\n })\n\n @inlineCallbacks\n def test_unbind(self):\n calls = []\n self.patch(EsmeTransceiver, 'handle_unbind_resp',\n lambda p, pdu: calls.append(pdu))\n transport, protocol = yield self.setup_bind()\n yield protocol.unbind()\n [unbind_pdu] = yield wait_for_pdus(transport, 1)\n protocol.dataReceived(UnbindResp(seq_no(unbind_pdu)).get_bin())\n [unbind_resp_pdu] = calls\n self.assertEqual(seq_no(unbind_resp_pdu), seq_no(unbind_pdu))\n\n @inlineCallbacks\n def test_bind_transmitter(self):\n transport, protocol = yield self.setup_bind(\n factory_class=EsmeTransmitterFactory)\n self.assertTrue(protocol.is_bound())\n self.assertEqual(protocol.state, protocol.BOUND_STATE_TX)\n\n @inlineCallbacks\n def test_bind_receiver(self):\n transport, protocol = yield self.setup_bind(\n factory_class=EsmeReceiverFactory)\n self.assertTrue(protocol.is_bound())\n self.assertEqual(protocol.state, protocol.BOUND_STATE_RX)\n\n @inlineCallbacks\n def test_partial_pdu_data_received(self):\n calls = []\n self.patch(EsmeTransceiver, 'handle_deliver_sm',\n lambda p, pdu: calls.append(pdu))\n transport, protocol = yield self.setup_bind()\n deliver_sm = DeliverSM(sequence_number=1, short_message='foo')\n pdu = deliver_sm.get_bin()\n half = len(pdu) / 2\n pdu_part1, pdu_part2 = pdu[:half], pdu[half:]\n protocol.dataReceived(pdu_part1)\n self.assertEqual([], calls)\n protocol.dataReceived(pdu_part2)\n [handled_pdu] = calls\n self.assertEqual(command_id(handled_pdu), 'deliver_sm')\n self.assertEqual(seq_no(handled_pdu), 1)\n self.assertEqual(short_message(handled_pdu), 'foo')\n\n @inlineCallbacks\n def test_unsupported_command_id(self):\n calls = []\n self.patch(EsmeTransceiver, 'on_unsupported_command_id',\n lambda p, pdu: calls.append(pdu))\n invalid_pdu = {\n 'header': {\n 'command_id': 'foo',\n }\n }\n transport, protocol = yield self.setup_bind()\n protocol.on_pdu(invalid_pdu)\n self.assertEqual(calls, [invalid_pdu])\n\n @inlineCallbacks\n def test_csm_split_message(self):\n protocol = yield self.get_protocol()\n\n def split(msg):\n return protocol.csm_split_message(msg.encode('utf-8'))\n\n # these are fine because they're in the 7-bit character set\n self.assertEqual(1, len(split(u'&' * 140)))\n self.assertEqual(1, len(split(u'&' * 160)))\n # ± is not in the 7-bit character set so it should utf-8 encode it\n # which bumps it over the 140 bytes\n self.assertEqual(2, len(split(u'±' + u'1' * 139)))\n","sub_path":"vumi/transports/smpp/tests/test_protocol.py","file_name":"test_protocol.py","file_ext":"py","file_size_in_byte":22045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"373753612","text":"#!/usr/bin/python\n\nfrom markov import MarkovModel\nfrom driving_q_learner import DrivingLearner\nfrom datastore import DataStore\nfrom RL_2_0 import FeatureLearner\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport random\nimport re\n\n\nindex_dict = {\"L\":0,\"F\":1,\"R\":2} \n\n\ndef advanceAll(source_list):\n \"\"\"Advances all entries in source_list at least once and then ensures\n that all of them have jumped. Returns the new indices for all the sources.\n If None is in the index list then one of the sources has reached the end of their datasets\"\"\"\n index_list = []\n # Advance all sources once\n for source in source_list:\n source.advance()\n\n #This is done to ensure that one data doesn't make a large timestep\n # While the others make a smaller timestep, leading to desynchronised data\n cur_time = max(source.time for source in source_list)\n for source in source_list:\n while source.timesource.time:\n cur_time = source.time\n cur_source = source\n cur_source.advance()\n index_list = [source.index for source in source_list]\n return index_list\n\ndef granularise(dataset,granularity=.5):\n \"\"\"Given a dataset with time as its first element binds dataset time component to \n nearest time step and reduces dataset to only stores one entry per time step\n at granularity specified. e.g. if granularity=.5 all entries time component is\n brought to the nearest .5 second and if multiple entries have same time value\n only first entry is kept\"\"\"\n last,ind = 0,1\n #Bind time to nearest granular time step\n for i in range(len(dataset)):\n if dataset[i][0]%granularity0 and entry-time_list[i-1]>.5:\n time_slots.append((begin,time_list[i-1]))\n begin = entry\n if i==len(time_list)-1:\n time_slots.append((begin,entry))\n\n return time_slots\n\n\ndef getData(dataset,start_time,end_time):\n i = 0\n while i0 :\n learner.learn(true_action_label)\n #learner.callback(num_ep%10!=0,num_ep,i,true_to_state)\n if learner_action != true_action_label: \n count_wrong += 1\n \n cross_section[index_dict[learner_action]][index_dict[true_to_state[-1]]] += 1\n explosion_test = learner.explosionCheck()\n if explosion_test: break\n\n if num_ep%10 == 0 or explosion_test:\n print(\"CROSS SECTION: {}\".format(num_ep))\n for entry in cross_section:\n print(entry)\n learner.featureCheck() \n print(\"\")\n if explosion_test:\n print(\"{}|{}: Program ended due to Explosion at {}\".format(num_ep,i,explosion_test))\n print(learner.weights)\n exit(-1) \n \n\n\n#Static Variables for simulation\nlook_back = 5\nnum_episodes = 200\nnum_iterations = 7200 #3600 half seconds = 30 minutes\n\n#Crawls the directory tree and finds all the files with annotated data\nsources = getDirectories()\n\n#Creates a list of lists. Each sub-list is a run in a single direction along\n# the motorway as well as the annotation associated with that run\n# One of the runs was broken up by a data input break somewhere along the way.\n# so this adds an extra file. For the moment nothing has been done about this.\ndata_list = []\nfor entry in sources:\n data_list += makeDataList(entry)\n\n#Initialise the Markov Model data simulator and the driving learner\nmarkov_model = MarkovModel(look_back)\nlearner = FeatureLearner(look_back)\n\n#Feed the data to the simulator so it can create simulations\nfor entry in data_list:\n markov_model.addData(entry)\n\n#After data input distributions over different actions are generated. This\n# is done in finishAdd\nmarkov_model.finishAdd()\n\n#Simulate the specified number of episodes\nfor i in range(1,num_episodes+1):\n runSimulation(markov_model,learner,i,num_iterations,look_back)\n\n#Rewards are appended in initialise, so at the start of an episode. This \n# means that the last episode's reward is not automatically included in the \n# reward_list\nlearner.reward_list.append(learner.total_reward)\n\n#Copy reward list so that testing does not affect printed results\nsim_reward_list = list(learner.reward_list[1:])\n\n#Dictionary used to keep track of how many actions the learner predicts correctly\n# (True) vs. incorrectly (False)\ncount_dict = {True:0,False:0}\n\n#Confusion matrix for the test data\ntest_cross_section = [[0,0,0],[0,0,0],[0,0,0]]\n\n\nrand_seed = 1234543\nfor i in range(2): #Run twice since each entry in datalist is only half a journey \n random.seed(rand_seed*i)\n np.random.seed(rand_seed*i)\n #Randomly selected run from the data list\n [test_data,annotation] = data_list[random.randint(0,len(data_list)-1)]\n #The learner marks the start of runs by a 0 initially in the sequence\n init_state = [0]+annotation[:look_back-1]\n\n #Initialise the learner and standard simulation runthrough\n #Keeping track of correct/accurate guesses. \n learner.initialise(init_state)\n for (inputs,annote) in zip(test_data[look_back:],annotation[look_back:]):\n learner.sense(inputs)\n learner_action = learner.act(None,learning=False)\n count_dict[learner_action==annote] += 1\n #The columns of the confusion matrix are the true classifications\n #The rows are the learners classifications\n test_cross_section[index_dict[learner_action]][index_dict[annote]] += 1\n init_state = init_state[1:]+[annote] #revise state\n #Pass False to indicate learner should not be learning here\n #learner.callback(False,None,None,init_state)\n\n\nprint(\"WEIGHTS: {}\\n\".format(learner.weights))\n\nprint(\"RESULTS: {}\".format(look_back))\nprint(\"COUNT_DICT: {}\".format(count_dict))\nprint(\"CROSS_SECTION:\")\nfor entry in test_cross_section:\n print(entry)\n\nprint(\"REWARDS: {}\".format(sim_reward_list))\n\nplt.plot(sim_reward_list)\nplt.title(\"Reward achieved for learner with {} Look Back\".format(look_back))\nplt.show()\n","sub_path":"feat_simulator.py","file_name":"feat_simulator.py","file_ext":"py","file_size_in_byte":10162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"137048341","text":"from aws_cdk import core as cdk\n\n# For consistency with other languages, `cdk` is the preferred import name for\n# the CDK's core module. The following line also imports it as `core` for use\n# with examples from the CDK Developer's Guide, which are in the process of\n# being updated to use `cdk`. You may delete this import if you don't need it.\nfrom aws_cdk import core\nfrom rds_shared_construct.rds import RDSInstance\n\nclass SharedConstructExampleStack(cdk.Stack):\n\n def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n\n # The code that defines your stack goes here\n\n RDSInstance(self, \"dev\",\n env=\"dev\",\n vpc_name=\"dev-vpc\",\n rds_name=\"dev-rds\"\n )\n\n RDSInstance(self, \"dev2\",\n env=\"dev\",\n vpc_name=\"dev-vpc\",\n rds_name=\"dev2-rds\"\n )\n\n","sub_path":"shared-construct-example/shared_construct_example/shared_construct_example_stack.py","file_name":"shared_construct_example_stack.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"314799380","text":"import functools\nimport operator\nfrom collections import defaultdict\nfrom typing import TYPE_CHECKING, Any, Dict, Generator, List, Tuple, Type\n\nfrom hypothesis import strategies as st\nfrom hypothesis.stateful import Bundle, Rule, rule\nfrom requests.structures import CaseInsensitiveDict\n\nfrom ....stateful import APIStateMachine, Direction, StepResult\nfrom ....utils import Ok\nfrom .. import expressions\nfrom ..links import OpenAPILink\nfrom . import links\n\nif TYPE_CHECKING:\n from ....models import APIOperation, Case\n from ..schemas import BaseOpenAPISchema\n\n\nAPIOperationConnections = Dict[str, List[st.SearchStrategy[Tuple[StepResult, OpenAPILink]]]]\n\n\nclass OpenAPIStateMachine(APIStateMachine):\n def transform(self, result: StepResult, direction: Direction, case: \"Case\") -> \"Case\":\n context = expressions.ExpressionContext(case=result.case, response=result.response)\n direction.set_data(case, elapsed=result.elapsed, context=context)\n return case\n\n\ndef create_state_machine(schema: \"BaseOpenAPISchema\") -> Type[APIStateMachine]:\n \"\"\"Create a state machine class.\n\n This state machine will contain transitions that connect some operations' outputs with other operations' inputs.\n \"\"\"\n bundles = init_bundles(schema)\n connections: APIOperationConnections = defaultdict(list)\n for result in schema.get_all_operations():\n if isinstance(result, Ok):\n links.apply(result.ok(), bundles, connections)\n\n rules = make_all_rules(schema, bundles, connections)\n\n kwargs: Dict[str, Any] = {\"bundles\": bundles, \"schema\": schema}\n return type(\"APIWorkflow\", (OpenAPIStateMachine,), {**kwargs, **rules})\n\n\ndef init_bundles(schema: \"BaseOpenAPISchema\") -> Dict[str, CaseInsensitiveDict]:\n \"\"\"Create bundles for all operations in the given schema.\n\n Each API operation has a bundle that stores all responses from that operation.\n We need to create bundles first, so they can be referred when building connections between operations.\n \"\"\"\n output: Dict[str, CaseInsensitiveDict] = {}\n for result in schema.get_all_operations():\n if isinstance(result, Ok):\n operation = result.ok()\n output.setdefault(operation.path, CaseInsensitiveDict())\n output[operation.path][operation.method.upper()] = Bundle(operation.verbose_name) # type: ignore\n return output\n\n\ndef make_all_rules(\n schema: \"BaseOpenAPISchema\", bundles: Dict[str, CaseInsensitiveDict], connections: APIOperationConnections\n) -> Dict[str, Rule]:\n \"\"\"Create rules for all API operations, based on the provided connections.\"\"\"\n return {\n f\"rule {operation.verbose_name} {idx}\": new\n for operation in (result.ok() for result in schema.get_all_operations() if isinstance(result, Ok))\n for idx, new in enumerate(make_rules(operation, bundles[operation.path][operation.method.upper()], connections))\n }\n\n\ndef make_rules(\n operation: \"APIOperation\", bundle: Bundle, connections: APIOperationConnections\n) -> Generator[Rule, None, None]:\n \"\"\"Create a rule for an API operation.\"\"\"\n\n def _make_rule(previous: st.SearchStrategy) -> Rule:\n decorator = rule(target=bundle, previous=previous, case=operation.as_strategy()) # type: ignore\n return decorator(APIStateMachine._step)\n\n previous_strategies = connections.get(operation.verbose_name)\n if previous_strategies is not None:\n yield _make_rule(_combine_strategies(previous_strategies))\n yield _make_rule(st.none())\n\n\ndef _combine_strategies(strategies: List[st.SearchStrategy]) -> st.SearchStrategy:\n \"\"\"Combine a list of strategies into a single one.\n\n If the input is `[a, b, c]`, then the result is equivalent to `a | b | c`.\n \"\"\"\n return functools.reduce(operator.or_, strategies[1:], strategies[0])\n","sub_path":"src/schemathesis/specs/openapi/stateful/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"5833707","text":"# -*- coding: utf-8 -*-\n\nimport loadimpact\n\n\nclass Client(object):\n \"\"\"\n Load Impact client\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self._client = None\n\n @property\n def client(self):\n \"\"\" Get instance of `loadimpact.ApiTokenClient` \"\"\"\n if self._client is None:\n self._client = loadimpact.ApiTokenClient()\n return self._client\n\n def create_user_scenario(self, **scenario):\n \"\"\" Create user scenario using client \"\"\"\n return self.client.create_user_scenario(scenario)\n\n def create_test_config(self, **kwargs):\n \"\"\" Create test config using client \"\"\"\n name = kwargs.get('name')\n url = kwargs.get('url')\n users = kwargs.get('users')\n duration = kwargs.get('duration')\n scenario_id = kwargs.get('scenario_id')\n config = {\n 'name': name,\n 'url': url,\n 'config': {\n 'user_type': 'sbu',\n 'load_schedule': [{'users': users, 'duration': duration}],\n 'tracks': [{\n 'clips': [{'user_scenario_id': scenario_id,\n 'percent': 100}],\n 'loadzone': loadimpact.LoadZone.AMAZON_JP_TOKYO\n }]\n }\n }\n return self.client.create_test_config(config)\n\n\nclient = Client()\n","sub_path":"impactor/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"168045200","text":"import functools\nimport re\n\n# Part one\n# find_number = re.compile(r\"\\d+\")\n# mem = {}\n\n# one_mask = 0\n# zero_mask = 0\n\n# def create_masks(mask_as_string):\n# one_mask = ''.join([char if char=='1' else '0' for char in list(mask_as_string)])\n# zero_mask = ''.join([char if char=='0' else '1' for char in list(mask_as_string)])\n# return (one_mask, zero_mask)\n\n# #read data\n# with open('data/day14.txt') as reader:\n# for line in reader.readlines():\n# ins, val = line.strip().split(' = ')\n# if ins == 'mask':\n# one_mask, zero_mask = create_masks(val)\n# else:\n# val_masked = (int(val) | int(one_mask, 2)) & int(zero_mask, 2)\n# adress = int(find_number.findall(ins)[0])\n# mem[adress] = val_masked\n\n# print(mem)\n# print(functools.reduce(lambda a, b: a + b, mem.values()))\n\nfind_number = re.compile(r\"\\d+\")\nmem = {}\n\nprint(mem)\nprint(int('111111111111111111111111111111111111',2))\none_mask = ''\nzero_mask = ''\nadress_range = ''\n\ndef create_masks(mask_as_string):\n one_mask = ''.join([char if char=='1' else '0' for char in list(mask_as_string)])\n zero_mask = ''.join(['0' if char == 'X' else '1' for char in list(mask_as_string)])\n x_mask = ''.join(['X' if char == 'X' else '0' for char in list(mask_as_string)])\n amount_of_x = zero_mask.count('0')\n adress_range = []\n for n in range(2 ** amount_of_x):\n new_adress = x_mask\n for char in bin(n)[2:].zfill(amount_of_x):\n new_adress = new_adress.replace('X',char, 1)\n adress_range.append(int(new_adress, 2))\n # print('got here again', adress_range)\n return (one_mask, zero_mask, adress_range)\n\n#read data\nwith open('data/day14.txt') as reader:\n for line in reader.readlines():\n ins, val = line.strip().split(' = ')\n if ins == 'mask':\n one_mask, zero_mask,adress_range = create_masks(val)\n else:\n val = int(val)\n adress = int(find_number.findall(ins)[0])\n adress_masked = (int(adress) | int(one_mask, 2)) & int(zero_mask, 2)\n for offset in adress_range:\n mem[adress_masked + offset] = val\n\n# print(mem)\nprint(functools.reduce(lambda a, b: a + b, mem.values()))","sub_path":"day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242753980","text":"'''\r\nCreated on Oct 17, 2010\r\n\r\n@author: turturica\r\n'''\r\nfrom django.core.exceptions import ObjectDoesNotExist\r\nfrom labinventory.asset.utils.populators import update_if_changed\r\nfrom labinventory.asset.utils.snmp import SNMPWrap\r\nfrom labinventory.asset.models_lantronix import LantronixPort\r\nimport labinventory.asset.constants as const\r\nimport reversion\r\n\r\ndef populate_lantronix_slc(asset, user, log, options=None):\r\n from labinventory.asset.constants import SLC_PORT_COUNT, SLC_PORT_ID, \\\r\n SLC_PORT_NAME, SLC_TELNET_ENABLE, SLC_TELNET_PORT, \\\r\n SLC_SSH_ENABLE, SLC_SSH_PORT, SLC_TCP_ENABLE, SLC_TCP_PORT, \\\r\n SLC_BAUD, SLC_DATA_BIT, SLC_STOP_BIT, SLC_PARITY\r\n if options is None:\r\n options = {}\r\n\r\n log.info(\"Started Lantronix SLC populator\")\r\n try:\r\n bag = asset.get_static_bag()\r\n mgmtip = bag.address_set.get(access=True)\r\n # Bail if no mgmt addresses are found.\r\n except ObjectDoesNotExist:\r\n raise ValueError(\"No mgmt addresses found.\")\r\n\r\n snmp = SNMPWrap(mgmtip.address)\r\n ret = snmp(0, 1, SLC_PORT_COUNT)\r\n port_count = int(ret[0][0].value)\r\n port_list = snmp(1, port_count+1, SLC_PORT_ID, SLC_PORT_NAME, \r\n SLC_TELNET_ENABLE, SLC_TELNET_PORT, SLC_SSH_ENABLE, \r\n SLC_SSH_PORT, SLC_TCP_ENABLE, SLC_TCP_PORT, SLC_BAUD, \r\n SLC_DATA_BIT, SLC_STOP_BIT, SLC_PARITY)\r\n\r\n any_changes = False\r\n with reversion.revision:\r\n #update = {'manufacturer': 'Lantronix'}\r\n for i in xrange(len(port_list)):\r\n defaults = {}\r\n defaultsextra = {}\r\n defaults['name'] = unicode(port_list[i][0].value)\r\n defaults['type'] = const.PORT_NETWORK\r\n \r\n defaultsextra['label'] = unicode(port_list[i][1].value)\r\n # 1 == disabled, 2 == enabled\r\n defaultsextra['telnet_enabled'] = port_list[i][2].value == 2\r\n defaultsextra['ssh_enabled'] = port_list[i][4].value == 2\r\n defaultsextra['tcp_enabled'] = port_list[i][6].value == 2\r\n \r\n defaultsextra['telnet_port'] = int(port_list[i][3].value)\r\n defaultsextra['ssh_port'] = int(port_list[i][5].value)\r\n defaultsextra['tcp_port'] = int(port_list[i][7].value)\r\n\r\n defaultsextra['serial_baud'] = int(port_list[i][8].value)\r\n defaultsextra['serial_db'] = int(port_list[i][9].value)\r\n defaultsextra['serial_sb'] = int(port_list[i][10].value)\r\n defaultsextra['serial_pt'] = int(port_list[i][11].value)\r\n\r\n check_for = {\r\n 'name': defaults['name'],\r\n 'type': defaults['type']\r\n }\r\n \r\n port, created = asset.port_set.get_or_create(defaults = defaults,\r\n **check_for)\r\n\r\n try:\r\n port = port.morph()\r\n except LantronixPort.DoesNotExist:\r\n created = True\r\n\r\n defaults.update(defaultsextra)\r\n if created:\r\n LantronixPort.objects.create(id=port.id, asset=port.asset,\r\n **defaults)\r\n port = port.morph()\r\n\r\n any_changes |= update_if_changed((port, created), defaults)\r\n\r\n reversion.revision.user = user\r\n \r\n log.info(\"Done\")\r\n #return any_changes\r\n return True\r\n","sub_path":"labinventory/asset/populators/lantronix.py","file_name":"lantronix.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125881635","text":"def solution(name):\n change = [min(ord(letter) - ord('A'), ord('Z') - ord(letter) + 1) for letter in name]\n i, answer = 0, 0\n\n while True:\n answer += change[i]\n change[i] = 0\n\n if sum(change) == 0:\n return answer\n\n left, right = 1, 1\n while change[i - left] == 0:\n left += 1\n\n while change[i + right] == 0:\n right += 1\n\n if left < right:\n answer += left\n i -= left\n else:\n answer += right\n i += right\n\nprint(solution(input()))\n","sub_path":"Greedy/조이스틱/Suhyeon.py","file_name":"Suhyeon.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"291759050","text":"import torch\nimport torch.optim as optim\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport model\nimport datasets\nimport copy\nimport numpy as np\nimport random\nfrom matplotlib import pyplot as plt\nimport torchvision.models as models\n\ndef set_parameter_requires_grad(model, feature_extracting):\n if feature_extracting:\n for param in model.parameters():\n param.requires_grad = False\n \ndef train():\n EPOCH_SIZE = 1\n LEARNING_RATE = 1e-3\n WEIGHT_DECAY_VALUE = 2e-4\n BATCH_SIZE = 4\n\n \n # Make sure to use the GPU. The following line is just a check to see if GPU is availables\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n print(device)\n\n # load your dataset and dataloader\n # feel free to change header of bird_dataset class\n root = 'birds_dataset/'\n train_dataset = datasets.bird_dataset(root,'train_list.txt')\n test_dataset = datasets.bird_dataset(root,'test_list.txt')\n\n valid_dataset = datasets.bird_dataset(root,'train_list.txt')\n\n valid_indices = []\n\n NUM_EXAMPLES_PER = 30\n for i in range(0, len(train_dataset), NUM_EXAMPLES_PER):\n valid_indices += random.sample(range(i, i + NUM_EXAMPLES_PER), 3)\n\n train_dataset.images = [train_dataset.images[i] for i in range(len(train_dataset.images)) if i not in valid_indices]\n train_dataset.labels = [train_dataset.labels[i] for i in range(len(train_dataset.labels)) if i not in valid_indices]\n\n valid_dataset.images = [valid_dataset.images[i] for i in range(len(valid_dataset.images)) if i in valid_indices]\n valid_dataset.labels = [valid_dataset.labels[i] for i in range(len(valid_dataset.labels)) if i in valid_indices]\n\n\n # Fill in optional arguments to the dataloader as you need it\n train_dataloader1 = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)\n test_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE)\n\n valid_dataloader1 = DataLoader(valid_dataset, batch_size=BATCH_SIZE)\n\n\n\n # CREATE SECOND FOLD\n train_dataset = datasets.bird_dataset(root,'train_list.txt')\n\n valid_dataset = datasets.bird_dataset(root,'train_list.txt')\n\n valid_indices = []\n\n NUM_EXAMPLES_PER = 30\n for i in range(0, len(train_dataset), NUM_EXAMPLES_PER):\n valid_indices += random.sample(range(i, i + NUM_EXAMPLES_PER), 2)\n\n train_dataset.images = [train_dataset.images[i] for i in range(len(train_dataset.images)) if i not in valid_indices]\n train_dataset.labels = [train_dataset.labels[i] for i in range(len(train_dataset.labels)) if i not in valid_indices]\n\n valid_dataset.images = [valid_dataset.images[i] for i in range(len(valid_dataset.images)) if i in valid_indices]\n valid_dataset.labels = [valid_dataset.labels[i] for i in range(len(valid_dataset.labels)) if i in valid_indices]\n\n train_dataloader2 = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)\n\n valid_dataloader2 = DataLoader(valid_dataset, batch_size=BATCH_SIZE)\n\n\n\n\n # train your model\n # For each epoch iterate over your dataloaders/datasets, pass it to your NN model, get output, calculate loss and\n # backpropagate using optimizer\n def train(train_dataloader, valid_dataloader, best_loss, best_model):\n train_loss = []\n valid_loss = []\n train_acc = []\n valid_acc = []\n\n\n for epoch in range(EPOCH_SIZE):\n print(\"Epoch:\", epoch)\n epoch_loss = 0\n accurate = 0\n\n nn_model.train()\n for i, (image, label) in enumerate(train_dataloader):\n image = image.cuda().float()\n label = label.cuda()\n\n output = nn_model.forward(image)\n\n loss = criterion(output, label)\n epoch_loss += loss.item()\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n value, index = torch.max(output.data, 1)\n accurate += (index == label).sum().item()\n\n # if index.item() == label.item():\n # accurate += 1\n\n epoch_loss = epoch_loss/len(train_dataloader.dataset)\n accuracy = accurate/len(train_dataloader.dataset)\n print(\"Train Accuracy:\", accuracy, \"| Loss:\", epoch_loss)\n train_loss.append(epoch_loss)\n train_acc.append(accuracy)\n\n nn_model.eval()\n epoch_loss = 0\n accurate = 0\n with torch.no_grad():\n for i, (image, label) in enumerate(valid_dataloader):\n image = image.cuda().float()\n label = label.cuda()\n\n output = nn_model.forward(image)\n\n loss = criterion(output, label)\n epoch_loss += loss.item()\n\n value, index = torch.max(output.data, 1)\n accurate += (index == label).sum().item()\n # if index.item() == label.item():\n # accurate += 1\n\n epoch_loss = epoch_loss/len(valid_dataloader.dataset)\n accuracy = accurate/len(valid_dataloader.dataset)\n print(\"Valid Accuracy:\", accuracy, \"| Loss:\", epoch_loss)\n valid_loss.append(epoch_loss)\n valid_acc.append(accuracy)\n\n if (epoch_loss < best_loss):\n best_loss = epoch_loss\n best_model = copy.deepcopy(nn_model)\n\n return best_model, train_loss, valid_loss, train_acc, valid_acc\n\n\n\n best_loss = float('inf')\n best_model = None\n\n # Create custom resnet model object\n weight_initialization = [nn.Conv2d, nn.Linear]\n nn_model = models.resnet18(pretrained=True)\n\n\n \n #FINETUNING------------------\n set_parameter_requires_grad(nn_model, True)\n count = 0\n #if you want to unfreeze specific layers\n# for layer in nn_model.modules():\n# if type(layer) in weight_initialization:\n# count += 1\n# if count >= 16 and count <= 19:\n# layer.weight.requires_grad = True\n# # layer.bias.requires_grad = True\n #----------------------------\n #set custom classifier with 20 categories\n nn_model.fc = nn.Linear(512, 20)\n nn_model.to(device)\n\n #only set weight if unfrozen\n for layer in nn_model.modules():\n if type(layer) in weight_initialization:\n if layer.weight.requires_grad: \n torch.nn.init.xavier_uniform_(layer.weight)\n \n params_to_update = []\n for name,param in nn_model.named_parameters():\n if param.requires_grad == True:\n params_to_update.append(param)\n print(name)\n\n criterion = nn.CrossEntropyLoss()\n\n #specify which layers to update weights for\n optimizer = torch.optim.Adam(params_to_update, lr=LEARNING_RATE)\n\n\n best_model, train_loss1, valid_loss1, train_acc1, valid_acc1 = train(train_dataloader1, valid_dataloader1, best_loss, best_model)\n\n\n\n\n # SECOND FOLD\n # Create NN model object\n nn_model = models.resnet18(pretrained=True)\n\n\n \n #FINETUNING------------------\n set_parameter_requires_grad(nn_model, True)\n count = 0\n #if you want to unfreeze specific layers\n# for layer in nn_model.modules():\n# if type(layer) in weight_initialization:\n# count += 1\n# if count >= 16 and count <= 19:\n# layer.weight.requires_grad = True\n# # layer.bias.requires_grad = True\n #----------------------------\n\n #set custom layer\n nn_model.fc = nn.Linear(512, 20)\n nn_model.to(device)\n\n #only set weight if unfrozen\n for layer in nn_model.modules():\n if type(layer) in weight_initialization:\n if layer.weight.requires_grad: \n torch.nn.init.xavier_uniform_(layer.weight)\n \n #specify which layers to update weights for\n params_to_update = []\n for name,param in nn_model.named_parameters():\n if param.requires_grad == True:\n params_to_update.append(param)\n\n\n\n\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(params_to_update, lr=LEARNING_RATE)\n\n best_model, train_loss2, valid_loss2, train_acc2, valid_acc2 = train(train_dataloader2, valid_dataloader2, best_loss, best_model)\n\n train_loss = [(train_loss1[i] + train_loss2[i])/2 for i in range(len(train_loss1))]\n valid_loss = [(valid_loss1[i] + valid_loss2[i])/2 for i in range(len(valid_loss1))]\n\n train_acc = [(train_acc1[i] + train_acc2[i])/2 for i in range(len(train_acc1))]\n valid_acc = [(valid_acc1[i] + valid_acc2[i])/2 for i in range(len(valid_acc1))]\n\n\n\n # PLOT LOSS/ACCURACY\n plt.errorbar(range(len(train_loss)), train_loss, color = 'blue', label='train loss')\n plt.errorbar(range(len(valid_loss)), valid_loss, color = 'red', label='valid loss')\n plt.xlabel('Epoch Number')\n plt.ylabel('Loss')\n plt.title('Loss For Each Epoch')\n\n\n plt.legend()\n plt.show()\n\n plt.errorbar(range(len(train_acc)), train_acc, color = 'blue', label='train accuracy')\n plt.errorbar(range(len(valid_acc)), valid_acc, color = 'red', label='valid accuracy')\n plt.xlabel('Epoch Number')\n plt.ylabel('Accuracy')\n plt.title('Accuracy For Each Epoch')\n\n plt.legend()\n plt.show()\n\n test_loss = 0\n test_accurate = 0\n\n best_model.eval()\n for i, (image, label) in enumerate(test_dataloader):\n image = image.cuda().float()\n label = label.cuda()\n\n output = best_model.forward(image)\n\n loss = criterion(output, label)\n test_loss += loss.item()\n\n value, index = torch.max(output.data, 1)\n test_accurate += (index == label).sum().item()\n\n\n test_loss = test_loss/len(test_dataloader.dataset)\n test_accuracy = test_accurate/len(test_dataloader.dataset)\n\n print(\"Test Accuracy:\", test_accuracy, \"| Loss:\", test_loss)\n print(\"Epoch size:\", EPOCH_SIZE, \"Learning rate:\", LEARNING_RATE)\n\n print(best_model)\n\n\n\n\n\n # First convolutional layer (for weight map)\n model_children = list(best_model.children())\n first_conv = best_model.conv1\n# first_conv = list(model_children[0].children())[0]\n first_conv.cpu()\n\n # Weight map\n for i, filter in enumerate(first_conv.weight):\n plt.subplot(8, 8, i+1) \n plt.imshow(filter[0, :, :].detach(), cmap='gray')\n plt.axis('off')\n plt.show()\n\n\n # Feature map\n image_dataset = datasets.bird_dataset(root,'test_list.txt')\n image_dataset.images = [image_dataset.images[0]]\n image_dataloader = DataLoader(image_dataset)\n\n first_image = None\n for i, (image, label) in enumerate(image_dataloader):\n if i == 0:\n first_image = image.float()\n break\n #idk how to get a single image from dataloader but you need dataloader to process it\n\n activation = {}\n\n def get_activation(name):\n def hook(model, input, output):\n activation[name] = output.detach()\n return hook\n\n #first conv layer\n best_model.conv1.register_forward_hook(get_activation('features'))\n best_model.cpu()\n output = best_model(first_image.cpu())\n\n act = activation['features'].squeeze()\n for idx in range(act.size(0)):\n plt.subplot(act.size(0)**0.5, act.size(0)**0.5, idx + 1)\n plt.imshow(act[idx])\n plt.axis('off')\n plt.show()\n \n ########################################\n best_model.layer2.register_forward_hook(get_activation('features'))\n best_model.cpu()\n output = best_model(first_image.cpu())\n\n #middle conv layer\n act = activation['features'].squeeze()\n for idx in range(act.size(0)):\n plt.subplot(act.size(0)**0.5, act.size(0)**0.5, idx + 1)\n plt.imshow(act[idx])\n plt.axis('off')\n plt.show()\n \n best_model.layer4.register_forward_hook(get_activation('features'))\n best_model.cpu()\n output = best_model(first_image.cpu())\n\n #last conv layer\n act = activation['features'].squeeze()\n for idx in range(act.size(0)):\n plt.subplot(act.size(0)**0.5+1, act.size(0)**0.5+1, idx + 1)\n plt.imshow(act[idx])\n plt.axis('off')\n plt.show()\n\n\n\n\n","sub_path":"Code/resnet_train.py","file_name":"resnet_train.py","file_ext":"py","file_size_in_byte":12159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"474176108","text":"import logging\nimport version as versionutils\n\n\n\n# Make a default logger object\nlog = logging.getLogger()\n\n\n\nclass session:\n def __init__(self, dfraws=None, dfversion=None):\n self.dfraws = dfraws\n self.dfversion = dfversion\n self.successes = []\n self.failures = []\n self.noresponse = []\n \n def successful(self, info):\n return self.inlist(info, self.successes)\n def failed(self, info):\n return self.inlist(info, self.failures)\n \n def inlist(self, info, flist):\n funcs = self.funcs(info)\n if funcs:\n return any([(func in flist) for func in funcs])\n else:\n return False\n \n def eval(self, func, args=None):\n # If the function is actually an urist, make sure we know that\n uristinstance = None\n if isinstance(func, urist): \n uristinstance = func\n func = uristinstance.fn\n name = uristinstance.getname()\n else:\n name = func.__name__\n # Actually execute the script\n log.info('Running script %s%s.' % (name, ('with args %s' % args) if args else ''))\n try:\n # Call the function\n response = func(self.dfraws, **args) if args else func(self.dfraws)\n if response:\n # Handle success/failure response\n log.info('%s: %s' % ('SUCCESS' if response.success else 'FAILURE', str(response)))\n (self.successes if response.success else self.failures).append(uristinstance if uristinstance else func)\n else:\n log.error('Received no response from script %s.' % name)\n self.noresponse.append(uristinstance if uristinstance else func)\n except Exception:\n log.exception('Unhandled exception while running script %s.' % name)\n return False\n else:\n log.info('Finished running script %s.' % name)\n return True\n \n def funcs(self, info):\n uristinstance, scriptname, scriptfunc, scriptargs, scriptmatch, checkversion = urist.info(info, self.dfversion)\n if uristinstance is None and scriptfunc is None and scriptname is not None:\n return urist.get(scriptname, version=checkversion, match=scriptmatch, session=self)\n elif uristinstance is not None:\n return (uristinstance,)\n elif scriptfunc is not None:\n return (scriptfunc,)\n else:\n return None\n \n def handle(self, info):\n funcs = self.funcs(info)\n if funcs:\n for func in funcs: self.eval(func)\n else:\n log.error('Found no scripts matching %s.' % info)\n \n def handleall(self, infos):\n for info in infos: self.handle(info)\n \n \n\n# Functions in scripts must be decorated with this in order to be made available to PyDwarf\nclass urist:\n '''Decorates a function as being an urist. Keyword arguments are treated as metadata.\n \n Special metadata - these are given special handling:\n name: If name is not specified, then the function name is used to refer to the script.\n If specified, this is used instead.\n compatibility: Informs PyDwarf, using a regular expression, which Dwarf Fortress\n versions a script is compatible with. If this is an iterable, later patterns\n should describe versions that the plugin is partially compatible with, or that\n it ought to be compatible with but that hasn't been tested. This way, a version\n with a more confident compatibility indicator can be chosen over one with a less\n confident indicator.\n namespace: Should correspond to an author or authors, groups of mods, or anything\n really. When specified, it becomes possible for a user to conveniently reference\n a particular one of multiple identically-named mods by a namespace. If there is\n a period in a script name, the text preceding the last period is assumed to be\n namespace and the text after the name.\n dependency: Will cause an error to be logged when running a script without having\n run all of its dependencies first.\n \n Standard metadata - PyDwarf does nothing special with these, but for the sake of standardization they ought to be included:\n author: Indicates who created the script. In the case of multiple authors, an\n iterable such as a tuple or list should be used to enumerate them.\n version: Indicates the script version.\n description: Describes the script's purpose and functioning.\n arguments: Should be a dict with argument names as keys corresponding to strings which\n explain their purpose.\n '''\n \n # Track registered functions\n registered = {}\n # Track data about which scripts have run successfully, etc.\n session = session()\n \n # Decorator handling\n def __init__(self, **kwargs):\n self.namespace = ''\n self.metadata = kwargs\n def __call__(self, fn):\n self.fn = fn\n if 'name' in self.metadata:\n self.name, self.namespace = urist.splitname(self.metadata['name'])\n else:\n self.name = fn.__name__\n if self.name not in urist.registered: urist.registered[self.name] = []\n urist.registered[self.name].append(self)\n log.debug('Registered script %s.' % self.getname())\n return fn\n \n def __str__(self):\n return self.getname()\n \n def __hash__(self):\n return hash(';'.join((self.getname(), str(self.meta('version')), str(self.meta('author')))))\n \n def getname(self):\n return '.'.join((self.meta('namespace'), self.name)) if 'namespace' in self.metadata else self.name\n \n def namespace(self):\n return self.meta('namespace')\n \n def meta(self, key):\n return self.metadata.get(key)\n \n def matches(self, match):\n return all([self.meta(i) == j for i, j in match.iteritems()]) if match else True\n \n def depsatisfied(self, session):\n deps = self.meta('dependency')\n if deps is not None:\n # Allow single dependencies to be indicated without being inside an iterable\n if isinstance(deps, basestring) or isinstance(deps, dict): deps = (deps,)\n # Check each dependency\n satisfied = 0\n for dep in deps:\n log.debug('Checking for dependency %s...' % dep)\n satisfied += session.successful(dep)\n # All done\n log.debug('Satisifed %d of %d dependencies.' % (satisfied, len(deps)))\n return satisfied == len(deps)\n else:\n return True\n \n @staticmethod\n def info(script, version=None):\n # A script can be specified in a variety of ways in the scripts iterable, this function is for understanding all the different options and returning the info the manager needs.\n uristinstance, scriptname, scriptfunc, scriptargs, scriptmatch = None, None, None, None, None\n scriptignoreversion = None\n \n if isinstance(script, urist):\n uristinstance = script\n elif callable(script):\n scriptfunc = script\n uristinstance = urist.forfunc(scriptfunc)\n elif isinstance(script, basestring):\n scriptname = script\n elif isinstance(script, dict):\n scriptname = script.get('name')\n scriptfunc = script.get('func')\n scriptargs = script.get('args')\n scriptmatch = script.get('match')\n scriptignoreversion = script.get('ignore_df_version')\n \n checkversion = None if scriptignoreversion else version\n \n if uristinstance is not None:\n scriptname = uristinstance.name\n scriptfunc = uristinstance.fn\n \n if scriptname is None and scriptfunc is not None:\n scriptname = scriptfunc.__name__\n \n return uristinstance, scriptname, scriptfunc, scriptargs, scriptmatch, checkversion\n \n @staticmethod\n def getregistered(name, namespace=None):\n named = urist.allregistered() if name == '*' else urist.registered.get(name)\n if named and namespace:\n return [ur for ur in named if ur.namespace == namespace or ur.namespace.startswith(namespace+'.')]\n else:\n return named\n \n @staticmethod\n def allregistered():\n results = []\n for rlist in urist.registered.itervalues():\n for r in rlist: results.append(r)\n return results\n \n @staticmethod\n def get(name, version=None, match=None, session=None):\n # Reduce list based on matching the match dict, version compatibility, dependencies, etc\n return urist.cullcandidates(\n version = version, \n match = match, \n session = session if session is not None else urist.session, \n candidates = urist.getregistered(*urist.splitname(name))\n )\n \n @staticmethod\n def cullcandidates(version, match, session, candidates):\n if candidates and len(candidates):\n candidates = urist.cullcandidates_match(match, candidates)\n candidates = urist.cullcandidates_compatibility(version, candidates)\n candidates = urist.cullcandidates_dependency(session, candidates)\n candidates = urist.cullcandidates_duplicates(candidates)\n return candidates\n \n @staticmethod\n def cullcandidates_match(match, candidates):\n return [c for c in candidates if c.matches(match)] if match else candidates\n \n @staticmethod\n def cullcandidates_compatibility(version, candidates):\n if version:\n comp = []\n nocomp = []\n for candidate in candidates:\n compatibility = candidate.meta('compatibility')\n if compatibility:\n if versionutils.compatible(compatibility, version): comp.append(candidate)\n else:\n nocomp.append(candidate)\n return comp + nocomp\n else:\n return candidates\n \n @staticmethod\n def cullcandidates_dependency(session, candidates):\n return [c for c in candidates if c.depsatisfied(session)]\n \n @staticmethod\n def cullcandidates_duplicates(candidates):\n names = {}\n for candidate in candidates:\n candname = candidate.name\n dupe = names.get(candname)\n if dupe is None:\n names[candname] = candidate\n elif candidate.meta('namespace') == dupe.meta('namespace'):\n if ((dupe.meta('version') is None) or ((candidate.meta('version') is not None) and candidate.meta('version') > dupe.meta('version'))):\n names[candname] = candidate\n else:\n pass # conflicting names in different namespaces, do nothing\n return names.values()\n \n @staticmethod\n def forfunc(func):\n for uristlist in registered:\n for urist in uristlist:\n if urist.fn == func: return urist\n return None\n \n @staticmethod\n def splitname(name):\n if '.' in name:\n nameparts = name.split('.')\n name = nameparts[-1]\n namespace = '.'.join(nameparts[:-1])\n return name, namespace\n else:\n return name, None\n","sub_path":"pydwarf/urist.py","file_name":"urist.py","file_ext":"py","file_size_in_byte":11534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"521380474","text":"from collections import defaultdict\nimport re\n\nwith open('day4.in') as f:\n logs = [r[1:].strip().split('] ') for r in f]\nlogs.sort()\n\n# Build asleep / awake timelines for each night's shift\nguards_asleep = defaultdict(int)\nguard = asleep_time = None\nfor ix, (dt, action) in enumerate(logs):\n time = int(dt[-2:])\n if 'begins shift' in action:\n guard = int(re.search(r'#(\\d+)', action).group(1))\n elif 'falls asleep' in action:\n asleep_time = time\n elif 'wakes up' in action:\n for m in range(asleep_time, time):\n guards_asleep[(guard, m)] += 1\n\n# Find guard asleep the most\nguard_totals = defaultdict(int)\nfor (guard, m), total in guards_asleep.items():\n guard_totals[guard] += total\nsleepiest_guard = max(guard_totals, key=guard_totals.get)\n\n# Find minute sleepiest guard was asleep the most\nminutes = {}\nfor (guard, m), total in guards_asleep.items():\n if guard == sleepiest_guard:\n minutes[m] = total\nsleepiest_minute = max(minutes, key=minutes.get)\n\nprint(f'Day 4 Part 1: {sleepiest_guard * sleepiest_minute}') # 103720\n\n# Part 2\nfreq_asleep_guard, freq_asleep_minute = max(guards_asleep, key=guards_asleep.get)\nprint(f'Day 4 Part 2: {freq_asleep_guard * freq_asleep_minute}') # 110913\n","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"145348964","text":"print(\"you have imported modelMethod\")\nfrom .publicLibrary import *\n\nfrom lightgbm import LGBMClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\nfrom catboost import CatBoostClassifier\n\nfrom bayes_opt import BayesianOptimization\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import roc_auc_score,classification_report,roc_curve,auc,accuracy_score\n\nclass BayesoptModel:\n \"\"\"\n example\n --------------\n model_params = {\n 'learning_rate':(0.05, 0.1),\n 'max_bin':(10,255),\n 'num_leaves':(10,35),\n 'n_estimators': (100, 300),\n 'max_depth': (2, 13),\n 'min_split_gain':(1,5),\n 'colsample_bytree':(0.9,1.0),\n 'subsample':(0.5,1.0),\n 'reg_alpha':(0.1,5.0),\n 'reg_lambda':(100,800),\n 'min_child_weight':(0.01,0.1),\n 'min_child_samples':(10,100)\n }\n bayesoptModel = modelMethod.BayesoptModel(x,y,model_type='LGBMClassifier',scoring='roc_auc',cv=5)\n model_bo_max = bayesoptModel.start_bayes_opt(model_params)\n \"\"\"\n def __init__(self,x,y,model_type='LGBMClassifier',scoring='roc_auc',cv=5):\n self.x = x\n self.y = y\n self.scoring = scoring\n self.cv = cv\n \n #dict替代if-else\n modeltype_dict = {'LogisticRegression':self.model_cv_LogisticRegression,\n 'SVC':self.model_cv_SVC,\n 'LGBMClassifier':self.model_cv_LGBMClassifier,\n 'RandomForestClassifier':self.model_cv_RandomForestClassifier,\n 'XGBClassifier':self.model_cv_XGBClassifier,\n 'CatBoostClassifier':self.model_cv_CatBoostClassifier}\n \n self.model_cv = modeltype_dict.get(model_type)\n \n def model_cv_LogisticRegression(self,tol,C,max_iter):\n val = cross_val_score(\n LogisticRegression(\n tol=tol,\n C=C,\n max_iter=int(max_iter),\n penalty='l2',\n dual=False,\n fit_intercept=True,\n intercept_scaling=1,\n class_weight='balanced',\n random_state=2020,\n solver='lbfgs',\n multi_class='auto',\n verbose=0,\n warm_start=False,\n n_jobs=None,\n l1_ratio=None\n ),self.x, self.y, scoring=self.scoring, cv=self.cv\n ).mean()\n return val\n \n def model_cv_SVC(self,C):\n val = cross_val_score(\n SVC(\n C=C,\n kernel='rbf',\n degree=3,\n gamma='scale',\n coef0=0.0,\n shrinking=True,\n probability=False,\n tol=0.001,\n cache_size=1000,\n class_weight='balanced',\n verbose=False,\n max_iter=-1,\n decision_function_shape='ovr',\n break_ties=False,\n random_state=2020,\n ),self.x, self.y, scoring=self.scoring, cv=self.cv\n ).mean()\n return val\n \n \n def model_cv_LGBMClassifier(self,learning_rate, max_bin, num_leaves, n_estimators, max_depth\n ,min_split_gain,colsample_bytree\n ,subsample,reg_alpha,reg_lambda,min_child_weight,min_child_samples\n ):\n val = cross_val_score(\n LGBMClassifier(\n learning_rate = learning_rate,\n max_bin = int(max_bin),\n num_leaves = int(num_leaves),\n n_estimators = int(n_estimators),\n max_depth=int(max_depth),\n min_split_gain=int(min_split_gain),\n colsample_bytree=colsample_bytree,\n subsample=subsample,\n reg_alpha=reg_alpha,\n reg_lambda=int(reg_lambda),\n min_child_weight=min_child_weight,\n min_child_samples=int(min_child_samples),\n\n random_state=2020,\n is_unbalance=True,\n objective='binary'\n # objective = 'multiclass',\n # num_class = 2,\n ),self.x, self.y, scoring=self.scoring, cv=self.cv\n ).mean()\n return val\n \n def model_cv_RandomForestClassifier(self,n_estimators,max_depth,min_samples_split,min_samples_leaf):\n val = cross_val_score(\n RandomForestClassifier(\n n_estimators=int(n_estimators),\n max_depth=int(max_depth),\n min_samples_split = int(min_samples_split),\n min_samples_leaf= int(min_samples_leaf),\n min_weight_fraction_leaf=0.0,\n criterion='gini',\n max_features='auto',\n max_leaf_nodes=None,\n min_impurity_decrease=0.0,\n min_impurity_split=None,\n bootstrap=True,\n oob_score=True,\n n_jobs=None,\n random_state=2020,\n verbose=0,\n warm_start=False,\n class_weight='balanced',\n ccp_alpha=0.0,\n max_samples=None,\n ),self.x, self.y, scoring=self.scoring, cv=self.cv\n ).mean()\n return val\n \n def model_cv_XGBClassifier(self,learning_rate,n_estimators,max_depth,gamma,\n subsample,colsample_bytree,reg_alpha,reg_lambda):\n val = cross_val_score(\n XGBClassifier(\n learning_rate = learning_rate,\n n_estimators = int(n_estimators),\n max_depth=int(max_depth),\n gamma = gamma,\n# min_child_weight=min_child_weight,\n subsample=subsample,\n colsample_bytree=colsample_bytree,\n reg_alpha= reg_alpha,\n reg_lambda = reg_lambda,\n \n random_state=2020,\n# scale_pos_weight=1,\n# objective='binary'\n # objective = 'multiclass',\n # num_class = 2,\n ),self.x, self.y, scoring=self.scoring, cv=self.cv\n ).mean()\n return val\n \n def model_cv_CatBoostClassifier(self,depth,n_estimators,l2_leaf_reg,subsample):\n val = cross_val_score(\n CatBoostClassifier(\n depth=int(depth),\n n_estimators=int(n_estimators),\n l2_leaf_reg=l2_leaf_reg,\n subsample=subsample,\n \n one_hot_max_size=2,\n# class_weights=None,\n random_state=2020,\n# scale_pos_weight=1,\n# objective='binary'\n # objective = 'multiclass',\n # num_class = 2,\n ),self.x, self.y, scoring=self.scoring, cv=self.cv\n ).mean()\n return val\n \n \n \n def start_bayes_opt(self,model_params):\n model_bo = BayesianOptimization(\n self.model_cv,\n model_params\n )\n model_bo.maximize()\n return model_bo.max\n\n \nfrom mlxtend.classifier import EnsembleVoteClassifier\nfrom mlxtend.plotting import plot_decision_regions\nclass EnsembleMethods:\n \"\"\"\n example\n --------------\n \n \"\"\"\n def __init__(self,models=[],):\n pass\n ","sub_path":"src/modelMethod.py","file_name":"modelMethod.py","file_ext":"py","file_size_in_byte":7503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"620171194","text":"from modules import tournament, mctsagent, gtpinterface, qb_rave_mctsagent, rave_mctsagent\n\ngame_number = 200\nmove_time = 1\nboardsize = 11\ntournament_number = 3\n\ndef main():\n\n interface1 = gtpinterface(rave_mctsagent())\n interface2 = gtpinterface(qb_rave_mctsagent())\n\n address = 'results/QB_RAVE_VS_RAVE.txt'\n\n f = open(address, 'a')\n f.write('QB_RAVE VS RAVE \\n')\n print('QB_RAVE VS RAVE \\n')\n f.close()\n for t in range(tournament_number):\n result = tournament(interface1, interface2, game_number, move_time, boardsize)\n with open(address, 'a') as file:\n file.write('Tournament %a \\n' % str(t+1))\n file.write('player 1 wins = %a games \\n' % result[0])\n file.write('player 2 wins = %a games \\n' % result[1])\n file.write('player 1 = %a percent \\n' % str((result[0] / game_number)*100))\n file.write('player 2 = %a percent \\n' % str((result[1] / game_number)*100))\n file.write(\"Simulations avg: \\nAgent1 [ %a ] Agent2 = [ %a ] \\n\" % tuple(result[2]))\n file.write(\"Total Time : [ %a ] seconds\\n\\n\" % int(result[3]))\n \n for i in range(10):\n file.write(\"*****\")\n file.write('\\n\\n')\n file.close()\n\nif __name__ == \"__main__\":\n main()","sub_path":"agent3_mcts/playtest.py","file_name":"playtest.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"331821127","text":"\"\"\"\n自定义进程类\n\"\"\"\nfrom multiprocessing import Process\n\n# 创建自己的类\nclass MyProcess(Process):\n def __init__(self, value=1):\n self.value = value\n super().__init__() # 执行父类的init方法\n\n # 重写run,作为子进程执行内容\n def run(self):\n for i in range(self.value):\n print(\"作为进程执行\")\n\nif __name__ == '__main__':\n process = MyProcess(3)\n process.start() # 启动进程 执行run\n\n# class Process:\n# def __init__(self,target=None):\n# self._target = target\n#\n# def run(self):\n# self._target()\n#\n# def start(self):\n# # 申请创建进程\n# self.run()\n\n\n\n\n\n\n\n","sub_path":"fancy_month02/day13_self_mprocessing/day13_teacher/my_process.py","file_name":"my_process.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"506605763","text":"import pygame as pg\r\nfrom pygame.sprite import Sprite\r\n\r\nWHITE = (255, 255, 255)\r\nBLACK = (0, 0, 0)\r\nDARKGREY = (40, 40, 40)\r\nLIGHTGREY = (100, 100, 100)\r\nGREEN = (0, 255, 0)\r\nRED = (255, 0, 0)\r\nYELLOW = (255, 255, 0)\r\n\r\nclass Tile(Sprite):\r\n \"\"\"Tile\"\"\"\r\n\r\n def __init__(self, color):\r\n \"\"\"Initialize the alien and set its starting position\"\"\"\r\n super(Tile, self).__init__()\r\n self.color = color\r\n\r\n\r\n\r\n\r\ntile = Tile(YELLOW)\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29629850","text":"import numpy as np\nimport pandas as pd\nimport gensim\nimport re\nfrom joblib import Parallel, delayed\nimport os\nfrom collections import defaultdict\nimport chainer.links as L\nimport pickle\nimport random\n\nresearch_path = '../../../data/'\nw2v_path = research_path + 'entity_vector/entity_vector.model.txt'\ndirectory = research_path + 'annotated/'\ndomain_dict = {'PM':'雑誌','PN':'新聞', 'OW':'白書', 'OC':'Yahoo!知恵袋', 'OY':'Yahoo!ブログ', 'PB':'書籍'}\n\ntsubame = True\nif tsubame == True:\n w2v_path = research_path + 'entity_vector/entity_vector.model.pickle'\nelse:\n import gensim\n\n#正規表現\n#正規表現\ndef get_tag_id(text):\n m = re.search(r'id=\"([0-9]+)\"', text)\n if m: return m.group(1)\n return ''\ndef get_ga_tag(text):\n m = re.search(r'ga=\"(.+?)\"', text)\n if m: return m.group(1)\n return ''\ndef get_o_tag(text):\n m = re.search(r'o=\"(.+?)\"', text)\n if m: return m.group(1)\n return ''\ndef get_ni_tag(text):\n m = re.search(r' ni=\"(.+?)\"', text)\n if m: return m.group(1)\n return ''\ndef get_ga_dep_tag(text):\n m = re.search(r'ga_dep=\"(.+?)\"', text)\n if m: return m.group(1)\n return None\ndef get_o_dep_tag(text):\n m = re.search(r'o_dep=\"(.+?)\"', text)\n if m: return m.group(1)\n return None\ndef get_ni_dep_tag(text):\n m = re.search(r' ni_dep=\"(.+?)\"', text)\n if m: return m.group(1)\n return None\ndef is_num(text):\n m = re.match('\\A[0-9]+\\Z', text)\n if m: return True\n else: return False\ndef get_type(text):\n m = re.search(r'type=\"(.+?)\"', text)\n if m: return m.group(1)\n return ''\n\nclass Word2Vec:\n def __init__(self, model_file_path):\n if tsubame:\n with open(model_file_path, 'rb') as f:\n model = pickle.load(f)\n words = model.keys()\n else:\n model = gensim.models.KeyedVectors.load_word2vec_format(model_file_path)\n words = model.vocab.keys()\n self.model = model\n self.words = words\n\n def word_to_vector(self, word):\n if word and word in self.words:\n return self.model[word]\n else:\n return np.zeros(200, dtype=np.float32)\n def word_to_dataframe(self, word):\n vector = self.word_to_vector(word)\n if word == 'exo1':\n vector = self.word_to_vector('僕')\n elif word == 'exo2':\n vector = self.word_to_vector('おまえ')\n elif word == 'exog':\n vector = self.word_to_vector('これ')\n df = pd.DataFrame([vector])\n df.columns = [f'word2vec:{i}' for i in range(200)]\n df['word'] = word\n return df\n\nclass FeatureToEmbedID:\n def __init__(self):\n feature_size_dict = {\"feature:0\":24, \"feature:1\":25, \"feature:2\":11, \"feature:3\":5, \"feature:4\":93,\n \"feature:5\":31, \"feature:6\":30119, \"feature:7\":35418, \"feature:8\":1,\n \"feature:9\":1, \"feature:10\":5545, \"feature:11\":1, \"feature:12\":7,\n \"feature:13\":1, \"feature:14\":5, \"feature:15\":1, \"feature:16\":1 }\n\n self.feature0 = {'*': 0, \"助詞\":1, \"未知語\":2, \"URL\":3, \"言いよどみ\":4, \"連体詞\":5, \"ローマ字文\":6, \"web誤脱\":7,\n \"英単語\":8, \"接頭辞\":9, \"助動詞\":10, \"接尾辞\":11, \"記号\":12, \"動詞\":13, \"漢文\":14, \"副詞\":15, \"形容詞\":16,\n \"接続詞\":17, \"補助記号\":18, \"代名詞\":19, \"名詞\":20, \"形状詞\":21, \"空白\":22, \"感動詞\":23}\n\n self.feature1 = {\"*\":0, \"AA\":1, \"形状詞的\":2, \"一般\":3, \"括弧閉\":4, \"終助詞\":5, \"フィラー\":6, \"係助詞\":7, \"句点\":8,\n \"普通名詞\":9, \"数詞\":10, \"固有名詞\":11, \"準体助詞\":12, \"タリ\":13, \"括弧開\":14, \"読点\":15, \"形容詞的\":16,\n \"動詞的\":17, \"名詞的\":18, \"格助詞\":19, \"接続助詞\":20, \"助動詞語幹\":21, \"非自立可能\":22, \"文字\":23, \"副助詞\":24}\n\n self.feature2 = {\"*\":0, \"助数詞可能\":1, \"一般\":2, \"副詞可能\":3, \"人名\":4, \"サ変形状詞可能\":5, \"顔文字\":6,\n \"助数詞\":7, \"地名\":8, \"サ変可能\":9, \"形状詞可能\":10}\n\n self.feature3 = {\"*\":0, \"国\":1, \"名\":2, \"姓\":3, \"一般\":4}\n\n self.feature4 = {\"*\":0, \"サ行変格\":1, \"文語助動詞-ヌ\":2, \"文語下二段-サ行\":3, \"文語下二段-ラ行\":4, \"下一段-バ行\":5,\n \"下一段-サ行\":6, \"文語四段-タ行\":7, \"助動詞-ヌ\":8, \"文語サ行変格\":9, \"下一段-ザ行\":10, \"文語助動詞-タリ-完了\":11,\n \"文語助動詞-ゴトシ\":12, \"下一段-カ行\":13, \"助動詞-レル\":14, \"文語助動詞-ナリ-断定\":15, \"文語ラ行変格\":16,\n \"���語四段-ハ行\":17, \"下一段-ガ行\":18, \"形容詞\":19, \"五段-バ行\":20, \"下一段-ナ行\":21, \"助動詞-ラシイ\":22,\n \"文語助動詞-ズ\":23, \"助動詞-ナイ\":24, \"五段-サ行\":25, \"五段-タ行\":26, \"文語助動詞-ケリ\":27, \"助動詞-ダ\":28,\n \"文語上一段-ナ行\":29, \"文語四段-マ行\":30, \"上一段-マ行\":31, \"文語下二段-ダ行\":32, \"文語助動詞-キ\":33,\n \"文語上一段-マ行\":34, \"文語助動詞-ベシ\":35, \"文語助動詞-ナリ-伝聞\":36, \"助動詞-ナンダ\":37, \"上一段-バ行\":38,\n \"助動詞-ジャ\":39, \"文語形容詞-ク\":40, \"文語上二段-ダ行\":41, \"文語下二段-タ行\":42, \"文語助動詞-タリ-断定\":43,\n \"文語下二段-ハ行\":44, \"文語四段-ガ行\":45, \"文語下二段-マ行\":46, \"文語助動詞-リ\":47, \"無変化型\":48, \"助動詞-ヘン\":49,\n \"文語下二段-ナ行\":50, \"上一段-ア行\":51, \"上一段-ガ行\":52, \"助動詞-デス\":53, \"五段-カ行\":54, \"助動詞-タ\":55,\n \"上一段-ザ行\":56, \"助動詞-タイ\":57, \"カ行変格\":58, \"五段-ガ行\":59, \"五段-ナ行\":60, \"文語上二段-バ行\":61,\n \"助動詞-ヤス\":62, \"五段-ワア行\":63, \"上一段-ラ行\":64, \"文語助動詞-ム\":65, \"上一段-ナ行\":66, \"五段-マ行\":67,\n \"文語形容詞-シク\":68, \"五段-ラ行\":69, \"文語四段-ラ行\":70, \"下一段-ラ行\":71, \"文語四段-サ行\":72, \"文語四段-カ行\":73,\n \"文語助動詞-ラシ\":74, \"助動詞-ヤ\":75, \"文語下一段-カ行\":76, \"助動詞-マイ\":77, \"文語下二段-ガ行\":78, \"助動詞-マス\":79,\n \"文語助動詞-マジ\":80, \"文語カ行変格\":81, \"下一段-タ行\":82, \"下一段-ダ行\":83, \"上一段-カ行\":84, \"文語上二段-ハ行\":85,\n \"下一段-ハ行\":86, \"文語助動詞-ジ\":87, \"上一段-タ行\":88, \"下一段-マ行\":89, \"文語下二段-カ行\":90, \"文語下二段-ア行\":91,\n \"下一段-ア行\":92}\n\n self.feature5 = {\"*\":0, \"連用形-イ音便\":1, \"連体形-撥音便\":2, \"連用形-一般\":3, \"語幹-一般\":4, \"ク語法\":5, \"終止形-融合\":6,\n \"未然形-サ\":7, \"終止形-一般\":8, \"語幹-サ\":9, \"已然形-一般\":10, \"未然形-撥音便\":11, \"仮定形-一般\":12, \"連体形-一般\":13,\n \"連体形-省略\":14, \"未然形-補助\":15, \"連用形-ニ\":16, \"仮定形-融合\":17, \"終止形-促音便\":18, \"終止形-ウ音便\":19,\n \"未然形-一般\":20, \"連用形-促音便\":21, \"終止形-撥音便\":22, \"未然形-セ\":23, \"意志推量形\":24, \"命令形\":25, \"連用形-省略\":26,\n \"連用形-撥音便\":27, \"連用形-ウ音便\":28, \"連体形-補助\":29, \"連用形-融合\":30}\n\n self.em_fe0 = L.EmbedID(24, 5)\n self.em_fe1 = L.EmbedID(25, 5)\n self.em_fe2 = L.EmbedID(11, 5)\n self.em_fe3 = L.EmbedID(5, 5)\n self.em_fe4 = L.EmbedID(93, 5)\n self.em_fe5 = L.EmbedID(31, 5)\n\n def feature_to_df_by_embed(self, feature):\n feature0_id = self.feature0[feature[0]]\n feature1_id = self.feature1[feature[1]]\n feature2_id = self.feature2[feature[2]]\n feature3_id = self.feature3[feature[3]]\n feature4_id = self.feature4[feature[4]]\n feature5_id = self.feature5[feature[5]]\n feature_vec0 = self.em_fe0(np.array([feature0_id], dtype=np.int32)).data[0]\n if feature0_id == 0:\n feature_vec0 = np.zeros(5)\n feature_vec1 = self.em_fe1(np.array([feature1_id], dtype=np.int32)).data[0]\n if feature1_id == 0:\n feature_vec1 = np.zeros(5)\n feature_vec2 = self.em_fe2(np.array([feature2_id], dtype=np.int32)).data[0]\n if feature2_id == 0:\n feature_vec2 = np.zeros(5)\n feature_vec3 = self.em_fe3(np.array([feature3_id], dtype=np.int32)).data[0]\n if feature3_id == 0:\n feature_vec3 = np.zeros(5)\n feature_vec4 = self.em_fe4(np.array([feature4_id], dtype=np.int32)).data[0]\n if feature4_id == 0:\n feature_vec4 = np.zeros(5)\n feature_vec5 = self.em_fe5(np.array([feature5_id], dtype=np.int32)).data[0]\n if feature5_id == 0:\n feature_vec5 = np.zeros(5)\n\n feature_vec = np.concatenate((feature_vec0, feature_vec1, feature_vec2, feature_vec3, feature_vec4, feature_vec5))\n df = pd.DataFrame([feature_vec])\n df.columns = [f'feature_vec:::{i}' for i in range(feature_vec.size)]\n\n return df\n\ndef file_to_dataframe_list(file_path):\n df_list = []\n print(file_path, flush=True)\n for sentence in load_file(file_path):\n for df in sentence_find_verb(sentence):\n df_list.append(df)\n # df_list = reduction_dataframe(df_list)\n return df_list\n\ndef load_file(file_path):\n sentence = ''\n with open(file_path) as f:\n for line in f:\n if line[0] == '#':\n continue\n if line.strip() == 'EOS':\n yield sentence.strip()\n sentence = ''\n else:\n sentence += line\n\ndef check_id_in_sentence(sentence, case_id):\n for line in sentence.split('\\n'):\n tag_id = get_tag_id(line)\n if tag_id == case_id:\n return True\n return False\n\ndef sentence_find_verb(sentence):\n \"\"\"\n 動詞,形容詞,サ変名詞を対象\n \"\"\"\n word_number = 0 #何単語目に出現したか\n for i, line in enumerate(sentence.split('\\n')):\n if line[0] != '*':\n word_number += 1\n pred_type = get_type(line)\n if pred_type == 'pred' or pred_type=='noun':\n ga_case_id = get_ga_tag(line)\n o_case_id = get_o_tag(line)\n ni_case_id = get_ni_tag(line)\n if is_num(ga_case_id):\n if not check_id_in_sentence(sentence, ga_case_id):\n ga_case_id = 'inter'\n if is_num(o_case_id):\n if not check_id_in_sentence(sentence, o_case_id):\n o_case_id = 'inter'\n if is_num(ni_case_id):\n if not check_id_in_sentence(sentence, ni_case_id):\n ni_case_id = 'inter'\n yield sentence_to_vector(sentence, word_number, ga_case_id, o_case_id, ni_case_id)\n if line[0] == '*':\n continue\n\ndef feature_to_dataframe(feature):\n feature = feature.split(',')\n df = pd.DataFrame([feature])\n df.columns = [f'feature:{i}' for i in range(17)]\n df_ = feature_to_embed.feature_to_df_by_embed(feature)\n df = pd.merge(df, df_, left_index=True, right_index=True, how='outer')\n return df\n\ndef make_df_none():\n df_word_vector = word2vec.word_to_dataframe('')\n df_feature = feature_to_dataframe('*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*')\n df_none = pd.merge(df_word_vector, df_feature, left_index=True, right_index=True, how='outer')\n return df_none\ndef make_df_exo1():\n df_word_vector = word2vec.word_to_dataframe('exo1')\n df_feature = feature_to_dataframe('代名詞,*,*,*,*,*,ボク,僕,*,*,*,*,漢,*,*,*,*')\n df_exo1 = pd.merge(df_word_vector, df_feature, left_index=True, right_index=True, how='outer')\n return df_exo1\ndef make_df_exo2():\n df_word_vector = word2vec.word_to_dataframe('exo2')\n df_feature = feature_to_dataframe('代名詞,*,*,*,*,*,オマエ,御前,*,*,*,*,和,*,*,*,*')\n df_exo2 = pd.merge(df_word_vector, df_feature, left_index=True, right_index=True, how='outer')\n return df_exo2\ndef make_df_exog():\n df_word_vector = word2vec.word_to_dataframe('exog')\n df_feature = feature_to_dataframe('代名詞,*,*,*,*,*,コレ,此れ,*,*,*,*,和,*,*,*,*')\n df_exog = pd.merge(df_word_vector, df_feature, left_index=True, right_index=True, how='outer')\n return df_exog\n\ndef df_drop(df):\n for i in range(17):\n df = df.drop(f\"feature:{i}\", axis=1)\n df = df.drop('word', axis=1)\n return df\n\ndef sentence_to_vector(sentence, verb_number, ga_case_id, o_case_id, ni_case_id):\n df_none = make_df_none()\n df_exo1 = make_df_exo1()\n df_exo2 = make_df_exo2()\n df_exog = make_df_exog()\n df = pd.concat([df_none, df_exo1, df_exo2, df_exog])\n \n word_number = 0 #何単語目に出現したか\n phrase_count = 0 #文節のカウント\n count_head_word_number = 0 #文節ごとの単語のカウント(主辞判定のため)\n for i, line in enumerate(sentence.split('\\n')):\n if line[0] == '*':\n head_word_number = int(line.split()[3].split('/')[0])\n count_head_word_number = 0\n phrase_count += 1\n continue\n word_number += 1\n word, feature, tag = line.split('\\t')\n df_word_vector = word2vec.word_to_dataframe(word)\n df_feature = feature_to_dataframe(feature)\n df_ = pd.merge(df_word_vector, df_feature, left_index=True, right_index=True, how='outer')\n #その他の素性\n #形態素距離\n df_['形態素距離'] = abs(word_number-verb_number)\n #主辞\n if count_head_word_number == head_word_number:\n df_['主辞'] = 1\n count_head_word_number += 1\n #文節\n df_['文節'] = phrase_count\n #述語の場合はdepのタグ付けもいれる\n if word_number == verb_number:\n df_['is_verb'] = 1\n ga_dep_tag = get_ga_dep_tag(tag)\n df_['ga_dep_tag'] = ga_dep_tag\n o_dep_tag = get_o_dep_tag(tag)\n df_['o_dep_tag'] = o_dep_tag\n ni_dep_tag = get_ni_dep_tag(tag)\n df_['ni_dep_tag'] = ni_dep_tag\n \n #正解ラベルか確認して,正解を入れる.\n tag_id = get_tag_id(tag)\n if is_num(tag_id):\n if ga_case_id == tag_id:\n df_['ga_case'] = 1\n if o_case_id == tag_id:\n df_['o_case'] = 1\n if ni_case_id == tag_id:\n df_['ni_case'] = 1\n df = pd.concat([df, df_], ignore_index=True)\n\n if 'ga_case' not in df.keys():\n if ga_case_id == 'exo1':\n df.at[1, 'ga_case'] = 1\n elif ga_case_id == 'exo2':\n df.at[2, 'ga_case'] = 1\n elif ga_case_id == 'exog' or ga_case_id == 'inter':\n df.at[3, 'ga_case'] = 1\n else:\n df.at[0, 'ga_case'] = 1\n if 'o_case' not in df.keys():\n if o_case_id == 'exo1':\n df.at[1, 'o_case'] = 1\n elif o_case_id == 'exo2':\n df.at[2, 'o_case'] = 1\n elif o_case_id == 'exog' or o_case_id == 'inter':\n df.at[3, 'o_case'] = 1\n else:\n df.at[0, 'o_case'] = 1\n if 'ni_case' not in df.keys():\n if ni_case_id == 'exo1':\n df.at[1, 'ni_case'] = 1\n elif ni_case_id == 'exo2':\n df.at[2, 'ni_case'] = 1\n elif ni_case_id == 'exog' or ni_case_id == 'inter':\n df.at[3, 'ni_case'] = 1\n else:\n df.at[0, 'ni_case'] = 1\n # df = df_drop(df)\n df = df.fillna(0)\n return df\n\n# def reduction_dataframe(df_list):\n# reduction_df_list = []\n# for df in df_list:\n# df = df.fillna(0)\n# if df.iloc[0]['ga_case'] == 1 and df.iloc[0]['o_case'] == 1 and df.iloc[0]['ni_case'] == 1:\n# \"ガ格,ヲ格,ニ格がいずれもないものは,対象としない.ただし,1/10だけデータに入れる.\"\n# if random.randint(0, 9) == 0:\n# reduction_df_list.append(df)\n# else:\n# reduction_df_list.append(df)\n# return reduction_df_list\n\ndef main():\n for domain in domain_dict:\n print(f'start {domain}')\n r = Parallel(n_jobs=-1)([delayed(file_to_dataframe_list)(f'{directory}{domain}/{file}') for file in os.listdir(f'{directory}{domain}/')])\n dataset = []\n for df_list in r:\n dataset += df_list\n del r\n with open(f'./dataframe/dataframe_list_{domain}.pickle', 'wb') as f:\n pickle.dump(dataset, f)\n del dataset\n\nif __name__=='__main__':\n word2vec = Word2Vec(w2v_path)\n feature_to_embed = FeatureToEmbedID()\n main()\n","sub_path":"src/neural_net/preprocess/preprocess_for_BCCWJ.py","file_name":"preprocess_for_BCCWJ.py","file_ext":"py","file_size_in_byte":16642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"394176287","text":"\n\nfrom textwrap import dedent\n\ndef _pluralize(l):\n if len(l) == 0:\n return 'no partner assigned.'\n elif len(l) == 1:\n return str(l[0])\n elif len(l) == 2:\n return '%s and %s' % tuple(l)\n else:\n return ', '.join(l[:-1]) + ', and %s' % l[-1]\n\ndef _name(u):\n fn = csm_cslog.most_recent('_extra_info', [], u, {})\n if fn is None or 'name' not in fn:\n return u\n else:\n return '%s (%s)' % (fn['name'], u)\n\nif dopartners:\n uname = cs_user_info.get('username', 'None')\n\n section, group, members = csm_groups.get_group(\n globals(),\n cs_path_info,\n uname,\n )\n\n if members:\n members = [_name(i) for i in members if i != uname]\n message = 'You should work at table %s with %s.' % (group, _pluralize(members))\n else:\n message = 'You have not yet been assigned a partner for this lab.'\n\n partners_display = '''\\\n
    \n
    \n Partners: \n \n {message}\n \n
    \n
    \n '''.format(message=message)\n\n cs_content = dedent(partners_display) + cs_content\n\n\n","sub_path":"_cached/Users/stefanie/catsoop-courses/courses/2018-fall-6810-engineering-interactive-devices/__PLUGINS__/partners/post_load.py","file_name":"post_load.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"630681672","text":"import torch\nimport numpy as np\nimport utils.geom\nimport utils.basic\n# import utils.vox\nimport utils.samp\nimport utils.misc\nimport torch.nn.functional as F\nimport sklearn\n\nnp.set_printoptions(suppress=True, precision=6, threshold=2000)\n\ndef merge_rt_py(r, t):\n # r is 3 x 3\n # t is 3 or maybe 3 x 1\n t = np.reshape(t, [3, 1])\n rt = np.concatenate((r,t), axis=1)\n # rt is 3 x 4\n br = np.reshape(np.array([0,0,0,1], np.float32), [1, 4])\n # br is 1 x 4\n rt = np.concatenate((rt, br), axis=0)\n # rt is 4 x 4\n return rt\n\ndef split_rt_py(rt):\n r = rt[:3,:3]\n t = rt[:3,3]\n r = np.reshape(r, [3, 3])\n t = np.reshape(t, [3, 1])\n return r, t\n\ndef apply_4x4_py(rt, xyz):\n # rt is 4 x 4\n # xyz is N x 3\n r, t = split_rt_py(rt)\n xyz = np.transpose(xyz, [1, 0])\n # xyz is xyz1 x 3 x N\n xyz = np.dot(r, xyz)\n # xyz is xyz1 x 3 x N\n xyz = np.transpose(xyz, [1, 0])\n # xyz is xyz1 x N x 3\n t = np.reshape(t, [1, 3])\n xyz = xyz + t\n return xyz\n\ndef rigid_transform_3d(xyz_cam0, xyz_cam1, do_ransac=True):\n # inputs are N x 3\n xyz_cam0 = xyz_cam0.detach().cpu().numpy()\n xyz_cam1 = xyz_cam1.detach().cpu().numpy()\n cam1_T_cam0 = rigid_transform_3d_py(xyz_cam0, xyz_cam1, do_ransac=do_ransac)\n cam1_T_cam0 = torch.from_numpy(cam1_T_cam0).float().to('cuda')\n return cam1_T_cam0\n\ndef differentiable_rigid_transform_3d(xyz_cam0, xyz_cam1):\n # inputs are N x 3\n # xyz0 and xyz1 are each N x 3\n assert len(xyz_cam0) == len(xyz_cam1)\n\n N = xyz_cam0.shape[0] # total points\n assert(N > 8)\n\n # nPts = 8 # anything >3 is ok really\n # if N <= nPts:\n # print('N = %d; returning an identity mat' % N)\n # R = np.eye(3, dtype=np.float32)\n # t = np.zeros(3, dtype=np.float32)\n # cam1_T_cam0 = merge_rt_py(R, t)\n # else:\n \n cam1_T_cam0 = rigid_transform_3d_pt_helper(xyz_cam0, xyz_cam1)\n return cam1_T_cam0\n\n \n cam1_T_cam0 = rigid_transform_3d_pt(xyz_cam0, xyz_cam1, do_ransac=do_ransac)\n cam1_T_cam0 = torch.from_numpy(cam1_T_cam0).float().to('cuda')\n return cam1_T_cam0\n\ndef rigid_transform_3d_py_helper(xyz0, xyz1):\n assert len(xyz0) == len(xyz1)\n N = xyz0.shape[0] # total points\n if N > 3:\n centroid_xyz0 = np.mean(xyz0, axis=0)\n centroid_xyz1 = np.mean(xyz1, axis=0)\n # print('centroid_xyz0', centroid_xyz0)\n # print('centroid_xyz1', centroid_xyz1)\n\n # center the points\n xyz0 = xyz0 - np.tile(centroid_xyz0, (N, 1))\n xyz1 = xyz1 - np.tile(centroid_xyz1, (N, 1))\n\n H = np.dot(xyz0.T, xyz1)\n\n U, S, Vt = np.linalg.svd(H)\n\n R = np.dot(Vt.T, U.T)\n\n # special reflection case\n if np.linalg.det(R) < 0:\n Vt[2,:] *= -1\n R = np.dot(Vt.T, U.T)\n\n t = np.dot(-R, centroid_xyz0.T) + centroid_xyz1.T\n t = np.reshape(t, [3])\n else:\n print('too few points; returning identity')\n R = np.eye(3, dtype=np.float32)\n t = np.zeros(3, dtype=np.float32)\n rt = merge_rt_py(R, t)\n return rt\n\ndef rigid_transform_3d_pt_helper(xyz0, xyz1):\n assert len(xyz0) == len(xyz1)\n N = xyz0.shape[0] # total points\n assert(N > 3)\n centroid_xyz0 = torch.mean(xyz0, axis=0, keepdim=True)\n centroid_xyz1 = torch.mean(xyz1, axis=0, keepdim=True)\n\n # center the points\n xyz0 = xyz0 - centroid_xyz0.repeat(N, 1)\n xyz1 = xyz1 - centroid_xyz1.repeat(N, 1)\n\n H = torch.matmul(xyz0.transpose(0,1), xyz1)\n\n U, S, Vt = torch.svd(H)\n\n R = torch.matmul(Vt.transpose(0,1), U.transpose(0,1))\n\n # # special reflection case\n # if np.linalg.det(R) < 0:\n # Vt[2,:] *= -1\n # R = np.dot(Vt.transpose(0,1), U.transpose(0,1))\n\n t = torch.matmul(-R, centroid_xyz0.transpose(0,1)) + centroid_xyz1.transpose(0,1)\n t = t.reshape([3])\n\n rt = utils.geom.merge_rt_single(R, t)\n return rt\n\ndef rigid_transform_3d_py(xyz0, xyz1, do_ransac=True):\n # xyz0 and xyz1 are each N x 3\n assert len(xyz0) == len(xyz1)\n\n N = xyz0.shape[0] # total points\n\n nPts = 8 # anything >3 is ok really\n if N <= nPts:\n print('N = %d; returning an identity mat' % N)\n R = np.eye(3, dtype=np.float32)\n t = np.zeros(3, dtype=np.float32)\n rt = merge_rt_py(R, t)\n elif not do_ransac:\n rt = rigid_transform_3d_py_helper(xyz0, xyz1)\n else:\n # print('N = %d' % N)\n # print('doing ransac')\n rts = []\n errs = []\n ransac_steps = 256\n for step in list(range(ransac_steps)):\n assert(N > nPts) \n perm = np.random.permutation(N)\n cam1_T_cam0 = rigid_transform_3d_py_helper(xyz0[perm[:nPts]], xyz1[perm[:nPts]])\n # i got some errors in matmul when the arrays were too big, \n # so let's just use 1k points for the error \n perm = np.random.permutation(N)\n xyz1_prime = apply_4x4_py(cam1_T_cam0, xyz0[perm[:min([1000,N])]])\n xyz1_actual = xyz1[perm[:min([1000,N])]]\n err = np.mean(np.sum(np.abs(xyz1_prime-xyz1_actual), axis=1))\n rts.append(cam1_T_cam0)\n errs.append(err)\n ind = np.argmin(errs)\n rt = rts[ind]\n return rt\n\ndef compute_mem1_T_mem0_from_object_flow(flow_mem, mask_mem, occ_mem):\n B, C, Z, Y, X = list(flow_mem.shape)\n assert(C==3)\n mem1_T_mem0 = utils.geom.eye_4x4(B)\n\n xyz_mem0 = utils.basic.gridcloud3d(B, Z, Y, X, norm=False)\n \n for b in list(range(B)):\n # i think there is a way to parallelize the where/gather but it is beyond me right now\n occ = occ_mem[b]\n mask = mask_mem[b]\n flow = flow_mem[b]\n xyz0 = xyz_mem0[b]\n # cam_T_obj = camR_T_obj[b]\n # mem_T_cam = mem_T_ref[b]\n\n flow = flow.reshape(3, -1).permute(1, 0)\n # flow is -1 x 3\n inds = torch.where((occ*mask).reshape(-1) > 0.5)\n # inds is ?\n flow = flow[inds]\n\n xyz0 = xyz0[inds]\n xyz1 = xyz0 + flow\n\n mem1_T_mem0_ = rigid_transform_3d(xyz0, xyz1)\n # this is 4 x 4 \n mem1_T_mem0[b] = mem1_T_mem0_\n\n return mem1_T_mem0\n\ndef compute_mem1_T_mem0_from_object_flow(flow_mem, mask_mem, occ_mem):\n B, C, Z, Y, X = list(flow_mem.shape)\n assert(C==3)\n mem1_T_mem0 = utils.geom.eye_4x4(B)\n\n xyz_mem0 = utils.basic.gridcloud3d(B, Z, Y, X, norm=False)\n \n for b in list(range(B)):\n # i think there is a way to parallelize the where/gather but it is beyond me right now\n occ = occ_mem[b]\n mask = mask_mem[b]\n flow = flow_mem[b]\n xyz0 = xyz_mem0[b]\n # cam_T_obj = camR_T_obj[b]\n # mem_T_cam = mem_T_ref[b]\n\n flow = flow.reshape(3, -1).permute(1, 0)\n # flow is -1 x 3\n inds = torch.where((occ*mask).reshape(-1) > 0.5)\n # inds is ?\n flow = flow[inds]\n\n xyz0 = xyz0[inds]\n xyz1 = xyz0 + flow\n\n mem1_T_mem0_ = rigid_transform_3d(xyz0, xyz1)\n # this is 4 x 4 \n mem1_T_mem0[b] = mem1_T_mem0_\n\n return mem1_T_mem0\n\n\ndef track_via_chained_flows(\n lrt_camIs_g,\n mask_mem0,\n model,\n occ_mems,\n occ_mems_half,\n unp_mems,\n summ_writer,\n include_image_summs=False,\n use_live_nets=False,\n):\n B, S, _, Z, Y, X = list(occ_mems.shape)\n B, S, _, Z2, Y2, X2 = list(occ_mems_half.shape)\n \n flow_mem0 = torch.zeros(B, 3, Z2, Y2, X2, dtype=torch.float32, device=torch.device('cuda'))\n cam0_T_camI = utils.geom.eye_4x4(B)\n\n obj_lengths, cams_T_obj0 = utils.geom.split_lrtlist(lrt_camIs_g)\n # this is B x S x 4 x 4\n\n cam0_T_obj = cams_T_obj0[:,0]\n obj_length = obj_lengths[:,0]\n\n occ_mem0 = occ_mems_half[:,0]\n\n input_mems = torch.cat([occ_mems, occ_mems*unp_mems], dim=2)\n\n mem_T_cam = utils.vox.get_mem_T_ref(B, Z2, Y2, X2)\n cam_T_mem = utils.vox.get_ref_T_mem(B, Z2, Y2, X2)\n\n lrt_camIs_e = torch.zeros_like(lrt_camIs_g)\n lrt_camIs_e[:,0] = lrt_camIs_g[:,0] # init with gt box on frame0\n\n all_ious = []\n for s in list(range(1, S)):\n input_mem0 = input_mems[:,0]\n input_memI = input_mems[:,s]\n\n if use_live_nets:\n\n use_rigid_warp = True\n if use_rigid_warp:\n xyz_camI = model.xyz_camX0s[:,s]\n xyz_camI = utils.geom.apply_4x4(cam0_T_camI, xyz_camI)\n occ_memI = utils.vox.voxelize_xyz(xyz_camI, Z, Y, X)\n unp_memI = unp_mems[:,s]\n unp_memI = utils.vox.apply_4x4_to_vox(cam0_T_camI, unp_memI, already_mem=False, binary_feat=False)\n input_memI = torch.cat([occ_memI, occ_memI*unp_memI], dim=1)\n # input_memI = utils.vox.apply_4x4_to_vox(cam0_T_camI, input_memI, already_mem=False, binary_feat=False)\n else:\n input_memI = utils.samp.backwarp_using_3d_flow(input_memI, F.interpolate(flow_mem0, scale_factor=2, mode='trilinear'))\n \n featnet_output_mem0, _, _ = model.featnet(input_mem0, None, None)\n featnet_output_memI, _, _ = model.featnet(input_memI, None, None)\n _, residual_flow_mem0 = model.flownet(\n featnet_output_mem0,\n featnet_output_memI,\n torch.zeros([B, 3, Z2, Y2, X2]).float().cuda(),\n occ_mem0, \n False,\n None)\n else:\n featnet_output_mem0 = model.feat_net.infer_pt(input_mem0)\n featnet_output_memI = model.feat_net.infer_pt(input_memI)\n featnet_output_memI = utils.samp.backwarp_using_3d_flow(featnet_output_memI, flow_mem0)\n residual_flow_mem0 = model.flow_net.infer_pt([featnet_output_mem0,\n featnet_output_memI])\n\n # if use_live_nets:\n # _, residual_flow_mem0 = model.flownet(\n # featnet_output_mem0,\n # featnet_output_memI,\n # torch.zeros([B, 3, Z2, Y2, X2]).float().cuda(),\n # occ_mem0, \n # False,\n # summ_writer)\n # else:\n # residual_flow_mem0 = model.flow_net.infer_pt([featnet_output_mem0,\n # featnet_output_memI])\n\n flow_mem0 = flow_mem0 + residual_flow_mem0\n\n if include_image_summs:\n summ_writer.summ_feats('3d_feats/featnet_inputs_%02d' % s, [input_mem0, input_memI], pca=True)\n summ_writer.summ_feats('3d_feats/featnet_outputs_warped_%02d' % s, [featnet_output_mem0, featnet_output_memI], pca=True)\n summ_writer.summ_3d_flow('flow/residual_flow_mem0_%02d' % s, residual_flow_mem0, clip=0.0)\n summ_writer.summ_3d_flow('flow/residual_masked_flow_mem0_%02d' % s, residual_flow_mem0*mask_mem0, clip=0.0)\n summ_writer.summ_3d_flow('flow/flow_mem0_%02d' % s, flow_mem0, clip=0.0)\n\n # compute the rigid motion of the object; we will use this for eval\n memI_T_mem0 = compute_mem1_T_mem0_from_object_flow(\n flow_mem0, mask_mem0, occ_mem0)\n mem0_T_memI = utils.geom.safe_inverse(memI_T_mem0)\n cam0_T_camI = utils.basic.matmul3(cam_T_mem, mem0_T_memI, mem_T_cam)\n\n # eval\n camI_T_obj = utils.basic.matmul4(cam_T_mem, memI_T_mem0, mem_T_cam, cam0_T_obj)\n # this is B x 4 x 4\n\n lrt_camIs_e[:,s] = utils.geom.merge_lrt(obj_length, camI_T_obj)\n ious = utils.geom.get_iou_from_corresponded_lrtlists(lrt_camIs_e[:,s:s+1],\n lrt_camIs_g[:,s:s+1])\n all_ious.append(ious)\n summ_writer.summ_scalar('box/mean_iou_%02d' % s, torch.mean(ious).cpu().item())\n\n # lrt_camIs_e is B x S x 19\n # this is B x S x 1 x 19\n return lrt_camIs_e, all_ious\n\ndef cross_corr_with_template(search_region, template):\n B, C, ZZ, ZY, ZX = list(template.shape)\n B2, C2, Z, Y, X = list(search_region.shape)\n assert(B==B2)\n assert(C==C2)\n corr = []\n\n Z_new = Z-ZZ+1\n Y_new = Y-ZY+1\n X_new = X-ZX+1\n corr = torch.zeros([B, 1, Z_new, Y_new, X_new]).float().cuda()\n\n # this loop over batch is ~2x faster than the grouped version\n for b in list(range(B)):\n search_region_b = search_region[b:b+1]\n template_b = template[b:b+1]\n corr[b] = F.conv3d(search_region_b, template_b).squeeze(0)\n\n # grouped version, for reference:\n # corr = F.conv3d(search_region.view(1, B*C, Z, Y, X), template, groups=B) # fast valid conv\n \n # adjust the scale of responses, for stability early on\n corr = 0.001 * corr\n\n # since we did valid conv (which is smart), the corr map is offset from the search region\n # so we need to offset the xyz of the answer\n # _, _, Z_new, Y_new, X_new = list(corr.shape)\n Z_clipped = (Z - Z_new)/2.0\n Y_clipped = (Y - Y_new)/2.0\n X_clipped = (X - X_new)/2.0\n xyz_offset = np.array([X_clipped, Y_clipped, Z_clipped], np.float32).reshape([1, 3])\n xyz_offset = torch.from_numpy(xyz_offset).float().to('cuda')\n return corr, xyz_offset\n\ndef cross_corr_with_templates(search_region, templates):\n B, C, Z, Y, X = list(search_region.shape)\n B2, N, C2, ZZ, ZY, ZX = list(templates.shape)\n assert(B==B2)\n assert(C==C2)\n\n Z_new = Z-ZZ+1\n Y_new = Y-ZY+1\n X_new = X-ZX+1\n corr = torch.zeros([B, N, Z_new, Y_new, X_new]).float().cuda()\n\n # this loop over batch is ~2x faster than the grouped version\n for b in list(range(B)):\n search_region_b = search_region[b:b+1]\n for n in list(range(N)):\n template_b = templates[b:b+1,n]\n corr[b,n] = F.conv3d(search_region_b, template_b).squeeze(0)\n\n # grouped version, for reference:\n # corr = F.conv3d(search_region.view(1, B*C, Z, Y, X), template, groups=B) # fast valid conv\n \n # adjust the scale of responses, for stability early on\n corr = 0.001 * corr\n\n # since we did valid conv (which is smart), the corr map is offset from the search region\n # so we need to offset the xyz of the answer\n # _, _, Z_new, Y_new, X_new = list(corr.shape)\n Z_clipped = (Z - Z_new)/2.0\n Y_clipped = (Y - Y_new)/2.0\n X_clipped = (X - X_new)/2.0\n xyz_offset = np.array([X_clipped, Y_clipped, Z_clipped], np.float32).reshape([1, 3])\n xyz_offset = torch.from_numpy(xyz_offset).float().to('cuda')\n return corr, xyz_offset\n\ndef track_via_inner_products(lrt_camIs_g, mask_mems, feat_mems, vox_util, mask_boxes=False, summ_writer=None):\n B, S, feat3d_dim, Z, Y, X = list(feat_mems.shape)\n\n feat_vecs = feat_mems.view(B, S, feat3d_dim, -1)\n # this is B x S x C x huge\n\n feat0_vec = feat_vecs[:,0]\n # this is B x C x huge\n feat0_vec = feat0_vec.permute(0, 2, 1)\n # this is B x huge x C\n\n obj_mask0_vec = mask_mems[:,0].reshape(B, -1).round()\n # this is B x huge\n\n orig_xyz = utils.basic.gridcloud3d(B, Z, Y, X)\n # this is B x huge x 3\n\n obj_lengths, cams_T_obj0 = utils.geom.split_lrtlist(lrt_camIs_g)\n obj_length = obj_lengths[:,0]\n # this is B x S x 4 x 4\n\n # this is B x S x 4 x 4\n cam0_T_obj = cams_T_obj0[:,0]\n\n lrt_camIs_e = torch.zeros_like(lrt_camIs_g)\n # we will fill this up\n\n mask_e_mems = torch.zeros_like(mask_mems)\n mask_e_mems_masked = torch.zeros_like(mask_mems)\n\n mem_T_cam = vox_util.get_mem_T_ref(B, Z, Y, X)\n cam_T_mem = vox_util.get_ref_T_mem(B, Z, Y, X)\n\n ious = torch.zeros([B, S]).float().cuda()\n point_counts = np.zeros([B, S])\n for s in list(range(S)):\n feat_vec = feat_vecs[:,s]\n feat_vec = feat_vec.permute(0, 2, 1)\n # B x huge x C\n\n memI_T_mem0 = utils.geom.eye_4x4(B)\n # we will fill this up\n\n # Use ground truth box to mask\n if s == 0:\n lrt = lrt_camIs_g[:,0].unsqueeze(1)\n # Use predicted box to mask\n else:\n lrt = lrt_camIs_e[:,s-1].unsqueeze(1)\n\n # Equal box length\n lrt[:,:,:3] = torch.ones_like(lrt[:,:,:3])*10\n\n # Remove rotation\n transform = lrt[:,:,3:].reshape(B, 1, 4, 4)\n transform[:,:,:3,:3] = torch.eye(3).unsqueeze(0).unsqueeze(0)\n transform = transform.reshape(B,-1)\n\n lrt[:,:,3:] = transform\n\n box_mask = vox_util.assemble_padded_obj_masklist(lrt, torch.ones(1,1).cuda(), Z, Y, X)\n\n # to simplify the impl, we will iterate over the batchmin\n for b in list(range(B)):\n feat_vec_b = feat_vec[b]\n feat0_vec_b = feat0_vec[b]\n obj_mask0_vec_b = obj_mask0_vec[b]\n orig_xyz_b = orig_xyz[b]\n # these are huge x C\n\n obj_inds_b = torch.where(obj_mask0_vec_b > 0)\n obj_vec_b = feat0_vec_b[obj_inds_b]\n xyz0 = orig_xyz_b[obj_inds_b]\n # these are med x C\n\n obj_vec_b = obj_vec_b.permute(1, 0)\n # this is is C x med\n\n corr_b = torch.matmul(feat_vec_b, obj_vec_b)\n # this is huge x med\n\n heat_b = corr_b.permute(1, 0).reshape(-1, 1, Z, Y, X)\n # this is med x 1 x Z4 x Y4 x X4\n\n \n # Mask by box to restrict area\n if mask_boxes:\n \n # Vanilla heatmap\n if summ_writer != None:\n heat_map = heat_b.max(0)[0]\n summ_writer.summ_feat(\"heatmap/vanilla\", heat_map.unsqueeze(0), pca=False)\n mask_e_mems[b,s] = heat_map\n \n box_mask = box_mask.squeeze(0).repeat(heat_b.shape[0],1,1,1,1)\n heat_b = heat_b*box_mask\n \n # Masked heatmap\n if summ_writer != None:\n heat_map = heat_b.max(0)[0]\n mask_e_mems_masked[b,s] = heat_map\n\n summ_writer.summ_feat(\"heatmap/masked\", heat_map.unsqueeze(0), pca=False)\n \n \n # for numerical stability, we sub the max, and mult by the resolution\n heat_b_ = heat_b.reshape(-1, Z*Y*X)\n heat_b_max = (torch.max(heat_b_, dim=1).values).reshape(-1, 1, 1, 1, 1)\n heat_b = heat_b - heat_b_max\n heat_b = heat_b * float(len(heat_b[0].reshape(-1)))\n\n xyzI = utils.basic.argmax3d(heat_b*float(Z*10), hard=False, stack=True)\n # this is med x 3\n memI_T_mem0[b] = rigid_transform_3d(xyz0, xyzI)\n\n # record #points, since ransac depends on this\n point_counts[b, s] = len(xyz0)\n # done stepping through batch\n\n mem0_T_memI = utils.geom.safe_inverse(memI_T_mem0)\n cam0_T_camI = utils.basic.matmul3(cam_T_mem, mem0_T_memI, mem_T_cam)\n\n # eval\n camI_T_obj = utils.basic.matmul4(cam_T_mem, memI_T_mem0, mem_T_cam, cam0_T_obj)\n # this is B x 4 x 4\n lrt_camIs_e[:,s] = utils.geom.merge_lrt(obj_length, camI_T_obj)\n ious[:,s] = utils.geom.get_iou_from_corresponded_lrtlists(lrt_camIs_e[:,s:s+1], lrt_camIs_g[:,s:s+1]).squeeze(1)\n\n if summ_writer != None:\n summ_writer.summ_feats('heatmap/mask_e_memX0s', torch.unbind(mask_e_mems, dim=1), pca=False)\n summ_writer.summ_feats('heatmap/mask_e_memX0s_masked', torch.unbind(mask_e_mems_masked, dim=1), pca=False)\n\n return lrt_camIs_e, point_counts, ious\n\n \ndef convert_corr_to_xyz(corr, xyz_offset, hard=True):\n # corr is B x 1 x Z x Y x X\n # xyz_offset is 1 x 3\n peak_z, peak_y, peak_x = utils.basic.argmax3d(corr, hard=hard)\n # these are B\n peak_xyz_corr = torch.stack([peak_x, peak_y, peak_z], dim=1)\n # this is B x 3, and in corr coords\n peak_xyz_search = xyz_offset + peak_xyz_corr\n # this is B x 3, and in search coords\n return peak_xyz_search\n\ndef convert_corrlist_to_xyzr(corrlist, radlist, xyz_offset, hard=True):\n # corrlist is a list of N different B x Z x Y x X tensors\n # radlist is N angles in radians\n # xyz_offset is 1 x 3\n corrcat = torch.stack(corrlist, dim=1)\n # this is B x N x Z x Y x X\n radcat = torch.from_numpy(np.array(radlist).astype(np.float32)).cuda()\n radcat = radcat.reshape(-1)\n # this is N\n peak_r, peak_z, peak_y, peak_x = utils.basic.argmax3dr(corrcat, radcat, hard=hard)\n # these are B\n peak_xyz_corr = torch.stack([peak_x, peak_y, peak_z], dim=1)\n # this is B x 3, and in corr coords\n peak_xyz_search = xyz_offset + peak_xyz_corr\n # this is B x 3, and in search coords\n return peak_r, peak_xyz_search\n\ndef convert_corrs_to_xyzr(corrcat, radcat, xyz_offset, hard=True, grid=None):\n # corrcat is B x N x Z x Y x X tensors\n # radcat is N\n # xyz_offset is 1 x 3\n # if grid is None we'll compute it during the argmax\n peak_r, peak_z, peak_y, peak_x = utils.basic.argmax3dr(corrcat, radcat, hard=hard, grid=grid)\n # these are B\n peak_xyz_corr = torch.stack([peak_x, peak_y, peak_z], dim=1)\n # this is B x 3, and in corr coords\n peak_xyz_search = xyz_offset + peak_xyz_corr\n # this is B x 3, and in search coords\n return peak_r, peak_xyz_search\n\ndef remask_via_inner_products(lrt_camIs_g, mask_mems, feat_mems, vox_util, mask_distance=False, summ_writer=None):\n B, S, feat3d_dim, Z, Y, X = list(feat_mems.shape)\n\n mask = mask_mems[:,0]\n distance_masks = torch.zeros_like(mask_mems)\n \n feat_vecs = feat_mems.view(B, S, feat3d_dim, -1)\n # this is B x S x C x huge\n\n feat0_vec = feat_vecs[:,0]\n # this is B x C x huge\n feat0_vec = feat0_vec.permute(0, 2, 1)\n # this is B x huge x C\n \n obj_mask0_vec = mask_mems[:,0].reshape(B, -1).round()\n # this is B x huge\n \n orig_xyz = utils.basic.gridcloud3d(B, Z, Y, X)\n # this is B x huge x 3\n \n obj_lengths, cams_T_obj0 = utils.geom.split_lrtlist(lrt_camIs_g)\n obj_length = obj_lengths[:,0]\n # this is B x S x 4 x 4\n \n # this is B x S x 4 x 4\n cam0_T_obj = cams_T_obj0[:,0]\n \n lrt_camIs_e = torch.zeros_like(lrt_camIs_g)\n # we will fill this up\n\n mem_T_cam = vox_util.get_mem_T_ref(B, Z, Y, X)\n cam_T_mem = vox_util.get_ref_T_mem(B, Z, Y, X)\n\n mask_e_mems = torch.zeros_like(mask_mems)\n mask_e_mems_thres = torch.zeros_like(mask_mems)\n mask_e_mems_hard = torch.zeros_like(mask_mems)\n mask_e_mems_spatial = torch.zeros_like(mask_mems)\n\n ious = torch.zeros([B, S]).float().cuda()\n ious_hard = torch.zeros([B, S]).float().cuda()\n ious_spatial = torch.zeros([B, S]).float().cuda()\n\n point_counts = np.zeros([B, S])\n rough_centroids_mem = torch.zeros(B, S, 3).float().cuda()\n for s in list(range(S)):\n feat_vec = feat_vecs[:,s]\n feat_vec = feat_vec.permute(0, 2, 1)\n # B x huge x C\n\n memI_T_mem0 = utils.geom.eye_4x4(B)\n # we will fill this up\n # to simplify the impl, we will iterate over the batchmin\n \n for b in list(range(B)):\n # Expand mask\n # Code for growing a distance constraint mask\n if s == 0:\n distance_mask = mask_mems[b,s]\n distance_masks[b,s] = distance_mask\n else:\n distance_mask = torch.nn.functional.conv3d(distance_masks[b,s-1].unsqueeze(0), torch.ones(1,1,3,3,3).cuda(), padding=1)\n distance_mask = (distance_mask > 0).float()\n distance_masks[b,s] = distance_mask\n\n distance_mask = distance_mask.reshape(X*Y*Z)\n\n feat_vec_b = feat_vec[b]\n feat0_vec_b = feat0_vec[b]\n obj_mask0_vec_b = obj_mask0_vec[b]\n orig_xyz_b = orig_xyz[b]\n # these are huge x C\n \n obj_inds_b = torch.where(obj_mask0_vec_b > 0)\n obj_vec_b = feat0_vec_b[obj_inds_b]\n xyz0 = orig_xyz_b[obj_inds_b]\n # these are med x C\n \n obj_vec_b = obj_vec_b.permute(1, 0)\n # this is is C x med\n \n # Calculate similarities\n similarity_b = torch.exp(torch.matmul(feat_vec_b, obj_vec_b))\n \n # Remove entries which could never happen\n if mask_distance == True:\n similarity_b = torch.mul(distance_mask.repeat(similarity_b.shape[1],1).permute(1,0),similarity_b)\n \n # calculate attention\n similarity_b = similarity_b/torch.sum(similarity_b, dim=0, keepdim=True) \n \n num_mask_channels = similarity_b.shape[1]\n \n # Calculate hard attention\n similarity_argmax = similarity_b.max(0)[1]\n hard_attention = torch.zeros_like(similarity_b)\n \n for i in range(num_mask_channels):\n hard_attention[similarity_argmax[i], i] = 1\n \n # Calculate positional average attention\n spatial_attention = hard_attention.permute(1,0)\n\n grid = utils.basic.gridcloud3d(1,Z,Y,X)\n \n pos_average = torch.zeros(3)\n \n spatial_attention_mask = torch.zeros(Z,Y,X)\n for i in range(num_mask_channels):\n weighted_grid = torch.mul(grid.squeeze(0), spatial_attention[i].unsqueeze(1))\n grid_average = torch.sum(weighted_grid, dim=0)\n grid_average = torch.round(grid_average)\n spatial_attention_mask[list(grid_average.long())] = 1\n #pos_average = pos_average + grid_average\n #import ipdb; ipdb.set_trace()\n\n #pos_average = pos_average/num_mask_channels\n #import ipdb; ipdb.set_trace()\n\n # this is huge x med normalized\n \n obj_mask0_vec_b = obj_mask0_vec[b]\n values = obj_mask0_vec_b[obj_inds_b].unsqueeze(1)\n #this is med x C\n\n # Propagated values are 1\n mask_e_mem = torch.matmul(similarity_b,values)\n mask_e_mem_hard = torch.matmul(hard_attention,values)\n # this is huge x 1\n \n # Threshold probabilities to be 1 close to the max\n mask_e_mem_t = (mask_e_mem > (mask_e_mem.mean()*0.3 + mask_e_mem.max()*0.7)).float()\n # this is huge x 1\n\n # Constrain to search region\n #mask_e_mem = torch.mul(distance_mask,mask_e_mem.reshape(-1))\n\n mask_e_mems[b,s] = mask_e_mem.reshape(1,Z,Y,X)\n mask_e_mems_thres[b,s] = mask_e_mem_t.reshape(1,Z,Y,X)\n mask_e_mems_hard[b,s] = mask_e_mem_hard.reshape(1,Z,Y,X)\n mask_e_mems_spatial[b,s] = spatial_attention_mask.reshape(1,Z,Y,X)\n\n set_A = mask_mems[b,s].reshape(Z*Y*X).bool()\n set_B = mask_e_mem_t.reshape(Z*Y*X).bool()\n\n iou = sklearn.metrics.jaccard_score(set_A.bool().cpu().data.numpy(), set_B.bool().cpu().data.numpy(), average='binary')\n ious[b,s] = iou\n\n iou_hard = sklearn.metrics.jaccard_score(mask_mems[b,s].reshape(Z*Y*X).bool().bool().cpu().data.numpy(), mask_e_mem_hard.reshape(Z*Y*X).bool().cpu().data.numpy(), average='binary') \n ious_hard[b,s] = iou_hard\n\n iou_spatial = sklearn.metrics.jaccard_score(mask_mems[b,s].reshape(Z*Y*X).bool().bool().cpu().data.numpy(), spatial_attention_mask.reshape(Z*Y*X).bool().cpu().data.numpy(), average='binary') \n ious_spatial[b,s] = iou_spatial\n\n\n # Visualization Logs\n if summ_writer != None:\n summ_writer.summ_feats('track/mask_e_memX0s', torch.unbind(mask_e_mems, dim=1), pca=False)\n summ_writer.summ_feats('track/mask_e_memX0s_t', torch.unbind(mask_e_mems_thres, dim=1), pca=False)\n summ_writer.summ_feats('track/mask_e_memX0s_h', torch.unbind(mask_e_mems_hard, dim=1), pca=False)\n summ_writer.summ_feats('track/mask_e_memX0s_s', torch.unbind(mask_e_mems_spatial, dim=1), pca=False)\n\n for s in range(S):\n summ_writer.summ_scalar('track/mean_iou_hard_%02d' % s, torch.mean(ious_hard[:,s]).cpu().item())\n summ_writer.summ_scalar('track/mean_iou_spatial_%02d' % s, torch.mean(ious_spatial[:,s]).cpu().item())\n\n return ious\n \n","sub_path":"models/replica/utils/track.py","file_name":"track.py","file_ext":"py","file_size_in_byte":28008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"592321920","text":"from unittest import TestCase\n\nfrom ..mixin import ElasticMixin, ESMapping, ESProp\n\n\ndef rgb_to_hex(rgb):\n return ('#' + ('%02x' * 3)) % rgb\n\n\nclass ESColor(ESProp):\n def __init__(self, name, *args, **kwargs):\n ESProp.__init__(self, name, *args, filter=rgb_to_hex, **kwargs)\n\n\nclass Thing(object):\n def __init__(self, id, foreground, child=None):\n self.id = id\n self.foreground = foreground\n self.child = child\n\n\nclass TestMixin(TestCase):\n\n def test_custom_prop(self):\n mapping = ESColor('foreground')\n\n obj = Thing(id=42, foreground=(60, 40, 30))\n doc = mapping(obj)\n\n self.assertEqual(doc, '#3c281e')\n\n def test_elastic_mixin_no_mapping(self):\n class Foo(ElasticMixin):\n pass\n\n with self.assertRaises(NotImplementedError):\n Foo.elastic_mapping()\n\n def test_nested_mappings(self):\n mapping = ESMapping(\n analyzer='lowercase',\n properties=ESMapping(\n ESColor('foreground'),\n child=ESMapping(\n analyzer='lowercase',\n properties=ESMapping(\n ESColor('foreground')))))\n\n thing1 = Thing(id=1,\n foreground=(40, 20, 27))\n thing2 = Thing(id=2,\n foreground=(37, 88, 19),\n child=thing1)\n\n doc = mapping(thing2)\n self.assertEqual(doc['_id'], 2)\n self.assertEqual(doc['child']['_id'], 1)\n\n def test_nested_mappings_dict(self):\n mapping = ESMapping(\n analyzer='lowercase',\n properties=ESMapping(\n ESColor('foreground'),\n child=dict(\n analyzer='lowercase',\n properties=ESMapping(\n ESColor('foreground')))))\n\n thing1 = Thing(id=1,\n foreground=(40, 20, 27))\n thing2 = Thing(id=2,\n foreground=(37, 88, 19),\n child=thing1)\n\n doc = mapping(thing2)\n self.assertEqual(doc['_id'], 2)\n self.assertEqual(doc['child']['_id'], 1)\n","sub_path":"pyramid_es/tests/test_mixin.py","file_name":"test_mixin.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"6782968","text":"\"\"\"\r\nCalculate true magnitudes for all standard stars\r\nPlot against catalogue magnitudes to check calibration\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\n\r\nFILTERS = {'B':0, 'V':1, 'R':2, 'I':3}\r\nSRETLIF = {0:'B', 1:'V', 2:'R', 3:'I'}\r\n\r\n# read zero point magnitudes in\r\nZPopen = open('rezero_vals.csv', 'r')\r\nZPreader = csv.reader(ZPopen)\r\n\r\nnext(ZPreader)\r\nBzp, Vzp, Rzp, Izp = next(ZPreader)\r\n\r\nzeropoints = [Bzp, Vzp, Rzp, Izp]\r\nZPopen.close()\r\n\r\nwith open('colour_term.dat', 'r') as fin:\r\n line = fin.readline().split(',')\r\ncol_grad = float(line[0])\r\ncol_int = float(line[1])\r\n\r\n# create catalogue and value lists for each filter\r\nBcat = []\r\nBval = []\r\nBavg = []\r\nVcat = []\r\nVval = []\r\nVavg = []\r\nRcat = []\r\nRval = []\r\nRavg = []\r\nIcat = []\r\nIval = []\r\nIavg = []\r\ncats = [Bcat, Vcat, Rcat, Icat]\r\nvals = [Bval, Vval, Rval, Ival]\r\n#avgs = [Bavg, Vavg, Ravg, Iavg]\r\n\r\nINGopen = open('ing_standards.csv', 'r')\r\nINGread = csv.reader(INGopen)\r\nnext(INGread)\r\n\r\nINGdict = {}\r\nfor line in INGread:\r\n INGdict[line[-1]] = line[0:-1]\r\nINGopen.close()\r\n\r\nmdopen = open('median_aamags.csv', 'r')\r\nmdread = csv.reader(mdopen)\r\n# skip headers\r\nnext(mdread)\r\n\r\nfor line in mdread:\r\n for i in range(0, 4):\r\n # read measured magnitude CORRECTED FOR colour term\r\n if i == 1:\r\n vals[i].append(float(line[i+1]) + float(zeropoints[i]) + col_int + col_grad * (float(line[2]) - float(line[4])))\r\n else:\r\n vals[i].append(float(line[i+1]) + float(zeropoints[i]))\r\n # same for weighted average values\r\n # avgs[i].append(float(line[2i + 4]))\r\n # read catalogue values\r\n cats[i].append(INGdict[line[0].replace('-','_')][i])\r\n\r\nline = [9,15]\r\n\r\nfor j in range(0,4):\r\n fig = plt.figure()\r\n plt.plot(cats[j], vals[j], \"o\", color = 'red')\r\n #plt.plot(cats[j], avgs[j], \"o\", color = 'green')\r\n plt.plot(line,line)\r\n plt.xlabel('catalogue mag')\r\n plt.ylabel('observed mag')\r\n plt.title(SRETLIF[j] + ' data')\r\n plt.show()\r\n\r\nprint('All calibration figures shown. Exiting...')","sub_path":"stdMagcheck.py","file_name":"stdMagcheck.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"510724885","text":"import heapq\r\n\r\n\r\ndef celebrity(in_file):\r\n try:\r\n assert not in_file == ''\r\n except AssertionError:\r\n print('Blank file name detected!')\r\n return False\r\n with open(in_file) as inf:\r\n values = inf.readline().split() # Read the first line to get N and k values\r\n n = int(values[0])\r\n k = int(values[1])\r\n\r\n heap = [] # Initialise the heap\r\n\r\n # This section takes O(N*log(k)) time\r\n id_num = 1 # Initialise the ID number\r\n for line in inf:\r\n if len(heap) < k: # If the number of items on the heap is smaller than the desired amount, always push\r\n heapq.heappush(heap, (int(line), id_num))\r\n id_num += 1\r\n else:\r\n # If the heap is full, check whether the current element is bigger than the smallest on the heap.\r\n # If it is, push it and pop the smallest. Otherwise, move on.\r\n if int(line) > heap[0][0]:\r\n popped = heapq.heapreplace(heap, (int(line), id_num))\r\n # If the most recently popped item has the same value as the new min and a lower ID,\r\n # put the popped item back.\r\n if popped[0] == heap[0][0] and popped[1] < heap[0][1]:\r\n heap[0] = popped\r\n id_num += 1\r\n else:\r\n id_num += 1\r\n\r\n # heapq.replace pushes an element and pops the smallest element. Pushing an element always takes\r\n # constant time. Popping retrieves the smallest element off the heap (constant time) and reshuffles the\r\n # tree (logarithmic time, as it is dependent on the height of the tree, which is log(size)).\r\n\r\n print(heap)\r\n\r\n\r\n # Pop all the elements off the heap and store them (this list will be in ascending order) - O(k*log(k))\r\n result = [heapq.heappop(heap) for i in range(k)]\r\n # print(result)\r\n\r\n # This takes O(k) time\r\n rank = 1 # Initialise rank to 1\r\n for i in range(k-1,-1,-1): # Print all the elements in the list, starting at the end\r\n print(str(rank) + ' ' + str(result[i][1]) + ' ' + str(result[i][0]))\r\n rank += 1\r\n\r\n # Then the total time complexity is N*log(k) + k*log(k) + k. N*log(k) dominates the other two, so the time\r\n # complexity is O(N*log(k)).\r\ncelebrity('testdata.txt')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Week 4/celebrity/celebrity.py","file_name":"celebrity.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"237525368","text":"\"\"\"\nTests the capability to use the case recorders to dump out larger amounts of information\nfrom a driver's workflow.\n\"\"\"\nimport StringIO\nimport unittest\n\nfrom openmdao.lib.casehandlers.api import DumpCaseRecorder\nfrom openmdao.lib.datatypes.api import Float, List, Str\nfrom openmdao.main.api import Component, Assembly, Driver, Run_Once, Case, set_as_top\n\nclass Basic_Component(Component):\n ''' Basic building block'''\n \n x1 = Float(0.0, iotype='in')\n y1 = Float(iotype='out')\n \n def execute(self):\n ''' pretty simple'''\n \n self.y1 = self.x1 + 1\n \nclass Nest_Me(Assembly):\n \n def configure(self):\n ''' add some comps'''\n \n self.add('comp1', Basic_Component())\n self.add('comp2', Basic_Component())\n self.add('comp3', Basic_Component())\n self.driver.workflow.add(['comp1', 'comp2', 'comp3'])\n \n self.connect('comp1.y1','comp2.x1')\n self.connect('comp2.y1','comp3.x1')\n \n \nclass Complex_Comp(Component):\n ''' Basic building block'''\n \n list_str = List(Str, iotype='in')\n \n string = Str('Testing', iotype='out')\n \n def execute(self):\n ''' pretty simple'''\n \n pass\n \nclass Run_N(Run_Once):\n def __init__(self, iter_stop, *args, **kwargs):\n super(Run_N, self).__init__(*args, **kwargs)\n self._iter_count = 0\n self._iter_stop = iter_stop\n \n def execute(self):\n Driver.execute(self)\n \n def start_iteration(self):\n super(Run_N, self).start_iteration()\n self._iter_count = 0\n\n def continue_iteration(self):\n return self._iter_count <= self._iter_stop\n\n def run_iteration(self):\n super(Run_N, self).run_iteration()\n self._iter_count += 1\n \n def post_iteration(self):\n self.record_case()\n \n\nclass Data_Dump_TestCase(unittest.TestCase):\n\n def setUp(self):\n self.top = set_as_top(Assembly())\n \n def tearDown(self):\n self.top = None\n \n def test_nested_assy_match_all(self):\n \n self.top.add('comp1', Basic_Component())\n self.top.add('nested', Nest_Me())\n self.top.driver.workflow.add('nested')\n self.top.nested.add('doublenest', Nest_Me())\n self.top.nested.driver.workflow.add('doublenest')\n \n sout = StringIO.StringIO()\n self.top.driver.recorders = [DumpCaseRecorder(sout)]\n self.top.driver.printvars = ['*']\n self.top.run()\n expected = [\n 'Case: ',\n ' uuid: ad4c1b76-64fb-11e0-95a8-001e8cf75fe',\n ' inputs:',\n ' driver.directory: ',\n ' driver.force_execute: True',\n \" driver.printvars: ['*']\",\n ' nested.comp1.directory: ',\n ' nested.comp1.force_execute: False',\n ' nested.comp1.x1: 0.0',\n ' nested.comp2.directory: ',\n ' nested.comp2.force_execute: False',\n ' nested.comp2.x1: 1.0',\n ' nested.comp3.directory: ',\n ' nested.comp3.force_execute: False',\n ' nested.comp3.x1: 2.0',\n ' nested.directory: ',\n ' nested.doublenest.comp1.directory: ',\n ' nested.doublenest.comp1.force_execute: False',\n ' nested.doublenest.comp1.x1: 0.0',\n ' nested.doublenest.comp2.directory: ',\n ' nested.doublenest.comp2.force_execute: False',\n ' nested.doublenest.comp2.x1: 1.0',\n ' nested.doublenest.comp3.directory: ',\n ' nested.doublenest.comp3.force_execute: False',\n ' nested.doublenest.comp3.x1: 2.0',\n ' nested.doublenest.directory: ',\n ' nested.doublenest.force_execute: False',\n ' nested.force_execute: False',\n ' outputs:',\n ' driver.derivative_exec_count: 0',\n ' driver.exec_count: 1',\n ' driver.itername: ',\n ' driver.workflow.itername: 1',\n ' nested.comp1.derivative_exec_count: 0',\n ' nested.comp1.exec_count: 1',\n ' nested.comp1.itername: 1-1.1-1',\n ' nested.comp1.y1: 1.0',\n ' nested.comp2.derivative_exec_count: 0',\n ' nested.comp2.exec_count: 1',\n ' nested.comp2.itername: 1-1.1-2',\n ' nested.comp2.y1: 2.0',\n ' nested.comp3.derivative_exec_count: 0',\n ' nested.comp3.exec_count: 1',\n ' nested.comp3.itername: 1-1.1-3',\n ' nested.comp3.y1: 3.0',\n ' nested.derivative_exec_count: 0',\n ' nested.doublenest.comp1.derivative_exec_count: 0',\n ' nested.doublenest.comp1.exec_count: 1',\n ' nested.doublenest.comp1.itername: 1-1.1-4.1-1',\n ' nested.doublenest.comp1.y1: 1.0',\n ' nested.doublenest.comp2.derivative_exec_count: 0',\n ' nested.doublenest.comp2.exec_count: 1',\n ' nested.doublenest.comp2.itername: 1-1.1-4.1-2',\n ' nested.doublenest.comp2.y1: 2.0',\n ' nested.doublenest.comp3.derivative_exec_count: 0',\n ' nested.doublenest.comp3.exec_count: 1',\n ' nested.doublenest.comp3.itername: 1-1.1-4.1-3',\n ' nested.doublenest.comp3.y1: 3.0',\n ' nested.doublenest.derivative_exec_count: 0',\n ' nested.doublenest.exec_count: 1',\n ' nested.doublenest.itername: 1-1.1-4',\n ' nested.exec_count: 1',\n ' nested.itername: 1-1',\n ]\n lines = sout.getvalue().split('\\n')\n \n for line, template in zip(lines, expected):\n if template.startswith(' uuid:'):\n self.assertTrue(line.startswith(' uuid:'))\n else:\n self.assertEqual(line, template)\n \n def test_nested_assy_match_wildcard(self):\n \n self.top.add('comp1', Basic_Component())\n self.top.add('nested', Nest_Me())\n self.top.driver.workflow.add('nested')\n self.top.nested.add('doublenest', Nest_Me())\n self.top.nested.driver.workflow.add('doublenest')\n \n sout = StringIO.StringIO()\n self.top.driver.recorders = [DumpCaseRecorder(sout)]\n self.top.driver.printvars = ['*comp1*']\n self.top.run()\n expected = [\n 'Case: ',\n ' uuid: ad4c1b76-64fb-11e0-95a8-001e8cf75fe',\n ' inputs:',\n ' nested.comp1.directory: ',\n ' nested.comp1.force_execute: False',\n ' nested.comp1.x1: 0.0',\n ' nested.doublenest.comp1.directory: ',\n ' nested.doublenest.comp1.force_execute: False',\n ' nested.doublenest.comp1.x1: 0.0',\n ' outputs:',\n ' driver.workflow.itername: 1',\n ' nested.comp1.derivative_exec_count: 0',\n ' nested.comp1.exec_count: 1',\n ' nested.comp1.itername: 1-1.1-1',\n ' nested.comp1.y1: 1.0',\n ' nested.doublenest.comp1.derivative_exec_count: 0',\n ' nested.doublenest.comp1.exec_count: 1',\n ' nested.doublenest.comp1.itername: 1-1.1-4.1-1',\n ' nested.doublenest.comp1.y1: 1.0',\n ]\n lines = sout.getvalue().split('\\n')\n \n for line, template in zip(lines, expected):\n if template.startswith(' uuid:'):\n self.assertTrue(line.startswith(' uuid:'))\n else:\n self.assertEqual(line, template)\n\n def test_more_datatypes(self):\n \n self.top.add('comp1', Complex_Comp())\n self.top.driver.workflow.add('comp1')\n \n sout = StringIO.StringIO()\n self.top.driver.recorders = [DumpCaseRecorder(sout)]\n self.top.driver.printvars = ['*']\n self.top.run()\n expected = [\n 'Case: ',\n ' uuid: ad4c1b76-64fb-11e0-95a8-001e8cf75fe',\n ' inputs:',\n ' comp1.directory: ',\n ' comp1.force_execute: False',\n ' comp1.list_str: []',\n ' driver.directory: ',\n ' driver.force_execute: True',\n \" driver.printvars: ['*']\",\n ' outputs:',\n ' comp1.derivative_exec_count: 0',\n ' comp1.exec_count: 1',\n ' comp1.itername: 1-1',\n ' comp1.string: Testing',\n ' driver.derivative_exec_count: 0',\n ' driver.exec_count: 1',\n ' driver.itername: ',\n ' driver.workflow.itername: 1',\n ]\n lines = sout.getvalue().split('\\n')\n \n for line, template in zip(lines, expected):\n if template.startswith(' uuid:'):\n self.assertTrue(line.startswith(' uuid:'))\n else:\n self.assertEqual(line, template)\n \n \n def test_workflow_itername(self):\n # top\n # comp1\n # driverA\n # comp1\n # comp2\n # driverB\n # comp2\n # subassy\n # comp3\n top = Assembly()\n top.add('comp1', Basic_Component())\n top.add('driverA', Run_N(4))\n top.add('comp2', Basic_Component())\n top.add('driverB', Run_N(3))\n\n sub = top.add('subassy', Assembly())\n sout_sub = StringIO.StringIO()\n sub.driver.recorders = [DumpCaseRecorder(sout_sub)]\n sub.add('comp3', Basic_Component())\n sub.driver.workflow.add('comp3')\n\n top.driver.workflow.add(('comp1', 'driverA', 'driverB'))\n sout = StringIO.StringIO()\n top.driver.recorders = [DumpCaseRecorder(sout)]\n \n top.driverA.workflow.add(('comp1', 'comp2'))\n soutA = StringIO.StringIO()\n top.driverA.recorders = [DumpCaseRecorder(soutA)]\n top.driverB.workflow.add(('comp2', 'subassy'))\n soutB = StringIO.StringIO()\n top.driverB.recorders = [DumpCaseRecorder(soutB)]\n\n top.run()\n\n lines = [l.strip() for l in sout.getvalue().split('\\n') if 'itername' in l]\n linesA = [l.strip() for l in soutA.getvalue().split('\\n') if 'itername' in l]\n linesB = [l.strip() for l in soutB.getvalue().split('\\n') if 'itername' in l]\n lines_sub = [l.strip() for l in sout_sub.getvalue().split('\\n') if 'itername' in l]\n \n self.assertEqual(lines, ['driver.workflow.itername: 1'])\n self.assertEqual(linesA, ['driverA.workflow.itername: 1-1.1',\n 'driverA.workflow.itername: 1-1.2',\n 'driverA.workflow.itername: 1-1.3',\n 'driverA.workflow.itername: 1-1.4',\n 'driverA.workflow.itername: 1-1.5'])\n self.assertEqual(linesB, ['driverB.workflow.itername: 1-2.1',\n 'driverB.workflow.itername: 1-2.2',\n 'driverB.workflow.itername: 1-2.3',\n 'driverB.workflow.itername: 1-2.4'])\n self.assertEqual(lines_sub, ['driver.workflow.itername: 1-2.1-2.1'])\n\n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"bin/Python27/Lib/site-packages/openmdao.lib-0.8.1-py2.7.egg/openmdao/lib/casehandlers/test/test_datadump.py","file_name":"test_datadump.py","file_ext":"py","file_size_in_byte":11598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"371487257","text":"import time\n\nfrom selenium.common.exceptions import ElementNotVisibleException, NoSuchElementException\n\nfrom Automate_Tests_Content.Web.Selenuim.logger import Logger\n\n__author__ = \"Julian Jubran and Chulud Mallak\"\n__copyright__ = \"Utility\"\n__credits__ = [\"Julian Jubran\"]\n__version__ = \"1.0.0\"\n__maintainer__ = \"Julian Jubran\"\n__email__ = \"julian.samirx.jubran@intel.com\"\n__status__ = \"Production\"\n\n\nclass FullRegressionUtility:\n logger = Logger()\n\n def __init__(self):\n pass\n\n def click_on_info_button(self, browser):\n # Function that click on Info button\n # When open the file in Web there is two buttons\n # in the right (Issues and Info) buttons\n info_button_id = \"InfoMenuButton\"\n try:\n time.sleep(2)\n info = browser.find_element_by_id(info_button_id)\n time.sleep(2)\n info.click()\n except Exception as e:\n self.logger.Error(e.message)\n\n def click_option_menu_button(self, option_text, browser):\n # Function that take string that is the name one of menu\n # that show when click on Info button\n # and it click on it\n try:\n menu = browser.find_element_by_class_name(\"InfoMenu\")\n options = menu.find_elements_by_tag_name(\"li\")\n for op in options:\n if op.text == option_text:\n op.click()\n time.sleep(8)\n self.logger.Info(\"Click On {} Button succeeded...\".format(option_text))\n except Exception as e:\n self.logger.Error(str(e))\n\n def switch_browser_to_frame(self, frame_id, browser):\n # function that get frame id and switch the browser to this frame\n try:\n self.logger.Info(\"Attempting navigation to frame\")\n time.sleep(1)\n frame = browser.find_element_by_id(frame_id)\n browser.switch_to.frame(frame)\n except Exception as e:\n self.logger.Error(str(e))\n\n def cancel_edit_mode(self, browser):\n try:\n\n try:\n toc_restored_dialog = browser.find_element_by_id('TocRestoredDialog')\n if toc_restored_dialog.is_displayed():\n toc_restored_dialog_ok_button = browser.find_element_by_id('TocRestoredDialogOkButton')\n toc_restored_dialog_ok_button.click()\n except NoSuchElementException:\n pass\n\n cancel_edit_mode = browser.find_element_by_id('TOCCancelButton')\n time.sleep(0.5)\n cancel_edit_mode.click()\n self.logger.Info('The TOC is in edit mode...')\n time.sleep(2)\n cancel_changes_dialog_yes_button = browser.find_element_by_id('CancelChangesDialogYesButton')\n cancel_changes_dialog_yes_button.click()\n self.logger.Info(\"The TOC back to 'normal' mode...\")\n time.sleep(2)\n except ElementNotVisibleException:\n self.logger.Info('The TOC is not in edit mode...')\n pass\n\n def sorting(self, tabname, column_name, col_num, num, browser):\n list_td = []\n try:\n div = browser.find_element_by_id(\"RevisionHistory317205\")\n rows = div.find_elements_by_tag_name(\"tr\")\n td = rows[1].find_elements_by_tag_name(\"td\")\n for i in td:\n if i.text == column_name:\n i.click()\n time.sleep(2)\n self.logger.Info(\"Sorting by {} :\\n\".format(column_name))\n time.sleep(1)\n break\n first_table = div.find_element_by_class_name(\"obj\")\n rows = first_table.find_elements_by_tag_name(\"tr\")\n rows.pop(0)\n time.sleep(1)\n for tr in rows:\n td = tr.find_elements_by_tag_name(\"td\")\n list_td.append(td[col_num].text)\n if num == 1:\n if list_td[0] < list_td[len(list_td) - 1]:\n self.logger.Info(\"{} table sort ascending succeeded...\\n\".format(tabname))\n else:\n if list_td[0] > list_td[len(list_td) - 1]:\n self.logger.Info(\"{} table sort descending succeeded...\\n\".format(tabname))\n except Exception as e:\n self.logger.Error(str(e))\n","sub_path":"Automate_Tests_Content/Web/Selenuim/utils/full_regression_utility.py","file_name":"full_regression_utility.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"307642579","text":"#!/usr/bin/env python\n\n\n################################################################\n\nimport rospy\nfrom std_msgs.msg import String, UInt16MultiArray, Int8\nfrom sensor_msgs.msg import Image, CompressedImage\nfrom geometry_msgs.msg import Twist, Point\n\nimport miro_msgs\nfrom miro_msgs.msg import platform_config, platform_sensors, platform_state, platform_mics, platform_control, \\\n core_state, core_control, core_config, bridge_config, bridge_stream\n\nimport math\nimport numpy\nimport time\nimport sys\nfrom miro_constants import miro\n\n\n################################################################\n\ndef fmt(x, f):\n s = \"\"\n x = bytearray(x)\n for i in range(0, len(x)):\n if not i == 0:\n s = s + \", \"\n s = s + f.format(x[i])\n return s\n\n\ndef hex2(x):\n return \"{0:#04x}\".format(x)\n\n\ndef hex4(x):\n return \"{0:#06x}\".format(x)\n\n\ndef hex8(x):\n return \"{0:#010x}\".format(x)\n\n\ndef flt3(x):\n return \"{0:.3f}\".format(x)\n\n\ndef error(msg):\n print(msg)\n sys.exit(0)\n\n\ndef usage():\n print(\"\"\"\nUsage:\n miro_teleop.py robot=\n\n Without arguments, this help page is displayed. To run the\n client you must specify at least the option \"robot\".\n\nOptions:\n robot=\n specify the name of the miro robot to connect to,\n which forms the ros base topic \"/miro/\".\n there is no default, this argument must be specified.\n \"\"\")\n sys.exit(0)\n\n\n################################################################\n\nclass miro_background:\n\n def callback_sensors(self, data):\n\n if not self.active:\n return\n\n self.sensors = data\n\n # check dangerous situations\n state = 0\n\n # sonar gives back a sginal between 0.00 (exclusive) and 0.05 (near obstacle)\n if 0.00 < self.sensors.sonar_range.range < 0.05:\n state = 1\n\n # cliff give back a signal that no surface was detected\n if self.sensors.cliff[0] < 2 or self.sensors.cliff[1] < 2:\n state = 3\n\n\n # change state if dangerous situation was found\n if (self.state != state and state != 0):\n self.state = state\n # clear the danger\n #self.clear_danger()\n\n def callback_state(self, data):\n\n if not self.active:\n return\n\n self.platform_state = data\n\n # check dangerous situations\n state = 0\n\n # P1_R_signals == 12 (joint stalled)\n\n if self.platform_state.P1_R_signals == 12:\n state = 3\n\n # change state if dangerous situation was found\n if (self.state != state and state != 0):\n self.state = state\n # clear the danger\n #self.clear_danger()\n\n def callback_control(self, data):\n\n if not self.active:\n return\n\n if not self.state == 0:\n return\n\n if self.sensors is None:\n return\n\n self.control = data\n\n\n # save the last actions \n # for body\n if self.control.body_vel.linear.x is not 0:\n self.last_body_move = \"forward\" if self.control.body_vel.linear.x > 0 else \"backward\"\n\n if self.control.body_vel.angular.z is not 0:\n self.last_body_turn = \"right\" if self.control.body_vel.angular.z > 0 else \"left\"\n\n # for head\n if self.sensors.joint_state.position[1] is not self.control.body_config[1]:\n self.last_head_change[1] = self.control.body_config[1] - self.sensors.joint_state.position[1]\n\n if self.sensors.joint_state.position[2] is not self.control.body_config[2]:\n self.last_head_change[2] = self.control.body_config[2] - self.sensors.joint_state.position[2]\n\n if self.sensors.joint_state.position[3] is not self.control.body_config[3]:\n self.last_head_change[3] = self.control.body_config[3] - self.sensors.joint_state.position[3] \n\n \n def callback_mics(self, data):\n\n if not self.active:\n return\n\n self.mics = data\n\n # check dangerous situations\n state = 0\n\n # a really loud situation is dangerous?\n\n # change state if dangerous situation was found\n if (self.state != state and state != 0):\n self.state = state\n # clear the danger\n #self.clear_danger()\n\n def callback_camr(self, data):\n\n if not self.active:\n return\n\n self.camr = data\n\n # check dangerous situations\n state = 0\n\n # a really dark situation is dangerous?\n\n # dangerous obstacles are near?\n\n # change state if dangerous situation was found\n if (self.state != state and state != 0):\n self.state = state\n # clear the danger\n #self.clear_danger()\n\n def callback_caml(self, data):\n\n if not self.active:\n return\n\n self.caml = data\n\n # check dangerous situations\n state = 0\n\n # a really dark situation is dangerous?\n\n # dangerous obstacles are near?\n\n # change state if dangerous situation was found\n if (self.state != state and state != 0):\n self.state = state\n # clear the danger\n #self.clear_danger()\n\n\n def clear_danger(self, state):\n\n if state == 0:\n return\n\n print(self.state )\n print(self.last_body_move)\n print(self.last_body_turn)\n print(self.last_head_change)\n\n # state 0= safe, 1 = move backwards, 2 = move forward, 3 = unclear/do nothing/ or turn etc.\n q = platform_control()\n\n # clear danger depending on memory of last actions \n\n # find out what is/what happening using current sensor information and last_head_move, last_body_move etc.\n\n # default wait\n\n # move backwards\n if self.last_body_move == \"forward\" and state == 1:\n q.body_vel.linear.x = -100\n\n # move forward \n elif self.last_body_move == \"backward\" and self.platform_state.P1_R_signals == 12:\n q.body_vel.linear.x = +100\n\n # turn right\n\n # turn left \n\n self.pub_platform_control.publish(q)\n\n # check if danger is still there, if yes repeat, else set state to safe\n if self.sensors.sonar_range.range > 0.05 and self.platform_state.P1_R_signals != 12 and self.sensors.cliff[0] > 2 and self.sensors.cliff[1] > 2:\n self.state = 0\n\n\n\n\n def loop(self):\n rate = rospy.Rate(10) # 10hz\n self.active = True\n #self.msg = platform_control()\n while not rospy.is_shutdown():\n self.pub_safe.publish(self.state)\n rate.sleep()\n #self.pub_platform_control.publish(self.msg) #Publish to MiRo\n\n\n \n def __init__(self, topic_root):\n\n # report\n print(\"initialising...\")\n print(sys.version)\n\n # set inactive\n self.active = False\n self.state = 0\n self.last_head_change = [0,0,0,0]\n self.last_body_move = 0\n self.last_body_turn = 0\n self.sensors = None\n\n # publish\n self.pub_safe = rospy.Publisher(topic_root + \"/safe\",\n Int8, queue_size=0)\n\n self.pub_platform_control = rospy.Publisher(topic_root + \"/platform/control\", platform_control, queue_size=1)\n\n # subscribe\n self.sub_platform_sensors = rospy.Subscriber(topic_root + \"/platform/sensors\", platform_sensors, self.callback_sensors)\n self.sub_platform_control = rospy.Subscriber(topic_root + \"/platform/control\", platform_control, self.callback_control)\n self.sub_platform_state = rospy.Subscriber(topic_root + \"/platform/state\", platform_state, self.callback_state)\n\n self.sub_platform_camr = rospy.Subscriber(topic_root + \"/platform/camr\", Image, self.callback_camr)\n self.sub_platform_caml = rospy.Subscriber(topic_root + \"/platform/caml\", Image, self.callback_caml)\n\n self.sub_platforrm_mics = rospy.Subscriber(topic_root + \"/platform/mics\", platform_mics, self.callback_mics)\n\n self.sub_safe = rospy.Subscriber(topic_root + \"/safe\", Int8, self.clear_danger)\n\nif __name__ == \"__main__\":\n # no arguments gives usage\n if len(sys.argv) == 1:\n usage()\n\n # options\n robot_name = \"\"\n\n print(sys.argv)\n\n # handle args\n for arg in sys.argv[1:]:\n f = arg.find('=')\n if f == -1:\n key = arg\n val = \"\"\n else:\n key = arg[:f]\n val = arg[f+1:]\n if key == \"robot\":\n robot_name = val\n elif key == \"__name:\":\n name = val\n elif key == \"__log:\":\n pass\n else:\n print(key)\n error(\"argument not recognised \\\"\" + arg + \"\\\"\")\n\n # check we got at least one\n if len(robot_name) == 0:\n error(\"argument \\\"robot\\\" must be specified\")\n\n # topic root\n topic_root = \"/miro/\" + robot_name\n print(\"topic_root\", topic_root)\n\n rospy.init_node(name, anonymous=True)\n main = miro_background(topic_root)\n main.loop()\n","sub_path":"scripts/background_safety.py","file_name":"background_safety.py","file_ext":"py","file_size_in_byte":9078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"344122583","text":"__author__ = \"monoDrive\"\n__copyright__ = \"Copyright (C) 2018 monoDrive\"\n__license__ = \"MIT\"\n__version__ = \"1.0\"\n\nimport numpy as np\nfrom numpy import linalg as lg\nfrom scipy import linalg\n\n\nclass RadarProcessing(object):\n \n def __init__(self):\n pass\n\n @staticmethod\n\n def modified_correlation(x, M):\n # ----Compute backward/Forward correlation\n # it is used by RootLMusic, Esprit and AIC algorithms\n # x : input signal vector\n # M : size of correlation window\n # ---- returns the correlation vector\n n = x.shape[0]\n x2 = np.conj(x[n-1::-1])\n\n x_vect = np.transpose(np.matrix(x)) # Forward vector\n x_vect2 = np.transpose(np.matrix(x2)) # Backward vector\n yn = x_vect[M - 1::-1] # Consider M samples forward\n zn = x_vect2[M - 1::-1] # consider M samples backward\n r = yn * yn.H # initialize forward correlation\n r2 = zn*zn.H # initialize backward correlation\n for idx in range(1, n - M):\n yn = x_vect[M - 1 + idx:idx - 1:-1]\n zn = x_vect2[M - 1 + idx:idx - 1:-1]\n r = r + yn * yn.H # Multiply and accumulate for forward correlation\n r2 = r2 + zn*zn.H # Multiply and accumulate for backward correlation\n\n r = (r+r2) / (2.* n) # final correlation is mean of forward and backward components\n return r\n \n @staticmethod\n def root_music(xr, n_freqs, correlation_size, sample_frequency):\n # --- This function estimates the frequency components from given signal using RootMusic algorithm\n # Can be used to estimate AoA or velocity\n # x : input signal vector\n # n_freqs : number of frequency components to be extracted\n # correlation_size : size of correlation window\n # sample_frequency : Sampling Frequency\n # ---- returns an array containing the L frequencies\n\n # N = xr.shape[0]\n # Compute correlation-size forward/backward correlation vector of input signal\n r = RadarProcessing.modified_correlation(xr, correlation_size)\n u, s, v = lg.svd(r) # Singular value decomposition of R\n g = u[:, 2:] # Unitary matrix\n\n p = g * g.H\n\n q = 0j * np.zeros(2 * correlation_size - 1) # Polynomial for which roots will be calculated\n\n for (idx, val) in enumerate(range(correlation_size - 1, -correlation_size, -1)):\n diag = np.diag(p, val)\n q[idx] = np.sum(diag)\n\n roots = np.roots(q)\n\n roots = np.extract(np.abs(roots) < 1, roots)\n distance_from_circle = np.abs(np.abs(roots) - 1) # Calculate the distance of different roots from unit circle\n index_sort = np.argsort(distance_from_circle) # sort roots by distance\n component_roots = roots[index_sort[:n_freqs]] # keep only L closer roots to circle\n\n angle = -np.angle(component_roots) # phase of L chosen roots\n\n f = sample_frequency * angle / (2. * np.pi) # convert phases to normalized frequencies\n\n return f\n\n @staticmethod\n def esprit(x, L, M, Fe): \n # --- This function estimates the frequency components from given signal using Esprit algorithm\n # Can be used to estimate AoA or velocity\n # x : input signal vector\n # L : number of frequency components to be extracted\n # M : size of correlation window\n # Fe : Sampling Frequency\n # ---- returns an array containing the L frequencies\n\n N = x.shape[0]\n\n if M == None:\n M = N // 2\n\n R = RadarProcessing.modified_correlation(x, M) # Compute M-size forward/backward correlation vector of input signal\n\n U, S, V = lg.svd(R) # Singular value decomposition of R\n\n S = U[:, :L] # Consider the signal subspace\n\n S1 = S[:-1, :] #Remove last row\n\n S2 = S[1:, :] #Remove first row\n\n Phi = (S1.H * S1).I * S1.H * S2 #Compute matrix Phi \n\n V, U = lg.eig(Phi) # Compute eigen values of matrix Phi\n\n angle = -np.angle(V) # extract phases\n\n f = Fe * angle / (2. * np.pi) # deduce normalized frequencies\n\n return f\n\n @staticmethod\n def range_by_fft(rx_signal_fft):\n # rx_signal_shaped = rx_signal * hanning # 1375x64 2D-array Hann windowed dechirped samples (fast/slow plan)\n # rx_signal_fft = pyfftw.interfaces.numpy_fft.fft(rx_signal_shaped, N_FFT, 0) # 1024 points FFT performed on the 64 1D-arrays\n rx_signal_abs_fft = abs(rx_signal_fft) # 1024x64 2D-array with amplitudes\n rx_sum = rx_signal_abs_fft[:, 0] # ZA.sum(axis=1)/64 # 1024 points 1D-Array, summing up over sweeps in order to reduce noise effect and clean up the spectrum\n # Lgx = rx_sum.size\n # Following is CFAR algorithm\n # we used CFAR order statistics : OSCFAR (refer to the report by Celite on Radar design, CFAR section)\n guard = 2 # Guard interval\n window_size = 10 # averaging window size\n threshold = 20 # threshold depending on false alarm detection probability\n rx_sum_sqr = rx_sum * rx_sum # compute energy x[k]^2\n # p = [] # initialization of peaks array\n peaks_index = np.array([]) # initialization of peaks array\n peaks_energy = 0 * rx_sum_sqr # initialization of the value of the peaks\n\n # compute CFAR for the first samples of the block (right neighbours)\n for idx in range(0, 2 * (guard + window_size) - 1):\n rx_sum_sqr_window = rx_sum_sqr[idx + guard:idx + guard +int(window_size/2)]\n rx_sum_sqr_median = np.median(rx_sum_sqr_window)\n if (rx_sum_sqr[idx] > threshold * rx_sum_sqr_median):\n peaks_index = np.hstack((peaks_index, [idx]))\n peaks_energy[idx] = rx_sum[idx]\n\n # compute CFAR for the following block (right and left neighbours)\n for idx in range(2 * (guard + window_size) - 1, 200): #(Lgx - G - Ncfar - 1)):\n rx_sum_sqr_window = np.concatenate((rx_sum_sqr[idx + guard:idx + guard + window_size], rx_sum_sqr[idx - guard:idx - guard - window_size:-1]), axis=0)\n rx_sum_sqr_median = np.median(rx_sum_sqr_window)\n if (rx_sum_sqr[idx] > threshold * rx_sum_sqr_median):\n peaks_index = np.hstack((peaks_index, [idx]))\n peaks_energy[idx] = rx_sum[idx]\n\n # compute CFAR for the last samples of the block (left neighbours)\n # for k in range(2 * (G + Ncfar) - 1, Lgx - 1):\n # z = y[k - G:k - G + Ncfar + 1:-1]\n # T = np.median(z)\n # if (y[k] > Thr * T):\n # p = np.hstack((p, [k]))\n # qy[k] = x[k]\n # peaks localization\n #DenoisingThreshold = 1/500\n DenoisingThreshold = 1/500\n #Lgy = peak_energy.size\n #k = 1\n peaks = np.array([]) #TODO setting this to zero? what does the above do?\n energy = np.array([])\n min_energy = max(peaks_energy) * DenoisingThreshold\n #RCS_Th = 2\n if (peaks_energy[0] > min_energy and peaks_energy[0] > peaks_energy[1]):\n peaks += [0]\n energy += [peaks_energy[0]]\n for idx in range(0, peaks_energy.size - 1):\n '''if (peaks_energy[idx] > 0):\n RCS_k = 10 * np.log10(peaks_energy[idx] * ((idx+1) ** 2) * (4 * np.pi) ** 3 / N_FFT ** 2) - 25\n else:\n RCS_k = 1'''\n if (peaks_energy[idx] > peaks_energy[idx - 1] and peaks_energy[idx] > peaks_energy[idx + 1] and peaks_energy[idx]> min_energy):\n peaks = np.hstack((peaks, [idx]))\n energy = np.hstack((energy, [peaks_energy[idx]]))\n return [peaks, energy]\n\n @staticmethod\n def max_likelihood_aoa_estimation(project): \n # --- This function estimates AoA from the projection vector obtained for a given Range\n # --- It is an alternative algorithm to RootMusic and Esprit for AoA estimation\n\n N = project.shape[0]\n # M = project.shape[1]\n\n theta = np.arange(-10,10,0.5) # operates in filed -10 to +10 degrees with a 0.5 resolution\n theta_rad = theta / 180. * np.pi\n theta_length = len(theta)\n V = np.zeros((N, theta_length)) + np.zeros((N, theta_length)) * 1j\n for idx in range(theta_length):\n for n in range(N):\n V[n, idx] = np.exp(-1j * np.pi * n * np.sin(theta_rad[idx])) \n theta_est = 0. #np.zeros(1, M)\n\n max_likelihood = np.zeros(theta_length) #initialize max likelihood to zeros\n for idx in range(theta_length):\n A = V[:, idx]\n cte = np.dot(np.conj(np.transpose(A)), np.transpose(project)) # correlation calculation\n max_likelihood[idx] = np.abs(cte)\n\n index = max_likelihood.argmax() # deduce component with maximum correlation\n theta_est = theta[index]\n\n return theta_est\n \n @staticmethod\n def NumberOfTargetsAIC(x, M): \n #--- This function estimates the number of targets based on the Akaike information criterion algorithm\n #--- It is used for a given range to compute the number of targets with different AoAs\n # x : input signal vector \n # M : size of correlation window\n # ---returns the number of detected targets\n\n N = x.shape[0]\n R = RadarProcessing.modified_correlation(x, M) # Compute M-size forward/backward correlation vector of input signal\n S_vec= abs(linalg.eigvals(R)) # compute signal space\n S_vec = np.sqrt(S_vec)\n S_vec = S_vec / S_vec.max() # and normalize it\n J = np.zeros(M - 2)\n for d in range(0, M - 2):\n cte1 = 1\n cte0 = 0\n for i in range(d, M):\n cte1 = cte1 * S_vec[i]\n cte0 = cte0 + S_vec[i]\n cte1 = cte1 ** (1 / (M - d))\n cte0 = cte0 / (M - d)\n J[d] = abs((M/2 * np.log((cte1 / cte0) ** (M - d))) + d * (2 * M - d) / 2)\n\n mn = np.argmin(J)\n toto = S_vec[0:mn + 1]\n L1 = mn+1 \n\n k = 0\n mn2 = 0\n p = 1\n while (k < M) & (p == 1):\n if S_vec[k] > 0.5e-1:\n k = k + 1\n mn2 = mn2 + 1\n else:\n p = 0\n\n L = min(L1, mn2)\n \n return L\n","sub_path":"monodrive/sensors/radar_processing.py","file_name":"radar_processing.py","file_ext":"py","file_size_in_byte":10313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"634071865","text":"import copy\nimport numpy as np\nimport torch\nimport matplotlib.pyplot as plt\nimport os\nimport pandas as pd\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import ConcatDataset, Dataset\nfrom torchvision.datasets.folder import default_loader\nfrom torchvision.datasets.utils import download_url\n\n\nclass UnNormalize(object):\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n\n def __call__(self, tensor):\n \"\"\"Denormalize image, either single image (C,H,W) or image batch (N,C,H,W)\"\"\"\n batch = (len(tensor.size())==4)\n for t, m, s in zip(tensor.permute(1,0,2,3) if batch else tensor, self.mean, self.std):\n t.mul_(s).add_(m)\n # The normalize code -> t.sub_(m).div_(s)\n return tensor\n\n\ndef _rotate_image(image, rotation):\n '''Rotating the pixels of an image according to [rotation].\n\n [image] 3D-tensor containing the image\n [rotation] rotation angle'''\n if rotation is None:\n return image\n else:\n img = transforms.ToPILImage()(image).rotate(rotation)\n image = transforms.ToTensor()(img)\n return image\n\n\ndef _permutate_image_pixels(image, permutation):\n '''Permutate the pixels of an image according to [permutation].\n\n [image] 3D-tensor containing the image\n [permutation] of pixel-indeces in their new order'''\n\n if permutation is None:\n return image\n else:\n c, h, w = image.size()\n image = image.view(c, -1)\n image = image[:, permutation] #--> same permutation for each channel\n image = image.view(c, h, w)\n return image\n\n\ndef get_augmentation(name, augment=False):\n dataset_transform = None\n if name in ['CIFAR10', 'CIFAR100'] and augment:\n dataset_transform = transforms.Compose([\n transforms.ToPILImage(),\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(32, padding=4),\n transforms.ToTensor()\n ])\n\n return dataset_transform\n\n\ndef get_dataset(name, mode='train', download=True, capacity=None, dir='./datasets',\n verbose=False, augment=False, normalize=False, target_transform=None):\n '''Create [train|valid|test]-dataset.'''\n\n data_name = 'mnist' if name=='mnist28' else name\n dataset_class = AVAILABLE_DATASETS[data_name]\n\n # specify image-transformations to be applied\n if mode == 'train':\n if name.lower() in ['imagenet', 'cub2011'] and augment:\n transforms_list = [*AVAILABLE_TRANSFORMS[f'{name}_augment']]\n else:\n transforms_list = [*AVAILABLE_TRANSFORMS['augment']] if augment else []\n else:\n if name.lower() in ['imagenet', 'cub2011'] and augment:\n transforms_list = [*AVAILABLE_TRANSFORMS[f'{name}_test_augment']]\n else:\n transforms_list = [*AVAILABLE_TRANSFORMS['augment']] if augment else []\n # transforms_list = [*AVAILABLE_TRANSFORMS['imagenet_test_augment']] if name == 'imagenet' else []\n transforms_list += [*AVAILABLE_TRANSFORMS[name]]\n if normalize:\n transforms_list += [*AVAILABLE_TRANSFORMS[name + \"_norm\"]]\n dataset_transform = transforms.Compose(transforms_list)\n # load data-set\n if name == 'cub2011':\n dataset = Cub2011(dir, train=False if mode == 'test' else True,\n transform=dataset_transform, target_transform=target_transform, download=download)\n elif name != 'imagenet':\n dataset = dataset_class('{dir}/{name}'.format(dir=dir, name=data_name), train=False if mode == 'test' else True,\n download=download, transform=dataset_transform, target_transform=target_transform)\n else:\n dataset = dataset_class('{dir}/{type}'.format(dir=dir, type=mode), transform=dataset_transform,\n target_transform=target_transform)\n # print information about dataset on the screen\n if verbose:\n print(\" --> {}: '{}'-dataset consisting of {} samples\".format(name, mode, len(dataset)))\n\n # if dataset is (possibly) not large enough, create copies until it is.\n if capacity is not None and len(dataset) < capacity:\n dataset_copy = copy.deepcopy(dataset)\n dataset = ConcatDataset([dataset_copy for _ in range(int(np.ceil(capacity / len(dataset))))])\n\n return dataset\n\n\n#----------------------------------------------------------------------------------------------------------#\n\n\nclass SubDataset(Dataset):\n '''To sub-sample a dataset, taking only those samples with label in [sub_labels].\n\n After this selection of samples has been made, it is possible to transform the target-labels,\n which can be useful when doing continual learning with fixed number of output units.'''\n\n def __init__(self, original_dataset, sub_labels, target_transform=None):\n super().__init__()\n self.dataset = original_dataset\n self.sub_indeces = []\n for index in range(len(self.dataset)):\n if hasattr(original_dataset, \"targets\"):\n if self.dataset.target_transform is None:\n label = self.dataset.targets[index]\n else:\n label = self.dataset.target_transform(self.dataset.targets[index])\n else:\n label = self.dataset[index][1]\n if label in sub_labels:\n self.sub_indeces.append(index)\n self.target_transform = target_transform\n\n def __len__(self):\n return len(self.sub_indeces)\n\n def __getitem__(self, index):\n sample = self.dataset[self.sub_indeces[index]]\n if self.target_transform:\n target = self.target_transform(sample[1])\n sample = (sample[0], target)\n return sample\n\n\nclass OnlineExemplarDataset(Dataset):\n '''Create dataset from list of with shape (N, C, H, W) (i.e., with N images each).\n '''\n def __init__(self, exemplar_sets, target_transform=None):\n super().__init__()\n images, labels = exemplar_sets[0], exemplar_sets[1]\n self.images = torch.from_numpy(images)\n self.labels = torch.from_numpy(labels)\n self.target_transform = target_transform\n\n def __len__(self):\n return self.images.size(0)\n\n def __getitem__(self, index):\n image = self.images[index]\n label = self.labels[index] if self.target_transform is None else self.target_transform(self.labels[index])\n return image.float(), label.long()\n\n\nclass ExemplarDataset(Dataset):\n '''Create dataset from list of with shape (N, C, H, W) (i.e., with N images each).\n\n The images at the i-th entry of [exemplar_sets] belong to class [i], unless a [target_transform] is specified'''\n\n def __init__(self, exemplar_sets, target_transform=None):\n super().__init__()\n self.exemplar_sets = exemplar_sets\n self.target_transform = target_transform\n\n def __len__(self):\n total = 0\n for class_id in range(len(self.exemplar_sets)):\n total += len(self.exemplar_sets[class_id])\n return total\n\n def __getitem__(self, index):\n total = 0\n for class_id in range(len(self.exemplar_sets)):\n exemplars_in_this_class = len(self.exemplar_sets[class_id])\n if index < (total + exemplars_in_this_class):\n class_id_to_return = class_id if self.target_transform is None else self.target_transform(class_id)\n exemplar_id = index - total\n break\n else:\n total += exemplars_in_this_class\n exemplar_id = index % total\n class_id_to_return = class_id if self.target_transform is None else self.target_transform(class_id)\n break\n image = torch.from_numpy(self.exemplar_sets[class_id][exemplar_id])\n return (image, class_id_to_return)\n\n\nclass TransformedDataset(Dataset):\n '''Modify existing dataset with transform; for creating multiple MNIST-permutations w/o loading data every time.'''\n\n def __init__(self, original_dataset, transform=None, target_transform=None):\n super().__init__()\n self.dataset = original_dataset\n self.transform = transform\n self.target_transform = target_transform\n\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, index):\n (input, target) = self.dataset[index]\n if self.transform:\n input = self.transform(input)\n if self.target_transform:\n target = self.target_transform(target)\n return (input, target)\n\n\nclass Cub2011(Dataset):\n base_folder = 'CUB_200_2011/images'\n url = 'https://drive.google.com/u/0/open?id=1hbzc_P1FuxMkcabkgn9ZKinBwW683j45'\n filename = 'CUB_200_2011.tgz'\n tgz_md5 = '97eceeb196236b17998738112f37df78'\n\n def __init__(self, root, train=True, transform=None, target_transform=None, download=True):\n self.root = os.path.expanduser(root)\n self.transform = transform\n self.target_transform = target_transform\n self.train = train\n\n if download:\n self._download()\n\n if not self._check_integrity():\n raise RuntimeError('Dataset not found or corrupted.' +\n ' You can use download=True to download it')\n\n def _load_metadata(self):\n images = pd.read_csv(os.path.join(self.root, 'CUB_200_2011', 'images.txt'), sep=' ',\n names=['img_id', 'filepath'])\n image_class_labels = pd.read_csv(os.path.join(self.root, 'CUB_200_2011', 'image_class_labels.txt'),\n sep=' ', names=['img_id', 'target'])\n train_test_split = pd.read_csv(os.path.join(self.root, 'CUB_200_2011', 'train_test_split.txt'),\n sep=' ', names=['img_id', 'is_training_img'])\n\n data = images.merge(image_class_labels, on='img_id')\n self.data = data.merge(train_test_split, on='img_id')\n\n if self.train:\n self.data = self.data[self.data.is_training_img == 1]\n else:\n self.data = self.data[self.data.is_training_img == 0]\n\n def _check_integrity(self):\n try:\n self._load_metadata()\n except Exception:\n return False\n\n for index, row in self.data.iterrows():\n filepath = os.path.join(self.root, self.base_folder, row.filepath)\n if not os.path.isfile(filepath):\n print(filepath)\n return False\n return True\n\n def _download(self):\n import tarfile\n\n if self._check_integrity():\n print('Files already downloaded and verified')\n return\n\n download_url(self.url, self.root, self.filename, self.tgz_md5)\n\n with tarfile.open(os.path.join(self.root, self.filename), \"r:gz\") as tar:\n tar.extractall(path=self.root)\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n sample = self.data.iloc[idx]\n path = os.path.join(self.root, self.base_folder, sample.filepath)\n target = sample.target - 1 # Targets start at 1 by default, so shift to 0\n img = default_loader(path)\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n#----------------------------------------------------------------------------------------------------------#\n\n\n# specify available data-sets.\nAVAILABLE_DATASETS = {\n 'mnist': datasets.MNIST,\n 'cifar10': datasets.CIFAR10,\n 'cifar100': datasets.CIFAR100,\n 'cub2011': None,\n 'imagenet': datasets.ImageFolder,\n}\n\n# specify available transforms.\nAVAILABLE_TRANSFORMS = {\n 'mnist': [\n transforms.Pad(2),\n transforms.ToTensor(),\n ],\n 'mnist28': [\n transforms.ToTensor(),\n ],\n 'cifar10': [\n transforms.ToTensor(),\n ],\n 'cifar100': [\n transforms.ToTensor(),\n ],\n 'mnist_norm': [\n transforms.Normalize(mean=(0.1307,), std=(0.3081,))\n ],\n 'cifar10_norm': [\n transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n ],\n 'cifar100_norm': [\n transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n ],\n 'cifar10_denorm': UnNormalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n 'cifar100_denorm': UnNormalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n 'cub2011': [\n transforms.ToTensor(),\n ],\n 'cub2011_norm': [\n transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n ],\n 'cub2011_denorm': UnNormalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n 'augment': [\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(32, padding=4),\n ],\n 'imagenet': [\n transforms.ToTensor()\n ],\n 'imagenet_norm': [\n transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n ],\n 'imagenet_denorm': UnNormalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n 'imagenet_augment': [\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n ],\n 'imagenet_test_augment': [\n transforms.Resize((224, 224))\n ],\n 'cub2011_augment': [\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n ],\n 'cub2011_test_augment': [\n transforms.Resize((224, 224))\n ]\n}\n\n# specify configurations of available data-sets.\nDATASET_CONFIGS = {\n 'mnist': {'size': 32, 'channels': 1, 'classes': 10},\n 'mnist28': {'size': 28, 'channels': 1, 'classes': 10},\n 'cifar10': {'size': 32, 'channels': 3, 'classes': 10},\n 'cifar100': {'size': 32, 'channels': 3, 'classes': 100},\n 'cub2011': {'size': 224, 'channels': 3, 'classes': 200},\n 'imagenet': {'size': 224, 'channels': 3, 'classes': 1000}\n}\n\n\n#----------------------------------------------------------------------------------------------------------#\n\ndef get_multitask_experiment(name, scenario, tasks, data_dir=\"./datasets\", normalize=False, augment=False,\n only_config=False, verbose=False, exception=False):\n '''Load, organize and return train- and test-dataset for requested experiment.\n\n [exception]: ; if True, for visualization no permutation is applied to first task (permMNIST) or digits\n are not shuffled before being distributed over the tasks (splitMNIST)'''\n ## NOTE: option 'normalize' and 'augment' only implemented for CIFAR-based experiments.\n\n # depending on experiment, get and organize the datasets\n if name == 'permMNIST':\n # configurations\n config = DATASET_CONFIGS['mnist']\n classes_per_task = 10\n if not only_config:\n # prepare dataset\n train_dataset = get_dataset('mnist', mode=\"train\", dir=data_dir,\n target_transform=None, verbose=verbose)\n test_dataset = get_dataset('mnist', mode=\"test\", dir=data_dir,\n target_transform=None, verbose=verbose)\n # generate permutations\n if exception:\n permutations = [None] + [np.random.permutation(config['size']**2) for _ in range(tasks-1)]\n else:\n permutations = [np.random.permutation(config['size']**2) for _ in range(tasks)]\n # prepare datasets per task\n train_datasets = []\n test_datasets = []\n for task_id, perm in enumerate(permutations):\n target_transform = transforms.Lambda(\n lambda y, x=task_id: y + x*classes_per_task\n ) if scenario in ('task', 'class') else None\n train_datasets.append(TransformedDataset(\n train_dataset, transform=transforms.Lambda(lambda x, p=perm: _permutate_image_pixels(x, p)),\n target_transform=target_transform\n ))\n test_datasets.append(TransformedDataset(\n test_dataset, transform=transforms.Lambda(lambda x, p=perm: _permutate_image_pixels(x, p)),\n target_transform=target_transform\n ))\n elif name == 'splitMNIST':\n # check for number of tasks\n if tasks > 10:\n raise ValueError(\"Experiment 'splitMNIST' cannot have more than 10 tasks!\")\n # configurations\n config = DATASET_CONFIGS['mnist28']\n classes_per_task = int(np.floor(10 / tasks))\n if not only_config:\n # prepare permutation to shuffle label-ids (to create different class batches for each random seed)\n permutation = np.array(list(range(10))) if exception \\\n else np.random.permutation(list(range(10)))\n target_transform = transforms.Lambda(lambda y, p=permutation: int(p[y]))\n # prepare train and test datasets with all classes\n mnist_train = get_dataset('mnist28', mode=\"train\", dir=data_dir, target_transform=target_transform,\n verbose=verbose)\n mnist_test = get_dataset('mnist28', mode=\"test\", dir=data_dir, target_transform=target_transform,\n verbose=verbose)\n # generate labels-per-task\n labels_per_task = [\n list(np.array(range(classes_per_task)) + classes_per_task * task_id) for task_id in range(tasks)\n ]\n # split them up into sub-tasks\n train_datasets = []\n test_datasets = []\n for labels in labels_per_task:\n target_transform = transforms.Lambda(\n lambda y, x=labels[0]: y - x\n ) if scenario=='domain' else None\n train_datasets.append(SubDataset(mnist_train, labels, target_transform=target_transform))\n test_datasets.append(SubDataset(mnist_test, labels, target_transform=target_transform))\n elif name == 'rotMNIST':\n # configurations\n config = DATASET_CONFIGS['mnist']\n classes_per_task = 10\n if not only_config:\n # prepare dataset\n train_dataset = get_dataset('mnist', mode=\"train\", dir=data_dir,\n target_transform=None, verbose=verbose)\n test_dataset = get_dataset('mnist', mode=\"test\", dir=data_dir,\n target_transform=None, verbose=verbose)\n # generate rotations\n if exception:\n rotations = [None] + np.random.choice(180, tasks - 1, replace=False).tolist()\n else:\n rotations = np.random.choice(180, tasks, replace=False).tolist()\n # prepare datasets per task\n train_datasets = []\n test_datasets = []\n for task_id, rot in enumerate(rotations):\n target_transform = transforms.Lambda(\n lambda y, x=task_id: y + x*classes_per_task\n ) if scenario in ('task', 'class') else None\n train_datasets.append(TransformedDataset(\n train_dataset, transform=transforms.Lambda(lambda x, p=rot: _rotate_image(x, p)),\n target_transform=target_transform\n ))\n test_datasets.append(TransformedDataset(\n test_dataset, transform=transforms.Lambda(lambda x, p=rot: _rotate_image(x, p)),\n target_transform=target_transform\n ))\n\n elif name == 'CIFAR10':\n # check for number of tasks\n if tasks > 10:\n raise ValueError(\"Experiment 'CIFAR10' cannot have more than 10 tasks!\")\n # configurations\n config = DATASET_CONFIGS['cifar10']\n classes_per_task = int(np.floor(10 / tasks))\n\n if not only_config:\n # prepare permutation to shuffle label-ids (to create different class batches for each random seed)\n permutation = np.random.permutation(list(range(10)))\n target_transform = transforms.Lambda(lambda y, x=permutation: int(permutation[y]))\n # prepare train and test datasets with all classes\n cifar10_train = get_dataset('cifar10', mode=\"train\", dir=data_dir, normalize=normalize,\n augment=augment, target_transform=target_transform, verbose=verbose)\n cifar10_test = get_dataset('cifar10', mode=\"test\", dir=data_dir, normalize=normalize,\n target_transform=target_transform, verbose=verbose)\n # generate labels-per-task\n labels_per_task = [\n list(np.array(range(classes_per_task)) + classes_per_task * task_id) for task_id in range(tasks)\n ]\n # split them up into sub-tasks\n train_datasets = []\n test_datasets = []\n for labels in labels_per_task:\n target_transform = transforms.Lambda(lambda y, x=labels[0]: y-x) if scenario=='domain' else None\n train_datasets.append(SubDataset(cifar10_train, labels, target_transform=target_transform))\n test_datasets.append(SubDataset(cifar10_test, labels, target_transform=target_transform))\n\n elif name == 'CIFAR100':\n # check for number of tasks\n if tasks>100:\n raise ValueError(\"Experiment 'CIFAR100' cannot have more than 100 tasks!\")\n # configurations\n config = DATASET_CONFIGS['cifar100']\n classes_per_task = int(np.floor(100 / tasks))\n if not only_config:\n # prepare permutation to shuffle label-ids (to create different class batches for each random seed)\n permutation = np.random.permutation(list(range(100)))\n target_transform = transforms.Lambda(lambda y, x=permutation: int(permutation[y]))\n # prepare train and test datasets with all classes\n cifar100_train = get_dataset('cifar100', mode=\"train\", dir=data_dir, normalize=normalize,\n augment=augment, target_transform=target_transform, verbose=verbose)\n cifar100_test = get_dataset('cifar100', mode=\"test\", dir=data_dir, normalize=normalize,\n target_transform=target_transform, verbose=verbose)\n # generate labels-per-task\n labels_per_task = [\n list(np.array(range(classes_per_task)) + classes_per_task * task_id) for task_id in range(tasks)\n ]\n # split them up into sub-tasks\n train_datasets = []\n test_datasets = []\n for labels in labels_per_task:\n target_transform = transforms.Lambda(lambda y, x=labels[0]: y-x) if scenario=='domain' else None\n train_datasets.append(SubDataset(cifar100_train, labels, target_transform=target_transform))\n test_datasets.append(SubDataset(cifar100_test, labels, target_transform=target_transform))\n\n elif name == 'CUB2011':\n # check for number of tasks\n if tasks > 10:\n raise ValueError(\"Experiment 'CUB-200-2011' cannot have more than 10 tasks!\")\n # configurations\n config = DATASET_CONFIGS[name.lower()]\n classes_per_task = int(np.floor(200 / tasks))\n\n if not only_config:\n # prepare permutation to shuffle label-ids (to create different class batches for each random seed)\n permutation = np.random.permutation(list(range(200)))\n target_transform = transforms.Lambda(lambda y, x=permutation: int(permutation[y]))\n # prepare train and test datasets with all classes\n cub2011_train = get_dataset(name.lower(), mode=\"train\", dir=data_dir, normalize=normalize,\n augment=augment, target_transform=target_transform, verbose=verbose)\n cub2011_test = get_dataset(name.lower(), mode=\"test\", dir=data_dir, normalize=normalize,\n augment=augment, target_transform=target_transform, verbose=verbose)\n # generate labels-per-task\n labels_per_task = [\n list(np.array(range(classes_per_task)) + classes_per_task * task_id) for task_id in range(tasks)\n ]\n # split them up into sub-tasks\n train_datasets = []\n test_datasets = []\n for labels in labels_per_task:\n target_transform = transforms.Lambda(lambda y, x=labels[0]: y-x) if scenario == 'domain' else None\n train_datasets.append(SubDataset(cub2011_train, labels, target_transform=target_transform))\n test_datasets.append(SubDataset(cub2011_test, labels, target_transform=target_transform))\n\n elif name == 'ImageNet':\n # check for number of tasks\n if tasks > 1000:\n raise ValueError(\"Experiment 'ImageNet' cannot have more than 1000 tasks!\")\n # configurations\n config = DATASET_CONFIGS['imagenet']\n classes_per_task = int(np.floor(1000 / tasks))\n if not only_config:\n # prepare permutation to shuffle label-ids (to create different class batches for each random seed)\n permutation = np.random.permutation(list(range(1000)))\n target_transform = transforms.Lambda(lambda y, x=permutation: int(permutation[y]))\n # prepare train and test datasets with all classes\n imagenet_train = get_dataset('imagenet', mode=\"train\", dir=data_dir, normalize=normalize,\n augment=augment, target_transform=target_transform, verbose=verbose)\n imagenet_test = get_dataset('imagenet', mode=\"test\", dir=data_dir, normalize=normalize,\n target_transform=target_transform, verbose=verbose)\n # generate labels-per-task\n labels_per_task = [\n list(np.array(range(classes_per_task)) + classes_per_task * task_id) for task_id in range(tasks)\n ]\n # split them up into sub-tasks\n train_datasets = []\n test_datasets = []\n for labels in labels_per_task:\n target_transform = transforms.Lambda(lambda y, x=labels[0]: y - x) if scenario == 'domain' else None\n train_datasets.append(SubDataset(imagenet_train, labels, target_transform=target_transform))\n test_datasets.append(SubDataset(imagenet_test, labels, target_transform=target_transform))\n else:\n raise RuntimeError('Given undefined experiment: {}'.format(name))\n\n # If needed, update number of (total) classes in the config-dictionary\n config['classes'] = classes_per_task if scenario == 'domain' else classes_per_task*tasks\n config['normalize'] = normalize if name in ['CUB2011', 'CIFAR10', 'CIFAR100', 'ImageNet'] else False\n if config['normalize']:\n config['denormalize'] = AVAILABLE_TRANSFORMS[\"{}_denorm\".format(name.lower())]\n\n # Return tuple of train-, validation- and test-dataset, config-dictionary and number of classes per task\n return config if only_config else ((train_datasets, test_datasets), config, classes_per_task)\n\n\nif __name__ == '__main__':\n image = torch.rand((1, 28, 28))\n print(image.size())\n img = transforms.ToPILImage()(image)\n # rot_img = F.rotate(img, 180)\n plt.imshow(img)\n plt.show()\n # plt.imshow(rot_img)\n # plt.show()\n # print(type(img), img.shape)","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":27653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"204937192","text":"import argparse\nimport cv2\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data, model_zoo\nimport numpy as np\nimport pickle\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport scipy.misc\nimport torch.backends.cudnn as cudnn\nimport sys\nfrom torchvision import transforms\nfrom transformers import Rescale\nimport os\nimport os.path as osp\nimport pickle\nfrom config import config\nfrom tqdm import tqdm\nfrom dataloader import MyDataSet\nfrom torch.utils import data\nfrom blocks import PolyLR, init_weight\nfrom sync_batchnorm import SynchronizedBatchNorm2d\nfrom generator import NestedUNet\nfrom discriminator import Discriminator_FCN\nfrom losses import ProbOhemCrossEntropy2d, Dice_loss\nfrom lovasz_losses import lovasz_softmax\n#import matplotlib.pyplot as plt\nimport random\nimport timeit\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0,1,2,3,4\" # specify which GPU(s) to be used\n\n\n\ndef lr_poly(base_lr, iter, max_iter, power):\n return base_lr*((1-float(iter)/max_iter)**(power))\n\n\ndef adjust_learning_rate(optimizer, i_iter):\n lr = lr_poly(config.lr, i_iter, config.total_niters, config.lr_power)\n optimizer.param_groups[0]['lr'] = lr\n if len(optimizer.param_groups) > 1 :\n optimizer.param_groups[1]['lr'] = lr * 10\n return lr\n\ndef adjust_learning_rate_D(optimizer, i_iter):\n lr = lr_poly(config.lr_D, i_iter, config.total_niters, config.lr_power)\n optimizer.param_groups[0]['lr'] = lr\n if len(optimizer.param_groups) > 1 :\n optimizer.param_groups[1]['lr'] = lr * 10\n return lr\n\ndef one_hot(label):\n label = label.cpu().numpy()\n one_hot = np.zeros((label.shape[0], config.num_classes, label.shape[1], label.shape[2]), dtype=label.dtype)\n for i in range(config.num_classes):\n one_hot[:,i,...] = (label==i)\n #handle ignore labels\n return torch.FloatTensor(one_hot).cuda()\n\ndef make_D_label(label, ignore_mask):\n ignore_mask = np.expand_dims(ignore_mask, axis=1)\n D_label = np.ones(ignore_mask.shape)*label\n D_label[ignore_mask] = 255\n D_label = Variable(torch.FloatTensor(D_label)).cuda(args.gpu)\n\n return D_label\n\n\ndef main():\n if not os.path.exists(config.snapshot_dir):\n os.makedirs(config.snapshot_dir)\n\n BatchNorm2d = SynchronizedBatchNorm2d\n\n # loss for adversarial training\n bce_criterion = nn.BCELoss().cuda()\n\n # loss for segmentation\n # criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=255)\n criterion = ProbOhemCrossEntropy2d(ignore_label=255, thresh=0.7, min_kept=100000, use_weight=False)\n dice_criterion = Dice_loss(config.num_classes)\n # dice_criterion = lovasz_softmax\n\n # create network\n model = NestedUNet(config.num_classes, criterion=criterion,\n dice_criterion=dice_criterion, \n is_training=True,\n norm_layer=BatchNorm2d,\n gamma=2) #Note gamma is the hyper-parameter for adversarial confidence learning\n init_weight(model.business_layer, nn.init.kaiming_normal_,\n BatchNorm2d, config.bn_eps, config.bn_momentum,\n mode='fan_in', nonlinearity='relu')\n\n model = model.cuda()\n model = nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))\n model.train()\n\n # init D\n model_D = Discriminator_FCN(num_classes=config.num_classes+3)\n init_weight(model_D.business_layer, nn.init.kaiming_normal_,\n BatchNorm2d, config.bn_eps, config.bn_momentum)\n model_D = model_D.cuda()\n model_D = nn.DataParallel(model_D, device_ids=range(torch.cuda.device_count()))\n\n if config.restore_from_D is not None:\n model_D.load_state_dict(torch.load(config.restore_from_D))\n model_D.train()\n\n train_dataset = MyDataSet(config.train_source, img_mean=config.image_mean, img_std=config.image_std, transform=transforms.Compose([Rescale((1024, 1024))]))\n # val_dataset = MyDataSet(config.eval_source)\n train_loader = data.DataLoader(train_dataset, batch_size=config.batch_size, shuffle=True, num_workers=config.num_workers)\n # val_loader = data.DataLoader(val_dataset, batch_size=config.batch_size, shuffle=True)\n\n # optimizer for segmentation network\n optimizer = optim.SGD(model.parameters(),\n lr=config.lr, momentum=config.momentum,weight_decay=config.weight_decay)\n optimizer.zero_grad()\n\n # optimizer for discriminator network\n optimizer_D = optim.SGD(model_D.parameters(), lr=config.lr_D, momentum=config.momentum,weight_decay=config.weight_decay)\n optimizer_D.zero_grad()\n\n\n base_lr = config.lr\n # config lr policy\n\n for epoch in range(config.nepochs):\n # t = tqdm(enumerate(iter(train_loader)), leave=False, total=len(train_loader))\n bar_format = '{desc}[{elapsed}<{remaining},{rate_fmt}]'\n pbar = tqdm(range(config.niters_per_epoch), file=sys.stdout, bar_format=bar_format)\n dataloader = iter(train_loader)\n # for batch_idx, batch in t:\n for batch_idx in pbar:\n minibatch = dataloader.next()\n x_ = Variable(minibatch[0]).type(torch.FloatTensor).contiguous().cuda(non_blocking=True)\n y_ = Variable(minibatch[1]).type(torch.LongTensor).contiguous().cuda(non_blocking=True)\n\n current_idx = epoch * config.niters_per_epoch + batch_idx\n\n # train D first\n optimizer_D.zero_grad()\n lr_D = adjust_learning_rate_D(optimizer_D, current_idx)\n\n x_, y_ = Variable(x_.cuda()), Variable(y_.cuda())\n\n D_result = model_D(x_, one_hot(y_))\n # print('D_result.shape is ',D_result.shape)\n D_result = F.interpolate(D_result, size=(x_.shape[-1], x_.shape[-2]), mode='bilinear', align_corners=True).squeeze()\n # print('D_result.shape is ',D_result.shape)\n #print('shape0: ',D_result.shape, '...', D_result, '...')\n D_result = F.sigmoid(D_result)\n #print('shape1: ',D_result.squeeze().shape, '...', D_result, '...')\n #cv2.imwrite('real_output.jpg', D_result[0, ...].cpu().detach().numpy().squeeze())\n D_real_loss = bce_criterion(D_result, Variable(torch.ones(D_result.size()).cuda()))\n\n G_result = model(x_) # has already softmaxed\n D_result = model_D(x_, G_result)\n D_result = F.interpolate(D_result, size=(x_.shape[-1], x_.shape[-2]), mode='bilinear', align_corners=True).squeeze()\n D_result = F.sigmoid(D_result)\n #cv2.imwrite('fake_output.jpg',D_result[0,...].cpu().detach().numpy().squeeze())\n D_fake_loss = bce_criterion(D_result, Variable(torch.zeros(D_result.size()).cuda()))\n #print('D_real_loss.mean: ',D_real_loss.mean().item(),' D_fake_loss.mean(): ',D_fake_loss.mean().item())\n D_train_loss = (D_real_loss + D_fake_loss) * 0.5\n D_train_loss = D_train_loss.mean()\n D_train_loss.backward()\n optimizer_D.step()\n\n\n # then train G\n optimizer.zero_grad()\n lr = adjust_learning_rate(optimizer, current_idx)\n D_result = model_D(x_, G_result)\n D_result = F.interpolate(D_result, size=(x_.shape[-1], x_.shape[-2]), mode='bilinear', align_corners=True).squeeze()\n D_result = F.sigmoid(D_result)\n G_adv_loss = bce_criterion(D_result, Variable(torch.ones(D_result.size()).cuda()))\n G_result, loss_seg, loss_ce, loss_dice = model(x_,y_, D_result)\n loss_seg = loss_seg.mean()\n G_adv_loss = G_adv_loss.mean()\n G_train_loss = config.lambda_adv*G_adv_loss + loss_seg\n G_train_loss.backward()\n optimizer.step()\n\n print_str = 'Epoch{}/{}'.format(epoch, config.nepochs) \\\n + ' Iter{}/{}:'.format(batch_idx + 1, config.niters_per_epoch) \\\n + ' lr_D=%.3e' %lr_D \\\n + ' D_train_loss=%.2f'%D_train_loss.item()\\\n + ' lr=%.3e' % lr \\\n + ' G_adv_loss=%.2f' % G_adv_loss.item() \\\n + ' loss_seg=%.2f' % loss_seg.item() \\\n + ' loss_ce=%.2f' % loss_ce.mean().item() \\\n + ' loss_dice=%.2f' % loss_dice.mean().item() +'\\n'\n\n pbar.set_description(print_str, refresh=False)\n\n if (epoch > config.nepochs - 20) or (epoch % config.snapshot_iter == 0):\n state = {\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n }\n torch.save(state, os.path.join(config.snapshot_dir,'modelG_Epoch%d.pth'%epoch))\n stateD = {\n 'epoch': epoch,\n 'state_dict': model_D.state_dict(),\n 'optimizer': optimizer_D.state_dict(),\n }\n torch.save(stateD, os.path.join(config.snapshot_dir,'modelD_Epoch%d.pth'%epoch))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"train_conGAN.py","file_name":"train_conGAN.py","file_ext":"py","file_size_in_byte":9005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"178897007","text":"#!/usr/bin/env python\n\n\nfrom os.path import splitext, basename, join\nimport SimpleITK as sitk\nimport numpy as np\ntry:\n from scipy.misc import imsave\n imsave_available = True\nexcept ImportError:\n imsave_available = True\n\nimport common\nfrom logzero import logger as logging\n\ndef make_normalization_roi_qc_images(img_dir, roi, out_dir):\n \"\"\"\n Make some QC images showing the roi used for normalization overlaid on the registered, normalised images\n Parameters\n ----------\n norm_image_folder: str\n path to normalised images\n roi: list\n [roi starts, roi_ends] z,yx\n \"\"\"\n\n if not imsave_available:\n logging.warning(\"Cannot import scipy.misc.imsave. So can't make QC ROI overlays\")\n return\n file_paths = common.get_file_paths(img_dir)\n if not file_paths or len(file_paths) < 1:\n return\n\n roi_starts, roi_ends = roi\n # Flip to zyx as they are passed in as zyx from the config file\n roi_starts = list(reversed(roi_starts))\n roi_ends = list(reversed(roi_ends))\n\n\n for img_path in file_paths:\n\n img = sitk.ReadImage(img_path)\n cast_img = sitk.Cast(sitk.RescaleIntensity(img), sitk.sitkUInt8)\n arr = sitk.GetArrayFromImage(cast_img)\n\n try:\n sag_slice_index = roi_starts[2] + ((roi_ends[2] - (roi_starts[2])) /2)\n cor_slice_index = roi_starts[1] + ((roi_ends[1] - (roi_starts[1])) / 2)\n ax_slice_index = roi_starts[0] + ((roi_ends[0] - (roi_starts[0])) / 2)\n except IndexError:\n print(roi_starts, roi_ends)\n logging.warn(\"Cannot generate roi QC overlays. ROi is out of bounds\")\n return\n try:\n sag_slice = arr[:, :, sag_slice_index]\n cor_slice = arr[:, cor_slice_index, :]\n ax_slice = arr[ax_slice_index, :, :]\n except IndexError:\n logging.warn(\"Cannot generate roi QC overlays. ROi is out of bounds\")\n return\n roi_props = []\n roi_props.append([sag_slice, roi_starts[0:2], roi_ends[0:2], True])\n roi_props.append([cor_slice, [roi_starts[0], roi_starts[2]], [roi_ends[0], roi_ends[2]], True])\n roi_props.append([ax_slice, [roi_starts[1], roi_starts[2]], [roi_ends[1], roi_ends[2]], False])\n # Draw roi on the slice\n widths = []\n heights = []\n images = []\n for slice_, roi_starts_1, roi_ends_1, do_flip in roi_props:\n widths.append(slice_.shape[1])\n heights.append(slice_.shape[0])\n yellow_indices = bounding_box_indices(roi_starts_1, roi_ends_1)\n rgb_arr = grey_to_rgb(slice_)\n for index in yellow_indices:\n rgb_arr[index[0], index[1]] = [255, 255, 0]\n if do_flip:\n images.append(np.flipud(rgb_arr))\n else:\n images.append(rgb_arr)\n\n # create an image array the combined width of the threee images\n max_height = max(heights)\n total_width = sum(widths)\n out_img_arr = np.zeros(max_height * total_width * 3).reshape((max_height, total_width, 3))\n\n accumulated_width = 0\n\n for single_rgb_img in images:\n width = single_rgb_img.shape[1]\n height = single_rgb_img.shape[0]\n print(out_img_arr[0: height, accumulated_width:accumulated_width + width].shape)\n print(single_rgb_img.shape)\n out_img_arr[0: height, accumulated_width: accumulated_width + width] = single_rgb_img\n accumulated_width += width\n base = splitext(basename(img_path))[0]\n out_path = join(out_dir, base + '.png')\n imsave(out_path, out_img_arr)\n\n\ndef bounding_box_indices(roi_starts, roi_ends):\n indices = []\n y1 = roi_starts[0]\n y2 = roi_ends[0]\n x1 = roi_starts[1]\n x2 = roi_ends[1]\n\n #left vertical\n for i in range(y1, y2):\n indices.append([i, x1])\n # right vertical\n for i in range(y1, y2):\n indices.append([i, x2])\n # top row\n for i in range(x1, x2):\n indices.append([y1, i])\n # bottom row\n for i in range(x1, x2):\n indices.append([y2, i])\n return indices\n\n\n\ndef grey_to_rgb(im):\n return np.asarray(np.dstack((im, im, im)), dtype=np.uint8)\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(\"The MRC Harwell image registration pipeline\")\n parser.add_argument('-i', dest='in_dir', help='A dir with images to overlay roi', required=True)\n parser.add_argument('-o', dest='out_dir', help='out directory', required=True)\n parser.add_argument('-s', dest='starts', help='start indices (x, y, z)', required=True, nargs=3, type=int)\n parser.add_argument('-e', dest='ends', help='end indices (x, y, z)', required=True, nargs=3, type=int)\n args = parser.parse_args()\n\n roi = [args.starts, args.ends]\n\n make_normalization_roi_qc_images(args.in_dir, roi, args.out_dir)","sub_path":"lama/qc/roi_overlay.py","file_name":"roi_overlay.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"178788927","text":"from datetime import timedelta\nfrom django.db.models import F\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.utils import timezone\n# import sendgrid\n# import os\n# from sendgrid.helpers.mail import *\nfrom django.core.mail import send_mail\nfrom django.contrib.auth.models import User\nfrom careplus.medications.models import Medication, MedicationCompletion, MedicationTime\nfrom careplus.residents.models import Resident\nfrom careplus.medications.tasks import send_test_email\n\n\n\n#This reads when the MedicationComplation form is saved. \n#When saved, signal is sent and updates the medicationStatus to True. \n#Meaning this medication has had action taken on it.\n@receiver(post_save, sender=MedicationCompletion)\ndef check_medication_status(sender, instance, created, **kwargs):\n\n\tif created:\n\t\ta = instance.completionMedication_id\n\t\tb = MedicationTime.objects.get(id=a)\n\t\tc = b.timeGivenStatus = 'True'\n\t\tb.save()\n\n\n#Update the completiontime object with the parent timeDue for reporting\n#purposes.\n@receiver(post_save, sender=MedicationCompletion)\ndef f(sender, instance, created, **kwargs):\n\n\t\ta = instance.completionMedication_id\n\t\tb = MedicationTime.objects.filter(id=a).values_list('timeDue', flat=True)\n\t\tMedicationCompletion.objects.filter(id=instance.id).update(completionDue=b[0])\n\n\n\n#Subtracts medication count each time medication given. Once medication reaches >= 5, then medication signal is fired off with email to pharmacy requesting refill for \n#patien't medication (tihs will be updated for users to choose how many days until the notificatino is sent (5 by default at ths time.)\n@receiver(post_save, sender=MedicationCompletion)\t\ndef update_medication_count(sender, instance, created, **kwargs):\t\n\n\tif created:\n\t\ta = instance.completionMedication_id\n\t\tb = MedicationTime.objects.filter(id=a).values('timeMedication_id')\n\t\tif instance.completionStatus == True:\n\t\t\tMedication.objects.filter(id=b).update(medicationQuantity=F('medicationQuantity') -1)\n\n#This code cheks the recent creation of the medication and if any of the medicationTimeSchedule 1-6 are not null,then take the value in there and create a new medicationTime\n#The medicationTime was the easiest way to split the medication in to bite sized chunks of pills to make the MAR work as needed. Note, at the very end, you will see \n#medicationDistribution = '0', this means the medication is a PRN and only one needs to be created and timeDue is None since it is PRN and must always be present.\n\n@receiver(post_save, sender=Medication, dispatch_uid='medication_time_add')\ndef create_medication_time(sender, instance, created, **kwargs):\n\n\tif created:\n\t\ttime = timezone.now()\n\t\ta = instance.id\n\t\tb = instance.medicationTimeSchedule\n\t\tc = instance.medicationTimeSchedule2\n\t\td = instance.medicationTimeSchedule3\n\t\te = instance.medicationTimeSchedule4\n\t\tf = instance.medicationTimeSchedule5\n\t\tg = instance.medicationTimeSchedule6\n\t\tif instance.medicationTimeSchedule != None:\n\t\t\tMedicationTime.objects.create(timeStatus=None, timeGivenStatus=False, timeCreated=time, timeDue=b, timeMedication_id=a, timeGivenNote='Auto Generated')\n\t\tif instance.medicationTimeSchedule2 != None:\n\t\t\tMedicationTime.objects.create(timeStatus=None, timeGivenStatus=False, timeCreated=time, timeDue=c, timeMedication_id=a, timeGivenNote='Auto Generated')\n\t\tif instance.medicationTimeSchedule3 != None:\n\t\t\tMedicationTime.objects.create(timeStatus=None, timeGivenStatus=False, timeCreated=time, timeDue=d, timeMedication_id=a, timeGivenNote='Auto Generated')\n\t\tif instance.medicationTimeSchedule4 != None:\n\t\t\tMedicationTime.objects.create(timeStatus=None, timeGivenStatus=False, timeCreated=time, timeDue=e, timeMedication_id=a, timeGivenNote='Auto Generated')\n\t\tif instance.medicationTimeSchedule5 != None:\n\t\t\tMedicationTime.objects.create(timeStatus=None, timeGivenStatus=False, timeCreated=time, timeDue=f, timeMedication_id=a, timeGivenNote='Auto Generated')\n\t\tif instance.medicationTimeSchedule6 != None:\n\t\t\tMedicationTime.objects.create(timeStatus=None, timeGivenStatus=False, timeCreated=time, timeDue=g, timeMedication_id=a, timeGivenNote='Auto Generated')\n\t\tif instance.medicationDistribution == '0':\n\t\t\tMedicationTime.objects.create(timeStatus=None, timePRN=True, timeGivenStatus=None, timeCreated=time, timeDue=None, timeMedication_id=a, timeGivenNote='Auto Generated - PRN')\n\n\n#This line of code was fun. In order for the MAR form to fill out correctly, I had to have fillers for the dates existed\n#before the medication was started. Example (without this code) if the medication start date waas 7/15/2017, then when the MAR form goes through its loops,\n#the first record would be placed under the 1st of the month. This is incorrect since the medication should start on the 15th of the month. \n#to solve this, I created this signal which is fired whenever a new medicationTime is created.\n#It (1) gets the startDate of the medication from the medicationTime (2) strips the day from it (3) converts it to an integer (4) checks if the integer (days)\n#is greater than 1 (i.e. the first of the month) (5) if it is, then create c - 1 many records to fill the void.\n#This allows for the loop to fill in the correct dates with the correct dates in the MAR. Problem solved\n#Note, I will probably look back on this in a few months or weeks and think this was a completely stupid way to do this, but it solves my problem at this point.\n#One issue, that Celery may be able to solve, is the Model.objects.latest(). This works great if there isonly one person entering medication, but what\n#happens if two pepole simultaneously enter different medications? Is it possible person a will get person b's latest medication from the DB (note, the latest is to retrieve\n#the most recently created medication. Since the medication kicks off the medicationTime creation signal, and the creation of the medicationTime kicks off this signal,\n#then there is a possibility - it seems - that you could have incorrect medication returned. This, again, is only an issue if there is more than one. For \n#carePlus home care plus facilities, it shouldn't be given small size of employee base. If we scale this, though, this code will need to be looked further in to.\n\n@receiver(post_save, sender=MedicationTime)\ndef create_medication_time_fill(sender, instance, created, **kwargs):\n\n\tif created:\n\t\tmed = Medication.objects.latest('medicationStartDate')\n\t\ta = med.medicationStartDate\n\t\tb = a.strftime('%d')\n\t\tc = int(b)\n\t\ttime = timezone.now()\n\t\td = instance.id\n\t\tif c > 1:\n\t\t\twhile (c > 1):\n\t\t\t\tc = c - 1\n\t\t\t\taa = a - timedelta(days=c)\n\t\t\t\tprint(\"THIS IS FROM SIGNAL\" + str(aa))\n\t\t\t\tfillRxTime = MedicationCompletion(completionStatus=None, completionDate=aa, completionDue=instance.timeDue, completionNote='SYSTEM RX PLACEHOLDER FILL', completionRx_id=med.id, completionMedication_id=instance.id)\n\t\t\t\tfillRxTime.save()\n\n##########################################\n###########Sendgrid Email Signals#########\n##########################################\n\n#Request Refill Signal - Needs some tweaking. \n@receiver(post_save, sender=MedicationCompletion, dispatch_uid='medication_refill')\ndef request_medication_refill(sender, instance, created, **kwargs):\n\n\tmed = Medication.objects.get(id=instance.completionRx_id)\n\tcount = med.medicationQuantity\n\tprint(count)\n\tif created:\n\t\tif count <= 5:\n\t\t\temail = 'stemado@outlook.com'\n\t\t\tsubject = 'Rx Refill Request: ' + str(med.medicationResident)\n\t\t\tcontent = \"Resident: \" + str(med.medicationResident) + \"needs Medication \" + str(med.medicationName) + \" refilled. Remaining Pill Count: \" + str(med.medicationQuantity)\n\t\t\tsend_mail(\n\t\t\t\tsubject, \n\t\t\t\tcontent, \n\t\t\t\t'no-reply@careplus.com', \n\t\t\t\t[email], \n\t\t\t\tfail_silently=False\n\t\t\t\t)\n\t\t\tprint('EMAIL SENT!')\n\t\telse:\n\t\t\tprint('It didn not send, home skillet.')\n\n# @receiver(post_save, sender=Medication)\n# def new_test_email(sender, instance, created, **kwargs):\n\n# \tif created:\n# \t\tsend_test_email.delay(each)\n# \t\tprint('Celery email is delayed...now what?')\n\n# \telse:\n# \t\tprint('Well, this did not work. Try again tomorrow')\n\n\n#################################################\n############## TWILIO SIGNALS ###################\n#################################################\n\n\n","sub_path":"careplus/medications/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":8243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"402659840","text":"from flask import Flask, url_for, request, render_template, redirect, make_response, abort\nfrom flask import session as flask_session\nfrom flask_login import LoginManager, login_user, logout_user, login_required, current_user\nimport os\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField, BooleanField, SubmitField, DateTimeField, IntegerField\nfrom wtforms.validators import DataRequired\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom data import db_session\nfrom data.users import User\nfrom data.jobs import Jobs\nfrom data.department import Department\nfrom data.category import Category\nimport pprint\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'yandexlyceum_secret_key'\n\ndb_session.global_init('db/mars.sqlite')\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\npath_to_templates = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"template\")\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n session = db_session.create_session()\n return session.query(User).get(user_id)\n\n\nclass RegisterForm(FlaskForm):\n login = StringField('Login / email', validators=[DataRequired()])\n password = PasswordField('Password', validators=[DataRequired()])\n rep_password = PasswordField('Repeat password', validators=[DataRequired()])\n surname = StringField('Surname', validators=[DataRequired()])\n name = StringField('Name', validators=[DataRequired()])\n age = StringField('Age', validators=[DataRequired()])\n position = StringField('Position', validators=[DataRequired()])\n specialty = StringField('Specialty', validators=[DataRequired()])\n address = StringField('Address', validators=[DataRequired()])\n submit = SubmitField('Submit')\n\n\nclass LoginForm(FlaskForm):\n login = StringField('Login / email', validators=[DataRequired()])\n password = PasswordField('Password', validators=[DataRequired()])\n remember_me = BooleanField('Запомнить меня')\n submit = SubmitField('Войти')\n\n\nclass JobForm(FlaskForm):\n team_leader = IntegerField(\"Тим Лидер\", validators=[DataRequired()])\n job = StringField(\"Описание задания\", validators=[DataRequired()])\n categories = StringField(\"Категории\")\n work_size = IntegerField(\"Количество часов для выполнения\", validators=[DataRequired()])\n collaborators = StringField(\"Id членов команды\", validators=[DataRequired()])\n start_date = DateTimeField(\"Дата начала (d.m.Y h.m)\", format='%d.%m.%Y %H:%M')\n is_finished = BooleanField('Закончена?')\n submit = SubmitField(\"Сохранить\")\n\nclass DepartmentForm(FlaskForm):\n chief = IntegerField(\"Шеф\", validators=[DataRequired()])\n title = StringField(\"Название \", validators=[DataRequired()])\n members = StringField(\"Члены\", validators=[DataRequired()])\n email = StringField(\"E-mail\", validators=[DataRequired()])\n submit = SubmitField(\"Сохранить\")\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n session = db_session.create_session()\n user = session.query(User).filter(User.email == form.login.data).first()\n if user and user.check_password(form.password.data):\n login_user(user, remember=form.remember_me.data)\n return redirect(\"/\")\n return render_template('login.html',\n message=\"Неправильный логин или пароль\",\n form=form)\n return render_template('login.html', title='Авторизация', form=form)\n\n\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n form = RegisterForm()\n\n if form.validate_on_submit():\n if form.password.data != form.rep_password.data:\n return render_template('register.html', title='Регистрация',\n form=form,\n message=\"Пароли не совпадают\")\n session = db_session.create_session()\n if session.query(User).filter(User.email == form.login.data).first():\n return render_template('register.html', title='Регистрация',\n form=form,\n message=\"Такой пользователь уже есть\")\n user = User(\n surname=form.surname.data,\n name=form.name.data,\n email=form.login.data,\n age=form.age.data,\n position=form.position.data,\n specialty=form.specialty.data,\n address=form.address.data\n )\n user.set_password(form.password.data)\n session.add(user)\n session.commit()\n print(\"success\")\n return redirect('/login')\n\n return render_template('register.html', title='Регистрация', form=form)\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(\"/\")\n \n\n@app.route(\"/\")\ndef index():\n session = db_session.create_session()\n jobs = session.query(Jobs)\n return render_template(\"index.html\", title=\"Миссия Марс\", jobs=jobs)\n\n\n@app.route('/addjob', methods=['GET', 'POST'])\n@login_required\ndef add_job():\n form = JobForm()\n if form.validate_on_submit():\n session = db_session.create_session()\n job = Jobs()\n job.team_leader = form.team_leader.data\n job.job = form.job.data\n job.work_size = form.work_size.data\n job.collaborators = form.collaborators.data\n job.start_date = form.start_date.data\n job.is_finished = form.is_finished.data\n job.categories = list(\n session.query(Category).\\\n filter(Category.id.in_(\n map(str.strip, form.categories.data.split(','))\n )\n )\n )\n session.add(job)\n session.commit()\n return redirect('/')\n return render_template('job_form.html', title='Добавление задания', \n form=form)\n\n\n@app.route('/job/', methods=['GET', 'POST'])\n@login_required\ndef edit_job(id):\n form = JobForm()\n if request.method == \"GET\":\n session = db_session.create_session()\n job = session.query(Jobs).filter(Jobs.id == id).first()\n if job and (job.user == current_user or current_user.id == 1):\n form.team_leader.data = job.team_leader\n form.job.data = job.job\n form.work_size.data = job.work_size\n form.collaborators.data = job.collaborators\n form.start_date.data = job.start_date\n form.is_finished.data = job.is_finished\n form.categories.data = ', '.join(map(lambda x: str(x.id), job.categories))\n else:\n abort(404)\n if form.validate_on_submit():\n session = db_session.create_session()\n job = session.query(Jobs).filter(Jobs.id == id).first()\n if job:\n job.team_leader = form.team_leader.data\n job.job = form.job.data\n job.work_size = form.work_size.data\n job.collaborators = form.collaborators.data\n job.start_date = form.start_date.data\n job.is_finished = form.is_finished.data\n job.categories.clear()\n job.categories = list(\n session.query(Category).\\\n filter(Category.id.in_(\n map(str.strip, form.categories.data.split(','))\n )\n )\n )\n session.commit()\n return redirect('/')\n else:\n abort(404)\n return render_template('job_form.html', title='Редактирование задания', form=form)\n\n\n@app.route('/delete_job/', methods=['GET', 'POST'])\n@login_required\ndef delete_job(id):\n session = db_session.create_session()\n job = session.query(Jobs).filter(Jobs.id == id).first()\n if job and (job.user == current_user or current_user.id == 1):\n session.delete(job)\n session.commit()\n else:\n abort(404)\n return redirect('/')\n\n\n@app.route(\"/departments\")\ndef department():\n session = db_session.create_session()\n departments = session.query(Department)\n return render_template(\"departments.html\", title=\"Список департаментов\", departments=departments)\n\n\n@app.route('/adddepartment', methods=['GET', 'POST'])\n@login_required\ndef add_department():\n form = DepartmentForm()\n if form.validate_on_submit():\n session = db_session.create_session()\n department = Department()\n department.chief = form.chief.data\n department.title = form.title.data\n department.members = form.members.data\n department.email = form.email.data\n session.add(department)\n session.commit()\n return redirect('/departments')\n return render_template('department_form.html', title='Добавление задания', \n form=form)\n\n\n@app.route('/departments/', methods=['GET', 'POST'])\n@login_required\ndef edit_department(id):\n form = DepartmentForm()\n if request.method == \"GET\":\n session = db_session.create_session()\n department = session.query(Department).filter(Department.id == id).first()\n if department and (department.user == current_user or current_user.id == 1):\n form.chief.data = department.chief\n form.title.data = department.title\n form.members.data = department.members\n form.email.data = department.email\n else:\n abort(404)\n if form.validate_on_submit():\n session = db_session.create_session()\n department = session.query(Department).filter(Department.id == id).first()\n if department:\n department.chief = form.chief.data\n department.title = form.title.data\n department.members = form.members.data\n department.email = form.email.data\n session.commit()\n return redirect('/departments')\n else:\n abort(404)\n return render_template('department_form.html', title='Редактирование департамента', form=form)\n\n\n@app.route('/delete_department/', methods=['GET', 'POST'])\n@login_required\ndef delete_department(id):\n session = db_session.create_session()\n department = session.query(Department).filter(Department.id == id).first()\n if department and (department.user == current_user or current_user.id == 1):\n session.delete(department)\n session.commit()\n else:\n abort(404)\n return redirect('/departments')\n\n\n@app.route(\"/cookie_test\")\ndef cookie_test():\n visits_count = int(request.cookies.get(\"visits_count\", 0))\n if visits_count:\n res = make_response(f\"Вы пришли на эту страницу {visits_count + 1} раз\")\n res.set_cookie(\"visits_count\", str(visits_count + 1), \n max_age=60 * 60 * 24 * 365 * 2)\n else:\n res = make_response(\n \"Вы пришли на эту страницу в первый раз за последние 2 года\")\n res.set_cookie(\"visits_count\", '1', \n max_age=60 * 60 * 24 * 365 * 2)\n return res\n\n\n@app.route('/session_test/')\ndef session_test():\n if 'visits_count' in flask_session:\n flask_session['visits_count'] = flask_session.get('visits_count') + 1\n else:\n flask_session['visits_count'] = 1\n \n return \"visit \" + str(flask_session['visits_count'])\n\n\nif __name__ == '__main__':\n app.run(port=8080, host='127.0.0.1')","sub_path":"Matric/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":11790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"443856802","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Blog\nfrom .forms import BlogPostForm\n\ndef blog_view(request):\n objs = list(Blog.objects.all())\n blog_context = {\n 'objects':objs\n }\n return render(request, \"blogtemplates/blogs.html\",blog_context)\n\ndef blogpost_view(request):\n form = BlogPostForm()\n if request.method == 'POST':\n form = BlogPostForm(request.POST)\n if form.is_valid():\n Blog.objects.create(**form.cleaned_data)\n return redirect('../')\n else:\n print(form.errors)\n bp_context = {\n 'form':form\n }\n return render(request, 'blogpost.html', bp_context)\n\ndef dynamic_blog_url(request, blog_id):\n nblog = get_object_or_404(Blog, id=blog_id)\n queryset = Blog.objects.all()\n\n if request.method == \"POST\":\n nblog.delete()\n return redirect('../')\n nblog_context = {\n 'blog': nblog,\n 'objects': queryset\n }\n return render(request, 'blogview.html', nblog_context)","sub_path":"src/thorbspot/blogs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"111487438","text":"\"\"\"\nProject 7: https://projecteuler.net/problem=7\n\nBy listing the first six prime numbers:\n\n 2, 3, 5, 7, 11, and 13\n\nWe can see that the 6th prime is 13. What is the Nth prime number?\n\"\"\"\nimport itertools\nimport math\n\n\ndef prime_check(number: int) -> bool:\n \"\"\"Determines whether a given number is prime or not\"\"\"\n if number % 2 == 0 and number > 2:\n return False\n return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2))\n\n\ndef prime_generator():\n num = 2\n while True:\n if prime_check(num):\n yield num\n num += 1\n\n\ndef solution(nth: int = 10001) -> int:\n \"\"\"Returns the n-th prime number.\n\n >>> solution(6)\n 13\n >>> solution(1)\n 2\n >>> solution(3)\n 5\n >>> solution(20)\n 71\n >>> solution(50)\n 229\n >>> solution(100)\n 541\n >>> solution()\n 104743\n \"\"\"\n return next(itertools.islice(prime_generator(), nth - 1, nth))\n\n\nif __name__ == \"__main__\":\n print(solution(int(input().strip())))\n","sub_path":"project_euler/problem_07/sol3.py","file_name":"sol3.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"183773773","text":"from 交易数据.CalculateStockPriceDifference import 获取给定时间段的股票最高价\nfrom 函数目录 import profile as pf, date\nimport xlrd\n\ndef 根据股票代码获取上市日期(stock_id,stock_dict):\n return stock_dict.stockDict[\"timeToMarket\"][stock_id]\n\ndef 获取股票上市n天以后的最高价格(stock_id,time_to_market,n_day):\n top_price_date, top_price = 获取给定时间段的股票最高价(stock_id,str(time_to_market),n_day, type=pf.Hfq)\n return top_price_date, top_price\n\ndef 给定一天获取这天以后的超过这个价格的日期及价格(stock_id,start_date,price,type=pf.Hfq):\n #print(stock_id,start_date)\n start_date = date.后几天(start_date,1)\n year, month, day = start_date[0:4], start_date[4:6], start_date[6:8]\n top_price = price\n top_price_date = \"\"\n while year != str(date.getCurrentYear() + 1) and top_price == price:\n #print(stock_id, start_date, top_price )\n top_price_date,top_price = 读取比较某年交易数据(stock_id, start_date, top_price, top_price_date, type)\n #print(stock_id, start_date, top_price,top_price_date)\n\n if top_price_date == \"\":\n year = str(int(year) + 1)\n start_date = \"%s%s%s\" % (year, \"01\", \"01\")\n #print(top_price , top_price_date)\n\n top_price_date = \"%s%s%s\" % (top_price_date[0:4], top_price_date[5:7], top_price_date[8:10])\n return top_price_date, top_price\n\ndef 读取比较某年交易数据(stock_id, start_date, top_price, top_price_date, type=pf.Hfq):\n #print(type(top_price))\n try:\n year, month, day = start_date[0:4], start_date[4:6], start_date[6:8]\n date = \"%s-%s-%s\" % (year ,month,day)\n # 打开文件,读取每一行,每一列\n dirBase = pf.GLOBAL_PATH + pf.SEPARATOR + pf.TransactionData + pf.SEPARATOR + pf.HistoryData + pf.SEPARATOR\n filename = dirBase + type + pf.SEPARATOR + year + pf.SEPARATOR + stock_id + pf.Execl\n workbook = xlrd.open_workbook(filename)\n sheet = workbook.sheet_by_index(0)\n rows = sheet.nrows\n for i in range(rows):\n if i != 0:\n row = sheet.row_values(i)\n if row[1] >= date:\n #print(row)\n if top_price < row[3]:\n top_price = row[3]\n top_price_date = row[1]\n workbook.release_resources()\n del workbook\n return top_price_date,top_price\n workbook.release_resources()\n del workbook\n return top_price_date,top_price\n except:\n return top_price_date,top_price\n\n\nif __name__ == '__main__':\n #stock_dict = 获取股票清单()\n #aa = 根据股票代码获取上市日期(\"600663\", stock_dict)\n #print(获取股票上市n天以后的最高价格(\"600663\", \"20100518\",20))\n\n date,price = 给定一天获取这天以后的超过这个价格的日期及价格(\"300745\", \"20180529\", 80.41)\n print(date)","sub_path":"策略/根据超过上市后的最高价/获取股票上市n天以后的最高价格.py","file_name":"获取股票上市n天以后的最高价格.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"625059852","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 17 13:04:56 2020\n\n@author: changkyupark\n\"\"\"\nimport numpy as np\nimport tools\n\ndef _theta(i, N):\n # i: i-th node\n # N: total no. of nodes\n return (i-1)*np.pi/N\n\ndef _coord(length, theta, theta_next):\n # length: length in specified axis (so la or Ca)\n # theta: i-th theta\n # theta_next: (i+1)-th theta\n return 0.5*(length/2*(1-np.cos(theta))+length/2*(1-np.cos(theta_next)))\n\n# Coordinates of the aerodynamic load\nla = 1.611\nCa = 0.505\nzcoord = [] #chordwise - 81 elements\nfor i in np.arange(81):\n zcoord.append(_coord(Ca, _theta(i, 41), _theta(i+1,41)) )\n \nxcoord = [] #spanwise - 41 elements\nfor j in np.arange(41):\n xcoord.append(_coord(la, _theta(j, 41), _theta(j+1,41)) )\n \n\n# Saves aerodynamic load in an array\nqdatafile = open(\"aerodynamicloadf100.dat\", \"r\")\nlines = qdatafile.readlines()\n\nqforces = []\nfor line in lines:\n currentline = line.split(\",\")\n spanwise = []\n for i in currentline:\n spanwise.append(i)\n qforces.append(spanwise)\n \nqforces = np.array(qforces) #chord*span (z*x) = (81*41)\n \n","sub_path":"Code safety/tools/qforcecoordinates.py","file_name":"qforcecoordinates.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"578986215","text":"\"\"\"\\\nPDF renderer for the aafigure package.\n\n(C) 2008 Chris Liechti \n\"\"\"\n\nimport sys\nimport reportlab\nfrom reportlab.lib import colors\nfrom reportlab.graphics.shapes import *\nfrom reportlab.graphics import renderPDF\n\nclass PDFOutputVisitor:\n \"\"\"Render a list of shapes as PDF vector image.\"\"\"\n\n def __init__(self, file_like, scale = 1, line_width = 1,\n foreground= (0, 0, 0), background = (255, 255, 255), fillcolor = (0, 0, 0),\n proportional = False\n ):\n self.file_like = file_like\n self.scale = 3.33*scale\n self.line_width = 0.4*line_width\n self.foreground = foreground\n self.background = background\n self.fillcolor = fillcolor\n if proportional:\n self.font = 'Helvetica'\n else:\n self.font = 'Courier'\n\n def _num(self, number):\n \"\"\"helper to format numbers with scale for PDF output\"\"\"\n return number*self.scale\n\n def _color(self, color):\n r,g,b = color\n return colors.HexColor('#%02x%02x%02x' % (r,g,b))\n\n def visit_image(self, aa_image):\n \"\"\"Process the given ASCIIArtFigure and output the shapes in\n the PDF file\n \"\"\"\n self.aa_image = aa_image # save for later XXX not optimal to do it here\n self.width = (aa_image.width)*aa_image.nominal_size*aa_image.aspect_ratio\n self.height = (aa_image.height)*aa_image.nominal_size\n self.drawing = Drawing(self._num(self.width), self._num(self.height))\n self.visit_shapes(aa_image.shapes)\n renderPDF.drawToFile(self.drawing, self.file_like, '')\n\n def visit_shapes(self, shapes):\n for shape in shapes:\n shape_name = shape.__class__.__name__.lower()\n visitor_name = 'visit_%s' % shape_name\n if hasattr(self, visitor_name):\n getattr(self, visitor_name)(shape)\n else:\n sys.stderr.write(\"WARNING: don't know how to handle shape %r\\n\"\n % shape)\n\n # - - - - - - PDF drawing helpers - - - - - - -\n def _line(self, x1, y1, x2, y2, thick):\n \"\"\"Draw a line, coordinates given as four decimal numbers\"\"\"\n self.drawing.add(Line(\n self._num(x1), self._num(self.height-y1),\n self._num(x2), self._num(self.height-y2),\n strokeColor=self._color(self.foreground),\n strokeWidth=self.line_width*(1+0.5*bool(thick))\n ))\n\n def _rectangle(self, x1, y1, x2, y2, style=''):\n \"\"\"Draw a rectangle, coordinates given as four decimal numbers.\"\"\"\n if x1 > x2: x1, x2 = x2, x1\n if y1 > y2: y1, y2 = y2, y1\n self.drawing.add(Rect(\n self._num(x1), self._num(self.height-y2),\n self._num(x2-x1), self._num(y2-y1),\n fillColor=self._color(self.fillcolor),\n strokeWidth=self.line_width\n ))\n\n # - - - - - - visitor function for the different shape types - - - - - - -\n\n def visit_point(self, point):\n self.drawing.add(Circle(\n self._num(point.x), self._num(self.height-point.y),\n self._num(0.2),\n fillColor=self._color(self.foreground),\n strokeWidth=self.line_width\n ))\n\n def visit_line(self, line):\n x1, x2 = line.start.x, line.end.x\n y1, y2 = line.start.y, line.end.y\n self._line(x1, y1, x2, y2, line.thick)\n\n def visit_rectangle(self, rectangle):\n self._rectangle(\n rectangle.p1.x, rectangle.p1.y,\n rectangle.p2.x, rectangle.p2.y\n )\n\n\n def visit_circle(self, circle):\n self.drawing.add(Circle(\n self._num(circle.center.x), self._num(self.height-circle.center.y),\n self._num(circle.radius),\n fillColor=self._color(self.foreground),\n strokeWidth=self.line_width\n ))\n\n def visit_label(self, label):\n # font-weight=\"bold\" style=\"stroke:%s\"\n self.drawing.add(String(\n self._num(label.position.x), self._num(self.height-label.position.y),\n label.text,\n fontSize=self._num(self.aa_image.nominal_size),\n fontName=self.font,\n fillColor=self._color(self.foreground),\n ))\n\n def visit_group(self, group):\n # XXX could add a group to the PDF file\n self.visit_shapes(group.shapes)\n\n\n","sub_path":"sandbox/aafigure/aafigure/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"375086572","text":"from typing import Optional\nfrom os.path import sep\nfrom loguru import logger\nfrom vcm import vcm as vcm\nfrom VirusGenoUtil.code.integrate_iedb_epitopes import epitopes_for_virus_taxon\nfrom data_sources.ncbi_services import host_taxon_name_from_ncbi_taxon_id\nfrom db_config import read_db_import_configuration as import_config, database\nfrom time import sleep\nimport wget\nfrom zipfile import ZipFile\nimport gzip, shutil\nfrom tqdm import tqdm\nfrom locations import remove_file\n\nepitope_id_mappings = dict()\n\n\ndef import_epitopes(virus_taxon_id: int):\n # remember to update the data source\n logger.warning(\"Keep in mind to update the data source with 'python main.py download epitopes' before performing\"\n \" the current action. This program will resume in 10 seconds.\")\n try:\n sleep(10)\n except KeyboardInterrupt:\n return\n\n # begin\n db_params: dict = import_config.get_database_config_params()\n database.config_db_engine(db_params[\"db_name\"], db_params[\"db_user\"], db_params[\"db_psw\"], db_params[\"db_port\"])\n if virus_taxon_id in [2010960, 186539]: # == bombali or reston ebolavirus\n logger.info(f'No epitopes available for virus {virus_taxon_id}.')\n return\n\n virus_db_id = virus_database_id(virus_taxon_id)\n\n if virus_db_id is None:\n raise Exception('Epitopes must be associated to a Virus DB entity. Before running epitopes, create the '\n f'virus associated with taxon {virus_taxon_id}')\n if epitopes_already_imported(virus_db_id):\n logger.info('Epitopes for this virus are already imported into the DB. Aborting import.')\n return\n\n # run epitopes' code\n logger.debug(\n f'calling epitopes for virus taxon {virus_taxon_id} associated to DB virud_id {virus_db_id}')\n epitopes, fragments = epitopes_for_virus_taxon(virus_taxon_id)\n\n # write to file\n # epitopes_file = open(f'.{sep}epitopes.csv', mode='w')\n # epitopes_file.write('virus_db_id\\thost_specie_db_id\\thost_name\\thost_iri\\tprotein_ncbi_id\\tcell_type\\tmhc_class\\t'\n # 'mhc_allele\\tresponse_frequency_positive\\tassay_type\\tseq\\tstart\\tstop\\text_links\\t'\n # 'prediction_process\\tis_linear\\tepitope_iri\\tiedb_epitope_id\\n')\n # epitopes_fragm_file = open(f'.{sep}epitopes_fragments.csv', mode='w')\n # epitopes_fragm_file.write('damianos_epitope_id\\tseq\\tstart\\tstop\\n')\n\n def do(session: database.Session):\n global epitope_id_mappings\n try:\n for epitope in epitopes:\n # get contained values\n damianos_epitope_id, virus_taxon_id, host_iri, host_name, host_taxon_id, protein_ncbi_id, cell_type, \\\n mhc_class, mhc_allele, response_frequency_positive, assay_type, seq, start, stop, ext_links, \\\n prediction_process, is_linear, epitope_iri, iedb_epitope_id = epitope\n\n # put host specie foreign key\n host_specie_db_id = create_or_get_host_specie_db_id(session, host_taxon_id)\n\n # insert epitope in the DB\n epitope = (virus_db_id, host_specie_db_id, host_name, host_iri, protein_ncbi_id, cell_type,\n mhc_class, mhc_allele, response_frequency_positive, assay_type, seq, start, stop, ext_links,\n prediction_process, is_linear, epitope_iri, iedb_epitope_id)\n\n # write to file\n # types = (str(type(i)) for i in epitope)\n # items = (str(i) for i in epitope)\n # for i in zip(items, types):\n # epitopes_file.write(f'{i[0], i[1]}\\t')\n # epitopes_file.write('\\n')\n\n epitope_db_id = vcm.create_epitope(session, epitope)\n # bind epitope ids from Damianos with the ones returned from database\n epitope_id_mappings[damianos_epitope_id] = epitope_db_id\n\n for fragment in fragments:\n _, damianos_epitope_id, seq, start, stop = fragment\n\n # bind epitope ids from Damianos with the ones returned from database\n try:\n epitope_db_id = epitope_id_mappings[damianos_epitope_id]\n except KeyError as e:\n raise KeyError(\n f'the epitope fragment ID {damianos_epitope_id} does not appear in the epitope IDs. This epitope fragment'\n f' will be not inserted into the DB.'\n )\n\n fragment = (epitope_db_id, seq, start, stop)\n\n # write to file\n # types = (str(type(i)) for i in fragment)\n # items = (str(i) for i in fragment)\n # for i in zip(items, types):\n # epitopes_fragm_file.write(f'{i[0], i[1]}\\t')\n # epitopes_fragm_file.write('\\n')\n\n vcm.create_epitope_fragment(session, fragment)\n vcm.DBCache.commit_changes()\n except Exception as e:\n logger.exception('Exception occurred while computing and importing epitopes. Epitopes won\\'t be inserted into the DB.')\n vcm.DBCache.rollback_changes()\n raise database.RollbackAndRaise(e)\n # finally:\n # epitopes_file.close()\n # epitopes_fragm_file.close()\n\n database.try_py_function(\n do\n )\n\n # insert one row for each linear epitope into epitope_fragment table\n database.run_script(f\".{sep}sql_scripts{sep}insert_linear_epitopes_into_epi_fragments.sql\")\n\n\ndef create_or_get_host_specie_db_id(session: database.Session, organism_ncbi_taxon_id):\n specie_db_id = vcm.get_specie_id(session, organism_ncbi_taxon_id)\n if not specie_db_id:\n organism_name_from_ncbi = host_taxon_name_from_ncbi_taxon_id(organism_ncbi_taxon_id)\n if organism_name_from_ncbi is not None:\n organism_name_from_ncbi = organism_name_from_ncbi.lower()\n specie_db_id = vcm.create_or_get_host_specie_alt(session, organism_name_from_ncbi, organism_ncbi_taxon_id)\n return specie_db_id\n\n\ndef virus_database_id(virus_taxon_id) -> Optional[int]:\n class Virus:\n @staticmethod\n def taxon_id():\n return virus_taxon_id\n\n def get_virus_db_id(session) -> Optional[int]:\n db_virus = vcm.get_virus(session, Virus())\n return db_virus.virus_id if db_virus else None\n\n return database.try_py_function(\n get_virus_db_id\n )\n\n\ndef epitopes_already_imported(virus_db_id):\n return database.try_py_function(\n vcm.check_existence_epitopes, virus_db_id)\n\n\ndef download_epitope_data() -> (str, str, str):\n \"\"\"\n :return: the local file path of the updated files from IEDB. In order, the files are:\n - bcell_full_v3\n - tcell_full_v3\n - mhc_ligand_full_v3\n \"\"\"\n tcell_url = \"http://www.iedb.org/downloader.php?file_name=doc/tcell_full_v3.zip\"\n bcell_url = \"http://www.iedb.org/downloader.php?file_name=doc/bcell_full_v3.zip\"\n mhc_ligand_url = \"http://www.iedb.org/downloader.php?file_name=doc/mhc_ligand_full_single_file.zip\"\n download_dir = f\".{sep}VirusGenoUtil{sep}data{sep}iedb_input{sep}cell_epitopes{sep}\"\n\n tcell_file_name = \"tcell_full_v3\"\n bcell_file_name = \"bcell_full_v3\"\n mhc_ligand_file_name = \"mhc_ligand_full\"\n\n final_tcell_local_file_path = download_dir + tcell_file_name + \".csv.gz\"\n final_bcell_local_file_path = download_dir + bcell_file_name + \".csv.gz\"\n final_mhc_ligand_local_file_path = download_dir + mhc_ligand_file_name + \".csv.gz\"\n\n download_tcell_local_file_path = download_dir + tcell_file_name + \".zip\"\n download_bcell_local_file_path = download_dir + bcell_file_name + \".zip\"\n download_mhc_ligand_local_file_path = download_dir + mhc_ligand_file_name + \".zip\"\n\n def download_epitopes_data():\n # make sure the output path does not exist already, or wget assigns a trailing number to it\n remove_file(download_bcell_local_file_path)\n remove_file(download_tcell_local_file_path)\n remove_file(download_mhc_ligand_local_file_path)\n logger.info(f'downloading tcell_full from {tcell_url} ...')\n wget.download(tcell_url, download_tcell_local_file_path)\n logger.info(f'downloading bcell_full from {bcell_url} ...')\n wget.download(bcell_url, download_bcell_local_file_path)\n logger.info(f'downloading mhc_ligand_full from {mhc_ligand_url} ...')\n wget.download(mhc_ligand_url, download_mhc_ligand_local_file_path)\n logger.info('\\n')\n\n def extract_epitopes_data():\n # unzip and gzip as requested by VirusGenoUtil library\n logger.info(\"transforming downloaded files as required by VirusGenoUtil...\")\n io_list = zip(\n (download_tcell_local_file_path, download_bcell_local_file_path, download_mhc_ligand_local_file_path),\n (tcell_file_name, bcell_file_name, mhc_ligand_file_name),\n (final_tcell_local_file_path, final_bcell_local_file_path, final_mhc_ligand_local_file_path))\n for downloaded_file_path, file_name, output_file_path in tqdm(io_list):\n inner_file_name = file_name + \".csv\"\n # unzip downloaded file into inner_file_name\n with ZipFile(file=downloaded_file_path, mode='r') as zipped_file:\n zipped_file.extract(member=inner_file_name, path=download_dir)\n # gzip extracted file\n with open(file=download_dir + inner_file_name, mode=\"rb\") as inner_file:\n with gzip.open(output_file_path, mode='wb') as output_file:\n shutil.copyfileobj(inner_file, output_file)\n # remove inner file as it is only an intermediate product\n remove_file(download_dir + inner_file_name)\n\n # download/update epitopes data from IEDB\n # IEDB does not send Content-Length HTTP header, so we cannot decide whether the source data is more recent than\n # the local data. Therefore we just download and replace the local files.\n download_epitopes_data()\n extract_epitopes_data()\n\n return final_bcell_local_file_path, final_tcell_local_file_path, final_mhc_ligand_local_file_path\n","sub_path":"epitopes.py","file_name":"epitopes.py","file_ext":"py","file_size_in_byte":10160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"98822301","text":"def groupAnagrams(lst):\n hashmap = {}\n for s in sorted(lst):\n key = ''.join(sorted(s))\n if key not in hashmap:\n hashmap[key] = [s]\n else:\n hashmap[key] += [s]\n return hashmap.values()\n\n\nlex = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]\nans = groupAnagrams(lex)\nprint(ans)\n","sub_path":"groupAnagrams.py","file_name":"groupAnagrams.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"138192877","text":"import dgl\nimport dgl.function as fn\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom dgl import DGLGraph\nimport numpy as np\nimport pickle\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\nfrom dgl import DGLGraph\nimport dgl.function as fn\nfrom functools import partial\nimport copy\nimport torch.optim as optim\nimport pickle\nfrom torch.distributions import Categorical\n\n\n\n# Texar Library\nimport texar\n\nfrom texar.torch.core.cell_wrappers import RNNCell, LSTMCell\n\nfrom texar.torch.modules import UnidirectionalRNNEncoder, WordEmbedder, BasicRNNDecoder\n\nfrom texar.torch import HParams\n\nfrom texar.torch.losses import sequence_sparse_softmax_cross_entropy\n\n\n# Co-Attention in Pytorch \n\n# It takes in as input the V visual features and the a semantic features along with the hidden vector of the \n# previous time step of the sentence LSTM layer 1 in the 2 layer hierarchical LSTM\n\nclass Co_Attention(nn.Module):\n \n def __init__(self, num_units, visual_units, semantic_units, hidden_size, N, M, batch_size = 1):\n \n super(Co_Attention, self).__init__()\n \n # initialise the variables\n \n # assuming hidden state and input to lstm have the same dimension\n # the hidden vector and input size of the sentence LSTM\n self.hidden_size = hidden_size \n self.batch_size = batch_size\n \n # attention parameters\n self.num_units = num_units# intermediate number of nodes for the BahdanauAttention attention calculation \n \n # dimension of visual and semantic features\n self.visual_units = visual_units \n self.semantic_units = semantic_units\n \n # As per the On the Automatic Generation of Medical Imaging Reports paper\n self.N = N # Number of Visual features\n self.M = M # Number of Semantic features\n \n # The attention layer\n \n self.visual_attn = BahdanauAttention(self.num_units, decoder_output_size = self.hidden_size, \n encoder_output_size = self.visual_units)\n \n self.semantic_attn = BahdanauAttention(self.num_units, decoder_output_size = self.hidden_size, \n encoder_output_size = self.semantic_units)\n \n # Context calculation layer\n \n self.layer = nn.Linear(self.N + self.M, self.hidden_size)\n \n def forward(self, v, a, hidden_state):\n \n # v has dimension [Batch size, max_time_steps = N_v, hidden_state = visual_units]\n \n # a has dimension [Batch size, max_time_steps = N_a, hidden_state = semantic_units]\n \n state_v = torch.rand(self.batch_size,self.N)\n \n visual_alignments, _ = visual_attn(hidden_state, state = state_v, memory = v)\n\n state_a = torch.rand(self.batch_size,self.M)\n \n semantic_alignments, _ = semantic_attn(hidden_state, state = state_a, memory = a)\n \n # v_attn has dimension [batch size, N_v]\n \n # a_attn has dimension [batch size, N_a]\n \n v_attn = torch.bmm(visual_alignments.view(self.batch_size,1,-1), v).squeeze(1)\n \n a_attn = torch.bmm(semantic_alignments.view(self.batch_size,1,-1), a).squeeze(1)\n \n cat_attn = torch.cat([v_attn.view(self.batch_size, -1), a_attn.view(self.batch_size, -1)], 1)\n \n ctx = self.layer(cat_attn)\n \n return ctx, visual_alignments, semantic_alignments\n\n\n### 2 layered Hierarchical LSTM in TEXAR-TORCH\n\n# This is an implementation of 2 layered hierarchical LSTM implementation in Texar. In this particular \n# application the first tier takes in the input which here is from co-attention and outputs a hidden state vector. \n# At each time step of the tier-1 LSTM, the hidden state vector is fed into the tier 2 LSTM as a state tuple \n# to output a sentence. \n\n \n# ---------------------- Hierarchical LSTM ----------------------------\n\n# NOTE: Run the LSTM sentence in a for loop range [0 max time steps] till termination\n# Because at each time step we calculate the visual and semantic attention (stack at the end of the max \n# timesteps to find the alpha and beta)\n# Output the t needed for the Word lstm \n# At each time step we produce a 0 or 1 to continue or stop\n\n# This is run at every time step of Sentence LSTM as stated above\n# It is Bernoulli variable\n# p_pred shape [Batch size, 2]\n# p_target shape [Batch size]\n\n\n#################################################################\n# Sentence generation and Loss for sentence generation\n#################################################################\ndef sentence_loss(p_pred, p_target):\n \n sentence_lossfn = nn.CrossEntropyLoss()\n \n return sentence_lossfn(p_pred, p_target)\n\n# 1st in the hierarchy\nclass LSTM_sentence(nn.Module):\n # hidden_size the same as GNN output\n def __init__(self, hidden_size, num_units, visual_units, semantic_units, N, M, seq_len = 1, batch_size = 1):\n super(LSTM_sentence, self).__init__()\n \n # initialise the variables\n\n # Here the input size is equal to the hidden size used as the input from co-attention\n self.input_size = hidden_size\n \n # the output size\n # LSTM parameters\n # the hidden vector and input size of the sentence LSTM\n self.hidden_size = hidden_size\n self.seq_len = seq_len\n self.batch_size = batch_size\n\n # attention parameters\n self.num_units = num_units# intermediate number of nodes for the BahdanauAttention attention calculation \n # dimension of visual and semantic features\n self.visual_units = visual_units \n self.semantic_units = semantic_units\n \n # As per the On the Automatic Generation of Medical Imaging Reports paper\n self.N = N # Number of Visual features\n self.M = M # Number of Semantic features\n\n # The Co_Attention module\n # observe that the input to the LSTM and hidden vector have the same dimension\n # If not add a new parameter and make changes accordingly\n self.co_attn = Co_Attention(self.num_units, self.visual_units, self.semantic_units, \n \tself.hidden_size, self.N, self.M, batch_size = self.batch_size)\n \n # LSTM layer -- batch_first = true\n \n enc_hparams = {'rnn_cell': {'type': 'LSTMCell', 'kwargs': {'num_units': self.hidden_size}}}\n \n default_hparams = UnidirectionalRNNEncoder.default_hparams()\n\n hparams_ = HParams(enc_hparams, default_hparams)\n \n self.lstm = UnidirectionalRNNEncoder(input_size=self.input_size, hparams=hparams_.todict())\n\n def forward(self, v, a, hidden):\n \n (h_0, c_0) = hidden\n\n inp_lstm, visual_alignments, semantic_alignments = self.co_attn(v, a, h_0)\n \n output, hidden = self.lstm(inp_lstm, initial_state=\n (h_0.view(self.batch_size, self.hidden_size), \n c_0.view(self.batch_size, self.hidden_size)))\n \n\n # return the visual_alignments, semantic_alignments for the loss function calculation\n # stack the visual_alignments, semantic_alignments at each time step of the sentence LSTM to \n # obtain the alpha (visual_alignments) beta (semantic_alignments)\n return output, hidden, visual_alignments, semantic_alignments \n\n def initHidden(self):\n return (torch.zeros(self.seq_len, self.batch_size, self.hidden_size), \n torch.zeros(self.seq_len, self.batch_size, self.hidden_size))\n\n\n# 2 nd in the hierarchy\nclass LSTM_word(nn.Module):\n # hidden_size the same as GNN output\n def __init__(self, hidden_size, output_size, seq_len = 1, batch_size = 1):\n super(LSTM_word, self).__init__()\n \n # initialise the variables\n\n # Here the input size is equal to the hidden size used as the input from co-attention\n self.input_size = hidden_size\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.seq_len = seq_len\n self.batch_size = batch_size\n \n # Embedding layer\n \n self.embedding = WordEmbedder(vocab_size=self.output_size, hparams={'dim': self.hidden_size})\n \n # LSTM layer -- batch_first = true\n \n enc_hparams = {'rnn_cell': {'type': 'LSTMCell', 'kwargs': {'num_units': self.hidden_size}}}\n \n default_hparams = BasicRNNDecoder.default_hparams()\n\n hparams_ = HParams(enc_hparams, default_hparams)\n \n self.decoder = BasicRNNDecoder(input_size = self.hidden_size, token_embedder = self.embedding, \n vocab_size=self.output_size, hparams=hparams_.todict())\n\n def forward(self, hidden, train, inp= None, sentence_len = None):\n \n if train:\n (output, final_state, sequence_lengths) = self.decoder( decoding_strategy='train_greedy', inputs=inp, sequence_length=sentence_len, initial_state = hidden)\n else:\n # Create helper\n helper = self.decoder.create_helper(decoding_strategy='infer_greedy',start_tokens=torch.Tensor([CLS_token]*self.batch_size).long(),\n end_token=SEP_token, embedding=self.embedding)\n\n # Inference sample\n # here sentence length is the max_decoding_length\n output, _, _ = self.decoder(helper=helper, initial_state = hidden, max_decoding_length=sentence_len)\n \n return output\n\n def initHidden(self):\n return (torch.zeros(self.seq_len, self.batch_size, self.hidden_size), \n torch.zeros(self.seq_len, self.batch_size, self.hidden_size))\n\n\n\n###################################################\n# Phrase generation and Loss for phrase generation\n###################################################\n# here the phrase_decoder is an instance of the class LSTM_word\n# This is a function that is executed at every time step S of sentence LSTM\n# new_node_embedding is the hidden statevector of time step S from sentence LSTM\ndef generate_phrase(phrase_decoder, new_node_embedding, index = None, train = True):\n \n phrase_loss = 0\n \n if train:\n phrase_decoder_input = torch.Tensor(tokenizer(index2phrase[index])['input_ids']).view(batch_size,-1).long().to(device)\n \n sentence_len = torch.Tensor([len(phrase_decoder_input[0,1:])]).long()\n \n state = new_node_embedding\n \n (state_h_0, state_c_0) = state\n\n # 1 because the number of stacked lstm layers are 1 pytorch input specification\n\n state_h_0 = (state_h_0).view(batch_size, hidden_size)\n\n state_c_0 = (state_c_0).view(batch_size, hidden_size)\n\n phrase_decoder_hidden = (state_h_0, state_c_0)\n \n if train:\n output = phrase_decoder(phrase_decoder_hidden, train, inp = phrase_decoder_input, \n sentence_len = sentence_len)\n \n # per time step S of sentence LSTM\n phrase_loss = sequence_sparse_softmax_cross_entropy( labels=phrase_decoder_input[:, 1:], logits=output.logits, \n sequence_length=sentence_len)\n else:\n \n output = phrase_decoder(phrase_decoder_hidden, train, sentence_len = 5)\n \n \n predict = list(np.array(output.sample_id.view(-1)))\n \n if train:\n return phrase_loss, tokenizer.decode(predict), phrase_decoder_input\n else:\n return phrase_loss, tokenizer.decode(predict)\n\n#################################################\n# Loss for attention and tags\n#################################################\n\n# Apply the weighting lambdas in the main function this is just a loss without lambda weights\ndef tag_loss(p_pred, p_target):\n # p_target is [Batch_size, hidden] \n # p_pred is [Batch_size, hidden]\n # assuming p_target is a normalised vector of distribution l/||l||_1 of tags\n # assuming is the output of the multi-label classification layer without the softmax we apply softmax here\n # pl,pred is before the application of softmax layer\n # We obtain the predicted distriubtion here\n logsoftmax = nn.LogSoftmax(dim=1)\n \n return torch.mean(torch.sum(- p_target * logsoftmax(p_pred), 1))\n\n# Attention loss \n# weigh it in the main loop as per lambda\ndef attn_loss(alpha, beta):\n # alpha is [Batch_size, N, S] \n # beta is [Batch_size, M, S]\n # N is the number of visual features, M is the number of semantic features\n # S is the number of time steps in Sentence LSTM\n visual_attn_loss = torch.sum(((1 - torch.sum(alpha, -1))**2), -1) \n \n semantic_attn_loss = torch.sum(((1 - torch.sum( beta, -1))**2), -1) \n\n return torch.mean(visual_attn_loss, semantic_attn_loss)\n\n\n \n\n","sub_path":"report-generation-nlp.py","file_name":"report-generation-nlp.py","file_ext":"py","file_size_in_byte":12910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"361451632","text":"import random\r\n\r\nrandom_num = random.randint(1,100)\r\nprint(\"\\n\\nLets play a game! Guess the number I am thinking about!\\n\")\r\nuser_num = int(input(\"Please guess the number :\"))\r\ncount = 0\r\nwhile user_num!=random_num:\r\n if user_num>random_num:\r\n print(\"Your guess is greater than my number!\\n\")\r\n user_num = int(input(\"Please Guess again : \"))\r\n count+=1\r\n elif user_num b:\n print(\"數字剛好出現\"+str(b)+\"次\")\nelse:\n print(\"出現最多的數字是\",n1[c])\n print(\"出現的次數是\",b)\n\n \n","sub_path":"8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259024939","text":"import requests\r\nimport json\r\nimport base64\r\nimport sys\r\n\r\n#图片是个四纬物体。\r\nbase64_data = None\r\n\r\nprint(sys.argv)\r\n#经过修改,使得源程序从写死到灵活,可以在命令行中输入参数即可\r\nif(len(sys.argv)>1):\r\n with open(sys.argv[1],\"rb\") as f:\r\n #把读取的图片进行编码,\r\n base64_data = base64.b64encode(f.read())\r\n\r\n host = 'http://plant.market.alicloudapi.com/plant/recognize'\r\n appcode = '586ed0a7d7e046db8c0e314234b081c5'\r\n #post的主体就是一个字典\r\n bodys = {'img_base64': base64_data}\r\n headers = {'Authorization': 'APPCODE ' + appcode,'Content-Type': 'application/x- www-form-urlencoded; charset=UTF-8'}\r\n response = requests.post(host, data = bodys, headers = headers)\r\n content = response.text\r\n if (content):\r\n data_reader = json.loads(content)['Result']\r\n for i in range(len(data_reader)):\r\n name = data_reader[i]['Name']\r\n score = data_reader[i]['Score']\r\n print(name,score)\r\n","sub_path":"flower_example.py","file_name":"flower_example.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"95431966","text":"import csv\nimport pprint as pp\nimport networkx as nx\nimport sys\nfrom operator import itemgetter\nimport WebIR_HW_2_part_1 as tspr\n\nalpha = .15\nepsilon = 10**-6\ntopic = {}\ntotal_rating = 0\npage_rank_vector={}\nexist = False\n\n#reading the input from the command line\nif (len(sys.argv) < 4):\n print(\"Usage: python WebIR_HW_2_part_2.py ./datasets/movie_graph.txt ./datasets/user_movie_rating.txt INPUT_USER_ID\\n\")\n exit(1)\nelse:\n\tmovie_graph_path = sys.argv[1]\n\tuser_movie_rating_path = sys.argv[2]\n\tuser_id = sys.argv[3]\n\tif int(user_id) < 1683 or int(user_id) > 2625:\n\t\tprint(\"user nonexistent\")\n\t\texit(1)\n\n#load graph\ng = nx.Graph()\ninput_file = open(movie_graph_path, 'r')\ninput_file_csv_reader = csv.reader(input_file, delimiter='\\t', quotechar='\"', quoting=csv.QUOTE_NONE)\nfor line in input_file_csv_reader:\n\tg.add_edge(int(line[0]), int(line[1]), weight=int(line[2]))\ninput_file.close()\n\n#load the topic\ninput_file = open(user_movie_rating_path, 'r')\ninput_file_csv_reader = csv.reader(input_file, delimiter='\\t', quotechar='\"', quoting=csv.QUOTE_NONE)\n\nfor line in input_file_csv_reader:\n\tif int(line[0]) == int(user_id):\n\t\texist=True\n\t\ttopic[int(line[1])] = float(line[2]) #line[1]= Movie_ID ; line[2]= Rating\ninput_file.close()\n\n#check if the user_id exists\nif exist==False:\n\tprint(\"user nonexistent\")\n\texit(1)\n\n#compute the total rating of the films belonging to the topic\ntotal_rating = sum(topic.values())\n\n#assign the correct probability to each movie belonging to the topic\nfor movie in topic:\n\ttopic[movie] = topic[movie] / total_rating\n\npage_rank_vector=tspr.topic_specific_pagerank(g,topic,alpha,epsilon)\nfor movie in sorted(page_rank_vector, key=page_rank_vector.get, reverse=True):\n\tif movie not in topic:\n\t\tprint(str(movie)+\", \"+str(page_rank_vector[movie]))\n","sub_path":"WebIR_HW_2_part_2.py","file_name":"WebIR_HW_2_part_2.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"308002217","text":"import numpy as np\nimport random\nimport json\nfrom matplotlib import pyplot as plt\nfrom base import activation_function, loss_function\n#from .base import activation_function, loss_function\n\nclass FNN():\n \"\"\"\n Feedforward Neural network Class.\n \n Attributes\n ---------- \n sizes: list\n List of number of nodes in the respective layers of the NN.\n \n n_layers: int\n Total number of layers in the NN.\n \n n_inputs: int\n Number of nodes in the input layer.\n \n weights: list of numpy arrays\n Each array has the weights in a particular layer.\n \n biases: list of numpy arrays\n Each array has the biases in a particular layer.\n \n prev_update_w: list\n List of all previous updates of weights in NN.\n \n prev_update_b: list\n List of all previous updates of weights in NN.\n \n activation_types: list\n List of all the activation functions used\n in the respective layers of NN.\n \n loss_fn: str\n Type of loss function used in the NN.\n Options:\n mse ( Mean squared error )\n ce ( Cross entropy )\n \n epoch_list: list\n List of numbers from 0 to max epochs.\n \n accuracy: list\n List to store the accuracy at each epoch.\n \n Methods\n -------\n weight_initializer(name=\"random\"):\n Initializes weights and biases.\n\n init_params(sizes, epochs):\n Initializes parameters in the NN.\n \n get_params():\n Return weights and biases of the NN.\n \n add_layer(n_nodes, activation_type):\n Adds a layer to the NN.\n \n feedforward(a):\n Return the output of NN if input is a. \n \n accuracy(data, task): \n Return the accuracy of NN on the given data.\n \n backprop(x, y, weights=None, biases=None):\n Returns the gradients of weights and biases\n for a given example.\n \n get_batch_size(training_data, mode, batch_size):\n Returns the batch size given mode.\n \n update_GD(mini_batch, eta):\n Updates weights and biases after \n applying Gradient Descent (GD)\n on the mini batch.\n \n update_MGD(mini_batch, gamma, eta):\n Updates weights and biases after \n applying Momentum based Gradient Descent (MGD)\n on the mini batch.\n \n update_NAG(mini_batch, eta, gamma):\n Updates weights and biases after \n applying Nesterov accerelated Gradient Descent (NAG)\n on the mini batch.\n \n compile(training_data, test_data=None):\n Compiles the NN.\n \n fit(training_data, validation_data=None):\n Runs the optimizer on the training data for given number of epochs.\n \n predict(new_data):\n Gives NN predictions on the new data\n \n logging(test_data=None):\n Given test data, it plots Epoch vs Error graph.\n \n save(filename):\n Saves the NN to the file.\n \n load(filename):\n laads the NN from the file.\n \"\"\"\n\n def __init__(self, n_inputs, loss_fn):\n \"\"\"\n Creates the Feedforward Neural Network\n \n Parameters\n ----------\n n_inputs: int\n Number of nodes in the input layer.\n \n loss_fn: str\n Type of loss function used in the NN.\n Options:\n mse ( Mean squared error )\n ce ( Cross entropy )\n \"\"\"\n \n self.sizes = [n_inputs]\n self.n_layers = 0\n self.n_inputs = n_inputs\n self.weights = list()\n self.biases = list()\n self.prev_update_w = list()\n self.prev_update_b = list()\n self.activation_types = list()\n self.loss_fn = loss_fn\n self.config = dict()\n self.epoch_list = list()\n \n def weight_initializer(self, name=\"random\"):\n \"\"\"\n Initializes weights and biases\n \n Parameters\n ----------\n \n name: str\n Type of weight initialization.\n Options:\n random ( Gauss distro mean 0, std 1 )\n xavier ( n^2 = 1 / n )\n he ( n^2 = 2 / n )\n \n Returns\n -------\n None\n \"\"\"\n \n if name == \"random\":\n self.weights = [np.random.randn(y, x) \n for x, y in zip(self.sizes[:-1], self.sizes[1:])]\n self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]\n \n elif name == \"xavier\":\n self.weights = [np.random.randn(y, x)/np.sqrt(x) \n for x, y in zip(self.sizes[:-1], self.sizes[1:])]\n self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]\n \n elif name == \"he\":\n self.weights = [np.random.randn(y, x)*np.sqrt(2/x)\n for x, y in zip(self.sizes[:-1], self.sizes[1:])]\n self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]\n\n def init_params(self, sizes, epochs, weight_init_type=None):\n \"\"\"\n Initializes parameters in the NN.\n \n Parameters\n ----------\n sizes: list\n List of number of nodes in the respective layers of the NN.\n \n epochs: int\n Number of maximum epochs \n \n weight_init_type: str\n Type of weight initialization\n Default: None \n \n Returns\n ------\n None\n \"\"\"\n \n self.n_layers = len(sizes)\n if weight_init_type: self.weight_initializer(weight_init_type)\n self.prev_update_w = [np.zeros(w.shape) for w in self.weights]\n self.prev_update_b = [np.zeros(b.shape) for b in self.biases]\n self.epoch_list = np.arange(0, epochs)\n\n def get_params(self):\n \"\"\"\n Return weights and biases of the NN.\n \n Returns\n -------\n List of weights and biases\n \"\"\"\n return [self.weights, self.biases]\n\n\n def add_layer(self, n_nodes, activation_type):\n \"\"\"\n Adds a layer to the NN.\n \n Parameters\n ----------\n n_nodes: int\n Number of nodes in the layer.\n \n activation_type: str\n Activation function used in the layer.\n Options:\n identity\n sigmoid\n softmax\n tanh\n relu\n \n Returns\n -------\n None\n \"\"\"\n \n self.activation_types.append(activation_type)\n self.sizes.append(n_nodes)\n self.n_layers += 1\n\n def feedforward(self, a):\n \"\"\"\n Return the output of NN if input is a. \n \n Parameter\n ---------\n a: array\n Inputs to the NN.\n \n Returns\n -------\n a: array\n Output of NN\n \"\"\"\n \n l = 0 # layer count\n for b, w in zip(self.biases, self.weights): \n a = activation_function(self.activation_types[l], np.dot(w, a) + b)\n l += 1\n return a\n\n def accuracy(self, data): \n \"\"\"\n Return the no of test inputs for which the NN outputs the correct result.\n \n Parameters\n ----------\n data: list\n List of tuples (x, y)\n \n Returns\n -------\n Returns int \n \"\"\"\n \n if self.config[\"task\"] == \"classification\":\n results = [(np.argmax(self.feedforward(x)), y) \n for (x, y) in data]\n elif self.config[\"task\"] == \"regression\":\n results = [(self.feedforward(x), y) for (x, y) in data]\n else:\n return -1\n return sum(int(x == y) for (x, y) in results) / len(data) * 100\n \n def backprop(self, x, y, weights=None, biases=None):\n \"\"\"\n Returns the gradients of weights and biases for a given example.\n \n Backpropagates the error.\n \n Parameters\n ----------\n x: tuple\n Input\n \n y: tuple\n Output\n \n weights: list\n Default: None\n \n biases: list\n Default: None\n \n Returns\n -------\n (gradient_w, gradient_b): tuple of lists of numpy arrays\n \"\"\"\n \n if weights: self.weights = weights\n if biases: self.biases = biases\n \n gradient_w = [np.zeros(w.shape) for w in self.weights]\n gradient_b = [np.zeros(b.shape) for b in self.biases]\n \n activation = x\n # list to store all the activations, layer by layer\n activations = [x] \n # list to store all the z vectors, layer by layer\n zs = [] \n # c: layer counter\n c = 0\n # feedforward\n for b, w in zip(self.biases, self.weights):\n z = np.dot(w, activation) + b\n zs.append(z)\n activation = activation_function(self.activation_types[c], z)\n activations.append(activation)\n c += 1\n \n loss_grad = loss_function(self.loss_fn, y, activations[-1], True)\n # delta: errors of the output layer\n if (self.loss_fn == \"mse\"):\n delta = loss_grad * activation_function(self.activation_types[-1], \n zs[-1], True)\n elif (self.loss_fn == \"ll\"):\n # if sigmoid or softmax: derivative is out*(1-out): \n # numerator and denominator get cancelled.\n if (self.activation_types[-1] == \"sigmoid\" or \n self.activation_types[-1] == \"softmax\"):\n delta = activations[-1]\n else:\n az = activation_function(\n self.activation_types[-1], zs[-1], False)\n delta = loss_grad * activation_function(\n self.activation_types[-1], zs[-1], True)\n elif (self.loss_fn == \"ce\"):\n # if sigmoid or softmax: derivative is out*(1-out)\n # numerator and denominator get cancelled.\n if (self.activation_types[-1] == \"sigmoid\" or\n self.activation_types[-1] == \"softmax\"):\n delta = loss_grad\n else:\n az = activation_function(\n self.activation_types[-1], zs[-1], False)\n delta = loss_grad * (activation_function(\n self.activation_types[-1], zs[-1], True) /\n (az * ( 1 - az )))\n \n gradient_w[-1] = np.dot(delta, activations[-2].transpose())\n gradient_b[-1] = delta\n # backpropagate the error\n for l in range(2, self.n_layers):\n z = zs[-l]\n d = activation_function(self.activation_types[-l], z, True)\n # Here delta is errors of the layer n_layers - l\n delta = np.dot(self.weights[-l + 1].transpose(), delta) * d\n gradient_b[-l] = delta\n gradient_w[-l] = np.dot(delta, activations[-l - 1].transpose())\n \n return (gradient_w, gradient_b)\n\n\n def get_batch_size(self, training_data, mode, batch_size):\n \"\"\"\n Returns the batch size given mode.\n \n Parameters\n ----------\n training_data: list\n List of tuples (x, y)\n \n mode: str\n Options:\n online\n mini_batch\n batch\n \n batch_size: int\n Size of the mini_batch\n \n Returns\n -------\n Returns int ( batch size )\n \"\"\"\n \n if mode == \"online\":\n return 1\n elif mode == \"mini_batch\":\n return batch_size\n elif mode == \"batch\":\n return len(training_data)\n\n def update_GD(self, mini_batch, eta):\n \"\"\"\n Updates parameters using GD.\n \n Updates weights and biases after \n applying Gradient Descent (GD)\n on the mini batch.\n \n Parameters\n ----------\n mini_batch: list\n List of tuples (x, y)\n \n eta: float\n Learning rate\n \n Returns\n -------\n None\n \"\"\"\n \n gradient_b = [np.zeros(b.shape) for b in self.biases]\n gradient_w = [np.zeros(w.shape) for w in self.weights]\n for x, y in mini_batch:\n delta_gradient_w, delta_gradient_b = self.backprop(x, y)\n gradient_b = [gb + dgb \n for gb, dgb in zip(gradient_b, delta_gradient_b)]\n gradient_w = [gw + dgw \n for gw, dgw in zip(gradient_w, delta_gradient_w)]\n \n self.weights = [w - (eta / len(mini_batch)) * gw \n for w, gw in zip(self.weights, gradient_w)]\n self.biases = [b - (eta / len(mini_batch)) * gb \n for b, gb in zip(self.biases, gradient_b)]\n \n\n def update_MGD(self, mini_batch, eta, gamma):\n \"\"\"\n Updates parameters using MGD.\n \n Updates weights and biases after applying \n Momentum based Gradient Descent (GD)\n on the mini batch.\n \n Parameters\n ----------\n mini_batch: list\n List of tuples (x, y)\n \n eta: float\n Learning rate\n \n gamma: float\n Momentum value\n \n Returns\n -------\n None\n \"\"\"\n \n gradient_b = [np.zeros(b.shape) for b in self.biases]\n gradient_w = [np.zeros(w.shape) for w in self.weights]\n for x, y in mini_batch:\n delta_gradient_w, delta_gradient_b = self.backprop(x, y)\n gradient_b = [gb + dgb \n for gb, dgb in zip(gradient_b, delta_gradient_b)]\n gradient_w = [gw + dgw \n for gw, dgw in zip(gradient_w, delta_gradient_w)]\n \n update_w = [o + n for o, n in zip([gamma * puw \n for puw in self.prev_update_w], [eta * gw for gw in gradient_w])]\n self.weights = [w - uw for w, uw in zip(self.weights, update_w)]\n \n update_b = [o + n for o, n in zip([gamma * pub for \n pub in self.prev_update_b], [eta * gb for gb in gradient_b])]\n #update_b = gamma * self.prev_update_b + eta * gradient_b\n self.biases = [b - ub for b, ub in zip(self.biases, update_b)]\n \n self.prev_update_w = update_w\n self.prev_update_b = update_b\n\n def update_NAG(self, mini_batch, eta, gamma):\n \"\"\"\n Updates parameters using NAG.\n \n Updates weights and biases after applying \n Nesterov accerelated Gradient Descent (GD)\n on the mini batch.\n \n Parameters\n ----------\n mini_batch: list\n List of tuples (x, y)\n \n eta: float\n Learning rate\n \n gamma: float\n Momentum value\n \n Returns\n -------\n None\n \"\"\"\n \n gradient_w = [np.zeros(w.shape) for w in self.weights]\n gradient_b = [np.zeros(b.shape) for b in self.biases]\n \n # w look_ahead partial update\n #update_w = gamma * self.prev_update_w\n update_w = [o + n for o, n in zip([gamma * puw \n for puw in self.prev_update_w], [eta * gw for gw in gradient_w])]\n #update_b = gamma * self.prev_update_b\n update_b = [o + n for o, n in zip([gamma * pub \n for pub in self.prev_update_b], [eta * gb for gb in gradient_b])]\n \n for x, y in mini_batch:\n delta_gradient_w, delta_gradient_b = self.backprop(\n x, y, self.weights - update_w, self.biases - update_b)\n gradient_w = [gw + dgw \n for gw, dgw in zip(gradient_w, delta_gradient_w)]\n gradient_b = [gb + dgb \n for gb, dgb in zip(gradient_b, delta_gradient_b)] \n \n # full update\n update_w = [o + n for o, n in zip([gamma * puw \n for puw in self.prev_update_w], [eta * gw for gw in gradient_w])]\n #update_w = gamma * self.prev_update_w + eta * gradient_w\n self.weights = [w - uw for w, uw in zip(self.weights, update_w)]\n \n update_b = [o + n for o, n in zip([gamma * pub\n for pub in self.prev_update_b], [eta * gb for gb in gradient_b])]\n #update_b = gamma * self.prev_update_b + eta * gradient_b\n self.biases = [b - ub for b, ub in zip(self.biases, update_b)]\n \n self.prev_update_w = update_w\n self.prev_update_b = update_b\n\n def compile(self):\n \"\"\"\n Compiles the NN.\n \n Initializes the parameters of the NN.\n \n Returns\n -------\n None\n \"\"\"\n \n self.config[\"epochs\"] = int(input(\"Number of epochs: \"))\n\n pretrain = input(\"Load Neural Network(Yes/No): \")\n if pretrain == \"Yes\":\n self.init_params(self.sizes, self.config[\"epochs\"])\n filename = input(\"Enter the filename: \")\n self.load(filename)\n else:\n print(\"Weight initialization methods available:\")\n print(\"random (Random initialization)\")\n print(\"xavier (Xavier initialization)\")\n print(\"he (He initialization)\")\n weight_init_type = input(\"Weight initialization: \")\n self.init_params(self.sizes, self.config[\"epochs\"], weight_init_type)\n \n print(\"Optimizer types available:\")\n print(\"GD (Gradient Desecent)\")\n print(\"MGD (Momentum based Gradient Desecent)\")\n print(\"NAG (Nesterov accerelated Gradient Desecent)\")\n self.config[\"optimizer\"] = input(\"Optimizer: \")\n if (self.config[\"optimizer\"] == \"MGD\" or self.config[\"optimizer\"] == \"NAG\"):\n self.config[\"gamma\"] = float(input(\"gamma (momentum): \"))\n else:\n self.config[\"gamma\"] = None\n \n self.config[\"eta\"] = float(input(\"Learning rate: \"))\n \n self.config[\"mode\"] = input(\"learning mode (online/mini_batch/batch): \")\n if self.config[\"mode\"] == \"mini_batch\":\n self.config[\"batch_size\"] = int(input(\"Mini-batch size: \"))\n else:\n self.config[\"batch_size\"] = None\n \n self.config[\"shuffle\"] = bool(input(\"Random shuffle training data (True/False): \"))\n \n self.config[\"task\"] = input(\"task (classification/regression): \")\n \n ''' \n self.fit(training_data, epochs, batch_size, eta, gamma,\n optimizer, mode, shuffle, test_data, task)\n \n if test_data:\n self.logging(test_data)\n\n save_option = input(\"Save Neural Network(Yes/No): \")\n if save_option == \"Yes\":\n filename = input(\"Enter the filename: \")\n self.save(filename)\n else:\n pass\n '''\n \n def fit(self, training_data, validation_data=None):\n \"\"\"\n Runs the optimizer on the training data for given number of epochs.\n \n Parameters\n ----------\n training_data: list\n List of tuples (x, y)\n \n epochs: int\n Maximum number of epochs.\n \n batch_size: int\n Size of the mini_batch\n \n eta: float\n Learning rate.\n \n gamma: float\n Momentum value\n Default: None \n \n optimizer: str\n Type of optimizer\n Options:\n GD ( Gradient Descent)\n MGD ( Momentum based GD )\n NAG ( Nesterov accelerated GD )\n Default: GD\n \n mode: str\n Mode of Learning\n Options:\n online ( Stochastic GD )\n mini-batch ( Mini-batch GD )\n batch ( Batch GD)\n Default: batch\n \n shuffle: bool\n Random shuffle the training data.\n Default: True\n \n test_data: list\n List of tuples (x, y)\n \n type: str\n Type of task.\n Options:\n classification\n regression\n \n Returns\n -------\n None\n \"\"\"\n \n n = len(training_data)\n batch_size = self.get_batch_size(training_data, self.config[\"mode\"]\n , self.config[\"batch_size\"])\n \n if self.config[\"optimizer\"] == \"MGD\":\n self.prev_update_w = [np.zeros(w.shape) for w in self.weights]\n self.prev_update_b = [np.zeros(b.shape) for b in self.biases]\n \n print(\"---------------Status---------------\")\n best_accuracy = 0\n best_weights = list()\n best_biases = list()\n for e in range(self.config[\"epochs\"]):\n if self.config[\"shuffle\"]:\n random.shuffle(training_data)\n \n mini_batches = [training_data[k:k+batch_size]\n for k in range(0, n, batch_size)]\n \n for mini_batch in mini_batches:\n if self.config[\"optimizer\"] == \"GD\":\n self.update_GD(mini_batch, self.config[\"eta\"])\n elif self.config[\"optimizer\"] == \"MGD\":\n self.update_MGD(mini_batch, self.conifg[\"eta\"],\n self.config[\"gamma\"])\n elif self.config[\"optimizer\"] == \"NAG\":\n self.update_MGD(mini_batch, self.conifg[\"eta\"],\n self.config[\"gamma\"])\n \n if validation_data:\n acc = self.accuracy(validation_data)\n if acc > best_accuracy:\n best_accuracy = acc\n best_weights = self.weights\n best_biases = self.biases\n print(\"Epoch: \", e, \"Accuracy: \", acc)\n if e == self.config[\"epochs\"] - 1:\n print(\"Max accuracy achieved on validation data: \",\n best_accuracy)\n self.weights = best_weights\n self.biases = best_biases\n else:\n print(\"Epoch {0} complete\".format(e))\n\n save_option = input(\"Save Neural Network(Yes/No): \")\n if save_option == \"Yes\":\n filename = input(\"Enter the filename: \")\n self.save(filename)\n else:\n pass\n \n def predict(self, new_data):\n return self.feedforward(x for x in new_data) \n \n def logging(self, test_data=None):\n \"\"\"\n Given test data it plots Epoch vs Error graph.\n \n Parameter\n ---------\n test_data: list\n List of tuples (x, y)\n \n Returns\n -------\n None\n \"\"\"\n \n if test_data:\n error = [(100 - a) for a in self.accuracy ]\n \n plt.plot(self.epoch_list, error)\n plt.title(\"Epoch vs Error\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Error\")\n plt.show()\n else:\n pass\n \n def save(self, filename):\n \"\"\"\n Save the NN to the file ``filename``.\n \n Parameters\n ----------\n filename: str\n \n Returns\n -------\n None \n \"\"\"\n \n config = {\"sizes\": self.sizes,\n \"weights\": [w.tolist() for w in self.weights],\n \"biases\": [b.tolist() for b in self.biases],\n \"activation_fns\": self.activation_types,\n \"loss\": self.loss_fn}\n fhand = open(filename, \"w\")\n json.dump(config, fhand)\n fhand.close()\n\n def load(self, filename):\n \"\"\"\n Load a neural network from the file ``filename``.\n \n Parameters\n ----------\n NN: Neural network object\n filename: str \n \n Returns\n -------\n NN: Neural network object\n \n \"\"\"\n fhand = open(filename, \"r\")\n config = json.load(fhand)\n fhand.close()\n \n self.sizes = config[\"sizes\"]\n self.weights = [np.array(w) for w in config[\"weights\"]]\n self.biases = [np.array(b) for b in config[\"biases\"]]\n self.activation_types = config[\"activation_fns\"]\n self.loss_fn = config[\"loss\"]","sub_path":"Feedforward Neural Network/fnn.py","file_name":"fnn.py","file_ext":"py","file_size_in_byte":24474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90607979","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: HuRuiFeng\n@file: types.py\n@time: 2020/8/18 17:21\n@project: wasm-python-book\n@desc: Wasm 8种实体类型\n\"\"\"\n\n# 值类型\n# 32位整数(简称i32)\nValTypeI32 = 0x7F\n# 64位整数(简称i64)\nValTypeI64 = 0x7E\n# 32位浮点数(简称f32)\nValTypeF32 = 0x7D\n# 64位浮点数(简称f64)\nValTypeF64 = 0x7C\n\nBlockTypeI32 = -1 # ()->(i32)\nBlockTypeI64 = -2 # ()->(i64)\nBlockTypeF32 = -3 # ()->(f32)\nBlockTypeF64 = -4 # ()->(f64)\nBlockTypeEmpty = -64 # ()->()\n\nFtTag = 0x60\nFuncRef = 0x70\n\nMutConst = 0\nMutVar = 1\n\n\nclass FuncType:\n \"\"\"\n 函数类型:函数的签名或原型\n \"\"\"\n\n def __init__(self, tag=0, param_types=None, result_types=None):\n if result_types is None:\n result_types = []\n if param_types is None:\n param_types = []\n self.tag = tag\n # 函数的参数数量和类型\n self.param_types = param_types\n # 函数的返回值数量和类型\n self.result_types = result_types\n\n def equal(self, ft2) -> bool:\n if len(self.param_types) != len(ft2.param_types) \\\n or len(self.result_types) != len(ft2.reslut_types):\n return False\n for i, vt in enumerate(self.param_types):\n if vt != ft2.param_types[i]:\n return False\n for i, vt in enumerate(self.result_types):\n if vt != ft2.reslut_types[i]:\n return False\n return True\n\n def get_signature(self) -> str:\n sb = \"(\"\n sb += \",\".join([val_type_to_str(vt) for vt in self.param_types])\n sb += \")->(\"\n sb += \",\".join([val_type_to_str(vt) for vt in self.result_types])\n sb += \")\"\n return sb\n\n def __str__(self):\n return self.get_signature()\n\n\nclass Limits:\n \"\"\"\n 限制类型:描述表的元素数量上下限,或者内存的页数上下限\n limits : tag|min|max?\n \"\"\"\n\n def __init__(self, tag=0, min=0, max=0):\n # 如果tag是0,表示只指定下限。否则,tag必须为1,表示既指定下限,又指定上限\n self.tag = tag\n self.min = min\n self.max = max\n\n def __str__(self):\n return \"{min: %d, max: %d}\" % (self.min, self.max)\n\n\n# 内存类型\n# mem_type: limits\nMemType = Limits\n\n\nclass TableType:\n \"\"\"\n 表类型:描述表的元素类型和元素数量的限制\n table_type: 0x70|limits\n \"\"\"\n\n def __init__(self, elem_type=0x70, limits=None):\n # 元素类型\n self.elem_type = elem_type\n # 元素数量的限制\n self.limits = limits\n\n\nclass GlobalType:\n \"\"\"\n 全局变量类型:描述全局变量的类型和可变性\n global_type: val_type|mut\n \"\"\"\n\n def __init__(self, val_type=0, mut=0):\n # 全局变量的类型\n self.val_type = val_type\n # 可变性\n self.mut = mut\n\n def __str__(self):\n return \"{type: %s, mut: %d}\" % (val_type_to_str(self.val_type), self.mut)\n\n\ndef val_type_to_str(vt) -> str:\n if vt == ValTypeI32:\n return \"i32\"\n elif vt == ValTypeI64:\n return \"i64\"\n elif vt == ValTypeF32:\n return \"f32\"\n elif vt == ValTypeF64:\n return \"f64\"\n else:\n raise Exception(\"invalid valtype: %d\" % vt)\n","sub_path":"src/ch06/binary/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"579188308","text":"\nfrom django.utils.translation import gettext_lazy as _\nfrom django.core.urlresolvers import reverse\n\nfrom horizon import tabs\nfrom horizon.utils import memoized\n\nfrom gutsdashboard.services.sources import tabs as sources_tabs\nfrom gutsdashboard.api import guts as guts_api\nfrom horizon import exceptions\n\n\nclass SourceDetailView(tabs.TabView):\n tab_group_class = sources_tabs.SourceDetailTabs\n template_name = 'services/sources/detail.html'\n page_title = _(\"Source Hypervisor Details\")\n\n @memoized.memoized_method\n def get_data(self):\n source_id = self.kwargs['source_id']\n try:\n source = guts_api.source_get(\n self.request, source_id\n )\n except Exception:\n exceptions.handle(\n self.request,\n _(\"Unable to retrieve source details\"),\n redirect=reverse(\"horizon:guts:services:index\")\n )\n return source\n\n def get_context_data(self, **kwargs):\n context = super(SourceDetailView, self).get_context_data(**kwargs)\n context['source'] = self.get_data()\n return context\n\n def get_tabs(self, request, *args, **kwargs):\n source = self.get_data()\n return self.tab_group_class(\n request, source=source, *args, **kwargs\n )\n","sub_path":"gutsdashboard/services/sources/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"624258565","text":"# -*- coding: utf-8 -*-\n\nimport sys\nmodule_path = '../estimate_emotion'\nif module_path not in sys.path:\n sys.path.append(module_path)\nimport datetime\nimport urllib.parse\nimport os\nimport sqlite3\nfrom collections import defaultdict\nimport pickle\nimport multiprocessing\nfrom itertools import repeat\nfrom functools import partial\nimport json\n \nimport pandas as pd\nfrom tqdm import tqdm\nimport gensim\nfrom keras.preprocessing import sequence\nimport torch\nfrom torch.autograd import Variable\nimport numpy as np\n\nimport cnn_text\nfrom prepare_dataset import padding_for_filter, word2index_parallel, word2index\n\n\nDATAPATH = '../data/'\nINTERVAL_TO_AJUST = 0 # day(s)\nINTERVAL_TO_TRADE = 1 # day(s)\nINTERVAL_TO_EVAL = 1 # day(s)\nTRADE_HOUR = 8\nN_WORKERS = 4 # or os.cpu_count()\nBATCH_SIZE = 50\nOUT_FILE_SUFFIX = 'both' # INTERVAL_TO_EVAL\n\n\ndef check_leap(dt):\n \"\"\"Check if datetime is a leap year.\"\"\"\n \n if '年' in dt:\n dt = datetime.datetime.strptime(dt, '%Y年%m月%d日 %H:%M')\n else:\n dt = datetime.datetime.strptime(dt, '%m月%d日 %H:%M')\n \n if dt.month == 2 and dt.day == 29:\n return True\n else:\n return False\n\n\ndef append_year(dt, this_year):\n \"\"\"Append a year to datetime string and convert it into datetime object.\"\"\"\n\n if '年' not in dt:\n dt = this_year + dt\n try:\n dt = datetime.datetime.strptime(dt, '%Y年%m月%d日 %H:%M')\n except:\n print(dt)\n raise ValueError('datetime format is not correct. dt is {}'.format(dt))\n return dt\n\n\ndef find_this_year(dates):\n \"\"\"Identify the latest year in posts for a stock. This is not smart. Rethink the other way later.\"\"\"\n\n joined_dates = ', '.join(dates)\n \n if '2017年' in joined_dates:\n this_year = '2018年'\n elif '2016年' in joined_dates:\n this_year = '2017年'\n elif '2015年' in joined_dates:\n this_year = '2016年'\n elif '2014年' in joined_dates:\n this_year = '2015年'\n elif '2013年' in joined_dates:\n this_year = '2014年'\n elif '2012年' in joined_dates:\n this_year = '2013年'\n else:\n raise\n \n return this_year\n\n\ndef extract_user_token(user_url):\n \"\"\"Extract user token in user_url for identifying users.\"\"\"\n \n parsed = urllib.parse.urlparse(user_url)\n query = urllib.parse.parse_qs(parsed.query)\n user_token = query['user'][0]\n return user_token\n\n\ndef round_off_datetime(date, hour):\n \"\"\"E.g.\n 2017-01-01 07:00 -> 2016-12-31\n 2017-01-01 09:00 -> 2017-01-01\"\"\"\n\n if date.hour <= hour:\n return (date - datetime.timedelta(days=1)).strftime('%Y-%m-%d')\n else:\n return date.strftime('%Y-%m-%d')\n\n\ndef eval_performance(code, user_tokens, dates, labels):\n \"\"\"Evaluate author's performance.\"\"\"\n \n performances = {}\n match_code = close_df[close_df['code'] == code]\n for user, date, label in zip(list(user_tokens), list(dates), list(labels)):\n date_t = round_off_datetime(date, TRADE_HOUR)\n date_t_d = round_off_datetime(date + datetime.timedelta(days=INTERVAL_TO_EVAL), TRADE_HOUR)\n close_t = match_code[match_code['日付'] == date_t]['終値']\n close_t_d = match_code[match_code['日付'] == date_t_d]['終値']\n \n if close_t.empty or close_t_d.empty:\n continue\n \n if user not in performances.keys():\n performances[user] = []\n \n close_t = close_t.item()\n close_t_d = close_t_d.item()\n if label == 1:\n ret = (close_t_d - close_t) / close_t\n elif label == 0: # -1 to 0 @2017-08-26\n ret = (close_t - close_t_d) / close_t\n label = -1\n else:\n print(type(label))\n print(label)\n raise ValueError('Unexpected label: {}'.format(label))\n \n performances[user].append({'code':code, 'date_t':date,\n 'date_t_d':datetime.datetime(date.year, date.month, date.day, 15, 0),\n 'label':label, 'return':ret})\n return performances\n\n\ndef construct_portfolios(all_records_df, begin_dt, end_dt):\n \"\"\"Construct portfolio of each day from begin_dt to end_dt.\"\"\"\n\n trade_dt = datetime.datetime.strptime(begin_dt, '%Y-%m-%d %H:%M')\n end_dt = datetime.datetime.strptime(end_dt, '%Y-%m-%d %H:%M')\n total_days = end_dt - trade_dt\n \n portfolios = {}\n while trade_dt < end_dt:\n # Print progress\n print('\\r{:5d} / {:5d} days'.format(total_days.days - (end_dt - trade_dt).days + 1,\n total_days.days), end='\\r')\n \n positions = all_records_df[(all_records_df['date_t'] > (trade_dt - datetime.timedelta(days=1))) & (all_records_df['date_t'] < trade_dt)]\n \n portfolio = defaultdict(int)\n duplicates = []\n for code, label, user in positions[['code', 'label', 'user']].values.tolist():\n # Could be duplicate posts, so skip it\n if (code, label, user) in duplicates:\n continue\n duplicates.append((code, label, user))\n \n # Past records of a user before trade_dt\n past_records = all_records_df[(all_records_df['user'] == user) & (all_records_df['date_t_d'] < (trade_dt - datetime.timedelta(days=1)))]\n \n # Cumulative return of a user before trade_dt\n i_S_t = past_records['return'].sum()\n \n # We assume we can take only long position.\n # There are two scenarios:\n # Follow a user whose cumulative return is positive and position in trade_dt is long\n # Oppose a user whose cumulative return is negative and position in trade_dt is short\n # Follow winners\n # if i_S_t > 0 and label == 1:\n # Oppose losers\n # if i_S_t < 0 and label == -1:\n # Follow winners and oppose losers\n if i_S_t*label > 0:\n portfolio[code] += i_S_t*label\n \n # Calculate proportion of investment for each stock\n S_t_plus = sum(portfolio.values())\n for code, i_S_t_plus in portfolio.items():\n portfolio[code] = i_S_t_plus / S_t_plus\n \n portfolios[trade_dt] = portfolio\n \n trade_dt += datetime.timedelta(days = INTERVAL_TO_TRADE)\n \n return portfolios\n\n\ndef calc_sub_return(trade_date, portfolio):\n date_t = round_off_datetime(trade_date, TRADE_HOUR)\n date_t_d = round_off_datetime(trade_date + datetime.timedelta(days=INTERVAL_TO_EVAL), TRADE_HOUR)\n \n our_return = 0\n for code, prop in portfolio.items():\n match_code = close_df[close_df['code'] == code]\n close_t = match_code[match_code['日付'] == date_t]['終値']\n close_t_d = match_code[match_code['日付'] == date_t_d]['終値']\n \n if close_t.empty or close_t_d.empty:\n continue\n \n close_t = close_t.item()\n close_t_d = close_t_d.item()\n ret = (close_t_d - close_t) / close_t\n \n our_return += prop * ret\n return (trade_date, our_return)\n \n\ndef calc_ret(portfolios, close_df):\n \"\"\"Calculate our returns of each day based on our portfolios.\"\"\"\n \n with multiprocessing.Pool(processes=N_WORKERS) as pool:\n our_returns = pool.starmap(calc_sub_return, list(portfolios.items()))\n our_returns = pd.DataFrame(list(our_returns), columns=['date', 'return']).set_index('date').sort_index()\n return our_returns\n\n\ndef get_performances(code, dates, comments, user_urls, model):\n \n # Convert to datetime object\n try:\n this_year = find_this_year(dates)\n except:\n return {}\n dates = [append_year(date, this_year) for date in dates]\n \n user_tokens = [extract_user_token(user_url) for user_url in user_urls]\n \n encoded_comments = word2index(word_list, comments)\n \n X = sequence.pad_sequences(encoded_comments, maxlen=100, dtype=int) # or maxlen = max_words\n X = padding_for_filter(X, filter_size=5)\n \n X = Variable(torch.LongTensor(X.astype(int)))\n batch_size = min(len(X), BATCH_SIZE) \n logit = cnn_text.predict(X, estimator, batch_size=batch_size)\n logit_np = logit.data.numpy()\n prob = np.exp(logit_np) / np.exp(logit_np).sum(axis=1)[:, np.newaxis]\n\n row, col = np.where(prob > .9)\n \n dates = [dates[i] for i in row]\n user_tokens = [user_tokens[i] for i in row]\n labels = col.tolist()\n \n performances = eval_performance(code, user_tokens, dates, labels)\n \n return performances\n\n\nif __name__ == '__main__':\n now = '2018-01-13' # or datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n out_dir = 'output/' + now\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n \n #Load stock time series data\n close_df = pd.read_csv('nikkei_close_2012-2017.csv', dtype={'code':str})\n \n # Prepare for database\n DBNAME = 'textream_db_nikkei_parse_predicted.db'\n dbpath = DATAPATH + 'textream/' + DBNAME\n conn = sqlite3.connect(dbpath)\n cursor = conn.cursor()\n\n # Stocks stored in database\n table_list = [item[1] for item in cursor.execute('select * from sqlite_master WHERE type=\"table\"')]\n \n # snapshot_path = '../predict_emotion/snapshot/2017-08-25_19-21-23/snapshot_epoch49.model'\n snapshot_path = '../estimate_emotion/output/snapshot/{}/snapshot_epoch3.pt'.format('2017-08-28_02-39-46')\n estimator = torch.load(snapshot_path, map_location=lambda storage, loc: storage)\n \n # w2v_name = 'w2v_10_100.model'\n # w2v_path = '../predict_emotion/output/' + w2v_name\n dt = '2017-08-28_02-00-47'\n min_count = 10\n size = 300\n w2v_path = '../estimate_emotion/output/{}/min_count{}_size{}.w2v'.format(dt, min_count, size)\n w2v = gensim.models.Word2Vec.load(w2v_path)\n word_list = w2v.wv.index2word\n \n dates, comments, user_tokens = [], [], []\n fetched_data = []\n for tablename in table_list:\n code = tablename.replace('code_', '')\n sql = 'select date, comment, user_url from ' + tablename\n cursor.execute(sql)\n try:\n dates, comments, user_urls = zip(*cursor.fetchall())\n except:\n print(tablename)\n continue\n comments = [json.loads(comment) for comment in comments]\n fetched_data.append((code, dates, comments, user_urls))\n conn.close()\n \n with multiprocessing.Pool(processes = N_WORKERS) as pool:\n performances_list = pool.starmap(partial(get_performances, model=estimator), fetched_data)\n \n # Put calculated performances all together\n all_performances = {}\n for performances in performances_list:\n for user, records in performances.items():\n if user not in all_performances.keys():\n all_performances[user] = []\n all_performances[user] += records\n \n all_perf_file = 'all_performances_{}.pkl'.format(OUT_FILE_SUFFIX)\n with open(os.path.join(out_dir, all_perf_file), 'wb') as f:\n pickle.dump(all_performances, f)\n \n # Transform all_performances into pandas DataFrame\n all_records_df = []\n for user, records in tqdm(all_performances.items()):\n records_df = pd.concat([pd.DataFrame(records),\n pd.Series([user]*len(records), name='user')], axis=1)\n all_records_df.append(records_df)\n all_records_df = pd.concat(all_records_df, ignore_index=True)\n all_records_file = 'all_records_{}.csv'.format(OUT_FILE_SUFFIX)\n all_records_df.to_csv(os.path.join(out_dir, all_records_file))\n \n # Construct portfolios\n begin_dt = '2013-01-05 08:00'\n end_dt = '2016-01-05 08:00'\n portfolios = construct_portfolios(all_records_df, begin_dt, end_dt)\n portfolio_file = 'portfolios_{}.pkl'.format(OUT_FILE_SUFFIX)\n with open(os.path.join(out_dir, portfolio_file), 'wb') as f:\n pickle.dump(portfolios, f)\n\n # Calculate returns\n our_returns = calc_ret(portfolios, close_df)\n our_ret_file = 'our_returns_{}.csv'.format(OUT_FILE_SUFFIX)\n our_returns.to_csv(os.path.join(out_dir, our_ret_file))\n\n # Plot cumulative returns\n # our_returns.cumsum().plot()\n\n","sub_path":"portfolio/portfolio_selection.py","file_name":"portfolio_selection.py","file_ext":"py","file_size_in_byte":12289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"441961074","text":"import appdaemon.plugins.hass.hassapi as hass\nfrom notify import notify\n# \n# Version 1.1: \nclass GarageDoor(hass.Hass):\n\n def initialize(self):\n self.handle = None\n self.listen_state(self.garage_door_switch, \"switch.garage_door_switch\")\n self.listen_state(self.garage_door_sensor, \"binary_sensor.garage_door_sensor_contact\")\n self.set_log_level(\"DEBUG\")\n\n def garage_door_switch(self, entity, attribute, old, new, kwargs):\n door_state = self.get_state(\"binary_sensor.garage_door_sensor_contact\")\n mode = self.get_state(\"input_select.holman_mode\")\n self.log(\"Switch is: {} Sensor is: {}:\".format(new, door_state))\n\n if door_state != new: \n if mode == \"Present\":\n self.log(\"Pushing button\")\n self.turn_on(\"switch.garage_door_button\")\n\n elif mode != \"Present\" and door_state in ( \"on\", \"On\", \"Open\", \"open\"):\n self.log(\"Pushing button\")\n self.turn_on(\"switch.garage_door_button\")\n\n else:\n self.log(\"Refusing to push button when door state is {} and mode is {}.\".format(door_state, mode))\n\n self.run_in(self.check_state, 22)\n\n def garage_door_sensor(self, entity, attribute, old, new, kwargs):\n switch_state_raw = self.get_state(\"switch.garage_door_switch\")\n mode = self.get_state(\"input_select.holman_mode\")\n\n if new == \"off\":\n sensor_state = \"closed\"\n elif new == \"on\":\n sensor_state = \"open\"\n\n if switch_state_raw == \"off\":\n switch_state = \"closed\"\n elif switch_state_raw == \"on\":\n switch_state = \"open\"\n\n logtxt=\"Garage Door Sensor is: {}. Switch state is: {}.\".format(sensor_state,switch_state_raw)\n self.log(logtxt)\n messagetxt=\"Garage Door Sensor is {}.\".format(sensor_state)\n self.call_service(\"notify/alexa_media\", target = [\"media_player.kitchen\", \"media_player.bedroom\"], message = messagetxt, data = {\"type\":\"tts\"})\n\n if mode != \"Present\" and new == \"on\":\n titletxt=\"Garage Door {} Mode: {} \".format,(new, mode)\n #notify.push_crit(self, title=titletxt, message=messagetxt)\n\n if mode != \"Present\" and new == \"on\":\n msg=\"Garage Door {} Mode: {} \".format,(new, mode)\n\n if switch_state != new: \n if new == \"on\":\n self.log(\"Turning garage door switch on to match.\")\n self.turn_on(\"switch.garage_door_switch\")\n\n if new == \"off\":\n self.log(\"Turning garage door switch off to match.\")\n self.turn_off(\"switch.garage_door_switch\")\n\n def check_state (self, kwargs):\n switch_state = self.get_state(\"switch.garage_door_switch\")\n door_state = self.get_state(\"binary_sensor.garage_door_sensor_contact\")\n if switch_state != door_state and ( door_state is not None or new is not None ):\n self.log(\"Switch is: {} Sensor is: {}. Button press failed.\".format(switch_state, door_state))\n if switch_state == \"on\":\n self.log(\"Retry button press\")\n self.turn_on(\"switch.garage_door_button\")\n\n if switch_state == \"off\":\n self.log(\"Revert garage door switch to on.\")\n self.turn_on(\"switch.garage_door_switch\")\n\n","sub_path":"garage_door.py","file_name":"garage_door.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"293594685","text":"import torch\nimport cv2\nimport torchvision.models as models\nfrom PIL import Image\nimport torch.nn as nn\nimport numpy as np\nfrom torchvision import transforms\ntransform = transforms.Compose([ #[1]\n transforms.Resize(256), #[2] 按比例把宽W缩小到256\n transforms.CenterCrop(224), #[3] 中间裁剪出224x224大小的图片\n transforms.ToTensor(), #[4]\n transforms.Normalize( #[5]\n mean=[0.485, 0.456, 0.406], #[6]\n std=[0.229, 0.224, 0.225] #[7]\n )])\n\nclass FeatureExtractor(nn.Module):\n def __init__(self, submodule, extracted_layers):\n super(FeatureExtractor, self).__init__()\n self.submodule = submodule\n self.extracted_layers = extracted_layers\n \n # 自己修改forward函数\n def forward(self, x):\n outputs = []\n print('forward')\n for name, module in self.submodule._modules.items():\n #print(x.shape)\n #print(name)\n #print(module)\n if name == \"fc\":\n x = x.view(x.size(0), -1)\n x = module(x)\n if name in self.extracted_layers:\n outputs.append(x)\n return outputs\n\nextract_list = [\"layer1\", \"avgpool\", \"fc\"]\n\n#加载参数\nweights = torch.load('image_retrieval\\\\pretrained_model\\\\resnet101-5d3b4d8f.pth')\nimg = Image.open('cola.jpg')\n#print(weights) \n#用参数加载模型\nnet = models.resnet101(pretrained=False)\nnet.load_state_dict(weights)\n#print(net)\n#预处理图片\n'''\nt = transforms.Resize(256)\nimg_t1 = t(img)\nimg_t1.show()\nt2 = transforms.CenterCrop(224)\nimg_t2 = t2(img_t1)\nimg_t2.show()\n'''\nimg_t = transform(img)\nbatch_t = torch.unsqueeze(img_t, 0)\nprint(batch_t.shape)\n#预测\nnet.eval()\nout = net(batch_t)\nprint(out.shape)\n_, index = torch.max(out, 1)\n\n#标签\nwith open('image_retrieval\\\\labels.txt') as f:\n classes = [line.strip() for line in f.readlines()]\n#\npercentage = torch.nn.functional.softmax(out, dim=1)[0] * 100\nprint(classes[index[0]], percentage[index[0]].item())\n#\nextract_result = FeatureExtractor(net, extract_list)\n\nresult = extract_result(batch_t)\nfeature = result[1].data.numpy()\nprint(feature.shape)\nprint(np.squeeze(feature).shape)\nprint(result[0].data.numpy().shape)","sub_path":"image_retrieval/resnet101.py","file_name":"resnet101.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"112436101","text":"from __future__ import annotations\nfrom typing import TypeVar, NewType, Union, Callable, Tuple, Any, Dict, get_type_hints, List, Optional, Generic\nimport os\nimport json\nimport random\nimport functools\nimport copy\n\nimport numpy as np\nimport pandas as pd\n\nimport trainer.lib as lib\nfrom trainer.cg.Dsl import Dsl, Context\nfrom trainer.cg.DslFunc import DslFunc, CNodeType, CNode\nfrom trainer.cg.samplers import Sampler, FloatSampler, NumberSampler\n\n\nclass ProgInstance:\n\n @classmethod\n def from_json(cls, state: Dict, s_dict: Dict[str, Sampler]):\n res = cls(-1)\n res.state = state['state']\n node_states = {}\n for node_id in state['node_states']:\n vals, sampler_name = state['node_states'][node_id]\n sampler = s_dict[sampler_name]\n node_states[node_id] = sampler.from_json_repr(vals), sampler\n res.node_state = node_states\n res.stats = state['stats']\n # res.state['instance_id'] = new_id\n return res\n\n def __init__(self, architecture_id: int):\n self.state = {\n 'instance_id': -1,\n 'architecture_id': architecture_id,\n 'locked': 0\n }\n self.node_state: Dict[int, Tuple[List[Any], Sampler]] = {}\n self.stats = {\n 'used': 0\n }\n\n def duplicate(self) -> ProgInstance:\n copy_dict = copy.deepcopy(self.state)\n new_instance = ProgInstance(self.get_architecture_id())\n new_instance.state = copy_dict\n return new_instance\n\n def get_json(self):\n node_states = {}\n for node_id in self.node_state:\n vals, s = self.node_state[node_id]\n node_states[node_id] = s.get_json_repr(vals), s.name\n return {\n 'state': self.state,\n 'node_states': node_states,\n 'stats': self.stats\n }\n\n def get_instance_id(self) -> int:\n return self.state['instance_id']\n\n def set_instance_id(self, new_id: int) -> None:\n self.state['instance_id'] = new_id\n\n def get_architecture_id(self) -> int:\n return self.state['architecture_id']\n\n def lock(self):\n self.state['locked'] += 1\n\n def unlock(self):\n self.state['locked'] -= 1 if self.state['locked'] > 0 else 0\n\n def is_locked(self):\n return self.state['locked'] > 0\n\n def get_node_dict(self, n_id: int):\n return self.node_state[n_id] if n_id in self.node_state else None\n\n def resample_node(self, n_id: int) -> Any:\n sampler = self.node_state[n_id][1]\n new_value = sampler.resample(last_value=self.node_state[n_id][0][-1])\n self.node_state[n_id][0].append(new_value)\n return new_value\n\n def revert_resampling(self, n_id):\n self.node_state[n_id][0].pop()\n\n def get_value(self, n_id: int):\n if n_id not in self.node_state:\n return None\n return self.node_state[n_id][0][-1]\n\n def set_value(self, n_id, new_val: Any, s: Sampler) -> Any:\n if n_id not in self.node_state:\n self.node_state[n_id] = ([], s)\n self.node_state[n_id][0].append(new_val)\n return new_val\n\n def pick_node_id(self) -> Optional[int]:\n if self.node_state:\n return random.choice(list(self.node_state))\n else:\n return None\n\n def increment_used(self):\n self.stats['used'] += 1\n\n\nclass ProgPool:\n\n @classmethod\n def from_disk(cls, p: str, r_type: Any, fs: List[Tuple[Callable, float]], c: Context, samplers: List[Sampler]):\n res = cls(r_type, fs, c, samplers)\n\n # Load from disk\n df_words = pd.read_excel(p, index_col=0)\n json_path = f'{os.path.splitext(p)[0]}.json'\n with open(json_path, 'r') as f:\n instances_json = json.load(f)\n\n words_ls = [(word, depth) for i, (word, depth) in df_words.iterrows()]\n res.words = words_ls\n res._parse_progs()\n\n s_dict = {s.name: s for s in samplers}\n\n for inst_key in instances_json:\n res.instances[inst_key] = ProgInstance.from_json(instances_json[inst_key], s_dict)\n\n return res\n\n def __init__(self, r_type: Any, fs: List[Tuple[Callable, float]], context: Context, samplers: List[Sampler],\n max_nodes=25, append_standard_samplers=True):\n if append_standard_samplers:\n samplers.append(FloatSampler())\n samplers.append(NumberSampler(0, 10))\n\n start_dict = {s.name: (s.sample, CNodeType.ParamNode) for s in samplers}\n self._dsl = Dsl(context, start_dict, samplers)\n for f, prio in fs:\n self._dsl.add_function(f, prio)\n self.r_type = r_type\n self.dsl_fs: List[DslFunc] = []\n self.words: List[Tuple[str, int]] = [] # [(string repr, grammar depth)]\n\n self.samplers = []\n self.set_samplers(samplers)\n\n self.instances: Dict[int, ProgInstance] = {}\n self.last_step: List[Tuple[int, int]] = []\n self.last_instance_invoked: int = -1\n self.new_instance_enumerator = 0\n self.last_killed_instances: Optional[List[ProgInstance]] = None\n self.last_birthed_instances: Optional[List[int]] = None\n self.init_n: int = 1\n self.max_nodes = max_nodes\n\n def set_samplers(self, samplers: List[Sampler]):\n for sampler in samplers:\n sampler.delegate = functools.partial(self._get_sampled_value, sampler)\n self.samplers = samplers\n\n def set_init_num(self, n: int):\n self.init_n: int = n\n\n def to_disk(self, identifier: str, parent_dir='') -> str:\n file_path = os.path.join(parent_dir, f'{lib.create_identifier(identifier)}')\n\n # Save programs\n writer = pd.ExcelWriter(f'{file_path}.xlsx')\n df_words = pd.DataFrame(self.words, columns=('ProgString', 'Depth'))\n df_words.to_excel(writer, sheet_name='main')\n writer.save()\n\n # Save instantiations\n save_json = {}\n for inst_key in self.instances:\n save_json[inst_key] = self.instances[inst_key].get_json()\n with open(f'{file_path}.json', 'w') as f:\n json.dump(save_json, f)\n return file_path\n\n def get_locks(self):\n return len([True for key in self.instances if self.instances[key].is_locked()])\n\n def optim_move(self, temperature: float, dim_factor=3.5):\n \"\"\"\n Resample one node of every program (which is not locked) inside the current instantiations.\n Performs birth and death moves randomly.\n \"\"\"\n assert 0. <= temperature <= 1.\n\n instance_keys = np.array(list(self.instances.keys()))\n np.random.shuffle(instance_keys)\n\n # Death Moves\n desired_deaths = len(self.instances) - self.init_n if self.init_n < len(self.instances) else 1.\n rand_deaths = np.floor((dim_factor * np.random.random()) * (desired_deaths * temperature))\n num_deaths = min(rand_deaths, len(self.instances) - 1)\n\n if num_deaths == len(self.instances):\n print('Do not kill all instances')\n\n death_ids = np.random.choice(instance_keys, size=int(num_deaths), replace=False)\n self.last_killed_instances = [self.instances[death_id] for death_id in death_ids]\n for death_id in death_ids:\n self.remove_instance(death_id)\n\n # The number of diffusion steps, proportional to temperature\n num_steps = int(np.ceil(len(self.instances) * temperature))\n instance_keys = list(instance_keys)\n for death_id in death_ids:\n instance_keys.remove(death_id)\n\n # Diffusion moves\n step = []\n for diff_step in range(num_steps):\n instance_key = instance_keys[diff_step % len(instance_keys)]\n if not self.instances[instance_key].is_locked():\n instance: ProgInstance = self.instances[instance_key]\n random_node_id = instance.pick_node_id() # Currently picks a node without a system\n if random_node_id is not None:\n # print(instance_key)\n # print(random_node_id)\n # vals, sampler = instance.get_node_dict(random_node_id)\n new_value = instance.resample_node(random_node_id)\n # print(new_value)\n step.append((instance_key, random_node_id))\n self.last_step = step\n\n # Birth Moves\n desired_births = self.init_n - len(self.instances) if self.init_n > len(self.instances) else 1.\n num_births = np.floor((dim_factor * np.random.random()) * (desired_births * temperature))\n self.last_birthed_instances = []\n for birth_step in range(int(num_births)):\n birthed_instance = self.sample_instance()\n self.last_birthed_instances.append(birthed_instance.get_instance_id())\n\n def revert_last_step(self):\n # Revert Birth steps\n for birth_id in self.last_birthed_instances:\n self.remove_instance(birth_id)\n\n # Revert diffusion steps\n for f_id, n_id in self.last_step:\n self.instances[f_id].revert_resampling(n_id)\n\n # Revert death steps\n for death_instance in self.last_killed_instances:\n self.append_instance(death_instance) # append_instance takes care of setting the new instance id\n\n def _get_sampled_value(self, s: Sampler, node_id: int):\n instance = self.instances[self.last_instance_invoked] # When executing an instance, make sure to first set this\n\n assert node_id is not None\n res = instance.get_value(node_id)\n if res is None:\n res = instance.set_value(node_id, s.resample(), s)\n\n return res\n\n def _parse_progs(self):\n if self.words is None:\n raise Exception(\"ProgPool is not correctly initialized\")\n\n roots = []\n self.dsl_fs = []\n for word, depth in self.words:\n j_word: Dict = json.loads(word)\n assert len(j_word.keys()) == 1\n # n_sem, n_type = self.semantics[list(j_word.keys())[0]]\n c_node = CNode.from_json(j_word, self._dsl.semantics)\n roots.append(c_node)\n\n dsl_f = DslFunc(c_node)\n if dsl_f.n_nodes <= self.max_nodes:\n self.dsl_fs.append(dsl_f)\n\n # self.dsl_fs = [DslFunc(n) for i, n in enumerate(roots)]\n # print(self.dsl_fs)\n\n def sample_words(self, max_n=10) -> None:\n words = self._dsl.sample_n_words(self.r_type, max_n=max_n)\n self.words = words\n self._parse_progs()\n\n def __getitem__(self, item: int):\n return self.dsl_fs[item]\n\n def append_instance(self, new_instance: ProgInstance):\n new_instance.set_instance_id(self.new_instance_enumerator)\n self.instances[self.new_instance_enumerator] = new_instance\n self.new_instance_enumerator += 1\n\n def initialize_instances(self):\n if self.init_n > len(self.dsl_fs):\n print(f\"There were less programs {len(self.dsl_fs)} than instances requested {self.init_n}\")\n for i in range(min(self.init_n, len(self.dsl_fs))):\n new_instance = ProgInstance(i)\n self.append_instance(new_instance)\n\n def visualize_instance(self, instance_id: int, parent_dir='', f_name='') -> None:\n if instance_id in self.instances:\n instance = self.instances[instance_id]\n dsl_func = self.dsl_fs[instance.get_architecture_id()]\n dsl_func.visualize(f_name, dir_path=parent_dir, instance_id=instance_id)\n else:\n lib.logger.debug_var(f\"Instance {instance_id} cannot be visualized, because it doesnt exist\")\n\n def sample_instance(self) -> ProgInstance:\n archi_id = random.randint(0, len(self.dsl_fs) - 1)\n new_instance = ProgInstance(archi_id)\n self.append_instance(new_instance)\n return new_instance\n\n def duplicate_instance(self, instance_id: int):\n new_instance = self.instances[instance_id].duplicate()\n self.append_instance(new_instance)\n\n def remove_instance(self, instance_id: int, p_locked=0.9) -> Optional[ProgInstance]:\n \"\"\"\n Removes an instance from the pool (Death Move).\n \"\"\"\n if instance_id in self.instances:\n if not self.instances[instance_id].is_locked():\n inst = self.instances.pop(instance_id)\n return inst\n else:\n # Instance is locked:\n if random.random() < p_locked:\n self.instances[instance_id].unlock()\n return None\n\n def remove_unused(self, remove_all_zero=True):\n usage = np.array([self.instances[key].stats['used'] for key in self.instances])\n candidates = np.where(usage == np.min(usage))[0]\n removal_id = np.random.choice(candidates)\n self.remove_instance(list(self.instances.keys())[removal_id])\n\n def execute(self, instance_id: int, state: Optional[Dict] = None, store=True, visualize_after=False):\n \"\"\"\n Executes a computational graph, specified by its instance_id in the current pool, on a given state.\n\n :param instance_id: Id of the graph-instance in the current pool.\n :param state: The state that the graph is computed upon. It will be applied to the context object.\n :param store: If true, stores intermediate values at each node. Slow, but improves visualization and debugging\n :param visualize_after: If true, writes the graph to disk after executing it\n :return: Result of the graph\n \"\"\"\n self.last_instance_invoked = instance_id\n instance: ProgInstance = self.instances[instance_id]\n dsl_func = self.dsl_fs[instance.get_architecture_id()]\n if state is not None:\n self._dsl.context.set_state(state)\n res = dsl_func.execute(store_result=store)\n\n if visualize_after:\n dsl_func.visualize(instance_id=instance_id)\n\n return res\n\n def compute_features(self, states: List[Dict], store=True, visualize_after=False) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Given a list of states, computes the output for all given states.\n Output: (#ProgramInstances, #states, Width, Height)\n \"\"\"\n res = []\n i_ids = []\n for instance_id in self.instances:\n state_results = []\n for state in states:\n state_res = self.execute(instance_id, state, store=store, visualize_after=visualize_after)\n state_results.append(state_res)\n res.append(np.array(state_results))\n i_ids.append(instance_id)\n r = np.array(res), np.array(i_ids)\n return r\n","sub_path":"trainer/cg/ProgPool.py","file_name":"ProgPool.py","file_ext":"py","file_size_in_byte":14653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"308667638","text":"\nimport os\nimport csv\nimport math\nimport numpy as np\nfrom datetime import datetime\n\nfrom numpy import array, empty\nfrom numpy.random import randint, rand\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom math import *\n\n\nHD = os.getenv('HOME')\n\nallDF = pd.DataFrame()\ndt = 20 # 20 frames is 1 second\ntimestep = 2\nframediff = (dt*timestep)\nposfilename = 'external.csv'\nposDF = pd.read_csv(posfilename) \nposDF['clip']=0\nposDF = posDF[posDF['frame']%framediff==0]\nposDF['move']=np.NaN\nposDF['moveLength']=np.NaN\nposDF['env_heading']=np.NaN\nfor index, row in posDF.iterrows():\n thisFrame = row['frame']\n thisID = row['c_id']\n thisX = row['x']\n thisY = row['y']\n \n thisTheta = row['heading']\n # calculate the change in heading from this point to the next\n nextTime = posDF[(np.abs(posDF['frame']-(thisFrame+framediff))<1e-6)&(posDF['c_id']==thisID)]\n if len(nextTime)==1:\n dx = nextTime.iloc[0]['x'] - thisX\n dy = nextTime.iloc[0]['y'] - thisY\n posDF.ix[index,'dx']=dx\n posDF.ix[index,'dy']=dy\n posDF.ix[index,'move'] = math.atan2(dy,dx) - thisTheta\n posDF.ix[index,'moveLength'] = (dy**2+dx**2)**0.5\n\n \n\n\nfor index, row in posDF.iterrows():\n thisFrame = row['frame']\n thisID = row['c_id']\n thisX = row['x']\n thisY = row['y']\n tdx = row['dx']\n tdy = row['dy']\n \n thisTheta = row['heading']\n # calculate the change in heading from this point to the next\n nextTime = posDF[(np.abs(posDF['frame']-(thisFrame+framediff))<1e-6)&(posDF['c_id']==thisID)]\n# prevTime = posDF[(np.abs(posDF['frame']-(thisFrame-2*dt))<1e-6)&(posDF['c_id']==thisID)]\n# if len(prevTime)==1:\n# pdx = prevTime.iloc[0]['dx'] \n# pdy = prevTime.iloc[0]['dy'] \n# posDF.ix[index,'heading'] = math.atan2(pdy,pdx) \n# thisTheta = math.atan2(pdy,pdx) \n#posDF.ix[index,'move'] = math.atan2(tdy,tdx) - thisTheta\n \n if len(nextTime)==1:\n # calculate the average heading all the other caribou were taking at this point\n excThis = posDF[posDF.c_id!=thisID]\n xp = excThis['x'].values\n yp = excThis['y'].values\n xdirs = excThis['dx'].values\n ydirs = excThis['dy'].values\n \n xp = xp[np.isfinite(xdirs)]\n yp = yp[np.isfinite(xdirs)]\n ydirs = ydirs[np.isfinite(xdirs)]\n xdirs = xdirs[np.isfinite(xdirs)]\n # decay rate of 4 gives the maximum likelihood for the environment only model\n kappa = 8.0**2\n dists = (((xp - thisX)**2 + (yp - thisY)**2))\n weights = np.exp(-dists/kappa)\n if np.sum(weights)>0:\n xav = np.sum(weights*xdirs)/np.sum(weights)\n yav = np.sum(weights*ydirs)/np.sum(weights)\n posDF.ix[index,'env_heading'] = math.atan2(yav,xav)- thisTheta\n else:\n posDF.ix[index,'env_heading'] = 0.0\n \nallDF = allDF.append(posDF,ignore_index=True)\n\n \n\n\n\nallDF = allDF.reset_index(drop=True)\ndsize = len(allDF)\nmaxN=0\nfor index, row in allDF.iterrows():\n thisFrame = row['frame']\n thisID = row['c_id']\n thisClip = row['clip']\n window = allDF[(allDF.frame==thisFrame)&(allDF['clip']==thisClip)&(allDF['c_id']!=thisID)]\n if len(window)>maxN:\n maxN=len(window)#\n\nneighbours = np.zeros((dsize,maxN,5)).astype(np.float32) # dist, angle\n#pixels are rescaled to meters based on flying at a height of 100m - camera fov = 60\npx_to_m = 100*2.0*math.tan(math.radians(30))/1920.0\n\nfor index, row in allDF.iterrows():\n print(index,len(allDF))\n \n thisFrame = row['frame']\n thisID = row['c_id']\n thisClip = row['clip']\n thisX = row['x']\n thisY = row['y']\n thisAngle = row['heading']\n window = allDF[(allDF.frame==thisFrame)&(allDF['clip']==thisClip)&(allDF['c_id']!=thisID)]\n prevTime = allDF[(np.abs(allDF['frame']-(thisFrame-2*dt))<1e-6)&(allDF['clip']==thisClip)&(allDF['c_id']!=thisID)]\n ncount = 0\n\n for i2, w in window.iterrows():\n xj = w.x\n yj = w.y\n dx = xj - thisX\n dy = yj - thisY\n \n neighbours[index,ncount,0] = ((((dx)**2+(dy)**2))**0.5) #* px_to_m \n angle = math.atan2(dy,dx)\n angle = angle - thisAngle\n\n neighbours[index,ncount,1] = math.atan2(math.sin(angle), math.cos(angle))\n w_id = w['clip']*10000 + w['c_id']\n neighbours[index,ncount,2] = w_id\n jdx = w.dx\n jdy = w.dy\n#nAngle = w.heading\n nAngle = math.atan2(jdy,jdx) \n jPT = prevTime[prevTime.c_id==w['c_id']]\n if len(jPT)==1:\n jdx = jPT.dx\n jdy = jPT.dy\n nAngle = math.atan2(jdy,jdx) \n\n jAngle = nAngle - thisAngle\n#jAngle = w.heading - thisAngle\n neighbours[index,ncount,3] = jAngle\n jMoveLength = ((jdx**2)+(jdy**2))**0.5\n neighbours[index,ncount,4] = jMoveLength\n \n ncount+=1\n\n# convert to a numpy array\n#allData = allDF.values\n#keep non nan moves, of more than 1m and less than 10m\nkeepIndexes = (np.isfinite(allDF['move'].values))&(allDF['moveLength'].values>0.01)&(allDF['moveLength'].values<10)\n\nuid = allDF['clip'].values*10000 + allDF['c_id'].values \n\nnp.save('pdata/neighbours.npy', neighbours[keepIndexes])\nnp.save('pdata/uid.npy', uid[keepIndexes])\n\nmvector = allDF['move'].values\nmvector[mvector<-pi]=mvector[mvector<-pi]+2*pi\nmvector[mvector>pi]=mvector[mvector>pi]-2*pi\nnp.save('pdata/mvector.npy', mvector[keepIndexes])\n\n\n\nevector = allDF['env_heading'].values\nevector[evector<-pi]=evector[evector<-pi]+2*pi\nevector[evector>pi]=evector[evector>pi]-2*pi\nnp.save('pdata/evector.npy', evector[keepIndexes])\n \n\n\n","sub_path":"analysis/movement/simulations/external/preprocessData.py","file_name":"preprocessData.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"82328445","text":"import numpy\r\nimport re\r\n\r\ndef decode(word):\r\n\tnumbers = re.findall(r\"\\d+\", word)\r\n\tnumbers = [int(i) for i in numbers]\r\n\tx1, y1, x2, y2 = numbers\r\n\t\r\n\tif \"off\" in word:\r\n\t\tcmd = \"turn off\"\r\n\telif \"on\" in word:\r\n\t\tcmd = \"turn on\"\r\n\telse:\r\n\t\tcmd = \"toggle\"\r\n\t\t\r\n\treturn cmd, (x1, y1), (x2, y2)\r\n\r\ndef main():\r\n\twith open(\"input.txt\") as fp:\r\n\t\tdata = fp.readlines()\r\n\t\tdata = [i.strip() for i in data]\r\n\t\r\n\tgrid = numpy.zeros((1000, 1000))\r\n\t\r\n\tfor i, word in enumerate(data):\r\n\t\tcmd, (x1, y1), (x2, y2) = decode(word)\r\n\t\t\r\n\t\tif cmd == \"turn on\":\r\n\t\t\tgrid[x1:x2+1, y1:y2+1] = 1\r\n\t\telif cmd == \"turn off\":\r\n\t\t\tgrid[x1:x2+1, y1:y2+1] = 0\r\n\t\telif cmd == \"toggle\":\r\n\t\t\tgrid[x1:x2+1, y1:y2+1] = 1 - grid[x1:x2+1, y1:y2+1]\r\n\t\r\n\tnum = numpy.sum(grid)\r\n\tprint(\"{:.0f} lights on ({:.1f}%)\".format(num, num / (1000 * 1000) * 100))\r\n\t\r\n\tprint(\"\\nPart 2:\", end = \" \")\r\n\t\r\n\tgrid = numpy.zeros((1000, 1000))\r\n\tfor i, word in enumerate(data):\r\n\t\tcmd, (x1, y1), (x2, y2) = decode(word)\r\n\t\t\r\n\t\tif cmd == \"turn on\":\r\n\t\t\tgrid[x1:x2+1, y1:y2+1] += 1\r\n\t\telif cmd == \"turn off\":\r\n\t\t\tgrid[x1:x2+1, y1:y2+1] -= 1\r\n\t\t\tgrid[grid < 0] = 0\r\n\t\telif cmd == \"toggle\":\r\n\t\t\tgrid[x1:x2+1, y1:y2+1] += 2\r\n\t\r\n\tprint(int(numpy.sum(grid)), \"light points\")\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n","sub_path":"06/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"266820756","text":"import pytest\n\nimport ibis\nimport ibis.common.exceptions as com\nimport ibis.expr.operations as ops\nfrom ibis.backends.pandas.dispatch import execute_node as pandas_execute_node\nfrom ibis.expr.scope import Scope\n\ndd = pytest.importorskip(\"dask.dataframe\")\n\nfrom dask.dataframe.utils import tm # noqa: E402\n\nfrom ibis.backends.dask import Backend # noqa: E402\nfrom ibis.backends.dask.core import execute # noqa: E402\nfrom ibis.backends.dask.dispatch import ( # noqa: E402\n execute_node,\n post_execute,\n pre_execute,\n)\n\n\ndef test_from_dataframe(dataframe, ibis_table, core_client):\n t = ibis.dask.from_dataframe(dataframe)\n result = t.execute()\n expected = ibis_table.execute()\n tm.assert_frame_equal(result, expected)\n\n t = ibis.dask.from_dataframe(dataframe, name='foo')\n expected = ibis_table.execute()\n tm.assert_frame_equal(result, expected)\n\n client = core_client\n t = ibis.dask.from_dataframe(dataframe, name='foo', client=client)\n expected = ibis_table.execute()\n tm.assert_frame_equal(result, expected)\n\n\ndef test_pre_execute_basic():\n \"\"\"Test that pre_execute has intercepted execution and provided its own\n scope dict.\"\"\"\n\n @pre_execute.register(ops.Add)\n def pre_execute_test(op, *clients, scope=None, **kwargs):\n return Scope({op: 4}, None)\n\n one = ibis.literal(1)\n expr = one + one\n result = execute(expr.op())\n assert result == 4\n\n del pre_execute.funcs[(ops.Add,)]\n pre_execute.reorder()\n pre_execute._cache.clear()\n\n\ndef test_execute_parameter_only():\n param = ibis.param('int64')\n result = execute(param.op(), params={param.op(): 42})\n assert result == 42\n\n\ndef test_missing_data_sources():\n t = ibis.table([('a', 'string')])\n expr = t.a.length()\n with pytest.raises(com.UnboundExpressionError):\n execute(expr.op())\n\n\ndef test_missing_data_on_custom_client():\n class MyBackend(Backend):\n def table(self, name):\n return ops.DatabaseTable(\n name, ibis.schema([('a', 'int64')]), self\n ).to_expr()\n\n con = MyBackend()\n t = con.table('t')\n with pytest.raises(\n com.OperationNotDefinedError,\n match=\"Operation 'DatabaseTable' is not implemented for this backend\",\n ):\n con.execute(t)\n\n\ndef test_post_execute_called_on_joins(dataframe, core_client, ibis_table):\n count = [0]\n\n @post_execute.register(ops.InnerJoin, dd.DataFrame)\n def tmp_left_join_exe(op, lhs, **kwargs):\n count[0] += 1\n return lhs\n\n left = ibis_table\n right = left.view()\n join = left.join(right, 'plain_strings')[left.plain_int64]\n result = join.execute()\n assert result is not None\n assert len(result.index) > 0\n assert count[0] == 1\n\n\ndef test_scope_look_up():\n # test if scope could lookup items properly\n scope = Scope()\n one_day = ibis.interval(days=1).op()\n one_hour = ibis.interval(hours=1).op()\n scope = scope.merge_scope(Scope({one_day: 1}, None))\n assert scope.get_value(one_hour) is None\n assert scope.get_value(one_day) is not None\n\n\ndef test_new_dispatcher():\n types = (ops.TableColumn, dd.DataFrame)\n assert execute_node.dispatch(*types) is not None\n assert pandas_execute_node.dispatch(*types).__name__ == 'raise_unknown_op'\n","sub_path":"ibis/backends/dask/tests/test_core.py","file_name":"test_core.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"26122279","text":"from threading import Thread\n\nfrom utils.download import download\nfrom utils import get_logger\nfrom scraper import scraper\nimport time\nimport variables\n\nclass Worker(Thread):\n def __init__(self, worker_id, config, frontier):\n self.logger = get_logger(f\"Worker-{worker_id}\", \"Worker\")\n self.config = config\n self.frontier = frontier\n super().__init__(daemon=True)\n self.iteration_counter = 0\n \n def run(self):\n while True:\n tbd_url = self.frontier.get_tbd_url()\n if not tbd_url:\n self.logger.info(\"Frontier is empty. Stopping Crawler.\")\n # print(\"NUMBER OF LINKS FOUND: \", len(links))\n print()\n # print(\"NUMBER OF VALID EXTRACTED LINKS: \", len(next_links))\n print()\n print(\"EXTRACTED LINKS: \",len(variables._links))\n print()\n print(\"VISITED_URLS: \", variables._visited)\n print()\n print(\"NUMBER OF SUBDOMAINS FOUND: \", len(variables._subdomain_dict))\n print()\n print(\"SUBDOMAINS FOUND: \", variables._subdomain_dict.keys())\n print(\"________________________________________________\")\n #At this point, we could log the value of our variables to answer the four questions in the spec\n break\n resp = download(tbd_url, self.config, self.logger)\n self.logger.info(\n f\"Downloaded {tbd_url}, status <{resp.status}>, \"\n f\"using cache {self.config.cache_server}.\")\n scraped_urls = scraper(tbd_url, resp)\n for scraped_url in scraped_urls:\n self.frontier.add_url(scraped_url)\n self.frontier.mark_url_complete(tbd_url)\n time.sleep(self.config.time_delay)\n if self.iteration_counter % 500 == 0:\n print(\"============================================================================================================\")\n print(\"EXTRACTED LINKS: \",len(variables._links))\n print()\n print(\"VISITED_URLS: \", variables._visited)\n print()\n print(\"NUMBER OF SUBDOMAINS FOUND: \", len(variables._subdomain_dict))\n print()\n print(\"SUBDOMAINS FOUND: \", variables._subdomain_dict.keys())\n print(\"============================================================================================================\")\n self.iteration_counter += 1\n","sub_path":"crawler/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"158947115","text":"#Autor: María Fernanda García Gastélum A01376181\r\n#Calcular perímetro y área de 2 rectángulos y después comparar\r\n\r\n\r\n#importar tortuga\r\nimport turtle\r\n\r\n#función para calcular perímetro\r\ndef calcularPerimetro(base, altura):\r\n perimetro= (base*2) + (altura*2)\r\n return perimetro\r\n\r\n\r\n#función para calcular área\r\ndef calcularArea(base, altura):\r\n area= base*altura\r\n return area\r\n\r\n\r\n#calcular cuál es el rectángulo mayor\r\ndef calcularRectanguloMayor(area1, area2):\r\n if area1 > area2:\r\n return \"El primer rectángulo es mayor\"\r\n if area2 > area1:\r\n return \"El segundo rectángulo es mayor\"\r\n else:\r\n return \"Los rectángulos son iguales\"\r\n\r\n\r\n#definir el color de los rectángulo mayor y menor\r\ndef definirColor(area1, area2):\r\n if area1 > area2:\r\n return turtle.color(\"red\")\r\n else:\r\n turtle.color(\"green\")\r\n\r\n\r\n#EXTRA: dibujar rectángulo\r\ndef dibujarRectangulo(base, altura):\r\n turtle.forward(base)\r\n turtle.left(90)\r\n turtle.forward(altura)\r\n turtle.left(90)\r\n turtle.forward(base)\r\n turtle.left(90)\r\n turtle.forward(altura)\r\n turtle.left(90)\r\n\r\n\r\ndef main():\r\n base1= int(input(\"Escribe la base del primer rectángulo: \"))\r\n altura1= int(input(\"Escribe la altura del primer rectángulo: \"))\r\n base2= int(input(\"Escribe la base del segundo rectángulo: \"))\r\n altura2= int(input(\"Escribe la altura del segundo rectángulo: \"))\r\n perimetro1= calcularPerimetro(base1, altura1)\r\n area1= calcularArea(base1, altura1)\r\n perimetro2 = calcularPerimetro(base2, altura2)\r\n area2 = calcularArea(base2, altura2)\r\n rectanguloMayor= calcularRectanguloMayor(area1, area2)\r\n print(\"Perímetro del 1er rectángulo: \", perimetro1)\r\n print(\"Área del 1er rectángulo: \", area1)\r\n print(\"Perímetro del 2ndo rectángulo: \", perimetro2)\r\n print(\"Área del 2ndo rectángulo: \", area2)\r\n print(rectanguloMayor)\r\n definirColor(area1, area2)\r\n dibujarRectangulo(base1, altura1)\r\n turtle.penup()\r\n turtle.forward(base1 + 15)\r\n turtle.pendown()\r\n definirColor(area2, area1)\r\n dibujarRectangulo(base2, altura2)\r\n turtle.exitonclick()\r\n\r\n\r\nmain()","sub_path":"Rectangulos.py","file_name":"Rectangulos.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41527246","text":"\n\nfrom xai.brain.wordbase.verbs._quiver import _QUIVER\n\n#calss header\nclass _QUIVERED(_QUIVER, ):\n\tdef __init__(self,): \n\t\t_QUIVER.__init__(self)\n\t\tself.name = \"QUIVERED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"quiver\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_quivered.py","file_name":"_quivered.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"637953813","text":"# THIS SUBROUTINE DEFINES THE STOCHASTIC PROCESS FOR LABOR PRODUCTIVITY\npilab = np.zeros((ns,jr-1))\nstdlel = np.zeros((jr-1))\niden = np.zeros((ns,ns))\ntheta = np.zeros(3)\n\n# ENDOWMENT PROCESS PARAMETER\nrho = 0.9394318181818182\nsigmaeps = 1.8081632653061224\nsigma2alpha = 0.2973579382613107 - np.var(np.log(ephansen[0:jr]))\n\nif ns==1:\n eta = [1]\n pi = np.zeros((ns,ns))\n pi[0,0] = 1\n pini = [1]\n ep = np.empty((nty, J))\n for j in range(J):\n ep[0, j] = np.exp(-np.sqrt(sigma2alpha)) * ephansen[j]\n ep[1, j] = np.exp(np.sqrt(sigma2alpha)) * ephansen[j]\nelif ns==3:\n eta = np.array((0.1,0.8,0.1))\n pi = np.array((((0.1,0.8,0.1),(0.1,0.8,0.1),(0.1,0.8,0.1))))\n pini[0] = 0\n pini[1] = 1\n pini[2] = 0\n ep = np.empty((nty, J))\n for j in range(J):\n ep[0, j] = np.exp(-np.sqrt(sigma2alpha)) * ephansen[j]\n ep[1, j] = np.exp(np.sqrt(sigma2alpha)) * ephansen[j]\n eta = np.exp(eta)\n eta = eta/sum(eta/3)\nelse:\n pilab = np.zeros((ns, jr - 1))\n stdlel = np.zeros((jr - 1))\n iden = np.zeros((ns, ns))\n\n theta[0] = 0\n theta[1] = rho\n theta[2] = (sigmaeps * (1 - rho ** 2) ** (1 / 2)) ** 2\n\n bbb = q.approximation.tauchen(theta[1], theta[2], theta[0], 3.5172413793103448, ns)\n bbbb = solveStationary(bbb.P)\n bbbb = bbbb.ravel()\n ttt = bbb.state_values\n ttt = np.exp(ttt)\n\n eta = ttt / (sum(sum(bbbb.__array__() * ttt)))\n pistat = bbbb\n pi = bbb.P\n # DETERMINE THE INITIAL DISTRIBUTION OF LABOUR PRODUCTIVITY\n # FIXED EFFECTS: sigma^2_alpha = 0.247\n ep = np.empty((nty, J))\n for j in range(J):\n ep[0, j] = np.exp(-np.sqrt(sigma2alpha)) * ephansen[j]\n ep[1, j] = np.exp(np.sqrt(sigma2alpha)) * ephansen[j]\n pini[2] = 1\n # Do Markov Mixing with Identity Matrix to increase persistance\n iden[:, :] = 0\n for s in range(ns):\n iden[s, s] = 1\n stdle = sum(pistat.__array__() * (np.log(eta) - sum(pistat.__array__() * np.log(eta))) ** 2)\n stdleini = sum(pini * (np.log(eta) - sum(pini * np.log(eta))) ** 2)\n # Compute cross-sectional variance of labour productivity over time\n pilab[:, 0] = pini\n for t in range(1, jr - 1):\n for s in range(ns):\n pilab[s, t] = sum(pi[:, s] * pilab[:, t - 1])\n for t in range(jr - 1):\n stdlel[t] = sum(pilab[:, t] * (np.log(eta) - sum(pistat.__array__() * np.log(eta))) ** 2)\n permanent_component = sigma2alpha + np.var(np.log(ephansen[0:jr])) # it is the permanent component of the variance, given by the ability type and the age dependent component\n stdlel = stdlel + permanent_component","sub_path":"Experiment/LABOUR.py","file_name":"LABOUR.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"108320225","text":"#!/usr/bin/env python\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport gzip\nimport re\nimport random\n\nfrom logistic_high_di import HighDimensionalLogisticRegression\n\n\n\nclass DataReader(object):\n def __init__(self):\n \n self.articles_old = set()\n self.articles_new = set()\n self.line = None\n \n \n self.files_list = ['/Users/xbb/Desktop/bandit_experiment/r6b_18k.txt']\n \n \n self. T = 0\n self.fin = open(self.files_list[self.T],'r')\n\n def come(self):\n '''\n extra, delete, key are string\n '''\n extra = set()\n delete = set()\n click = 0\n \n self.line = self.fin.readline()\n \n if not self.line: \n self.T += 1\n self.fin = gzip.open(self.files_list[self.T], 'r')\n self.line = self.fin.readline()\n 'If self.T >= 13, we are running out of the data.'\n \n cha = self.line\n \n \n \n matches = re.search(r\"id-(\\d+)\\s(\\d).+user\\s([\\s\\d]+)(.+)\", cha)\n \n article = int(matches.group(1))\n click = int(matches.group(2))\n covariates = np.zeros(136).astype(int)\n \n covariates[[int(elem) - 1 for elem in matches.group(3).split(' ') if elem != '']] = 1\n key = ''.join(map(str, covariates))\n \n \n \n \n ####guest\n mab = False\n if sum(covariates) == 1:\n mab = True\n \n \n \n finder = re.findall(r'\\|id-(\\d+)', matches.group(4))\n \n self.articles_new = set([int(result) for result in finder])\n \n\n \n if self.articles_new != self.articles_old:\n extra = self.articles_new - self.articles_old\n delete = self.articles_old - self.articles_new\n \n self.articles_old = self.articles_new\n \n\n return {'covariates':covariates, 'article':article, 'click':click, 'extra':extra, 'delete':delete, 'mab':mab, 'key':key}\n\n\n\n\n\n\nclass Util(object):\n \n @staticmethod\n def zeros_and_ones(relevents, coefficients):\n '''relevents and coefficients are ndarray'''\n '''return ones and zeros' indexes'''\n coef_ = coefficients[0,relevents]\n ones = coef_ >= 0\n zeros = coef_ < 0\n return list(relevents[ones]), list(relevents[zeros])\n \n \n \nclass Graph(object): \n def __init__(self, articles_set, list_keys_set, collector):\n '''\n articles_set: a set of articles(numbers)\n list_keys_set: exhaustive sets\n articles_set: a set of numbers\n '''\n self.__articles = set()\n self.__articles.update(articles_set)\n \n self.__article_numbers = [{} for i in range(len(list_keys_set))]\n self.__article_clicks = [{} for i in range(len(list_keys_set))]\n \n \n self.__collector = collector\n \n self.__all_keys = set()\n self.__list_keys_set = [] #list of sets\n \n self.__numbers_keys_set = [0 for i in range(len(list_keys_set))]\n \n self.__clicks_keys_set = [0 for i in range(len(list_keys_set))]\n \n \n \n for index, keyset in enumerate(list_keys_set):\n self.__list_keys_set.append(keyset)\n print(index, len(articles_set), 'length of article sets', len(keyset), '126')\n self.__all_keys.update(keyset)\n \n X, y = self.__collector.get_article_covariates(articles_set, keyset)\n self.__numbers_keys_set[index] += len(y)\n self.__clicks_keys_set[index] += sum(y)\n \n \n \n '''initializeing article-specific clicks'''\n for article in self.__articles: \n for index, keyset in enumerate(list_keys_set):\n X, y = self.__collector.get_article_covariates(article, keyset)\n self.__article_numbers[index].update({article:len(y)})\n self.__article_clicks[index].update({article:sum(y)})\n\n print(self.__article_numbers, '145')\n print(self.__article_clicks, '146')\n \n '''Updating for newly coming key'''\n def update(self, article, key, click):\n \n if article in self.__articles:\n if key in self.__all_keys:\n for index, keyset in enumerate(self.__list_keys_set):\n if key in keyset:\n self.__numbers_keys_set[index] += 1\n self.__clicks_keys_set[index] += click\n \n self.__article_numbers[index][article] += 1\n self.__article_clicks[index][article] += click\n \n else:#Adding key to the first set\n index = 0\n self.__all_keys.add(key)\n self.__list_keys_set[index].add(key)\n \n self.__numbers_keys_set[index] += 1\n self.__clicks_keys_set[index] += click\n \n self.__article_numbers[index][article] += 1\n self.__article_clicks[index][article] += click\n \n \n def get_data(self, key):\n '''return playing times and clicks for this articles set'''\n '''\n key: string\n '''\n \n for index, keyset in enumerate(self.__list_keys_set):\n if key in keyset:\n index_ = index \n return self.__numbers_keys_set[index_], self.__clicks_keys_set[index_]\n \n \n\n @property\n def all_keys(self):\n return self.__all_keys\n @property\n def get_articles(self):\n return self.__articles\n @property\n def get_list_keys_sets(self):\n return self.__list_keys_set\n \n def get_detailed_data(self, key):\n '''return detailed numbers and clicks data''' \n for index, keyset in enumerate(self.__list_keys_set):\n if key in keyset: \n return self.__article_numbers[index], self.__article_clicks[index]\n \n \n \n \n def update_articles(self, articles_collector, first_graph, delete_articles=None, extra_articles=None): \n \n if first_graph:\n \n self.__articles.update(extra_articles)\n \n for article in extra_articles:\n len_ = len(self.__article_numbers)\n \n for index in range(len_):\n #set_ is a dictionary of articles and numbers.\n self.__article_numbers[index][article] = 0\n self.__article_clicks[index][article] = 0\n \n for article in delete_articles:\n if article in self.__articles:\n len_ = len(self.__article_numbers)\n \n \n for index in range(len_): \n #if article in self.__article_numbers[index].keys():\n number = self.__article_numbers[index][article]\n \n del self.__article_numbers[index][article]\n click = self.__article_clicks[index][article]\n del self.__article_clicks[index][article]\n \n \n \n self.__numbers_keys_set[index] -= number \n self.__clicks_keys_set[index] -= click\n \n \n self.__articles.remove(article)\n \n #destroy this graph\n if not self.__articles:\n print('destroyed graph 223!!!!')\n return True\n \n \n \n return False\n \n \n @property\n def test(self):\n return self.__article_numbers\n \n\n \n \nclass model_UCB1(object):\n def __init__(self, collector, articles_collector, list_graphs):\n '''list_graphs: list of graph objects'''\n \n self.__articles_collector = articles_collector\n self.__collector = collector\n self.__list_graphs = list_graphs\n \n \n self.last_action = -1\n \n \n self.alpha = 0.5\n \n self.first_round = -1\n \n \n self.counter = 0\n def update_graphs(self, list_graphs):\n self.__list_graphs = list_graphs\n \n def update(self, key, article, click):\n self.counter += 1\n \n '''\n Newly coming article comes into the first graph.\n Newly coming key comes into the first key set of the corresponding article graph.\n '''\n for graph in self.__list_graphs:\n if article in graph.get_articles:\n graph.update(article, key, click)\n \n \n \n def recommend(self, key):\n\t\t\t\t\t\t\t\t#Because not all graphs contain identical key subsets.\n\t\t\t\t\t\t\t\t#IF there's any graph being without such key, use overall MAB.\n\t\t\t\t\t\t\t\twhole_key = self.__collector.all_keys\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tfor graph in self.__list_graphs:\n\t\t\t\t\t\t\t\t\t\t\t\twhole_key = whole_key & graph.all_keys\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t#If the it's a new key\n\t\t\t\t\t\t\t\tif not key in whole_key:\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tnumbers_object = self.__collector.article_numbers\n\t\t\t\t\t\t\t\t\t\t\t\tclicks_object = self.__collector.article_clicks \n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tarticles = set()\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tarticles.update(numbers_object.keys())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tnumbers = [0 for i in range(len(articles))]\n\t\t\t\t\t\t\t\t\t\t\t\tclicks = [0 for i in range(len(articles))]\n\t\t\t\t\t\t\t\t\t\t\t\tarticles_ = []\n\t\t\t\t\t\t\t\t\t\t\t\tfor index, article in enumerate(articles):\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumbers[index] = numbers_object[article]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclicks[index] = clicks_object[article]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tarticles_.append(article)\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tmax_index = model_UCB1.max_finder(numbers, clicks, self.counter)\n\t\t\t\t\t\t\t\t\t\t\t\tself.last_action = articles_[max_index]\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.last_action\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t#first round\n\t\t\t\t\t\t\t\tnumbers = [0 for i in range(len(self.__list_graphs))]\n\t\t\t\t\t\t\t\tclicks = [0 for i in range(len(self.__list_graphs))]\n\t\t\t\t\t\t\t\tfor index, graph in enumerate(self.__list_graphs):\n\t\t\t\t\t\t\t\t\t\t\t\tnumbers[index], clicks[index] = graph.get_data(key)\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tmax_index = model_UCB1.max_finder_cluster(numbers, clicks, self.counter)\n\t\t\t\t\t\t\t\tself.first_round = max_index #TESTING\n\t\t\t\t\t\t\t\t#second round\n\t\t\t\t\t\t\t\tnumbers_object, clicks_object = self.__list_graphs[max_index].get_detailed_data(key)\n\t\t\t\t\t\t\t\tarticles = set()\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tarticles.update(numbers_object.keys())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tnumbers = [0 for i in range(len(articles))]\n\t\t\t\t\t\t\t\tclicks = [0 for i in range(len(articles))]\n\t\t\t\t\t\t\t\tarticles_ = []\n\t\t\t\t\t\t\t\tfor index, article in enumerate(articles):\n\t\t\t\t\t\t\t\t\t\t\t\tnumbers[index] = numbers_object[article]\n\t\t\t\t\t\t\t\t\t\t\t\tclicks[index] = clicks_object[article]\n\t\t\t\t\t\t\t\t\t\t\t\tarticles_.append(article)\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tmax_index = model_UCB1.max_finder_within(numbers, clicks, self.counter)\n\t\t\t\t\t\t\t\tself.last_action = articles_[max_index]\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\treturn self.last_action\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n @staticmethod\n def max_finder(numbers, clicks, total = None):\n\t\t\t\t\t\t\t\t'''\n\t\t\t\t\t\t\t\tnumbers: list\n\t\t\t\t\t\t\t\tclicks: list\n\t\t\t\t\t\t\t\t'''\n\t\t\t\t\t\t\t\tnumbers = np.array(numbers)\n\t\t\t\t\t\t\t\tsum_ = np.sum(numbers)\n\t\t\t\t\t\t\t\tclicks = np.array(clicks)\n\t\t\t\t\t\t\t\t###ALPHA!!\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tarray_ = clicks / (numbers + 1) + 0.055 * np.sqrt(np.log(sum_+1)/(numbers+1))\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\treturn np.random.choice(np.where(array_ == array_.max())[0])\n\t\t\t\t\t\t\t\t\n\n @staticmethod\n def max_finder_cluster(numbers, clicks, total = None):\n '''\n numbers: list\n clicks: list\n '''\n numbers = np.array(numbers)\n sum_ = np.sum(numbers)\n clicks = np.array(clicks)\n ###ALPHA!!\n array_ = clicks / (numbers + 1) + 0.055 * np.sqrt(np.log(sum_+1)/(numbers+1))\n\t\t\t\t\t\t\t\t#arg_ = np.argmax(array_)\n\t\t\t\t\t\t\t\t\n return np.random.choice(np.where(array_ == array_.max())[0])\n \n \n \n \n \n @staticmethod\n def max_finder_within(numbers, clicks, total = None):\n '''\n numbers: list\n clicks: list\n '''\n numbers = np.array(numbers)\n sum_ = np.sum(numbers)\n clicks = np.array(clicks)\n ###ALPHA!!\n \n array_ = clicks / (numbers + 1) + 0.055 * np.sqrt(np.log(sum_+1)/(numbers+1))\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n return np.random.choice(np.where(array_ == array_.max())[0])\n \n \n \n \n \n \n #Updating the article, not the keys\n def update_articles(self, articles_collector):\n destroying = [False]\n \n extra_articles = articles_collector.active_articles\n for graph in self.__list_graphs:\n extra_articles = extra_articles - graph.get_articles\n \n delete_articles = set()\n mid_ = set()\n for graph in self.__list_graphs:\n mid_ = mid_ | graph.get_articles\n \n delete_articles = mid_ - articles_collector.active_articles\n \n \n \n \n \n for index in range(len(self.__list_graphs)): \n if index == 0:\n \n \n self.__list_graphs[index].update_articles(articles_collector, True, delete_articles, extra_articles)\n else:\n destroying.append(self.__list_graphs[index].update_articles(articles_collector, False, delete_articles))\n \n list_mid_graphs = []\n for index, bool_ in enumerate(destroying):\n if not bool_:\n list_mid_graphs.append(self.__list_graphs[index])\n \n #Remove those article empty graph \n self.__list_graphs = list_mid_graphs\n \n \n \n @property\n def get_graphs(self):\n return self.__list_graphs\n \n \n \n \n \n \nclass Collector(object):\n \n def __init__(self):\n self.__overall_key_covariates = {}\n self.__overall_key_numbers = {}\n self.__overall_key_clicks = {}\n self.__article_key_covariates = {}\n self.__article_key_numbers = {}#{article:{key:numbers, }, }\n self.__article_key_clicks = {}\n \n self.__article_numbers = {}#{article: numbers, }\n self.__article_clicks = {}#{article: clicks, }\n \n self.__all_active_keys = set()\n self.__all_active_articles = set()\n \n self.__nonzero_sets = {}\n for index in range(136):\n self.__nonzero_sets[index] = set()\n \n self.__zero_sets = {}\n for index in range(136):\n self.__zero_sets[index] = set()\n \n \n \n \n \n def __update_nonzero_sets(self, covariates, key):\n for index, elem in enumerate(covariates):\n if elem != 0: \n self.__nonzero_sets[index].add(key)\n \n \n def __update_zero_sets(self, covariates, key):\n for index, elem in enumerate(covariates):\n if elem != 1: \n self.__zero_sets[index].add(key)\n \n \n \n '''get any nonzero sets'''\n def get_any_nonzero_sets(self, index):\n '''index is a list'''\n result = set()\n \n for i in index:\n if i != 0:\n result = result | self.__nonzero_sets[i]\n \n return result\n \n def get_any_zero_sets(self, index):\n '''index is a list'''\n result = self.__all_active_keys\n \n for i in index:\n if i != 0:\n result = result & self.__nonzero_sets[i]\n \n result = self.__all_active_keys - result\n \n return result\n \n \n \n def get_sets(self, ones, zeros, keyset):\n \n if len(ones) + len(zeros) == 1:\n return set()\n \n return self.get_nonzero_sets(ones) & self.get_zero_sets(zeros) & keyset\n \n def get_nonzero_sets(self, index):\n '''index is a list'''\n result = self.__all_active_keys\n \n for i in index:\n if i != 0:\n result = result & self.__nonzero_sets[i] \n return result\n \n def get_zero_sets(self, index):\n '''index is a list'''\n result = self.__all_active_keys\n \n for i in index:\n if i != 0:\n result = result & self.__zero_sets[i] \n return result\n \n \n def update_key(self, key, covariates, article, click):\n \n self.__article_numbers[article] += 1\n self.__article_clicks[article] += click\n \n \n self.__all_active_keys.add(key)\n self.__update_nonzero_sets(covariates, key)\n self.__update_zero_sets(covariates, key)\n self.__all_active_articles.add(article)\n \n \n self.__add_overall_key_covariates(key, covariates)\n self.__add_overall_key_numbers(key)\n self.__add_overall_key_clicks(key, click)\n self.__add_article_key_covariates(article, key, covariates)\n self.__add_article_key_numbers(article, key)\n self.__add_article_key_clicks(article, key, click)\n \n \n \n \n def update_articles(self, articles_collector):\n '''Some minor changes have been ignored'''\n \n deletes = self.__all_active_articles - articles_collector.active_articles\n for article in deletes:\n \n del self.__article_key_covariates[article]\n numbers = self.__article_key_numbers[article]\n del self.__article_key_numbers[article]\n clicks = self.__article_key_clicks[article]\n del self.__article_key_clicks[article]\n \n \n del self.__article_numbers[article]\n del self.__article_clicks[article]\n \n self.__all_active_articles.remove(article)\n \n for key in numbers.keys():\n self.__overall_key_numbers[key] -= numbers[key]\n self.__overall_key_clicks[key] -= clicks[key]\n \n extras = articles_collector.active_articles - self.__all_active_articles\n for article in extras: \n self.__article_key_covariates[article] = {}\n self.__article_key_numbers[article] = {}\n self.__article_key_clicks[article] = {}\n \n self.__article_numbers[article] = 0\n self.__article_clicks[article] = 0\n \n \n \n self.__all_active_articles.add(article)\n \n \n def __add_overall_key_covariates(self, key, covariates):\n 'covariates is a list of numbers'\n self.__overall_key_covariates.update({key:covariates})\n \n \n def __add_overall_key_numbers(self, key):\n if not key in self.__overall_key_numbers.keys(): \n self.__overall_key_numbers.update({key:1})\n else:\n self.__overall_key_numbers[key] += 1\n \n def __add_overall_key_clicks(self, key, click):\n if not key in self.__overall_key_clicks.keys(): \n self.__overall_key_clicks.update({key:click})\n else:\n self.__overall_key_clicks[key] += click\n \n \n \n def __add_article_key_covariates(self, article, key, covariates):\n 'covariates is a list of numbers'\n if not article in self.__article_key_covariates.keys(): \n self.__article_key_covariates[article] = {}\n self.__article_key_covariates[article].update({key:covariates})\n else:\n self.__article_key_covariates[article].update({key:covariates})\n \n def __add_article_key_numbers(self, article, key):\n if not article in self.__article_key_numbers.keys():\n self.__article_key_numbers[article] = {}\n self.__article_key_numbers[article].update({key:1})\n else:\n if not key in self.__article_key_numbers[article].keys():\n self.__article_key_numbers[article].update({key:1})\n else:\n self.__article_key_numbers[article][key] += 1\n \n \n \n def __add_article_key_clicks(self, article, key, click):\n if not article in self.__article_key_clicks.keys():\n self.__article_key_clicks[article] = {}\n self.__article_key_clicks[article].update({key:click})\n else:\n if not key in self.__article_key_clicks[article].keys():\n self.__article_key_clicks[article].update({key:click})\n else:\n self.__article_key_clicks[article][key] += click\n \n def get_article_covariates(self, articles, key_subsets):\n design_ = []\n y_ = []\n \n if not isinstance(articles, int):\n for article in articles:\n \n key_subset = self.__article_key_numbers[article].keys() & key_subsets\n \n len_ = len(key_subset)\n key_subset = iter(key_subset)\n \n for i in range(len_):\n key = next(key_subset)\n \n row_ = self.__article_key_numbers[article][key]\n click_ = self.__article_key_clicks[article][key]\n \n design_.extend([self.__article_key_covariates[article][key],]*row_)\n y_.extend([1]*click_)\n y_.extend([0]*(row_ - click_))\n else:\n article = articles#int\n key_subsets = self.__article_key_numbers[article].keys() & key_subsets\n \n len_ = len(key_subsets)\n key_subsets = iter(key_subsets)\n \n for i in range(len_):\n key = next(key_subsets)\n \n row_ = self.__article_key_numbers[article][key]\n click_ = self.__article_key_clicks[article][key] \n \n design_.extend([self.__article_key_covariates[article][key],]*row_)\n y_.extend([1]*click_)\n y_.extend([0]*(row_ - click_))\n \n return np.array(design_), np.array(y_)\n \n \n \n def get_covariates(self, key_subsets):\n design_ = []\n y_ = []\n \n len_ = len(key_subsets)\n key_subsets = iter(key_subsets)\n \n for i in range(len_):\n key = next(key_subsets)\n \n row_ = self.__overall_key_numbers[key]\n click_ = self.__overall_key_clicks[key] \n \n design_.extend([self.__overall_key_covariates[key],]*row_)\n y_.extend([1]*click_)\n y_.extend([0]*(row_ - click_))\n \n \n return np.array(design_), np.array(y_)\n \n \n \n \n \n '''Refresh the newly coming keys (in all graphs)'''\n def model_selection_graphs(self, list_graphs):\n \n final_graphs_list = []\n \n Logistic = HighDimensionalLogisticRegression(fit_intercept=False)\n \n keys_set = self.all_keys\n \n X, y = self.get_article_covariates(self.all_articles, keys_set)\n \n \n Logistic.fit(X, y)\n '''Combo!'''\n ones, zeros = Util.zeros_and_ones(Logistic.model_, Logistic.coef_)\n second_key_set = self.get_sets(ones, zeros, keys_set) #keys set\n \n \n \n articles = set()\n if len(keys_set) != len(second_key_set) and len(second_key_set) != 0: \n \n \n for article in self.all_articles:\n \n X, y = self.get_article_covariates(article, second_key_set)\n \n if len(y) > 5:\n Logistic.fit(X, y)\n \n if len(Logistic.model_) > 1:\n articles.add(article)\n \n \n \n graphs = []\n if len(articles) > 0:\n for article in articles:\n article_ = set([article])\n X, y = self.get_article_covariates(article_, keys_set)\n \n Logistic.fit(X, y)\n \n \n \n '''Combo!'''\n ones, zeros = Util.zeros_and_ones(Logistic.model_, Logistic.coef_)\n second_key_set = self.get_sets(ones, zeros, keys_set) #keys set\n \n \n \n \n if len(keys_set) != len(second_key_set) and len(second_key_set) != 0:\n list_key_sets = [keys_set - second_key_set, second_key_set]\n else: \n list_key_sets = [keys_set]\n \n \n list_key_sets_2 = []\n \n for elem in list_key_sets:\n if len(elem) > 0:\n list_key_sets_2.append(elem)\n \n graph2 = Graph(article_, list_key_sets_2, self)#collector\n graphs.append(graph2)\n \n \n X, y = self.get_article_covariates(self.all_articles - articles, keys_set)\n \n Logistic.fit(X, y)\n '''Combo!'''\n ones, zeros = Util.zeros_and_ones(Logistic.model_, Logistic.coef_)\n second_key_set = self.get_sets(ones, zeros, keys_set) #keys set\n \n \n if len(keys_set) != len(second_key_set) and len(second_key_set) != 0:\n list_key_sets = [keys_set - second_key_set, second_key_set]\n else: \n list_key_sets = [keys_set]\n \n \n list_key_sets_2 = []\n \n for elem in list_key_sets:\n if len(elem) > 0:\n list_key_sets_2.append(elem)\n \n graph2 = Graph(self.all_articles - articles, list_key_sets_2, self)#collector\n final_graphs_list.append(graph2)\n final_graphs_list.extend(graphs)\n \n return final_graphs_list\n \n \n \n\n #####\n def graph_refresher(self):\n '''return list of one graph'''\n \n \n graph = Graph(self.all_articles, [self.__all_active_keys], self)#collector\n \n \n return [graph]\n \n \n \n \n \n @property\n def overall_key_covariates(self):\n return self.__overall_key_covariates\n @property \n def overall_key_numbers(self):\n return self.__overall_key_numbers\n @property\n def overall_key_clicks(self):\n return self.__overall_key_clicks\n @property\n def article_key_covariates(self):\n return self.__article_key_covariates\n @property\n def article_key_numbers(self):\n return self.__article_key_numbers\n @property\n def article_key_clicks(self):\n return self.__article_key_clicks\n @property\n def all_articles(self):\n return self.__all_active_articles\n @property\n def all_keys(self):\n return self.__all_active_keys\n @property\n def article_numbers(self):\n return self.__article_numbers\n @property\n def article_clicks(self):\n return self.__article_clicks\n \n \n \n \n\n\nclass ArticlesCollector(object):\n '''\n This object will be assigned to Groups and MAB object\n \n '''\n def __init__(self):\n self.__active_articles = set()\n self.__extras = set()\n self.__deletes = set()\n \n def update(self, extra, delete): \n self.__active_articles = self.__active_articles - delete\n self.__active_articles = self.__active_articles.union(extra)\n self.__extras = extra\n self.__deletes = delete\n \n @property\n def active_articles(self):\n return self.__active_articles\n \n @property\n def extras(self):\n return self.__extras\n \n @property\n def deletes(self):\n return self.__deletes\n \n def reset(self):\n self.__deletes = set()\n self.__extras = set()\n \n \n \n \nclass Agent_model_UCB1(object):\n '''\n Takes Groups object and MAB object as parameters\n '''\n def __init__(self, articles_collector, collector):\n '''\n articles_collector as the input parameter\n '''\n self.acc_reward = 0\n \n \n self.collector = collector\n '''mab object is used for guests'''#list_keys_set\n self.model_UCB1_object = model_UCB1(collector, articles_collector, [Graph(collector.all_articles, [collector.all_keys], collector)])\n \n \n self.extra_bonus = 0.0\n self.articles_collector = articles_collector\n \n \n self.last_action = '' # a string\n \n self.first_time = True\n self.counter = 0\n self.counter_usual = 0\n \n def update(self, reward, stuff):\n '''\n key is a string\n mab is a bool\n stuff, {'covariates':covariates, 'article':article, 'click':click, 'extra':extra, 'delete':delete, 'mab':mab, 'key':None}\n '''\n key = stuff['key']\n \n covariates = stuff['covariates']\n\n \n \n article = self.last_action\n \n if not self.first_time:\n self.model_UCB1_object.update(key, article, reward) #self.last_action is an article number\n self.collector.update_key(key, covariates, article, reward)\n \n #Updating model\n self.counter += 1\n self.counter_usual += 1\n if self.counter >= 500:\n if self.first_time:\n list_graphs = self.collector.graph_refresher()\n self.model_UCB1_object.update_graphs(list_graphs)\n self.first_time = False\n \n if self.counter_usual >= 3000:\n\n list_graphs = self.collector.model_selection_graphs(self.model_UCB1_object.get_graphs)\n self.model_UCB1_object.update_graphs(list_graphs)\n self.counter_usual = 0\n\n def recommend(self, stuff):\n '''\n receiving a key and decide self.last_acion and self.extra_bonus\n \n key is a string\n \n stuff, {'covariates':covariates, 'article':article, 'click':click, 'extra':extra, 'delete':delete, 'mab':mab, 'key':None}\n '''\n \n key = stuff['key']\n \n covariates = stuff['covariates']\n \n \n self.collector.update_articles(self.articles_collector)\n \n #Block the first 500 round for program satability\n if self.counter >= 500: \n self.model_UCB1_object.update_articles(self.articles_collector)#add the newly coming article to the first graph\n \n \n \n self.last_action = self.model_UCB1_object.recommend(key) #self.last_action is a number \n \n \n \n return self.last_action\n \n\n def update_arms(self, stuff):\n self.articles_collector.update(stuff['extra'], stuff['delete'])\n \n \n \n\nclass Environment(object):\n \n def run(self, agents, data_reader, timestamp = 70000):\n self.reward_curves = np.zeros((timestamp, len(agents)))\n self.timer = np.zeros(len(agents)).astype(int)\n self.agents = agents\n times = 0\n while np.min(self.timer) < timestamp:\n #Also in this step, arms will be refreshed\n stuff = data_reader.come()\n \n \n times += 1\n for i, agent in enumerate(agents):# agents can be [...]\n \n if int(np.sqrt(times)) == np.sqrt(times):\n print(np.sqrt(times), times, self.timer, agent.acc_reward, '714')\n \n if self.timer[i] < timestamp:\n \n agent.update_arms(stuff)\n \n agent.last_action = agent.recommend(stuff)\n \n if agent.last_action == stuff['article']:\n reward = stuff['click']\n agent.update(reward, stuff)\n agent.acc_reward += reward\n self.reward_curves[self.timer[i], i] = agent.acc_reward / (self.timer[i] + 1)\n \n self.timer[i] += 1\n \n print('final', times, self.timer)\n \n def plot(self, number_of_agents):\n if number_of_agents == 1:\n label_list = ['Logistic']\n elif number_of_agents == 2:\n label_list = ['Logistic', 'ucb1']\n \n collect = {}\n for j in range(len(self.reward_curves[0,:])):\n \n collect[j], = plt.plot(self.reward_curves[:,j], label=label_list[j])\n mid_ = \"/Users/apple/Desktop/bandit_experiment/bandit_modified\" + str(j)\n #np.save(mid_, self.reward_curves[:,j])\n \n if number_of_agents == 1:\n plt.legend(handles=[collect[0]])\n \n elif number_of_agents == 2:\n plt.legend(handles=[collect[0], collect[1]])\n else:\n plt.legend(handles=[collect[0], collect[1], collect[2]])\n \n x1,x2,y1,y2 = plt.axis()\n plt.axis((x1,x2,0,0.1))\n plt.show()\n\n\n\n\n###########\n####MAB####\n\nclass MAB(object):\n '''\n ArticlesCollector object will be assigned to this MAB object\n '''\n def __init__(self, articles_collector):\n self.articles_collector = articles_collector\n \n self.clicks = {}\n self.counts = {}\n \n \n self.alpha = 0.2\n \n \n def recommend(self):\n '''updating all article indexes'''\n \n \n \n values = np.array([])\n articles = []\n for article in self.counts.keys():\n sum_ = sum(self.clicks.values())\n values = np.append(values, self.clicks[article] / self.counts[article] + self.alpha * np.sqrt(np.log(sum_)/(self.counts[article]+1)))\n articles.append(article)\n \n \n \n return articles[np.argmax(values)]\n\n def update(self, reward, article):\n '''\n article is a numbe\n '''\n \n \n self.counts[article] += 1\n self.clicks[article] += reward\n \n \n '''While the node hasnt made its own decision, it still require arms updating'''\n def articles_update(self, articles_collector):\n '''updating all article indexes'''\n \n current_articles_set = self.counts.keys()#set of articles(string)\n extra_articles = articles_collector.active_articles - current_articles_set\n delete_articles = current_articles_set - articles_collector.active_articles\n \n\n for article in extra_articles: \n self.counts[article] = 1\n self.clicks[article] = 0\n for article in delete_articles:\n del self.counts[article]\n del self.clicks[article]\n\n \n\n\nclass Agent(object):\n '''\n Takes Groups object and MAB object as parameters\n '''\n def __init__(self, mab_object, articles_collector):\n \n '''\n articles_collector is the same one in the groups_object\n '''\n \n self.acc_reward = 0\n \n \n '''mab object is used for guests'''\n self.mab_object = mab_object\n \n \n self.articles_collector = articles_collector\n \n \n self.last_action = '' # a string\n \n \n \n def update(self, reward, stuff):\n \n '''\n key is a string\n stuff, {'covariates':covariates, 'article':article, 'click':click, 'extra':extra, 'delete':delete, 'mab':mab, 'key':None}\n '''\n \n key = stuff['key'] \n covariates = stuff['covariates']\n \n \n \n '''MAB can share the information'''\n self.mab_object.update(reward, self.last_action) #self.last_action is an article string\n \n \n \n \n def recommend(self, stuff):\n '''\n receiving a key and decide self.last_acion and self.extra_bonus\n \n key is a string\n stuff, {'covariates':covariates, 'article':article, 'click':click, 'extra':extra, 'delete':delete, 'mab':mab, 'key':None}\n '''\n \n key = stuff['key']\n covariates = stuff['covariates']\n \n self.mab_object.articles_update(self.articles_collector)\n \n self.last_action = self.mab_object.recommend() \n \n \n return self.last_action\n \n \n\n def update_arms(self, stuff):\n self.articles_collector.update(stuff['extra'], stuff['delete'])\n \n \n\n\n\n\n\n\n\n \ndef main():\n DR = DataReader()\n C = Collector()\n A = ArticlesCollector()\n E = Environment()\n AG = Agent_model_UCB1(A, C)\n \n \n \n ##MAB\n M = MAB(A)\n Ag = Agent(M, A)\n \n \n E.run([AG], DR)\n E.plot(len([AG]))\nif __name__ == '__main__':\n main()","sub_path":"bandit_experiment/logistic_bandit.py","file_name":"logistic_bandit.py","file_ext":"py","file_size_in_byte":37270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"313903735","text":"import pandas as pd\nfrom .log.core import logger\nfrom .db import engine\n\n\ndef m_per_point(player):\n \"\"\"Calculates the effective price (in millions) per point one would\n pay for the player\n\n AVG Points are max'ed with 0.01 to avoid division by zero\n\n \"\"\"\n price = max(player[\"playerMaster\"][\"marketValue\"], player[\"salePrice\"])\n avg_points = player[\"playerMaster\"][\"averagePoints\"]\n return (price / max(avg_points, 0.01)) / 1000000\n\n\ndef m_per_point_2(player):\n \"\"\"Lite version of the same function. Accounts for API endpoints\n discrepancies\n\n \"\"\"\n price = int(player[\"marketValue\"])\n avg_points = player[\"averagePoints\"]\n return (price / max(avg_points, 0.01)) / 1000000\n\n\ndef change(player):\n \"\"\"Performance change from last season to this season\n\n \"\"\"\n this_season_forecast = player[\"playerMaster\"][\"averagePoints\"] * 38\n last_season_points = max(player[\"playerMaster\"][\"lastSeasonPoints\"], 0.001) if \"lastSeasonPoints\" in player[\"playerMaster\"] else None\n return ((this_season_forecast / last_season_points) - 1) * 100 if last_season_points is not None else 0\n\n\ndef change_2(player):\n \"\"\"Performance change from last season to this season\n\n \"\"\"\n this_season_forecast = player[\"averagePoints\"] * 38\n last_season_points = max(int(player[\"lastSeasonPoints\"]), 0.001) if \"lastSeasonPoints\" in player else None\n return ((this_season_forecast / last_season_points) - 1) * 100 if last_season_points is not None else 0\n\n\ndef clean(player):\n \"\"\"JSON filtering and basic transformations\n\n \"\"\"\n new_player = {\n \"id\": int(player[\"playerMaster\"][\"id\"]),\n \"name\": player[\"playerMaster\"][\"nickname\"],\n \"status\": player[\"playerMaster\"][\"playerStatus\"],\n \"team\": player[\"playerMaster\"][\"team\"][\"name\"],\n \"market_value\": player[\"playerMaster\"][\"marketValue\"],\n \"sale_price\": player[\"salePrice\"],\n \"price\": max(player[\"playerMaster\"][\"marketValue\"], player[\"salePrice\"]),\n \"points\": player[\"playerMaster\"][\"points\"],\n \"last_season_points\": player[\"playerMaster\"][\"lastSeasonPoints\"] if \"lastSeasonPoints\" in player[\"playerMaster\"] else None,\n \"avg_points\": player[\"playerMaster\"][\"averagePoints\"],\n \"potential\": player[\"playerMaster\"][\"averagePoints\"] * 38,\n \"m_per_point\": m_per_point(player),\n \"change\": change(player)\n }\n return new_player\n\n\ndef clean_2(player):\n \"\"\"JSON filtering and fewer transformations. Used on a different\n endpoint that does serialisation differently\n\n \"\"\"\n new_player = {\n \"id\": int(player[\"id\"]),\n \"name\": player[\"nickname\"],\n \"position\": int(player[\"positionId\"]),\n \"status\": player[\"playerStatus\"],\n \"team\": player[\"team\"][\"name\"],\n \"market_value\": int(player[\"marketValue\"]),\n \"points\": player[\"points\"],\n \"last_season_points\": int(player[\"lastSeasonPoints\"]) if \"lastSeasonPoints\" in player else None,\n \"avg_points\": player[\"averagePoints\"],\n \"potential\": player[\"averagePoints\"] * 38,\n \"m_per_point\": m_per_point_2(player),\n \"change\": change_2(player)\n }\n return new_player\n\n\ndef clean_3(manager_id, player):\n \"\"\"Same kind of transform, for the 'team' (manager) endpoint\n\n \"\"\"\n new_player = {\n \"id\": int(player[\"playerMaster\"][\"id\"]),\n \"manager_id\": int(manager_id),\n \"clause\": int(player[\"buyoutClause\"]),\n \"clause_lock_end\": pd.to_datetime(player[\"buyoutClauseLockedEndTime\"], utc=True)\n }\n return new_player\n\n\ndef clean_4(team):\n \"\"\"Same kind of transform, for the 'ranking' endpoint\n\n \"\"\"\n new_team = {\n \"id\": int(team[\"team\"][\"id\"]),\n \"position\": int(team[\"position\"]),\n \"points\": int(team[\"points\"]),\n \"name\": team[\"team\"][\"manager\"][\"managerName\"],\n \"value\": int(team[\"team\"][\"teamValue\"]),\n \"team_points\": int(team[\"team\"][\"teamPoints\"]),\n \"ts\": pd.to_datetime(\"today\")\n }\n return new_team\n\n\ndef write_db(df, table_name):\n \"\"\"Writes dataframe df to table table_name using the imported\n SQLAlchemy engine.\n\n \"\"\"\n logger.info(f\"Rebuilding and loading {table_name}...\")\n df.to_sql(table_name, con=engine, if_exists='replace', method='multi')\n logger.info(\"done\")\n\n\ndef insert_db(df, table_name):\n \"\"\"Same as write_db, only inserting instead of truncating and\n reloading.\n\n \"\"\"\n logger.info(f\"Appending to {table_name}...\")\n df.to_sql(table_name, con=engine, if_exists='append', method='multi')\n logger.info(\"done\")\n","sub_path":"src/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"485759981","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n# https://leetcode.com/problems/diameter-of-binary-tree/discuss/101145/Simple-Python\nclass Solution:\n def diameterOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n\n def diameter_of_sub_tree(root, result):\n if not root:\n return 0\n left = diameter_of_sub_tree(root.left, result)\n right = diameter_of_sub_tree(root.right, result)\n\n result[0] = max(result[0], left + right)\n return 1 + max(left, right)\n\n result = [0]\n diameter_of_sub_tree(root, result)\n return result[0]\n","sub_path":"python/543. Diameter of Binary Tree.py","file_name":"543. Diameter of Binary Tree.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274695081","text":"# open reading frames\n\nfrom re import finditer\nfrom biolib import *\n\ninfile = 'rosalind_orf.txt'\n\nstring = fasta_string(infile)[0]\n\nuniq = set()\nfor frame in reading_frames(string):\n\tstrings = []\n\tread = False\n\tfor cdn in frame:\n\t\tif cdn == DNA_START_CODON:\n\t\t\tstrings = [s + DNA_CODONS[cdn] for s in strings]\n\t\t\tstrings.append(DNA_CODONS[cdn])\n\t\t\tread = True\n\t\telif cdn in DNA_STOP_CODONS and read:\n\t\t\tfor s in strings:\n\t\t\t\tuniq.add(s)\n\t\t\tstrings = []\n\t\t\tread = False\n\t\telif read:\n\t\t\tstrings = [s + DNA_CODONS[cdn] for s in strings]\n\nfor s in uniq:\n\tprint(s)\n","sub_path":"orf.py","file_name":"orf.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"563356455","text":"from .lists_base import FunctionalTest\n\n\nclass LayoutAndStylingTest(FunctionalTest):\n def test_layout_and_styling(self):\n # Edith goes to the home page\n lists_server_url = '%s%s' % (self.server_url, '/lists')\n self.browser.get(lists_server_url)\n self.browser.set_window_size(800, 600)\n\n # She notices the input box is nicely centered\n inputbox = self.get_item_input_box()\n self.assertAlmostEqual(\n inputbox.location['x'] + inputbox.size['width'] / 2,\n 400,\n delta=5\n )\n","sub_path":"functional_tests/lists/test_lists_layout_and_styling.py","file_name":"test_lists_layout_and_styling.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"189339631","text":"\"\"\"\n该模块实现了一维数据集的冒泡排序\n\"\"\"\n\n\ndef bubbleSort(data=[5, 4, 3, 2, 1]):\n for i in range(len(data)-1):\n print(\"第{}趟排序\".format(i))\n for j in range(len(data)-1-i):\n if data[j] > data[j+1]:\n data[j], data[j+1] = data[j+1], data[j]\n print(\"当前排序结果为:\", data)\n return None\n\n\ndef bubbleSortOptimized(data=[1, 2, 3, 4, 5]):\n for i in range(len(data)-1):\n flag = False\n print(\"第{}趟排序\".format(i))\n for j in range(len(data)-i-1):\n if data[j] > data[j+1]:\n data[j], data[j+1] = data[j+1], data[j]\n flag = True\n if flag is False:\n break\n print(\"当前排序结果为:\", data)\n return None\n\n\nif __name__ == '__main__':\n testData = [1, 3, 5, 7, 9, 8, 6, 4, 2]\n testData2 = [1, 2, 3, 4, 5, 6, 7, 9, 8]\n print(\"原来数据\", testData)\n bubbleSort(testData)\n bubbleSortOptimized(testData2)\n","sub_path":"Sort/BubbleSort/BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76140255","text":"\"\"\"Module implements pytest-bdd steps for operations on regular files.\n\"\"\"\n__author__ = \"Jakub Kudzia\"\n__copyright__ = \"Copyright (C) 2015 ACK CYFRONET AGH\"\n__license__ = \"This software is released under the MIT license cited in \" \\\n \"LICENSE.txt\"\n\nfrom tests import *\n\nimport subprocess\n\nfrom tests.utils.cucumber_utils import *\nfrom tests.utils.client_utils import cp, truncate, dd, echo_to_file, cat, \\\n md5sum, replace_pattern, client_mount_path, save_op_code, get_client\nfrom tests.utils.docker_utils import run_cmd\n\n\n@when(parsers.parse('{user} writes \"{data}\" at offset {offset} to {file} on {client_node}'))\ndef write_at_offset(user, data, offset, file, client_node, context):\n client = get_client(client_node, user, context)\n path = client_mount_path(file, client)\n write_command = '''python -c \"with open(\\\\\"{path}\\\\\", \\\\\"r+b\\\\\") as file:\n file.seek({offset})\n file.write(\\\\\"{data}\\\\\")\"\n'''.format(path=path, offset=offset, data=data)\n ret = run_cmd(user, client, write_command)\n save_op_code(context, user, ret)\n\n\n@when(parsers.parse('{user} writes {megabytes} MB of random characters to {file} on {client_node} and saves MD5'))\n@then(parsers.parse('{user} writes {megabytes} MB of random characters to {file} on {client_node} and saves MD5'))\ndef write_rand_text(user, megabytes, file, client_node, context):\n client = get_client(client_node, user, context)\n file_path = client_mount_path(file, client)\n ret = dd(client, megabytes, 1, file_path, user=user, output=False)\n md5 = md5sum(client, file_path, user=user)\n context.md5 = md5.split()[0]\n save_op_code(context, user, ret)\n\n\n@when(parsers.parse('{user} writes \"{text}\" to {file} on {client_node}'))\n@then(parsers.parse('{user} writes \"{text}\" to {file} on {client_node}'))\ndef write_text(user, text, file, client_node, context):\n client = get_client(client_node, user, context)\n file_path = client_mount_path(file, client)\n ret = echo_to_file(client, str(text), file_path, escape=True, user=user)\n save_op_code(context, user, ret)\n\n\n@when(parsers.parse('{user} reads \"{text}\" from {file} on {client_node}'))\n@then(parsers.parse('{user} reads \"{text}\" from {file} on {client_node}'))\ndef read(user, text, file, client_node, context):\n client = get_client(client_node, user, context)\n text = text.decode('string_escape')\n\n def condition():\n\n try:\n read_text = cat(client, client_mount_path(file, client), user=user)\n return read_text == text\n except subprocess.CalledProcessError:\n return False\n\n assert repeat_until(condition, client.timeout)\n\n\n@then(parsers.parse('{user} reads \"\" from {file} on {client_node}'))\ndef read_empty(user, file, client_node, context):\n read(user, '', file, client_node, context)\n\n\n@then(parsers.parse('{user} cannot read from {file} on {client_node}'))\ndef cannot_read(user, file, client_node, context):\n client = get_client(client_node, user, context)\n return_code = cat(client, client_mount_path(file, client), user=user, output=False)\n assert return_code != 0\n\n\n@when(parsers.parse('{user} appends \"{text}\" to {file} on {client_node}'))\ndef append(user, text, file, client_node, context):\n client = get_client(client_node, user, context)\n file_path = client_mount_path(file, client)\n ret = echo_to_file(client, str(text), file_path, user=user, overwrite=False)\n save_op_code(context, user, ret)\n\n\n@when(parsers.parse('{user} replaces \"{text1}\" with \"{text2}\" in {file} on {client_node}'))\ndef replace(user, text1, text2, file, client_node, context):\n client = get_client(client_node, user, context)\n file_path = client_mount_path(file, client)\n ret = replace_pattern(client, file_path, text1, text2, user)\n save_op_code(context, user, ret)\n\n\n@when(parsers.parse('{user} executes {file} on {client_node}'))\n@then(parsers.parse('{user} executes {file} on {client_node}'))\ndef execute_script(user, file, client_node, context):\n client = get_client(client_node, user, context)\n ret = run_cmd(user, client, client_mount_path(file, client))\n save_op_code(context, user, ret)\n\n\n@when(parsers.parse('{user} checks MD5 of {file} on {client_node}'))\n@then(parsers.parse('{user} checks MD5 of {file} on {client_node}'))\ndef check_md5(user, file, client_node, context):\n client = get_client(client_node, user, context)\n\n def condition():\n try:\n md5 = md5sum(client, client_mount_path(file, client), user=user)\n return md5.split()[0] == context.md5\n except subprocess.CalledProcessError:\n return False\n\n assert repeat_until(condition, client.timeout)\n\n\n@when(parsers.parse('{user} copies regular file {file} to {path} on {client_node}'))\ndef copy_reg_file(user, file, path, client_node, context):\n client = get_client(client_node, user, context)\n src_path = client_mount_path(file, client)\n dest_path = client_mount_path(path, client)\n ret = cp(client, src_path, dest_path, user=user)\n save_op_code(context, user, ret)\n\n\n@when(parsers.parse('{user} changes {file} size to {new_size} bytes on {client_node}'))\ndef do_truncate(user, file, new_size, client_node, context):\n client = get_client(client_node, user, context)\n file_path = client_mount_path(file, client)\n ret = truncate(client, file_path, new_size, user=user)\n save_op_code(context, user, ret)\n","sub_path":"tests/cucumber/steps/multi_reg_file_steps.py","file_name":"multi_reg_file_steps.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"645838728","text":"'''\nGiven an array of N distinct elements A[ ]. The task is to find the minimum number of swaps required to sort the array. \nYour are required to complete the function which returns an integer denoting the minimum number of swaps, required to sort the array.\n\nInput:\nThe first line of input contains an integer T denoting the no of test cases. Then T test cases follow. \nEach test case contains an integer N denoting the no of element of the array A[ ]. In the next line are N space separated values of the array A[ ] .\n\nOutput:\nFor each test case in a new line output will be an integer denoting minimum umber of swaps that are required to sort the array.\n\nConstraints:\n1 <= T <= 100\n1 <= N <= 105\n1 <= A[] <= 106\n\nUser Task:\nYour task is to complete minSwaps() which should return number of swaps required to make the array elements sorted.\n\nExample(To be used only for expected output):\nInput:\n2\n4\n4 3 2 1\n5\n1 5 4 3 2\n\nOutput:\n2\n2\n\nExplanation:\nTestcase 1: We need two swaps, swap 1 with 4 and 3 with 2 to make it sorted.\n\nhttps://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/\nhttps://www.youtube.com/watch?v=f7IIW0HVUcQ\n\n'''\ndef minSwaps(a,n):\n \n arrPos = []\n \n for i in range(n):\n arrPos.append([a[i], i])\n \n print(arrPos)\n \n arrPos.sort()\n print(arrPos)\n \n vis = [0 for i in range(n)]\n print(vis)\n \n ans = 0\n \n for i in range(n):\n \n if(vis[i] or arrPos[i][1] == i):\n continue\n \n cycle_size = 0\n j = i\n while(not vis[j]):\n vis[j] = 1\n j = arrPos[j][1]\n cycle_size += 1\n ans += cycle_size - 1\n \n return ans\n \n \n#a = [1,5,4,3,2]\na = [0,2,3,4,1,6,5]\nn = len(a)\nprint(minSwaps(a, n))","sub_path":"geeksforgeeks/searching/19_minimum_swaps_to_sort.py","file_name":"19_minimum_swaps_to_sort.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558641930","text":"# \n\nimport datetime\nimport yfinance as yf\nimport matplotlib.pyplot as plt\n\nstart = datetime.date(2020, 3, 23) # コロナ底\nend = datetime.date.today()\n\ncodelist = [\"VUG\", \"VTV\", \"VBK\", \"VBR\"]\n\ndata = yf.download(codelist, start=start, end=end)[\"Adj Close\"]\ndf_all = (1+data.pct_change()).cumprod()\ndf_all.rename(columns={'VBR': 'Small Value', 'VTV': 'Large Value',\n 'VBK': 'Small Growth', 'VUG': 'Large Growth'}, inplace=True)\n\ndf_all.plot(figsize=(16, 9), fontsize=30, linewidth=5, alpha=0.5)\nplt.legend(fontsize=18)\n\nx1 = \"2020-10-29\" # 転換点1\nplt.axvline(x1, color='gray', linewidth=2)\nx1 = \"2021-02-13\" # 転換点2\nplt.axvline(x1, color='gray', linewidth=2)\nx1 = \"2021-03-29\" # 転換点3\nplt.axvline(x1, color='gray', linewidth=2)\n\nplt.title(\"Growth vs Value , Small vs Large\", color='gray', fontsize=50)\nplt.show()\n","sub_path":"stock/hippen1_chart.py","file_name":"hippen1_chart.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"508466264","text":"#coding:utf-8\n\nfrom bs4 import BeautifulSoup\nimport requests\nfrom lib.common import requests_headers,requests_proxies\n\nclass FindSubDomains(object):\n _base_url = 'https://findsubdomains.com/'\n _modes = {\n 'full': _base_url + 'subdomains-of/',\n 'startswith': _base_url + 'subdomains-starts-with/'\n }\n\n def __init__(self, domain, startswith=False):\n self._domain = domain\n\n if startswith:\n self._selected_mode = 'startswith'\n else:\n self._selected_mode = 'full'\n\n\n def get(self):\n html = self._get_data(self._build_url(self._selected_mode))\n\n if not html:\n return []\n\n return self._parse_html(html)\n \n \n def _build_url(self, mode):\n return FindSubDomains._modes[mode] + self._domain\n\n def _get_data(self, url):\n r = requests.get(url,timeout=15,headers=requests_headers(),proxies=requests_proxies())\n\n return {\n 0: None,\n 1: r.text\n }[r.status_code == 200]\n \n\n def _parse_html(self, html):\n for tr in BeautifulSoup(html, \"html.parser\").find('table', {\n 'id': 'table-view'\n }).find_all('tr')[1:]:\n yield {\n 'domain': tr.find('td', {'data-field': 'Domain'})['title'],\n 'ip': tr.find('td', {'data-field': 'IP'}).text,\n 'asn': tr.find('td', {'data-field': 'AS'}).text,\n 'org': tr.find('td', {'data-field': 'Organization'}).text,\n }\n\ndef findsubdomain(domain=''):\n\talldomains = []\n\ttry:\n\t\tfsd = FindSubDomains(domain)\n\t\tfor result in fsd.get():\n\t\t\talldomains.append(result['domain'])\n\texcept:pass\n\treturn alldomains\n\nif __name__ == '__main__':\n pass","sub_path":"plugins/subdomain_findsubdomain.py","file_name":"subdomain_findsubdomain.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"548648003","text":"# -*- coding: UTF-8 -*-\n\nimport os\nimport cv2\nimport numpy as np\nimport utils\nfrom PIL import Image,ImageDraw,ImageFont\nimport json\n\ndef cutImg(peek_ranges, vertical_peek_ranges2d, index, text, counts, image_color, color, fontPath, saveDir, size, isSave):\n old_two_x = 0\n old_two_y = 0\n for i, peek_range in enumerate(peek_ranges):\n for (j,vertical_range) in enumerate(vertical_peek_ranges2d[i]):\n print(\"[INFO] processing image {}/{} {} {} {} {}\".format(index + 1, len(text), len(vertical_peek_ranges2d[i]), j, \n vertical_range[0], vertical_range[1]))\n if(index >= len(text)):\n continue\n code = text[index]\n x = vertical_range[0]\n y = peek_range[0]\n if(len(vertical_peek_ranges2d[i]) > (j+1)):\n if(abs(vertical_peek_ranges2d[i][j + 1][0] - vertical_range[1]) < size):\n old_two_x = vertical_range[1]\n old_two_y = y\n continue\n if(j != 0 and abs(x - old_two_x) < size):\n x = vertical_peek_ranges2d[i][j - 1][0]\n y = old_two_y\n \n old_two_x = vertical_range[1]\n old_two_y = peek_range[0]\n index += 1\n \n w = vertical_range[1] - x\n h = peek_range[1] - y\n image = image_color[y - 2:y + h + 2, x - 2:x + w + 2]\n save_path = os.path.join(saveDir, code)\n \n if not os.path.exists(save_path):\n os.makedirs(save_path)\n \n count = counts.get(code, 0)\n p = os.path.join(save_path, \"{}.png\".format(str(count).zfill(6)))\n if(isSave):\n cv2.imwrite(p, image)\n \n pt1 = (x, y)\n pt2 = (x + w, y + h)\n cv2.rectangle(image_color, pt1, pt2, color)\n \n pil_im = Image.fromarray(image_color)\n draw = ImageDraw.Draw(pil_im) # 括号中为需要打印的canvas,这里就是在图片上直接打印\n font = ImageFont.truetype(fontPath, 20, encoding=\"utf-8\") # 第一个参数为字体文件路径,第二个为字体大小\n draw.text((x, y - 20), code, (0, 0, 255), font=font) # 第一个参数为打印的坐标,第二个为打印的文本,第三个为字体颜色,第四个为字体\n image_color = cv2.cvtColor(np.array(pil_im), cv2.COLOR_RGB2BGR)\n \n counts[code] = counts.get(code, 0) + 1\n \n return counts,index,image_color\n\ndef cut_img_font_by_img(imgPath, txtPath, isSave, counts, writePath):\n peek_ranges,vertical_peek_ranges2d,image_color = utils.get_font_face_peek_ranges(imgPath)\n text = utils.readTextByStr(txtPath)\n index = 0\n counts,index,image_color = cutImg(peek_ranges, vertical_peek_ranges2d, index, text, counts, image_color, color, fontPath, saveDir, size, isSave)\n cv2.imwrite(writePath, image_color)\n return counts\n\ndef cut_img_font_by_dir(Path, font_suffix, img_suffix, counts):\n for p in os.listdir(Path) :\n pPath = os.path.join(Path, p)\n if os.path.isfile(pPath) and os.path.splitext(p)[1] == font_suffix:\n p_name = os.path.splitext(p)[0]\n txtPath = os.path.join(Path, p)\n imgPath = os.path.join(Path, p_name+img_suffix)\n writePath = os.path.join(tmpPath, p_name+img_suffix)\n counts = cut_img_font_by_img(imgPath, txtPath, isSave, counts, writePath)\n return counts\n\ncolor = (0, 0, 255)\nPath = \"tmp\"\ncountJsonPath = \"counts.json\"\nfontPath = \"1234.ttf\"\nisSave = True\nsaveDir = \"fonts\"\nsize = 8\ntmpPath = \"writeTmp\"\nfont_suffix = \".txt\"\nimg_suffix = \".png\"\ncounts = json.loads(utils.readTextByStr(countJsonPath))\n\nif not os.path.exists(tmpPath):\n os.makedirs(tmpPath)\n\ncounts = cut_img_font_by_dir(Path, font_suffix, img_suffix, counts)\n\nif(isSave):\n utils.readWrite(countJsonPath, json.dumps(counts))\nprint(counts)\n\n\n\n\n","sub_path":"demo/font/img_cut_dir.py","file_name":"img_cut_dir.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"554625127","text":"###IMPORTS\r\n##pygame\r\nimport pygame\r\nfrom pygame.locals import *\r\n\r\nfrom objects import Floor\r\n\r\n\r\n###INITIALIZATION\r\n##pygame\r\npygame.init()\r\n\r\n\r\ndef room_generator(file, floors):\r\n file = open(file)\r\n room = []\r\n for i in file.readlines():\r\n room.append(i[:-1])\r\n file.close()\r\n \r\n n_room = []\r\n c1 = 0\r\n c2 = 0\r\n \"\"\"\r\n for i in room:\r\n for j in i:\r\n if j == \"R\":\r\n n_room.append( floors[\"red\"] )\r\n elif j == \"O\":\r\n n_room.append( floors[\"orange\"] )\r\n elif j == \"S\":\r\n n_room.append( floors[\"strange\"] )\r\n else:\r\n assert(1 == 0);\r\n n_room[-1].pos.x = c2*100\r\n n_room[-1].pos.y = c1*100 #локальное положение обьекта \r\n c2 += 1\r\n c2 = 0\r\n c1 += 1\r\n \"\"\"\r\n for i in room:\r\n for j in i:\r\n if j == \"R\":\r\n n_room.append( Floor(floors[\"red\"] ) )\r\n elif j == \"O\":\r\n n_room.append( Floor(floors[\"orange\"] ) )\r\n elif j == \"S\":\r\n n_room.append( Floor(floors[\"strange\"] ) )\r\n else:\r\n assert(1 == 0);\r\n n_room[-1].pos.x = c2*100\r\n n_room[-1].pos.y = c1*100 #локальное положение обьекта \r\n c2 += 1\r\n c2 = 0\r\n c1 += 1\r\n \r\n \r\n return n_room\r\n\r\nclass Room():\r\n def __init__(self, objects, pos = [0,0], file = \"maps/room1.txt\"):\r\n self.pos = pos\r\n #room generation\r\n self.objects = room_generator(file, objects) #получаем обьекты и их локальное положение в комнате\r\n for i in range(len(self.objects)): #меняем глобальную позицию обьектов по отношению к сцене\r\n self.objects[i].pos.x += pos[0]\r\n self.objects[i].pos.y += pos[1]\r\n \r\n def blit(self, window):\r\n for i in range(len(self.objects)):\r\n self.objects[i].blit(window)\r\n \r\n def move(self, apos):\r\n self.pos[0] += apos[0]\r\n self.pos[1] += apos[1]\r\n \r\n for i in range(len(self.objects)):\r\n self.objects[i].pos.x += apos[0]\r\n self.objects[i].pos.y += apos[1]","sub_path":"alpha 0.0000001/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"411383186","text":"# -*- coding: utf-8 -*- \nfrom odoo import models, fields, api\n\nclass DemandNote(models.Model):\n\n\t_name = 'demand.note'\n\t_rec_name = 'dm_no'\n\n\tdm_no = fields.Char(\"Demand Note # \" ,readonly=True)\n\tdm_date = fields.Date(\"Demand Note Date\")\n\treq_dep = fields.Char(\"Requisitioning Department\")\n\tpurpose = fields.Char(\"Purpose\")\n\tmo_no = fields.Char(\"Manufacturing Order #\")\n\tuser = fields.Char(\"User\")\n\tdemand_note_tree_link=fields.One2many('demand.note.tree','demand_note_tree')\n\n\t@api.model \n\tdef create(self, vals):\n\t\tvals['dm_no'] = self.env['ir.sequence'].next_by_code('dem.seq')\n\t\tnew_record = super(DemandNote, self).create(vals) \n\t\treturn new_record\n\n\nclass DemandNoteTree(models.Model):\n\t\n\t_name = 'demand.note.tree'\n\n\tserial_no = fields.Char(\"Serial #\")\n\tmaterial_id = fields.Char(\"Material ID\")\n\titem_desc = fields.Many2one('product.template', string=\"Item Description\")\n\tuom = fields.Many2one('product.uom', string=\"UOM\", readonly=True)\n\trequisite_quantity = fields.Char(\"Requisite Quantity\")\n\t# issued_quantity = fields.Char(\" Issued Quantity\")\n\tremarks = fields.Char(\"Remarks\")\n\tcolor=fields.Many2one('product.attribute.value',\"Color\")\n\tsize=fields.Many2one('product.attribute.value',\"Size\")\n\tdemand_note_tree = fields.Many2one('demand.note')\n\n\n\t@api.onchange('item_desc')\n\tdef on_change_item_desc(self):\n\t\tif self.item_desc.name:\n\t\t\tsimilar_id = self.env['product.template'].search([('name','=',self.item_desc.name)])\n\t\t\tself.material_id = similar_id.internal_ref\n\t\t\tself.uom = similar_id.uom\n\t\t\t\n\t\t\n\t\t\n\n\t\t\t","sub_path":"demand_note_arian/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"60429988","text":"from http_adapter.url_types import UrlTypes\nfrom rip.crud.crud_actions import CrudActions\n\nmethod_to_action_mapping = {\n 'GET': 'read',\n 'POST': 'create',\n 'PATCH': 'update',\n 'DELETE': 'delete',\n 'PUT': 'create_or_update'\n}\n\n\nclass DefaultRipActionResolver(object):\n def __init__(self, http_request, url_type, url_kwargs,\n resource_detail_identifier='id'):\n self.resource_detail_identifier = resource_detail_identifier\n self.url_kwargs = url_kwargs\n self.url_type = url_type\n self.http_request = http_request\n\n def is_detail_action(self):\n if self.http_request.method == 'POST' and \\\n self.url_type == UrlTypes.list_url:\n return True\n return self.resource_detail_identifier in self.url_kwargs and \\\n self.url_type == UrlTypes.detail_url\n\n def determine_end_point(self):\n \"\"\"\n returns detail, list or aggregates\n \"\"\"\n if self.is_detail_action():\n return 'detail'\n elif self.url_type == UrlTypes.list_url and \\\n self.http_request.method == 'GET':\n return 'list'\n else:\n return None\n\n def get_action_name(self):\n if self.url_type == UrlTypes.aggregates_url and \\\n self.http_request.method == 'GET':\n return CrudActions.GET_AGGREGATES\n\n endpoint = self.determine_end_point()\n if endpoint is None or \\\n method_to_action_mapping.get(self.http_request.method) is None:\n return None\n action_name = \"%s_%s\" % (\n method_to_action_mapping.get(self.http_request.method), endpoint)\n return action_name\n","sub_path":"http_adapter/default_rip_action_resolver.py","file_name":"default_rip_action_resolver.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"235477857","text":"# Copyright (c) 2020 original 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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom expertai.nlapi.v1.object_mapper import ObjectMapper\nfrom tests import BaseTestCase\n\n\nclass KeyphraseExtraction(BaseTestCase):\n def test_the_response_is_passed_to_the_object_mapper(self):\n \"\"\"\n ...then verify that the values are correctly set\n \"\"\"\n response_json = {\n \"success\": True,\n \"data\": {\n \"content\": \"Facebook is looking at buying U.S. startup for $6 million\",\n \"language\": \"en\",\n \"version\": \"sensei: 3.1.0; disambiguator: 15.0-QNTX-2016\",\n \"knowledge\": [\n {\n \"label\": \"organization.company\",\n \"properties\": [\n {\"type\": \"WikiDataId\", \"value\": \"Q380\"}\n ],\n \"syncon\": 45740,\n }\n ],\n \"topics\": [\n {\n \"id\": 223,\n \"label\": \"mechanics\",\n \"score\": 3.5,\n \"winner\": True,\n }\n ],\n \"mainSentences\": [\n {\n \"value\": \"The machine is held until ready to start by a sort of trap to be sprung when all is ready; then with a tremendous flapping and snapping of the four-cylinder engine, the huge machine springs aloft.\",\n \"score\": 13.3,\n \"start\": 740,\n \"end\": 936,\n },\n ],\n \"mainPhrases\": [\n {\n \"value\": \"four-cylinder engine\",\n \"score\": 8,\n \"positions\": [{\"start\": 883, \"end\": 903}],\n }\n ],\n \"mainSyncons\": [\n {\n \"positions\": [{\"end\": 19, \"start\": 11}],\n \"score\": 35.59,\n \"syncon\": 45740,\n }\n ],\n \"mainLemmas\": [\n {\n \"value\": \"locomotive\",\n \"score\": 6.5,\n \"positions\": [\n {\"start\": 1152, \"end\": 1162},\n {\"start\": 1163, \"end\": 1167},\n {\"start\": 1239, \"end\": 1249},\n {\"start\": 1335, \"end\": 1345},\n {\"start\": 1394, \"end\": 1404},\n ],\n }\n ],\n },\n }\n\n omapper = ObjectMapper()\n data_model = omapper.read_json(response_json)\n self.assertEqual(\n data_model.knowledge[0].properties[0].type_, \"WikiDataId\"\n )\n self.assertEqual(data_model.main_lemmas[0].score, 6.5)\n self.assertEqual(data_model.main_lemmas[0].positions[1].end, 1167)\n self.assertEqual(data_model.main_syncons[0].syncon, 45740)\n","sub_path":"tests/v1/integration/test_keyphrase_extraction.py","file_name":"test_keyphrase_extraction.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"617661005","text":"from PyQt4 import QtCore, QtGui\nfrom pysat.utils.gui_utils import make_combobox\nfrom ui_modules.Error_ import error_print\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass dim_red_plot_:\n def __init__(self, pysat_fun, module_layout,arg_list,kw_list):\n self.pysat_fun = pysat_fun\n self.arg_list = arg_list\n self.kw_list = kw_list\n self.ui_id = None\n self.module_layout = module_layout\n self.main()\n\n def main(self):\n self.ui_id = self.pysat_fun.set_list(None, None, None, None, self.ui_id)\n self.dim_red_plot_ui()\n self.set_dim_red_params()\n self.get_dim_red_params()\n self.pysat_fun.set_greyed_modules(self.dim_red_plot)\n\n def set_dim_red_params(self):\n if self.arg_list is not None:\n datakey = self.arg_list[0]\n xvar = self.arg_list[1]\n yvar = self.arg_list[2]\n filename = self.arg_list[3]\n colorvar = self.kw_list['colorvar'][1]\n method = self.kw_list['method']\n\n self.dim_red_plot_choose_data.setCurrentIndex(self.dim_red_plot_choose_data.findText(datakey))\n self.dim_red_choosealg.setCurrentIndex(self.dim_red_choosealg.findText(method))\n self.xychoices_change_vars(self.xvar_choices)\n self.xychoices_change_vars(self.yvar_choices)\n self.xvar_choices.setCurrentIndex(self.xvar_choices.findText(xvar))\n self.yvar_choices.setCurrentIndex(self.yvar_choices.findText(yvar))\n self.colorchoices.setCurrentIndex(self.colorchoices.findText(colorvar))\n self.file_text.setText(filename)\n\n\n\n def get_dim_red_params(self):\n datakey=self.dim_red_plot_choose_data.currentText()\n method=self.dim_red_choosealg.currentText()\n xvar=self.xvar_choices.currentText()\n yvar=self.yvar_choices.currentText()\n colorvar=('comp',self.colorchoices.currentText())\n filename=self.file_text.text()\n\n\n args=[datakey,xvar,yvar,filename]\n kws={'colorvar':colorvar,'method':method}\n\n ui_list = \"do_plot_dim_red\"\n fun_list = \"do_plot_dim_red\"\n self.ui_id = self.pysat_fun.set_list(ui_list, fun_list, args, kws, self.ui_id)\n\n\n\n def dim_red_plot_ui(self):\n self.dim_red_plot = QtGui.QGroupBox()\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dim_red_plot.setFont(font)\n self.dim_red_plot.setObjectName(_fromUtf8(\"Dimensionality Reduction Plot\"))\n self.dim_red_plot_vlayout = QtGui.QVBoxLayout(self.dim_red_plot)\n self.dim_red_plot_vlayout.setObjectName(_fromUtf8(\"dim_red_plot_vlayout\"))\n #choose data set to apply dim reduction to\n self.dim_red_plot_choose_data_label = QtGui.QLabel(self.dim_red_plot)\n self.dim_red_plot_choose_data_label.setObjectName(_fromUtf8(\"dim_red_plot_choose_data_label\"))\n self.dim_red_plot_choose_data_label.setText(_translate(\"dim_red_plot\", \"Choose data:\", None))\n self.dim_red_plot_vlayout.addWidget(self.dim_red_plot_choose_data_label)\n datachoices = self.pysat_fun.datakeys\n if datachoices == []:\n error_print('No data has been loaded!')\n datachoices = ['No data has been loaded!']\n self.dim_red_plot_choose_data = make_combobox(datachoices)\n self.dim_red_plot_vlayout.addWidget(self.dim_red_plot_choose_data)\n\n #Choose the algorithm\n self.dim_red_choosealg_label=QtGui.QLabel(self.dim_red_plot)\n self.dim_red_choosealg_label.setText(_translate(\"dim_red_plot\", \"Choose method:\", None))\n self.dim_red_plot_vlayout.addWidget(self.dim_red_choosealg_label)\n alg_choices=['Choose a method','PCA','ICA','ICA-JADE']\n self.dim_red_choosealg=make_combobox(alg_choices)\n self.dim_red_plot_vlayout.addWidget(self.dim_red_choosealg)\n\n #choose the x and y variables\n xyvarchoices=['Choose a method first']\n self.xvar_choices_label=QtGui.QLabel(self.dim_red_plot)\n self.xvar_choices_label.setText('Choose X variable:')\n self.xvar_choices = make_combobox(xyvarchoices)\n self.xvar_choices.setObjectName(_fromUtf8(\"xvar_choices\"))\n self.dim_red_plot_vlayout.addWidget(self.xvar_choices_label)\n self.dim_red_plot_vlayout.addWidget(self.xvar_choices)\n\n self.yvar_choices_label = QtGui.QLabel(self.dim_red_plot)\n self.yvar_choices_label.setText('Choose Y variable:')\n self.yvar_choices = make_combobox(xyvarchoices)\n self.yvar_choices.setObjectName(_fromUtf8(\"yvar_choices\"))\n self.dim_red_plot_vlayout.addWidget(self.yvar_choices_label)\n self.dim_red_plot_vlayout.addWidget(self.yvar_choices)\n\n #choose the (optional) variable to use to color code the points\n self.colorchoices_label = QtGui.QLabel(self.dim_red_plot)\n self.colorchoices_label.setText('Choose variable to color code points (optional):')\n self.colorchoices = make_combobox([''])\n self.colorchoices_change_vars(self.colorchoices)\n self.colorchoices.setObjectName(_fromUtf8(\"colorchoices\"))\n self.dim_red_plot_vlayout.addWidget(self.colorchoices_label)\n self.dim_red_plot_vlayout.addWidget(self.colorchoices)\n\n #choose a filename for the plot\n self.file_label = QtGui.QLabel(self.dim_red_plot)\n self.file_label.setObjectName(_fromUtf8(\"file_label\"))\n self.file_text = QtGui.QLineEdit(self.dim_red_plot)\n self.file_text.setObjectName(_fromUtf8(\"file_text\"))\n self.dim_red_plot_vlayout.addWidget(self.file_label)\n self.dim_red_plot_vlayout.addWidget(self.file_text)\n\n\n self.module_layout.addWidget(self.dim_red_plot)\n self.dim_red_plot.raise_()\n self.dim_red_plot.setTitle(_translate(\"MainWindow\", \"Dimensionality Reduction\", None))\n\n\n self.dim_red_plot_choose_data.currentIndexChanged.connect(lambda: self.get_dim_red_params())\n self.dim_red_choosealg.currentIndexChanged.connect(lambda: self.get_dim_red_params())\n self.dim_red_choosealg.currentIndexChanged.connect(lambda: self.xychoices_change_vars(self.xvar_choices))\n self.dim_red_choosealg.currentIndexChanged.connect(lambda: self.xychoices_change_vars(self.yvar_choices))\n self.xvar_choices.currentIndexChanged.connect(lambda: self.get_dim_red_params())\n self.yvar_choices.currentIndexChanged.connect(lambda: self.get_dim_red_params())\n self.colorchoices.currentIndexChanged.connect(lambda: self.get_dim_red_params())\n self.file_text.textChanged.connect(lambda: self.get_dim_red_params())\n def xychoices_change_vars(self,obj):\n obj.clear()\n choices=self.pysat_fun.data[self.dim_red_plot_choose_data.currentText()].df[self.dim_red_choosealg.currentText()].columns.values\n for i in choices:\n obj.addItem(str(i))\n\n def colorchoices_change_vars(self, obj):\n obj.clear()\n choices = ['None']\n try:\n self.vars_level0 = self.pysat_fun.data[self.dim_red_plot_choose_data.currentText()].df.columns.get_level_values(0)\n self.vars_level1 = self.pysat_fun.data[self.dim_red_plot_choose_data.currentText()].df.columns.get_level_values(1)\n self.vars_level1 = self.vars_level1[self.vars_level0 != 'wvl']\n self.vars_level0 = self.vars_level0[self.vars_level0 != 'wvl']\n self.vars_level1 = list(self.vars_level1[self.vars_level0 != 'masked'])\n self.vars_level0 = list(self.vars_level0[self.vars_level0 != 'masked'])\n try:\n self.vars_level0 = [i for i in self.vars_level0 if 'Unnamed' not in str(i)] # remove unnamed columns from choices\n except:\n pass\n try:\n self.vars_level1 = [i for i in self.vars_level1 if 'Unnamed' not in str(i)] # remove unnamed columns from choices\n except:\n pass\n for i in self.vars_level1:\n choices.append(str(i))\n\n except:\n try:\n choices.append(self.pysat_fun.data[self.dim_red_plot_choose_data.currentText()].columns.values)\n except:\n pass\n for i in choices:\n obj.addItem(str(i))","sub_path":"point_spectra_gui/ui_modules/dim_red_plot_.py","file_name":"dim_red_plot_.py","file_ext":"py","file_size_in_byte":8603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"556574724","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom math import cos, pi, sin\n\n\nclass FlowField2D(object):\n \"\"\"\n DESCRIPTION\n \"\"\"\n def __init__(self, points=[], uinf=0., alpha=0., xlim=(-1., 1.), ylim=(-1., 1.), nx=100, ny=100):\n\n self.points = points\n self.uinf = uinf\n self.alpha = alpha\n self.xlim = xlim\n self.ylim = ylim\n self.nx = nx\n self.ny = ny\n\n @property\n def flow(self):\n u = np.ones(self.x.shape) * self.freestream[0]\n v = np.ones(self.x.shape) * self.freestream[1]\n for point in self.points:\n point_flow = point.compute_flow(self.x, self.y)\n u += point_flow[0]\n v += point_flow[1]\n return u, v\n\n @property\n def freestream(self):\n return [self.uinf * cos(self.alpha),\n self.uinf * sin(self.alpha)]\n\n @property\n def grid(self):\n return np.meshgrid(self.x_values, self.y_values)\n\n @property\n def psi(self):\n psi = self.uinf * (self.y * cos(self.alpha) - self.x * sin(self.alpha))\n for point in self.points:\n psi += point.compute_psi(self.x, self.y)\n return psi\n\n @property\n def u(self):\n return self.flow[0]\n\n @property\n def v(self):\n return self.flow[1]\n\n @property\n def x(self):\n return self.grid[0]\n\n @property\n def x_values(self):\n return np.linspace(self.xlim[0], self.xlim[1], self.nx)\n\n @property\n def y(self):\n return self.grid[1]\n\n @property\n def y_values(self):\n return np.linspace(self.ylim[0], self.ylim[1], self.ny)\n\n def plot_streamlines(self,\n arrowsize=1,\n arrowstyle='->',\n axes=None,\n density=1.,\n divide_linecolor='r',\n divide_linewidth=2,\n grid=True,\n linewidth=1,\n scaled=True,\n show_divide=False,\n show_points=True,\n title=None,\n xlabel='x',\n ylabel='y'):\n if not axes:\n axes = plt.subplot(111)\n\n axes.streamplot(self.x, self.y, self.u, self.v,\n density=density, linewidth=linewidth, arrowsize=arrowsize, arrowstyle=arrowstyle)\n\n if title:\n axes.set_title(title)\n if xlabel:\n axes.set_xlabel(xlabel)\n if ylabel:\n axes.set_ylabel(ylabel)\n if grid:\n axes.grid()\n\n axes.set_xlim(self.xlim)\n axes.set_ylim(self.ylim)\n\n if show_divide:\n axes.contour(self.x, self.y, self.psi,\n levels=[0.], colors=divide_linecolor,\n linewidth=divide_linewidth)\n\n if show_points:\n for point in self.points:\n axes.plot(point.x, point.y, color=point.default_color, marker='o')\n\n if scaled:\n axes.axis('scaled')\n\n return axes","sub_path":"src/potential/d2/_flow_field.py","file_name":"_flow_field.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"248212949","text":"# Muhammad Khan\n# Build.py\n# Includes Scroll\n\nfrom pygame import *\nfrom math import *\n\n\nscreen = display.set_mode((600, 600))\n\nfloorPicsAll = [image.load(\"Pictures/FloorTest2.png\"), image.load(\"Pictures/FloorTest2.png\")]\nfloorPics = [image.load(\"Pictures/FloorTest2.png\")]\npopY = -200\npopSpeed = 0.40\ndelta = 0\ncap = ()\npause = False\npopup = Rect(150, popY, 300, 200)\nbutton = Rect(20, 580, 60, 15)\nmenu = Rect(0, 570, 600, 30)\nphase = 1\nphaseI = [Rect(120, popY + 20, 50, 50), Rect(190, popY + 20, 50, 50)] # USE LOOP\ny = 150\nscrollSpeed = 2\n\nrunning = True\nfps = time.Clock()\nwhile running:\n mClickL = False\n mScrollU = False\n mScrollD = False\n for e in event.get():\n if e.type == QUIT:\n running = False\n if e.type == KEYDOWN:\n if e.key == K_UP:\n kUp = True\n if e.key == K_w:\n mScrollU = True\n if e.key == K_s:\n mScrollD = True\n if e.type == MOUSEBUTTONDOWN:\n if e.button == 1:\n mClickL = True\n if e.button == 4:\n mScrollU = True\n if scrollSpeed < 12:\n scrollSpeed += 2\n if e.button == 5:\n mScrollD = True\n if scrollSpeed > -12:\n scrollSpeed -= 2\n\n # _______\n keys = key.get_pressed()\n mx, my = mouse.get_pos()\n mb = mouse.get_pressed()\n screen.fill((55, 55, 55)) # Background\n\n if pause:\n # QUESTION : SHOULD THIS BE A FUNCTION?\n screen.blit(cap, (0, 0))\n draw.rect(screen, (0, 90, 90), button)\n\n # Drawing popup\n if popSpeed < 10:\n popSpeed += 0.25\n if popY < 150:\n popY += popSpeed\n popup = Rect(150, popY, 300, 200)\n draw.rect(screen, (0, 90, 90), popup)\n\n if phase == 1:\n phaseI = [Rect(170, popY + 20, 50, 50), Rect(240, popY + 20, 50, 50)] # USE LOOP\n for i in phaseI:\n draw.rect(screen, (0, 0, 90), i)\n\n if phase == 2:\n screen.set_clip(popup)\n\n if popup.collidepoint(mx, my) and mScrollU:\n y -= 2\n if popup.collidepoint(mx, my) and mScrollD:\n y += 2\n screen.blit(transform.scale(floorPicsAll[0], (200, 150//2)), (170, y + 20))\n buy1 = Rect(390, y + 20, 50, 20)\n draw.rect(screen, (0, 200, 100), buy1)\n screen.blit(transform.scale(floorPicsAll[1], (200, 150//2)), (170, y + 100))\n if buy1.collidepoint(mx, my) and mClickL:\n pause = False\n popSpeed = 0.40\n floorPics.append(floorPicsAll[0])\n screen.set_clip()\n if phaseI[0].collidepoint(mx, my) and mClickL:\n phase = 2\n\n else:\n # Scrolling\n\n if delta < 31:\n delta += scrollSpeed\n else:\n delta = 30\n scrollSpeed = 0\n\n if scrollSpeed > 0 and delta < 31:\n scrollSpeed -= 0.25\n if scrollSpeed < 0 and delta < 31:\n scrollSpeed += 0.25\n\n print(scrollSpeed, delta)\n\n # Draws floors\n for i in range(0, len(floorPics)):\n screen.blit(floorPics[i], (100, 400 - (150 * i) - delta))\n\n draw.rect(screen, (30, 30, 30), (0, 550 - delta, 600, 50)) # Drawing base\n draw.rect(screen, (90, 90, 90), menu)\n draw.rect(screen, (0, 90, 90), button)\n\n # Bringing back popup # MAKE A FUNCTION: Same for up and down, input differs, global vars.\n if popY > -200:\n if popSpeed < 10:\n popSpeed += 0.25\n popY -= popSpeed\n popup = Rect(150, popY, 300, 200)\n phaseI = [Rect(170, popY + 20, 50, 50), Rect(240, popY + 20, 50, 50)]\n draw.rect(screen, (0, 90, 90), popup)\n if phase == 1:\n for i in phaseI:\n draw.rect(screen, (0, 0, 90), i)\n if phase == 2:\n screen.set_clip(popup)\n y -= popSpeed\n screen.blit(transform.scale(floorPicsAll[0], (200, 150//2)), (170, y + 20))\n buy1 = Rect(390, y + 20, 50, 20)\n draw.rect(screen, (0, 200, 100), buy1)\n screen.blit(transform.scale(floorPicsAll[1], (200, 150//2)), (170, y + 100))\n screen.set_clip()\n\n if button.collidepoint(mx, my) and mClickL:\n cap = screen.copy()\n if pause:\n pause = False\n popSpeed = 0.40\n else:\n pause = True\n phase = 1\n y = 150\n popSpeed = 0.40\n\n # _______\n display.flip()\n fps.tick(60)\nquit()\n","sub_path":"Build + Menus.py","file_name":"Build + Menus.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"83538798","text":"from allauth.account.adapter import DefaultAccountAdapter\nfrom allauth.account.utils import user_field\nfrom requests import Response\n\n\nclass CustomUserAccountAdapter(DefaultAccountAdapter):\n\n def save_user(self, request, user, form, commit=True):\n\n print(request.META.get('HTTP_AUTHORIZATION', None))\n user = super().save_user(request, user, form, False)\n user_field(user, 'first_name', request.data.get('firstName'))\n user_field(user, 'second_name', request.data.get('secondName'))\n user_field(user, 'age', request.data.get('age'))\n user.save()","sub_path":"project_football/adapters.py","file_name":"adapters.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"601768108","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 21 22:45:50 2016\n\n@author: Neo\n\nregional differences\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n## Nodes of RA and DE\nsra = 10\nsde = 10\nNra = np.arange([ 0, 370, sra]) ## deg\nNde = np.arange([-90, 100, sde]) ## deg\nlra = len(Nra)\nlde = len(Nde)\n## coordinates of center of grids\nMra = Nra[:lra-1] + sra/2\nMde = Nde[:lde-1] + sde/2\n\ndef compart(l1, l2):\n '''\n find the common part of l1 and l2, return a list of common part.\n '''\n com = []\n for i in range(len(l1)):\n if l1[i] in l2:\n com.append(l1[i])\n return com\n \ndef elim(xo, xc, err):\n '''\n eliminate outliers that statisfied the condition:\n abs(xo(obs) - xc(cal))> n*err\n xo, xc should be arrays.\n '''\n n =2.6\n res = np.abs(xo - xc) - n*err\n ind = np.where(res<0)\n \n return ind\n \ndef WgtMean(x, err):\n wgt = err*-2\n mean = np.sum(x*wgt)/np.sum(wgt)\n \n return mean \n \ndef CalMean(x, err):\n if len(x)>3:\n mean = WgtMean(x, err)\n ind = elim(x, mean, err)\n xn = np.take(x, ind)\n errn = np.take(err, ind)\n mean = WgtMean(xn, errn)\n else:\n mean = 0.0\n return mean\n\ndef RegErr(RA, DE, x, y, e_x, e_y):\n '''\n compute the regional differences for a two-dimensional vector (x, y)\n '''\n Regx = np.zeros([lra-1, lde-1])\n Regy = np.zeros([lra-1, lde-1])\n \n for i in range(lra-1):\n id1 = np.where(RA>Nra[i])\n id2 = np.where(RANde[i])\n id4 = np.where(DE 4:\n raise LookupError\n break;\n except ValueError as error:\n print('Error: please enter a valid option(number)..\\n')\n except LookupError as error:\n print('Error: please enter a valid option..\\n')\n \n\n if choice < 2: \n menuOptions[choice]()\n else:\n while True:\n filename = input('Please enter the file name that you want to modify (has to be in the same directory): ')\n if filename == 'm':\n break;\n try:\n if os.path.isfile(filename) == False or len(filename) < 5 or filename[-4:] != '.wav':\n raise LookupError\n break;\n except LookupError as error: \n print('\\n\\nError: please enter a valid file name in the same directory..')\n print('Example: example.wav')\n print('Enter m if you want to return to the main menu\\n\\n')\n #print('we are here after file addition')\n if filename != 'm':\n info = audiomin.getFileInfo(filename)\n csvLogger.createSpecificLog(filename, info)\n if choice == 2:\n while True:\n amplifySet = int(input('Please enter by how much you would want to amplify the audio clip(1-5), or 0 for the default value: '))\n if amplifySet > 5 or amplifySet < 0:\n print('error, please enter a valid value')\n else:\n break;\n if amplifySet == 0:\n audiomin.amplify(filename, amplifyDef)\n setting = amplifyDef\n else:\n audiomin.amplify(filename, amplifySet)\n setting = amplifySet\n csvLogger.increFile(filename)\n csvLogger.addNewEntry(filename, 'Yes', amplifySet, 'No', '(0, 0)', 'No', 0)\n elif choice == 3:\n low = int(input('Please enter the number of the low frequency to filter out, or -1 for the default value: '))\n if low == -1:\n low = lowDef\n high = int(input('Please enter the number of the high frequency to filter out, or -1 for the default value: '))\n if high == -1:\n high = highDef\n audiomin.filterNoise(filename, 21, 9000)\n csvLogger.increFile(filename)\n csvLogger.addNewEntry(filename, 'No', 0, 'Yes', '('+str(low)+', '+str(high)+')', 'No', 0)\n elif choice == 4:\n target = int(input('Please enter the the decibel, or -1 for the default value: '))\n if target == -1:\n target = normDef\n audiomin.normalize(filename, target)\n csvLogger.increFile(filename)\n csvLogger.addNewEntry(filename, 'No', 0, 'No', '(0, 0)', 'Yes', target)\n\n\n \n\n \n \n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"19160929","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 19 23:24:52 2012\r\n\r\n@author: Nikolay\r\n\"\"\"\r\nimport csv\r\nimport cPickle\r\n\r\nfrom chord_utils import list_spectrum_data, through_da\r\n\r\ndef autoencode_file(source, target):\r\n with open(source, 'rb') as i:\r\n reader = csv.reader(i)\r\n (before, chords) = list_spectrum_data(reader, components=240, allow_no_chord=True)\r\n result = through_da(before)\r\n with open(target, 'wb') as o:\r\n writer = csv.writer(o)\r\n writer.writerows(result)\r\n\r\nwith open('dA_spectrum/corruption_30.dat', 'rb') as d:\r\n da = cPickle.load(d)\r\n autoencode_file('data/track_short.csv', 'data/encoded_short.csv')\r\n","sub_path":"chordest/py/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"206103316","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\nimport sys\nimport time\n\nfrom somfy import Remote\n\n\nbtn = {\n\"UP\": Remote.UP_BTN,\n\"DOWN\": Remote.DOWN_BTN,\n\"STOP\": Remote.STOP_BTN,\n\"SETUP\": Remote.SETUP_BTN\n}\n\nif len(sys.argv) == 3:\n rem = Remote(sys.argv[1])\n rem.send_signal(btn[sys.argv[2].upper()])\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"517615123","text":"#要操作关系数据库,首先需要连接到数据库,一个数据库连接称为Connection;\n#连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果\n\nimport sqlite3 as sq\nimport csv\nimport pandas as pd\n\n\nif __name__ == '__main__':\n #数据库地址 \n #r'C:\\Users\\Administrator\\Desktop\\Model\\restaurant\\restaurant.db'\n file_path = r'C:\\Users\\Administrator\\Desktop\\finance\\finance.db'\n\n conn = sq.connect(file_path)\n cur = conn.cursor()\n\n print(\"Opened database successfully\")\n\n cur.execute(\n '''\n\n '''\n )\n\n #print(cur.fetchall())\n\n cur.close()\n conn.commit()\n conn.close()\n","sub_path":"sql-practice/py操作sqlite.py","file_name":"py操作sqlite.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"470599453","text":"from math import log2\n\nimport matplotlib.pyplot as plt\n\nMAX_BATCH_SIZE = 11\n\n\ndef get_number_of_exec():\n x_data = list()\n y_data = list()\n y2_data = list()\n y3_data = list()\n y5_data = [3, 4]\n y4_data = list()\n\n # x_data.append(1)\n # y_data.append(1)\n # y2_data.append(1)\n # y3_data.append(1)\n y4_data.append(0)\n\n for batch_size in range(2, MAX_BATCH_SIZE):\n x = batch_size\n y = 2 * log2(x) + 1\n test_list = [False]\n test_list += [True for _ in range(batch_size - 1)]\n\n x_data.append(x)\n y_data.append(y)\n y2_data.append(x + 1)\n y3_data.append(2 * x - 1)\n y4_data.append(0)\n\n for batch_size in range(4, MAX_BATCH_SIZE):\n x = batch_size\n y5_data.append(1.5 * x - 1)\n\n fig, ax = plt.subplots(1)\n\n ax.plot(x_data, y_data, 'g--', label='BatchBisect/BatchStop4 minimum (2 * log2(n) + 1)')\n ax.plot(x_data, y2_data, 'b-', label='Dorfman - Batching without bisection (n + 1)')\n ax.plot(x_data, y3_data, 'r:', label='BatchBisect Maximum (2 * n - 1)')\n ax.plot(x_data, y5_data, '--', color='purple' ,label='BatchStop4 Maximum (1.5 * n - 1)')\n ax.plot(4, 5, marker='o', color='#871912', label='Batch4 (4 + 1)', ls='', ms=10, mfc='none', mew=2)\n\n plt.xlim(1, MAX_BATCH_SIZE)\n plt.ylim(1, MAX_BATCH_SIZE)\n plt.xticks(range(1, MAX_BATCH_SIZE, 1))\n plt.yticks(range(1, MAX_BATCH_SIZE + 1, 1))\n plt.xlabel('Batch Size')\n plt.ylabel('Number of executions')\n plt.grid(True)\n plt.legend()\n plt.savefig(\"logn.png\", format=\"png\", dpi=300)\n plt.show()\n\n\nif __name__ == \"__main__\":\n get_number_of_exec()\n","sub_path":"RQ1and2/code/2logn.py","file_name":"2logn.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"221290575","text":"import copy\nimport hashlib\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.cache import cache\nfrom django.db import models\nfrom django.db.models import (\n Max,\n F,\n Q,\n Sum,\n UniqueConstraint,\n)\nfrom django.template.defaultfilters import slugify\n\n# https://github.com/martsberger/django-pivot/blob/master/django_pivot/pivot.py\nfrom django_pivot.pivot import pivot\n\nfrom chartofaccountDIT.models import (\n Analysis1,\n Analysis2,\n BudgetType,\n NaturalCode,\n ProgrammeCode,\n ProjectCode,\n)\n\nfrom core.metamodels import BaseModel\nfrom core.models import FinancialYear\nfrom core.utils.generic_helpers import GRAND_TOTAL_CLASS, SUB_TOTAL_CLASS, TOTAL_CLASS\nfrom core.utils.generic_helpers import get_current_financial_year\n\nfrom costcentre.models import CostCentre\n\nfrom forecast.utils.view_field_definition import (\n budget_field,\n outturn_field,\n outturn_variance_field,\n)\n\nGRAND_TOTAL_ROW = \"grand_total\"\nMAX_PERIOD_CODE = 15\n\n\nclass SubTotalFieldDoesNotExistError(Exception):\n pass\n\n\nclass SubTotalFieldNotSpecifiedError(Exception):\n pass\n\n\nclass ForecastEditState(BaseModel):\n closed = models.BooleanField(\n default=False,\n help_text=\"Ticking this option will close editing access \"\n \"to all non finance staff. Forecast editing is still \"\n \"available to Finance business partners/BSCEs and admin.\"\n )\n lock_date = models.DateField(\n null=True,\n blank=True,\n verbose_name=\"Lock system\",\n help_text=\"The system is locked from the date entered. \"\n \"The system will remain locked to users without \"\n \"'unlocked' user status, until the date is removed \"\n \"from the input field above. Please remember to archive the \"\n \"data after locking the forecast.\",\n )\n\n def __str__(self):\n return 'Forecast edit state'\n\n class Meta:\n verbose_name_plural = \"Forecast edit state\"\n default_permissions = ('view', 'change')\n permissions = [\n (\"can_set_edit_lock\", \"Can set edit lock\"),\n (\n \"can_edit_whilst_closed\",\n \"Can edit forecasts whilst system is closed\",\n ),\n (\n \"can_edit_whilst_locked\",\n \"Can edit forecasts whilst system is locked\",\n ),\n ]\n\n\nclass UnlockedForecastEditor(BaseModel):\n user = models.ForeignKey(\n get_user_model(),\n on_delete=models.CASCADE,\n related_name=\"users\"\n )\n\n def __str__(self):\n return str(self.user)\n\n\nclass ForecastExpenditureType(BaseModel):\n \"\"\"The expenditure type is a combination of\n the economic budget (NAC) and the budget type (Programme).\n As such, it can only be defined for a forecast\n row, when both NAC and programme are defined.\n This table is prepopulated with the information\n needed to get the expenditure_type.\n \"\"\"\n\n nac_economic_budget_code = models.CharField(\n max_length=255, verbose_name=\"economic budget code\"\n )\n programme_budget_type = models.ForeignKey(BudgetType, on_delete=models.CASCADE)\n\n forecast_expenditure_type_name = models.CharField(max_length=100)\n forecast_expenditure_type_description = models.CharField(max_length=100)\n forecast_expenditure_type_display_order = models.IntegerField()\n\n class Meta:\n unique_together = (\"nac_economic_budget_code\", \"programme_budget_type\")\n\n def __str__(self):\n return self.forecast_expenditure_type_name\n\n\nclass FinancialPeriodManager(models.Manager):\n def month_display_list(self):\n return list(\n self.get_queryset()\n .filter(financial_period_code__lte=12)\n .values_list(\"period_short_name\", flat=True)\n )\n\n def month_adj_display_list(self):\n return list(\n self.get_queryset()\n .values_list(\"period_short_name\", flat=True)\n )\n\n def adj_display_list(self):\n return list(\n self.get_queryset()\n .filter(financial_period_code__gt=12, display_figure=True)\n .values_list(\"period_short_name\", flat=True)\n )\n\n def all_adj_list(self):\n return list(\n self.get_queryset()\n .filter(financial_period_code__gt=12)\n .values_list(\"period_short_name\", flat=True)\n )\n\n def period_display_list(self):\n return list(\n self.get_queryset()\n .filter(display_figure=True)\n .values_list(\"period_short_name\", flat=True)\n )\n\n def period_display_all_list(self):\n return list(\n self.get_queryset()\n .values_list(\"period_short_name\", flat=True)\n )\n\n def period_display_code_list(self):\n return list(\n self.get_queryset()\n .filter(display_figure=True)\n .values_list(\"financial_period_code\", flat=True)\n )\n\n def month_sublist(self, month):\n if month > MAX_PERIOD_CODE:\n # needed for displaying previous year outturn\n month = MAX_PERIOD_CODE\n return self.period_display_list()[: month]\n\n def actual_month(self):\n # use the Max to protect us from the situation of\n # non contiguous actual month.\n aggregate_queryset = (\n self.get_queryset()\n .filter(actual_loaded=True)\n .aggregate(Max(\"financial_period_code\"))\n )\n return aggregate_queryset[\"financial_period_code__max\"] or 0\n\n def actual_period_code_list(self):\n last_actual_month = self.actual_month()\n return list(\n self.get_queryset()\n .filter(financial_period_code__lte=last_actual_month)\n .values_list(\"financial_period_code\", flat=True,)\n )\n\n def forecast_period_code_list(self):\n last_actual_month = self.actual_month()\n return list(\n self.get_queryset()\n .filter(financial_period_code__gt=last_actual_month)\n .values_list(\"financial_period_code\", flat=True,)\n )\n\n def actual_month_previous_year(self):\n # use the Max to protect us from the situation of\n # non contiguous actual month.\n m = (\n self.get_queryset()\n .filter(actual_loaded_previous_year=True)\n .aggregate(Max(\"financial_period_code\"))\n )\n return m[\"financial_period_code__max\"] or 0\n\n def actual_month_list(self):\n return self.month_sublist(self.actual_month())\n\n def actual_month_previous_year_list(self):\n # use period_display_all_list because adjustement (ADJxx) periods\n # must be included when showing previous year data\n return self.period_display_all_list()[: self.actual_month_previous_year()]\n\n def periods(self):\n return (\n self.get_queryset()\n .filter(display_figure=True)\n .values_list(\"period_short_name\", \"period_long_name\")\n )\n\n def month_periods(self):\n return (\n self.get_queryset()\n .filter(financial_period_code__lte=12)\n .values_list(\"period_short_name\", \"period_long_name\")\n )\n\n def adj_periods(self):\n return (\n self.get_queryset()\n .filter(financial_period_code__gt=12, display_figure=True)\n .values_list(\"period_short_name\", \"period_long_name\")\n )\n\n def reset_actuals(self):\n self.get_queryset().filter(actual_loaded=True,).update(actual_loaded=False,)\n\n def get_max_period(self):\n return self.get_queryset().order_by(\"-financial_period_code\").first()\n\n\nclass FinancialPeriod(BaseModel):\n \"\"\"Financial periods: correspond\n to month, but there are 3 extra\n periods at the end\"\"\"\n\n financial_period_code = models.IntegerField(primary_key=True) # April = 1\n period_long_name = models.CharField(max_length=20)\n period_short_name = models.CharField(max_length=10)\n period_calendar_code = models.IntegerField() # January = 1\n # use a flag to indicate if the \"actuals\"\n # have been uploaded instead of relying on the date\n # the \"actuals\" are manually uploaded, so it is not\n # guaranteed on which date they are uploaded\n actual_loaded = models.BooleanField(default=False)\n actual_loaded_previous_year = models.BooleanField(default=False)\n display_figure = models.BooleanField(default=True)\n\n objects = models.Manager() # The default manager.\n financial_period_info = FinancialPeriodManager()\n\n class Meta:\n ordering = [\"financial_period_code\"]\n\n def __str__(self):\n return self.period_long_name\n\n\nclass FinancialCodeAbstract(models.Model):\n \"\"\"Contains the members of Chart of Account needed to create a unique key\"\"\"\n class Meta:\n abstract = True\n # Several constraints required, to cover all the permutations of\n # fields that can be Null\n constraints = [\n UniqueConstraint(\n fields=[\n \"programme\",\n \"cost_centre\",\n \"natural_account_code\",\n \"analysis1_code\",\n \"analysis2_code\",\n \"project_code\",\n ],\n name=\"financial_row_unique_6\",\n condition=Q(analysis1_code__isnull=False)\n & Q(analysis2_code__isnull=False)\n & Q(project_code__isnull=False),\n ),\n UniqueConstraint(\n fields=[\n \"programme\",\n \"cost_centre\",\n \"natural_account_code\",\n \"analysis2_code\",\n \"project_code\",\n ],\n name=\"financial_row_unique_5a\",\n condition=Q(analysis1_code__isnull=True)\n & Q(analysis2_code__isnull=False)\n & Q(project_code__isnull=False),\n ),\n UniqueConstraint(\n fields=[\n \"programme\",\n \"cost_centre\",\n \"natural_account_code\",\n \"analysis1_code\",\n \"project_code\",\n ],\n name=\"financial_row_unique_5b\",\n condition=Q(analysis1_code__isnull=False)\n & Q(analysis2_code__isnull=True)\n & Q(project_code__isnull=False),\n ),\n UniqueConstraint(\n fields=[\n \"programme\",\n \"cost_centre\",\n \"natural_account_code\",\n \"analysis1_code\",\n \"analysis2_code\",\n ],\n name=\"financial_row_unique_5c\",\n condition=Q(analysis1_code__isnull=False)\n & Q(analysis2_code__isnull=False)\n & Q(project_code__isnull=True),\n ),\n UniqueConstraint(\n fields=[\n \"programme\",\n \"cost_centre\",\n \"natural_account_code\",\n \"project_code\",\n ],\n name=\"financial_row_unique_4a\",\n condition=Q(analysis1_code__isnull=True)\n & Q(analysis2_code__isnull=True)\n & Q(project_code__isnull=False),\n ),\n UniqueConstraint(\n fields=[\n \"programme\",\n \"cost_centre\",\n \"natural_account_code\",\n \"analysis1_code\",\n ],\n name=\"financial_row_unique_4b\",\n condition=Q(analysis1_code__isnull=False)\n & Q(analysis2_code__isnull=True)\n & Q(project_code__isnull=True),\n ),\n UniqueConstraint(\n fields=[\n \"programme\",\n \"cost_centre\",\n \"natural_account_code\",\n \"analysis2_code\",\n ],\n name=\"financial_row_unique_4c\",\n condition=Q(analysis1_code__isnull=True)\n & Q(analysis2_code__isnull=False)\n & Q(project_code__isnull=True),\n ),\n UniqueConstraint(\n fields=[\"programme\", \"cost_centre\", \"natural_account_code\", ],\n name=\"financial_row_unique_3\",\n condition=Q(analysis1_code__isnull=True)\n & Q(analysis2_code__isnull=True)\n & Q(project_code__isnull=True),\n ),\n ]\n permissions = [\n (\"can_view_forecasts\", \"Can view forecast\"),\n (\"can_upload_files\", \"Can upload files\"),\n (\"can_download_oscar\", \"Can download OSCAR\"),\n (\"can_download_mi_reports\", \"Can download mi reports\"),\n ]\n\n def save(self, *args, **kwargs):\n # Override save to calculate the forecast_expenditure_type.\n if self.pk is None or self.forecast_expenditure_type is None:\n # calculate the forecast_expenditure_type\n nac_economic_budget_code = self.natural_account_code.economic_budget_code\n programme_budget_type = self.programme.budget_type\n forecast_type = ForecastExpenditureType.objects.filter(\n programme_budget_type=programme_budget_type,\n nac_economic_budget_code__iexact=nac_economic_budget_code,\n )\n self.forecast_expenditure_type = forecast_type.first()\n\n super(FinancialCodeAbstract, self).save(*args, **kwargs)\n\n\nclass FinancialCode(FinancialCodeAbstract, BaseModel):\n programme = models.ForeignKey(ProgrammeCode, on_delete=models.PROTECT)\n cost_centre = models.ForeignKey(CostCentre, on_delete=models.PROTECT)\n natural_account_code = models.ForeignKey(NaturalCode, on_delete=models.PROTECT)\n analysis1_code = models.ForeignKey(\n Analysis1, on_delete=models.PROTECT, blank=True, null=True\n )\n analysis2_code = models.ForeignKey(\n Analysis2, on_delete=models.PROTECT, blank=True, null=True\n )\n project_code = models.ForeignKey(\n ProjectCode, on_delete=models.PROTECT, blank=True, null=True\n )\n # The following field is calculated from programme and NAC.\n forecast_expenditure_type = models.ForeignKey(\n ForecastExpenditureType,\n on_delete=models.PROTECT,\n default=1,\n blank=True,\n null=True,\n )\n\n\nclass SubTotalForecast:\n result_table = []\n period_list = []\n full_list = []\n output_subtotal = []\n previous_values = []\n display_total_column = \"\"\n\n def __init__(self, data):\n self.display_data = data\n self.result_table = []\n self.period_list = []\n self.full_list = []\n self.output_subtotal = []\n self.previous_values = []\n self.display_total_column = \"\"\n\n def output_row_to_table(self, row, style_name=\"\"):\n # Add the stile entry to the dictionary\n # add the resulting dictionary to the list\n # if style_name != '':\n # style_name = '{}-{}'.format(style_name, level)\n row[\"row_type\"] = style_name\n self.result_table.append(row)\n\n def add_row_to_subtotal(self, row_from, sub_total):\n for period in self.period_list:\n val = None\n if row_from[period]:\n val = row_from[period]\n else:\n val = 0\n if sub_total[period]:\n sub_total[period] += val\n else:\n sub_total[period] = val\n\n def clear_row(self, row):\n for period in self.period_list:\n row[period] = 0\n\n def row_has_values(self, row):\n has_values = False\n for period in self.period_list:\n if row[period] and (row[period] > 50 or row[period] < -50):\n has_values = True\n break\n return has_values\n\n def remove_empty_rows(self):\n # period_list has to be initialised before we can check if the row\n # has values different from 0\n how_many_row = len(self.display_data) - 1\n for i in range(how_many_row, -1, -1):\n row = self.display_data[i]\n if not self.row_has_values(row):\n del self.display_data[i]\n\n def do_output_subtotal(self, current_row):\n new_flag = False\n # Check the subtotals, from the outer subtotal to the inner one.\n # if an outer subtotal is needed, all the inner one are needed too\n for column in self.subtotal_columns[::-1]:\n if self.output_subtotal[column]:\n # this trigger the subtotals in the inner fields.\n new_flag = True\n else:\n self.output_subtotal[column] = new_flag\n\n for column in self.subtotal_columns:\n if self.output_subtotal[column]:\n subtotal_row = self.subtotals[column].copy()\n level = self.subtotal_columns.index(column)\n subtotal_row[\n self.display_total_column\n ] = f\"Total {self.previous_values[column]}\"\n show_class = TOTAL_CLASS\n for out_total in self.subtotal_columns[level + 1:]:\n subtotal_row[self.display_total_column] = (\n f\"{subtotal_row[self.display_total_column]} \"\n f\"{self.previous_values[out_total]}\"\n )\n show_class = SUB_TOTAL_CLASS\n self.output_row_to_table(\n subtotal_row, show_class,\n )\n self.clear_row(self.subtotals[column])\n self.previous_values[column] = current_row[column]\n self.output_subtotal[column] = False\n else:\n break\n\n def calculate_subtotal_data(\n self, display_total_column, subtotal_columns_arg, show_grand_total,\n ):\n # Make a copy so that modifying this will not touch\n # the original subtotal_columns_arg\n # otherwise each time the view is called the calculation order changes.\n self.subtotal_columns = copy.deepcopy(subtotal_columns_arg)\n # The self.subtotals are passed in from\n # the outer totals for calculation,\n # it is easier to call subtotal 0\n # the innermost subtotal\n self.subtotal_columns.reverse()\n self.display_total_column = display_total_column\n self.result_table = []\n self.output_subtotal = []\n self.previous_values = []\n\n self.full_list = list(\n FinancialPeriod.objects.values_list(\"period_short_name\", flat=True)\n )\n\n self.full_list.append(budget_field)\n self.full_list.append(\"Previous_outturn\")\n self.full_list.append(outturn_field)\n self.full_list.append(outturn_variance_field)\n\n # remove missing periods (like Adj1,\n # etc from the list used to add the\n # periods together.\n self.period_list = [\n value for value in self.full_list if value in self.display_data[0].keys()\n ]\n\n self.remove_empty_rows()\n # Check that there are rows left. Maybe they were all\n # with values of 0.\n if not self.display_data:\n return []\n first_row = self.display_data.pop(0)\n self.output_row_to_table(first_row, \"\")\n # Initialise the structure required\n # a dictionary with the previous\n # value of the columns to be\n # sub-totalled a dictionary of\n # subtotal dictionaries, with an\n # extra entry for the final total\n # (gran total)\n sub_total_row = {\n k: (v if k in self.period_list else \" \") for k, v in first_row.items()\n }\n self.previous_values = {\n field_name: first_row[field_name] for field_name in self.subtotal_columns\n }\n # initialise all the self.subtotals,\n # and add an extra row for the\n # final total (gran total)\n self.subtotals = {\n field_name: sub_total_row.copy() for field_name in self.subtotal_columns\n }\n\n self.subtotals[GRAND_TOTAL_ROW] = sub_total_row.copy()\n self.output_subtotal = {\n field_name: False for field_name in self.subtotal_columns\n }\n for current_row in self.display_data:\n subtotal_time = False\n # check if we need a subtotal.\n # we check from the inner subtotal\n for column in self.subtotal_columns:\n if current_row[column] != self.previous_values[column]:\n subtotal_time = True\n self.output_subtotal[column] = True\n if subtotal_time:\n self.do_output_subtotal(current_row)\n for k, totals in self.subtotals.items():\n self.add_row_to_subtotal(current_row, totals)\n self.output_row_to_table(current_row, \"\")\n\n # output all the subtotals, because it is finished\n for column in self.subtotal_columns:\n level = self.subtotal_columns.index(column)\n caption = f\"Total {self.previous_values[column]}\"\n show_class = TOTAL_CLASS\n for out_total in self.subtotal_columns[level + 1:]:\n caption = f\"{caption} {self.previous_values[out_total]}\"\n show_class = SUB_TOTAL_CLASS\n\n self.subtotals[column][self.display_total_column] = caption\n self.output_row_to_table(\n self.subtotals[column], show_class,\n )\n if show_grand_total:\n self.subtotals[GRAND_TOTAL_ROW][\n self.display_total_column\n ] = \"Total Managed Expenditure\"\n self.output_row_to_table(self.subtotals[GRAND_TOTAL_ROW], GRAND_TOTAL_CLASS)\n\n return self.result_table\n\n\nclass PivotManager(models.Manager):\n \"\"\"Managers returning the data in Monthly figures pivoted\"\"\"\n\n def pivot_data(self, columns, filter_dict={}, year=0, order_list=[]):\n if year == 0:\n year = get_current_financial_year()\n\n q1 = (\n self.get_queryset()\n .filter(financial_year=year, **filter_dict)\n .order_by(*order_list)\n )\n pivot_data = pivot(\n q1, columns, \"financial_period__period_short_name\", \"amount\",\n )\n return pivot_data\n\n\nclass DisplaySubTotalManager(models.Manager):\n \"\"\"Managers returning the actual/forecast/budget data\n in a format suitable for display\"\"\"\n\n def subtotal_data(\n self,\n display_total_column,\n subtotal_columns,\n data_columns,\n filter_dict={},\n year=0,\n order_list=[],\n show_grand_total=True,\n ):\n # If requesting a subtotal, the\n # list of columns must be specified\n if not subtotal_columns:\n raise SubTotalFieldNotSpecifiedError(\"Sub-total field not specified\")\n\n correct = True\n error_msg = \"\"\n for elem in subtotal_columns:\n if elem not in [*data_columns]:\n correct = False\n error_msg += f\"'{elem}', \"\n if not correct:\n raise SubTotalFieldDoesNotExistError(\n f\"Sub-total column(s) {error_msg} not found.\"\n )\n\n if display_total_column not in [*data_columns]:\n raise SubTotalFieldDoesNotExistError(\n f\"Display sub-total column '{display_total_column}' \"\n f\"does not exist in provided columns: '{[*data_columns]}'.\"\n )\n\n data_returned = self.raw_data_annotated(\n data_columns, filter_dict, year, order_list\n )\n raw_data = list(data_returned)\n if not raw_data:\n return []\n r = SubTotalForecast(raw_data)\n return r.calculate_subtotal_data(\n display_total_column, subtotal_columns, show_grand_total,\n )\n\n def raw_data_annotated(\n self, columns, filter_dict={}, year=0, order_list=[], include_zeros=False\n ):\n annotations = {\n budget_field: Sum(\"budget\"),\n \"Apr\": Sum(\"apr\"),\n \"May\": Sum(\"may\"),\n \"Jun\": Sum(\"jun\"),\n \"Jul\": Sum(\"jul\"),\n \"Aug\": Sum(\"aug\"),\n \"Sep\": Sum(\"sep\"),\n \"Oct\": Sum(\"oct\"),\n \"Nov\": Sum(\"nov\"),\n \"Dec\": Sum(\"dec\"),\n \"Jan\": Sum(\"jan\"),\n \"Feb\": Sum(\"feb\"),\n \"Mar\": Sum(\"mar\"),\n \"Adj1\": Sum(\"adj1\"),\n \"Adj2\": Sum(\"adj2\"),\n \"Adj3\": Sum(\"adj3\"),\n outturn_field: Sum(\n F(\"apr\")\n + F(\"may\")\n + F(\"jun\")\n + F(\"jul\")\n + F(\"aug\")\n + F(\"sep\")\n + F(\"oct\")\n + F(\"nov\")\n + F(\"dec\")\n + F(\"jan\")\n + F(\"feb\")\n + F(\"mar\")\n + F(\"adj1\")\n + F(\"adj2\")\n + F(\"adj3\")\n ),\n outturn_variance_field: Sum(\n F(\"apr\")\n + F(\"may\")\n + F(\"jun\")\n + F(\"jul\")\n + F(\"aug\")\n + F(\"sep\")\n + F(\"oct\")\n + F(\"nov\")\n + F(\"dec\")\n + F(\"jan\")\n + F(\"feb\")\n + F(\"mar\")\n + F(\"adj1\")\n + F(\"adj2\")\n + F(\"adj3\")\n - F(\"previous_outturn\")\n ),\n \"Previous_outturn\": Sum(\"previous_outturn\"),\n }\n # Lines with 0 values across the year have no year specified:\n # they come from an outer join in the query.\n # So use financial_year = NULL to filter them in or out.\n\n if include_zeros:\n year_filter = Q(financial_year=year) | Q(financial_year__isnull=True)\n else:\n year_filter = Q(financial_year=year)\n\n # Current must NOT use year in query as this kills query performance\n if year == 0 or year == get_current_financial_year():\n raw_data = (\n self.get_queryset()\n .values(*columns)\n .filter(\n **filter_dict,\n )\n .annotate(**annotations)\n .order_by(*order_list)\n )\n else:\n # Get previous year from cache if possible\n query_key = f'{self.model._meta.db_table}_{str(columns)}_{str(filter_dict)}_{str(year)}' # noqa\n key_slug = slugify(query_key)\n cache_key = hashlib.md5(str.encode(key_slug)).hexdigest()\n try:\n raw_data = cache.get(cache_key)\n\n if raw_data:\n return raw_data\n except: # noqa E722\n pass\n\n raw_data = (\n self.get_queryset()\n .values(*columns)\n .filter(\n year_filter,\n **filter_dict,\n )\n .annotate(**annotations)\n .order_by(*order_list)\n )\n # 7 day cache period\n cache_invalidation_time = 7 * 24 * 60 * 60\n try:\n cache.set(\n cache_key,\n raw_data,\n cache_invalidation_time,\n )\n except: # noqa E722\n pass\n\n return raw_data\n\n\n# Does not inherit from BaseModel as it maps to database view\nclass ForecastingDataViewAbstract(models.Model):\n \"\"\"Used for joining budgets and forecast.\n The view adds rows with 0 values across the year (zero-values rows),\n to be consistent with the Edit Forecast logic.\n The zero-values rows have a null value for the year,\n because the year is linked to the figures, and they have none!\n Mapped to a view in the database, because\n the query is too complex\"\"\"\n\n id = models.IntegerField(primary_key=True,)\n financial_code = models.ForeignKey(FinancialCode, on_delete=models.DO_NOTHING,)\n financial_year = models.IntegerField()\n budget = models.BigIntegerField(default=0)\n apr = models.BigIntegerField(default=0)\n may = models.BigIntegerField(default=0)\n jun = models.BigIntegerField(default=0)\n jul = models.BigIntegerField(default=0)\n aug = models.BigIntegerField(default=0)\n sep = models.BigIntegerField(default=0)\n oct = models.BigIntegerField(default=0)\n nov = models.BigIntegerField(default=0)\n dec = models.BigIntegerField(default=0)\n jan = models.BigIntegerField(default=0)\n feb = models.BigIntegerField(default=0)\n mar = models.BigIntegerField(default=0)\n adj1 = models.BigIntegerField(default=0)\n adj2 = models.BigIntegerField(default=0)\n adj3 = models.BigIntegerField(default=0)\n previous_outturn = models.BigIntegerField(default=0, blank=True, null=True,)\n objects = models.Manager() # The default manager.\n view_data = DisplaySubTotalManager()\n\n class Meta:\n abstract = True\n\n\nclass ForecastingDataView(ForecastingDataViewAbstract):\n # The view is created by a migration. Its code is at the bottom of this file.\n class Meta:\n managed = False\n db_table = \"forecast_forecast_download_view\"\n\n\nclass MonthlyFigureAbstract(BaseModel):\n \"\"\"It contains the forecast and the actuals.\n The current month defines what is Actual and what is Forecast\"\"\"\n\n amount = models.BigIntegerField(default=0) # stored in pence\n id = models.AutoField(primary_key=True)\n financial_year = models.ForeignKey(FinancialYear, on_delete=models.PROTECT,)\n financial_period = models.ForeignKey(\n FinancialPeriod,\n on_delete=models.PROTECT,\n related_name=\"%(app_label)s_%(class)ss\",\n )\n financial_code = models.ForeignKey(\n FinancialCode,\n on_delete=models.PROTECT,\n related_name=\"%(app_label)s_%(class)ss\",\n )\n objects = models.Manager() # The default manager.\n pivot = PivotManager()\n\n # TODO don't save to month that have actuals\n class Meta:\n abstract = True\n\n def __str__(self):\n return (\n f\"{self.financial_code.cost_centre}\"\n f\"--{self.financial_code.programme}\"\n f\"--{self.financial_code.natural_account_code}\"\n f\"--{self.financial_code.analysis1_code}\"\n f\"--{self.financial_code.analysis2_code}\"\n f\"--{self.financial_code.project_code}:\"\n f\"{self.financial_year} \"\n f\"{self.financial_period} \"\n f\"{self.amount}\"\n )\n\n\nclass ForecastMonthlyFigure(MonthlyFigureAbstract):\n starting_amount = models.BigIntegerField(default=0)\n # If archived_status is null, the record is the current one.\n # Because EndOfMonthStatus uses FinancialPeriod,\n # it cannot be imported from the end_of_month models: it gives\n # a circular reference and several errors.\n archived_status = models.ForeignKey(\n \"end_of_month.EndOfMonthStatus\",\n on_delete=models.PROTECT,\n related_name=\"%(app_label)s_%(class)ss\",\n blank=True,\n null=True,\n )\n\n class Meta:\n constraints = [\n UniqueConstraint(\n fields=[\n \"financial_code\",\n \"financial_year\",\n \"financial_period\",\n \"archived_status\",\n ],\n name=\"ForecastMonthlyFigure_unique1\",\n condition=Q(archived_status__isnull=False),\n ),\n UniqueConstraint(\n fields=[\"financial_code\", \"financial_year\", \"financial_period\", ],\n name=\"ForecastMonthlyFigure_unique2\",\n condition=Q(archived_status__isnull=True),\n ),\n ]\n\n\nclass ActualUploadMonthlyFigure(MonthlyFigureAbstract):\n class Meta:\n constraints = [\n UniqueConstraint(\n fields=[\"financial_code\", \"financial_year\", \"financial_period\", ],\n name=\"ActualUploadMonthlyFigure_unique1\",\n ),\n ]\n\n\nclass BudgetMonthlyFigure(MonthlyFigureAbstract):\n \"\"\"Used to store the budgets\n for the financial year.\"\"\"\n\n starting_amount = models.BigIntegerField(default=0)\n # If archived_status is null, the record is the current one.\n # Because EndOfMonthStatus uses FinancialPeriod,\n # it cannot be imported from the end_of_month models: it gives\n # a circular reference and several errors.\n archived_status = models.ForeignKey(\n \"end_of_month.EndOfMonthStatus\",\n on_delete=models.PROTECT,\n related_name=\"%(app_label)s_%(class)ss\",\n blank=True,\n null=True,\n )\n\n class Meta:\n constraints = [\n UniqueConstraint(\n fields=[\n \"financial_code\",\n \"financial_year\",\n \"financial_period\",\n \"archived_status\",\n ],\n name=\"BudgetMonthlyFigure_unique1\",\n condition=Q(archived_status__isnull=False),\n ),\n UniqueConstraint(\n fields=[\"financial_code\",\n \"financial_year\",\n \"financial_period\",\n ],\n name=\"BudgetMonthlyFigure_unique2\",\n condition=Q(archived_status__isnull=True),\n ),\n ]\n\n\nclass BudgetUploadMonthlyFigure(MonthlyFigureAbstract):\n class Meta:\n constraints = [\n UniqueConstraint(\n fields=[\"financial_code\",\n \"financial_year\",\n \"financial_period\",\n ],\n name=\"BudgetUploadMonthlyFigure_unique1\",\n ),\n ]\n","sub_path":"forecast/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":33859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"538942202","text":"__author__ = 'ssm'\n\nimport numpy as np\nfrom collections import defaultdict\nfrom sklearn.metrics.pairwise import cosine_distances\n\n'''\ninput: keywords + weights + centroids\noutput: the possible area (index of centroids)\n\nfor each kw:\n\tfor each centroid:\n\t\tget dist(kw, centroid)\n\t\tdist -> score\n\t\trecord += weight * score\n'''\n\ndef softmax_score(l):\n return np.exp(l) / np.sum(np.exp(l), axis=0)\n\ndef transform(base, d, roof, r):\n return (roof-d)/(r*base)\n\ndef calculate_scores(distances):\n r = 1#0.5\n base = distances[0][1]\n delta_list = [d-base for (i,d) in distances]\n roof = delta_list[-1]\n final = [transform(base, d, roof, r) for d in delta_list]\n #print(\"final {}\".format(final))\n return softmax_score(final)\n\ndef get_scores(vec, centroids):\n dist = []\n for idx, c in enumerate(centroids):\n #dis = np.linalg.norm(np.array(vec)-np.array(c))\n dis = cosine_distances([vec], [c])\n dist.append((idx, dis))\n sorted_dis = sorted(dist, key=lambda a: a[1])\n top_dis = sorted_dis[:5]\n #print(\"top dis {}\".format(top_dis))\n scores = calculate_scores(top_dis)\n indices = [i for (i,d) in top_dis[:len(scores)]]\n #print(\"scores {}\".format(scores))\n\n return list(scores), indices\n\ndef area_score(vecs, weights, centroids):\n '''\n :param vecs: keyword vecs\n :param weights: weights\n :param centroids: centroids\n :return: centroid index\n '''\n record = defaultdict(float)\n for vi in range(len(vecs)):\n #get scores of vi to nearest m centroids\n scores, indices = get_scores(vecs[vi], centroids)\n if scores is None:\n continue\n for idx in range(len(scores)):\n record[indices[idx]] += weights[vi]*scores[idx]\n sorted_record = sorted(record.items(), key=lambda a:a[1], reverse=True)\n #print(\"record {}\".format(record))\n #print(\"weights {}\".format(weights))\n #exit()\n return sorted_record\n","sub_path":"classify/area_score.py","file_name":"area_score.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"346047699","text":"#!/usr/bin/env python\n#\n# Reads all header files for SDK and project and saves protocol definitions to disk.\n#\n\nimport os\nimport subprocess\n\nfrom norlinter.parser.io import get_cache_dir, is_c_header, append_protocol_cache, clean_protocol_cache, get_protocols\n\nSDK_PATH = \"/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks/\"\n\ndef cache_dir(group, filepath):\n cache_path = os.path.join(get_cache_dir(), group)\n clean_protocol_cache(cache_path)\n # Find header files in filepath\n files = subprocess.check_output([\"find\", filepath, \"-name\", \"*.h\"])\n # Read and cache all protocols for each header file\n for _file in files.split(\"\\n\"):\n if len(_file.strip()) == 0: continue\n try:\n if not is_c_header(_file):\n protocols = get_protocols(_file)\n append_protocol_cache(cache_path, protocols)\n else:\n print(\"Excluding C header: {}\".format(_file))\n except Exception as exc:\n print(\"Failed to get protocols for file: {}\".format(os.path.join(filepath, _file)))\n raise\n\ndef cache_project(filepath):\n if not os.path.isdir(args.project):\n raise Exception(\"Project does not exist at path {}\".format(args.project))\n cache_dir(os.path.basename(filepath.rstrip(\"/\")), filepath)\n\ndef cache_sdk(sdkpath):\n if not os.path.isdir(sdkpath):\n raise Exception(\"SDK does not exist at path {}\".format(args.project))\n cache_dir(\"ios_sdk\", sdkpath)\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description=\"objclint - Cache SDK and project header protocol definitions\")\n parser.add_argument('--project', help=\"Path to project header path.\")\n parser.add_argument('--cache-sdk', action=\"store_true\", help=\"The version of cocos to clean. Version must be in the format of #.#.# (e.g. 1.0.4)\")\n\n args = parser.parse_args()\n\n if args.project:\n cache_project(args.project)\n if args.cache_sdk:\n cache_sdk(SDK_PATH)\n","sub_path":"norlinter/source/cache_headers.py","file_name":"cache_headers.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"275870363","text":"# !/usr/bin/python\n# -*- coding:utf-8 -*-\n\"\"\"\n作者:wangyuxiang\n创建时间:2018/7/12 下午10:41\nIDE:PyCharm\n描述:\n目前只能插入,满足数据库表字段格式为'DEFAULT NULL'的数据\ndict_to_mysql有个坑:\n0\n1、如果dict的values是None的话,会插入失败,因此需要把None替换为''\n2、有的爬出来,dict的values不是None,而是空格,不考虑此情况也会失败,因此需要去除空格\n3、数据库字段如果不是char、vchar字段的,会插入失败,后优化把第一点的None替换为'',改为None替换为NULL\n4、数据库字段如果是NOT NULL DEFAULT '0',会插入失败(目前还没有解决)\n\"\"\"\nfrom support.common.connect_mysql.connect_mysql_and_query import localhost_insert_or_update\n\ndef dict_to_mysql(table_name, insert_data_dict, column_name_dict):\n \"\"\"\n 字典,json插入mysql\n :param table_name: 表名\n :param insert_data_dict: 待插入的数据的dict\n :param column_name_dict: 插入的表的字段名dict\n :return:\n \"\"\"\n column_name = ''\n for i in column_name_dict:\n if column_name != '':\n column_name = column_name + ',' + column_name.join(i.values())\n else:\n column_name = column_name + column_name.join(i.values())\n\n cols = ', '.join(insert_data_dict.values())\n sql = \"INSERT INTO %s (%s) VALUES (%s)\" % (table_name, column_name, cols)\n localhost_insert_or_update(sql)\n\ndef replace_dict_none_to_null(my_dict):\n for key in my_dict:\n if my_dict[key].strip() != '':\n None\n else:\n my_dict[key] = 'NULL'\n return my_dict","sub_path":"support/common/others/dict_to_mysql.py","file_name":"dict_to_mysql.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"397206486","text":"\"\"\"\n Script for extended ascii vigenere\n\"\"\"\n\ndef padd_key(key, seq_input):\n \"\"\"\n Input :\n key : Key of the vigenere algorithm\n plaintext : list of bytes/char\n Output :\n padded key as sequence of bytes\n \"\"\"\n pad_len = len(seq_input) - len(key)\n j = 0 #index of key\n output = [c for c in key]\n for i in range(pad_len):\n output += key[j]\n j += 1\n if (j == len(key)):\n j = 0\n return output\n\nclass Vigenere_Ascii:\n \"\"\"\n Vigenere Ascii Class\n \"\"\"\n def encrypt(self, key, plaintext):\n \"\"\"\n This function will return ciphertext of the plain ascii Text in char\n Input : Sequence of ASCII bytes\n output : Encrypted sequence of ascii bytes in char\n \"\"\"\n output = []\n padded_key = padd_key(key, plaintext)\n for i in range(len(plaintext)):\n enc_ascii = (ord(plaintext[i]) + ord(padded_key[i])) % 256\n output.append(chr(enc_ascii))\n return ''.join(output)\n\n\n def decrypt(self, key, encrypted):\n \"\"\"\n This function will return decrypted text\n Input :\n key : Key string\n encrypted_txt : encrypted string\n Output :\n decrypted string\n \"\"\"\n output = []\n padded_key = padd_key(key, encrypted)\n for i in range(len(encrypted)):\n dec_ascii = (ord(encrypted[i]) - ord(padded_key[i])) % 256\n output.append(chr(dec_ascii))\n return ''.join(output)\n","sub_path":"vigenere_ascii.py","file_name":"vigenere_ascii.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"302472362","text":"from tkinter import *\nfrom tkinter import messagebox\nimport pymysql as pm\n\nroot = Tk()\nroot.geometry('700x700')\nroot.title('Note Taking App')\n\n#database\ntry:\n con = pm.connect(host='localhost', database='project', user='root',password='oggy123')\n cursor = con.cursor()\n query1 = 'create table note_making(note_title varchar(40) primary key,notes varchar(1000))'\n cursor.execute(query1)\n \n\n #functions\n\n #function for adding new notes\n def add_new_notes():\n top1 = Toplevel()\n top1.title('Adding notes')\n top1.geometry('550x550')\n \n l2 = Label(top1,text = 'NOTES TITLE')\n l2.place(x = 5,y = 5)\n e2 = Entry(top1,width = 30,font = ('calibri',15))\n e2.place(x = 5,y = 25)\n\n l3 = Label(top1,text = 'NOTES')\n l3.place(x = 5,y = 70)\n\n s2=Scrollbar(top1)\n s2.place(x = 430,y =90)\n s4 = Scrollbar(top1)\n t2 = Text(top1,height = 20,wrap = NONE,width = 50,xscrollcommand = s4.set,yscrollcommand = s2.set)\n s2.config(command = t2.yview)\n s4.config(command = t2.xview,orient = HORIZONTAL)\n t2.place(x = 5,y = 90)\n s4.place(x = 5,y =425)\n \n\n \n def add_to_database():\n try:\n if len(e2.get())!=0:\n if (len(t2.get(\"1.0\", \"end-1c\"))==0):\n temp = messagebox.askokcancel(\"WARNING!\",\"No content is added to %s note\"%(e2.get()))\n if temp:\n cursor.execute(\" INSERT INTO note_making VALUES (%s,%s) \", (e2.get(),t2.get(\"1.0\",END)))\n con.commit()\n e2.delete(0,'end')\n t2.delete(\"1.0\",END)\n messagebox.showinfo(\"Congratulations!!\",\"Your Note is added succeessfully\")\n \n else:\n sol = messagebox.askyesno(\"QUESTION!\",\"Do you want to add another?\")\n if sol:\n add_new_notes()\n \n else:\n cursor.execute(\" INSERT INTO note_making VALUES (%s,%s) \", (e2.get(),t2.get(\"1.0\",END)))\n con.commit()\n e2.delete(0,'end')\n t2.delete(\"1.0\",END)\n l4 = Label(top1,text = 'Data is inserted successfully')\n l4.place(x = 100,y = 500)\n else:\n messagebox.showinfo(\"EMPTY TITLE!!\",\"You have not given any title to your notes.\\nNotes without title cannot be added.\")\n except Exception as e:\n messagebox.showinfo(\"DUPLICATE NOTES\",\"Note with this name %s already exists.Try giving a new name. \"%(e2.get()))\n \n b4 = Button(top1,text = 'ADD',bg = 'green',width = 20,command = add_to_database)\n b4.place(x = 200,y = 440)\n\n b5 = Button(top1,text = 'Exit',bg = 'red',width = 15,command = top1.destroy)\n b5.place(x = 380,y = 440)\n\n\n #function to list all notes\n def list_notes():\n query3 = 'select note_title from note_making order by note_title asc'\n rows_count = cursor.execute(query3)\n t1.config(state=NORMAL)\n t4.config(state=NORMAL)\n t1.delete(\"1.0\",END)\n t4.delete(\"1.0\",END)\n \n if rows_count>0:\n t4.insert(END,\"ALL NOTES--\")\n data1 = cursor.fetchall()\n for row in data1:\n t1.insert(END,row[0]+'\\n')\n \n else:\n messagebox.showinfo(\"Failure\",\"There are no notes present.\")\n t1.config(state=DISABLED) \n \n #function to update notes\n def update_notes():\n top2 = Toplevel()\n top2.title('Updating notes')\n top2.geometry('550x550')\n \n l5 = Label(top2,text = 'NOTES TITLE')\n l5.place(x = 5,y = 5)\n e3 = Entry(top2,width = 30,font = ('calibri',15))\n e3.place(x = 5,y = 25)\n\n l6 = Label(top2,text = 'NOTES')\n l6.place(x = 5,y = 70)\n\n s3=Scrollbar(top2)\n s3.place(x = 430,y =90)\n t3 = Text(top2,height = 20,width = 50,yscrollcommand = s3.set)\n s3.config(command = t3.yview)\n t3.place(x = 5,y = 90)\n\n\n def update_to_database():\n rows_count = cursor.execute(\"\"\"UPDATE note_making SET notes=%s WHERE note_title=%s\"\"\",(t3.get(\"1.0\",END),e3.get()))\n con.commit()\n \n if rows_count>0:\n l7 = Label(top2,text = 'successfully updated notes',width = 50)\n l7.place(x = 150,y = 480)\n else:\n l7 = Label(top2,text = 'There is no notes found as titled %s'%(e3.get()),width = 50)\n l7.place(x = 150,y = 480)\n\n t3.delete(\"1.0\",END)\n e3.delete(0,'end')\n\n b8 = Button(top2,text = 'Save New Changes',bg = 'blue',width = 20,command = update_to_database)\n b8.place(x = 150,y = 440)\n\n def view_notes():\n rows_count = cursor.execute(\"select notes from note_making where note_title=%s\",(e3.get()))\n if rows_count>0:\n data1 = cursor.fetchall()\n for row in data1:\n t3.insert(END,row[0])\n else:\n l7 = Label(top2,text = 'There are no existing notes titled %s'%(e3.get()),width = 50)\n l7.place(x = 150,y = 480)\n \n \n b10 = Button(top2,text = 'Change in existing file',command = view_notes)\n b10.place(x = 300,y = 25)\n\n\n b9 = Button(top2,text = 'Exit',bg = 'red',width = 15,command = top2.destroy)\n b9.place(x = 380,y = 440)\n\n\n #function to delete notes\n def delete_notes():\n top3 = Toplevel()\n top3.geometry('400x150')\n l8 = Label(top3,text = \"Which note you want to delete?\")\n l8.place(x = 5,y = 5)\n e4 = Entry(top3,width = 30,font = ('calibri',15))\n e4.place(x = 5,y = 30)\n\n def delete_from_database():\n result = messagebox.askokcancel(\"Delete Notes\",\"Are you sure you want to delete this note?\")\n if result:\n rows_count = cursor.execute(\"\"\" DELETE from note_making WHERE note_title=%s\"\"\",(e4.get()))\n con.commit()\n if rows_count>0:\n messagebox.showinfo(\"Success\",\"Notes with title %s are deleted succeessfully\"%(e4.get()))\n else:\n if(len(e4.get())!=0):\n messagebox.showinfo(\"Failure\",\"There are no notes having title %s\"%(e4.get()))\n else:\n messagebox.showinfo(\"OOPS!!\",\"Nothing to delete.\")\n\n \n def deleteall_from_database():\n result = messagebox.askokcancel(\"Delete All Notes\",\"Are you sure you want to delete all the available notes ?\")\n if result:\n rows_count = cursor.execute(\"\"\" DELETE from note_making \"\"\")\n con.commit()\n if rows_count>0:\n messagebox.showinfo(\"Success\",\"All Notes were deleted succeessfully\")\n else:\n messagebox.showinfo(\"Failure\",\"There are no notes present.\")\n \n b9 = Button(top3,text = 'DELETE',width = 17,command = delete_from_database)\n b9.place(x =20,y=70)\n\n b11 = Button(top3,text = 'DELETE All',width = 17,bg = 'red',command = deleteall_from_database)\n b11.place(x =180,y=70)\n\n\n #function to search notes\n def search_notes():\n if(len(e1.get())==0):\n messagebox.showinfo(\"OOPS!!\",\"Nothing to search\")\n else:\n rows_count = cursor.execute(\"\"\"SELECT * from note_making WHERE note_title=%s\"\"\",(e1.get()))\n t1.config(state=NORMAL)\n t4.config(state=NORMAL)\n t1.delete('1.0',END)\n t4.delete('1.0',END)\n e1.delete(0,'end')\n if rows_count > 0:\n rs = cursor.fetchall()\n for row in rs:\n t1.insert(END,row[1])\n if(len(t1.get(\"1.0\", \"end-1c\"))==1):\n messagebox.showinfo(\"EMPTY\",row[0]+\" is empty.\")\n else:\n t4.insert(END,\"NOTES TITLE: \"+row[0])\n\n else:\n messagebox.showinfo(\"ERROR\",'no results found')\n t1.config(state=DISABLED)\n \n\n ####MAIN WINDOW WIDGETS####\n \n\n #button for adding new notes\n b1 = Button(root,text='Add New Note>>',height = 2,width = 30,bg ='orange',foreground='white',font=('calibri', 10, 'bold'))\n b1.config(command = add_new_notes)\n b1.place(anchor='nw', x=20,y=20)\n\n #button for listing all notes\n b2 = Button(root,text='List All Notes>>',height = 2,width = 30,bg ='orange',foreground='white',font=('calibri', 10, 'bold'),command = list_notes)\n b2.place(x=320,y =20)\n\n #button for updating notes\n b6 = Button(root,text = 'Update Notes>>',height = 2,width = 30,bg ='orange',foreground='white',font=('calibri', 10, 'bold'),command =update_notes)\n b6.place(x = 20,y = 70)\n\n #button for deleting notes\n b7 = Button(root,text = 'Delete Notes>>',height = 2,width = 30,bg ='red',foreground='white',font=('times', 10, 'bold'),command =delete_notes)\n b7.place(x = 320,y = 70)\n \n\n l1 = Label(root,text = 'Search Notes',font = ('calibri',20,'bold'))\n l1.place(x = 20, y = 135)\n\n #entry box for searching notes\n large_font = ('calibri',15)\n e1 = Entry(root,width = 40,font = large_font)\n e1.place(x = 20,y = 185)\n\n b3 = Button(root,text='Search',height = 1,width = 15,bg ='orange',foreground='white',font=('calibri', 10, 'bold'))\n b3.config(command = search_notes)\n b3.place(x=430,y =185)\n\n l2 = Label(root,text = '--Notes--',font = ('calibri',15,'bold'))\n l2.place(x = 250,y = 250)\n\n #text box to view heading\n t4 = Text(root,height = 2,width = 70,bg = 'green',state=DISABLED)\n t4.place(x = 0,y =280)\n \n\n #text box to view notes\n s1=Scrollbar(root)\n s1.place(x = 570,y =320)\n s5 = Scrollbar(root,orient = HORIZONTAL)\n t1 = Text(root,wrap = NONE,height = 20,width = 70,bg = 'green',state=DISABLED,yscrollcommand = s1.set,xscrollcommand = s5.set)\n s1.config(command = t1.yview)\n s5.config(command = t1.xview)\n s5.place(x = 0,y = 640)\n t1.place(x = 0,y = 320)\n\n root.mainloop()\n\n \n \nexcept pm.DatabaseError as e:\n if con:\n con.rollback()\n print(\"problem\",e)\nfinally:\n cursor.close()\n con.close()\n","sub_path":"Note-Making.py","file_name":"Note-Making.py","file_ext":"py","file_size_in_byte":10608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"373289010","text":"import critter\nimport critter_main\nimport collections\nimport color\nimport inspect\nimport random\nimport os\nimport pprint\n\n# some constants to help us\nATTACK_DAMAGE = 25\nHEAL_RESTORE = 50\nDEFEND_KARMA = 1\nPARTY_KARMA = 3\nHEAL_KARMA = 5\nATTACK_PARTY_KARMA = -PARTY_KARMA\nATTACK_HEAL_KARMA = -HEAL_KARMA\n\n# Just an (x, y) pair, but more readable.\nPoint = collections.namedtuple('Point', ['x', 'y'])\n\n# Again, we don't really need a whole class just to store this info.\nCritterInfo = collections.namedtuple('CritterInfo', ['x', 'y', 'width', 'height', 'char', 'color', 'getNeighbor', 'getNeighborHealth'])\n\nclass CritterModel():\n \"\"\"\n The main Critter simulation. Takes care of all the logic of\n Critter interactions.\n \"\"\"\n \n def __init__(self, width, height, list_lock):\n self.width = width\n self.height = height\n self.critters = []\n self.move_count = 0\n # A map of critters to (x, y) positions.\n self.critter_positions = {}\n # A map of critter classes to the number alive of that class.\n self.critter_class_states = {}\n self.grid = [[None for x in range(height)] for y in range(width)]\n # Make sure nothing bad happens due to concurrent list access.\n self.list_lock = list_lock\n\n def add(self, critter, num):\n \"\"\"\n Adds a particular critter type num times. The critter should\n be a class, not an instantiated critter.\n \"\"\"\n if critter not in self.critter_class_states:\n self.critter_class_states[critter] = ClassInfo(initial_count=num)\n self.critter_class_states[critter].alive += num\n self.critter_class_states[critter].health += num * 100\n for i in range(num):\n args = CritterModel.create_parameters(critter)\n c = critter(*args)\n self.critters.append(c)\n pos = self.random_location()\n self.critter_positions[c] = pos\n self.grid[pos.x][pos.y] = c\n \n def reset(self, num_critters):\n '''\n Resets the model, clearing out the whole board and\n repopulating it with num_critters of the same Critter types.\n '''\n self.grid = [[None for x in range(self.height)] for y in range(self.width)]\n self.critter_positions = {}\n self.critters = []\n self.move_count = 0\n new_states = {}\n for critter_class in self.critter_class_states.keys():\n new_states[critter_class] = ClassInfo(initial_count=num_critters)\n new_states[critter_class].alive += num_critters\n for i in range(num_critters):\n args = CritterModel.create_parameters(critter_class)\n c = critter_class(*args)\n self.critters.append(c)\n pos = self.random_location()\n self.critter_positions[c] = pos\n self.grid[pos.x][pos.y] = c\n self.critter_class_states = new_states\n\n def update(self):\n \"\"\"\n Takes care of updating all Critters. For each Critter, it\n firsts moves. If the position it moves to is occupied, the two\n critters interact. If one runs out of health, it loses and is removed\n and the other moves into the position.\n \"\"\"\n self.move_count += 1\n random.shuffle(self.critters)\n # Unclean while loop, because we'll be removing any losing critters\n # as we iterate through the list.\n i = 0\n l = len(self.critters)\n while i < l:\n critter1 = self.critters[i]\n # Move the critter\n old_position = self.critter_positions[critter1]\n direction = critter1.getMove(CritterInfo(old_position.x, old_position.y,\n self.width, self.height,\n critter1.getChar(),\n critter1.getColor(),\n self.get_neighbor_func(old_position),\n self.get_neighbor_health_func(old_position)))\n\n CritterModel.verify_move(direction)\n position = self.move(direction, old_position)\n\n # Interact, if necessary\n winner = critter1\n loser = None\n critter2 = self.grid[position.x][position.y]\n if critter2 and position != old_position and critter1 != critter2: # Save each stone from fighting itself\n winner = self.interact(critter1, critter2)\n\n # NOTE: most updates happen in interact method called above\n # such as health and karma\n\n loser = critter1 if winner == critter2 else critter2\n\n # here, we remove a critter if it no longer has health\n if loser.health <= 0:\n self.critter_positions[winner] = position\n\n # Get the loser out of here\n with self.list_lock:\n index = self.critters.index(loser)\n if index <= i:\n # the loser was earlier in the list, so the\n # winner's index decreases\n i -= 1\n\n \n self.critter_positions.pop(loser)\n self.critters.remove(loser)\n l -= 1 # we have one fewer total critter\n\n # Make sure we've got an accurate kill/alive count\n self.critter_class_states[loser.__class__].alive -= 1\n self.critter_class_states[winner.__class__].kills += 1\n\n # this loser no longer exists\n loser = None\n \n # Update positions\n self.grid[old_position.x][old_position.y] = loser\n self.grid[position.x][position.y] = winner\n self.critter_positions[winner] = position\n if loser is not None:\n self.critter_positions[loser] = old_position\n \n i += 1\n \n def move(self, direction, pos):\n \"\"\"\n Returns the new position after moving in direction. This\n assumes that (0, 0) is the top-left.\n \"\"\"\n if direction == critter.NORTH:\n return Point(pos.x, (pos.y - 1) % self.height)\n elif direction == critter.SOUTH:\n return Point(pos.x, (pos.y + 1) % self.height)\n elif direction == critter.EAST:\n return Point((pos.x + 1) % self.width, pos.y)\n elif direction == critter.WEST:\n return Point((pos.x - 1) % self.width, pos.y)\n elif direction == critter.NORTHEAST:\n return Point((pos.x + 1) % self.width, (pos.y - 1) % self.height)\n elif direction == critter.NORTHWEST:\n return Point((pos.x - 1) % self.width, (pos.y - 1) % self.height)\n elif direction == critter.SOUTHWEST:\n return Point((pos.x + 1) % self.width, (pos.y + 1) % self.height)\n elif direction == critter.SOUTHEAST:\n return Point((pos.x - 1) % self.width, (pos.y + 1) % self.height)\n else:\n return pos\n \n def interact(self, critter1, critter2):\n \"\"\"\n Force poor innocent Critters to interact and possibly risk death for\n the entertainment of Oberlin students. Returns the glorious\n victor.\n \"\"\"\n position = self.critter_positions[critter2]\n action1 = critter1.interact(CritterInfo(position.x, position.y,\n self.width, self.height,\n critter2.getChar(),\n critter2.getColor(),\n self.get_neighbor_func(position),\n self.get_neighbor_health_func(position)))\n position = self.critter_positions[critter1]\n action2 = critter2.interact(CritterInfo(position.x, position.y,\n self.width, self.height,\n critter1.getChar(),\n critter1.getColor(),\n self.get_neighbor_func(position),\n self.get_neighbor_health_func(position))) \n CritterModel.verify_action(action1)\n CritterModel.verify_action(action2)\n\n # did the first critter fight?\n fight1 = action1 == critter.ROAR or action1 == critter.SCRATCH or action1 == critter.POUNCE\n \n # did the second critter fight?\n fight2 = action2 == critter.ROAR or action2 == critter.SCRATCH or action2 == critter.POUNCE\n\n # find the \"winner\"\n critter2won = True\n\n if (fight1 and fight2): \n if (action1 == critter.ROAR and action2 == critter.SCRATCH or\n action1 == critter.SCRATCH and action2 == critter.POUNCE or\n action1 == critter.POUNCE and action2 == critter.ROAR):\n # critter 1 won\n \n # update critter 2's health\n critter2.health = max(0, critter2.health - ATTACK_DAMAGE)\n self.critter_class_states[critter2.__class__].health -= ATTACK_DAMAGE\n\n # update critter 1's karma\n critter1.karma += DEFEND_KARMA\n self.critter_class_states[critter1.__class__].karma += DEFEND_KARMA\n\n # update the winner\n critter2won = False\n elif action1 == action2:\n if random.random() > .5:\n # critter 1 won\n \n # update critter 2's health\n critter2.health = max(0, critter2.health - ATTACK_DAMAGE)\n self.critter_class_states[critter2.__class__].health -= ATTACK_DAMAGE\n \n # update critter 1's karma\n critter1.karma += DEFEND_KARMA\n self.critter_class_states[critter1.__class__].karma += DEFEND_KARMA\n\n # update the winner\n critter2won = False\n else:\n # critter 2 won\n \n # update critter 1's health\n critter1.health = max(0, critter1.health - ATTACK_DAMAGE)\n self.critter_class_states[critter1.__class__].health -= ATTACK_DAMAGE\n\n # update critter 2's karma\n critter2.karma += DEFEND_KARMA\n self.critter_class_states[critter2.__class__].karma += DEFEND_KARMA\n\n # update the winner\n critter2won = True\n else:\n # critter 2 won\n \n # update critter 1's health\n critter1.health = max(0, critter1.health - ATTACK_DAMAGE) \n self.critter_class_states[critter1.__class__].health -= ATTACK_DAMAGE\n\n # update critter 2's karma\n critter2.karma += DEFEND_KARMA\n self.critter_class_states[critter2.__class__].karma += DEFEND_KARMA\n\n # update the winner\n critter2won = True\n elif (fight1):\n # only critter 1 chose to fight, so they win by default\n\n # update critter2's health\n critter2.health = max(0, critter2.health - ATTACK_DAMAGE)\n self.critter_class_states[critter2.__class__].health -= ATTACK_DAMAGE\n \n if (action2 == critter.PARTY):\n # update critter1's karma\n critter1.karma += ATTACK_PARTY_KARMA\n self.critter_class_states[critter1.__class__].karma += ATTACK_PARTY_KARMA\n elif (action2 == critter.HEAL):\n critter1.karma += ATTACK_HEAL_KARMA\n self.critter_class_states[critter1.__class__].karma += ATTACK_HEAL_KARMA\n\n # update the winner\n critter2won = False\n elif (fight2):\n # only critter 2 chose to fight, so they win by default\n\n # update critter1's health\n critter1.health = max(0, critter1.health - ATTACK_DAMAGE)\n self.critter_class_states[critter1.__class__].health -= ATTACK_DAMAGE\n \n if (action1 == critter.PARTY):\n # update critter2's karma\n critter2.karma += ATTACK_PARTY_KARMA\n self.critter_class_states[critter2.__class__].karma += ATTACK_PARTY_KARMA\n elif (action1 == critter.HEAL):\n critter2.karma += ATTACK_HEAL_KARMA\n self.critter_class_states[critter2.__class__].karma += ATTACK_HEAL_KARMA\n\n # update the winner\n critter2won = True\n else:\n # did anyone try to heal?\n # note: nothing happens if you try to heal a critter\n # with perfect health\n if (action1 == critter.HEAL and critter2.health < 100):\n # update critter2's health\n oldHealth = critter2.health\n critter2.health = min(100, critter2.health + HEAL_RESTORE)\n self.critter_class_states[critter2.__class__].health += critter2.health - oldHealth\n\n # update critter1's karma\n critter1.karma += HEAL_KARMA\n self.critter_class_states[critter1.__class__].karma += HEAL_KARMA\n elif (action1 == critter.PARTY):\n # update critter1's karma\n critter1.karma += PARTY_KARMA\n self.critter_class_states[critter1.__class__].karma += PARTY_KARMA\n\n if (action2 == critter.HEAL and critter1.health < 100):\n # update critter1's health\n oldHealth = critter1.health\n critter1.health = min(100, critter1.health + HEAL_RESTORE)\n self.critter_class_states[critter1.__class__].health += critter1.health - oldHealth\n\n # update critter2's karma\n critter2.karma += HEAL_KARMA\n self.critter_class_states[critter2.__class__].karma += HEAL_KARMA\n elif (action2 == critter.PARTY):\n # update critter2's karma\n critter2.karma += PARTY_KARMA\n self.critter_class_states[critter2.__class__].karma += PARTY_KARMA\n \n # pick a winner at random\n critter2won = True\n if random.random() > .5:\n critter2won = False\n\n # alert the critters about the interaction\n critter1.interactionOver(not critter2won, action2)\n critter2.interactionOver(critter2won, action1)\n\n # return the \"winner\"\n if (critter2won):\n return critter2\n else:\n return critter1\n\n def verify_action(action):\n \"\"\"\n Make sure students are using the right actions. If not, throws\n an exception.\n \"\"\"\n if action not in (critter.ROAR, critter.POUNCE, critter.SCRATCH, critter.PARTY, critter.HEAL):\n raise ActionException(\"Critter action must be ROAR, POUNCE, SCRATCH, PARTY, or HEAL!\")\n \n def verify_move(move):\n \"Make sure they don't move diagonally.\"\n if move not in (critter.NORTH, critter.SOUTH, critter.EAST, critter.WEST, critter.CENTER):\n raise LocationException(\"Don't move diagonally! %s\" % move)\n\n def verify_location(location):\n \"\"\"\n Make sure students are using the right locations. If not,\n throws an exception.\n \"\"\"\n if location not in (critter.NORTH, critter.NORTHEAST, critter.NORTHWEST,\n critter.SOUTH, critter.SOUTHEAST, critter.SOUTHWEST,\n critter.EAST, critter.WEST, critter.CENTER):\n raise LocationException(\"That is not a real direction!\")\n\n def random_location(self):\n \"\"\"\n Calculate a random location for a Critter to be placed. This\n is not guaranteed to terminate by any means, but practically\n we (probably) don't need to be concerned.\n\n Returns a 2-tuple of integers.\n \"\"\"\n x = random.randint(0, self.width-1)\n y = random.randint(0, self.height-1)\n while self.grid[x][y] is not None:\n x = random.randint(0, self.width-1)\n y = random.randint(0, self.height-1)\n return Point(x, y)\n \n def create_parameters(critter):\n \"\"\"\n This is a bit funky. Because not all Critters take the same\n arguments in their constructor (for example, a Mouse gets a\n color while an Elephant gets an int), we need to check the\n classname and return appropriate things based on that. The\n Java version is a bit nicer because it has access to type\n information for each parameter, but c'est la vie.\n \n Return value is a tuple, which will be passed as *args to\n the critter's constructor.\n \"\"\"\n if critter.__name__ == 'Mouse':\n return (color.Color(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),)\n elif critter.__name__ == 'Elephant':\n return (random.randint(1, 15),)\n # No other class needs parameters\n else:\n return ()\n \n def get_neighbor_func(self, position):\n \"Returns the getNeighbor function for a particular position.\"\n def get_neighbor(direction):\n neighbor_pos = self.move(direction, position)\n neighbor = self.grid[neighbor_pos.x][neighbor_pos.y]\n #print( neighbor, type(neighbor) )\n return neighbor.__class__.__name__ if neighbor else '.'\n return get_neighbor\n\n def get_neighbor_health_func(self, position):\n \"Returns the getNeighborHealth function for a particular position.\"\n def get_neighbor_health(direction):\n neighbor_pos = self.move(direction, position)\n neighbor = self.grid[neighbor_pos.x][neighbor_pos.y]\n #print( neighbor, type(neighbor) )\n return neighbor.health if neighbor else 0\n return get_neighbor_health\n\n def results(self):\n \"\"\"\n Returns the critters in the simulation, sorted by karma\n results()[0] is (overall winner, karma of winner)\n \"\"\"\n return sorted(self.critter_class_states.items(),\n key=lambda state: -(state[1].karma))\n \n \nclass ClassInfo():\n \"\"\"\n This would be a named tuple, but they're immutable and that's\n somewhat unwieldy for this particular case.\n \"\"\"\n def __init__(self, kills=0, alive=0, initial_count=0, karma=0):\n self.kills = kills\n self.alive = alive\n self.count = initial_count\n self.health = 0\n self.karma = karma\n \n def __repr__(self):\n return '%s %s %s %s %s' % (self.kills, self.alive, self.count, self.health, self.karma)\n\n# These exceptions don't really need fancy names\nclass ActionException(Exception):\n pass\n\nclass LocationException(Exception):\n pass\n","sub_path":"CSCI_364_Labs/hw1-critters/critter_model.py","file_name":"critter_model.py","file_ext":"py","file_size_in_byte":19359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"282329197","text":"from __future__ import print_function\nimport torch\nimport torch.utils.data\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\nimport numpy as np\n\n\nclass VAE_CNN(nn.Module):\n def __init__(self, input_size=(1,28,28)):\n super(VAE_CNN, self).__init__()\n\n # input size\n self.input_size = input_size\n\n # Encoder\n self.conv1 = nn.Conv2d(self.input_size[0], 16, kernel_size=3, stride=1, padding=1) # (16, 28, 28)\n self.conv2 = nn.Conv2d(16, 32, kernel_size=2, stride=2, padding=0) # (32, 14, 14)\n self.conv3 = nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1) # (32, 14, 14)\n self.conv4 = nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1) # (32, 14, 14)\n self.fc1 = nn.Linear(14 * 14 * 32, 128)\n\n # Latent space\n self.fc21 = nn.Linear(128, 20)\n self.fc22 = nn.Linear(128, 20)\n\n # Decoder\n self.fc3 = nn.Linear(20, 128)\n self.fc4 = nn.Linear(128, 14 * 14 * 32)\n self.deconv1 = nn.ConvTranspose2d(32, 32, kernel_size=3, stride=1, padding=1)\n self.deconv2 = nn.ConvTranspose2d(32, 32, kernel_size=3, stride=1, padding=1)\n self.deconv3 = nn.ConvTranspose2d(32, 32, kernel_size=2, stride=2, padding=0)\n self.conv5 = nn.Conv2d(32, self.input_size[0], kernel_size=3, stride=1, padding=1)\n\n self.relu = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n\n def encode(self, x):\n out = self.relu(self.conv1(x))\n out = self.relu(self.conv2(out))\n out = self.relu(self.conv3(out))\n out = self.relu(self.conv4(out))\n out = out.view(out.size(0), -1)\n h1 = self.relu(self.fc1(out))\n return self.fc21(h1), self.fc22(h1)\n\n def reparameterize(self, mu, logvar):\n if self.training:\n std = logvar.mul(0.5).exp_()\n eps = Variable(std.data.new(std.size()).normal_())\n return eps.mul(std).add_(mu)\n else:\n return mu\n\n def decode(self, z):\n h3 = self.relu(self.fc3(z))\n out = self.relu(self.fc4(h3))\n out = out.view(out.size(0), 32, 14, 14)\n out = self.relu(self.deconv1(out))\n out = self.relu(self.deconv2(out))\n out = self.relu(self.deconv3(out))\n out = self.sigmoid(self.conv5(out))\n return out\n\n def forward(self, x):\n mu, logvar = self.encode(x)\n z = self.reparameterize(mu, logvar)\n return self.decode(z), mu, logvar\n\n def calculate_size(self, input_size, device='cuda'):\n x = torch.randn(input_size, device=device).unsqueeze(0)\n output = self.conv4(x)\n return output.size()[1:]","sub_path":"vae/VAE_CNN.py","file_name":"VAE_CNN.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"334872337","text":"\n ####################\n # PygameUtils.py #\n # by -=avokado0h=- #\n ####################\n\nimport pygame\n\nclass Colors():\n def __init__(self):\n self.white = pygame.Color('#ebdbb2')\n self.black = pygame.Color('#000000')\n self.bg = pygame.Color('#282828')\n self.bg1 = pygame.Color('#3c3836')\n self.cyan = pygame.Color('#b16286')\n self.yellow = pygame.Color('#fabd2f')\n self.blue = pygame.Color('#458588')\n self.green = pygame.Color('#b8bb26')\n self.red = pygame.Color('#fb4934')\n\nclass Settings():\n def __init__(self,width=1000,height=800,caption='PygamePlotLib_by_avokado0h'):\n pygame.init()\n self.width = width\n self.height = height\n self.screen = pygame.display.set_mode((self.width,self.height))\n pygame.font.init()\n # self.font = pygame.font.Font(pygame.font.get_default_font(),20)\n self.pltFont = pygame.font.SysFont('DejaVu Sans Mono', 15)\n self.font = pygame.font.SysFont('DejaVu Sans Mono', 25)\n pygame.display.set_caption(caption)\n self.clock = pygame.time.Clock()\n self.c = Colors()\n self.fps = 0\n self.running = True\n self.key = ''\n \n def checkInput(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.running = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n self.running = False\n if event.key == pygame.K_LEFT:\n self.key = 'j'\n else: self.key = ''\n\n def Update(self):\n self.checkInput()\n pygame.display.flip()\n self.clock.tick(30)\n self.fps = self.clock.get_fps()\n self.screen.fill(self.c.bg)\n return self.running\n\ndef showText (a,x,y,text='',size=20):\n c = Colors()\n font = pygame.font.SysFont('DejaVu Sans Mono', size)\n txt = font.render(text,True,c.white)\n a.screen.blit(txt,(x,y))\n","sub_path":"pygameplotlib/PygameUtils.py","file_name":"PygameUtils.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"532879789","text":"from metodos_de_busca.sociedade.cidade import Vizinho\nfrom typing import List, Optional\n\nfrom metodos_de_busca.sociedade import Cidade\n\nfrom .busca import (\n IBusca,\n BuscaInputDto,\n ResultadoBusca,\n)\n\n\nclass BuscaAEstrela(IBusca): # A*\n def __init__(self):\n self.arvore_de_busca: List[Vizinho] = []\n self.caminho: List[Vizinho] = []\n\n def executa(self, input_dto: BuscaInputDto) -> ResultadoBusca:\n input_dto.partida.visitar()\n\n if input_dto.partida.nome == input_dto.chegada.nome:\n return ResultadoBusca(\n caminho=self.caminho, arvore_de_cidades=self.arvore_de_busca\n )\n else:\n if input_dto.partida.vizinhos[0].cidade_destino.foi_visitado():\n cidade_a_visitar = input_dto.partida.vizinhos[1]\n else:\n cidade_a_visitar = input_dto.partida.vizinhos[0]\n\n for vizinho in input_dto.partida.vizinhos:\n if not vizinho.cidade_destino.foi_visitado():\n custo = vizinho.cidade_destino.heuristica + vizinho.custo_do_caminho\n custo_a_visitar = (\n cidade_a_visitar.cidade_destino.heuristica\n + cidade_a_visitar.custo_do_caminho\n )\n if custo < custo_a_visitar:\n cidade_a_visitar = vizinho\n\n self.arvore_de_busca.append(cidade_a_visitar)\n self.caminho.append(cidade_a_visitar)\n\n return self.executa(\n BuscaInputDto(\n partida=cidade_a_visitar.cidade_destino,\n chegada=input_dto.chegada,\n )\n )\n","sub_path":"metodos_de_busca/buscas/a_estrela.py","file_name":"a_estrela.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"481468392","text":"import random\nfrom tkinter import *\n\n####################################\n# Fonction de découpage des pièces #\n####################################\n\ndef pieces():\n i = 0 \n aire_totale=longueur*largeur \n while i != nb_pieces:\n x = random.randint(int(largeur/5),int(largeur/2))\n y = random.randint(int(longueur/5),int(longueur/2))\n aire = x*y \n if aire_totale - aire <= largeur*longueur/25 : \n print(\"$: Nous avons cré�� seulement {} pièces car il n'y a pas assez de place\".format(i)) \n break \n if 2 >= x-y >=-2 :\n aire_totale = aire_totale - aire\n i = i+1 \n liste_bazar.append(x)\n liste_bazar.append(y)\n print(\"$: Pièces définies :{}\".format(i)) \n print(liste_bazar) \n\n\n################################################\n# Fonction de rangement de valeurs d'une liste #\n################################################\n\ndef tri():\n c=0 # c sera le curseur qui marquera la valeur maximale \n k=0 # k sera le curseur qui marquera la position de la valeur maximale dans la liste\n for y in range (0,len(liste_bazar),2): # pour chaque couple de la liste_bazar\n c=0 # on met remet c à 0\n for x in range (0,len(liste_bazar),2): # pour chaque couple de la liste_bazar\n if liste_bazar[x]*liste_bazar[x+1]>c: # si l'aire de la pièce (produit des dimensions liste_bazar[x],liste_bazar[x+1] de la pièce de rang x) est supérieure à c\n c=liste_bazar[x]*liste_bazar[x+1] # alors c prend la valeur la plus haute qu'il a pu rencontrer\n k=x # et on note le rang de la valeur maximale \n else: # si c est supérieur à l'aire de la pièce de rang x, x+1\n c=c # alors c garde sa valeur\n liste_rangée.append(liste_bazar[k]) # à la fin de la deuxième boucle, on ajoute la pièce d'aire maximale à la liste rangée\n liste_rangée.append(liste_bazar[k+1])\n liste_bazar[k],liste_bazar[k+1]=0,0 # et on enlève la pièce de la liste_bazar\n print(\"$: Tri effectué\") # à la fin de la première boucle, on affiche la liste triée\n print(liste_rangée)\n \n \n####################################################\n# Fonction qui lance le placement des pièces crées #\n####################################################\n\ndef placement() :\n liste_definitive.append(0) # On place la première pièce de façon manuelle (en haut à gauche de la fenêtre)\n liste_definitive.append(0) \n liste_definitive.append(liste_rangée[0])\n liste_definitive.append(liste_rangée[1])\n print(\"$: pièce n°1 placée\") # On rend compte du placement de la première pièce\n for h in range (2,len(liste_rangée),2): # Puis pour le nombre de pieces qu'il reste\n check_impair(h) # Et on lance la fonction qui va placer la pièce désignée par la boucle\n \n \n#######################################\n# Fonction qui place les pièces crées #\n#######################################\n\ndef check_impair(h):\n # ici on part du coin gauche supérieur\n for x in range (largeur) : # Les deux boucles servent de moteur pour quadriller à l'échelle d'un mètre toute l'habitation, elles forment un curseur qui se déplace\n for y in range (longueur) : # il faut s'illustrer le coin gauche supérieur de la pièce étant à la position du curseur\n c=0 # ici c sera le compteur de superpositions ou d'erreurs fatales\n for z in range(4,len(liste_definitive),4): # cette dernière boucle parcourt toute les pièces déjà placée dans liste_definitive\n if chev(x,x+liste_rangée[h],liste_definitive[z],liste_definitive[z+2]) and chev(y,y+liste_rangée[h+1],liste_definitive[z+1],liste_definitive[z+3]):\n # S'il y a chevauchement entre la pièce à placer et une pièce déjà existante\n c=c+1 # Alors on ajoute 1 à c\n if not dans(liste_definitive[0],x+liste_rangée[h],liste_definitive[2]) or not dans(liste_definitive[1],y+liste_rangée[h+1],liste_definitive[3]):\n # Si la pièce à placer sort du cadre de l'habitation\n c=c+1 # Alors on ajoute 1 à c\n else:# S'il n'y a aucune de ces deux conditions, c n'évolue pas\n c=c\n #si c est égal à 0 alors il peut être placé à ces coordonnés (x,y) car il n'y a aucune erreur vis à vis des pièces déjà placées\n if not c:\n liste_definitive.append(x) # On ajoute la pièce aux positions ne posant aucune erreur\n liste_definitive.append(y)\n liste_definitive.append(x+liste_rangée[h])\n liste_definitive.append(y+liste_rangée[h+1])\n liste_rangée[h]=0 # On efface les dimensions de la pièce à placer car elle vient d'être placée\n liste_rangée[h+1]=0\n print(\"$: pièce n°{} placée\".format(int(h/2)+1))\n return True # La fonction s'arrête et renvoie une valeur positive\n #si c est différent de 0 alors il ne peut être placé à ces coordonnés (x,y) car il y a au moins une erreur vis à vis des pièces déjà placées\n if c:\n True # Donc on ne fait rien\n print(\"ERR$: Impossible de placer la pièce numéro {}\".format(int(h/2)+1)) # si la boucle est finie et que la pièce n'a pas été placée, alors on affiche un message d'erreur\n return False # et on termine la fonction par une valeur négative\n\n\n#########################\n# Fonctions auxiliaires #\n#########################\n\ndef chev(a,b,c,d): # Cette fonction définit si [a;b]∩[c,d]=∅ (0), si l'intervalle [a;b] et [c;d] ont des valeurs communes\n # On s'en sert pour définir si deux pièces se supersposent\n if a 4 :\n x1 = liste_definitive[4]\n y1 = liste_definitive[5]-(1*echelle)\n x2 = liste_definitive[6]\n y2 = liste_definitive[7]-(1*echelle)\n liste_definitive.append(x1)\n liste_definitive.append(y1)\n liste_definitive.append(x2)\n liste_definitive.append(y2)\n \n \n################################### \n# Fonction qui dessine les pièces #\n###################################\n\ndef dessin():\n x=0\n y=-1\n for i in range(0,len(liste_definitive),4):\n canvas.create_rectangle(10+liste_definitive[i],10+liste_definitive[i+1],10+liste_definitive[i+2],10+liste_definitive[i+3],fill=color[x])\n y=y+1\n canvas.create_text(10+int((liste_definitive[i+2]+liste_definitive[i])/2),10+int((liste_definitive[i+1]+liste_definitive[i+3])/2), text=nom[x])\n x=x+1 # On change l'indice de la couleur\n # On ajoute 10 à chaques dimensions pour qu'on puisse apercevoir une marge autour de la maison, le fill=color[x] permet de colorier la pièce\n # à l'aide d'une couleur déjà définie par la fonction couleur() et stockée dans la liste color\n\n\n######################################\n# Fonction qui fabrique des couleurs #\n######################################\n\ndef couleur():\n comp_color=[\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"]\n for x in range(50):\n k=\"#\"\n for y in range(6):\n a=random.randint(0,15)\n k=k+comp_color[a]\n color.append(k)\n\n\n#########################\n# Fonction de \"lissage\" #\n#########################\n\ndef jonction():\n for i in range(4,len(liste_definitive),4):\n c=0 # c est encore ici un compteur d'erreur\n cx=0\n cy=0\n for x in range(4,len(liste_definitive),4): # Les deux boucles permettent de traiter chaque pièce placée avec une autre pièce placée\n if x!=i: \n if chev(liste_definitive[i],liste_definitive[2],liste_definitive[x],liste_definitive[x+2]) and chev(liste_definitive[i+1],liste_definitive[3],liste_definitive[x+1],liste_definitive[x+3]):\n c=c+1\n if abs(liste_definitive[i+2]-liste_definitive[2])<=2: # S'il existe un espace entre une pièce et le mur extérieur, dont on ne peut rien faire\n liste_definitive[i+2]=liste_definitive[2] # alors on agrandit la pièce pour qu'elle touche le mur extérieur\n if abs(liste_definitive[i+3]-liste_definitive[3])<=2:\n liste_definitive[i+3]=liste_definitive[3]\n if dans(liste_definitive[i],((liste_definitive[x]+liste_definitive[x+2])/2),liste_definitive[2]) and dans(liste_definitive[i+1],((liste_definitive[x+1]+liste_definitive[x+3])/2),liste_definitive[3]):\n cx=cx+1\n cy=cy+1\n if not dans(liste_definitive[i+1],((liste_definitive[x+1]+liste_definitive[x+3])/2),liste_definitive[3]):\n if liste_definitive[x+2]<=liste_definitive[i]:\n cx=cx\n else:\n cx=cx+1\n if not dans(liste_definitive[i],((liste_definitive[x]+liste_definitive[x+2])/2),liste_definitive[2]):\n if liste_definitive[x+3]<=liste_definitive[i+1]:\n cy=cy\n else:\n cy=cy+1\n if x==i: # Si les deux pièces sont en fait la même, un traitement est inutile\n True\n if not c:\n liste_definitive[i+2]=liste_definitive[2]\n liste_definitive[i+3]=liste_definitive[3]\n if not cy:\n liste_definitive[i+3]=liste_definitive[3]\n if not cx:\n liste_definitive[i+2]=liste_definitive[2]\n \n \n \n\n\n\n################################\n#------------------------------#\n#--------Premère partie--------#\n#------------------------------#\n################################\n\n#Entrer des valeurs: \nfenetre = Tk()\nfenetre.title('Architecktor 2000: maison sur mesure')\n\nlongueur_ = IntVar()\nlargeur_ = IntVar()\nnb_pieces_ = IntVar()\n\n#Phrase de présentation\nen_tete = Label(fenetre)\nen_tete.grid(column= 0, row= 0, columnspan=2, sticky='s', ipady=20)\n#Entrer la taille du terrain\ntexte_terrain = Label(fenetre, text=\"Veuillez nous donner les dimensions de votre maison (en mètres):\", foreground='#f08080' ,font=('Trebuchet','13','bold'))\ntexte_terrain.grid(column= 0, row= 1, columnspan=2)\n#Première zone de saisie: Longueur\nlongueur = Label(fenetre, text='Longueur de votre maison :',foreground='#f08080' ,font='Trebuchet')\nlongueur.grid(column= 0, row= 2, sticky='e')\nchoix_longueur = Spinbox(fenetre, textvariable=longueur_, from_=8, to=35)\nchoix_longueur.grid(column=1, row=2, sticky='w')\n#Deuxième zone de saisie: Largeur\nlargeur = Label(fenetre, text='Largeur de votre maison :',foreground='#f08080' ,font='Trebuchet')\nlargeur.grid(column= 0, row= 3, sticky='e')\nchoix_largeur = Spinbox(fenetre, textvariable=largeur_, from_=8, to=35)\nchoix_largeur.grid(column=1, row=3, sticky='w')\n\n\n#Entrer le nombre de pièces\ntexte_terrain = Label(fenetre, text=\"Veuillez nous donner le nombre de pièces :\", foreground='#f08080' ,font=('Trebuchet','13','bold'))\ntexte_terrain.grid(column= 0, row= 4, sticky='se')\nchoix_nb_pieces = Spinbox(fenetre, textvariable=nb_pieces_, from_=3, to=20)\nchoix_nb_pieces.grid(column=1, row=4, sticky='sw') \n\n#Bouton\nbouton = Button(fenetre, text=\" Créer un plan \", foreground='#f08080' ,font='Trebuchet',command=fenetre.destroy)\nbouton.grid(column=0, row=10, columnspan=2) \n\n#Les marges\nfenetre.columnconfigure(0, pad=400)\nfenetre.columnconfigure(1, pad=400)\nfenetre.rowconfigure(0, pad=30)\nfenetre.rowconfigure(4, pad=20)\nfenetre.rowconfigure(10, pad=50)\n\nfenetre.mainloop()\n\nlongueur=longueur_.get()\nlargeur=largeur_.get()\nnb_pieces=nb_pieces_.get()\n\n################################\n#------------------------------#\n#--------Deuxieme partie-------#\n#------------------------------#\n################################\n\nprint(longueur)\nprint(largeur)\nprint(nb_pieces)\n\n#Valeurs de base\nechelle=30\n#Création fenetre et canvas\nfenetre=Tk()\nH,W=fenetre.winfo_screenheight(),fenetre.winfo_screenwidth()\ncanvas=Canvas(fenetre, width=W-150, height=H-170, background='#f08080')\ncanvas.grid(column=0, row=0, ipadx=20, ipady=20)\nfenetre.columnconfigure(0, pad= 100)\nfenetre.rowconfigure(0, pad=100)\n\nif largeur>longueur:\n echelle = int((H-200)/largeur)\nif largeur 0)\n self.intervals = intervals\n self.num_intervals = len(intervals)\n\n def findPrevInterval(self):\n self.intervals.sort(key = lambda x: x.end)\n self.prevs = [-1] * self.num_intervals\n for i, interval in enumerate(self.intervals):\n for j in range(i-1, -1, -1):\n if self.intervals[j].end <= interval.start:\n self.prevs[i] = j\n break\n\n def maxScheduling(self, new_intervals = None):\n \"\"\"\n Params:\n new_intervals type: List[Interval]\n ret type: int\n \"\"\"\n if new_intervals:\n self.intervals = new_intervals\n self.num_intervals = len(self.intervals)\n\n self.findPrevInterval()\n\n dp = [0] * (self.num_intervals+1)\n for i, interval in enumerate(self.intervals):\n if self.prevs[i] == -1:\n dp[i+1] = max(interval.weight, dp[i])\n else:\n dp[i+1] = max(dp[self.prevs[i]+1] + interval.weight, dp[i])\n self.dp = dp\n return self.dp[-1]\n\n def find_solution(self, j):\n \"\"\"\n print intervals in the range of 1 to j that belong to the optimal solution.\n \"\"\"\n if j == 0:\n return\n prev = self.prevs[j-1]\n if self.intervals[j-1].weight + self.dp[prev+1] >= self.dp[j-1]:\n print ('%d' % j)\n self.find_solution(prev+1)\n else:\n self.find_solution(j-1)\n\n# Testing\ni1 = Interval(1,3,5)\ni2 = Interval(2,4,6)\ni3 = Interval(3,10,10)\ni4 = Interval(4,13,12)\ni5 = Interval(2,11,20)\nOBJ = WIS([i1, i2, i3, i4, i5])\nprint(\"The weighted scheduling interval sum is: %d\" % OBJ.maxScheduling())\nprint ('The solution is:')\nOBJ.find_solution(OBJ.num_intervals)\n","sub_path":"Dynamic_programming/Weighted_interval_scheduling.py","file_name":"Weighted_interval_scheduling.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"240562080","text":"import requests\nfrom bs4 import BeautifulSoup\n\nresponse = requests.get(\"https://habr.com/ru/all/\")\n\ntext = response.text\n\nKEYWORDS = {'дизайн', 'фото', 'web', 'python'}\n\nsoup = BeautifulSoup(text, features=\"html.parser\")\n\narticles = soup.find_all(class_=\"tm-articles-list__item\")\n\nfor article in articles:\n article_mod = set(article.get_text(\" \", strip=True).lower().split())\n if KEYWORDS & article_mod:\n data = article.find('time').attrs.get(\"title\")\n title = article.find(\"h2\").find(\"a\").find('span').text\n link = \"https://habr.com\" + article.find(\"h2\").find(\"a\").attrs.get(\"href\")\n print(f\"{data} - {title} - {link}\")\n","sub_path":"Web scraping lec.py","file_name":"Web scraping lec.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"380430350","text":"import os\nfrom setup import config, directory\n\nclass Config:\n\n def __init__(self):\n self.home_path = directory()\n self.user_defaults = None\n self.main_db = None\n self.users_db = None\n self.tests = None\n self.forms = None\n\n def setup_main_db(self, main_db_folder=\"DATABASE\", main_db=\"data\", main_db_extension=\".db\"):\n db = main_db + main_db_extension\n self.main_db = os.path.join(self.home_path, main_db_folder, db)\n file = open(directory()+\"/CONFIG.txt\", \"r\")\n my_setup = {}\n for line in file:\n splitted = line.strip().split('`')\n my_setup[splitted[0]] = splitted[1]\n file.close()\n if \"MAIN_DB\" in my_setup.keys():\n raise IsADirectoryError(\"Configuration has already been set, to change use function edit_conf(current_conf_name, new)\")\n else:\n file = open(directory()+\"/CONFIG.txt\", 'a')\n file.write(\"MAIN_DB`{}\\n\".format(self.main_db))\n file.close()\n\n def set_users_db(self, users_folder=\"USERS\", users_db='data1', users_db_extenstion='.db'):\n file = open(directory()+\"/CONFIG.txt\", 'r')\n my_setup = {}\n for line in file:\n splitted = line.strip().split('`')\n my_setup[splitted[0]] = splitted[1]\n file.close()\n if \"USERS_DB\" in my_setup.keys():\n raise IsADirectoryError(\n \"Configuration has already been set, to change use function edit_conf(current_conf_name, new)\")\n else:\n userdb = directory()+\"/{}\".format(users_folder)+\"/{}/\"+users_db+users_db_extenstion\n file = open(directory()+\"/CONFIG.txt\", 'a')\n file.write(\"USERS_DB`{}\\n\".format(userdb))\n file.close()\n\ndef load_in():\n file = open(config(), 'r')\n my_setup = {}\n for line in file:\n splitted = line.strip().split('`')\n my_setup[splitted[0]] = splitted[1]\n file.close()\n return my_setup\n\n","sub_path":"TheBeets/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"264565603","text":"from .base_dataset import Dataset\nimport numpy as np\nimport pandas as pd\nimport os.path\n\n\nclass CSVDataset(Dataset):\n \"\"\" \n CSVDataset class.\n Provide access to the Boston Housing Prices dataset. \n \"\"\"\n\n def __init__(self, target_column, transform=None, mode=\"train\", *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # The name of the .csv dataset file should be the same as the name\n # of the archive, but with a different extension.\n name_prefix = self.dataset_zip_name[:self.dataset_zip_name.find('.')]\n dataset_csv_name = name_prefix + '.csv'\n data_path = os.path.join(self.root_path, dataset_csv_name)\n\n self.target_column = target_column\n self.df = pd.read_csv(data_path)\n\n # split the dataset into train - val - test with the ratio 60 - 20 - 20\n assert mode in [\"train\", \"val\", \"test\"], \"wrong mode for dataset given\"\n train, val, test = np.split(self.df.sample(frac=1, random_state=0),\n [int(.6 * len(self.df)), int(.8 * len(self.df))])\n if mode == \"train\":\n self.df = train\n elif mode == \"val\":\n self.df = val\n elif mode == \"test\":\n self.df = test\n\n self.data = self.df.loc[:, self.df.columns != self.target_column]\n self.targets = self.df[self.target_column]\n self.transforms = transform if transform is not None else lambda x: x\n\n self.data.iloc[0]['OverallQual'] = np.nan\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index):\n \"\"\"\n Create a dict of the data at the given index in your dataset.\n\n The dict should have the following format: \n { \"features\" : , \n \"label\" : } \n \"\"\"\n\n data_dict = {}\n data_dict['features'] = self.data.iloc[index]\n data_dict['target'] = self.targets.iloc[index]\n\n return self.transforms(data_dict)\n\n\nclass FeatureSelectorAndNormalizationTransform:\n \"\"\"\n Select some numerical features and normalize them between 0 and 1.\n \"\"\"\n\n def __init__(self, column_stats, target_column):\n \"\"\"\n :param column_stats: a dictionary mapping the column name to the\n relevant statistics for normalization (min and max on that column). \n It should also include the statistics for the target column.\n \"\"\"\n self.column_stats = column_stats\n self.target_column = target_column\n\n def __call__(self, data_dict):\n def normalize_column(old_value, column_name):\n mn = self.column_stats[column_name]['min']\n mx = self.column_stats[column_name]['max']\n return (old_value - mn) / (mx - mn)\n\n # For every feature column, normalize it if it's one of the columns\n # we want to keep.\n feature_columns = []\n for column_idx in data_dict['features'].index:\n if column_idx in self.column_stats and column_idx != self.target_column:\n feature_columns.append(column_idx)\n\n if np.isnan(data_dict['features'][column_idx]):\n mean_col_val = self.column_stats[column_idx]['mean']\n data_dict['features'][column_idx] = mean_col_val\n\n old_value = data_dict['features'][column_idx]\n normalized = normalize_column(old_value, column_idx)\n data_dict['features'][column_idx] = normalized\n\n # Drop the rest of the columns.\n data_dict['features'] = data_dict['features'][feature_columns]\n data_dict['features'] = data_dict['features'].values.astype(np.float32)\n\n # Also normalize the target.\n old_value = data_dict['target']\n normalized = normalize_column(old_value, self.target_column)\n data_dict['target'] = np.array([normalized])\n\n return data_dict\n","sub_path":"exercise2/exercise_04/exercise_code/data/csv_dataset.py","file_name":"csv_dataset.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234095571","text":"import sys\nsys.stdin = open(\"input.txt\", \"rt\")\n\nN, M = map(int, input().split())\narr = list(map(int, input().split()))\narr.sort()\n\ncntBoat = 0\nminIdx = 0\nmaxIdx = N-1\n\nwhile minIdx <= maxIdx:\n if len(arr) == 1:\n cntBoat += 1\n break\n\n if arr[maxIdx] + arr[minIdx] <= M:\n maxIdx -= 1\n minIdx += 1\n cntBoat += 1\n elif arr[maxIdx] + arr[minIdx] > M:\n cntBoat += 1\n maxIdx -= 1\n\nprint(cntBoat)\n\n","sub_path":"section3/6_boat/boat.py","file_name":"boat.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"371723816","text":"#Take 10 numbers and get their average\r\n\r\nsum = 0\r\n\r\nfor i in range (0,10):\r\n num = int(input(\"Enter the numbers: \"))\r\n sum += num\r\naverage = sum/(i+1)\r\naverage = str(average)\r\nprint(\"The average is: \" + average)","sub_path":"Average of Numbers.py","file_name":"Average of Numbers.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"555496035","text":"import requests\nimport json\nimport time\nimport threading\nstart = time.time()\n\ndef request4():\n url = 'http://127.0.0.1:5000/user/yangr5/18'\n \n print('Waiting for', url)\n s = json.dumps({'name': 'merry'})\n result = requests.post(url,json=s).text\n print('Get response from', url, 'Result:', result)\n\ndef request3():\n url = 'http://127.0.0.1:5000/yangr5'\n \n d = {'name': 'vicent'}\n print('Waiting for', url)\n result = requests.post(url,data=d).text\n print('Get response from', url, 'Result:', result)\n\ndef request2():\n url = 'http://127.0.0.1:5000/user/yangr5'\n print('Waiting for', url)\n result = requests.get(url).text\n print('Get response from', url, 'Result:', result)\ndef request(name):\n url = 'http://127.0.0.1:5000'\n print('Waiting for', url)\n result = requests.get(url).text\n print('Get response from {} Result {} at {}'.format(url,result,name))\n# for _ in range(20):\n # if _%5 ==1:\n # request()\n # elif _%5 ==2:\n # request2()\n # elif _%5 ==3:\n # request3()\n # else:\n # request4()\n# request3()\n# for _ in range(10):\n # request()\n\n\nthreads = [\n threading.Thread(target=request4 ) for _ in range(20)\n]\n\n[t.start() for t in threads]\n[t.join() for t in threads]\nend = time.time()\nprint('Cost time:', end - start)","sub_path":"flask/thread_flask.py","file_name":"thread_flask.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"133892129","text":"from telegram_bot_sdk.telegram_objects import inputMedia\n\n\nclass InputMediaPhoto(inputMedia):\n \"\"\"This class represents a photo to be sent\n\n :param type_result: Type of the result, must be **photo**\n :type type_result: str\n :param media: File to send. Pass a file_id to send a file that exists on that Telegram servers (recommended), pass \\\n an HTTP URL for Telegram to get a file from the Internet, or pass \"attach://\" to upload a new one\\\n using multipart/form-data under \n :type media: str\n :param caption: Optional: Caption of the audio to be sent, 0-1024 characters\n :type caption: str\n :param parse_mode: Optional: Send *Markdown* or *HTML*, if you want Telegram apps to show bold, italic, fixed-width\\\n text or inline URLs in the media caption\n :type parse_mode: str\n \"\"\"\n def __init__(self, *, type_result, media, caption=None, parse_mode=None):\n self.type_result = type_result\n self.media = media\n self.caption = caption\n self.parse_mode = parse_mode\n","sub_path":"tbot_venv/lib/python3.9/site-packages/telegram_bot_sdk/telegram_objects/inputMediaPhoto.py","file_name":"inputMediaPhoto.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"5347948","text":"#!/usr/bin/env python\n\"\"\"Initialize neo4j database.\"\"\"\nimport argparse\nimport logging\nimport time\n\nfrom neo4j import GraphDatabase\nfrom neo4j.exceptions import ServiceUnavailable, DatabaseUnavailable\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef get_driver(url):\n \"\"\"Get Neo4j driver.\n\n Wait up to ~512 seconds for Neo4j to be ready.\n \"\"\"\n seconds = 1\n while True:\n try:\n driver = GraphDatabase.driver(url, auth=None)\n # make sure we can start and finish a session\n with driver.session() as session:\n session.run(\"CALL dbms.procedures()\")\n return driver\n except (OSError, ServiceUnavailable, DatabaseUnavailable) as err:\n if seconds >= 256:\n raise err\n LOGGER.error(\n \"Neo4j service unavailable. Trying again in %d seconds...\",\n seconds\n )\n time.sleep(seconds)\n seconds *= 2\n\n\ndef main(hash: str = None):\n \"\"\"Delete any existing data and initialize with dummy data.\"\"\"\n url = \"bolt://localhost:7687\"\n driver = get_driver(url)\n LOGGER.info(\"Connected to Neo4j. Initializing...\")\n if hash is not None:\n node_file = f\"https://raw.githubusercontent.com/ranking-agent/reasoner/{hash}/tests/neo4j_csv/nodes.csv\"\n edge_file = f\"https://raw.githubusercontent.com/ranking-agent/reasoner/{hash}/tests/neo4j_csv/edges.csv\"\n else:\n node_file = f\"file:///nodes.csv\"\n edge_file = f\"file:///edges.csv\"\n with driver.session() as session:\n session.run(\"MATCH (m) DETACH DELETE m\")\n session.run(f\"LOAD CSV WITH HEADERS FROM \\\"{node_file}\\\" \"\n \"AS row \"\n \"CALL apoc.create.node([row.category, 'biolink:NamedThing'], apoc.map.merge({\"\n \"name: row.name, id: row.id\"\n \"}, apoc.convert.fromJsonMap(row.props))) YIELD node \"\n \"RETURN count(*)\")\n session.run(f\"LOAD CSV WITH HEADERS FROM \\\"{edge_file}\\\" \"\n \"AS edge \"\n \"MATCH (subject), (object) \"\n \"WHERE subject.id = edge.subject AND object.id = edge.object \"\n \"CALL apoc.create.relationship(subject, edge.predicate, \"\n \"apoc.map.merge({predicate: edge.predicate, id: edge.id}, \"\n \"apoc.convert.fromJsonMap(edge.props)), object) YIELD rel \"\n \"RETURN count(*)\")\n LOGGER.info(\"Done. Neo4j is ready for testing.\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Initialize Neo4j.\")\n parser.add_argument(\n \"commit_hash\",\n type=str,\n help=\"a commit hash from github.com/ranking-agent/reasoner\",\n nargs=\"?\",\n )\n\n args = parser.parse_args()\n main(args.commit_hash)\n","sub_path":"tests/initialize_db.py","file_name":"initialize_db.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"305151390","text":"from pomegranate import GeneralMixtureModel, MultivariateGaussianDistribution\nfrom sklearn.mixture.gaussian_mixture import GaussianMixture\nimport numpy as np\n\nfrom .base_clustream import CluStream, MicroCluster\n\n\nclass GmmMicroCluster(MicroCluster):\n pass\n\n\nclass GmmCluStream(CluStream):\n def __init__(self, n_microclusters, **kwargs):\n super().__init__(n_microclusters, **kwargs)\n self.gmm_model = None\n\n def calculate_distances(self, sample):\n cluster_means = np.array([m.mean() for m in self.micro_clusters])\n cluster_means -= sample\n d = np.linalg.norm(cluster_means, axis=1)\n return d\n\n def find_closest_clusters(self):\n cluster_means = np.array([m.mean() for m in self.micro_clusters])\n d_matrix = np.linalg.norm(cluster_means[..., None] - cluster_means[..., None].T, axis=1, ord=2)\n np.fill_diagonal(d_matrix, d_matrix.max() + 1)\n cluster_1, cluster_2 = np.unravel_index(np.argmin(d_matrix), d_matrix.shape)\n return cluster_1, cluster_2\n\n def macro_clusters(self, n_clusters, max_iters=1000, **kwargs):\n data = np.concatenate([m.sample(np.int32(np.ceil(m.n / 100))) for m in self.micro_clusters])\n\n gmm = GaussianMixture(n_components=n_clusters)\n gmm.fit(data)\n self.macro_centroids = gmm.means_\n self.gmm_model = gmm\n\n def transform(self, data):\n return self.gmm_model.predict(data)","sub_path":"clustream/gmm_clustream.py","file_name":"gmm_clustream.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"326228441","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 5 00:02:55 2019\n\n@author: curtisbucher\n\nCreates images from python programs. Because every program is a work of art.\nWill recursively run through all programs in a specified directory.\n\"\"\"\n\nimport pygame\nimport math\nfrom numpy import array\nimport random\nimport os\n\n\ndef get_next_square(number: int):\n # Returns the next square number after the given number.\n if number == 0:\n return 1\n if not math.sqrt(number).is_integer():\n return (int(math.sqrt(number)) + 1) ** 2\n else:\n return number\n\n\ndef random_palette(seed: str):\n random.seed(seed)\n palette = []\n for x in range(255):\n palette += [\n (\n random.randint(0, 255),\n random.randint(0, 255),\n random.randint(0, 255),\n )\n ]\n return palette\n\n\ndef gen_image_from_file(filename):\n with open(filename, \"rb\") as d:\n # Opening file and reading data as bytes\n data = d.read()\n # Making the list a square number for a square image\n data += b\" \" * (get_next_square(len(data)) - len(data))\n\n # Creating 2d list from data, then a numpy array\n data = [*zip(*[iter(data)] * int(math.sqrt(len(data))))]\n data = array(data)\n\n # Initiating pygame\n pygame.init()\n screen = pygame.surfarray.make_surface(data)\n screen = pygame.transform.flip(screen, True, False)\n screen = pygame.transform.rotate(screen, 90)\n screen = pygame.transform.scale(screen, (2000, 2000))\n screen.set_palette(random_palette(filename))\n\n return screen\n\n\ndef recur_gen_image():\n try:\n os.mkdir(\"./Images\")\n except FileExistsError:\n pass\n for dir, subdirs, files in os.walk(input(\"Directory: \")):\n for file in files:\n if os.path.splitext(file)[-1] == \".py\":\n img = gen_image_from_file(os.path.join(dir, file))\n filename = os.path.splitext(file)[0] + \".png\"\n filename = os.path.join(\"./Images\", filename)\n print(filename)\n pygame.image.save(img, filename)\n \n subdirs_list = []\n for dir, subdirs, files in os.walk(\"./Images\"):\n for subdir in subdirs:\n subdirs_list += [os.path.join(dir, subdir)]\n for dir in reversed(subdirs_list):\n try:\n os.rmdir(dir)\n except OSError:\n pass\n\n\nif __name__ == \"__main__\":\n recur_gen_image()\n# filename = input(\"Filename: \")\n# img = gen_image_from_file()\n# try:\n# pygame.image.save(img, filename[: filename.index(\".\")] + \".png\")\n# except Exception:\n# pygame.image.save(img, filename + \"png\")\n","sub_path":"pyArtist.py","file_name":"pyArtist.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"453740011","text":"'''\n问题描述:\n给出一棵二叉树和一个整数代表树的某层深度。\n计算二叉树的某层节点之和。\n\n示例:\n输入:{1,2,3,4,5,6,7,#,#,8,#,#,#,#,9},2\n输出:5\n解释:\n 1\n / \\\n 2 3\n / \\ / \\\n4 5 6 7\n / \\\n 8 9\n2+3=5\n\n思路:层次遍历,记录下某层的结点和存放于列表即可\n\n\n'''\n\n\ndef levelSum(root, level):\n # write your code here\n # 用于控制层次遍历的队列\n queue = []\n # 用于存放每层结点和的列表\n sum_list = []\n if not root:\n return 0\n queue.append(root)\n # 队列不为空\n while queue:\n sum_of_level = 0\n length = len(queue)\n for i in range(length):\n sum_of_level += queue[i].val\n # 左孩子存在则入队\n if queue[i].left:\n queue.append(queue[i].left)\n # 右孩子存在则入队\n if queue[i].right:\n queue.append(queue[i].right)\n # 截取新入队的元素\n queue = queue[length:]\n sum_list.append(sum_of_level)\n if level > len(sum_list) or level < 1:\n return 0\n else:\n return sum_list[level - 1]","sub_path":"482_done.py","file_name":"482_done.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"246567044","text":"\n# coding: utf-8\n\n# # Text Processing functions\n# ## for generating normalised output for text of the following classes:\n# \n# 1. Cardinal\n# 2. Digit\n# 3. Ordinal\n# 4. Letters\n# 5. Address\n# 6. Telephone\n# 7. Electronic\n# 8. Fractions\n# 9. Money\n# \n# The idea is to first create a dictionary of all the training input strings and their corresponding normalised text. For normalising the test data, we first look it up in the dictionary and return the corresponding 'after' value. If the string is not in the dictionary, we use these functions to generate normalised text.\n\n# ## Import modules and data sets\n\n# In[108]:\n\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport inflect\nfrom num2words import num2words \nimport re\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nfrom datetime import datetime\np = inflect.engine()\n\nimport string\n# Any results you write to the current directory are saved as output.\n\n\n# ## CARDINAL\n\n# In[109]:\n\n\ndef cardinal(x):\n try:\n if re.match('.*[A-Za-z]+.*', x):\n return x\n x = re.sub(',', '', x, count = 10)\n\n if(re.match('.+\\..*', x)):\n x = p.number_to_words(float(x))\n elif re.match('\\..*', x): \n x = p.number_to_words(float(x))\n x = x.replace('zero ', '', 1)\n else:\n x = p.number_to_words(int(x))\n x = x.replace('zero', 'o') \n x = re.sub('-', ' ', x, count=10)\n x = re.sub(' and','',x, count = 10)\n return x\n except:\n return x\n\n\n# In[110]:\n\n\ndef is_num(key):\n if is_float(key) or re.match(r'^-?[0-9]\\d*?$', key.replace(',','')): return True\n else: return False\n\ndef is_float(string):\n try:\n return float(string.replace(',','')) and \".\" in string # True if string is a number contains a dot\n except ValueError: \n return False\n \ndef num2word(key):\n bag_res = bag2word(key, digit_trained)\n if bag_res != key: return bag_res\n if re.match(r'^-?\\d+$', key.replace(',','')):\n return cardinal(key)\n if is_float(key):\n return float2word(key)\n\n\n# # Measure\n\ndict_m = {'\"': 'inches',\n \"'\": 'feet',\n 'km/s': 'kilometers per second',\n 'AU': 'units', 'BAR': 'bars',\n 'CM': 'centimeters',\n 'mm': 'millimeters',\n 'FT': 'feet',\n 'G': 'grams', \n 'GAL': 'gallons',\n 'GB': 'gigabytes',\n 'GHZ': 'gigahertz',\n 'HA': 'hectares',\n 'HP': 'horsepower', \n 'HZ': 'hertz',\n 'KM':'kilometers',\n 'km3': 'cubic kilometers',\n 'KA':'kilo amperes',\n 'KB': 'kilobytes',\n 'KG': 'kilograms',\n 'KHZ': 'kilohertz',\n 'KM²': 'square kilometers',\n 'KT': 'knots',\n 'KV': 'kilo volts',\n 'M': 'meters',\n 'KM2': 'square kilometers',\n 'Kw':'kilowatts',\n 'KWH': 'kilo watt hours',\n 'LB': 'pounds',\n 'LBS': 'pounds',\n 'MA': 'mega amperes',\n 'MB': 'megabytes',\n 'KW': 'kilowatts',\n 'MPH': 'miles per hour',\n 'MS': 'milliseconds',\n 'MV': 'milli volts',\n 'kJ':'kilojoules',\n 'km/h': 'kilometers per hour',\n 'V': 'volts',\n '%':'percent',\n 'M2': 'square meters', 'M3': 'cubic meters', 'MW': 'megawatts', 'M²': 'square meters', 'M³': 'cubic meters', 'OZ': 'ounces', 'MHZ': 'megahertz', 'MI': 'miles',\n 'MB/S': 'megabytes per second', 'MG': 'milligrams', 'ML': 'milliliters', 'YD': 'yards', 'au': 'units', 'bar': 'bars', 'cm': 'centimeters', 'ft': 'feet', 'g': 'grams', \n 'gal': 'gallons', 'gb': 'gigabytes', 'ghz': 'gigahertz', 'ha': 'hectares', 'hp': 'horsepower', 'hz': 'hertz', 'kWh': 'kilo watt hours', 'ka': 'kilo amperes', 'kb': 'kilobytes', \n 'kg': 'kilograms', 'khz': 'kilohertz', 'km': 'kilometers', 'km2': 'square kilometers', 'km²': 'square kilometers', 'kt': 'knots','kv': 'kilo volts', 'kw': 'kilowatts', \n 'lb': 'pounds', 'lbs': 'pounds', 'm': 'meters', 'm2': 'square meters','m3': 'cubic meters', 'ma': 'mega amperes', 'mb': 'megabytes', 'mb/s': 'megabytes per second', \n 'mg': 'milligrams', 'mhz': 'megahertz', 'mi': 'miles', 'ml': 'milliliters', 'mph': 'miles per hour','ms': 'milliseconds', 'mv': 'milli volts', 'mw': 'megawatts', 'm²': 'square meters',\n 'm³': 'cubic meters', 'oz': 'ounces', 'v': 'volts', 'yd': 'yards', 'µg': 'micrograms', 'ΜG': 'micrograms', 'kg/m3': 'kilograms per meter cube'}\n\ndef measure(key):\n if \"%\" in key:\n unit = \"percent\";\n val = key[:len(key)-1]\n elif \"/\" in key and key.split(\"/\")[0].replace(\".\",\"\").isdigit():\n try:\n unit = \"per \" + dict_m[key.split(\"/\")[-1]]\n except KeyError:\n unit = \"per \" + key.split(\"/\")[-1].lower()\n \n val = key.split(\"/\")[0]\n else:\n v = key.split()\n if len(v)>2:\n try:\n unit = \" \".join(v[1:-1])+\" \"+dict_m[v[-1]]\n except KeyError:\n unit = \" \".join(v[1:-1])+\" \"+v[-1].lower()\n else:\n try:\n unit = dict_m[v[-1]]\n except KeyError:\n unit = v[-1].lower()\n val = v[0]\n if is_num(val):\n val = p.number_to_words(val,andword='').replace(\"-\",\" \").replace(',','')\n text = val + ' ' + unit\n else: text = key\n return text\n\n\n# # Verbatim\n\ndef verbatim(key):\n\n dict_verb = {\"#\":\"number\",\"&\":\"and\",\"α\":\"alpha\",\"Α\":\"alpha\",\"β\":\"beta\",\"Β\":\"beta\",\"γ\":\"gamma\",\"Γ\":\"gamma\",\n \"δ\":\"delta\",\"Δ\":\"delta\",\"ε\":\"epsilon\",\"Ε\":\"epsilon\",\"Ζ\":\"zeta\",\"ζ\":\"zeta\",\"η\":\"eta\",\"Η\":\"eta\",\n \"θ\":\"theta\",\"Θ\":\"theta\",\"ι\":\"iota\",\"Ι\":\"iota\",\"κ\":\"kappa\",\"Κ\":\"kappa\",\"λ\":\"lambda\",\"Λ\":\"lambda\",\n \"Μ\":\"mu\",\"μ\":\"mu\",\"ν\":\"nu\",\"Ν\":\"nu\",\"Ξ\":\"xi\",\"ξ\":\"xi\",\"Ο\":\"omicron\",\"ο\":\"omicron\",\"π\":\"pi\",\"Π\":\"pi\",\n \"ρ\":\"rho\",\"Ρ\":\"rho\",\"σ\":\"sigma\",\"Σ\":\"sigma\",\"ς\":\"sigma\",\"Φ\":\"phi\",\"φ\":\"phi\",\"τ\":\"tau\",\"Τ\":\"tau\",\n \"υ\":\"upsilon\",\"Υ\":\"upsilon\",\"Χ\":\"chi\",\"χ\":\"chi\",\"Ψ\":\"psi\",\"ψ\":\"psi\",\"ω\":\"omega\",\"Ω\":\"omega\",\n \"$\":\"dollar\",\"€\":\"euro\",\"~\":\"tilde\",\"_\":\"underscore\",\"ₐ\":\"sil\",\"%\":\"percent\",\"³\":\"cubed\"}\n if key in dict_verb: \n return dict_verb[key]\n if len(key)==1 or not(key.isalpha()):\n return key\n if key=='-':\n return \"to\"\n return letters(key)\n\n\n# # Decimal\n\n# In[115]:\n\n\ndef decimal(key):\n if \"million\" in key or \"billion\" in key:\n return money(key)\n if key.find(\" \") != (-1):\n return measure(key)\n try:\n key = float(key.replace(',',''))\n except ValueError:\n return measure(key)\n try:\n key = float(key.replace(',',''))\n key = p.number_to_words(key,decimal='point',andword='', zero='o')\n if 'o' == key.split()[0]:\n key = key[2:]\n key = key.replace('-',' ').replace(',','')\n return key.lower()\n except:\n try:\n m=key.split('.')\n if len(m)>2 and m[2]!='':\n return date(key)\n except:\n return key\n\n\n# # DATE\n\n# In[123]:\n\n\ndict_mon = {'jan': \"January\", \n \"feb\": \"February\", \"mar \": \"march\", \"apr\":\n \"april\", \"may\": \"may \",\"jun\": \"june\",\n \"jul\": \"july\", \"aug\": \"august\",\n \"sep\": \"september\",\n \"oct\": \"october\",\"nov\": \"november\",\n \"dec\": \"december\", \"january\":\"January\",\n \"february\":\"February\", \"march\":\"march\",\n \"april\":\"april\", \"may\": \"may\", \n \"june\":\"june\",\"july\":\"july\", \"august\":\"august\",\n \"september\":\"september\", \"october\":\"october\",\n \"november\":\"november\", \"december\":\"december\"}\ndef date(key):\n try:\n v = key.split('-')\n if len(v)==1:\n text=cardinal(v[0][:-2])+\" \"+cardinal(v[0][-2:])\n return text\n if len(v)==3:\n if v[1].isdigit():\n try:\n date = datetime.strptime(key , '%Y-%m-%d')\n text = 'the '+ p.ordinal(p.number_to_words(int(v[2]))).replace('-',' ')+' of '+datetime.date(date).strftime('%B')\n if int(v[0])>=2000 and int(v[0]) < 2010:\n text = text + ' '+cardinal(v[0])\n else: \n text = text + ' ' + cardinal(v[0][0:2]) + ' ' + cardinal(v[0][2:])\n except:\n text = key\n return text.lower() \n else: \n v = re.sub(r'[^\\w]', ' ', key).split()\n\n if v[0].isalpha():\n try:\n if len(v)==3:\n text = dict_mon[v[0].lower()] + ' '+ p.ordinal(p.number_to_words(int(v[1]))).replace('-',' ')\n if int(v[2])>=2000 and int(v[2]) < 2010:\n text = text + ' '+cardinal(v[2])\n else: \n text = text + ' ' + cardinal(v[2][0:2]) + ' ' + cardinal(v[2][2:]) \n elif len(v)==2:\n\n if int(v[1])>=2000 and int(v[1]) < 2010:\n text = dict_mon[v[0].lower()] + ' '+ cardinal(v[1])\n else: \n if len(v[1]) <=2:\n text = dict_mon[v[0].lower()] + ' ' + cardinal(v[1])\n else:\n text = dict_mon[v[0].lower()] + ' ' + cardinal(v[1][0:2]) + ' ' + cardinal(v[1][2:])\n else: text = key\n except: text = key\n return text.lower()\n else: \n key = re.sub(r'[^\\w]', ' ', key)\n v = key.split()\n\n try:\n\n date = datetime.strptime(key , '%d %b %Y')\n\n text = 'the '+ p.ordinal(p.number_to_words(int(v[0]))).replace('-',' ')+' of '+ dict_mon[v[1].lower()]\n if int(v[2])>=2000 and int(v[2]) < 2010:\n text = text + ' '+cardinal(v[2])\n else: \n text = text + ' ' + cardinal(v[2][0:2]) + ' ' + cardinal(v[2][2:])\n except:\n\n try:\n\n date = datetime.strptime(key , '%d %B %Y')\n\n text = 'the '+ p.ordinal(p.number_to_words(int(v[0]))).replace('-',' ')+' of '+ dict_mon[v[1].lower()]\n if int(v[2])>=2000 and int(v[2]) < 2010:\n text = text + ' '+cardinal(v[2])\n else: \n text = text + ' ' + cardinal(v[2][0:2]) + ' ' + cardinal(v[2][2:])\n except:\n\n try:\n date = datetime.strptime(key , '%d %m %Y')\n\n text = 'the '+ p.ordinal(p.number_to_words(int(v[0]))).replace('-',' ')+' of '+datetime.date(date).strftime('%B')\n if int(v[2])>=2000 and int(v[2]) < 2010:\n text = text + ' '+cardinal(v[2])\n else: \n text = text + ' ' + cardinal(v[2][0:2]) + ' ' + cardinal(v[2][2:])\n except:\n try:\n date = datetime.strptime(key , '%d %m %y')\n\n text = 'the '+ p.ordinal(p.number_to_words(int(v[0]))).replace('-',' ')+' of '+datetime.date(date).strftime('%B')\n v[2] = datetime.date(date).strftime('%Y')\n if int(v[2])>=2000 and int(v[2]) < 2010:\n text = text + ' '+cardinal(v[2])\n else: \n text = text + ' ' + cardinal(v[2][0:2]) + ' ' + cardinal(v[2][2:])\n except:\n\n text = key\n return text.lower()\n except:\n return key\n\n\n# In[214]:\n\n\ndef time(key):\n v=key.split()\n try:\n if \":\" in key:\n if len(v)==1:\n v=key.split(\":\")\n if len(v)==3:\n text=cardinal(v[0])+\" hours \"+cardinal(v[1])+\" minutes and \"+cardinal(v[2])+\" seconds\"\n elif len(v)==2:\n s=v[1]\n if \".\" in key:\n t=v[1].split('.')\n text=cardinal(v[0])+\" hours \"+cardinal(t[0])+\" minutes and \"+cardinal(t[1])+\" seconds\"\n \n elif len(s)==4:\n m=s\n if (m[:-2]==\"0\" or m[:-2]==\"00\"):\n text=cardinal(v[0])+\" \"+letters(m[-2:])\n elif m[0]!=\"0\":\n text=cardinal(v[0])+\" \"+cardinal(m[:-2])+\" \"+letters(m[-2:])\n else:\n text=cardinal(v[0])+\" \"+cardinal(m[0])+\" \"+cardinal(m[1])+\" \"+letters(s[-2:])\n else:\n if (v[0]==\"0\"):\n v[0]=\"zero\"\n if (s[0]==\"0\"):\n text=cardinal(v[0])+\" \"+cardinal(s[0])+\" \"+cardinal(s[1])\n else:\n text=cardinal(v[0])+\" \"+cardinal(s)\n elif len(v)==2:\n m=v[1]\n t=v[0].split(\":\")\n if (t[1]==\"0\" or t[1]==\"00\"):\n try:\n text=cardinal(t[0])+\" \"+letters(m)\n except:\n j=key.split(':')\n text=cardinal(j[0])+\" \"+cardinal(j[1])\n else:\n s=t[1]\n if (s[0]==\"0\"):\n text=cardinal(t[0])+\" \"+cardinal(s[0])+\" \"+cardinal(s[1])+\" \"+letters(m)\n else:\n text=cardinal(t[0])+\" \"+cardinal(s)+\" \"+letters(m)\n else:\n if len(v)==2:\n if \".\" in key and len(key)>=7:\n t=v[0].split(\".\")\n m=t[1]\n if (m[:-2]==\"0\" or m[:-2]==\"00\"):\n text=cardinal(t[0])+\" \"+letters(m[-2:])\n else:\n text=cardinal(t[0])+\" \"+cardinal(m[:-2])+\" \"+letters(m[-2:])+\" \"+letters(v[1])\n else:\n text=cardinal(v[0])+\" \"+letters(v[1])\n elif \".\" in key:\n t=v[0].split(\".\")\n m=t[1]\n if (len(m)==4):\n if (m[:-2]==\"0\" or m[:-2]==\"00\"):\n text=cardinal(t[0])+\" \"+letters(m[-2:])\n else:\n text=cardinal(t[0])+\" \"+cardinal(m[:-2])+\" \"+letters(m[-2:])\n else:\n text=cardinal(t[0])+\" \"+cardinal(t[1])\n else:\n if (len(key)==3 or len(key)==4):\n text=cardinal(key[:-2])+\" \"+letters(key[-2:])\n \n \n return text \n except:\n return key\n \n \n \n \n\n\n# ## DIGIT\n\n# In[24]:\n\n\ndef digit(x): \n try:\n x = re.sub('[^0-9]', '',x)\n result_string = ''\n for i in x:\n result_string = result_string + cardinal(i) + ' '\n result_string = result_string.strip()\n return result_string\n except:\n return(x)\n\n\n# ## LETTERS\n\n# In[35]:\n\n\ndef letters(x):\n try:\n x = re.sub('[^a-zA-Z]', '', x)\n x = x.lower()\n result_string = ''\n for i in range(len(x)):\n result_string = result_string + x[i] + ' '\n return(result_string.strip()) \n except:\n return x\n\n\n# ## ORDINAL\n\n# In[72]:\n\n\n#Convert Roman to integers\n#https://codereview.stackexchange.com/questions/5091/converting-roman-numerals-to-integers-and-vice-versa\ndef rom_to_int(string):\n table=[['M',1000], ['CM',900], ['D',500], ['CD',400], ['C',100], ['XC',90],\n ['L',50], ['XL',40], ['X',10], ['IX',9], ['V',5], ['IV',4], ['I',1]]\n returnint=0\n for pair in table:\n continueyes=True\n while continueyes:\n if len(string)>=len(pair[0]):\n if string[0:len(pair[0])]==pair[0]:\n returnint+=pair[1]\n string=string[len(pair[0]):]\n else: continueyes=False\n else: continueyes=False\n return returnint\n\ndef ordinal(x):\n try:\n result_string = ''\n x = x.replace(',', '')\n x = x.replace('[\\.]$', '')\n if re.match('^[0-9]+$',x):\n x = num2words(int(x), ordinal=True)\n return(x.replace('-', ' '))\n if re.match('.*V|X|I|L|D',x):\n if re.match('.*th|st|nd|rd',x):\n x = x[0:len(x)-2]\n x = rom_to_int(x)\n result_string = re.sub('-', ' ', num2words(x, ordinal=True))\n else:\n x = rom_to_int(x)\n result_string = 'the '+ re.sub('-', ' ', num2words(x, ordinal=True))\n else:\n x = x[0:len(x)-2]\n result_string = re.sub('-', ' ', num2words(float(x), ordinal=True))\n return(result_string) \n except:\n return x\n\n\n# ## ADDRESS\n\n# In[221]:\n\n\ndef address(key):\n try:\n text = re.sub('[^a-zA-Z]+', '', key)\n num = re.sub('[^0-9]+', '', key)\n result_string = ''\n if len(text)>0: result_string = ' '.join(list(text.lower()))\n if num.isdigit():\n if int(num)<1000:\n result_string = result_string + \" \" + cardinal(num)\n else:\n result_string = result_string + \" \" + telephone(num)\n return(result_string.strip()) \n except: \n return(key)\n\n\n# ## TELEPHONE\n\n# In[37]:\n\n\ndef telephone(x):\n try:\n result_string = ''\n for i in range(0,len(x)):\n if re.match('[0-9]+', x[i]):\n result_string = result_string + cardinal(x[i]) + ' '\n else:\n result_string = result_string + 'sil '\n return result_string.strip() \n except: \n return(x)\n\n\n# ## ELECTRONIC\n\n# In[41]:\n\n\ndef electronic(x):\n try:\n replacement = {'.' : 'dot', ':' : 'colon', '/':'slash', '-' : 'dash', '#' : 'hash tag', }\n result_string = ''\n if re.match('.*[A-Za-z].*', x):\n for char in x:\n if re.match('[A-Za-z]', char):\n result_string = result_string + letters(char) + ' '\n elif char in replacement:\n result_string = result_string + replacement[char] + ' '\n elif re.match('[0-9]', char):\n if char == 0:\n result_string = result_string + 'o '\n else:\n number = cardinal(char)\n for n in number:\n result_string = result_string + n + ' ' \n return result_string.strip() \n else:\n return(x)\n except: \n return(x)\n\n\n# ## FRACTIONS\n\n# In[45]:\n\n\ndef fraction(x):\n if x.find(\"½\") != -1:\n x = x.replace(\"½\",\"\").strip()\n if len(x) != 0: \n return p.number_to_words(x,andword='').replace(\"-\",\" \").replace(',','')+\" and a half\"\n else: \n return \"one half\"\n elif x.find(\"¼\") != -1:\n x = x.replace(\"¼\",\"\").strip()\n if len(x) != 0: \n return p.number_to_words(x,andword='').replace(\"-\",\" \").replace(',','')+\" and a quarter\"\n else: \n return \"one quarter\"\n elif x.find(\"⅓\") != -1:\n x = x.replace(\"⅓\",\"\").strip()\n if len(x) != 0: \n return p.number_to_words(x,andword='').replace(\"-\",\" \").replace(',','')+\" and a third\"\n else:\n return \"one third\"\n elif x.find(\"⅔\") != -1:\n x = x.replace(\"⅔\",\"\").strip()\n if len(x) != 0:\n return p.number_to_words(x,andword='').replace(\"-\",\" \").replace(',','')+\" and two thirds\"\n else:\n return \"two third\"\n elif x.find(\"⅞\") != -1:\n x = x.replace(\"⅞\",\"\").strip()\n if len(x) != 0:\n return p.number_to_words(x,andword='').replace(\"-\",\" \").replace(',','')+\" and seven eighths\"\n else:\n return \"seven eighth\"\n elif x.find(\" \") != -1:\n v = x.split(\" \")\n res = \" and \".join([fraction(val) for val in v])\n return res.replace(\"and one\",\"and a\")\n \n try:\n y = x.split('/')\n result_string = ''\n if len(y)==1 and y[0].isdigit(): return p.number_to_words(y[0],andword='').replace(\"-\",\" \").replace(',','')\n y[0] = p.number_to_words(y[0],andword='').replace(\"-\",\" \").replace(',','')\n y[1] = ordinal(y[1]).replace(\"-\",\" \").replace(\" and \",\" \").replace(',','')\n if y[1] == \"first\":\n return y[0]+\" over one\"\n if y[1] == 'fourth':\n if y[0]=='one': result_string = y[0] + ' quarter'\n else: result_string = y[0] + ' quarters'\n elif y[1] == 'second':\n if y[0]=='one': result_string = y[0] + ' half'\n else: result_string = y[0] + ' halves'\n else:\n if y[0]=='one': result_string = y[0] + \" \"+ y[1]\n else: result_string = y[0] + ' ' + y[1] + 's'\n return(result_string)\n except: \n return(x)\n\n\n# ## MONEY\n\n# In[20]:\n\n\ndef money(x):\n try:\n if re.match('^\\$', x):\n x = x.replace('$','')\n if len(x.split(' ')) == 1:\n if re.match('.*M|m$',x):\n x = x.replace('M', '')\n x = x.replace('m', '')\n text = cardinal(x)\n x = text + ' million dollars'\n elif re.match('.*b|B$', x):\n x = x.replace('B', '')\n x = x.replace('b', '')\n text = cardinal(x)\n x = text + ' million dollars'\n else:\n text = cardinal(x)\n x = text + ' dollars'\n return x.lower()\n elif len(x.split(' ')) == 2:\n text = cardinal(x.split(' ')[0])\n if x.split(' ')[1].lower() == 'million':\n x = text + ' million dollars'\n elif x.split(' ')[1].lower() == 'billion':\n x = text + ' billion dollars'\n return x.lower()\n if re.match('^US\\$', x):\n x = x.replace('US$','')\n if len(x.split(' ')) == 1:\n if re.match('.*M|m$', x):\n x = x.replace('M', '')\n x = x.replace('m', '')\n text = cardinal(x)\n x = text + ' million dollars'\n elif re.match('.*b|B$', x):\n x = x.replace('b', '')\n x = x.replace('B', '')\n text = cardinal(x)\n x = text + ' million dollars'\n else:\n text = cardinal(x)\n x = text + ' dollars'\n return x.lower()\n elif len(x.split(' ')) == 2:\n text = cardinal(x.split(' ')[0])\n if x.split(' ')[1].lower() == 'million':\n x = text + ' million dollars'\n elif x.split(' ')[1].lower() == 'billion':\n x = text + ' billion dollars'\n return x.lower()\n elif re.match('^£', x):\n x = x.replace('£','')\n if len(x.split(' ')) == 1:\n if re.match('.*M|m$', x):\n x = x.replace('M', '')\n x = x.replace('m', '')\n text = cardinal(x)\n x = text + ' million pounds'\n elif re.match('.*b|B$', x):\n x = x.replace('b', '')\n x = x.replace('B', '')\n text = cardinal(x)\n x = text + ' million pounds'\n else:\n text = cardinal(x)\n x = text + ' pounds'\n return x.lower()\n elif len(x.split(' ')) == 2:\n text = cardinal(x.split(' ')[0])\n if x.split(' ')[1].lower() == 'million':\n x = text + ' million pounds'\n elif x.split(' ')[1].lower() == 'billion':\n x = text + ' billion pounds'\n return x.lower() \n elif re.match('^€', x):\n x = x.replace('€','')\n if len(x.split(' ')) == 1:\n if re.match('.*M|m$', x):\n x = x.replace('M', '')\n x = x.replace('m', '')\n text = cardinal(x)\n x = text + ' million euros'\n elif re.match('.*b|B$', x):\n x = x.replace('B', '')\n x = x.replace('b', '')\n text = cardinal(x)\n x = text + ' million euros'\n else:\n text = cardinal(x)\n x = text + ' euros'\n return x.lower()\n elif len(x.split(' ')) == 2:\n text = cardinal(x.split(' ')[0])\n if x.split(' ')[1].lower() == 'million':\n x = text + ' million euros'\n elif x.split(' ')[1].lower() == 'billion':\n x = text + ' billion euros'\n return x.lower() \n except: \n return(x)\n\n","sub_path":"FYP_Phase-II/writtenToSpoken.py","file_name":"writtenToSpoken.py","file_ext":"py","file_size_in_byte":25991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"623765807","text":"\r\nimport pygame\r\nimport random as rd\r\n\r\n# iniitializing pygame\r\npygame.init()\r\n\r\n# setting up colors for background and othe objects\r\nblack = (0, 0, 0)\r\nwhite = (255, 255, 255)\r\n\r\n# define the pygame window size\r\nscreen = pygame.display.set_mode([500, 500])\r\n\r\n# set screen background color\r\nscreen.fill(black)\r\n\r\n# push changes to the display\r\npygame.display.update()\r\n\r\n# counter to monitor screen status\r\nrunning = True\r\n\r\n# Randomly set the no of stars present on screen that are used to draw line\r\nstar_count = rd.randrange(50, 70)\r\n\r\nfor i in range(10):\r\n\r\n screen.fill(black)\r\n # to make screen blank after each round\r\n\r\n # list to store randomly geneated x and y position of each star\r\n rdm_xpos_list = []\r\n rdm_ypos_list = []\r\n\r\n for i in range(star_count):\r\n \r\n # for each star generate a random x&y pos\r\n rdm_xpos = rd.randrange(0, 500)\r\n rdm_ypos = rd.randrange(0, 500)\r\n\r\n # store star position in list\r\n rdm_xpos_list.append(rdm_xpos)\r\n rdm_ypos_list.append(rdm_ypos)\r\n\r\n # draw star to the screen\r\n pygame.draw.circle(screen, white,\r\n (rdm_xpos, rdm_ypos), 1, 1)\r\n # push changes to the screen\r\n pygame.display.update()\r\n\r\n # wait for some time \r\n pygame.time.wait(250)\r\n\r\n # set numnber of static stars i.e to make sure universe doen't appear to be \r\n # devoid of stars when we warp\r\n rand_star_count2 = rd.randrange(30,50)\r\n\r\n # draw static stars to the screen\r\n for q in range(rand_star_count2):\r\n rdm_xpos = rd.randrange(0, 500)\r\n rdm_ypos = rd.randrange(0, 500)\r\n pygame.draw.circle(screen, white,\r\n (rdm_xpos, rdm_ypos), 1, 1)\r\n \r\n # push changes to the screen\r\n pygame.display.update()\r\n\r\n # randomly geneate a number to set counter for specifying line direction \r\n # on the screen with respect to X-pos of the star\r\n randx_counter = rd.randrange(200, 270)\r\n\r\n # draw lines from star positions to give warp effect\r\n for i in range(star_count):\r\n if(rdm_xpos_list[i] <= randx_counter):\r\n pygame.draw.line(screen, white, (rdm_xpos_list[i], rdm_ypos_list[i]), (\r\n rdm_xpos_list[i]-40, rdm_ypos_list[i]+55), 6)\r\n else:\r\n pygame.draw.line(screen, white, (rdm_xpos_list[i], rdm_ypos_list[i]), (\r\n rdm_xpos_list[i]+40, rdm_ypos_list[i]+55), 6)\r\n pygame.time.wait(2)\r\n pygame.display.update()\r\n \r\n# monitor window status is window open or has been closed \r\nwhile running:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n\r\n#stop the simulation\r\npygame.quit()\r\n\r\n# references - \r\n# https://thecodingtrain.com/CodingChallenges/001-starfield.html\r\n# https://editor.p5js.org/codingtrain/sketches/1wLHIck3T\r\n# https://realpython.com/pygame-a-primer/\r\n# https://sites.cs.ucsb.edu/~pconrad/cs5nm/topics/pygame/drawing/index.html\r\n# https://www.youtube.com/watch?v=SmxMw37pqJ8\r\n# http://www.petercollingridge.co.uk/tutorials/3d/pygame/\r\n# https://stackoverflow.com/\r\n# https://pythonprogramming.net/opengl-rotating-cube-example-pyopengl-tutorial/\r\n","sub_path":"starwarp.py","file_name":"starwarp.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"238462436","text":"import threading\n\nfrom django.core.mail import EmailMessage\n\n\ndef sendEmailThread(message, title, email_addres, task):\n thread = myThread(\n 1,\n \"Sending Email\",\n task=task,\n message=message,\n title=title,\n email_addres=email_addres,\n )\n thread.start()\n\n\nclass myThread(threading.Thread):\n def __init__(self, threadID, name, task, message, title, email_addres):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.message = message\n self.title = title\n self.email_addres = email_addres\n self.task = task\n\n def run(self):\n self.sendEmail()\n\n def sendEmail(self):\n email = EmailMessage(self.title, self.message, to=self.email_addres)\n email.content_subtype = \"html\"\n try:\n email.send()\n except Exception as e:\n print(\"Error\", self.task.name, \":\", e)\n self.task.status = 4\n self.task.save()\n else:\n print(\"Sucess\", self.task.name)\n self.task.status = 3\n self.task.save()\n","sub_path":"tasks/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"198934679","text":"import logging\nimport pickle\n\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n\n# ------------------------------------------- #\n# producing (or loading, if already produced) #\n# the Glove embeddings\t\t\t\t\t\t #\n# ------------------------------------------- #\ndef produce_Glove_embedding(glove_file, output_dic):\n\tf = open(glove_file, 'r', encoding='utf-8')\n\tmodel = {}\n\tline_number = 1\n\tfor line in f:\n\t\tsplit_line = line.split()\n\t\tword = split_line[0]\n\t\ttry:\n\t\t\tembedding = [float(val) for val in split_line[1:]]\n\t\t\tmodel[word] = embedding\n\t\texcept ValueError as e:\n\t\t\tprint(\"Error\", e, \"on line\", line_number, \"\\n\", line)\n\t\t\tpass\n\t\tline_number += 1\n\twith open(output_dic, 'wb') as handle:\n\t\tpickle.dump(model, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\tlogger.info(\"produced and saved the dictionary\")\n\n\ndef load_Glove_embedding(input_dic):\n\twith open(input_dic, 'rb') as handle:\n\t\tlogger.info(\"loading the model\")\n\t\treturn pickle.load(handle)\n\n\n# ------------------ #\n# running the script #\n# ------------------ #\nif __name__ == \"__main__\":\n\tglove_file = \"Glove_embeddings.txt\" # <-- path to the actual Glove embeddings\n\toutput_pickle = \"glove_model.pickle\"\n\n\t# produce_Glove_model(glove_file, output_dic)\n\tproduce_Glove_embedding(glove_file, output_pickle)\n","sub_path":"src/sentences_embeddings/Glove_embeddings/Glove_embeddings.py","file_name":"Glove_embeddings.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"14431611","text":"from scrapy.crawler import CrawlerProcess\nfrom scraping.scraping.spiders.forecast import ForecastSpider\n\n\ndef run_spider():\n process = CrawlerProcess(\n settings={\n \"ROBOTSTXT_OBEY\": True,\n \"DOWNLOAD_DELAY\": 3,\n \"ITEM_PIPELINES\": {\"scraping.scraping.pipelines.ForecastPipeline\": 300,},\n }\n )\n process.crawl(ForecastSpider)\n process.start(stop_after_crawl=False)\n","sub_path":"services/web/scraping/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"133455691","text":"\"\"\"\nThe following demonstrates a Noise_IK_25519_AESGCM_SHA256 that fails during handshake, making initiator and responder\nswitch to Noise_XXfallback_25519_AESGCM_SHA256\n\"\"\"\nfrom noise.processing.impl.handshakestate import HandshakeState\nfrom noise.processing.impl.symmetricstate import SymmetricState\nfrom noise.processing.impl.cipherstate import CipherState\nfrom noise.processing.handshakepatterns.interactive.XX import XXHandshakePattern\nfrom noise.processing.handshakepatterns.interactive.IK import IKHandshakePattern\nfrom noise.processing.modifiers.fallback import FallbackPatternModifier\nfrom noise.cipher.aesgcm import AESGCMCipher\nfrom noise.dh.x25519.x25519 import X25519DH\nfrom noise.hash.sha256 import SHA256Hash\nfrom noise.exceptions.decrypt import DecryptFailedException\nimport noise, logging\n\n\nif __name__ == \"__main__\":\n noise.logger.setLevel(logging.DEBUG)\n # setup initiator and responder variables\n alice_s = X25519DH().generate_keypair()\n alice_rs = X25519DH().generate_keypair().public\n bob_s = X25519DH().generate_keypair()\n\n # prepare handshakestate objects for initiator and responder\n alice_handshakestate = HandshakeState(\n SymmetricState(\n CipherState(\n AESGCMCipher()\n ),\n SHA256Hash()\n ),\n X25519DH()\n )\n bob_handshakestate = HandshakeState(\n SymmetricState(\n CipherState(\n AESGCMCipher()\n ),\n SHA256Hash()\n ),\n X25519DH()\n )\n # initialize handshakestate objects\n alice_handshakestate.initialize(IKHandshakePattern(), True, b'', s=alice_s, rs=alice_rs)\n bob_handshakestate.initialize(IKHandshakePattern(), False, b'', s=bob_s)\n\n # -> e, es, s, ss\n message_buffer = bytearray()\n alice_handshakestate.write_message(b'', message_buffer)\n try:\n bob_handshakestate.read_message(bytes(message_buffer), bytearray())\n except DecryptFailedException:\n # bob failed to read alice's message, possibly because alice used wrong static keys for bob, will now fallback\n # to XX\n bob_handshakestate.initialize(\n FallbackPatternModifier().modify(XXHandshakePattern()), False, b'', s=bob_s, re=bob_handshakestate.re\n )\n\n # <- e, ee, s, es\n message_buffer = bytearray()\n bob_handshakestate.write_message(b'', message_buffer)\n\n try:\n # alice doesn't yet know about the XX fallback switch and still expects IK's (e, ee, se) pattern\n alice_handshakestate.read_message(bytes(message_buffer), bytearray())\n except DecryptFailedException:\n # alice failed to read bob's message. but alice and bob had a pre-agreement that if will happen if bob for\n # whatever reason descides to fall back to XX, an therefore so must alice\n alice_handshakestate.initialize(\n FallbackPatternModifier().modify(XXHandshakePattern()), True, b'', s=alice_s, e=alice_handshakestate.e\n )\n\n # alice should now successfuly read bob's message, which includes bob's new static public key.\n alice_handshakestate.read_message(bytes(message_buffer), bytearray())\n\n # -> s, se\n message_buffer = bytearray()\n alice_cipherstates = alice_handshakestate.write_message(b'', message_buffer)\n bob_cipherstates = bob_handshakestate.read_message(bytes(message_buffer), bytearray())\n\n # transport phase\n # alice to bob\n ciphertext = alice_cipherstates[0].encrypt_with_ad(b'', b'Hello')\n plaintext = bob_cipherstates[0].decrypt_with_ad(b'', ciphertext)\n assert plaintext == b'Hello'\n\n # bob to alice\n ciphertext = bob_cipherstates[1].encrypt_with_ad(b'', b'World')\n plaintext = alice_cipherstates[1].decrypt_with_ad(b'', ciphertext)\n assert plaintext == b'World'\n","sub_path":"examples/patterns/Noise_XXfallback_25519_AESGCM_SHA256.py","file_name":"Noise_XXfallback_25519_AESGCM_SHA256.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"538358594","text":"from django.http import Http404, HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render_to_response\nfrom django.contrib.auth.decorators import login_required\nfrom django.template.context import RequestContext\nfrom google.appengine.ext import ndb\nfrom django.template.defaultfilters import slugify\n\nfrom gae_django.auth.models import User\n\nfrom july.people.models import Commit, Location\n\ndef user_profile(request, username):\n user = User.get_by_auth_id('twitter:%s' % username)\n if user == None:\n raise Http404(\"User not found\")\n\n commits = Commit.query(ancestor=user.key).order(-Commit.timestamp).fetch(100)\n\n return render_to_response('people/profile.html', \n {\"commits\":commits, 'profile':user}, \n context_instance=RequestContext(request)) \n\ndef users_by_location(request, location_slug, \n template_name='people/people_list.html'):\n\n users = User.query(User.location_slug == location_slug)\n users.order(-ndb.GenericProperty('total')).fetch(1000)\n\n location = Location.get_by_id(location_slug)\n \n return render_to_response(template_name, \n {'users':users, 'location': location, 'slug': location_slug}, \n context_instance=RequestContext(request)) \n\ndef locations(request, template_name='people/locations.html'):\n\n locations = Location.query().order(-Location.total).fetch(1000)\n \n return render_to_response(template_name,\n {'locations': locations},\n context_instance=RequestContext(request))\n \n@login_required\ndef edit_profile(request, username, template_name='people/edit.html'):\n from forms import EditUserForm\n user = User.get_by_auth_id('twitter:%s' % username)\n\n if user == None:\n raise Http404(\"User not found\")\n \n if user.key != request.user.key:\n http403 = HttpResponse(\"This ain't you!\")\n http403.status = 403\n return http403\n \n\n form = EditUserForm(request.POST or None, user=request.user)\n if form.is_valid():\n for key in form.cleaned_data:\n if key == 'email':\n continue\n setattr(user, key, form.cleaned_data.get(key))\n slugify(user.location)\n user.put()\n return HttpResponseRedirect(\n reverse('member-profile', \n kwargs={'username':request.user.username}\n )\n )\n \n \n\n return render_to_response(template_name, \n {'form':form}, \n context_instance=RequestContext(request))\n\n@login_required\ndef delete_email(request, username, email):\n \n # the ID we are to delete\n auth_id = 'email:%s' % email\n \n user = User.get_by_auth_id('twitter:%s' % username)\n e_user = User.get_by_auth_id(auth_id)\n\n if user is None or e_user is None:\n raise Http404(\"User not found\")\n \n if user != request.user or user != e_user:\n http403 = HttpResponse(\"This ain't you!\")\n http403.status = 403\n return http403\n \n if request.method == \"POST\":\n # delete the email from the user\n user.auth_ids.remove(auth_id)\n user.unique_model.delete_multi(['User.auth_id:%s' % auth_id])\n user.put()\n return HttpResponseRedirect(\n reverse('member-profile', kwargs={'username':request.user.username})\n )\n \n \n\n return render_to_response('people/delete_email.html', \n {'email': email}, \n context_instance=RequestContext(request))\n","sub_path":"july/people/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"494971341","text":"from DBModels.KB_Names import *\nfrom controllers.DataCleaning import Patterns as pat\nfrom controllers.Sentiment_Analysis.Sentiment_Identification import *\n\nnum_partitions = 6 # number of partitions to split dataframe\nnum_cores = 6 # number of cores on your machine\ncolumns = ['Tweet', 'binay', 'duterte', 'poe', 'roxas', 'santiago']\n\nscript_path = os.path.dirname(os.path.dirname(__file__))\nfile_path = os.path.join(script_path, \"controllers\", \"stop_words\")\n\n# loads stop words list from file\nstopwords = pd.read_csv(file_path + \"/final_stop_words_list.csv\", header=None, squeeze=True).tolist()\n# loads contractions from file\ncontractions = pd.read_csv(file_path + \"/contractions.csv\", header=None, delimiter=',')\ndictionary = dict(zip(contractions[0].tolist(), contractions[1].tolist()))\n\nc_re = re.compile('(%s)' % '|'.join(dictionary.keys()))\n\n# path for classifiers\ns_path = os.path.dirname(os.path.dirname(__file__))\npath = os.path.join(s_path, \"controllers\", \"Pickles\", \"ML_Classifier\")\n\n# load pickled classififer\nwith open(os.path.join(path, 'LSVC.pkl'), 'rb') as fid:\n lscv_clf = pickle.load(fid)\n\n\ndef read_csv(filename):\n return pd.read_csv(filename, encoding=\"utf8\", keep_default_na=False, index_col=None,\n sep=\",\", skipinitialspace=True, usecols=['Tweet'], chunksize=100000)\n\n\ndef get_mention_index(tweet, candidate_names):\n # returns the position of the names used for the candidate in the tweet,\n # if candidate was not mentioned -1 is returned\n\n index = next((tweet.index(word) for word in tweet if any(name in word\n for name in candidate_names)), -1)\n return index\n\n\ndef process_df(candidate_data, tweet_df):\n for candidate in candidate_data:\n tweet_df[candidate['candidate_name']] = tweet_df.apply(lambda row: get_mention_index(row['tweet_cleaned'],\n candidate['kb_names']),\n axis=1)\n return tweet_df\n\n\ndef lower_split_tweet(tweet):\n return tweet.lower().split(' ')\n\n\ndef identify_candidate(candidate_data, tweet_df):\n # convert all tweets to list of words\n # if isinstance(tweet_df['Tweet'].iloc[0], list):\n # tweet_df['Tweet'] = tweet_df.apply(lambda row: row['Tweet'], axis=1)\n # else:\n # tweet_df['tweet_cleaned'] = tweet_df.apply(lambda row: lower_split_tweet(row['tweet_cleaned']), axis=1)\n\n # creates a new column per candidate and stores the index of word mentioned for the candidate\n # tweet_df = parallelize_dataframe(tweet_df, process_df, candidate_data)\n\n tweet_df = process_df(candidate_data, tweet_df)\n\n return tweet_df\n\n\ndef parallelize_chunk(chunk, func, candidate_data):\n df_split = np.array_split(chunk, num_partitions)\n pool = Pool(num_cores)\n func = partial(func, candidate_data)\n df = pd.concat(pool.map(func, df_split))\n pool.close()\n pool.join()\n return df\n\n\ndef find_more_names(tweets):\n candidate_names = get_all_kb_names()\n results = {}\n\n for candidate in candidate_names:\n l1 = [word for tweet in tweets for word in tweet if any(name in word for name in candidate['kb_names'])]\n l1_unique = list(set(l1))\n l1_final = [x for x in l1_unique if x not in candidate['blacklist_names']]\n\n results[candidate['candidate_name']] = l1_final\n\n # for candidate in candidate_names:\n # results[candidate['candidate_name']] = list(set([word for tweet in tweets for word in tweet\n # if any(name in word for name in candidate['kb_names'])\n # and (word not in candidate['blacklist_names'])]))\n\n kb_names_update(results)\n\n\ndef write_csv(filename, tweets):\n import os\n # if file does not exist write header\n if not os.path.isfile(filename):\n return tweets.to_csv(filename, header=True, sep=',', columns=columns, index=False, chunksize=10000)\n else: # else it exists so append without writing the header\n return tweets.to_csv(filename, mode='a', sep=',', columns=columns, index=False, header=False, chunksize=10000)\n\n\ndef write_data(filename, data):\n import os\n # if file does not exist write header\n if not os.path.isfile(filename):\n return data.to_csv(filename, header=True, sep=',', index=False)\n else: # else it exists so append without writing the header\n return data.to_csv(filename, mode='a', sep=',', index=False, header=False)\n\n\ndef expand_contractions(text, c_re=c_re):\n def replace(match):\n return dictionary[match.group(0)]\n\n return c_re.sub(replace, text)\n\n\ndef init_data_cleaning(tweet):\n # removes URL, hashtags, HTML, and Reserved words\n tweet = pat.remove_from_tweet(tweet)\n # converts the tweets to lowercase\n tweet = tweet.lower()\n # expand contradictions\n tweet = expand_contractions(tweet)\n\n split_tweet = tweet.split(' ')\n split_tweet = filter(None, split_tweet)\n\n # standardize words collapse to 2 letter ex: cooool to cool\n tweet = ' '.join([(re.sub(r'(.)\\1+', r'\\1\\1', word)) if word[0] != '@' else word for word in split_tweet])\n\n # processes emoticons\n # positive\n tweet = re.sub(\"[:;8=x][-oc]*[>D)}P\\]3]+\", \"POSEMOTE\", tweet)\n tweet = re.sub(\"[<({\\[]+[-o]*[:;8=x]\", \"POSEMOTE\", tweet)\n\n tweet = re.sub(\"[:;8=x][-oc]*[<({\\[]+\", \"NEGEMOTE\", tweet)\n tweet = re.sub(\"[>D)}\\]]+[-o]*[:;8=x]\", \"NEGEMOTE\", tweet)\n\n # remove punctuation marks\n tweet = re.sub('[^A-Za-z0-9@ ]+', ' ', tweet)\n\n split_tweet = tweet.split(' ')\n\n # remove stopwords\n split_tweet = [word for word in split_tweet if word not in stopwords]\n\n # remove shortwords 1-2 characters\n split_tweet = [word for word in split_tweet if len(word) > 1]\n\n # remove extra spaces between words\n tweet = ' '.join(split_tweet)\n\n # return tweet.split(' ')\n return tweet\n\n\ndef cleaning(df):\n df['tweet_cleaned'] = df.apply(lambda row: init_data_cleaning(row['Tweet']), axis=1)\n return df\n\n\ndef parallelize_cleaning(df, func):\n df_split = np.array_split(df, num_partitions)\n pool = Pool(num_cores)\n df = pd.concat(pool.map(func, df_split))\n pool.close()\n pool.join()\n return df\n\n\ndef start_process(file_name):\n filepath = \"/home/dudegrim/Documents/CSV8/\"\n\n print(\"Start\", file_name)\n reader = read_csv(filepath + file_name)\n results = pd.DataFrame()\n\n # gets all the known candidate names in the database\n candidate_data = get_all_kb_names()\n\n for ctr, chunk1 in enumerate(reader):\n # add usernames to DB\n cleaned = parallelize_cleaning(chunk1, cleaning)\n results = parallelize_chunk(cleaned, identify_candidate, candidate_data)\n # this removes empty tweets after cleaning\n results.drop(results[results.tweet_cleaned == \"\"].index, inplace=True)\n\n # find_more_names(results[\"tweet_cleaned\"])\n\n cand_count = {}\n for candidate in candidate_data:\n cand_df = results[results[candidate['candidate_name']] >= 0]\n\n cand_count[candidate['candidate_name']] = len(cand_df)\n # save the stuff\n write_csv(\"/home/dudegrim/Documents/whole/\" + candidate['candidate_name'] + \".csv\", cand_df)\n\n data_count = pd.DataFrame(cand_count, index=[0])\n\n write_data(\"/home/dudegrim/Documents/whole/candidate_data_count.csv\", data_count)\n\n return\n\n\ndef bitch_file():\n filepath = \"/home/dudegrim/Documents/CSV8/Election-13.csv\"\n\n print(\"Start\", \"Bitch\")\n reader = read_csv(filepath)\n results = pd.DataFrame()\n\n # gets all the known candidate names in the database\n candidate_data = get_all_kb_names()\n\n for ctr, chunk1 in enumerate(reader):\n\n chunk1['tweet_cleaned'] = [init_data_cleaning(row['Tweet']) for key, row in chunk1.iterrows()]\n results = parallelize_chunk(chunk1, identify_candidate, candidate_data)\n # this removes empty tweets after cleaning\n results.drop(results[results.tweet_cleaned == \"\"].index, inplace=True)\n\n # find_more_names(results[\"tweet_cleaned\"])\n\n cand_count = {}\n for candidate in candidate_data:\n cand_df = results[results[candidate['candidate_name']] >= 0]\n\n cand_count[candidate['candidate_name']] = len(cand_df)\n # save the stuff\n write_csv(\"/home/dudegrim/Documents/whole/\" + candidate['candidate_name'] + \".csv\", cand_df)\n\n data_count = pd.DataFrame(cand_count, index=[0])\n\n write_data(\"/home/dudegrim/Documents/whole/candidate_data_count.csv\", data_count)\n\n return\n\n\ndef lscv_sentiment(tweet_list):\n # predict sentiment of tweet\n return lscv_clf.predict(tweet_list)\n\n\ndef read_csv_sentiment(filename):\n print(filename)\n return pd.read_csv(filename, encoding=\"utf8\", keep_default_na=False, index_col=None,\n sep=\",\", skipinitialspace=True, usecols=columns, chunksize=100000, engine='python')\n\n\ndef process_sentiment():\n filepath = \"/home/dudegrim/Documents/whole/\"\n\n results = pd.DataFrame()\n\n # gets all the known candidate names in the database\n candidate_data = get_all_kb_names()\n\n for cand in candidate_data:\n reader = read_csv_sentiment(filepath + cand['candidate_name'] + \".csv\")\n\n for ctr, chunk1 in enumerate(reader):\n chunk1['tweet_cleaned'] = chunk1.apply(lambda row: init_data_cleaning(row['Tweet']), axis=1)\n chunk1['sentiment'] = lscv_sentiment(chunk1['tweet_cleaned'])\n\n positive_tweets = chunk1.loc[chunk1['sentiment'] == \"Positive\"]\n neutral_tweets = chunk1.loc[chunk1['sentiment'] == \"Neutral\"]\n negative_tweets = chunk1.loc[chunk1['sentiment'] == \"Negative\"]\n\n write_csv(\"/home/dudegrim/Documents/whole/Sentiment/positive_tweets_\" + cand['candidate_name'] + \".csv\",\n positive_tweets)\n write_csv(\"/home/dudegrim/Documents/whole/Sentiment/neutral_tweets_\" + cand['candidate_name'] + \".csv\",\n neutral_tweets)\n write_csv(\"/home/dudegrim/Documents/whole/Sentiment/negative_tweets_\" + cand['candidate_name'] + \".csv\",\n negative_tweets)\n\n data_count = pd.DataFrame({'Positive': len(positive_tweets), 'Neutral': len(neutral_tweets),\n 'Negative': len(negative_tweets)}, index=[0])\n\n write_data(\"/home/dudegrim/Documents/whole/Sentiment/data_count_\" + cand['candidate_name'] + \".csv\",\n data_count)\n\n\n# start = time.time()\n# process_sentiment()\n# end = time.time()\n# print(end-start)\n\n# for r in range(14, 18, 1):\n# print(r)\n# start = time.time()\n# start_process(\"Election-\"+str(r)+\".csv\")\n# end = time.time()\n# print(end-start)\n# bitch_file()\n\n\nprocess_sentiment()\n","sub_path":"test scripts/whole_db.py","file_name":"whole_db.py","file_ext":"py","file_size_in_byte":10922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"490405698","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : main.py\n# @Author: muyao\n# @Date : 2020/2/4/004\n\nimport torch\nfrom pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport matplotlib.pyplot as plt\n\n# Load pre-trained model tokenizer (vocabulary)\n# F:\\Corpus\\uncased_L-12_H-768_A-12\n\ntokenizer = BertTokenizer.from_pretrained('F:\\\\Corpus\\\\uncased_L-12_H-768_A-12')\nprint(\"tokenizer: \", tokenizer, '\\n')\n\n# BERT tokenizer模型的词汇量限制大小为30,000\n# 句子切分示例1\ntext1 = \"Here is the sentence I want embeddings for the sentence.\"\nmarked_text1 = \"[CLS] \" + text1 + \" [SEP]\"\nprint(\"marked_text1: \", marked_text1)\ntokenized_text1 = tokenizer.tokenize(marked_text1)\nprint(\"tokenized_text1: \", tokenized_text1, '\\n')\n\n# 句子切分示例2\ntext2 = \"After stealing money from the bank vault, the bank robber was seen fishing on the Mississippi river bank.\"\nmarked_text2 = \"[CLS] \" + text2 + \" [SEP]\"\nprint(\"marked_text2: \", marked_text2)\ntokenized_text2 = tokenizer.tokenize(marked_text2)\nprint(\"tokenized_text2: \", tokenized_text2, '\\n')\n\n# 下面是词汇表中包含的一些token示例。以两个#号开头的标记是子单词或单个字符。\nprint(\"词汇表中包含的一些token示例: \", list(tokenizer.vocab.keys())[5000:5020])\nprint(\"词汇表长度 =\", len(tokenizer.vocab.keys()), '\\n')\n\n# 调用tokenizer来匹配tokens在词汇表中的索引\nindexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text1)\nprint(\"tokenized_text1: \", tokenized_text1)\nprint(\"tokenized_text1中每个词在词汇表的索引(indexed_tokens): \", indexed_tokens)\nfor tup in zip(tokenized_text1, indexed_tokens):\n print(tup)\nprint('\\n')\n\n# Segment ID 区分句子: 单句id全为1;若两个句子,第一句加[SEP] 所有token赋值为0,第二句所有token赋值为1。\nsegments_ids = [1] * len(tokenized_text1)\nprint(\"segments_ids: \", segments_ids, '\\n')\n\n# 开始调用bert\n# 把输入list转换为PyTorch tensors\ntokens_tensor = torch.tensor([indexed_tokens]) # 索引list -> tensor\nsegments_tensors = torch.tensor([segments_ids]) # seg嵌入list -> tensor\nprint(\"tokens_tensor: \", tokens_tensor, tokens_tensor.shape)\nprint(\"segments_tensors: \", segments_tensors, segments_tensors.shape, '\\n')\n\n# Load pre-trained model (weights)\nprint(\"=========load model=========\")\nmodel = BertModel.from_pretrained(pretrained_model_name_or_path='F:\\\\Corpus\\\\uncased_L-12_H-768_A-12',\n from_tf=False, cache_dir='cache')\n# 模型置于评估模式,而不是训练模式 关闭了训练中使用的dropout正则化\nmodel.eval()\n# print(model, \"\\n\")\n\n# Predict hidden states features for each layer\n# torch.no_grad禁用梯度计算,节省内存,并加快计算速度(我们不需要梯度或反向传播,因为我们只是运行向前传播)。\nwith torch.no_grad():\n encoded_layers, _ = model(tokens_tensor, segments_tensors)\n # 这个模型的全部隐藏状态存储在对象“encoded_layers”中。这个对象有四个维度,顺序如下:\n # 1.层数(12层)\n # 2.batch号(1句)\n # 3.单词/令牌号(在我们的句子中有14个令牌)\n # 4.隐藏单元/特征号(768个特征)\n print(\"len of encoded_layers(type:list): \", len(encoded_layers))\n print(\"encoded_layers[0].shape: \", encoded_layers[0].shape)\n\n print(\"Number of layers:\", len(encoded_layers))\n layer_i = 0\n print(\"Number of batches:\", len(encoded_layers[layer_i]))\n batch_i = 0\n print(\"Number of tokens:\", len(encoded_layers[layer_i][batch_i]))\n token_i = 0\n print(\"Number of hidden units:\", len(encoded_layers[layer_i][batch_i][token_i]), '\\n')\n\n # 查看一下给定层5和token5的值范围\n token_i = 5\n layer_i = 5\n vec = encoded_layers[layer_i][batch_i][token_i]\n # 绘制直方图\n plt.figure(figsize=(10, 10))\n plt.hist(vec, bins=200)\n plt.show()\n\n # 按token摘出来, 每个token 12层中每层有768维度\n token_embeddings = [] # [# tokens, # layers, # features]\n for token_i in range(len(tokenized_text1)):\n # Holds 12 layers of hidden states for each token\n hidden_layers = []\n # For each of the 12 layers...\n for layer_i in range(len(encoded_layers)):\n # Lookup the vector for `token_i` in `layer_i`\n vec = encoded_layers[layer_i][batch_i][token_i]\n hidden_layers.append(vec)\n token_embeddings.append(hidden_layers)\n # Sanity check the dimensions:\n print(\"Number of tokens in sequence:\", len(token_embeddings))\n print(\"Number of layers per token:\", len(token_embeddings[0]))\n\n # 每个token有12个768dim的表示 怎么得到token的最终表示呢?\n # bert作者实验了一波发现 最后四层横向拼接(768 768 768 768) 效果最好\n\n # 下��分别用最后四层的 横向拼接/直接求和 来创建单词向量\n concatenated_last_4_layers = [torch.cat((layer[-1], layer[-2], layer[-3], layer[-4]), 0)\n for layer in token_embeddings] # [number_of_tokens, 3072]\n summed_last_4_layers = [torch.sum(torch.stack(layer)[-4:], 0)\n for layer in token_embeddings] # [number_of_tokens, 768]\n\n # 句子向量:每个token的倒数第二层表示 求平均\n sentence_embedding = torch.mean(encoded_layers[11], 1)\n print(\"句子向量shape:\", sentence_embedding[0].shape, '\\n')\n\n # 验证上下文相关性 :输出每个token的768维embed的前5维,看看句子中相同单词“sentence”编码是不是一样(不一样)\n for idx, token in enumerate(tokenized_text1):\n print(idx, token,\n '\\n最后四层相加的方式(前5维):', summed_last_4_layers[idx][:5],\n '\\n最后四层拼接的方式(前5维):', concatenated_last_4_layers[idx][:5])\n\n print(cosine_similarity(summed_last_4_layers[4].reshape(1, -1),\n summed_last_4_layers[13].reshape(1, -1))[0][0])\n print(cosine_similarity(concatenated_last_4_layers[4].reshape(1, -1),\n concatenated_last_4_layers[13].reshape(1, -1))[0][0])\n","sub_path":"bert_eng.py","file_name":"bert_eng.py","file_ext":"py","file_size_in_byte":6188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"192210335","text":"import re\n\nfrom .transform import Transform\nfrom ..dataparsers import DefaultChain\nfrom ..models import Citation\n\nfrom concurrent.futures import as_completed\nfrom urllib.parse import urlparse\n\n\nclass FillExternal(Transform):\n def __init__(self, ctx=None):\n super().__init__(ctx)\n\n def apply(self, wikicode):\n futures = set()\n\n linkCount = 0\n completeCount = 0\n errors = []\n\n self._ctx.reportProgress('SCANNING', 0, {})\n for tag in wikicode.ifilter_external_links(recursive=False):\n if tag.title:\n continue\n\n linkCount += 1\n\n url = str(tag.url)\n futures.add(self._ctx.executor.submit(self._fulfill, url, tag))\n\n for future in as_completed(futures):\n try:\n future.result()\n except Exception as e:\n raise\n errors.append(str(e))\n else:\n completeCount += 1\n\n self._ctx.reportProgress('FETCHING', completeCount / linkCount, {\n 'errors': errors\n })\n\n return wikicode\n\n def _fulfill(self, url, tag):\n citation = Citation()\n citation.url = url\n citation.freezeOriginal()\n\n for p in DefaultChain:\n p.apply(citation)\n\n tag.title = citation.title\n tag.brackets = True\n","sub_path":"backend/refill/transforms/fillexternal.py","file_name":"fillexternal.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66852546","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"Q1mi\"\n\n\"\"\"\nlogging配置\n\"\"\"\n\nimport os\nimport logging.config\nfrom datetime import datetime\n\nclass myLogger():\n def __init__(self, LogPath = None):\n\n # 定义三种日志输出格式 开始\n self.standard_format = '[%(asctime) -s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \\\n '[%(levelname)s][%(message)s]'\n self.simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'\n self.id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'\n\n self.logfile_dir = os.path.dirname(os.path.abspath(LogPath)) + '\\\\log\\\\' # log文件的目录\n\n # 如果不存在定义的日志目录就创建一个\n if not os.path.isdir(self.logfile_dir):\n os.mkdir(self.logfile_dir)\n\n self.logfile_name = datetime.now().strftime('%Y-%m-%d')+ '.log' # log文件名\n\n # log文件的全路径\n self.logfile_path = os.path.join(self.logfile_dir, self.logfile_name)\n\n # log配置字典\n self.LOGGING_DIC = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'standard': {\n 'format': self.standard_format,\n 'datefmt': '%Y-%m-%d %H:%M:%S',\n },\n 'simple': {\n 'format': self.simple_format\n },\n },\n 'filters': {},\n 'handlers': {\n 'console': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler', # 打印到屏幕\n 'formatter': 'simple'\n },\n 'default': {\n 'level': 'INFO',\n 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件\n 'filename': self.logfile_path, # 日志文件\n 'maxBytes': 1024*1024*5, # 日志大小 5M\n 'backupCount': 5,\n 'formatter': 'standard',\n 'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕\n 'level': 'DEBUG',\n 'propagate': True, # 向上(更高level的logger)传递\n },\n },\n }\n logging.config.dictConfig(self.LOGGING_DIC) # 导入上面定义的配置\n self.wt = logging.getLogger(__name__) # 生成一个log实例\n \n# logger.info('It works!') # 记录该文件的运行状态\n# logger.debug('debug message')\n# logger.info('info message')\n# logger.warning('warning message')\n# logger.error('error message')\n# logger.critical('critical message')","sub_path":"logger_package/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29708669","text":" \n# from torch.autograd import Variable\nimport numpy as np\nimport pdb \nimport matplotlib.pyplot as plt \nmin_lr = 1e-4 \nlr = 1e-3 \nmax_epoches = 20 \n\nlr_decay_f = (min_lr/lr)**(1./(max_epoches-1) )\n\ndef adjust_lr(cur_lr, lr_decay_f):\n\tlr = cur_lr*lr_decay_f \n\tprint('===> cur_lr %.5f, updated lr %.5f, decay factor %.4f'%(cur_lr, lr, lr_decay_f))\n\treturn lr \nlr_array = []\nepoches = []\nfor i in range(max_epoches):\n\tepoches.append(i)\n\tlr_array.append(lr)\n\tlr = adjust_lr(lr, lr_decay_f)\n\nplt.plot(lr_array)\nplt.show() \n","sub_path":"HW3/submission/code/part2/junks/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"327855617","text":"from flask import Flask, flash, redirect, render_template, request, session, send_from_directory, Response, send_file\nfrom cs50 import SQL\nfrom flask_session import Session\nfrom tempfile import mkdtemp\nfrom datetime import datetime\nimport xlsxwriter\nimport os\n\napp = Flask(__name__, static_folder='/project/excel')\n\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\napp.config[\"SESSION_FILE_DIR\"] = mkdtemp()\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\n\ndb = SQL(\"sqlite:///database.db\")\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n\n placas = request.form.get('placas')\n arreglo = request.form.get('arreglos')\n costo = request.form.get('costo')\n otros = request.form.get('otro')\n\n if request.method == 'POST':\n\n if not placas or not arreglo or not costo:\n flash('Ingrese todos los datos')\n else:\n db.execute(\"INSERT INTO arreglos (dia, placas, arreglo, otro, costo) VALUES (?,?,?,?,?)\", datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"), placas, arreglo, otros, costo)\n\n arreglos = db.execute(\"SELECT * FROM arreglos WHERE placas = ?\", placas)\n print(arreglos)\n\n return render_template('index.html', arreglos=arreglos)\n\n else:\n return render_template('index.html')\n\n@app.route('/download', methods=['GET', 'POST'])\ndef download():\n placas = request.form.get('placas')\n if request.method == 'POST':\n arreglos = db.execute(\"SELECT * FROM arreglos WHERE placas = ?\", placas)\n if len(arreglos) == 0:\n flash('Automovil no registrado')\n return render_template('download.html')\n\n\n workbook = xlsxwriter.Workbook('Arreglos.xlsx')\n worksheet = workbook.add_worksheet()\n worksheet.write('A1', arreglos[0]['placas'])\n worksheet.write('A2', 'Dia')\n worksheet.write('B2', 'Arreglo')\n worksheet.write('C3', 'Otro')\n worksheet.write('C4', 'Costo')\n row = 1\n col = 0\n\n for i in arreglos:\n worksheet.write(row, col, i['dia'])\n worksheet.write(row, col+1, i['arreglo'])\n worksheet.write(row, col+2, i['otro'])\n worksheet.write(row, col+2, i['costo'])\n row += 1\n\n workbook.close()\n\n #return send_file (path, as_attachment=True)\n path = os.path.join(app.root_path)\n return send_from_directory(path, \"Arreglos.xlsx\")\n flash('Reporte generado')\n else:\n return render_template('download.html')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"164811354","text":"\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport random\n\nfrom torchvision import datasets, transforms, models\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\nimport IPython\n\n\nclass AdversarialNet(nn.Module):\n\n def __init__(self, target):\n super(AdversarialNet, self).__init__()\n self.features = models.resnet101(pretrained=True).cuda()\n self.features.eval()\n self.target = target\n\n def forward(self, x):\n\n y = x+0.0\n y[0] = (x[0]-0.485)/(0.229)\n y[1] = (x[1]-0.456)/(0.224)\n y[2] = (x[2]-0.406)/(0.225)\n x = y\n\n def scale(x, min_val=0.8, max_val=1.2):\n C, H, W = 2, 224, 224\n scale_val = random.uniform(min_val, max_val)\n\n grid = F.affine_grid(torch.eye(3).unsqueeze(0)[:, 0:2], size=torch.Size((1, C, H, W))).cuda()\n img = F.grid_sample(x.unsqueeze(0), grid*scale_val)[0]\n return img\n\n def rotate(x, max_angle=30):\n C, H, W = 2, 224, 224\n theta = np.radians(random.randint(-max_angle, max_angle))\n c, s = np.cos(theta), np.sin(theta)\n R = np.array([[c, -s], [s, c], [0, 0]]).T\n grid = F.affine_grid(torch.FloatTensor(R).unsqueeze(0), size=torch.Size((1, C, H, W))).cuda()\n img = F.grid_sample(x.unsqueeze(0), grid)[0]\n return img\n\n def distribution(x):\n return rotate(scale(x))\n\n images = torch.cat([distribution(x).unsqueeze(0) for i in range(0, 10)], dim=0)\n predictions = F.softmax(self.features(images)) [:, self.target].mean()\n\n return predictions\n\nmodel = AdversarialNet(398) #target=abacus\n\ntform = transforms.Compose([\n transforms.ToTensor(),\n ])\n\ninverse_tform = transforms.Compose([\n transforms.ToPILImage(),\n ])\n\ndef plot(image_data):\n plt.imshow(inverse_tform(image_data.data.cpu()))\n plt.show()\n\ndef save(image_data, file):\n plt.imsave(file, inverse_tform(image_data.data.cpu()))\n plt.show()\n\noriginal = Image.open(\"cat.jpg\")\ndata = tform(original)\n\nimage = Variable(data.cuda())\nperturbation = nn.Parameter(torch.randn(image.size()).cuda()+0.0)\nopt = optim.Adam([perturbation], lr=0.06)\nepsilon, start, fade_in = 5e-3, 4e-2, 1000\n\nlosses = []\nfor i in range(0, 2000):\n\n epsilon_scaled = (min(i, fade_in) * epsilon + (fade_in - min(i, fade_in))*start)/fade_in\n def closure():\n opt.zero_grad()\n\n perturbation_zc = (perturbation - perturbation.mean())/(perturbation.std()) * epsilon_scaled\n loss = -model((image + perturbation_zc).clamp(min=0.1, max=0.99))\n loss.backward()\n losses.append(loss.cpu().data.numpy()) \n return loss\n\n opt.step(closure)\n\n if i % 10 == 0:\n print (\"Loss: \", np.mean(losses[-100:]))\n print (\"Epsilon: \", epsilon_scaled)\n\n perturbation_zc = (perturbation - perturbation.mean())/(perturbation.std()) * epsilon_scaled\n changed_image = (image + perturbation_zc).clamp(min=0.1, max=0.99)\n\n save(image, file=\"image.jpg\")\n save(perturbation, file=\"perturbation.jpg\")\n save(changed_image, file=\"changed_image.jpg\")\n\nperturbation_zc = (perturbation - perturbation.mean())/(perturbation.std()) * epsilon\nchanged_image = (image + perturbation_zc).clamp(min=0.1, max=0.99)\n\nprint (\"Original predictions: \", model(image))\nprint (\"Perturbation: \", model(perturbation_zc))\nprint (\"Modified prediction: \", model(changed_image))\n\n\n","sub_path":"adversarial/imagenet_adversary.py","file_name":"imagenet_adversary.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"442829289","text":"#!/usr/bin/python\n\nfrom markdown import markdown\nimport os\n\n# load head, midd, foot\n\nhead_file = open('html/head.html')\nhead = head_file.read()\nhead_file.close()\n\nmidd_file = open('html/midd.html')\nmidd = midd_file.read()\nmidd_file.close()\n\nfoot_file = open('html/foot.html')\nfoot = foot_file.read()\nfoot_file.close()\n\nmds = os.listdir('md')\nfor md in mds:\n\t\n\t# convert md to html\n\tbody_file = open('md/' + md)\n\tbody = markdown(body_file.read())\n\tbody_file.close()\n\n\ttitle = md[:-3]\n\n\t# combine everything, write to file\n\tsite_file = open(title + '.html', 'w')\n\tsite_file.write(head + title + midd + body + foot)\n\tsite_file.close()\n","sub_path":"docs/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"43111503","text":"from selenium.webdriver.common.by import By\nfrom behave import given, when, then\nfrom time import sleep\n\nSEARCH_INPUT = (By.CSS_SELECTOR, \"#twotabsearchtextbox\")\nSEARCH_BUTTON = (By.CSS_SELECTOR, \".nav-input[value='Go']\")\nSEARCH_RESULTS_LOCATOR = (By.CSS_SELECTOR, '.s-result-list.s-search-results > div[data-index]')\nBEST_SELLER = (By.CSS_SELECTOR, \".a-badge-label\")\n\n\n@given('Open Amazon page')\ndef open_amazon_help_page(context):\n context.driver.get('https://www.amazon.com')\n\n@when ('Search input fill {search_text}')\ndef input_text(context, search_text):\n search_input = context.driver.find_element(*SEARCH_INPUT)\n search_input.clear()\n search_input.send_keys(search_text)\n\n sleep(2)\n\n@when ('Click search button')\ndef click_button(context):\n search_button = context.driver.find_element(*SEARCH_BUTTON)\n search_button.click()\n\n sleep(2)\n\n\n@then ('Counting best sellers fantasy books')\ndef count_bsfantasy_books(context):\n best_seller_count = 0\n bsfantasy_books_list = context.driver.find_elements(*BEST_SELLER)\n best_seller_count += len(bsfantasy_books_list)\n print(best_seller_count)\n\n","sub_path":"hw_5/features/steps/hw_5_2.py","file_name":"hw_5_2.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"188385846","text":"from flask_restful import Resource\nfrom pygal.style import Style\nfrom master import ctx\nimport pygal\nimport timeago\nfrom math import ceil\n\nclass HistoryGraph(Resource):\n def get(self, history_count):\n try:\n custom_style = Style(\n background='transparent',\n plot_background='transparent',\n foreground='rgba(109, 118, 126, 0.3)',\n foreground_strong='rgba(109, 118, 126, 0.3)',\n foreground_subtle='rgba(109, 118, 126, 0.3)',\n opacity='0.1',\n opacity_hover='0.2',\n transition='100ms ease-in',\n colors=('#007acc', '#749363')\n )\n\n graph = pygal.StackedLine(\n stroke_style={'width': 0.4}, \n show_dots=False, \n show_legend=False, \n fill=True, \n style=custom_style, \n disable_xml_declaration=True)\n \n instance_count = [history['time'] for history in ctx.history.instance_history][-history_count:]\n \n if len(instance_count) > 0:\n graph.x_labels = [ timeago.format(instance_count[0])]\n\n instance_counts = [history['count'] for history in ctx.history.instance_history][-history_count:]\n client_counts = [history['count'] for history in ctx.history.client_history][-history_count:]\n\n graph.add('Instance Count', instance_counts)\n graph.add('Client Count', client_counts)\n return { 'message' : graph.render(), \n 'data_points' : len(instance_count),\n 'instance_count' : 0 if len(instance_counts) is 0 else instance_counts[-1],\n 'client_count' : 0 if len(client_counts) is 0 else client_counts[-1]\n }, 200\n except Exception as e:\n return { 'message' : str(e) }, 500\n","sub_path":"Master/master/resources/history_graph.py","file_name":"history_graph.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"375757635","text":"#encoding=utf-8\nimport pymysql,threading,os,json,sys,socket,time,logging,re,datetime,pandas,pymongo,redis\nfrom patsy.util import pandas_Categorical_categories\n\nclass Utils():\n\tconnections = {\"QT_Stock\" : None, \"HF_Future\" : None, \"jydb0\" : None, \"qkhf1\" : None, \\\n\t\t\t\t\"QT_BasicInfo\" : None, \"QT_Macro\" : None, \"redis_SHFE\" : None, \"redis_CFE\" : None}\n\ttradingdayInst = \"QT_BasicInfo\"\n\tconfig = {\"db.config\" : {}, \"inst.config\" : {}}\n\tmutex = threading.Lock()\n\tenv = None\n\t\t\n\tdef __init__(self):\n\t\tpass\n\n\t@staticmethod\t\n\tdef is_ali():\n\t\t\"\"\"\n\t\tjudge if host is in ali.\n\t\t:return Boolean\n\t\t\"\"\"\t\n\t\treturn socket.gethostname().find('ali') >= 0\n\t\n\t@staticmethod\t\n\tdef is_aws():\n\t\t\"\"\"\n\t\tjudge if host is in aws.\n\t\t:return Boolean\n\t\t\"\"\"\t\n\t\treturn socket.gethostname().find('qa') >= 0 or socket.gethostname().find('qutke') >= 0 or socket.gethostname().find('huidi') >= 0\n\t\n\t@staticmethod\n\tdef get_connection(inst):\n\t\t\"\"\"\n\t\tget mysql connection(there exists only one connection for specified db inst).\n\t\t:param inst: db inst name\n\t\t:return pymysql connection for inst\n\t\t\"\"\"\t\t\n\t\tif(Utils.env is None):\n\t\t\t# do initialization\n\t\t\tUtils.env = \"aws\" if Utils.is_aws() else ('ali' if Utils.is_ali() else 'other')\n\t\t\tprint(\"Current server in \",Utils.env)\n\t\t\n\t\tif(Utils.connections[inst] == None):\n\t\t\tUtils.mutex.acquire()\n\t\t\tif(Utils.connections[inst] == None):\n\t\t\t\tUtils.read_config();\n\t\t\t\tdbconfig = Utils.config[\"db.config\"]\n\t\t\t\ttry:\n\t\t\t\t\tprint(\"host=\",dbconfig[Utils.env][inst]['host'])\n\t\t\t\t\tif(dbconfig[Utils.env][inst]['host'].find(\"mongo\") == -1 and dbconfig[Utils.env][inst]['type'] == \"mysql\"): \t\t#mysql\n\t\t\t\t\t\tUtils.connections[inst] = pymysql.connect(user = dbconfig[Utils.env][inst]['user'], passwd = dbconfig[Utils.env][inst]['passwd'], \\\n\t\t\t\t\t\t\thost = dbconfig[Utils.env][inst]['host'], db = dbconfig[Utils.env][inst]['db'], charset = 'utf8')\n\t\t\t\t\telif(dbconfig[Utils.env][inst]['type'] == \"mongodb\"):#mongo\n\t\t\t\t\t\tUtils.connections[inst] = pymongo.MongoClient(dbconfig[Utils.env][inst]['host'])\n\t\t\t\t\telse: #redis\n\t\t\t\t\t\tUtils.connections[inst] = redis.Redis(host = dbconfig[Utils.env][inst]['host'], port = dbconfig[Utils.env][inst]['port'],\n\t\t\t\t\t\t\t\t\tdb = dbconfig[Utils.env][inst]['db'], password = dbconfig[Utils.env][inst]['passwd'], charset = 'utf-8', socket_keepalive = True)\n\t\t\t\texcept: \n\t\t\t\t\tinfo = sys.exc_info() \n\t\t\t\t\tprint (\"[E] failed to connect to database,\", info[0], \":\" ,info[1])\n\t\t\t\t\texit(-1)\n\t\t\tUtils.mutex.release()\n\t\treturn Utils.connections[inst]\n\t\n\t@staticmethod\n\tdef get_rt_data(key = None):\n\t\t[inst_abbr, type] = Utils.get_inst_abbr(key)\n\t\tif(type not in ['CFE', 'SHFE']):\n\t\t\tlogging.error(\"[E] invalid key! Must be CFE or SHFE type. Right e.g. cu1606, TF1602\")\n\t\t\texit(-1)\n\t\tconn = None\n\t\tif(type == \"SHFE\"):\n\t\t\tconn = Utils.get_connection(\"redis_SHFE\")\n\t\telse:\n\t\t\tconn = Utils.get_connection(\"redis_CFE\")\n\t\tdata = None\n\t\ttemp = list(list())\n\t\ttry:\n\t\t\tdata = conn.lrange(key, 0, -1)\n\t\texcept: \n\t\t\tinfo = sys.exc_info() \n\t\t\tprint (\"[E] failed to read \", type, \" data from redis,\", info[0], \":\" ,info[1])\n\t\t\texit(-1)\n\t\trowdatas = list()\n\t\tfor i in data:\n\t\t\trowdatas = str(i).replace(\"b'\", \"\").replace(\"'\", \"\").split(',')\n\t\t\ttemp.append(list(rowdatas))\n\t\treturn pandas.DataFrame(data = temp, columns = Utils.config[\"inst.config\"][type + \"_COLUMNS\"])\n\n\t@staticmethod\n\tdef bus_day_range(startDate = None, endDate = None, n = None):\n\t\t\"\"\"\n\t\tget tradingday list between two dates.\n\t\t:param startDate: e.g. '20150101', must not be None\n\t\t:param endDate: e.g. '20150201', use today as default date\n\t\t:param n: used when endDate is None. \n\t\t:return tradingdates list between startDate and endDate or n tradingdays since startDate\n\t\t\"\"\"\n\t\tif(endDate == None and (n == None or n < 0)):\n\t\t\tendDate = time.strftime('%Y%m%d',time.localtime())\n\t\tif(startDate == None or (endDate != None and (n != None and n >= 0))):\n\t\t\tprint(\"Invalid parameters: startDate=\",str(startDate),\" endDate=\", str(endDate), \" n=\", str(n),\n\t\t\t\t\"\\nUseage: bus_day_range('20160101'', '20160112', None) or\" \\\n\t\t\t\t\"\\n bus_day_range('20160101, None, 2)\")\n\t\t\tsys.exit(-1)\n\t\tconn = Utils.get_connection(Utils.tradingdayInst)\n\t\tsqlstr = \"\"\n\t\tif(endDate != None):\n\t\t\tsqlstr = \"select * from tradingDay where busDate between \" + startDate + \" and \" + endDate\n\t\telse:\n\t\t\tsqlstr = \"select * from tradingDay where busDate >\" + startDate + \" limit \" + str(n)\n\t\tprint(sqlstr)\n\t\tbus_dates = Utils.exec_mysql(conn, sqlstr)\n\t\t#print(\",\".join(bus_dates))\n\t\treturn bus_dates\n\t\t\t\n\t@staticmethod\n\tdef to_bus_day(date = None, shift = 0, forward = True):\n\t\t\"\"\"\n\t\tget specified tradingday with a shift and forward direction.\n\t\t:param date:start day e.g. '20150101'\n\t\t:param shift: date shift, must be not litter than 0\n\t\t:param forward: direction of shift.\n\t\t:return tradingday\n\t\t\"\"\"\n\t\tif(date == None or int(shift) < 0 or not(str(forward) in[\"True\", \"False\"])):\n\t\t\tprint(\"Invalid parameters: date=\",str(date),\" shift=\", str(shift), \" forward=\", str(forward),\n\t\t\t\t\"\\nUsage: to_bus_day('20160101', 1, True) \\nNote:shift>=0\")\n\t\t\tsys.exit(-1)\n\t\tconn = Utils.get_connection(Utils.tradingdayInst)\n\t\tsqlstr = \"\"\n\t\tif(str(forward) == \"True\"):\n\t\t\tsqlstr = \"select * from (select * from tradingDay where busDate <= \" + str(date) + \" order by busDate desc limit \" + str(int(shift) + 1) + \") as temp order by busDate asc limit 1\" \n\t\telse:\n\t\t\tsqlstr = \"select * from(select * from tradingDay where busDate >=\" + str(date) + \" limit \" + str(int(shift) + 1) + \" )as tmp order by busDate desc limit 1\"\n\t\tprint(sqlstr)\n\t\tbus_dates = Utils.exec_mysql(conn, sqlstr)\n\t\t#print(\",\".join(bus_dates))\n\t\treturn bus_dates\n\t\n\t@staticmethod\n\tdef get_HF_db(db_table, codes = None, start_date = None, end_date = None,vars = None):\n\t\t\"\"\"\n\t\tread mysql HF_Future data into pandas.dataframe.\n\t\t:param db_table: source mysql table name. type:string\n\t\t:param codes: codes(contractid) of data to get e.g. (TF1603) or (T1603) or (cu1602). type: pandas.series or NoneType\n\t\t:param start_date: to get data start from start_date. default date: the min date in table. type: string like '2015-01-01'\n\t\t:param end_date: to get data before end_date. default date: the max date in table\n\t\t:param vars: vars intersect with [qtid, date] will be returned . default *. type: pandas.series or NoneType\n\t\t:return: specified HF_Future data read from mysql. type:DataFrame\n\t\t\"\"\"\n\t\tconn = Utils.get_connection(\"HF_Future\")\n\t\tsqlstr = \"\"\n\t\tcolumns = \" * \"\n\t\tqtids = \"\"\n\t\tdata = pandas.DataFrame()\n\t\tif(db_table is None):\n\t\t\tlogging.error(\"[E] table name can not be None!\")\n\t\t\texit(-1)\n\t\tif(str(type(codes)).find(\"Series\") == -1 and str(type(codes)).find(\"None\") == -1):\n\t\t\tlogging.error(\"type of codes must be None or Series\")\n\t\t\texit(-1)\n\t\tif(str(type(vars)).find(\"Series\") == -1 and str(type(vars)).find(\"None\") == -1):\n\t\t\tlogging.error(\"type of vars must be None or Series\")\n\t\t\texit(-1)\n\t\tif(start_date is None):\n\t\t\t start_date = \"1900-01-01\"; # set to very early date\n\t\tif(end_date is None):\n\t\t\tend_date = \"3000-01-01\"; # set to very late date \n\t\tstart_date = str(Utils.date_transform(start_date))\n\t\tend_date = str(Utils.date_transform(end_date))\n\t\tif((str(type(vars)).find(\"Series\") > 0 and not(vars.empty))):\n\t\t\tcolumns = \", \".join(set([\"contractid\", \"tradingdate\"]).union(set(vars.values)))\n\t\tif((str(type(codes)).find(\"Series\") > 0 and not(codes.empty))):\n\t\t\tcontractids = \"', '\".join(codes.values)\n\t\tif(contractids != \"\"):\n\t\t\tsqlstr = \"select \" + columns + \" from \" + str(db_table) + \" where tradingdate between '\" + start_date + \"' and '\" + end_date + \"' and contractid in ('\" + contractids + \"')\"\n\t\telse:\n\t\t\tsqlstr = \"select \" + columns + \" from \" + str(db_table) + \" where tradingdate between '\" + start_date + \"' and '\" + end_date + \"'\"\n\t\tprint(sqlstr)\n\t\ttry:\n\t\t\tdata = pandas.read_sql(sqlstr, conn)\n\t\texcept: \n\t\t\tinfo = sys.exc_info()\n\t\t\tprint((\"[E] failed to read HF data from mysql,\", info[0], \":\" ,info[1])) \n\t\t\tlogging.error(\"[E] failed to read HF data from mysql,\" + (info[0]) + \":\" + str(info[1]))\n\t\treturn data\n\n\t@staticmethod\n\tdef get_marco_db(db_name = \"QT_Macro\", key = None, start_date = None, end_date = None):\n\t\t\"\"\"\n\t\tread mongodb Micro data into pandas.dataframe.\n\t\t:param db_name: source mongo db name. default QT_Macro. type:string\n\t\t:param db_table: source mongo keys name. Can not be None. type:string\n\t\t:param start_date: to get data start from start_date. default date: the min date in key. type:string like '2015-01-01'\n\t\t:param end_date: to get data before end_date. default date: the max date in key\n\t\t:return: specified Micro data read from mongo. type:DataFrame\n\t\t\"\"\"\n\t\tdata = pandas.DataFrame()\n\t\tif(key == None):\n\t\t\treturn data\n\t\tif(start_date is None):\n\t\t\t start_date = \"1900-01-01\"; # set to very early date\n\t\tif(end_date is None):\n\t\t\tend_date = \"3000-01-01\"; # set to very late date \n\t\tstart_date = str(Utils.date_transform(start_date))\n\t\tend_date = str(Utils.date_transform(end_date))\n\t\tUTC_FORMAT = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n\t\tstart_date = datetime.datetime.strptime(start_date + \"T00:00:00.000Z\", UTC_FORMAT)\n\t\tend_date = datetime.datetime.strptime(end_date + \"T23:59:59.000Z\", UTC_FORMAT)\n\t\tconn = Utils.get_connection(\"QT_Macro\")\n\t\t#print(conn)\n\t\ttry:\n\t\t\tdb = conn[db_name]\n\t\t\tcoll = db[key]\n\t\t\tdata = pandas.DataFrame(list(coll.find({\"_id\" : {\"$lt\" : end_date, \"$gt\" : start_date}})))\n\t\texcept:\n\t\t\tinfo = sys.exc_info()\n\t\t\tprint((\"[E] failed to read Micro data from mongo,\", info[0], \":\" ,info[1])) \n\t\t\tlogging.error(\"[E] failed to read Micro data from mongo,\" + (info[0]) + \":\" + str(info[1]))\n\t\treturn data\n\t\t\t\n\t@staticmethod\n\tdef bus_day_diff(fromDate, toDate):\n\t\t\"\"\"\n\t\tcaculate business day gap btween two dates.\n\t\t:param fromDate:start day. type: string like '20150101'\n\t\t:param toDate:stop day\n\t\t:return count of days gap type: int\n\t\t\"\"\"\n\t\tif(toDate == None):\n\t\t\ttoDate = time.strftime('%Y%m%d',time.localtime())\n\t\tif(fromDate == None):\n\t\t\tprint(\"Invalid parameters: fromDate can not been None\", \"\\nUsage: bus_day_diff('20160101', '20160201')\")\n\t\t\tsys.exit(-1)\n\t\tconn = Utils.get_connection(Utils.tradingdayInst)\n\t\tsqlstr = \"select * from tradingDay where busDate between \" + str(fromDate) + \" and \" + str(toDate)\n\t\tprint(sqlstr)\n\t\tbus_dates = Utils.exec_mysql(conn, sqlstr)\n\t\t#print(\",\".join(bus_dates))\n\t\treturn len(bus_dates)\n\t\n\t@staticmethod\n\tdef exec_mysql(conn, sqlstr):\n\t\t\"\"\"\n\t\tExecute mysql command.\n\t\t:param conn: pymysql connection\n\t\t:param sqlstr: mysql command str. type:string\n\t\t:return: execute results as list. type:list\n\t\t\"\"\"\n\t\tbus_dates = list()\n\t\tcur = None\n\t\ttry: \n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(sqlstr)\n\t\t\tdata =cur.fetchall()\n\t\t\tbus_dates = [d[0] for d in data]\n\t\texcept: \n\t\t\tinfo = sys.exc_info() \n\t\t\tprint (\"Encountered error in connectiong to mysql,\", info[0], \":\" ,info[1])\n\t\t\tlogging.error(\"Encountered error in connectiong to mysql,\" + (info[0]) + \":\" + str(info[1]))\n\t\tfinally:\n\t\t\tif(cur != None):\n\t\t\t\tcur.close()\n\t\treturn bus_dates\n\t\n\t@staticmethod\t\n\tdef get_inst_abbr(inst):\n\t\t\"\"\"\n\t\tget instrument abbreviation and its exchange from instrument ID.\n\t\t:param inst: instrument name. e.g. \"TF1603\"\n\t\t:return: tuple(inst_abbr, exchange)\n\t\t\"\"\"\n\t\tUtils.read_config()\n\t\tif(inst is None):\n\t\t\treturn None, None\n\t\tinst_abbr = re.findall('(^[A-Za-z]{1,2})[0-9]+', inst)\n\t\tif inst_abbr != None and len(inst_abbr) == 1:\n\t\t\tif str(inst_abbr[0]).upper() in Utils.config[\"inst.config\"][\"CFE_INST\"]:\n\t\t\t\treturn str(inst_abbr[0]).upper(), \"CFE\"\n\t\t\tif str(inst_abbr[0]).lower() in Utils.config[\"inst.config\"][\"SHFE_INST\"]:\n\t\t\t\treturn str(inst_abbr[0]).lower(), \"SHFE\"\n\t\t\telse:\n\t\t\t\tlogging.error(\"[E] Not a valid CFE or SHE instrument abbr.\")\n\t\t\t\treturn None, None\n\t\telse:\n\t\t\tlogging.error(\"[E] Invalid instrument ID\")\n\t\t\treturn None,None\n\n\t@staticmethod\n\tdef is_time_valid(inst, cur_time = None):\n\t\t\"\"\"\n\t\tcheck if cur_time is in valid trading time for inst.\n\t\t:param inst: instrument name. e.g. \"TF1603\"\n\t\t:param cur_time:cur time, 24 hours formatted string. e.g. \"13:35:25\"\n\t\t:return: Boolean\n\t\t\"\"\"\n\t\tinst_abbr = re.findall('^[0-9]{6}\\\\.([A-Za-z]{2})', inst)\n\t\tif inst_abbr: # xxxxxx.sz or xxxxxx.sh\n\t\t\tif not cur_time:\n\t\t\t\tcur_time = time.strftime('%H:%M:%S',time.localtime())\n\t\t\t\tfor time_period in [i.split('-') for i in Utils.config[\"inst.config\"][\"ASHARE_OPENTIME\"][str(inst_abbr[0]).lower()]]:\n\t\t\t\t\tif time_period[0] < cur_time < time_period[1]:\n\t\t\t\t\t\treturn True\n\t\telse:\n\t\t\t[inst_abbr, exchange] = Utils.get_inst_abbr(inst)\n\t\t\tif inst_abbr:\n\t\t\t\tif not cur_time:\n\t\t\t\t\tcur_time = time.strftime('%H:%M:%S',time.localtime())\n\t\t\t\tfor time_period in [i.split('-') for i in Utils.config[\"inst.config\"][\"FUTURE_OPENTIME\"][str(inst_abbr).lower()]]:\n\t\t\t\t\tif time_period[0] < cur_time < time_period[1]:\n\t\t\t\t\t\treturn True\n\t\treturn False\n\t\n\t@staticmethod\n\tdef date_transform(date):\n\t\t\"\"\"\n\t\t:param date, must be as: 2016-01-01 or 20160101 or 2016:01:01\n\t\t:return: date object(2016-01-01) or None\n\t\t\"\"\"\n\t\tif(date == None):\n\t\t\treturn None\n\t\tdates = re.findall('(^[0-9]{4})[-.:]{0,1}([0-9]{2})[-.:]{0,1}([0-9]{2})', str(date)) \n\t\tresultDate = None\n\t\tif(len(dates) == 1):\n\t\t\tresultDate = str(dates[0][0]) + \"-\" + str(dates[0][1]) + \"-\" + str(dates[0][2])\n\t\tif(resultDate == None):\n\t\t\tlogging.error(\"[E] Invalid date format, check it. Format must be '2015-01-01' or '20150101' or '2015.01.01'. input date=\" + str(date))\n\t\t\texit(-1)\n\t\ty,m,d = time.strptime(resultDate, \"%Y-%m-%d\")[0:3]\n\t\treturn datetime.datetime(y,m,d).date()\n\t\n\t@staticmethod\n\tdef read_daily_db(db_table, codes = None, start_date = None, end_date = None, vars = None):\n\t\t\"\"\"\n\t\tread mysql data into pandas.dataframe.\n\t\t:param db_table: source mysql table name\n\t\t:param codes: codes of data to get e.g. (000001.SZ) or (TF1603). type: pandas.series or NoneType\n\t\t:param start_date: to get data start from start_date. default date: the min date in table\n\t\t:param end_date: to get data before end_date. default date: the max date in table\n\t\t:param vars: vars intersect with [qtid, date] will be returned . default *. type: pandas.series or NoneType\n\t\t:return: specified data read from mysql\n\t\t\"\"\"\n\t\tconn = Utils.get_connection(\"QT_Stock\")\n\t\tsqlstr = \"\"\n\t\tcolumns = \" * \"\n\t\tqtids = \"\"\n\t\tdata = pandas.DataFrame()\n\t\tif(db_table is None):\n\t\t\tlogging.error(\"[E] table name can not be None!\")\n\t\t\texit(-1)\n\t\tif(str(type(codes)).find(\"Series\") == -1 and str(type(codes)).find(\"None\") == -1):\n\t\t\tlogging.error(\"type of codes must be None or Series\")\n\t\t\texit(-1)\n\t\tif(str(type(vars)).find(\"Series\") == -1 and str(type(vars)).find(\"None\") == -1):\n\t\t\tlogging.error(\"type of vars must be None or Series\")\n\t\t\texit(-1)\n\t\tif(start_date is None):\n\t\t\t start_date = \"1900-01-01\"; # set to very early date\n\t\tif(end_date is None):\n\t\t\tend_date = \"3000-01-01\"; # set to very late date \n\t\tstart_date = str(Utils.date_transform(start_date))\n\t\tend_date = str(Utils.date_transform(end_date))\n\t\tif((str(type(vars)).find(\"Series\") > 0 and not(vars.empty))):\n\t\t\tcolumns = \", \".join(set([\"qtid\", \"date\"]).union(set(vars.values)))\n\t\tif((str(type(codes)).find(\"Series\") > 0 and not(codes.empty))):\n\t\t\tqtids = \"', '\".join(codes.values)\n\t\tif(qtids != \"\"):\n\t\t\tsqlstr = \"select \" + columns + \" from \" + str(db_table) + \" where date between '\" + start_date + \"' and '\" + end_date + \"' and qtid in ('\" + qtids + \"')\"\n\t\telse:\n\t\t\tsqlstr = \"select \" + columns + \" from \" + str(db_table) + \" where date between '\" + start_date + \"' and '\" + end_date + \"'\"\n\t\tprint(sqlstr)\n\t\ttry:\n\t\t\t#data = pandas.read_sql(sqlstr, conn, coerce_float=False)\n\t\t\tdata = pandas.read_sql_query(sql = sqlstr, con = conn, index_col = None, coerce_float = False, params = None, parse_dates = None, chunksize = None)\n\t\texcept: \n\t\t\tinfo = sys.exc_info()\n\t\t\tprint((\"[E] failed to read from mysql,\", info[0], \":\" ,info[1])) \n\t\t\tlogging.error(\"[E] failed to read from mysql,\" + str(info[0]) + \":\" + str(info[1]))\n\t\treturn data\n\t\n\t@staticmethod\n\tdef write_daily_db(data, db_table, codes = None, start_date = None, end_date = None, vars = None):\n\t\t\"\"\"\n\t\twrite data(pandas.dataframe) into mysql(delete old data daily first).\n\t\t:param data: panas dataframe data\n\t\t:param db_table: des mysql table name. must not be None\n\t\t:param codes: codes of data to write e.g. (000001.SZ) or (TF1603). Series or NoneType\n\t\t:param start_date: to get data start from start_date. default date: the min date in table\n\t\t:param end_date: to get data before end_date. default date: the max date in table\n\t\t:param vars: vars intersect with [qtid, date] is the columns to write. default *. type: pandas.series or NoneType\n\t\t\"\"\"\n\t\tconn = Utils.get_connection(\"QT_Stock\")\n\t\tdata = Utils.data_filter(data, codes, start_date, end_date, vars)\n\t\t#print(data)\n\t\tresult = list()\n\t\tsql_find_table = \"select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME= '\" + db_table + \"'\"\n\t\tsql_find_index = \"select index_name from information_schema.statistics where table_name= '\" + db_table + \"'\"\n\t\tsql_create_index = \"ALTER TABLE `\" + db_table + \"` MODIFY COLUMN `qtid` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL FIRST,\\\n\t\tMODIFY COLUMN `date` date NOT NULL AFTER `qtid`,ADD PRIMARY KEY (`qtid`, `date`),ADD INDEX `index_\" + db_table + \"_date` (`date`) USING BTREE\"\n\t\t\n\t\t# delete old data if table exists\n\t\tcur = None\n\t\ttry: \n\t\t\t#print(\"sql_find_table:\", sql_find_table)\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(sql_find_table)\n\t\t\tresult = [d[0] for d in cur.fetchall()]\n\t\t\tif(len(result) != 0): # table already exists\n\t\t\t\t#delete duplicate data\n\t\t\t\tif(start_date is None):\n\t\t\t\t\tstart_date = \"1900-01-01\"; # set to very early date\n\t\t\t\tif(end_date is None):\n\t\t\t\t\tend_date = \"3000-01-01\"; # set to very late date \n\t\t\t\tstart_date = Utils.date_transform(start_date)\n\t\t\t\tend_date = Utils.date_transform(end_date)\n\t\t\t\tsql_delete_data = \"delete from \" + db_table + \" where `date` between '\" + str(start_date) + \"' and '\" + str(end_date) + \"' and qtid in \" + str(\"('\" + \"','\".join(codes) + \"') \")\n\t\t\t\t#print(\"sql_delete_data=\",sql_delete_data)\n\t\t\t\tcur.execute(sql_delete_data)\n\t\texcept: \n\t\t\tinfo = sys.exc_info() \n\t\t\tprint (\"Encountered error in finding table or create index,\", info[0], \":\" ,info[1])\n\t\t\tlogging.error(\"Encountered error in finding table or create index,\" + (info[0]) + \":\" + str(info[1]))\n\t\t\texit(-1)\n\t\tfinally:\n\t\t\tif(cur != None):\n\t\t\t\tcur.close()\n\t\t\t\t\n\t\t# insert new data and create index if necessary\n\t\ttry:\n\t\t\tpandas.DataFrame.to_sql(data, name = db_table, con = conn, flavor = 'mysql',index = False, index_label= None, if_exists = 'append', chunksize = 2000)\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(sql_find_index)\n\t\t\tresult = [d[0] for d in cur.fetchall()]\n\t\t\tif(len(result) == 0): # index does not exist\n\t\t\t\tresult = cur.execute(sql_create_index)\n\t\t\t\tlogging.info(\"create index: \" + str([d[0] for d in cur.fetchall()]))\n\t\t\t#else:\n\t\t\t\t#print(\"index already exist\")\n\t\texcept: \n\t\t\tinfo = sys.exc_info() \n\t\t\tprint(\"Encountered error in writing data into db or create index,\", info[0], \":\" ,info[1])\n\t\t\tlogging.error(\"Encountered error in writing data into db or create index,\" + (info[0]) + \":\" + str(info[1]))\n\t\t\texit(-1)\n\t\tfinally:\n\t\t\tif(cur != None):\n\t\t\t\tcur.close()\n\t\t\t\t\t\t\n\t@staticmethod\n\tdef data_filter(data, codes = None, start_date = None, end_date = None, vars = None):\n\t\t\"\"\"\n\t\tfilter out DataFrame data according to codes start_date end_date vars.\n\t\t:param data: panas dataframe data\n\t\t:param codes: codes of data to write e.g. (000001.SZ) or (TF1603). Series or NoneType\n\t\t:param start_date: to get data start from start_date. default date: the min date in table\n\t\t:param end_date: to get data before end_date. default date: the max date in table\n\t\t:param vars: vars intersect with [qtid, date] is the columns to write. default *. type: pandas.series or NoneType\n\t\t:return: new DataFrame\n\t\t\"\"\"\n\t\tif(str(type(data)).find(\"DataFrame\") == -1):\n\t\t\tlogging.error(\"type of data must be DataFrame\")\n\t\t\texit(-1)\n\t\tif(str(type(codes)).find(\"Series\") == -1 and str(type(codes)).find(\"None\") == -1):\n\t\t\tlogging.error(\"type of codes must be None or Series\")\n\t\t\texit(-1)\n\t\tif(str(type(vars)).find(\"Series\") == -1 and str(type(vars)).find(\"None\") == -1):\n\t\t\tlogging.error(\"type of vars must be None or Series\")\n\t\t\texit(-1)\n\t\tif(start_date is None):\n\t\t\t start_date = \"1900-01-01\"; # set to very early date\n\t\tif(end_date is None):\n\t\t\tend_date = \"3000-01-01\"; # set to very late date \n\t\tstart_date = Utils.date_transform(start_date)\n\t\tend_date = Utils.date_transform(end_date)\n\t\tif(not codes.empty):\n\t\t\tdata = data[data['qtid'].isin(codes)]\n\t\tif(not vars.empty):\n\t\t\tcolumns = list(set([\"qtid\", \"date\"]).union(set(vars.values)))\n\t\t\tdata = data[data['qtid'].isin(codes)][columns]\n\t\tdata = data[data['date'] > start_date]\n\t\tdata = data[data['date'] < end_date]\n\t\treturn data\n\t\n\t@staticmethod\n\tdef read_config():\n\t\t\"\"\"\n\t\tread all config json file into Utils.config dicts\n\t\t\"\"\"\t\n\t\tfor key in Utils.config:\n\t\t\tfp = None\n\t\t\tif (Utils.config[key] != None and len(Utils.config[key]) != 0):\n\t\t\t\t#print(\"Config dict already initialized\")\n\t\t\t\tcontinue\n\t\t\tcurPath = os.path.abspath('..')\n\t\t\tpath = curPath + '/pingo/' + key\n\t\t\ttry:\n\t\t\t\tfp = open(path, 'r')\n\t\t\t\tUtils.config[key] = json.load(fp)\n\t\t\texcept: \n\t\t\t\tinfo = sys.exc_info() \n\t\t\t\tprint(\"[E] failed to read config:\", info[0], \":\" ,info[1])\n\t\t\t\tlogging.error(\"[E]failed to read config:\" + (info[0]) + \":\" + str(info[1]))\n\t\t\t\texit(-1)\n\t\t\tfinally:\n\t\t\t\tif(fp != None):\n\t\t\t\t\tfp.close()","sub_path":"pingo/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":21199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"184103071","text":"def wystepuje(x, tab):\n wys=False\n for i in tab:\n if x==i:\n wys=True\n else:\n continue\n return(wys)\n\nx=23\ntablica=[15, 38, 7, 23, 14]\n\nprint(f\"Liczba: {x}\\nTablica: {tablica}\")\nif wystepuje(x, tablica):\n print(\"Wystepuje\")\nelse:\n print(\"Nie wystepuje\")\n\n","sub_path":"04-Subroutines/04/z14.py","file_name":"z14.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56344686","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# dit bovenstaande niet aanraken, het is nodig\n\n# let op: importeer enkel het nodige, schoolpc's zijn sceer\nimport sys\nfrom PyQt4 import QtGui\nfrom PyQt4 import QtCore\n\nresx = 600\nresy = 400\n\nclass Fourth(QtGui.QMainWindow):\n def __init__(self):\n super(Fourth, self).__init__()\n self.initUI()\n def initUI(self):\n\n self.lbl = QtGui.QLabel('Rohan, het is me gelukt. Dit is VIER!!!', self)\n self.lbl.resize(self.lbl.sizeHint())\n self.lbl.move(250, 120)\n\n\n # maak even menubar\n # een mooie statusbar gewoon omdat het kan\n self.statusBar().showMessage('Gereed')\n exitAction = QtGui.QAction('Exit' , self)\n exitAction.setShortcut('Ctrl+Q')\n exitAction.setStatusTip('GEWOON OPTIEFTEN BEN ER HELEMAAL KLAAR MEE')\n exitAction.triggered.connect(QtGui.qApp.quit)\n\n # maak even menubar\n menubar = self.menuBar()\n fileMenu = menubar.addMenu('&File')\n fileMenu.addAction(exitAction)\n self.resize(resx, resy)\n self.center()\n self.setWindowTitle('Overgang SLC')\n self.setWindowIcon(QtGui.QIcon('3.png'))\n # nu is het venster klaar in geheugen, projecteer naar scherm\n # pas op het laatst doen natuurlijk\n self.show()\n\n def center(self):\n\n qr = self.frameGeometry()\n cp = QtGui.QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n","sub_path":"vier.py","file_name":"vier.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"538284934","text":"\"\"\"Definitely still a beta -- could work some more on error checking, thread closure...etc\"\"\"\n#!/usr/bin/env python\n\nimport serial\nimport threading\nimport time\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nclass CMS50Dplus(threading.Thread):\n def __init__(self, port):\n threading.Thread.__init__(self)\n self.port = port\n self.conn = None\n self.counter_data = []\n self.pulse_data = []\n self.spo2_data = []\n\n def is_connected(self):\n return type(self.conn) is serial.Serial and self.conn.isOpen()\n\n def connect(self):\n if self.conn is None:\n self.conn = serial.Serial(port = self.port,\n baudrate = 19200,\n parity = serial.PARITY_ODD,\n stopbits = serial.STOPBITS_ONE,\n bytesize = serial.EIGHTBITS,\n timeout = 5,\n xonxoff = 1)\n elif not self.is_connected():\n self.conn.open()\n\n def disconnect(self):\n if self.is_connected():\n self.conn.close()\n\n def get_byte(self):\n char = self.conn.read()\n if len(char) == 0:\n return None\n else:\n return ord(char)\n\n def decode_packet(self, data): \n if [d & 0x80 != 0 for d in data] != [True, False, False, False, False]:\n raise ValueError(\"Invalid data packet.\")\n\n pulse_rate = (data[2] & 0x40) << 1# see CommunicationProtocolDoc.pdf\n pulse_rate |= data[3] & 0x7f\n\n blood_spo2 = data[4] & 0x7f\n\n return pulse_rate, blood_spo2\n \n def run(self):\n counter = 0\n self.connect()\n packet = [0]*5\n idx = 0\n while True:\n byte = self.get_byte()\n \n if byte is None:\n break\n\n if byte & 0x80:\n if idx == 5 and packet[0] & 0x80:\n pulse_rate, blood_spo2 = self.decode_packet(packet)\n if len(self.counter_data) > 5000:\n self.counter_data.pop(0)\n self.pulse_data.pop(0)\n self.spo2_data.pop(0)\n self.counter_data.append(counter)\n self.pulse_data.append(pulse_rate)\n self.spo2_data.append(blood_spo2)\n else:\n self.counter_data.append(counter)\n self.pulse_data.append(pulse_rate)\n self.spo2_data.append(blood_spo2)\n counter += 1\n packet = [0]*5\n idx = 0\n \n if idx < 5:\n packet[idx] = byte\n idx+=1\n\ndef animate(i):\n ax1.clear()\n ax1.plot(CMS50Dplus_1.counter_data, CMS50Dplus_1.pulse_data, 'blue', CMS50Dplus_1.counter_data, CMS50Dplus_1.spo2_data, 'green')\n ax1.set_title(\"Pulse and SpO2 Tracker\")\n ax1.set_autoscaley_on(False)\n ax1.set_ylim([40,140])\n text_pulse = \"Pulse: {}\".format(str(CMS50Dplus_1.pulse_data[-1]))\n text_spo2 = \"SpO2: {}\".format(str(CMS50Dplus_1.spo2_data[-1]))\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n ax1.text(0.05, 0.95, text_pulse, transform=ax1.transAxes, fontsize=14, color='blue', verticalalignment='top', bbox=props)\n ax1.text(0.05, 0.85, text_spo2, transform=ax1.transAxes, fontsize=14, color='green', verticalalignment='top', bbox=props)\n\nCMS50Dplus_1 = CMS50Dplus(\"COM3\")# adjust COM port as needed\nCMS50Dplus_1.start()\ntime.sleep(1)\n\nfig = plt.figure()\nax1 = fig.add_subplot(1, 1, 1)\nani = animation.FuncAnimation(fig, animate, 1000)\nplt.show()\n","sub_path":"CMS50DPlusPulseSpO2.py","file_name":"CMS50DPlusPulseSpO2.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"290603352","text":"#https://www.anchor.com.au/hosting/support/CreatingAQuickMySQLRelationalDatabase#head-e553653f2d7e592b1cbba9afca44c25cd12f6ee4\nfrom connect_and_run import sql_connect\nfrom datetime import datetime\nimport re\n\ndef create_table_setup(league):\n query = (\"CREATE TABLE IF NOT EXISTS db_setup (\"\n \"setup_date DATE,\"\n \"table_name VARCHAR(20))\"\n \" ENGINE = InnoDB\") #Alternativ use the `` instead of ' or \"\n query_type = query[0:query.find(\" \",0)]\n try:\n cursor_data = sql_connect(query,query_type,'')\n print(cursor_data)\n except Exception as e:\n print(e)\n\ndef create_table_teams(league):\n query = (f\"CREATE TABLE IF NOT EXISTS {league}_teams (\"\n \"teamid INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (teamid) ,\"\n \"team VARCHAR(6),\"\n \"team_name VARCHAR(30)) ENGINE = InnoDB;\")\n query_type = query[0:query.find(\" \",0)]\n try:\n cursor_data = sql_connect(query,query_type,'')\n print(cursor_data)\n except Exception as e:\n print(e)\n\ndef create_table_results(league):\n query = (f\"CREATE TABLE IF NOT EXISTS {league}_results (\"\n \"resultid INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (resultid),\"\n \"season VARCHAR(9),\"\n \"matchweek INT NOT NULL,\"\n \"date VARCHAR (10),\"\n \"weekday VARCHAR(10),\"\n \"teamhome VARCHAR (40),\"\n \"teamguest VARCHAR (40),\"\n \"scorehome INT,\"\n \"scoreguest INT) ENGINE = InnoDB;\")\n query_type = query[0:query.find(\" \",0)]\n try:\n cursor_data = sql_connect(query,query_type,'')\n print(cursor_data)\n except Exception as e:\n print(e)\n\ndef create_table_leaguetables(league):\n query = (f\"CREATE TABLE IF NOT EXISTS {league}_leaguetables (\"\n \"leaguetablesid INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (leaguetablesid),\"\n \"season VARCHAR(9),\"\n \"date VARCHAR (10),\"\n \"matchweek INT,\"\n \"team VARCHAR(30),\"\n \"league_rank INT,\"\n \"points INT,\"\n \"won INT,\"\n \"lost INT,\"\n \"drawn INT,\"\n \"goalsfor INT,\"\n \"goalsagainst INT,\"\n \"goalsdiff VARCHAR(5)) ENGINE = InnoDB;\")\n query_type = query[0:query.find(\" \",0)]\n try:\n cursor_data = sql_connect(query,query_type,'')\n print(cursor_data)\n except Exception as e:\n print(e)\n","sub_path":"create_table.py","file_name":"create_table.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"465026935","text":"#-*- coding:utf-8 -*\n\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.linear_model import BayesianRidge, LinearRegression \n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef get_dataset():\n fp = open('dataset/boston.csv','r')\n title = fp.readline()\n Xdata = []\n Ydata = []\n for line in fp.readlines():\n line = list(map(float, line.strip().split(',')))\n Ydata.append(line[-1:])\n Xdata.append(line[:-1])\n return np.asarray(Xdata), np.asarray(Ydata)\n\nif __name__ == \"__main__\":\n Xdata, Ydata = get_dataset()\n ols = LinearRegression()\n clf = BayesianRidge(compute_score=True)\n \n #predicted = cross_val_predict(ols, Xdata, Ydata, cv=10)\n predicted = cross_val_predict(clf, Xdata, Ydata, cv=10)\n\n fig, ax = plt.subplots()\n ax.scatter(Ydata, predicted)\n ax.plot([Ydata.min(), Ydata.max()], [Ydata.min(), Ydata.max()], 'k--', lw=4)\n ax.set_xlabel('Measured')\n ax.set_ylabel('Predicted')\n plt.show()\n\n","sub_path":"1_linear.py","file_name":"1_linear.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445119715","text":"# -*- coding: UTF-8 -*-\nimport asyncio\nimport aiohttp\nimport time\nimport os\ntasks =[]\nasync def get(url,semaphore):\n async with semaphore:\n print('Waiting for', url)\n print(f\"started at {time.strftime('%X')}\")\n session = aiohttp.ClientSession()\n response = await session.get(url)\n result = await response.text()\n await session.close()\n #print('Get response from', url, 'Result:', result)\n return result\nasync def request():\n semaphore = asyncio.Semaphore(200)\n url = 'http://127.0.0.1:5000'\n for t in range(1000):\n t = asyncio.create_task(get(url,semaphore))\n tasks.append(t)\n print(f\"started at {time.strftime('%X')}\")\n for t in tasks:\n await t\n print(f\"started at {time.strftime('%X')}\")\nstart = time.time()\nasyncio.run(request())\nend = time.time()\nprint('Cost time:', end - start)\n","sub_path":"python/Learn/Study/Concurrency/ThreadCases4/dev.3.py","file_name":"dev.3.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649384111","text":"from .cmd import *\nfrom .common import *\n\n\n@dataclass\nclass Packet:\n sequence: Sequence\n source_port: PortId\n source_channel: ChannelId\n destination_port: PortId\n destination_channel: ChannelId\n data: Hex\n timeout_height: Height\n timeout_timestamp: Timestamp\n\n\n@dataclass\nclass TxPacketSendRes:\n height: BlockHeight\n packet: Packet\n\n\n@cmd(\"tx raw ft-transfer\")\n@dataclass\nclass TxPacketSend(Cmd[TxPacketSendRes]):\n dst_chain_id: ChainId\n src_chain_id: ChainId\n src_port: PortId\n src_channel: ChannelId\n timeout_offset: int\n\n def args(self) -> List[str]:\n return [self.dst_chain_id, self.src_chain_id, self.src_port, self.src_channel, \"9999\", str(self.timeout_offset)]\n\n def process(self, result: Any) -> TxPacketSendRes:\n entry = find_entry(result, 'SendPacket')\n return from_dict(TxPacketSendRes, entry)\n\n# -----------------------------------------------------------------------------\n\n\n@dataclass\nclass TxPacketRecvRes:\n height: BlockHeight\n packet: Packet\n ack: Hex\n\n\n@cmd(\"tx raw packet-recv\")\n@dataclass\nclass TxPacketRecv(Cmd[TxPacketRecvRes]):\n dst_chain_id: ChainId\n src_chain_id: ChainId\n src_port: PortId\n src_channel: ChannelId\n\n def args(self) -> List[str]:\n return [self.dst_chain_id, self.src_chain_id, self.src_port, self.src_channel]\n\n def process(self, result: Any) -> TxPacketRecvRes:\n entry = find_entry(result, 'WriteAcknowledgement')\n return from_dict(TxPacketRecvRes, entry)\n\n# -----------------------------------------------------------------------------\n\n\n@dataclass\nclass TxPacketTimeoutRes:\n height: BlockHeight\n packet: Packet\n\n\n@cmd(\"tx raw packet-recv\")\n@dataclass\nclass TxPacketTimeout(Cmd[TxPacketTimeoutRes]):\n dst_chain_id: ChainId\n src_chain_id: ChainId\n src_port: PortId\n src_channel: ChannelId\n\n def args(self) -> List[str]:\n return [self.dst_chain_id, self.src_chain_id, self.src_port, self.src_channel]\n\n def process(self, result: Any) -> TxPacketTimeoutRes:\n entry = find_entry(result, 'TimeoutPacket')\n return from_dict(TxPacketTimeoutRes, entry)\n\n\n# -----------------------------------------------------------------------------\n\n\n@dataclass\nclass TxPacketAckRes:\n height: BlockHeight\n packet: Packet\n\n\n@cmd(\"tx raw packet-ack\")\n@dataclass\nclass TxPacketAck(Cmd[TxPacketAckRes]):\n dst_chain_id: ChainId\n src_chain_id: ChainId\n src_port: PortId\n src_channel: ChannelId\n\n def args(self) -> List[str]:\n return [self.dst_chain_id, self.src_chain_id, self.src_port, self.src_channel]\n\n def process(self, result: Any) -> TxPacketAckRes:\n entry = find_entry(result, 'AcknowledgePacket')\n return from_dict(TxPacketAckRes, entry)\n\n# =============================================================================\n# TRANSFER (packet send)\n# =============================================================================\n\n\ndef packet_send(c: Config, src: ChainId, dst: ChainId, src_port: PortId, src_channel: ChannelId, timeout_offset: int) -> Packet:\n cmd = TxPacketSend(dst_chain_id=dst, src_chain_id=src,\n src_port=src_port, src_channel=src_channel,\n timeout_offset=timeout_offset)\n\n res = cmd.run(c).success()\n l.info(\n f'PacketSend to {src} and obtained sequence number {res.packet.sequence}')\n\n return res.packet\n\n\ndef packet_recv(c: Config, dst: ChainId, src: ChainId, src_port: PortId, src_channel: ChannelId) -> Packet:\n cmd = TxPacketRecv(dst_chain_id=dst, src_chain_id=src,\n src_port=src_port, src_channel=src_channel)\n\n res = cmd.run(c).success()\n l.info(\n f'PacketRecv to {dst} done for sequence number {res.packet.sequence}')\n\n return res.packet\n\n\ndef packet_timeout(c: Config, dst: ChainId, src: ChainId, src_port: PortId, src_channel: ChannelId) -> Packet:\n cmd = TxPacketTimeout(dst_chain_id=dst, src_chain_id=src,\n src_port=src_port, src_channel=src_channel)\n\n res = cmd.run(c).success()\n l.info(\n f'Timeout to {src} done for sequence number {res.packet.sequence}')\n\n return res.packet\n\n\ndef packet_ack(c: Config, dst: ChainId, src: ChainId, src_port: PortId, src_channel: ChannelId) -> Packet:\n cmd = TxPacketAck(dst_chain_id=dst, src_chain_id=src,\n src_port=src_port, src_channel=src_channel)\n\n res = cmd.run(c).success()\n l.info(\n f'PacketAck to {dst} done for sequence number {res.packet.sequence}')\n\n return res.packet\n\n\ndef ping_pong(c: Config,\n side_a: ChainId, side_b: ChainId,\n a_chan: ChannelId, b_chan: ChannelId,\n port_id: PortId = PortId('transfer')):\n\n pkt_send_a = packet_send(c, side_a, side_b, port_id, a_chan, 1000)\n\n split()\n\n pkt_recv_b = packet_recv(c, side_b, side_a, port_id, a_chan)\n\n if pkt_send_a.sequence != pkt_recv_b.sequence:\n l.error(\n f'Mismatched sequence numbers for path {side_a} -> {side_b} : Sent={pkt_send_a.sequence} versus Received={pkt_recv_b.sequence}')\n\n split()\n\n # write the ack\n pkt_ack_a = packet_ack(c, side_a, side_b, port_id, b_chan)\n\n if pkt_recv_b.sequence != pkt_ack_a.sequence:\n l.error(\n f'Mismatched sequence numbers for ack on path {side_a} -> {side_b} : Recv={pkt_recv_b.sequence} versus Ack={pkt_ack_a.sequence}')\n\n split()\n\n pkt_send_b = packet_send(c, side_b, side_a, port_id, b_chan, 1000)\n\n split()\n\n pkt_recv_a = packet_recv(c, side_a, side_b, port_id, b_chan)\n\n if pkt_send_b.sequence != pkt_recv_a.sequence:\n l.error(\n f'Mismatched sequence numbers for path {side_b} -> {side_a} : Sent={pkt_send_b.sequence} versus Received={pkt_recv_a.sequence}')\n\n split()\n\n pkt_ack_b = packet_ack(c, side_b, side_a, port_id, a_chan)\n\n if pkt_recv_a.sequence != pkt_ack_b.sequence:\n l.error(\n f'Mismatched sequence numbers for ack on path {side_a} -> {side_b} : Recv={pkt_recv_a.sequence} versus Ack={pkt_ack_b.sequence}')\n\n\ndef timeout(c: Config,\n side_a: ChainId, side_b: ChainId,\n a_chan: ChannelId, b_chan: ChannelId,\n port_id: PortId = PortId('transfer')):\n\n pkt_send_a = packet_send(c, side_a, side_b, port_id, a_chan, 1)\n\n split()\n\n pkt_timeout_a = packet_timeout(c, side_b, side_a, port_id, a_chan)\n\n if pkt_send_a.sequence != pkt_timeout_a.sequence:\n l.error(\n f'Mismatched sequence numbers for path {side_a} -> {side_b} : Sent={pkt_send_a.sequence} versus Timeout={pkt_timeout_a.sequence}')\n\n split()\n\n pkt_send_b = packet_send(c, side_b, side_a, port_id, b_chan, 1)\n\n split()\n\n pkt_timeout_b = packet_timeout(c, side_a, side_b, port_id, b_chan)\n\n if pkt_send_b.sequence != pkt_timeout_b.sequence:\n l.error(\n f'Mismatched sequence numbers for path {side_b} -> {side_a} : Sent={pkt_send_b.sequence} versus Timeout={pkt_timeout_b.sequence}')\n\n split()\n\ndef find_entry(result: Any, key: str) -> Any:\n for entry in result:\n if key in entry:\n return entry[key]\n","sub_path":"e2e/e2e/packet.py","file_name":"packet.py","file_ext":"py","file_size_in_byte":7141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"22183538","text":"from flask import Flask\nfrom flask_restful import Resource, Api, reqparse, abort\nfrom config import debug\nfrom db import currencies, trade_currencies, trades, engine\nfrom utils import currencyRowToJson, tradesRowToJson, tradeCurrencyRowToJson\nfrom contract_helper import getAddressFromPuzzleHash, getContractProgram, programToPuzzleHash, getSolutionProgram\nfrom full_node_client import FullNodeClient\nfrom helper import bytes32\nfrom clvm.casts import int_from_bytes, int_to_bytes\nimport random\nimport blspy\nimport threading\nimport time\n\napp = Flask(\"yakuSwap API\")\napi = Api(app)\n\ndef std_hash(b) -> bytes32:\n \"\"\"\n The standard hash used in many places.\n \"\"\"\n return bytes32(blspy.Util.hash256(bytes(b)))\n\n\nclass HelloThere(Resource):\n\tdef get(self):\n\t\treturn {'message': 'Hello there!'}\n\n\nclass Currencies(Resource):\n\tdef get(self):\n\t\tconn = engine.connect()\n\n\t\ts = currencies.select()\n\t\tresult = conn.execute(s)\n\t\tres = []\n\n\t\tfor row in result:\n\t\t\tres.append(currencyRowToJson(row))\n\n\t\tconn.close()\n\t\treturn {'currencies': res}\n\n\nclass Trades(Resource):\n\tdef get(self):\n\t\tconn = engine.connect()\n\n\t\ts = trades.select()\n\t\tresult = conn.execute(s)\n\t\tres = []\n\n\t\tfor row in result:\n\t\t\tstmt = trade_currencies.select().where(trade_currencies.c.id == row[1])\n\t\t\ttrade_currency_one = conn.execute(stmt).all()[0]\n\t\t\tstmt = trade_currencies.select().where(trade_currencies.c.id == row[2])\n\t\t\ttrade_currency_two = conn.execute(stmt).all()[0]\n\n\t\t\tres.append(tradesRowToJson(row, tradeCurrencyRowToJson(trade_currency_one), tradeCurrencyRowToJson(trade_currency_two)))\n\n\t\tconn.close()\n\t\treturn {'trades': res}\n\n\n\nclass Currency(Resource):\n\tdef put(self, address_prefix):\n\t\tparser = reqparse.RequestParser()\n\t\tparser.add_argument('name',type=str, required=True)\n\t\tparser.add_argument('photo_url', type=str, required=True)\n\t\tparser.add_argument('units_per_coin', type=int, required=True)\n\t\tparser.add_argument('min_fee', type=int, required=True)\n\t\tparser.add_argument('default_max_block_height', type=int, required=True)\n\t\tparser.add_argument('default_min_confirmation_height', type=int, required=True)\n\t\tparser.add_argument('host', type=str, required=True)\n\t\tparser.add_argument('port', type=int, required=True)\n\t\tparser.add_argument('ssl_directory', type=str, required=True)\n\t\targs = parser.parse_args(strict=True)\n\n\t\tconn = engine.connect()\n\n\t\ts = currencies.select().where(currencies.c.address_prefix == address_prefix)\n\t\tresult = conn.execute(s)\n\t\tst = None\n\t\tif len(result.all()) == 0:\n\t\t\tst = currencies.insert()\n\t\telse:\n\t\t\tst = currencies.update().where(currencies.c.address_prefix == address_prefix)\n\t\tst = st.values(\n\t\t\taddress_prefix = address_prefix,\n\t\t\tname = args['name'],\n\t\t\tphoto_url = args['photo_url'],\n\t\t\tunits_per_coin = args['units_per_coin'],\n\t\t\tmin_fee = args['min_fee'],\n\t\t\tdefault_max_block_height = args['default_max_block_height'],\n\t\t\tdefault_min_confirmation_height = args['default_min_confirmation_height'],\n\t\t\thost = args['host'],\n\t\t\tport = args['port'],\n\t\t\tssl_directory = args['ssl_directory']\n\t\t)\n\t\tconn.execute(st)\n\n\t\tconn.close()\n\t\treturn {'success': True}\n\n\tdef delete(self, address_prefix):\n\t\tconn = engine.connect()\n\n\t\tstmt = currencies.delete().where(currencies.c.address_prefix == address_prefix)\n\t\tconn.execute(stmt)\n\n\t\tconn.close()\n\t\treturn {'success': True}\n\ntrade_threads_ids = []\ntrade_threads_messages = []\ntrade_threads_addresses = []\ntrade_threads_files = []\n\ndef tradeWaitForContract(trade_index, trade, trade_currency, currency, issue_contract, wait = False, other_trade_currency = False, other_currency = False):\n\tglobal trade_threads_ids, trade_threads_messages, trade_threads_addresses, trade_threads_files\n\n\tprogram = getContractProgram(\n\t\ttrade.secret_hash,\n\t\ttrade_currency.total_amount,\n\t\ttrade_currency.fee,\n\t\ttrade_currency.from_address,\n\t\ttrade_currency.to_address,\n\t\ttrade_currency.max_block_height,\n\t\tcurrency.min_fee\n\t)\n\tprogramPuzzleHash = programToPuzzleHash(program)\n\tprogramAddress = getAddressFromPuzzleHash(programPuzzleHash, currency.address_prefix)\n\ttrade_threads_files[trade_index].write(f\"Waiting for contract with puzzlehash {programPuzzleHash} and address {programAddress} to be confirmed\\n\")\n\ttrade_threads_files[trade_index].flush()\n\n\tfull_node_client = FullNodeClient(\n\t\tcurrency.ssl_directory,\n\t\tcurrency.host,\n\t\tcurrency.port,\n\t\ttrade_threads_files[trade_index]\n\t)\n\n\tamount_to_send = trade_currency.total_amount - currency.min_fee\n\tamount_to_send = amount_to_send / currency.units_per_coin\n\tfee = trade_currency.fee / currency.units_per_coin\n\tfirst_transacrion_fee = currency.min_fee / currency.units_per_coin\n\n\tif issue_contract:\n\t\ttrade_threads_messages[trade_index] = f\"Please send {amount_to_send:.12f} {currency.name} with a fee of {first_transacrion_fee:.12f} {currency.name} to the address found below. Double-check the address before confirming the transaction - if it's wrong, your coins will be lost.\"\n\t\ttrade_threads_addresses[trade_index] = programAddress\n\telse:\n\t\ttrade_threads_messages[trade_index] = f\"Waiting for the other human to send {amount_to_send:.12f} {currency.name} with a fee of {first_transacrion_fee:.12f} {currency.name} to the address found below...\"\n\t\ttrade_threads_addresses[trade_index] = programAddress\n\n\tif wait:\n\t\ttime.sleep(180)\n\n\theight = full_node_client.getBlockchainHeight()\n\n\tshouldCancel = False\n\tif other_trade_currency != False and other_currency != False:\n\t\tother_program = getContractProgram(\n\t\t\ttrade.secret_hash,\n\t\t\tother_trade_currency.total_amount,\n\t\t\tother_trade_currency.fee,\n\t\t\tother_trade_currency.from_address,\n\t\t\tother_trade_currency.to_address,\n\t\t\tother_trade_currency.max_block_height,\n\t\t\tother_currency.min_fee,\n\t\t)\n\t\totherProgramPuzzleHash = programToPuzzleHash(other_program)\n\n\t\tother_full_node_client = FullNodeClient(\n\t\t\tother_currency.ssl_directory,\n\t\t\tother_currency.host,\n\t\t\tother_currency.port,\n\t\t\ttrade_threads_files[trade_index]\n\t\t)\n\n\t\tother_coin_record = other_full_node_client.getContractCoinRecord(otherProgramPuzzleHash.hex(), height - 7 - other_trade_currency.max_block_height)\n\t\tif other_coin_record == False:\n\t\t\tshouldCancel = True\n\t\telse:\n\t\t\tother_coin_block_index = other_coin_record['confirmed_block_index']\n\t\n\t\ttrade_threads_files[trade_index].write(f\"Other coin record: {other_coin_record}\\nShould cancel? {shouldCancel}\\n\")\n\t\ttrade_threads_files[trade_index].flush()\n\n\tcontract_coin_record = full_node_client.getContractCoinRecord(programPuzzleHash.hex(), height - 7 - trade_currency.max_block_height)\n\twhile contract_coin_record == False and shouldCancel == False:\n\t\ttime.sleep(60)\n\t\theight = full_node_client.getBlockchainHeight()\n\t\tif other_trade_currency != False:\n\t\t\tother_height = other_full_node_client.getBlockchainHeight()\n\t\t\tif other_height - other_coin_block_index > other_trade_currency.max_block_height // 3 - other_trade_currency.min_confirmation_height * 2 - 25:\n\t\t\t\tshouldCancel = True\n\t\tif not shouldCancel:\n\t\t\tcontract_coin_record = full_node_client.getContractCoinRecord(programPuzzleHash.hex(), height - 7 - trade_currency.max_block_height)\n\n\n\tif shouldCancel == False and contract_coin_record[\"coin\"][\"amount\"] != trade_currency.total_amount - currency.min_fee:\n\t\ttrade_threads_files[trade_index].write(f\"Trickster detected!\\n\")\n\t\ttrade_threads_files[trade_index].flush()\n\t\tshouldCancel = True\n\n\ttrade_threads_files[trade_index].write(f\"Contract coin record: {contract_coin_record}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\tif shouldCancel:\n\t\ttrade_threads_files[trade_index].write(f\"Should cancel!\\n\")\n\t\ttrade_threads_files[trade_index].flush()\n\t\ttrade_threads_messages[trade_index] = \"Cancelling trade...\"\n\t\ttrade_threads_addresses[trade_index] = None\n\telse:\n\t\tconfirmed_block_index = contract_coin_record['confirmed_block_index']\n\t\ttrade_threads_messages[trade_index] = \"Waiting for transaction confirmation...\"\n\t\ttrade_threads_addresses[trade_index] = None\n\n\t\theight = full_node_client.getBlockchainHeight()\n\t\twhile confirmed_block_index + trade_currency.min_confirmation_height > height:\n\t\t\tdelta = height - confirmed_block_index\n\t\t\ttrade_threads_messages[trade_index] = f\"Waiting for transaction confirmation ({delta} / {trade_currency.min_confirmation_height})\"\n\t\t\ttrade_threads_addresses[trade_index] = None\n\t\t\ttime.sleep(15)\n\t\t\theight = full_node_client.getBlockchainHeight()\n\n\t\ttrade_threads_messages[trade_index] = \"Commencing to next step...\"\n\t\ttrade_threads_addresses[trade_index] = None\n\n\ttime.sleep(3)\n\treturn shouldCancel, contract_coin_record\n\ndef lookForSolutionInBlockchain(trade_index, trade, trade_currency, currency, coin_record):\n\tglobal trade_threads_ids, trade_threads_messages, trade_threads_addresses, trade_threads_files\n\n\tprogram = getContractProgram(\n\t\ttrade.secret_hash,\n\t\ttrade_currency.total_amount,\n\t\ttrade_currency.fee,\n\t\ttrade_currency.from_address,\n\t\ttrade_currency.to_address,\n\t\ttrade_currency.max_block_height,\n\t\tcurrency.min_fee\n\t)\n\tprogramPuzzleHash = programToPuzzleHash(program).hex()\n\n\ttrade_threads_files[trade_index].write(f\"Loking for solution of contract with puzzlehash {programPuzzleHash}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\n\tfull_node_client = FullNodeClient(\n\t\tcurrency.ssl_directory,\n\t\tcurrency.host,\n\t\tcurrency.port,\n\t\ttrade_threads_files[trade_index]\n\t)\n\n\tif coin_record == False:\n\t\ttrade_threads_messages[trade_index] = \"Getting contract coin record...\"\n\t\theight = full_node_client.getBlockchainHeight()\n\t\tcoin_record = full_node_client.getContractCoinRecord(programPuzzleHash, height - 10000 - trade_currency.max_block_height, True)\n\t\n\ttrade_threads_files[trade_index].write(f\"Coin record: {coin_record}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\n\tif coin_record == False:\n\t\ttrade_threads_messages[trade_index] = \"Something really strange happened...\"\n\t\treturn\n\n\ttrade_threads_messages[trade_index] = \"Getting contract solution...\"\n\tspent_block_index = coin_record[\"spent_block_index\"]\n\n\twhile spent_block_index == 0:\n\t\ttime.sleep(15)\n\t\theight = full_node_client.getBlockchainHeight()\n\t\tcoin_record = full_node_client.getContractCoinRecord(programPuzzleHash, height - 10000 - trade_currency.max_block_height, True)\n\t\tspent_block_index = coin_record[\"spent_block_index\"]\n\n\tcoin = coin_record[\"coin\"]\n\tcoin_id = std_hash(bytes.fromhex(coin[\"parent_coin_info\"][2:]) + bytes.fromhex(coin[\"puzzle_hash\"][2:]) + int_to_bytes(coin[\"amount\"])).hex()\n\ttrade_threads_files[trade_index].write(f\"Coin id: {coin_id}\\nSpent block index: {spent_block_index}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\tsol = full_node_client.getCoinSolution(coin_id, spent_block_index)\n\twhile sol == False:\n\t\ttrade_threads_messages[trade_index] = \"Getting contract solution (again)...\"\n\t\ttime.sleep(30)\n\t\tsol = full_node_client.getCoinSolution(coin_id, spent_block_index)\n\t\n\ttrade_threads_files[trade_index].write(f\"Solution: {sol}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\treturn sol\n\ndef tradeClaimContract(trade_index, trade, trade_currency, currency, solution_program_hex, coin_record, cancel = False):\n\tglobal trade_threads_ids, trade_threads_messages, trade_threads_addresses, trade_threads_files\n\n\tif cancel:\n\t\ttrade_threads_messages[trade_index] = \"Preparing to cancel trade :(\"\n\n\ttrade_threads_files[trade_index].write(f\"tradeClaimContract - cancel? {cancel}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\n\tprogram = getContractProgram(\n\t\ttrade.secret_hash,\n\t\ttrade_currency.total_amount,\n\t\ttrade_currency.fee,\n\t\ttrade_currency.from_address,\n\t\ttrade_currency.to_address,\n\t\ttrade_currency.max_block_height,\n\t\tcurrency.min_fee\n\t)\n\tprogramPuzzleHash = programToPuzzleHash(program).hex()\n\ttrade_threads_files[trade_index].write(f\"tradeClaimContract - contract with puzzlehash {programPuzzleHash}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\n\tfull_node_client = FullNodeClient(\n\t\tcurrency.ssl_directory,\n\t\tcurrency.host,\n\t\tcurrency.port,\n\t\ttrade_threads_files[trade_index]\n\t)\n\n\tif coin_record == False:\n\t\ttrade_threads_messages[trade_index] = \"Getting contract coin record...\"\n\t\theight = full_node_client.getBlockchainHeight()\n\t\tcoin_record = full_node_client.getContractCoinRecord(programPuzzleHash, height - 10000 - trade_currency.max_block_height, True)\n\ttrade_threads_files[trade_index].write(f\"Coin record: {coin_record}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\n\tif coin_record == False:\n\t\ttrade_threads_messages[trade_index] = \"Contract already claimed\"\n\t\treturn\n\n\ttrade_threads_messages[trade_index] = \"Waiting for node to be synced...\"\n\theight = full_node_client.getBlockchainHeight()\n\tcoin = coin_record[\"coin\"]\n\ttrade_threads_messages[trade_index] = \"Pushing transaction...\"\n\tr = full_node_client.pushTransaction(\n\t\tprogram.as_bin().hex(),\n\t\tsolution_program_hex,\n\t\tcoin\n\t)\n\twhile r == False:\n\t\ttrade_threads_messages[trade_index] = \"Pushing transaction again...\"\n\t\tr = full_node_client.pushTransaction(\n\t\t\tprogram.as_bin().hex(),\n\t\t\tsolution_program_hex,\n\t\t\tcoin\n\t\t)\n\t\ttime.sleep(5)\n\tif r == \"pending\":\n\t\twhile r == \"pending\":\n\t\t\ttrade_threads_messages[trade_index] = \"The transaction was marked as PENDING. I'll push it every 15 mins just to make sure.\"\n\t\t\tr = full_node_client.pushTransaction(\n\t\t\t\tprogram.as_bin().hex(),\n\t\t\t\tsolution_program_hex,\n\t\t\t\tcoin\n\t\t\t)\n\t\t\ttime.sleep(60 * 15)\n\t\ttrade_threads_messages[trade_index] = \"Done! Check your wallet :)\"\t\n\telse:\n\t\ttrade_threads_messages[trade_index] = \"Done! Check your wallet :)\"\t\n\ndef shouldCancelTrade(trade_index, trade, trade_currency, currency, coin_record):\n\tglobal trade_threads_ids, trade_threads_messages, trade_threads_addresses, trade_threads_files\n\n\ttrade_threads_files[trade_index].write(f\"Should cancel trade?\\n\")\n\ttrade_threads_files[trade_index].flush()\n\tprogram = getContractProgram(\n\t\ttrade.secret_hash,\n\t\ttrade_currency.total_amount,\n\t\ttrade_currency.fee,\n\t\ttrade_currency.from_address,\n\t\ttrade_currency.to_address,\n\t\ttrade_currency.max_block_height,\n\t\tcurrency.min_fee\n\t)\n\tprogramPuzzleHash = programToPuzzleHash(program).hex()\n\ttrade_threads_files[trade_index].write(f\"Contract with puzzlehash {programPuzzleHash}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\n\tfull_node_client = FullNodeClient(\n\t\tcurrency.ssl_directory,\n\t\tcurrency.host,\n\t\tcurrency.port,\n\t\ttrade_threads_files[trade_index]\n\t)\n\n\tif coin_record == False:\n\t\ttrade_threads_messages[trade_index] = \"Getting contract coin record...\"\n\t\theight = full_node_client.getBlockchainHeight()\n\t\tcoin_record = full_node_client.getContractCoinRecord(programPuzzleHash, height - 10000 - trade_currency.max_block_height, True)\n\t\n\tif coin_record == False:\n\t\ttrade_threads_messages[trade_index] = \"Contract already claimed\"\n\t\treturn False, False\n\n\ttrade_threads_files[trade_index].write(f\"Coin record: {coin_record}\\n\")\n\ttrade_threads_files[trade_index].flush()\n\ttrade_threads_messages[trade_index] = \"Waiting for node to be synced...\"\n\theight = full_node_client.getBlockchainHeight()\n\ttrade_threads_messages[trade_index] = \"Verifying height...\"\n\t\n\tcancel = False\n\n\tif height - coin_record['confirmed_block_index'] > trade_currency.max_block_height // 3 - trade_currency.min_confirmation_height * 2 - 25:\n\t\tcancel = True\n\n\treturn coin_record, cancel\n\ndef _dumpTradeCurrency(trade_index, trade_currency_one):\n\tglobal trade_threads_files\n\ttrade_threads_files[trade_index].write(f\"Addres prefix: {trade_currency_one.address_prefix}\\n\")\n\ttrade_threads_files[trade_index].write(f\"Fee: {trade_currency_one.fee}\\n\")\n\ttrade_threads_files[trade_index].write(f\"Max block height: {trade_currency_one.max_block_height}\\n\")\n\ttrade_threads_files[trade_index].write(f\"Min conf time: {trade_currency_one.min_confirmation_height}\\n\")\n\ttrade_threads_files[trade_index].write(f\"From: {trade_currency_one.from_address}\\n\")\n\ttrade_threads_files[trade_index].write(f\"To: {trade_currency_one.to_address}\\n\")\n\ttrade_threads_files[trade_index].write(f\"Total amount: {trade_currency_one.total_amount}\\n\\n\\n\")\n\ttrade_threads_files[trade_index].flush()\n\ndef tradeCode(trade_id):\n\tglobal trade_threads_ids, trade_threads_messages, trade_threads_addresses, trade_threads_files\n\ttrade_index = 0\n\tfor i, v in enumerate(trade_threads_ids):\n\t\tif v == trade_id:\n\t\t\ttrade_index = i\n\n\ttrade_threads_files[trade_index].write(\"ONLY SHARE THE CONTENTS OF THIS FILE WITH TRUSTED PEOPLE\\n\")\n\n\tconn = engine.connect()\n\n\ts = trades.select().where(trades.c.id == trade_id)\n\ttrade = conn.execute(s).all()[0]\n\ttrade_threads_files[trade_index].write(f\"Trade\\n\\n\")\n\ttrade_threads_files[trade_index].write(f\"Trade id: {trade_id}\\n\")\n\ttrade_threads_files[trade_index].write(f\"Secret hash: {trade.secret_hash}\\n\")\n\ttrade_threads_files[trade_index].write(f\"Is Buyer?: {trade.is_buyer}\\n\")\n\ttrade_threads_files[trade_index].write(f\"Secret: {trade.secret}\\n\")\n\ttrade_threads_files[trade_index].write(f\"Step: {trade.step}\\n\\n\\n\")\n\ttrade_threads_files[trade_index].flush()\n\n\ts = trade_currencies.select().where(trade_currencies.c.id == trade.trade_currency_one)\n\ttrade_currency_one = conn.execute(s).all()[0]\n\ttrade_threads_files[trade_index].write(f\"Trade currency one\\n\\n\")\n\t_dumpTradeCurrency(trade_index, trade_currency_one)\n\n\ts = currencies.select().where(currencies.c.address_prefix == trade_currency_one.address_prefix)\n\tcurrency_one = conn.execute(s).all()[0]\n\n\ts = trade_currencies.select().where(trade_currencies.c.id == trade.trade_currency_two)\n\ttrade_currency_two = conn.execute(s).all()[0]\n\ttrade_threads_files[trade_index].write(f\"Trade currency two\\n\\n\")\n\t_dumpTradeCurrency(trade_index, trade_currency_two)\n\n\ts = currencies.select().where(currencies.c.address_prefix == trade_currency_two.address_prefix)\n\tcurrency_two = conn.execute(s).all()[0]\n\t\n\tcoin_record_one = False\n\tcoin_record_two = False\n\tcoming_from_step_0 = False\n\n\tshouldCancel = False\n\n\tif trade.step == 0:\n\t\tshouldCancel, coin_record_one = tradeWaitForContract(trade_index, trade, trade_currency_one, currency_one, trade.is_buyer, True)\n\n\t\ts = trades.update().where(trades.c.id == trade_id).values(step = 1)\n\t\tconn.execute(s)\n\t\ts = trades.select().where(trades.c.id == trade_id)\n\t\ttrade = conn.execute(s).all()[0]\n\t\tcoming_from_step_0 = True\n\n\tif trade.step == 1:\n\t\tshouldCancel, coin_record_two = tradeWaitForContract(trade_index, trade, trade_currency_two, currency_two, not trade.is_buyer, coming_from_step_0, trade_currency_one, currency_one)\n\n\t\ts = trades.update().where(trades.c.id == trade_id).values(step = 2)\n\t\tconn.execute(s)\n\t\ts = trades.select().where(trades.c.id == trade_id)\n\t\ttrade = conn.execute(s).all()[0]\n\n\tif trade.step == 2:\n\t\ttrade_threads_messages[trade_index] = \"Starting last step...\"\n\t\ttrade_threads_addresses[trade_index] = None\n\n\t\tcancelTrade = shouldCancel\n\t\tif not cancelTrade:\n\t\t\tif trade.is_buyer:\n\t\t\t\tcoin_record_two, cancelTrade = shouldCancelTrade(trade_index, trade, trade_currency_two, currency_two, coin_record_two)\n\t\t\telse:\n\t\t\t\tcoin_record_one, cancelTrade = shouldCancelTrade(trade_index, trade, trade_currency_one, currency_one, coin_record_one)\n\n\t\ttrade_threads_files[trade_index].write(f\"Cancel trade: {cancelTrade}\\n\")\n\t\ttrade_threads_files[trade_index].flush()\n\t\tif cancelTrade:\n\t\t\tsolution_program = getSolutionProgram(\"CANCEL-\" + str(random.SystemRandom().getrandbits(128))).as_bin().hex()\n\t\t\tif trade.is_buyer:\n\t\t\t\ttradeClaimContract(trade_index, trade, trade_currency_one, currency_one, solution_program, coin_record_one, True)\n\t\t\telse:\n\t\t\t\ttradeClaimContract(trade_index, trade, trade_currency_two, currency_two, solution_program, coin_record_two, True)\n\t\telse:\n\t\t\tif trade.is_buyer:\n\t\t\t\tsolution_program = getSolutionProgram(trade.secret).as_bin().hex()\n\t\t\t\ttradeClaimContract(trade_index, trade, trade_currency_two, currency_two, solution_program, coin_record_two)\n\t\t\telse:\n\t\t\t\tsolution_program = lookForSolutionInBlockchain(trade_index, trade, trade_currency_two, currency_two, coin_record_two)\n\t\t\t\ttradeClaimContract(trade_index, trade, trade_currency_one, currency_one, solution_program, coin_record_one)\n\n\tconn.close()\n\nclass Trade(Resource):\n\tdef get(self, trade_id):\n\t\tglobal trade_threads_ids, trade_threads_messages, trade_threads_addresses, trade_threads_files\n\t\tif not trade_id in trade_threads_ids:\n\t\t\tt = threading.Thread(target=tradeCode, args=(trade_id, ))\n\t\t\ttrade_threads_ids.append(trade_id)\n\t\t\ttrade_threads_messages.append(\"Starting thread...\")\n\t\t\ttrade_threads_addresses.append(None)\n\t\t\ttrade_threads_files.append(open(f\"{trade_id}-log.txt\", \"a+\"))\n\t\t\tt.start()\n\n\t\tindex = 0\n\t\tfor i, v in enumerate(trade_threads_ids):\n\t\t\tif v == trade_id:\n\t\t\t\tindex = i\n\t\treturn {\n\t\t\t\"message\": trade_threads_messages[index],\n\t\t\t\"address\": trade_threads_addresses[index]\n\t\t}\n\n\tdef addTradeCurrency(self, engine, data):\n\t\tconn = engine.connect()\n\n\t\ts = trade_currencies.select().where(trade_currencies.c.id == data['id'])\n\t\tresult = conn.execute(s)\n\t\tst = None\n\t\tif len(result.all()) == 0:\n\t\t\tst = trade_currencies.insert()\n\t\telse:\n\t\t\tst = trade_currencies.update().where(trade_currencies.c.id == data['id'])\n\t\tst = st.values(\n\t\t\tid = data['id'],\n\t\t\taddress_prefix = data['address_prefix'],\n\t\t\tfee = data['fee'],\n\t\t\tmax_block_height = data['max_block_height'],\n\t\t\tmin_confirmation_height = data['min_confirmation_height'],\n\t\t\tfrom_address = data['from_address'],\n\t\t\tto_address = data['to_address'],\n\t\t\ttotal_amount = data['total_amount']\n\t\t)\n\t\tconn.execute(st)\n\n\t\tconn.close()\n\n\tdef put(self, trade_id):\n\t\tparser = reqparse.RequestParser()\n\t\tparser.add_argument('trade_currency_one', type=dict, required=True)\n\t\tparser.add_argument('trade_currency_two', type=dict, required=True)\n\t\tparser.add_argument('secret', type=str, required=True)\n\t\tparser.add_argument('secret_hash', type=str, required=True)\n\t\tparser.add_argument('is_buyer', type=bool, required=True)\n\t\tparser.add_argument('secret', type=str, required=True)\n\t\tparser.add_argument('step', type=int, required=True)\n\n\t\targs = parser.parse_args(strict=True)\n\n\t\tself.addTradeCurrency(engine, args['trade_currency_one'])\n\t\tself.addTradeCurrency(engine, args['trade_currency_two'])\n\n\t\tconn = engine.connect()\n\n\t\ts = trades.select().where(trades.c.id == trade_id)\n\t\tresult = conn.execute(s)\n\t\tst = None\n\t\tif len(result.all()) == 0:\n\t\t\tst = trades.insert()\n\t\telse:\n\t\t\tst = trades.update().where(trades.c.id == trade_id)\n\t\tst = st.values(\n\t\t\tid = trade_id,\n\t\t\ttrade_currency_one = args['trade_currency_one']['id'],\n\t\t\ttrade_currency_two = args['trade_currency_two']['id'],\n\t\t\tsecret_hash = args['secret_hash'],\n\t\t\tis_buyer = args['is_buyer'],\n\t\t\tsecret = args['secret'],\n\t\t\tstep = args['step'],\n\t\t)\n\t\tconn.execute(st)\n\n\t\tconn.close()\n\t\treturn {'success': True}\n\n\tdef delete(self, trade_id):\n\t\tconn = engine.connect()\n\n\t\tstmt = trades.delete().where(trades.c.id == trade_id)\n\t\tconn.execute(stmt)\n\n\t\tconn.close()\n\t\treturn {'success': True}\n\n\napi.add_resource(HelloThere, '/')\napi.add_resource(Currencies, '/currencies')\napi.add_resource(Trades, '/trades')\napi.add_resource(Currency, '/currency/')\napi.add_resource(Trade, '/trade/')\n\nif __name__ == '__main__':\n\tapp.run(host='127.0.0.1', port=4143, debug=debug)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618889431","text":"def main():\n n = input()\n numbers = input().split()\n A = []\n for i in range(len(numbers)):\n A.append(int(numbers[i]))\n\n S = set(A)\n longest = 0\n\n # For each initial f0 (A[i]) and f1 (A[j]) we need to search for\n # the next f's\n for i in range(len(A)):\n for j in range(i+1, len(A)):\n x, y = A[j], A[i]+A[j]\n length = 2\n\n while y in S:\n x, y = y, x+y\n length += 1\n\n if length > longest:\n longest = length\n print(longest)\n\n\nif __name__ == '__main__':\n main()","sub_path":"Problema 3.py","file_name":"Problema 3.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"141878238","text":"from django.urls import path\n\nfrom . import views\nfrom .views import (BueroAddView, BueroChangeView, BueroDeleteView, BueroView,\n BusAddView, BusChangeView, BusDeleteView, BusView)\n\napp_name = 'Einsatzmittel'\nurlpatterns = [\n path('busse/', BusView.as_view()),\n path('busse/add/', BusAddView.as_view()),\n path('busse//', BusChangeView.as_view()),\n path('busse//delete/', BusDeleteView.as_view()),\n path('bueros/', BueroView.as_view()),\n path('bueros/add/', BueroAddView.as_view()),\n path('bueros//', BueroChangeView.as_view()),\n path('bueros//delete/', BueroDeleteView.as_view()),\n]\n","sub_path":"Einsatzmittel/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"418678228","text":"from data_structures.cluster import Cluster\nimport re\n\n\nclass Datacenter:\n def __init__(self, name, cluster_dict):\n \"\"\"\n Constructor for Datacenter data structure.\n\n self.name -> str\n self.clusters -> list(Cluster)\n \"\"\"\n self.name = name\n self.clusters = [Cluster(name, values['networks'], values['security_level'])\n for name, values in cluster_dict.items()]\n\n def remove_invalid_clusters(self):\n \"\"\"\n Removes invalid objects from the clusters list.\n \"\"\"\n\n valid_clusters = []\n\n for cluster in self.clusters:\n if self.match_name_pattern(cluster.name):\n valid_clusters.append(cluster)\n\n self.clusters = valid_clusters\n\n def match_name_pattern(self, name):\n \"\"\"\n Args:\n name: datacenter name\n\n Returns: true if name matches first 3 letters of the parrent, a dash and a number <= 999\n\n \"\"\"\n first3_upper = self.name[:3].upper()\n pattern = '^' + first3_upper + '\\-\\d{1,3}$'\n c_pattern = re.compile(pattern)\n return c_pattern.match(name) is not None\n","sub_path":"data_structures/datacenter.py","file_name":"datacenter.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"526007926","text":"from inf import *\r\nclass Button: # Класс для создание простых кнопок с ссылкой\r\n\r\n\tdef __init__(self, width, height, active_button = (200,200,200), unactive_button = (200,200,255), link = None):\r\n\t\tself.width = width\r\n\t\tself.height = height\r\n\t\tself.active_button = active_button\r\n\t\tself.unactive_button = unactive_button\r\n\t\tself.link = link\r\n\tdef draw_rect(self, x, y,):\r\n\t\tglobal click_press\r\n\t\tmouse = pygame.mouse.get_pos() # print(mouse) >>> [x, y]\r\n\t\tclick = pygame.mouse.get_pressed() # print(click) >>> [0, 0]\r\n\r\n\t\tif x < mouse[0] < x + self.width and y < mouse[1] < y + self.height:\r\n\t\t\tpygame.draw.rect(win, self.active_button, (x, y, self.width, self.height))\r\n\t\t\r\n\t\t\tif click[0] == 1 and self.link != None and click_press:\r\n\t\t\t\tclick_press = False\r\n\t\t\t\tself.link()\r\n\t\t\tif click[0] != 1:\r\n\t\t\t\tclick_press = True\r\n\t\t\t\r\n\t\telse:\r\n\t\t\tpygame.draw.rect(win, self.unactive_button, (x, y, self.width, self.height))\r\n\r\n\r\n","sub_path":"_AlleyWay(3)/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390976615","text":"import pygame\r\n\r\n# Class for help screen app, contains text boxes\r\n\r\nclass HelpScreenApp():\r\n def __init__(app, screen, screenWidth, screenHeight):\r\n app.screen = screen\r\n app.screenWidth = screenWidth\r\n app.screenHeight = screenHeight\r\n app.clock = pygame.time.Clock()\r\n app.frameRate = 30\r\n\r\n app.white = (255,255,255)\r\n app.blue = (0,0,255)\r\n app.black = (0,0,0)\r\n app.red = (255,0,0)\r\n\r\n # Title text box\r\n titleText = ['Intro to Shredding']\r\n titleFontSize = 40\r\n titleTextFont = pygame.font.Font('Fonts/EncodeSans-Black.ttf', titleFontSize)\r\n app.titleTextBox = app.createTextBox(titleTextFont, titleFontSize, titleText, app.blue, app.black, app.red)\r\n app.titleTextBoxRect = app.titleTextBox.get_rect()\r\n app.titleTextBoxRect.centerx = app.screenWidth/2\r\n app.titleTextBoxRect.centery = app.screenHeight/5\r\n\r\n # Help text box\r\n helpTextList = ['Goal is to have fun and get points by doing tricks off cliffs',\r\n 'Controls are left and right arrows for directional movement and in-air spinning',\r\n 'In-air you can perform grabs using the \\'a\\' and \\'d\\' keys',\r\n 'Explore the grabs for yourself!',\r\n 'Press \\'p\\' to pause game (and option to exit if infinite mode)']\r\n helpFontSize = 25\r\n helpTextFont = pygame.font.Font('Fonts/EncodeSans-Black.ttf', helpFontSize)\r\n app.helpTextBox = app.createTextBox(helpTextFont, helpFontSize, helpTextList, app.white, app.black, app.blue)\r\n app.helpTextBoxRect = app.helpTextBox.get_rect()\r\n app.helpTextBoxRect.centerx = app.screenWidth/2\r\n app.helpTextBoxRect.centery = app.screenHeight/2\r\n\r\n # Control text box\r\n controlText = ['Press \\'m\\' to return to main screen']\r\n controlFontSize = 20\r\n controlTextFont = pygame.font.Font('Fonts/EncodeSans-Black.ttf', controlFontSize)\r\n app.controlTextBox = app.createTextBox(controlTextFont, controlFontSize, controlText, app.white, app.black, app.red)\r\n app.controlTextBoxRect = app.controlTextBox.get_rect()\r\n app.controlTextBoxRect.centerx = app.screenWidth/2\r\n app.controlTextBoxRect.centery = 4*app.screenHeight/5\r\n\r\n\r\n # Create a text box depending on the inputs\r\n def createTextBox(app, font, textSize, textList, textColor, borderColor, fillColor):\r\n maxWidth = 0\r\n textHeight = 0\r\n # List to store the text renders\r\n textDisplays = []\r\n\r\n # Loop through the list of text and render text and find the text line that is longest and store the pixel width\r\n # Also store sum of the height of the text\r\n for text in textList:\r\n textDisplay = font.render(text, True, textColor)\r\n textDisplays.append(textDisplay)\r\n if textDisplay.get_width() > maxWidth:\r\n maxWidth = textDisplay.get_width()\r\n textHeight += textDisplay.get_height()\r\n\r\n # Set the text box to a little larger than the text\r\n height = textHeight + 30\r\n width = maxWidth + 20\r\n\r\n # Create the text box surface and fill it with border color, fill a deflated rect with the fill color\r\n textBox = pygame.Surface((width, height))\r\n textBoxRect = textBox.get_rect()\r\n textBox.fill(borderColor)\r\n border = -7\r\n textBox.fill(fillColor, rect=textBoxRect.inflate(border, border))\r\n\r\n # Draw the text onto the box surface\r\n y = abs(border)\r\n for textDisplay in textDisplays:\r\n x = textBoxRect.width/2 - textDisplay.get_width()/2\r\n textBox.blit(textDisplay, (x, y))\r\n y += textSize + 10\r\n return textBox\r\n \r\n\r\n def processEvent(app, event):\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_m: # Go back to main screen if press m key\r\n return 'MainScreen'\r\n return 'HelpScreen'\r\n \r\n def displayFrame(app):\r\n app.screen.fill(app.white)\r\n app.screen.blit(app.helpTextBox, app.helpTextBoxRect)\r\n app.screen.blit(app.controlTextBox, app.controlTextBoxRect)\r\n app.screen.blit(app.titleTextBox, app.titleTextBoxRect)\r\n pygame.display.update()","sub_path":"Game/Code/helpScreenMode.py","file_name":"helpScreenMode.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"541010549","text":"from urllib import request\nfrom urllib.request import Request\n\nfrom bs4 import BeautifulSoup\n\nimport mail\n\ndict = {}\nurl = 'https://movie.douban.com/top250'\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}\n\n\ndef get_html(url):\n req = Request(url, headers=headers)\n html = request.urlopen(req).read().decode()\n return html\n\n\ndef parse_html(htmlfile):\n bs = BeautifulSoup(htmlfile, 'html.parser')\n movie_zone = bs.find('ol')\n movie_list = movie_zone.find_all('li')\n for movie in movie_list:\n dict.__setitem__(movie.find('span', attrs={'class': 'title'}).getText(),\n movie.find('span', attrs={'class': 'inq'}).getText())\n\n\ndef to_content(**kwargs):\n message = ''\n n = 1\n for k, v in kwargs.items():\n message += 'top %s 名称: <%s> 简介: %s \\n' % (n, k, v)\n n += 1\n return message\n\n\ndef get_receivers():\n try:\n file = open('mail.txt', 'r')\n return file.readlines()\n finally:\n if file:\n file.close()\n\n\ndef send_top25_movies():\n parse_html(get_html(url))\n mail.send_mail(get_receivers(), title='top25 电影', subject=to_content(**dict))\n\nif __name__ == '__main__':\n send_top25_movies()\n","sub_path":"movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"533412820","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# #*** ************************************************************#\n# This module is part of the repository CNDB.\n# \n# This module is licensed under the terms of the BSD 3-Clause License\n# .\n# #*** ***********************************************************#\n\nfrom rsclib.HTML_Parse import tag\nfrom rsclib.autosuper import autosuper\n\nclass Version_Mixin (autosuper) :\n version = \"Unknown\"\n luci_version = bf_version = None\n\n def try_get_version (self, div) :\n if div.get ('class') == 'footer' :\n for p in div.findall (\".//%s\" % tag (\"p\")) :\n if ( p.get ('class') == 'luci'\n and len (p)\n and p [0].tag == tag (\"a\")\n ) :\n a = p [0]\n if a.text.startswith (\"Powered by LuCI\") :\n self.luci_version = a.text\n if div.get ('class') == 'header_right' :\n self.bf_version = div.text\n if div.get ('class') == 'hostinfo' :\n assert self.bf_version is None\n self.bf_version = div.text.split ('|') [0].strip ()\n if div.get ('id') == 'header' and not self.bf_version :\n p = div.find (\".//%s\" % tag (\"p\"))\n if p is not None :\n v = p.text.split (':', 1) [-1].split ('|', 1) [0]\n self.bf_version = v\n # end def try_get_version\n\n def set_version (self, root) :\n lv = self.luci_version\n if lv is None :\n p = root [-1][-1]\n if p.tag == tag ('p') and p.get ('class') == 'luci' :\n lv = self.luci_version = self.tree.get_text (p)\n # New 2014-Beta (sic) backfire has changed the version info :-(\n if lv is None :\n footer = None\n for a in root.findall (\".//%s\" % tag (\"a\")) :\n if a.get ('href') == 'http://luci.subsignal.org/' :\n break\n if a is not None :\n if a.text.startswith (\"Powered by LuCI\") :\n self.luci_version = lv = a.text\n self.bf_version = a.tail.strip ()\n if (lv and lv.startswith ('Powered by LuCI')) :\n lv = lv.split ('(', 1) [-1].split (')', 1) [0]\n self.luci_version = lv\n if self.bf_version and self.luci_version :\n self.version = \"%s / Luci %s\" % (self.bf_version, self.luci_version)\n # end def set_version\n\n# end class Version_Mixin\n","sub_path":"spider/luci.py","file_name":"luci.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"569183196","text":"import paho.mqtt.client as mqtt\nimport time\n#f = open(\"/proc/loadavg\", \"r+\")\n\n#load = f.read()\n\ndef on_connect(client,userdata,flags,rc):\n\tprint(\"connected\")\n\n\ndef on_publish(client,userdata,result):\n\tprint(\"data published\")\n\nclient = mqtt.Client(\"clientid\")\nclient.on_publish=on_publish\n\nclient.will_set(\"client/dead\",\"client disconnected\",0,True)\nclient.connect(\"192.168.75.140\", 1883, 60)\nclient.on_connect=on_connect\n#client.will_set(\"client/dead\",\"client disconnected\",0,True)\nwhile True:\n\tf = open(\"/proc/loadavg\", \"r+\")\n\tload = f.read()\n#\tprint(type(load))\n\tloadl=load.split()\n\tret=client.publish(\"hello/pc/1minavg\",'1minavg '+loadl[0])\n\tret=client.publish(\"hello/pc1/5minavg\",'5minavg '+loadl[1])\n\tret=client.publish(\"hello/pc3/10minavg\",'10minavg '+loadl[2])\n\t#client.will_set(\"client/dead\",\"client disconnected\",0,True)\n\ttime.sleep(5)\n\tf.close()\nclient.loop_forever()\n","sub_path":"mqqtclipub.py","file_name":"mqqtclipub.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115770038","text":"import tensorflow as tf\n\nimport helper\n\nclass MemoryBase:\n '''\n This is the base class for all sorts of memory\n \n Functions to expand in child classes:\n __init__(self, ...): Setup the parameters\n setup(self, batchSize): Setup the start variables\n '''\n\n def __init__(self, name):\n self.name = name\n self.ops = []\n\n def queueWrite(self, w, erase, add):\n assert helper.check(w, [self.length], self.batchSize)\n assert helper.check(erase, [self.bitDepth], self.batchSize)\n assert helper.check(add, [self.bitDepth], self.batchSize)\n\n self.ops.append({'w':w,'e':erase,'a':add})\n\n def write(self):\n if len(self.ops) == 1:\n erase = 1 - tf.matmul(tf.expand_dims(self.ops[0]['w'], axis=-1),tf.expand_dims(self.ops[0]['e'], axis=-2))\n add = tf.matmul(tf.expand_dims(self.ops[0]['w'], axis=-1),tf.expand_dims(self.ops[0]['a'], axis=-2))\n\n self.M.append(self.M[-1] * erase + add)\n else:\n erase = tf.ones([self.batchSize, self.length, self.bitDepth])\n add = tf.zeros([self.batchSize, self.length, self.bitDepth])\n\n for op in self.ops:\n erase *= 1 - tf.matmul(tf.expand_dims(op['w'], axis=-1),tf.expand_dims(op['e'], axis=-2))\n add += tf.matmul(tf.expand_dims(op['w'], axis=-1),tf.expand_dims(op['a'], axis=-2))\n\n self.M.append(self.M[-1] * erase + add)\n\n self.ops = []\n\n def read(self, w):\n if len(w.get_shape())==2:\n assert helper.check(w, [self.length], self.batchSize)\n assert helper.check(self.M[-1], [self.length, self.bitDepth], self.batchSize)\n\n r = tf.squeeze(tf.matmul(tf.expand_dims(w,axis=-2), self.M[-1]),axis=-2)\n assert helper.check(r, [self.bitDepth], self.batchSize)\n\n return r\n else:\n multiple = w.get_shape()[1]\n\n assert helper.check(w, [multiple, self.length], self.batchSize)\n assert helper.check(self.M[-1], [self.length, self.bitDepth], self.batchSize)\n\n r = tf.matmul(w, self.M[-1])\n assert helper.check(r, [multiple, self.bitDepth], self.batchSize)\n\n r = tf.reshape(r, [self.batchSize, multiple * self.bitDepth])\n assert helper.check(r, [multiple * self.bitDepth], self.batchSize)\n\n return r\n \n\n","sub_path":"Philippe_Code/NTM/MANN/Memory/MemoryBase.py","file_name":"MemoryBase.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455550084","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom pathlib import Path\nimport os\nimport pandas as pd \nimport codecs\nimport urllib\nimport time\nimport csv\n\n###################################\n\ndef isNeedInfo(n):\n if(n == \"エネルギー\" or n == \"食物繊維\" or n == \"たんぱく質\" or n == \"脂質\" or n == \"炭水化物\"):\n return True\n return False\n\ndef getInfo(soup, num):\n \n product_need_info_list = []\n # picture\n # name\n swp = soup.find(\"picture\", class_=\"block\")\n im = swp.find(\"img\")\n name = im.get(\"alt\")\n print(name)\n product_need_info_list.append(name)\n # print(im.et(\"src\"))\n\n # price\n swp = soup.find(class_=\"pdp__product-info\")\n span = swp.find_all(\"span\", class_=\"product-section-price-primary-val\")\n\n if len(span) >= 1:\n price = span[num].text \n else:\n price = span[0].text\n print(price)\n product_need_info_list.append(price)\n\n # カロリー, タンパク質, \b脂質, 炭水化物, 食塩相当量, 食物繊維\n swp = soup.find(id=\"product-nutrients-block\")\n nutrients_list = swp.find_all(class_=\"pdp-card-item-box\")\n for element in nutrients_list :\n product_info = element.find_all(\"span\")\n if isNeedInfo(product_info[0].text):\n product_need_info_list.append(product_info[1].text)\n # data_list.append(product_info[1].text)\n return product_need_info_list\n\n\n###################################\n\ndata_col = [\"size\", \"name\", \"price\", \"calorie\", \"protein\", \"fat\", \"carbohydrate\", \"dietary_fiber\", \"isSetMain\", \"isSetSide\", \"isSetDrink\"]\nbase_url = \"https://www.mcdonalds.co.jp\"\n\nset_datas_list = []\nset_datas_list.append(data_col)\n\n# URL \nbase_url = \"https://www.mcdonalds.co.jp\"\nload_url = \"https://www.mcdonalds.co.jp/menu/drink/\"\nhtml = requests.get(load_url)\nsoup = BeautifulSoup(html.content, \"lxml\")\n\ndetail_oods_atag_list = soup.find_all(\"a\", class_=\"inline-block\")\nfor atag in detail_oods_atag_list:\n url = atag.get(\"href\")\n html = requests.get(base_url + url)\n soup = BeautifulSoup(html.content, \"lxml\")\n\n# # print(soup)\n if soup.find(\"div\", class_=\"dropdown-menu\"):\n # has many size\n html = soup.find(\"div\", class_=\"dropdown-menu\")\n size_list_atag_list = html.find_all(\"a\")\n print(size_list_atag_list)\n\n count = 0\n for atag in size_list_atag_list:\n print(atag)\n data_list = []\n data_list.append(None)\n url = atag.get(\"href\")\n url = url.split(\"#\")[0]\n html = requests.get(base_url + url)\n soup = BeautifulSoup(html.content, \"lxml\")\n getInfo_list = getInfo(soup, count)\n\n for data in getInfo_list :\n data_list.append(data)\n\n data_list.append(None)\n data_list.append(None)\n data_list.append(None)\n print(data_list)\n\n set_datas_list.append(data_list)\n print(set_datas_list)\n\n count += 1\n time.sleep(5)\n\n\n\n\n\n\n\n else:\n # URL \n data_list = []\n data_list.append(None)\n\n # # picture\n # # name\n # swp = soup.find(\"picture\", class_=\"block\")\n # im = swp.find(\"im\")\n # name = im.et(\"alt\")\n # print(name)\n # data_list.append(name)\n # # print(im.et(\"src\"))\n\n # # price\n # swp = soup.find(class_=\"pdp__product-info\")\n # span = swp.find(\"span\", class_=\"product-section-price-primary-val\")\n # price = span.text\n # print(price)\n # data_list.append(price)\n\n # # カロリー, タンパク質, \b脂質, 炭水化物, 食塩相当量, 食物繊維\n # swp = soup.find(id=\"product-nutrients-block\")\n # nutrients_list = swp.find_all(class_=\"pdp-card-item-box\")\n # product_need_info_list = []\n # for element in nutrients_list :\n # product_info = element.find_all(\"span\")\n # if isNeedInfo(product_info[0].text):\n # # product_need_info_list.append(product_info[1].text)\n # data_list.append(product_info[1].text)\n\n getInfo_list = getInfo(soup, 0)\n\n for data in getInfo_list:\n data_list.append(data)\n\n data_list.append(None)\n data_list.append(None)\n data_list.append(None)\n print(data_list)\n\n set_datas_list.append(data_list)\n print(set_datas_list)\n time.sleep(5)\n\n\nwith open('data.csv', 'w') as file:\n writer = csv.writer(file, lineterminator='\\n')\n writer.writerows(set_datas_list)","sub_path":"input-drink.py","file_name":"input-drink.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"617011777","text":"from django.urls import path, re_path\nfrom .views import product_list, product_detail,product_category\n\napp_name = 'products'\n\nurlpatterns = [\n path('', product_list, name='product_list'),\n\n re_path(r'(?P[-\\w]+)/detail/', product_detail, name='product_detail'),\n\n path('/دسته-بندی-ها/', product_category, name='product_category'),\n\n]\n","sub_path":"products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"413680695","text":"#Program Completed \nimport requests \nfrom bs4 import BeautifulSoup\n\n#Gets a string with the description of the course and \ndef getTopics(description):\n topics = []\n if(\"Engineering\" in description or \"engineering\" in description):\n topics.append(\"Engineering\")\n if(\"Art\" in description or \"art\" in description):\n topics.append(\"Art\")\n if(\"Coding\" in description or \"coding\" in description):\n topics.append(\"Code\")\n #maybe needs more topics'\n #print(topics)\n return topics\n\n#Takes in a string holding the info of the website\n#returns the courseType if a certain keyword is founded.\ndef getCourseType(description):\n courseType = \"\"\n if(\"course\" in description):\n courseType = \"Course\"\n elif(\"camp\" in description):\n courseType = \"Camp\"\n elif(\"program\" in description):\n courseType = \"Program\"\n else:\n courseType = \"\"\n #print(courseType)\n return courseType\n\n#Takes a string holding the program details(Grade level, cost, & refund deadline)\n#parse out Grade level and returns it as a string.\ndef getGradeLevel(program_details):\n grade_index = program_details.find(\"Grades:\")\n cost_index = program_details.find(\"Cost:\")\n return program_details[grade_index:cost_index]\n\n#Takes in a string that hold info on the grade level and returns the Minimum Age level. \ndef getMinimumAge(grade_levels):\n #Format: \"Grades: X-Y \"\n dash_index = grade_levels.find(\"–\")\n min_grade_level = int(grade_levels[8:dash_index])\n #print(min_grade_level)\n age = min_grade_level + 6\n #print(age)\n return age\n\n#Takes in a string that hold info on the grade level and returns the Maximum Age level. \ndef getMaximumAge(grade_levels):\n #Format: \"Grades: X-Y \"\n dash_index = grade_levels.find(\"–\")\n max_grade_level = int(grade_levels[dash_index+1:len(grade_levels)-1])\n #print(max_grade_level)\n age = max_grade_level + 6\n #print(age)\n return age\n\nif __name__ == \"__main__\":\n print('Program running...')\n base_url = 'https://www.summer-camp.uw.edu'\n csv = []\n\n r = requests.get(base_url + '/camps-courses/')\n soup = BeautifulSoup(r.text, 'html5lib')\n #Prints the Raw HTML code.\n #print(soup)\n\n course_tags = soup.find_all('a', attrs={'id':'linkCourse'})\n #print(len(course_tags))\n\n '''geting the URL from the tag and storing in list: course_urls.'''\n course_urls = []\n for tag in course_tags:\n course_url = base_url + tag['href'] #getting the link by adding the base and remaing url which is in URF\n course_urls.append(course_url)\n #Print check to see if the url is correct.\n #print(course_url)\n\n '''information that need to be obtained: CourseType, Description, Locations, MaximumAge, MinimumAge, Provider, SkillLevel, Title, Topic, & URL'''\n for url in course_urls:\n course_info = {}\n\n r = requests.get(url)\n soup = BeautifulSoup(r.text, 'html5lib')\n\n #1) URL for the course\n course_info['URL'] = url\n\n #2) Title for the course\n website_body_text = soup.find('div', attrs={'class':'uw-body-copy'})\n title = website_body_text.find('h1').getText()\n course_info['Title'] = title\n #print(title)\n\n #3) Topics - using the description to detemine the topics\n course_info['Topics'] = getTopics(soup.find('p').getText())\n\n #4) Skill level - initlizing it to just Beginner & Advanced.\n course_info['SkillLevel'] = \"Beginner-Advanced\"\n\n #5) Course Type\n course_info['CourseType'] = getCourseType(website_body_text.getText())\n\n #6) Age for the course (Min & Max Ages)\n '''The course bases the ages by grade levels, and doesn't have tag for just the grades.\n 1)taking the whole div tag as string\n 2)break it apart to get \"Grade: X - Y\" (x & y reprsents a grade) \n 3)Then take X & Y and change to actual ages.'''\n course_details_blocks = soup.find('div', attrs={'class':'course-setails-card'})\n #print(course_details_blocks.getText())\n grade_levels = getGradeLevel(course_details_blocks.getText())\n #print(grade_levels)\n\n course_info['MaximumAge'] = getMaximumAge(grade_levels)\n course_info['MinimumAge'] = getMinimumAge(grade_levels)\n\n #7) Description\n description = soup.find('p').getText()\n course_info['Description'] = description\n #print(description)\n\n #8) Course provider\n course_info['Provider'] = 'UW Summer Youth Programs'\n\n #9) Locations\n dates_and_time_section = website_body_text.find('div')\n tables = dates_and_time_section.find_all('table')\n locations = []\n for table in tables:\n location_section = table.find('td', attrs={'class':\"matrixBG matrixBorderBottom\"})\n location = location_section.find('a').getText()\n if(location not in locations):\n locations.append(location)\n #print(locations)\n course_info['Locations'] = locations\n\n csv.append(course_info)\n\n #--------------------------------------------------#\n #Converting list of dictionary into CSV\n import pandas as pd\n\n df = pd.DataFrame(csv)\n df.to_csv('csv\\\\course_UWSummerYouthPrograms.csv', index=False, encoding='utf-8')\n\n print('Complete!')\n\n\n","sub_path":"WebScraping/WebScrap_UWYouthSummerPrograms_WS.py","file_name":"WebScrap_UWYouthSummerPrograms_WS.py","file_ext":"py","file_size_in_byte":5362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"556064829","text":"import pandas as pd\nfrom imblearn.over_sampling import SMOTE\n\ndef get_data(file, oversampling):\n \n data = pd.read_csv(file)\n train= data[data['ORIGIN']=='train']\n test= data[data['ORIGIN']=='test']\n\n X_train = train.iloc[:,1:-1]\n X_test = test.iloc[:,1:-1]\n y_train = train.iloc[:,-1:]\n y_test = test.iloc[:,-1:]\n if oversampling== True:\n sm = SMOTE()\n X_train2, y_train2 = sm.fit_sample(X_train, y_train)\n if oversampling== False:\n X_train2 = X_train \n y_train2 = y_train\n print('Training Set Shape after oversampling: ', X_train2.shape, y_train2.shape)\n return X_train2, X_test, y_train2, y_test","sub_path":"modules/dataprep.py","file_name":"dataprep.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"178256512","text":"# -*- coding: utf-8 -*-\n#\n# Copyright © 2009- The Spyder Development Team\n# Copyright © 2014-2015 Colin Duquesnoy\n#\n# Licensed under the terms of the MIT License\n# (see LICENSE.txt for details)\n\n\"\"\"\n**QtPy** is a shim over the various Python Qt bindings. It is used to\nwrite Qt binding independent libraries or applications.\n\nYou can set the use of one specific binding by setting up the ``QT_API``\nenvironment variable. The default value for ``QT_API = 'pyqt5'``\n(not case sensitive). For each selected binding, there will be more three\nattempts if it is not found, following the most recent (Qt5) and most\nstable (PyQt) API. See below:\n\n* pyqt5: PyQt5, PySide2, PyQt4, PySide;\n* pyside2: PySide2, PyQt5, PyQt4, PySide;\n* pyqt4: PyQt4, PySide, PyQt5, PySide2;\n* pyside: PySide, PyQt4, PyQt5, PySide2.\n\nIf one of the APIs has already been imported, then that one will be used.\n(if the environment variable FORCE_QT_API is not set or set to false).\nIf you want to ensure that the set binding will be used, indepedent if\nany other binding was imported before, you can set ``FORCE_QT_API = True``\n\nThere are some globlas variables that can be used to reach information\nafter QtPy is imported that shows the current setup.\n\n- Binding set (bool): PYQT5, PYQT4, PYSIDE, PYSIDE2;\n- Specific binding version (str): PYQT_VERSION, PYSIDE_VERSION;\n- General binding name (str, import name): BINDING_NAME;\n- General binding version (str): BINDING_VERSION;\n- General generator name (str): GENERATOR_NAME;\n- General generator version (str): GENERATOR_VERSION;\n- General Qt version (str): QT_VERSION;\n- Composed API name (str): API_NAME = BINDING_NAME (BINDING_VERSION),\n GENERATOR_NAME (GENERATOR_VERSION),\n QT_VERSION\n\nThe priority when setting the Qt binding API is detailed below:\n\n1 QT_API is set but incorrectly, stop, error;\n\n2 No bindings are found installed, stop, error;\n\n3 Have NOT been already imported any Qt binding, independs on FORCE_QT_API:\n 3.1 QT_API is set correctly;\n 3.1.1 If binding is found, pass, no output;\n 3.1.2 If binding is NOT found, try another one (three more);\n 3.1.2.a If any is found (different from set), pass but warns;\n 3.3 QT_API is not set, use default, continue to 3.1.1, without warning;\n\n4 Have been already imported ONE Qt binding (not recommended):\n 4.1 QT_API is set correctly;\n 4.1.1 If the binding is is identical to QT_API, pass, no output,\n independs on FORCE_QT_API;\n 4.1.2 If the binding is different from QT_API;\n 4.1.2.a FORCE_QT_API is not set, use that imported binding,\n pass, but warns;\n 4.1.2.b FORCE_QT_API is set, stop, error;\n 4.2 QT_API is not set, use default, continue to 4.1.1, without warning;\n\n5 Have been already imported MORE than one Qt binding (highly unrecommended):\n 5.1 QT_API is set correctly;\n 5.1.1 If the binding is found in the imported bindings, pass,\n no output, independs on FORCE_QT_API;\n 5.1.2 If the binding is NOT found in the imported bindings;\n 5.1.2.a FORCE_QT_API is not set, try another one (three more);\n 5.1.2.a.i If any is found (different from set), pass\n but warns;\n 5.1.2.b FORCE_QT_API is set, stop, error;\n 5.2 QT_API is not set, use default, continue to 5.1.1, without warning.\n\nNote:\n Always preffer set the things (QT_API and FORCE_QT_API) explicit at\n the beggining of your code. Also, do all your imports using QtPy,\n avoiding using imports from PySide or PyQt directly.\n\nImportant:\n We always preffer to not break the code when something is not\n found, so we use ``warnings`` module to alert changes and show\n information that may be useful when developing with QtPy. Remember\n to set warnings to show messages.\n\nCaution:\n Importing more than one binding in the code could cause issues and\n errors that are unpredictable, for example, when comparing instance\n types, inserting widgets from one biding to another. So, it is not\n recommended you do that.\n\nWarning:\n If any Qt binding is imported (a different one) after QtPy import,\n issues and errors may occur and QtPy won't be able to help you\n with any warning, see Caution note.\n\n\nPyQt5\n=====\n\nFor PyQt5, you don't have to set anything as it will be used automatically::\n\n >>> from qtpy import QtGui, QtWidgets, QtCore\n >>> print(QtWidgets.QWidget)\n\nPySide2\n=======\n\nSet the QT_API environment variable to 'PySide2' before importing other\npackages::\n\n >>> import os\n >>> os.environ['QT_API'] = 'pyside2'\n >>> from qtpy import QtGui, QtWidgets, QtCore\n >>> print(QtWidgets.QWidget)\n\nPyQt4\n=====\n\nSet the ``QT_API`` environment variable to 'PyQt4' before importing any python\npackage::\n\n >>> import os\n >>> os.environ['QT_API'] = 'pyqt4'\n >>> from qtpy import QtGui, QtWidgets, QtCore\n >>> print(QtWidgets.QWidget)\n\nPySide\n======\n\nSet the QT_API environment variable to 'PySide' before importing other\npackages::\n\n >>> import os\n >>> os.environ['QT_API'] = 'pyside'\n >>> from qtpy import QtGui, QtWidgets, QtCore\n >>> print(QtWidgets.QWidget)\n\n\"\"\"\n\nimport logging\nimport os\nimport pkgutil\nimport platform\nimport sys\nimport warnings\nfrom distutils.version import LooseVersion\n\n# Version of QtPy\nfrom ._version import __version__\n\n_logger = logging.getLogger(__name__)\n\n\nclass PythonQtError(RuntimeError):\n \"\"\"Error raise if no bindings could be selected.\"\"\"\n pass\n\n\nclass PythonQtWarning(Warning):\n \"\"\"Warning if some features are not implemented in a binding.\"\"\"\n pass\n\n\ndef get_installed_bindings(import_list):\n \"\"\"Return a list of Qt bindings that are installed.\n\n Args:\n import_list (list): List of importing names to check, case sensitive.\n\n Returns:\n list: List of installed binding names.\n \"\"\"\n\n installed_bindings = []\n\n for imp_name in import_list:\n # Using 'try...import' or __import__ to TEST causes the\n # imp_name to be imported and accumulating on sys.modules\n # Using pkgutil.get_loader(), that works on both py2 and py3\n # it works as expected without the need of restore sys.path\n can_import = pkgutil.get_loader(imp_name)\n\n if can_import:\n installed_bindings.append(imp_name)\n\n return installed_bindings\n\n\ndef get_imported_bindings(import_list):\n \"\"\"Return a list of Qt bindings that are imported (sys.modules).\n\n Args:\n import_list (list): List of importing names to check, case sensitive.\n\n Returns:\n list: List of imported binding names.\n \"\"\"\n\n imported_bindings = []\n\n for imp_name in import_list:\n if imp_name in sys.modules:\n imported_bindings.append(imp_name)\n\n return imported_bindings\n\n\ndef get_binding_info(binding_name):\n \"\"\"Get binding, generator and Qt version information by the import system.\n\n All the tool names are given by their import names, so we get:\n\n - Bindings are PyQt4, PyQt5, PySide2, PySide;\n - Generators of code are the tools sip (for PyQt) and shiboken\n (for PySide).\n\n Note:\n - This function should be called after using the\n get_installed_bindings to avoid raise the PythonQtError\n by the not installed bindings. So, this error will only be\n raised if the specific import used here fails.\n - It must be rewrite to use pkgutil/importlib to check version\n numbers when after only py36 be used.\n\n Args:\n binding_name (str): Importing binding name, case sensitive. Bindings\n must be installed, otherwise it will raise an error.\n\n Raises:\n PythonQtError: If is not possible to import the selected binding,\n or if it is not recognized by the QtPy as a binding.\n\n Returns:\n tuple: Binding name, binding version, generator name,\n generator version and Qt version as strings.\n \"\"\"\n\n # Copy sys path to restore later\n sys_path = sys.path\n binding_version = generator_version = qt_version = generator_name = ''\n\n if binding_name == 'PyQt4':\n generator_name = 'sip'\n try:\n from PyQt4.Qt import PYQT_VERSION_STR as binding_version # analysis:ignore\n from PyQt4.Qt import QT_VERSION_STR as qt_version # analysis:ignore\n except ImportError:\n raise PythonQtError('\"PyQt4\" cannot be imported by QtPy.')\n try:\n from sip import SIP_VERSION_STR as generator_version # analysis:ignore\n except ImportError:\n raise PythonQtError('\"sip\" (PyQt4) cannot be imported by QtPy.')\n\n elif binding_name == 'PyQt5':\n generator_name = 'sip'\n try:\n from PyQt5.QtCore import PYQT_VERSION_STR as binding_version # analysis:ignore\n from PyQt5.QtCore import QT_VERSION_STR as qt_version # analysis:ignore\n except ImportError:\n raise PythonQtError('\"PyQt5\" cannot be imported by QtPy.')\n try:\n from sip import SIP_VERSION_STR as generator_version # analysis:ignore\n except ImportError:\n raise PythonQtError('\"sip\" (PyQt5) cannot be imported by QtPy.')\n\n elif binding_name == 'PySide':\n generator_name = 'shiboken'\n try:\n from PySide import __version__ as binding_version # analysis:ignore\n from PySide.QtCore import __version__ as qt_version # analysis:ignore\n except ImportError:\n raise PythonQtError('\"PySide\" cannot be imported by QtPy.')\n try:\n import shiboken # analysis:ignore\n except ImportError:\n # Unable to get this info using PySide, there is no __version__\n # After PySide2 we get from\n generator_version = 'Unknown'\n\n elif binding_name == 'PySide2':\n generator_name = 'shiboken2'\n try:\n from PySide2 import __version__ as binding_version # analysis:ignore\n from PySide2.QtCore import __version__ as qt_version # analysis:ignore\n except ImportError:\n raise PythonQtError('\"PySide2\" cannot be imported by QtPy.')\n try:\n from shiboken2 import __version__ as generator_version # analysis:ignore\n except ImportError:\n raise PythonQtError('\"shiboken2\" (PySide2) cannot be imported by QtPy.')\n else:\n msg = '{} is not recognized as a binding by QtPy.'.format(binding_name)\n raise PythonQtError(msg)\n\n # Restore sys path\n sys.path = sys_path\n\n return (binding_name, binding_version,\n generator_name, generator_version,\n qt_version)\n\n\n# Qt API environment variable name\nQT_API = 'QT_API'\n\n# When `FORCE_QT_API` is set, we disregard\n# any previously imported python bindings\nFORCE_QT_API = 'FORCE_QT_API'\n\n# Default/Preferrable API, must be one of api_names keys\nDEFAULT_API = 'pyqt5'\n\n# All false/none/empty because they were not imported yet\nPYQT5 = PYQT4 = PYSIDE = PYSIDE2 = False\nPYQT_VERSION = PYSIDE_VERSION = ''\nis_old_pyqt = is_pyqt46 = False\n\n# Keep for compatibility with older versions\nAPI = API_NAME = API_VERSION = ''\n\n# Respective to Qt C++ compiled version\nQT_VERSION = ''\n\n# Binding name and version such as PySide2, PyQt5\nBINDING_NAME = BINDING_VERSION = ''\n\n# Generator name and version such as sip and shiboken\nGENERATOR_NAME = GENERATOR_VERSION = ''\n\n# Keys: names of the expected Qt API (internal names)\n# Values: ordered list of importing names based on its key\n# The sequence preserves the most recent (Qt5) and stable (PyQt)\n# TODO: If 'pyside', keep chosen order as PySide2, PyQt5 or use PyQt5, PySide2?\napi_names = {'pyqt4': ['PyQt4', 'PySide', 'PyQt5', 'PySide2'],\n 'pyqt5': ['PyQt5', 'PySide2', 'PyQt4', 'PySide'],\n 'pyside': ['PySide', 'PyQt4', 'PySide2', 'PyQt5'],\n 'pyside2': ['PySide2', 'PyQt5', 'PySide', 'PyQt4']}\n\n# Other keys for the same Qt API that can be used for compatibility\n# pyqt4 -> pyqode.qt original name, pyqt -> name used in IPython.qt\napi_names['pyqt'] = api_names['pyqt4']\n\n# Detecting if a api/force was specified by the user, before setting default\napi_specified = QT_API in os.environ\nforce_specified = FORCE_QT_API in os.environ\n\n# Setting a default value for QT_API\nos.environ.setdefault(QT_API, DEFAULT_API)\n\n# Get the value from environment (or default if not set)\nenv_api = os.environ[QT_API].lower()\n\n# If QT_API exists but it is empty, use default and unset api_specified\nif api_specified and not env_api:\n api_specified = False\n env_api = DEFAULT_API\n\n_logger.debug('API is specified: %s FORCE is specified: %s' % (api_specified,\n force_specified))\n\n# Check if env_api was correctly set with environment variable\nif env_api not in api_names.keys():\n msg = 'Qt binding \"{}\" is unknown. Use one from these: {}.'\n msg = msg.format(env_api, api_names[DEFAULT_API])\n raise PythonQtError(msg)\n\n# NOW GET A LIST OF TRIALS (SET + 3 MORE) BASED ON SET VALUE AND API_NAMES\n\n# The preference sequence is given by env_api\nenv_api_list = api_names[env_api]\n\n# Initial value is get from environment first trial, index 0 (set value)\ninitial_api = env_api_list[0]\n\n# Check if Qt bindings have been already imported in 'sys.modules'\nimp_api_list = get_imported_bindings(api_names[env_api])\n_logger.info('Already imported bindings: {}'.format(imp_api_list))\n\n# Importing order for binding trial if they are not found\napi_trial_list = env_api_list\n\nif imp_api_list and not force_specified:\n api_trial_list = imp_api_list\n\n# Refined import order with installed ones\napi_trial_avaliable_list = get_installed_bindings(api_trial_list)\n_logger.info('Installed bindings: {}'.format(api_trial_avaliable_list))\n\n# Check if something is installed\nif not api_trial_avaliable_list:\n msg = 'No Qt binding could be found. Install at least one of these: {}.'\n msg = msg.format(api_names[DEFAULT_API])\n raise PythonQtError(msg)\n\n# If more than one Qt binding is imported but none is specified\nif len(imp_api_list) >= 2 and not force_specified:\n msg = 'There is more than one imported Qt binding: {}. It is impossible '\n 'to know which one is to import. You must specify QT_API and '\n 'FORCE_QT_API if using both is your desire. We warn that this mix '\n 'could cause inexpected results.'\n msg = msg.format(imp_api_list)\n raise PythonQtError(msg)\n\n# In most cases, it will execute only the first item as expected\n# because we already refined the list of installed bindings\n# Only if any importing problem occurs it will try other ones\nfor binding_name in api_trial_avaliable_list:\n\n _logger.debug('Trying to use: {}'.format(binding_name))\n\n try:\n info = get_binding_info(binding_name)\n\n except PythonQtError as er:\n msg = 'The binding \"{}\" is installed but cannot be used. '\n msg += 'Check the original error message: {}.'\n msg = msg.format(binding_name, str(er))\n warnings.warn(msg, RuntimeWarning)\n\n else:\n # Set values for general configuration\n (BINDING_NAME, BINDING_VERSION, GENERATOR_NAME,\n GENERATOR_VERSION, QT_VERSION) = info\n\n _logger.info('Binding: {} v{}'.format(BINDING_NAME, BINDING_VERSION))\n _logger.info('Generator: {} v{}'.format(GENERATOR_NAME, GENERATOR_VERSION))\n _logger.info('Qt: v{}'.format(QT_VERSION))\n\n if binding_name == 'PyQt4':\n # Set values for specific binding\n PYQT4 = True\n PYQT_VERSION = BINDING_VERSION\n\n versions = ('4.4', '4.5', '4.6', '4.7')\n is_old_pyqt = PYQT_VERSION.startswith(versions)\n is_pyqt46 = PYQT_VERSION.startswith('4.6')\n\n try:\n import sip\n except ImportError:\n msg = '\"sip\" (PyQt4) cannot be imported in QtPy.'\n raise PythonQtError(msg)\n else:\n try:\n sip.setapi('QString', 2)\n sip.setapi('QVariant', 2)\n sip.setapi('QDate', 2)\n sip.setapi('QDateTime', 2)\n sip.setapi('QTextStream', 2)\n sip.setapi('QTime', 2)\n sip.setapi('QUrl', 2)\n except (AttributeError, ValueError):\n # PyQt < v4.6\n pass\n\n elif binding_name == 'PyQt5':\n # Set values for the specific binding\n PYQT5 = True\n PYQT_VERSION = BINDING_VERSION\n\n if sys.platform == 'darwin':\n\n macos_version = LooseVersion(platform.mac_ver()[0])\n\n if macos_version < LooseVersion('10.10'):\n if LooseVersion(QT_VERSION) >= LooseVersion('5.9'):\n msg = \"Qt 5.9 or higher only works in macOS 10.10 \"\n \"or higher. Your program will fail in this \"\n \"system.\"\n raise PythonQtError(msg)\n\n elif macos_version < LooseVersion('10.11'):\n if LooseVersion(QT_VERSION) >= LooseVersion('5.11'):\n msg = \"Qt 5.11 or higher only works in macOS 10.11 \"\n \"or higher. Your program will fail in this \"\n \"system.\"\n raise PythonQtError(msg)\n\n del macos_version\n\n elif binding_name == 'PySide':\n # Set values for the specific binding\n PYSIDE = True\n PYSIDE_VERSION = BINDING_VERSION\n\n elif binding_name == 'PySide2':\n # Set values for the specific binding\n PYSIDE2 = True\n PYSIDE_VERSION = BINDING_VERSION\n\n if sys.platform == 'darwin':\n macos_version = LooseVersion(platform.mac_ver()[0])\n if macos_version < LooseVersion('10.11'):\n if LooseVersion(QT_VERSION) >= LooseVersion('5.11'):\n msg = \"Qt 5.11 or higher only works in macOS 10.11 \"\n \"or higher. Your program will fail in this \"\n \"system.\"\n raise PythonQtError(msg)\n del macos_version\n break\n\n_logger.debug('Keys: PYQT5={}, PYQT4={}, PYSIDE={}, PYSIDE2={}'.format(PYQT5,\n PYQT4,\n PYSIDE2,\n PYSIDE))\n\n# BINDING_NAME and initial_api are importing names, case sensitive\nif BINDING_NAME != initial_api and api_specified:\n # If the code is using QtPy is not supposed do directly import Qt api's,\n # so a warning is sent to check consistence\n if imp_api_list and not force_specified:\n msg = 'Selected binding \"{}\" could not be set because \"{}\" has '\n msg += 'already been imported. Check your code for consistence.'\n msg = msg.format(initial_api, BINDING_NAME)\n warnings.warn(msg, RuntimeWarning)\n # If a correct API name is passed to QT_API and it cannot be found,\n # switches to another and informs through the warning\n else:\n msg = 'Selected binding \"{}\" could not be used. Using \"{}\".'\n msg = msg.format(initial_api, BINDING_NAME)\n warnings.warn(msg, RuntimeWarning)\n\n# Set the environment variable to the current used API after all tests\nos.environ['QT_API'] = API\n\nAPI_VERSION = BINDING_VERSION\nAPI = BINDING_VERSION.lower()\n\nAPI_NAME = '{} v{}, {} v{}, Qt v{}'.format(BINDING_NAME,\n BINDING_VERSION,\n GENERATOR_NAME,\n GENERATOR_VERSION,\n QT_VERSION)\n\n_logger.info('Using API_NAME: {}'.format(API_NAME))\n","sub_path":"qtpy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":19974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"639474581","text":"import visa\r\nimport time\r\nimport warnings \r\n\r\nclass keithley2026:\r\n def __init__(self):\r\n instlist=visa.ResourceManager()\r\n print(instlist.list_resources())\r\n self.kei026=instlist.open_resource(\"GPIB1::4::INSTR\")\r\n self.timedelay=1\r\n\r\n def testIO(self):\r\n message=self.kei026.ask('*IDN?')\r\n print(message)\r\n \r\n def set_voltage(self,vol):\r\n if vol > 5.0:\r\n warnings.warn(\"Warning High Voltage!!!!\")\r\n self.kei026.write(\"smua.source.limiti=5E-7\")\r\n self.kei026.write(\"smua.source.func=smua.OUTPUT_DCVOLTS\")\r\n vols=self.show_voltage()\r\n self.sweep(vols,vol,0.1)\r\n vols=self.show_voltage()\r\n return vols\r\n\r\n def show_voltage(self):\r\n self.kei026.write(\"voltagea=smua.measure.v()\")\r\n voltage=self.kei026.ask(\"printnumber(voltagea)\")\r\n print(\"voltage [V]: \" + str(voltage))\r\n return float(str(voltage))\r\n\r\n def sweep(self, vols, vole, step):\r\n if vols < vole:\r\n self.sweep_forward(vols,vole,step)\r\n else:\r\n self.sweep_backward(vols,vole,step) \r\n\r\n def sweep_forward(self, vols, vole, step):\r\n # Conveter from V to mV\r\n mvols=vols*1000\r\n mvole=vole*1000\r\n mstep=step*1000\r\n \r\n for mvol in range(int(mvols),int(mvole),int(mstep)):\r\n vol=mvol/1000 # mV -> V\r\n self.kei026.write(\"smua.source.levelv=\"+str(vol))\r\n self.kei026.write(\"smua.source.limiti=5E-7\")\r\n self.show_voltage()\r\n time.sleep(self.timedelay)\r\n self.kei026.write(\"smua.source.levelv=\"+str(vole))\r\n self.show_voltage()\r\n\r\n def sweep_backward(self, vols, vole, step):\r\n # Conveter from V to mV\r\n mvols=vols*1000\r\n mvole=vole*1000\r\n mstep=step*1000\r\n \r\n for mvol in range(int(mvols),int(mvole), -int(mstep)):\r\n vol=mvol/1000 # mV -> V\r\n self.kei026.write(\"smua.source.levelv=\"+str(vol))\r\n self.kei026.write(\"smua.source.limiti=5E-7\")\r\n self.show_voltage()\r\n time.sleep(self.timedelay)\r\n self.kei026.write(\"smua.source.levelv=\"+str(vole))\r\n self.show_voltage()\r\n \r\n def display_current(self):\r\n self.kei026.write(\"display.smua.measure.func=display.MEASURE_DCAMPS\")\r\n self.kei026.write(\"smua.measure.rangei=1E-6\")\r\n self.kei026.write(\"smua.measure.rel.enablei=1\")\r\n self.kei026.write(\"currenta=smua.measure.i()\")\r\n current=self.kei026.ask(\"printnumber(currenta)\")\r\n print(\"current [A]: \" + str(current))\r\n \r\n time.sleep(self.timedelay)\r\n self.kei026.write(\"currenta=smua.measure.i()\")\r\n current=self.kei026.ask(\"printnumber(currenta)\")\r\n return float(str(current))\r\n\r\n def output_on(self):\r\n self.kei026.write(\"smua.source.output=smua.OUTPUT_ON\")\r\n print(\"On\")\r\n\r\n def output_off(self):\r\n self.kei026.write(\"smua.source.output=smua.OUTPUT_OFF\")\r\n print(\"Off\")\r\n\r\n\r\nif __name__==\"__main__\":\r\n kei026=keithley2026()\r\n kei026.output_on()\r\n kei026.set_voltage(0.1)\r\n current=kei026.display_current()\r\n print(current)\r\n #kei026.output_off()\r\n\r\n","sub_path":"powercontrol/Kei2026BiasControl.py","file_name":"Kei2026BiasControl.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558882456","text":"\"\"\"\n Evaluation-related codes are modified from\n https://github.com/hughw19/NOCS_CVPR2019\n\"\"\"\nimport logging\nimport os\nimport math\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport _pickle as cPickle\nfrom tqdm import tqdm\n\n\ndef setup_logger(logger_name, log_file, level=logging.INFO):\n logger = logging.getLogger(logger_name)\n formatter = logging.Formatter('%(asctime)s : %(message)s')\n fileHandler = logging.FileHandler(log_file, mode='a')\n fileHandler.setFormatter(formatter)\n logger.setLevel(level)\n logger.addHandler(fileHandler)\n streamHandler = logging.StreamHandler()\n streamHandler.setFormatter(formatter)\n logger.addHandler(streamHandler)\n return logger\n\n\ndef load_obj(path_to_file):\n \"\"\" Load obj file.\n\n Args:\n path_to_file: path\n\n Returns:\n vertices: ndarray\n faces: ndarray, index of triangle vertices\n\n \"\"\"\n vertices = []\n faces = []\n with open(path_to_file, 'r') as f:\n for line in f:\n if line[:2] == 'v ':\n vertex = line[2:].strip().split(' ')\n vertex = [float(xyz) for xyz in vertex]\n vertices.append(vertex)\n elif line[0] == 'f':\n face = line[1:].replace('//', '/').strip().split(' ')\n face = [int(idx.split('/')[0])-1 for idx in face]\n faces.append(face)\n else:\n continue\n vertices = np.asarray(vertices)\n faces = np.asarray(faces)\n return vertices, faces\n\n\ndef create_sphere():\n # 642 verts, 1280 faces,\n verts, faces = load_obj('assets/sphere_mesh_template.obj')\n return verts, faces\n\n\ndef random_point(face_vertices):\n \"\"\" Sampling point using Barycentric coordiante.\n\n \"\"\"\n r1, r2 = np.random.random(2)\n sqrt_r1 = np.sqrt(r1)\n point = (1 - sqrt_r1) * face_vertices[0, :] + \\\n sqrt_r1 * (1 - r2) * face_vertices[1, :] + \\\n sqrt_r1 * r2 * face_vertices[2, :]\n\n return point\n\n\ndef pairwise_distance(A, B):\n \"\"\" Compute pairwise distance of two point clouds.point\n\n Args:\n A: n x 3 numpy array\n B: m x 3 numpy array\n\n Return:\n C: n x m numpy array\n\n \"\"\"\n diff = A[:, :, None] - B[:, :, None].T\n C = np.sqrt(np.sum(diff**2, axis=1))\n\n return C\n\n\ndef uniform_sample(vertices, faces, n_samples, with_normal=False):\n \"\"\" Sampling points according to the area of mesh surface.\n\n \"\"\"\n sampled_points = np.zeros((n_samples, 3), dtype=float)\n normals = np.zeros((n_samples, 3), dtype=float)\n faces = vertices[faces]\n vec_cross = np.cross(faces[:, 1, :] - faces[:, 0, :],\n faces[:, 2, :] - faces[:, 0, :])\n face_area = 0.5 * np.linalg.norm(vec_cross, axis=1)\n cum_area = np.cumsum(face_area)\n for i in range(n_samples):\n face_id = np.searchsorted(cum_area, np.random.random() * cum_area[-1])\n sampled_points[i] = random_point(faces[face_id, :, :])\n normals[i] = vec_cross[face_id]\n normals = normals / np.linalg.norm(normals, axis=1, keepdims=True)\n if with_normal:\n sampled_points = np.concatenate((sampled_points, normals), axis=1)\n return sampled_points\n\n\ndef farthest_point_sampling(points, n_samples):\n \"\"\" Farthest point sampling.\n\n \"\"\"\n selected_pts = np.zeros((n_samples,), dtype=int)\n dist_mat = pairwise_distance(points, points)\n # start from first point\n pt_idx = 0\n dist_to_set = dist_mat[:, pt_idx]\n for i in range(n_samples):\n selected_pts[i] = pt_idx\n dist_to_set = np.minimum(dist_to_set, dist_mat[:, pt_idx])\n pt_idx = np.argmax(dist_to_set)\n return selected_pts\n\n\ndef sample_points_from_mesh(path, n_pts, with_normal=False, fps=False, ratio=2):\n \"\"\" Uniformly sampling points from mesh model.\n\n Args:\n path: path to OBJ file.\n n_pts: int, number of points being sampled.\n with_normal: return points with normal, approximated by mesh triangle normal\n fps: whether to use fps for post-processing, default False.\n ratio: int, if use fps, sample ratio*n_pts first, then use fps to sample final output.\n\n Returns:\n points: n_pts x 3, n_pts x 6 if with_normal = True\n\n \"\"\"\n vertices, faces = load_obj(path)\n if fps:\n points = uniform_sample(vertices, faces, ratio*n_pts, with_normal)\n pts_idx = farthest_point_sampling(points[:, :3], n_pts)\n points = points[pts_idx]\n else:\n points = uniform_sample(vertices, faces, n_pts, with_normal)\n return points\n\n\ndef load_depth(img_path):\n \"\"\" Load depth image from img_path. \"\"\"\n depth_path = img_path + '_depth.png'\n depth = cv2.imread(depth_path, -1)\n if len(depth.shape) == 3:\n # This is encoded depth image, let's convert\n # NOTE: RGB is actually BGR in opencv\n depth16 = depth[:, :, 1]*256 + depth[:, :, 2]\n depth16 = np.where(depth16==32001, 0, depth16)\n depth16 = depth16.astype(np.uint16)\n elif len(depth.shape) == 2 and depth.dtype == 'uint16':\n depth16 = depth\n else:\n assert False, '[ Error ]: Unsupported depth type.'\n return depth16\n\n\ndef get_bbox(bbox):\n \"\"\" Compute square image crop window. \"\"\"\n y1, x1, y2, x2 = bbox\n img_width = 480\n img_length = 640\n window_size = (max(y2-y1, x2-x1) // 40 + 1) * 40\n window_size = min(window_size, 440)\n center = [(y1 + y2) // 2, (x1 + x2) // 2]\n rmin = center[0] - int(window_size / 2)\n rmax = center[0] + int(window_size / 2)\n cmin = center[1] - int(window_size / 2)\n cmax = center[1] + int(window_size / 2)\n if rmin < 0:\n delt = -rmin\n rmin = 0\n rmax += delt\n if cmin < 0:\n delt = -cmin\n cmin = 0\n cmax += delt\n if rmax > img_width:\n delt = rmax - img_width\n rmax = img_width\n rmin -= delt\n if cmax > img_length:\n delt = cmax - img_length\n cmax = img_length\n cmin -= delt\n return rmin, rmax, cmin, cmax\n\n\ndef compute_sRT_errors(sRT1, sRT2):\n \"\"\"\n Args:\n sRT1: [4, 4]. homogeneous affine transformation\n sRT2: [4, 4]. homogeneous affine transformation\n\n Returns:\n R_error: angle difference in degree,\n T_error: Euclidean distance\n IoU: relative scale error\n\n \"\"\"\n try:\n assert np.array_equal(sRT1[3, :], sRT2[3, :])\n assert np.array_equal(sRT1[3, :], np.array([0, 0, 0, 1]))\n except AssertionError:\n print(sRT1[3, :], sRT2[3, :])\n\n s1 = np.cbrt(np.linalg.det(sRT1[:3, :3]))\n R1 = sRT1[:3, :3] / s1\n T1 = sRT1[:3, 3]\n s2 = np.cbrt(np.linalg.det(sRT2[:3, :3]))\n R2 = sRT2[:3, :3] / s2\n T2 = sRT2[:3, 3]\n R12 = R1 @ R2.transpose()\n R_error = np.arccos(np.clip((np.trace(R12)-1)/2, -1.0, 1.0)) * 180 / np.pi\n T_error = np.linalg.norm(T1 - T2)\n IoU = np.abs(s1 - s2) / s2\n\n return R_error, T_error, IoU\n\n\n############################################################\n# Evaluation\n############################################################\n\ndef get_3d_bbox(size, shift=0):\n \"\"\"\n Args:\n size: [3] or scalar\n shift: [3] or scalar\n Returns:\n bbox_3d: [3, N]\n\n \"\"\"\n bbox_3d = np.array([[+size[0] / 2, +size[1] / 2, +size[2] / 2],\n [+size[0] / 2, +size[1] / 2, -size[2] / 2],\n [-size[0] / 2, +size[1] / 2, +size[2] / 2],\n [-size[0] / 2, +size[1] / 2, -size[2] / 2],\n [+size[0] / 2, -size[1] / 2, +size[2] / 2],\n [+size[0] / 2, -size[1] / 2, -size[2] / 2],\n [-size[0] / 2, -size[1] / 2, +size[2] / 2],\n [-size[0] / 2, -size[1] / 2, -size[2] / 2]]) + shift\n bbox_3d = bbox_3d.transpose()\n return bbox_3d\n\n\ndef transform_coordinates_3d(coordinates, sRT):\n \"\"\"\n Args:\n coordinates: [3, N]\n sRT: [4, 4]\n\n Returns:\n new_coordinates: [3, N]\n\n \"\"\"\n assert coordinates.shape[0] == 3\n coordinates = np.vstack([coordinates, np.ones((1, coordinates.shape[1]), dtype=np.float32)])\n new_coordinates = sRT @ coordinates\n new_coordinates = new_coordinates[:3, :] / new_coordinates[3, :]\n return new_coordinates\n\n\ndef compute_3d_IoU(sRT_1, sRT_2, size_1, size_2, class_name_1, class_name_2, handle_visibility):\n \"\"\" Computes IoU overlaps between two 3D bboxes. \"\"\"\n def asymmetric_3d_iou(sRT_1, sRT_2, size_1, size_2):\n noc_cube_1 = get_3d_bbox(size_1, 0)\n bbox_3d_1 = transform_coordinates_3d(noc_cube_1, sRT_1)\n noc_cube_2 = get_3d_bbox(size_2, 0)\n bbox_3d_2 = transform_coordinates_3d(noc_cube_2, sRT_2)\n\n bbox_1_max = np.amax(bbox_3d_1, axis=0)\n bbox_1_min = np.amin(bbox_3d_1, axis=0)\n bbox_2_max = np.amax(bbox_3d_2, axis=0)\n bbox_2_min = np.amin(bbox_3d_2, axis=0)\n\n overlap_min = np.maximum(bbox_1_min, bbox_2_min)\n overlap_max = np.minimum(bbox_1_max, bbox_2_max)\n\n # intersections and union\n if np.amin(overlap_max - overlap_min) < 0:\n intersections = 0\n else:\n intersections = np.prod(overlap_max - overlap_min)\n union = np.prod(bbox_1_max - bbox_1_min) + np.prod(bbox_2_max - bbox_2_min) - intersections\n overlaps = intersections / union\n return overlaps\n\n if sRT_1 is None or sRT_2 is None:\n return -1\n\n if (class_name_1 in ['bottle', 'bowl', 'can'] and class_name_1 == class_name_2) or \\\n (class_name_1 == 'mug' and class_name_1 == class_name_2 and handle_visibility==0):\n def y_rotation_matrix(theta):\n return np.array([[ np.cos(theta), 0, np.sin(theta), 0],\n [ 0, 1, 0, 0],\n [-np.sin(theta), 0, np.cos(theta), 0],\n [ 0, 0, 0, 1]])\n n = 20\n max_iou = 0\n for i in range(n):\n rotated_RT_1 = sRT_1 @ y_rotation_matrix(2 * math.pi * i / float(n))\n max_iou = max(max_iou, asymmetric_3d_iou(rotated_RT_1, sRT_2, size_1, size_2))\n else:\n max_iou = asymmetric_3d_iou(sRT_1, sRT_2, size_1, size_2)\n\n return max_iou\n\n\ndef compute_IoU_matches(gt_class_ids, gt_sRT, gt_size, gt_handle_visibility,\n pred_class_ids, pred_sRT, pred_size, pred_scores,\n synset_names, iou_3d_thresholds, score_threshold=0):\n \"\"\" Find matches between NOCS prediction and ground truth instances.\n\n Args:\n size: 3D bounding box size\n bboxes: 2D bounding boxes\n\n Returns:\n gt_matches: 2-D array. For each GT box it has the index of the matched predicted box.\n pred_matches: 2-D array. For each predicted box, it has the index of the matched ground truth box.\n overlaps: IoU overlaps.\n indices:\n\n \"\"\"\n num_pred = len(pred_class_ids)\n num_gt = len(gt_class_ids)\n indices = np.zeros(0)\n if num_pred:\n # Sort predictions by score from high to low\n indices = np.argsort(pred_scores)[::-1]\n pred_class_ids = pred_class_ids[indices].copy()\n pred_size = pred_size[indices].copy()\n pred_sRT = pred_sRT[indices].copy()\n # compute IoU overlaps [pred_bboxs gt_bboxs]\n overlaps = np.zeros((num_pred, num_gt), dtype=np.float32)\n for i in range(num_pred):\n for j in range(num_gt):\n overlaps[i, j] = compute_3d_IoU(pred_sRT[i], gt_sRT[j], pred_size[i, :], gt_size[j],\n synset_names[pred_class_ids[i]], synset_names[gt_class_ids[j]], gt_handle_visibility[j])\n # loop through predictions and find matching ground truth boxes\n num_iou_3d_thres = len(iou_3d_thresholds)\n pred_matches = -1 * np.ones([num_iou_3d_thres, num_pred])\n gt_matches = -1 * np.ones([num_iou_3d_thres, num_gt])\n for s, iou_thres in enumerate(iou_3d_thresholds):\n for i in range(indices.shape[0]):\n # Find best matching ground truth box\n # 1. Sort matches by score\n sorted_ixs = np.argsort(overlaps[i])[::-1]\n # 2. Remove low scores\n low_score_idx = np.where(overlaps[i, sorted_ixs] < score_threshold)[0]\n if low_score_idx.size > 0:\n sorted_ixs = sorted_ixs[:low_score_idx[0]]\n # 3. Find the match\n for j in sorted_ixs:\n # If ground truth box is already matched, go to next one\n if gt_matches[s, j] > -1:\n continue\n # If we reach IoU smaller than the threshold, end the loop\n iou = overlaps[i, j]\n if iou < iou_thres:\n break\n # Do we have a match?\n if not pred_class_ids[i] == gt_class_ids[j]:\n continue\n if iou > iou_thres:\n gt_matches[s, j] = i\n pred_matches[s, i] = j\n break\n return gt_matches, pred_matches, overlaps, indices\n\n\ndef compute_RT_errors(sRT_1, sRT_2, class_id, handle_visibility, synset_names):\n \"\"\"\n Args:\n sRT_1: [4, 4]. homogeneous affine transformation\n sRT_2: [4, 4]. homogeneous affine transformation\n\n Returns:\n theta: angle difference of R in degree\n shift: l2 difference of T in centimeter\n \"\"\"\n # make sure the last row is [0, 0, 0, 1]\n if sRT_1 is None or sRT_2 is None:\n return -1\n try:\n assert np.array_equal(sRT_1[3, :], sRT_2[3, :])\n assert np.array_equal(sRT_1[3, :], np.array([0, 0, 0, 1]))\n except AssertionError:\n print(sRT_1[3, :], sRT_2[3, :])\n exit()\n\n R1 = sRT_1[:3, :3] / np.cbrt(np.linalg.det(sRT_1[:3, :3]))\n T1 = sRT_1[:3, 3]\n R2 = sRT_2[:3, :3] / np.cbrt(np.linalg.det(sRT_2[:3, :3]))\n T2 = sRT_2[:3, 3]\n # symmetric when rotating around y-axis\n if synset_names[class_id] in ['bottle', 'can', 'bowl'] or \\\n (synset_names[class_id] == 'mug' and handle_visibility == 0):\n y = np.array([0, 1, 0])\n y1 = R1 @ y\n y2 = R2 @ y\n cos_theta = y1.dot(y2) / (np.linalg.norm(y1) * np.linalg.norm(y2))\n else:\n R = R1 @ R2.transpose()\n cos_theta = (np.trace(R) - 1) / 2\n\n theta = np.arccos(np.clip(cos_theta, -1.0, 1.0)) * 180 / np.pi\n shift = np.linalg.norm(T1 - T2) * 100\n result = np.array([theta, shift])\n\n return result\n\n\ndef compute_RT_overlaps(gt_class_ids, gt_sRT, gt_handle_visibility, pred_class_ids, pred_sRT, synset_names):\n \"\"\" Finds overlaps between prediction and ground truth instances.\n\n Returns:\n overlaps:\n\n \"\"\"\n num_pred = len(pred_class_ids)\n num_gt = len(gt_class_ids)\n overlaps = np.zeros((num_pred, num_gt, 2))\n\n for i in range(num_pred):\n for j in range(num_gt):\n overlaps[i, j, :] = compute_RT_errors(pred_sRT[i], gt_sRT[j], gt_class_ids[j],\n gt_handle_visibility[j], synset_names)\n return overlaps\n\n\ndef compute_RT_matches(overlaps, pred_class_ids, gt_class_ids, degree_thres_list, shift_thres_list):\n num_degree_thres = len(degree_thres_list)\n num_shift_thres = len(shift_thres_list)\n num_pred = len(pred_class_ids)\n num_gt = len(gt_class_ids)\n\n pred_matches = -1 * np.ones((num_degree_thres, num_shift_thres, num_pred))\n gt_matches = -1 * np.ones((num_degree_thres, num_shift_thres, num_gt))\n\n if num_pred == 0 or num_gt == 0:\n return gt_matches, pred_matches\n\n assert num_pred == overlaps.shape[0]\n assert num_gt == overlaps.shape[1]\n assert overlaps.shape[2] == 2\n\n for d, degree_thres in enumerate(degree_thres_list):\n for s, shift_thres in enumerate(shift_thres_list):\n for i in range(num_pred):\n # Find best matching ground truth box\n # 1. Sort matches by scores from low to high\n sum_degree_shift = np.sum(overlaps[i, :, :], axis=-1)\n sorted_ixs = np.argsort(sum_degree_shift)\n # 2. Find the match\n for j in sorted_ixs:\n # If ground truth box is already matched, go to next one\n if gt_matches[d, s, j] > -1 or pred_class_ids[i] != gt_class_ids[j]:\n continue\n # If we reach IoU smaller than the threshold, end the loop\n if overlaps[i, j, 0] > degree_thres or overlaps[i, j, 1] > shift_thres:\n continue\n gt_matches[d, s, j] = i\n pred_matches[d, s, i] = j\n break\n\n return gt_matches, pred_matches\n\n\ndef compute_ap_and_acc(pred_matches, pred_scores, gt_matches):\n # sort the scores from high to low\n assert pred_matches.shape[0] == pred_scores.shape[0]\n score_indices = np.argsort(pred_scores)[::-1]\n # pred_scores = pred_scores[score_indices]\n pred_matches = pred_matches[score_indices]\n precisions = np.cumsum(pred_matches > -1) / (np.arange(len(pred_matches)) + 1)\n recalls = np.cumsum(pred_matches > -1).astype(np.float32) / len(gt_matches)\n # Pad with start and end values to simplify the math\n precisions = np.concatenate([[0], precisions, [0]])\n recalls = np.concatenate([[0], recalls, [1]])\n # Ensure precision values decrease but don't increase. This way, the\n # precision value at each recall threshold is the maximum it can be\n # for all following recall thresholds, as specified by the VOC paper.\n for i in range(len(precisions) - 2, -1, -1):\n precisions[i] = np.maximum(precisions[i], precisions[i + 1])\n # compute mean AP over recall range\n indices = np.where(recalls[:-1] != recalls[1:])[0] + 1\n ap = np.sum((recalls[indices] - recalls[indices - 1]) * precisions[indices])\n # accuracy\n acc = np.sum(pred_matches > -1) / len(pred_matches)\n\n return ap, acc\n\n\ndef compute_mAP(pred_results, out_dir, degree_thresholds=[180], shift_thresholds=[100],\n iou_3d_thresholds=[0.1], iou_pose_thres=0.1, use_matches_for_pose=False):\n \"\"\" Compute mean Average Precision.\n\n Returns:\n iou_aps:\n pose_aps:\n iou_acc:\n pose_acc:\n\n \"\"\"\n synset_names = ['BG', 'bottle', 'bowl', 'camera', 'can', 'laptop', 'mug']\n num_classes = len(synset_names)\n degree_thres_list = list(degree_thresholds) + [360]\n num_degree_thres = len(degree_thres_list)\n shift_thres_list = list(shift_thresholds) + [100]\n num_shift_thres = len(shift_thres_list)\n iou_thres_list = list(iou_3d_thresholds)\n num_iou_thres = len(iou_thres_list)\n\n if use_matches_for_pose:\n assert iou_pose_thres in iou_thres_list\n\n # pre-allocate more than enough memory\n iou_aps = np.zeros((num_classes + 1, num_iou_thres))\n iou_acc = np.zeros((num_classes + 1, num_iou_thres))\n iou_pred_matches_all = [np.zeros((num_iou_thres, 30000)) for _ in range(num_classes)]\n iou_pred_scores_all = [np.zeros((num_iou_thres, 30000)) for _ in range(num_classes)]\n iou_gt_matches_all = [np.zeros((num_iou_thres, 30000)) for _ in range(num_classes)]\n iou_pred_count = [0 for _ in range(num_classes)]\n iou_gt_count = [0 for _ in range(num_classes)]\n\n pose_aps = np.zeros((num_classes + 1, num_degree_thres, num_shift_thres))\n pose_acc = np.zeros((num_classes + 1, num_degree_thres, num_shift_thres))\n pose_pred_matches_all = [np.zeros((num_degree_thres, num_shift_thres, 30000)) for _ in range(num_classes)]\n pose_pred_scores_all = [np.zeros((num_degree_thres, num_shift_thres, 30000)) for _ in range(num_classes)]\n pose_gt_matches_all = [np.zeros((num_degree_thres, num_shift_thres, 30000)) for _ in range(num_classes)]\n pose_pred_count = [0 for _ in range(num_classes)]\n pose_gt_count = [0 for _ in range(num_classes)]\n\n # loop over results to gather pred matches and gt matches for iou and pose metrics\n progress = 0\n for progress, result in enumerate(tqdm(pred_results)):\n gt_class_ids = result['gt_class_ids'].astype(np.int32)\n gt_sRT = np.array(result['gt_RTs'])\n gt_size = np.array(result['gt_scales'])\n gt_handle_visibility = result['gt_handle_visibility']\n\n pred_class_ids = result['pred_class_ids']\n pred_sRT = np.array(result['pred_RTs'])\n pred_size = result['pred_scales']\n pred_scores = result['pred_scores']\n\n if len(gt_class_ids) == 0 and len(pred_class_ids) == 0:\n continue\n\n for cls_id in range(1, num_classes):\n # get gt and predictions in this class\n cls_gt_class_ids = gt_class_ids[gt_class_ids==cls_id] if len(gt_class_ids) else np.zeros(0)\n cls_gt_sRT = gt_sRT[gt_class_ids==cls_id] if len(gt_class_ids) else np.zeros((0, 4, 4))\n cls_gt_size = gt_size[gt_class_ids==cls_id] if len(gt_class_ids) else np.zeros((0, 3))\n if synset_names[cls_id] != 'mug':\n cls_gt_handle_visibility = np.ones_like(cls_gt_class_ids)\n else:\n cls_gt_handle_visibility = gt_handle_visibility[gt_class_ids==cls_id] if len(gt_class_ids) else np.ones(0)\n\n cls_pred_class_ids = pred_class_ids[pred_class_ids==cls_id] if len(pred_class_ids) else np.zeros(0)\n cls_pred_sRT = pred_sRT[pred_class_ids==cls_id] if len(pred_class_ids) else np.zeros((0, 4, 4))\n cls_pred_size = pred_size[pred_class_ids==cls_id] if len(pred_class_ids) else np.zeros((0, 3))\n cls_pred_scores = pred_scores[pred_class_ids==cls_id] if len(pred_class_ids) else np.zeros(0)\n\n # calculate the overlap between each gt instance and pred instance\n iou_cls_gt_match, iou_cls_pred_match, _, iou_pred_indices = \\\n compute_IoU_matches(cls_gt_class_ids, cls_gt_sRT, cls_gt_size, cls_gt_handle_visibility,\n cls_pred_class_ids, cls_pred_sRT, cls_pred_size, cls_pred_scores,\n synset_names, iou_thres_list)\n if len(iou_pred_indices):\n cls_pred_class_ids = cls_pred_class_ids[iou_pred_indices]\n cls_pred_sRT = cls_pred_sRT[iou_pred_indices]\n cls_pred_scores = cls_pred_scores[iou_pred_indices]\n\n num_pred = iou_cls_pred_match.shape[1]\n pred_start = iou_pred_count[cls_id]\n pred_end = pred_start + num_pred\n iou_pred_count[cls_id] = pred_end\n iou_pred_matches_all[cls_id][:, pred_start:pred_end] = iou_cls_pred_match\n cls_pred_scores_tile = np.tile(cls_pred_scores, (num_iou_thres, 1))\n assert cls_pred_scores_tile.shape[1] == num_pred\n iou_pred_scores_all[cls_id][:, pred_start:pred_end] = cls_pred_scores_tile\n num_gt = iou_cls_gt_match.shape[1]\n gt_start = iou_gt_count[cls_id]\n gt_end = gt_start + num_gt\n iou_gt_count[cls_id] = gt_end\n iou_gt_matches_all[cls_id][:, gt_start:gt_end] = iou_cls_gt_match\n\n if use_matches_for_pose:\n thres_ind = list(iou_thres_list).index(iou_pose_thres)\n iou_thres_pred_match = iou_cls_pred_match[thres_ind, :]\n cls_pred_class_ids = cls_pred_class_ids[iou_thres_pred_match > -1] if len(iou_thres_pred_match) > 0 else np.zeros(0)\n cls_pred_sRT = cls_pred_sRT[iou_thres_pred_match > -1] if len(iou_thres_pred_match) > 0 else np.zeros((0, 4, 4))\n cls_pred_scores = cls_pred_scores[iou_thres_pred_match > -1] if len(iou_thres_pred_match) > 0 else np.zeros(0)\n iou_thres_gt_match = iou_cls_gt_match[thres_ind, :]\n cls_gt_class_ids = cls_gt_class_ids[iou_thres_gt_match > -1] if len(iou_thres_gt_match) > 0 else np.zeros(0)\n cls_gt_sRT = cls_gt_sRT[iou_thres_gt_match > -1] if len(iou_thres_gt_match) > 0 else np.zeros((0, 4, 4))\n cls_gt_handle_visibility = cls_gt_handle_visibility[iou_thres_gt_match > -1] if len(iou_thres_gt_match) > 0 else np.zeros(0)\n\n RT_overlaps = compute_RT_overlaps(cls_gt_class_ids, cls_gt_sRT, cls_gt_handle_visibility,\n cls_pred_class_ids, cls_pred_sRT, synset_names)\n pose_cls_gt_match, pose_cls_pred_match = compute_RT_matches(RT_overlaps, cls_pred_class_ids, cls_gt_class_ids,\n degree_thres_list, shift_thres_list)\n num_pred = pose_cls_pred_match.shape[2]\n pred_start = pose_pred_count[cls_id]\n pred_end = pred_start + num_pred\n pose_pred_count[cls_id] = pred_end\n pose_pred_matches_all[cls_id][:, :, pred_start:pred_end] = pose_cls_pred_match\n cls_pred_scores_tile = np.tile(cls_pred_scores, (num_degree_thres, num_shift_thres, 1))\n assert cls_pred_scores_tile.shape[2] == num_pred\n pose_pred_scores_all[cls_id][:, :, pred_start:pred_end] = cls_pred_scores_tile\n num_gt = pose_cls_gt_match.shape[2]\n gt_start = pose_gt_count[cls_id]\n gt_end = gt_start + num_gt\n pose_gt_count[cls_id] = gt_end\n pose_gt_matches_all[cls_id][:, :, gt_start:gt_end] = pose_cls_gt_match\n\n # trim zeros\n for cls_id in range(num_classes):\n # IoU\n iou_pred_matches_all[cls_id] = iou_pred_matches_all[cls_id][:, :iou_pred_count[cls_id]]\n iou_pred_scores_all[cls_id] = iou_pred_scores_all[cls_id][:, :iou_pred_count[cls_id]]\n iou_gt_matches_all[cls_id] = iou_gt_matches_all[cls_id][:, :iou_gt_count[cls_id]]\n # pose\n pose_pred_matches_all[cls_id] = pose_pred_matches_all[cls_id][:, :, :pose_pred_count[cls_id]]\n pose_pred_scores_all[cls_id] = pose_pred_scores_all[cls_id][:, :, :pose_pred_count[cls_id]]\n pose_gt_matches_all[cls_id] = pose_gt_matches_all[cls_id][:, :, :pose_gt_count[cls_id]]\n\n # compute 3D IoU mAP\n for cls_id in range(1, num_classes):\n for s, iou_thres in enumerate(iou_thres_list):\n iou_aps[cls_id, s], iou_acc[cls_id, s] = compute_ap_and_acc(iou_pred_matches_all[cls_id][s, :],\n iou_pred_scores_all[cls_id][s, :],\n iou_gt_matches_all[cls_id][s, :])\n iou_aps[-1, :] = np.mean(iou_aps[1:-1, :], axis=0)\n iou_acc[-1, :] = np.mean(iou_acc[1:-1, :], axis=0)\n # compute pose mAP\n for i, degree_thres in enumerate(degree_thres_list):\n for j, shift_thres in enumerate(shift_thres_list):\n for cls_id in range(1, num_classes):\n cls_pose_pred_matches_all = pose_pred_matches_all[cls_id][i, j, :]\n cls_pose_gt_matches_all = pose_gt_matches_all[cls_id][i, j, :]\n cls_pose_pred_scores_all = pose_pred_scores_all[cls_id][i, j, :]\n pose_aps[cls_id, i, j], pose_acc[cls_id, i, j] = compute_ap_and_acc(cls_pose_pred_matches_all,\n cls_pose_pred_scores_all,\n cls_pose_gt_matches_all)\n pose_aps[-1, i, j] = np.mean(pose_aps[1:-1, i, j])\n pose_acc[-1, i, j] = np.mean(pose_acc[1:-1, i, j])\n\n # save results to pkl\n result_dict = {}\n result_dict['iou_thres_list'] = iou_thres_list\n result_dict['degree_thres_list'] = degree_thres_list\n result_dict['shift_thres_list'] = shift_thres_list\n result_dict['iou_aps'] = iou_aps\n result_dict['pose_aps'] = pose_aps\n result_dict['iou_acc'] = iou_acc\n result_dict['pose_acc'] = pose_acc\n pkl_path = os.path.join(out_dir, 'mAP_Acc.pkl')\n with open(pkl_path, 'wb') as f:\n cPickle.dump(result_dict, f)\n return iou_aps, pose_aps, iou_acc, pose_acc\n\n\ndef plot_mAP(iou_aps, pose_aps, out_dir, iou_thres_list, degree_thres_list, shift_thres_list):\n \"\"\" Draw iou 3d AP vs. iou thresholds.\n \"\"\"\n\n labels = ['bottle', 'bowl', 'camera', 'can', 'laptop', 'mug', 'mean', 'nocs']\n colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:pink', 'tab:olive', 'tab:purple', 'tab:red', 'tab:gray']\n styles = ['-', '-', '-', '-', '-', '-', '--', ':']\n\n fig, (ax_iou, ax_degree, ax_shift) = plt.subplots(1, 3, figsize=(8, 3.5))\n # IoU subplot\n ax_iou.set_title('3D IoU', fontsize=10)\n ax_iou.set_ylabel('Average Precision')\n ax_iou.set_ylim(0, 100)\n ax_iou.set_xlabel('Percent')\n ax_iou.set_xlim(0, 100)\n ax_iou.xaxis.set_ticks([0, 25, 50, 75, 100])\n ax_iou.grid()\n for i in range(1, iou_aps.shape[0]):\n ax_iou.plot(100*np.array(iou_thres_list), 100*iou_aps[i, :],\n color=colors[i-1], linestyle=styles[i-1], label=labels[i-1])\n # rotation subplot\n ax_degree.set_title('Rotation', fontsize=10)\n ax_degree.set_ylim(0, 100)\n ax_degree.yaxis.set_ticklabels([])\n ax_degree.set_xlabel('Degree')\n ax_degree.set_xlim(0, 60)\n ax_degree.xaxis.set_ticks([0, 20, 40, 60])\n ax_degree.grid()\n for i in range(1, pose_aps.shape[0]):\n ax_degree.plot(np.array(degree_thres_list), 100*pose_aps[i, :len(degree_thres_list), -1],\n color=colors[i-1], linestyle=styles[i-1], label=labels[i-1])\n # translation subplot\n ax_shift.set_title('Translation', fontsize=10)\n ax_shift.set_ylim(0, 100)\n ax_shift.yaxis.set_ticklabels([])\n ax_shift.set_xlabel('Centimeter')\n ax_shift.set_xlim(0, 10)\n ax_shift.xaxis.set_ticks([0, 5, 10])\n ax_shift.grid()\n for i in range(1, pose_aps.shape[0]):\n ax_shift.plot(np.array(shift_thres_list), 100*pose_aps[i, -1, :len(shift_thres_list)],\n color=colors[i-1], linestyle=styles[i-1], label=labels[i-1])\n ax_shift.legend(loc='lower right', fontsize='small')\n plt.tight_layout()\n # plt.show()\n plt.savefig(os.path.join(out_dir, 'mAP.png'))\n plt.close(fig)\n return\n\n\ndef calculate_2d_projections(coordinates_3d, intrinsics):\n \"\"\"\n Args:\n coordinates_3d: [3, N]\n intrinsics: [3, 3]\n\n Returns:\n projected_coordinates: [N, 2]\n \"\"\"\n projected_coordinates = intrinsics @ coordinates_3d\n projected_coordinates = projected_coordinates[:2, :] / projected_coordinates[2, :]\n projected_coordinates = projected_coordinates.transpose()\n projected_coordinates = np.array(projected_coordinates, dtype=np.int32)\n\n return projected_coordinates\n\n\ndef align_rotation(sRT):\n \"\"\" Align rotations for symmetric objects.\n Args:\n sRT: 4 x 4\n \"\"\"\n s = np.cbrt(np.linalg.det(sRT[:3, :3]))\n R = sRT[:3, :3] / s\n T = sRT[:3, 3]\n\n theta_x = R[0, 0] + R[2, 2]\n theta_y = R[0, 2] - R[2, 0]\n r_norm = math.sqrt(theta_x**2 + theta_y**2)\n s_map = np.array([[theta_x/r_norm, 0.0, -theta_y/r_norm],\n [0.0, 1.0, 0.0 ],\n [theta_y/r_norm, 0.0, theta_x/r_norm]])\n rotation = R @ s_map\n aligned_sRT = np.identity(4, dtype=np.float32)\n aligned_sRT[:3, :3] = s * rotation\n aligned_sRT[:3, 3] = T\n return aligned_sRT\n\n\ndef draw_bboxes(img, img_pts, color):\n img_pts = np.int32(img_pts).reshape(-1, 2)\n # draw ground layer in darker color\n color_ground = (int(color[0]*0.3), int(color[1]*0.3), int(color[2]*0.3))\n for i, j in zip([4, 5, 6, 7], [5, 7, 4, 6]):\n img = cv2.line(img, tuple(img_pts[i]), tuple(img_pts[j]), color_ground, 2)\n # draw pillars in minor darker color\n color_pillar = (int(color[0]*0.6), int(color[1]*0.6), int(color[2]*0.6))\n for i, j in zip(range(4), range(4, 8)):\n img = cv2.line(img, tuple(img_pts[i]), tuple(img_pts[j]), color_pillar, 2)\n # draw top layer in original color\n for i, j in zip([0, 1, 2, 3], [1, 3, 0, 2]):\n img = cv2.line(img, tuple(img_pts[i]), tuple(img_pts[j]), color, 2)\n\n return img\n\n\ndef draw_detections(img, out_dir, data_name, img_id, intrinsics, pred_sRT, pred_size, pred_class_ids,\n gt_sRT, gt_size, gt_class_ids, nocs_sRT, nocs_size, nocs_class_ids, draw_gt=True, draw_nocs=True):\n \"\"\" Visualize pose predictions.\n \"\"\"\n out_path = os.path.join(out_dir, '{}_{}_pred.png'.format(data_name, img_id))\n\n # draw nocs results - BLUE color\n if draw_nocs:\n for i in range(nocs_sRT.shape[0]):\n if nocs_class_ids[i] in [1, 2, 4]:\n sRT = align_rotation(nocs_sRT[i, :, :])\n else:\n sRT = nocs_sRT[i, :, :]\n bbox_3d = get_3d_bbox(nocs_size[i, :], 0)\n transformed_bbox_3d = transform_coordinates_3d(bbox_3d, sRT)\n projected_bbox = calculate_2d_projections(transformed_bbox_3d, intrinsics)\n img = draw_bboxes(img, projected_bbox, (255, 0, 0))\n # darw ground truth - GREEN color\n if draw_gt:\n for i in range(gt_sRT.shape[0]):\n if gt_class_ids[i] in [1, 2, 4]:\n sRT = align_rotation(gt_sRT[i, :, :])\n else:\n sRT = gt_sRT[i, :, :]\n bbox_3d = get_3d_bbox(gt_size[i, :], 0)\n transformed_bbox_3d = transform_coordinates_3d(bbox_3d, sRT)\n projected_bbox = calculate_2d_projections(transformed_bbox_3d, intrinsics)\n img = draw_bboxes(img, projected_bbox, (0, 255, 0))\n # darw prediction - RED color\n for i in range(pred_sRT.shape[0]):\n if pred_class_ids[i] in [1, 2, 4]:\n sRT = align_rotation(pred_sRT[i, :, :])\n else:\n sRT = pred_sRT[i, :, :]\n bbox_3d = get_3d_bbox(pred_size[i, :], 0)\n transformed_bbox_3d = transform_coordinates_3d(bbox_3d, sRT)\n projected_bbox = calculate_2d_projections(transformed_bbox_3d, intrinsics)\n img = draw_bboxes(img, projected_bbox, (0, 0, 255))\n\n cv2.imwrite(out_path, img)\n # cv2.imshow('vis', img)\n # cv2.waitKey(0)\n","sub_path":"lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":33837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"91402802","text":"# -*- coding: utf-8 -*-\n# Author: Jorge A. Toro\n#\nimport sys\nimport datetime\nimport StringIO\nfrom UserDict import UserDict\nimport simplejson as json\nfrom Gps.Antares.convert import latWgs84ToDecimal, lngWgs84ToDecimal\nfrom Gps.SkyPatrol.convert import degTodms\nfrom Gps.common import MphToKph\nimport Location.geomapgoogle\n\n\ndef tagData(dFile, position, bit=None, seek=0):\n \"\"\"\n Toma un punto de partida (position), cantidad de bit y un punto de \n referencia para leer los bit(según el método seek() de los fichero).\n Además dataFile el cual es objeto StringIO.\n \"\"\"\n try:\n dFile.seek(position, seek)\n tagdata = dFile.read(bit)\n except: sys.stderr.write(\"Error al obtener el Tag Data\")\n \n return tagdata\n\n\n# Clase que actua como un diccionario\nclass Device(UserDict):\n \"\"\" Store Device\"\"\"\n def __init__(self, deviceData=None, address=None):\n UserDict.__init__(self)\n self[\"data\"] = deviceData\n #self[\"address\"] = address\n self[\"address\"] = \"%s,%s\" % address\n #self[\"geocoding\"] = None\n # Fecha y hora (del sistema)\n self[\"datetime\"] = datetime.datetime.now()\n\n\nclass ANTDevice(Device):\n \"\"\"\n Dispositivo Antares\n \"\"\"\n tagDataANT = { # (position, bit, seek, function_tagData, function_convert )\n #\"id\" : (-6, 6, 2, tagData)#, # ID de la unidad\n \"id\" : (-6, None, 2, tagData, None), # ID de la unidad\n \"type\" : (0, 1, 0, tagData, None),\n \"typeEvent\" : (1, 2, 0, tagData, None), # \n \"codEvent\" : (3, 2, 0, tagData, None), # Codigo de evento activado (en Antares de 00 a 49, en e.Track de 00 a 99)\n \"weeks\" : (5, 4, 0, tagData, None), # Es el numero de semanas desde 00:00AM del 6 de enero de 1980.\n \"dayWeek\" : (9, 1, 0, tagData, None), # 0=Domingo, 1=Lunes, etc hasta 6=sabado.\n \"time\" : (10, 5, 0, tagData, None), # Hora expresada en segundos desde 00:00:00AM\n \"lat\" : (15, 8, 0, tagData, latWgs84ToDecimal), # Latitud\n \"lng\" : (23, 9, 0, tagData, lngWgs84ToDecimal), # Longitud\n \"speed\" : (-18, 3, 2, tagData, MphToKph), # Velocidad en MPH\n \"course\" : (-15, 3, 2, tagData, None), # Curso en grados\n \"gpsSource\" : (-12, 1, 2, tagData, None), # Fuente GPS. Puede ser 0=2D GPS, 1=3D GPS, 2=2D DGPS, 3=3D DGPS, 6=DR, 8=Degraded DR. \n \"ageData\" : (-11, 1, 2, tagData, None) # Edad del dato. Puede ser 0=No disponible, 1=viejo (10 segundos) ó 2=Fresco (menor a 10 segundos)\n }\n\n\n def __parse(self, data):\n self.clear()\n try:\n dataFile = StringIO.StringIO(data[1:-1]) # remove '<' y '>'\n #\n for tag, (position, bit, seek, parseFunc, convertFunc) in self.tagDataANT.items():\n self[tag] = convertFunc and convertFunc(parseFunc(dataFile, position, bit, seek)) or parseFunc(dataFile, position, bit, seek)\n\n # Creamos una key para la altura (estandar), ya que las tramas actuales no la incluyen:\n self['altura'] = None\n # Creamos una key para el dato position:\n self['position'] = \"(%(lat)s,%(lng)s)\" % self\n\n # Realizamos la Geocodificación. Tratar de no hacer esto\n # es mejor que se realize por cada cliente con la API de GoogleMap\n self[\"geocoding\"] = None \n self[\"geocoding\"] = json.loads(Location.geomapgoogle.regeocode('%s,%s' % (self[\"lat\"], self[\"lng\"])))[0]\n\n except: print(sys.exc_info()) #sys.stderr.write('Error Inesperado:', sys.exc_info())\n finally: dataFile.close()\n\n\n def __setitem__(self, key, item):\n if key == \"data\" and item:\n self.__parse(item)\n # Llamamos a __setitem__ de nuestro ancestro\n Device.__setitem__(self, key, item) \n\n \ndef tagDataskp(dList, start, end):\n \"\"\"\n Toma una posición para obtener de la lista dList.\n \"\"\"\n try:\n #if end is not None: \n if end: \n #tagdata = \",\".join(dList[start:end + 1])\n tagdata = dList[start:end + 1]\n else:\n tagdata = dList[start]\n except: sys.stderr.write(\"Error al obtener el Tag Data\")\n \n return tagdata or None\n \n\nclass SKPDevice(Device):\n \"\"\"\n Dispositivo Skypatrol\n \"\"\"\n # ['', '5', 'SKP87', '$GPRMC', '122408.00', 'A', '0441.935953', 'N', '07404.450302', 'W', '0.0', '0.0', '180912', '5.5', 'E', 'A*2F']\n tagDataSKP = { # (position_start, position_end, function_tagData, function_convert )\n \"id\" : (2, None, tagDataskp, None), # ID de la unidad\n \"type\" : (0, None, tagDataskp, None),\n \"typeEvent\" : (3, None, tagDataskp, None), # \n \"codEvent\" : (1, None, tagDataskp, None), # Codigo de evento activado (en Antares de 00 a 49, en e.Track de 00 a 99)\n \"weeks\" : (0, None, tagDataskp, None), # Es el numero de semanas desde 00:00AM del 6 de enero de 1980.\n \"dayWeek\" : (0, None, tagDataskp, None), # 0=Domingo, 1=Lunes, etc hasta 6=sabado.\n \"time\" : (4, None, tagDataskp, None), # Hora expresada en segundos desde 00:00:00AM\n \"lat\" : (6, 7, tagDataskp, degTodms), # Latitud\n #\"lat\" : (6, tagDataskp, latWgs84ToDecimal), # Latitud\n \"lng\" : (8, 9, tagDataskp, degTodms), # Longitud\n #\"lng\" : (23, 9, 0, tagDataskp, lngWgs84ToDecimal), # Longitud\n \"speed\" : (10, None, tagDataskp, MphToKph), # Velocidad en MPH\n \"course\" : (11, None, tagDataskp, None), # Curso en grados\n \"gpsSource\" : (0, None, tagDataskp, None), # Fuente GPS. Puede ser 0=2D GPS, 1=3D GPS, 2=2D DGPS, 3=3D DGPS, 6=DR, 8=Degraded DR. # Problema DB si no son enteros \n \"ageData\" : (0, None, tagDataskp, None), # Edad del dato. Puede ser 0=No disponible, 1=viejo (10 segundos) ó 2=Fresco (menor a 10 segundos) # Problema DB si no son enteros\n \"odometro\" : (15, None, tagDataskp, None) # Odómetro\n }\n\n\n def __parse(self, data):\n self.clear()\n try:\n import re\n ####\n # data = ' 5 SKP87 $GPRMC,122408.00,A,0441.935953,N,07404.450302,W,0.0,0.0,180912,5.5,E,A*2F'\n data = data.replace(' ', ',')\n # ',,,,,5,,,,,,,,,,,,,,,,,SKP87,$GPRMC,122408.00,A,0441.935953,N,07404.450302,W,0.0,0.0,180912,5.5,E,A*2F'\n data = re.sub(r\",,\", \"\", data)\n # ',5,SKP87,$GPRMC,122408.00,A,0441.935953,N,07404.450302,W,0.0,0.0,180912,5.5,E,A*2F'\n dataList = data.split(',')\n # ['', '5', 'SKP87', '$GPRMC', '122408.00', 'A', '0441.935953', 'N', '07404.450302', 'W', '0.0', '0.0', '180912', '5.5', 'E', 'A*2F']\n #\n for tag, (position_start, position_end, parseFunc, convertFunc) in self.tagDataSKP.items():\n self[tag] = convertFunc and convertFunc(parseFunc(dataList, position_start, position_end)) or parseFunc(dataList, position_start, position_end)\n\n # Creamos una key para la altura (estandar), ya que las tramas actuales no la incluyen:\n self['altura'] = None\n # Creamos una key para el dato position:\n self['position'] = \"(%(lat)s,%(lng)s)\" % self\n\n # Realizamos la Geocodificación. Tratar de no hacer esto\n # es mejor que se realize por cada cliente con la API de GoogleMap\n self[\"geocoding\"] = None \n self[\"geocoding\"] = json.loads(Location.geomapgoogle.regeocode('%s,%s' % (self[\"lat\"], self[\"lng\"])))[0]\n\n except: print(sys.exc_info()) #sys.stderr.write('Error Inesperado:', sys.exc_info())\n #finally: dataFile.close()\n\n\n def __setitem__(self, key, item):\n if key == \"data\" and item:\n self.__parse(item)\n # Llamamos a __setitem__ de nuestro ancestro\n Device.__setitem__(self, key, item) \n\n\nclass HUNTDevice(Device):\n \"\"\"\n Dispositivo Hunter\n \"\"\"\n pass\n\n\n\ndef typeDevice(data):\n \"\"\"\n Determina que tipo de Dispositivo GPS es dueña de la data.\n\n Usage:\n >>> import devices\n >>> \n >>> data='>REV041674684322+0481126-0757378200000012;ID=ANT001<'\n >>> devices.typeDevice(data)\n 'ANT'\n >>>\n >>> type(devices.typeDevice(''))\n \n >>>\n >>> if devices.typeDevice('') is not None: print \"Seguir con el programa...\"\n ... \n >>> if devices.typeDevice(data) is not None: print \"Seguir con el programa...\"\n ... \n Seguir con el programa...\n >>> \n \"\"\"\n # Dispositivos soportados:\n types = ('ANT', 'SKP', 'HUNT')\n\n typeDev = lambda dat: (\"\".join(\n [d for d in types \n if dat.find(d) is not -1])\n )\n return typeDev(data) or None #raise\n\n\n#\ndef getTypeClass(data, address=None, module=sys.modules[Device.__module__]):\n \"\"\"\n Determina que clase debe manejar un determinado dispositivo y\n retorna un diccionario con la trama procesada.\n\n Recibe la data enviada por el dispositivo (data), y opcionalmente \n el nombre del módulo donde se encuentra la clase que manipula este \n tipo de dispositivo (module). La clase manejador debe tener un \n formato compuesto por 'TIPO_DISPOSITIVO + Device' por ejemplo: ANTDevice,\n SKPDevice, etc.\n\n Usage:\n >>> import devices\n >>> \n >>> data='>REV001447147509+2578250-0802813901519512;ID=ANT001<'\n >>> devices.getTypeClass(data)\n {'codEvent': '00', 'weeks': '1447', 'dayWeek': '1', 'ageData': '2', \\\n 'type': 'R', 'data': '>REV001447147509+2578250-0802813901519512;ID=ANT001<', \\\n 'course': '195', 'gpsSource': '1', 'time': '47509', 'lat': '+2578250', \\\n 'typeEvent': 'EV', 'lng': '-08028139', 'speed': '015', 'id': 'ANT001'}\n >>> print \"\\n\".join([\"%s=%s\" % (key,value) for key, value in devices.getTypeClass(data).items()])\n codEvent=00\n weeks=1447\n dayWeek=1\n ageData=2\n type=R\n data=>REV001447147509+2578250-0802813901519512;ID=ANT001<\n course=195\n gpsSource=1\n time=47509\n lat=+2578250\n typeEvent=EV\n lng=-08028139\n speed=015\n id=ANT001\n >>> \n \"\"\"\n import re\n\n #data = data.replace('\\n','')\n #data = data.strip('\\n')\n data = re.sub(r\"[\\r\\n]+\", \"\", data)\n\n # Determinamos la clase manejadora adecuado según el dispositivo\n dev = \"%sDevice\" % typeDevice(data)\n\n #return dev\n def getClass(module, dev): \n \"\"\" \n Retorna una referencia a la clase manejadora. \n Usage:\n >>> getClass(module, 'ANTDevice')\n \n >>> getClass(module, 'SKPDevice')\n \n >>> getClass(module, '')\n \n >>> \n \"\"\"\n return hasattr(module, dev) and getattr(module, dev) or Device\n\n return getClass(module, dev)(data, address)\n\n \n\n","sub_path":"Devices/devices.py","file_name":"devices.py","file_ext":"py","file_size_in_byte":11736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"89973884","text":"import pygame\r\nimport os\r\nimport in_game\r\nfrom menuFolder.menu import menu\r\nfrom levelsFolder.level_A import Map_A\r\nfrom towersFolder.tower_A import Tower_A\r\nfrom towersFolder.supportTower import supportTower_A\r\n\r\nstart_img = pygame.image.load(os.path.join(\"img/main_page_img\",\"start_button.png\"))\r\nborder_img = pygame.image.load(os.path.join(\"img/borders\",\"b1.png\"))\r\nexit_img = pygame.image.load(os.path.join(\"img/prep_page\",\"exit.png\"))\r\ntower_select_img = pygame.image.load(os.path.join(\"img/prep_page\",\"tower_select.jpg\"))\r\n\r\npygame.init()\r\npygame.font.init()\r\n\r\nitems_per_row = 5\r\n\r\nclass prepPage:\r\n def __init__(self, screen_width, screen_height, current_player):\r\n self.screen_width = screen_width\r\n self.screen_height = screen_height\r\n self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))\r\n\r\n self.bg = pygame.transform.scale(\r\n pygame.image.load(os.path.join(\r\n \"img\",\"main_page_bg.jpg\")), (self.screen_width,self.screen_height))\r\n\r\n self.tower_slots = current_player.general_upgrades['tower_slots'][0]\r\n \r\n self.stw_width = 0.75 * self.screen_width\r\n self.stw_height = 0.8 * self.stw_width\r\n\r\n self.selected_tower = []\r\n\r\n self.allTowers = [Tower_A(), supportTower_A()]\r\n\r\n self.towerdisplay = {}\r\n\r\n for tower in self.allTowers:\r\n if current_player.towers_upgrades[\"{}\".format(tower.id)]['unlocked'][0]:\r\n self.towerdisplay[tower.id] = [tower.tower_imgs[0], tower, 1]\r\n else:\r\n self.towerdisplay[tower.id] = [tower.locked_img, tower, 0]\r\n\r\n \r\n self.tower_islocked = []\r\n self.towers_img = [Tower_A().tower_imgs[0],supportTower_A().tower_imgs[0]]\r\n self.towers_obj = [Tower_A(), supportTower_A()]\r\n \r\n #stw resolution is always 1:0.8\r\n self.stw_items = [(0.004*self.stw_width,0.004*self.stw_height,0.19*self.stw_width,0.125*self.stw_height,\r\n None,(252, 115, 3),\r\n None,\r\n 1),\r\n (0.004*self.stw_width,0.125*self.stw_height,0.19*self.stw_width,0.875*self.stw_height,\r\n tower_select_img,None,\r\n [(self.towerdisplay[1][0], self.towerdisplay[1][1], None, None, self.towerdisplay[1][2]),\r\n (self.towerdisplay[2][0], self.towerdisplay[2][1], None, None, self.towerdisplay[2][2])]\r\n ,2),\r\n (0.19*self.stw_width,0.004*self.stw_height,0.81*self.stw_width,0.8125*self.stw_height,\r\n None,(222, 51, 42),\r\n None\r\n ,3),\r\n (0.19*self.stw_width,0.8125*self.stw_height,0.81*self.stw_width,0.1875*self.stw_height,\r\n tower_select_img,None,\r\n [(None,None,None,None),\r\n (None,None,None,None),\r\n (None,None,None,None),\r\n (None,None,None,None),\r\n (None,None,None,None),\r\n (None,None,None,None)]\r\n ,4),\r\n (0.80*self.stw_width,0.8125*self.stw_height,0.20*self.stw_width,0.1875*self.stw_height,\r\n tower_select_img,None,\r\n [(start_img, \"start\", None, None)]\r\n ,5),\r\n (0.93*self.stw_width,0,0.07*self.stw_width,0.0875*self.stw_height,\r\n exit_img,None,\r\n [(None,\"e\",None,None)]\r\n ,6)\r\n ]\r\n\r\n self.stw = menu(0.125*self.screen_width, 0.108*self.screen_height,\r\n self.stw_width, self.stw_height, self.stw_items, border_img, None,\r\n None, None, None,\r\n None, None, None,\r\n None, (59, 64, 71), 2)\r\n\r\n\r\n\r\n \r\n self.gap = 0.02*self.screen_width\r\n self.button_width = ((self.screen_width - self.gap * (items_per_row+1)) / items_per_row)*0.8\r\n self.button_height = 0.8*self.button_width\r\n \r\n self.level_one_menu_items = [(Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None)]\r\n \r\n self.level_one_menu = menu(0.05*self.screen_width, 0.05*self.screen_height, #need to increase the y by at least this height\r\n 0.9*self.screen_width, 2.6*(self.button_height + self.gap), self.level_one_menu_items, None, (41, 51, 61),\r\n None, None, None,\r\n self.button_width, self.button_height, self.gap,\r\n None, None\r\n )\r\n\r\n self.level_two_menu_items = [(Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None),\r\n (Map_A().bg, Map_A, None, None)]\r\n \r\n self.level_two_menu = menu(0.05*self.screen_width, 2*(0.05*self.screen_height) + 2.6*(self.button_height + self.gap), #need to increase the y by at least this height\r\n 0.9*self.screen_width, 2.6*(self.button_height + self.gap), self.level_one_menu_items, None, (41, 51, 61),\r\n None, None, None,\r\n self.button_width, self.button_height, self.gap,\r\n None, None\r\n )\r\n\r\n self.exit_menu_item = [(exit_img, \"e\", None, (255,255,255))]\r\n self.exit_menu = menu(self.screen_width*0.95, 0,\r\n self.screen_width*0.05, self.screen_width*0.05, self.exit_menu_item, None, None,\r\n None, None, None,\r\n self.screen_width*0.05, self.screen_width*0.05, 0,\r\n None, None)\r\n\r\n \r\n self.drag_x = 0 #difference from origin to draged position, compared with top left corners\r\n self.drag_y = 0\r\n self.drag = False\r\n\r\n self.map_selection_surface = pygame.Surface((self.screen_width, 900),pygame.SRCALPHA)\r\n\r\n self.clock = pygame.time.Clock()\r\n self.start = True\r\n\r\n self.selected_level = None\r\n self.selected_map = None\r\n self.selected_map_num = None\r\n self.isSelected_map = False\r\n self.gameStart = False\r\n\r\n\r\n\r\n def draw(self, cursor_pos):\r\n self.level_one_menu.level_menu_withSetItemPerRow(self.map_selection_surface, items_per_row, \"Level 1\")\r\n self.level_two_menu.level_menu_withSetItemPerRow(self.map_selection_surface, items_per_row, \"Level 2\")\r\n self.screen.blit(self.bg,(0,0))\r\n self.screen.blit(self.map_selection_surface, (self.drag_x,self.drag_y))\r\n\r\n\r\n self.exit_menu.draw_horizontal_small(self.screen)\r\n \r\n if self.isSelected_map:\r\n self.get_set_tower(cursor_pos, self.stw)\r\n \r\n\r\n\r\n def run(self):\r\n while self.start:\r\n\r\n self.clock.tick(20)\r\n\r\n if self.gameStart:\r\n return (self.selected_map, self.selected_tower)\r\n \r\n \r\n cursor_pos = pygame.mouse.get_pos()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n self.start = False\r\n \r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n\r\n cursor_pos = pygame.mouse.get_pos()\r\n offset_x = self.drag_x - cursor_pos[0]\r\n offset_y = self.drag_y - cursor_pos[1]\r\n normal_coord = (abs(offset_x), abs(offset_y))\r\n\r\n if event.button == 1:\r\n\r\n if self.exit_menu.buttons[0].click(cursor_pos[0],cursor_pos[1]) == \"e\":\r\n return \"e\"\r\n \r\n if not self.selected_map:\r\n \r\n if self.cursor_in_range(normal_coord, self.level_one_menu):\r\n selected = self.get_set_map(normal_coord, self.level_one_menu)\r\n if selected != None:\r\n self.selected_level = str(1)\r\n self.selected_map = selected[0]\r\n self.selected_map_num = selected[1]\r\n \r\n if self.cursor_in_range(normal_coord, self.level_two_menu):\r\n selected = self.get_set_map(normal_coord, self.level_two_menu)\r\n if selected != None:\r\n self.selected_level = str(1)\r\n self.selected_map = selected[0]\r\n self.selected_map_num = selected[1]\r\n \r\n if event.button == 3:\r\n self.drag = True\r\n cursor_pos = pygame.mouse.get_pos()\r\n\r\n elif event.type == pygame.MOUSEBUTTONUP:\r\n if event.button == 3:\r\n self.drag = False\r\n\r\n elif event.type == pygame.MOUSEMOTION:\r\n if self.drag:\r\n self.drag_y = cursor_pos[1] + offset_y\r\n\r\n if self.drag_y > 0:\r\n self.drag_y = 0\r\n if self.drag_y < -self.screen_height:\r\n self.drag_y = -self.screen_height\r\n\r\n \r\n self.draw(cursor_pos)\r\n pygame.display.update()\r\n pygame.quit()\r\n\r\n\r\n \r\n \r\n def cursor_in_range(self, cursor, obj):\r\n if obj.x < cursor[0] < obj.x + obj.menu_width:\r\n if obj.y < cursor[1] < obj.y + obj.menu_height:\r\n return True\r\n return False\r\n\r\n\r\n\r\n def get_set_map(self, cursor, menu):\r\n offset_x = menu.ori_x\r\n offset_y = menu.ori_y\r\n for x, button in enumerate(menu.buttons):\r\n selected_map = button.click(cursor[0]-offset_x,cursor[1]-offset_y)\r\n if selected_map != None:\r\n self.isSelected_map = True\r\n return (selected_map, str(x+1))\r\n\r\n def get_set_tower(self, cursor, menu):\r\n\r\n self.stw.displayers[0].displayer_items = self.selected_level+'-'+self.selected_map_num\r\n self.stw.displayers[2].displayer_items = self.selected_map().bg #map display\r\n self.stw.drawDisplayers(self.screen)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n self.start = False\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n if event.button == 1:\r\n if (menu.displayers[1].x + menu.ori_x < cursor[0] < menu.displayers[1].x + menu.ori_x + menu.displayers[1].menu_width) and (menu.displayers[1].y + menu.ori_y < cursor[0] < menu.displayers[1].y + menu.ori_y + menu.displayers[1].menu_height):\r\n offset_x = menu.displayers[1].x + menu.ori_x\r\n offset_y = menu.displayers[1].y + menu.ori_y\r\n for t1button in menu.displayers[1].buttons:\r\n v = t1button.click(cursor[0]-offset_x,cursor[1]-offset_y)\r\n if v != None and v.id not in self.selected_tower:\r\n if len(self.selected_tower) < self.tower_slots:\r\n self.selected_tower.append(v.id)\r\n for t4button in menu.displayers[3].buttons:\r\n if t4button.button_img == None:\r\n t4button.button_img = t1button.button_img\r\n t4button.button_obj = t1button.button_obj\r\n #print(t4button.x, t4button.button_width)\r\n #print(t4button.y, t4button.button_height)\r\n break\r\n else:\r\n print('cant add more tower')\r\n \r\n \r\n \r\n\r\n else:\r\n offset_x = menu.ori_x\r\n offset_y = menu.ori_y\r\n \r\n\r\n for t4button in menu.displayers[3].buttons:\r\n v1 = t4button.click(cursor[0]-offset_x,cursor[1]-offset_y)\r\n if v1 != None:\r\n v1 = v1.id\r\n self.selected_tower.remove(v1)\r\n t4button.button_img = t4button.button_obj = None\r\n \r\n \r\n if menu.displayers[5].buttons[0].click(cursor[0]-offset_x,cursor[1]-offset_y) == \"e\":\r\n self.selected_map = None\r\n self.isSelected_map = False\r\n\r\n elif menu.displayers[4].buttons[0].click(cursor[0]-offset_x,cursor[1]-offset_y) == \"start\":\r\n if self.selected_tower:\r\n self.gameStart = True\r\n else:\r\n print(\"need at least one tower\")\r\n\r\n\r\n\r\n\r\n","sub_path":"prep_page.py","file_name":"prep_page.py","file_ext":"py","file_size_in_byte":14213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"637309667","text":"import openpyxl\nimport docx\nimport csv\nimport os\nimport exp_finder as f\nfrom docx.shared import Cm\n\n# constants \ncwd = os.getcwd()\ninput_directory = 'py-files\\\\data\\\\testdc'\ninput_file_name = 'fulltestdc.xlsx'\ninput_path = os.path.join(cwd, input_directory, input_file_name)\noutput_directory = 'py-files\\\\data\\\\resultsdc'\noutput_file_name = 'results.docx'\noutput_path = os.path.join(cwd, output_directory, output_file_name)\noutput_analysis_file_name = 'results.csv'\noutput_analysis_directory = 'py-files\\\\data\\\\resultsdc'\noutput_analysis_path = os.path.join(cwd, output_analysis_directory, output_analysis_file_name)\n\nanalysis = {\n 'norms': set(),\n 'appendixes': set(),\n 'acronyms': set(),\n 'count_lsc4_chars': 0,\n 'count_lsc2_chars': 0,\n 'count_lsc4_words': 0,\n 'count_lsc2_words': 0\n}\nwords_per_page = 363.25\n\nwb = openpyxl.load_workbook(input_path)\nprint('-> Excel source file opened successfully')\ntabs = wb.sheetnames\n\nletters = [ 'A', 'B', 'C', 'D', 'E', 'F']\ndoc = docx.Document(output_path)\nprint('-> Word target file opened successfully')\nstyles = doc.styles\ni = 0\n\nfor tab in tabs:\n print(' > transfering worksheet ', tab)\n # doc.add_heading(tab, level=2)\n ws = wb[tab]\n max_rows = ws.max_row\n\n heading = doc.add_paragraph(tab.upper())\n heading.style = styles['Heading 1']\n table = doc.add_table(rows=0, cols=3)\n table.alignment = docx.enum.table.WD_TABLE_ALIGNMENT.LEFT\n table.allow_autofit = False\n table.width = Cm(17.43)\n previous_code = ''\n previous_title = ''\n\n for i in range(2, max_rows + 1):\n position_code = 'A' + str(i)\n code = str(ws[position_code].value).strip()\n if (code == 'None'): continue\n position_title = 'B' + str(i)\n title = str(ws[position_title].value).strip()\n position_text = 'G' + str(i)\n text = str(ws[position_text].value).strip()\n position_lsc2 = 'C' + str(i)\n lsc2_text = str(ws[position_lsc2].value)\n if (previous_code != code and code != 'None'): \n previous_code = code\n code_changed = True\n else:\n code = previous_code\n code_changed = False\n if (previous_title != title and title != 'None'): \n previous_title = title\n else:\n title = ''\n if (title != 'None' and text != 'None'):\n cells = table.add_row().cells\n if (code != 'None' and code_changed): \n cells[0].text = code\n cells[0].width = Cm(2.23)\n if (title != 'None'): \n cells[1].text = title\n cells[1].width = Cm(3.77)\n if (text != 'None'): \n cells[2].text = text\n cells[2].width = Cm(11.44)\n else:\n cells[2].text = ''\n i += 1\n acronyms = f.find_acronyms(text)\n for acronym in acronyms:\n analysis['acronyms'].add(acronym)\n appendixes = f.find_appendixes(text)\n for appendix in appendixes:\n analysis['appendixes'].add(appendix)\n norms = f.find_norms(text)\n for norm in norms:\n analysis['norms'].add(norm)\n analysis['count_lsc2_chars'] += len(lsc2_text)\n analysis['count_lsc4_chars'] += len(text)\n analysis['count_lsc2_words'] += len(lsc2_text.split())\n analysis['count_lsc4_words'] += len(text.split())\n\n par = doc.add_paragraph()\n run = par.add_run()\n run.add_break(docx.enum.text.WD_BREAK.PAGE)\n\nanalysis['acronyms'] = sorted(analysis['acronyms'])\nanalysis['appendixes'] = sorted(analysis['appendixes'])\nanalysis['norms'] = sorted(analysis['norms'])\n\n#end\ndoc.save(output_path)\nprint('-> Word target file saved successfully')\nprint('-> Transfer completed')\nprint('-> Sending analytical results to csv file')\nwith open(output_analysis_path, 'w', newline='', encoding='utf-8') as file_output:\n writer = csv.writer(file_output, delimiter=' ')\n writer.writerow(['\\n\\nWORDCOUNT LSC2'])\n writer.writerow([str(analysis['count_lsc2_chars']), 'characters'])\n writer.writerow([str(analysis['count_lsc2_words']), 'words'])\n pages_lsc2 = round(analysis['count_lsc2_words'] / words_per_page, 2)\n writer.writerow([str(pages_lsc2), 'pages'])\n writer.writerow(['\\n\\nWORDCOUNT LSC4'])\n writer.writerow([str(analysis['count_lsc4_chars']), 'characters'])\n writer.writerow([str(analysis['count_lsc4_words']), 'words']) \n pages_lsc4 = round(analysis['count_lsc4_words'] / words_per_page, 2)\n writer.writerow([str(pages_lsc4), 'pages'])\n writer.writerow(['\\n\\nACRONYMS'])\n for row in analysis['acronyms']:\n writer.writerow([str(row)])\n writer.writerow(['\\n\\nNORMS'])\n for row in analysis['norms']:\n writer.writerow([str(row)])\n writer.writerow(['\\n\\nAPPENDIXES'])\n for row in analysis['appendixes']:\n writer.writerow([str(row)])\n\n file_output.close()\nprint('-> results.csv file created successfully')","sub_path":"src/process_word.py","file_name":"process_word.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"36408562","text":"#!/usr/bin/env python3\n#coding: utf-8\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage \nfrom email.header import Header\nfrom email.mime.multipart import MIMEMultipart\nimport yaml\n\ndef create_mime_alternative():\n # multipart/alternative\n msg = MIMEMultipart('alternative')\n msg['Subject'] = \"Link\"\n # Attach parts into message container.\n # According to RFC 2046, the last part of a multipart message, in this case\n # the HTML message, is best and preferred.\n\n msg.attach(MIMEText('hello plain text', 'plain'))\n msg.attach(MIMEText('

    hello html

    MyBlog
    ', 'html') )\n \n with open('logo.png', 'rb') as fin:\n att = MIMEText(fin.read(), 'base64', 'utf-8')\n att[\"Content-Type\"] = 'application/octet-stream'\n att[\"Content-Disposition\"] = 'attachment; filename=\"logp.png\"'\n msg.attach(att) \n # print(msg.as_string())\n return msg.as_string()\n \ndef create_mime_image():\n msg = MIMEMultipart('related')\n msg['Subject'] = 'test message' \n\n msgText = MIMEText('''Some HTML text and an image. \"\"''','html','utf-8')\n msg.attach(msgText) \n \n with open('logo.png', 'rb') as fin:\n att = MIMEText(fin.read(), 'base64', 'utf-8')\n att[\"Content-Type\"] = 'application/octet-stream'\n att[\"Content-Disposition\"] = 'attachment; filename=\"logo.png\"'\n msg.attach(att) \n \n with open('logo.png', 'rb') as fp:\n msgImage = MIMEImage(fp.read())\n \n msgImage.add_header('Content-ID', 'image1')\n msg.attach(msgImage) \n \n \n return msg.as_string()\n \ndef create_mime_text():\n msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8',单字节字符不需要\n subject = 'python email test'\n msg['Subject'] = Header(subject, 'utf-8')\n # msg['From'] = ''\n # msg['To'] = ''\n \n return msg.as_string()\n \ndef create_gmail_smtp(config):\n # http://stackoverflow.com/questions/9216127/smtp-auth-extension-not-supported-by-server-in-python-2-4\n s=smtplib.SMTP()\n s.connect(\"smtp.gmail.com\",465)\n s.ehlo()\n s.starttls()\n s.ehlo()\n s.login(config['username'], config['password'])\n \ndef create_qq_smtp(config):\n smtp = smtplib.SMTP_SSL(\"smtp.qq.com\", 465)\n smtp.login(config['username'], config['password'])\n return s\n \ndef create_163_smtp(config):\n smtp = smtplib.SMTP()\n smtp.connect('smtp.163.com')\n smtp.ehlo()\n smtp.starttls()\n smtp.ehlo()\n smtp.set_debuglevel(1)\n smtp.login(config['username'], config['password'])\n \n return smtp\n\ndef create_fake_smtp(config):\n server = smtplib.SMTP(timeout=10)\n server.set_debuglevel(1)\n server.connect(config['host'], config['port'])\n return server\n \nd = yaml.load(file('account.yaml'))\ntry:\n server = create_fake_smtp(d['dev'])\n server.login('guest', '1234')\n sender = 'admin@example.com'\n receiver = 'guest@example.com'\n server.sendmail(sender, receiver, create_mime_text())\n server.sendmail(sender, receiver, create_mime_image())\n server.sendmail(sender, receiver, create_mime_alternative())\n server.quit()\nexcept smtplib.SMTPException as ex:\n print(ex)","sub_path":"009_Net/smtp/test_smtplib.py","file_name":"test_smtplib.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"537658671","text":"\"\"\"\nMap words into vectors using different algorithms such as TF-IDF, word2vec or GloVe.\n\"\"\"\n\nimport pandas as pd\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA, NMF\nfrom sklearn.cluster import KMeans, DBSCAN, MeanShift\nfrom sklearn.metrics.pairwise import cosine_similarity\n\nfrom typing import Optional\n\nimport logging\n\nlogging.getLogger(\"gensim\").setLevel(logging.WARNING)\n\nfrom gensim.models import Word2Vec\n\n# from texthero import pandas_ as pd_\n\"\"\"\nVectorization\n\"\"\"\n\n\ndef term_frequency(\n s: pd.Series, max_features: Optional[int] = None, return_feature_names=False\n):\n \"\"\"\n Represent a text-based Pandas Series using term_frequency.\n\n Parameters\n ----------\n s : Pandas Series\n max_features : int, optional\n Maximum number of features to keep.\n return_features_names : Boolean, False by Default\n If True, return a tuple (*term_frequency_series*, *features_names*)\n\n\n Examples\n --------\n >>> import texthero as hero\n >>> import pandas as pd\n >>> s = pd.Series([\"Sentence one\", \"Sentence two\"])\n >>> hero.term_frequency(s)\n 0 [1, 1, 0]\n 1 [1, 0, 1]\n dtype: object\n \n To return the features_names:\n \n >>> import texthero as hero\n >>> import pandas as pd\n >>> s = pd.Series([\"Sentence one\", \"Sentence two\"])\n >>> hero.term_frequency(s, return_feature_names=True)\n (0 [1, 1, 0]\n 1 [1, 0, 1]\n dtype: object, ['Sentence', 'one', 'two'])\n\n \"\"\"\n # TODO. Can be rewritten without sklearn.\n tf = CountVectorizer(\n max_features=max_features, lowercase=False, token_pattern=\"\\S+\"\n )\n s = pd.Series(tf.fit_transform(s).toarray().tolist(), index=s.index)\n\n if return_feature_names:\n return (s, tf.get_feature_names())\n else:\n return s\n\n\ndef tfidf(s: pd.Series, max_features=None, min_df=1, return_feature_names=False):\n \"\"\"\n Represent a text-based Pandas Series using TF-IDF.\n\n Parameters\n ----------\n s : Pandas Series\n max_features : int, optional\n Maximum number of features to keep.\n min_df : int, optional. Default to 1.\n When building the vocabulary ignore terms that have a document frequency strictly lower than the given threshold.\n return_features_names : Boolean. Default to False.\n If True, return a tuple (*tfidf_series*, *features_names*)\n\n\n Examples\n --------\n >>> import texthero as hero\n >>> import pandas as pd\n >>> s = pd.Series([\"Sentence one\", \"Sentence two\"])\n >>> hero.tfidf(s)\n 0 [0.5797386715376657, 0.8148024746671689, 0.0]\n 1 [0.5797386715376657, 0.0, 0.8148024746671689]\n dtype: object\n \n To return the *feature_names*:\n \n >>> import texthero as hero\n >>> import pandas as pd\n >>> s = pd.Series([\"Sentence one\", \"Sentence two\"])\n >>> hero.tfidf(s, return_feature_names=True)\n (0 [0.5797386715376657, 0.8148024746671689, 0.0]\n 1 [0.5797386715376657, 0.0, 0.8148024746671689]\n dtype: object, ['Sentence', 'one', 'two'])\n \"\"\"\n\n # TODO. In docstring show formula to compute TF-IDF and also avoid using sk-learn if possible.\n\n tfidf = TfidfVectorizer(\n use_idf=True,\n max_features=max_features,\n min_df=min_df,\n token_pattern=\"\\S+\",\n lowercase=False,\n )\n s = pd.Series(tfidf.fit_transform(s).toarray().tolist(), index=s.index)\n\n if return_feature_names:\n return (s, tfidf.get_feature_names())\n else:\n return s\n\n\n\"\"\"\nDimensionality reduction\n\"\"\"\n\n\ndef pca(s, n_components=2):\n \"\"\"\n Perform principal component analysis on the given Pandas Series.\n\n In general, *pca* should be called after the text has already been represented.\n\n Parameters\n ----------\n s : Pandas Series\n n_components : Int. Default is 2.\n Number of components to keep. If n_components is not set or None, all components are kept.\n\n Examples\n --------\n >>> import texthero as hero\n >>> import pandas as pd\n >>> s = pd.Series([\"Sentence one\", \"Sentence two\"])\n \n \"\"\"\n pca = PCA(n_components=n_components)\n return pd.Series(pca.fit_transform(list(s)).tolist(), index=s.index)\n\n\ndef nmf(s, n_components=2):\n \"\"\"\n Perform non-negative matrix factorization.\n\n \n \"\"\"\n nmf = NMF(n_components=n_components, init=\"random\", random_state=0)\n return pd.Series(nmf.fit_transform(list(s)).tolist(), index=s.index)\n\n\ndef tsne(\n s: pd.Series,\n n_components=2,\n perplexity=30.0,\n early_exaggeration=12.0,\n learning_rate=200.0,\n n_iter=1000,\n n_iter_without_progress=300,\n min_grad_norm=1e-07,\n metric=\"euclidean\",\n init=\"random\",\n verbose=0,\n random_state=None,\n method=\"barnes_hut\",\n angle=0.5,\n n_jobs=-1,\n):\n \"\"\"\n Perform TSNE on the given pandas series.\n\n Parameters\n ----------\n s : Pandas Series\n n_components : int, default is 2.\n Number of components to keep. If n_components is not set or None, all components are kept.\n perplexity : int, default is 30.0\n\n \"\"\"\n tsne = TSNE(\n n_components=n_components,\n perplexity=perplexity,\n early_exaggeration=early_exaggeration,\n learning_rate=learning_rate,\n n_iter=n_iter,\n n_iter_without_progress=n_iter_without_progress,\n min_grad_norm=min_grad_norm,\n metric=metric,\n init=init,\n verbose=verbose,\n random_state=random_state,\n method=method,\n angle=angle,\n n_jobs=n_jobs,\n )\n return pd.Series(tsne.fit_transform(list(s)).tolist(), index=s.index)\n\n\n\"\"\"\nClustering\n\"\"\"\n\n\ndef kmeans(\n s: pd.Series,\n n_clusters=5,\n init=\"k-means++\",\n n_init=10,\n max_iter=300,\n tol=0.0001,\n precompute_distances=\"auto\",\n verbose=0,\n random_state=None,\n copy_x=True,\n n_jobs=-1,\n algorithm=\"auto\",\n):\n \"\"\"\n Perform K-means clustering algorithm.\n \"\"\"\n vectors = list(s)\n kmeans = KMeans(\n n_clusters=n_clusters,\n init=init,\n n_init=n_init,\n max_iter=max_iter,\n tol=tol,\n precompute_distances=precompute_distances,\n verbose=verbose,\n random_state=random_state,\n copy_x=copy_x,\n n_jobs=n_jobs,\n algorithm=algorithm,\n ).fit(vectors)\n return pd.Series(kmeans.predict(vectors), index=s.index)\n\n\ndef dbscan(\n s,\n eps=0.5,\n min_samples=5,\n metric=\"euclidean\",\n metric_params=None,\n algorithm=\"auto\",\n leaf_size=30,\n p=None,\n n_jobs=None,\n):\n \"\"\"\n Perform DBSCAN clustering.\n \"\"\"\n\n return pd.Series(\n DBSCAN(\n eps=eps,\n min_samples=min_samples,\n metric=metric,\n metric_params=metric_params,\n algorithm=algorithm,\n leaf_size=leaf_size,\n p=p,\n n_jobs=n_jobs,\n ).fit_predict(list(s)),\n index=s.index,\n )\n\n\ndef meanshift(\n s,\n bandwidth=None,\n seeds=None,\n bin_seeding=False,\n min_bin_freq=1,\n cluster_all=True,\n n_jobs=None,\n max_iter=300,\n):\n \"\"\"\n Perform mean shift clustering.\n \"\"\"\n\n return pd.Series(\n MeanShift(\n bandwidth=bandwidth,\n seeds=seeds,\n bin_seeding=bin_seeding,\n min_bin_freq=min_bin_freq,\n cluster_all=cluster_all,\n n_jobs=n_jobs,\n max_iter=max_iter,\n ).fit_predict(list(s)),\n index=s.index,\n )\n\n\n\"\"\"\nTopic modelling\n\"\"\"\n\n# TODO.\n\n\"\"\"\nWord2Vec\n\"\"\"\n\n\ndef word2vec(\n s: pd.Series,\n size=300,\n algorithm: str = \"cbow\",\n num_epochs: int = 30,\n min_count: int = 5,\n window_size: int = 5,\n alpha: float = 0.03,\n max_vocab_size: int = None,\n downsample_freq: float = 0.0001,\n min_alpha: float = 0.0001,\n negative_samples: int = 5,\n workers: int = None,\n seed: int = None,\n):\n \"\"\"Perform Word2vec on the given Pandas Series\n \n Return a Pandas Dataframe of shape (vocabulary_size, vectors_size).\n\n Word2vec is a two-layer neural network used to map each word to its vector representation. In general, its input is a text corpus and its output is a set of vectors: feature vectors that represent words in that corpus. In this specific case, the input is a Pandas Series containing in each cell a tokenized text and the output is a Pandas DataFrame where indexes are words and columns are the vector dimensions.\n\n Under the hoods, this function makes use of Gensim Word2Vec module.\n \n Parameters\n ----------\n s : Pandas Series\n size : int, optional, default is 300\n Size of the returned vector. A good values is anything between 100-300. For very large dataset, a smaller values requires less training time.\n algorithm : str, optional, default is \"cbow\".\n The training algorithm. It can be either \"skipgram\" or \"cbow\". \n With CBOW (continuous bag-of-words) the model predicts the current word from a window of surrounding context words. \n In the continuous skip-gram mode, the model uses the current word to predict the surrounding window of context words.\n According to the authors, CBOW is faster while skip-gram is slower but does a better job for infrequent words.\n num_epochs : int, optional, default is 30\n Number of epochs to train the model.\n min_count : int, optional, default is 5\n Keep only words with a frequency equal or higher than min_count.\n window_size : int, optional, default is 5\n Surrounding window size of context words.\n alpha : float, optional, default is 0.03\n Initial learning rate\n max_vocab_size : int, optional, default to None\n Maximum number of words to keep. This corresponds to the length of the returned DataFrame. \n downsample_freq : float, optional, default to 0.0001 (10^-4)\n Threshold frequency to downsample very frequent words. The results is similar to remove stop-words. The random removal of tokens is executed before word2vec is executed, reducing the distance between words. \n min_alpha : float, default to 0.0001 (10^-4)\n The learning rate will drop linearly to min_alpha during training.\n negative_samples : int, optional, 5 by default\n Number of negative samples to use. Negative sampling addresses \n the problem of avoding updating all weights at each epoch. It does so by selecting and modifing during each epoch only a small percentage of the total weights.\n\n The authors of the paper suggests to set negative sampling to 5-20 words for smaller datasets, and 2-5 words for large datasets.\n workers : int, optional, None by default.\n For improved performance, by default use all available computer workers. When set, use the same number of cpu.\n seed : int, optional, None by default.\n Seed for the random number generator. All vectors are initialized randomly using an hash function formed by the concatenation of the word itself and str(seed). Important: for a fully deterministically-reproducible run, you must set the model to run on a single worker thread (workers=1).\n\n See Also\n --------\n `Word2Vec Tutorial - The Skip-Gram Model `_ and `Word2Vec Tutorial Part 2 - Negative Sampling `_ for two great tutorial on Word2Vec\n\n \"\"\"\n\n if algorithm == \"cbow\":\n sg = 0\n elif algorithm == \"skipgram\":\n sg = 1\n else:\n raise ValueError(\"algorithm must be either 'cbow' or 'skipgram'\")\n\n w2v_model = Word2Vec(\n size=size,\n min_count=min_count,\n window=window_size,\n alpha=alpha,\n max_vocab_size=max_vocab_size,\n sample=downsample_freq,\n seed=seed,\n min_alpha=min_alpha,\n negative=negative_samples,\n sg=sg,\n )\n\n w2v_model.build_vocab(s.values, progress_per=10000)\n\n if len(w2v_model.wv.vocab.keys()) == 0:\n print(\"Vocabulary ...\")\n\n w2v_model.train(\n s.values,\n total_examples=w2v_model.corpus_count,\n epochs=num_epochs,\n report_delay=1,\n )\n\n all_vocabulary = sorted(list(set(w2v_model.wv.vocab.keys())))\n\n return pd.DataFrame(data=w2v_model.wv[all_vocabulary], index=all_vocabulary)\n\n\ndef most_similar(df_embedding: pd.DataFrame, to: str) -> pd.Series:\n \"\"\"\n Find most similar words to *to* for the given df_embedding.\n\n Given a Pandas DataFrame representing a word embedding, where each index is a word and the size of the dataframe corresponds to the length of the word vectors, return a Pandas Series containing as index the words and as value the cosine distance between *to* and the word itself.\n\n Parameters\n ----------\n df_embeddings: Pandas DataFrame\n to: str\n Word to find the most similar words to. That word must be in the DataFrame index.\n \n \"\"\"\n\n if type(df_embedding) != pd.DataFrame:\n raise ValueError(\n \"The first argument of most_similar must be a Pandas Dataframe representing a word embedding.\"\n )\n\n if to not in df_embedding.index:\n raise ValueError(\n f\"Argument to={to} is not present in the index of the passed DataFrame.\"\n )\n\n return pd.Series(\n cosine_similarity(\n df_embedding, df_embedding.loc[to].to_numpy().reshape(1, -1)\n ).reshape(1, -1)[0],\n index=df_embedding.index,\n ).sort_values(ascending=True)\n","sub_path":"texthero/representation.py","file_name":"representation.py","file_ext":"py","file_size_in_byte":13549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"490098336","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#Created Time: 2015/8/25 17:46:50\r\n#author: Cactus\r\nimport threading\r\nimport time\r\n# from myemail import Myemail\r\n\r\nclass Msg_Thread(threading.Thread):\r\n\r\n def __init__(self, log, email, msg_queue):\r\n threading.Thread.__init__(self)\r\n self.timeToQuit = threading.Event()\r\n self.timeToQuit.clear()\r\n self.log = log\r\n self.q = msg_queue\r\n self.identity = ''\r\n self.email = email\r\n # self.init()\r\n\r\n def init(self):\r\n self.mail_server = {'host':\"mail.test.cn\",\r\n 'port':25}\r\n self.mail_sender = {'address':'123@test.cn',\r\n 'user':'123',\r\n 'password':'******',\r\n 'header_from':'系统提醒'}\r\n self.email = Myemail(self.mail_server, self.mail_sender, [])\r\n\r\n \r\n def stop(self):\r\n self.timeToQuit.set()\r\n self.log.debug('thread %s stop' % self.identity)\r\n\r\n def setIdentity(self, text):\r\n self.identity = text\r\n\r\n def work_sendmail(self, msgdata):\r\n subject, receivers, msg = msgdata\r\n self.log.debug('receivers:%s,subject:%s,msg:%s'%(receivers,subject,msg))\r\n # self.email.setReceivers(receivers.split(','))\r\n self.email.setReceivers(receivers)\r\n self.email.sendmail(subject, msg)\r\n\r\n def work_log(self, data):\r\n try:\r\n loglevel, msg = data\r\n func = {'debug':self.log.debug, 'info':self.log.info,\r\n 'warning':self.log.warning, 'error':self.log.error,\r\n 'critical':self.log.critical,\r\n 'exception':self.log.exception}\r\n func.get(loglevel,self.log.debug)(msg)\r\n except:\r\n self.log.trace()\r\n\r\n def work(self):\r\n self.log.debug('thread %s work begin' % self.identity)\r\n func = {'log':self.work_log, 'email':self.work_sendmail}\r\n while True:\r\n try:\r\n if self.timeToQuit.isSet():\r\n self.log.debug('thread %s stop by user' % self.identity)\r\n break\r\n msg_flag, msg_data = self.q.get(True)\r\n self.log.debug('msg_thread :%s'%str((msg_flag,msg_data)))\r\n func.get(msg_flag)(msg_data)\r\n except:\r\n self.log.trace()\r\n self.log.debug('thread %s work end' % self.identity)\r\n\r\n def run(self):\r\n self.log.debug('thread %s begin' % self.identity)\r\n self.work()\r\n\r\nif __name__ == '__main__':\r\n import log\r\n import os\r\n # import myxml\r\n # config = myxml.get_sysconfig_from_xml()\r\n # data = myxml.get_task_from_xml()\r\n import myxml2\r\n config = myxml2.get_sysconfig_from_xml()\r\n data = myxml2.get_task_from_xml()\r\n mylog = log.Log()\r\n work = Work_Thread(mylog, config, data)\r\n work.setIdentity(\"Work_Thread\")\r\n work.setDaemon(True)\r\n work.start()\r\n\r\n","sub_path":"process_msg_thread.py","file_name":"process_msg_thread.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"528670856","text":"from django.shortcuts import render\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.management import call_command\nfrom django.apps import apps\nfrom django.http import JsonResponse\nfrom django.utils.dateparse import parse_date\nfrom django.contrib.auth.models import User\n# from ..actions.utils import create_action\n\n\ndef home(request):\n title = _('Core App')\n return render(request, 'core/home.html', {'title': title})\n\n\ndef post_ajax_create_action(request):\n try:\n obj = None\n if request.POST.get('model') and request.POST.get('model') != \"\":\n app_ = request.POST.get('app')\n model_ = request.POST.get('model')\n model = apps.get_model(app_label=app_, model_name=model_)\n try:\n obj_slug = request.POST.get('obj_slug')\n # print(obj_slug)\n obj = model.objects.filter(translations__language_code=get_language()).filter(translations__slug=obj_slug).all()[0]\n except Exception as er:\n pkey_ = request.POST.get('pkey')\n obj = model.objects.get(id=pkey_)\n\n verb_ = request.POST.get('verb')\n create_action(request.user, verb_, obj)\n except Exception as err:\n JsonResponse({'status': 'ko'})\n return JsonResponse({'status': 'ok'})\n\n\ndef update_field_model(request):\n app_ = request.POST.get('app')\n model_ = request.POST.get('model')\n pkey_ = request.POST.get('pkey')\n value_ = request.POST.get('value')\n field_ = request.POST.get('field')\n type_ = request.POST.get('type')\n # print('1-'*20)\n # print(value_)\n # print(model_)\n # print(pkey_)\n # print('1-'*20)\n # print('2-'*20)\n # print(field_)\n # print('2-'*20)\n model = apps.get_model(app_label=app_, model_name=model_)\n try:\n obj_slug = request.POST.get('obj_slug')\n # print(obj_slug)\n obj = model.objects.filter(translations__language_code=get_language()).filter(translations__slug=obj_slug).all()[0]\n except Exception as er:\n obj = model.objects.get(id=pkey_)\n # print(obj)\n # print('3-'*20)\n # print(type_)\n # print('4-'*20)\n if type_ == \"checkbox\":\n if value_ == 'true':\n value_ = True\n else:\n value_ = False\n elif type_ == \"date\":\n value_ = parse_date(value_)\n elif type_ == \"multiple_select\":\n value_ = value_.split(\",\")\n for k in obj.instructors.all():\n obj.instructors.remove(k)\n for i in value_:\n u_ins = User.objects.get(id=int(i))\n obj.instructors.add(u_ins)\n return JsonResponse({'status': 'ok'})\n try:\n # print(value_)\n s = 'obj.' + field_ + ' = value_'\n # print(s)\n # print('-'*30)\n # print(s)\n # print('-'*30)\n exec(s)\n obj.save()\n if model_ == \"Game\" and field_ == \"number_of_periods\":\n obj.get_schedule_period_dates\n return JsonResponse({'status': 'ok'})\n except Exception as e:\n # print('-'*30)\n # print(\"err\")\n # print(e)\n # print(\"err\")\n # print('-'*30)\n pass\n return JsonResponse({'status': 'ko'})\n\n\ndef create_db_backup():\n call_command('dbbackup', compress=True, clean=True)\n\n\ndef clean_registrations(request):\n clean_accounting_registrations()\n\n\n","sub_path":"highschooledu/highschooledu/apps/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"157692487","text":"# The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power.\n\n# How many n-digit positive integers exist which are also an nth power?\n\ncount = 0\n\na = 1\nb = 1\n\ndigPow = str(a**b)\na = 1\nwhile len(digPow) <= b:\n if len(digPow) == b:\n count += 1\n digPow = str(a**b)\n a += 1","sub_path":"p0063.py","file_name":"p0063.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"651399036","text":"\"\"\"users table\n\nRevision ID: b6dff5751433\nRevises: a3b825827cd5\nCreate Date: 2020-02-04 14:10:49.954415\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b6dff5751433'\ndown_revision = 'a3b825827cd5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('poem',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(length=64), nullable=True),\n sa.Column('author', sa.String(), nullable=True),\n sa.Column('root', sa.String(), nullable=True),\n sa.Column('text', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_poem_author'), 'poem', ['author'], unique=False)\n op.create_index(op.f('ix_poem_title'), 'poem', ['title'], unique=False)\n op.drop_index('ix_poem_data_author', table_name='poem_data')\n op.drop_index('ix_poem_data_title', table_name='poem_data')\n op.drop_table('poem_data')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('poem_data',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('title', sa.VARCHAR(length=64), nullable=True),\n sa.Column('author', sa.VARCHAR(), nullable=True),\n sa.Column('root', sa.VARCHAR(), nullable=True),\n sa.Column('text', sa.VARCHAR(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index('ix_poem_data_title', 'poem_data', ['title'], unique=False)\n op.create_index('ix_poem_data_author', 'poem_data', ['author'], unique=False)\n op.drop_index(op.f('ix_poem_title'), table_name='poem')\n op.drop_index(op.f('ix_poem_author'), table_name='poem')\n op.drop_table('poem')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/b6dff5751433_users_table.py","file_name":"b6dff5751433_users_table.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"365433492","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport argparse\nimport operator\nimport subprocess\n\n# argument parser\nparser = argparse.ArgumentParser(prog=\"augustus-to-gbrowse.py\", description='''\n\n\nMatteo Schiavinato\n2016\nBOKU - Vienna Institute of Biotechnology\n\nThe program will take in input the raw output from Augustus, either GFF or GFF3, and prepare it for GBrowse.\n\n\n''')\nparser.add_argument(\"-i\", \"--input-file\", help=\"The input file. It can either be a GFF or a GFF3 file but it must be the raw output from Augustus.\", required=True)\nparser.add_argument(\"-o\", \"--output-file\", help=\"The output file. This has to be [file].gff3\", required=True)\nparser.add_argument(\"-f\", \"--file-format\", help=\"specify if the file is \\\"gff\\\" or \\\"gff3\\\" to let the program do the correct analyses.\", required=True)\nparser.add_argument(\"--reference\", help=\"Provide the reference FASTA file that you used to produce the Augustus output GFF / GFF3 file.\", required=True)\nparser.add_argument(\"--repeats\", help=\"Provide the eventual repeats file. This program supports only RepeatMasker *.out file as input for repeats, or an already standardized GFF3 file describing repeats, that will be just concatenated and sorted together.\")\nparser.add_argument(\"--repmask-out\", action=\"store_true\", help=\"Specify this parameter if your repeats file is the RepeatMasker *.out file. Otherwise, don't use this parameter and make sure to provide a valid GFF3 file containing repeats lines. It will not be checked and just added.\")\nargs = parser.parse_args()\n\n# conversion from gff to gff3 with mRNA instead of transcript in the feature field \nif args.file_format == \"gff\":\n\tsys.stderr.write(\"Converting GFF format to GFF3 format...\")\n\tINPUT = open(args.input_file, \"r\")\n\tgenes = {}\n\tfor line in INPUT:\n\t\t# selecting only lines without \"#\"\n\t\t## not losing the evidence level \n\t\tif line[0:1] != \"#\":\n\t\t\tline_list = line.rstrip().split(\"\\t\")\n\t\t\tif line_list[2] == \"gene\":\n\t\t\t\tgene_name = line_list[8].rstrip()\n\t\t\t\tgenes[gene_name] = {}\n\t\t\t\t#\n\t\t\telif line_list[2] == \"transcript\":\n\t\t\t\ttranscript_name = line_list[8].rstrip()\n\t\t\t\tgenes[gene_name][transcript_name] = {\"evidence\":None, \"start_codon\":0, \"stop_codon\":0}\n\t\t\t\tstartstop = 0\n\t\t\t\t#\n\t\t\telif line_list[2] == \"start_codon\":\n\t\t\t\tfield9list = line_list[8].split(\"; \")\n\t\t\t\tfield9dic = {}\n\t\t\t\tfor element in field9list:\n\t\t\t\t\tfield9dic[element.split(\" \")[0]] = element.split(\" \")[1].strip(\"\\\";\")\n\t\t\t\t\t#\n\t\t\t\tgene_name = field9dic[\"gene_id\"]\n\t\t\t\ttranscript_name = field9dic[\"transcript_id\"]\n\t\t\t\ttry:\n\t\t\t\t\tgenes[gene_name][transcript_name]\n\t\t\t\t\t#\n\t\t\t\texcept KeyError:\n\t\t\t\t\tgenes[gene_name] = {transcript_name:{\"evidence\":None, \"start_codon\":0, \"stop_codon\":0}}\n\t\t\t\t\t#\n\t\t\t\tgenes[gene_name][transcript_name][\"start_codon\"] = 1\n\t\t\t\t#\n\t\t\telif line_list[2] == \"stop_codon\":\n\t\t\t\tfield9list = line_list[8].split(\"; \")\n\t\t\t\tfield9dic = {}\n\t\t\t\tfor element in field9list:\n\t\t\t\t\tfield9dic[element.split(\" \")[0]] = element.split(\" \")[1].strip(\"\\\";\")\n\t\t\t\t\t#\n\t\t\t\tgene_name = field9dic[\"gene_id\"]\n\t\t\t\ttranscript_name = field9dic[\"transcript_id\"]\n\t\t\t\ttry:\n\t\t\t\t\tgenes[gene_name][transcript_name]\n\t\t\t\t\t#\n\t\t\t\texcept KeyError:\n\t\t\t\t\tgenes[gene_name] = {transcript_name:{\"evidence\":None, \"start_codon\":0, \"stop_codon\":0}}\n\t\t\t\t\t#\n\t\t\t\tgenes[gene_name][transcript_name][\"stop_codon\"] = 1\n\t\t\t\t#\n\t\telif line[0:36] == \"# % of transcript supported by hints\":\n\t\t\tevidence = float(line.rstrip().split(\": \")[1])\n\t\t\ttry:\n\t\t\t\tgenes[gene_name][transcript_name]\n\t\t\texcept KeyError:\n\t\t\t\tgenes[gene_name][transcript_name] = {transcript_name:{\"evidence\":None, \"start_codon\":0, \"stop_codon\":0}}\n\t\t\t\t#\n\t\t\tgenes[gene_name][transcript_name][\"evidence\"] = evidence\n\t\t\t#\n\tINPUT.close()\n\t#\n\tselected_genes = {}\n\tfor gene in genes:\n\t\tfor transcript in genes[gene]:\n\t\t\tif genes[gene][transcript][\"evidence\"] >= 1:\n\t\t\t\ttry:\n\t\t\t\t\tselected_genes[gene][transcript] = genes[gene][transcript][\"evidence\"]\n\t\t\t\t\t#\n\t\t\t\texcept KeyError:\n\t\t\t\t\tselected_genes[gene] = {transcript:genes[gene][transcript][\"evidence\"]}\n\t\t\t\t\t#\n\tgene_switch = \"off\"\n\ttranscript_switch = \"off\"\n\tenabled_gene = None\n\tenabled_transcript = None\n\tINPUT = open(args.input_file, \"r\")\n\tOUTPUT = open(\"temp\", \"w\")\n\tfor line in INPUT:\n\t\tif line[0:1] != \"#\":\n\t\t\tline_list = line.rstrip().split(\"\\t\")\n\t\t\tif line_list[2] == \"gene\":\n\t\t\t\tgene_switch = \"off\"\n\t\t\t\tgene_name = line_list[8].rstrip()\n\t\t\t\tif gene_name in selected_genes.keys():\n\t\t\t\t\tgene_switch = \"on\"\n\t\t\t\t\tenabled_gene = gene_name\n\t\t\t\t\tline_list[8] = \"ID={0};Name={0}\".format(gene_name)\n\t\t\t\t\tprint >>OUTPUT, \"\\t\".join(line_list)\n\t\t\t\t\t#\n\t\t\telif line_list[2] == \"transcript\":\n\t\t\t\ttranscript_switch = \"off\"\n\t\t\t\tif gene_switch == \"on\":\n\t\t\t\t\ttranscript_name = line_list[8].rstrip()\n\t\t\t\t\tgene_name = transcript_name.split(\".\")[0]\n\t\t\t\t\tif transcript_name in selected_genes[gene_name].keys():\n\t\t\t\t\t\ttranscript_switch = \"on\"\n\t\t\t\t\t\tenabled_transcript = transcript_name\n\t\t\t\t\t\tline_list[8] = \"ID={0};Name={0};Parent={1};Note=evidence_{2}%\".format(transcript_name, gene_name, selected_genes[gene_name][transcript_name])\n\t\t\t\t\t\tline_list[2] = \"mRNA\"\n\t\t\t\t\t\tprint >>OUTPUT, \"\\t\".join(line_list)\n\t\t\t\t\t\t#\n\t\t\telse:\n\t\t\t\tfield9list = line_list[8].split(\"; \")\n\t\t\t\tfield9dic = {}\n\t\t\t\tfor element in field9list:\n\t\t\t\t\tfield9dic[element.split(\" \")[0]] = element.split(\" \")[1].strip(\"\\\";\")\n\t\t\t\t\t#\n\t\t\t\tif (field9dic[\"gene_id\"] == enabled_gene) and (field9dic[\"transcript_id\"] == enabled_transcript):\n\t\t\t\t\tline_list[8] = \"ID={0}.{1};Name={0}.{1};Parent={0}\".format(field9dic[\"transcript_id\"], line_list[2])\n\t\t\t\t\tprint >>OUTPUT, \"\\t\".join(line_list)\n\t\t\t\t\t#\n\t#\n\tOUTPUT.close()\n\tINPUT.close()\n\tsys.stderr.write(\"Sorting...\")\n\tsubprocess.call(\"cat temp | sort -sk1,1 -k4n,4 -k5nr,5 > temp.out ; cp temp.out temp ; rm temp.out\", shell=True)\n\tsys.stderr.write(\"Done.\\n\")\n\tdel genes\n\tdel selected_genes\n\t#\nelif args.file_format == \"gff3\":\n\tsys.stderr.write(\"Checking if field \\\"feature\\\" is ready for GBrowse...\")\n\tINPUT = open(args.input_file, \"r\")\n\tOUTPUT = open(\"temp\", \"w\")\n\tfor line in INPUT:\n\t\tif line[0:1] != \"#\":\n\t\t\tline_list = line.rstrip().split(\"\\t\")\n\t\t\tif line_list[2] == \"transcript\":\n\t\t\t\tline_list[2] = \"mRNA\"\n\t\t\t\tprint >>OUTPUT, \"\\t\".join(line_list)\n\t\t\t\t#\n\t\t\telse:\n\t\t\t\tprint >>OUTPUT, line.rstrip()\n\t\t\t\t#\n\tsys.stderr.write(\"Done.\\n\")\n\tOUTPUT.close()\n\tINPUT.close()\n\t#\nelse:\n\tsys.exit(\"ERROR: you didn't specify a correct file format. It must be either \\\"gff\\\" or \\\"gff3\\\".\\n\")\n\t#\n\n\n## conversion from exon to UTR starts here\n\n# sort the file according to contig, start and end position\nsys.stderr.write(\"Sorting input file to increase read speed...\")\nsubprocess.call(\"sort -sk1,1 -k4n,4 -k5nr,5 temp > temp.in\", shell=True)\nsys.stderr.write(\"Done.\\n\")\n\n# reading data from sorted input\nsys.stderr.write(\"Converting \\\"exon\\\" feature to \\\"UTR\\\" [3' and 5']...\")\ntranscripts = {}\nINPUT = open(\"temp.in\", \"r\")\nOUTPUT = open(\"temp.out\", \"w\")\nfor line in INPUT:\n\tif line[0:1] != \"#\":\n\t\tline_list = line.rstrip().split(\"\\t\")\n\t\tif line_list[2] == \"mRNA\":\n\t\t\tf9list = line_list[8].split(\";\")\n\t\t\tf9dic = {}\n\t\t\tfor element in f9list:\n\t\t\t\tf9dic[element.split(\"=\")[0]] = element.split(\"=\")[1]\n\t\t\t\t#\n\t\t\ttranscript_name = f9dic[\"ID\"]\n\t\t\ttranscripts[transcript_name] = {\"CDS\":[], \"exons\":[], \"strand\":line_list[6]}\n\t\t\tprint >>OUTPUT, line.rstrip()\n\t\t\t#\n\t\telif line_list[2] == \"CDS\":\n\t\t\tstart = int(line_list[3])\n\t\t\tend = int(line_list[4])\n\t\t\tstrand = line_list[6]\n\t\t\tf9list = line_list[8].split(\";\")\n\t\t\tf9dic = {}\n\t\t\tfor element in f9list:\n\t\t\t\tf9dic[element.split(\"=\")[0]] = element.split(\"=\")[1]\n\t\t\t\t#\n\t\t\ttranscript_name = f9dic[\"Parent\"]\n\t\t\ttry:\n\t\t\t\ttranscripts[transcript_name]\n\t\t\texcept KeyError:\n\t\t\t\ttranscripts[transcript_name] = {\"strand\":strand}\n\t\t\t\t#\n\t\t\ttry:\n\t\t\t\ttranscripts[transcript_name][\"CDS\"]\n\t\t\texcept KeyError:\n\t\t\t\ttranscripts[transcript_name][\"CDS\"] = []\n\t\t\t\t#\n\t\t\ttranscripts[transcript_name][\"CDS\"].append((start, end, line.rstrip()))\n\t\t\tprint >>OUTPUT, line.rstrip()\n\t\t\t#\n\t\telif line_list[2] == \"exon\":\n\t\t\tstart = int(line_list[3])\n\t\t\tend = int(line_list[4])\n\t\t\tline_list[6]\n\t\t\tf9list = line_list[8].split(\";\")\n\t\t\tf9dic = {}\n\t\t\tfor element in f9list:\n\t\t\t\tf9dic[element.split(\"=\")[0]] = element.split(\"=\")[1]\n\t\t\t\t#\n\t\t\ttranscript_name = f9dic[\"Parent\"]\n\t\t\ttry:\n\t\t\t\ttranscripts[transcript_name]\n\t\t\texcept KeyError:\n\t\t\t\ttranscripts[transcript_name] = {\"strand\":strand}\n\t\t\t\t#\n\t\t\ttry:\n\t\t\t\ttranscripts[transcript_name][\"exons\"]\n\t\t\texcept KeyError:\n\t\t\t\ttranscripts[transcript_name][\"exons\"] = []\n\t\t\t\t#\n\t\t\ttranscripts[transcript_name][\"exons\"].append((start, end, line.rstrip()))\n\t\t\t#\n\t\telse:\n\t\t\tprint >>OUTPUT, line.rstrip()\n\t\t\t#\n#\nINPUT.close()\nsys.stderr.write(\"Done.\\n\")\n\n# sorting dictionary\nsorted_transcripts = {}\nfor transcript in transcripts:\n\tsorted_transcripts[transcript] = {\"CDS\":sorted(transcripts[transcript][\"CDS\"], key=operator.itemgetter(0)), \"exons\":sorted(transcripts[transcript][\"exons\"], key=operator.itemgetter(0)), \"strand\":transcripts[transcript][\"strand\"]}\n\t#\n\n# assigning 3' or 5' and writing to output\nsys.stderr.write(\"Assigning 3' or 5'...\")\nfor transcript in sorted_transcripts:\n\tif sorted_transcripts[transcript][\"strand\"] == \"+\":\n\t\tif len(sorted_transcripts[transcript][\"exons\"]) == 1:\n\t\t\t#five_prime_UTR\n\t\t\tstart = int(sorted_transcripts[transcript][\"exons\"][0][0])\n\t\t\tend = int(sorted_transcripts[transcript][\"CDS\"][0][0])-1\n\t\t\tline_model_list = sorted_transcripts[transcript][\"exons\"][0][2].split(\"\\t\")\n\t\t\tline_model_list[2] = \"five_prime_UTR\"\n\t\t\tline_model_list[3] = str(start)\n\t\t\tline_model_list[4] = str(end)\n\t\t\tline_model_list[8] = \"ID={0}.five_prime_UTR;Name={0}.five_prime_UTR;Parent={0}\".format(transcript)\n\t\t\tprint >>OUTPUT, \"\\t\".join(line_model_list)\n\t\t\t#three_prime_UTR\n\t\t\tstart = int(sorted_transcripts[transcript][\"CDS\"][-1][1])+1\n\t\t\tend = int(sorted_transcripts[transcript][\"exons\"][-1][1])\n\t\t\tline_model_list = sorted_transcripts[transcript][\"exons\"][0][2].split(\"\\t\")\n\t\t\tline_model_list[2] = \"three_prime_UTR\"\n\t\t\tline_model_list[3] = str(start)\n\t\t\tline_model_list[4] = str(end)\n\t\t\t#\n\t\t\tline_model_list[8] = \"ID={0}.three_prime_UTR;Name={0}.three_prime_UTR;Parent={0}\".format(transcript)\n\t\t\tprint >>OUTPUT, \"\\t\".join(line_model_list)\n\t\t\t#\n\t\telse:\n\t\t\t#five_prime_UTR\n\t\t\tfive_prime_UTR = []\n\t\t\tthree_prime_UTR = []\n\t\t\tfirst_CDS_start = int(sorted_transcripts[transcript][\"CDS\"][0][0])\n\t\t\tfirst_CDS_end = int(sorted_transcripts[transcript][\"CDS\"][0][1])\n\t\t\t#\n\t\t\tk=0\n\t\t\texon_start = int(sorted_transcripts[transcript][\"exons\"][k][0])\n\t\t\texon_end = int(sorted_transcripts[transcript][\"exons\"][k][1])\n\t\t\t#\n\t\t\twhile (exon_end < first_CDS_start):\n\t\t\t\tfive_prime_UTR.append((exon_start, exon_end))\n\t\t\t\tk+=1\n\t\t\t\texon_start = int(sorted_transcripts[transcript][\"exons\"][k][0])\n\t\t\t\texon_end = int(sorted_transcripts[transcript][\"exons\"][k][1])\n\t\t\t\t#\n\t\t\tif (exon_start < first_CDS_start) and (exon_end >= first_CDS_end):\n\t\t\t\tfive_prime_UTR.append((exon_start, first_CDS_start-1))\n\t\t\t\tif exon_end > first_CDS_end:\n\t\t\t\t\tthree_prime_UTR.append((first_CDS_end+1, exon_end))\n\t\t\t\t\t#\n\t\t\t# three_prime_UTR\n\t\t\tlast_CDS_start = int(sorted_transcripts[transcript][\"CDS\"][-1][0])\n\t\t\tlast_CDS_end = int(sorted_transcripts[transcript][\"CDS\"][-1][1])\n\t\t\t#\n\t\t\tk=-1\n\t\t\texon_start = int(sorted_transcripts[transcript][\"exons\"][k][0])\n\t\t\texon_end = int(sorted_transcripts[transcript][\"exons\"][k][1])\n\t\t\t#\n\t\t\twhile (exon_start > last_CDS_end):\n\t\t\t\tthree_prime_UTR.append((exon_start, exon_end))\n\t\t\t\tk-=1\n\t\t\t\texon_start = int(sorted_transcripts[transcript][\"exons\"][k][0])\n\t\t\t\texon_end = int(sorted_transcripts[transcript][\"exons\"][k][1])\n\t\t\t\t#\n\t\t\tif (exon_end > last_CDS_end) and (exon_start <= last_CDS_start):\n\t\t\t\tthree_prime_UTR.append((last_CDS_end+1, exon_end))\n\t\t\t\tif exon_start < last_CDS_start:\n\t\t\t\t\tfive_prime_UTR.append((exon_start, last_CDS_start-1))\n\t\t\t\t\t#\n\t\t\tline_model_list = sorted_transcripts[transcript][\"exons\"][0][2].split(\"\\t\")\n\t\t\tfor chunk in five_prime_UTR:\n\t\t\t\tline_model_list[2] = \"five_prime_UTR\"\n\t\t\t\tline_model_list[3] = str(chunk[0])\n\t\t\t\tline_model_list[4] = str(chunk[1])\n\t\t\t\tline_model_list[8] = \"ID={0}.five_prime_UTR;Name={0}.five_prime_UTR;Parent={0}\".format(transcript)\n\t\t\t\tprint >>OUTPUT, \"\\t\".join(line_model_list)\n\t\t\t\t#\n\t\t\tline_model_list = sorted_transcripts[transcript][\"exons\"][0][2].split(\"\\t\")\n\t\t\tfor chunk in three_prime_UTR:\n\t\t\t\tline_model_list[2] = \"three_prime_UTR\"\n\t\t\t\tline_model_list[3] = str(chunk[0])\n\t\t\t\tline_model_list[4] = str(chunk[1])\n\t\t\t\tline_model_list[8] = \"ID={0}.three_prime_UTR;Name={0}.three_prime_UTR;Parent={0}\".format(transcript)\n\t\t\t\tprint >>OUTPUT, \"\\t\".join(line_model_list)\n\t\t\t\t#\n\telif sorted_transcripts[transcript][\"strand\"] == \"-\":\n\t\tif len(sorted_transcripts[transcript][\"exons\"]) == 1:\n\t\t\t#three_prime_UTR\n\t\t\tstart = int(sorted_transcripts[transcript][\"exons\"][0][0])\n\t\t\tend = int(sorted_transcripts[transcript][\"CDS\"][0][0])-1\n\t\t\tline_model_list = sorted_transcripts[transcript][\"exons\"][0][2].split(\"\\t\")\n\t\t\tline_model_list[2] = \"three_prime_UTR\"\n\t\t\tline_model_list[3] = str(start)\n\t\t\tline_model_list[4] = str(end)\n\t\t\tline_model_list[8] = \"ID={0}.three_prime_UTR;Name={0}.three_prime_UTR;Parent={0}\".format(transcript)\n\t\t\tprint >>OUTPUT, \"\\t\".join(line_model_list)\n\t\t\t#five_prime_UTR\n\t\t\tstart = int(sorted_transcripts[transcript][\"CDS\"][-1][1])+1\n\t\t\tend = int(sorted_transcripts[transcript][\"exons\"][-1][1])\n\t\t\tline_model_list = sorted_transcripts[transcript][\"exons\"][0][2].split(\"\\t\")\n\t\t\tline_model_list[2] = \"five_prime_UTR\"\n\t\t\tline_model_list[3] = str(start)\n\t\t\tline_model_list[4] = str(end)\n\t\t\t#\n\t\t\tline_model_list[8] = \"ID={0}.five_prime_UTR;Name={0}.five_prime_UTR;Parent={0}\".format(transcript)\n\t\t\tprint >>OUTPUT, \"\\t\".join(line_model_list)\n\t\t\t#\n\t\telse:\n\t\t\t#three_prime_UTR\n\t\t\tthree_prime_UTR = []\n\t\t\tfive_prime_UTR = []\n\t\t\tfirst_CDS_start = int(sorted_transcripts[transcript][\"CDS\"][0][0])\n\t\t\tfirst_CDS_end = int(sorted_transcripts[transcript][\"CDS\"][0][1])\n\t\t\t#\n\t\t\tk=0\n\t\t\texon_start = int(sorted_transcripts[transcript][\"exons\"][k][0])\n\t\t\texon_end = int(sorted_transcripts[transcript][\"exons\"][k][1])\n\t\t\t#\n\t\t\twhile (exon_end < first_CDS_start):\n\t\t\t\tthree_prime_UTR.append((exon_start, exon_end))\n\t\t\t\tk+=1\n\t\t\t\texon_start = int(sorted_transcripts[transcript][\"exons\"][k][0])\n\t\t\t\texon_end = int(sorted_transcripts[transcript][\"exons\"][k][1])\n\t\t\t\t#\n\t\t\tif (exon_start < first_CDS_start) and (exon_end >= first_CDS_end):\n\t\t\t\tthree_prime_UTR.append((exon_start, first_CDS_start-1))\n\t\t\t\tif exon_end > first_CDS_end:\n\t\t\t\t\tfive_prime_UTR.append((first_CDS_end+1, exon_end))\n\t\t\t\t\t#\n\t\t\t# five_prime_UTR\n\t\t\tlast_CDS_start = int(sorted_transcripts[transcript][\"CDS\"][-1][0])\n\t\t\tlast_CDS_end = int(sorted_transcripts[transcript][\"CDS\"][-1][1])\n\t\t\t#\n\t\t\tk=-1\n\t\t\texon_start = int(sorted_transcripts[transcript][\"exons\"][k][0])\n\t\t\texon_end = int(sorted_transcripts[transcript][\"exons\"][k][1])\n\t\t\t#\n\t\t\twhile (exon_start > last_CDS_end):\n\t\t\t\tfive_prime_UTR.append((exon_start, exon_end))\n\t\t\t\tk-=1\n\t\t\t\texon_start = int(sorted_transcripts[transcript][\"exons\"][k][0])\n\t\t\t\texon_end = int(sorted_transcripts[transcript][\"exons\"][k][1])\n\t\t\t\t#\n\t\t\tif (exon_end > last_CDS_end) and (exon_start <= last_CDS_start):\n\t\t\t\tfive_prime_UTR.append((last_CDS_end+1, exon_end))\n\t\t\t\tif exon_start < last_CDS_start:\n\t\t\t\t\tthree_prime_UTR.append((exon_start, last_CDS_start-1))\n\t\t\t\t\t#\n\t\t\tline_model_list = sorted_transcripts[transcript][\"exons\"][0][2].split(\"\\t\")\n\t\t\tfor chunk in five_prime_UTR:\n\t\t\t\tline_model_list[2] = \"five_prime_UTR\"\n\t\t\t\tline_model_list[3] = str(chunk[0])\n\t\t\t\tline_model_list[4] = str(chunk[1])\n\t\t\t\tline_model_list[8] = \"ID={0}.five_prime_UTR;Name={0}.five_prime_UTR;Parent={0}\".format(transcript)\n\t\t\t\tprint >>OUTPUT, \"\\t\".join(line_model_list)\n\t\t\t\t#\n\t\t\tline_model_list = sorted_transcripts[transcript][\"exons\"][0][2].split(\"\\t\")\n\t\t\tfor chunk in three_prime_UTR:\n\t\t\t\tline_model_list[2] = \"three_prime_UTR\"\n\t\t\t\tline_model_list[3] = str(chunk[0])\n\t\t\t\tline_model_list[4] = str(chunk[1])\n\t\t\t\tline_model_list[8] = \"ID={0}.three_prime_UTR;Name={0}.three_prime_UTR;Parent={0}\".format(transcript)\n\t\t\t\tprint >>OUTPUT, \"\\t\".join(line_model_list)\n\t\t\t\t#\n#\nOUTPUT.close()\nsys.stderr.write(\"Done.\\n\")\n\n# final sorting\nsys.stderr.write(\"Final sorting...\")\nsubprocess.call(\"cat temp.out | sort -sk1,1 -k4n,4 -k5nr,5 | uniq > temp\", shell=True)\nsubprocess.call(\"rm temp.in temp.out\", shell=True)\nsys.stderr.write(\"Done.\\n\")\ndel transcripts\ndel sorted_transcripts\n\n## removing artifacts\nsys.stderr.write(\"Removing artifacts...\")\nINPUT = open(\"temp\", \"r\")\nOUTPUT = open(\"temp.out\", \"w\")\nfor line in INPUT:\n\tlinelist = line.rstrip().split(\"\\t\")\n\tif (linelist[2] in [\"three_prime_UTR\", \"five_prime_UTR\"]) and (linelist[3] == linelist[4]):\n\t\tpass\n\telse:\n\t\tprint >>OUTPUT, line.rstrip()\n\t\t#\nINPUT.close()\nOUTPUT.close()\nsubprocess.call(\"cp temp.out temp ; rm temp.out\", shell=True)\nsys.stderr.write(\"Done.\\n\")\n\n## convert positions that were falsely assigned\nsys.stderr.write(\"Correcting positions...\")\nINPUT = open(\"temp\", \"r\")\nOUTPUT = open(\"temp.out\", \"w\")\n\nfor line in INPUT:\n\tlinelist = line.rstrip().split(\"\\t\")\n\tif int(linelist[3]) > int(linelist[4]):\n\t\tnewlinelist = linelist\n\t\tnewlinelist[3] = linelist[4]\n\t\tnewlinelist[4] = linelist[3]\n\t\tprint >>OUTPUT, \"\\t\".join(newlinelist)\n\t\t#\n\telse:\n\t\tprint >>OUTPUT, \"\\t\".join(linelist)\n\t\t#\n#\nINPUT.close()\nOUTPUT.close()\nsubprocess.call(\"cp temp.out temp ; rm temp.out\", shell=True)\nsys.stderr.write(\"Done.\\n\")\n\n## extract scaffold length \nINPUT = open(args.reference, \"r\")\nOUTPUT = open(\"temp.scaffolds\", \"w\")\nsys.stderr.write(\"Extracting scaffold names from reference...\")\nscaffold_names = []\nsubprocess.call(\"fgrep \\\">\\\" {0} > temp.scaffold_names\".format(args.reference), shell=True)\nINPUT.close()\nINPUT = open(\"temp.scaffold_names\", \"r\")\nfor line in INPUT:\n\tscaffold_names.append(line.rstrip().strip(\">\").split(\"\\t\")[0].split(\" \")[0])\n\t#\nsys.stderr.write(\"Done.\\n\")\nINPUT.close()\nfile_scaffolds = []\nINPUT = open(\"temp\", \"r\")\nsys.stderr.write(\"Reading scaffold names from input file...\")\nfor line in INPUT:\n\tlinelist = line.rstrip().split(\"\\t\")\n\tfile_scaffolds.append(linelist[0])\n\t#\nINPUT.close()\nunique_scaffolds = list(sorted(set(file_scaffolds)))\ndel file_scaffolds\nsys.stderr.write(\"Done.\\n\")\n\n# intersect function\ndef intersect(a, b):\n\treturn list(set(a) & set(b))\n\nsys.stderr.write(\"Determining scaffold lengths...\")\nselected_scaffolds = intersect(unique_scaffolds, scaffold_names)\ndel unique_scaffolds\ndel scaffold_names\nscaffolds = {}\nINPUT = open(args.reference, \"r\")\nfor line in INPUT:\n\tif line[0:1] == \">\":\n\t\tswitch = \"off\"\n\t\tscaffold_name = line.rstrip().strip(\">\").split(\"\\t\")[0].split(\" \")[0]\n\t\tif scaffold_name in selected_scaffolds:\n\t\t\tscaffolds[scaffold_name] = 0\n\t\t\tswitch = \"on\"\n\t\t\t#\n\telse:\n\t\tif switch == \"on\":\n\t\t\tscaffolds[scaffold_name] += len(line.rstrip())\n\t\t\t#\nINPUT.close()\nsys.stderr.write(\"Done.\\n\")\n\n\nsys.stderr.write(\"Adding required scaffold lines to file...\")\nif len(selected_scaffolds) > 0:\n\tfor scaffold in selected_scaffolds:\n\t\tprint >>OUTPUT, \"{0}\\ta2gb\\tcontig\\t1\\t{1}\\t.\\t.\\t.\\tID={0};Name={0}\".format(scaffold, scaffolds[scaffold])\n\t\t#\n\tOUTPUT.close()\n\tsubprocess.call(\"cat temp.scaffolds temp | sort -dsk1,1 -k4n,4 -k5nr,5 > temp.out ; mv temp.out temp ; rm temp.scaffolds temp.scaffold_names\", shell=True)\n\tsys.stderr.write(\"Done.\\n\")\n\t#\nelse:\n\tsys.exit(\"It seems that between your reference and the scaffolds of your augustus output there is no intersection. Are you sure you are specifying the correct reference or the correct augustus output? Check field number 1 of your GFF / GFF3 and the scaffold names of your reference.\\n\\n\")\n\t#\ndel scaffolds\n\n## inserting repeat information\nif args.repeats:\n\tsys.stderr.write(\"Adding repeats information...\")\n\tif args.repmask_out:\n\t\tINPUT = open(args.repeats, \"r\")\n\t\tOUTPUT = open(\"temp.repeats\", \"w\")\n\t\tk=0\n\t\trm_switch = \"off\"\n\t\tfor line in INPUT:\n\t\t\tline_list = line.rstrip().split()\n\t\t\twhile (k==0):\n\t\t\t\tif line_list[0] == \"SW\":\n\t\t\t\t\tsys.stderr.write(\"Removing repeats header...\")\n\t\t\t\t\tsubprocess.check_call(\"tail -n+4 {0} > temp.in\".format(args.repeats), shell=True)\n\t\t\t\t\trm_switch = \"on\"\n\t\t\t\t\tINPUT = open(\"temp.in\", \"r\")\n\t\t\t\t\tk+=1\n\t\t\t\t\t#\n\t\t\t\telse:\n\t\t\t\t\tINPUT = open(args.repeats, \"r\")\n\t\t\t\t\tk+=1\n\t\t\t\t\t#\n\t\tfor line in INPUT:\n\t\t\tline_list = line.rstrip().split()\n\t\t\tif line_list[4] in selected_scaffolds:\n\t\t\t\tprint >>OUTPUT, \"\\t\".join([line_list[4], \"RepeatMasker\", \"repeat\", line_list[5], line_list[6], \".\", \".\", \".\", \"ID={0}.{1};Name={0}.{1}\".format(line_list[10], line_list[14])])\n\t\t\t\t#\n\t\tOUTPUT.close()\n\t\tINPUT.close()\n\t\tsubprocess.call(\"cat temp temp.repeats | sort -dsk1,1 -k4n,4 -k5nr,5 > temp.out; cp temp.out temp; rm temp.repeats temp.out\".format(args.repeats), shell=True)\n\t\tif rm_switch == \"on\":\n\t\t\tsubprocess.call(\"rm temp.in\", shell=True)\n\t\t\t#\n\telse:\n\t\tsubprocess.call(\"cat {0} temp | sort -dsk1,1 -k4n,4 -k5nr,5 > temp.out ; cp temp.out temp; rm temp.out\".format(args.repeats), shell=True)\n\t\tif rm_switch == \"on\":\n\t\t\tsubprocess.call(\"rm temp.in\", shell=True)\n\t\t\t#\nsys.stderr.write(\"Done.\\n\")\n## adding evidence to the transcripts \n# raw augustus output reading\nsys.stderr.write(\"Adding evidence values to the transcripts...\")\nINPUT = open(args.input_file, \"r\")\ntranscripts = {}\nfor line in INPUT:\n\tif line[0:1] != \"#\":\n\t\tlinelist = line.rstrip().split(\"\\t\")\n\t\tif linelist[2] == \"transcript\":\n\t\t\tf9list = linelist[8].split(\";\")\n\t\t\tf9dic = {}\n\t\t\tfor element in f9list:\n\t\t\t\tf9dic[element.split(\"=\")[0]] = element.split(\"=\")[1]\n\t\t\t\t#\n\t\t\ttranscript_name = f9dic[\"ID\"]\n\t\t\t#\n\telse:\n\t\tif line[0:36] == \"# % of transcript supported by hints\":\n\t\t\tevidence = float(line.rstrip().split(\": \")[1])\n\t\t\ttranscripts[transcript_name] = evidence\n\t\t\t#\nINPUT.close()\n\nINPUT = open(\"temp\", \"r\")\nOUTPUT = open(\"temp.out\", \"w\")\nfor line in INPUT:\n\tlinelist = line.rstrip().split(\"\\t\")\n\tif linelist[2] == \"mRNA\":\n\t\tf9list = linelist[8].split(\";\")\n\t\tf9dic = {}\n\t\tfor element in f9list:\n\t\t\tf9dic[element.split(\"=\")[0]] = element.split(\"=\")[1]\n\t\t\t#\n\t\tnew_f9 = \"ID={0};Parent={1};Note=evidence_{2}%\".format(f9dic[\"ID\"], f9dic[\"Parent\"], transcripts[f9dic[\"ID\"]])\n\t\tlinelist[8] = new_f9\n\t\tprint >>OUTPUT, \"\\t\".join(linelist)\n\t\t#\n\telse:\n\t\tprint >>OUTPUT, line.rstrip()\n\t\t#\nINPUT.close()\nOUTPUT.close()\nsys.stderr.write(\"Done.\\n\")\n\n# output sorting\nsys.stderr.write(\"Sorting final output gff3 file...\")\nsubprocess.call(\"cat temp.out | sort -dsk1,1 -k4n,4 -k5nr,5 > temp\", shell=True)\nsys.stderr.write(\"Done.\\n\")\n\n## converting transcription start and end site to tts and tss \nsys.stderr.write(\"Converting transcription start and end site to tts and tss...\")\nINPUT = open(\"temp\", \"r\")\nOUTPUT = open(\"temp.out\", \"w\")\nfor line in INPUT:\n linelist = line.rstrip().split(\"\\t\")\n if linelist[2] == \"transcription_start_site\":\n linelist[2] = \"tss\"\n #\n elif linelist[2] == \"transcription_end_site\":\n linelist[2] = \"tts\"\n #\n print >>OUTPUT, \"\\t\".join(linelist)\n #\n\nINPUT.close()\nOUTPUT.close()\nsubprocess.call(\"cat temp.out | sort -dsk1,1 -k4n,4 -k5nr,5 > {0} ; rm temp temp.out\".format(args.output_file), shell=True)\nsys.stderr.write(\"Done.\\nYou find your file at:\\n{0}\\n\\n\".format(args.output_file))\n","sub_path":"prepare-annotation-from-augustus.py","file_name":"prepare-annotation-from-augustus.py","file_ext":"py","file_size_in_byte":22917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"254687965","text":"import numpy as np\nimport cv2\nimport time\n\nface_model = './model/res10_300x300_ssd_iter_140000.caffemodel'\nface_prototxt = './model/deploy.prototxt.txt'\nage_model = './model/age_net.caffemodel'\nage_prototxt = './model/age_deploy.prototxt'\ngender_model = './model/gender_net.caffemodel'\ngender_prototxt = './model/gender_deploy.prototxt'\n\nage_list = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']\ngender_list = ['Male','Female']\n\ntitle_name = 'Age and Gender Recognition'\nmin_confidence = 0.5\nrecognition_count = 0\nelapsed_time = 0\nOUTPUT_SIZE = (300, 300)\n\ndetector = cv2.dnn.readNetFromCaffe(face_prototxt, face_model)\nage_detector = cv2.dnn.readNetFromCaffe(age_prototxt, age_model)\ngender_detector = cv2.dnn.readNetFromCaffe(gender_prototxt, gender_model)\n\n \ndef detectAndDisplay(image):\n start_time = time.time()\n (h, w) = image.shape[:2]\n\n \n imageBlob = cv2.dnn.blobFromImage(image, 1.0, OUTPUT_SIZE,\n (104.0, 177.0, 123.0), swapRB=False, crop=False)\n\n detector.setInput(imageBlob)\n detections = detector.forward()\n\n for i in range(0, detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n\n if confidence > min_confidence:\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n face = image[startY:endY, startX:endX]\n (fH, fW) = face.shape[:2]\n\n face_blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227),\n (78.4263377603, 87.7689143744, 114.895847746),swapRB=False)\n \n \n age_detector.setInput(face_blob)\n age_predictions = age_detector.forward()\n age_index = age_predictions[0].argmax()\n age = age_list[age_index]\n age_confidence = age_predictions[0][age_index]\n \n gender_detector.setInput(face_blob)\n gender_predictions = gender_detector.forward()\n gender_index = gender_predictions[0].argmax()\n gender = gender_list[gender_index]\n gender_confidence = gender_predictions[0][gender_index]\n\n text = \"{}: {:.2f}% {}: {:.2f}%\".format(gender, gender_confidence*100, age, age_confidence*100)\n y = startY - 10 if startY - 10 > 10 else startY + 10\n cv2.rectangle(image, (startX, startY), (endX, endY),\n (0, 255, 0), 2)\n cv2.putText(image, text, (startX, y),\n cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)\n print('==============================')\n print(\"Gender {} time {:.2f} %\".format(gender, gender_confidence*100))\n print(\"Age {} time {:.2f} %\".format(age, age_confidence*100))\n print(\"Age Probability(%)\")\n for i in range(len(age_list)):\n print(\"{} {:.2f}%\".format(age_list[i], age_predictions[0][i]*100))\n \n print(\"Gender Probability(%)\")\n for i in range(len(gender_list)):\n print(\"{} {:.2f} %\".format(gender_list[i], gender_predictions[0][i]*100))\n \n\n \n frame_time = time.time() - start_time\n global elapsed_time\n elapsed_time += frame_time\n print(\"Frame time {:.3f} seconds\".format(frame_time))\n \n cv2.imshow(title_name, image)\n \n\nvs = cv2.VideoCapture(0, cv2.CAP_DSHOW)\ntime.sleep(2.0)\nif not vs.isOpened:\n print('### Error opening video ###')\n exit(0)\nwhile True:\n ret, frame = vs.read()\n if frame is None:\n print('### No more frame ###')\n vs.release()\n break\n detectAndDisplay(frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\nvs.release()\ncv2.destroyAllWindows()\n","sub_path":"face_age_gender_recognition_video.py","file_name":"face_age_gender_recognition_video.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"11814544","text":"# test_base.py\n#\n#\n\n## IMPORTS\n\nfrom meds.object import Object\nfrom meds.bots.test import TestBot\n\nimport unittest\n\n## Test_Base class\n\nclass Test_Base(unittest.TestCase):\n\n def test_construct(self):\n o = Object()\n self.assertEqual(type(o), Object)\n\n def test_settingattribute(self):\n o = Object()\n o.bla = \"mekker\"\n self.assertEqual(o.bla, \"mekker\")\n\n def test_checkattribute(self):\n o = Object()\n self.failUnlessRaises(AttributeError)\n\n def test_undersopzet(self):\n o = Object()\n o._bla = \"mekker\"\n self.assertEqual(o._bla, \"mekker\")\n\n def test_update(self):\n o1 = Object()\n o1._bla = \"mekker\"\n o2 = Object()\n o2._bla = \"blaet\"\n o1.update(o2)\n self.assertEqual(o1._bla, \"blaet\")\n\n def test_iter(self):\n o1 = Object()\n o1.bla1 = 1\n o1.bla2 = 2\n o1.bla3 = 3\n res = sorted(list(o1))\n self.assertEqual(res, [\"bla1\",\"bla2\",\"bla3\"])\n","sub_path":"tests/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"450077055","text":"import numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\n\n\nimg = cv.imread('img/bb.jpg')\n\noriginal=img.copy()\n\nl = int(max(5, 6))\nu = int(min(6, 6))\n\nedges = cv.GaussianBlur(img, (21, 51),3)\nedges = cv.cvtColor(edges , cv.COLOR_BGR2GRAY)\n\n\nedges = cv.Canny(edges,l,u)\n# edges = cv.dilate(edges, None)\n# edges = cv.erode(edges, None)\n\n_,thresh=cv.threshold(edges,0,255,cv.THRESH_BINARY + cv.THRESH_OTSU)\nkernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5,5))\nmask = cv.morphologyEx(thresh, cv.MORPH_CLOSE, kernel, iterations=4)\n\n\n# kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (30,30))\n# morphed = cv.morphologyEx(thresh, cv.MORPH_CLOSE, kernel)\n# dilate=cv.dilate(morphed, None, iterations = 30) #change iteration\n\n# mask = dilate\n\n# (cnt, _) = cv.findContours(dilate, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n# for contour in cnt:\n# if len(contour) > 40:\n# cv.drawContours(mask ,contour, -1, (255, 255, 255), 50)\n# continue\n\n\n# cnts = cv.findContours(dilate, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n# cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n# cnts = sorted(cnts, key=cv.contourArea, reverse=True)\n# for c in cnts:\n# cv.drawContours(mask, [c], -1, (255,255,255), 30)\n# break\n\n# # msk=mask\n# # mask=255-mask\n# mask = cv.morphologyEx(mask, cv.MORPH_CLOSE, kernel, iterations=4)\n# # mask=255-mask\n\n\n# result = cv.bitwise_and(original, original, mask=mask)\n# result[mask==0] = (0,0,0)\n\nimg1=cv.resize(edges,(600,400))\nimport sys\nimg=cv.resize(mask,(300,200))\ndata=img.tolist()\nsys.setrecursionlimit(10**8) \nfor i in range(len(data)):\n for j in range(len(data[i])):\n if data[i][j]!=255:\n data[i][j]=-1\n else:\n break\n for j in range(len(data[i])-1,-1,-1):\n if data[i][j]!=255:\n data[i][j]=-1\n else:\n break\nimage=np.array(data)\nimage[image!=-1]=255\nimage[image==-1]=0\nplt.imshow(image)\n\n# plt.imshow(result,cmap = 'gray')\n# plt.title('edge')\n# plt.show()\n\n","sub_path":"remove.py","file_name":"remove.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"454305594","text":"import elegy\n\n\nfrom elegy import utils\nimport jax.numpy as jnp\nimport jax\nimport tensorflow.keras as tfk\n\n# import debugpy\n\n# print(\"Waiting for debugger...\")\n# debugpy.listen(5679)\n# debugpy.wait_for_client()\n\n\ndef test_basic():\n\n y_true = jnp.array([[0.0, 1.0], [0.0, 0.0]])\n y_pred = jnp.array([[1.0, 1.0], [1.0, 0.0]])\n\n # Using 'auto'/'sum_over_batch_size' reduction type.\n msle = elegy.losses.MeanSquaredLogarithmicError()\n\n assert msle(y_true, y_pred) == 0.24022643\n\n # Calling with 'sample_weight'.\n assert msle(y_true, y_pred, sample_weight=jnp.array([0.7, 0.3])) == 0.12011322\n\n # Using 'sum' reduction type.\n msle = elegy.losses.MeanSquaredLogarithmicError(\n reduction=elegy.losses.Reduction.SUM\n )\n\n assert msle(y_true, y_pred) == 0.48045287\n\n # Using 'none' reduction type.\n msle = elegy.losses.MeanSquaredLogarithmicError(\n reduction=elegy.losses.Reduction.NONE\n )\n\n assert jnp.equal(msle(y_true, y_pred), jnp.array([0.24022643, 0.24022643])).all()\n\n\ndef test_function():\n\n rng = jax.random.PRNGKey(42)\n\n y_true = jax.random.randint(rng, shape=(2, 3), minval=0, maxval=2)\n y_pred = jax.random.uniform(rng, shape=(2, 3))\n\n loss = elegy.losses.mean_squared_logarithmic_error(y_true, y_pred)\n\n assert loss.shape == (2,)\n\n first_log = jnp.log(jnp.maximum(y_true, utils.EPSILON) + 1.0)\n second_log = jnp.log(jnp.maximum(y_pred, utils.EPSILON) + 1.0)\n assert jnp.array_equal(loss, jnp.mean(jnp.square(first_log - second_log), axis=-1))\n\n\ndef test_compatibility():\n # Input: true (y_true) and predicted (y_pred) tensors\n y_true = jnp.array([[0.0, 1.0], [0.0, 0.0]])\n y_pred = jnp.array([[0.6, 0.4], [0.4, 0.6]])\n\n # MSLE using sample_weight\n msle_elegy = elegy.losses.MeanSquaredLogarithmicError()\n msle_tfk = tfk.losses.MeanSquaredLogarithmicError()\n assert jnp.isclose(\n msle_elegy(y_true, y_pred, sample_weight=jnp.array([1, 0])),\n msle_tfk(y_true, y_pred, sample_weight=jnp.array([1, 0])),\n rtol=0.0001,\n )\n\n # MSLE with reduction method: SUM\n msle_elegy = elegy.losses.MeanSquaredLogarithmicError(\n reduction=elegy.losses.Reduction.SUM\n )\n msle_tfk = tfk.losses.MeanSquaredLogarithmicError(\n reduction=tfk.losses.Reduction.SUM\n )\n assert jnp.isclose(\n msle_elegy(y_true, y_pred), msle_tfk(y_true, y_pred), rtol=0.0001\n )\n\n # MSLE with reduction method: NONE\n msle_elegy = elegy.losses.MeanSquaredLogarithmicError(\n reduction=elegy.losses.Reduction.NONE\n )\n msle_tfk = tfk.losses.MeanSquaredLogarithmicError(\n reduction=tfk.losses.Reduction.NONE\n )\n assert jnp.all(\n jnp.isclose(msle_elegy(y_true, y_pred), msle_tfk(y_true, y_pred), rtol=0.0001)\n )\n\n\nif __name__ == \"__main__\":\n\n test_basic()\n test_function()\n","sub_path":"elegy/losses/mean_squared_logarithmic_error_test.py","file_name":"mean_squared_logarithmic_error_test.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"378310034","text":"# Jorge Guevara\n# jorged@br.ibm.com\n# compute VLAD descriptors per PDF using a visual dictionary and a set of descriptors\n# USAGE :\n# python vladDescriptorsPerPDF.py -d dataset -dV visualDictionaryPath -n descriptor -o output\n# example :\n# python vladDescriptorsPerPDF.py -d dataset -dV visualDictionary/visualDictionary16SURF.pickle --descriptor SURF -o VLADdescriptors/VLAD_SURF_W16\n\nfrom VLADlib.VLAD import *\nfrom VLADlib.Descriptors import *\nimport argparse\nimport glob\nimport cv2\n\n\n#parser\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", required = True,\n\thelp = \"Path to image dataset\")\nap.add_argument(\"-dV\", \"--visualDictionaryPath\", required = True,\n\thelp = \"Path to the visual dictionary\")\nap.add_argument(\"-n\", \"--descriptor\", required = True,\n\thelp = \"descriptor = SURF, SIFT or ORB\")\nap.add_argument(\"-o\", \"--output\", required = True,\n\thelp = \"Path to where VLAD descriptors will be stored\")\nargs = vars(ap.parse_args())\n\n\n#args\npath = args[\"dataset\"]\npathVD = args[\"visualDictionaryPath\"]\ndescriptorName=args[\"descriptor\"]\noutput=args[\"output\"]\n\n\n\n#estimating VLAD descriptors for the whole dataset\nprint(\"estimating VLAD descriptors per PDF using \"+descriptorName+ \" for dataset: /\"+path+ \" and visual dictionary: /\"+pathVD)\n\n\nwith open(pathVD, 'rb') as f:\n visualDictionary=pickle.load(f) \n\n#computing the VLAD descriptors\ndict={\"SURF\":describeSURF,\"SIFT\":describeSIFT,\"ORB\":describeORB} \nV, idImages = getVLADDescriptorsPerPDF(path,dict[descriptorName],visualDictionary)\n\n#output\nfile=output+\".pickle\"\n\nwith open(file, 'wb') as f:\n\tpickle.dump([idImages, V,path], f)\n\nprint(\"The VLAD descriptors per PDF are saved in \"+file)\n\n","sub_path":"VLAD/vladDescriptorsPerPDF.py","file_name":"vladDescriptorsPerPDF.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"449854531","text":"from Camel import config\nfrom flask import request, make_response\nimport sys\nimport MySQLdb\n\ndef db_connect(config):\n db_conf = config['database']\n try:\n db = MySQLdb.connect(host=db_conf['HOST'],\n user=db_conf['USER'],\n passwd=db_conf['PASSWORD'],\n db=db_conf['NAME'],\n charset='utf8'\n )\n except:\n print(\"Can't connect to database\")\n sys.exit(1)\n\n return db\n\ndef is_authenticated(): \n if 'AuthToken' in request.headers:\n token = request.headers['AuthToken']\n else:\n return False\n \n db = db_connect(config)\n sql = \"SELECT `token` from `sessions` WHERE `token` = %(token)s\"\n c = db.cursor()\n c.execute(sql, {'token': token})\n rows = c.fetchall() \n c.close()\n db.close()\n\n return len(rows)==1\n \n","sub_path":"api/Camel/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"69027618","text":"import string\nimport random\nimport hashlib\n\ndef randomString(size =20):\n chars = string.ascii_uppercase + string.digits + string.ascii_lowercase\n return ''.join(random.choice(chars)for _ in range(size))\n\ndef randomName(n=30):\n s = randomString(n)\n hash_object = hashlib.sha1(s.encode())\n name = hash_object.hexdigest()\n nameAsNum=int(name,16)\n return nameAsNum\n\ndef aEntero(s):\n hash_object = hashlib.sha1(s)\n name = hash_object.hexdigest()\n nameAsNum=int(name,16)\n return nameAsNum\n\nclass Range:\n def __init__(self,lb,ub):\n self.lb = lb\n self.ub = ub\n \n def isFirst(self):\n return self.lb > self.ub\n \n def member(self, id):\n if self.isFirst():\n return (id >= self.lb and id < 1<<160) or (id >= 0 and id < self.ub )\n else:\n return id >= self.lb and id < self.ub\n \n def toStr(self):\n if self.isFirst():\n return '[' + str(self.lb) + ' , 2^160) U [' + '0 , ' + str(self.ub) + ')'\n else:\n return '[' + str (self.lb) + ' , ' + str(self.ub) + ')'\n\nservers = [randomName() for _ in range(5)]\nservers.sort()\nranges = []\nfor n in range(len(servers)-1):\n lb = servers[n]\n ub = servers[n+1]\n ranges.append(Range(lb,ub))\n \"\"\" print(Range(lb,ub)) \"\"\"\nranges.append(Range(servers[4], servers[0]))\n\nload = {}\nFiles = 10\nfile = 'imagen3.jpg'\nindex = file.split('.')[0]+'.index'\n\nwith open(file, 'rb') as f:\n with open(index, 'a') as f2:\n f2.write(file+'\\n')\n while True:\n aux = f.read(512)\n if (not len(aux)):\n break\n hf = aEntero(aux)\n \n for s in ranges:\n if s.member(hf):\n print('nelson estoyn aca..')\n f2.write(str(hf)+'\\n')\n break\n \n\n\n","sub_path":"Entrega2/Cliente/shalb.py","file_name":"shalb.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"498618579","text":"\"\"\"\nfacial_recog.py\n===============\n\nAcknowledgement\n Code was adapted from TutLab 9 01_capture.py, 02_encode.py, and 03_recognise.py\n which in turn was adapted from\n https://www.hackster.io/mjrobot/real-time-face-recognition-an-end-to-end-project-a10826\n and\n https://www.pyimagesearch.com/2018/06/18/face-recognition-with-opencv-python-and-deep-learning/\n\"\"\"\nimport time\nimport os\nimport pickle\nimport cv2\nimport imutils\nfrom imutils import paths\nfrom imutils.video import VideoStream\nimport face_recognition\n\n\nclass FacialRecog():\n \"\"\"\n Handles taking pictures, encoding them and recognising known people\n \"\"\"\n def __init__(self):\n self.face_detector = cv2.CascadeClassifier(\n './framework/reception/haarcascade_frontalface_default.xml')\n\n def capture_photo(self, username):\n \"\"\"Captures a photo\"\"\"\n folder = './dataset/{}'.format(username)\n if not os.path.exists(folder):\n os.makedirs(folder)\n # Start the camera\n cam = cv2.VideoCapture(0)\n # Set video width\n cam.set(3, 640)\n # Set video height\n cam.set(4, 480)\n # Get the pre-built classifier that had been trained on 3 million faces\n\n img_counter = 0\n while img_counter <= 10:\n key = input('Press q to stop or ENTER to continue: ')\n if key == 'q':\n break\n\n ret, frame = cam.read()\n if not ret:\n break\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = self.face_detector.detectMultiScale(gray, 1.3, 5)\n\n if len(faces) == 0:\n print('No face detected, please try again')\n continue\n\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)\n img_name = '{}/{:04}.jpg'.format(folder, img_counter)\n cv2.imwrite(img_name, frame[y: y + h, x: x + w])\n print('{} written!'.format(img_name))\n img_counter += 1\n\n cam.release()\n\n def encode(self):\n \"\"\"Encodes the dataset into a pickled dataset\"\"\"\n image_paths = list(paths.list_images('dataset'))\n\n # initialize the list of known encodings and known names\n known_encodings = []\n known_names = []\n\n # loop over the image paths\n for (i, image_path) in enumerate(image_paths):\n # extract the person name from the image path\n print(\"[INFO] processing image {}/{}\".format(\n i + 1, len(image_paths)))\n name = image_path.split(os.path.sep)[-2]\n\n # load the input image and convert it from RGB (OpenCV ordering)\n # to dlib ordering (RGB)\n image = cv2.imread(image_path)\n rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # detect the (x, y)-coordinates of the bounding boxes\n # corresponding to each face in the input image\n boxes = face_recognition.face_locations(\n rgb, model='hog')\n\n # compute the facial embedding for the face\n encodings = face_recognition.face_encodings(rgb, boxes)\n\n # loop over the encodings\n for encoding in encodings:\n # add each encoding + name to our set of known names\n # and encodings\n known_encodings.append(encoding)\n known_names.append(name)\n\n # dump the facial encodings + names to disk\n print(\"[INFO] serializing encodings...\")\n data = {\"encodings\": known_encodings, \"names\": known_names}\n\n with open('encodings.pickle', \"wb\") as file:\n file.write(pickle.dumps(data))\n\n def facial_recog_login(self, state, login):\n \"\"\"\n Constantly searches for a known face\n\n Params\n :state: the state object that stores whether there is a user logged in\n :login: the callback to log a user in if detected\n \"\"\"\n\n # load the known faces and embeddings\n # print('[INFO] loading encodings...')\n\n while not os.path.isfile('encodings.pickle'):\n time.sleep(3.0)\n\n data = pickle.loads(open('encodings.pickle', 'rb').read())\n\n # initialize the video stream and then allow the\n # camera sensor to warm up\n print('[INFO] starting video stream...')\n video_stream = VideoStream(src=0).start()\n time.sleep(2.0)\n\n # loop over frames from the video file stream\n while True:\n # grab the frame from the threaded video stream\n if state.is_logged_in():\n time.sleep(3.0)\n continue\n\n frame = video_stream.read()\n\n # convert the input frame from BGR to RGB then resize it to have\n # a width of 750px (to speedup processing)\n rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n rgb = imutils.resize(frame, width=240)\n\n # detect the (x, y)-coordinates of the bounding boxes\n # corresponding to each face in the input frame, then compute\n # the facial embeddings for each face\n boxes = face_recognition.face_locations(rgb, model='hog')\n encodings = face_recognition.face_encodings(rgb, boxes)\n names = []\n\n # loop over the facial embeddings\n for encoding in encodings:\n # attempt to match each face in the input image to our known\n # encodings\n matches = face_recognition.compare_faces(\n data['encodings'], encoding)\n name = 'Unknown'\n\n # check to see if we have found a match\n if True in matches:\n # find the indexes of all matched faces then initialize a\n # dictionary to count the total number of times each face\n # was matched\n matched_idxs = [i for (i, b) in enumerate(matches) if b]\n counts = {}\n\n # loop over the matched indexes and maintain a count for\n # each recognized face face\n for i in matched_idxs:\n name = data['names'][i]\n counts[name] = counts.get(name, 0) + 1\n\n # determine the recognized face with the largest number\n # of votes (note: in the event of an unlikely tie Python\n # will select first entry in the dictionary)\n name = max(counts, key=counts.get)\n\n # update the list of names\n names.append(name)\n\n # loop over the recognized faces\n for name in names:\n # print to console, identified person\n if name == 'Unknown':\n continue\n\n login(name)\n # Set a flag to sleep the cam for fixed time\n time.sleep(3.0)\n\n # do a bit of cleanup\n video_stream.stop()\n","sub_path":"src/framework/reception/facial_recog.py","file_name":"facial_recog.py","file_ext":"py","file_size_in_byte":7073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"499655071","text":"array=list(map(int,input().split()))\nfor j in range(0,len(array)):\n min=array[j]\n for i in range(j+1,len(array)):\n if array[i] seconds:\n log.debug('Removing signed app: %s, %dsecs old.' % (full, age))\n shutil.rmtree(full)\n\n\n@cronjobs.register\ndef update_app_trending():\n \"\"\"\n Update trending for all apps.\n\n Spread these tasks out successively by 15 seconds so they don't hit\n Monolith all at once.\n\n \"\"\"\n chunk_size = 50\n seconds_between = 15\n\n all_ids = list(Webapp.objects.filter(status=amo.STATUS_PUBLIC)\n .values_list('id', flat=True))\n\n countdown = 0\n for ids in chunked(all_ids, chunk_size):\n update_trending.delay(ids, countdown=countdown)\n countdown += seconds_between\n\n\n@cronjobs.register\ndef dump_user_installs_cron():\n \"\"\"\n Sets up tasks to do user install dumps.\n \"\"\"\n chunk_size = 100\n # Get valid users to dump.\n user_ids = set(Installed.objects.filter(addon__type=amo.ADDON_WEBAPP)\n .values_list('user', flat=True))\n\n # Remove old dump data before running.\n user_dir = os.path.join(settings.DUMPED_USERS_PATH, 'users')\n if os.path.exists(user_dir):\n shutil.rmtree(user_dir)\n\n grouping = []\n for chunk in chunked(user_ids, chunk_size):\n grouping.append(dump_user_installs.subtask(args=[chunk]))\n\n post = zip_users.subtask(immutable=True)\n ts = chord(grouping, post)\n ts.apply_async()\n\n\n@cronjobs.register\ndef update_app_downloads():\n \"\"\"\n Update download/install stats for all apps.\n\n Spread these tasks out successively by `seconds_between` seconds so they\n don't hit Monolith all at once.\n\n \"\"\"\n chunk_size = 50\n seconds_between = 2\n\n all_ids = list(Webapp.objects.filter(status=amo.STATUS_PUBLIC)\n .values_list('id', flat=True))\n\n countdown = 0\n for ids in chunked(all_ids, chunk_size):\n update_downloads.delay(ids, countdown=countdown)\n countdown += seconds_between\n\n\n@cronjobs.register\ndef mkt_gc(**kw):\n \"\"\"Site-wide garbage collections.\"\"\"\n days_ago = lambda days: datetime.today() - timedelta(days=days)\n\n log.debug('Collecting data to delete')\n logs = (ActivityLog.objects.filter(created__lt=days_ago(90))\n .exclude(action__in=amo.LOG_KEEP).values_list('id', flat=True))\n\n for chunk in chunked(logs, 100):\n chunk.sort()\n log.debug('Deleting log entries: %s' % str(chunk))\n amo.tasks.delete_logs.delay(chunk)\n\n # Clear oauth nonce rows. These expire after 10 minutes but we're just\n # clearing those that are more than 1 day old.\n Nonce.objects.filter(created__lt=days_ago(1)).delete()\n\n # Delete the dump apps over 30 days.\n for app in os.listdir(settings.DUMPED_APPS_PATH):\n app = os.path.join(settings.DUMPED_APPS_PATH, app)\n if (os.stat(app).st_mtime < time.time() -\n settings.DUMPED_APPS_DAYS_DELETE):\n log.debug('Deleting old tarball: {0}'.format(app))\n os.remove(app)\n\n # Delete the dumped user installs over 30 days.\n tarball_path = os.path.join(settings.DUMPED_USERS_PATH, 'tarballs')\n for filename in os.listdir(tarball_path):\n filepath = os.path.join(tarball_path, filename)\n if (os.stat(filepath).st_mtime < time.time() -\n settings.DUMPED_USERS_DAYS_DELETE):\n log.debug('Deleting old tarball: {0}'.format(filepath))\n os.remove(filepath)\n","sub_path":"mkt/webapps/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"15151522","text":"\"\"\"\nMethods that execute specific queries against the SQLite database for the CONDITIONS table.\nThis supports the policy_sentry query functionality\n\"\"\"\nfrom sqlalchemy import and_\nfrom policy_sentry.shared.database import ConditionTable, ActionTable, ArnTable\nfrom policy_sentry.util.conditions import translate_condition_key_data_types\n\n\n# Per service\ndef get_condition_keys_for_service(db_session, service):\n \"\"\"\n Get a list of available conditions per AWS service\n\n :param db_session: SQLAlchemy database session object\n :param service: An AWS service prefix, like `s3` or `kms`\n :return: A list of condition keys\n \"\"\"\n results = []\n rows = db_session.query(\n ConditionTable.condition_key_name,\n ConditionTable.condition_value_type,\n ConditionTable.description,\n ).filter(ConditionTable.service.like(service))\n for row in rows:\n results.append(str(row.condition_key_name))\n return results\n\n\n# Per condition key name\ndef get_condition_key_details(db_session, service, condition_key_name):\n \"\"\"\n Get details about a specific condition key in JSON format\n\n :param db_session: SQLAlchemy database session object\n :param service: An AWS service prefix, like `ec2` or `kms`\n :param condition_key_name: The name of a condition key, like `ec2:Vpc`\n :return: Metadata about the condition key\n \"\"\"\n rows = db_session.query(\n ConditionTable.condition_key_name,\n ConditionTable.condition_value_type,\n ConditionTable.description,\n ).filter(\n and_(\n ConditionTable.condition_key_name.like(condition_key_name),\n ConditionTable.service.like(service),\n )\n )\n result = rows.first()\n output = {\n \"name\": result.condition_key_name,\n \"description\": result.description,\n \"condition_value_type\": result.condition_value_type,\n }\n return output\n\n\ndef get_conditions_for_action_and_raw_arn(db_session, action, raw_arn):\n \"\"\"\n Get a list of conditions available to an action.\n\n :param db_session: SQLAlchemy database session object\n :param action: The IAM action, like s3:GetObject\n :param raw_arn: The raw ARN format specific to the action\n :return:\n \"\"\"\n service, action_name = action.split(\":\")\n\n if raw_arn == \"*\":\n rows = db_session.query(ActionTable).filter(\n and_(\n ActionTable.service.ilike(service),\n ActionTable.name.ilike(action_name),\n ActionTable.resource_arn_format.is_(raw_arn),\n )\n )\n else:\n rows = db_session.query(ActionTable).filter(\n and_(\n ActionTable.service.ilike(service),\n ActionTable.name.ilike(action_name),\n ActionTable.resource_arn_format.ilike(raw_arn),\n )\n )\n result = rows.first()\n if result.condition_keys is None:\n return False\n else:\n condition_keys_list = result.condition_keys.split(\",\")\n return condition_keys_list\n\n\ndef get_condition_keys_available_to_raw_arn(db_session, raw_arn):\n \"\"\"\n Get a list of condition keys available to a RAW ARN\n\n :param db_session: SQLAlchemy database session object\n :param raw_arn: The value in the database, like arn:${Partition}:s3:::${BucketName}/${ObjectName}\n \"\"\"\n rows = db_session.query(ArnTable).filter(ArnTable.raw_arn.like(raw_arn))\n result = rows.first()\n if result.condition_keys:\n condition_keys = result.condition_keys.split(\",\")\n return condition_keys\n else:\n return False\n\n\ndef get_condition_value_type(db_session, condition_key):\n \"\"\"\n Get the data type of the condition key - like Date, String, etc.\n :param db_session: SQLAlchemy database session object\n :param condition_key: A condition key, like a4b:filters_deviceType\n :return:\n \"\"\"\n rows = db_session.query(ConditionTable).filter(\n ConditionTable.condition_key_name.ilike(condition_key)\n )\n result = rows.first()\n if result is None:\n raise Exception(\n f\"There is no condition key titled {condition_key}. Please provide a valid condition key. \"\n f\"\\nYou can query available condition keys with query command, such as the following: \"\n f\"\\n\\tpolicy_sentry query condition-table --service ec2\"\n )\n condition_value_type = translate_condition_key_data_types(\n result.condition_value_type\n )\n return condition_value_type\n","sub_path":"policy_sentry/querying/conditions.py","file_name":"conditions.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68230323","text":"import os\nfrom glob import glob\nfrom typing import List\n\nimport pandas as pd\nfrom PIL import Image\nfrom torch.utils import data\nfrom torchvision import transforms as T\n\nimport environments\n\n\nclass AbstractDataset(data.Dataset):\n root_path = None\n meta_filename = 'meta.csv'\n relative_path = True\n\n label_colname = 'label'\n img_colname = 'img_path'\n\n def __init__(self,\n phase='train',\n input_shape=(1, 128, 128),\n recreate=False):\n\n self.phase = phase\n self.input_shape = input_shape\n if self.phase == 'train':\n self.transforms = T.Compose([\n T.RandomCrop(self.input_shape[1:]),\n T.RandomGrayscale(),\n T.RandomHorizontalFlip(),\n T.ToTensor(),\n ])\n else:\n self.transforms = T.Compose([\n T.CenterCrop(self.input_shape[1:]),\n T.ToTensor(),\n ])\n\n self.df_meta = self.read_metadata(force=recreate)\n self.index_to_data = self.df_meta.to_dict(orient='index')\n\n def __str__(self):\n cls_name = self.__class__.__name__\n s = cls_name.replace('Dataset', '')\n s = s.lower()\n return s\n\n @classmethod\n def name(cls):\n s = cls.__name__\n s = s.replace('Dataset', '')\n s = s.lower()\n return s\n\n @property\n def meta_path(self):\n return os.path.join(self.root_path, self.meta_filename)\n\n @property\n def exist_metadata(self):\n return os.path.exists(self.meta_path)\n\n @property\n def is_greyscale(self):\n return self.input_shape[0] == 1\n\n @property\n def img_to(self):\n if self.is_greyscale:\n return 'L'\n else:\n return 'RGB'\n\n def read_metadata(self, force=False):\n if self.exist_metadata and not force:\n return pd.read_csv(self.meta_path)\n\n print('create metadata')\n df = self.create_metadata()\n df.to_csv(self.meta_path, index=False)\n return df\n\n def create_metadata(self) -> pd.DataFrame:\n raise NotImplementedError()\n\n @property\n def n_classes(self):\n return len(self.df_meta[self.label_colname].unique())\n\n def __getitem__(self, index):\n data = self.index_to_data[index]\n img_path, label = data[self.img_colname], data[self.label_colname]\n\n if self.relative_path:\n img_path = os.path.join(self.root_path, img_path)\n data = Image.open(img_path)\n data = data.convert(self.img_to)\n data = self.transforms(data)\n return data, label\n\n def __len__(self):\n return len(self.df_meta)\n\n\nclass CASIAFullDataset(AbstractDataset):\n \"\"\"\n CASIA Full Dataset\n\n あまり画像枚数が多くない人物が増えると学習が上手く行かないと考えて\n 画像枚数の最小値 `min_value_count` を設定できるようにしています.\n\n \"\"\"\n root_path = os.path.join(environments.DATASET_DIR, 'CASIA-WebFace')\n relative_path = False\n meta_filename = 'meta_full.csv'\n min_value_count = 20\n\n def create_metadata(self):\n img_paths = glob(os.path.join(self.root_path, '*/*.jpg'))\n df_meta = pd.DataFrame(img_paths, columns=['img_path'])\n df_meta['dir_name'] = [str(p.split('/')[-2]) for p in img_paths]\n vc = df_meta.dir_name.value_counts()\n use_dirnames = self.get_use_dirnames(vc)\n df_label = pd.DataFrame(use_dirnames, columns=['dir_name'])\n df_label.index.name = 'label'\n df_label = df_label.reset_index()\n df_meta = pd.merge(df_meta, df_label, on='dir_name', how='right')\n return df_meta\n\n def get_use_dirnames(self, vc) -> List[str]:\n use = vc[vc >= self.min_value_count]\n return use.index\n\n\nclass CASIADataset(CASIAFullDataset):\n \"\"\"\n CASIA (mini) Dataset\n\n 200 枚の画像がない人物を弾いています\n \"\"\"\n min_value_count = 200\n meta_filename = f'meta_{min_value_count}.csv'\n\n\nclass CASIAAllDataset(CASIAFullDataset):\n \"\"\"\n CASIA Dataset using all images\n \"\"\"\n min_value_count = 0\n meta_filename = f'meta_{min_value_count}.csv'\n\n\nclass CelebaDataset(AbstractDataset):\n root_path = os.path.join(environments.DATASET_DIR, 'celeba')\n relative_path = True\n n_classes = 2000\n\n\nclass CASIAAlignDataset(AbstractDataset):\n root_path = os.path.join(environments.DATASET_DIR, 'casiafull_polished')\n relative_path = True\n\n def read_metadata(self, force=False):\n df = pd.read_csv(self.meta_path)\n df = df[~df[self.img_colname].isnull()].reset_index(drop=True)\n return df\n\n\nclass CASIAAlign112Dataset(AbstractDataset):\n root_path = os.path.join(environments.DATASET_DIR, 'casiaall_112_pad=0.2')\n relative_path = True\n\n\ndef get_dataset(name, *args, **kwargs) -> AbstractDataset:\n all_datasets = [\n CASIAFullDataset,\n CASIADataset,\n CASIAAllDataset,\n CelebaDataset,\n CASIAAlignDataset,\n CASIAAlign112Dataset\n ]\n\n for d in all_datasets:\n if d.name() == name:\n return d(*args, **kwargs)\n\n raise ModuleNotFoundError()\n","sub_path":"data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"217410119","text":"with open(\"data\") as f:\n data = f.read().strip().split(\",\")\n data = [int(x) for x in data if len(x) != 0]\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nd = np.array(data).reshape((520, 504))/2\n\nprint(d.shape)\n\nplt.imshow(d, cmap=\"Greys\")\nplt.show()\n","sub_path":"renderer/plot_data.py","file_name":"plot_data.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"325531390","text":"from indexapp.models import TBook\n\n\nclass Car_item():\n def __init__(self, book, number): # book为model对象\n self.book = book\n self.number = int(number)\n\n def sum(self):\n self.one_total_price = float(self.book.book_dprice) * int(self.number)\n self.one_save_price = float(self.book.book_price - self.book.book_dprice) * int(self.number)\n\n\nclass Car():\n def __init__(self):\n self.car_item = []\n self.del_car_item = []\n self.total_price = 0\n self.save_price = 0\n\n def sums(self):\n self.total_price = 0\n self.save_price = 0\n for i in self.car_item:\n self.total_price += float(float(i.book.book_dprice) * int(i.number))\n self.save_price += float((float(i.book.book_price) - float(i.book.book_dprice)) * int(i.number))\n\n def add_item(self, book_id, number=1):\n for i in self.car_item:\n print(number, 127)\n print(i.book.book_id)\n print(book_id)\n if int(i.book.book_id) == int(book_id):\n i.number += int(number)\n i.sum()\n self.sums()\n # print('添加成功')\n return\n print(number,'添加成功')\n self.car_item.append(Car_item(TBook.objects.filter(book_id=book_id)[0], 1))\n self.sums()\n\n def del_item(self, book_id):\n print('进入删除aaaaaaaaaaaaaaaaaaaaaaaaa')\n for i in self.car_item:\n print('进入循环aaaaaaaaaaaaaaaaaaaaaaaaa')\n if int(i.book.book_id) == int(book_id):\n self.car_item.remove(i)\n self.del_car_item.append(i)\n self.sums()\n\n def recover_item(self, book_id):\n for i in self.del_car_item:\n if int(i.book.book_id) == int(book_id):\n self.del_car_item.remove(i)\n self.add_item(book_id)\n self.sums()\n\n def change_item(self, book_id, number):\n for i in self.car_item:\n if int(i.book.book_id) == int(book_id):\n i.number = int(number)\n i.sum()\n self.sums()\n\n\n","sub_path":"项目/dang/carapp/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"156617803","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\n\n\n\n# Create your views here.\n\n\nfrom .models import Meal\nfrom .forms import MealForm\n\ndef index(request):\n\ttemplate = 'list.html'\n\tmeals = Meal.objects.all()\n\tcontext = {\n\t\t'meals': meals,\n\t}\n\n\treturn render(request, template, context)\n\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse_lazy\ndef add_meal(request):\n\ttemplate = \"add_meal.html\"\n\n\tif request.method == \"POST\":\n\t\t\n\t\tform = MealForm(request.POST)\n\t#print request.POST\n\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn HttpResponseRedirect(reverse_lazy('food:index'))\n\n\telse:\n\t\tcontext = {\n\n\t\t\t'meal_form': MealForm(),\n\t\t}\n\treturn render(request, template, context)\n\n\ndef delete_meal(request, meal_id):\n\tmeal = Meal.objects.get(id=int(meal_id))\n\n\tmeal.delete()\n\treturn HttpResponseRedirect(reverse_lazy('food:index'))\n\n\n\ndef update_meal(request, meal_id):\n\ttemplate = \"update_meal.html\"\n\tmeal = Meal.objects.get(id=int(meal_id))\n\n\tif request.method == \"POST\":\n\t\tform = MealForm(request.POST, instance=meal)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\treturn HttpResponseRedirect(reverse_lazy('food:index'))\n\n\n\telse:\n\t\tcontext = {\n\n\t\t\t'meal_form': MealForm(instance=meal),\n\n\t\t}\n\treturn render(request, template, context)\n\n\n\n\n","sub_path":"django_exer1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"600432341","text":"# -*- coding: utf-8 -*-\nfrom django.http import HttpResponse\nimport re\nimport os\nfrom tastypie import resources\n\nfrom tastypie.resources import ModelResource, Resource, ALL_WITH_RELATIONS, fields, Bundle\nfrom test.models import Lesson, Test, Question\nfrom test import results\nfrom zno.settings import GOOGLE_ANALYTICS_ID\nfrom UniversalAnalytics import Tracker\n\n\ndef build_content_type(format, encoding='utf-8'):\n \"\"\"\n Appends character encoding to the provided format if not already present.\n \"\"\"\n if 'charset' in format:\n return format\n\n return \"%s; charset=%s\" % (format, encoding)\n\n\nclass UTFModelResource(resources.ModelResource):\n def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):\n \"\"\"\n Extracts the common \"which-format/serialize/return-response\" cycle.\n\n Mostly a useful shortcut/hook.\n \"\"\"\n desired_format = self.determine_format(request)\n serialized = self.serialize(request, data, desired_format)\n return response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs)\n\n\nclass LessonResource(UTFModelResource):\n class Meta:\n queryset = Lesson.objects.all()\n resource_name = 'lesson'\n excludes = ['pic_header', 'docs_site', 'docs_books', 'docs_official']\n\n\nclass TestResource(UTFModelResource):\n class Meta:\n queryset = Test.objects.filter(is_public=1, api_availiable__lte=1)\n resource_name = 'test'\n include_resource_uri = False\n\n def dehydrate(self, bundle):\n bundle.data['lesson_id'] = bundle.obj.lesson_id\n return bundle\n\n\nclass QuestionResource(UTFModelResource):\n test = fields.ForeignKey(TestResource, 'test')\n\n class Meta:\n queryset = Question.objects.filter(test__api_availiable__lte=1).order_by('id_on_test')\n resource_name = 'question'\n include_resource_uri = False\n filtering = {\n 'test': ALL_WITH_RELATIONS,\n }\n\n def dispatch(self, request_type, request, **kwargs):\n if 'test' in request.GET:\n tracker = Tracker.create(GOOGLE_ANALYTICS_ID, client_id=request.META.get('HTTP_X_REAL_IP'))\n tracker.send('event', 'API', 'test', request.GET['test'])\n\n return super(QuestionResource, self).dispatch(request_type, request, **kwargs)\n\n def dehydrate(self, bundle):\n images = []\n images_relative_url = ''\n\n pics = re.findall('src=\"(.*?)\"', bundle.obj.question + bundle.obj.answers)\n for one_pic in pics:\n if not any(d['name'] == os.path.basename(one_pic) for d in images):\n images.append({'name': os.path.basename(one_pic)})\n images_relative_url = os.path.dirname(one_pic)\n\n if images:\n bundle.data['images'] = images\n bundle.data['images_relative_url'] = images_relative_url\n\n bundle.data['correct_answer'] = {\n 1: int(bundle.obj.correct_answer),\n 2: int(bundle.obj.correct_answer),\n 3: int(bundle.obj.correct_answer),\n 4: int(bundle.obj.correct_answer),\n 5: float(bundle.obj.correct_answer)\n }[bundle.obj.type_question]\n\n if bundle.obj.parent_question:\n bundle.data['parent_question'] = Question.objects.get(test_id=bundle.obj.test_id,\n id_on_test=bundle.obj.parent_question.id_on_test).question\n return bundle\n\n\nclass Result(object):\n pass\n\n\nclass ResultResource(Resource):\n zno_ball = fields.FloatField(attribute='zno_ball')\n test_id = fields.IntegerField(attribute='test_id')\n test_ball = fields.IntegerField(attribute='test_ball')\n\n class Meta:\n resource_name = 'result'\n object_class = Result\n include_resource_uri = False\n filtering = {\n \"test_id\": ('exact', ),\n }\n\n def get_object_list(self, request, parent_id=None):\n result = []\n\n for result_tests in results.tests_results:\n question_id = 0\n for result_test in results.tests_results[result_tests]:\n temp = Result()\n temp.test_id = result_tests\n temp.zno_ball = result_test\n temp.test_ball = question_id\n if parent_id and result_tests == parent_id:\n result.append(temp)\n elif not parent_id:\n result.append(temp)\n\n question_id += 1\n return result\n\n def detail_uri_kwargs(self, bundle_or_obj):\n kwargs = {}\n\n if isinstance(bundle_or_obj, Bundle):\n kwargs['pk'] = bundle_or_obj.obj.test_id\n else:\n kwargs['pk'] = bundle_or_obj.test_id\n\n return kwargs['pk']\n\n def obj_get_list(self, bundle, **kwargs):\n return self.get_object_list(self, parent_id=int(bundle.request.GET.get('test_id', 1)))\n\n def get_detail(self, request, **kwargs):\n return self.get_detail(self)\n\n def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):\n \"\"\"\n Extracts the common \"which-format/serialize/return-response\" cycle.\n\n Mostly a useful shortcut/hook.\n \"\"\"\n desired_format = self.determine_format(request)\n serialized = self.serialize(request, data, desired_format)\n return response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs)\n","sub_path":"test/api/v1.py","file_name":"v1.py","file_ext":"py","file_size_in_byte":5500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558106185","text":"import numpy as np\n\n\ndef cdf(ax, values, bins='exact', range=None, **kwargs):\n \"\"\"Plot the empirical CDF.\n\n Parameters\n ----------\n ax : matplotlib.pyplot.Axes\n The axis to plot on\n Values : array-like\n The data to be plotted.\n bins\n See matplotlib.pyplot.hist documentation.\n Can also be 'exact' to calculate the exact empirical CDF\n range\n See matplotlib.pyplot.hist documentation.\n **kwargs\n Any additional keyword arguments are passed to the plotting function.\n\n \"\"\"\n if bins == 'exact':\n bins = np.unique(np.sort(values))\n if len(bins) == 1:\n return None, None\n hist_counts, hist_bins = np.histogram(values, bins=bins, range=range)\n\n cum_counts = np.cumsum(hist_counts)\n cdf = cum_counts * 1.0 / cum_counts[-1]\n\n # Want to plot each value at the right side of the bin, but then also put\n # back in value for the beginning of the first bin\n cdf_zero = np.sum(values <= hist_bins[0]) * 1.0 / cum_counts[-1]\n cdf = np.hstack([cdf_zero, cdf])\n\n ax.plot(hist_bins, cdf, **kwargs)\n\n ax.set_ylim((0, 1))\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n ax.tick_params(axis='x', direction='out')\n ax.tick_params(axis='y', direction='out')\n ax.set_ylabel('Cumulative probability')\n\n return hist_bins, cdf","sub_path":"lab_repo/misc/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"474907735","text":"#!/usr/bin/env python3 \n\nimport unittest \nimport numpy as np\nimport struct\nimport os\nimport tempfile\nimport subprocess \n\nfrom backend.branch_analysis import reconvergence_analysis \nimport program.prog_api as prog_api \nimport config.config_api as config_api \nimport simulator.sim_api as sim_api \n\nNUM_THREADS_X = 32\nNUM_THREADS_Y = 4\nBLOCK_SIZE = 32\n\n\ndef _py_transpose(input_matrix, num_rows, num_cols):\n output_matrix = np.zeros((num_rows * num_cols))\n num_blocks = (num_rows * num_cols) // (BLOCK_SIZE * BLOCK_SIZE)\n for bid in range(num_blocks):\n for i in range(BLOCK_SIZE):\n for j in range(BLOCK_SIZE):\n slice_id = i // NUM_THREADS_Y \n row_id = i % NUM_THREADS_Y \n val = input_matrix[\n slice_id * NUM_THREADS_X * NUM_THREADS_Y * num_blocks\n + bid * NUM_THREADS_X * NUM_THREADS_Y\n + row_id * NUM_THREADS_X + j]\n\n slice_id = j // NUM_THREADS_Y\n row_id = j % NUM_THREADS_Y \n output_matrix[\n slice_id * NUM_THREADS_X * NUM_THREADS_Y * num_blocks\n + bid * NUM_THREADS_X * NUM_THREADS_Y\n + row_id * NUM_THREADS_X + i] = val \n\n return output_matrix.astype(np.float32) \n\n\nclass TestMatrixTrans(unittest.TestCase): \n\n def setUp(self):\n self.curr_dir = os.path.dirname(os.path.realpath(__file__))\n self.proj_dir = os.path.dirname(os.path.dirname(self.curr_dir))\n _, self.ptx_file = tempfile.mkstemp(suffix=\".ptx\", dir=self.curr_dir)\n\n cuda_file_path = os.path.join(\n self.proj_dir, \"benchmark\", \"matrixtrans\", \"matrixtrans_kernel.cu\"\n )\n self.assertTrue(os.path.isfile(cuda_file_path))\n self.assertTrue(os.path.isfile(self.ptx_file))\n\n subprocess.run(\n [\"nvcc\", \"-O2\", \"--ptx\", \"-o\", self.ptx_file, cuda_file_path], \n check=True\n )\n\n self.raw_kernel_list = prog_api.load_kernel(self.ptx_file)\n self.kernel_list = []\n for each_kernel in self.raw_kernel_list:\n output_kernel = reconvergence_analysis(each_kernel, mode=\"instr\")\n self.kernel_list.append(output_kernel)\n self.config = config_api.load_hardware_config() \n return \n\n def tearDown(self):\n os.remove(self.ptx_file)\n\n def _run_matrix_trans(self, num_rows, num_cols, \n grid_dim, block_dim, mapping_dict):\n self.assertTupleEqual(block_dim, (1, NUM_THREADS_Y, NUM_THREADS_X))\n\n hardware = sim_api.init_hardware(self.config)\n ptr_input = hardware.mem.allocate(num_rows * num_cols * 4)\n ptr_output = hardware.mem.allocate(num_rows * num_cols * 4)\n hardware.mem.finalize() \n\n input_matrix = np.random.rand(num_rows * num_cols).astype(np.float32)\n hardware.mem.set_value(ptr_input, input_matrix.tobytes())\n\n total_cycles, sim_freq = hardware.run_simulation(\n kernel=self.kernel_list[0],\n kernel_args=[ptr_input, ptr_output, num_rows, num_cols],\n grid_dim=grid_dim,\n block_dim=block_dim,\n block_schedule=mapping_dict, \n )\n\n output_buffer = hardware.mem.get_value(ptr_output, \n num_rows * num_cols * 4)\n sim_results = np.array(\n struct.unpack(\"{}f\".format(num_rows * num_cols), output_buffer)\n ).astype(np.float32) \n\n groud_truth = _py_transpose(input_matrix, num_rows, num_cols)\n\n np.testing.assert_allclose(sim_results, groud_truth, atol=1e-6)\n return \n\n def test_single_threadblock(self):\n self._run_matrix_trans(\n num_rows=32,\n num_cols=32,\n grid_dim=(1, 1, 1),\n block_dim=(1, 4, 32),\n mapping_dict={0: 0},\n )\n return\n\n def test_multiple_matrix_blocks(self):\n self._run_matrix_trans(\n num_rows=(32 * 2),\n num_cols=(32 * 3),\n grid_dim=(1, 1, 4),\n block_dim=(1, 4, 32),\n mapping_dict={0: 0, 1: 1, 2: 2, 3: 3},\n )\n return \n\n\nif __name__ == \"__main__\":\n unittest.main() \n","sub_path":"simulator/test/test_matrixtrans.py","file_name":"test_matrixtrans.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128185530","text":"import time\nimport scapy.all as scapy\n\nfrom utils import clear, standardPorts, saveToFile\n\n\ndef netscan():\n ''' This function is the main netscan loop\n '''\n\n while True:\n clear()\n\n # Print Menu\n print(\"######################\")\n print(\"\")\n print(\"PCS NetScan Menu\")\n print(\"\")\n print(\"1 > SoftScan - Scan net address\")\n print(\"2 > AdavancedScan - address and common ports\")\n print(\"3 > CustomScan - address and common ports\")\n print(\"0 > Back to MainMenu\")\n print(\"\")\n print(\"######################\")\n print(\"\")\n\n choice = input(\"Your choice: \")\n\n # Launch PCS SoftSCan\n if choice == \"1\":\n target = input(\"Target ip or subnet (xx.xx.xx.xx/yy): \")\n result = softScan(target)\n print(result)\n\n save_continue = input(\"\\nPress s to save result or any other key to continue \")\n\n if save_continue == \"s\" or save_continue == \"S\":\n saveToFile(result)\n \n # Launch PCS AdvancedScan\n elif choice == \"2\":\n target = input(\"Target ip or subnet (xx.xx.xx.xx/yy): \")\n list_flag_string = input(\"1. for light port list (default - faster) or 2. for full port list (slower): \")\n if list_flag_string == \"2\":\n list_flag = True\n else:\n list_flag = False\n\n result = advancedScan(target, list_flag)\n print(result)\n\n save_continue = input(\"\\nPress s to save result or any other key to continue \")\n\n if save_continue == \"s\" or save_continue == \"S\":\n saveToFile(result)\n\n # Launch PCS CustomScan\n elif choice == \"3\":\n try:\n target = input(\"Target ip or subnet (\\\"xx.xx.xx.xx/yy\\\"): \")\n ports_string = input(\"Target ports (\\\"22 80 443 ...\\\") : \")\n ports = list(map(int,ports_string.split()))\n method = input(\"Method (\\\"syn\\\" or \\\"udp\\\" or \\\"xmas\\\"): \")\n timeout = input(\"Timeout of port scan (seconds): \")\n result = customScan(target, ports, method, float(timeout))\n\n print(result)\n\n save_continue = input(\"\\nPress s to save result or any other key to continue \")\n\n if save_continue == \"s\" or save_continue == \"S\":\n saveToFile(result)\n\n except Exception as e:\n print(\"SCAN ERROR: {}\".format(e))\n \n input(\"Press any key to continue . . .\")\n\n # Exit\n elif choice == \"0\":\n break\n\n # Wrong choice\n else:\n clear()\n print(\"WRONG CHOICE!\")\n time.sleep(2)\n\ndef _targetIPScan(target_subnet):\n '''A function to scan a target subnet \n\n Params:\n target_subnet (String) - XX.XX.XX.XX/YY\n '''\n arp_req_frame = scapy.ARP(pdst = target_subnet)\n broadcast_ether_frame = scapy.Ether(dst = \"ff:ff:ff:ff:ff:ff\")\n broadcast_ether_arp_req_frame = broadcast_ether_frame / arp_req_frame\n\n\n ans = scapy.srp(broadcast_ether_arp_req_frame, timeout = 1, verbose = False)[0]\n result = []\n\n for sent, received in ans:\n result.append({'IP': received.psrc, 'MAC': received.hwsrc})\n\n return result\n\n\ndef _targetPortScan(target_ip, target_ports, method, timeout=1):\n '''A function to scan ports of a target ip.\n Supported scan methods: \"syn\" - \"udp\" - \"xmas\".\n Supported TCP port status: \"unknow\", \"mute\", \"open\", \"closed\", \"filtered TCP\" , \"filtered ICMP\"\n Supported UDP port status: \"unknow\", \"open\", \"closed\"\n\n Params\n target_ip (string) - The target IP\n target_ports ([int]) - A list with target ports\n method (string) - Port scsan method. \n \n Return\n open_ports ([(int,string)]) - A list of tuples with scaned ports with status\n '''\n\n scanned_ports = []\n\n ########################################\n # SYN PORT SCAN\n if method == \"syn\":\n for target_port in target_ports:\n src_port = scapy.RandShort()\n port_status = \"mute\"\n\n response = scapy.sr1(scapy.IP(dst=target_ip)/scapy.TCP(sport= src_port, dport=target_port, flags=\"S\"), verbose=False, timeout=timeout)\n\n if response != None:\n if response.haslayer(scapy.TCP):\n if response[scapy.TCP].flags == 18:\n port_status = \"open\" \n elif response[scapy.TCP].flags == 20:\n port_status = \"closed\"\n else:\n port_status = \"filtered TCP\"\n\n elif response.haslayer(scapy.ICMP):\n port_status = \"filtered ICMP\"\n\n else:\n port_status = \"unknow\"\n \n else:\n port_status = \"mute\"\n\n scanned_ports.append((target_port, port_status))\n port_status = \"mute\"\n\n return scanned_ports\n\n ########################################\n # UPD PORT SCAN\n elif method == \"udp\":\n for target_port in target_ports:\n port_status = \"unknow\"\n\n response = scapy.sr1(scapy.IP(dst=target_ip)/scapy.UDP(dport=target_port), verbose=False, timeout=timeout)\n\n if response == None:\n port_status = \"unknow\"\n\t\t\n else:\n if response.haslayer(scapy.UDP):\n port_status = \"open\"\n else:\n port_status = \"unknown\"\n\n scanned_ports.append((target_port, port_status))\n port_status = \"unknown\"\n\n return scanned_ports\n\n ########################################\n # XMAS PORT SCAN\n elif method == \"xmas\":\n for target_port in target_ports:\n src_port = scapy.RandShort()\n port_status = \"mute\"\n\n response = scapy.sr1(scapy.IP(dst=target_ip)/scapy.TCP(sport= src_port, dport=target_port, flags=\"FPU\"), verbose=False, timeout=timeout)\n \n if response != None:\n if response.haslayer(scapy.TCP):\n if response[scapy.TCP].flags == 20:\n port_status = \"closed\"\n else:\n port_status = \"muted\"\n elif response.haslayer(scapy.ICMP):\n port_status = \"filtered ICMP\"\n else:\n port_status = \"unknow\"\n else:\n port_status = \"filtered\"\n\n scanned_ports.append((target_port, port_status))\n port_status = \"unknown\"\n\n return scanned_ports\n \n\n ########################################\n # WRONG METHOD\n else:\n return None\n\n\n\ndef softScan(target_subnet):\n '''A function to scan IP of a subnet via ARP.\n This scan only detects IP and MAC addresses within a subnet.\n\n Params:\n target_subnet (string) - Subnet string \"xx.xx.xx.xx./yy\"\n '''\n\n print(\">> PCS SoftScan in progress . . .\\n\")\n scan_result = _targetIPScan(target_subnet)\n result_string = \"\"\n for item in scan_result:\n result_string += \"Client retrieved: \\nIP: {} MAC: {}\\n\".format(item[\"IP\"], item[\"MAC\"])\n\n return result_string\n\ndef advancedScan(target_subnet, full_port_list = False):\n '''A function to scan IP of a subnet via ARP.\n This scan detects IP, MAC addresses and common TCP port status within a subnet.\n\n Params:\n target_subnet (string) - Subnet string \"xx.xx.xx.xx./yy\"\n full_port_list (boolean) - Flag to choice full/light port list\n '''\n\n print(\">> PCS AdvancedScan in progress . . .\\n\")\n scan_result = _targetIPScan(target_subnet)\n standard_ports_list = standardPorts(full_port_list)\n result_string = \"\"\n for item in scan_result:\n result_string += \"Client retrieved: \\nIP: {} MAC: {}\\n\".format(item[\"IP\"], item[\"MAC\"])\n\n scanned_ports = _targetPortScan(item[\"IP\"], standard_ports_list, \"syn\")\n\n for port in scanned_ports:\n if port[1] != \"closed\":\n result_string += \"Port {} is {}\\n\".format(port[0], port[1])\n\n result_string += \"----\\n\"\n\n return result_string\n \n\n\ndef customScan(target_subnet, target_ports=[], method=\"syn\", timeout=1):\n '''A function to scan IP of a subnet via ARP.\n This scan detects IP, MAC addresses and common TCP port status within a subnet.\n\n Params:\n target_subnet (string) - Subnet string \"xx.xx.xx.xx./yy\"\n '''\n\n print(\">> PCS CustomScan in progress . . .\\n\")\n scan_result = _targetIPScan(target_subnet)\n result_string = \"\"\n \n for item in scan_result:\n result_string += \"Client retrieved: \\nIP: {} MAC: {}\\n\".format(item[\"IP\"], item[\"MAC\"])\n\n scanned_ports = _targetPortScan(item[\"IP\"], target_ports, method)\n\n for port in scanned_ports:\n if port[1] != \"closed\":\n result_string += \"Port {} is {}\\n\".format(port[0], port[1])\n\n result_string += \"----\"\n\n return result_string\n\n\n\n","sub_path":"tools/netscan.py","file_name":"netscan.py","file_ext":"py","file_size_in_byte":9067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234950694","text":"import multiprocessing as mp\nimport os\nimport os.path as osp\nimport shutil\nfrom ogb.utils.torch_util import replace_numpy_with_torchtensor\nfrom ogb.utils.url import decide_download, download_url, extract_zip\nimport pandas as pd\nfrom tqdm import tqdm\nimport torch\n#os.system(\"taskset -p 0xff %d\" % os.getpid())\nfrom pathos.multiprocessing import ProcessPool\nfrom torch_geometric.data import InMemoryDataset, dataloader, Batch\nfrom torch_geometric.data import Data\nimport copy\nfrom itertools import repeat, product\nfrom utils.utils_mol import smiles2graph, smiles2subgraphs, get_global_features\n\n\n\nclass SubPygPCQM4MDataset(InMemoryDataset):\n\n\n def __init__(self, root='dataset', smiles2graph=smiles2graph, smiles2subgraphs=smiles2subgraphs,\n transform=None, pre_transform=None):\n '''\n Pytorch Geometric PCQM4M dataset object\n - root (str): the dataset folder will be located at root/pcqm4m_kddcup2021\n - smiles2graph (callable): A callable function that converts a SMILES string into a graph object\n * The default smiles2graph requires rdkit to be installed\n '''\n\n self.data, self.slices = [], {}\n self.original_root = root\n self.smiles2graph = smiles2graph\n self.smiles2subgraphs = smiles2subgraphs\n self.root = osp.join(root, 'pcqm4m_kddcup2021')\n self.folder = osp.join(root, 'pcqm4m_kddcup2021')\n self.version = 1\n self.url = f'http://ogb-data.stanford.edu/data/lsc/pcqm4m_kddcup2021.zip'\n self.extra =osp.join('/data/', 'processed/')\n\n # check version and update if necessary\n if osp.isdir(self.folder) and (not osp.exists(osp.join(self.folder, f'RELEASE_v{self.version}.txt'))):\n print('PCQM4M dataset has been updated.')\n if input('Will you update the dataset now? (y/N)\\n').lower() == 'y':\n shutil.rmtree(self.folder)\n\n super(SubPygPCQM4MDataset, self).__init__(self.folder, transform, pre_transform)\n self.data, self.slices = torch.load(self.processed_paths[0])\n\n self.nosubgraph_counter = 0\n self.cache={}\n\n\n\n @property\n def raw_file_names(self):\n return 'data.csv.gz'\n\n @property\n def processed_file_names(self):\n return 'geometric_data_processed.pt'\n\n\n def download(self):\n if decide_download(self.url):\n path = download_url(self.url, self.original_root)\n extract_zip(path, self.original_root)\n os.unlink(path)\n else:\n print('Stop download.')\n exit(-1)\n\n def read_subgraphs(self, idx):\n\n try:\n sub =torch.load(osp.join(self.extra, 'geometric_data_processed_data_{}.pt'.format(idx)))\n\n self.cache[idx] = sub\n except OSError:\n # we may be using too much memory\n del self.cache[list(self.cache.keys())[0]]\n try:\n sub = torch.load(osp.join(self.extra, 'geometric_data_processed_data_{}.pt'.format(idx)))\n self.cache[idx] = sub\n except:\n sub = []\n self.cache[idx] = sub\n\n except FileNotFoundError:\n sub = []\n self.cache[idx] = sub\n self.nosubgraph_counter += 1\n\n return sub\n #\n #\n # def _get_(self, idx):\n # if hasattr(self, '__data_list__'):\n # if self.__data_list__ is None:\n # self.__data_list__ = self.len() * [None]\n # else:\n # data = self.__data_list__[idx]\n # if data is not None:\n # return copy.copy(data)\n #\n # data = self.data.__class__()\n # if hasattr(self.data, '__num_nodes__'):\n # data.num_nodes = self.data.__num_nodes__[idx]\n #\n # for key in self.data.keys:\n # item, slices = self.data[key], self.slices[key]\n # start, end = slices[idx].item(), slices[idx + 1].item()\n # if torch.is_tensor(item):\n # s = list(repeat(slice(None), item.dim()))\n # s[self.data.__cat_dim__(key, item)] = slice(start, end)\n # elif start + 1 == end:\n # s = slices[start]\n # else:\n # s = slice(start, end)\n # data[key] = item[s]\n #\n # if hasattr(self, '__data_list__'):\n # self.__data_list__[idx] = copy.copy(data)\n #\n # return data\n #\n # def get(self, idx):\n # data = self._get_(idx)\n # # sub = self.cache.get(idx, None)\n # # if sub is None:\n # # sub = self.read_subgraphs(idx)\n # return (data, idx)\n # # return (data,sub)\n def get_data(self, graph):\n data = Data()\n if graph is not None:\n data.edge_index = torch.from_numpy(graph['edge_index']).to(torch.int64)\n data.edge_attr = torch.from_numpy(graph['edge_feat']).to(torch.int64)\n data.x = torch.from_numpy(graph['node_feat']).to(torch.int64)\n data.nn = int(graph['nodes_num'])\n data.smiles = str(graph[\"smiles\"]) # to check\n return data\n\n def get_data_subgraph(self,i, smiles):\n\n subgraphs = self.smiles2subgraphs(smiles)\n if len(subgraphs)>1:\n data_list = []\n for sub in subgraphs:\n data_list.append(self.get_data(sub))\n\n # print('Saving...', self.processed_paths[0] + 'data_{}.pt'.format(i))\n torch.save(Batch.from_data_list(data_list),osp.join(self.extra, 'geometric_data_processed_data_{}.pt'.format(i)))\n\n\n\n def get_data_graph(self, a ):\n i, smiles, homolumogap = a\n graph = self.smiles2graph(smiles)\n\n assert (len(graph['edge_feat']) == graph['edge_index'].shape[1])\n assert (len(graph['node_feat']) == graph['nodes_num'])\n\n data = self.get_data(graph)\n data.idx = int(i)\n data.__num_nodes__ = int(graph['nodes_num'])\n data.y = torch.Tensor([homolumogap])\n # Extra feautres : Getting mol data\n data.mol_attr = torch.from_numpy(get_global_features(smiles)).to(torch.float)\n # data.subgraphs = self.smiles2subgraphs(data.smiles)\n # data.nsub = len(data.subgraphs)\n # self.get_data_subgraph( i, smiles)\n return data\n\n\n\n def process(self):\n data_df = pd.read_csv(osp.join(self.raw_dir, 'data.csv.gz'))\n args = list(zip(data_df.idx, data_df.smiles, data_df.homolumogap))\n\n poolp = ProcessPool() # multiprocessing.pool.ThreadPool(200)\n print('Converting SMILES strings into graphs...')\n data_list = list(tqdm(poolp.imap(self.get_data_graph, args)))\n poolp.close()\n poolp.join()\n\n split_dict = self.get_idx_split()\n\n if self.pre_transform is not None:\n data_list = [self.pre_transform(data) for data in data_list]\n\n\n data, slices = self.collate(data_list)\n print('Saving...', self.processed_paths[0])\n torch.save((data, slices), self.processed_paths[0])\n\n\n\n\n def get_idx_split(self):\n split_dict = replace_numpy_with_torchtensor(torch.load(osp.join(self.root, 'split_dict.pt')))\n return split_dict\n\nif __name__ == '__main__':\n dataset = SubPygPCQM4MDataset(root=\"/usr/src/kdd/data_test7/\")\n print(dataset)\n print(dataset.data.edge_index)\n print(dataset.data.edge_index.shape)\n print(dataset.data.x.shape)\n print(dataset[50])\n print(dataset[50].y)\n\n\n","sub_path":"Dev/examples/WorkingMol/utils/sub_dataset_2.py","file_name":"sub_dataset_2.py","file_ext":"py","file_size_in_byte":7532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"482150474","text":"import logging\n\nimport requests\n\nfrom . import errors\n\n\nlogger = logging.Logger('yadisk-api')\n\n\n_CODE_TO_ERROR = {\n 401: errors.UnauthorizedError,\n 403: errors.ForbiddenError,\n 409: errors.DiskPathError,\n 404: errors.NotFoundError,\n 412: errors.PreconditionFailed,\n 413: errors.PayloadTooLarge,\n 500: errors.InternalServerError,\n 503: errors.ServiceUnavailable,\n 507: errors.InsufficientStorageError,\n}\n\nSTATUS_OK = 200\nSTATUS_CREATED = 201\nSTATUS_ACCEPTED = 202\nSTATUS_NO_CONTENT = 204\n\nOK_STATUSES = {\n STATUS_OK,\n STATUS_CREATED,\n STATUS_ACCEPTED,\n STATUS_NO_CONTENT,\n}\n\n\nclass Requester(object):\n _disk_url = 'https://cloud-api.yandex.net/v1/'\n\n def __init__(self, token):\n self._token = token\n\n def get(self, url, params=None, **kwargs):\n return self.wrap(requests.get)(url=url, params=params, **kwargs)\n\n def post(self, url, data=None, json=None, **kwargs):\n return self.wrap(requests.post)(url=url, data=data, json=json, **kwargs)\n\n def put(self, url, data=None, **kwargs):\n return self.wrap(requests.put)(url=url, data=data, **kwargs)\n\n def patch(self, url, data=None, **kwargs):\n return self.wrap(requests.patch)(url=url, data=data, **kwargs)\n\n def delete(self, url, **kwargs):\n return self.wrap(requests.delete)(url=url, **kwargs)\n\n def wrap(self, method):\n \"\"\"\n - Add extra headers to request\n - Change url\n - Handle response status code\n \"\"\"\n method_name = {\n self.get: 'GET',\n self.post: 'POST',\n self.put: 'PUT',\n self.patch: 'PATCH',\n self.delete: 'DELETE',\n }\n def wrapped(url, *args, **kwargs):\n absolute_url = kwargs.pop('absolute_url', False)\n if not absolute_url:\n url = '{}{}'.format(self._disk_url, url)\n if 'headers' not in kwargs:\n kwargs['headers'] = {}\n\n logger.debug('Call {!r} method by url={!r}'.format(method_name, url))\n if kwargs.pop('without_auth', False) is not True:\n kwargs['headers']['Authorization'] = 'OAuth {}'.format(self._token)\n response = method(url, *args, **kwargs)\n logger.debug('Response status_code={} by url={}/{}'.format(\n response.status_code,\n url,\n method_name\n ))\n if response.status_code in OK_STATUSES:\n return response\n\n try:\n response_msg = response.json()['message']\n except ValueError:\n response_msg = str(response.content)\n\n logger.error(\n 'Status_code={}; response body: {}; request_url={!r}; method={!r}'.format(\n response.status_code,\n response_msg,\n url,\n method,\n )\n )\n\n # handle status code\n if response.status_code not in _CODE_TO_ERROR:\n raise errors.RequestError(response_msg)\n\n raise _CODE_TO_ERROR[response.status_code](response_msg)\n\n return wrapped\n","sub_path":"yandex/requester.py","file_name":"requester.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"111706369","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'ytx'\n\nfrom pymongo import MongoClient\nimport time\nfrom selenium import webdriver\nimport os\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nimport pandas as pd\nimport json\nimport requests\nimport datetime\nimport tushare as ts\nimport interface_trade as trade_inf\nfrom strategy_roe import roe_strategy\nfrom conf import user\n\nchromedriver = \"D:\\chrome\\Google\\Chrome\\Application\\chromedriver.exe\" if user == 'viruser' else \"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\"\nos.environ[\"webdriver.chrome.driver\"] = chromedriver\n\nheaders = {\n \"Accept\": \"application/json, text/javascript, */*; q=0.01\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Referer\": \"http://mncg.10jqka.com.cn/cgiwt/index/index\",\n \"Accept-Language\": \"zh-CN\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko\",\n \"Host\": \"mncg.10jqka.com.cn\",\n \"Content-Length\": \"81\",\n \"DNT\": \"1\",\n \"Connection\": \"Keep-Alive\",\n \"Pragma\": \"no-cache\",\n \"Cookie\": \"Hm_lvt_78c58f01938e4d85eaf619eae71b4ed1=1503127213; Hm_lpvt_78c58f01938e4d85eaf619eae71b4ed1=1503127242; user=MDq62tK5tMy%2FzTo6Tm9uZTo1MDA6MTkzNDA3MDk0OjcsMTExMTExMTExMTEsNDA7NDQsMTEsNDA7NiwxLDQwOzUsMSw0MDoyNzo6OjE4MzQwNzA5NDoxNTAzMTI2OTMzOjo6MTM5MzMyMzU0MDo2MDQ4MDA6MDpjNmE4ZmYzYjFhMTBkNDZkMWU4ZmQ3NDc0MWJiZGYxMjpkZWZhdWx0XzI6MA%3D%3D; userid=183407094; u_name=%BA%DA%D2%B9%B4%CC%BF%CD; escapename=%25u9ed1%25u591c%25u523a%25u5ba2; ticket=82c4bb57c65d6d497633b2adc0fa65fa; PHPSESSID=e3cmnciurq7baui5mso2fatea6; isSaveAccount=0\",\n}\n\n\ndef connect_to_db(tablename):\n # client = MongoClient()\n # client = MongoClient('127.0.0.1', 27017)\n # 连接mongodb数据库\n client = MongoClient('mongodb://127.0.0.1:27017/')\n # 指定数据库名称\n db = client.local_project\n # 获取非系统的集合\n # xx = db.collection_names(include_system_collections=False)\n # 获取集合名\n collection = db[tablename]\n return collection\n\n\ndef read_hold_data(file_path):\n # date, ',', stock, ',', stock_name, ',', buy_price, ',', high_price, ',', buy_date, ',' , yes_quotation[3], yes_quotation[4], bef_yes_quotation[3], bef_yes_quotation[4]\n # date, ',', stock, ',', stock_name, ',', buy_price, ',', high_price, ',', buy_date\n positions_list = []\n with open(file_path, 'r') as test_file:\n result = test_file.readlines()\n for item in result:\n item_info_list = item.strip().split(',')\n id_str = item_info_list[0].strip()\n if id_str.startswith(''):\n id_str = id_str[1:]\n item_dict = dict(\n _id=id_str + '_' + item_info_list[1].strip(),\n calc_date=item_info_list[0].strip(),\n stock_code=item_info_list[1].strip(),\n stock_name=item_info_list[2].strip(),\n buy_price=item_info_list[3].strip(),\n high_price=item_info_list[4].strip(),\n buy_date=item_info_list[5].strip(),\n yes_high=item_info_list[6].strip(),\n yes_close=item_info_list[7].strip(),\n bef_yes_high=item_info_list[8].strip(),\n bef_yes_close=item_info_list[9].strip(),\n )\n positions_list.append(item_dict)\n return positions_list\n\n\ndef get_token():\n url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'\n values = {'corpid': 'wxf649ac329034ced5',\n 'corpsecret': '5uOQQnEaaTd462VuEE2MfTGS8hCKI6mUuWbk2q6tThvzc6V3OMI2K5IFO2rCGFxq',\n }\n req = requests.post(url, params=values)\n data = json.loads(req.text)\n return data[\"access_token\"]\n\n\ndef send_msg(_msg):\n url = \"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=\" + get_token()\n values = \"\"\"{\"touser\" : \"0\" ,\n \"toparty\":\"1\",\n \"msgtype\":\"text\",\n \"agentid\":\"0\",\n \"text\":{\n \"content\": \"%s\"\n },\n \"safe\":\"0\"\n }\"\"\" % ('今日应该卖出的股票:' + str(','.join(_msg)))\n # data = json.loads(values)\n requests.post(url, values)\n\ndef send_every_msg(_msg):\n url = \"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=\" + get_token()\n values = \"\"\"{\"touser\" : \"0\" ,\n \"toparty\":\"1\",\n \"msgtype\":\"text\",\n \"agentid\":\"0\",\n \"text\":{\n \"content\": \"%s\"\n },\n \"safe\":\"0\"\n }\"\"\" % (_msg)\n # data = json.loads(values)\n requests.post(url, values)\n\n\ndef write_hold_db(dbob, datas):\n for every_hold in datas:\n # dbob.update(every_hold)\n dbob.update({\"_id\": every_hold['_id']}, {\"$set\": every_hold}, upsert=True)\n\n\ndef write_mn_db(dbob, _date):\n for every_hold in get_mn_hold(_date):\n dbob.update({\"_id\": every_hold['_id']}, {\"$set\": every_hold}, upsert=True)\n\n\ndef check_holdindb(dbob, hold_date):\n temp_flag = dbob.find_one({\"calc_date\": hold_date})\n if temp_flag:\n return False\n else:\n return True\n\n\ndef check_mnindb(dbob, _date):\n temp_flag = dbob.find_one({\"real_date\": _date})\n if temp_flag:\n return False\n else:\n return True\n\n\ndef getdatafromdb(dbob, hold_date):\n return list(dbob.find({\"calc_date\": hold_date}))\n\n\ndef getmndatafromdb(dbob, hold_date):\n return list(dbob.find({\"real_date\": hold_date}))\n\n\ndef get_mn_hold(_date):\n # chromedriver = \"D:\\python\\Anaconda2\\chromedriver.exe\"\n\n browser = webdriver.Chrome(chromedriver)\n mn_tmp_hold_list = []\n try:\n # 登录\n # browser.get('http://upass.10jqka.com.cn/login?redir=HTTP_REFERER&sign=8fd3cc7c13f0c48fa2ff383a74a7b5b4')\n browser.get('http://upass.10jqka.com.cn/login')\n browser.implicitly_wait(3)\n browser.find_element_by_xpath(\"//input[@id='username']\").send_keys('hrbuy2012@163.com')\n browser.find_element_by_xpath(\"//input[@id='password']\").send_keys('a6120035')\n time.sleep(2)\n wait_second(browser)\n login = browser.find_element_by_xpath(\"//input[@id='loginBtn']\").click()\n wait_second(browser)\n browser.get('http://moni.10jqka.com.cn/')\n wait_second(browser)\n time.sleep(3)\n # 进入模拟交易界面\n browser.find_element_by_xpath(\"//a[@class='xzjrjyq']\").click()\n wait_second(browser)\n current_handle = browser.current_window_handle\n handles = browser.window_handles\n # 对窗口进行遍历\n for newhandle in handles:\n # 筛选新打开的窗口B\n if newhandle != current_handle:\n # 切换到新打开的窗口B\n browser.switch_to.window(newhandle)\n wait_second(browser)\n\n time.sleep(2)\n all_list = browser.find_elements_by_xpath(\"//tr[@class='red_font']\")\n all_list1 = browser.find_elements_by_xpath(\"//tr[@class='blue_font']\")\n all_list.extend(all_list1)\n\n tmp_date = pd.Timestamp.now().strftime(\"%Y%m%d\")\n for item in all_list:\n # 证券代码\t证券名称\t证券余额\t可用余额\t冻结数量\t股票实际\t成本价\t市价\t市值\t浮动盈亏\t盈亏比例(%)\n # print 'item:', str(item.text)\n if str(item.text).strip() == '':\n continue\n td_list = str(item.text).split(' ')\n code = td_list[0]\n name = td_list[1]\n if len(name.strip()) >= 9:\n xx = len(name.strip())\n remain_amount = td_list[2]\n can_use_amount = td_list[3]\n freezon_amount = td_list[4]\n real_amount = td_list[5]\n cost_price = td_list[6]\n current_price = td_list[7]\n current_value = td_list[8]\n current_profit = td_list[9]\n profit_rate = td_list[10]\n else:\n name = td_list[1].strip() + td_list[2].strip() + td_list[3].strip()\n remain_amount = td_list[4]\n can_use_amount = td_list[5]\n freezon_amount = td_list[6]\n real_amount = td_list[7]\n cost_price = td_list[8]\n current_price = td_list[9]\n current_value = td_list[10]\n current_profit = td_list[11]\n profit_rate = td_list[12]\n tem_dict = dict(\n _id=_date + '_' + code,\n real_date=_date,\n stock_code=code,\n stock_name=name,\n remain_amount=remain_amount,\n can_use_amount=can_use_amount,\n freezon_amount=freezon_amount,\n real_amount=real_amount,\n cost_price=cost_price,\n current_price=current_price,\n current_value=current_value,\n current_profit=current_profit,\n profit_rate=profit_rate,\n )\n if float(can_use_amount) > 0:\n mn_tmp_hold_list.append(tem_dict)\n except Exception as e:\n print(e)\n finally:\n cookie = [item[\"name\"] + \"=\" + item[\"value\"] for item in browser.get_cookies() if item[\"name\"] != \"log\"]\n # print cookie\n\n cookiestr = '; '.join(item for item in cookie)\n headers['Cookie'] = cookiestr\n browser.close()\n return mn_tmp_hold_list\n\n\ndef wait_second(browser):\n browser.implicitly_wait(10)\n time.sleep(3)\n\n\ndef get_yesterday_quotation(stock, st_date=None, ed_date=None):\n if st_date is None or ed_date is None:\n st_date = (pd.Timestamp(st_date) - datetime.timedelta(days=1)).strftime(\"%Y-%m-%d\")\n ed_date = (pd.Timestamp(ed_date) - datetime.timedelta(days=1)).strftime(\"%Y-%m-%d\")\n else:\n st_date = pd.Timestamp(st_date).strftime(\"%Y-%m-%d\")\n ed_date = pd.Timestamp(ed_date).strftime(\"%Y-%m-%d\")\n df = ts.get_hist_data(stock,start=st_date,end=ed_date) # Single stock symbol\n return df\n\n\ndef get_east_stock_price(stock):\n df = ts.get_realtime_quotes(stock) # Single stock symbol\n return df['price'][0]\n\n # url = 'http://hq.sinajs.cn/list=%s' % stock\n # req = requests.get(url)\n # request_text = req.text\n # price_list = request_text.split(',')\n # print price_list\n # open_price = price_list[1]\n # last_close_price = price_list[2]\n # now_price = price_list[3]\n # high_price = price_list[4]\n # low_price = price_list[5]\n\n # print 'open_price:',open_price,' ',\n # print 'last_close_price:',last_close_price,' ',\n # print 'now_price:',now_price,' ',\n # print 'high_price:',high_price,' ',\n # print 'low_price:',low_price,' ',\n # print 'profit:',(float(now_price) - float(last_close_price)) / float(last_close_price)\n\n # print req.text.encode('latin1').decode('gbk')\n\n # print 'now_price:',now_price\n # return now_price\n\n\ndef run_project(tmp_date, yesterday):\n # 持仓数据文件路径\n file_path = 'D:\\\\positions.txt'\n # 创建数据库某表链接对象\n db_object = connect_to_db('finance_infos')\n mn_db_object = connect_to_db('mn_day_hold')\n # 从文件中获取持仓数据\n hold_data = read_hold_data(file_path)\n print(len(hold_data))\n # 判断是否已经将持仓数据存入数据库\n if check_holdindb(db_object, yesterday):\n print(\"start insert hold_data\")\n write_hold_db(db_object, hold_data)\n\n # 理论持仓数据\n db_hold_data = getdatafromdb(db_object, yesterday)\n # print db_hold_data\n\n # 判断是否已经将模拟持仓数据存入数据库\n if check_mnindb(mn_db_object, tmp_date):\n print(\"start insert real_data\")\n write_mn_db(mn_db_object, tmp_date)\n\n # 模拟持仓数据\n db_mn_data = getmndatafromdb(mn_db_object, tmp_date)\n mn_hold_stocks = [str(item['stock_code']) for item in db_mn_data]\n hold_stocks = [str(item['stock_code']) for item in db_hold_data]\n\n should_sale_stocks = list(set(mn_hold_stocks).difference(set(hold_stocks)))\n if should_sale_stocks:\n print('今日应该卖出的股票:' + str(','.join(should_sale_stocks)))\n # send_msg(should_sale_stocks)\n\n # db_object = connect_to_db('day_hold')\n # operating_db(db_object)\n return db_hold_data, db_mn_data, should_sale_stocks\n\ndef every_hour_warn(db_hold_data, db_mn_data, tmpyesterday, tmpbefore_yesterday, trade=0):\n can_buy_stocks_list = []\n try:\n mn_hold_stocks = [str(item['stock_code']) for item in db_mn_data]\n hold_stocks = [str(item['stock_code']) for item in db_hold_data]\n should_stocks = list(set(hold_stocks).difference(set(mn_hold_stocks)))\n db_hold_data = sorted(db_hold_data, key=lambda x: x['buy_date'], reverse=True)\n roe_stocks = roe_strategy(roe=True, roe_num=5)\n\n should_attention = []\n should_attention_msg = []\n for _stock_item in db_hold_data:\n stock_name = _stock_item['stock_name']\n stock_code = _stock_item['stock_code']\n if stock_code not in roe_stocks:\n continue\n if stock_code in should_stocks:\n try:\n now_price = get_east_stock_price(str(stock_code))\n except:\n print('{name}, {code}当前价格获取失败'.format(code=stock_code, name=stock_name))\n try:\n now_price = get_east_stock_price(str(stock_code))\n except:\n print('{name}, {code}当前价格获取失败'.format(code=stock_code, name=stock_name))\n now_price = 0\n if now_price == 0:\n continue\n if str(stock_name).find('ST') > 0 or float(now_price) < 3 or float(now_price) <= float(_stock_item['buy_price']) * 0.97:\n continue\n # yesday_data = get_yesterday_quotation(str(stock_code), tmpyesterday, tmpyesterday)\n # befyesday_data = get_yesterday_quotation(str(stock_code), tmpbefore_yesterday, tmpbefore_yesterday)\n yesday_close = _stock_item['yes_close']\n befyesday_close = _stock_item['bef_yes_close']\n try:\n # if len(yesday_data) >= 1:\n # if len(befyesday_data) >= 1:\n # bef_two = float(yesday_data['close'][0]) if float(yesday_data['close'][0]) > float(befyesday_data['close'][0]) else float(befyesday_data['close'][0])\n # near_high_oftwo = bef_two if bef_two > float(_stock_item['high_price']) else float(_stock_item['high_price'])\n if yesday_close and befyesday_close:\n bef_two = float(yesday_close) if float(yesday_close) > float(befyesday_close) else float(befyesday_close)\n near_high_oftwo = bef_two if bef_two > float(_stock_item['high_price']) else float(_stock_item['high_price'])\n else:\n near_high_oftwo = _stock_item['high_price']\n except:\n near_high_oftwo = _stock_item['high_price']\n if float(now_price) < float(near_high_oftwo) * 0.95:\n should_attention.append(stock_code)\n msg = '通过前日和昨日价格判定今日有可能卖出:' + str(_stock_item['stock_code']) + ', 当前价格为:' + str(now_price) + ', 预计成本价格为:' + \\\n str(_stock_item['buy_price']) + ', 理论买入日期:' + str(_stock_item['buy_date']) + ', 判定最高价为:' + str(_stock_item['high_price']) \\\n + ', 近两天最高价:' + str(near_high_oftwo)\n # print msg\n should_attention_msg.append(msg)\n # send_every_msg(msg)\n\n for _stock_item in db_hold_data:\n stock_name = _stock_item['stock_name']\n stock_code = _stock_item['stock_code']\n if stock_code in should_stocks:\n if stock_code not in roe_stocks:\n continue\n try:\n now_price = get_east_stock_price(str(stock_code))\n except:\n print('{name}, {code}当前价格获取失败'.format(code=stock_code, name=stock_name))\n if now_price == 0 or stock_code in should_attention:\n continue\n if str(stock_name).find('ST') > 0 or float(now_price) < 3 or float(now_price) <= float(_stock_item['buy_price']) * 0.95:\n continue\n # print float(now_price), float(_stock_item['buy_price']), abs(float(now_price) - float(_stock_item['buy_price'])) / float(_stock_item['buy_price']) >= 0.05\n # 需要增加最高价显示以及只显示最近两个月买入的股票\n # if int(pd.Timestamp(str(_stock_item['buy_date'])).strftime(\"%m\")) >= int(pd.Timestamp.now().strftime(\"%m\")) - 1 and float(now_price) >= float(_stock_item['high_price']):\n # print pd.Timestamp.now() - datetime.timedelta(days=2), pd.Timestamp(str(_stock_item['buy_date'])), pd.Timestamp.now() - datetime.timedelta(days=2), pd.Timestamp(str(_stock_item['buy_date']))\n # if pd.Timestamp.now() - datetime.timedelta(days=2) <= pd.Timestamp(str(_stock_item['buy_date'])) and float(now_price) >= float(_stock_item['high_price']):\n if float(now_price) >= float(_stock_item['high_price']) and str(_stock_item['buy_date']) >= tmpbefore_yesterday:\n can_buy_stocks_list.append(str(_stock_item['stock_code']))\n msg = '当前可以买入的股票' + str(_stock_item['stock_code']) + ', 当前价格为:' + str(now_price) + \\\n ', 预计成本价格为:' + str(_stock_item['buy_price']) + ', 理论买入日期:' + str(_stock_item['buy_date']) + \\\n ', 判定最高价为:' + str(_stock_item['high_price'])\n print(msg)\n elif float(now_price) >= float(_stock_item['high_price']) and str(_stock_item['buy_date']) < tmpbefore_yesterday:\n # can_buy_stocks_list.append(str(_stock_item['stock_code']))\n msg = '####****过去可以买' + str(_stock_item['stock_code']) + ', 当前价格为:' + str(now_price) + \\\n ', 预计成本价格为:' + str(_stock_item['buy_price']) + ', 理论买入日期:' + str(_stock_item['buy_date']) + \\\n ', 判定最高价为:' + str(_stock_item['high_price'])\n # print msg\n # send_every_msg(msg)\n\n for item_msg in should_attention_msg:\n print(item_msg)\n\n for mn_stock_item in db_mn_data:\n if str(mn_stock_item['stock_code']) not in roe_stocks:\n continue\n now_price = get_east_stock_price(str(mn_stock_item['stock_code']))\n if now_price == 0:\n continue\n if float(now_price) <= float(mn_stock_item['cost_price']) * 0.95:\n msg = '今日价格判定卖出的股票:' + str(mn_stock_item['stock_code']) + ', 当前价格为:' + str(now_price) + ', 成本价格为:' + str(mn_stock_item['cost_price'])\n print(msg)\n # send_every_msg(msg)\n print(pd.Timestamp.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n except Exception as e:\n print('error', e)\n # every_hour_warn(db_hold_data, db_mn_data, yesterday, before_yesterday)\n return can_buy_stocks_list\n\ndef end_warn(db_hold_data, db_mn_data):\n db_hold_data = sorted(db_hold_data, key=lambda x: x['buy_date'], reverse=True)\n roe_stocks = roe_strategy(roe=True, roe_num=5)\n for _stock_item in db_hold_data:\n stock_name = _stock_item['stock_name']\n stock_code = _stock_item['stock_code']\n if stock_code not in roe_stocks:\n continue\n now_price = get_east_stock_price(str(stock_code))\n\n if str(stock_name).find('ST') > 0 or float(now_price) < 3:\n continue\n if float(now_price) < float(_stock_item['buy_price']) * 0.95:\n msg = '当日买入操���失败的股票:' + str(_stock_item['stock_code']) + ', 当前价格为:' + str(now_price) + ', 预计成本价格为:' + \\\n str(_stock_item['buy_price']) + ', 理论买入日期:' + str(_stock_item['buy_date']) + ', 判定最高价为:' + str(_stock_item['high_price'])\n print(msg)\n # send_every_msg(msg)\n\n\ndef interface_trade_func(trade_stocks_list, mn_hold_list, can_buy_stocks, not_sale_list, hastoken=0):\n if hastoken != 0:\n headers['Cookie'] = trade_inf.get_token()\n for sale_stock in trade_stocks_list:\n if sale_stock not in not_sale_list:\n if str(sale_stock) == '600242' or str(sale_stock) == '300351' or str(sale_stock) == '002036':\n print('choice is error, please check')\n continue\n for item_dict in mn_hold_list:\n if str(sale_stock) == str(item_dict['stock_code']):\n now_price = get_east_stock_price(str(sale_stock))\n try:\n trade_inf.sale_trade(headers, str(sale_stock), float(now_price), int(item_dict['can_use_amount']))\n except:\n print('{sale_stock} sale order failed.'.format(sale_stock=sale_stock))\n\n\n\nif __name__ == '__main__':\n import pandas as pd\n # yesterday = \"20170804\"\n # date = \"20171120\"\n # yesterday = (pd.Timestamp.now() - datetime.timedelta(days=1)).strftime(\"%Y%m%d\")\n date = pd.Timestamp.now().strftime(\"%Y%m%d\")\n\n not_sale_list = []\n\n trade_db_object = connect_to_db('trade_days')\n # yesterday = list(trade_db_object.find({\"isOpen\": 1, \"trade_date\": {\"$lt\": date}}).sort([(\"trade_date\", -1)]).limit(1))\n yesdaylist = list(trade_db_object.find({\"isOpen\": 1, \"trade_date\": {\"$lt\": date}}).sort([(\"trade_date\", -1)]).limit(2))\n if yesdaylist:\n yesterday = yesdaylist[0]['trade_date']\n before_yesterday = yesdaylist[1]['trade_date']\n else:\n yesterday = (pd.Timestamp.now() - datetime.timedelta(days=1)).strftime(\"%Y%m%d\")\n before_yesterday = (pd.Timestamp.now() - datetime.timedelta(days=2)).strftime(\"%Y%m%d\")\n print(yesterday, before_yesterday)\n year_time = datetime.datetime.now().strftime(\"%Y\")\n month_time = datetime.datetime.now().strftime(\"%m\")\n day_time = datetime.datetime.now().strftime(\"%d\")\n sched_Timers_list = []\n # sched_Timers_list.append(datetime.datetime(int(year_time), int(month_time), int(day_time), 9, 00, 0))\n sched_Timers_list.append(datetime.datetime(int(year_time), int(month_time), int(day_time), 9, 25, 0))\n sched_Timers_list.append(datetime.datetime(int(year_time), int(month_time), int(day_time), 9, 40, 0))\n sched_Timers_list.append(datetime.datetime(int(year_time), int(month_time), int(day_time), 10, 40, 0))\n sched_Timers_list.append(datetime.datetime(int(year_time), int(month_time), int(day_time), 11, 40, 0))\n # sched_Timers_list.append(datetime.datetime(int(year_time), int(month_time), int(day_time), 12, 40, 0))\n sched_Timers_list.append(datetime.datetime(int(year_time), int(month_time), int(day_time), 13, 40, 0))\n sched_Timers_list.append(datetime.datetime(int(year_time), int(month_time), int(day_time), 14, 40, 0))\n sched_Timers_list.append(datetime.datetime(int(year_time), int(month_time), int(day_time), 15, 1, 0))\n day_start_sche = datetime.datetime(int(year_time), int(month_time), int(day_time), 9, 30, 0)\n day_end_sche = datetime.datetime(int(year_time), int(month_time), int(day_time), 15, 10, 0)\n db_hold_data, db_mn_data, should_sale_stocks = run_project(date, yesterday)\n flag = 0\n can_buy_print_list = every_hour_warn(db_hold_data, db_mn_data, yesterday, before_yesterday)\n if user != 'viruser':\n print(can_buy_print_list)\n exit()\n while True:\n now = datetime.datetime.now()\n if now == day_start_sche:\n can_buy_stocks_list = every_hour_warn(db_hold_data, db_mn_data, yesterday, before_yesterday)\n print(can_buy_stocks_list)\n # interface_trade_func(should_sale_stocks, db_mn_data, can_buy_stocks_list, not_sale_list)\n if now in sched_Timers_list:\n print('run sched')\n every_hour_warn(db_hold_data, db_mn_data, yesterday, before_yesterday)\n flag = 1\n else:\n if flag == 1:\n print('run half sched')\n sched_Timer = now + datetime.timedelta(minutes=30)\n every_hour_warn(db_hold_data, db_mn_data, yesterday, before_yesterday)\n flag = 0\n if now >= day_end_sche:\n end_warn(db_hold_data, db_mn_data)\n break\n","sub_path":"run_in_day/do_mongo.py","file_name":"do_mongo.py","file_ext":"py","file_size_in_byte":24840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"407468887","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport os\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport dash_daq as daq\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nfrom datetime import datetime as dt\nimport pickle\nimport numpy as np\n\n\ndef RADIANS(x):\n rad = x * np.pi / 180\n return rad\ndef RADIANS_TO_KM(y):\n distance_to_km = 111.045 * 180 * y / np.pi\n return distance_to_km\ndef HAVERSINE(lat1, long1, lat2, long2):\n distance = RADIANS_TO_KM(np.arccos(np.cos(RADIANS(lat1)) * np.cos(RADIANS(lat2)) * np.cos(RADIANS(long1) - RADIANS(long2)) + np.sin(RADIANS(lat1)) * np.sin(RADIANS(lat2))))\n return distance\n###########################################################################\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\nmapbox_access_token='pk.eyJ1Ijoic2hhbmVub2x1bmExMTA2IiwiYSI6ImNqdmdocHg3dDAzdG8zeW1ncGs4ODY1ZWoifQ.ImCgzxvA8o8saZp2KjFODg'\n###########################################################################\n\n\napp.layout = html.Div(\n style={\n 'background-image':'url(\"/assets/taxi_black.png\")'\n },\n \n children=[\n html.H1(children='A taxi duration ETA app',\n style={\n 'textAlign': 'center',\n 'color': '#1ab6ff',\n 'font-weight':'bold'\n }),\n\n html.Div([\n html.Div([\n html.H4('Travel Date',style={'color':'#1ab6ff'}),\n dcc.DatePickerSingle(\n id='date',\n date=dt(2016, 5, 10)\n ),\n html.H4('Temperature',style={'color':'#1ab6ff'}),\n dcc.Input(id='temp', value=60, type='number')],\n style={'width': '20%', 'display': 'inline-block'}),\n\n html.Div([\n html.H4('Pickup Latitude',style={'color':'#1ab6ff'}),\n dcc.Input(id='pickup_latitude', value=40.75, type='number'),\n html.H4('Pickup Longitude',style={'color':'#1ab6ff'}),\n dcc.Input(id='pickup_longitude', value=-73.99, type='number')],\n style={'width': '20%', 'display': 'inline-block'}),\n\n html.Div([\n html.H4('Dropoff Latitude',style={'color':'#1ab6ff'}),\n dcc.Input(id='dropoff_latitude', value=40.75, type='number'),\n html.H4('Dropoff Longitude',style={'color':'#1ab6ff'}),\n dcc.Input(id='dropoff_longitude', value=-73.95, type='number')],\n style={'width': '20%', 'float': 'left', 'display': 'inline-block'})],\n\n style={'width': '96%','padding-left':'23%', 'padding-right':'1%'}\n\n ),\n\n html.Div([\n dcc.Graph(id='map')],\n style={'width': '96%','padding-left':'20%', 'padding-right':'1%'}\n ), \n\n html.Div([\n html.H4(children='Estimated Travel Duration: ',\n style={\n 'color': '#1ab6ff',\n 'font-weight':'bold'}), ##FF3D55\n # dcc.Textarea(\n # id='estimate_time',\n # placeholder='Enter a value...',\n # value='This is a TextArea component',\n # style={'width': '20%'})\n daq.LEDDisplay(\n id='estimate_time',\n color='#1ab6ff',\n value=\"100.00\") \n ],style={'width': '96%','padding-left':'40%', 'padding-right':'1%'})\n\n])\n\n\n@app.callback(\n [Output(component_id='map', component_property='figure'),\n Output(component_id='estimate_time', component_property='value')],\n [Input(component_id='pickup_latitude', component_property='value'),\n Input(component_id='pickup_longitude', component_property='value'),\n Input(component_id='dropoff_latitude', component_property='value'),\n Input(component_id='dropoff_longitude', component_property='value'),\n Input(component_id='date', component_property='date'),\n Input(component_id='temp', component_property='value')])\n\ndef update_graph(p_lat,p_lon,d_lat,d_lon,date,temp):\n # create test data\n df_test=pd.read_csv('../Data/test_weather.csv',nrows = 1)\n df_test[['pickup_latitude']]=p_lat\n df_test[['pickup_longitude']]=p_lon\n df_test[['dropoff_latitude']]=d_lat\n df_test[['dropoff_longitude']]=d_lon\n df_test[['temp']]=temp\n if p_lat==d_lat and p_lon==d_lon:\n df_test['distancce_in_km'] = 0\n else:\n df_test['distancce_in_km'] = HAVERSINE(df_test.pickup_latitude, df_test.pickup_longitude, df_test.dropoff_latitude, df_test.dropoff_longitude)\n # create `day_of_week` and `pickup_hour` column\n df_test['pickup_datetime'] = date\n df_test['pickup_datetime'] = pd.to_datetime(df_test['pickup_datetime'])\n df_test['day_of_week'] = df_test.pickup_datetime.dt.weekday\n # Add pick-up hour\n df_test['pickup_hour'] = df_test.pickup_datetime.dt.hour\n\n # get X\n X=df_test[['passenger_count', 'pickup_longitude', 'pickup_latitude','dropoff_longitude', 'dropoff_latitude',\n 'temp', 'distancce_in_km','day_of_week', 'pickup_hour']] #'vendor_id',\n # get saved model\n with open('saved/xgb.pickle', 'rb') as f:\n xgb = pickle.load(f)\n time = xgb.predict(X)\n\n return {\n 'data': [go.Scattermapbox(\n lat=[str(p_lat),str(d_lat)],\n lon=[str(p_lon),str(d_lon)],\n mode='markers',\n marker=go.scattermapbox.Marker(\n size=10,\n opacity=1,\n # 'line': {'width': 0.5, 'color': 'white'}\n ),\n text=['Pickup Location','Dropoff Location'],\n )],\n 'layout': go.Layout(\n # title='NYC Taxi Map',\n width=800,\n height=800,\n autosize=True,\n hovermode='closest',\n showlegend=False,\n paper_bgcolor = 'rgba(0,0,0,0)',\n mapbox=go.layout.Mapbox(\n accesstoken=mapbox_access_token,\n bearing=0,\n center=go.layout.mapbox.Center(\n lat=40.75,\n lon=-73.99\n ),\n pitch=0,\n zoom=11,\n style='light'\n ),\n )\n }, u'{:.2f}'.format(time[0]) # This travel will likely cost you \n\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)","sub_path":"Analysis/Dash_web_applicatioin.py","file_name":"Dash_web_applicatioin.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"539334564","text":"\"\"\"This module can convert any number base to other any number base\n Test string\n\"\"\"\n\nclass NumberConversion(object):\n \"\"\"This class can convert any number base to any other number base.\n First it convert a number to decimal and then it convert it to\n required format.\n \"\"\"\n def convert_to_decimal(self, number, digits):\n \"\"\"This function convert a number to decimal.\n \"\"\"\n tot_sum = 0\n number = number[::-1]\n length = len(digits)\n cnt = 0\n for i in number:\n tot_sum += digits.index(i) * ( length ** cnt )\n cnt = cnt + 1\n return tot_sum\n\n def convert_to_x(self, number, digits):\n \"\"\"This function convert a decimal number to other number.\n It requires decimal number and digits in destination numbers as list.\n \"\"\"\n new_num = '' \n ndigits = len(digits)\n while number != 0:\n new_num += digits[number % ndigits]\n number = number / ndigits \n return new_num[::-1]\n\n def convert(self, num, src_digits, dest_digits):\n \"\"\"This function first convert number to decimal number\n and then convert that nunmber to required base.\n \"\"\"\n dec_num = self.convert_to_decimal(num, src_digits)\n# print dec_num\n return self.convert_to_x(dec_num, dest_digits)\n \n\n#dest_digits = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\n#obj = NumberConversion()\n#print obj.convert(423434, hexdecimal)\n#octal = ['0','1','2','3','4','5','6','7']\n#print obj.convert(423434, octal)\n#src_digits = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\n#src_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n#dest_digits = ['0', '1']\n#print obj.convert('56456466465456', src_digits, dest_digits)\n","sub_path":"binary_octal_hex.py","file_name":"binary_octal_hex.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"646233102","text":"import redis\nimport datetime\nimport json\n\nclient = redis.Redis()\n\n# client.rpush(\"aa\", 1)\n# client.rpush(\"aa\", 2)\n# d = client.blpop(\"aa\")\n# print(d)\n# d = client.blpop(\"aa\")\n# print(d)\n\ndef add_task(task_id, target): # 添加任务\n task_detail = {\n \"task_id\": task_id,\n \"target\": target,\n \"create_time\": datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n }\n client.hset(\"task:detail\", task_id, json.dumps(task_detail))\n client.rpush(\"task_queue\", task_id)\n\ndef read_task(): # 读取任务发送邮件\n task_id = client.blpop(\"task_queue\")[1].decode() # 阻塞式的等待有数据\n task_detail = client.hget(\"task:detail\", task_id)\n target = json.loads(task_detail)[\"target\"]\n print(\"给\", target, \"发送邮件\")\n\ndef del_task(task_id): # 删除任务\n client.lrem(\"task:queue\", 0, task_id)\n client.hdel(\"task_detail\", task_id)\n\ndef pause_task(task_id): # 暂停任务\n client.lrem(\"task:queue\", 0, task_id)\n client.rpush(\"task:pause\", task_id)\n\ndef resume_task(task_id): # 恢复任务\n client.lrem(\"task:pause\", 0, task_id)\n client.rpush(\"task_queue\", task_id)\n\nadd_task(1, \"1072772483@qq.com\")\nadd_task(1, \"1072772483@qq.com\")\nadd_task(1, \"1072772483@qq.com\")\nadd_task(2, \"1756088786@qq.com\")\nread_task()","sub_path":"task_queue/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"137780397","text":"import config\nimport praw\nimport prawcore\nimport json\nimport requests\nfrom time import time, sleep\nfrom random import choice, getrandbits, randint\n\n# file containing the default subreddits\nDEFAULT = \"default_subreddits.txt\"\n\n\ndef error_message():\n input(\"Press any key...\")\n exit(1)\n\n\ndef get_subreddits():\n\n subs = []\n file = open(DEFAULT)\n for line in file:\n if '*' not in line:\n # lines containing * will not be included\n subs.append(line.rstrip('\\n'))\n file.close()\n return subs\n\n\ndef test_subreddit_validity(sub):\n\n # used for startup and routine checks.\n # not 100% sure about ResponseException here.\n\n client_id = config.client_id\n secret = config.secret\n user_agent = config.user_agent\n\n reddit = praw.Reddit(client_id=client_id, client_secret=secret, user_agent=user_agent)\n\n try:\n test_sub = reddit.subreddit(sub)\n # this line does the actual check, posts is not supposed to be used anymore\n posts = [post for post in test_sub.hot(limit=1)]\n return True\n\n except prawcore.exceptions.Redirect:\n print(\"Error: subreddit not accessible:\", sub)\n return False\n\n except prawcore.exceptions.ResponseException:\n print(\"Error: 401 response from reddit\")\n return False\n\n\ndef startup():\n\n print(\"Starting up...\")\n\n token = config.token\n subs = get_subreddits()\n subs_to_be_removed = []\n\n print(\"Accessing reddit...\")\n for sub in subs:\n\n flag = test_subreddit_validity(sub)\n if not flag:\n subs_to_be_removed.append(sub)\n\n sleep(1)\n\n print(\"Accessing telegram...\")\n url = 'https://api.telegram.org/bot%s/' % token\n tg_test = json.loads(requests.get(url + 'getUpdates').content)\n\n if tg_test['ok'] is False:\n print(\"Error:\", tg_test['error_code'], tg_test['description'])\n error_message()\n\n print(\"Done!\\n\")\n\n\ndef decide(msg):\n\n separator = \"vai \"\n command = \"/help\"\n\n if msg[-1] == '?':\n # 0 or 1\n rnd = getrandbits(1)\n if rnd:\n return \"Joo\"\n else:\n return \"Ei\"\n\n if separator not in msg:\n return \"/help: Käytä avainsanaa \\\"vai\\\" tai päätä viesti kysymysmerkkiin\"\n\n # TODO: better handling of empty fields\n\n index = msg.find(command)\n beginning = msg[:index]\n msg = msg.replace(beginning, \"\")\n\n msg = msg.replace(command, \"\")\n choices = msg.split(separator)\n choices = [word for word in choices if word not in [\"\", \" \"]]\n choices = [word.strip(\" \") for word in choices]\n choices = [word.rstrip(\" \") for word in choices]\n return beginning + choice(choices)\n\n\ndef uptime(timestamp):\n\n days = int(timestamp // 86400)\n timestamp = timestamp - (days * 86400)\n hours = int(timestamp // 3600)\n timestamp = timestamp - (hours * 3600)\n minutes = int(timestamp // 60)\n timestamp = timestamp - (minutes * 60)\n seconds = int(timestamp)\n\n message = f\"{days} days\\n\" \\\n f\"{hours} hours\\n\" \\\n f\"{minutes} minutes\\n\" \\\n f\"{seconds} seconds\"\n\n return message\n\n\ndef scramble(text):\n closest_symbols_qwerty = {\n\n ' ': ['.', ',', 'b', 'c', 'm', 'n', 'v', 'x'],\n '.': ['', '\\n', ' ', 'm', 'n'],\n '/': [',', ')', '9', '0'],\n '@': ['#', '1', '2'],\n '#': ['*', '1', '2', '3', '@', '€'],\n\n '0': ['+', '0', '8', '9', 'i', 'k', 'l', 'p', 'ö'],\n '1': ['2', 'q', 'w', '§'],\n '2': ['1', '3', 'e', 'q', 'w'],\n '3': ['2', '4', 'e', 'w'],\n '4': ['3', '5', 'e', 'r'],\n '5': ['4', '6', 'r', 't'],\n '6': ['5', '7', 't', 'y'],\n '7': ['6', '8', 'u', 'y'],\n '8': ['7', '9', 'i', 'u'],\n '9': ['0', '8', 'i', 'o'],\n\n 'a': ['q', 's', 'w'],\n 'b': [' ', 'g', 'h', 'n', 'v'],\n 'c': [' ', 'c', 'd', 'f', 'g', 'x'],\n 'd': ['e', 'f', 'r', 's', 'w', 'x', 'z'],\n 'e': ['d', 'f', 'r', 's', 'w'],\n 'f': ['c', 'd', 'e', 'g', 'r', 't', 'v'],\n 'g': ['b', 'f', 'h', 'r', 't', 'v', 'y'],\n 'h': ['b', 'g', 'j', 'n', 't', 'u', 'y'],\n 'i': ['j', 'k', 'l', 'o', 'u'],\n 'j': ['h', 'i', 'k', 'm', 'n', 'u'],\n 'k': [',', 'i', 'j', 'l', 'm', 'o'],\n 'l': [',', '.', 'k', 'o', 'p', 'ö'],\n 'm': [' ', ',', 'j', 'k', 'n'],\n 'n': [' ', 'b', 'h', 'j', 'm'],\n 'o': ['i', 'k', 'l', 'p', 'ö'],\n 'p': ['o', 'ä', 'å', 'ö'],\n 'q': ['a', 's', 'w'],\n 'r': ['d', 'e', 'f', 'g', 't'],\n 's': ['a', 'd', 'e', 'q', 'w', 'x', 'z'],\n 't': ['f', 'g', 'h', 'r', 'y'],\n 'u': ['h', 'i', 'j', 'k', 'y'],\n 'v': [' ', 'b', 'c', 'f', 'g'],\n 'w': ['a', 'd', 'e', 'q', 's'],\n 'x': [' ', ',', 'c', 'd', 'f', 'g', 's', 'z'],\n 'y': ['g', 'h', 'j', 't', 'u'],\n 'z': [',', 'd', 'f', 's', 'x'],\n 'å': ['p', 'ä', 'ö'],\n 'ä': ['', 'p', 'å', 'ö'],\n 'ö': ['', '.', 'o', 'p', 'ä', 'å'],\n\n 'A': ['Q', 'S', 'W'],\n 'B': [' ', 'G', 'H', 'N', 'V'],\n 'C': [' ', 'C', 'D', 'F', 'G', 'X'],\n 'D': ['E', 'F', 'R', 'S', 'W', 'X', 'Z'],\n 'E': ['D', 'F', 'R', 'S', 'W'],\n 'F': ['C', 'D', 'E', 'G', 'R', 'T', 'V'],\n 'G': ['B', 'F', 'H', 'R', 'T', 'V', 'Y'],\n 'H': ['B', 'G', 'J', 'N', 'T', 'U', 'Y'],\n 'I': ['J', 'K', 'L', 'O', 'U'],\n 'J': ['H', 'I', 'K', 'M', 'N', 'U'],\n 'K': [',', 'I', 'J', 'L', 'M', 'O'],\n 'L': [',', '.', 'K', 'O', 'P', 'Ö'],\n 'M': [' ', ',', 'J', 'K', 'N'],\n 'N': [' ', 'B', 'H', 'J', 'M'],\n 'O': ['I', 'K', 'L', 'P', 'Ö'],\n 'P': ['L', 'O', 'Ä', 'Å', 'Ö'],\n 'Q': ['A', 'S', 'W'],\n 'R': ['D', 'E', 'F', 'G', 'T'],\n 'S': ['A', 'D', 'E', 'Q', 'W', 'X', 'Z'],\n 'T': ['F', 'G', 'H', 'R', 'Y'],\n 'U': ['H', 'I', 'J', 'K', 'Y'],\n 'V': [' ', 'B', 'C', 'F', 'G'],\n 'W': ['A', 'D', 'E', 'Q', 'S'],\n 'X': [' ', ',', 'C', 'D', 'F', 'G', 'S', 'Z'],\n 'Y': ['G', 'H', 'J', 'T', 'U'],\n 'Z': [',', 'D', 'F', 'S', 'X'],\n 'Å': ['P', 'Ä', 'Ö'],\n 'Ä': ['', 'P', 'Å', 'Ö'],\n 'Ö': ['', '.', 'L', 'O', 'P', 'Ä', 'Å']\n\n }\n\n scrambled_text = ''\n\n for i in range(len(text)):\n\n if text[i] not in closest_symbols_qwerty.keys():\n # Current character is something like an emoji or something\n char = text[i]\n\n else:\n # Every n character on average will be misclicked (value from testing).\n # People capable of typing longer messages are typically less likely\n # to be super intoxicated.\n if len(text) < 50:\n chance = randint(0, 13)\n else:\n chance = randint(0, 23)\n\n if chance == 0:\n typos = closest_symbols_qwerty[text[i]]\n rnd = randint(0, len(typos))\n char = typos[rnd]\n else:\n char = text[i]\n\n scrambled_text += char\n\n if scrambled_text == text:\n # Recursion to avoid cases where no characters were changed (somewhat volatile)\n scrambled_text = scramble(text)\n\n return scrambled_text\n\n\ndef find_choice(msg, array):\n msg = msg.lower()\n\n for thing in array:\n if thing in msg:\n return thing\n return False\n\n\ndef uwu(msg):\n words = msg.split(' ')\n arr = []\n\n postfix = choice( (\"uwu\", \"o_0\", \"゚✧ ^w^✧ ゚\", \"(´◠ω◠`)\", \"ฅ^•ﻌ•^ฅ\") )\n\n for word in words:\n word = word.replace('l', 'w').replace('r', 'w')\n word = word.replace('L', 'W').replace('R', 'W')\n arr.append(word)\n\n return ' '.join(arr) + \" \" + postfix\n","sub_path":"funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":7724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"24335564","text":"\"\"\" sch2ps.py\n Convert schematic files to postscript. \"\"\"\nimport json, os, sys\nprojfile = '../../projdefs.json'\nprintscript = 'print.scm'\nprintdir = './printable'\n\n\"\"\" Load the project definition file if it exists \"\"\"\ntry:\n sys.stdout.write ('Opening the project definition file at ' +\n projfile + '...')\n fin = open(projfile, \"ro\")\n sys.stdout.write ('done.\\n')\nexcept IOError as e:\n print ('Could not open the project definition file ' + projfile + '.')\n sys.exit()\nprojdefs = json.loads(fin.read())\n\n\"\"\" Check to see if the print guile script is in this directory \"\"\"\ntry:\n open(printscript,'ro')\nexcept IOError as e:\n print ('Could not open the guile script ' + printscript + '.')\n sys.exit()\n \n\"\"\" Create the print directory if necessary \"\"\"\nif (not os.access(printdir,os.F_OK)):\n os.mkdir(printdir)\n print ('* Created ' + printdir)\nelse:\n print('* ' + printdir + \" already exists. I'll overwrite it.\")\n\n\n\"\"\" Convert each schematic page to postscript \"\"\"\npslist = []\nfor page in projdefs['schematic_pages']:\n try:\n open(page,'ro')\n outfile = printdir + '/' + page.split('.')[0] + '.ps'\n sys.stdout.write('Converting ' + page + ' to ' + outfile + '...')\n os.popen('gschem -p -o ' + outfile + ' -s ' + printscript +\n ' ' + page)\n sys.stdout.write('done.\\n')\n pslist.append(outfile) # Make a list of ps outputs for joining\n except IOError as e:\n print ('Could not open the schematic page ' + page + '.')\n sys.exit()\n \n\"\"\" Join postscript files \"\"\"\nallpsname = (printdir + '/' + projdefs['project_name'] + '_schematics.ps')\ntry:\n os.popen('gs -sDEVICE=pswrite -dNOPAUSE -dBATCH -dSAFER -sOutputFile=' + \n allpsname + ' ' + ' '.join(pslist)) \nexcept:\n sys.exit()\n\n\"\"\" Convert postscript files to pdf if they exist \"\"\"\nfor page in projdefs['schematic_pages']:\n psfile = printdir + '/' + page.split('.')[0] + '.ps'\n pdfout = printdir + '/' + page.split('.')[0] + '.pdf'\n if (os.access(psfile,os.F_OK)):\n sys.stdout.write('Converting ' + page + ' to pdf...')\n os.popen('ps2pdfwr ' + psfile + ' ' + pdfout)\n sys.stdout.write('done.\\n')\n\n\nfin.close()\n","sub_path":"implement/schematics/sch2ps.py","file_name":"sch2ps.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
    Username
    Comment
    ''' + ch.username +'''
    ''' + ch.comment +\"