diff --git "a/4848.jsonl" "b/4848.jsonl"
new file mode 100644--- /dev/null
+++ "b/4848.jsonl"
@@ -0,0 +1,698 @@
+{"seq_id":"369627469","text":"#2020-12-04\n#embedding(벡터화)\n#LSTM\n\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nimport numpy as np\n\n\n#X\ndocs = [\"너무 재밌어요\", \"참 최고예요\", \"참 잘 만든 영화예요\", \"추천하고 싶은 영화입니다\",\n \"한 번 더 보고 싶네요\", \"글쎄요\", \"별로예요\", \"생각보다 지루해요\", \"연기가 어색해요\",\n \"재미없어요\", \"너무 재미없다\", \"참 재밌네요\"] \n\n#Y\n#1. 긍정 1, 부정 0\nlabels = np.array([1, 1, 1, 1,1, 0, 0, 0, 0, 0, 0, 1])\n\n#docs를 수치화하면 처리 가능 \n\ntoken = Tokenizer()\ntoken.fit_on_texts(docs)\nprint(token.word_index) #많이 나오는 애가 앞으로 감(빈도수 높은 애): 25개\n\nx = token.texts_to_sequences(docs)\n# [[2, 3], [1, 4], [1, 5, 6, 7], [8, 9, 10], [11, 12, 13, 14, 15], [16], [17], [18, 19], [20, 21], [22], [2, 23], [1, 24]]\n# 긴 쪽으로 맞추자 (짧은 쪽에 맞추면 데이터 날아감) 빈 앞을 0으로 채우기(의미 있는 숫자가 뒤로 밀림) \n# 일정하지 않음\n\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences #0으로 채우는\npad_x = pad_sequences(x, padding='pre') #뒤로 채우는 건 post\nprint(pad_x) #(12, 5) docs의 개수, 5(제일 긴 것)\nprint(pad_x.shape) #25개 vector화\n\n\nword_size = len(token.word_index) + 1 #padding\n# print(\"전체 토큰 사이즈: \", word_size) 전체 토큰 사이즈: 25\n# 12, 5지만 그 안에 들어가는 종류는 25가지\n\n\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Embedding, LSTM, Flatten, Conv1D\n\n\nmodel = Sequential()\n\nmodel.add(Embedding(25, 10, input_length=5)) #12, 5였음(명시해 줄 때는 column 개수 같아야)\n# model.add(Embedding(25, 10)) #25, 9도 오케이 25, 8도 오케이... \n\n# model.add(LSTM(32))\nmodel.add(Conv1D(32, 2))\nmodel.add(Flatten())\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.summary()\n\n#input_length 없이 flatten -> dense? x\n#input_length + flatten -> dense o \n\n\n#embedding은 처음에 output node 개수 아님#\n#embedding = one hot encoding을 벡터화\n#단어 사전의 수, output node 개수, \n\n#input_length 다른 걸로 해도 돌아가긴 함 \n#WARNING:tensorflow:Model was constructed with shape (None, 3) for input Tensor(\"embedding_input:0\", shape=(None, 3), dtype=float32), but it was called on an input with incompatible shape (None, 5).\n#하지만 column 개수 맞춰 주는 게 좋다\n\n##### 다 대충 써도 되지만... input_length는 가급적이면 column 개수랑 맞춰 주고, 사전 수는 25보다 작게....\n\n\n#명시 안 하면 자동으로 먹힌다\n #26, 10 -> 이래도 에러 남...\n #input_length만 잘 맞춰 주면... 잘 돌아가는 거 아닌지 \n #단, 사전의 개수보다 작게 주면 터짐 \n\n# 원핫인코딩이었다면 25, 25 -> 임베딩 레이어로 하면 25, 10으로 벡터화(10은 그냥 임의로 해도 됨)\n# 3차원 input -> LSTM 가능\n\n\nmodel.compile(optimizer='adam', \n loss='binary_crossentropy', \n metrics=['acc'])\n\nmodel.fit(pad_x, labels, epochs=30)\n\n#data 적으니까 그냥 이렇게 한다 \nacc = model.evaluate(pad_x, labels)[1]\nprint(\"acc: \", acc)\n\n\n\n'''\n# model.add(Embedding(25, 10, input_length=5)) #12, 5였음\n\nModel: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param #\n=================================================================\nembedding (Embedding) (None, 5, 10) 250 = 25 * 10 \n_________________________________________________________________\nlstm (LSTM) (None, 32) 5504\n_________________________________________________________________\ndense (Dense) (None, 1) 33\n=================================================================\nTotal params: 5,787\nTrainable params: 5,787\nNon-trainable params: 0\n_________________________________________________________________\n'''\n\n'''\nmodel.add(Embedding(25, 10))\n#5가 사라졌는데도 똑같음 None이 됐는데 ;;\nModel: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param #\n=================================================================\nembedding (Embedding) (None, None, 10) 250\n_________________________________________________________________\nlstm (LSTM) (None, 32) 5504\n_________________________________________________________________\ndense (Dense) (None, 1) 33\n=================================================================\nTotal params: 5,787\nTrainable params: 5,787\nNon-trainable params: 0\n_________________________________________________________________\n'''\n\n","sub_path":"keras2/keras79_embedding2.py","file_name":"keras79_embedding2.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"455512239","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom scipy.optimize import curve_fit, fmin\n\n\n\ndef quadr(x, a, b, c):\n return a + b*x + c*x**2\n\ndef line (x, a, b):\n return a - b*x\n\ndef line2 (x, a, b):\n return -b*(a-x)\n\n\ndef size_distribution (x, sigma, m):\n ln = np.log(x)-m\n exp = np.exp(-(ln**2)/(2*sigma**2))\n const = 1/((np.sqrt(2*np.pi))*sigma*x)\n return const * exp\n\n\n#a = 0.3219 #nanometer\nwl = 1.4235e-2 #nm\n\n\n\n\n\nloaddir = '/Users/ivanov/Yandex.Disk.localized/DESY_2018/Ti/FFT/'\nsavepng = '/Users/ivanov/Yandex.Disk.localized/DESY_2018/Ti/Results/Pictures/xarea.png'\nxarea_save = '/Users/ivanov/Yandex.Disk.localized/DESY_2018/Ti/Results/Data/Calculated/xarea.txt'\n\n\nborder = 169\ntemperature = np.linspace(4, border, border-4)\n\ndirectorylist = []\nfor file in os.listdir('/Users/ivanov/Yandex.Disk.localized/DESY_2018/Ti/Integrated/'):\n if file.endswith('.txt'):\n directorylist.append(file[:-4])\ndirectorylist.sort()\n\nfilenums = [int(directoryname) for directoryname in directorylist]\n\nxarea_list = []\n\n\n\ndirectorylist = directorylist[4:border]\nx_axis = temperature\n\nfor k, directory in enumerate(directorylist):\n reversedir = loaddir+directory\n filelist = []\n\n #b = burgers_list[k, 1]\n\n for file in os.listdir(reversedir):\n if file.endswith('.txt'):\n filelist.append(file)\n filelist.sort()\n allLlist = []\n alist = []\n blist = []\n\n ran = 12\n for i in range(ran):\n\n ALlist = []\n Xlist = []\n hkdotl = []\n Llist = []\n\n lnALlist = []\n mark = ['o', 'v', 'P', 's', '^', 'h', 'X']\n approx = ['black', 'orangered', 'mediumblue', 'crimson', 'green', 'maroon', 'rebeccapurple']\n style = ['--', '-.', ':']\n mark = mark * 50\n approx = approx * 50\n style = style * 50\n\n for j, file in enumerate(filelist):\n data = np.loadtxt(os.path.join(reversedir, file))\n\n if j == 0:\n L_ = data[i, 0]\n allLlist.append(L_)\n\n L = data[i, 0]\n Llist.append(L)\n K = float(file[6:-4])\n\n X = K**2\n Xlist.append(X)\n AL0 = data[0, 1]\n AL = data[i, 1]\n lnAL = np.log(AL/AL0)\n lnALlist.append(lnAL)\n\n Xlist = np.array(Xlist)\n lnALlist = np.array(lnALlist)\n\n popt, pcov = curve_fit(quadr, Xlist, lnALlist, bounds=(-np.inf, [np.inf, np.inf, 0]))\n alist.append(popt[0])\n blist.append(popt[1])\n\n\n '''\n plt.scatter(Xlist, lnALlist, marker='%s' % mark[i], edgecolor='indianred', color='white', label='L = %.2f' % L)\n Xlist = np.linspace(np.min(Xlist) - 0.25, np.max(Xlist) + 0.25, 50)\n plt.plot(Xlist, quadr(Xlist, *popt), linestyle='%s' % style[i], color='%s' % approx[i], alpha=0.8)\n plt.ylabel(r'$lnA(L)$')\n plt.xlabel(r'$K^2\\overline{C_{hkl}}$')\n # plt.xlim(0, 0.1)\n # plt.ylim(-5, 1)\n # plt.xticks(np.arange(0, 2.1, step=1))\n #plt.title('%s' % object[num], loc='right')\n plt.legend(edgecolor='white')\n\n #plt.savefig(savelnAL, dpi=150)\n #plt.savefig(savelnALpdf, dpi=150)\n plt.show()\n '''\n\n\n length = 6\n\n allLlist = np.array(allLlist)\n alist = np.array(alist)\n blist = np.array(blist)\n\n allL_list = allLlist[:length]\n a_list = alist[:length]\n b_list = blist[:length]\n\n AS = np.exp(a_list)\n AS_full = np.exp(alist)\n\n # AS_full = AS_full[:-15]\n # allLlist = allLlist [:-15]\n\n popt, pcov = curve_fit(line, allL_list, AS)\n perr = np.sqrt(np.diag(pcov)) / np.sqrt(len(allL_list))\n\n L0 = popt[0] / popt[1]\n xarea = 1.5*L0\n xarea_list.append(xarea)\n\n print (directory)\n print ('xarea = %.2f nm'%xarea)\n\n '''\n A_ = AS[0] * 1.5 * 2\n L_ = L0 * 1.5\n beta = 2.5 / 4.5\n m = ((A_ ** beta) / L_) ** (1.5)\n\n D_ = 1 / 2.5 * np.log(L_ / m)\n sigma = np.sqrt(D_)\n print(L_, m, sigma)\n\n xarea = m * np.exp(2.5 * sigma ** 2)\n xvol = m * np.exp(3.5 * sigma ** 2)\n d = 3 / 4 * m * np.exp(7 / 4 * (np.sqrt(2) * sigma) ** 2)\n\n \n x = np.linspace(0, 100, 1000)\n plt.plot(x, size_distribution(x, sigma, m), label = 'm %.2f\\ns %.2f\\nx %.2f'%(m, sigma, 1.5*L0))\n plt.ylim(0, 1)\n plt.xlim(0, 10)\n plt.legend()\n plt.show()\n '''\n\n\n'''\n #fig, ax = plt.subplots(figsize=(7, 3.5))\n # plt.subplot (211) #211 for two\n\n plt.scatter(allLlist, AS_full, marker='o', edgecolor='darkred', color='white', alpha=0.7)\n fitallLlist = np.linspace(0, popt[0] / popt[1] + 0.5, 50)\n plt.plot(fitallLlist, line(fitallLlist, *popt), linestyle='-.', color='midnightblue', alpha=0.7)\n plt.plot(fitallLlist, line(fitallLlist, *popt), linestyle='-.', color='white', alpha=0) # ,\n # label = ' L0 %.2f(%.2f)\\n %.2f(%.2f)' %(L0, dL0, 1.5*L0, 1.5*dL0))\n plt.ylabel(r'$A^s(L)$')\n plt.xlabel(r'$L$')\n # plt.title('%s' % object[num], loc='right')\n plt.legend(edgecolor='white')\n # plt.text (popt[0]/popt[1], 0.2, r'$L_0 = %.2f(%.2f) nm$'%(L0, dL0), horizontalalignment='left')\n plt.xlim(-2, 100)\n # plt.yticks(np.arange(0, 1.1, step=0.5))\n # if num == 0 or num == 1:\n # plt.ylim(-0.2, AS[0]+0.7)\n #plt.savefig(saveASpng, dpi=150)\n #plt.savefig(saveASpdf, dpi=150)\n plt.show()\n # plt.clf()\n'''\n\n\n#xarea_data = np.array((np.row_stack((np.array(filenums), np.array(xarea_list))).T))\n#np.savetxt(xarea_save, xarea_data, fmt = '%.6d %.6f')\n\n\nfig, ax = plt.subplots(figsize=(7, 3.5))\nplt.scatter(x_axis, xarea_list, color='white', edgecolor='darkred',\n marker='s', s=14)\nplt.ylabel(r'$x_{area}\\/[nm]$')\nplt.xlabel(r'$Approximate\\/\\/temperature$')\nplt.title(r'$MWA\\/\\beta Ti\\/ $', loc = 'right')\n\n#plt.savefig(savepng, dpi = 150)\n\nplt.show()\n","sub_path":"DESY_2018/Ti/12_mwa_size.py","file_name":"12_mwa_size.py","file_ext":"py","file_size_in_byte":5785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"461589056","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 1 01:53:51 2018\r\n\r\n@author: dell\r\n\"\"\"\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\n\r\ndef main ():\r\n imgpath = \"//home//vaibhav//Documents//OMR Project//omr samples//sheet1.jpg\"\r\n #imgpath = \"C:\\\\Users\\\\dell\\\\Desktop\\\\Documents\\\\OMR project\\\\standard_test_images\\\\lena_color_256.tif\"\r\n img = cv2.imread(imgpath,0)\r\n \r\n block_size = 11\r\n constant = 2\r\n #th1 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, block_size, constant)\r\n \r\n th1 = cv2.adaptiveThreshold (img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, block_size, constant)\r\n \r\n plt.imshow(th1,cmap = 'gray')\r\n plt.show()\r\n\r\nif __name__ ==\"__main__\":\r\n main() \r\n \r\n","sub_path":"thresholding.py","file_name":"thresholding.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"318309533","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\nimport sys\nfrom optparse import make_option\nfrom pyflakes.scripts import pyflakes\nfrom cStringIO import StringIO\nfrom django_jenkins.functions import relpath\nfrom django_jenkins.tasks import BaseTask, get_apps_locations\n\n\nclass Task(BaseTask):\n option_list = [\n make_option(\"--pyflakes-with-migrations\",\n action=\"store_true\", default=False,\n dest=\"pyflakes_with_migrations\",\n help=\"Don't check migrations with pyflakes.\")]\n\n def __init__(self, test_labels, options):\n super(Task, self).__init__(test_labels, options)\n self.test_all = options['test_all']\n self.with_migrations = options['pyflakes_with_migrations']\n\n if options.get('pyflakes_file_output', True):\n output_dir = options['output_dir']\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n self.output = open(os.path.join(output_dir, 'pyflakes.report'), 'w')\n else:\n self.output = sys.stdout\n\n def teardown_test_environment(self, **kwargs):\n locations = get_apps_locations(self.test_labels, self.test_all)\n\n # run pyflakes tool with captured output\n old_stdout, pyflakes_output = sys.stdout, StringIO()\n sys.stdout = pyflakes_output\n try:\n for location in locations:\n if os.path.isdir(location):\n for dirpath, dirnames, filenames in os.walk(relpath(location)):\n if not self.with_migrations and 'migrations' in dirpath:\n continue\n for filename in filenames:\n if filename.endswith('.py'):\n pyflakes.checkPath(os.path.join(dirpath, filename))\n else:\n pyflakes.checkPath(relpath(location))\n finally:\n sys.stdout = old_stdout\n\n # save report\n pyflakes_output.reset()\n while True:\n line = pyflakes_output.readline()\n if not line:\n break\n message = re.sub(r': ', r': [E] PYFLAKES:', line)\n self.output.write(message)\n\n self.output.close()\n","sub_path":"django_jenkins-0.13.0-py2.7.egg/django_jenkins/tasks/run_pyflakes.py","file_name":"run_pyflakes.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"593161145","text":"'''\r\nUsage: python ./dtld_to_tfrecord.py --input_yaml input_file_name.yaml --output_path output_file_name.record\r\n'''\r\n\r\nimport tensorflow as tf\r\nimport yaml\r\nimport os, sys\r\nimport io\r\nfrom PIL import Image\r\n# from utilities import dataset_util\r\nsys.path.append('C:/Users/xinch/Documents/Python/TensorFlow/models/research/object_detection')\r\nfrom utils import dataset_util\r\nimport hashlib\r\nfrom random import shuffle\r\n\r\nflags = tf.app.flags\r\nflags.DEFINE_string('output_path', '', 'Path to output TFRecord')\r\nflags.DEFINE_string('input_yaml', '', 'Path to labeling YAML')\r\nFLAGS = flags.FLAGS\r\n\r\nLABEL_DICT = {\r\n \"Circle\" : 0,\r\n \"Straight\" : 1,\r\n \"Left\" : 2,\r\n \"StraightLeft\" : 3,\r\n \"Right\": 4,\r\n \"Bus\":7, # in digital 3\r\n \"Pedestrian\": 8, \r\n \"Bike\": 9\r\n }\r\n # classes are saved as in bstld\r\n\r\nLABEL_DICT_R={v: k for k, v in LABEL_DICT.items()}\r\n\r\ndef create_tf_example(example):\r\n \r\n filename = example['path'] # Filename of the image. Empty if image is not from file\r\n filename = filename.encode()\r\n\r\n with tf.gfile.GFile(example['path'], 'rb') as fid:\r\n encoded_image = fid.read()\r\n encoded_jpg_io = io.BytesIO(encoded_image)\r\n image = Image.open(encoded_jpg_io)\r\n width, height = image.size\r\n key = hashlib.sha256(encoded_image).hexdigest()\r\n\r\n image_format = 'jpg'.encode() \r\n\r\n xmins = [] # List of normalized left x coordinates in bounding box (1 per box)\r\n xmaxs = [] # List of normalized right x coordinates in bounding box\r\n # (1 per box)\r\n ymins = [] # List of normalized top y coordinates in bounding box (1 per box)\r\n ymaxs = [] # List of normalized bottom y coordinates in bounding box\r\n # (1 per box)\r\n classes_text = [] # List of string class name of bounding box (1 per box)\r\n classes = [] # List of integer class id of bounding box (1 per box)\r\n\r\n for box in example['objects']:\r\n # adding box, one image may have multiple detected boxes\r\n class_id_d3=int(str(box['class_id'])[2])\r\n class_id=str(box['class_id'])[-1]\r\n class_id=int(class_id)\r\n if class_id == 3: # ignore \"StraightLeft\"\r\n continue\r\n if class_id == 9: # ignore \"Bike\"\r\n continue\r\n if box['x'] + box['width'] > width or box['y']+ box['height'] > height:\r\n continue\r\n \r\n xmins.append(float(box['x']) / width)\r\n xmaxs.append(float(box['x'] + box['width']) / width)\r\n ymins.append(float(box['y']) / height)\r\n ymaxs.append(float(box['y']+ box['height']) / height)\r\n classes_text.append((LABEL_DICT_R[class_id]).encode())\r\n # to match with bstld_label_map\r\n\r\n if class_id==0:\r\n if class_id_d3==7:\r\n #classes.append(class_id_d3)\r\n classes.append(int(6))\r\n\r\n else:\r\n classes.append(class_id+1)\r\n\r\n\r\n elif class_id==1 or class_id==2:\r\n classes.append(class_id+1)\r\n\r\n elif class_id == 4:\r\n classes.append(int(4))\r\n \r\n elif class_id == 8:\r\n classes.append(int(5))\r\n\r\n # elif class_id == 9:\r\n # classes.append(int(6))\r\n\r\n\r\n tf_example = tf.train.Example(features=tf.train.Features(feature={\r\n 'image/height': dataset_util.int64_feature(height),\r\n 'image/width': dataset_util.int64_feature(width),\r\n 'image/filename': dataset_util.bytes_feature(filename),\r\n 'image/source_id': dataset_util.bytes_feature(filename),\r\n 'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')),\r\n 'image/encoded': dataset_util.bytes_feature(encoded_image),\r\n 'image/format': dataset_util.bytes_feature(image_format),\r\n 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),\r\n 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),\r\n 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),\r\n 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),\r\n 'image/object/class/text': dataset_util.bytes_list_feature(classes_text),\r\n 'image/object/class/label': dataset_util.int64_list_feature(classes),\r\n }))\r\n\r\n return tf_example\r\n\r\n\r\ndef main(_):\r\n \r\n writer = tf.python_io.TFRecordWriter(FLAGS.output_path)\r\n \r\n INPUT_YAML = FLAGS.input_yaml\r\n examples = yaml.load(open(INPUT_YAML, 'rb').read())\r\n\r\n len_examples = len(examples)\r\n print(\"Loaded \", len(examples), \"examples\")\r\n\r\n # for i in range(len(examples)):\r\n # examples[i]['path'] = os.path.abspath(os.path.join(os.path.dirname(INPUT_YAML), examples[i]['path']))\r\n \r\n shuffle(examples)\r\n \r\n counter = 0\r\n\r\n for example in examples:\r\n tf_example = create_tf_example(example)\r\n writer.write(tf_example.SerializeToString())\r\n\r\n if counter % 10 == 0:\r\n print(\"Percent done\", (counter/len_examples)*100)\r\n counter += 1.\r\n writer.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n tf.app.run()\r\n","sub_path":"DTLD/DTLD_to_tfrecord_pictogram_simple_old.py","file_name":"DTLD_to_tfrecord_pictogram_simple_old.py","file_ext":"py","file_size_in_byte":4687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"424122880","text":"import collections\nimport platform\nimport usb1\nfrom usb1 import USBError\n\nG13_KEY_BYTES = collections.namedtuple('G13_KEY_BYTES', [\n 'stick_x', 'stick_y', 'keys'])\n\nKeyPress = collections.namedtuple('KeyPress', ['key_name', 'is_pressed'])\nNamedColor = collections.namedtuple('NamedColor', [\n 'name', 'red_value', 'green_value', 'blue_value'])\n\nG13_KEYS = [ # Which bit should be set\n # /* byte 3 */\n 'G01',\n 'G02',\n 'G03',\n 'G04',\n\n 'G05',\n 'G06',\n 'G07',\n 'G08',\n\n # /* byte 4 */\n 'G09',\n 'G10',\n 'G11',\n 'G12',\n\n 'G13',\n 'G14',\n 'G15',\n 'G16',\n\n # /* byte 5 */\n 'G17',\n 'G18',\n 'G19',\n 'G20',\n\n 'G21',\n 'G22',\n 'UN1', # 'UNDEF1',\n 'LST', # 'LIGHT_STATE',\n\n # /* byte 6 */\n 'BD',\n 'L1',\n 'L2',\n 'L3',\n\n 'L4',\n 'M1',\n 'M2',\n 'M3',\n\n # /* byte 7 */\n 'MR',\n 'LFT',\n 'DWN',\n 'TOP',\n\n 'UN2', # 'UNDEF2',\n 'LT1', # 'LIGHT',\n 'LT2', # 'LIGHT2',\n # 'MISC_TOGGLE',\n]\n\n\nclass LedColors(object):\n PINK = NamedColor('pink', 100, 100, 100)\n FUSCHIA = NamedColor('fuschia', 255, 100, 255)\n PURPLE = NamedColor('purple', 128, 0, 128)\n RED = NamedColor('red', 255, 0, 0)\n MAROON = NamedColor('maroon', 128, 0, 0)\n YELLOW = NamedColor('yellow', 250, 250, 0)\n GREEN = NamedColor('green', 5, 200, 5)\n LIME = NamedColor('lime', 0, 255, 0)\n AQUA = NamedColor('aqua', 0, 255, 255)\n BLUE = NamedColor('blue', 0, 128, 255)\n\n\nclass MissingG13Error(Exception):\n \"\"\"No G13 found on USB.\"\"\"\n\n\nclass G13Device(object):\n VENDOR_ID = 0x046d\n PRODUCT_ID = 0xc21c\n INTERFACE = 0\n MODE_LED_CONTROL = 0x301 # Could be 0x302?\n COLOR_CONTROL = 0x301 # Could be 0x307? Graham: Nope, so far just 0x301\n KEY_ENDPOINT = 1\n REPORT_SIZE = 8\n REQUEST_TYPE = usb1.REQUEST_TYPE_CLASS | usb1.RECIPIENT_INTERFACE\n\n LCD_WIDTH = 160\n LCD_HEIGHT = 43\n\n def __init__(self):\n # 160 across and 43 down (6 bytes down)\n self.pixels = self.get_new_buffer()\n self.device = None\n self.device_handle = None\n self.device_context = None\n self.open()\n\n def open(self):\n try:\n self.device = self._try_obtain_device()\n self._try_obtain_device_handle()\n except IOError as io_ex:\n raise io_ex # nothing we can do to recover from this\n except usb1.USBError as ex:\n if self.device is not None and self.device_handle is not None:\n self.device_handle.resetDevice()\n self._try_obtain_device_handle()\n\n # interruptRead -> R\n # controlWrite -> Out\n\n def _try_obtain_device(self):\n try:\n self.device_context = usb1.USBContext()\n self.device = self.device_context.getByVendorIDAndProductID(self.VENDOR_ID, self.PRODUCT_ID)\n\n if self.device is None:\n raise MissingG13Error()\n return self.device\n except MissingG13Error as missing_ex:\n raise missing_ex\n except Exception as ex:\n print(ex)\n raise IOError(ex, \"Did you run utils/set_perms.sh?\")\n\n def _try_obtain_device_handle(self):\n\n try:\n self.device_handle = self.device.open()\n\n except Exception as ex:\n raise IOError(ex, \"Did you run utils/set_perms.sh?\")\n\n if platform.system() == 'Linux' and \\\n self.device_handle.kernelDriverActive(self.INTERFACE):\n self.device_handle.detachKernelDriver(self.INTERFACE)\n\n self.device_handle.claimInterface(self.INTERFACE)\n\n def close(self):\n if self.device_handle is not None:\n self.device_handle.releaseInterface(self.INTERFACE)\n self.device_handle.close()\n if self.device_context is not None:\n self.device_context.exit()\n\n def get_key_press_bytes(self):\n try:\n data = None\n try:\n data = self.device_handle.interruptRead(\n endpoint=self.KEY_ENDPOINT, length=self.REPORT_SIZE, timeout=500)\n except USBError as usb_ex:\n if usb_ex.value == -7:\n pass\n if data is not None:\n print(data)\n # ord() expected string of length 1, but int found\n keys = list(map(ord, [chr(byte) for byte in data]))\n keys[7] &= ~0x80 # knock out a floating-value key\n return G13_KEY_BYTES(keys[1], keys[2], keys[3:])\n return None\n except Exception as ex:\n print(ex)\n self.close()\n raise ex\n\n def parse_keys(self):\n keys = self.get_key_press_bytes()\n if not any(keys.keys):\n return None\n key_press_bit_map = []\n for i, key in enumerate(G13_KEYS):\n b = keys.keys[int(i / 8)]\n key_press_bit_map.append(KeyPress(key, b & 1 << (i % 8)))\n return key_press_bit_map\n\n def set_led_mode(self, mode):\n try:\n data = ''.join(map(chr, [5, mode, 0, 0, 0]))\n self.device_handle.controlWrite(\n request_type=self.REQUEST_TYPE, request=9,\n value=self.MODE_LED_CONTROL, index=0, data=data.encode(),\n timeout=1000)\n except Exception as ex:\n self.close()\n\n def set_color(self, color):\n self.set_color_from_rgb(color[0], color[1], color[2])\n\n def set_color_from_named_color(self, named_color):\n self.set_color_from_rgb(named_color[1], named_color[2], named_color[3])\n\n def set_color_from_rgb(self, red_value, green_value, blue_value):\n try:\n data = ''.join(map(chr, [7, red_value, green_value, blue_value, 0]))\n self.device_handle.controlWrite(\n request_type=self.REQUEST_TYPE, request=9,\n value=self.COLOR_CONTROL, index=0, data=data.encode(),\n timeout=1000)\n except Exception as ex:\n self.close()\n\n @staticmethod\n def get_new_buffer():\n new_buffer = bytearray(992)\n new_buffer[0] = 3\n return new_buffer\n\n def update_lcd_from_pixels(self):\n try:\n self.device_handle.interruptWrite(endpoint=2, data=memoryview(self.pixels).tobytes(), timeout=1000)\n except Exception as ex:\n self.close()\n\n def update_lcd_from_buffer(self, bytesarray_buffer):\n self.pixels = bytesarray_buffer\n self.update_lcd_from_pixels()\n\n def set_pixel(self, x, y, val):\n x = min(x, 159)\n y = min(y, 43)\n idx = 32 + x + (y / 8) * 160\n if val:\n self.pixels[int(idx)] |= 1 << (y % 8)\n else:\n self.pixels[int(idx)] &= ~(1 << (y % 8))\n\n def __del__(self):\n self.close()\n","sub_path":"LikeAG13/g13_device.py","file_name":"g13_device.py","file_ext":"py","file_size_in_byte":6796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"603098016","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDictionary-based Thai Word Segmentation\nusing maximal matching algorithm and Thai Character Cluster (TCC).\n\nThe code is based on the notebooks created by Korakot Chaovavanich.\n\n:See Also:\n * \\\n https://colab.research.google.com/notebook#fileId=1V1Z657_5eSWPo8rLfVRwA0A5E4vkg7SI\n * \\\n https://colab.research.google.com/drive/14Ibg-ngZXj15RKwjNwoZlOT32fQBOrBx#scrollTo=MYZ7NzAR7Dmw\n\"\"\"\nimport re\nfrom collections import defaultdict\nfrom heapq import heappop, heappush # for priority queue\nfrom typing import Generator, List\n\nfrom pythainlp.tokenize import DEFAULT_DICT_TRIE\n\nfrom .tcc import tcc_pos\nfrom .trie import Trie\n\n# To tokenize English words, for example\n_PAT_ENG = re.compile(\n r\"\"\"(?x)\n[-a-zA-Z]+| # Latin\n\\d[\\d,\\.]*| # number\n[ \\t]+| # space\n\\r?\\n # newline\n\"\"\"\n)\n\n_PAT_TWOCHARS = re.compile(\"[ก-ฮ]{,2}$\")\n\n_TEXT_LIMIT = 120\n_TEXT_SCAN_LEFT = 20\n_TEXT_SCAN_RIGHT = 20\n\n\ndef _bfs_paths_graph(\n graph: defaultdict, start: int, goal: List[int]\n) -> Generator[List[int], None, None]:\n queue = [(start, [start])]\n while queue:\n (vertex, path) = queue.pop(0)\n for next in graph[vertex]:\n if next == goal:\n yield path + [next]\n else:\n queue.append((next, path + [next]))\n\n\ndef _onecut(text: str, custom_dict: Trie) -> Generator[str, None, None]:\n graph = defaultdict(list) # main data structure\n allow_pos = tcc_pos(text) # separating position should aligned with TCC\n\n q = [0] # min-heap queue\n last_p = 0 # last position for yield\n while q[0] < len(text):\n p = heappop(q)\n\n for w in custom_dict.prefixes(text[p:]):\n p_ = p + len(w)\n if p_ in allow_pos: # only pick one that is TCC-valid\n graph[p].append(p_)\n if p_ not in q:\n heappush(q, p_)\n\n # if length == 1 means no longer ambiguous, return previous result\n if len(q) == 1:\n pp = next(_bfs_paths_graph(graph, last_p, q[0]))\n # will eventually start at last_p = pp[0]\n for p in pp[1:]:\n yield text[last_p:p]\n last_p = p\n # will eventually stop at last_p == q[0]\n\n # if length == 0 means not found in dictionary\n if len(q) == 0:\n m = _PAT_ENG.match(text[p:])\n if m: # Latin characters, numeric, space\n i = p + m.end()\n else: # as mininum skip as possible\n for i in range(p + 1, len(text)):\n if i in allow_pos: # only if TCC-valid\n ww = [\n w\n for w in custom_dict.prefixes(text[i:])\n if (i + len(w) in allow_pos)\n ]\n ww = [w for w in ww if not _PAT_TWOCHARS.match(w)]\n m = _PAT_ENG.match(text[i:])\n if ww or m:\n break\n else:\n i = len(text)\n w = text[p:i]\n graph[p].append(i)\n yield w\n last_p = i\n heappush(q, i)\n\n\ndef segment(\n text: str, custom_dict: Trie = DEFAULT_DICT_TRIE, safe_mode: bool = False\n) -> List[str]:\n \"\"\"\n Dictionary-based maximal matching word segmentation, constrained with\n Thai Character Cluster boundaries.\n\n :param str text: text to be tokenized to words\n :param pythainlp.trie.Trie custom_dict: dictionary for tokenization\n :param bool safe_mode: True to avoid long wait for long continuous text\\\n (edge case); Default is False\n :return: list of words, tokenized from the text\n \"\"\"\n if not text or not isinstance(text, str):\n return []\n\n if not custom_dict:\n custom_dict = DEFAULT_DICT_TRIE\n\n if not safe_mode:\n return list(_onecut(text, custom_dict))\n\n text_len = len(text)\n\n if text_len < (_TEXT_LIMIT + _TEXT_SCAN_RIGHT):\n # if the text is shorter than the limit,\n # tokenizes the whole text at once\n return list(_onecut(text, custom_dict))\n else:\n # if the text is longer than the limit,\n # breaks them into smaller chunks then tokenizes each chunk\n text_parts = []\n\n while text_len >= (_TEXT_LIMIT + _TEXT_SCAN_RIGHT):\n sample_start = _TEXT_LIMIT - _TEXT_SCAN_LEFT\n sample_end = _TEXT_LIMIT + _TEXT_SCAN_RIGHT\n sample = text[sample_start:sample_end]\n\n # find possible break positions\n cut_pos = sample_end\n\n # try to break by space first\n space_idx = sample.rfind(\" \")\n if space_idx >= 0:\n cut_pos = space_idx + 1\n else:\n tokens = list(_onecut(sample, custom_dict))\n token_max_idx = 0\n for i, token in enumerate(tokens):\n token_max_len = 0\n if len(token) > token_max_len:\n token_max_len = len(token)\n token_max_idx = i\n\n # choose the position that covers longest token\n cut_pos = sample_start\n for i in range(0, token_max_idx):\n cut_pos = cut_pos + len(tokens[i])\n\n text_parts.append(text[:cut_pos])\n text = text[cut_pos:]\n text_len = len(text)\n\n # append remaining text\n if text_len:\n text_parts.append(text)\n\n # tokenizes each text parts\n tokens = []\n for text_part in text_parts:\n tokens.extend(list(_onecut(text_part, custom_dict)))\n\n return tokens\n","sub_path":"pythainlp/tokenize/newmm.py","file_name":"newmm.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"592999320","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom progressbar import ProgressBar\n\nimport cifar10_input\ncifar10_input.maybe_download_and_extract()\n\n\nlearning_rate = 0.01\ntraining_epochs = 20\nbatch_size = 10\ndislay_step = 1\n\n\ndef inputs(eval_data=True):\n data_dir = os.path.join('data/cifar10_data', 'cifar-10-batches-bin')\n return cifar10_input.inputs(eval_data=eval_data,\n data_dir=data_dir,\n batch_size=batch_size)\n\n\ndef distorted_inputs():\n data_dir = os.path.join('data/cifar10_data', 'cifar-10-batches-bin')\n return cifar10_input.distorted_inputs(data_dir=data_dir,\n batch_size=batch_size)\n\n\ndef conv_batch_norm(x, n_out, phase_train):\n beta_init = tf.constant_initializer(value=0.0, dtype=tf.float32)\n gamma_init = tf.constant_initializer(value=1.0, dtype=tf.float32)\n\n beta = tf.get_variable(\"beta\", [n_out], initializer=beta_init)\n gamma = tf.get_variable(\"gamma\", [n_out], initializer=gamma_init)\n\n batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], name=\"moments\")\n ema = tf.train.ExponentialMovingAverage(decay=0.9)\n ema_apply_op = ema.apply([batch_mean, batch_var])\n ema_mean, ema_var = ema.average(batch_mean), ema.average(batch_var)\n\n def mean_var_with_update():\n with tf.control_dependencies([ema_apply_op]):\n return tf.identity(batch_mean), tf.identity(batch_var)\n\n mean, var = tf.cond(\n phase_train,\n mean_var_with_update,\n lambda: (ema_mean, ema_var)\n )\n\n normed = tf.nn.batch_norm_with_global_normalization(\n x,\n mean,\n var,\n beta,\n gamma,\n 1e-3,\n True\n )\n return normed\n\n\ndef layer_batch_norm(x, n_out, phase_train):\n beta_init = tf.constant_initializer(value=0.0, dtype=tf.float32)\n gamma_init = tf.constant_initializer(value=1.0, dtype=tf.float32)\n\n beta = tf.get_variable(\"beta\", [n_out], initializer=beta_init)\n gamma = tf.get_variable(\"gamma\", [n_out], initializer=gamma_init)\n\n batch_mean, batch_var = tf.nn.moments(x, [0], name=\"moments\")\n ema = tf.train.ExponentialMovingAverage(decay=0.9)\n ema_apply_op = ema.apply([batch_mean, batch_var])\n ema_mean, ema_var = ema.average(batch_mean), ema.average(batch_var)\n\n def mean_var_with_update():\n with tf.control_dependencies([ema_apply_op]):\n return tf.identity(batch_mean), tf.identity(batch_var)\n\n mean, var = tf.cond(\n phase_train,\n mean_var_with_update,\n lambda: (ema_mean, ema_var)\n )\n\n x_r = tf.reshape(x, [-1, 1, 1, n_out])\n normed = tf.nn.batch_norm_with_global_normalization(\n x_r,\n mean,\n var,\n beta,\n gamma,\n 1e-3,\n True\n )\n return tf.reshape(normed, [-1, n_out])\n\n\ndef conv2d(input, weight_shape, bias_shape, phase_train, visualize=False):\n weight_prod = weight_shape[0] * weight_shape[1] * weight_shape[2]\n weight_init = tf.random_normal_initializer(stddev=(2.0/weight_prod)**0.5)\n W = tf.get_variable(\"W\",\n weight_shape,\n initializer=weight_init)\n\n bias_init = tf.constant_initializer(value=0)\n b = tf.get_variable(\"b\",\n bias_shape,\n initializer=bias_init)\n logits = tf.nn.bias_add(\n tf.nn.conv2d(input, W, strides=[1, 1, 1, 1], padding='SAME'),\n b\n )\n return tf.nn.relu(conv_batch_norm(logits, weight_shape[3], phase_train))\n\n\ndef max_pool(input, k=2):\n return tf.nn.max_pool(input,\n ksize=[1, k, k, 1],\n strides=[1, k, k, 1],\n padding='SAME')\n\n\ndef layer(input, weight_shape, bias_shape, phase_train):\n weight_stdev = (2.0/weight_shape[0])**0.5\n weight_init = tf.random_normal_initializer(stddev=weight_stdev)\n bias_init = tf.constant_initializer(value=0)\n W = tf.get_variable(\n \"W\",\n weight_shape,\n initializer=weight_init\n )\n b = tf.get_variable(\n \"b\",\n bias_shape,\n initializer=bias_init\n )\n logits = tf.matmul(input, W) + b\n return tf.nn.relu(\n layer_batch_norm(logits, weight_shape[1], phase_train)\n )\n\n\ndef inference(x, keep_prob, phase_train):\n\n with tf.variable_scope(\"conv_1\"):\n conv_1 = conv2d(x, [5, 5, 3, 64], [64], phase_train)\n pool_1 = max_pool(conv_1)\n\n with tf.variable_scope(\"conv_2\"):\n conv_2 = conv2d(pool_1, [5, 5, 64, 64], [64], phase_train)\n pool_2 = max_pool(conv_2)\n\n with tf.variable_scope(\"fc_1\"):\n dim = 1\n for d in pool_2.get_shape()[1:].as_list():\n dim *= d\n\n pool_2_flat = tf.reshape(pool_2, [-1, dim])\n fc_1 = layer(pool_2_flat, [dim, 384], [384], phase_train)\n fc_1_drop = tf.nn.dropout(fc_1, keep_prob)\n\n with tf.variable_scope(\"fc_2\"):\n fc_2 = layer(fc_1_drop, [384, 192], [192], phase_train)\n # apply dropout\n fc_2_drop = tf.nn.dropout(fc_2, keep_prob)\n\n with tf.variable_scope(\"output\"):\n output = layer(fc_2_drop, [192, 10], [10], phase_train)\n return output\n\n\ndef loss(output, y):\n print(output, y)\n xentropy = tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=y)\n loss = tf.reduce_mean(xentropy)\n return loss\n\n\ndef training(cost, global_step):\n tf.summary.scalar(\"cost\", cost)\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n train_op = optimizer.minimize(cost, global_step=global_step)\n return train_op\n\n\ndef evaluate(output, y):\n correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n tf.summary.scalar(\"validation\", accuracy)\n return accuracy\n\n\npb = ProgressBar()\ntotal = 0\nfor i in pb(range(10)):\n total += i\n\nwith tf.Graph().as_default():\n # cifar10_input data image of shape 24 * 24 * 3 (color)\n x = tf.placeholder(tf.float32, name=\"x\", shape=[None, 24, 24, 3])\n y = tf.placeholder(tf.float32, name=\"y\", shape=[None])\n keep_prob = tf.placeholder(tf.float32)\n phase_train = tf.placeholder(tf.bool)\n with tf.variable_scope(\"mlp_model\"):\n output = inference(x, 0.5, phase_train)\n cost = loss(output, y)\n\n global_step = tf.Variable(0, name='global_step', trainable=False)\n train_op = training(cost, global_step)\n eval_op = evaluate(output, y)\n\n summary_op = tf.summary.merge_all()\n saver = tf.train.Saver()\n\n distorted_images, distorted_labels = distorted_inputs()\n val_images, val_labels = inputs()\n\n # sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n sess = tf.Session()\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n summary_writer = tf.summary.FileWriter(\n \"ch6-02-logistic_logs/\",\n graph_def=sess.graph_def\n )\n\n init_op = tf.initialize_all_variables()\n sess.run(init_op)\n\n valid_errors = []\n\n pb = ProgressBar()\n\n for epoch in range(training_epochs):\n avg_cost = 0.\n total_batch = int(\n cifar10_input.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN/batch_size\n )\n\n # Loop over all batches\n for i in pb(range(total_batch)):\n print(\"run session againt sistords ?\")\n train_x, train_y = sess.run([distorted_images, distorted_labels])\n # fit the training set\n feed_dict = {\n x: train_x,\n y: train_y,\n keep_prob: 1,\n phase_train: True\n }\n print(\"run feed dict?\")\n sess.run(train_op, feed_dict=feed_dict)\n # computer average loss\n minibach_cost = sess.run(cost, feed_dict=feed_dict)\n avg_cost += minibach_cost / total_batch\n valid_errors.append(avg_cost)\n\n # displays logs per epoch step\n if epoch % dislay_step == 0:\n val_feed_dict = {\n x: cifar10_input.validation.images,\n y: cifar10_input.validation.labels\n }\n accuracy = sess.run(eval_op, feed_dict=val_feed_dict)\n print(\"Epoch \", epoch, \"Validation Error: \", (1 - accuracy))\n summary_str = sess.run(summary_op, feed_dict=feed_dict)\n summary_writer.add_summary(summary_str, sess.run(global_step))\n\n save_path = saver.save(\n sess,\n \"ch6-02-logistic_logs/model-checkpoint\"\n )\n print(\"Model saved in file: %s\" % save_path)\n\n print(\"Optimization Finished!\")\n\n test_feed_dict = {\n x: cifar10_input.test.images,\n y: cifar10_input.test.labels\n }\n accuracy = sess.run(eval_op, feed_dict=test_feed_dict)\n print(\"Test Accuracy \", accuracy)\n\n print(\"plot the results\")\n plt.plot(np.arange(0, training_epochs, 1), valid_errors, 'ro')\n plt.ylabel('Error Incurred')\n plt.xlabel('Alpha')\n plt.show()\n","sub_path":"ch6-02-convolution-norm-net.py","file_name":"ch6-02-convolution-norm-net.py","file_ext":"py","file_size_in_byte":9036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"129366659","text":"n=int(input())\nres=[]\nfor _ in range(n):\n res.append(int(input()))\ndef findclose(num):\n if num==1:\n return 0\n k=1\n while num>pow(2,k)-1:\n if num<=pow(2,k+1)-1:\n return pow(2,k+1)-1\n k+=1\nfor h in res:\n minus=findclose(h)-h\n res=str(minus)+\" \"+str(findclose(h))\n print(res)","sub_path":"Code/CodeRecords/2668/60749/257831.py","file_name":"257831.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"29209840","text":"\"\"\"\n队列Block模式\n\"\"\"\nimport gevent\nimport gevent.monkey\nimport time\nimport datetime\nimport requests\nfrom gevent import queue\ngevent.monkey.patch_all()\n\ndata_queue = queue.Queue()\n\n\ndef push_data():\n data_list = []\n\n while True:\n item = data_queue.get()\n data_list.append(item)\n\n while len(data_list) < 30:\n try:\n item = data_queue.get(block=False)\n data_list.append(item)\n time.sleep(0.31)\n continue\n except queue.Empty:\n break\n print(\"pushed: {}\".format(data_list))\n data_list = []\n time.sleep(1)\n\n\ndef create_data():\n count = 0\n while True:\n count += 1\n if count % 100 == 0:\n time.sleep(0.2)\n data_queue.put(count)\n print(\"created: {}\".format(count))\n time.sleep(0.3)\n\n\ndef gevent_main():\n spawns = []\n spawns = [gevent.spawn(create_data), gevent.spawn(push_data)]\n\n gevent.joinall(spawns)\n\n\nif __name__ == '__main__':\n gevent_main()\n","sub_path":"Gevent/queue_with_get_block.py","file_name":"queue_with_get_block.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"150455289","text":"N = int(input())\na = list(map(int,input().split()))\nans = 0\na = sorted(a)\na = a[::-1]\nfor i in range(N):\n if i % 2 == 0:\n ans += a[i]\n else:\n ans -=a[i]\nprint(ans)","sub_path":"Python_codes/p03434/s086331937.py","file_name":"s086331937.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"229584049","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\nfrom __future__ import annotations\nimport copy\n\nclass Solution:\n def pruneTree(self, root: TreeNode) -> TreeNode:\n\n def pruneLeave(root: TreeNode) -> TreeNode:\n if root is None:\n return None\n else:\n if root.left is None and root.right is None and root.val == 0:\n return None\n else:\n return root\n \n level = 0\n stack = [(level, root)]\n while stack != []:\n level, curr = stack.pop()\n curr = pruneLeave(curr)\n if curr is not None:\n print(level, curr.val)\n if not curr.left and not curr.right and curr.val == 0:\n curr = None\n else:\n if curr.left:\n curr.left = pruneLeave(curr.left)\n if curr.left:\n stack.append((level+1, curr.left))\n if curr.right:\n curr.right = pruneLeave(curr.right)\n if curr.right:\n stack.append((level+1, curr.right))\n if not curr.left and not curr.right and curr.val == 0:\n stack.append( (level, curr) )\n\n return root\n\nif __name__ == '__main__':\n from binarytree import TreeNode\n\n sol = Solution()\n\n input_list = [\n [0, None, 3],\n [1, None, 0, 0, 1],\n [1,0,1,0,0,0,1],\n ]\n\n for i, x in enumerate(input_list):\n print(\"=============={}==============\".format(x))\n tree = TreeNode.list2tree(x)\n #TreeNode.printTree(tree)\n\n \n tree_ = sol.pruneTree(tree)\n TreeNode.printTree_bfs(tree_)\n ","sub_path":"ex814_binary_tree_pruning/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"444920650","text":"# -*- coding: utf-8 -*-\n\n# OCGUI ... Open Campus Graphical User Interface\n\nimport pygame\nfrom pygame.locals import *\nimport codecs\nimport Util\nimport sys\nimport Window\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport datetime\nimport PrototypeScene\nimport IScene\nimport MakeScene\n\nclass OCGUI:\n __dirPathOfInitInfoFiles = './init'\n __pathOfInitInfoForWindow = __dirPathOfInitInfoFiles + '/window.info'\n\n # コンストラクタ\n def __init__(self):\n # ウィンドウの初期設定を行う\n self.__initWindow()\n # シーンを作成する\n self.__scene = MakeScene.makeScene(\n IScene.SceneID.PROTOTYPE_SCENE,\n #IScene.SceneID.PLAY_GAME_SCENE ,\n self.__window\n )\n #Scene.Scene(self.__window)\n\n\n # 描画処理を行うメソッド\n def __draw(self):\n self.__window.fill() # ウィンドウの描画内容を消す\n self.__scene.draw() # 描画処理を行う\n self.__window.flip() # バッファに描画された内容を画面へ表示する\n \n\n # 更新処理を行うメソッド\n def __update(self): \n self.__scene.update() # シーンの状態を更新する\n\n\n # メインループ用のメソッド\n def do(self):\n # Sceneが終了状態出ない限りループ\n while self.__scene.isRunning():\n self.__draw() # 描画処理\n self.__update() # 更新処理 \n \n if self.__scene.isExit():\n self.__scene = MakeScene.makeScene(\n self.__scene.getNextSceneID(),\n self.__window\n )\n\n self.__clock.tick(self.__FPS) # FPS調整\n # ウィンドウを閉じる\n self.__window.quit() \n\n\n # ウィンドウの初期設定を行うメソッド\n def __initWindow(self):\n # ウィンドウに関する情報を読み込む\n windowInfoFile = open(self.__pathOfInitInfoForWindow, 'r') # ウィンドウの初期設定が記述されたファイルを開く\n windowCaption = windowInfoFile.readline() # ウィンドウのキャプションを読み込む\n windowCaption = windowCaption.strip(\"\\n\") # readlineでは改行\"\\n\"も読み込まれるので\"\\n\"を削除する\n windowSize = windowInfoFile.readline().split() # 空白区切りでウィンドウサイズを読み込む\n windowSize = [ int(windowSize[0]), int(windowSize[1]) ] # 読み込まれたデータは文字列なので各々をint型へ変換する\n windowBgColor = windowInfoFile.readline().split() # ウィンドウの画面の初期RGBを設定する\n windowFontName = windowInfoFile.readline() # 読み込まれたデータは文字列なので各々をint型へ変換する\n windowFontName = windowFontName.strip(\"\\n\") # フォントの名前を読み込む\n windowFontSize = int(windowInfoFile.readline()) # フォントのサイズを読み込む\n windowFontColor = windowInfoFile.readline().split() # フォントの色を設定する\n windowFontColor = [ int(windowFontColor[0]), # 読み込まれたデータは文字列なので各々をint型へ変換する\n int(windowFontColor[1]), \n int(windowFontColor[2]),\n ]\n windowFPS = int( (windowInfoFile.readline()).strip(\"\\n\") )# FPSを読み込む\n\n self.__window = Window.Window(windowSize[0], windowSize[1]) # ウィンドウを作成する\n self.__window.setWindowCaption(windowCaption) # ウィンドウのキャプションを作成する\n self.__window.setFont( # ウィンドウで使用されるフォントを設定する\n windowFontName, # フォント名\n windowFontSize, # フォントサイズ\n [ int(windowFontColor[0]), int(windowFontColor[1]), int(windowFontColor[2]) ] # フォントの色(R,G,B)\n )\n self.__clock = pygame.time.Clock() # FPS計算用のインスタンスを作成\n self.__FPS = windowFPS # FPSを設定する\n","sub_path":"結合テスト(仮)/Decoration(old)/OCGUI.py","file_name":"OCGUI.py","file_ext":"py","file_size_in_byte":4736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"56597075","text":"# vim: set et sw=2 :\n\n\"\"\" buildbot resource for submitting try server patches via HTTP \"\"\"\n\nfrom twisted.web.resource import Resource\n#from twisted.web.error import ErrorPage\nfrom twisted.web import http\nimport twisted.web.server\nfrom buildbot.sourcestamp import SourceStamp\nimport os, time, random\n\nDEBUG = False\n\nclass TrySubmitter(Resource):\n \"\"\" a IResource to accept submission of a patch for the try server \"\"\"\n\n def __init__(self, trydir, builders=[], userpass=None):\n Resource.__init__(self)\n self.builders = builders\n self.path = trydir\n if userpass is not None:\n assert len(userpass) is 2\n self.userpass = userpass\n\n def render(self, request):\n \"\"\" Check for HTTP basic auth, and pass to normal rendering if accepted \"\"\"\n\n try:\n self.projectName = request.site.buildbot_service.parent.projectName\n except:\n self.projectName = \"\"\n\n if self.userpass is not None:\n if request.getUser() != self.userpass[0] or request.getPassword() != self.userpass[1]:\n realm = \"%s buildbot tryserver\" % self.projectName\n\n request.setHeader('WWW-Authenticate',\n 'Basic Realm=\"%s\"' % realm)\n errpage = ErrorPage(http.UNAUTHORIZED,\n \"Unauthorized\",\n \"401 Authentication required\")\n return errpage.render(request)\n return Resource.render(self, request) \n\n def render_GET(self, request):\n request.write(\"\"\"\n \n \n Buildbot try submit\n \n \n \n \n \n \n \"\"\")\n\n if DEBUG:\n object = request.site.buildbot_service.parent\n for i in dir(object):\n request.write(\"%s
\" % i)\n request.write(\"%s
\" % str(object).replace(\"<\", \"<\"))\n\n request.finish()\n return twisted.web.server.NOT_DONE_YET\n\n\n def render_POST(self, request):\n request.write(\"\"\"\n \n \"\"\")\n if not request.args.has_key(\"patch\"):\n request.write(\"no patch submitted\")\n request.finish()\n return twisted.web.server.NOT_DONE_YET\n\n patch = \"\\n\".join(request.args[\"patch\"])\n \n #ss = SourceStamp(self.branch, self.baserev, (self.patchlevel, patch))\n # generate random unique build stamp id\n bsid = \"%d-%s\" % (time.time(), random.randint(0, 1000000))\n\n if request.args.has_key(\"branch\"):\n branch = str(request.args[\"branch\"][0])\n else:\n branch = None\n\n if request.args.has_key(\"rev\"):\n rev = str(request.args[\"rev\"][0])\n else:\n rev = None\n\n if request.args.has_key(\"builder\"):\n builders = request.args[\"builder\"]\n else:\n builders = self.builders\n for builder in builders:\n if not builder in self.builders:\n request.write(\"\"\"builder %s unknown
\"\"\" % builder)\n\n patchlevel = 1 # default vaule\n if request.args.has_key(\"patchlevel\"):\n try:\n lvl = int(request.args[\"patchlevel\"][0])\n if lvl >= 0:\n patchlevel = lvl\n except (TypeError, ValueError):\n pass\n\n request.write(\"\"\"submitting patch:
\n revision %s branch %s with patchlevel %s to builders %s\n %s
\n \"\"\" % ((rev or \"HEAD\"), (branch or \"trunk\"), patchlevel, \", \".join(builders), patch))\n\n def ns(s):\n return \"%d:%s,\" % (len(s), s)\n \n job = \"\"\n job += ns(\"1\") # jobspec version\n job += ns(bsid) # build stamp id\n job += ns(str(branch or \"\"))\n job += ns(str(rev or \"\"))\n job += ns(\"%d\" % patchlevel)\n job += ns(patch)\n for name in builders:\n job += ns(name)\n\n if DEBUG:\n request.write(\"\"\"%s
\"\"\" % job)\n else:\n path = os.path.join(self.path, \"new\", bsid)\n f = open(path, \"w\")\n f.write(job)\n f.close()\n\n request.finish()\n return twisted.web.server.NOT_DONE_YET\n\n\n","sub_path":"experimental/buildbot/trysubmitter.py","file_name":"trysubmitter.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"609202349","text":"import unittest\nimport random\n\nN_RANGE = (1, 50)\nGRID_RANGE = (0, 50)\n\nclass Solution(object):\n def solution(self, s, t):\n if not s:\n return False\n if not t:\n return True\n if self.isSameTree(s, t):\n return True\n\n return self.solution(s.left, t) or self.solution(s.right, t)\n\n def isSameTree(self, p, q):\n if not p and not q:\n return True\n if not p or not q:\n return False\n if p.val != q.val:\n return False\n \n return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n\n\nclass Test(unittest.TestCase):\n\n def __init__(self, _):\n super(Test, self).__init__(_)\n self.s = Solution()\n\n def test_example1(self):\n self.assertEqual(self.s.solution(['a','b','c','a','c','c']), 3) # ['a','a'], ['b'], ['c','c','c']\n self.assertEqual(self.s.solution(['aa','bb','ab','ba']), 4) # ['aa'], ['bb'], ['ab'], ['ba']\n self.assertEqual(self.s.solution(['abc','acb','bac','bca','cab','cba']), 3) # ['abc','cba'], ['acb','bca'], ['bac','cab']\n self.assertEqual(self.s.solution(['abcd','cdab','adcb','cbad']), 1) # ['abcd','cdab','adcb','cbad']\n\n # def test_example2(self):\n # self.assertEqual(self.s.solution([[2], [1, 2]]), 22)\n \n\ndef main():\n unittest.main()\n\nif __name__ == '__main__':\n main()","sub_path":"leetcode/572_Subtree_of_Another_Tree.py","file_name":"572_Subtree_of_Another_Tree.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"2643215","text":"import os\r\n\r\ndef cal(filename):\r\n\tf=open(filename)\r\n\tfor i in range(3):\r\n\t\tf.readline()\r\n\tsize=f.readline()\r\n\tsize=size.split(',')[2].split(':')[1][1:]\r\n\tt=f.readline()\r\n\tt=t.split(',')[0]\r\n\tf.close()\r\n\treturn (size,t)\r\n\r\n\r\nif __name__=='__main__':\r\n files=os.listdir()\r\n models=list(filter(lambda x:'.model' in x,files))\r\n models=list(map(lambda x:x.split('.')[0],models))\r\n res=dict()\r\n for i in models:\r\n \tres[i]=[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]\r\n results=list(filter(lambda x:'result' in x,files))\r\n for i in results:\r\n \tname=i.split('_')\r\n \tmodel=name[0]\r\n \tstrength=int(name[2])\r\n \trepeat=int(name[3])\t\r\n \tres[model][strength-2][repeat-1]=cal(i)\r\n f=open('res.csv','w')\r\n f.write('model,2_1,2_2,2_3,3_1,3_2,3_3,4_1,4_2,4_3,5_1,5_2,5_3,6_1,6_2,6_3\\n')\r\n for key in res:\r\n \tf.write(key+',')\r\n \tvalue=res[key]\r\n \tfor i in range(5):\r\n for j in range(3):\r\n \tif not value[i][j]==0:\r\n \t\tf.write(value[i][j][0]+'/'+value[i][j][1]+',')\r\n \telse:\r\n \t\tf.write('-,')\r\n \tf.write('\\n')\r\n f.close()\r\n \r\n\r\n","sub_path":"results/issta20model/cal_old.py","file_name":"cal_old.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"122418576","text":"import logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\n\ndef _input_path_sanitizer(func):\n def inner(trie, path):\n if not path.startswith(\"/\"):\n raise SyntaxError(\"Path must starts with a / character\")\n return func(trie, path)\n return inner\n\n\nclass _Trie(object):\n\n _paths = {}\n __end = 'end'\n\n def make_trie(self, *args):\n for path in args:\n self.add(path)\n\n @staticmethod\n def get_pieces(path):\n return path.split(\"/\")[1:]\n\n @_input_path_sanitizer\n def add(self, path):\n logging.info(\"Adding directory {}\".format(path))\n pieces = self.get_pieces(path)\n temp_trie = self._paths\n for piece in pieces:\n # if we're at the end of the trie, take out the delimiter.\n if piece in temp_trie and self.__end in temp_trie[piece]:\n del temp_trie[piece][self.__end]\n # setdefault() tries to get the key, if it exists. if it doesn't set it to the second parameter\n temp_trie = temp_trie.setdefault(piece, {})\n # set the delimiter here in all cases\n temp_trie.setdefault(self.__end, self.__end)\n\n @_input_path_sanitizer\n def exists(self, path):\n pieces = self.get_pieces(path)\n temp = self._paths\n for piece in pieces:\n if piece not in temp:\n logging.info(\"{} does not exist\".format(path))\n return False\n temp = temp[piece]\n logging.info(\"{} exists\".format(path))\n return True\n\n @_input_path_sanitizer\n def remove(self, path):\n pass # this one is a bit harder...\n\n\n @property\n def paths(self):\n return self._paths\n\n @property\n def end(self):\n return self.__end\n\n\nclass _FkDir(object):\n\n files = []\n\n def __init__(self, path):\n self.path = path\n\n\nclass _FkFile(object):\n\n def __init__(self, path, contents):\n self.path = path\n self.contents = contents\n\n\nclass FakeFs(object):\n\n def __init__(self):\n self._dirs = _Trie()\n self._paths = set(\"/\")\n\n def mkdir(self, directory):\n self._dirs.add(directory)\n self._compile_dirs()\n\n def dir_exists(self, dir_path):\n return self._dirs.exists(dir_path)\n\n def rm(self, dir_path):\n if self.dir_exists(dir_path):\n return self._dirs.remove(dir_path)\n else:\n logging.error(\"Cannot remove directory.\")\n\n def rmdir(self, directory):\n pass\n\n def touch(self, filename):\n pass\n\n def _compile_dirs(self):\n paths = set()\n for k, v in self._dirs.paths.items():\n path = [k]\n has_more = type(v) is dict\n while has_more and type(v) is not str:\n for inside_k, inside_v in v.items():\n has_more = type(v) is dict\n v = inside_v\n if inside_v != self._dirs.end:\n path.append(inside_k)\n paths.add(\"/{}\".format(\"/\".join(path)))\n self._paths = sorted(paths)\n\n @property\n def paths(self):\n return self._paths\n\nfs = FakeFs()\nfs.mkdir(\"/poo/woo/soo/doo/poo\")\nfs.mkdir(\"/etc\")\nfs.mkdir(\"/\")\nfs.mkdir(\"/tmp\")\nfs.mkdir(\"/tmp/whatever\")\nfs.mkdir(\"/var/www/mysite\")\nfs.dir_exists(\"/sadsad\")\nfs.dir_exists(\"/etc\")\nprint(fs.paths)","sub_path":"fakefs.py","file_name":"fakefs.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"28618975","text":"from __future__ import division\nfrom scipy.ndimage import zoom\nfrom random import randint\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom datetime import datetime, timedelta, time\nfrom data_helper_functions_webapp import *\nfrom time import sleep\n\ndef return_power(month_data, day_data, hour_data, sat_to_sensor_model, sensor_to_power_mod):\n '''Input: datetime\n Output: power\n Info: also makes satellite image'''\n\n ######### Satellite image ###############\n # get sat image first, so it may be redered by computation is done\n desired_channel = 'BAND_01'\n desired_date = datetime(2014, month_data, day_data)\n desired_timedelta = timedelta(hours = hour_data)\n desired_datetime = desired_date + desired_timedelta\n satellite_filefolder = '../../data/satellite/colorado/summer6months/data/'\n sensor_filefolder = '../../data/sensor_data/colorado6months/'\n pvoutput_filefolder = '../../data/pvoutput/pvoutput6months/'\n\n #satellite data\n satellite_filename = find_filename(desired_datetime, desired_channel, satellite_filefolder)\n lons, lats, data = return_satellite_data(satellite_filename, satellite_filefolder)\n\n plt.figure(figsize=(8, 8))\n imgplot = plt.imshow(data)\n imgplot.set_interpolation('none')\n plt.savefig('static/images/foo.png', bbox_inches='tight') # save sat image to foo.png\n\n ############## Model for satellite to sensor ############################\n\n X = [] #sat data\n Y = [] #sensor data\n\n desired_date = (desired_datetime - timedelta(hours=6)).date() #make sure correct date\n desired_date = datetime.combine(desired_date, time.min) #get into datetime format\n\n desired_channel = 'BAND_01' #problems with an inner for loop (doesn't look good, but works)\n satellite_filename = find_filename(desired_datetime, desired_channel, satellite_filefolder)\n lons, lats, data1 = return_satellite_data(satellite_filename, satellite_filefolder)\n\n desired_channel = 'BAND_02'\n satellite_filename = find_filename(desired_datetime, desired_channel, satellite_filefolder)\n lons, lats, data2 = return_satellite_data(satellite_filename, satellite_filefolder)\n\n desired_channel = 'BAND_03'\n satellite_filename = find_filename(desired_datetime, desired_channel, satellite_filefolder)\n lons, lats, data3 = return_satellite_data(satellite_filename, satellite_filefolder) \n\n desired_channel = 'BAND_04'\n satellite_filename = find_filename(desired_datetime, desired_channel, satellite_filefolder)\n lons, lats, data4 = return_satellite_data(satellite_filename, satellite_filefolder)\n\n desired_channel = 'BAND_06'\n satellite_filename = find_filename(desired_datetime, desired_channel, satellite_filefolder)\n lons, lats, data5 = return_satellite_data(satellite_filename, satellite_filefolder)\n\n sensor_filename = find_file_from_date(desired_date, sensor_filefolder)\n df_sensor = return_sensor_data(sensor_filename, sensor_filefolder).ix[:,-15:-1]\n df_sensor[df_sensor.index == desired_datetime]\n\n Y.append(df_sensor[df_sensor.index == desired_datetime].values[0])\n X.append(np.hstack( ( np.ravel(data1) , np.ravel(data2), np.ravel(data3) , np.ravel(data4), np.ravel(data5) ) ) )\n\n X,Y = (np.array(X),np.array(Y))\n\n ####################### Make sat data useful ####################\n X_ratio_1_2 = []\n for i in xrange(X.shape[0]): #a little awkward since X is only one row, but no need to change\n CH1 = zoom(X[:,0:1972][i].reshape((29,68)),zoom=(0.48, 0.53), order=5)\n CH2 = X[:,1972:2476][i].reshape((14,36))\n X_ratio_1_2.append(25000* (CH2) / (CH1 + CH2+1.0) )\n X_ratio_1_2 = np.array(X_ratio_1_2)\n\n X_ratio_1_6 = []\n for i in xrange(X.shape[0]):\n CH1 = zoom(X[:,0:1972][i].reshape((29,68)),zoom=(0.48, 0.53), order=5)\n CH6 = X[:,3484:3988][i].reshape((14,36))\n X_ratio_1_6.append(25000* CH6 / (CH1 + CH6 + 0.1) )\n X_ratio_1_6 = np.array(X_ratio_1_6)\n\n X_ratio_2_6 = []\n for i in xrange(X.shape[0]):\n CH2 = X[:,1972:2476][i].reshape((14,36))\n CH6 = X[:,3484:3988][i].reshape((14,36))\n X_ratio_2_6.append(25000* CH6 / (CH2 + CH6 + 0.1) )\n X_ratio_2_6 = np.array(X_ratio_2_6)\n\n ######## change X into histogram #############\n X_hist = []\n bins = 25\n for i in xrange(X.shape[0]):\n myval1 = pd.DataFrame(np.ravel(X_ratio_1_2[i])).fillna(np.mean).values.flatten();\n myval2 = pd.DataFrame(np.ravel(X_ratio_1_6[i])).fillna(np.mean).values.flatten();\n myval3 = pd.DataFrame(np.ravel(X_ratio_2_6[i])).fillna(np.mean).values.flatten();\n\n hist1, _ = np.histogram(X[:,0:1972][i], density=True, bins=bins, range=(0,25000))\n hist2, _ = np.histogram(X[:,1972:2476][i], density=True, bins=bins, range=(0,25000))\n hist3, _ = np.histogram(X[:,2476:2980][i], density=True, bins=bins, range=(0,25000))\n hist4, _ = np.histogram(X[:,2980:3484][i], density=True, bins=bins, range=(0,25000))\n hist5, _ = np.histogram(X[:,3484:3988][i], density=True, bins=bins, range=(0,25000))\n hist6, _ = np.histogram( myval1 , density=True, bins=bins, range=(0,25000) )\n hist7, _ = np.histogram( myval2 , density=True, bins=bins, range=(0,25000))\n hist8, _ = np.histogram( myval3, density=True, bins=bins, range=(0,25000))\n X_hist.append(np.hstack((hist1,hist2,hist3,hist4,hist5,hist6,hist7,hist8)))\n\n X_hist = np.array(X_hist)\n\n #################### #Import models (run models) #######################\n\n # from sklearn.externals import joblib #joblib is sklearn's pickle\n # sat_to_sensor_model = joblib.load('models/sat-to-sensor-model/sat-to-sensor-model.pkl')\n # sensor_to_power_mod = joblib.load('models/sensor-to-power-model/sensor-to-power-model.pkl')\n\n X_sensor = sat_to_sensor_model.predict(X_hist)\n y_power = sensor_to_power_mod.predict(X_sensor)\n\n return y_power[0]\n\n\n","sub_path":"webapp/solarApp/solarApp_helper_functions.py","file_name":"solarApp_helper_functions.py","file_ext":"py","file_size_in_byte":5915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"169079571","text":"#! /usr/bin/env python\n#! /bin/env python\n# coding=utf-8\n# Source code on GitHub, link \"https://github.com/ssssssbn/cloudflare_ddns\", modified based on \"https://github.com/AmirAzodi/cloudflare_ddns\"\n# place cloudflare_ddns_lib.py, cloudflare_api.py, logger.py, cloudflare-ddns.py and cloudflare-ddns.conf on your server (e.g. /usr/local/bin/ or ~/)\n# run this command:\n# chmod +x /\"PATH_TO_FILE\"/cloudflare-ddns.py\n# open cloudflare-ddns.conf in a text editor and set the necessary parameters.\n# (One domain name, one type, one way to get IPv4/6, email address and api_key are required)\n\n#import pdb;\n\nimport os;\nimport json;\nimport re;\nimport logging;\nimport copy;\nimport time;\n\ntry:\n # For Python 3.0 and later\n from urllib.request import urlopen;\n from urllib.request import Request;\n from urllib.error import URLError;\n from urllib.error import HTTPError;\n # import urllib.parse\nexcept ImportError:\n # Fall back to Python 2's urllib2\n from urllib2 import urlopen;\n from urllib2 import Request;\n from urllib2 import HTTPError;\n from urllib2 import URLError;\n\n\nimport cloudflare_api;\nimport logger;\n\nipv4_regex = '^(\\d{1,3}\\.){4}$';\nipv6_regex = '^(([\\da-fA-F]{0,4}):){2,8}$';\nttl_range = [1, 120, 300, 600, 900, 1800, 3600, 7200, 18000, 43200, 86400];\ntype_support = ['A', 'AAAA', 'CNAME'];\n \n\npublic_ipv4 = None;\ntry_get_ipv4 = False;\npublic_ipv6 = None;\ntry_get_ipv6 = False;\nupdate = False;\ncontent_header = None;\nverify_account = False;\nconfig_file_path = None;\nconfig_file_name = 'cloudflare_ddns.conf';\n__config_file_location__ = None;\nconfig = None;\nlog_file_path = '/tmp/cloudflare_ddns';\nlog_file_name = 'cloudflare_ddns.log';\n\nclass_logger = None;\nlog = None;\n\n#pdb.set_trace();\ndef get_ipv4():\n try:\n if config['get_ipv4_by_command']:\n log.info('* Getting public IPv4 address by \"get_ipv4_by_command\"');\n result = os.popen(config['get_ipv4_by_command']).read().rstrip();\n if not re.match(ipv4_regex, result + '.'):\n log.warning('* The obtained public IPv4 address({0}) by \"get_ipv4_by_command\" is invalid, please check configured \"get_ipv4_by_command\" item'.format(\n result));\n else:\n log.info('* Succeed to get IPv4 address({0}) by \"get_ipv4_by_command\"'.format(\n result));\n return result;\n\n if config['get_ipv4_via_url']:\n log.info('* Getting public IPv4 address by \"get_ipv4_via_url\", it may take a while...');\n result = urlopen(Request(config['get_ipv4_via_url'])).read().rstrip().decode('utf-8');\n if not re.match(ipv4_regex, result + '.'):\n log.warning('* The obtained public IPv4 address({0}) by \"get_ipv4_via_url\" is invalid, please check configured \"get_ipv4_via_url\" item'.format(\n result));\n log.warning('* Unable to get public IPv4, please check configured \"get_ipv4_by_command\" and \"get_ipv4_via_url\" items');\n else:\n log.info('* Succeed to get IPv4 address({0}) by \"get_ipv4_via_url\"'.format(\n result));\n return result;\n except (Exception, URLError) as e:\n if str(e).find('Network is unreachable') != -1:\n log.error('* Ignore this message if this host does not have a public IPv4, otherwise check your network');\n else:\n log.error('* An exception occurred while getting public IPv4 address. Exception: {0}'.format(\n e));\n return None;\n\n#pdb.set_trace();\ndef get_ipv6():\n try:\n if config['get_ipv6_by_command']:\n log.info('* Getting public IPv6 address by \"get_ipv6_by_command\"');\n result = os.popen(config['get_ipv6_by_command']).read().rstrip();\n if not re.match(ipv6_regex, result + ':'):\n log.warning('* The obtained public IPv6 address({0}) by \"get_ipv6_by_command\" is invalid, please check configured \"get_ipv6_by_command\" item'.format(\n result));\n else:\n log.info('* Succeed to get IPv6 address({0}) by \"get_ipv6_by_command\"'.format(\n result));\n return result;\n\n if not got_ipv6 and config['get_ipv6_via_url']:\n log.info('* Getting public IPv6 address by \"get_ipv6_via_url\", it may take a while...');\n result = urlopen(Request(config['get_ipv6_via_url'])).read().rstrip().decode('utf-8');\n if not re.match(ipv6_regex, result + ':'):\n log.warning('* The obtained public IPv6 address({0}) by \"get_ipv6_via_url\" is invalid, please check configured \"get_ipv6_via_url\" item'.format(\n result));\n log.warning('* Unable to get public IPv6, please check configured \"get_ipv6_by_command\" and \"get_ipv6_via_url\" items');\n else:\n log.info('* Succeed to get IPv6 address({0}) by \"get_ipv6_via_url\"'.format(\n result));\n return result;\n except (Exception, URLError) as e:\n if str(e).find('Network is unreachable') != -1:\n log.error('* Ignore this message if this host does not have a public IPv6, otherwise check your network');\n else:\n log.error('* An exception occurred while getting public IPv6 address. Exception: {0}'.format(\n e));\n return None;\n\ndef get_zone_info(domain, root_domain_name, header):\n log.info('* Getting zone information for \"{0}\"'.format(\n root_domain_name));\n try:\n result = cloudflare_api.get_zone(root_domain_name, header);\n if result['success']:\n log.info('* Succeed to get zone information for \"{0}\"'.format(\n root_domain_name));\n if result['result_info']['total_count'] != 1:\n if domain['create_if_root_domain_not_exists']:\n log.info('* No active zone for \"{0}\" found, configuration \"create_if_root_domain_not_exists\" is \"True\", creating automatically '.format(\n root_domain_name));\n try:\n #pdb.set_trace();\n zone_create_json = cloudflare_api.create_zone(root_domain_name, False, 'full', header);\n if zone_create_json['success']:\n log.info('* Succeed to create zone for \"{0}\"'.format(\n root_domain_name));\n return zone_create_json;\n else:\n log.error('Failed to create zone for \"{0}\", skipping the update for this domain. Errors: {1}, messages: {2}'.format(\n root_domain_name, zone_create_json['errors'], zone_create_json['messages']));\n return None;\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while creating zone for \"{0}\", skipping the update for this domain. Exception: {1}'.format(\n root_domain_name, e));\n return None;\n else:\n log.info('* No active zone for \"{0}\" found, configuration \"create_if_root_domain_not_exists\" is \"False\", skipping the update for this domain. Please check configuration and cloudflare settings and try again'.format(\n root_domain_name));\n return None;\n else:\n return result;\n else:\n log.error('* Failed to get zone for \"{0}\", skipping the update for this domain. Errors: {1}, messages: {2}'.format(\n root_domain_name, result['errors'], result['messages']));\n return None;\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while getting zone information for: \"{0}\". Exception: {1}'.format(\n root_domain_name, e));\n return None;\n\ndef run():\n global public_ipv4;\n global try_get_ipv4;\n global public_ipv6;\n global try_get_ipv6;\n global update;\n global content_header;\n global verify_account;\n global config_file_path;\n global config_file_name;\n global __config_file_location__;\n global config;\n global log_file_path;\n global log_file_name;\n \n global class_logger;\n global log;\n\n if not config_file_path:\n config_file_path = os.path.realpath(\n os.path.join(os.getcwd(), os.path.dirname(__file__)))\n __config_file_location__ = os.path.join(config_file_path, config_file_name);\n \n log_file_location = os.path.join(log_file_path, log_file_name);\n if not os.path.exists(log_file_path):\n os.makedirs(log_file_path);\n os.popen('touch {0}'.format(log_file_location));\n elif not os.path.exists(log_file_location):\n os.popen('touch {0}'.format(log_file_location));\n #else:\n # os.popen('cat /dev/null > {0}'.format(log_file_location));\n \n if not class_logger:\n class_logger = logger.Logger('logger', \n logging.DEBUG, \n log_file_path + '/cloudflare_ddns.log', \n 'a', \n '%(asctime)s-%(levelname)s[line:%(lineno)d]: %(message)s', \n 'utf-8', \n True, \n 'D', \n 1,\n 30);\n log = class_logger.logger;\n \n log.info('------------------------------');\n \n try:\n with open(__config_file_location__, 'r') as config_file:\n try:\n config = json.loads(config_file.read());\n except (Exception, ValueError) as e:\n log.critical('* An exception occurred while loading file \"{0}\", please check if the file content conforms to the JSON format, the program exit. Exception: {1}'.format(\n __config_file_location__, e));\n exit(0);\n except Exception as e:\n log.critical('* An exception occurred while opening file \"{0}\", make sure the file exists and you have the permission to read and write it, the program exit. Exception: {1}'.format(\n __config_file_location__, e));\n exit(0);\n \n log_level = None;\n if config['log_level'] not in (0, 1, 2, 3, 4):\n update = True;\n log_level = config['log_level'] = 1;\n else:\n log_level = config['log_level'];\n \n if log_level == 0:\n class_logger.SetLogLevel(logging.DEBUG);\n elif log_level == 1:\n class_logger.SetLogLevel(logging.INFO);\n elif log_level == 2:\n class_logger.SetLogLevel(logging.WARNING);\n elif log_level == 3:\n class_logger.SetLogLevel(logging.ERROR);\n elif log_level == 4:\n class_logger.SetLogLevel(logging.CRITICAL);\n\n if not config['user']['email'] or not config['user']['api_key']:\n log.critical('* Program is unable to continue without Cloudflare authentication credentials');\n exit(0);\n \n content_header = {'X-Auth-Email': config['user']['email'],\n 'X-Auth-Key': config['user']['api_key'],\n 'Content-type': 'application/json'};\n\n\n for domain in config['domains']:\n zone_json = None;\n get_zone = False;\n new_zone = False;\n next_zone = False;\n root_domain_name = domain['root_domain_name'];\n # check to make sure domain name is specified\n if not root_domain_name:\n log.error('* Missing root_domain name, skipping the update this domain, please check configuration');\n continue;\n \n \n # get domain zone id from CloudFlare if missing\n for host in domain['hosts']:\n # check to make sure host name is specified\n # otherwise move on to the next host\n full_domain_name = None;\n if not host['sub_domain_name_prefix']:\n full_domain_name = root_domain_name;\n else:\n full_domain_name = host['sub_domain_name_prefix'] + '.' + root_domain_name;\n \n types = [];\n \n # iterate over the DNS record types\n for record in host['records']:\n type =record['type'];\n content = record['content'];\n ttl = record['ttl'];\n proxied = record['proxied'];\n \n dns_record_json = None;\n need_update = False;\n # select which IP to use based on DNS record type (e.g. A or AAAA)\n #pdb.set_trace()\n if type not in type_support:\n log.error('* Missing or wrong or unsupported DNS record type: \"{0}\", skipping the update for type \"{1}\" of \"{2}\"'.format(\n type, type, full_domain_name));\n continue;\n elif type == 'A':\n global try_get_ipv4;\n if not try_get_ipv4:\n try_get_ipv4 = True;\n public_ipv4 = get_ipv4();\n \n if record['content']:\n if re.match(ipv4_regex, record['content'] + '.'):\n content = record['content'];\n else:\n log.warning('* The content of type \"A\" DNS record of \"{0}\" does not seem to be a valid IPv4 address, skipping the update for type \"A\" DNS record of \"{1}\"'.format(\n full_domain_name, full_domain_name));\n continue;\n elif public_ipv4:\n content = public_ipv4;\n else:\n log.warning('* Unable to set type \"A\" DNS record because no IPv4 address is available, skipping the update for type \"A\" DNS record of \"{0}\"'.format(\n full_domain_name));\n continue;\n elif type == 'AAAA':\n if not try_get_ipv6:\n try_get_ipv6 = True;\n public_ipv6 = get_ipv6();\n \n if record['content']:\n if re.match(ipv6_regex, record['content'] + ':'):\n content = record['content'];\n else:\n log.warning('* The content of type \"AAAA\" DNS record of \"{0}\" does not seem to be a valid IPv6 address, skipping the update for type \"AAAA\" DNS record of \"{1}\"'.format(\n full_domain_name, full_domain_name));\n continue;\n elif public_ipv6:\n content = public_ipv6;\n else:\n log.warning('* Unable to set type \"AAAA\" DNS record because no IPv6 address is available, skipping the update for type \"AAAA\" DNS record of \"{0}\"'.format(\n full_domain_name));\n continue;\n elif type == 'CNAME':\n if record['content']:\n content = record['content'];\n else:\n log.warning('* The content of type \"{0}\" DNS record is empty, but required, using the default content({1}) to update type \"{2}\" DNS record of \"{3}\"'.format(\n type, root_domain_name, type, full_domain_name));\n content = root_domain_name;\n \n if type not in types:\n types.append(type);\n else:\n log.warning('* Type \"{0}\" DNS record repeated, skipping the update for this DNS record'.format(\n type));\n continue;\n \n #pdb.set_trace();\n if ttl not in ttl_range:\n log.warning('* TTL is invalid and must be 1(Auto), 120 2 min), 300(5 min), 600(10 min), 900(15 min), 1800(30 min), 3600(1 hr), 7200(2 hr ), 18000(5 hr), 43200(12 hr), 86400(1 day), using default value(1(Auto))');\n ttl = 1;\n \n # update ip address/ttl if it has changed since last update\n if record['cloudflare']['content'] != content:\n log.info('* The {0} of DNS recorded as type \"{1}\" on Cloudflare is different from the local {2}'.format(\n 'content' if type == 'CNAME' else 'IP address', type, 'content' if type == 'CNAME' else 'IP address'));\n need_update = True;\n if record['cloudflare']['ttl'] != ttl:\n log.info('* The TTL of DNS recorded as type \"{0}\" on Cloudflare is different from the local TTL'.format(\n type));\n need_update = True;\n \n \n if not need_update:\n continue;\n # log.info('* The IP/TTL/content of DNS recorded as type \"{0}\" on Cloudflare is different from the local public IP/TTL/content, updating type \"{1}\" DNS record for \"{2}\"'.format(\n # type, type, full_domain_name));\n #else:\n # log.info('* The IP/TTL/content of DNS recorded as type \"{0}\" on Cloudflare is the same as the local public IP/TTL/content, skipping the update for type \"{1}\" DNS record of \"{2}\"'.format(\n # type, type, full_domain_name));\n # continue;\n \n \n if not verify_account:\n log.info('* verifying user account');\n try:\n user_detail_json = cloudflare_api.get_user_detail(content_header);\n if user_detail_json['success']:\n log.info('* Succeed to verify user account');\n verify_account = True;\n else:\n log.error('* Failed to verify user account, please check user account, the program exit');\n exit(0);\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while verifying user account, the program exit. Exception: {0}'.format(\n e));\n exit(0);\n \n #get domain information from Cloudflare\n if not get_zone:\n zone_json = get_zone_info(domain, root_domain_name, content_header);\n if not zone_json:\n next_zone = True;\n break;\n elif not isinstance(zone_json['result'], list):\n new_zone = True;\n get_zone = True;\n \n \n if not need_update:\n continue;\n \n #get DNS record information from Cloudflare\n log.info('* Getting type \"{0}\" DNS record of \"{1}\"'.format(\n type, full_domain_name));\n try:\n #pdb.set_trace();\n dns_record_json = cloudflare_api.get_dns_record(zone_json['result']['id'] if new_zone else zone_json['result'][0]['id'], type, full_domain_name, content_header);\n if dns_record_json['success']:\n log.info('* Succeed to get type \"{0}\" DNS record of \"{1}\"'.format(\n type, full_domain_name));\n else:\n log.warning('* Failed to get type \"{0}\" DNS record of \"{1}\", skipping the update for type \"{2}\" DNS record of \"{3}\"'.format(\n type, full_domain_name, type, full_domain_name));\n continue;\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while getting type \"{0}\" DNS record of \"{1}\", skipping the update for type \"{2}\" DNS record of \"{3}\". Exception: {4}'.format(\n type, full_domain_name, type, full_domain_name, e));\n continue;\n \n \n \n try:\n if dns_record_json['result_info']['total_count'] < 1:\n if host['create_if_the_record_not_exists']:\n log.info('* No type \"{0}\" DNS record of \"{1}\" found, configuration \"create_if_the_record_not_exists\" is \"True\", creating DNS record(type: {2}, name: {3}, content: {4}, ttl: {5}) automatically'.format(\n type, root_domain_name, type, full_domain_name, content, ttl));\n try:\n dns_record_create_json = cloudflare_api.create_dns_record(zone_json['result']['id'] if new_zone else zone_json['result'][0]['id'], type, full_domain_name, content, ttl, proxied, content_header);\n if dns_record_create_json['success']:\n update = True;\n #dns_record_json['result'][0]['id'] = dns_record_create_json['result']['id'];\n record['cloudflare']['content'] = content;\n record['cloudflare']['ttl'] = ttl;\n record['cloudflare']['proxied'] = proxied;\n log.info('* Succeed to create DNS record(id: {0}, type: {1}, name: {2}, content: {3}, ttl: {4}, proxied: {5})'.format(\n dns_record_create_json['result']['id'], type, full_domain_name, content, ttl, proxied));\n else:\n log.warning('* Failed to create DNS record(type: {0}, name: {1}, content: {2}, ttl: {3}, proxied: {4}). Errors:{5}, messages:{6}'.format(\n type, full_domain_name, content, ttl, proxied, dns_record_create_json['errors'], dns_record_create_json['messages']));\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while creating DNS record(type: {0}, name: {1}, content: {2}, ttl: {3}, proxied: {4}), skipping the update this DNS record. Exception:{5}'.format(\n type, full_domain_name, content, ttl, proxied, e));\n else:\n log.warning('* No type \"{0}\" DNS record \"{1}\" found, configuration \"create_if_the_record_not_exists\" is \"False\", skipping the update this DNS record. Please check configuration and cloudflare settings and try again'.format(\n type, root_domain_name));\n continue;\n elif dns_record_json['result_info']['total_count'] > 1:\n if host['delete_if_the_same_type_of_record_repeated']:\n log.info('* Type \"{0}\" DNS record of \"{1}\" is not unique, configuration \"delete_if_the_same_type_of_record_repeated\" is \"True\", using the first DNS record and deleting others'.format(\n type, root_domain_name));\n for index in range(dns_record_json['result_info']['total_count']):\n if index == 0:\n log.info('* Keep the first DNS record(id: {0}, type: {1}, name: {2}, content: {3}, ttl: {4}, proxied: {5})'.format(\n dns_record_json['result'][index]['id'], dns_record_json['result'][index]['type'], dns_record_json['result'][index]['name'], dns_record_json['result'][index]['content'], dns_record_json['result'][index]['ttl'], dns_record_json['result'][index]['proxied']));\n continue;\n else:\n log.info('* Deleting DNS record(id: {0}, type: {1}, name: {2}, content: {3}, ttl: {4}, proxied: {5})'.format(\n dns_record_json['result'][index]['id'], dns_record_json['result'][index]['type'], dns_record_json['result'][index]['name'], dns_record_json['result'][index]['content'], dns_record_json['result'][index]['ttl'], dns_record_json['result'][index]['proxied']));\n try:\n dns_record_delete_json = cloudflare_api.delete_dns_record(zone_json['result']['id'] if new_zone else zone_json['result'][0]['id'], dns_record_json['result'][index]['id'], content_header);\n if dns_record_delete_json['success']:\n log.info('* Succeed to delete type \"{0}\" DNS record(id: {1})'.format(\n type, dns_record_delete_json['result']['id']));\n else:\n log.warning('* Failed to delete type \"{0}\" DNS record(id: {1}). Errors:{2}, messages:{3}'.format(\n type, dns_record_json['result'][index]['id'], dns_record_delete_json['errors'], dns_record_delete_json['messages']));\n break;\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while deleting type \"{0}\" DNS record(id: {1}), gave up deleting type \"{2}\" DNS record(id: {3}) for \"{4}\". Exception:{5}'.format(\n type, dns_record_json['result'][index]['id'], type, dns_record_json['result'][index]['id'], full_domain_name, e));\n break;\n else:\n log.warning('* Type \"{0}\" DNS record \"{1}\" is not unique, configuration \"delete_if_the_same_type_of_record_repeated\" is \"False\", using the first DNS record'.format(\n type, root_domain_name));\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while handling DNS records, skipping the update for type \"{0}\" DNS record of \"{1}\". Exception: {2}'.format(\n type, full_domain_name, e));\n continue;\n \n log.info('* Updating type \"{0}\" DNS record for \"{1}\"'.format(\n type, full_domain_name));\n try:\n #pdb.set_trace();\n if not record['cloudflare']['content'] and content == dns_record_json['result'][0]['content'] and ttl == dns_record_json['result'][0]['ttl'] and proxied == dns_record_json['result'][0]['proxied']:\n update = True;\n record['cloudflare']['content'] = content;\n record['cloudflare']['ttl'] = ttl;\n record['cloudflare']['proxied'] = proxied;\n log.info('* Succeed to update DNS record(id: {0}, type: {1}, name: {2}, content: {3}, ttl: {4}, proxied: {5})'.format(\n dns_record_json['result'][0]['id'], type, full_domain_name, content, ttl, proxied));\n continue;\n update_res_json = cloudflare_api.update_dns_record(zone_json['result']['id'] if new_zone else zone_json['result'][0]['id'], dns_record_json['result'][0]['id'], type, full_domain_name, content, ttl, proxied, content_header);\n if update_res_json['success']:\n update = True;\n record['cloudflare']['content'] = content;\n record['cloudflare']['ttl'] = ttl;\n record['cloudflare']['proxied'] = proxied;\n log.info('* Succeed to update DNS record(id: {0}, type: {1}, name: {2}, content: {3}, ttl: {4}, proxied: {5})'.format(\n update_res_json['result']['id'], type, full_domain_name, content, ttl, proxied));\n else:\n log.warning('* Failed to update type \"{0}\" DNS record(id: {1}, type: {2}, name: {3}). Errors: {4}, messages: {5}'.format(\n type, dns_record_json['result'][0]['id'], type, full_domain_name, update_res_json['errosr'], update_res_json['messages']));\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while updating DNS record(id: {0}, type: {1}, name: {2}). Exception: {3}'.format(\n dns_record_json['result'][0]['id'], type, full_domain_name, e));\n \n \n if next_zone:\n continue;\n \n \n if host['delete_the_other_unused_type_of_record']:\n log.info('* Configuration \"delete_the_other_unused_type_of_record\" is \"True\", deleting other unused type DNS record for \"{0}\" if exists'.format(\n full_domain_name));\n \n if not get_zone:\n zone_json = get_zone_info(domain, root_domain_name, content_header);\n if not zone_json:\n continue;\n elif not isinstance(zone_json['result'], list):\n new_zone = True;\n get_zone = True;\n \n #pdb.set_trace();\n delete_type = copy.deepcopy(type_support);\n for type in types:\n try:\n del delete_type[delete_type.index(type)];\n except Exception:\n pass;\n if len(delete_type) > 0:\n for type in delete_type:\n try:\n type_record_json = cloudflare_api.get_dns_record(zone_json['result']['id'] if new_zone else zone_json['result'][0]['id'], type, full_domain_name, content_header);\n if type_record_json['success']:\n for delete_record_json in type_record_json['result']:\n log.info('* Deleting type \"{0}\" DNS record(id: {1})'.format(\n type, delete_record_json['id']));\n try:\n type_record_delete_json = cloudflare_api.delete_dns_record(zone_json['result']['id'] if new_zone else zone_json['result'][0]['id'], delete_record_json['id'], content_header);\n if type_record_delete_json['success']:\n log.info('* Succeed to delete type \"{0}\" DNS record(id: {1})'.format(\n type, delete_record_json['id']));\n else:\n log.warning('* Failed to delete type \"{0}\" DNS record(id: {1}). Errors: {2}, messages: {3}'.format(\n type, delete_record_json['id'], type_record_delete_json['errors'], type_record_delete_json['messages']));\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while deleting type \"{0}\" DNS record(id: {1}), gave up deleting this DNS record. Exception: {2}'.format(\n type, delete_record_json['id'], e));\n else:\n log.warning('* Failed to get type \"{0}\" DNS records for \"{1}\", gave up deleting DNS records'.format(\n type, full_domain_name));\n except (Exception, HTTPError) as e:\n log.error('* An exception occurred while deleting type \"{0}\" DNS records, gave up deleting type \"{1}\" DNS records. Exception: {2}'.format(\n type, type, e));\n \n host['delete_the_other_unused_type_of_record'] = False;\n update = True;\n \n \n \n # if any DNS records were updated, update the config file accordingly\n if update:\n try:\n with open(__config_file_location__, 'w') as config_file:\n json.dump(config, config_file, indent = 1, sort_keys = True);\n except Exception as e:\n log.error('* An exception occurred while writing the configuration to the file \"{0}\". Exception: {1}'.format(\n __config_file_location__, e));\n log.info('* Updates completed. Bye.');\n else:\n log.info('* Nothing to update. Bye.');\n \n public_ipv4 = None;\n try_get_ipv4 = False;\n public_ipv6 = None;\n try_get_ipv6 = False;\n update = False;\n\nif __name__ == '__main__':\n try:\n while True:\n run();\n #pdb.set_trace();\n if config['check_interval']:\n time.sleep(config['check_interval']);\n else:\n break;\n except Exception as e:\n log.error('* An exception occurred while running, the program exit. Exception: {0}'.format(\n e));\n exit(0);\n","sub_path":"cloudflare_ddns.py","file_name":"cloudflare_ddns.py","file_ext":"py","file_size_in_byte":28597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"336650356","text":"import numpy as np\nimport scipy.io, math, sys, time\nfrom matplotlib import pyplot\n\nfrom utils import Utils\nfrom statistics import Statistics\nfrom features import Features\nfrom reader import Reader\nfrom plots import Plots\n\n\n\nclass LogisticRegression:\n\t\"\"\"\n\tSimple Logistic Regression with OneVsAll methods\n\t\"\"\"\n\n\tdef __init__(self, nb_input, nb_output, nb_features):\n\t\t\"\"\"\n\t\t:param nb_input: number of input samples\n\t\t:param nb_output: number of classes\n\t\t:param nb_features: number of features\n\t\t\"\"\"\n\n\t\tself.nb_input = nb_input\n\t\tself.nb_output = nb_output\n\t\tself.nb_features = nb_features\n\n\t\t# Weights:\n\t\tself.weights = np.zeros((nb_features, 1))\n\t\tself.all_weights = np.zeros((nb_output, nb_features))\n\n\t\t# Gradients:\n\t\tself.gradients = np.zeros((nb_features, 1))\n\n\n\n\tdef initialize_weights(self):\n\t\tepsilon = Utils.get_epsilon(self.nb_features, 1)\n\t\tself.weights = np.random.randn(self.nb_features, 1) * 2 * epsilon - epsilon\n\n\n\tdef set_weights(self, w):\n\t\tself.weights = w\n\n\n\tdef get_weights(self):\n\t\treturn self.weights\n\n\n\tdef predict_classes(self, X):\n\t\treturn np.argmax(X.dot(self.all_weights.T), axis=1)\n\n\t\n\tdef predict_binary(self, X):\n\t\treturn Utils.sigmoid(X.dot(self.weights)) >= Utils.sigmoid(0)\n\n\n\tdef predict(self, X):\n\t\tif self.nb_output > 2:\n\t\t\treturn self.predict_classes(X_norm)\n\t\telse:\n\t\t\treturn self.predict_binary(X_norm)\n\n\n\tdef cost(self, X, Y, lbda):\n\n\n\t\tm, n = X.shape\n\t\t\n\t\tZ = Utils.sigmoid(X.dot(self.weights))\n\t\t\n\t\tA = np.log(Z).T.dot(Y)\n\t\tB = np.log(1 - Z).T.dot(1 - Y)\n\t\tJ = -(A+B)/m\n\n\n\t\t# regularization (not for bias):\n\t\tJ += (lbda * np.sum(np.power(self.weights[1:], 2)))/(2.0*m)\n\n\t\t\n\t\t# get gradients\n\t\tgrad = np.zeros(self.weights.shape)\n\t\tgrad[0] = X[:,0].T.dot(Z - Y)/m\n\t\tgrad[1:] = (X[:, 1:].T.dot(Z - Y)/m) + (lbda*self.weights[1:])/m\n\n\t\treturn np.sum(J), grad\n\n\n\tdef update_weights(self, grad, alpha):\n\t\tself.weights = self.weights - alpha*grad\n\n\n\n\t\n\tdef train_binary(self, X, Y, alpha, lbda, precision, nb_iters, verbose=True):\n\n\t\tdef reached_precision(cost, precision):\n\t\t\tif len(cost) < 2:\n\t\t\t\treturn True\n\t\t\treturn abs(cost[-1] - cost[-2]) > precision\n\n\t\tcost_history = []\n\t\ti = 0\n\n\n\n\t\twhile i < nb_iters and reached_precision(cost_history, precision):\n\t\t\tJ, G = self.cost(X, Y, lbda)\n\t\t\tself.update_weights(G, alpha)\n\t\t\tcost_history.append(J)\n\n\t\t\tif verbose:\n\t\t\t\tsys.stdout.write(\"Iteration %4d - Cost %.4f \\r\" % (i+1, J))\n\t\t\t\tsys.stdout.flush()\n\n\t\t\ti += 1\n\n\t\tif verbose:\n\t\t\tprint(\"\\n\"+\"-\"*30)\n\t\treturn cost_history\n\n\n\tdef train_classes(self, X, Y, alpha, lbda, precision, nb_iters, verbose=True):\n\n\t\tm, n = X.shape\n\t\tcost_history = []\n\n\t\tfor k in range(self.nb_output):\n\n\t\t\tself.initialize_weights()\n\t\t\tJ = self.train_binary(X, Y == k, alpha, lbda, precision, nb_iters, verbose)\n\n\t\t\tself.all_weights[k] = self.weights[:,0]\n\t\t\tcost_history.append(J)\n\t\t\t\n\n\t\treturn cost_history\n\n\n\tdef train(self, X, Y, alpha=0.3, lbda=0.5, precision=1e-6, nb_iters=10000, verbose=True):\n\t\tif self.nb_output > 2:\n\t\t\treturn self.train_classes(X, Y, alpha, lbda, precision, nb_iters, verbose)\n\t\telse:\n\t\t\treturn self.train_binary(X, Y, alpha, lbda, precision, nb_iters, verbose)\n\n\n\nif __name__ == '__main__':\n\n\n\t# X, Y = Reader.read_data('dados/xor.txt', ignore_line_number=False)\n\n\t# data = {'X':X, 'Y':Y}\n\t# Reader.save_mat('dados/xor.mat', data)\n\n\tmat = Reader.load_mat('dados/xor.mat')\n\tX_orig, Y = np.matrix(mat['X']), mat['Y']\n\n\t# X, mu, sigma = Features.normalize(X)\n\tPlots.scatterplot(X_orig, Y)\n\tpyplot.show()\n\n\tmax_degree = 60\n\titers, times, accs, alphas = [], [], [], []\n\n\n\tresult_times = open(\"reg_result_times.txt\", \"w\")\n\tresult_times.write(\"alpha tempo\\n\")\n\n\tresult_iters = open(\"reg_result_iters.txt\", \"w\")\n\tresult_iters.write(\"alpha iters\\n\")\n\n\tresult_accs = open(\"reg_result_accs.txt\", \"w\")\n\tresult_accs.write(\"alpha acc\\n\")\n\n\tresult_alphas = open(\"reg_result_alphas.txt\", \"w\")\n\tresult_alphas.write(\"alpha custo\\n\")\n\n\tlalphas = [0.01, 0.03, 0.1, 0.3, 1.0, 3.0, 6.0, 12.0, 24.0, 48.0]\n\n\tfor nb_degree in range(1, max_degree+1):\n\t\tfor k, alpha in enumerate(lalphas):\n\n\t\t\tX = Utils.add_column_with_ones(Features.map(X_orig, degree=nb_degree))\n\n\t\t\tvalidation_split = 0.2\n\t\t\tuse_shuffle = False\n\t\t\tuse_validation = False\n\n\t\t\tnb_input = X.shape[0]\n\t\t\tnb_features = X.shape[1]\n\t\t\tnb_labels = len(set(np.squeeze(np.asarray(Y))))\n\n\t\t\tnb_iters = 50000\n\t\t\tnb_epochs = 1\n\n\t\t\t# alpha\t = 3.0\n\t\t\tlbda\t = 0.0\n\t\t\tmomentum = 0.9\n\t\t\tprecision = 1e-6\n\n\t\t\ttimer \t = time.clock if (sys.platform == 'win32') else time.time\n\n\n\n\t\t\tlg = LogisticRegression(nb_input, nb_labels, nb_features)\n\n\t\t\ta,b,c,d = [],[],[],[]\n\t\t\tfor i in range(nb_epochs):\n\t\t\t\t\n\n\t\t\t\t# print('Epoch %d' % (i+1))\n\t\t\t\t# print(\"-\"*30)\n\n\t\t\t\tsys.stdout.write(\"Degree %2d - Alpha %2.2lf - Epoch %2d \\r\" % (nb_degree, alpha, i+1))\n\t\t\t\tsys.stdout.flush()\n\n\t\t\t\tstart_time = timer()\n\t\t\t\tlg.initialize_weights()\n\t\t\t\tj_history = lg.train(X, Y, alpha, lbda, precision, nb_iters, verbose=False)\t\n\t\t\t\ttotal_time = timer() - start_time\n\t\t\t\t\n\t\t\t\ta.append(len(j_history))\n\t\t\t\tb.append(total_time)\n\t\t\t\tc.append(Statistics.accuracy(lg.predict_binary(X), Y))\n\t\t\t\td = j_history\n\n\t\t\t\t# print('Iterations:\\t %d' % a[-1])\n\t\t\t\t# print('Time:\\t\\t %.2f seconds' % b[-1])\n\t\t\t\t# print('Accuracy:\\t %.2f' % c[-1])\n\n\t\t\t\t# f1, precision, recall, acc = Statistics.f_score(lg.predict_binary(X), Y)\n\t\t\t\t# print('F1:\\t %.2f' % f1)\n\t\t\t\t# print('Prec:\\t %.2f' % precision)\n\t\t\t\t# print('Rec:\\t %.2f' % recall)\n\t\t\t\t# print('Acc:\\t %.2f' % acc)\n\n\t\t\t\t# print('\\n')\n\n\t\t\t\t# if nb_degree == 2:\n\t\t\t\t# \tcolors = \"gbrcmyk\"*2\n\t\t\t\t# \tPlots.lineplot(list(range(len(d))), d, color=colors[k], label='Alpha {}'.format(alpha))\n\t\t\t\t# Plots.draw_boundary(X[:, 1:], lg.get_weights(), degree=nb_degree)\n\n\t\t\tma, da = np.mean(np.array(a)), np.std(np.array(a))\n\t\t\tmb, db = np.mean(np.array(b)), np.std(np.array(b))\n\t\t\tmc, dc = np.mean(np.array(c)), np.std(np.array(c))\n\t\t\tmd, dd = np.mean(np.array(d)), np.std(np.array(d))\n\n\t\t\titers.append(ma)\n\t\t\ttimes.append(mb)\n\t\t\taccs.append(mc)\n\t\t\talphas.append(md)\n\n\t\t\tresult_iters.write(\"%.2f %.4f\\n\" % (alpha, ma))\n\t\t\tresult_times.write(\"%.2f %.4f\\n\" % (alpha, mb))\n\t\t\tresult_accs.write(\"%.2f %.4f\\n\" % (alpha, mc))\n\t\t\tresult_alphas.write(\"%.2f %.4f\\n\" % (alpha, md))\n\n\n\n\t\t\tprint('Degree %d - %d' % (nb_degree, nb_features))\n\t\t\tprint(\"-\"*30)\n\t\t\tprint('Iterations:\\t media:%.2lf \\t desvio:%.2f' % (ma, da))\n\t\t\tprint('Time:\\t\\t media:%.2lf \\t desvio:%.2f seconds' % (mb, db))\n\t\t\tprint('Accuracy:\\t media:%.2lf \\t desvio:%.2f' % (mc, dc))\n\t\t\tprint('\\n')\n\n\n\tpyplot.legend(loc='upper right', numpoints=1, shadow=True, fancybox=True)\n\tpyplot.show()\n\n\tpyplot.xlabel('Taxa de aprendizagem')\n\tpyplot.ylabel('J(W)')\n\tPlots.lineplot(lalphas, alphas, color='g', label='Custo')\n\tpyplot.legend(loc='upper right', numpoints=1, shadow=True, fancybox=True)\n\tpyplot.show()\n\n\tPlots.lineplot(lalphas, times, color='g', label='Times')\n\tpyplot.legend(loc='upper right', numpoints=1, shadow=True, fancybox=True)\n\tpyplot.show()\n\n\tPlots.lineplot(lalphas, iters, color='b', label='Iterations')\n\tpyplot.legend(loc='upper right', numpoints=1, shadow=True, fancybox=True)\n\tpyplot.show()\n\t\n\n","sub_path":"Machine Learning/Trabalho1/reglog.py","file_name":"reglog.py","file_ext":"py","file_size_in_byte":7034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"87043544","text":"#!/usr/bin/env python\n# coding=utf-8\n'''\nAuthor: Wei Luo\nDate: 2020-08-21 18:02:38\nLastEditors: Wei Luo\nLastEditTime: 2020-08-31 13:53:51\nNote: Note\n'''\nfrom .traj_gen_base import TrajGen\nimport numpy as np\nfrom scipy.linalg import block_diag, solve\nimport mosek as mk\nimport mosek.fusion as mkfs\nfrom qpsolvers import solve_qp\nimport sys\nimport casadi as ca\nimport time\n\n\nclass PolyTrajGen(TrajGen):\n def __init__(self, knots_, order_, algo_, dim_, maxContiOrder_):\n \"\"\" Initialize the class of the trajectory generator\"\"\"\n super().__init__(knots_, dim_)\n self.N = order_ # polynomial order\n self.algorithm = algo_\n\n self.M = knots_.shape[0] - 1 # segments which is knots - 1\n self.maxContiOrder = maxContiOrder_\n self.num_variables = (self.N+1) * self.M\n self.inf = np.inf\n self.segState = np.zeros((self.M, 2)) # 0 dim -> how many fixed pins in this segment,\n # muss smaller than the polynomial order+1\n # more fixed pins (higher order) will be ignored.\n # 1 dim -> continuity degree. should be defined by\n # user (maxContiOrder_+1)\n self.polyCoeffSet = np.zeros((self.dim, self.N+1, self.M))\n\n ## math functions\n def scaleMat(self, delT):\n mat_ = np.diag([delT**i for i in range(self.N+1)])\n return mat_\n\n def scaleMatBigInv(self,):\n mat_ = None\n for m in range(self.M):\n matSet_ = self.scaleMat(1/(self.Ts[m+1]-self.Ts[m]))\n if mat_ is None:\n mat_ = matSet_.copy()\n else:\n mat_ = block_diag(mat_, matSet_)\n return mat_\n\n ## functional definition\n def setDerivativeObj(self, weights):\n if weights.shape[0] > self.N:\n print(\"Order of derivative objective > order of poly. Higher terms will be ignored.\")\n self.weight_mask = weights[:self.N]\n else:\n self.weight_mask = weights\n\n def addPin(self, pin_):\n t_ = pin_['t']\n X_ = pin_['X']\n super().addPin(pin_)\n m, _ = self.findSegInteval(t_)\n if len(X_.shape) == 2: # 2 dimension ==> loose pin\n if m in self.loosePinSet.keys():\n self.loosePinSet[m].append(pin_)\n else:\n self.loosePinSet[m] = [pin_]\n elif len(X_.shape) == 1: # vector ==> fix pin\n assert (t_==self.Ts[m] or t_==self.Ts[-1]), 'Fix pin should be imposed only knots'\n if self.segState[m, 0] <= self.N+1:\n if m in self.fixPinSet.keys():\n self.fixPinSet[m].append(pin_)\n self.fixPinOrder[m].append(pin_['d'])\n else:\n self.fixPinSet[m] = [pin_]\n self.fixPinOrder[m] = [pin_['d']]\n self.segState[m, 0] += 1\n\n else:\n print('FixPin exceed the dof of this segment. Pin ignored')\n else:\n print('Dim of pin value is invalid')\n\n\n def nthCeoff(self, n, d):\n \"\"\" Returns the nth order ceoffs (n=0...N) of time vector of d-th\n derivative.\n\n Args:\n n(int): target order\n d(int): order derivative\n\n Returns:\n val_: n-th ceoffs\n \"\"\"\n if d == 0:\n val_ = 1\n else:\n accumProd_ = np.cumprod(np.arange(n, n-d, -1))\n val_ = accumProd_[-1]*(n>=d)\n return val_\n\n def IntDerSquard(self, d):\n \"\"\"\n {x^(d)(t)}^2 = (tVec(t,d)'*Dp)'*(tVec(t,d)'*Dp)\n\n Args:\n d(int): order derivative\n\n Returns:\n mat_: matrix of the cost function\n \"\"\"\n mat_ = np.zeros((self.N+1, self.N+1))\n if d > self.N:\n print(\"Order of derivative > poly order, return zeros-matrix \\n\")\n for i in range(d, self.N+1):\n for j in range(d, self.N+1):\n # if i+j-2*d+1 > 0:\n mat_[i,j] = self.nthCeoff(i, d) * self.nthCeoff(j, d) / (i+j-2*d+1)\n return mat_\n\n def findSegInteval(self, t_):\n idx_ = np.where(self.Ts<=t_)[0]\n if idx_.shape[0]>0:\n m_ = np.max(idx_)\n if m_ >= self.M:\n if t_ != self.Ts[-1]:\n print('Eval of t : geq TM. eval target = last segment')\n m_ = self.M-1\n else:\n print('Eval of t : leq T0. eval target = 1st segment')\n m_ = 0\n tau_ = (t_-self.Ts[m_])/(self.Ts[m_+1]-self.Ts[m_])\n return m_, tau_\n\n def tVec(self, t_, d_):\n # time vector evaluated at time t with d-th order derivative.\n vec_ = np.zeros((self.N+1, 1))\n for i in range(d_, self.N+1):\n vec_[i] = self.nthCeoff(i, d_)*t_**(i-d_)\n return vec_\n\n def fixPinMatSet(self, pin):\n t_ = pin['t']\n X_ = pin['X']\n d_ = pin['d']\n m_, tau_ = self.findSegInteval(t_)\n idxStart_ = m_*(self.N+1)\n idxEnd_ = (m_+1)*(self.N+1)\n dTm_ = self.Ts[m_+1] - self.Ts[m_]\n aeqSet_ = np.zeros((self.dim, self.num_variables))\n beqSet_ = np.zeros((self.dim, 1))\n for dd in range(self.dim):\n aeqSet_[dd, idxStart_:idxEnd_] = self.tVec(tau_, d_).flatten()/dTm_**d_#\n beqSet_[dd] = X_[dd]\n return aeqSet_, beqSet_\n\n def contiMat(self, m_, dmax):\n \"\"\"\n ensure in dmax derivative degree the curve should be continued.\n from 0 to dmax derivative\n Args:\n m_: index of the segment <= M-1\n dmax: max conti-degree\n \"\"\"\n dmax_ = int(dmax)\n aeq_ = np.zeros((dmax_+1, self.num_variables))\n beq_ = np.zeros((dmax_+1, 1)) # different of the eq should be zero\n idxStart_ = m_*(self.N+1)\n idxEnd_ = (m_+2)*(self.N+1) # end of the next segment\n dTm1_ = self.Ts[m_+1] - self.Ts[m_]\n dTm2_ = self.Ts[m_+2] - self.Ts[m_+1]\n for d in range(dmax_+1):\n # the end of the first segment should be the same as the begin of the next segment at each derivative\n aeq_[d, idxStart_:idxEnd_] = np.concatenate((self.tVec(1, d)/dTm1_**d, - self.tVec(0, d)/dTm2_**d), axis=0).flatten() #\n\n return aeq_, beq_\n\n def loosePinMatSet(self, pin_):\n aSet_ = np.zeros((self.dim, 2, self.num_variables))\n bSet_ = np.zeros((self.dim, 2, 1))\n t_ = pin_['t']\n X_ = pin_['X']\n d_ = pin_['d']\n m_, tau_ = self.findSegInteval(t_)\n dTm_ = self.Ts[m_+1] - self.Ts[m_]\n idxStart_ = m_*(self.N+1)\n idxEnd_ = (m_+1)*(self.N+1)\n for dd in range(self.dim):\n aSet_[dd, :, idxStart_:idxEnd_] = np.array([self.tVec(tau_, d_)/dTm_**d_,-self.tVec(tau_, d_)/dTm_**d_]).reshape(2, -1) #\n bSet_[dd, :] = np.array([X_[dd, 1], -X_[dd, 0]]).reshape(2, -1)\n return aSet_, bSet_\n\n\n def getQPset(self,):\n # objective\n QSet = np.zeros((self.dim, self.num_variables, self.num_variables))\n for dd in range(self.dim):\n Q_ = np.zeros((self.num_variables, self.num_variables))\n\n for d in range(1, self.weight_mask.shape[0]+1):\n if self.weight_mask[d-1] > 0:\n Qd_ = None\n for m in range(self.M):\n dT_ = self.Ts[m+1] - self.Ts[m]\n Q_m_ = self.IntDerSquard(d)/dT_**(2*d-1)\n if Qd_ is None:\n Qd_ = Q_m_.copy()\n else:\n Qd_ = block_diag(Qd_, Q_m_)\n Q_ = Q_ + self.weight_mask[d-1]*Qd_\n QSet[dd] = Q_\n\n # constraint\n AeqSet = None\n ASet = None\n BSet = None\n BeqSet = None\n\n for m in range(self.M): # segments\n ## fix pin\n if m in self.fixPinSet.keys():\n for pin in self.fixPinSet[m]:\n aeqSet, beqSet = self.fixPinMatSet(pin)\n if AeqSet is None:\n AeqSet = aeqSet.reshape(self.dim, -1, self.num_variables)\n BeqSet = beqSet.reshape(self.dim, -1, 1)\n else:\n AeqSet = np.concatenate((AeqSet, aeqSet.reshape(self.dim, -1, self.num_variables)), axis=1)\n BeqSet = np.concatenate((BeqSet, beqSet.reshape(self.dim, -1, 1)), axis=1)\n\n ## continuity\n if m < self.M-1:\n contiDof_ = min(self.maxContiOrder+1, self.N+1-self.segState[m, 0])\n self.segState[m, 1] = contiDof_\n if contiDof_ != self.maxContiOrder+1:\n print('Connecting segment ({0},{1}) : lacks {2} dof for imposed {3} th continuity'.format(m, m+1, self.maxContiOrder-contiDof_, self.maxContiOrder))\n if contiDof_ >0:\n aeq, beq = self.contiMat(m, contiDof_-1)\n AeqSet = np.concatenate((AeqSet, aeq.reshape(1, -1, self.num_variables).repeat(self.dim, axis=0)), axis=1)\n BeqSet = np.concatenate((BeqSet, beq.reshape(1, -1, 1).repeat(self.dim, axis=0)), axis=1)\n else:\n pass # not pin in this interval\n\n ## loose pin\n if m in self.loosePinSet.keys():\n for pin in self.loosePinSet[m]:\n aSet, bSet = self.loosePinMatSet(pin)\n if ASet is None:\n ASet = aSet\n BSet = bSet\n else:\n ASet = np.concatenate((ASet, aSet), axis=1)\n BSet = np.concatenate((BSet, bSet), axis=1)\n\n\n return QSet, ASet, BSet, AeqSet, BeqSet\n\n def coeff2endDerivatives(self, Aeq_):\n assert Aeq_.shape[1] <= self.num_variables, 'Pin + continuity constraints are already full. No dof for optim.'\n mapMat_ = Aeq_.copy()\n for m in range(self.M):\n freePinOrder_ = np.setdiff1d(np.arange(self.N+1), self.fixPinOrder[m]) # free derivative (not defined by fixed pin)\n dof_ = self.N+1 - np.sum(self.segState[m])\n freeOrder = freePinOrder_[:int(dof_)]\n for order in freeOrder:\n virtualPin_ = {'t':self.Ts[m], 'X':np.zeros((self.dim, 1)), 'd':order}\n # print('virtual Pin {}'.format(virtualPin_))\n aeqSet_, _ = self.fixPinMatSet(virtualPin_)\n aeq_ = aeqSet_[0] # only one dim is taken.\n mapMat_ = np.concatenate((mapMat_, aeq_.reshape(-1, self.num_variables)), axis=0)\n return mapMat_\n\n def mapQP(self, QSet_, ASet_, BSet_, AeqSet_, BeqSet_):\n Afp_ = self.coeff2endDerivatives(AeqSet_[0]) # sicne all Aeq in each dim are the same\n AfpInv_ = np.linalg.inv(Afp_)\n Nf_ = int(AeqSet_[0].shape[0])\n Qtemp_ = np.dot(np.dot(AfpInv_.T, QSet_[0]), AfpInv_)\n # Qff_ = Qtemp_[:Nf_, :Nf_]\n Qfp_ = Qtemp_[:Nf_, Nf_:]\n Qpf_ = Qtemp_[Nf_:, :Nf_]\n Qpp_ = Qtemp_[Nf_:, Nf_:]\n QSet = np.zeros((self.dim, self.num_variables-Nf_, self.num_variables-Nf_))\n HSet = np.zeros((self.dim, self.num_variables-Nf_))\n # check ASet ?\n if ASet_ is not None:\n ASet = np.zeros((self.dim, ASet_.shape[1], self.num_variables-Nf_))\n BSet = BSet_.copy()\n dp_ = None\n for dd in range(self.dim):\n df_ = BeqSet_[dd]\n QSet[dd] = 2*Qpp_\n HSet[dd] = np.dot(df_.T, (Qfp_+Qpf_.T))\n A_ = np.dot(ASet_[dd], AfpInv_)\n ASet[dd] = A_[:, Nf_:]\n BSet[dd] = BSet_[dd] - np.dot(A_[:, :Nf_], df_)\n else:\n ASet = None\n BSet = None\n # directly solving the problem without making an optimization problem\n dp_ = np.zeros((self.dim, self.num_variables-Nf_))\n for dd in range(self.dim):\n df_ = BeqSet_[dd]\n dp_[dd] = np.dot(np.dot(-np.linalg.inv(Qpp_), Qfp_.T), df_).flatten()\n\n return QSet, HSet, ASet, BSet, dp_\n\n def qp_mk_solver(self, P, q=None, G=None, h=None, A=None, b=None, lb=None, ub=None):\n '''\n description:\n using MOSEK to solve a qp problem\n param {type}\n return {type}\n '''\n num_x = P.shape[0]\n num_c = 0\n\n bound_key_cons = []\n bound_low_cons = []\n bound_up_cons = []\n\n A_sum = None\n xx = None\n # print('solving using mosek')\n\n ## only for print optimizer states\n # def streamprinter(text):\n # sys.stdout.write(text + '\\n')\n # sys.stdout.flush()\n # prepare data\n num_x = P.shape[0]\n if lb is None and ub is None:\n bound_low_x = [-self.inf]*num_x\n bound_up_x = [self.inf]*num_x\n bound_key_x = [mk.boundkey.fr]*num_x\n elif lb is None and ub is not None:\n bound_key_x = [mk.boundkey.up]*num_x\n elif lb is not None and ub is None:\n bound_key_x = [mk.boundkey.lo]*num_x\n else:\n bound_key_x = [mk.boundkey.ra]*num_x\n if G is not None:\n num_c += G.shape[0]\n bound_key_cons = bound_key_cons + [mk.boundkey.up]*G.shape[0]\n bound_low_cons = bound_low_cons + [-np.inf]*G.shape[0]\n bound_up_cons = bound_up_cons + h.flatten().tolist()\n if A_sum is None:\n A_sum = G\n else:\n A_sum = np.concatenate((A_sum, G))\n if A is not None:\n num_c += A.shape[0]\n bound_key_cons = bound_key_cons + [mk.boundkey.fx]*A.shape[0]\n bound_low_cons = bound_low_cons + b.flatten().tolist()\n bound_up_cons = bound_up_cons + b.flatten().tolist()\n if A_sum is None:\n A_sum = A\n else:\n A_sum = np.concatenate((A_sum, A))\n\n with mk.Env() as env:\n with env.Task(0, 0) as task:\n # task.set_Stream(mk.streamtype.log, streamprinter) # for print solver information\n task.appendvars(num_x)\n for i in range(num_x):\n task.putvarbound(i, bound_key_x[i], bound_low_x[i], bound_up_x[i])\n if q is not None:\n for i in range(num_x):\n task.putcj(i, q[i]) # add q vector\n for i in range(num_x):\n for j in range(num_x):\n if j <= i: # only the lower triangle matrix needs to be defined\n task.putqobjij(i, j, P[i, j])\n\n task.appendcons(num_c)\n for i in range(num_c):\n task.putconbound(i, bound_key_cons[i], bound_low_cons[i], bound_up_cons[i])\n for i in range(num_c):\n for j in range(num_x):\n task.putaij(i, j, A_sum[i, j])\n # task.putaij(i, j, A[i, j])\n task.putobjsense(mk.objsense.minimize)\n task.optimize()\n # task.solutionsummary(mk.streamtype.msg)\n prosta = task.getprosta(mk.soltype.itr)\n solsta = task.getsolsta(mk.soltype.itr)\n xx = [0.]*num_x\n task.getxx(mk.soltype.itr, xx)\n if solsta == mk.solsta.optimal:\n print(\"Optimal solution found.\")\n elif solsta == mk.solsta.dual_infeas_cer:\n print(\"Primal or dual infeasibility.\\n\")\n elif solsta == mk.solsta.prim_infeas_cer:\n print(\"Primal or dual infeasibility.\\n\")\n elif mk.solsta.unknown:\n print(\"Unknown solution status\")\n else:\n print(\"Other solution status\")\n\n return xx\n\n def qp_mk_fusion_solver(self, P, q=None, G=None, h=None, A=None, b=None, lb=None, ub=None):\n '''\n description:\n param {type}\n return {type}\n '''\n num_x = P.shape[0]\n num_c_eq = 0\n xx = None\n print('solving using mosek fusion')\n\n ## only for print optimizer states\n # def streamprinter(text):\n # sys.stdout.write(text + '\\n')\n # sys.stdout.flush()\n # prepare data\n if G is not None:\n num_c_ieq = G.shape[0]\n\n if A is not None:\n num_c_eq = A.shape[0]\n\n with mkfs.Model('test') as M:\n x = M.variable('x', num_x, mkfs.Domain.unbounded())\n t_0 = M.variable('t0', 1, mkfs.Domain.unbounded())\n # F_chol, d, _ = ldl(P, lower=True)\n try:\n F_chol = np.linalg.cholesky(P)\n except:\n F_chol =np.linalg.cholesky(P+np.diag(np.ones(P.shape[0]))*1e-7)\n # result of the cholesky decomposition\n F_ = M.parameter('F', [num_x, num_x])\n # set up value of the mksf parameter\n F_.setValue(F_chol.T)\n quad_cost = mkfs.Expr.vstack(t_0, mkfs.Expr.mul(F_, x))\n M.constraint(\"lc\", quad_cost, mkfs.Domain.inQCone())\n\n if A is not None:\n A_ = M.parameter('A', [num_c_eq, num_x])\n b_ = M.parameter('b', num_c_eq)\n A_.setValue(A)\n b_.setValue(b.flatten())\n M.constraint(mkfs.Expr.sub(mkfs.Expr.mul(A_, x), b_), mkfs.Domain.equalsTo(0.0))\n if G is not None:\n A_ieq_ = M.parameter('A_ieq', [num_c_ieq, num_x])\n b_ieq_ = M.parameter('b_ieq', num_c_ieq)\n A_ieq_.setValue(G)\n b_ieq_.setValue(h.flatten())\n M.constraint(mkfs.Expr.sub(mkfs.Expr.mul(A_ieq_, x), b_ieq_), mkfs.Domain.lessThan(0.0))\n\n M.objective('obj', mkfs.ObjectiveSense.Minimize, t_0)\n t1 = time.time()\n M.solve()\n sol_x = x.level()\n return sol_x\n\n def solve(self,):\n self.isSolved = True\n # prepare QP\n QSet, ASet, BSet, AeqSet, BeqSet = self.getQPset()\n\n if self.algorithm == 'end-derivative':# and ASet is not None:\n mapMat = self.coeff2endDerivatives(AeqSet[0])\n QSet, HSet, ASet, BSet, dp_e = self.mapQP(QSet, ASet, BSet, AeqSet, BeqSet)\n elif self.algorithm == 'poly-coeff': # or ASet is None:\n pass\n\n for dd in range(self.dim):\n print('soving {}th dimension ...'.format(dd))\n if self.algorithm == 'poly-coeff': # or ASet is None:\n try:\n if ASet is not None:\n t1 = time.time()\n result = solve_qp(P=QSet[dd], q=np.zeros((QSet[dd].shape[0])), G=ASet[dd],\n h=BSet[dd], A=AeqSet[dd], b=BeqSet[dd], solver='cvxopt')\n print(\"solve qp time {}\".format(time.time() - t1))\n t2 = time.time()\n result = self.qp_mk_solver(P=QSet[dd], G=ASet[dd], h=BSet[dd], A=AeqSet[dd], b=BeqSet[dd])\n print(\"mosek using api {0}\".format(time.time() - t2))\n t3 = time.time()\n result = self.qp_mk_fusion_solver(P=QSet[dd], G=ASet[dd], h=BSet[dd], A=AeqSet[dd], b=BeqSet[dd])\n print(\"mosek using fusion {0}\".format(time.time() - t3))\n # print(\"result qpsolver {0} \\n and result mosek {1}\".format(result, result_test))\n else:\n if dd == 3:\n print(BeqSet[dd].shape)\n # print(QSet[dd].shape)\n # t1 = time.time()\n result = solve_qp(P=QSet[dd], q=np.zeros((QSet[dd].shape[0])), A=AeqSet[dd], b=BeqSet[dd], solver='cvxopt')\n # print(time.time() - t1)\n # t2 = time.time()\n result = self.qp_mk_solver(P=QSet[dd], A=AeqSet[dd], b=BeqSet[dd])\n result = self.qp_mk_fusion_solver(P=QSet[dd], A=AeqSet[dd], b=BeqSet[dd])\n print(result)\n # print(\"saving\")\n # np.savetxt(\"P_\"+str(dd)+\".csv\", QSet[dd], delimiter=\",\")\n # np.savetxt(\"A_\"+str(dd)+\".csv\", AeqSet[dd], delimiter=\",\")\n # np.savetxt(\"B_\"+str(dd)+\".csv\", BeqSet[dd], delimiter=\",\")\n # np.save(\"P_\"+str(dd)+\".npy\", QSet[dd])\n # np.save(\"A_\"+str(dd)+\".npy\", AeqSet[dd])\n # np.save(\"B_\"+str(dd)+\".npy\", BeqSet[dd])\n # print(time.time()-t2)\n Phat_ = result\n if Phat_ is not None:\n flag_ = True\n else:\n flag_ = False\n except:\n Phat_ = None\n flag_ = False\n else: # using end-derivative method\n if ASet is not None:\n # result = solve_qp(P=QSet[dd], q=HSet[dd], G=ASet[dd],\n # h=BSet[dd], solver='cvxopt')\n # dP_ = result.reshape(-1, 1)\n t1 = time.time()\n result = self.qp_mk_solver(P=QSet[dd], q=HSet[dd], G=ASet[dd], h=BSet[dd])\n print(time.time()-t1)\n dP_ = np.array(result).reshape(-1, 1)\n dF_ = BeqSet[dd]\n Phat_ = solve(mapMat, np.concatenate((dF_, dP_)))\n\n flag_ = True\n else:\n # without considering the optimization problem, get the result directly\n dP_ = dp_e.copy()\n dF_ = BeqSet[dd]\n Phat_ = solve(mapMat, np.concatenate((dF_, dP_[dd].reshape(-1, 1))))\n flag_ = True\n # ## ipopt version [this is an alternative choice to solve the opt problem, however it is slower than the sigle qp problem]\n # t3 = time.time()\n # x_sym = ca.SX.sym('x', QSet[0].shape[0])\n # opts_setting = {'ipopt.max_iter':100, 'ipopt.print_level':0, 'print_time':0, 'ipopt.acceptable_tol':1e-8, 'ipopt.acceptable_obj_change_tol':1e-6}\n # obj = 0.5* ca.mtimes([x_sym.T, QSet[dd], x_sym]) + ca.mtimes([HSet[dd].reshape(1, -1), x_sym])\n # Ax_sym = ca.mtimes([ASet[dd], x_sym])\n # nlp_prob = {'f': obj, 'x': x_sym, 'g':Ax_sym}\n # solver = ca.nlpsol('solver', 'ipopt', nlp_prob, opts_setting)\n # try:\n # result = solver(ubg=BSet[dd],)\n # dP_ = result['x']\n # # print(dP_)\n # dF_ = BeqSet[dd]\n # Phat_ = solve(mapMat, np.concatenate((dF_, dP_)))\n # flag_ = True\n # except:\n # dP_ = None\n # flag_ = False\n # print(time.time() - t3)\n # except:\n # dP_ = None\n # flag_ = False\n # else:\n # # without considering the optimization problem, get the result directly\n # dP_ = dp_e.copy()\n # dF_ = BeqSet[dd]\n # Phat_ = solve(mapMat, np.concatenate((dF_, dP_[dd].reshape(-1, 1))))\n # flag_ = True\n if flag_:\n print(\"success !\")\n # print('phat shape: {}'.format(Phat_.shape))\n P_ = np.dot(self.scaleMatBigInv(), Phat_)\n self.polyCoeffSet[dd] = P_.reshape(-1, self.N+1).T\n # print('for dd {0}, Phat {1}, P_{2}, result {3}'.format(dd, Phat_, P_, self.polyCoeffSet[dd]))\n print(\"done\")\n\n def eval(self, t_, d_):\n val_ = np.zeros((self.dim, t_.shape[0]))\n for dd in range(self.dim):\n for idx in range(t_.shape[0]):\n t_i = t_[idx]\n if t_i < self.Ts[0] or t_i > self.Ts[-1]:\n print(\"WARNING: Eval of t: out of bound. Extrapolation\\n\")\n m, _ = self.findSegInteval(t_i)\n # dTm = self.Ts[m+1] - self.Ts[m]\n val_[dd, idx] = np.dot(self.tVec(t_i-self.Ts[m], d_).T, self.polyCoeffSet[dd, :, m])\n\n return val_","sub_path":"python/scripts/traj_gen/poly_trajectory_mosek.py","file_name":"poly_trajectory_mosek.py","file_ext":"py","file_size_in_byte":24549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"605708707","text":"#!/usr/bin/env python\nfrom general import *\n\nclass Event:\n def __init__(self, system, type):\n self.system = system\n self.type = type\n\nclass Event_handler:\n def __init__(self, system):\n self.system = system\n self.events = []\n self.event_create_functions = {\n EVENT_CAST : self.event_cast,\n EVENT_REMOVE : self.event_remove,\n EVENT_DEATH : self.event_death,\n EVENT_DAMAGE : self.event_damage,\n EVENT_COLLISION : self.event_collision,\n EVENT_COLLISION_DURATION: self.event_collision_duration\n }\n self.event_process_functions = {\n EVENT_CAST : self.do_cast,\n EVENT_REMOVE : self.do_remove,\n EVENT_DEATH : self.do_death,\n EVENT_DAMAGE : self.do_damage,\n EVENT_COLLISION : self.do_collision,\n EVENT_COLLISION_DURATION: self.do_collision_duration\n }\n\n def on_update(self):\n for event in self.events:\n self.do_event(event)\n self.events.remove(event)\n\n def do_event(self, event):\n characters = self.system.characters.copy()\n for i in characters:\n character = characters[i]\n for j in character.components:\n component = character.components[j]\n if event.type in component.event_before_functions:\n for k in range(EVENT_BEFORE_PROCEDURE[event.type]):\n if k in component.event_before_functions[event.type]:\n if not (component.event_functions[event.type][k](event)):\n return False\n if not self.event_process_functions[event.type](event):\n return False\n for i in characters:\n character = characters[i]\n for j in character.components:\n component = character.components[j]\n if event.type in component.event_after_functions:\n for k in range(EVENT_AFTER_PROCEDURE[event.type]):\n if k in component.event_after_functions[event.type]:\n if not (component.event_after_functions[event.type][k](event)):\n return False\n return True\n\n\n # 01 CAST\n def event_cast(self, ability, aim_targets):\n castable = ability.components[COMPONENT_CASTABLE]\n if (not castable.castable(aim_targets)):\n return False\n\n event = Event(self.system, EVENT_CAST)\n event.ability = ability\n event.aim_targets = aim_targets\n self.events.append(event)\n return True\n\n def do_cast(self, event):\n castable = event.ability.components[COMPONENT_CASTABLE]\n castable.cool_down_left = castable.value_table.value_total(ATTRIBUTE_COOLDOWN)\n return True\n\n # 02 REMOVE\n def event_remove(self, character):\n if not (character.id in self.system.characters):\n return False\n character.on_remove()\n event = Event(self.system, EVENT_REMOVE)\n event.character = character\n self.events.append(event)\n return True\n\n def do_remove(self, event):\n character = event.character\n if not (character.id in self.system.characters):\n return False\n character.on_remove()\n return True\n\n # 03 DEATH\n def event_death(self, character):\n if not (character.id in self.system.characters):\n return False\n\n event = Event(self.system, EVENT_DEATH)\n event.character = character\n self.events.append(event)\n return True\n\n def do_death(self, event):\n return True\n\n # 04 DAMAGE\n def event_damage(self, attacker, source, target, damage, type, subtype):\n event = Event(self.system, EVENT_DAMAGE)\n event.attacker = attacker\n event.source = source\n event.target = target\n event.damage = damage\n event.damage_type = type\n event.damage_subtype = subtype\n\n self.events.append(event)\n return True\n\n def do_damage(self, event):\n if (COMPONENT_LIFE in event.target.components):\n event.target.components[COMPONENT_LIFE].on_damage(event.damage)\n return True\n return False\n\n # 05 COLLISION\n def event_collision(self, c1, c2):\n event = Event(self.system, EVENT_COLLISION)\n event.c1 = c1\n event.c2 = c2\n\n self.events.append(event)\n return True\n\n def do_collision(self, event):\n return True\n\n # 05 COLLISION_DURATION\n def event_collision_duration(self, c1, c2, delta_time):\n event = Event(self.system, EVENT_COLLISION_DURATION)\n event.c1 = c1\n event.c2 = c2\n event.delta_time = delta_time\n\n self.events.append(event)\n return True\n\n def do_collision_duration(self, event):\n return True","sub_path":"game_project/server/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":5021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"359474561","text":"\n# coding=utf8\n\n# представьте, что следующий словарь - база данных\n# в дальнейших комментах под базой будет подразумеваться этот список\n\n\ndb = [\n {'id': 1, 'name': 'Chuck Norris', 'rate': 2},\n {'id': 2, 'name': 'Bruce Lee', 'rate': 1},\n {'id': 3, 'name': 'Jackie Chan', 'rate': 3},\n]\n\n\nclass EntityMeta(type):\n def __new__(mcs, name, parents, props):\n for key, value in props.items():\n if isinstance(value, Field):\n value.name = key\n value.__tablename__ = props['__tablename__']\n\n return super(EntityMeta, mcs).__new__(mcs, name, parents, props)\n\n\nclass Entity:\n def __init__(self, **kwargs):\n setattr(self, '__data__', {})\n if 'id' not in kwargs:\n self.id = self.__next_id()\n self.__save(kwargs)\n for key, value in kwargs.items():\n setattr(self, key, value)\n\n def __save(self, props):\n d = {'id': self.id}\n for key, value in props.items():\n d[key] = value\n db.append(d)\n\n @classmethod\n def __next_id(cls):\n return max([record['id'] for record in db]) + 1\n\n @staticmethod\n def get(id):\n for record in db:\n if record['id'] == id:\n return User(**record)\n return None\n\n\nclass Field:\n def __init__(self):\n self.name = None\n self.__tablename__ = None\n\n def __get__(self, instance, owner):\n if instance:\n return instance.__data__[self.name]\n else:\n return self\n\n def __eq__(self, other):\n return '\"%s\".\"%s\" = \\'%s\\'' % (self.__tablename__, self.name, str(other))\n\n\nclass TextField(Field):\n def __set__(self, instance, value):\n instance.__data__[self.name] = str(value)\n\n\nclass IntegerField(Field):\n def __set__(self, instance, value):\n try:\n instance.__data__[self.name] = int(value)\n except ValueError:\n raise ValueError('Field \"%s\" should be an integer.' % self.name)\n\n# Д��лаем мини-модель ORM, нужно заставить работать следующий кусок кода.\n# Для этого реализуйте объявленные выше классы, а также, если необходимо,\n# базовые и метаклассы.\n\n\nclass User(Entity, metaclass=EntityMeta):\n __tablename__ = 'user'\n name = TextField()\n rate = IntegerField()\n # если угодно, можно заменить TextField на Field(Text), Field.Text и т.п.\n\nu = User.get(2) # u должен присвоиться объект типа User\n # с аттрибутами id=2, name='Bruce Lee', rate=1\n\nprint(u.name) # вернет строку 'Bruce Lee'\n\nu2 = User(name='Arni', rate=4) # В \"базу\" должен записаться новый dict\n # {'id': 4, 'name': 'Arni', 'rate': 4},\n # переменной u2 должен присвоиться объект\n # типа User c аттрибутами name='Arni', rate=4\n\nprint(u2.rate) # Должно вернуть 4 (int(4))\n\nprint(db)\n\nprint(User.name == 'Duncan MacLeod') # Выражение должно вернуть SQL statement\n # (просто строку):\n # \"user\".\"name\" = 'Duncan MacLeod'\n","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"184078502","text":"# Copyright 2022 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"\nTesting AdjustSaturation op in DE\n\"\"\"\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport PIL\nfrom PIL import Image, ImageEnhance\n\nimport mindspore.dataset as ds\nimport mindspore.dataset.transforms.transforms\nimport mindspore.dataset.vision as vision\nfrom mindspore import log as logger\n\n\nDATA_DIR = \"../data/dataset/testImageNetData/train/\"\nMNIST_DATA_DIR = \"../data/dataset/testMnistData\"\n\nDATA_DIR_2 = [\"../data/dataset/test_tf_file_3_images/train-0000-of-0001.data\"]\nSCHEMA_DIR = \"../data/dataset/test_tf_file_3_images/datasetSchema.json\"\n\nIMAGE_FILE = \"../data/dataset/apple.jpg\"\n\n\ndef generate_numpy_random_rgb(shape):\n \"\"\"\n Only generate floating points that are fractions like n / 256, since they\n are RGB pixels. Some low-precision floating point types in this test can't\n handle arbitrary precision floating points well.\n \"\"\"\n return np.random.randint(0, 256, shape) / 255.\n\n\ndef test_adjust_saturation_eager():\n \"\"\"\n Feature: AdjustSaturation op\n Description: Test eager support for AdjustSaturation C implementation\n Expectation: Output is the same as expected output\n \"\"\"\n # Eager 3-channel\n rgb_flat = generate_numpy_random_rgb((64, 3)).astype(np.uint8)\n img_in = rgb_flat.reshape((8, 8, 3))\n img_pil = Image.fromarray(img_in)\n\n adjustsaturation_op = vision.AdjustSaturation(0.0)\n img_out = adjustsaturation_op(img_in)\n pil_out = ImageEnhance.Color(img_pil).enhance(0)\n pil_out = np.array(pil_out)\n assert_allclose(pil_out.flatten(),\n img_out.flatten(),\n rtol=1e-5,\n atol=0)\n\n img_in2 = PIL.Image.open(\"../data/dataset/apple.jpg\").convert(\"RGB\")\n\n adjustsaturation_op2 = vision.AdjustSaturation(1.0)\n img_out2 = adjustsaturation_op2(img_in2)\n img_out2 = np.array(img_out2)\n pil_out2 = ImageEnhance.Color(img_in2).enhance(1)\n pil_out2 = np.array(pil_out2)\n assert_allclose(pil_out2.flatten(),\n img_out2.flatten(),\n rtol=1e-5,\n atol=0)\n\n\ndef test_adjust_saturation_invalid_saturationfactor_param():\n \"\"\"\n Feature: AdjustSaturation op\n Description: Test AdjustSaturation Cpp implementation with invalid ignore parameter\n Expectation: Correct error is raised as expected\n \"\"\"\n logger.info(\"Test AdjustSaturationC implementation with invalid ignore parameter\")\n try:\n data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)\n data_set = data_set.map(\n operations=[vision.Decode(), vision.Resize((224, 224)), lambda img: np.array(img[:, :, 0])],\n input_columns=[\"image\"])\n # invalid alpha\n data_set = data_set.map(operations=vision.AdjustSaturation(saturation_factor=-10.0),\n input_columns=\"image\")\n except ValueError as error:\n logger.info(\"Got an exception in AdjustSaturation: {}\".format(str(error)))\n assert \"Input is not within the required interval of \" in str(error)\n try:\n data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)\n data_set = data_set.map(\n operations=[vision.Decode(), vision.Resize((224, 224)), lambda img: np.array(img[:, :, 0])],\n input_columns=[\"image\"])\n # invalid alpha\n data_set = data_set.map(operations=vision.AdjustSaturation(saturation_factor=[1.0, 2.0]),\n input_columns=\"image\")\n except TypeError as error:\n logger.info(\"Got an exception in AdjustSaturation: {}\".format(str(error)))\n assert \"is not of type [, ], but got\" in str(error)\n\n\ndef test_adjust_saturation_pipeline():\n \"\"\"\n Feature: AdjustSaturation op\n Description: Test AdjustSaturation Cpp implementation Pipeline\n Expectation: Output is the same as expected output\n \"\"\"\n # First dataset\n transforms1 = [vision.Decode(), vision.Resize([64, 64])]\n transforms1 = mindspore.dataset.transforms.transforms.Compose(\n transforms1)\n ds1 = ds.TFRecordDataset(DATA_DIR_2,\n SCHEMA_DIR,\n columns_list=[\"image\"],\n shuffle=False)\n ds1 = ds1.map(operations=transforms1, input_columns=[\"image\"])\n\n # Second dataset\n transforms2 = [\n vision.Decode(),\n vision.Resize([64, 64]),\n vision.AdjustSaturation(1.0)\n ]\n transform2 = mindspore.dataset.transforms.transforms.Compose(\n transforms2)\n ds2 = ds.TFRecordDataset(DATA_DIR_2,\n SCHEMA_DIR,\n columns_list=[\"image\"],\n shuffle=False)\n ds2 = ds2.map(operations=transform2, input_columns=[\"image\"])\n\n num_iter = 0\n for data1, data2 in zip(ds1.create_dict_iterator(num_epochs=1),\n ds2.create_dict_iterator(num_epochs=1)):\n num_iter += 1\n ori_img = data1[\"image\"].asnumpy()\n cvt_img = data2[\"image\"].asnumpy()\n assert_allclose(ori_img.flatten(),\n cvt_img.flatten(),\n rtol=1e-5,\n atol=0)\n assert ori_img.shape == cvt_img.shape\n\n\nif __name__ == \"__main__\":\n test_adjust_saturation_eager()\n test_adjust_saturation_invalid_saturationfactor_param()\n test_adjust_saturation_pipeline()\n","sub_path":"tests/ut/python/dataset/test_adjust_saturation.py","file_name":"test_adjust_saturation.py","file_ext":"py","file_size_in_byte":6065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"401453693","text":"import testing_base as base\r\nimport testing_logger as logger\r\nfrom pymodbus.pdu import ExceptionResponse\r\n\r\n@base.testClass('wpt')\r\nclass Ping_Test(base.testingBase):\r\n '''\r\nThis test simply pings the target over modbus, according\r\nto the command parameters.\r\nUses: -i, -s, -p, -w, -l, -f, -t\r\n'''\r\n\r\n def __init__(self, cfg):\r\n self.log = logger.get_logger('Ping_Test')\r\n self.log.info(\"Look at the modbus watchdog to check for false triggers\")\r\n self.config = cfg\r\n self.ping = 0\r\n base.testingBase.__init__(self, cfg)\r\n\r\n def init_test(self):\r\n self.log.info(\"setup target state\")\r\n self.log.info(\"sleep time between iterations: %.3f\"%(self.config.sleep))\r\n self.log.info(\"iterations between pings: %d\"%(self.config.ping))\r\n\r\n def iterate_test(self):\r\n # read bulk data\r\n regs = self.client.client.read_holding_registers(0, 10)\r\n if ExceptionResponse is type(regs):\r\n self.log.error(\"read configurations from target failed: %s\"%(str(regs)))\r\n","sub_path":"testing/tests/wd_ping_test.py","file_name":"wd_ping_test.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"369738182","text":"# -*- coding: utf-8 -*-\n\nfrom pvfactors import PVFactorsError\nfrom pvfactors.pvcore import LinePVArray, Y_GROUND\nfrom shapely.geometry import LineString, Point\nfrom shapely.affinity import affine_transform\nimport numpy as np\n\n\nclass PVRowBase(object):\n \"\"\"\n ``PVRowBase`` exists for future developments of the model. It is the\n base class for PV Rows that will contain all the boiler plate code\n shared by sub classes like :class:`PVRowLine`, or for instance\n ``PVRowRoof``.\n \"\"\"\n\n def __init__(self):\n\n self.front = None\n self.back = None\n self.shadow = None\n self.shadow_line_index = None\n self.lines = []\n self.highest_point = None # for shading purposes\n self.lowest_point = None # for shading purposes\n self.left_point = None # for shading purposes\n self.right_point = None # for shading purposes\n self.director_vector = None # for shading purposes\n self.normal_vector = None # for shading purposes\n # Complete line will have the full PVRow linestring with possibly\n # multiple points on it, but still one linestring only\n self.complete_linestring = None # for obstruction purposes\n\n def create_lines(self, *args, **kwargs):\n raise NotImplementedError\n\n def get_shadow_bounds(self, *args, **kwargs):\n raise NotImplementedError\n\n def translate_2d_lines(self, x_off, y_off):\n \"\"\"\n Translate all the :class:`pvfactors.components.LinePVArray` objects in\n the line attribute in the x and y directions.\n /!\\ method is unfinished\n\n :param float x_off: translation in the x direction\n :param float y_off: translation in the y direction\n :return: None\n \"\"\"\n matrix_2d_translation = [1, 1, 1, 1, x_off, y_off]\n for line in self.lines:\n line['shapeline'] = affine_transform(line['shapeline'],\n matrix_2d_translation)\n # and update lines in line_registry\n\n\nclass PVRowLine(PVRowBase):\n \"\"\"\n ``PVRowLine`` is sub-classed from :class:`PVRowBase`, and its core is\n made of :class:`pvfactors.components.LinePVArray` objects. It is a\n container that has methods and attributes relative to PV Rows and their\n shadows.\n ``PVRowLine`` can only create PV rows that have the shape of\n straight lines. So it won't be able to create shapes like dual-tilt\n systems for instance.\n\n :param line_registry: line registry passed by :class:`pvarray.Array`\n object\n :type line_registry: :class:`pvcore.Registry`\n :param float x_center: x coordinate of center of the line [m]\n :param float y_center: y coordinate of center of the line [m]\n :param int index: PV row index, used to distinguish different PV rows\n :param float array_tilt: tilt of the PV row, same as the whole array a\n priori [deg]\n :param float pvrow_width: width of the PV row, which is the length of\n the PV row line [m]\n \"\"\"\n\n def __init__(self, line_registry, x_center, y_center, index, array_tilt,\n pvrow_width):\n super(PVRowLine, self).__init__()\n self.width = pvrow_width\n self.tilt = array_tilt\n self.index = index\n self.x_center = x_center\n self.y_center = y_center\n (self.lines, self.highest_point, self.lowest_point, self.right_point,\n self.left_point, self.director_vector, self.normal_vector) = (\n self.create_lines(self.tilt, index))\n self.line_registry_indices = line_registry.pvgeometry.add(self.lines)\n # Complete line will have the full pvrow linestring with possibly\n # multiple points on it, but still one linestring only\n self.complete_linestring = self.lines[0]['geometry']\n self.cut_points = []\n\n def create_lines(self, tilt, index):\n \"\"\"\n Create the :class:`pvcore.LinePVArray` objects that the PV row\n is made out of, based on the inputted geometrical parameters.\n\n :param float tilt: tilt angle of the PV row [deg]\n :param int index: PV row index, used to distinguish different PV rows\n :return: [line_pvarray], highest_point, lowest_point,\n right_point, left_point, director_vector, normal_vector // which\n are: list of :class:`pvcore.LinePVArray`;\n :class:`shapely.Point` of the line with biggest y coordinate;\n :class:`shapely.Point` of the line with smallest y coordinate;\n :class:`shapely.Point` of the line with biggest x coordinate;\n :class:`shapely.Point` of the line with smallest x coordinate;\n list of 2 coordinates for director vector of the line; list of\n 2 coordinates for normal vector of the line\n \"\"\"\n tilt_rad = np.radians(tilt)\n\n # Create the three trackers\n radius = self.width / 2.\n x1 = radius * np.cos(tilt_rad + np.pi) + self.x_center\n y1 = radius * np.sin(tilt_rad + np.pi) + self.y_center\n x2 = radius * np.cos(tilt_rad) + self.x_center\n y2 = radius * np.sin(tilt_rad) + self.y_center\n\n highest_point = Point(x2, y2) if y2 >= y1 else Point(x1, y1)\n lowest_point = Point(x1, y1) if y2 >= y1 else Point(x2, y2)\n right_point = Point(x2, y2) if x2 >= x1 else Point(x1, y1)\n left_point = Point(x1, y1) if x2 >= x1 else Point(x2, y2)\n\n # making sure director_vector[0] >= 0\n director_vector = [x2 - x1, y2 - y1]\n # making sure normal_vector[1] >= 0\n normal_vector = [- director_vector[1], director_vector[0]]\n geometry = LineString([(x1, y1), (x2, y2)])\n line_pvarray = LinePVArray(geometry=geometry, line_type='pvrow',\n shaded=False, pvrow_index=index)\n return ([line_pvarray], highest_point, lowest_point,\n right_point, left_point, director_vector, normal_vector)\n\n def get_shadow_bounds(self, solar_2d_vector):\n \"\"\"\n Calculate the x coordinates of the boundary points of the shadow lines\n on the ground, assuming Y_GROUND is the y coordinate of the ground.\n Note: this shadow construction is more or less ignored when direct\n shading happens between rows, leading to one continous shadows formed by\n all the PV rows in the array.\n\n :param list solar_2d_vector: projection of solar vector into the 2D\n plane of the array geometry\n :return: x1_shadow, x2_shadow // ``float`` smallest x coordinate of\n shadow, ``float`` largest x coordinate of shadow\n \"\"\"\n list_x_values = []\n for line in self.lines:\n geometry = line['geometry']\n b1 = geometry.boundary[0]\n b2 = geometry.boundary[1]\n shadow_intercept_1 = - (solar_2d_vector[1] * b1.x\n + solar_2d_vector[0] * b1.y)\n shadow_intercept_2 = - (solar_2d_vector[1] * b2.x\n + solar_2d_vector[0] * b2.y)\n x1_shadow = - ((shadow_intercept_1\n + solar_2d_vector[0] * Y_GROUND)\n / solar_2d_vector[1])\n x2_shadow = - ((shadow_intercept_2\n + solar_2d_vector[0] * Y_GROUND)\n / solar_2d_vector[1])\n list_x_values.append(x1_shadow)\n list_x_values.append(x2_shadow)\n x1_shadow = min(list_x_values)\n x2_shadow = max(list_x_values)\n return x1_shadow, x2_shadow\n\n def is_front_side_illuminated(self, solar_2d_vector):\n \"\"\"\n Find out if the direct sun light is incident on the front or back\n surface of the PV rows\n\n :param list solar_2d_vector: projection of solar vector into the 2D\n plane of the array geometry\n :return: ``bool``, True if front surface is illuminated\n \"\"\"\n # Only 1 normal vector here\n dot_product = np.dot(solar_2d_vector, self.normal_vector)\n return dot_product <= 0\n\n @property\n def facing(self):\n \"\"\"\n This property is mainly used to calculate the view_matrix\n :return: direction that the pvrow front surfaces are facing\n \"\"\"\n if self.tilt == 0.:\n direction = 'up'\n elif self.tilt > 0:\n direction = 'left'\n elif self.tilt < 0:\n direction = 'right'\n else:\n raise PVFactorsError(\"Unknown facing condition for pvrow\")\n return direction\n\n def calculate_cut_points(self, n_segments):\n \"\"\"\n Calculate the points of the PV row geometry on which the PV line will be\n cut and discretized. The list of cut points is saved into the object.\n\n :param int n_segments: number of segments wanted for the discretization\n :return: None\n \"\"\"\n fractions = np.linspace(0., 1., num=n_segments + 1)[1:-1]\n list_points = [self.complete_linestring.interpolate(fraction,\n normalized=True)\n for fraction in fractions]\n self.cut_points = list_points\n","sub_path":"pvfactors/pvrow.py","file_name":"pvrow.py","file_ext":"py","file_size_in_byte":9200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"57315705","text":"from . import speakandlisten\nimport wikipedia\n\ndef wiki():\n #taking the input for what to know about\n wikiknowabout = speakandlisten.takeCommand()\n #getting the search results\n wiki_result = wikipedia.summary(wikiknowabout, sentences = 3 or 4)\n print(wiki_result)\n speakandlisten.speak(wiki_result)","sub_path":"Abilities/get_wiki.py","file_name":"get_wiki.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"101136742","text":"#栈\n\nclass Node(object):\n def __init__(self, elem):\n #节点数据\n self.elem = elem\n #节点指针\n self.next = None\n\nclass Link(object):\n def __init__(self, node=None):\n #初始化头指针指向None\n self.head = node\n\n #入栈\n def into(self, item):\n #创建新节点\n node = Node(item)\n #新节点指针指向上一个节点\n node.next = self.head\n #头指针指向新插入的节点\n self.head = node\n\n #出栈\n def out(self):\n #头指针指��下一个节点\n node=self.head\n self.head=node.next\n #上一个栈的指针指向none\n node.next=None\n #返回出栈数据\n return node.elem\n\n #遍历\n def select(self,item):\n # 头指针\n cur = self.head\n while cur != None:\n if cur.elem==item:\n return cur.elem\n break\n cur = cur.next\n\nif __name__=='__main__':\n item=Link()\n item.into(1)\n item.into(2)\n item.into(3)\n print(item.out())\n print(item.select(1))\n","sub_path":"数据结构/MyStack.py","file_name":"MyStack.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"245905067","text":"# -*- coding: utf-8 -*-\n\"\"\"\n**************************************************************************\n* E-Yantra Robotics Competition\n* ================================\n* This software is intended to check version compatiability of open source software\n* Theme: ANT BOT\n* MODULE: Task1.1\n* Filename: Task1.1.py\n* Version: 1.0.0 \n* Date: October 31, 2018\n* \n* Author: e-Yantra Project, Department of Computer Science\n* and Engineering, Indian Institute of Technology Bombay.\n* \n* Software released under Creative Commons CC BY-NC-SA\n*\n* For legal information refer to:\n* http://creativecommons.org/licenses/by-nc-sa/4.0/legalcode \n* \n*\n* This software is made available on an “AS IS WHERE IS BASIS”. \n* Licensee/end user indemnifies and will keep e-Yantra indemnified from\n* any and all claim(s) that emanate from the use of the Software or \n* breach of the terms of this agreement.\n* \n* e-Yantra - An MHRD project under National Mission on Education using \n* ICT(NMEICT)\n*\n**************************************************************************\n\"\"\"\n\n\"\"\"\nArUco ID Dictionaries: 4X4 = 4-bit pixel, 4X4_50 = 50 combinations of a 4-bit pixel image\nList of Dictionaries in OpenCV's ArUco library:\nDICT_4X4_50\t \nDICT_4X4_100\t \nDICT_4X4_250\t \nDICT_4X4_1000\t \nDICT_5X5_50\t \nDICT_5X5_100\t \nDICT_5X5_250\t \nDICT_5X5_1000\t \nDICT_6X6_50\t \nDICT_6X6_100\t \nDICT_6X6_250\t \nDICT_6X6_1000\t \nDICT_7X7_50\t \nDICT_7X7_100\t \nDICT_7X7_250\t \nDICT_7X7_1000\t \nDICT_ARUCO_ORIGINAL\n\nReference: http://hackage.haskell.org/package/opencv-extra-0.2.0.1/docs/OpenCV-Extra-ArUco.html\n\"\"\"\n\nimport numpy\nimport cv2\nimport cv2.aruco as aruco\n\nimport os\nfrom pathlib import Path\n\nmappingName = {}\n\ndef aruco_gen(id_aruco, num_pixels):\n\n # Setting up n and C according to the id_aruco \t\t\n\n if id_aruco == 8 or id_aruco == 27:\n aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)\n\n elif id_aruco == 92 or id_aruco == 4:\n aruco_dict = aruco.Dictionary_get(aruco.DICT_5X5_250)\n\n\n\n # ----------Building the Marker----------\n \t \n img = aruco.drawMarker(aruco_dict, id_aruco,num_pixels)\n\n tempImg = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n \n finalImg = cv2.copyMakeBorder(tempImg,25,25,25,25,cv2.BORDER_CONSTANT,value = (255,255,255))\n\n\n # -------------- Adding Red label to RGB File ------------\n\n title = 'ArUco ID = '+ str(id_aruco)\n\n fontStyle = cv2.FONT_HERSHEY_SIMPLEX\n\n cv2.putText(finalImg, title , (170, 17), fontStyle, 0.6, (0, 0, 255), 1, cv2.LINE_AA)\n\n # ------------- Creating the .jpg file from RGB file -----------\n\n fileName = '../Images/ArUco'+ str(id_aruco) +'.jpg'\n\n tempName = 'Aruco'+str(id_aruco)+'.jpg'\n global mappingName\n mappingName[tempName] = 1\n\n cv2.imwrite(fileName,finalImg)\n\n # ------------ Display RGB Image -----\n\n cv2.imshow('frame',finalImg)\n\n\n cv2.waitKey(0)\n\n cv2.destroyAllWindows()\n\n\ndef generalised_version(id_aruco, n, C, num_pixels):\n\n global c\n\n if n == 'ARUCO' and C == 'ORIGINAL':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_ARUCO_ORIGINAL)\n\n elif n == '4':\n if C == '50':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)\n \n elif C == '100':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_100)\n \n elif C == '250':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_250)\n\n elif C == '1000':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_1000)\n\n elif n == '5':\n if C == '50':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_5X5_50)\n \n elif C == '100':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_5X5_100)\n \n elif C == '250':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_5X5_250)\n\n elif C == '1000':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_5X5_1000)\n\n elif n == '6':\n if C == '50':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_50)\n \n elif C == '100':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_100)\n \n elif C == '250':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)\n\n elif C == '1000':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_1000)\n\n elif n == '7':\n if C == '50':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_7X7_50)\n \n elif C == '100':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_7X7_100)\n \n elif C == '250':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_7X7_250)\n\n elif C == '1000':\n aruco_dict = aruco.Dictionary_get(aruco.DICT_7X7_1000)\n \n # ----------Building the Marker----------\n \t \n img = aruco.drawMarker(aruco_dict, id_aruco,num_pixels)\n\n tempImg = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n \n finalImg = cv2.copyMakeBorder(tempImg,25,25,25,25,cv2.BORDER_CONSTANT,value = (255,255,255))\n\n # -------------- Adding Red label to RGB File ------------\n\n title = 'ArUco ID = '+ str(id_aruco)\n\n fontStyle = cv2.FONT_HERSHEY_SIMPLEX\n\n cv2.putText(finalImg, title , (170, 17), fontStyle, 0.6, (0, 0, 255), 1, cv2.LINE_AA)\n\n # ------------- Creating the .jpg file from RGB file -----------\n\n fileName = '../Images/ArUco'+ str(id_aruco) +'.jpg'\n\n global mappingName\n tempName = 'Aruco'+str(id_aruco)+'.jpg'\n \n if tempName in mappingName:\n fileName = '../Images/Aruco'+str(id_aruco)+'_'+str(mappingName[tempName])+'.jpg'\n print('\\n\"' +tempName+'\"','already present. New name is : '+'\"'+ 'Aruco'+str(id_aruco) + '_' + str(mappingName[tempName]) + '.jpg' + '\"')\n mappingName[tempName] +=1\n\n else:\n mappingName[tempName] = 1\n\n cv2.imwrite(fileName,finalImg)\n\n # ------------ Display RGB Image -----\n\n cv2.imshow('frame',finalImg)\n\n cv2.waitKey(0)\n\n cv2.destroyAllWindows()\n \n\nif __name__ == \"__main__\": \n aruco_gen(8, 400)\n aruco_gen(27, 400)\n aruco_gen(92, 400)\n aruco_gen(4, 400)\n\n print(\"\\n\\n*** THE 4 ARUCO MARKERS HAVE BEEN GENERATED AS SPECIFIED IN TABLE 1 of Task1.1.pdf ***\\n\")\n\n print(\"*** Now the Generalised Code is running ***\\n\")\n\n choice = input(\"\\nPress 0 to EXIT or ANY KEY to CONTINUE : \")\n\n while choice != '0':\n\n id_aruco = input(\"\\nEnter ArUco ID : \")\n n = input(\"Enter n (bits/'ARUCO'): \")\n C = input(\"Enter C (combination/'ORIGINAL') : \")\n\n if (not id_aruco.isdecimal()) or (int(id_aruco) > 1023):\n print(\"Exception : Invalid value of ArUco ID.\")\n\n elif(n == 'ARUCO'):\n if(C == 'ORIGINAL'):\n generalised_version(int(id_aruco),n,C,400)\n else:\n print(\"Exception : Invalid Value of C (combination/'ORIGINAL').\")\n\n elif not n.isdecimal() or (int(n)>7) or (int(n)<4):\n print(\"Exception : Invalid value of n (bits/'ARUCO').\")\n\n elif not C.isdecimal() or ((int(C) != 50) and (int(C) != 100) and (int(C) != 250) and (int(C) != 1000)):\n print(\"Exception : Invalid value of C (comnination).\")\n\n \n elif int(id_aruco) >= int(C):\n print(\"Exception : Aruco ID exceeding C (combination).\")\n\n elif(int(id_aruco) < int(C)):\n generalised_version(int(id_aruco),n,C,400)\n \n else:\n print(\"Exception : Invalid Dictionary.\")\n \n\n #------ Choose to Exit program or not.------\n\n choice = input(\"\\nPress 0 to EXIT or ANY KEY to CONTINUE : \")\n \n \n","sub_path":"Task 1/Task1.1/2121_Task1.1/Code/2121_Task1.1.py","file_name":"2121_Task1.1.py","file_ext":"py","file_size_in_byte":7758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"258494310","text":"\"\"\"\n版本 2月 23日 00:50 用来发送email的程序\n维护:张天翊\n\"\"\"\n\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom general import notify\nimport time\n\ntime.sleep(1)\nprint(\"print file path please:\")\nfile_path = input()\n\nif os.path.exists(file_path):\n notify.add_file(file_path)\n\n print(\"write the target email path please: use blankspace for the dafult path \")\n email_path = input()\n\n if len(email_path) < 5:\n print(\"send mail to defult list\")\n notify.send_log()\n else:\n print(\"send mail to:\", email_path)\n notify.send_log(email_path)\n\nelse:\n print(\"file path is not exist!!!!\")\n\n\n","sub_path":"send_file_by_email.py","file_name":"send_file_by_email.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"604894250","text":"import re\n\nfrom flask import render_template, request, redirect, flash, url_for\n\nfrom main import env, app\nfrom views.forms import EmployeeForm, DeleteByIdForm\n\nEMAIL_PATTERN = '\\w*[@]\\w*[.]\\w{2,3}'\nPHONE_NUM_PATTERN = '[+]{1}[3]{1}[8]{1}[0]{1}[0-9]{9}'\n\n\n@app.route('/create_employee', methods=['GET', 'POST'])\ndef create_employee():\n form = EmployeeForm(request.form)\n departments_list = [(department.id, department.name, 'department') for department in env.departments]\n units_list = [(unit.id, unit.name, 'unit') for unit in env.units]\n form.subdivision_data.choices = departments_list + units_list\n form.vacancy_data.choices = [(vacancy.id, vacancy.name) for vacancy in env.vacancies]\n if request.method == 'POST':\n print('/create employee', form.data)\n if request.form['first_name'] == '' or request.form['last_name'] == '':\n flash('First and last names should be mentioned!', category='danger')\n elif request.form['subdivision_data'] == '' or request.form['vacancy_data'] == '':\n flash('Subdivision and vacancy information should be mentioned!', category='danger')\n elif re.match(EMAIL_PATTERN, request.form['email']) is None:\n flash('Incorrect email format!', category='danger')\n elif re.match(PHONE_NUM_PATTERN, request.form['phone_number']) is None:\n flash('Incorrect phone number format!', category='danger')\n else:\n env.create_employee(object_type='employee', **form.data)\n flash('Employee successfully created!', category='success')\n return redirect(url_for('index'))\n return render_template('create_employee.html', form=form)\n\n\n@app.route('/update_employee', methods=['GET', 'POST'])\ndef update_employee():\n form = EmployeeForm(request.form)\n form.id.choices = [(employee.id, employee.name) for employee in env.employees]\n departments_list = [(department.id, department.name, 'department') for department in env.departments]\n units_list = [(unit.id, unit.name, 'unit') for unit in env.units]\n form.subdivision_data.choices = departments_list + units_list\n form.vacancy_data.choices = [(vacancy.id, vacancy.name) for vacancy in env.vacancies]\n if request.method == 'POST':\n print('/update employee', form.data)\n if request.form['id'] == 'None':\n flash('There is no existing employee!', category='warning')\n elif request.form['email'] and re.match(EMAIL_PATTERN, request.form['email']) is None:\n flash('Incorrect email format!', category='danger')\n elif request.form['phone_number'] and re.match(PHONE_NUM_PATTERN, request.form['phone_number']) is None:\n flash('Incorrect phone number format!', category='danger')\n else:\n env.update_employee(object_type='employee', **form.data)\n flash('Employee successfully updated!', category='success')\n return redirect(url_for('index'))\n return render_template('update_employee.html', form=form)\n\n\n@app.route('/delete_employee', methods=['GET', 'POST'])\ndef delete_employee():\n form = DeleteByIdForm(request.form)\n form.id.choices = [(employee.id, employee.name) for employee in env.employees]\n if request.method == 'POST':\n if request.form['id'] == 'None':\n flash('There is no employees to delete!', category='warning')\n else:\n env.delete_object(object_type='employee', **form.data)\n flash('Employee successfully deleted!', category='success')\n return redirect(url_for('index'))\n return render_template('delete_employee.html', form=form)\n\n\n@app.route('/show_employee')\ndef show_employee():\n return render_template('show_employee.html', employees=env.employees)\n\n\n@app.route('/employee/')\ndef employee_details(id):\n for employee in env.employees:\n if employee.id == int(id):\n return render_template('details.html', employee=employee)\n return render_template('index.html')\n","sub_path":"views/employee_view.py","file_name":"employee_view.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"260549821","text":"# -*- coding: utf-8 -*-\nimport sys\nimport uuid\nimport scrapy\nfrom scrapy.selector import Selector\n\nfrom crawldatapro.items import CrawldataproItem\n\n\nclass SmzdmspiSpider(scrapy.Spider):\n name = 'smzdmspi'\n allowed_domains = ['smzdm.com']\n start_urls = ['http://smzdm.com/']\n\n def get_comment_page(self,pstr):\n m = int(pstr)\n m_result = int(0)\n if m == 0:\n pass\n else:\n r_rem = 16 % 30\n r_mod = 16 // 30\n if r_rem > 0:\n r_mod = r_mod + 1\n m_result = r_mod\n return m_result\n\n # 爬虫启动时,引擎自动调用该方法,并且只会被调用一次,用于生成初始的请求对象(Request)。\n # start_requests()方法读取start_urls列表中的URL并生成Request对象,发送给引擎。\n # 引擎再指挥其他组件向网站服务器发送请求,下载网页\n def start_requests(self):\n for i in range(1, 2):\n url = f'https://www.smzdm.com/fenlei/qipaoshui/p{i}'\n yield scrapy.Request(url=url, callback=self.parse_products)\n # url 请求访问的网址\n # callback 回调函数,引擎回将下载好的页面(Response对象)发给该方法,执行数据解析\n # 这里可以使用callback指定新的函数,不是用parse作为默认的回调参数\n\n # 解析函数\n def parse_products(self, response):\n # 打印网页的url\n # print(f'开始处理:{response.url}')\n # 打印网页的内容\n # print(response.text)\n bandlist = []\n if response.url == 'https://www.smzdm.com/fenlei/qipaoshui/':\n bands = Selector(response=response).xpath('/html/body/div[1]/div/div[3]/div[2]/div[1]/div[1]/div[2]/div[2]/div[2]/div/a')\n for band in bands:\n m = str(band.xpath('./text()').extract_first()).strip('\\n').strip()\n bandlist.append(m)\n # print(m)\n\n products = Selector(response=response).xpath('//li[@class=\"feed-row-wide\"]')\n if products:\n for product in products:\n title = product.xpath('./div/div[2]/h5/a/text()')\n link = product.xpath('./div/div[2]/h5/a/@href')\n zhi = product.xpath('//div/div[2]/div[4]/div[1]/span/a[1]/span[1]/span/text() | //div/div[2]/div[2]/div[1]/span[1]/span[1]/span[1]/span/text()')\n buzhi = product.xpath('//div/div[2]/div[4]/div[1]/span/a[2]/span[1]/span/text() | //div/div[2]/div[2]/div[1]/span[1]/span[2]/span[1]/span/text()')\n collectcount = product.xpath('//div/div[2]/div[4]/div[1]/a[1]/span/text()')\n commentcount = product.xpath('//div/div[2]/div[4]/div[1]/a[2]/span/text()')\n platform = product.xpath('//div/div[2]/div[4]/div[2]/span/a/text()')\n publish = product.xpath('//div/div[2]/div[4]/div[2]/span/text()')\n\n productitem = CrawldataproItem()\n productitem['title'] = str(title.extract_first()).strip('\\n').strip()\n productitem['link'] = str(link.extract_first()).strip('\\n').strip()\n productitem['zhi'] = str(zhi.extract_first()).strip('\\n').strip()\n productitem['buzhi'] = str(buzhi.extract_first()).strip('\\n').strip()\n productitem['collectcount'] = str(collectcount.extract_first()).strip('\\n').strip()\n productitem['commentcount'] = str(commentcount.extract_first()).strip('\\n').strip()\n productitem['platform'] = str(platform.extract_first()).strip('\\n').strip()\n productitem['publish'] = str(publish.extract_first()).strip('\\n').strip()\n productitem['uid'] = str(uuid.uuid1())\n productitem['bands'] = bandlist\n\n print(f\"产品内容:{productitem['title']}-{productitem['link']}-{ productitem['zhi']}-{productitem['buzhi']}-{productitem['collectcount']}-{productitem['commentcount']}-{productitem['platform']}-{productitem['publish']}\")\n\n # 实现评论翻页功能(思路:每页最多30个评论,根据评论数推断评论页数)\n page_count = self.get_comment_page(productitem['commentcount'])\n if page_count > 0:\n for i in range(1, page_count+1):\n url = f'{link.extract()[0]}/p{i}'\n yield scrapy.Request(url=url, meta={'item': productitem}, callback=self.parse_details)\n else:\n yield productitem\n\n # 解析具体页面\n def parse_details(self, response):\n print('-----------------------开始评论详情---------------------------------------')\n print(response.url)\n details = Selector(response=response).xpath('//li[@class=\"comment_list\"]')\n productitem = response.meta['item']\n mlist = []\n if details:\n for detail in details:\n publisher = str(detail.xpath('./div[2]/div[1]/a/span/text()').extract_first().strip('\\n').strip())\n datePublished = str(detail.xpath('./div[2]/div[1]/div[1]/meta/@content').extract_first().strip('\\n').strip())\n timePublished = str(detail.xpath('./div[2]/div[1]/div[1]/text()').extract_first().strip('\\n').strip())\n comment = str(detail.xpath('./div[2]/div[3]/div[1]/p/span/text() | ./div[2]/div[2]/div[1]/p/span/text()').extract_first().strip('\\n').strip())\n print(f'评论内容:{publisher}-{datePublished}-{timePublished}-{comment}')\n dict = {'uid':productitem['uid'],'publisher':publisher,'datePublished': datePublished,'timePublished':timePublished, 'comment':comment}\n mlist.append(dict)\n productitem['comments'] = mlist\n yield productitem\n\n","sub_path":"week10/homework/crawldatapro/spiders/smzdmspi.py","file_name":"smzdmspi.py","file_ext":"py","file_size_in_byte":5812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"645796229","text":"'''\nvae.py\ncontains the setup for autoencoders.\n\ncreated by shadySource\n\nTHE UNLICENSE\n'''\nimport tensorflow as tf\nfrom tensorflow.python.keras.models import Model\nfrom tensorflow.python.keras import backend as K\n\nclass AutoEncoder(object):\n def __init__(self, encoderArchitecture, \n decoderArchitecture):\n\n self.encoder = encoderArchitecture.model\n self.decoder = decoderArchitecture.model\n\n self.ae = Model(self.encoder.inputs, self.decoder(self.encoder.outputs))\n\ndef test():\n import os\n import numpy as np\n from PIL import Image\n from tensorflow.python.keras.preprocessing.image import load_img\n\n import models\n\n inputShape = (256, 256, 3)\n batchSize = 20\n latentSize = 100\n\n img = load_img(os.path.join('..','images', 'img.jpg'), target_size=inputShape[:-1])\n img.show()\n\n img = np.array(img, dtype=np.float32) / 255 - 0.5\n img = np.array([img]*batchSize) # make fake batches to improve GPU utilization\n\n # This is how you build the autoencoder\n encoder = models.BetaEncoder(inputShape, batchSize, latentSize, 'bvae', beta=69, capacity=15, randomSample=True)\n decoder = models.BetaDecoder(inputShape, batchSize, latentSize)\n bvae = AutoEncoder(encoder, decoder)\n\n bvae.ae.compile(optimizer='adam', loss='mean_absolute_error')\n while True:\n bvae.ae.fit(img, img,\n epochs=100,\n batch_size=batchSize)\n \n # example retrieving the latent vector\n latentVec = bvae.encoder.predict(img)[0]\n print(latentVec)\n\n pred = bvae.ae.predict(img) # get the reconstructed image\n pred[pred > 0.5] = 0.5 # clean it up a bit\n pred[pred < -0.5] = -0.5\n pred = np.uint8((pred + 0.5)* 255) # convert to regular image values\n\n pred = Image.fromarray(pred[0])\n pred.show() # display popup\n\ndef test2():\n import os\n import numpy as np\n from PIL import Image\n from tensorflow.python.keras.preprocessing.image import load_img\n import cv2\n import models\n import random\n\n inputShape = (32, 32, 3)\n batchSize = 32\n latentSize = 128\n episodes = 1000\n verbose = 1\n\n loadFolder = 'imageNet1'\n loadFile = 'PtBetaEncoder-32px-128l-1000e'\n load = False\n saveFolder = 'imageNet2'\n saveFile = 'PtBetaEncoder-32px-128l-1000e'\n save = True\n # C:\\Users\\slani\\Documents\\GitHub\\montazuma\\dataset\\0000001.png\n # C:\\Users\\slani\\Documents\\GitHub\\montazuma\\dataset\\1281149.png\n dataPath = os.path.join('..', '..', 'dataset', 'train_32x32')\n saveFolderPath = os.path.join('..', 'save', saveFolder)\n loadPath = os.path.join('..', 'save', loadFolder, loadFile + '.h5')\n savePath = os.path.join(saveFolderPath, saveFile + '.h5')\n\n if not os.path.exists(saveFolderPath):\n os.makedirs(saveFolderPath)\n\n # This is how you build the autoencoder\n encoder = models.BetaEncoder(inputShape, batchSize, latentSize, 'bvae', beta=128, capacity=15, randomSample=True)\n decoder = models.BetaDecoder(inputShape, batchSize, latentSize)\n bvae = AutoEncoder(encoder, decoder)\n\n bvae.ae.compile(optimizer='adam', loss='mean_absolute_error')\n\n for epoch in range(episodes):\n imgs = []\n for _batch in range(batchSize):\n imageNum = str(random.randrange(1, 1281150)).zfill(7)\n img = load_img(os.path.join(dataPath, imageNum+\".png\"), target_size=inputShape[:-1])\n imgs.append(np.array(img, dtype=np.uint8))\n\n \n if verbose == 1:\n batch_view = np.array(imgs, dtype=np.uint8)\n print(\"batch.shape\", batch_view.shape)\n visualize_batch = np.concatenate((*batch_view,), axis=1)\n visualize_batch = cv2.cvtColor(visualize_batch, cv2.COLOR_RGB2BGR)\n cv2.imshow(\"batch\", visualize_batch)\n cv2.waitKey(1)\n \n batch = np.array(imgs, dtype=np.float32)\n batch = batch / 255 - 0.5\n\n bvae.ae.fit(batch, batch,\n epochs=100,\n batch_size=batchSize)\n \n # example retrieving the latent vector\n if verbose == 1:\n latentVec = bvae.encoder.predict(batch)[0]\n print(latentVec)\n\n print(\"episode: {}/{}\".format(epoch+1, episodes))\n if save:\n bvae.ae.save_weights(savePath)\n\n if verbose == 1:\n pred = bvae.ae.predict(batch) # get the reconstructed image\n print(\"pred.shape\", pred.shape)\n pred[pred > 0.5] = 0.5 # clean it up a bit\n pred[pred < -0.5] = -0.5\n pred = np.uint8((pred + 0.5)* 255) # convert to regular image values\n\n visualize_pred = np.concatenate((*pred,), axis=1)\n visualize_pred = cv2.cvtColor(visualize_pred, cv2.COLOR_RGB2BGR)\n visualize_both = np.concatenate((visualize_batch, visualize_pred), axis=0)\n\n cv2.imwrite(os.path.join(saveFolderPath, \"sample_{}.png\".format(str(epoch).zfill(7))), visualize_both)\n cv2.imshow(\"prediction\", visualize_both)\n cv2.waitKey(1)\n\n # pred = Image.fromarray(pred[0])\n # pred.show() # display popup\n\nif __name__ == \"__main__\":\n test2()\n","sub_path":"bvae/ae.py","file_name":"ae.py","file_ext":"py","file_size_in_byte":5210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"584749818","text":"#!/usr/bin/env python3\n\nfrom matplotlib import pylab\nimport math\nimport random\n\nglobal w_hid_units\nglobal a_hid_units\nglobal o_hid_units\n\nglobal w_out\nglobal a_out\nglobal o_out\n\nglobal delta_out\nglobal ny\n\ndef f(x):\n return -4*math.cos(x/3.0) + math.sin( 15 / (abs(0.5*x+2) +1)) + 0.2*x\n\ndef backprop_out(y):\n global w_hid_units\n global a_hid_units\n global o_hid_units\n \n global w_out\n global a_out\n global o_out\n \n global delta_out\n global ny\n\n delta_out = fermiAbl(a_out)*(o_out-y)\n for i in range(11):\n w_out[i] += -ny*o_hid_units[i]*delta_out\n\ndef fermi_function(x):\n return 1/(math.exp(-x)+1)\n\ndef fermiAbl(x):\n return fermi_function(x)*(1-fermi_function(x))\n\ndef network(x_in):\n global w_hid_units\n global a_hid_units\n global o_hid_units\n \n global w_out\n global a_out\n global o_out\n \n global delta_out\n global ny\n\n for i in range(1,11):\n a_hid_units[i] = x_in*w_hid_units[1][i] + 1*w_hid_units[0][i]\n o_hid_units[i] = fermi_function(a_hid_units[i])\n \n a_out = 0\n for i in range(11):\n a_out += o_hid_units[i]*w_out[i]\n o_out = a_out\n return o_out\n\ndef main():\n global w_hid_units\n global a_hid_units\n global o_hid_units\n \n global w_out\n global a_out\n global o_out\n \n global delta_out\n global ny\n \n ny = 0.0001\n \"\"\"\n Smaller, to reduce \"errors\" in error function.\n \"\"\"\n\n err_x = []\n err_y = []\n \n trained = []\n fx_values = []\n \n a_out = 0\n o_out = 0\n\n filename_training_trained = \"a3_2_training_trained.png\"\n filename_training_set = \"a3_2_training_set.png\"\n filename_error_set = \"a3_2_error_set.png\"\n\n training_set = list(range(1001))\n training_set = [ (i/50.0 - 10) for i in training_set ]\n \n \"\"\"\n training set has to contain values from -10 to 10,\n so for every x in range(1001) /50.0 -10 for values from\n -10 to 10\n \"\"\"\n #matplotlib.interactive(True)\n \n for i in training_set:\n fx_values.append(f(i))\n \n w_hid_units = [[random.uniform(-0.5,0.5) for i in range(11)] for j in range(2)]\n w_out = [random.uniform(-0.5,0.5) for i in range(11)]\n a_hid_units = list(range(11))\n o_hid_units = list(range(11))\n o_hid_units[0] = 1\n \n print(\"ny: \", ny)\n \n mse = 0\n for i in range(1001):\n y = network(training_set[i])\n mse += (y-fx_values[i])**2\n \n mse /= 1001\n print(\"mse_before_training: \",mse)\n \n #Training\n for k in range(500):\n for j in range(100):\n i = random.randrange(0,1001)\n y = network(training_set[i])\n backprop_out(fx_values[i])\n mse = 0\n for i in range(1001):\n y = network(training_set[i])\n mse += (y-fx_values[i])**2\n \n mse /= 1001\n #print(\"Iter:\\t\", k, \" Err:\",mse)\n err_x.append(k)\n err_y.append(mse)\n \n # Ausgabe am Ende\n mse = 0\n for i in range(1001):\n y = network(training_set[i])\n mse += (y-fx_values[i])**2\n trained.append(y)\n \n mse /= 1001\n print(\"mse_after_training: \",mse)\n pylab.plot(training_set, trained)\n pylab.title('the training set')\n pylab.xlabel('training set')\n pylab.ylabel('trained values')\n pylab.savefig(filename_training_trained)\n \n pylab.plot(training_set, fx_values)\n pylab.title('the training set')\n pylab.xlabel('training set')\n pylab.ylabel('f(x) values')\n pylab.savefig(filename_training_set)\n \n pylab.plot(err_x, err_y)\n pylab.title('error function')\n pylab.xlabel('err_x')\n pylab.ylabel('err_y')\n pylab.savefig(filename_error_set)\n \nif __name__ == '__main__':\n main()","sub_path":"Python_Dienstag_14_16/03/a3_2.py","file_name":"a3_2.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"7180191","text":"#!/usr/bin/python3\n\n\"\"\"\n Summary\n -------\n Get a parameter entry from DB for a specific telescope or a site.\n The application receives a parameter name, a site, a telescope (if applicable) and \\\n optionally a version. It then prints out the parameter entry.\n If no version is provided, the value of the current model is printed..\n\n Command line arguments\n ----------------------\n parameter (str, required)\n Parameter name\n\n site (str, required)\n South or North.\n\n telescope (str, optional)\n Telescope model name (e.g. LST-1, SST-D, ...)\n\n log_level (str, optional)\n Log level to print (default=INFO).\n\n Raises\n ------\n KeyError in case the parameter requested does not exist in the model parameters.\n\n Example\n -------\n Get the mirror_list parameter from the DB.\n\n .. code-block:: console\n\n python applications/get_parameter.py --parameter mirror_list --site North --telescope LST-1\\\n --model_version prod5\n\n Expected final print-out message:\n\n .. code-block:: console\n\n {'Applicable': True,\n 'File': True,\n 'Type': 'str',\n 'Value': 'mirror_CTA-N-LST1_v2019-03-31.dat',\n 'Version': '2020-06-28',\n '_id': ObjectId('608834f257df2db2531b8e78'),\n 'entry_date': datetime.datetime(2021, 4, 27, 15, 59, 46, tzinfo=)}\n\n\"\"\"\n\nimport logging\nfrom pprint import pprint\n\nimport simtools.util.general as gen\nfrom simtools import db_handler\nfrom simtools.configuration import configurator\n\n\ndef main():\n\n config = configurator.Configurator(\n description=(\n \"Get a parameter entry from DB for a specific telescope or a site. \"\n \"The application receives a parameter name a site, a telescope (if applicable), \"\n \" and optionally a version. It then prints out the parameter entry. \"\n \"If no version is provided, the value of the current model is printed. \"\n )\n )\n config.parser.add_argument(\"--parameter\", help=\"Parameter name\", type=str, required=True)\n args_dict, db_config = config.initialize(db_config=True, telescope_model=True)\n\n logger = logging.getLogger()\n logger.setLevel(gen.get_log_level_from_user(args_dict[\"log_level\"]))\n\n db = db_handler.DatabaseHandler(mongo_db_config=db_config)\n\n if args_dict[\"telescope\"] is not None:\n pars = db.get_model_parameters(\n args_dict[\"site\"], args_dict[\"telescope\"], args_dict[\"model_version\"]\n )\n else:\n pars = db.get_site_parameters(args_dict[\"site\"], args_dict[\"model_version\"])\n if args_dict[\"parameter\"] not in pars:\n raise KeyError(f\"The requested parameter, {args_dict['parameter']}, does not exist.\")\n print()\n pprint(pars[args_dict[\"parameter\"]])\n print()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"simtools/applications/get_parameter.py","file_name":"get_parameter.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"301290333","text":"import datetime\nfrom bitmovin import Bitmovin, Encoding, S3Input, S3Output, H264CodecConfiguration, \\\n AACCodecConfiguration, H264Profile, StreamInput, SelectionMode, Stream, EncodingOutput, ACLEntry, ACLPermission, \\\n MP4Muxing, MuxingStream, CloudRegion, SmoothManifest, MP4Representation, PlayReadyDRM, PlayReadyMethod, \\\n SmoothContentProtection, Condition\nfrom bitmovin.errors import BitmovinError\n\nAPI_KEY = ''\n\nS3_INPUT_ACCESSKEY = ''\nS3_INPUT_SECRETKEY = ''\nS3_INPUT_BUCKETNAME = ''\nS3_INPUT_PATH = ''\n\nS3_OUTPUT_ACCESSKEY = ''\nS3_OUTPUT_SECRETKEY = ''\nS3_OUTPUT_BUCKETNAME = ''\n\nPLAYREADY_KEYSEED = ''\nPLAYREADY_KID = ''\nPLAYREADY_LA_URL = ''\n\ndate_component = str(datetime.datetime.now()).replace(' ', '_').replace(':', '-').split('.')[0].replace('_', '__')\nOUTPUT_BASE_PATH = 'output/python-smooth/{}/'.format(date_component)\n\n# Please set here the encoding profiles. You can modify height, bitrate and fps.\nencoding_profiles_h264 = [\n dict(height=240, bitrate=400, fps=None, profile=H264Profile.HIGH),\n dict(height=360, bitrate=800, fps=None, profile=H264Profile.HIGH),\n dict(height=480, bitrate=1200, fps=None, profile=H264Profile.HIGH),\n dict(height=720, bitrate=2400, fps=None, profile=H264Profile.HIGH),\n]\n\ndef main():\n bitmovin = Bitmovin(api_key=API_KEY)\n\n s3_input = S3Input(access_key=S3_INPUT_ACCESSKEY,\n secret_key=S3_INPUT_SECRETKEY,\n bucket_name=S3_INPUT_BUCKETNAME,\n name='Sample S3 Output')\n s3_input = bitmovin.inputs.S3.create(s3_input).resource\n\n s3_output = S3Output(access_key=S3_OUTPUT_ACCESSKEY,\n secret_key=S3_OUTPUT_SECRETKEY,\n bucket_name=S3_OUTPUT_BUCKETNAME,\n name='Sample S3 Output')\n\n s3_output = bitmovin.outputs.S3.create(s3_output).resource\n\n acl_entry = ACLEntry(permission=ACLPermission.PUBLIC_READ)\n\n encoding = Encoding(name='example mp4 encoding for smooth + playready',\n cloud_region=CloudRegion.GOOGLE_EUROPE_WEST_1)\n encoding = bitmovin.encodings.Encoding.create(encoding).resource\n\n encoding_configs = []\n\n # Iterate over all encoding profiles and create the H264 configuration with the defined height and bitrate.\n for idx, _ in enumerate(encoding_profiles_h264):\n profile_h264 = encoding_profiles_h264[idx]\n encoding_config = dict(profile_h264=profile_h264)\n h264_codec = H264CodecConfiguration(\n name='H264 Codec {}p {}k Configuration'.format(profile_h264.get('height'),\n profile_h264.get('bitrate')),\n bitrate=profile_h264.get('bitrate') * 1000,\n height=profile_h264.get('height'),\n profile=profile_h264.get('profile'),\n rate=profile_h264.get(\"fps\"))\n encoding_config['h264_codec'] = bitmovin.codecConfigurations.H264.create(h264_codec).resource\n encoding_configs.append(encoding_config)\n\n audio_codec_configuration = AACCodecConfiguration(name='example_audio_codec_configuration_english',\n bitrate=128000,\n rate=48000)\n\n audio_codec_configuration = bitmovin.codecConfigurations.AAC.create(audio_codec_configuration).resource\n\n video_input_stream = StreamInput(input_id=s3_input.id,\n input_path=S3_INPUT_PATH,\n selection_mode=SelectionMode.AUTO)\n audio_input_stream = StreamInput(input_id=s3_input.id,\n input_path=S3_INPUT_PATH,\n selection_mode=SelectionMode.AUTO)\n\n # With the configurations and the input file streams are now created and muxed later on.\n for encoding_config in encoding_configs:\n encoding_profile = encoding_config.get(\"profile_h264\")\n video_stream_condition = Condition(attribute=\"HEIGHT\", operator=\">=\", value=str(encoding_profile.get('height')))\n video_stream_h264 = Stream(codec_configuration_id=encoding_config.get(\"h264_codec\").id,\n input_streams=[video_input_stream],\n conditions=video_stream_condition,\n name='Stream H264 {}p_{}k'.format(encoding_profile.get('height'),\n encoding_profile.get('bitrate')))\n\n encoding_config['h264_stream'] = bitmovin.encodings.Stream.create(object_=video_stream_h264,\n encoding_id=encoding.id).resource\n\n audio_stream = Stream(codec_configuration_id=audio_codec_configuration.id,\n input_streams=[audio_input_stream],\n name='Sample Stream AUDIO')\n\n audio_stream = bitmovin.encodings.Stream.create(object_=audio_stream, encoding_id=encoding.id).resource\n\n for encoding_config in encoding_configs:\n encoding_profile = encoding_config.get(\"profile_h264\")\n video_muxing_stream_h264 = MuxingStream(encoding_config.get(\"h264_stream\").id)\n video_muxing_output_h264 = EncodingOutput(output_id=s3_output.id, output_path=OUTPUT_BASE_PATH, acl=[acl_entry])\n\n video_muxing_h264 = MP4Muxing(filename='video_{}p.ismv'.format(encoding_profile.get('height')),\n fragment_duration=4000,\n streams=[video_muxing_stream_h264],\n outputs=[video_muxing_output_h264],\n name='Sample Muxing {}p'.format(encoding_profile.get('height')))\n\n encoding_config['h264_muxing'] = bitmovin.encodings.Muxing.MP4.create(object_=video_muxing_h264,\n encoding_id=encoding.id).resource\n\n playready_drm = PlayReadyDRM(key_seed=PLAYREADY_KEYSEED,\n kid=PLAYREADY_KID,\n method=PlayReadyMethod.PIFF_CTR,\n la_url=PLAYREADY_LA_URL,\n outputs=[video_muxing_output_h264],\n name=\"PlayReady\")\n\n encoding_config['playready_drm'] = bitmovin.encodings.Muxing.MP4.DRM.PlayReady.create(object_=playready_drm,\n encoding_id=encoding.id,\n muxing_id=encoding_config['h264_muxing'].id).resource\n\n audio_muxing_stream = MuxingStream(audio_stream.id)\n audio_muxing_output = EncodingOutput(output_id=s3_output.id, output_path=OUTPUT_BASE_PATH, acl=[acl_entry])\n\n audio_muxing = MP4Muxing(filename='audio.isma',\n fragment_duration=4000,\n streams=[audio_muxing_stream],\n outputs=[audio_muxing_output],\n name='Sample Muxing AUDIO')\n\n audio_muxing = bitmovin.encodings.Muxing.MP4.create(object_=audio_muxing, encoding_id=encoding.id).resource\n\n playready_audio = PlayReadyDRM(key_seed=PLAYREADY_KEYSEED,\n kid=PLAYREADY_KID,\n method=PlayReadyMethod.PIFF_CTR,\n la_url=PLAYREADY_LA_URL,\n outputs=[audio_muxing_output],\n name='PlayReady')\n\n playready_audio = bitmovin.encodings.Muxing.MP4.DRM.PlayReady.create(object_=playready_audio,\n encoding_id=encoding.id,\n muxing_id=audio_muxing.id).resource\n\n bitmovin.encodings.Encoding.start(encoding_id=encoding.id)\n\n try:\n bitmovin.encodings.Encoding.wait_until_finished(encoding_id=encoding.id)\n except BitmovinError as bitmovin_error:\n print(\"Exception occurred while waiting for encoding to finish: {}\".format(bitmovin_error))\n\n manifest_output = EncodingOutput(output_id=s3_output.id,\n output_path=OUTPUT_BASE_PATH,\n acl=[acl_entry])\n\n smooth_manifest = SmoothManifest(server_manifest_name='example_manifest_smooth.ism',\n client_manifest_name='example_manifest_smooth.ismc',\n outputs=[manifest_output],\n name='Sample SmoothStreaming Manifest')\n smooth_manifest = bitmovin.manifests.Smooth.create(object_=smooth_manifest).resource\n\n for encoding_config in encoding_configs:\n encoding_profile = encoding_config.get(\"profile_h264\")\n muxing = encoding_config.get('h264_muxing')\n mp4_representation = MP4Representation(encoding_id=encoding.id,\n muxing_id=muxing.id,\n media_file='video_{}p.ismv'.format(encoding_profile.get('height')))\n\n encoding_config['h264_smooth'] = bitmovin.manifests.Smooth.MP4Representation.create(manifest_id=smooth_manifest.id,\n object_=mp4_representation)\n\n mp4_representation_audio = MP4Representation(encoding_id=encoding.id,\n muxing_id=audio_muxing.id,\n media_file='audio.isma')\n\n bitmovin.manifests.Smooth.MP4Representation.create(manifest_id=smooth_manifest.id, object_=mp4_representation_audio)\n\n content_protection = SmoothContentProtection(encoding_id=encoding.id,\n muxing_id=audio_muxing.id,\n drm_id=playready_audio.id)\n\n bitmovin.manifests.Smooth.ContentProtection.create(object_=content_protection, manifest_id=smooth_manifest.id)\n\n bitmovin.manifests.Smooth.start(manifest_id=smooth_manifest.id)\n\n try:\n bitmovin.manifests.Smooth.wait_until_finished(manifest_id=smooth_manifest.id)\n except BitmovinError as bitmovin_error:\n print(\"Exception occurred while waiting for Smooth manifest creation to finish: {}\".format(bitmovin_error))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/encoding/create_simple_mp4_smooth_playready_encoding.py","file_name":"create_simple_mp4_smooth_playready_encoding.py","file_ext":"py","file_size_in_byte":10832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"387497506","text":"#!/usr/bin/python3\n''' Project for studying doctest in python '''\n\n\ndef print_square(size):\n '''Function that prints a square'''\n\n if not isinstance(size, int):\n raise TypeError(\"size must be an integer\")\n\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n\n for _ in range(size):\n print('#' * size)\n","sub_path":"0x07-python-test_driven_development/4-print_square.py","file_name":"4-print_square.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"329847943","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport time\nimport csv\n\nclass GeneticAlgorithm(object):\n def __init__(self, pop_size, gen_size, mutation_rate, crossover_rate, epochs):\n self.pop_size = pop_size # no.chromosomes selected\n self.gen_size = gen_size # no.variables = 50\n # self.K = K # no.mem/tournament\n self.mutation_rate = mutation_rate # mutation rate\n self.crossover_rate = crossover_rate # crossover_rate\n self.epochs = epochs\n\n def initial_population(self):\n pop = [np.random.uniform(-10, 10, self.gen_size) for _ in range(0, self.pop_size)] \n pop = np.array(pop)\n return pop # initial population\n\n # fitness function: pop_size (array: sum)\n def get_fitness(self, pop):\n fitness = np.zeros((self.pop_size, 1))\n for i in range(0, self.pop_size):\n sum = 0\n # print(pop[i])\n for j in range(0, self.gen_size):\n if (j % 2 == 0):\n sum += pop[i, j] ** 2\n else:\n sum += pop[i, j] ** 3\n fitness[i] = sum\n return fitness\n\n # get best chromo\n def get_best(self, fitness):\n return min(fitness)\n\n # select parent by fitness\n def tournament_selection(self, fitness):\n i = random.randint(0, self.pop_size - 1)\n j = random.randint(0, self.pop_size - 1)\n while (i == j):\n j = random.randint(0, self.pop_size - 1)\n\n if (fitness[i] < fitness[j]):\n return i\n else:\n return j\n \n # pop = [x1, x2, ... ,x50]\n def select_parents(self, pop, fitness):\n parents = np.zeros((self.pop_size, self.gen_size))\n for i in range(0, self.pop_size):\n parents[i] = pop[self.tournament_selection(fitness)]\n return parents\n\n # par1, par2 = [x1, x2, ... ,x50]\n def crossover_OX1(self, par1, par2):\n f = np.random.random_sample()\n if (f < self.crossover_rate):\n cp1 = random.randint(1, self.gen_size - 2)\n cp2 = random.randint(1, self.gen_size - 2)\n while (cp1 >= cp2):\n cp1 = random.randint(1, self.gen_size - 2)\n cp2 = random.randint(1, self.gen_size - 2)\n \n child = np.zeros((1, self.gen_size))\n child[0, cp1:cp2+1] = par1[cp1:cp2+1]\n\n temp = np.zeros((1, self.gen_size))\n id = 0\n for i in range(cp2+1, self.gen_size):\n if (par2[i] not in par1[cp1:cp2+1]):\n temp[0, id] = par2[i]\n id += 1 \n for i in range(cp2+1):\n if (par2[i] not in par1[cp1:cp2+1]):\n temp[0, id] = par2[i]\n id += 1 \n k = self.gen_size - cp2 - 1\n child[0, cp2+1:] = temp[0, :k]\n child[0, :cp1] = temp[0, k:k + cp1]\n return child\n else:\n return par1\n\n # mutation with random resetting \n def random_resetting(self, child):\n f = np.random.random_sample()\n if (f < self.mutation_rate):\n index = random.randint(0, self.gen_size - 1)\n num = np.random.uniform(-10, 10, 1)\n child[index] = num\n return child\n\n def creat_child(self, parents):\n child = np.zeros((self.pop_size, self.gen_size))\n for k in range(self.pop_size):\n i = random.randint(0, self.pop_size - 1)\n j = random.randint(0, self.pop_size - 1)\n while (i == j):\n j = random.randint(0, self.pop_size - 1)\n child[k, :] = self.crossover_OX1(parents[i], parents[j])\n \n for k in range(0, self.pop_size):\n child[k] = self.random_resetting(child[k])\n return child\n\n def draw_chart(self, Epochs, TS_OX1_RS, mean_time, score):\n plt.plot(Epochs, TS_OX1_RS, 'r-')\n plt.axis([0, self.epochs, -25000, 25000])\n plt.xlabel('Epochs')\n plt.ylabel('Best score')\n plt.text(1800, 10000, str(mean_time))\n plt.text(1800, 8000, str(score))\n plt.show()\n\n def implement_with_RS(self, pop):\n sta_time = []\n best = []\n \n Epochs = np.arange(1, self.epochs + 1, dtype=int)\n Epochs = np.reshape(Epochs, (self.epochs, 1))\n TS_OX1_RS = np.zeros((self.epochs, 1), dtype=float)\n\n fitness = self.get_fitness(pop)\n parents = self.select_parents(pop, fitness)\n with open('D:\\\\Lab609\\\\GeneticAlgorithm\\\\TS_OX1_RS.csv', 'w') as csvfile:\n fieldnames = ['Epochs', 'TS_OX1_RS']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for id in range(0, self.epochs):\n start = time.clock()\n child = np.zeros((self.pop_size, self.gen_size))\n child = self.creat_child(parents)\n \n self.pop_size = self.pop_size\n child_score = self.get_fitness(child)\n best_score = self.get_best(child_score)\n TS_OX1_RS[id] = best_score\n\n fitness = self.get_fitness(child)\n parents = self.select_parents(child, fitness)\n \n writer.writerow({'Epochs' : Epochs[id,0], 'TS_OX1_RS' : TS_OX1_RS[id,0]})\n\n time_waste = time.clock() - start\n sta_time.append(time_waste)\n best.append(best_score)\n \n print(\"Iteration: \", id + 1, \", best score: \", best_score, \", time: \",time_waste)\n \n mean_time = sum(sta_time)/len(sta_time)\n score = min(best)\n\n # draw chart\n self.draw_chart(Epochs, TS_OX1_RS, mean_time, score)\n\nif __name__ == \"__main__\":\n pop_size = 100\n gen_size = 50\n mutation_rate = 0.03\n crossover_rate = 0.65#0.9\n epochs = 3000\n GA = GeneticAlgorithm(pop_size, gen_size, mutation_rate, crossover_rate, epochs)\n population = GA.initial_population()\n GA.implement_with_RS(population)","sub_path":"anh_duc/week1/GA_with_TS_OX1_RS.py","file_name":"GA_with_TS_OX1_RS.py","file_ext":"py","file_size_in_byte":6113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"253924720","text":"from __future__ import absolute_import\n\nfrom datetime import datetime\n\nfrom flask import current_app\nimport mock\n\nfrom changes.config import db\nfrom changes.constants import Result, Status\nfrom changes.testutils import TestCase\nfrom changes.models import FailureReason\nfrom changes.listeners.analytics_notifier import (\n build_finished_handler, _get_phabricator_revision_url, _get_failure_reasons\n)\n\n\ndef ts_to_datetime(ts):\n return datetime.utcfromtimestamp(ts)\n\n\nclass AnalyticsNotifierTest(TestCase):\n\n def setUp(self):\n super(AnalyticsNotifierTest, self).setUp()\n\n def _set_config_url(self, url):\n current_app.config['ANALYTICS_POST_URL'] = url\n\n @mock.patch('changes.listeners.analytics_notifier.post_build_data')\n def test_no_url(self, post_fn):\n self._set_config_url(None)\n project = self.create_project(name='test', slug='test')\n build = self.create_build(project, result=Result.failed)\n build_finished_handler(build_id=build.id.hex)\n self.assertEquals(post_fn.call_count, 0)\n\n @mock.patch('changes.listeners.analytics_notifier.post_build_data')\n def test_failed_build(self, post_fn):\n URL = \"https://analytics.example.com/report?source=changes\"\n self._set_config_url(URL)\n project = self.create_project(name='test', slug='project-slug')\n self.assertEquals(post_fn.call_count, 0)\n duration = 1234\n created = 1424998888\n started = created + 10\n finished = started + duration\n\n build = self.create_build(project, result=Result.failed, target='D1',\n label='Some sweet diff', duration=duration,\n date_created=ts_to_datetime(created), date_started=ts_to_datetime(started),\n date_finished=ts_to_datetime(finished))\n\n job = self.create_job(build=build, result=Result.failed)\n jobphase = self.create_jobphase(job)\n jobstep = self.create_jobstep(jobphase, status=Status.finished, result=Result.failed)\n db.session.add(FailureReason(step_id=jobstep.id, job_id=job.id, build_id=build.id, project_id=project.id,\n reason='missing_tests'))\n db.session.commit()\n\n with mock.patch('changes.listeners.analytics_notifier._get_phabricator_revision_url') as mock_get_phab:\n mock_get_phab.return_value = 'https://example.com/D1'\n with mock.patch('changes.listeners.analytics_notifier._get_failure_reasons') as mock_get_failures:\n mock_get_failures.return_value = ['aborted', 'missing_tests']\n build_finished_handler(build_id=build.id.hex)\n\n expected_data = {\n 'build_id': build.id.hex,\n 'number': 1,\n 'target': 'D1',\n 'project_slug': 'project-slug',\n 'result': 'Failed',\n 'label': 'Some sweet diff',\n 'is_commit': True,\n 'duration': 1234,\n 'date_created': created,\n 'date_started': started,\n 'date_finished': finished,\n 'phab_revision_url': 'https://example.com/D1',\n 'failure_reasons': ['aborted', 'missing_tests'],\n }\n post_fn.assert_called_once_with(URL, expected_data)\n\n def test_get_failure_reasons_no_failures(self):\n project = self.create_project(name='test', slug='project-slug')\n build = self.create_build(project, result=Result.passed, target='D1',\n label='Some sweet diff')\n self.assertEquals(_get_failure_reasons(build), [])\n\n def test_get_failure_reasons_multiple_failures(self):\n project = self.create_project(name='test', slug='project-slug')\n build = self.create_build(project, result=Result.failed, target='D1',\n label='Some sweet diff')\n job = self.create_job(build=build, result=Result.failed)\n jobphase = self.create_jobphase(job)\n jobstep = self.create_jobstep(jobphase, status=Status.finished, result=Result.failed)\n for reason in ('missing_tests', 'timeout', 'aborted'):\n db.session.add(FailureReason(step_id=jobstep.id, job_id=job.id, build_id=build.id, project_id=project.id,\n reason=reason))\n jobstep2 = self.create_jobstep(jobphase, status=Status.finished, result=Result.failed)\n for reason in ('timeout', 'insufficient_politeness'):\n db.session.add(FailureReason(step_id=jobstep2.id, job_id=job.id, build_id=build.id, project_id=project.id,\n reason=reason))\n db.session.commit()\n\n self.assertEquals(_get_failure_reasons(build),\n ['aborted', 'insufficient_politeness', 'missing_tests', 'timeout'])\n\n def test_get_phab_revision_url_diff(self):\n project = self.create_project(name='test', slug='test')\n source_data = {'phabricator.revisionURL': 'https://tails.corp.dropbox.com/D6789'}\n source = self.create_source(project, data=source_data)\n build = self.create_build(project, result=Result.failed, source=source, message='Some commit')\n self.assertEquals(_get_phabricator_revision_url(build), 'https://tails.corp.dropbox.com/D6789')\n\n def test_get_phab_revision_url_commit(self):\n project = self.create_project(name='test', slug='test')\n source_data = {}\n source = self.create_source(project, data=source_data)\n msg = \"\"\"\n Some fancy commit.\n\n Summary: Fixes T33417.\n\n Test Plan: Added tests.\n\n Reviewers: mickey\n\n Reviewed By: mickey\n\n Subscribers: changesbot\n\n Maniphest Tasks: T33417\n\n Differential Revision: https://tails.corp.dropbox.com/D6789\"\"\"\n build = self.create_build(project, result=Result.failed, source=source, message=msg)\n self.assertEquals(_get_phabricator_revision_url(build), 'https://tails.corp.dropbox.com/D6789')\n\n def test_get_phab_revision_url_commit_conflict(self):\n project = self.create_project(name='test', slug='test')\n source_data = {}\n source = self.create_source(project, data=source_data)\n msg = \"\"\"\n Some fancy commit.\n\n Summary: Fixes T33417.\n Adds messages like:\n Differential Revision: https://tails.corp.dropbox.com/D1234\n\n Test Plan: Added tests.\n\n Reviewers: mickey\n\n Reviewed By: mickey\n\n Subscribers: changesbot\n\n Maniphest Tasks: T33417\n\n Differential Revision: https://tails.corp.dropbox.com/D6789\"\"\"\n build = self.create_build(project, result=Result.failed, source=source, message=msg)\n self.assertEquals(_get_phabricator_revision_url(build), None)\n\n def test_get_phab_revision_url_no_message(self):\n project = self.create_project(name='test', slug='test')\n source_data = {}\n source = self.create_source(project, data=source_data)\n build = self.create_build(project, result=Result.failed, source=source, message=None)\n self.assertEquals(_get_phabricator_revision_url(build), None)\n","sub_path":"tests/changes/listeners/test_analytics_notifier.py","file_name":"test_analytics_notifier.py","file_ext":"py","file_size_in_byte":7161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"231797449","text":"import cv2\nimport numpy as np\nimport random\n\nO = np.ones((256,256,1,1))\nZ = np.zeros((256,256,1,1))\n\nA = np.expand_dims(cv2.imread('./I_sharp.png'),axis=3) / 255\nB = np.expand_dims(cv2.imread('./I_blurred.png'),axis=3) / 255\n\nR = np.concatenate((Z,Z,O),axis=2)\nG = np.concatenate((Z,O,Z),axis=2)\n\ndata = np.concatenate((A,B,R,G),axis=3)\n\nwhile(1):\n\tidx = random.randint(0,3)\n\n\tframe = data[:,:,:,idx]\n\n\tcv2.imshow('Frame', frame)\n\n\tif cv2.waitKey(500) & 0xFF == ord('q'):\n\t\tbreak\n","sub_path":"python/generateTest.py","file_name":"generateTest.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"557074781","text":"# -*- coding: utf-8 -*-\n\nfrom flask import jsonify, make_response, current_app\nfrom flask.ext.restful import Resource\nfrom module.user.user import User as UserModel\nfrom module.user.userinfo import UserInfo as UserInfoModel\nfrom module.user.useralipay import UserAlipay\nfrom module.user.user_wechat import UserWechat\nfrom flask.ext.login import current_user\nfrom control.pp import logit\nfrom control.ErrorMessages import ErrorMessages as errMsgs\nfrom view.tools.tools import sendException\n\n\nclass MyUserInfo(Resource):\n\n @logit\n def get(self):\n try:\n if current_user.is_authenticated():\n uid = current_user.id\n user = UserModel.query.get(uid)\n info = UserInfoModel.query.filter_by(uid=uid).first()\n alipay = UserAlipay.query.filter_by(\n uid=uid, isValid=True).first()\n alipay_acct = alipay.alipay_account if alipay else ''\n wechat = UserWechat.query.filter_by(uid=uid).first()\n wechat_acct = wechat.wechat_openid if wechat else ''\n\n if user and info:\n userlist = {\n 'id': user.id,\n 'nickname': user.nickname,\n 'email': user.email,\n 'avatar': info.avatar,\n 'alipay_acct': alipay_acct,\n 'wechat_acct': wechat_acct\n }\n return make_response(jsonify({\"user\": userlist}), 200)\n make_response(jsonify({'messages': errMsgs.NOT_EXIST}), 404)\n return make_response(jsonify({'messages': errMsgs.NOT_LOGIN}), 401)\n except Exception as e:\n current_app.logger.exception('MyUserInfo get()')\n sendException(e, 'MyUserInfo get()')\n return make_response(jsonify({'messages': errMsgs.SERVER_ERROR}), 500)\n","sub_path":"api/user/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"544834155","text":"import newspaper\nfrom newspaper import Article\nimport os\nfrom queue import Queue\nimport json\nimport time\nfrom fake_useragent import UserAgent\nimport telnetlib\nimport random\nimport requests\nimport pymysql\n\n\nclass NewsSpider:\n\n def __init__(self):\n self.current_path = os.path.dirname(__file__)\n self.main_url_file = 'platform list.txt'\n self.file_path = os.path.join(self.current_path, self.main_url_file)\n self.news_paper_size = None\n self.news_brand = None\n self.Article_detas_list = None\n self.user_agent_list = None\n self.ip_address_list = None\n self.Article_details = {}\n self.connet_mysql = None\n self.cursor_db = None\n self.art_url = None \n self.article_url_queue = Queue()\n\n # # if platform list.txt is empty, get populate url list and write into the file\n def url_path(self):\n if os.path.getsize(self.file_path) == 0:\n with open(self.file_path, \"w+\", encoding=\"utf-8\") as uf:\n popular_urls_list= newspaper.popular_urls()\n for i in range(len(popular_urls_list)):\n uf.write(popular_urls_list[i])\n uf.write(\"\\n\")\n print(\"populate url list have worte\")\n\n # get different platform url\n def platform_url_list(self):\n platform_list = []\n with open(self.file_path, \"r\", encoding=\"utf-8\") as f:\n for line in f:\n line = line.strip()\n print(line)\n platform_list.append(line)\n print(platform_list)\n return platform_list\n print(\"*******end of get platform_url*********\")\n # build source and get articles urls\n\n def articles_url_list(self,plat_url_list):\n print(\"*******start get articles_url*********\")\n for platfrom_url in plat_url_list:\n news_paper = newspaper.build(platfrom_url,memoize_articles=False) #got all\n# news_paper = newspaper.build(platfrom_url) # got from start\n for article in news_paper.articles:\n article_list = []\n self.news_brand = news_paper.brand\n article_list.append(self.news_brand)\n article_list.append(article.url)\n print(article_list)\n self.article_url_queue.put(article_list)\n print(\"have got\", self.news_brand, news_paper.size(), \"articles'\")\n print(\"*******end of get articles_url*********\")\n\n # download articles and parse\n def parse_article(self):\n print(\"*******start of parse article*********\")\n self.user_agent_list = self.User_Agent()\n# self.ip_address_list = self.get_ip_address()\n self.connect_mysql()\n while not self.article_url_queue.empty():\n article_url = self.article_url_queue.get()\n print(article_url[1])\n self.art_url=article_url[1]\n verfity_result = self.verfity_art_url(article_url[1])\n if verfity_result == 200:\n print(\"sleep 3 secs\")\n time.sleep(3)\n Article_html = Article(url=article_url[1])\n try:\n Article_html.download()\n except Exception:\n print(\"error in url\",Article_html)\n continue\n else:\n Article_html.parse()\n self.Article_details = {}\n self.Article_details[\"class\"] = article_url[0]\n self.Article_details[\"title\"] = Article_html.title if len(Article_html.title) > 0 else ' '\n self.Article_details[\"top_image\"] = Article_html.top_image if len(Article_html.top_image) > 0 else ' '\n self.Article_details[\"author\"] = Article_html.authors if len(Article_html.authors) > 0 else ' '\n self.Article_details[\"Image_list\"] = Article_html.images if len(Article_html.images) > 0 else ' '\n self.Article_details[\"Videos\"] = Article_html.movies if len(Article_html.movies) > 0 else ' '\n self.Article_details[\"Text\"] = Article_html.text if len(Article_html.text) > 0 else ' '\n if self.Article_details[\"Text\"] and self.Article_details[\"title\"] is not ' ':\n Article_html.nlp()\n self.Article_details[\"summary\"] = Article_html.summary if len(Article_html.summary) > 0 else ' '\n self.Article_details[\"keywords\"] = Article_html.keywords if len(Article_html.keywords) > 0 else ' '\n else:\n self.Article_details[\"summary\"] = ' '\n self.Article_details[\"keywords\"] = ' '\n print(self.Article_details)\n# self.save_data(Article_details)\n self.save_into_db()\n else:\n print(\"invalid article, pass\")\n self.article_url_queue.task_done()\n print(\"*******end of get parse_article*********\")\n\n def User_Agent(self):\n ua = UserAgent(verify_ssl=False)\n print(\"got UserAgent\")\n return ua\n\n def verfity_art_url(self,article_url):\n user_agent = self.user_agent_list.random\n headers = {\"user-agent\":user_agent}\n print(headers)\n url = article_url\n response = requests.get(url=url, headers=headers, timeout=5)\n print(response.status_code)\n return response.status_code\n\n def connect_mysql(self):\n self.connet_mysql = pymysql.connect(host='127.0.0.1',\n user='root',\n password ='Max13579',\n db ='newsdata',\n port = 3306,\n charset='utf8')\n self.cursor = self.connet_mysql.cursor()\n print(\"connected to MySQL DB\")\n\n # save article data, use mysqldb to repleace txt\n# def save_data(self,Article_detas):\n# print(\"*******start save_data*********\")\n# file_path = os.path.join(self.current_path ,'news details.txt')\n# with open(file_path, \"a\", encoding=\"utf-8\") as pf:\n# # for content in Article_detas_list:\n# details = str(Article_detas)\n# pf.write(json.dumps(details, ensure_ascii=False, indent=1))\n# pf.write(\"\\n\")\n# print(\"saved successfully\")\n\n def save_into_db(self):\n sql = 'insert into news_content(news_platform,news_title,news_top_image_url,news_author,news_image_list,news_videos,news_text,news_summary,news_keywords,news_url) values(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")' \\\n %(pymysql.escape_string(self.Article_details[\"class\"]),\n pymysql.escape_string(self.Article_details[\"title\"]),\n pymysql.escape_string(self.Article_details[\"top_image\"]),\n self.Article_details[\"author\"],\n self.Article_details[\"Image_list\"],\n pymysql.escape_string(self.Article_details[\"Videos\"]),\n pymysql.escape_string(self.Article_details[\"Text\"]),\n pymysql.escape_string(self.Article_details[\"summary\"]),\n self.Article_details[\"keywords\"],\n pymysql.escape_string(self.art_url))\n print(sql)\n try:\n self.cursor.execute(sql)\n self.connet_mysql.commit()\n except:\n print(\"*****************************error at sql %s while save data into DB\" %sql)\n\n # main logic:\n def run(self):\n self.url_path()\n # 1. prepare url list for different platform\n plat_url_list = self.platform_url_list()\n # 2. according to the different platform to get all the articles url\n self.articles_url_list(plat_url_list)\n # 3. parse url and get article details and parse it. at last save article details into DB\n self.parse_article()\n # 4. close DB\n self.cursor.close()\n self.connet_mysql.close()\n\nif __name__ == '__main__':\n NewsSpider = NewsSpider()\n NewsSpider.run()\n","sub_path":"News_Spider.py","file_name":"News_Spider.py","file_ext":"py","file_size_in_byte":8156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"372653015","text":"#!/usr/bin/env python\nimport random\nimport rclpy\nimport sys\n\nfrom rclpy.executors import MultiThreadedExecutor\nfrom rclpy.callback_groups import MutuallyExclusiveCallbackGroup\nfrom suave.task_bridge_none import TaskBridgeNone\nfrom system_modes_msgs.srv import ChangeMode\nfrom system_modes_msgs.srv import GetAvailableModes\n\n\nclass TaskBridgeRandom(TaskBridgeNone):\n def __init__(self):\n super().__init__()\n\n self.declare_parameter('adaptation_period', 15)\n self.adaptation_period = self.get_parameter('adaptation_period').value\n\n self.generate_path_modes_cli = self.create_client(\n GetAvailableModes,\n '/f_generate_search_path/get_available_modes',\n callback_group=self.client_cb_group)\n\n self.follow_pipeline_modes_cli = self.create_client(\n GetAvailableModes,\n '/f_follow_pipeline/get_available_modes',\n callback_group=self.client_cb_group)\n\n self.available_modes_cli = {\n 'f_generate_search_path': self.generate_path_modes_cli,\n 'f_follow_pipeline': self.follow_pipeline_modes_cli,\n }\n\n self.reasoner_timer = self.create_timer(\n self.adaptation_period,\n self.reasoner_cb,\n callback_group=self.task_cb_group\n )\n\n def reasoner_cb(self):\n for task_name in self.current_tasks:\n function_names = self.task_functions_dict[task_name]\n for function in function_names:\n self.forward_task_request(function)\n\n def forward_task_request(self, function):\n modes_cli = self.available_modes_cli[function]\n mode_name = random.choice(\n self.call_service(\n modes_cli, GetAvailableModes.Request()).available_modes\n )\n\n cli = self.sm_cli_dict[function]\n return self.call_sysmode_change_mode(function, mode_name)\n\n\ndef main():\n print('Starting random task bridge node')\n\n rclpy.init(args=sys.argv)\n\n task_bridge_node = TaskBridgeRandom()\n\n executor = MultiThreadedExecutor()\n rclpy.spin(task_bridge_node, executor=executor)\n\n task_bridge_node.destroy_node()\n rclpy.shutdown()\n","sub_path":"suave_metacontrol/suave_metacontrol/task_bridge_random.py","file_name":"task_bridge_random.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"179304489","text":"################################################################################\n# Modules and functions import statements\n################################################################################\n\nimport logging\nimport sys\n\nfrom flask import url_for, get_flashed_messages\nfrom helpers.app_runtime import jinja2_env, app_settings\n\n################################################################################\n# Functions\n################################################################################\n\ndef get_model(cookie_json=None):\n caller = sys._getframe(1) # '_getframe(1)' gets previous stack; \n # '_getframe()' gets current stack\n caller_name = caller.f_code.co_name # returns 'view_home'\n module_name = caller.f_globals['__name__'] # returns 'modules.default_routes'\n package_name = caller.f_globals['__package__'] # returns 'modules'\n\n context = cookie_json if cookie_json is not None else {}\n context['url_for'] = url_for # function for Flask\n context['get_flashed_messages'] = get_flashed_messages # function for Flask\n context['app_settings'] = app_settings # make application settings available\n context['view_name'] = caller_name\n context['view_module'] = module_name\n context['view_package'] = package_name\n context['view_id'] = \"{0}.{1}\".format(module_name, caller_name)\n\n # context['auth_cookie'] = request.cookies.get(appconfig[\"application\"][\"auth_cookie_name\"])\n # context['current_datetime'] = datetime.now()\n # context = {\n # 'auth_cookie' : request.cookies.get(appconfig[\"application\"][\"auth_cookie_name\"]),\n # 'current_datetime' : datetime.now()\n # }\n return context\n\ndef view(model=None, view_path=None):\n if view_path is None:\n caller = sys._getframe(1) # '_getframe(1)' gets previous stack; \n # '_getframe()' gets current stack\n caller_name = caller.f_code.co_name # returns 'view_home'\n module_name = caller.f_globals['__name__'] # returns 'modules.default_routes'\n package_name = caller.f_globals['__package__'] # returns 'modules'\n\n view_path = module_name.split('.')\n view_path.remove(package_name)\n view_path.append(\"{0}.html\".format(caller_name))\n view_path = '/'.join(view_path) # returns 'default_routes/view_home.html\n\n logging.info(\"fetching view [{0}]\".format(view_path))\n\n if model is None:\n model = get_model()\n\n return jinja2_env.get_template(view_path).render(model)\n\n################################################################################\n# Export module variables\n################################################################################\n \n # N/A\n\n################################################################################\n# Main function\n################################################################################\n\nif __name__ == '__main__':\n pass\n","sub_path":"google-cloud/hci/public-web/helpers/app_helper.py","file_name":"app_helper.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"357720103","text":"# 客户端\n'''\nclient端流程\n1, 建立通信socket\n2, 发送内容到指定服务器\n3, 接受服务器给定的反馈内容\n'''\nimport socket\n\ndef clientFunc():\n sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n # 给服务器发送\n text = \"i love china\"\n\n # 发送的娥数据必须用bytes格式\n data = text.encode()\n\n # 发送 然后等待\n sock.sendto(data,(\"127.0.0.1\",7852))\n\n # 服务器反馈的内容\n data,addr = sock.recvfrom(500)\n data = data.decode()\n print(data)\n print(addr)\nif __name__ == '__main__':\n clientFunc()","sub_path":"02 高级语法系列/cp net编程/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"212917987","text":"# coding: utf-8\n\n\"\"\"\n Collibra Data Governance Center Core API\n\n The Core REST API allows you to create your own integrations with Collibra Data Governance Center.
Create custom applications to help users get access to the right data.
# noqa: E501\n\n The version of the OpenAPI document: 2.0\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom collibra_core.configuration import Configuration\n\n\nclass AddAssetTypeAssignmentRuleRequest(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'workflow_definition_id': 'str',\n 'asset_type_id': 'str',\n 'domain_id': 'str',\n 'community_id': 'str',\n 'status_id': 'str'\n }\n\n attribute_map = {\n 'workflow_definition_id': 'workflowDefinitionId',\n 'asset_type_id': 'assetTypeId',\n 'domain_id': 'domainId',\n 'community_id': 'communityId',\n 'status_id': 'statusId'\n }\n\n def __init__(self, workflow_definition_id=None, asset_type_id=None, domain_id=None, community_id=None, status_id=None, local_vars_configuration=None): # noqa: E501\n \"\"\"AddAssetTypeAssignmentRuleRequest - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._workflow_definition_id = None\n self._asset_type_id = None\n self._domain_id = None\n self._community_id = None\n self._status_id = None\n self.discriminator = None\n\n self.workflow_definition_id = workflow_definition_id\n self.asset_type_id = asset_type_id\n if domain_id is not None:\n self.domain_id = domain_id\n if community_id is not None:\n self.community_id = community_id\n if status_id is not None:\n self.status_id = status_id\n\n @property\n def workflow_definition_id(self):\n \"\"\"Gets the workflow_definition_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n\n The ID of the workflow definition containing the assignment rule to be added. # noqa: E501\n\n :return: The workflow_definition_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._workflow_definition_id\n\n @workflow_definition_id.setter\n def workflow_definition_id(self, workflow_definition_id):\n \"\"\"Sets the workflow_definition_id of this AddAssetTypeAssignmentRuleRequest.\n\n The ID of the workflow definition containing the assignment rule to be added. # noqa: E501\n\n :param workflow_definition_id: The workflow_definition_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and workflow_definition_id is None: # noqa: E501\n raise ValueError(\"Invalid value for `workflow_definition_id`, must not be `None`\") # noqa: E501\n\n self._workflow_definition_id = workflow_definition_id\n\n @property\n def asset_type_id(self):\n \"\"\"Gets the asset_type_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n\n The ID of the asset type the added rule should refer to. # noqa: E501\n\n :return: The asset_type_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._asset_type_id\n\n @asset_type_id.setter\n def asset_type_id(self, asset_type_id):\n \"\"\"Sets the asset_type_id of this AddAssetTypeAssignmentRuleRequest.\n\n The ID of the asset type the added rule should refer to. # noqa: E501\n\n :param asset_type_id: The asset_type_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and asset_type_id is None: # noqa: E501\n raise ValueError(\"Invalid value for `asset_type_id`, must not be `None`\") # noqa: E501\n\n self._asset_type_id = asset_type_id\n\n @property\n def domain_id(self):\n \"\"\"Gets the domain_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n\n The ID of the domain the assignment rule should apply for. # noqa: E501\n\n :return: The domain_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._domain_id\n\n @domain_id.setter\n def domain_id(self, domain_id):\n \"\"\"Sets the domain_id of this AddAssetTypeAssignmentRuleRequest.\n\n The ID of the domain the assignment rule should apply for. # noqa: E501\n\n :param domain_id: The domain_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :type: str\n \"\"\"\n\n self._domain_id = domain_id\n\n @property\n def community_id(self):\n \"\"\"Gets the community_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n\n The ID of the community the assignment rule should apply for. # noqa: E501\n\n :return: The community_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._community_id\n\n @community_id.setter\n def community_id(self, community_id):\n \"\"\"Sets the community_id of this AddAssetTypeAssignmentRuleRequest.\n\n The ID of the community the assignment rule should apply for. # noqa: E501\n\n :param community_id: The community_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :type: str\n \"\"\"\n\n self._community_id = community_id\n\n @property\n def status_id(self):\n \"\"\"Gets the status_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n\n The ID of the status the assignment rule should apply for. # noqa: E501\n\n :return: The status_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._status_id\n\n @status_id.setter\n def status_id(self, status_id):\n \"\"\"Sets the status_id of this AddAssetTypeAssignmentRuleRequest.\n\n The ID of the status the assignment rule should apply for. # noqa: E501\n\n :param status_id: The status_id of this AddAssetTypeAssignmentRuleRequest. # noqa: E501\n :type: str\n \"\"\"\n\n self._status_id = status_id\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, AddAssetTypeAssignmentRuleRequest):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, AddAssetTypeAssignmentRuleRequest):\n return True\n\n return self.to_dict() != other.to_dict()\n","sub_path":"collibra_core/models/add_asset_type_assignment_rule_request.py","file_name":"add_asset_type_assignment_rule_request.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"436462999","text":"from datetime import datetime, timezone\nfrom decimal import Decimal\nfrom os import environ\nfrom pathlib import Path\nfrom uuid import UUID, uuid4\n\nimport requests\nfrom boto3.dynamodb.conditions import Attr, Key\nfrom connexion import problem\nfrom connexion.apps.flask_app import FlaskJSONEncoder\nfrom flask import jsonify, make_response\nfrom flask_cors import CORS\nfrom jsonschema import draft4_format_checker\n\nfrom hyp3_api import DYNAMODB_RESOURCE, connexion_app\nfrom hyp3_api.openapi import get_spec\nfrom hyp3_api.util import convert_floats_to_decimals, format_time, get_remaining_jobs_for_user, \\\n get_request_time_expression\nfrom hyp3_api.validation import GranuleValidationError, validate_jobs\n\n\nclass DecimalEncoder(FlaskJSONEncoder):\n def default(self, o):\n if isinstance(o, Decimal):\n if o == int(o):\n return int(o)\n return float(o)\n return super(DecimalEncoder, self).default(o)\n\n\n@draft4_format_checker.checks('uuid')\ndef is_uuid(val):\n try:\n UUID(val, version=4)\n except ValueError:\n return False\n return True\n\n\n@connexion_app.app.before_request\ndef check_system_available():\n if environ['SYSTEM_AVAILABLE'] != \"true\":\n message = 'HyP3 is currently unavailable. Please try again later.'\n error = {\n 'detail': message,\n 'status': 503,\n 'title': 'Service Unavailable',\n 'type': 'about:blank'\n }\n return make_response(jsonify(error), 503)\n\n\ndef post_jobs(body, user):\n print(body)\n\n quota = get_user(user)['quota']\n if quota['remaining'] - len(body['jobs']) < 0:\n max_jobs = quota['max_jobs_per_month']\n message = f'Your monthly quota is {max_jobs} jobs. You have {quota[\"remaining\"]} jobs remaining.'\n return problem(400, 'Bad Request', message)\n\n try:\n validate_jobs(body['jobs'])\n except requests.HTTPError as e:\n print(f'WARN: CMR search failed: {e}')\n except GranuleValidationError as e:\n return problem(400, 'Bad Request', str(e))\n\n request_time = format_time(datetime.now(timezone.utc))\n table = DYNAMODB_RESOURCE.Table(environ['JOBS_TABLE_NAME'])\n\n for job in body['jobs']:\n job['job_id'] = str(uuid4())\n job['user_id'] = user\n job['status_code'] = 'PENDING'\n job['request_time'] = request_time\n if not body.get('validate_only'):\n job = convert_floats_to_decimals(job)\n table.put_item(Item=job)\n\n return body\n\n\ndef get_jobs(user, start=None, end=None, status_code=None, name=None):\n table = DYNAMODB_RESOURCE.Table(environ['JOBS_TABLE_NAME'])\n\n key_expression = Key('user_id').eq(user)\n if start is not None or end is not None:\n key_expression &= get_request_time_expression(start, end)\n\n filter_expression = Attr('job_id').exists()\n if status_code is not None:\n filter_expression &= Attr('status_code').eq(status_code)\n if name is not None:\n filter_expression &= Attr('name').eq(name)\n\n response = table.query(\n IndexName='user_id',\n KeyConditionExpression=key_expression,\n FilterExpression=filter_expression,\n )\n return {'jobs': response['Items']}\n\n\ndef get_job_by_id(job_id):\n table = DYNAMODB_RESOURCE.Table(environ['JOBS_TABLE_NAME'])\n response = table.get_item(Key={'job_id': job_id})\n if 'Item' not in response:\n return problem(404, 'Not Found', f'job_id does not exist: {job_id}')\n return response['Item']\n\n\ndef get_names_for_user(user):\n table = DYNAMODB_RESOURCE.Table(environ['JOBS_TABLE_NAME'])\n key_expression = Key('user_id').eq(user)\n response = table.query(\n IndexName='user_id',\n KeyConditionExpression=key_expression,\n )\n names = {record['name'] for record in response['Items'] if 'name' in record}\n return sorted(list(names))\n\n\ndef get_max_jobs_per_month(user):\n table = DYNAMODB_RESOURCE.Table(environ['USERS_TABLE_NAME'])\n response = table.get_item(Key={'user_id': user})\n if 'Item' in response:\n max_jobs_per_month = response['Item']['max_jobs_per_month']\n else:\n max_jobs_per_month = int(environ['MONTHLY_JOB_QUOTA_PER_USER'])\n return max_jobs_per_month\n\n\ndef get_user(user):\n max_jobs = get_max_jobs_per_month(user)\n\n return {\n 'user_id': user,\n 'quota': {\n 'max_jobs_per_month': max_jobs,\n 'remaining': get_remaining_jobs_for_user(user, max_jobs),\n },\n 'job_names': get_names_for_user(user)\n }\n\n\napi_spec_file = Path(__file__).parent / 'api-spec' / 'openapi-spec.yml'\napi_spec = get_spec(api_spec_file)\nconnexion_app.app.json_encoder = DecimalEncoder\nconnexion_app.add_api(api_spec, validate_responses=True, strict_validation=True)\nCORS(connexion_app.app, origins=r'https?://([-\\w]+\\.)*asf\\.alaska\\.edu', supports_credentials=True)\n","sub_path":"apps/api/src/hyp3_api/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":4864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"309460293","text":"\nfrom Networks import *\nfrom torch import optim\nimport torch\nimport time\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nimport numpy as np\nimport torchvision.transforms.functional as TF\n\nclass Sketch_Classification(nn.Module):\n def __init__(self, hp):\n super(Sketch_Classification, self).__init__()\n self.Network = eval(hp.backbone_name + '_Network(hp)')\n self.train_params = self.parameters()\n self.optimizer = optim.Adam(self.train_params, hp.learning_rate)\n self.loss = nn.CrossEntropyLoss()\n self.hp = hp\n self.step = 0\n\n def train_supervised(self, batch, step):\n self.train()\n self.step = step\n self.optimizer.zero_grad()\n output = self.Network(batch['sketch_img'].to(device))\n\n loss = self.loss(output, batch['sketch_label'].to(device))\n loss.backward()\n self.optimizer.step()\n return loss.item()\n\n def train_rotation_self_supervised(self, batch, step):\n\n batch_image_4x = []\n label_4x = []\n for image in batch['sketch_img']:\n batch_image_4x.append(image)\n label_4x.append(0)\n image = TF.normalize(image, mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225],\n std=[1/0.229, 1/0.224, 1/0.225])\n pil_image = TF.to_pil_image(image)\n tensor_rotate = TF.normalize(TF.to_tensor(TF.rotate(pil_image, 90)),\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n batch_image_4x.append(tensor_rotate)\n label_4x.append(1)\n tensor_rotate = TF.normalize(TF.to_tensor(TF.rotate(pil_image, 180)),\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n batch_image_4x.append(tensor_rotate)\n label_4x.append(2)\n tensor_rotate = TF.normalize(TF.to_tensor(TF.rotate(pil_image, 270)),\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n batch_image_4x.append(tensor_rotate)\n label_4x.append(3)\n\n random_indices = torch.randperm(len(label_4x))\n batch_image_4x = torch.stack(batch_image_4x)[random_indices]\n label_4x = torch.tensor(label_4x)[random_indices]\n\n self.train()\n self.step = step\n self.optimizer.zero_grad()\n output = self.Network(batch_image_4x.to(device))\n loss = self.loss(output, label_4x.to(device))\n loss.backward()\n self.optimizer.step()\n return loss.item()\n\n\n def fine_tune_linear(self, datloader_Train, datloader_Test):\n self.freeze_weights()\n\n Train_Image_Feature = {}\n Train_Image_Label = []\n\n Test_Image_Feature = {}\n Test_Image_Label = []\n\n start_time = time.time()\n self.eval()\n\n with torch.no_grad():\n\n for i_batch, sampled_batch in enumerate(datloader_Train):\n sketch_feature = self.Network.extract_features(sampled_batch['sketch_img'].to(device))\n if not Train_Image_Feature:\n for key in list(sketch_feature.keys()):\n Train_Image_Feature[key] = []\n for key in list(sketch_feature.keys()):\n Train_Image_Feature[key].extend(sketch_feature[key].detach())\n Train_Image_Label.extend(sampled_batch['sketch_label'])\n if i_batch%50 == 0:\n print('Extracting Training Features:' + str(i_batch) + '/' + str(len(datloader_Train)))\n\n\n for i_batch, sampled_batch in enumerate(datloader_Test):\n sketch_feature = self.Network.extract_features(sampled_batch['sketch_img'].to(device))\n if not Test_Image_Feature:\n for key in list(sketch_feature.keys()):\n Test_Image_Feature[key] = []\n for key in list(sketch_feature.keys()):\n Test_Image_Feature[key].extend(sketch_feature[key].detach())\n Test_Image_Label.extend(sampled_batch['sketch_label'])\n if i_batch%50 == 0:\n print('Extracting Testing Features: ' + str(i_batch) + '/' + str(len(datloader_Test)))\n\n Train_Image_Label, Test_Image_Label = torch.tensor(Train_Image_Label).to(device), torch.tensor(Test_Image_Label).to(device)\n save_result = []\n\n for i_key, key in enumerate(list(Train_Image_Feature.keys())[::-1]):\n\n Train_Feature, Test_Feature = torch.stack(Train_Image_Feature[key]), torch.stack(Test_Image_Feature[key])\n model = nn.Linear(Train_Feature.shape[1], 250).to(device)\n optimizer = optim.Adam(model.parameters(), 0.0001)\n\n max_epoch_finetune = [50, 200, 300, 400]\n batch_finetune = 128\n step = 0\n best_accuracy = 0\n\n for epoch in range(max_epoch_finetune[i_key]):\n\n for idx in range(len(Train_Feature) // batch_finetune):\n step = step + 1\n optimizer.zero_grad()\n batch_train_feature = Train_Feature[idx * batch_finetune: (idx + 1) * batch_finetune]\n batch_train_label = Train_Image_Label[idx * batch_finetune: (idx + 1) * batch_finetune]\n output = model(batch_train_feature)\n loss = F.cross_entropy(output, batch_train_label)\n loss.backward()\n optimizer.step()\n\n if step%100 == 0:\n prediction = output.argmax(dim=1, keepdim=True)\n bacth_accuracy = prediction.eq(batch_train_label.view_as(prediction)).sum().item()\n print('@FineTuning: {}, Epoch: {}, Steps: {}, Iter: {}, Loss: {}, '\n 'Train Accuracy: {}, Max Test Accuracy: {}'.format(key, epoch, step, idx, loss,\n bacth_accuracy/batch_finetune*100, best_accuracy))\n\n if step%1000 == 0:\n output = model(Test_Feature)\n prediction = output.argmax(dim=1, keepdim=True)\n test_accuracy = prediction.eq(Test_Image_Label.view_as(prediction)).sum().item()/Test_Feature.shape[0] * 100\n if test_accuracy > best_accuracy:\n best_accuracy = test_accuracy\n\n print(\"Step: {}::::Layer Name: {} ---> Accuracy: {}\".format(self.step, key, best_accuracy))\n save_result.append((key, best_accuracy))\n\n with open('Results.txt', 'a') as filehandle:\n filehandle.write('Step: ' + str(self.step) + '\\n')\n np.savetxt(filehandle, np.array(save_result), fmt='%s', comments=str(self.step))\n\n print('Time to Evaluate:{} Minutes'.format((time.time() - start_time)/60.))\n\n self.unfreeze_weights()\n\n\n return save_result[0][-1]\n\n def evaluate(self, dataloader_Test):\n self.eval()\n correct = 0\n test_loss = 0\n start_time = time.time()\n for i_batch, batch in enumerate(dataloader_Test):\n output = self.Network(batch['sketch_img'].to(device))\n test_loss += self.loss(output, batch['sketch_label'].to(device)).item()\n prediction = output.argmax(dim=1, keepdim=True).to('cpu')\n correct += prediction.eq(batch['sketch_label'].view_as(prediction)).sum().item()\n\n test_loss /= len(dataloader_Test.dataset)\n accuracy = 100. * correct / len(dataloader_Test.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%), Time_Takes: {}\\n'.format(\n test_loss, correct, len(dataloader_Test.dataset), accuracy, (time.time() - start_time) ))\n\n return accuracy\n\n def freeze_weights(self):\n for name, x in self.named_parameters():\n x.requires_grad = False\n\n def unfreeze_weights(self):\n for name, x in self.named_parameters():\n x.requires_grad = True\n\n\n\n","sub_path":"baselines/RotationNet/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"648107961","text":"# *- code: utf-8 -*\n\nimport json\nimport os\nimport subprocess\nimport datetime\n'''\n# initiating for a complete blogs list\narticles = []\nfor file in os.listdir():\n if file.endswith(\".md\"):\n with open(file, encoding='utf-8') as post:\n post = post.readlines()\n title = \"\"\n date = \"\"\n for line in post[:5]:\n if line.startswith('title:'):\n title = line.split(\":\")[1].strip()\n if line.startswith('date'):\n date = line.split(\":\")[1].strip().split()[0].strip()\n articles.append({\"title\":title, \"date\": date,\"content\":\"\".join(post[5:])}) \nct = json.dumps({\"post\":articles})\nwith open('db.json','w') as df:\n df.write(ct)\n \n'''\ndbs = None\ndate = None\nwith open('db.json') as blogs:\n try:\n dbs = json.loads(blogs.read())\n except:\n dbs = json.loads('{\"post\":[{\"title\":\"\",\"date\":\"\"}]}')\n\nfor file in os.listdir():\n if file.endswith(\".md\"):\n new_post = True\n with open(file,encoding='utf-8') as post:\n post = post.readlines()\n title = None\n date = None\n for line in post[:5]:\n if line.startswith('title:'):\n title = line.split(\":\")[1].strip()\n if line.startswith('date'):\n date = line.split(\":\")[1].strip().split()[0].strip()\n if not title or not date:\n continue\n for blog in dbs['post']:\n if blog['title'] == title and blog['date'] == date:\n new_post = False \n break\n if new_post:\n new_article = {\"title\":title,\"date\":date,\"content\":\"\".join(post[5:])}\n old_post = dbs['post']\n old_post.append(new_article)\n new_dbs = json.dumps({'post':old_post})\n with open('db.json','w') as post_list:\n post_list.write(new_dbs)\n \n dt = datetime.datetime.strptime(date,\"%Y-%m-%d\")\n year = str(dt.year)\n month = str(\"{:0>2d}\".format(dt.month))\n day = str(\"{:0>2d}\".format(dt.day))\n blog_url = os.path.join(os.path.pardir,'content',year,month,day,title)\n \n if not os.path.exists(blog_url):\n os.makedirs(blog_url)\n \n blog_url = blog_url.replace(os.sep,\"/\")\n cmd = 'pandoc ' + file + \" -s -o \\\"\" + blog_url + \"/index.html\\\" --template=default.html\"\n print(cmd)\n subprocess.call(cmd)\n pos = None\n ct = None\n with open('../index.html',encoding='utf-8') as page:\n ct = page.read()\n ltag = \"2020
\"\n pos = ct.find(ltag)\n \n new_content = ct[:pos+len(ltag)] + \"\\n\" + title + \"\\n\" + dt.strftime(\"%Y-%m-%d\") + \"\" + ct[pos+len(ltag):]\n with open('../index.html','w',encoding='utf-8') as page:\n page.write(new_content)\n \nos.chdir('../')\nsubprocess.call(\"git add .\")\nsubprocess.call(\"git commit -m \\\"add new record \" + datetime.datetime.today().strftime(\"%Y-%m-%d\") + \"\\\"\")\nsubprocess.call(\"git push blog master\")\n","sub_path":"sources/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"542908366","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport aiohttp\nimport asyncio\nimport jmespath\nimport json\nimport logging\nimport requests\nimport signal\n\nfrom .providers import providers\n\nlogging.basicConfig(level=logging.WARNING)\nlogging.getLogger(\"requests\").setLevel(logging.WARNING)\n\nclass ActivityCount(object):\n \"\"\"Gather activity/share stats from social APIs\"\"\"\n def __init__(self, url=None):\n self.url = url or None\n self.responses = []\n\n def establish_client(self, loop):\n self.loop = asyncio.new_event_loop()\n self.client = aiohttp.ClientSession(loop=self.loop)\n asyncio.set_event_loop(self.loop)\n\n async def async_get_all(self, loop):\n self.establish_client(loop)\n \n for provider in providers:\n url = provider[\"endpoint\"].format(self.url)\n asyncio.ensure_future(self.collect_sharecount(url, provider), loop=self.loop)\n\n # loop over all providers\n pending = asyncio.Task.all_tasks(loop=self.loop)\n self.loop.run_until_complete(asyncio.gather(*pending, loop=self.loop))\n self.client.close()\n self.loop.close()\n\n async def get_json(self, url):\n async with self.client.get(url) as response:\n assert response.status == 200\n logging.debug(\"Got response for URL {0} with statuscode {1}\".format(url, response.status))\n response = await response.read()\n return response.decode('utf-8')\n\n async def collect_sharecount(self, url, provider):\n response = await self.get_json(url)\n j = json.loads(response)\n\n data = {\n \"provider\": provider[\"provider\"],\n \"metrics\": []\n }\n\n for m in provider[\"metrics\"]:\n data[\"metrics\"].append({\n \"count\": jmespath.search(m[\"path\"], j),\n \"label\": m[\"label\"]\n })\n \n self.responses.append(data)\n","sub_path":"metadoc/social/activity.py","file_name":"activity.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"57354151","text":"# -*- coding: utf-8 -*-\n\n'''\n Based on Covenant's search\n Author Bugatsinho\n\n License summary below, for more details please read license.txt file\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 2 of the License, or\n (at your option) any later version.\n 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 You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n'''\nimport xbmc\nimport urllib\nimport json\nimport random\nimport urlparse\nimport sys\nimport re\nfrom resources.lib.modules import control\nfrom resources.lib.modules import cache\nfrom resources.lib.modules import client\nfrom resources.lib.modules import view\nfrom t0mm0.common.addon import Addon\n\naddon = Addon('plugin.video.releaseBB', sys.argv)\nLang = control.lang\nADDON = control.addon()\nFANART = ADDON.getAddonInfo('fanart')\nICON = ADDON.getAddonInfo('icon')\nNAME = ADDON.getAddonInfo('name')\nversion = ADDON.getAddonInfo('version')\nIconPath = control.addonPath + \"/resources/icons/\"\nbase = control.setting('domain')\nBASE_URL = 'http://%s' % base.lower()\n\ntry:\n from sqlite3 import dbapi2 as database\nexcept ImportError:\n from pysqlite2 import dbapi2 as database\n\n\ndef Search_bb(url):\n kodi_ver = float(xbmc.getInfoLabel(\"System.BuildVersion\")[:4])\n if kodi_ver >= 18:\n from resources.lib.modules import cfscrape as cfscrape\n else:\n from resources.lib.modules import cfscrape17 as cfscrape\n scraper = cfscrape.create_scraper()\n if 'new' == url:\n keyboard = xbmc.Keyboard()\n keyboard.setHeading(control.lang(32002).encode('utf-8'))\n keyboard.doModal()\n if keyboard.isConfirmed():\n _query = keyboard.getText()\n query = _query.encode('utf-8')\n try:\n query = urllib.quote_plus(query)\n referer_link = 'http://search.rlsbb.ru?s={0}'.format(query)\n\n url = 'http://search.rlsbb.ru/Home/GetPost?phrase={0}&pindex=1&content=true&type=Simple&rad=0.{1}'\n url = url.format(query, random.randint(0o000000000000001, 99999999999999999))\n #########save in Database#########\n term = urllib.unquote_plus(query).decode('utf-8')\n dbcon = database.connect(control.searchFile)\n dbcur = dbcon.cursor()\n dbcur.execute(\"DELETE FROM Search WHERE search = ?\", (term,))\n dbcur.execute(\"INSERT INTO Search VALUES (?,?)\", (url, term))\n dbcon.commit()\n dbcur.close()\n\n #########search in website#########\n headers = {'Referer': referer_link,\n 'X-Requested-With': 'XMLHttpRequest'}\n first = scraper.get(referer_link, headers=headers).text\n xbmc.sleep(10)\n html = scraper.get(url, headers=headers).text\n posts = json.loads(html)['results']\n posts = [(i['post_name'], i['post_title'], i['post_content'], i['domain']) for i in posts if i]\n for movieUrl, title, infos, domain in posts:\n base = BASE_URL if 'old' not in domain else 'http://old2.rlsbb.ru/'\n movieUrl = urlparse.urljoin(base, movieUrl) if not movieUrl.startswith('http') else movieUrl\n title = title.encode('utf-8')\n infos = infos.replace('\\\\', '')\n try:\n img = client.parseDOM(infos, 'img', ret='src')[0]\n img = img.replace('.ru', '.to')\n except:\n img = ICON\n\n try:\n fan = client.parseDOM(infos, 'img', ret='src')[1]\n except:\n fan = FANART\n\n try:\n desc = re.search(r'Plot:(.+?)
![]()
![]()
', OPEN, re.DOTALL)[0]\n else:\n Sinopsis = re.findall('
\\n(.+?)
', OPEN, re.DOTALL)[0]\n\n except:\n Sinopsis = re.findall('
\\n(.+?)
\\n', '', Sinopsis)\n part = re.sub('\\.\\s+', '.', part)\n desc = clear_Title(part)\n desc = desc.decode('ascii', errors='ignore')\n return desc\n except BaseException:\n return 'N/A'\n\ndef clear_Title(txt):\n txt = re.sub('<.+?>', '', txt)\n txt = txt.replace(\""\", \"\\\"\").replace('()', '').replace(\"&\", \"&\").replace('–', ':')\n txt = txt.replace(\"&\", \"&\").replace('’', \"'\").replace(''', ':').replace('', '\\'')\n txt = txt.replace(\"&\", \"&\").replace('”', '\"').replace('‘', '\"').replace(' ', '')\n txt = txt.replace(\" \", \"\").replace('“', '\"').replace('\\t', ' ').replace('\\n', ' ')\n return txt","sub_path":"plugin.video.releaseBB/resources/lib/modules/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":13822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"491075735","text":"import tornado\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado import gen\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nfrom tornado.options import define, options\nimport sys\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n\n\ndef dot():\n \"\"\"callback for showing that IOLoop is still responsive while we wait\"\"\"\n sys.stdout.write('.')\n sys.stdout.flush()\n\nclass MainHandler(tornado.web.RequestHandler):\n @tornado.gen.coroutine\n def get(self):\n futures = []\n print('begginging')\n http_client = AsyncHTTPClient()\n for i in range(1,60):\n try:\n #response = yield http_client.fetch('http://www.google.com')\n request = tornado.httpclient.HTTPRequest(url='http://www.google.com',\n connect_timeout=60.0,\n request_timeout=60.0)\n response = yield tornado.gen.Task(http_client.fetch, request)\n \n #print(response.body)\n except Exception as e:\n # Other errors are possible, such as IOError.\n print(\"Error: \" + str(e))\n except tornado.gen.BadYieldError as e:\n print(\"error: \" + str(e))\n ##print(response)\n http_client.close()\n print(\"response is {} long\".format(len(response.body)))\n self.write(\"ok\")\n #print(response)\n\n\ndef main():\n tornado.options.parse_command_line()\n application = tornado.web.Application([\n (r\"/\", MainHandler),\n ])\n http_server = tornado.httpserver.HTTPServer(application)\n http_server.listen(options.port)\n beat = tornado.ioloop.PeriodicCallback(dot, 100)\n beat.start()\n tornado.ioloop.IOLoop.current().start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"async_server/async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"20546088","text":"##### DUELS #####\n\n# Amount of time before a duel request expires\nduelReqExpiryTime = {\"days\":1}\n# duelReqExpiryTime as a user-friendly string for printing\nduelReqExpiryTimeStr = \"1 day\"\n# The amount to vary ship stats (+-) by before executing a duel\nduelVariancePercent = 0.05\n\n# Max number of entries that can be printed for a duel log\nduelLogMaxLength = 10\n\n# Percentage probability of a user envoking a cloak module in a given timeStep, should they have one equipped\nduelCloakChance = 20\n\n\n\n##### SHOPS #####\n\n# Amount of time to wait between refreshing stock of all shops\nshopRefreshStockPeriod = {\"days\":0, \"hours\":12, \"minutes\":0, \"seconds\":0}\n\n# The number of ranks to use when randomly picking shop stock\nnumShipRanks = 10\nnumWeaponRanks = 10\nnumModuleRanks = 7\nnumTurretRanks = 3\n\n# The default number of items shops should generate every shopRefreshStockPeriod\nshopDefaultShipsNum = 5\nshopDefaultWeaponsNum = 5\nshopDefaultModulesNum = 5\nshopDefaultTurretsNum = 2\n\n# bbTurret is the only item that has a probability not to be spawned. This metric indicates the percentage chance of turrets being stocked on a given day\nturretSpawnProbability = 45\n\n\n\n##### BOUNTIES #####\n\nmaxBountiesPerFaction = 5\n\n# can be \"fixed\" or \"random\"\nnewBountyDelayType = \"random\"\n\n# only spawn bounties at this time\nnewBountyFixedDailyTime = {\"hours\":18, \"minutes\":40, \"seconds\":0}\n# use the above, or just spawn after every newBountyFixedDelta\nnewBountyFixedUseDailyTime = False\n\n# time to wait inbetween spawning bounties\nnewBountyFixedDelta = {\"days\":0, \"hours\":0, \"minutes\":40, \"seconds\":0}\n\n# when using random delay generation, use this as the minimum wait time in seconds\nnewBountyDelayMin = 15 * 60\n# when using random delay generation, use this as the maximum wait time in seconds\nnewBountyDelayMax = 1 * 60 * 60\n\n# The number of credits to award for each bPoint (each system in a criminal route)\nbPointsToCreditsRatio = 1000\n\n# time to put users on cooldown between using !bb check\ncheckCooldown = {\"minutes\":3}\n\n# number of bounties ahead of a checked system in a route to report a recent criminal spotting (+1)\ncloseBountyThreshold = 4\n\n\n\n##### SAVING #####\n\n# The time to wait inbetween database autosaves.\nsavePeriod = {\"hours\":1}\n\n# path to JSON files for database saves\nuserDBPath = \"saveData/users.json\"\nguildDBPath = \"saveData/guilds.json\"\nbountyDBPath = \"saveData/bounties.json\"\n\n\n\n##### SCHEDULING #####\n\n# Whether to execute timedtask checks every timedTaskLatenessThresholdSeconds (\"fixed\"), or to calculate the delay to wait until the next TimedTask is schedule to expire (\"dynamic\")\ntimedTaskCheckingType = \"fixed\"\n\n# How late a timed task acceptably be\n# I.e a scheduled task may expire up to timedTaskLatenessThresholdSeconds seconds after their intended expiration time.\n# replaces the depracated 'delayFactor' variable\ntimedTaskLatenessThresholdSeconds = 10\n\n\n\n##### MISC #####\n\n# prefix for bot commands. dont forget a space if you want one!\ncommandPrefix = \"$\"\n\n# When a user message prompts a DM to be sent, this emoji will be added to the message reactions.\ndmSentEmoji = \"📬\"\n\n# max number of characters accepted by nameShip\nmaxShipNickLength = 30\n\n# The default emojis to list in a reaction menu\ndefaultMenuEmojis = [\"0️⃣\", \"1️⃣\", \"2️⃣\", \"3️⃣\", \"4️⃣\", \"5️⃣\", \"6️⃣\", \"7️⃣\", \"8️⃣\", \"9️⃣\", \"🔟\"]\n\n\n\n##### ADMINISTRATION #####\n\n# discord user IDs of all developers\ndevelopers = [188618589102669826, 448491245296418817]\n\n# titles to give each type of user when reporting error messages etc\ndevTitle = \"officer\"\nadminTitle = \"commander\"\nuserTitle = \"pilot\"\n\n# Servers where bountyBot commands are disabled. Currently this is just the emoji servers:\ndisabledServers = [723704980246233219, 723702782640783361, 723708988830515231, 723704665560055848, 723705817764986900, 723703454635393056, 723708655031156742, 723706906517962814, 723704087962583131, 723704350131748935]\n\n\n\n##### HANGARS #####\n\n# The maximum number of items that will be displayed per page of a user's hangar, when all item types are requested\nmaxItemsPerHangarPageAll = 3\n# The maximum number of items that will be displayed per page of a user's hangar, when a single item type is requested\nmaxItemsPerHangarPageIndividual = 5\n\n# Names to be used when checking input to !bb hangar and bbUser.numInventoryPages\nvalidItemNames = [\"ship\", \"weapon\", \"module\", \"turret\", \"all\"]\n\n\n\n##### INTERNAL #####\n# Do not touch these!\nnewBountyDelayReset = False\nnewBountyFixedDeltaChanged = False","sub_path":"BB/bbConfig/bbConfig.py","file_name":"bbConfig.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"297631859","text":"\"\"\"\nBootstrap's user's development environment by creating cloud resources required by SAM CLI\n\"\"\"\n\nimport logging\n\nimport boto3\n\nimport click\n\nfrom botocore.config import Config\nfrom botocore.exceptions import ClientError, BotoCoreError, NoRegionError, NoCredentialsError, ProfileNotFound\n\nfrom samcli.commands.exceptions import UserException, CredentialsError, RegionError\n\n\nSAM_CLI_STACK_PREFIX = \"aws-sam-cli-managed-\"\nLOG = logging.getLogger(__name__)\n\n\nclass ManagedStackError(UserException):\n def __init__(self, ex):\n self.ex = ex\n message_fmt = f\"Failed to create managed resources: {ex}\"\n super().__init__(message=message_fmt.format(ex=self.ex))\n\n\ndef manage_stack(profile, region, stack_name, template_body):\n try:\n if profile:\n session = boto3.Session(profile_name=profile, region_name=region if region else None)\n cloudformation_client = session.client(\"cloudformation\")\n else:\n cloudformation_client = boto3.client(\n \"cloudformation\", config=Config(region_name=region if region else None)\n )\n except ProfileNotFound as ex:\n raise CredentialsError(\n f\"Error Setting Up Managed Stack Client: the provided AWS name profile '{profile}' is not found. \"\n \"please check the documentation for setting up a named profile: \"\n \"https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html\"\n ) from ex\n except NoCredentialsError as ex:\n raise CredentialsError(\n \"Error Setting Up Managed Stack Client: Unable to resolve credentials for the AWS SDK for Python client. \"\n \"Please see their documentation for options to pass in credentials: \"\n \"https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html\"\n ) from ex\n except NoRegionError as ex:\n raise RegionError(\n \"Error Setting Up Managed Stack Client: Unable to resolve a region. \"\n \"Please provide a region via the --region parameter or by the AWS_REGION environment variable.\"\n ) from ex\n return _create_or_get_stack(cloudformation_client, stack_name, template_body)\n\n\ndef _create_or_get_stack(cloudformation_client, stack_name, template_body):\n try:\n ds_resp = cloudformation_client.describe_stacks(StackName=stack_name)\n stacks = ds_resp[\"Stacks\"]\n stack = stacks[0]\n click.echo(\"\\n\\tLooking for resources needed for deployment: Found!\")\n _check_sanity_of_stack(stack, stack_name)\n return stack[\"Outputs\"]\n except ClientError:\n click.echo(\"\\n\\tLooking for resources needed for deployment: Not found.\")\n\n try:\n stack = _create_stack(\n cloudformation_client, stack_name, template_body\n ) # exceptions are not captured from subcommands\n _check_sanity_of_stack(stack, stack_name)\n return stack[\"Outputs\"]\n except (ClientError, BotoCoreError) as ex:\n LOG.debug(\"Failed to create managed resources\", exc_info=ex)\n raise ManagedStackError(str(ex)) from ex\n\n\ndef _check_sanity_of_stack(stack, stack_name):\n tags = stack.get(\"Tags\", None)\n outputs = stack.get(\"Outputs\", None)\n\n # For some edge cases, stack could be in invalid state\n # Check if stack information contains the Tags and Outputs as we expected\n if tags is None or outputs is None:\n stack_state = stack.get(\"StackStatus\", None)\n msg = (\n f\"Stack {stack_name} is missing Tags and/or Outputs information and therefore not in a \"\n f\"healthy state (Current state:{stack_state}). Failing as the stack was likely not created \"\n f\"by the AWS SAM CLI\"\n )\n raise UserException(msg)\n\n # Sanity check for non-none stack? Sanity check for tag?\n try:\n sam_cli_tag = next(t for t in tags if t[\"Key\"] == \"ManagedStackSource\")\n if not sam_cli_tag[\"Value\"] == \"AwsSamCli\":\n msg = (\n \"Stack \"\n + stack_name\n + \" ManagedStackSource tag shows \"\n + sam_cli_tag[\"Value\"]\n + \" which does not match the AWS SAM CLI generated tag value of AwsSamCli. \"\n \"Failing as the stack was likely not created by the AWS SAM CLI.\"\n )\n raise UserException(msg)\n except StopIteration as ex:\n msg = (\n \"Stack \" + stack_name + \" exists, but the ManagedStackSource tag is missing. \"\n \"Failing as the stack was likely not created by the AWS SAM CLI.\"\n )\n raise UserException(msg) from ex\n\n\ndef _create_stack(cloudformation_client, stack_name, template_body):\n click.echo(\"\\tCreating the required resources...\")\n change_set_name = \"InitialCreation\"\n change_set_resp = cloudformation_client.create_change_set(\n StackName=stack_name,\n TemplateBody=template_body,\n Tags=[{\"Key\": \"ManagedStackSource\", \"Value\": \"AwsSamCli\"}],\n ChangeSetType=\"CREATE\",\n ChangeSetName=change_set_name, # this must be unique for the stack, but we only create so that's fine\n )\n stack_id = change_set_resp[\"StackId\"]\n change_waiter = cloudformation_client.get_waiter(\"change_set_create_complete\")\n change_waiter.wait(\n ChangeSetName=change_set_name, StackName=stack_name, WaiterConfig={\"Delay\": 15, \"MaxAttempts\": 60}\n )\n cloudformation_client.execute_change_set(ChangeSetName=change_set_name, StackName=stack_name)\n stack_waiter = cloudformation_client.get_waiter(\"stack_create_complete\")\n stack_waiter.wait(StackName=stack_id, WaiterConfig={\"Delay\": 15, \"MaxAttempts\": 60})\n ds_resp = cloudformation_client.describe_stacks(StackName=stack_name)\n stacks = ds_resp[\"Stacks\"]\n click.echo(\"\\tSuccessfully created!\")\n return stacks[0]\n","sub_path":"samcli/lib/utils/managed_cloudformation_stack.py","file_name":"managed_cloudformation_stack.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"332233155","text":"f1=open(\"input2\",'r')\r\nf2=open(\"output2.txt\",'w')\r\nt=int(f1.readline()[:-1])\r\nfor k in range(1,t+1):\r\n r= str(f1.readline()[:-1])\r\n s,m=r.split()\r\n s=list(s)\r\n m=int(m)\r\n i = 0\r\n flag=0\r\n imp = \"IMPOSSIBLE\"\r\n moves = 0\r\n while i <= len(s) - m:\r\n if s[i] == '-':\r\n moves += 1\r\n for j in range(i, i + m):\r\n if s[j] == '+':\r\n s[j] = '-'\r\n else:\r\n s[j] = '+'\r\n i = i + 1\r\n for i in range(0, len(s)):\r\n if s[i] == '-':\r\n flag = 1\r\n break\r\n if flag == 0:\r\n f2.write(\"Case #{}: {}\".format(k, moves) + '\\n')\r\n else:\r\n f2.write(\"Case #{}: {}\".format(k, imp) + '\\n')\r\n","sub_path":"solutions_python/Problem_199/2773.py","file_name":"2773.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"138491432","text":"\"\"\"\nMain run file.\n\"\"\"\n\nimport pandas as pd\nimport argparse\nfrom settings import conf\nfrom load_data import load_action_units_x, load_facial_attributes_x,\\\n load_body_keypoints_x\nfrom utils import load_model, evaluate_model, \\\n average_ensemble, wtd_average_ensemble\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Process OpenPose output.')\n\n parser.add_argument('--model_path', required=True,\n help='Path of folder containing models.')\n\n args = parser.parse_args()\n model_path = args.model_path\n\n val_data = pd.read_csv(conf.VAL_DATA, delimiter=',')\n val_engagement_value = val_data.attention\n\n print(\"Validating models\")\n\n val_x_openface_au = load_action_units_x(val_data, \"val\")\n print(\"Loaded validation FAU features\")\n val_x_openface_face = load_facial_attributes_x(val_data, \"val\")\n print(\"Loaded validation FA features\")\n val_x_openpose = load_body_keypoints_x(val_data, \"val\")\n print(\"Loaded validation BL features\")\n\n au_model = load_model(conf.MODEL_AU_NAME, model_path)\n pred_au = au_model.predict(val_x_openface_au)\n mse_au, pcc_au = evaluate_model(pred_au, val_engagement_value)\n print(\"FAU: MSE = {}, PCC = {}\".format(mse_au, pcc_au))\n\n face_model = load_model(conf.MODEL_FACE_NAME, model_path)\n pred_face = face_model.predict(val_x_openface_face)\n mse_face, pcc_face = evaluate_model(pred_face, val_engagement_value)\n print(\"FA: MSE = {}, PCC = {}\".format(mse_face, pcc_face))\n\n bodylandmark_model = load_model(conf.MODEL_BL_NAME, model_path)\n pred_bl = bodylandmark_model.predict(val_x_openpose)\n mse_bl, pcc_bl = evaluate_model(pred_bl, val_engagement_value)\n print(\"BL: MSE = {}, PCC = {}\".format(mse_bl, pcc_bl))\n\n average_pred = average_ensemble(pred_au, pred_face, pred_bl)\n mse_avg, pcc_avg = evaluate_model(average_pred, val_engagement_value)\n print(\"Avg Ensemble: MSE = {}, PCC = {}\".format(mse_avg, pcc_avg))\n\n wtd_average_pred = wtd_average_ensemble(pred_au, pred_face, pred_bl)\n mse_wtd, pcc_wtd = evaluate_model(\n wtd_average_pred, val_engagement_value)\n print(\"Wtd Avg Ensemble: MSE = {}, PCC = {}\".format(mse_wtd, pcc_wtd))\n","sub_path":"validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"599093662","text":"from app.models import db, Comment\nfrom faker import Faker\nimport random\n\nfaker = Faker()\n\ndef seed_comments():\n \n for i in range(50):\n comments = Comment(\n content = faker.sentence()\n )\n db.session.add(comments)\n db.session.commit()\n \ndef undo_comments():\n db.session.execute('TRUNCATE comments RESTART IDENTITY CASCADE;')\n db.session.commit()\n","sub_path":"app/seeds/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"54945386","text":"# -*- coding: utf-8 -*-\n#\n# Convex Search Algorithm\n#\nimport random\nimport statistics as stats\n\n###########################\n### AUXILIARY FUNCTIONS ###\n###########################\n\ndef all_equal(bunch):\n first = bunch[0]\n return all(x == first for x in bunch)\n\ndef any_greater_than(bunch, threshold):\n return any(x >= threshold for x in bunch)\n\n\n### Using any_two_greater_than instead of any_greater_than may be preferable\n### because it avoids constructing a mating pool of individuals above average\n### containing only a single individidual. Doing recombination only on one\n### individual can only lead to the same individual, and this might accelerate\n### premature convergence. Whereas if we have a mating pool consisting of at\n### least two different individuals, the offspring are more likely to be\n### different than parents.\ndef any_two_greater_than(bunch, threshold):\n return len(set([x for x in bunch if x >= threshold])) > 2\n\n##################################\n### PROBLEMS' FITNESS FUNCTION ###\n##################################\n\n### Leading-Ones\n\ndef leadingones_fitness(individual):\n for position in range(INDIVIDUAL_SIZE):\n if individual[position] == 0:\n break\n else:\n position += 1\n return position\ndef leadingones_avg_fitness():\n ### avg(n) is the sum of fitnesses of all sequences with leading ones,\n ### i.e. (2^n) - 1, divided by the number of sequences with leading ones,\n ### i.e. 2^(n - 1):\n ###\n ### avg(n) = (2^n) - 1 / 2^(n - 1)\n ### = (2^n / 2^n-1) - (1 / 2^n-1)\n ### = 2 - 2^(1 - n) .\n ###\n ### In the limit: lim n->+inf (2 - 2^(1 - n)) = 2 - 0 = 2 .\n return 2 - (2**(1 - INDIVIDUAL_SIZE))\n\n### One-Max\n\ndef onemax_fitness(individual):\n return sum(individual)\n\ndef onemax_avg_fitness():\n return sum([0.5 for _ in range(INDIVIDUAL_SIZE)])\n\n######################\n### REPRESENTATION ###\n######################\n\ndef create_ind():\n return [random.randint(0, 1) for _ in range(INDIVIDUAL_SIZE)]\n\ndef create_pop():\n return [create_ind() for _ in range(POPULATION_SIZE)]\n\ndef evaluate_pop(population):\n return [PROBLEM_FITNESS(individual) for individual in population]\n\n#################################\n### SELECTION META-HEURISTICS ###\n#################################\n\ndef select_better_than_worst(population, fitness_population):\n worst_fitness = min(fitness_population)\n return [individual\n for (individual, fitness) in zip(population, fitness_population)\n if fitness > worst_fitness]\n\ndef select_above_avg(population, fitness_population):\n avg_fitness = stats.mean(fitness_population)\n return [individual\n for (individual, fitness) in zip(population, fitness_population)\n if fitness >= avg_fitness]\n\n#####################\n### RECOMBINATION ###\n#####################\n\ndef convex_recombination_pop(mating_pool):\n return [convex_recombination_ind(mating_pool)\n for _ in range(POPULATION_SIZE)]\n\ndef convex_recombination_ind(mating_pool):\n transposed_mating_pool = zip(*mating_pool)\n def recombine_column(col):\n return col[0] if all_equal(col) else random.randint(0, 1)\n return list(map(recombine_column, transposed_mating_pool))\n\n#####################\n### CONVEX SEARCH ###\n#####################\n\ndef convex_search():\n gens = 0\n population = create_pop()\n fitness_population = evaluate_pop(population)\n while (not all_equal(population)) and (gens < MAX_GENERATIONS):\n mating_pool = population\n if not all_equal(fitness_population):\n mating_pool = select_better_than_worst(\n population,\n fitness_population\n )\n population = convex_recombination_pop(mating_pool)\n fitness_population = evaluate_pop(population)\n gens += 1\n return (fitness_population[0], gens)\n\ndef convex_search2():\n gens = 0\n population = create_pop()\n fitness_population = evaluate_pop(population)\n while (not all_equal(population)) and (gens < MAX_GENERATIONS):\n mating_pool = population\n avg_fitness_pop = stats.mean(fitness_population)\n if any_two_greater_than(fitness_population, avg_fitness_pop):\n mating_pool = select_above_avg(population, fitness_population)\n elif not all_equal(fitness_population):\n mating_pool = select_better_than_worst(\n population,\n fitness_population\n )\n population = convex_recombination_pop(mating_pool)\n fitness_population = evaluate_pop(population)\n gens += 1\n return (fitness_population[0], gens)\n\n\n\n\n############\n### MAIN ###\n############\n\n### (Corollary 9) Recommended population sizes for a given individual size,\n### so that \"normal\" convex search optimises LeadingOnes in O(n log n).\n### - population size: 25, 40, 60, 75\n### - individual size: 10, 100, 1000, 10000\n\nSEARCH = convex_search2\nPROBLEM_FITNESS = leadingones_fitness\nMAX_RUNS = 300\nMAX_GENERATIONS = 100\nPOPULATION_SIZE = 50\nINDIVIDUAL_SIZE = 100\n\ndef main():\n ### Settings\n print(\"-------------------- SETTINGS --------------------\")\n print(\"Search algorithm: %s\" % SEARCH.__name__)\n print(\"Problem fitness function: %s\" % PROBLEM_FITNESS.__name__)\n print(\"Max runs: %d, Max gens.: %d, Pop. size: %d, Ind. size: %d\" %\n (MAX_RUNS, MAX_GENERATIONS, POPULATION_SIZE, INDIVIDUAL_SIZE)\n )\n ### Start\n print(\"-------------------- START --------------------\")\n runs = 0\n fitnesses = []\n generations = []\n while (runs < MAX_RUNS):\n (fit, gens) = SEARCH()\n fitnesses.append(fit)\n generations.append(gens)\n runs += 1\n print(\"Runs: %d | fitness: %d, gens.: %d\" % (runs, fit, gens))\n ### Results\n print(\"-------------------- SUMMARY --------------------\")\n print(\"Fitness | Max: %d, Min: %d, Avg: %f, Median high: %f, Stdev: %f\"\n % (max(fitnesses),\n min(fitnesses),\n stats.mean(fitnesses),\n stats.median_high(fitnesses),\n stats.stdev(fitnesses))\n )\n print(\"Generations | Max: %d, Min: %d, Avg: %f, Median low: %f, Stdev: %f\"\n % (max(generations),\n min(generations),\n stats.mean(generations),\n stats.median_low(generations),\n stats.stdev(generations))\n )\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"ces.py","file_name":"ces.py","file_ext":"py","file_size_in_byte":6423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"300769585","text":"from rest_framework_mongoengine.serializers import DocumentSerializer\nfrom eledata.models.watcher import *\n\n\nclass GeneralWatcherSerializer(DocumentSerializer):\n class Meta:\n model = Watcher\n depth = 2\n fields = [\n 'sku_id', 'product_name', 'item_url', 'default_price', 'final_price', 'seller_name', 'seller_url', 'images',\n 'platform', 'current_stock', 'comments_count', 'bundle', 'detail', 'support', 'model', 'seller_location',\n 'sales_count', 'search_keyword', 'search_rank', 'search_order', 'last_crawling_timestamp', ]\n","sub_path":"eledata/serializers/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"267657956","text":"\"\"\"\n@Author: jinzhuan\n@File: baidu.py\n@Desc: \n\"\"\"\nfrom ..processor import Processor\nfrom cogie.core import DataTable\n\n\nclass BaiduRelationProcessor(Processor):\n\n def __init__(self, label_list=None, path=None, padding=None, unknown='',\n bert_model='hfl/chinese-roberta-wwm-ext', max_length=256, blank_padding=True, mask_entity=False):\n super().__init__(label_list, path, padding, unknown, bert_model, max_length)\n self.max_length = max_length\n self.blank_padding = blank_padding\n self.mask_entity = mask_entity\n\n def process(self, dataset):\n datable = DataTable()\n for i in range(len(dataset)):\n token, relation, subj_start, subj_end, obj_start, obj_end = dataset[i]\n label_id = self.vocabulary.to_index(relation)\n item = {'token': token, 'h': {'pos': [subj_start, subj_end + 1]}, 't': {'pos': [obj_start, obj_end + 1]}}\n indexed_tokens, att_mask, pos1, pos2 = self.tokenize(item)\n datable('input_ids', indexed_tokens)\n datable('attention_mask', att_mask)\n datable('pos1', pos1)\n datable('pos2', pos2)\n datable('label_id', label_id)\n\n datable('input_ids', indexed_tokens)\n datable('attention_mask', att_mask)\n datable('pos1', pos2)\n datable('pos2', pos1)\n datable('label_id', self.vocabulary.to_index(''))\n return datable\n\n def tokenize(self, item):\n # Sentence -> token\n if 'text' in item:\n sentence = item['text']\n is_token = False\n else:\n sentence = item['token']\n is_token = True\n pos_head = item['h']['pos']\n pos_tail = item['t']['pos']\n\n pos_min = pos_head\n pos_max = pos_tail\n if pos_head[0] > pos_tail[0]:\n pos_min = pos_tail\n pos_max = pos_head\n rev = True\n else:\n rev = False\n\n if not is_token:\n sent0 = self.tokenizer.tokenize(sentence[:pos_min[0]])\n ent0 = self.tokenizer.tokenize(sentence[pos_min[0]:pos_min[1]])\n sent1 = self.tokenizer.tokenize(sentence[pos_min[1]:pos_max[0]])\n ent1 = self.tokenizer.tokenize(sentence[pos_max[0]:pos_max[1]])\n sent2 = self.tokenizer.tokenize(sentence[pos_max[1]:])\n else:\n sent0 = self.tokenizer.tokenize(' '.join(sentence[:pos_min[0]]))\n ent0 = self.tokenizer.tokenize(' '.join(sentence[pos_min[0]:pos_min[1]]))\n sent1 = self.tokenizer.tokenize(' '.join(sentence[pos_min[1]:pos_max[0]]))\n ent1 = self.tokenizer.tokenize(' '.join(sentence[pos_max[0]:pos_max[1]]))\n sent2 = self.tokenizer.tokenize(' '.join(sentence[pos_max[1]:]))\n\n if self.mask_entity:\n ent0 = ['[unused4]'] if not rev else ['[unused5]']\n ent1 = ['[unused5]'] if not rev else ['[unused4]']\n else:\n ent0 = ['[unused0]'] + ent0 + ['[unused1]'] if not rev else ['[unused2]'] + ent0 + ['[unused3]']\n ent1 = ['[unused2]'] + ent1 + ['[unused3]'] if not rev else ['[unused0]'] + ent1 + ['[unused1]']\n\n re_tokens = ['[CLS]'] + sent0 + ent0 + sent1 + ent1 + sent2 + ['[SEP]']\n pos1 = 1 + len(sent0) if not rev else 1 + len(sent0 + ent0 + sent1)\n pos2 = 1 + len(sent0 + ent0 + sent1) if not rev else 1 + len(sent0)\n pos1 = min(self.max_length - 1, pos1)\n pos2 = min(self.max_length - 1, pos2)\n\n indexed_tokens = self.tokenizer.convert_tokens_to_ids(re_tokens)\n avai_len = len(indexed_tokens)\n\n # Position\n # pos1 = torch.tensor([[pos1]]).long()\n # pos2 = torch.tensor([[pos2]]).long()\n\n # Padding\n if self.blank_padding:\n while len(indexed_tokens) < self.max_length:\n indexed_tokens.append(0) # 0 is id for [PAD]\n indexed_tokens = indexed_tokens[:self.max_length]\n # indexed_tokens = torch.tensor(indexed_tokens).long().unsqueeze(0) # (1, L)\n\n # Attention mask\n # att_mask = torch.zeros(indexed_tokens.size()).long() # (1, L)\n # att_mask[0, :avai_len] = 1\n att_mask = [0] * len(indexed_tokens)\n for i in range(min(avai_len, self.max_length)):\n att_mask[i] = 1\n\n return indexed_tokens, att_mask, [pos1], [pos2]\n","sub_path":"cogie/io/processor/re/baidu.py","file_name":"baidu.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"128085002","text":"\"\"\"\nhttps://github.com/apache/spark/blob/master/examples/src/main/python/ml/dataframe_example.py\n\"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport tempfile\nimport shutil\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.mllib.stat import Statistics\nfrom pyspark.mllib.util import MLUtils\n\nspark = SparkSession.builder.appName(\"DataFrameML\").getOrCreate()\n\ndf = spark.read.format(\"libsvm\").load(\"testdata/libsvm.data\").cache()\nprint(\"Schema from LIBSVM:\")\ndf.printSchema()\nprint(\"Loaded training data as a DataFrame with \" + str(df.count()) + \" records.\")\n\n# show statistical summary of labels\nlabelSummary = df.describe(\"label\")\nlabelSummary.show()\n\n# convert features column to an RDD of vectors\nfeatures = MLUtils.convertVectorColumnsFromML(df, \"features\") \\\n .select(\"features\") \\\n .rdd \\\n .map(lambda r: r.features)\nsummary = Statistics.colStats(features)\nprint(\"Selected features solumn with average values:\\n\" + str(summary.mean()))\n\n# save the records in a parquet file\ntempdir = tempfile.NamedTemporaryFile(delete=False).name\nos.unlink(tempdir)\nprint(\"Saving to \" + tempdir + \" as Parquet file.\")\ndf.write.parquet(tempdir)\n\n# load the records back\nprint(\"Loading Parquet file with UDT from \" + tempdir)\nnewDF = spark.read.parquet(tempdir)\nprint(\"Schema from Parquet:\")\nnewDF.printSchema()\nshutil.rmtree(tempdir)\n\nspark.stop()\n","sub_path":"refs/pyspark/ml/df.py","file_name":"df.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"473181387","text":"from config import GS1_USER, GS1_PASS, GS1_URL, BINARY_LOC\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nimport os\nimport time\n\n\n\nclass Page:\n\n def __init__(self):\n chrome_options = Options()\n chrome_options.headless = False\n chrome_options.binary_location = BINARY_LOC\n\n self.driver = webdriver.Chrome(os.path.abspath('chromedriver'),\n options=chrome_options)\n self.driver.implicitly_wait(10)\n\n # can we add the chrome_options here?\n def quit(self):\n return self.driver.quit()\n\n def login(self):\n driver = self.driver\n driver.get(GS1_URL)\n driver.find_element_by_xpath(\n '//input[@id=\"signInName\"]').send_keys(GS1_USER)\n driver.find_element_by_xpath(\n '//input[@id=\"password\"]').send_keys(GS1_PASS)\n\n driver.find_element_by_xpath(\n '//button[@id=\"next\"]').click()\n # lands on 'Products' page\n driver.find_element_by_xpath(\n '//*[@id=\"product\"]/a').click()\n return print('Logged in...')\n\n def create_new(self, obj):\n driver = self.driver\n driver.find_element_by_xpath('//*[@id=\"addnewproduct\"]/a').click()\n # Single pass of GS1 creation loop.\n de = driver.find_element_by_xpath('//input[@id=\"txtProductDescription\"]')\n de.send_keys(obj.name)\n # Brand Name\n bn = driver.find_element_by_xpath('//input[@id=\"txtBrandName\"]')\n bn.send_keys(obj.brand_name)\n # SKU\n sku = driver.find_element_by_xpath('//input[@id=\"txtSKU\"]')\n sku.send_keys(obj.sku)\n # Need to save here\n driver.find_element_by_xpath('//button[@id=\"btnSave\"]').click()\n #Waits for the auto assign to pop up, clicks it and then moves to the continue model.\n time.sleep(1)\n element = WebDriverWait(driver, 10).until(\n EC.element_to_be_clickable((By.XPATH, '//button[@id=\"btnAutoAssign\"]'))\n ).click()\n driver.find_element_by_xpath('//button[@id=\"btnAutoAssignGtinStartContinue\"]').click()\n \n## # Save right here.\n## time.sleep(1)\n## elementd = WebDriverWait(driver, 10).until(\n## EC.element_to_be_clickable((By.XPATH, '//button[@id=\"btnSave\"]'))\n## )\n## elementd.click()\n#### driver.find_element_by_xpath('//button[@id=\"btnSave\"]').click()\n## # Try to find status dropdown and change\n try:\n time.sleep(3)\n dropdown = Select(driver.find_element_by_xpath('//select[@id=\"ddlStatus\"]'))\n dropdown.select_by_visible_text(\"In Use\")\n\n # Save again.\n driver.find_element_by_xpath('//button[@id=\"btnSave\"]').click()\n # asks for continue if marked 'In Use'\n try:\n driver.find_element_by_xpath('//button[@id=\"btnConfirmInUse\"]').click()\n except:\n print('failed')\n\n except Exception as err:\n print(err)\n driver.find_element_by_xpath('//button[@id=\"btnSave\"]').click()\n print('Item saved as Draft.')\n pass\n\n def download(self):\n driver = self.driver\n # Currently only starts from download point\n # Move on to barcode\n driver.find_element_by_xpath(\n '//*[@id=\"ProductdetailTabs\"]/li[6]/a').click()\n \n # Attempts to wait for the 'preview' button.\n time.sleep(1)\n driver.find_element_by_xpath(\n '//button[@id=\"btnPreview\"]').click()\n # downloads preview PNG\n driver.find_element_by_xpath(\n '//button[@id=\"btnDownload\"]').click()\n upc = driver.find_element_by_xpath('/html/body/main/div/div[1]/div[1]/div/div/h1').text\n self.upc = upc.split(' ')[2][3:-1]\n print(f'Downloading png for {self.upc}')\n\n # closes\n time.sleep(1)\n driver.find_element_by_xpath(\n '//*[@id=\"barcodePreviewModal\"]/div[2]/div[1]/div[1]').click()\n print('download button clicked...')\n # returns the UPC into the object.\n return self.upc\n\n def find_existing(self, sku):\n download_path = os.path.expanduser('~') + '\\\\downloads\\\\'\n driver = self.driver\n sku_field = driver.find_element_by_xpath('//input[@id=\"dtProductListSKU5\"]')\n sku_field.send_keys(sku)\n time.sleep(1)\n driver.find_element_by_xpath('//*[@id=\"dtProductList\"]/tbody/tr/td[3]/a').click()\n upc = self.download()\n old_file = f'00{upc} UPC-A SST1.png'\n new_file = f'{sku} UPC.png'\n os.rename(download_path + old_file, download_path + new_file)\n## Rename file? \n driver.get('https://dh.gs1us.org/Product/Home') \n\n pass\n def create_and_download(self, obj):\n self.create_new(self, obj)\n self.download()\n\n return\n\n\n","sub_path":"GS1Class.py","file_name":"GS1Class.py","file_ext":"py","file_size_in_byte":5174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"596875915","text":"import torch\nfrom torch.optim import Optimizer\nimport math\nimport sys\nimport traceback\nfrom functools import lru_cache\nfrom torch_ps.import_util import get_libtorch_embedding_module_dim\n\n\nclass BaseTorchPSOptimizer(Optimizer):\n def __init__(self, params, defaults):\n if \"staleness\" not in defaults:\n ValueError(\"staleness is not specified\")\n if isinstance(defaults[\"staleness\"], bool):\n ValueError(\"staleness must be bool\")\n super(BaseTorchPSOptimizer, self).__init__(params, defaults)\n self.safe = defaults.get(\"safe\", True)\n assert isinstance(self.safe, bool)\n\n def step(self, rank=-1, total_ranks=1, staleness=1, chunked_grad=True):\n if self.defaults[\"staleness\"]:\n staleness_coef = 1.0 / max(staleness, 1)\n # print(staleness_coef, chunked_grad)\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n if chunked_grad:\n grad = p.grad.data.view(-1)\n if len(grad) > total_ranks > 1:\n grad = grad.chunk(total_ranks)\n if rank < len(grad):\n grad = grad[rank]\n grad.mul_(staleness_coef)\n elif rank == 0:\n p.grad.mul_(staleness_coef)\n else:\n p.grad.mul_(staleness_coef, total_ranks)\n\n\nclass FastEmbeddingOptimizerBase(BaseTorchPSOptimizer):\n def share_memory(self):\n pass\n\n def step(self, rank=-1, total_ranks=1, staleness=1, closure=None):\n super(FastEmbeddingOptimizerBase, self).step(rank, total_ranks, staleness, False)\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n if p.hash_table is None:\n raise ValueError(\"No hash table found. Seems you've forgot to set hash table\")\n\n p.hash_table.update(p.grad, self.updater, total_ranks, self.safe)\n\n def update_counter(self, value=1):\n self.updater.update_counter(value)\n\n def erase_useless(self):\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n if p.hash_table is None:\n raise ValueError(\"No hash table found. Seems you've forgot to set hash table\")\n\n p.hash_table.erase_useless(self.updater)\n\n\nclass EmbeddingFTRLOptimizer(FastEmbeddingOptimizerBase):\n def __init__(self, params, dim=1, lr_eta=0.1, lr_beta=0.0001, l2=0, l1=0, decay=1.0, ttl=1 << 31, staleness=False, safe=True):\n self.updater = getattr(get_libtorch_embedding_module_dim(dim), 'FTRLEmbeddingUpdater_{}'.format(dim))(lr_eta, lr_beta, l1, l2, decay, ttl)\n super(EmbeddingFTRLOptimizer, self).__init__(params, dict(dim=dim, lr_eta=lr_eta, lr_beta=lr_beta, l2=l2, l1=l1, ttl=ttl, staleness=staleness, safe=safe))\n\n\nclass Adagrad(BaseTorchPSOptimizer):\n \"\"\"Implements Adagrad algorithm.\n\n It has been proposed in `Adaptive Subgradient Methods for Online Learning\n and Stochastic Optimization`_.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-2)\n lr_decay (float, optional): learning rate decay (default: 0)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n\n .. _Adaptive Subgradient Methods for Online Learning and Stochastic\n Optimization: http://jmlr.org/papers/v12/duchi11a.html\n \"\"\"\n\n def __init__(self, params, lr=1e-2, lr_beta=0.0001, lr_decay=0, weight_decay=0, staleness=False):\n defaults = dict(lr=lr, lr_decay=lr_decay, lr_beta=lr_beta, weight_decay=weight_decay, staleness=staleness)\n super(Adagrad, self).__init__(params, defaults)\n\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['step'] = 1\n state['sum'] = torch.zeros_like(p.data).view(-1)\n\n def share_memory(self):\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['sum'].share_memory_()\n\n def step(self, rank=-1, total_ranks=1, staleness=1, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n super(Adagrad, self).step(rank, total_ranks, staleness)\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n\n state = self.state[p]\n\n chunked = False\n grad = p.grad.data.view(-1)\n data = p.data.view(-1)\n cur_sum = state['sum']\n if len(grad) > total_ranks > 1:\n chunked = True\n grad = grad.chunk(total_ranks)\n if rank < len(grad):\n grad = grad[rank]\n data = data.chunk(total_ranks)[rank]\n cur_sum = cur_sum.chunk(total_ranks)[rank]\n else:\n continue\n elif rank > 0:\n continue\n\n state['step'] += 1\n\n if group['weight_decay'] != 0:\n grad = grad.add(group['weight_decay'], data)\n\n clr = group['lr'] / (1 + (state['step'] - 1) * group['lr_decay'])\n\n cur_sum.addcmul_(1, grad, grad)\n std = cur_sum.sqrt().add_(group['lr_beta'])\n p.data.addcdiv_(-clr, grad, std)\n\n return loss\n\n\nclass Adam(BaseTorchPSOptimizer):\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False, staleness=False):\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad, staleness=staleness)\n super(Adam, self).__init__(params, defaults)\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data).view(-1)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data).view(-1)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data).view(-1)\n\n def __setstate__(self, state):\n super(Adam, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n\n def share_memory(self):\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['step'] = 0\n state['exp_avg'].share_memory_()\n state['exp_avg_sq'].share_memory_()\n if group['amsgrad']:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'].share_memory_()\n\n def step(self, rank=-1, total_ranks=1, staleness=1):\n super(Adam, self).step(rank, total_ranks, staleness)\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n chunked = False\n grad = p.grad.data.view(-1)\n data = p.data.view(-1)\n if len(grad) > total_ranks > 1:\n chunked = True\n grad = grad.chunk(total_ranks)\n if rank < len(grad):\n grad = grad[rank]\n data = data.chunk(total_ranks)[rank]\n else:\n continue\n elif rank > 0:\n continue\n\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n amsgrad = group['amsgrad']\n\n state = self.state[p]\n\n if state['step'] is None:\n state['step'] = 0\n state['step'] += 1\n step = state['step']\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if chunked:\n exp_avg = exp_avg.chunk(total_ranks)[rank]\n exp_avg_sq = exp_avg_sq.chunk(total_ranks)[rank]\n if amsgrad:\n max_exp_avg_sq = state['max_exp_avg_sq']\n if chunked:\n max_exp_avg_sq = max_exp_avg_sq.chunk(total_ranks)[rank]\n beta1, beta2 = group['betas']\n\n if group['weight_decay'] != 0:\n grad = grad.add(group['weight_decay'], data)\n\n # Decay the first and second moment running average coefficient\n\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = max_exp_avg_sq.sqrt().add_(group['eps'])\n else:\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** step\n bias_correction2 = 1 - beta2 ** step\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\n if staleness:\n step_size /= staleness\n\n data.addcdiv_(-step_size, exp_avg, denom)\n\n\nclass ParameterServerOptimizer(object):\n def __init__(self, *optimizers):\n self.threaded_optimizers = [x for x in optimizers if isinstance(x, FastEmbeddingOptimizerBase)]\n self.synchronous_optimizers = [x for x in optimizers if not isinstance(x, FastEmbeddingOptimizerBase)]\n\n def share_memory(self):\n for x in self.threaded_optimizers + self.synchronous_optimizers:\n x.share_memory()\n\n def synchronous_step(self, rank=-1, total_ranks=1, staleness=1):\n try:\n for x in self.synchronous_optimizers:\n x.step(rank, total_ranks, staleness)\n finally:\n _, exc, _ = sys.exc_info()\n if exc is not None:\n traceback.print_exc()\n\n def thread_step(self, rank=-1, total_ranks=1, staleness=0):\n try:\n for x in self.threaded_optimizers:\n x.step(rank, total_ranks, staleness)\n finally:\n _, exc, _ = sys.exc_info()\n if exc is not None:\n traceback.print_exc()\n\n def step(self, rank=-1, total_ranks=1, staleness=0):\n self.thread_step(rank, total_ranks, staleness)\n self.synchronous_step(rank, total_ranks, staleness)\n\n def model_dict(self):\n res = {\n \"threaded_optimizers\" : [opt.state_dict() for opt in self.threaded_optimizers],\n \"synchronous_optimizers\" : [opt.state_dict() for opt in self.synchronous_optimizers]\n }\n return res\n\n def load_model_dict(self, state_dict):\n assert len(self.threaded_optimizers) == len(state_dict.get(\"threaded_optimizers\", []))\n assert len(self.synchronous_optimizers) == len(state_dict.get(\"synchronous_optimizers\", []))\n\n for i, local_state_dict in enumerate(state_dict.get(\"threaded_optimizers\", [])):\n self.threaded_optimizers[i].load_state_dict(local_state_dict)\n for i, local_state_dict in enumerate(state_dict.get(\"synchronous_optimizers\", [])):\n self.synchronous_optimizers[i].load_state_dict(local_state_dict)\n","sub_path":"torch_ps/optim.py","file_name":"optim.py","file_ext":"py","file_size_in_byte":12726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"649272513","text":"import sopel.module\n\nbodypartsarray = ['head','chest','arm','junk','leg']\narmorarray = ['helmet','breastplate','gauntlets','codpiece','greaves']\n\n@sopel.module.commands('armor')\ndef mainfunction(bot, trigger):\n bot.say(\"testing armor\")\n for bodypart in bodypartsarray:\n armortype = array_compare(bot, bodypart, bodypartsarray, armorarray)\n bot.say(str(bodypart) + \" = \" + str(armortype))\n \n \n \ndef array_compare(bot, indexitem, arraytoindex, arraytocompare):\n item = ''\n for x, y in zip(arraytoindex, arraytocompare):\n if x == indexitem:\n item = y\n return item\n \n \n","sub_path":"modules/testexamples/armor.py","file_name":"armor.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"648529058","text":"import xml.etree.cElementTree as ET\r\nfrom collections import defaultdict\r\nimport re\r\nimport pprint\r\n\r\nOSMFILE = \"delaware_beach.osm\"\r\nstreet_type_re = re.compile(r'\\b\\S+\\.?$', re.IGNORECASE)\r\n\r\n\r\nexpected = [\"Boardwalk\", \"Street\", \"Avenue\", \"Boulevard\", \"Drive\", \"Court\", \"Place\", \"Square\", \"Lane\", \"Road\",\r\n \"Trail\", \"Parkway\", \"Commons\",\"Crescent\",\"Close\",\"East\",\"West\",\"North\",\"South\",\"Way\",\"Terrace\"]\r\n\r\n# UPDATE THIS VARIABLE\r\nmapping = { \"St\": \"Street\",\r\n \"St.\": \"Street\",\r\n \"Blvd\": \"Boulevard\",\r\n \"Blvd.\": \"Boulevard\",\r\n \"Ave\": \"Avenue\",\r\n \"Ave.\": \"Avenue\",\r\n \"Rd\": \"Road\",\r\n \"STREET\": \"Street\",\r\n \"avenue\": \"Avenue\",\r\n \"street\": \"Street\",\r\n \"E\": \"East\",\r\n \"W\": \"West\",\r\n \"Ln\": \"Lane\",\r\n \"Cout\": \"Court\",\r\n \"Hwy\": \"Highway\",\r\n \"N\": \"North\",\r\n \"S\": \"South\",\r\n \"Bdwk\": \"Boardwalk\"\r\n }\r\n\r\n\r\ndef audit_street_type(street_types, street_name):\r\n m = street_type_re.search(street_name)\r\n if m:\r\n street_type = m.group()\r\n if street_type not in expected:\r\n street_types[street_type].add(street_name)\r\n\r\n\r\ndef is_street_name(elem):\r\n return (elem.attrib['k'] == \"addr:street\")\r\n\r\n\r\ndef audit(osmfile):\r\n osm_file = open(osmfile, \"r\")\r\n street_types = defaultdict(set)\r\n for event, elem in ET.iterparse(osm_file, events=(\"start\",)):\r\n\r\n if elem.tag == \"node\" or elem.tag == \"way\":\r\n for tag in elem.iter(\"tag\"):\r\n if is_street_name(tag):\r\n audit_street_type(street_types, tag.attrib['v'])\r\n print (street_types)\r\n break\r\n osm_file.close()\r\n return street_types\r\n\r\n\r\ndef update_name(name, mapping):\r\n\r\n for key, value in mapping.iteritems():\r\n if re.search(key, name):\r\n name = re.sub(street_type_re, value, name)\r\n\r\n return name\r\n\r\n\r\ndef do_things():\r\n st_types = audit(OSMFILE)\r\n pprint.pprint(dict(st_types))\r\n\r\n return\r\n\r\nif __name__ == '__main__':\r\n do_things()","sub_path":"clean_streets_audit.py","file_name":"clean_streets_audit.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"250734260","text":"'''\nFind the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...\n\nNote:\nn is positive and will fit within the range of a 32-bit signed integer (n < 231).\n\nExample 1:\n\nInput:\n3\n\nOutput:\n3\nExample 2:\n\nInput:\n11\n\nOutput:\n0\n\nExplanation:\nThe 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of \nthe number 10.\n'''\n\ndef nth_digit(n):\n start, size, step = 1, 1, 9\n\n while n > size * step:\n n, start, size, step = n - size * step, start * 10, size + 1, step * 10\n\n return int(str(start + (n - 1) // size)[(n - 1) % size])\n\ndef nth_digit_v2(n):\n start, size = 1, 1\n\n while n > size:\n n, start = n - size, start + 1\n size = len(str(start))\n\n return int(str(start)[n-1])\n\n","sub_path":"algorithms/math/nth_digit.py","file_name":"nth_digit.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"430082362","text":"import datetime, inspect\nfrom paw_wis.sequencers import Sequence\nfrom paw_wis.tasks import Task\nfrom paw_wis import debugging\nfrom paw_wis.sqs import SQSClient, SQSQueues\n\n\nclass SampleTask(Task):\n '''\n This is an example task.\n '''\n def __init__(self, task_output_queue, sqs_client, task_pickup_queue=None, echo_text=None, show_timestamp=True, set_error=False):\n '''\n This is an example task that will produce a message for another example task to consume\n :param task_output_queue: String with the queue name of where messages will be posted\n :param sqs_client: SQSClient instance\n :param task_pickup_queue: [OPTIONAL] String with queue to check for messages to process. DEFAULT=None\n :param echo_text: [OPTIONAL] String with text to echo. DEFAULT=None\n :param show_timestamp: Boolean to indicate if timestamps must be shown. DEFAULT=True\n :param set_error: Boolean to indicate if this task must set an error condition. DEFAULT=False\n '''\n debugging.debug_dump(\"example_queue: %s\" % sqs_client.queues.is_queue_managed('example_queue'), line_number=inspect.currentframe().f_lineno, stack=\"%s\" % inspect.getfile(inspect.currentframe()))\n super(SampleTask, self).__init__(task_pickup_queue, task_output_queue, sqs_client)\n if echo_text is None:\n self.init_params['Echo'] = ''\n else:\n self.init_params['Echo'] = echo_text\n self.init_params['DateStr'] = None\n if show_timestamp is not None:\n self.init_params['DateStr'] = datetime.datetime.now().strftime('%Y-%m-%d %X')\n self.init_params['Err'] = set_error\n\n def run(self):\n print(\"*** I am a running SampleTask() instance...\")\n if 'QueuedData' in self.init_params:\n self.init_params['Echo'] = \"Data from Queue: %s\" % self.init_params['QueuedData']\n if self.init_params['DateStr'] is not None:\n self.data = '[%s] %s' % (self.init_params['DateStr'], self.init_params['Echo'])\n else:\n self.data = '[No DateStr Data] %s' % self.init_params['Echo']\n if 'Err' in self.init_params or 'Error' in self.init_params:\n self.is_error = self.init_params['Err']\n if self.is_error:\n self.data = '[ERROR RAISED] %s' % self.data\n debugging.debug_dump(\"MY DATA: %s\" % self.data, line_number=inspect.currentframe().f_lineno, stack=\"%s\" % inspect.getfile(inspect.currentframe()))\n print(\"*** DATA: %s\" % self.data)\n print(\"*** DONE\")\n\n\nclass SampleSequence(Sequence):\n def __init__(self, show_timestamps=True, set_error=False, tasks_to_use=('t1', 't2')):\n q = SQSQueues()\n if q.is_queue_managed('example_queue') is False:\n q.create_queue('example_queue')\n debugging.debug_dump(\"queue 'example_queue' managed: %s\" % q.is_queue_managed('example_queue'), line_number=inspect.currentframe().f_lineno, stack=\"%s\" % inspect.getfile(inspect.currentframe()))\n # task_output_queue, sqs_client, task_pickup_queue=None, echo_text=None, show_timestamp=True, set_error=False\n t1 = SampleTask(task_output_queue='example_queue', sqs_client=SQSClient(q), echo_text='SampleSequence is working!', show_timestamp=show_timestamps, set_error=set_error)\n t2 = SampleTask(task_output_queue='example_queue', sqs_client=SQSClient(q), task_pickup_queue='example_queue', echo_text=None, show_timestamp=show_timestamps, set_error=set_error)\n final_tasks = []\n for t2use in tasks_to_use:\n if t2use == 't1':\n final_tasks.append(t1)\n elif t2use == 't2':\n final_tasks.append(t2)\n final_tasks = tuple(final_tasks)\n super(SampleSequence, self).__init__(final_tasks)\n\n\nSampleSequence(tasks_to_use=('t1', 't2'))","sub_path":"tests/sequencer_test_01.py","file_name":"sequencer_test_01.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"645215798","text":"from __future__ import division\nfrom numpy.linalg import norm\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport model_aggregator\nimport softmax_model_test\nimport softmax_model_obj\nimport poisoning_compare\nimport heapq\nimport numpy as np\nimport utils\n\nimport pdb\nimport sys\n\nnp.set_printoptions(suppress=True)\n\n\n# Just a simple sandbox for testing out python code, without using Go.\ndef debug_signal_handler(signal, frame):\n import pdb\n pdb.set_trace()\n\n\nimport signal\n\nsignal.signal(signal.SIGINT, debug_signal_handler)\n\n\ndef basic_conv(dataset, num_params, softmax_test, iterations=3000):\n batch_size = 5\n\n # Global\n # numFeatures = softmax_model.init(dataset, epsilon=epsilon)\n softmax_model = softmax_model_obj.SoftMaxModel(dataset, numClasses)\n\n print(\"Start training\")\n\n weights = np.random.rand(num_params) / 100.0\n\n train_progress = np.zeros(iterations)\n test_progress = np.zeros(iterations)\n\n for i in range(iterations):\n deltas = softmax_model.privateFun(1, weights, batch_size)\n weights = weights + deltas\n\n if i % 100 == 0:\n print(\"Train error: %.10f\" % softmax_test.train_error(weights))\n\n print(\"Done iterations!\")\n print(\"Train error: %d\", softmax_test.train_error(weights))\n print(\"Test error: %d\", softmax_test.test_error(weights))\n return weights\n\n\ndef rescale(x, a, b):\n minNum = np.min(x)\n maxNum = np.max(x)\n return (b - a) * (x - minNum) / (maxNum - minNum) + a\n\n\ndef cos(vecA, vecB):\n return np.dot(vecA, vecB) / (np.linalg.norm(vecA) * np.linalg.norm(vecB))\n\n\n# Variant of non_iid, where noise is added to poisoner_indices\ndef non_iid(model_names, numClasses, numParams, softmax_test, topk_prop, iterations=3000, numSybils=2,\n ideal_attack=False, poisoner_indices=[], solution=None):\n batch_size = 50\n topk = int(numParams / 10)\n\n list_of_models = []\n\n for dataset in model_names:\n list_of_models.append(softmax_model_obj.SoftMaxModel(dataset, numClasses))\n\n # Include the model that sends the ideal vector on each iteration\n if ideal_attack:\n list_of_models.append(softmax_model_obj.SoftMaxModelEvil(dataPath +\n \"_bad_ideal_4_9\", numClasses))\n\n numClients = len(list_of_models)\n model_aggregator.init(numClients, numParams, numClasses)\n\n print(\"\\nStart training across \" + str(numClients) + \" clients with solution \" + str(solution) + '.')\n\n weights = np.random.rand(numParams) / 100.0\n lr = np.ones(numClients, )\n acc_in_iterations = []\n delta_all = []\n train_progress = []\n norm_progress = []\n loss_progress = []\n\n summed_deltas = np.zeros((numClients, numParams))\n\n for i in range(iterations):\n\n delta = np.zeros((numClients, numParams))\n\n # Significant features filter\n # sig_features_idx = np.argpartition(weights, -topk)[-topk:]\n sig_features_idx = np.arange(numParams)\n\n for k in range(len(list_of_models)):\n delta[k, :], _ = list_of_models[k].privateFun(weights, batch_size)\n\n # normalize delta\n if np.linalg.norm(delta[k, :]) > 1:\n delta[k, :] = delta[k, :] / np.linalg.norm(delta[k, :])\n\n # Add adversarial noise\n noisevec = rescale(np.random.rand(numParams), np.min(delta), np.max(delta))\n delta[poisoner_indices[0], :] = delta[poisoner_indices[0], :] + noisevec\n delta[poisoner_indices[1], :] = delta[poisoner_indices[1], :] - noisevec\n\n # Track the total vector from each individual client\n summed_deltas = summed_deltas + delta\n if solution:\n if solution == 'fg':\n # Use Foolsgold\n this_delta = model_aggregator.foolsgold(delta, summed_deltas, sig_features_idx, i, weights, lr,\n topk_prop,\n importance=False, importanceHard=True)\n if solution == 'ours':\n this_delta, lr = model_aggregator.foolsgold2(delta, summed_deltas, sig_features_idx, i, weights, lr,\n topk_prop,\n importance=False, importanceHard=True)\n if solution == 'krum':\n # Krum\n this_delta = model_aggregator.krum(delta, clip=1)\n if solution == 'average':\n this_delta = model_aggregator.average(delta)\n if solution == 'median':\n this_delta = model_aggregator.median(delta)\n if solution == 'trimmed_mean':\n this_delta = model_aggregator.trimmed_mean(delta, 0.2)\n else:\n this_delta = np.dot(delta.T, lr)\n\n weights = weights + this_delta\n\n if i % 10 == 0:\n delta_index = heapq.nlargest(20, range(len(this_delta)), this_delta.take)\n delta_each_client = []\n for idx in delta_index:\n delta_each_client.append(np.hstack(([i, idx], delta[:, idx], this_delta[idx])))\n delta_all.append(delta_each_client)\n norm_progress.append(np.mean(np.linalg.norm(delta, axis=1)))\n test_error = softmax_test.test_error(weights)\n train_progress.append(test_error)\n acc_in_iterations.append(\n [test_error] + list(poisoning_compare.eval(Xtest, ytest, weights, int(from_class), int(to_class),\n numClasses, numFeatures, verbose=False)))\n\n # if i % 100 == 0:\n # print(\"Validation error: %.5f\" % test_error)\n column = ['iteration', 'deltaInxex'] + ['client{}'.format(i) for i in range(numClients)] + ['combined']\n pd.DataFrame(columns=column,\n data=np.reshape(delta_all, (-1, len(column)))).to_csv(\n '_'.join(argv) + '_' + str(solution) + '_delta.csv')\n test_error = softmax_test.test_error(weights)\n acc_in_iterations.append(\n [test_error] + list(poisoning_compare.eval(Xtest, ytest, weights, int(from_class), int(to_class),\n numClasses, numFeatures, verbose=True)))\n # column = ['iteration', 'Test error', 'Accuracy overall', 'Accuracy on other digits',\n # 'Target Accuracy on source label',\n # 'Target Accuracy on target label', 'Target Attack Rate']\n # acc_in_iterations = np.insert(acc_in_iterations, 0, values=np.arange(0, iterations + 1, 10), axis=1)\n # res = pd.DataFrame(columns=column, data=acc_in_iterations)\n # res.to_csv('_'.join(argv) + '_' + str(solution) + '.csv')\n print(\"Done iterations!\")\n print(\"Train error: {}\".format(softmax_test.train_error(weights)))\n print(\"Test error: {}\".format(softmax_test.test_error(weights)))\n # pdb.set_trace()\n # import sklearn.metrics.pairwise as smp\n # cs = smp.cosine_similarity(summed_deltas)\n return weights\n\n\n# amazon: 50 classes, 10000 features\n# mnist: 10 classes, 784 features\n# kdd: 23 classes, 41 features\nif __name__ == \"__main__\":\n argv = sys.argv[1:]\n\n dataset = argv[0]\n iterations = int(argv[1])\n\n if dataset == \"mnist\":\n numClasses = 10\n numFeatures = 784\n elif dataset == \"kddcup\":\n numClasses = 23\n numFeatures = 41\n elif dataset == \"amazon\":\n numClasses = 50\n numFeatures = 10000\n else:\n print(\"Dataset \" + dataset + \" not found. Available datasets: mnist kddcup amazon\")\n\n numParams = numClasses * numFeatures\n dataPath = dataset + \"/\" + dataset\n\n full_model = softmax_model_obj.SoftMaxModel(dataPath + \"_train\", numClasses)\n Xtest, ytest = full_model.get_data()\n\n models = []\n\n for i in range(numClasses):\n # Try a little more IID\n models.append(dataPath + str(i)) # + str((i + 1) % 10) + str((i\n # + 2) % 10))\n from_class = to_class = None\n for attack in argv[2:]:\n attack_delim = attack.split(\"_\")\n sybil_set_size = attack_delim[0]\n from_class = attack_delim[1]\n to_class = attack_delim[2]\n for i in range(int(sybil_set_size)):\n models.append(dataPath + \"_bad_\" + from_class + \"_\" + to_class)\n\n softmax_test = softmax_model_test.SoftMaxModelTest(dataset, numClasses, numFeatures)\n # Hard code poisoners in a 2_x_x attack\n eval_data = np.ones((10, 5))\n for eval_i in range(1):\n topk_prop = 0.1 + eval_i * .1\n\n weights = non_iid(models, numClasses, numParams, softmax_test, topk_prop, iterations, int(sybil_set_size),\n ideal_attack=False, poisoner_indices=[10, 11], solution=None)\n non_iid(models, numClasses, numParams, softmax_test, topk_prop, iterations, int(sybil_set_size),\n ideal_attack=False, poisoner_indices=[10, 11], solution='ours')\n non_iid(models, numClasses, numParams, softmax_test, topk_prop, iterations, int(sybil_set_size),\n ideal_attack=False, poisoner_indices=[10, 11], solution='krum')\n non_iid(models, numClasses, numParams, softmax_test, topk_prop, iterations, int(sybil_set_size),\n ideal_attack=False, poisoner_indices=[10, 11], solution='median')\n non_iid(models, numClasses, numParams, softmax_test, topk_prop, iterations, int(sybil_set_size),\n ideal_attack=False, poisoner_indices=[10, 11], solution='trimmed_mean')\n\n # for attack in argv[2:]:\n # attack_delim = attack.split(\"_\")\n # from_class = attack_delim[1]\n # to_class = attack_delim[2]\n # score = poisoning_compare.eval(Xtest, ytest, weights, int(from_class), int(to_class), numClasses,\n # numFeatures)\n # eval_data[eval_i] = score\n #\n # np.savetxt('hard_topk_eval_data.csv', eval_data, '%.5f', delimiter=\",\")\n # # Sandbox: difference between ideal bad model and global model\n # compare = False\n # if compare:\n # bad_weights = basic_conv(dataPath + \"_bad_ideal_\" + from_class + \"_\" +\n # to_class, numParams, softmax_test)\n # poisoning_compare.eval(Xtest, ytest, bad_weights, int(from_class),\n # int(to_class), numClasses, numFeatures)\n\n # diff = np.reshape(bad_weights - weights, (numClasses, numFeatures))\n # abs_diff = np.reshape(np.abs(bad_weights - weights), (numClasses,\n # numFeatures))\n\n # pdb.set_trace()\n","sub_path":"ML/code/ML_noisyPoisoners.py","file_name":"ML_noisyPoisoners.py","file_ext":"py","file_size_in_byte":10494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"39494491","text":"\"\"\"\n This spider is a Recruitacommunity spider created on top of the ATSSpider\n scrapy crawl recruitacommunity -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://www.recruitacommunity.com/srctcb/RTI.home?t=7465\"\n\n sample seed url:\n https://www.recruitacommunity.com/srctcb/RTI.home?t=11265\n https://www.recruitacommunity.com/srctcb/RTI.home?t=62664\n https://www.recruitacommunity.com/srctcb/RTI.home?t=56260\n\n sample job url:\n https://www.recruitacommunity.com/srctcb/reqDetails.ajax?_reqID=5000017188110&_tcbWidgetID=164965\n\"\"\"\n\nfrom urllib import urlencode\nfrom re import compile, sub\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, Replace, NormalizedJoin\n\n\nclass Recruitacommunity(ATSSpider):\n\n name = \"recruitacommunity\"\n handle_httpstatus_list = [404]\n download_delay = 1\n Redirect_Url = compile(r\",\\s*'(.*searchResults.page)',\")\n Widget_Id = compile(r'\"&_tcbWidgetID=(\\d+)\"')\n Job_Url = compile(r\"(_reqID=(\\S+)&_tcbWidgetID=\\S+)&_popup=\")\n Company_Id = compile(r\"\\?t=(\\d+)\")\n company_id = ''\n Location_Re = compile(r\"(\\(.*\\))\")\n cur_page = 0\n item_map = {\n 'Title': 'title',\n 'Location': 'location',\n 'Company Name': 'company',\n 'Position Title:': 'title',\n 'Location:': 'location',\n 'Job Family:': 'jobcategory',\n 'Position Type:': 'jobtype',\n 'City': 'city',\n 'State': 'state',\n 'Job Function': 'jobcategory',\n }\n\n def __init__(self, *args, **kwargs):\n super(Recruitacommunity, self).__init__(*args, **kwargs)\n\n self.company_id = self.Company_Id.search(self.start_urls[0])\n if self.company_id:\n self.company_id = self.company_id.group(1)\n\n def parse(self, response):\n redirect_url = response.xpath('//script').re(self.Redirect_Url)\n widget_id = response.xpath('//script').re(self.Widget_Id)\n if redirect_url and widget_id:\n params = {\n '_tcbWidgetID': widget_id[0],\n '_wrenderer_SEARCH_resultsStart': str(self.cur_page)\n }\n url = urljoin(\n response.url, '/srctcb%s?%s' % (\n redirect_url[0], urlencode(params)\n )\n )\n yield Request(\n callback=self.parse_jobs_list,\n url=url\n )\n\n def parse_jobs_list(self, response):\n selector = Selector(response)\n tableheads = selector.xpath(\n '//table[@class=\"tcbReqs\"]/thead//span[@class=\"tcbSearch_resultsHeader\"]/text()'\n ).extract()\n jobs = selector.xpath(\n '//table[@class=\"tcbReqs\"]//tr[contains(@class, \"tcbReqs\")]')\n for job in jobs:\n url = job.xpath('./td/a/@href').re(self.Job_Url)\n if url:\n meta = {}\n for index, th in enumerate(tableheads):\n if th in self.item_map:\n meta[self.item_map[th]] = job.xpath(\n \"./td[\" + str(index + 1) + \"]//text()\").extract()\n\n meta['ref_num'] = url[1]\n\n job_url = urljoin(\n response.url, '/srctcb/reqDetails.ajax?%s' % url[0]\n )\n yield Request(\n callback=self.parse_job_callback(),\n meta=meta,\n url=job_url\n )\n\n next_page = selector.xpath(\n '//div[@class=\"tcbSearch_nextPage\"]/input/@value').extract()\n if next_page:\n self.cur_page += 5\n yield Request(\n callback=self.parse_jobs_list,\n url=sub(\n '_wrenderer_SEARCH_resultsStart=(\\d+)',\n '_wrenderer_SEARCH_resultsStart=%s' % (self.cur_page),\n response.url\n )\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n url = urljoin(\n response.url, '/srctcb/RTI.home?t=%(company)s&r=%(ref_id)s' % {\n 'company': self.company_id,\n 'ref_id': response.meta.get('ref_num')\n }\n )\n desc_xpath = '//td[contains(text(), \"%s\")]/../following-sibling::tr[1]'\n\n loader.add_xpath(\n 'description',\n desc_xpath % 'Description'\n )\n loader.add_xpath(\n 'requirements', desc_xpath % 'Requirements'\n )\n\n loader.add_value(\n 'referencenumber', response.meta.get('ref_num'),\n Prefix('%s-%s-' % (self.name, self.company_id))\n )\n loader.add_value(\n 'location', response.meta.get('location'),\n Replace('Working at Home;'), Replace(self.Location_Re)\n )\n if not loader.get_output_value('location'):\n loc = [response.meta.get(i)[0] for i in ['city', 'state'] if response.meta.get(i)]\n loader.add_value('location', loc, NormalizedJoin(\", \"))\n\n loader.add_value('jobcategory', response.meta.get('jobcategory'))\n loader.add_value('jobtype', response.meta.get('jobtype'))\n loader.add_value('company', response.meta.get('company'))\n loader.add_value('title', response.meta.get('title', ''))\n loader.add_value('url', url)\n loader.add_value('apply_url', url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/recruitacommunity.py","file_name":"recruitacommunity.py","file_ext":"py","file_size_in_byte":5583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"213781682","text":"from mudwyrm_users.admin.achaea.trigger import Trigger, Alias, OnEvent\r\n\r\np = None\r\n\r\ndef init(processor):\r\n assert processor is not None\r\n global p\r\n p = processor\r\n \r\n\r\n#@OnEvent('BalanceChanged')\r\n#def on_balance_changed(type):\r\n# if balance(type):\r\n# p.echo(\"Balance gained: %s\" % type)\r\n# else:\r\n# p.echo(\"Balance lost: %s\" % type)\r\n\r\n@OnEvent('StatusChanged')\r\ndef on_status_changed(type, value):\r\n if value:\r\n p.hecho(('div', 'script', [\"%s is \" % type, ('span', 'green', \"up\"), \".\"]))\r\n p.debug(\"%s status is up.\" % type)\r\n else:\r\n p.hecho(('div', 'script', [\"%s is \" % type, ('span', 'red', \"down\"), \".\"]))\r\n p.debug(\"%s status is down.\" % type)\r\n","sub_path":"mudwyrm_users/admin/achaea/scripts/highlights.py","file_name":"highlights.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"388926120","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields, api\nimport datetime\nfrom dateutil.relativedelta import relativedelta\nfrom openerp.exceptions import Warning, ValidationError\nfrom num2words import num2words\n\n\nclass jmdcalculator(models.Model):\n _inherit = \"mail.thread\"\n _name = \"sofom.calculator\"\n\n @api.depends('lineas')\n def get_pago(self):\n for record in self:\n monto = 0\n for linea in record.lineas:\n monto = linea.total\n if record.frecuencia == \"26\":\n monto *= 2\n elif record.frecuencia == \"52\":\n monto *= 4\n record.pago = monto\n\n @api.one\n def get_comision(self):\n monto = 0\n if self.producto == \"nom\":\n if self.monto < 9000:\n monto = self.monto * 0.03\n elif self.monto >= 9000:\n monto = 406\n self.comision = monto\n\n @api.one\n def get_centavos(self):\n centavos = round(self.monto - int(self.monto), 2)\n self.centavos = str(int(centavos * 100)).zfill(2)\n\n @api.one\n def get_letra(self):\n self.monto_letra = num2words(self.monto, lang='es').upper()\n\n @api.one\n def get_tasaletra(self):\n tasa = round(self.tasa.name, 1)\n entero = (int(tasa))\n decimal = round(tasa - int(tasa), 2) * 100\n self.tasa_letra = num2words(entero, lang='es').upper() + \" PUNTO \" +\\\n num2words(decimal, lang='es').upper()\n\n name = fields.Char(\"Descripción\", default=lambda self: self.\n env[\"ir.sequence\"].get(\"sofom.calculator\"))\n monto = fields.Float(\"Monto\")\n monto_letra = fields.Char(\"Monto con Letra\", compute=get_letra)\n total = fields.Float(\"Total del Prestamo\")\n ciclo = fields.Integer(\"Ciclo\", related=\"lead.partner_id.ciclo\",\n store=\"True\")\n producto = fields.Selection([(\"micro\", \"Microcrédito\"),\n (\"nom\", \"Nómina\")], string=\"Producto\", related=\"lead.producto\",\n store=True)\n pagos = fields.Integer(\"Numero de Pagos\")\n tipo = fields.Selection([(\"no\", \"Principal\"),\n (\"si\", \"Interciclo\"), ('an', \"Anticipo de Nómina\")], string=\"Tipo\")\n tasa = fields.Many2one(\"sofom.tasa\", string=\"Tasa mensual\")\n tasa_letra = fields.Char(\"Tasa Letra\", compute=get_tasaletra)\n inicio = fields.Date(\"Fecha de inicio\")\n lineas = fields.One2many(\"sofom.calculator.line\", \"calculator\", \"Lineas\")\n lead = fields.Many2one(\"crm.lead\", string=\"Prospecto\")\n frecuencia = fields.Selection([(\"26\", \"Quincenal\"), (\"52\", \"Semanal\"),\n (\"12\", \"Mensual\")], string=\"Frecuencia\")\n plazo = fields.Many2one(\"sofom.plazo\", string=\"Plazo\")\n pago = fields.Float(\"Pago Mensual\", compute=get_pago)\n destino = fields.Many2one(\"sofom.destino\", string=\"Destino de Crédito\")\n apertura = fields.Float(\"Comisión por apertura\")\n cat = fields.Float(\"CAT\")\n partner_id = fields.Many2one(\"res.partner\",\n string=\"Cliente\", related=\"lead.partner_id\")\n ciclo_principal = fields.Many2one(\"sofom.credito\", string=\"Ciclo Principal\")\n tope = fields.Float(\"Tope del Crédito\",\n related=\"plazo.monto_max\")\n comision = fields.Float(\"Comisión por Apertura\", compute=get_comision)\n\n total_intereses = fields.Float(\"Total Intereses\")\n total_iva = fields.Float(\"Total IVA\")\n centavos = fields.Char(\"Centavos\", compute=get_centavos)\n\n @api.onchange('monto')\n def onchange_monto(self):\n if self.monto > self.tope:\n self.monto = 0.0\n self.write({'monto': 0.0})\n raise Warning('Excede el tope del monto')\n return False\n\n @api.multi\n def c_delete(self):\n for i in self.lineas:\n i.unlink()\n\n @api.one\n @api.constrains('monto')\n def check_monto(self):\n if self.monto > self.tope:\n raise ValidationError(\"El monto cotizado excede el tope permitido\")\n\n def c_payment(self, cr, uid, ids, context=None):\n ret = {}\n for i in self.browse(cr, uid, ids, context):\n #finicio = datetime.srtptime(i.inicio, \"%Y-%m-%d\")\n insoluto = i.monto\n interes_periodo = i.tasa.name / (float(i.plazo.frecuencia) / 12)\n pago_fijo = i.calculate_payment(insoluto, interes_periodo,\n i.plazo.pagos)\n dias_plazo = i.plazo.dias_ciclo\n meses_plazo = i.plazo.meses_ciclo\n inicio_obj = datetime.datetime.strptime(i.inicio, \"%Y-%m-%d\")\n siguiente_pago = inicio_obj\n gran_total = 0\n total_iva = 0\n total_intereses = 0\n for j in range(i.plazo.pagos):\n line_obj = self.pool.get(\"sofom.calculator.line\")\n interes = i.calculate_interest(interes_periodo, insoluto)\n capital = i.calculate_capital(interes, pago_fijo)\n insoluto -= capital\n iva = (interes / 1.16) * 0.16\n total = pago_fijo\n gran_total += total\n total_iva += iva\n total_intereses += interes\n print((\"Numero de pago \" + str(j)))\n line_obj.create(cr, uid, {\n 'calculator': i.id,\n 'fecha': siguiente_pago.strftime(\"%Y-%m-%d\"),\n 'monto': pago_fijo,\n 'npago': str((j + 1)),\n 'capital': capital,\n 'intereses': interes,\n 'iva': iva,\n 'total': total,\n 'restante': insoluto,\n })\n self.write(cr, uid, ids, {'pago': total})\n siguiente_pago += datetime.timedelta(days=dias_plazo)\n siguiente_pago += relativedelta(months=+meses_plazo)\n self.write(cr, uid, [i.id], {'total': gran_total,\n 'total_iva': total_iva, 'total_intereses': total_intereses})\n return ret\n\n def calculate_payment(self, prestamo, interes, numero_cuotas):\n interes = interes / 100\n return prestamo * (interes * ((interes + 1) ** numero_cuotas)) / \\\n (((interes + 1) ** numero_cuotas) - 1)\n\n def calculate_interest(self, interes, capital_pendiente):\n return (interes / 100) * capital_pendiente\n\n def calculate_capital(self, monto_interes, monto_pago):\n return monto_pago - monto_interes\n\n\nclass jmdcalculatorline(models.Model):\n _name = \"sofom.calculator.line\"\n name = fields.Char(\"Nombre\")\n calculator = fields.Many2one(\"sofom.calculator\", \"Calculator\")\n fecha = fields.Date(\"Fecha\")\n monto = fields.Float(\"Monto\")\n npago = fields.Char(\"Periodo\")\n capital = fields.Float(\"Capital\")\n intereses = fields.Float(\"Intereses\")\n iva = fields.Float(\"IVA\")\n total = fields.Float(\"Pago Total\")\n restante = fields.Float(\"Capital Restante\")","sub_path":"sofom/cotizador.py","file_name":"cotizador.py","file_ext":"py","file_size_in_byte":6830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"233737102","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Jesse Rubin - project Euler\n\"\"\"\nSub-string divisibility\nProblem 43\nThe number, 1406357289, is a 0 to 9 pandigital number because it is made up\nof each of the digits 0 to 9 in some order, but it also has a rather\ninteresting sub-string divisibility property.\n\nLet d1 be the 1st digit, d2 be the 2nd digit, and so on.\nIn this way, we note the following:\n\nd2d3d4=406 is divisible by 2\nd3d4d5=063 is divisible by 3\nd4d5d6=635 is divisible by 5\nd5d6d7=357 is divisible by 7\nd6d7d8=572 is divisible by 11\nd7d8d9=728 is divisible by 13\nd8d9d10=289 is divisible by 17\n\nFind the sum of all 0 to 9 pandigital numbers with this property.\n\"\"\"\n\nfrom bib.listless import int_from_digits\nfrom itertools import permutations\n\n\ndef pandigital_substring_thing(pandigit_list):\n if pandigit_list[0] == 0:\n return False # leading 0 shouldnt count\n else:\n div_primes = [2, 3, 5, 7, 11, 13, 17]\n for i in range(1, 8):\n if int_from_digits(pandigit_list[i:i + 3]) % div_primes[i - 1] != 0:\n return False\n return True\n\n\ndef p043():\n # well_they_gave_us_this_one = [1,4,0,6,3,5,7,2,8,9]\n # test_answer = pandigital_substring_thing(well_they_gave_us_this_one)\n # print(test_answer)\n circle_to_nine = [i for i in range(0, 10)] # circle is the way kids say 0 now a days\n pandigit_lists = [int_from_digits(i) for i in permutations(circle_to_nine) if pandigital_substring_thing(i)]\n return sum(pandigit_lists)\n\n\nif __name__ == '__main__':\n ans = p043()\n print(\"Sum of products: {}\".format(ans))\n","sub_path":"done/py/euler_043.py","file_name":"euler_043.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"475583696","text":"# Create your views here.\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotFound\nfrom django.template import RequestContext\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\nimport simplejson, re\nfrom django.db import connection\nfrom datetime import datetime\nfrom django.http import Http404\nfrom django.core.urlresolvers import resolve\nfrom decimal import *\nfrom annotation_server.models import *\nfrom annotation_server.utils import *\nimport logging\nfrom django.db.models import Q\n\n# get module logger\nlogger = logging.getLogger(__name__)\n\ndef search_genes(request, genome, search_string):\n \"\"\" \n Function for searching basic gene table currently: Ensembl (EnsGene table from UCSC genome browser)\n \"\"\"\n logger.debug(\"annotation_server.search_genes called for genome: %s search: %s\" % (genome, search_string)) \n \n if genome in SUPPORTED_GENOMES:\n current_table = eval(genome+ \"_EnsGene\")\n curr_vals = current_table.objects.filter(\n Q(name__contains=search_string) | Q(name2__contains=search_string)\n ).values('name', 'chrom', 'strand', 'txStart', 'txEnd', 'cdsStart', 'cdsEnd', 'exonCount', 'exonStarts', 'exonEnds')\n \n data = ValuesQuerySetToDict(curr_vals)\n return HttpResponse(data, 'application/json')\n else:\n return HttpResponse(status=400)\n \n # Postbio query\n #cursor = connection.cursor() \n #query = \"\"\"Select a.name, a.symbol, a.synonyms,\n #b.region as end, b.chrom FROM (SELECT name, symbol,\n #synonyms from dm3.flybase2004xref where symbol ilike '%s') a JOIN\n #(SELECT f.name, f.region, f.seq_id, s.name as chrom FROM dm3.flybase f JOIN\n #dm3.sequence s ON f.seq_id = s.id where s.name = 'chr2L' OR s.name = 'chr2R'\n #OR s.name = 'chr3L' OR s.name = 'chr3R' OR s.name = 'chr4' OR s.name =\n #'chrX' ) b ON a.name = b.name \"\"\" % (search_string)\n #cursor.execute(query)\n \n return HttpResponse(cursor_to_json(cursor), 'application/javascript')\n\ndef search_extended_genes(request, genome, search_string):\n \"\"\" \n Function for searching extended gene tables currently: GenCode (hg19), Flybase (dm3), or Wormbase (ce10)\n \"\"\"\n logger.debug(\"annotation_server.search_extended_genes called for genome: %s search: %s\" % (genome, search_string))\n\n\n # extended genes\n #url(r'^search_genes/(?P[a-zA-Z0-9]+)/(?P[a-zA-Z0-9]+)/$', 'search_genes' ),\n # extended genes\n #url(r'^get_genes/(?P[a-zA-Z0-9]+)/(?P[a-zA-Z0-9]+)/(?P[0-9]+)/(?P[0-9]+)/$', 'get_genes' ),\n \n\ndef get_sequence(request, genome, chrom, start, end):\n \"\"\" \n returns sequence for a specified chromosome start and end\n \"\"\"\n logger.debug(\"annotation_server.get_sequence called for genome: %s chrom: %s\" % (genome, chrom)) \n offset = int(end) - int(start)\n \n # NO SUBSTRING METHOD USING DJANGO ORM\n if genome in SUPPORTED_GENOMES:\n cursor = connection.cursor() \n db_table = 'annotation_server_dm3_sequence'\n query = \"\"\"select name as chrom, substr(seq, %s, %s) as seq from annotation_server_%s_sequence where name = '%s'\"\"\" % (start, offset, genome, chrom)\n cursor.execute(query)\n return HttpResponse(cursor_to_json(cursor), 'application/javascript') \n else:\n return HttpResponse(status=400)\n\n # POSTBIO QUERY\n #cursor = connection.cursor() \n #query = \"\"\"select name as chrom, substr(seq, %s, %s) as seq from %s.sequence where name = '%s'\"\"\" % (start, offset, genome, chrom)\n #cursor.execute(query)\n #return HttpResponse(cursor_to_json(cursor), 'application/javascript')\n\ndef get_length(request, genome):\n \"\"\"\n Returns all chromosome lengths depending on genome i.e. dm3, hg18, etc.\n \"\"\"\n logger.debug(\"annotation_server.get_length called for genome: %s\" % (genome)) \n \n if genome in SUPPORTED_GENOMES:\n current_table = eval(genome+ \"_ChromInfo\")\n data = ValuesQuerySetToDict(current_table.objects.values('chrom', 'size'))\n return HttpResponse(data, 'application/json')\n else:\n return HttpResponse(status=400)\n \n # POSTBIO QUERY\n #cursor = connection.cursor() \n #query = \"\"\"SELECT chrom, size from %s.chrominfo where chrom !~* '_' order by size desc\"\"\" % (genome) \n #cursor.execute(query)\n #return HttpResponse(cursor_to_json(cursor), 'application/javascript')\n\n\ndef get_chrom_length(request, genome, chrom):\n \"\"\"\n returns the length of a specified chromosome\n \"\"\"\n logger.debug(\"annotation_server.get_chrom_length called for genome: %s chromosome: %s\" % (genome, chrom)) \n \n if genome in SUPPORTED_GENOMES:\n current_table = eval(genome+ \"_ChromInfo\")\n curr_vals = current_table.objects.filter(chrom__iexact=chrom).values('chrom', 'size')\n data = ValuesQuerySetToDict(curr_vals)\n return HttpResponse(data, 'application/json')\n else:\n return HttpResponse(status=400)\n \n # TODO: return genome lengths according to chrom order i.e. 1,2,3 etc. \n #cursor = connection.cursor() \n #if (chrom):\n # query = \"\"\"SELECT chrom, size from %s.chrominfo where chrom ilike '%s'\"\"\" % (genome, chrom)\n #cursor.execute(query)\n #return HttpResponse(cursor_to_json(cursor), 'application/javascript')\n\ndef get_cytoband(request, genome, chrom):\n \"\"\"\n returns the length of a specified chromosome\n \"\"\"\n logger.debug(\"annotation_server.get_cytoband called for genome: %s chromosome: %s\" % (genome, chrom)) \n \n if genome in SUPPORTED_GENOMES:\n current_table = eval(genome+ \"_CytoBand\")\n curr_vals = current_table.objects.filter(chrom__iexact=chrom).values('chrom', 'chromStart', 'chromEnd', 'name', 'gieStain')\n data = ValuesQuerySetToDict(curr_vals)\n return HttpResponse(data, 'application/json')\n else:\n return HttpResponse(status=400)\n \n #cursor = connection.cursor() \n #query = \"\"\"SELECT s.name as chrom, #region as end, region_name from dm3.cytobandideo c join dm3.sequence s on s.id = c.seq_id where s.name ilike '%s' order by region;\"\"\" % (chrom)\n #cursor.execute(query)\n #return HttpResponse(cursor_to_json(cursor), 'application/javascript')\n\ndef get_genes(request, genome, chrom, start, end):\n \"\"\"\n gets a list of genes within a range i.e. gene start, cds, gene symbol\n \"\"\"\n logger.debug(\"annotation_server.get_genes called for genome: %s chromosome: %s\" % (genome, chrom)) \n \n if genome in SUPPORTED_GENOMES:\n current_table = eval(genome+ \"_EnsGene\")\n curr_vals = current_table.objects.filter(\n Q(chrom__iexact=chrom),\n Q(cdsStart__range=(start, end)) | Q(cdsEnd__range=(start, end))\n ).values('name', 'chrom', 'strand', 'txStart', 'txEnd', 'cdsStart', 'cdsEnd', 'exonCount', 'exonStarts', 'exonEnds')\n data = ValuesQuerySetToDict(curr_vals)\n return HttpResponse(data, 'application/json')\n else:\n return HttpResponse(status=400)\n \n \n # Postbio query\n #cursor = connection.cursor() \n #query = \"\"\"SELECT x.symbol, r.name, #r.region as end, case when r.same_orient then '+' else '-' end as strand, #r.cds as cds_end from dm3.flybase r join dm3.flyBase2004Xref x on r.name = x.name JOIN (select id, name from dm3.sequence where name = '%s') n ON n.id = r.seq_id and region && int_interval '(%s,%s)' order by region\"\"\" % (chrom, start, end)\n #cursor.execute(query) \n #return HttpResponse(cursor_to_json(cursor), 'application/javascript')\n\n'''\ndef get_exons(request, genome, chrom, start, end):\n #Get list of all gene exons within a specified range\n \n print \"annotation_server.get_exons\"\n \n cursor = connection.cursor() \n query = \"\"\"select x.symbol, r.name, s.name as chrom, case when r.same_orient then '+' else '-' end as strand, #r.region as gene_end, #e.region as exonend, exon_id from dm3.flybase r join dm3.sequence s on r.seq_id=s.id join dm3.flybase_exon ie on isoform_id=r.id join dm3.exon e on exon_id=e.id join dm3.flyBase2004Xref x on r.name = x.name where s.name = '%s' and r.region && int_interval'(%s,%s)' order by r.id, # ? AND time < ?\n GROUP BY sensor_id''', [from_time, to_time])\n return measurements\n\ndef timeline(sensor_id):\n \"\"\"\n Returns all measurements for one particular sensor.\n \"\"\"\n timeline = db.dict_query('''SELECT time, temperature FROM measurements\n WHERE sensor_id = ? ORDER BY time''', [sensor_id])\n return timeline\n\n\n\n","sub_path":"examples/i2maps_projects/modules/weather/sensors.py","file_name":"sensors.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"240770417","text":"#!/usr/bin/python\n\nimport re\n\npostcode = str(raw_input('Enter a postcode: '))\n\nm = re.search(r'^[A-Z]{2}[0-9][0-9]?\\s?[0-9][A-Z]{2}$', postcode, re.I)\n\nif m:\n\tprint('{} is valid'.format(m.group(0)))\nelse:\n\tprint('invalid')\n","sub_path":"regex/postcode.py","file_name":"postcode.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"576153974","text":"import time, functools\ndef metric(fn):\n\n # @functools.wraps(fn)\n def wrapper(*args,**kwargs):\n time_start=time.time()\n res=fn(*args,**kwargs)\n time_end=time.time()-time_start\n print('%s usertime %s ms'% (fn.__name__,1000*time_end))\n return res\n return wrapper\n# 测试\n@metric\ndef fast(x, y):\n time.sleep(0.0012)\n return x + y;\n\n@metric\ndef slow(x, y, z):\n time.sleep(0.1234)\n return x * y * z;\n\nf = fast(11, 22)\ns = slow(11, 22, 33)\nprint(f,s)\nif f == 33 and s == 7986:\n print('success!')\nelse:\n print('wrong')\n\nf = fast(22, 44)\ns = slow(22, 44, 66)\n\nprint(fast.__name__)\nprint(slow.__name__)","sub_path":"PythonBasic/DecoratorDemo.py","file_name":"DecoratorDemo.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"370991831","text":"import numpy as np\nfrom multiagent.core import World, Agent, Landmark\nfrom multiagent.scenario import BaseScenario\nimport math\nimport copy\n\nattack_angle = 90\ndefense_angle = 90\nfire_range = 0.3\ncomput_range = 0.6\n\n\nclass Scenario(BaseScenario):\n def make_world(self):\n print(\"**********liyuan scenario*************\")\n world = World()\n # set any world properties first\n world.dim_c = 2\n num_good_agents = 3\n num_adversaries = 3\n num_agents = num_adversaries + num_good_agents\n num_landmarks = 0\n\n self.num_green = copy.deepcopy(num_good_agents)\n self.num_red = copy.deepcopy(num_adversaries)\n # add agents\n world.agents = [Agent() for i in range(num_agents)]\n for i, agent in enumerate(world.agents):\n agent.name = 'agent %d' % i\n agent.collide = True\n agent.silent = True\n agent.adversary = True if i < num_adversaries else False\n agent.size = 0.04 if agent.adversary else 0.04\n #agent.accel = 3.0 if agent.adversary else 2.0\n agent.accel = 2.0 if agent.adversary else 2.0\n #agent.accel = 20.0 if agent.adversary else 25.0\n #agent.max_speed = 1.5 if agent.adversary else 1.2\n agent.max_speed = 1.0 if agent.adversary else 1.0\n #agent.max_speed = 1.0 if agent.adversary else 0.3 ###changed by liyuan\n agent.death = False\n\n agent.chi = np.array([0.1,0])\n\n if agent.adversary:\n agent.lock_num=[0 for j in range(num_good_agents)]\n else:\n agent.lock_num=[0 for j in range(num_adversaries)]\n # add landmarks\n world.landmarks = [Landmark() for i in range(num_landmarks)]\n for i, landmark in enumerate(world.landmarks):\n landmark.name = 'landmark %d' % i\n landmark.collide = True\n landmark.movable = False\n landmark.size = 0.2\n landmark.boundary = False\n # make initial conditions\n self.reset_world(world)\n return world\n\n\n def reset_world(self, world):\n # random properties for agents\n for i, agent in enumerate(world.agents):\n agent.color = np.array([0.35, 0.85, 0.35]) if not agent.adversary else np.array([0.85, 0.35, 0.35])\n # random properties for landmarks\n for i, landmark in enumerate(world.landmarks):\n landmark.color = np.array([0.25, 0.25, 0.25])\n # set random initial states\n for agent in world.agents:\n agent.state.p_pos = np.random.uniform(-1, +1, world.dim_p)\n agent.state.p_vel = np.zeros(world.dim_p)\n agent.state.c = np.zeros(world.dim_c)\n agent.death = False\n for i, landmark in enumerate(world.landmarks):\n if not landmark.boundary:\n landmark.state.p_pos = np.random.uniform(-0.9, +0.9, world.dim_p)\n landmark.state.p_vel = np.zeros(world.dim_p)\n \n if agent.adversary:\n agent.lock_num=[0 for j in range(self.num_green)]\n else:\n agent.lock_num=[0 for j in range(self.num_red)]\n\n\n def benchmark_data(self, agent, world):\n # returns data for benchmarking purposes\n if agent.adversary:\n collisions = 0\n for a in self.good_agents(world):\n if self.is_collision(a, agent) and a.death == False:\n collisions += 1\n return collisions\n else:\n return 0\n\n '''\n def is_collision(self, agent1, agent2):\n if agent1.death or agent2.death:\n return False\n delta_pos = agent1.state.p_pos - agent2.state.p_pos\n dist = np.sqrt(np.sum(np.square(delta_pos)))\n #dist_min = agent1.size + agent2.size\n dist_min = 0.1\n return True if dist < dist_min else False\n '''\n\n ##liyuan: compute the number of lokcing number of the agent\n def compute_lock_num(self, agent, world):\n opponent = []\n if agent.adversary:\n opponent = self.good_agents(world)\n else:\n opponent = self.adversaries(world)\n \n for i, opp in enumerate(opponent):\n if self.is_collision(opp,agent):\n agent.lock_num[i] += 1\n else:\n agent.lock_num[i] = 0\n \n ###liyuan: True if agent1 win, False for others\n def is_collision(self, agent1, agent2):\n if agent1.death or agent2.death:\n return False\n\n ###liyuan:judged by angle\n delta_pos = agent2.state.p_pos - agent1.state.p_pos\n distance = np.sqrt(np.sum(np.square(delta_pos)))\n if distance <= 1e-5:\n return False\n \n agent1_chi = [agent1.state.p_vel[0],agent1.state.p_vel[1]]\n\n if abs(agent1.state.p_vel[0]) < 1e-5 and abs(agent1.state.p_vel[1])<1e-5:\n agent1_chi[0] = 0.1\n agent1_chi[1] = 0\n agent2_chi = [agent2.state.p_vel[0],agent2.state.p_vel[1]]\n\n if abs(agent2.state.p_vel[0]) < 1e-5 and abs(agent2.state.p_vel[1])<1e-5:\n agent2_chi[0] = 0.1\n agent2_chi[1] = 0\n\n agent1_chi_value = np.sqrt(np.sum(np.square(agent1_chi)))\n agent1_cross = (delta_pos[0]*agent1_chi[0]+delta_pos[1]*agent1_chi[1])/(distance*agent1_chi_value)\n if agent1_cross < -1:\n agent1_cross = -1\n if agent1_cross > 1:\n agent1_cross = 1\n agent1_angle = math.acos(agent1_cross)\n\n\n agent2_chi_value = np.sqrt(np.sum(np.square(agent2_chi)))\n agent2_cross = (-delta_pos[0]*agent2_chi[0]-delta_pos[1]*agent2_chi[1])/(distance*agent2_chi_value)\n if agent2_cross < -1:\n agent2_cross = -1\n if agent2_cross > 1:\n agent2_cross = 1\n agent2_angle = math.acos(agent2_cross)\n\n revised_defense = 180-defense_angle/2\n if distance < fire_range and agent2_angle*180/math.pi>revised_defense and agent1_angle*180/math.pirevised_defense:\n #return True,2\n #else:\n return False\n \n ###liyuan: True if agent1 win, False for others\n def will_hit(self, agent1, agent2,hit_range):\n if agent1.death or agent2.death:\n return False\n\n ###liyuan:judged by angle\n delta_pos = agent2.state.p_pos - agent1.state.p_pos\n distance = np.sqrt(np.sum(np.square(delta_pos)))\n if distance <= 1e-5:\n return False\n \n agent1_chi = [agent1.state.p_vel[0],agent1.state.p_vel[1]]\n\n if abs(agent1.state.p_vel[0]) < 1e-5 and abs(agent1.state.p_vel[1])<1e-5:\n agent1_chi[0] = 0.1\n agent1_chi[1] = 0\n agent2_chi = [agent2.state.p_vel[0],agent2.state.p_vel[1]]\n\n if abs(agent2.state.p_vel[0]) < 1e-5 and abs(agent2.state.p_vel[1])<1e-5:\n agent2_chi[0] = 0.1\n agent2_chi[1] = 0\n\n agent1_chi_value = np.sqrt(np.sum(np.square(agent1_chi)))\n agent1_cross = (delta_pos[0]*agent1_chi[0]+delta_pos[1]*agent1_chi[1])/(distance*agent1_chi_value)\n if agent1_cross < -1:\n agent1_cross = -1\n if agent1_cross > 1:\n agent1_cross = 1\n agent1_angle = math.acos(agent1_cross)\n\n\n agent2_chi_value = np.sqrt(np.sum(np.square(agent2_chi)))\n agent2_cross = (-delta_pos[0]*agent2_chi[0]-delta_pos[1]*agent2_chi[1])/(distance*agent2_chi_value)\n if agent2_cross < -1:\n agent2_cross = -1\n if agent2_cross > 1:\n agent2_cross = 1\n agent2_angle = math.acos(agent2_cross)\n\n revised_defense = 180-defense_angle/2\n if distance < hit_range and agent2_angle*180/math.pi>revised_defense and agent1_angle*180/math.pirevised_defense:\n #return True,2\n #else:\n return False\n\n # return all agents that are not adversaries\n def good_agents(self, world):\n return [agent for agent in world.agents if not agent.adversary]\n\n # return all adversarial agents\n def adversaries(self, world):\n return [agent for agent in world.agents if agent.adversary]\n\n\n def reward(self, agent, world):\n # Agents are rewarded based on minimum agent distance to each landmark\n main_reward = self.adversary_reward(agent, world) if agent.adversary else self.agent_reward(agent, world)\n return main_reward\n\n def agent_reward(self, agent, world):\n ####added by liyuan\n if agent.death == True:\n return 0\n # Agents are negatively rewarded if caught by adversaries\n rew = 0\n #shape = False\n shape = True\n adversaries = self.adversaries(world)\n '''\n if shape: # reward can optionally be shaped (increased reward for increased distance from adversary)\n for adv in adversaries:\n ###changed by liyuan\n if adv.death == True:\n continue\n rew += 0.1 * np.sqrt(np.sum(np.square(agent.state.p_pos - adv.state.p_pos)))\n '''\n self.compute_lock_num(agent, world)\n if agent.collide:\n for i,a in enumerate(adversaries):\n ###changed by liyuan\n if self.is_collision(a, agent) and a.death == False:\n #if agent.lock_num[i]>=3 and a.death == False:\n #rew -= 10\n agent.death = True\n \n\n # agents are penalized for exiting the screen, so that they can be caught by the adversaries\n def bound(x):\n if x < 0.9:\n return 0\n if x < 1.0:\n return (x - 0.9) * 10\n return min(np.exp(2 * x - 2), 10)\n for p in range(world.dim_p):\n x = abs(agent.state.p_pos[p])\n rew -= bound(x)\n \n for p in range(world.dim_p):\n x = abs(agent.state.p_pos[p])\n if (x > 1.0):\n rew -= 20\n break\n\n return rew\n\n def adversary_reward(self, agent, world):\n ####added by liyuan\n if agent.death == True:\n return 0\n # Adversaries are rewarded for collisions with agents\n rew = 0\n #shape = False\n shape = True\n agents = self.good_agents(world)\n adversaries = self.adversaries(world)\n \n \n '''\n if shape: # reward can optionally be shaped (decreased reward for increased distance from agents)\n for adv in adversaries:\n ###rew -= 0.1 * min([np.sqrt(np.sum(np.square(a.state.p_pos - adv.state.p_pos))) for a in agents])\n if adv.death == False:\n dis = []\n for a in agents:\n if a.death == False:\n dis.append(np.sqrt(np.sum(np.square(a.state.p_pos - adv.state.p_pos))))\n if len(dis) > 0:\n rew -= 0.1 * min(dis)\n '''\n \n if shape: \n dis = []\n for a in agents:\n if a.death == False:\n dis.append(np.sqrt(np.sum(np.square(a.state.p_pos - agent.state.p_pos))))\n if len(dis) > 0:\n rew -= 0.1*min(dis)\n \n '''\n eat_num = 0\n by_eat_num = 0\n \n for a in agents:\n if self.will_hit(agent,a,comput_range):\n eat_num=eat_num+1\n elif self.will_hit(a,agent,comput_range):\n by_eat_num=by_eat_num+1\n rew += 0.1*(eat_num-by_eat_num)\n '''\n \n \n self.compute_lock_num(agent, world)\n if agent.collide:\n for ag in agents:\n for i,adv in enumerate(adversaries):\n ###changed by liyuan\n if self.is_collision(adv,ag) and ag.death == False and adv.death == False:\n #if self.ag.lock_num[i]>=3 and ag.death == False and adv.death == False:\n if adv is agent:\n rew += 4\n else:\n rew += 2\n break\n \n if agent.collide:\n for ag in agents:\n for i,adv in enumerate(adversaries):\n if self.is_collision(ag,adv) and ag.death == False and adv.death == False:\n #if self.ag.lock_num[i]>=3 and ag.death == False and adv.death == False:\n if not (adv is agent):\n rew -= 2\n \n ###if the red agent is eatten\n if agent.collide:\n for i,ag in enumerate(agents):\n if self.is_collision(ag, agent) and ag.death == False:\n #if ag.death == False and agent.lock_num[i]>=3:\n agent.death = True\n rew -= 4 \n break\n \n for adv in adversaries:\n if adv.death == False:\n exceed = False\n for p in range(world.dim_p):\n x = abs(adv.state.p_pos[p])\n if (x > 1.0):\n exceed = True\n break\n if exceed == True:\n if adv is agent:\n rew -= 10\n else:\n rew -=0\n break\n\n return rew\n\n def observation(self, agent, world):\n # get positions of all entities in this agent's reference frame\n entity_pos = []\n for entity in world.landmarks:\n if not entity.boundary:\n entity_pos.append(entity.state.p_pos - agent.state.p_pos)\n # communication of all other agents\n comm = []\n other_pos = []\n other_vel = []\n other_chi = []\n our_chi = []\n\n my_chi = np.zeros(1)\n if abs(agent.state.p_vel[0])<1e-5 and abs(agent.state.p_vel[1])<1e-5:\n my_chi[0] = 0\n else:\n my_chi[0] = math.atan2(agent.state.p_vel[1],agent.state.p_vel[0])\n our_chi.append(my_chi)\n\n temp_agents=[]\n for agent_i in world.agents:\n if agent_i.adversary == agent.adversary:\n temp_agents.append(agent_i)\n for agent_i in world.agents:\n if agent_i.adversary != agent.adversary:\n temp_agents.append(agent_i)\n\n for other in temp_agents:\n if other is agent: continue \n ###changed by liyuan\n if other.death:\n comm.append(np.zeros(world.dim_c))\n other_pos.append(np.zeros(world.dim_p))\n other_vel.append(np.zeros(world.dim_p))\n tmp_chi = np.zeros(1)\n other_chi.append(tmp_chi)\n else:\n comm.append(other.state.c)\n other_pos.append(other.state.p_pos - agent.state.p_pos)\n #if not other.adversary:\n other_vel.append(other.state.p_vel)\n\n tmp_chi = np.zeros(1)\n if abs(other.state.p_vel[0])<1e-5 and abs(other.state.p_vel[1])<1e-5:\n tmp_chi[0] = 0\n else:\n tmp_chi[0] = math.atan2(other.state.p_vel[1],other.state.p_vel[0])\n other_chi.append(tmp_chi)\n\n action_number=[np.zeros(5)]\n\n #comm.append(other.state.c)\n #other_pos.append(other.state.p_pos - agent.state.p_pos)\n #if not other.adversary:\n #other_vel.append(other.state.p_vel)\n return np.concatenate([agent.state.p_vel] + [agent.state.p_pos] + entity_pos + other_pos + other_vel + our_chi + other_chi+action_number)\n\n ##added by liyuan: if all green nodes die, this epsoid is over.\n def done(self, agent, world):\n allDie = True\n agents = self.good_agents(world)\n for agent in agents:\n if agent.death == False:\n allDie = False\n break\n return allDie\n","sub_path":"MADDPG/multiagent-particle-envs/multiagent/scenarios/competition_3v3.py","file_name":"competition_3v3.py","file_ext":"py","file_size_in_byte":16279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"547242637","text":"import json\n\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponseRedirect, HttpResponseNotFound\nfrom django.views.generic import View\n\nfrom django.contrib.auth import authenticate, login\n\nfrom .models import LOT\n\n\nclass LOTLogin(View):\n def get(self, request, uuid):\n next_url = request.GET.get('next', '/')\n lot = get_object_or_404(LOT, uuid=uuid)\n if not lot.verify():\n lot.delete()\n return HttpResponseNotFound()\n\n user = authenticate(lot_uuid=uuid)\n login(request, user)\n\n try:\n session_data = json.loads(lot.session_data)\n request.session.update(session_data)\n except Exception:\n # If not correctly serialized not set the session_data\n pass\n\n if lot.is_one_time():\n lot.delete()\n\n return HttpResponseRedirect(next_url)\n","sub_path":"lot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"372523344","text":"\"\"\"The tests for the Google Actions component.\"\"\"\n# pylint: disable=protected-access\nimport asyncio\n\nfrom homeassistant import const\nfrom homeassistant.components import climate\nfrom homeassistant.components import google_assistant as ga\nfrom homeassistant.util.unit_system import (IMPERIAL_SYSTEM, METRIC_SYSTEM)\n\nDETERMINE_SERVICE_TESTS = [{ # Test light brightness\n 'entity_id': 'light.test',\n 'command': ga.const.COMMAND_BRIGHTNESS,\n 'params': {\n 'brightness': 95\n },\n 'expected': (\n const.SERVICE_TURN_ON,\n {'entity_id': 'light.test', 'brightness': 242}\n )\n}, { # Test light color temperature\n 'entity_id': 'light.test',\n 'command': ga.const.COMMAND_COLOR,\n 'params': {\n 'color': {\n 'temperature': 2300,\n 'name': 'warm white'\n }\n },\n 'expected': (\n const.SERVICE_TURN_ON,\n {'entity_id': 'light.test', 'kelvin': 2300}\n )\n}, { # Test light color blue\n 'entity_id': 'light.test',\n 'command': ga.const.COMMAND_COLOR,\n 'params': {\n 'color': {\n 'spectrumRGB': 255,\n 'name': 'blue'\n }\n },\n 'expected': (\n const.SERVICE_TURN_ON,\n {'entity_id': 'light.test', 'rgb_color': [0, 0, 255]}\n )\n}, { # Test light color yellow\n 'entity_id': 'light.test',\n 'command': ga.const.COMMAND_COLOR,\n 'params': {\n 'color': {\n 'spectrumRGB': 16776960,\n 'name': 'yellow'\n }\n },\n 'expected': (\n const.SERVICE_TURN_ON,\n {'entity_id': 'light.test', 'rgb_color': [255, 255, 0]}\n )\n}, { # Test unhandled action/service\n 'entity_id': 'light.test',\n 'command': ga.const.COMMAND_COLOR,\n 'params': {\n 'color': {\n 'unhandled': 2300\n }\n },\n 'expected': (\n None,\n {'entity_id': 'light.test'}\n )\n}, { # Test switch to light custom type\n 'entity_id': 'switch.decorative_lights',\n 'command': ga.const.COMMAND_ONOFF,\n 'params': {\n 'on': True\n },\n 'expected': (\n const.SERVICE_TURN_ON,\n {'entity_id': 'switch.decorative_lights'}\n )\n}, { # Test light on / off\n 'entity_id': 'light.test',\n 'command': ga.const.COMMAND_ONOFF,\n 'params': {\n 'on': False\n },\n 'expected': (const.SERVICE_TURN_OFF, {'entity_id': 'light.test'})\n}, {\n 'entity_id': 'light.test',\n 'command': ga.const.COMMAND_ONOFF,\n 'params': {\n 'on': True\n },\n 'expected': (const.SERVICE_TURN_ON, {'entity_id': 'light.test'})\n}, { # Test Cover open close\n 'entity_id': 'cover.bedroom',\n 'command': ga.const.COMMAND_ONOFF,\n 'params': {\n 'on': True\n },\n 'expected': (const.SERVICE_OPEN_COVER, {'entity_id': 'cover.bedroom'}),\n}, {\n 'entity_id': 'cover.bedroom',\n 'command': ga.const.COMMAND_ONOFF,\n 'params': {\n 'on': False\n },\n 'expected': (const.SERVICE_CLOSE_COVER, {'entity_id': 'cover.bedroom'}),\n}, { # Test cover position\n 'entity_id': 'cover.bedroom',\n 'command': ga.const.COMMAND_BRIGHTNESS,\n 'params': {\n 'brightness': 50\n },\n 'expected': (\n const.SERVICE_SET_COVER_POSITION,\n {'entity_id': 'cover.bedroom', 'position': 50}\n ),\n}, { # Test media_player volume\n 'entity_id': 'media_player.living_room',\n 'command': ga.const.COMMAND_BRIGHTNESS,\n 'params': {\n 'brightness': 30\n },\n 'expected': (\n const.SERVICE_VOLUME_SET,\n {'entity_id': 'media_player.living_room', 'volume_level': 0.3}\n ),\n}, { # Test climate temperature\n 'entity_id': 'climate.living_room',\n 'command': ga.const.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT,\n 'params': {'thermostatTemperatureSetpoint': 24.5},\n 'expected': (\n climate.SERVICE_SET_TEMPERATURE,\n {'entity_id': 'climate.living_room', 'temperature': 24.5}\n ),\n}, { # Test climate temperature Fahrenheit\n 'entity_id': 'climate.living_room',\n 'command': ga.const.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT,\n 'params': {'thermostatTemperatureSetpoint': 24.5},\n 'units': IMPERIAL_SYSTEM,\n 'expected': (\n climate.SERVICE_SET_TEMPERATURE,\n {'entity_id': 'climate.living_room', 'temperature': 76.1}\n ),\n}, { # Test climate temperature range\n 'entity_id': 'climate.living_room',\n 'command': ga.const.COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE,\n 'params': {\n 'thermostatTemperatureSetpointHigh': 24.5,\n 'thermostatTemperatureSetpointLow': 20.5,\n },\n 'expected': (\n climate.SERVICE_SET_TEMPERATURE,\n {'entity_id': 'climate.living_room',\n 'target_temp_high': 24.5, 'target_temp_low': 20.5}\n ),\n}, { # Test climate temperature range Fahrenheit\n 'entity_id': 'climate.living_room',\n 'command': ga.const.COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE,\n 'params': {\n 'thermostatTemperatureSetpointHigh': 24.5,\n 'thermostatTemperatureSetpointLow': 20.5,\n },\n 'units': IMPERIAL_SYSTEM,\n 'expected': (\n climate.SERVICE_SET_TEMPERATURE,\n {'entity_id': 'climate.living_room',\n 'target_temp_high': 76.1, 'target_temp_low': 68.9}\n ),\n}, { # Test climate operation mode\n 'entity_id': 'climate.living_room',\n 'command': ga.const.COMMAND_THERMOSTAT_SET_MODE,\n 'params': {'thermostatMode': 'heat'},\n 'expected': (\n climate.SERVICE_SET_OPERATION_MODE,\n {'entity_id': 'climate.living_room', 'operation_mode': 'heat'}\n ),\n}]\n\n\n@asyncio.coroutine\ndef test_determine_service():\n \"\"\"Test all branches of determine service.\"\"\"\n for test in DETERMINE_SERVICE_TESTS:\n result = ga.smart_home.determine_service(\n test['entity_id'],\n test['command'],\n test['params'],\n test.get('units', METRIC_SYSTEM))\n assert result == test['expected']\n","sub_path":"tests/components/google_assistant/test_smart_home.py","file_name":"test_smart_home.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"191784933","text":"\"\"\"Remove obsolete indexes\n\nRevision ID: 20cd91cbf353\nRevises: 1ddbb9093570\nCreate Date: 2016-07-04 14:14:37.873240\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '20cd91cbf353'\ndown_revision = '1ddbb9093570'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.drop_index('journey_sections_type_idx', schema='stat')\n op.drop_index('requests_user_name_idx', schema='stat')\n op.drop_index('requests_api_idx', schema='stat')\n\n\ndef downgrade():\n op.create_index('journey_sections_type_idx', 'journey_sections', ['type'], schema='stat')\n op.create_index('requests_user_name_idx', 'requests', ['user_name'], schema='stat')\n op.create_index('requests_api_idx', 'requests', ['api'], schema='stat')\n","sub_path":"migrations/alembic/versions/20cd91cbf353_remove_obsolete_indexes.py","file_name":"20cd91cbf353_remove_obsolete_indexes.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"265127232","text":"from stellar_sdk import Asset\nfrom stellar_sdk.call_builder.call_builder_sync import OrderbookCallBuilder\nfrom tests.call_builder.call_builder_sync import client, horizon_url\n\n\nclass TestOrderbookCallBuilder:\n def test_init(self):\n selling = Asset(\n \"BTC\", \"GATEMHCCKCY67ZUCKTROYN24ZYT5GK4EQZ65JJLDHKHRUZI3EUEKMTCH\"\n )\n buying = Asset.native()\n builder = OrderbookCallBuilder(horizon_url, client, selling, buying)\n assert builder.endpoint == \"order_book\"\n assert builder.params == {\n \"selling_asset_type\": selling.type,\n \"selling_asset_code\": selling.code,\n \"selling_asset_issuer\": selling.issuer,\n \"buying_asset_type\": buying.type,\n }\n","sub_path":"tests/call_builder/call_builder_sync/test_orderbook_call_builder.py","file_name":"test_orderbook_call_builder.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"435821155","text":"\"\"\"\nGiven preorder and inorder traversal of a tree, construct the binary tree.\n Note: You may assume that duplicates do not exist in the tree.\nExample :\nInput :\n Preorder : [1, 2, 3]\n Inorder : [2, 1, 3]\nReturn :\n 1\n / \\\n 2 3\n\"\"\"\n\n\n# Focus on the preorder traversal to begin with.\n# The first element in the traversal will definitely be the root.\n# Based on this information, can you identify the elements in the left subtree and right subtree ?\n# ( Hint : Focus on inorder traversal and root information )\n# Once you do that, your problem has now been reduced to a smaller set. Now you have the inorder and preorder\n# traversal for the left and right subtree and you need to figure them out.\n# Divide and conquer.\n# Bonus points if you can do it without recursion.\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n # @param A : list of integers\n # @param B : list of integers\n # @return the root node in the tree\n def buildTree(self, A, B):\n if not B:\n return None\n root_pos = B.index(A[0])\n new_node = TreeNode(A[0])\n new_node.left = self.buildTree(A[1:root_pos + 1], B[:root_pos])\n new_node.right = self.buildTree(A[root_pos + 1:], B[root_pos + 1:])\n return new_node\n","sub_path":"InterviewBits/tree/binary-tree-from-inorder-and-preorder.py","file_name":"binary-tree-from-inorder-and-preorder.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"132695360","text":"#\n# Copyright 2017 by Delphix\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\"\"\"\nPackage \"database.performanceHistory\"\n\"\"\"\nAPI_VERSION = \"1.9.0\"\n\nimport urllib\nfrom delphixpy.v1_9_0 import response_validator\n\ndef get_all(engine, sampling_interval=None, to_date=None, from_date=None):\n \"\"\"\n Reports the utilization of all containers during a particular period of\n time.\n\n :param engine: The Delphix Engine\n :type engine: :py:class:`delphixpy.v1_9_0.delphix_engine.DelphixEngine`\n :param sampling_interval: The interval at which data is to be sampled,\n measured in seconds.\n :type sampling_interval: ``float``\n :param to_date: The latest date for which container utilization statistics\n will be reported.\n :type to_date: ``basestring``\n :param from_date: The earliest date for which container utilization\n statistics will be reported.\n :type from_date: ``basestring``\n :rtype: ``list`` of :py:class:`v1_9_0.web.vo.ContainerUtilization`\n \"\"\"\n assert API_VERSION == engine.API_VERSION, \"Wrong API version (%s) for parameter 'engine' (%s)\" % (API_VERSION, engine.API_VERSION)\n url = \"/resources/json/delphix/database/performanceHistory\"\n query_params = {\"samplingInterval\": sampling_interval, \"toDate\": to_date, \"fromDate\": from_date}\n query_dct = {k: query_params[k] for k in query_params if query_params[k] is not None}\n if query_dct:\n url_params = urllib.urlencode(query_dct)\n url += \"?%s\" % url_params\n response = engine.get(url)\n result = response_validator.validate(response, engine)\n raw_result = getattr(engine, 'raw_result', False)\n return response_validator.parse_result(result, undef_enabled=True, return_types=[u'ContainerUtilization'], returns_list=True, raw_result=raw_result)\n\n","sub_path":"src/main/resources/delphixpy/v1_9_0/web/database/performanceHistory/performanceHistory.py","file_name":"performanceHistory.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"583465116","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'CCCYT'\n\n\"\"\"\ncustomer\n\"\"\"\nimport logging\nimport random\nimport time\n\nimport function as func\nfrom DataBase import DataBase\n\n# 创建logger\nlogger = logging.getLogger()\n\n\nclass Customer(object):\n\n def __init__(self, be_id='', birthday='', pesel='', id_number='', gender='1', email='cheng.yutao@plus.pl',\n first_name='BES', last_name='CCCYT',\n mobile_phone='609067758'):\n self.__beId = be_id\n self.__birthday, self.__pesel = (birthday, pesel) if (\n birthday != '' and pesel != '') else Customer.generate_pesel()\n\n self.__id_number = id_number if id_number != '' else Customer.generate_id_number()\n self.__gender = gender\n self.__email = email\n self.__firstName = first_name\n self.__lastName = last_name\n self.__mobilePhone = mobile_phone\n\n @classmethod\n def generate_pesel(cls, birthday=None):\n def generate_birthday():\n # 在开始时间和结尾时间中随机选择一个日期作为客户的出生时间\n # 开始时间元组\n start = (1980, 1, 1, 0, 0, 0, 0, 0, 0)\n # 开始时间戳\n start_timestamp = time.mktime(start)\n # 结尾时间元组\n end = (2010, 12, 31, 23, 59, 59, 0, 0, 0)\n # 结尾时间戳\n end_timestamp = time.mktime(end)\n timestamp = random.randint(start_timestamp, end_timestamp)\n return time.strftime(\"%Y%m%d\", time.localtime(timestamp))\n\n def cal_pesel(birthday_date):\n # 生成三位随机数\n zzz = func.add_leading_zero(random.randint(0, 999), 3)\n # 性别,奇数是男,偶数是女\n x = str(random.randint(0, 9))\n temp_pesel = birthday_date[2:] + zzz + x\n # 数字元组,用以乘以pesel,生成校验码\n code = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3)\n check_sum = 0\n i = 0\n while i < 10:\n check_sum += code[i] * int(temp_pesel[i])\n i += 1\n # 校验和求模10, 大于0 则被10 减 , 等于0 则为0\n check_num = (10 - check_sum % 10) if (check_sum % 10 > 0) else 0\n return temp_pesel + str(check_num)\n\n # 客户生日\n birthday = birthday if birthday is not None else generate_birthday()\n pesel = cal_pesel(birthday)\n while DataBase().query_customer_by_pesel(pesel) is not None:\n pesel = cal_pesel(birthday)\n\n return birthday, pesel\n\n @classmethod\n def generate_id_number(cls):\n\n # 26个字母\n letter = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',\n 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')\n # 字母对于的值\n letter_value = {\"A\": 10, \"B\": 11, \"C\": 12, \"D\": 13, \"E\": 14, \"F\": 15, \"G\": 16, \"H\": 17, \"I\": 18, \"J\": 19,\n \"K\": 20, \"L\": 21, \"M\": 22, \"N\": 23, \"O\": 24, \"P\": 25, \"Q\": 26, \"R\": 27, \"S\": 28, \"T\": 29,\n \"U\": 30, \"V\": 31, \"W\": 32, \"X\": 33, \"Y\": 34, \"Z\": 35}\n # 用以乘以字母和数字部分生成校验位\n code = (7, 3, 1, 7, 3, 1, 7, 3)\n\n def cal_id_number():\n # 从26个字母中随机取三位,z作为字母部分\n letter_part = letter[random.randint(0, 25)] + letter[random.randint(0, 25)] + letter[random.randint(0, 25)]\n # 随机取五位以内的数, 不足五位,前面补0, 作为数字部分\n digit_part = func.add_leading_zero(random.randint(0, 99999), 5)\n check_sum = 0\n i = 0\n while i < 8:\n if i < 3:\n check_sum += code[i] * letter_value[letter_part[i]]\n else:\n check_sum += code[i] * int(digit_part[i - 3])\n i += 1\n check_num = str(check_sum % 10)\n return letter_part + check_num + digit_part\n\n id_number = cal_id_number()\n while DataBase().query_customer_by_id_number(id_number) is not None:\n id_number = cal_id_number()\n return id_number\n\n def get_customer(self):\n return {'beid': self.__beId, 'birthday': self.__birthday, 'pesel': self.__pesel, 'idNumber': self.__id_number,\n 'gender': self.__gender, 'email': self.__email, 'firstName': self.__firstName,\n 'lastName': self.__lastName, 'mobilePhone': self.__mobilePhone}\n\n def set_customer(self, customer_code):\n self.__customer_code = customer_code\n\n\nif __name__ == '__main__':\n print(Customer.generate_pesel())\n print(Customer.generate_id_number())\n","sub_path":"BESTool/bestool/Customer.py","file_name":"Customer.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"442545588","text":"from django.contrib import admin\nfrom django.forms.models import modelform_factory\n\nfrom environment.models import Environment\n\nfrom models import Building, Tenure\n\n\nclass EnvironmentInline(admin.TabularInline):\n model = Environment\n\n\nclass TenureInline(admin.TabularInline):\n model = Tenure\n extra = 1\n\n\nclass BuildingAdmin(admin.ModelAdmin):\n inlines = [TenureInline]\n form = modelform_factory(Building, exclude=())\n list_per_page = 30\n\n class Media:\n js = (\n 'js/ubigeo.js',\n )\n\nadmin.site.register(Building, BuildingAdmin)\n","sub_path":"building/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"157064536","text":"from image import ImageCaptcha\nimport random\nimport string\ndef run():\n seed = \"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n sa = []\n for i in range(8):\n sa.append(random.choice(seed))\n salt = ''.join(sa)\n#print salt\n img = ImageCaptcha()\n img1 = img.generate_image(salt)\n img1.save(\"captcha.jpg\")\n# with open(\"captcha.jpg\",'wb') as f:\n# f.write(data)\nif __name__ == '__main__':\n run()\n","sub_path":"flask/utils/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"85071262","text":"from Model.Data import *\nimport Utils.Storage as Storage\n\ncomment_handler = CommentedTreeBuilder()\n\nparser = ET.XMLParser(target=comment_handler)\n\nwith open('test_aimls/utils.aiml', 'r') as f:\n tree = ET.parse(f, parser)\n\nroot = tree.getroot()\nprint(root.tag)\n\nfor child in root:\n print(\"child.tag: {}\".format(child.tag))\n print(\"child.text: {}\".format(child.text))\n # print(\"child.tags: {}\".format(child.tags))\n tag_obj = Storage.decode_tag(child.tag.lower())\n print(tag_obj)\n raise exception\n# ET.dump(tree)","sub_path":"Examples/writeout_comments.py","file_name":"writeout_comments.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"129537490","text":"import utils.sys.config\nimport pymongo\n\nfrom utils.db.mongodb.cursor_result import CursorResult\nfrom utils.gadget.general import SysUtils\nfrom utils.const.file_source import FileSource\nfrom utils.const.file_type import FileType\nfrom utils.const.pack_type import PackType\n\n\n# 固件包记录集合\npack_files_coll = utils.sys.config.g_firmware_db_full[\"pack_files\"]\n\n\nclass PackFileDO:\n\n # def __init__(self, pack_id=None):\n # # pack_id 为None时表示新建的pack文件对象\n # pass\n\n @staticmethod\n def save(pack_id, file_id, name=None, description='', pack_type=PackType.REAL,\n source_type=FileSource.REMOTE_DOWNLOAD, file_type=FileType.OTHER_FILE, source_addr=''):\n doc = {'pack_id': pack_id, 'file_id': file_id, 'name': name, 'description': description,\n 'pack_type': pack_type, 'source_type': source_type, 'file_type': file_type, 'source_addr': source_addr,\n 'create_time': SysUtils.get_now_time()}\n # 更新一条函数分析结果,如果没有旧记录,则创建一条新记录\n pack_files_coll.update_one({'pack_id': pack_id}, {'$set': doc}, True)\n\n @staticmethod\n def save_manufacturer(pack_id, manufacturer, model, version):\n doc = {'pack_id': pack_id, 'manufacturer': manufacturer, 'model': model, 'version': version}\n # 更新一条函数分析结果,如果没有旧记录,则创建一条新记录\n pack_files_coll.update_one({'pack_id': pack_id}, {'$set': doc}, True)\n\n @staticmethod\n def savefs(pack_id, filesystem, arch=None):\n doc = {'filesystem': filesystem, 'arch': arch}\n # 更新一条函数分析结果,如果没有旧记录,则创建一条新记录\n pack_files_coll.update_one({'pack_id': pack_id}, {'$set': doc}, True)\n\n @staticmethod\n def updateArch(pack_id, arch):\n doc = {'arch': arch}\n # 更新一条函数分析结果,如果没有旧记录,则创建一条新记录\n pack_files_coll.update_one({'pack_id': pack_id}, {'$set': doc}, True)\n\n @staticmethod\n def analyze_complet(pack_id, flag):\n doc = {'analyze': flag}\n # 更新一条函数分析结果,如果没有旧记录,则创建一条新记录\n pack_files_coll.update_one({'pack_id': pack_id}, {'$set': doc}, True)\n\n @staticmethod\n def fetch_pack(pack_id):\n cursor = pack_files_coll.find({'pack_id': pack_id}, {'_id': 0})\n return CursorResult.one(cursor)\n\n @staticmethod\n def all_packs():\n # cursor = pack_files_coll.find({}, {'_id': 0})\n cursor = pack_files_coll.find({}, {'_id': 0}).sort([(\"_id\", pymongo.DESCENDING)])\n\n return CursorResult.many(cursor)\n\n @staticmethod\n def all_packs_type(pack_type):\n cursor = pack_files_coll.find({'pack_type': pack_type}, {'_id': 0})\n return CursorResult.many(cursor)\n\n @staticmethod\n def delete(pack_id):\n result = pack_files_coll.delete_one({'pack_id': pack_id})\n return result.deleted_count == 1\n\n @staticmethod\n def delete_many(pack_id_list):\n for pack_id in pack_id_list:\n PackFileDO.delete(pack_id)\n","sub_path":"utils/db/mongodb/pack_file.py","file_name":"pack_file.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"184166713","text":"import os\nimport pickle\nimport re\n\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom src.languange_classifier import code_language_classifier as clc\nfrom src.text_based_similarities import Levenshtein_distance\nfrom src.text_based_similarities import cos_similarity\ndata_path = \"../../data/leetcode_cpp\"\n\n\ndef init_tokenizer():\n cpp_data = clc.load_data(data_path, \"cpp\")\n tokenizer = Tokenizer(filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',)\n tokenizer.fit_on_texts(cpp_data)\n # save\n f = open('tokenizer_lcs_cpp.pkl', 'wb')\n pickle.dump(tokenizer, f)\n f.close()\n\n\ndef code2text(path):\n text = open(path, encoding='UTF-8').read()\n text = re.sub(\"(?:/\\\\*(?:[^*]|(?:\\\\*+[^*/]))*\\\\*+/)|(?://.*)\", '', text)\n return text\n\n\ndef token_lcs(path1, path2):\n text1 = code2text(path1)\n text2 = code2text(path2)\n path = os.path.abspath(os.path.dirname(__file__)) + \"\\\\tokenizer_lcs_cpp.pkl\"\n f1 = open(path, 'rb')\n tokenizer = pickle.load(f1)\n f1.close()\n\n # java_data = clc.load_data(data_path, \"java\")\n # tokenizer = Tokenizer(filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',)\n # tokenizer.fit_on_texts(java_data)\n\n seq1 = tokenizer.texts_to_sequences([text1])[0]\n seq2 = tokenizer.texts_to_sequences([text2])[0]\n return Levenshtein_distance.Levenshtein_distance(seq1,seq2) / max(len(seq1), len(seq2))\n\ndef token_cos(path1, path2):\n text1 = code2text(path1)\n text2 = code2text(path2)\n path = os.path.abspath(os.path.dirname(__file__)) + \"\\\\tokenizer_lcs_cpp.pkl\"\n f1 = open(path, 'rb')\n tokenizer = pickle.load(f1)\n f1.close()\n\n # java_data = clc.load_data(data_path, \"java\")\n # tokenizer = Tokenizer(filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',)\n # tokenizer.fit_on_texts(java_data)\n\n # 这里有一个问题:如果一段text从未在tokenizer中出现,则cos_similarity的除数是0\n seq1 = tokenizer.texts_to_sequences([text1])[0]\n seq2 = tokenizer.texts_to_sequences([text2])[0]\n return cos_similarity.cos_similarity_text(seq1, seq2)\n\nif __name__ == \"__main__\":\n # init_tokenizer()\n path1 = \"../../test/bubblesort.cpp\"\n path2 = \"../../test/heapsort.cpp\"\n similarity = token_cos(path1, path2)\n print(similarity)","sub_path":"src/token_based_similarities/token_lcs_cpp.py","file_name":"token_lcs_cpp.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"359686844","text":"from e2 import Board, Piece\r\nfrom typing import List, Tuple\r\nfrom sortedcontainers import SortedList\r\nimport copy\r\n\r\n\r\nclass Backtrack:\r\n def __init__(self, board: Board, pieces: List[Piece]):\r\n \"\"\"\r\n Implementation of the backtrack solver which mutates the board parameter\r\n by placing the pieces in the correct position/rotations.\r\n Starts from bot left going rightwards.\r\n Args:\r\n board: The board\r\n pieces: A list of all available the pieces\r\n \"\"\"\r\n self._board = copy.deepcopy(board)\r\n self._pieces = SortedList(pieces)\r\n\r\n @property\r\n def board(self) -> Board:\r\n \"\"\"\r\n Returns:\r\n The Board instance\r\n \"\"\"\r\n return self._board\r\n\r\n def is_valid(self, piece: Piece, x: int, y: int) -> bool:\r\n \"\"\"\r\n Checks if placing piece at positition (x, y) is a valid move\r\n Args:\r\n piece: The piece to be placed\r\n x: The x-coordinate.\r\n y: The y-coordinate.\r\n\r\n Returns:\r\n True if placement is valid, False otherwise\r\n \"\"\"\r\n # Check top edge\r\n if y == self._board.height:\r\n if piece.top_edge != 0:\r\n return False\r\n else:\r\n if not self._board.piece_at(x, y + 1) is None:\r\n if piece.top_edge != self._board.piece_at(x, y + 1).bot_edge:\r\n return False\r\n\r\n # Check right edge\r\n if x == self._board.width:\r\n if piece.right_edge != 0:\r\n return False\r\n else:\r\n if not self._board.piece_at(x + 1, y) is None:\r\n if piece.right_edge != self._board.piece_at(x + 1, y).left_edge:\r\n return False\r\n\r\n # Check bot edge\r\n if y == 1:\r\n if piece.bot_edge != 0:\r\n return False\r\n else:\r\n if not self._board.piece_at(x, y - 1) is None:\r\n if piece.bot_edge != self._board.piece_at(x, y - 1).top_edge:\r\n return False\r\n\r\n # Check left edge\r\n if x == 1:\r\n if piece.left_edge != 0:\r\n return False\r\n else:\r\n if not self._board.piece_at(x - 1, y) is None:\r\n if piece.left_edge != self._board.piece_at(x - 1, y).right_edge:\r\n return False\r\n\r\n return True\r\n\r\n def next_step(self) -> Tuple[Piece, int, int]:\r\n \"\"\"\r\n Performs the next step in the backtracking process\r\n Returns:\r\n The Piece which was placed and the (x, y) location.\r\n If we backtracked, it returns None and the (x, y) location\r\n of the piece we removed\r\n \"\"\"\r\n row = 1\r\n col = 1\r\n i = 0\r\n while len(self._pieces) != 0:\r\n start_rot = 0\r\n # backtrack if we tried all pieces\r\n if i == len(self._pieces):\r\n if col == 1 and row == 1:\r\n print('Puzzle is unsolvable')\r\n elif col % self._board.width == 1:\r\n row -= 1\r\n col = self._board.width\r\n else:\r\n col -= 1\r\n removed_piece = self._board.remove_piece_at(col, row)\r\n self._pieces.add(removed_piece)\r\n i = self._pieces.index(removed_piece)\r\n start_rot = removed_piece.rotation + 90\r\n piece = copy.deepcopy(self._pieces[i])\r\n piece_placed = False\r\n for rot in range(start_rot, 360, 90):\r\n piece.rotation = rot\r\n if self.is_valid(piece, col, row):\r\n self._board.place_piece_at(piece, col, row)\r\n self._pieces.remove(piece)\r\n piece_placed = True\r\n yield piece, col, row\r\n if col % self._board.width != 0:\r\n col += 1\r\n else:\r\n col = 1\r\n row += 1\r\n break\r\n\r\n if piece_placed:\r\n i = 0\r\n else:\r\n i += 1\r\n\r\n def solve(self):\r\n for _ in self.next_step():\r\n pass\r\n","sub_path":"e2/solvers/backtrack.py","file_name":"backtrack.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"353715337","text":"# Name: Frank Shang\n# OSU Email: shangf@oregonstate.edu\n# Course: CS261 - Data Structures\n# Assignment: 3\n# Due Date: 10/25/2021\n# Description: Implementing a Stack ADT by using a dynamic array.\n\nfrom dynamic_array import *\n\n\nclass StackException(Exception):\n \"\"\"\n Custom exception to be used by Stack class\n DO NOT CHANGE THIS METHOD IN ANY WAY\n \"\"\"\n pass\n\n\nclass Stack:\n def __init__(self):\n \"\"\"\n Init new stack based on Dynamic Array\n DO NOT CHANGE THIS METHOD IN ANY WAY\n \"\"\"\n self._da_val = DynamicArray()\n\n def __str__(self) -> str:\n \"\"\"\n Return content of stack in human-readable form\n DO NOT CHANGE THIS METHOD IN ANY WAY\n \"\"\"\n out = \"STACK: \" + str(self._da_val.length()) + \" elements. [\"\n out += ', '.join([str(self._da_val[i]) for i in range(self._da_val.length())])\n return out + ']'\n\n def is_empty(self) -> bool:\n \"\"\"\n Return True is the stack is empty, False otherwise\n DO NOT CHANGE THIS METHOD IN ANY WAY\n \"\"\"\n return self._da_val.is_empty()\n\n def size(self) -> int:\n \"\"\"\n Return number of elements currently in the stack\n DO NOT CHANGE THIS METHOD IN ANY WAY\n \"\"\"\n return self._da_val.length()\n\n # -----------------------------------------------------------------------\n\n def push(self, value: object) -> None:\n \"\"\"\n This method adds a new element to the top of the stock.\n \"\"\"\n self._da_val.append(value)\n\n def pop(self) -> object:\n \"\"\"\n This method removes the top element from the stack and returns its value.\n If the stack is empty, the method raises a custom \"StackException\".\n \"\"\"\n if self.is_empty():\n raise StackException\n\n # determine if the length of the dynamic array to find the last index\n index = self.size() - 1\n value = self._da_val.get_at_index(index)\n self._da_val.remove_at_index(index)\n return value\n\n def top(self) -> object:\n \"\"\"\n This method returns the value of the top element of the stack without removing it.\n If the stack is empty, the method raises StackException.\n \"\"\"\n if self.is_empty():\n raise StackException\n\n return self._da_val.get_at_index(self.size()-1)\n\n\n# ------------------- BASIC TESTING -----------------------------------------\n\n\nif __name__ == \"__main__\":\n\n print(\"\\n# push example 1\")\n s = Stack()\n print(s)\n for value in [1, 2, 3, 4, 5]:\n s.push(value)\n print(s)\n\n\n print(\"\\n# pop example 1\")\n s = Stack()\n try:\n print(s.pop())\n except Exception as e:\n print(\"Exception:\", type(e))\n for value in [1, 2, 3, 4, 5]:\n s.push(value)\n for i in range(6):\n try:\n print(s.pop())\n except Exception as e:\n print(\"Exception:\", type(e))\n\n\n print(\"\\n# top example 1\")\n s = Stack()\n try:\n s.top()\n except Exception as e:\n print(\"No elements in stack\", type(e))\n s.push(10)\n s.push(20)\n print(s)\n print(s.top())\n print(s.top())\n print(s)\n","sub_path":"stack_da.py","file_name":"stack_da.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"618011077","text":"import boto3\n\ns3_resource = boto3.resource('s3')\nbucket_name = 'pytorch-geometric.com'\nbucket = s3_resource.Bucket(name=bucket_name)\nobjects = bucket.objects.all()\nwheels = [obj.key for obj in objects if obj.key[-3:] == 'whl']\nversions = sorted(list(set([wheel.split('/')[1] for wheel in wheels])))\n\nwheels_dict = {}\nfor torch_version in versions:\n wheels_dict[torch_version] = []\n\nfor wheel in wheels:\n torch_version = wheel.split('/')[1]\n wheels_dict[torch_version].append(\n (torch_version, '/'.join(wheel.split('/')[2:])))\n\nhtml = '\\n\\n\\n{}\\n\\n'\nhref = '{}
'\n\n# Add wheels for PyTorch 1.7.1 and 1.8.1\nfor key, value in list(wheels_dict.items()):\n if '1.7.0' in key:\n wheels_dict[key.replace('1.7.0', '1.7.1')] = value\n if '1.8.0' in key:\n wheels_dict[key.replace('1.8.0', '1.8.1')] = value\n\nindex_html = html.format('\\n'.join(\n [href.format(f'{key}.html', key) for key in wheels_dict.keys()]))\n\nwith open('index.html', 'w') as f:\n f.write(index_html)\n\nbucket.Object('whl/index.html').upload_file(\n Filename='index.html', ExtraArgs={\n 'ContentType': 'text/html',\n 'CacheControl': 'max-age=300',\n 'ACL': 'public-read'\n })\n\nfor key, wheels in wheels_dict.items():\n version_html = html.format('\\n'.join([\n href.format(f'{version}/{wheel}', wheel) for version, wheel in wheels\n ]))\n\n with open('{}.html'.format(key), 'w') as f:\n f.write(version_html)\n\n bucket.Object('whl/{}.html'.format(key)).upload_file(\n Filename='{}.html'.format(key), ExtraArgs={\n 'ContentType': 'text/html',\n 'CacheControl': 'max-age=300',\n 'ACL': 'public-read'\n })\n","sub_path":"wheel.py","file_name":"wheel.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"452891472","text":"my_dict = {}\n\nwith open('my_file_6.txt') as f:\n for line in f:\n content = line.split()\n sum_num = 0\n for el in content[1:]:\n num = el[:el.find('(')]\n if num:\n sum_num += int(num)\n \n my_dict[content[0]] = sum_num\n\n print(my_dict)","sub_path":"lesson05/5.6.py","file_name":"5.6.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"648243018","text":"from time import sleep\nfrom BMI160_i2c import Driver\n\nprint('Trying to initialize the sensor...')\nsensor = Driver()\nprint('Initialization done')\n\nwhile True:\n data = sensor.getMotion6()\n # fetch all gyro and acclerometer values\n print({\n 'gx': data[0],\n 'gy': data[1],\n 'gz': data[2],\n 'ax': data[3],\n 'ay': data[4],\n 'az': data[5]\n })\n sleep(0.1)\n\n","sub_path":"examples/all.py","file_name":"all.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"396255243","text":"from socket import socket, AF_INET, SOCK_STREAM\nfrom additionals.settings import DEFAULT_PORT, DEFAULT_IP, ACTION, PRESENCE, TIME, USER, ACCOUNT_NAME, RESPONSE, ERROR\nfrom additionals.utils import send_msg, receive_msg\nfrom logging import getLogger\nfrom log.config import client_log_config\nimport time, json, sys\n\n\nclass Client:\n\n def __init__(self):\n self.logger = getLogger('app.client')\n try:\n self.connection_addr = sys.argv[1]\n self.connection_port = int(sys.argv[2])\n self.logger.debug(f'clients starts with {self.connection_addr}:{self.connection_port}')\n if 65535 < self.connection_port < 1024:\n raise ValueError\n except IndexError:\n self.connection_port = DEFAULT_PORT\n self.connection_addr = DEFAULT_IP\n self.logger.debug(f'clients starts without additional arguments '\n f'with default settings - {DEFAULT_IP}:{DEFAULT_PORT}')\n except ValueError:\n self.logger.critical(f'port is out off range 1024 - 65535')\n sys.exit(1)\n\n def client_presence(self, name='Guest'):\n self.presence = {\n ACTION: PRESENCE,\n TIME: time.time(),\n USER: {\n ACCOUNT_NAME: name\n }\n }\n self.logger.debug(f\"client created presence: {self.presence}\")\n return self.presence\n\n def presence_response(self, message):\n if RESPONSE in message:\n if message[RESPONSE] == 200:\n return '200 : OK'\n return f'400 : {message[ERROR]}'\n raise ValueError\n\n def start(self):\n try:\n self.sock = socket(AF_INET, SOCK_STREAM)\n self.logger.warning(f'client successfully started socket {self.sock}')\n self.sock.connect((self.connection_addr, self.connection_port))\n self.logger.debug(f'client successfully connected to {self.connection_addr}:{self.connection_port}')\n self.presence_msg = self.client_presence()\n send_msg(self.sock, self.presence_msg)\n self.logger.debug(f'client sent message to {self.sock} with {self.presence_msg}')\n\n except ConnectionRefusedError:\n self.logger.critical(f'error - connection refused')\n sys.exit(1)\n\n try:\n self.response = self.presence_response(receive_msg(self.sock))\n self.logger.info(f'client got response - {self.response}')\n print(self.response)\n\n except (ValueError, json.JSONDecodeError):\n self.logger.error(f'JSONDecodeError, can not to encode message')\n\n finally:\n self.logger.warning(f'clients stops')\n sys.exit(0)\n\n\nif __name__ == '__main__':\n try:\n client = Client()\n client.start()\n except SystemError:\n sys.exit(1)","sub_path":"lesson_5/client_oop.py","file_name":"client_oop.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"536490256","text":"import numpy as np\nimport zipfile\n\ndef evaluate(path):\n archive = zipfile.ZipFile(path, 'r')\n\n test_labels = np.array([int(e) for e in open(\"challenges/mnist/test_labels.csv\")])\n pred_labels = np.array([int(e) for e in archive.open(\"predictions.csv\")])\n\n assert len(test_labels) == len(pred_labels), \"Must have correct number of samples\"\n score = 100 * (1 - sum(test_labels == pred_labels)/len(test_labels))\n\n return int(score * 100)/100\n","sub_path":"server/challenges/mnist/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"139228024","text":"\"\"\"\nPrimary module for Alien Invaders\n\nThis module contains the main controller class for the Alien Invaders application. There\nis no need for any additional classes in this module. If you need more classes, 99% of\nthe time they belong in either the wave module or the models module. If you are unsure\nabout where a new class should go, post a question on Piazza.\n\nConner Swenberg, cls364 ; Jay Chand, jpc342\n12/8/17\n\"\"\"\nimport cornell\nfrom consts import *\nfrom game2d import *\nfrom wave import *\n\n\n# PRIMARY RULE: Invaders can only access attributes in wave.py via getters/setters\n# Invaders is NOT allowed to access anything in models.py\n\nclass Invaders(GameApp):\n \"\"\"\n The primary controller class for the Alien Invaders application\n\n This class extends GameApp and implements the various methods necessary for processing\n the player inputs and starting/running a game.\n\n Method start begins the application.\n\n Method update either changes the state or updates the Play object\n\n Method draw displays the Play object and any other elements on screen\n\n Because of some of the weird ways that Kivy works, you SHOULD NOT create an\n initializer __init__ for this class. Any initialization should be done in\n the start method instead. This is only for this class. All other classes\n behave normally.\n\n Most of the work handling the game is actually provided in the class Wave.\n Wave should be modeled after subcontrollers.py from lecture, and will have\n its own update and draw method.\n\n The primary purpose of this class is to manage the game state: which is when the\n game started, paused, completed, etc. It keeps track of that in an attribute\n called _state.\n\n INSTANCE ATTRIBUTES:\n view: the game view, used in drawing (see examples from class)\n [instance of GView; it is inherited from GameApp]\n input: the user input, used to control the ship and change state\n [instance of GInput; it is inherited from GameApp]\n _state: the current state of the game represented as a value from consts.py\n [one of STATE_INACTIVE, STATE_NEWWAVE, STATE_ACTIVE, STATE_PAUSED, STATE_CONTINUE, STATE_COMPLETE]\n _wave: the subcontroller for a single wave, which manages the ships and aliens\n [Wave, or None if there is no wave currently active]\n _text: the currently active message\n [GLabel, or None if there is no message to display]\n\n STATE SPECIFIC INVARIANTS:\n Attribute _wave is only None if _state is STATE_INACTIVE.\n Attribute _text is only None if _state is STATE_ACTIVE.\n\n For a complete description of how the states work, see the specification for the\n method update.\n\n You may have more attributes if you wish (you might want an attribute to store\n any score across multiple waves). If you add new attributes, they need to be\n documented here.\n\n LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY\n _lastkeys: the number key(s) pressed in the last frame [int>=0]\n _background: the background image of the game [class: Background]\n _death: used to express if the ship has run out of lives [bool]\n _newpara: string used in STATE_INTRO to create visual and time spacing between writing lines [str]\n _intro: the intro message to display on the screen when starting the game [str]\n _message: message currently displayed on the screen starting as empty and finishing at _intro [str]\n _iwrite: loop vairable in STATE_INTRO that increments each run through [0>=int>=WRITE_SPEED*len(self._message)]\n _jwrite: loop variable in STATE_INTRO that increments every WRITE_SPEED run throughs [0>=int>=len(self._message)]\n \"\"\"\n\n # DO NOT MAKE A NEW INITIALIZER!\n\n # THREE MAIN GAMEAPP METHODS\n def start(self):\n \"\"\"\n Initializes the application.\n\n This method is distinct from the built-in initializer __init__ (which you\n should not override or change). This method is called once the game is running.\n You should use it to initialize any game specific attributes.\n\n This method should make sure that all of the attributes satisfy the given\n invariants. When done, it sets the _state to STATE_INACTIVE and create a message\n (in attribute _text) saying that the user should press to play a game.\n \"\"\"\n self._state=STATE_INACTIVE\n self._text=GLabel(text='Press s to play')\n self.GLabelstuff(self._text,60,'Arcade.ttf',GAME_WIDTH//2,GAME_HEIGHT//2,cornell.RGB(255, 255, 255))\n self._wave=None\n self._background = Background('space.png')\n self.draw()\n self._lastkeys=0\n self._pause=' '\n self._newpara='\\n'+self._pause+'\\n'\n self._intro=(''+self._newpara+'Hello starfighter..'+self._newpara+\n 'The American Galactic Force needs your help\\n'+\n 'to defend our precious home from alien invaders..'+self._newpara+\n 'To engage with the enemy,\\n use leftarrow and rightarrow keys to move\\n'+\n 'and uparrow to fire laser bolts..'+self._newpara+\n 'Powerups will periodically drop from destroyed aliens..'+self._newpara+\n 'Good luck out there starfighter..'+self._pause)\n self._endmessage=''\n self._message=''\n self._iwrite=0\n self._jwrite=0\n def update(self,dt):\n \"\"\"\n Animates a single frame in the game.\n\n It is the method that does most of the work. It is NOT in charge of playing the\n game. That is the purpose of the class Wave. The primary purpose of this\n game is to determine the current state, and -- if the game is active -- pass\n the input to the Wave object _wave to play the game.\n\n As part of the assignment, you are allowed to add your own states. However, at\n a minimum you must support the following states: STATE_INACTIVE, STATE_NEWWAVE,\n STATE_ACTIVE, STATE_PAUSED, STATE_CONTINUE, and STATE_COMPLETE. Each one of these\n does its own thing and might even needs its own helper. We describe these below.\n\n STATE_INACTIVE: This is the state when the application first opens. It is a\n paused state, waiting for the player to start the game. It displays a simple\n message on the screen. The application remains in this state so long as the\n player never presses a key. In addition, this is the state the application\n returns to when the game is over (all lives are lost or all aliens are dead).\n\n STATE_NEWWAVE: This is the state creates a new wave and shows it on the screen.\n The application switches to this state if the state was STATE_INACTIVE in the\n previous frame, and the player pressed a key. This state only lasts one animation\n frame before switching to STATE_ACTIVE.\n\n STATE_ACTIVE: This is a session of normal gameplay. The player can move the\n ship and fire laser bolts. All of this should be handled inside of class Wave\n (NOT in this class). Hence the Wave class should have an update() method, just\n like the subcontroller example in lecture.\n\n STATE_PAUSED: Like STATE_INACTIVE, this is a paused state. However, the game is\n still visible on the screen.\n\n STATE_CONTINUE: This state restores the ship after it was destroyed. The\n application switches to this state if the state was STATE_PAUSED in the\n previous frame, and the player pressed a key. This state only lasts one animation\n frame before switching to STATE_ACTIVE.\n\n STATE_COMPLETE: The wave is over, and is either won or lost.\n\n You are allowed to add more states if you wish. Should you do so, you should\n describe them here.\n\n STATE_INTRO: This state comes immediatly after starting up the game from STATE_INACTIVE.\n it displayes an introduction message to orient the player with the setting and also\n provides the game controls and that powerups are worth grabbing. STATE_INTRO automatically\n enters STATE_ACTIVE after its message is complete, but can also be skipped by pressing\n spacebar.\n\n Parameter dt: The time in seconds since last update\n Precondition: dt is a number (int or float)\n \"\"\"\n # IMPLEMENT ME\n self._stateInfo()\n if self._state==STATE_INTRO:\n self._text=GLabel(text=self._message)\n self.GLabelstuff(self._text,30,'Arcade.ttf',GAME_WIDTH//2,GAME_HEIGHT//2,cornell.RGB(255, 255, 255))\n self.textwrite()\n if self._message==self._intro:\n self._state=STATE_NEWWAVE\n if self._state==STATE_NEWWAVE:\n self._wave=Wave()\n self._state=STATE_ACTIVE\n if self._state==STATE_ACTIVE:\n self.draw()\n self.view.clear()\n self._wave.update(self.view,self._state,self.input,dt)\n if self._state==STATE_PAUSED:\n self._text=GLabel(text='Press s to continue')\n if self._state==STATE_CONTINUE:\n self._wave.update(self.view,self._state,self.input,dt)\n self._state=STATE_ACTIVE\n if self._state==STATE_COMPLETE and self._wave.getLives()>0 and self._wave.getAliens()==0 and self._wave.getWavesleft()==0:\n self.view.clear()\n self._text=GLabel(text='You won!'+self._endmessage)\n if self._state==STATE_COMPLETE and self._wave.getLives()>0 and self._wave.getAliens()>0 and self._wave.getWavesleft()>=0:\n self.view.clear()\n self._text=GLabel(text='You lost :/'+self._endmessage)\n if self._state==STATE_COMPLETE and self._wave.getLives()==0:\n self.view.clear()\n self._text=GLabel(text='You lost :/'+self._endmessage)\n if self._state==STATE_COMPLETE and self._wave.getWavesleft()!=0:\n self.newwave()\n\n def draw(self):\n \"\"\"\n Draws the game objects to the view.\n\n Every single thing you want to draw in this game is a GObject. To draw a GObject\n g, simply use the method g.draw(self.view). It is that easy!\n\n Many of the GObjects (such as the ships, aliens, and bolts) are attributes in\n Wave. In order to draw them, you either need to add getters for these attributes\n or you need to add a draw method to class Wave. We suggest the latter. See\n the example subcontroller.py from class.\n \"\"\"\n self._background.draw(self.view)\n if self._text!=None:\n self._text.draw(self.view)\n if self._state==STATE_NEWWAVE:\n self._wave.draw(self.view)\n if self._state==STATE_ACTIVE:\n self._text.text=('Lives: '+str(self._wave.getLives()) +\n ' '+self._wave.getPowerup()+' '+\n 'Score: '+str(self._wave.getScore()))\n self.GLabelstuff(self._text,40,'Arcade.ttf',GAME_WIDTH//2,GAME_HEIGHT-60,cornell.RGB(255,255,255))\n self._wave.draw(self.view)\n if self._state==STATE_PAUSED or self._state==STATE_COMPLETE:\n self._wave.draw(self.view)\n self.GLabelstuff(self._text,60,'Arcade.ttf',GAME_WIDTH//2,GAME_HEIGHT//2,cornell.RGB(255,255,255))\n\n\n # HELPER METHODS FOR THE STATES GO HERE\n\n def _stateInfo(self):\n \"\"\"\n Called by update(), used to determine useful information depending on self._state.\n For STATE_INACTIVE, changes state from welcome screen to a new wave upon pressing 's'\n For STATE_PAUSED, changes state to STATE_CONTINUE upon pressing 's'\n For STATE_ACTIVE, gathers information on the current state of the wave and aliens left\n For STATE_INTRO, checks key presses to determine if the user wants to skip the intro\n For STATE_COMPLETE, creates the ending message to display and checks key presses\n to determine if user wishes to start over.\n \"\"\"\n key_s=self.input.is_key_down('s')\n curr_keys=self.input.key_count\n change=key_s and curr_keys>0\n key_space=self.input.is_key_down('spacebar')\n change2=key_space and curr_keys>0\n if self._state==STATE_INACTIVE:\n self._text=GLabel(text='Press s to play')\n self.GLabelstuff(self._text,60,'Arcade.ttf',GAME_WIDTH//2,GAME_HEIGHT//2,cornell.RGB(255, 255, 255))\n if change:\n self._state=STATE_INTRO\n self._lastkeys= curr_keys\n if self._state==STATE_PAUSED:\n if change:\n self._state=STATE_CONTINUE\n self._wave.setState(self._state)\n if self._state==STATE_ACTIVE:\n self._state=self._wave.getState()\n if self._state==STATE_INTRO:\n if change2:\n self._state=STATE_NEWWAVE\n if self._state==STATE_COMPLETE:\n self._endmessage='\\nScore: '+str(self._wave.getScore())+'\\n'\n if change2:\n self._state=STATE_INACTIVE\n\n\n def textwrite(self):\n \"\"\"\n Helper method used to write the intro message in STATE_INTRO.\n Utilizes two loop variables to adjust the speed at which text is written.\n Adds to the message on screen by adding each character in the str self._intro\n and stops when the two messages are the same.\n \"\"\"\n if self._jwrite0\n if change:\n self._wave = Wave(lives, waves-1, score)\n self._state = STATE_ACTIVE\n\n def GLabelstuff(self,obj,size,font,x,y,linecolor):\n \"\"\"\n Helper function that changes the other attributes of a created GLabel\n\n Parameter obj: GLabel object to modify\n Precondition: obj is a valid GLabel with text already assigned to it\n\n Parameter size: size of text to set\n Precondition: size is an int>0\n\n Parameter font: choice of font to use for text\n Precondition: font is a valid font_name\n\n Parameter x: center x coordinate for GLabel text\n Precondition: x is an int, 0 OrderListSchema:\n url = f'{self.main_api}/order/{self.get_default_query_parm(page, page_size, last_id, last_tm)}'\n response = requests.get(url, headers=self.headers)\n self.check_status_code(response.status_code)\n return order_parser(response)\n\n def get_measurement(\n self, page: int = 1, page_size: int = 25, last_id: int = 0, last_tm: int = 0\n ) -> MeasurementListSchema:\n\n url = f'{self.main_api}/measurement/{self.get_default_query_parm(page, page_size, last_id, last_tm)}'\n response = requests.get(url, headers=self.headers)\n self.check_status_code(response.status_code)\n return measurement_parser(response)\n\n def get_brand(\n self, page: int = 1, page_size: int = 25, last_id: int = 0, last_tm: int = 0\n ) -> BrandListSchema:\n\n url = f'{self.main_api}/brand/{self.get_default_query_parm(page, page_size, last_id, last_tm)}'\n response = requests.get(url, headers=self.headers)\n self.check_status_code(response.status_code)\n return brand_parser(response)\n\n def create_product(self, product_dto: ProductCreateSchema):\n product_dto = dataclasses.asdict(product_dto)\n url = f'{self.main_api}/product/'\n response = requests.post(url, headers=self.headers, json=product_dto)\n self.check_status_code(response.status_code)\n if response.status_code == 201:\n return True\n return print(response.text)\n\n def delete_product(self, provider_product_id: int):\n url = f'{self.main_api}/product/{provider_product_id}/'\n response = requests.delete(url, headers=self.headers)\n self.check_status_code(response.status_code)\n return True\n\n def upload_file(self, file_path: str) -> int:\n file = open(file_path, 'rb')\n url = f'{self.url}/api/v1/file/'\n response = requests.post(url, files={'file': file})\n self.check_status_code(response.status_code)\n return response.json()['id']\n\n def get_category(self):\n url = f'{self.main_api}/category/'\n response = requests.get(url, headers=self.headers)\n self.check_status_code(response.status_code)\n data = response.json()\n return data\n\n def check_status_code(self, status_code: int):\n if status_code == 401:\n raise AuthenticationError\n elif status_code == 404:\n raise NotFoundError\n\n def get_default_query_parm(self, page: int = 0, page_size: int = 25, last_id: int = 0, last_tm: int = 0) -> str:\n return f'?page={page}&page_size={page_size}&last_id={last_id}&last_tm={last_tm}'\n","sub_path":"setuz/setuz.py","file_name":"setuz.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"14876364","text":"import os\nfrom datetime import datetime\n\nimport xlrd\nfrom xlrd import xldate_as_tuple\nfrom xlutils.copy import copy\n\nDATAPATH = os.path.dirname(os.path.realpath(__file__)) # 获取项目根目录\nclass Excel():\n def __init__(self, filename):\n \"\"\"filename = excel文件名称,row = 从excel表的第几行开始读取\"\"\"\n\n self.filename = filename\n\n self.workbook = xlrd.open_workbook(DATAPATH+\n r\"/{}.xls\".format(\n filename)) #加载EXCLE文件\n\n self.table = self.workbook.sheets()[0] #获取文件sheet\n\n self.nrows = self.table.nrows #excel表格中的行数\n\n self.ncols = self.table.ncols #excel表格中的列数\n\n def read_excel(self, row):\n \"\"\"读取excel表格内的文件并且使用字典表进行储存\"\"\"\n list = []\n for r in range(row, self.nrows):\n app = {}\n for col in range(self.ncols):\n value = self.table.cell(r, col).value\n ctype = self.table.cell(r, col).ctype\n if ctype == 0:\n value = \"\"\n elif ctype == 1:\n value = value\n elif ctype == 2:\n value = int(value)\n elif ctype == 3:\n date = datetime(*xldate_as_tuple(value, 0))\n value = date.strftime(\"%Y/%m/%d %H:%M:%S\")\n elif ctype == 4:\n if value == 0:\n value = False\n if value == 1:\n value = True\n elif ctype == 5:\n value = \"错误~~~~~\"\n app[self.table.cell(row-1, col).value] = value\n list.append(app)\n\n return list\n def write_excel(self,datas,row = 1):\n \"\"\"写入excel表格\"\"\"\n new_excel = copy(self.workbook)\n ws = new_excel.get_sheet(0)\n if len(datas) == 0:\n print(\"错误!!!!\")\n else:\n for col in range(self.ncols):\n print(datas[col], \"datas[col]\")\n if datas[col] != \"\" or datas[col] == None:\n ws.write(row, col, datas[col])\n new_excel.save(DATAPATH+\n r\"\\{}.xls\".format(\n self.filename))\n def write_excel_rol(self,col,row, data):\n new_excel = copy(self.workbook)\n ws = new_excel.get_sheet(0)\n #print('写入中')\n ws.write(col, row, data)\n ws.col(0).width = 5555\n ws.col(1).width = 5555\n ws.col(2).width = 5555\n ws.col(4).width = 5555\n ws.col(5).width = 5555\n ws.col(6).width = 5555\n ws.col(8).width = 5555\n ws.col(9).width = 5555\n ws.col(10).width = 5555\n new_excel.save(DATAPATH +\n r\"/{}.xls\".format(\n self.filename))","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"288189577","text":"from keyboard import press_and_release, write\nfrom time import sleep, localtime\nimport webbrowser\nfrom pynput.mouse import Button, Controller\n\nmouse = Controller()\n\n\ndef marca():\n press_and_release('shift+2') # @\n write('victorialuquett')\n press_and_release('enter')\n sleep(1)\n press_and_release('shift+2') # @\n write('Quequeh0uve')\n press_and_release('enter')\n sleep(1)\n press_and_release('shift+2') # @\n write('juuldecereja')\n press_and_release('enter')\ndef envia():\n mouse.position = (1007, 458) # envia o cursor para o botao de enviar do twitter\n mouse.click(Button.left, 1)\ndef fechar():\n mouse.position = (1514, 11) # envia o cursor para o botão de fechar o chrome\n mouse.click(Button.left, 1)\n\nwhile True:\n hora = localtime()\n if(hora.tm_hour != 14): # caso não seja 14 horas \n print(\"esperando proxima hora\")\n sleep(3600)\n elif(hora.tm_hour == 14 and hora.tm_min == 30): # caso seja a hora exata do novo post\n webbrowser.open('https://twitter.com/vomaxroupa', new=2) # abre a pagina do twitter no chrome\n sleep(8)\n mouse.position = (739, 803) # Abre a Publicação mais recente\n sleep(0.1)\n mouse.click(Button.left, 1)\n sleep(2)\n press_and_release('r') # Aperta R para responder o tweet\n sleep(2)\n marca()\n sleep(2)\n envia()\n sleep(2)\n fechar()\n sleep(60)\n else:\n print(\"esperando minutagem\") #caso seja 14 horas porém não seja 14:30\n print(hora.tm_min)\n sleep(60)\n","sub_path":"Max.py","file_name":"Max.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"219172506","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom whichsandwich.models import Profile, Sandwich, Ingredient, Comment\nfrom whichsandwich.forms import UserForm, UserProfileForm, SandwichForm, CommentForm\nfrom django.urls import reverse\nimport random\n\ndef index(request):\n #http://127.0.0.1:8000/whichsandwich/\n\n sotd = None\n top_sandwiches = Sandwich.objects.order_by('-likes')\n if top_sandwiches:\n sotd = top_sandwiches[0]\n\n context_dict = {\n 'top_sandwiches': top_sandwiches[1:5],\n 'sotd': sotd,\n }\n\n response = render(request, 'whichsandwich/index.html', context = context_dict)\n return response\n\n #How do we define sandwich of the day\n\ndef browse(request):\n return render(request, 'whichsandwich/browse.html')\n\ndef modal(request):\n context_dict = {}\n if request.method == 'GET':\n sandwich_id = request.GET['sandwich_id']\n sandwich = Sandwich.objects.get(id=sandwich_id)\n context_dict['sandwich'] = sandwich\n try:\n comments = Comment.objects.filter(sandwich=sandwich)\n rand_comment_index = random.randint(0,len(comments) - 1)\n context_dict['comment'] = comments[rand_comment_index]\n except (IndexError, ValueError) as e:\n print(e)\n context_dict['comment'] = None\n return render(request, 'whichsandwich/modal.html', context_dict)\n\ndef browse_filter(request):\n sort_filter = None\n if request.method == 'GET':\n sort_filter = request.GET['sort_filter']\n if sort_filter == 'new':\n return new(request)\n elif sort_filter == 'controversial':\n return controversial(request)\n else:\n # Top by default\n return top(request)\n\ndef show_sandwich(request, sandwich_slug):\n context_dict = {}\n creator = request.user\n\t\n try:\n creator = Profile.objects.get(user=creator)\n context_dict['favourites'] = creator.favourites.all();\n except:\n context_dict['favourites'] = None\n\t\n try:\n sandwich = Sandwich.objects.get(slug=sandwich_slug)\n context_dict['sandwich'] = sandwich\n comments = Comment.objects.filter(sandwich=sandwich)\n context_dict['comments'] = comments\n except Sandwich.DoesNotExist:\n context_dict['sandwich'] = None\n context_dict['comments'] = None\n return render(request, 'whichsandwich/sandwich.html', context_dict)\n\ndef top(request):\n top_sandwiches = Sandwich.objects.order_by('-likes')\n \n context_dict = {'sandwiches': top_sandwiches}\n response = render(request, 'whichsandwich/sandwich_grid.html', context = context_dict)\n return response\n\ndef new(request):\n new_sandwiches = Sandwich.objects.order_by('-created_date')\n \n context_dict = {'sandwiches': new_sandwiches}\n response = render(request, 'whichsandwich/sandwich_grid.html', context = context_dict)\n return response\n\ndef controversial(request):\n # Maximum percentage difference between likes and dislikes for controversy\n max_perc_diff = 25\n\n # After a set number of likes & dislikes, a sandwich becomes elligible for controversy\n sandwiches = Sandwich.objects.filter(likes__gt=10, dislikes__gt=10)\n\n c_sandwiches = []\n\n # Get controversial sandwiches\n for sandwich in sandwiches:\n delta = abs(sandwich.likes - sandwich.dislikes)\n avg = (sandwich.likes + sandwich.dislikes)/2\n c_level = delta/avg*100\n if c_level <= max_perc_diff:\n # Add controversial sandwich to list alongside percentage difference\n # between likes and dislikes\n c_sandwiches.append([c_level, sandwich])\n\n # Sort sandwiches by difference between likes and dislikes\n c_sandwiches = sorted(c_sandwiches, key=lambda s: s[0])\n # Retrieve just the sandwich\n c_sandwiches = [s for c,s in c_sandwiches]\n \n return render(request, 'whichsandwich/sandwich_grid.html', {'sandwiches': c_sandwiches})\n\ndef sandwich_name(request):\n \n context_dict = {}\n try:\n # If we can't, the .get() method raises a DoesNotExist exception.\n names = Sandwich.objects.get('name')\n context_dict['Sandwich Names'] = names\n except Category.DoesNotExist:\n context_dict['Sandwich Names'] = None\n \n response = render(request, 'whichsandwich/browse.html', context = context_dict)\n return response\n\n@login_required\ndef my_account(request):\n best_sandwiches = Sandwich.objects.filter(creator=request.user).order_by('-likes', 'dislikes')\n top_favourites = request.user.profile.favourites.all().order_by('-likes', 'dislikes')[0:5]\n\n context_dict = {\n 'best_sandwiches': best_sandwiches,\n\t\t\t'top_favourites': top_favourites,\n }\n\n return render(request, 'whichsandwich/my_account.html', context = context_dict)\n\n@login_required\ndef my_sandwiches(request):\n sandwiches = Sandwich.objects.filter(creator=request.user)\n context_dict = {'sandwiches': sandwiches}\n return render(request, 'whichsandwich/my_sandwiches.html',\n context = context_dict)\n\n@login_required\ndef my_favourites(request):\n context_dict = {}\n favourites = request.user.profile.favourites.all()\n context_dict['sandwiches'] = favourites\n return render(request, 'whichsandwich/my_favourites.html', context=context_dict)\n\n@login_required\ndef create_sandwich(request):\n form = SandwichForm()\n\n if request.method == 'POST':\n form = SandwichForm(request.POST, request.FILES)\n\n if form.is_valid():\n sandwich = form.save(commit=False)\n sandwich.creator = request.user\n sandwich.save()\n form.save_m2m()\n return show_sandwich(request, sandwich.slug)\n else:\n print(form.errors)\n\n return render(request, 'whichsandwich/create_sandwich.html', {'form':form})\n\ndef about(request):\n\n #No need for context_dict if we do not show user's number of visits.\n return render(request, 'whichsandwich/about.html')\n\n@login_required\ndef comment(request, sandwich_slug):\n creator = request.user.profile\n sandwich = Sandwich.objects.get(slug=sandwich_slug)\n form = CommentForm()\n\n if request.method == 'POST':\n form = CommentForm(request.POST)\n\n if form.is_valid():\n comment = form.save(commit=False)\n comment.user = creator\n comment.sandwich = sandwich\n comment.save()\n form.save_m2m()\n return show_sandwich(request, sandwich.slug)\n else:\n print(form.errors)\n\n return render(request, 'whichsandwich/comment.html', {'form':form, 'sandwich':sandwich})\n\ndef add_to_favourites(request):\n creator = request.user\n creator = Profile.objects.get(user=creator)\n sw_name = None\n if request.method == 'GET':\n sw_name = request.GET['sandwich_name']\n if sw_name:\n sandwich = Sandwich.objects.get(name=sw_name)\n if sandwich:\n creator.favourites.add(sandwich)\n creator.save()\n\t\t\t\n return HttpResponse(\"Added to favourites\")\n\t\ndef like_sandwich(request):\n sw_name = None\n if request.method == 'GET':\n sw_name = request.GET['sandwich_name']\n likes = 0;\n if sw_name:\n sandwich = Sandwich.objects.get(name=sw_name)\n if sandwich:\n likes = sandwich.likes + 1\n sandwich.likes = likes\n sandwich.save()\n return HttpResponse(likes)\n\t\ndef dislike_sandwich(request):\n sw_name = None\n if request.method == 'GET':\n sw_name = request.GET['sandwich_name']\n dislikes = 0;\n if sw_name:\n sandwich = Sandwich.objects.get(name=sw_name)\n if sandwich:\n dislikes = sandwich.dislikes + 1\n sandwich.dislikes = dislikes\n sandwich.save()\n return HttpResponse(dislikes)\n","sub_path":"which_sandwich_project/whichsandwich/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"615269469","text":"import numpy as np\nimport numpy.linalg as nla\n\nimport fym\nimport fym.core\nimport fym.agents.LQR\nimport fym.logging as logging\nfrom fym.models.aircraft import MorphingLon\nfrom fym.utils.linearization import jacob_analytic\n\nfrom utils import get_poly\n\n\nclass BaseEnv(fym.core.BaseEnv):\n Q = np.diag([1, 100, 10, 100])\n R = np.diag([50, 1, 1, 1])\n\n def __init__(self, initial_perturb, **kwargs):\n self.system = MorphingLon([0, 0, 0, 0])\n self.IR_system = fym.core.BaseSystem(0, name=\"integral reward\")\n super().__init__(\n systems_dict={\n \"main\": self.system,\n \"IR\": self.IR_system,\n },\n **kwargs\n )\n\n self.initial_perturb = initial_perturb\n trim_x, trim_u = self.system.get_trim()\n self.trim_x = trim_x\n self.trim_u = trim_u\n self.system.initial_state = trim_x + initial_perturb\n\n def reset(self, initial_perturb=None):\n if initial_perturb == \"random\":\n self.system.initial_state = (\n self.trim_x\n + self.initial_perturb\n + [1, 0.05, 0.05, 0.05] * np.random.randn(4)\n )\n\n super().reset()\n return self.observation()\n\n def observation(self):\n return self.system.state - self.trim_x\n\n def step(self, action):\n done = self.clock.time_over()\n time = self.clock.get()\n x = self.observation()\n IR = self.IR_system.state\n u = action + self.trim_u\n\n if np.any(np.abs(x[(1, 3), ]) > np.deg2rad(30)):\n done = True\n\n self.update(u)\n\n next_x = self.observation()\n nIR = self.IR_system.state\n reward = nIR - IR\n\n info = {\n \"time\": time,\n \"state\": x,\n \"action\": action,\n \"reward\": reward,\n \"next_state\": next_x\n }\n\n return next_x, reward, done, info\n\n def set_dot(self, time, u):\n x, _ = self.observe_list()\n\n self.system.dot = self.system.deriv(x, u)\n self.systems_dict[\"IR\"].dot = self.reward(x, u)\n\n def reward(self, x, u):\n tx = x - self.trim_x\n tu = u - self.trim_u\n return tx.dot(self.Q).dot(tx) + tu.dot(self.R).dot(tu)\n\n\nclass AdpEnv(BaseEnv):\n def __init__(self, initial_perturb, W_init, eta, **kwargs):\n super().__init__(initial_perturb, W_init, **kwargs)\n self.eta = eta\n self.grad_u_phi_c = jacob_analytic(self.phi_c, i=1)\n\n def reset(self):\n super().reset()\n return self.observation()\n\n def observation(self):\n return self.observe_list()\n\n def step(self, action):\n done = self.clock.time_over()\n time = self.clock.get()\n x, dIR, W = self.observe_list()\n\n Wb, Wc = action\n bu = self.get_behavior(Wb, x)\n\n if np.any(np.abs(x[(1, 3), ]) > np.deg2rad(30)):\n done = True\n\n if np.abs(W).max() > 100 or np.abs(Wc).max() > 100:\n done = True\n\n self.update(action)\n\n IR = self.IR_system.state\n reward = IR - dIR\n\n info = {\n \"time\": time,\n \"trim_x\": self.trim_x,\n \"trim_u\": self.trim_u,\n \"state\": x,\n \"control\": bu,\n \"W\": W.ravel(),\n \"Wb\": Wb.ravel(),\n \"Wc\": Wc.ravel(),\n \"reward\": reward,\n }\n\n return self.observation(), reward, done, info\n\n def get_behavior(self, Wb, x):\n \"\"\"If ``x = self.trim_x``, then ``del_u = 0``. This is ensured by\n the structure of ``phi`` which has no constant term. Also,\n the behavior policy should always be saturated by the control limits\n defined by the system.\"\"\"\n del_ub = Wb.T.dot(self.phi(x))\n return self.system.saturation(self.trim_u + del_ub)\n\n def get_target(self, Wc, W, x):\n del_u = W.T.dot(self.phi(x))\n return self.system.saturation(self.trim_u + del_u)\n\n def set_dot(self, time, action):\n super().set_dot(time, action)\n x, _ = self.observe_list()\n Wb, Wc = action\n bu = self.get_behavior(Wb, x)\n # us = self.get_behavior(W, x)\n grad_Q = np.outer(\n self.phi(x),\n self.grad_u_phi_c(x, bu).T.dot(Wc)\n )\n\n self.systems_dict[\"W\"].dot = - self.eta * grad_Q\n","sub_path":"envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"77346620","text":"\n\nfrom xai.brain.wordbase.verbs._throb import _THROB\n\n#calss header\nclass _THROBBED(_THROB, ):\n\tdef __init__(self,): \n\t\t_THROB.__init__(self)\n\t\tself.name = \"THROBBED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"throb\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_throbbed.py","file_name":"_throbbed.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"526718025","text":"import tkinter as tk\nfrom tkinter import ttk\n\n#link\n\n__title__ = \"Statusbar\"\n__version__ = \"1.0.0\"\n__author__ = \"DeflatedPickle\"\n\nclass Statusbar (ttk.Frame):\n \"\"\"\n -----DESCRIPTION-----\n The Statusbar can be used to show certain variables.\n\n -----USAGE-----\n statusbar = Statusbar (parent)\n statusbar.pack ()\n statusbar.add_label (text = [string], textvariable = [string], image = [string], side = [string])\n statusbar.add_separator ()\n\n -----CONTENTS-----\n ---VARIABLES---\n\n ---WIDGETS---\n Self\n\n ---FUNCTIONS---\n add_label () = Adds a label to the statusbar.\n add_separator () = Adds a separator to the statusbar.\n \"\"\"\n def __init__ (self, parent, *args):\n ttk.Frame.__init__ (self, parent, *args)\n\n def add_label (self, text = \"\", textvariable = \"\", image = \"\", side = \"left\"):\n ttk.Label (self, text = text, textvariable = textvariable, image = image).pack (side = side)\n\n def add_sizegrip (self, side = \"left\"):\n ttk.Sizegrip (self).pack (side = side)\n\n def add_separator (self):\n ttk.Separator (self, orient = \"vertical\").pack (side = \"left\", fill = \"y\", padx = 3, pady = 1)\n\n##################################################\n\nif __name__ == \"__main__\":\n root = tk.Tk ()\n sbar = Statusbar (root)\n sbar.pack (expand = True, fill = \"x\", padx = 5, pady = 5)\n sbar.add_label (text = \"A Label\")\n sbar.add_separator ()\n sbar.add_sizegrip (side = \"right\")\n root.mainloop ()\n","sub_path":"pkinter/statusbar.py","file_name":"statusbar.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"397666497","text":"import pygame\n\nfrom Simulation import screen\n\nclass Info():\n def __init__( self, x, y, population ):\n self.x = x\n self.y = y\n self.height = 600\n self.width = 300\n self.color = (20,20,20)\n self.font_color = (229, 231, 233)\n self.font_title = pygame.font.Font(\"freesansbold.ttf\", 25 )\n self.font_normal = pygame.font.Font(\"freesansbold.ttf\", 20 )\n\n self.generation = 0\n self.population = population\n self.best = 0\n\n def Draw( self ):\n pygame.draw.rect(screen, self.color, [self.x, self.y, self.width, self.height])\n title_ = self.font_title.render(\"Genetic Algorithm\", True, self.font_color )\n pop_ = self.font_normal.render(\"Population: {}\".format(self.population ), True, self.font_color )\n gen_ = self.font_normal.render(\"Generation: {}\".format(self.generation), True, self.font_color )\n best = self.font_normal.render(\"Shortest: {}\".format(self.best), True, self.font_color )\n\n screen.blit( title_, (15,20) )\n screen.blit( pop_, (15,80) )\n screen.blit( gen_, (15,110) )\n screen.blit( best, (15,140) )\n","sub_path":"Simulation/classes/information.py","file_name":"information.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"115101274","text":"#!/usr/bin/env python\n#*-*coding:utf-8*-*\n#\n\nimport json\n\nclass ResponseDecorator():\n def __init__(self):\n self.data = {}\n self.fin_rsp = {}\n self.fin_rsp_j = None\n\n def get_images_deco(self, func):\n def get_image_rsp_deco():\n rsp = func()\n self.fin_rsp = {}\n self.data = {}\n self.data['images'] = []\n for i in range(len(rsp['data']['images'])):\n self.data['images'].append({\"id\": rsp['data']['images'][i]['id'], \n \"name\": rsp['data']['images'][i]['name']})\n self.fin_rsp['data'] = self.data\n self.fin_rsp_j = json.dumps(self.fin_rsp)\n return self.fin_rsp_j\n return get_image_rsp_deco\n\n def get_flavors_deco(self, func):\n def get_flavors_rsp_deco():\n rsp = func()\n self.data['success'] = True\n self.data['message'] = \"\"\n self.data['flavors'] = []\n for i in range(len(rsp['data']['flavors'])):\n self.data['flavors'].append({\"id\": rsp['data']['flavors'][i]['id'],\n \"name\": rsp['data']['flavors'][i]['name'],\n \"vcpus\": rsp['data']['flavors'][i]['vcpus'],\n \"memory\": rsp['data']['flavors'][i]['ram'],\n \"disk\": rsp['data']['flavors'][i]['disk']})\n self.fin_rsp['data'] = self.data\n self.fin_rsp_j = json.dumps(self.fin_rsp)\n return self.fin_rsp_j\n return get_flavors_rsp_deco\n\n def create_tenant_deco(self, func):\n def create_tenant_rsp_deco():\n rsp = func()\n self.data['success'] = True\n self.data['message'] = \"\"\n tenant_id = rsp['data']['tenant']['id']\n self.data['tenantId'] = tenant_id\n self.fin_rsp['data'] = self.data\n self.fin_rsp_j = json.dumps(self.fin_rsp)\n return self.fin_rsp_j\n return create_tenant_rsp_deco\n\n def get_quota_deco(self, func):\n def get_quota_rsp_deco():\n rsp = func()\n quota = {}\n self.data['message'] = \"\"\n self.data['quotas'] = {}\n self.data['success'] = True\n\n iaas_quota = rsp['data']['quota_set']\n quota['cores'] = iaas_quota.get('cores', None)\n quota['floatingIps'] = iaas_quota.get('floating_ips', None)\n quota['gigaBytes'] = iaas_quota.get('gigabytes', None)\n quota['injectedFileContentBytes'] = iaas_quota.get('injected_file_content_bytes', None)\n quota['injectedFilePathBytes'] = iaas_quota.get('injected_file_path_bytes', None)\n quota['injectedFiles'] = iaas_quota.get('injected_files', None)\n quota['instances'] = iaas_quota.get('instances', None)\n quota['keyPairs'] = iaas_quota.get('key_pairs', None)\n quota['metadataItems'] = iaas_quota.get('metadata_items', None)\n quota['ram'] = iaas_quota.get('ram', None)\n quota['securityGroupRules'] = iaas_quota.get('cores', None)\n quota['securityGroups'] = iaas_quota.get('security_groups', None)\n quota['volumes'] = iaas_quota.get('volumes', None)\n self.data['quotas'] = quota\n\n if self.data['quotas']:\n self.data['message'] = \"获取配额成功\"\n\n self.fin_rsp['data'] = self.data\n self.fin_rsp_j = json.dumps(self.fin_rsp)\n return self.fin_rsp_j\n return get_quota_rsp_deco\n\n def release_tenant_deco(self, func):\n def release_tenant_rsp_deco():\n rsp = func()\n self.data['message'] = \"\"\n self.data['success'] = rsp['data']['success']\n self.fin_rsp['data'] = self.data\n self.fin_rsp_j = json.dumps(self.fin_rsp)\n return self.fin_rsp_j\n return release_tenant_rsp_deco","sub_path":"decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"299587183","text":"# -*- coding: utf-8 -*-\n'''\nThis module implements :class:`AnalogSignalArray`, an array of analog signals.\n\n:class:`AnalogSignalArray` derives from :class:`BaseAnalogSignal`, from\n:module:`neo.core.analogsignal`.\n\n:class:`BaseAnalogSignal` inherits from :class:`quantites.Quantity`, which\ninherits from :class:`numpy.array`.\nInheritance from :class:`numpy.array` is explained here:\nhttp://docs.scipy.org/doc/numpy/user/basics.subclassing.html\n\nIn brief:\n* Initialization of a new object from constructor happens in :meth:`__new__`.\nThis is where user-specified attributes are set.\n\n* :meth:`__array_finalize__` is called for all new objects, including those\ncreated by slicing. This is where attributes are copied over from\nthe old object.\n'''\n\n# needed for python 3 compatibility\nfrom __future__ import absolute_import, division, print_function\n\nimport logging\n\nimport numpy as np\nimport quantities as pq\n\nfrom neo.core.analogsignal import (BaseAnalogSignal, AnalogSignal,\n _get_sampling_rate)\nfrom neo.core.baseneo import BaseNeo, merge_annotations\n\nlogger = logging.getLogger(\"Neo\")\n\n\nclass AnalogSignalArray(BaseAnalogSignal):\n '''\n Several continuous analog signals\n\n A representation of several continuous, analog signals that\n have the same duration, sampling rate and start time.\n Basically, it is a 2D array like AnalogSignal: dim 0 is time, dim 1 is\n channel index\n\n Inherits from :class:`quantities.Quantity`, which in turn inherits from\n :class:`numpy.ndarray`.\n\n *Usage*::\n\n >>> from neo.core import AnalogSignalArray\n >>> import quantities as pq\n >>>\n >>> sigarr = AnalogSignalArray([[1, 2, 3], [4, 5, 6]], units='V',\n ... sampling_rate=1*pq.Hz)\n >>>\n >>> sigarr\n \n >>> sigarr[:,1]\n \n >>> sigarr[1, 1]\n array(5) * V\n\n *Required attributes/properties*:\n :signal: (quantity array 2D, numpy array 2D, or list (data, chanel))\n The data itself.\n :units: (quantity units) Required if the signal is a list or NumPy\n array, not if it is a :class:`Quantity`\n :t_start: (quantity scalar) Time when signal begins\n :sampling_rate: *or* :sampling_period: (quantity scalar) Number of\n samples per unit time or\n interval between two samples.\n If both are specified, they are\n checked for consistency.\n\n *Recommended attributes/properties*:\n :name: (str) A label for the dataset.\n :description: (str) Text description.\n :file_origin: (str) Filesystem path or URL of the original data file.\n :channel_index: (numpy array 1D dtype='i') You can use this to order\n the columns of the signal in any way you want. It should have the\n same number of elements as the signal has columns.\n :class:`AnalogSignal` and :class:`Unit` objects can be given\n indexes as well so related objects can be linked together.\n\n *Optional attributes/properties*:\n :dtype: (numpy dtype or str) Override the dtype of the signal array.\n :copy: (bool) True by default.\n\n Note: Any other additional arguments are assumed to be user-specific\n metadata and stored in :attr:`annotations`.\n\n *Properties available on this object*:\n :sampling_rate: (quantity scalar) Number of samples per unit time.\n (1/:attr:`sampling_period`)\n :sampling_period: (quantity scalar) Interval between two samples.\n (1/:attr:`quantity scalar`)\n :duration: (Quantity) Signal duration, read-only.\n (size * :attr:`sampling_period`)\n :t_stop: (quantity scalar) Time when signal ends, read-only.\n (:attr:`t_start` + :attr:`duration`)\n :times: (quantity 1D) The time points of each sample of the signal,\n read-only.\n (:attr:`t_start` + arange(:attr:`shape`[0])/:attr:`sampling_rate`)\n :channel_indexes: (numpy array 1D dtype='i') The same as\n :attr:`channel_index`, read-only.\n\n *Slicing*:\n :class:`AnalogSignalArray` objects can be sliced. When taking a single\n row (dimension 1, e.g. [:, 0]), a :class:`AnalogSignal` is returned.\n When taking a single element, a :class:`~quantities.Quantity` is\n returned. Otherwise a :class:`AnalogSignalArray` (actually a view) is\n returned, with the same metadata, except that :attr:`t_start`\n is changed if the start index along dimension 1 is greater than 1.\n Getting a single item returns a :class:`~quantity.Quantity` scalar.\n\n *Operations available on this object*:\n == != + * /\n\n '''\n\n _single_parent_objects = ('Segment', 'RecordingChannelGroup')\n _quantity_attr = 'signal'\n _necessary_attrs = (('signal', pq.Quantity, 2),\n ('sampling_rate', pq.Quantity, 0),\n ('t_start', pq.Quantity, 0))\n _recommended_attrs = ((('channel_index', np.ndarray, 1, np.dtype('i')),) +\n BaseNeo._recommended_attrs)\n\n def __new__(cls, signal, units=None, dtype=None, copy=True,\n t_start=0 * pq.s, sampling_rate=None, sampling_period=None,\n name=None, file_origin=None, description=None,\n channel_index=None, **annotations):\n '''\n Constructs new :class:`AnalogSignalArray` from data.\n\n This is called whenever a new class:`AnalogSignalArray` is created from\n the constructor, but not when slicing.\n '''\n if (isinstance(signal, pq.Quantity)\n and units is not None\n and units != signal.units):\n signal = signal.rescale(units)\n if not units and hasattr(signal, \"units\"):\n units = signal.units\n obj = pq.Quantity.__new__(cls, signal, units=units, dtype=dtype,\n copy=copy)\n\n obj.t_start = t_start\n obj.sampling_rate = _get_sampling_rate(sampling_rate, sampling_period)\n\n obj.channel_index = channel_index\n obj.segment = None\n obj.recordingchannelgroup = None\n\n return obj\n\n def __init__(self, signal, units=None, dtype=None, copy=True,\n t_start=0 * pq.s, sampling_rate=None, sampling_period=None,\n name=None, file_origin=None, description=None,\n channel_index=None, **annotations):\n '''\n Initializes a newly constructed :class:`AnalogSignalArray` instance.\n '''\n BaseNeo.__init__(self, name=name, file_origin=file_origin,\n description=description, **annotations)\n\n @property\n def channel_indexes(self):\n '''\n The same as :attr:`channel_index`.\n '''\n return self.channel_index\n\n def __getslice__(self, i, j):\n '''\n Get a slice from :attr:`i` to :attr:`j`.\n\n Doesn't get called in Python 3, :meth:`__getitem__` is called instead\n '''\n return self.__getitem__(slice(i, j))\n\n def __getitem__(self, i):\n '''\n Get the item or slice :attr:`i`.\n '''\n obj = super(BaseAnalogSignal, self).__getitem__(i)\n if isinstance(i, int):\n return obj\n elif isinstance(i, tuple):\n j, k = i\n if isinstance(k, int):\n if isinstance(j, slice): # extract an AnalogSignal\n obj = AnalogSignal(obj, sampling_rate=self.sampling_rate)\n if j.start:\n obj.t_start = (self.t_start +\n j.start * self.sampling_period)\n # return a Quantity (for some reason quantities does not\n # return a Quantity in this case)\n elif isinstance(j, int):\n obj = pq.Quantity(obj, units=self.units)\n return obj\n elif isinstance(j, int): # extract a quantity array\n # should be a better way to do this\n obj = pq.Quantity(np.array(obj), units=obj.units)\n return obj\n else:\n return obj\n elif isinstance(i, slice):\n if i.start:\n obj.t_start = self.t_start + i.start * self.sampling_period\n return obj\n else:\n raise IndexError(\"index should be an integer, tuple or slice\")\n\n def time_slice(self, t_start, t_stop):\n '''\n Creates a new AnalogSignal corresponding to the time slice of the\n original AnalogSignal between times t_start, t_stop. Note, that for\n numerical stability reasons if t_start, t_stop do not fall exactly on\n the time bins defined by the sampling_period they will be rounded to\n the nearest sampling bins.\n '''\n\n # checking start time and transforming to start index\n if t_start == None:\n i = 0\n else:\n t_start = t_start.rescale(self.sampling_period.units)\n i = (t_start - self.t_start) / self.sampling_period\n i = int(np.rint(i.magnitude))\n\n # checking stop time and transforming to stop index\n if t_stop == None:\n j = len(self)\n else:\n t_stop = t_stop.rescale(self.sampling_period.units)\n j = (t_stop - self.t_start) / self.sampling_period\n j = int(np.rint(j.magnitude))\n\n if (i < 0) or (j > len(self)):\n raise ValueError('t_start, t_stop have to be withing the analog \\\n signal duration')\n\n # we're going to send the list of indicies so that we get *copy* of the\n # sliced data\n obj = super(BaseAnalogSignal, self).__getitem__(np.arange(i, j, 1))\n obj.t_start = self.t_start + i * self.sampling_period\n\n return obj\n\n def merge(self, other):\n '''\n Merge the another :class:`AnalogSignalArray` into this one.\n\n The :class:`AnalogSignalArray` objects are concatenated horizontally\n (column-wise, :func:`np.hstack`).\n\n If the attributes of the two :class:`AnalogSignalArray` are not\n compatible, and Exception is raised.\n '''\n assert self.sampling_rate == other.sampling_rate\n assert self.t_start == other.t_start\n other.units = self.units\n stack = np.hstack(map(np.array, (self, other)))\n kwargs = {}\n for name in (\"name\", \"description\", \"file_origin\"):\n attr_self = getattr(self, name)\n attr_other = getattr(other, name)\n if attr_self == attr_other:\n kwargs[name] = attr_self\n else:\n kwargs[name] = \"merge(%s, %s)\" % (attr_self, attr_other)\n if self.channel_index is None:\n channel_index = other.channel_index\n elif other.channel_index is None:\n channel_index = self.channel_index\n else:\n channel_index = np.append(self.channel_index,\n other.channel_index)\n merged_annotations = merge_annotations(self.annotations,\n other.annotations)\n kwargs.update(merged_annotations)\n return AnalogSignalArray(stack, units=self.units, dtype=self.dtype,\n copy=False, t_start=self.t_start,\n sampling_rate=self.sampling_rate,\n channel_index=channel_index,\n **kwargs)\n","sub_path":"core/analogsignalarray.py","file_name":"analogsignalarray.py","file_ext":"py","file_size_in_byte":11882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"440623955","text":"import os\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport utils\nfrom keras.models import load_model\nfrom keras import backend as K\nfrom sklearn.neighbors import NearestNeighbors\nfrom preprocess import preprocess\n\nparser = argparse.ArgumentParser(description='Malconv-keras classifier training')\nparser.add_argument('--save_path', type=str, default='../saved/adversarial_samples', help=\"Directory for saving adv samples\")\nparser.add_argument('--model_path', type=str, default='../saved/malconv.h5', help='Path to target model')\nparser.add_argument('--log_path', type=str, default='../saved/adversarial_log.csv', help=\"[csv file] Adv sample generation log\")\nparser.add_argument('--pad_percent', type=float, default=0.1, help=\"padding percentage to origin file\")\nparser.add_argument('--thres', type=float, default=0.5, help=\"generate adv if origin score below threshold\")\nparser.add_argument('--step_size', type=float, default=0.01, help=\"optimiztion step size for fgsm, senitive\")\nparser.add_argument('--limit', type=float, default=0., help=\"limit gpu memory percentage\")\nparser.add_argument('csv', type=str, help=\"[csv file] Filenames\")\n\ndef fgsm(model, inp, pad_idx, pad_len, e, step_size=0.001):\n adv = inp.copy()\n loss = K.mean(model.output[:, 0])\n grads = K.gradients(loss, model.layers[1].output)[0]\n grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-8)\n \n mask = np.zeros(model.layers[1].output.shape[1:]) # embedding layer output shape\n mask[pad_idx:pad_idx+pad_len] = 1\n grads *= K.constant(mask)\n \n iterate = K.function([model.layers[1].output], [loss, grads])\n g = 0.\n step = int(1/step_size)*10\n for _ in range(step):\n loss_value, grads_value = iterate([adv])\n grads_value *= step_size\n g += grads_value\n adv += grads_value\n #print (e, loss_value, end='\\r')\n if loss_value >= 0.9:\n break\n \n return adv, g, loss_value\n\n \ndef gen_adv_samples(model, fn_list, pad_percent=0.1, step_size=0.001, thres=0.5):\n \n ### search for nearest neighbor in embedding space ###\n def emb_search(org, adv, pad_idx, pad_len, neigh):\n out = org.copy()\n for idx in range(pad_idx, pad_idx+pad_len):\n target = adv[idx].reshape(1, -1)\n best_idx = neigh.kneighbors(target, 1, False)[0][0]\n out[0][idx] = best_idx\n return out\n \n \n max_len = int(model.input.shape[1])\n emb_layer = model.layers[1]\n emb_weight = emb_layer.get_weights()[0]\n inp2emb = K.function([model.input]+ [K.learning_phase()], [emb_layer.output]) # [function] Map sequence to embedding \n \n # Build neighbor searches\n neigh = NearestNeighbors(1)\n neigh.fit(emb_weight)\n \n log = utils.logger()\n adv_samples = []\n\n for e, fn in enumerate(fn_list):\n\n ### run one file at a time due to different padding length, [slow]\n inp, len_list = preprocess([fn], max_len)\n inp_emb = np.squeeze(np.array(inp2emb([inp, False])), 0)\n\n pad_idx = len_list[0]\n pad_len = max(min(int(len_list[0]*pad_percent), max_len-pad_idx), 0)\n org_score = model.predict(inp)[0][0] ### origianl score, 0 -> malicious, 1 -> benign\n loss, pred = float('nan'), float('nan')\n \n if pad_len > 0:\n \n if org_score < thres:\n adv_emb, gradient, loss = fgsm(model, inp_emb, pad_idx, pad_len, e, step_size)\n adv = emb_search(inp, adv_emb[0], pad_idx, pad_len, neigh)\n pred = model.predict(adv)[0][0]\n final_adv = adv[0][:pad_idx+pad_len]\n \n else: # use origin file\n final_adv = inp[0][:pad_idx]\n \n \n log.write(fn, org_score, pad_idx, pad_len, loss, pred)\n \n # sequence to bytes\n bin_adv = bytes(list(final_adv))\n adv_samples.append(bin_adv)\n \n return adv_samples, log\n \n\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n \n # limit gpu memory\n if args.limit > 0:\n utils.limit_gpu_memory(args.limit)\n \n df = pd.read_csv(args.csv, header=None)\n fn_list = df[0].values\n model = load_model(args.model_path)\n \n adv_samples, log = gen_adv_samples(model, fn_list, args.pad_percent, args.step_size, args.thres)\n \n # write to file\n log.save(args.log_path)\n for fn, adv in zip(fn_list, adv_samples):\n _fn = fn.split('/')[-1]\n dst = os.path.join(args.save_path, _fn)\n with open(dst, 'wb') as f:\n f.write(adv)\n","sub_path":"deep_learning/src/gen_adversarial.py","file_name":"gen_adversarial.py","file_ext":"py","file_size_in_byte":4742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"396539421","text":"import mtcnn\nfrom PIL import Image\nfrom numpy import asarray\nimport matplotlib.pyplot as plt\nimport os\n\ndef detect_face(path):\n img = Image.open(path,\"r\")\n if img.mode in (\"RGBA\", \"P\"): img = img.convert(\"RGB\")\n img_array = asarray(img)\n detector = mtcnn.MTCNN()\n face = detector.detect_faces(img_array)\n if (face):\n x,y,w,h = face[0]['box']\n x1 = x - w*0.1 if x - w*0.1 > 0 else 0\n y1 = y - h*0.1 if y - h*0.1 > 0 else 0\n x2 = x1 + w*1.2 if x1 + w*1.2 < img_array.shape[1] else img_array.shape[1]\n y2 = y1 + h*1.2 if y1 + w*1.2 < img_array.shape[0] else img_array.shape[0]\n img_new = img_array[int(y1):int(y2), int(x1):int(x2)]\n img_new = Image.fromarray(img_new)\n return img_new\n else :\n return 0\n\ndef detect_all_image(path):\n train_folder = path+\"train/\"\n val_folder = path+\"val/\"\n\n train_img_list = []\n val_img_list = []\n\n list_dir_train = os.listdir(train_folder)\n list_dir_val = os.listdir(val_folder)\n\n for dir in list_dir_train:\n count=0\n for img_dir in os.listdir(train_folder+\"/\" +dir):\n img_path = train_folder+dir+\"/\"+img_dir\n face = detect_face(img_path)\n if (face):\n train_img_list.append(face)\n face.save(\"../dataAfterDetect/train/\"+dir+str(count)+\".jpg\")\n count+=1\n for dir in list_dir_val:\n count=0\n for img_dir in os.listdir(val_folder+\"/\"+dir):\n img_path = val_folder+dir+\"/\"+img_dir\n face = detect_face(img_path)\n if(face):\n val_img_list.append(face)\n face.save(\"../dataAfterDetect/val/\"+dir+str(count)+\".jpg\")\n count+=1\n\n return train_img_list, val_img_list\n\ntrain_img_list, val_img_list = detect_all_image(\"../Data/\")","sub_path":"main/detectFace.py","file_name":"detectFace.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"71028241","text":"from django.utils import translation\n\nclass LocaleMiddleware(object):\n \"\"\"This middleware checks if we come from a Plone site\n that set a language cookie. In that case we use that\n language\"\"\"\n\n def process_request(self, request):\n forced_lang = request.GET.get('set_language', None)\n request.forced_lang = forced_lang\n if forced_lang:\n translation.activate(forced_lang)\n request.LANGUAGE_CODE = translation.get_language()\n if hasattr(request, 'session'):\n request.session['django_language'] = forced_lang","sub_path":"src/classifieds/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"636826570","text":"import tensorflow as tf\nimport numpy as np\nimport pickle\nimport time\n\nStart_time = time.time()\nimport matplotlib.pyplot as plt\nimport warnings\ntf.compat.v1.enable_eager_execution()\nwarnings.filterwarnings(\"ignore\")\n\n\ntrain_features = pickle.load(open(\"X_train.pickle\", \"rb\"))\nprint(\"X\", len(train_features))\ntrain_labels = pickle.load(open(\"y_train.pickle\", \"rb\"))\nprint(\"y\", len(train_labels), \"Shape\", tf.shape(train_labels))\ntest_features = pickle.load(open(\"X_test.pickle\", \"rb\"))\nprint(\"X\", len(test_features))\ntest_labels = pickle.load(open(\"y_test.pickle\", \"rb\"))\nprint(\"y\", len(test_labels))\nprint(\"DATA LOADED\")\ntest_features = test_features / 255.0\n\nbatch_size = 32\n\ntrain_dataset = tf.data.Dataset.from_tensor_slices((train_features, train_labels))\ntrain_dataset = train_dataset.shuffle(1024).batch(batch_size)\ntest_dataset = tf.data.Dataset.from_tensor_slices((test_features, test_labels))\ntest_dataset = test_dataset.shuffle(1024).batch(batch_size)\n\nrelu_alpha = 0.2\ndropout_rate = 0.0\npadding = 'SAME'\n\n\ndef conv2d(inputs, filters, stride_size):\n out = tf.nn.conv2d(inputs, filters, strides=[1, stride_size, stride_size, 1], padding=padding)\n return tf.nn.relu(out)\n\n\ndef maxpool(inputs, pool_size, stride_size):\n return tf.nn.max_pool2d(inputs, ksize=[1, pool_size, pool_size, 1], padding=padding,\n strides=[1, stride_size, stride_size, 1])\n\n\ndef dense(inputs, weights):\n # x = tf.nn.leaky_relu(tf.matmul(inputs, weights), alpha=relu_alpha)\n x = tf.nn.relu(tf.matmul(inputs, weights))\n return tf.nn.dropout(x, rate=dropout_rate)\n\n\ninitializer = tf.initializers.glorot_uniform()\n\n\ndef get_weight(shape, name, is_training):\n return tf.Variable(initializer(shape), name=name, trainable=True)\n\n\noutput_classes = 3\nshapes = [\n [3, 3, 3, 16],\n [3, 3, 16, 16],\n [3, 3, 16, 32],\n [3, 3, 32, 32],\n [3, 3, 32, 64],\n [3, 3, 64, 64],\n [3, 3, 64, 128],\n [3, 3, 128, 128],\n [3, 3, 128, 256],\n [3, 3, 256, 256],\n [3, 3, 256, 512],\n [3, 3, 512, 512],\n [2048, 800], # weight of flattening layer changes according to size of the image\n # [3600, 2400],\n # [2400, 1600],\n # [512, 800],\n [800, 64],\n [64, output_classes]\n]\n\nshapes1 = [\n [3, 3, 3, 8],\n [3, 3, 8, 16],\n [3, 3, 16, 32],\n [3, 3, 32, 64],\n [3, 3, 64, 128],\n [3, 3, 128, 256],\n [3, 3, 256, 512],\n [3, 3, 512, 1024],\n [3, 3, 1024, 1024],\n [3, 3, 1024, 2048],\n [3, 3, 2048, 2048],\n [3, 3, 2048, 4096],\n [16384, 800], # weight of flattening layer changes according to size of the image\n #[3600, 2400],\n #[2400, 1600],\n #[512, 800],\n [800, 64],\n [64, output_classes]\n]\n\nweights = []\n#for i in range(len(shapes1)):\n# weights.append(get_weight(shapes1[i], 'weight{}'.format((i)), True))\n\ndef model(x):\n x = tf.cast(x, dtype=tf.float32)\n c1 = conv2d(x, weights[0], stride_size=1)\n c1 = conv2d(c1, weights[1], stride_size=1)\n p1 = maxpool(c1, pool_size=2, stride_size=2)\n\n c2 = conv2d(p1, weights[2], stride_size=1)\n c2 = conv2d(c2, weights[3], stride_size=1)\n p2 = maxpool(c2, pool_size=2, stride_size=2)\n\n c3 = conv2d(p2, weights[4], stride_size=1)\n c3 = conv2d(c3, weights[5], stride_size=1)\n p3 = maxpool(c3, pool_size=2, stride_size=2)\n\n c4 = conv2d(p3, weights[6], stride_size=1)\n c4 = conv2d(c4, weights[7], stride_size=1)\n p4 = maxpool(c4, pool_size=2, stride_size=2)\n\n c5 = conv2d(p4, weights[8], stride_size=1)\n c5 = conv2d(c5, weights[9], stride_size=1)\n p5 = maxpool(c5, pool_size=2, stride_size=2)\n\n c6 = conv2d(p5, weights[10], stride_size=1)\n c6 = conv2d(c6, weights[11], stride_size=1)\n p6 = maxpool(c6, pool_size=2, stride_size=2)\n\n flatten = tf.reshape(p6, shape=(tf.shape(p6)[0], -1))\n\n # d1 = dense(flatten, weights[12])\n # d2 = dense(d1, weights[13])\n # d3 = dense(d2, weights[14])\n d4 = dense(flatten, weights[12])\n d5 = dense(d4, weights[13])\n logits = tf.matmul(d5, weights[14])\n\n return tf.nn.softmax(logits)\n\n\noptimizer = tf.compat.v2.optimizers.SGD()\ntrain_loss = tf.compat.v2.metrics.Mean()\ntrain_accuracy = tf.compat.v2.metrics.SparseCategoricalAccuracy()\ntest_loss = tf.compat.v2.metrics.Mean()\ntest_accuracy = tf.compat.v2.metrics.SparseCategoricalAccuracy()\nloss_object = tf.compat.v2.losses.SparseCategoricalCrossentropy()\n\ndef train_step(images, labels):\n global weights\n weights = []\n for i in range(len(shapes)):\n weights.append(get_weight(shapes[i], 'weight{}'.format(i), True))\n with tf.GradientTape() as tape:\n predictions = model(images, True)\n loss = loss_object(labels, predictions)\n grads = tape.gradient(loss, weights)\n optimizer.apply_gradients(zip(grads, weights))\n train_loss(loss)\n train_accuracy(labels, predictions)\n\n\ndef test_step(images, labels):\n global weights\n weights = []\n for i in range(len(shapes)):\n weights.append(get_weight(shapes[i], 'weight{}'.format(i), False))\n predictions = model(images, False)\n t_loss = loss_object(labels, predictions)\n test_loss(t_loss)\n test_accuracy(labels, predictions)\n\n\nnum_epochs = 200\n\nTrain_loss =[]\nTrain_accuracy =[]\nTest_loss = []\nTest_accuracy =[]\n\ndef train_and_test(EPOCHS):\n weights = []\n for e in range(EPOCHS):\n print('Epoch {} out of {} {}'.format(e + 1, num_epochs, '--' * 20))\n for images, labels in train_dataset:\n train_step(tf.cast(images, tf.float32), labels)\n for test_images, test_labels in test_dataset:\n test_step(tf.cast(test_images, tf.float32), test_labels)\n\n print(\"Average Loss = {:.4f}\".format(train_loss.result()))\n Train_loss.append(train_loss.result())\n print(\"Avrage Accuracy = {:.3f}%\".format(train_accuracy.result() * 100))\n Train_accuracy.append(train_accuracy.result() * 100)\n print(\"Test Average Loss = {:.4f}\".format(test_loss.result()))\n Test_loss.append(test_loss.result())\n print(\"Test Avrage Accuracy = {:.3f}%\".format(test_accuracy.result() * 100))\n Test_accuracy.append( test_accuracy.result() * 100)\n\ntf.executing_eagerly()\n\nfor i in range(10):\n print(\"TRIAL\", (i + 1), \"----------------------------------------------------------\")\n train_and_test(num_epochs)\n plt.figure(1)\n plt.title('TRAIN ACCURACY')\n plt.plot(Train_accuracy)\n plt.figure(2)\n plt.title('TRAIN LOSS')\n plt.plot(Train_loss)\n plt.figure(3)\n plt.title('TEST ACCURACY')\n plt.plot(Test_accuracy)\n plt.figure(4)\n plt.title('TEST LOSS')\n plt.plot(Test_loss)\n print(\"Maximum Training Accuracy {:.3f}%\".format((np.amax(Train_accuracy))))\n print(\"Maximum Testing Accuracy {:.3f}%\".format((np.amax(Test_accuracy))))\n Train_accuracy = []\n Train_loss = []\n Test_accuracy = []\n Test_loss = []\nprint(\"EXECUTION TIME: \", int((time.time() - Start_time) // 3600), \":\",\n int((time.time() - Start_time) % 3600 // 60), \":\",\n int((time.time() - Start_time) % 3600 % 60))\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.show()\n","sub_path":"CNN_2.py","file_name":"CNN_2.py","file_ext":"py","file_size_in_byte":7092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"357211371","text":"from mlflow import log_metric, log_param, log_artifacts\nimport mlflow.sklearn\nfrom mlops_pipeline.modelisation import get_data, get_params, make_model, preprocess_data, split_data, get_scores\nfrom mlops_pipeline import get_commit\n\n\ndef run_model_safe(file):\n try:\n model, score_cv, accuracy = run_model(file)\n\n except Exception as e:\n with open(\"outputs/exception.txt\", \"w\") as f:\n f.write(f\"Got an error message on the run : {e}\")\n log_artifacts(\"outputs\")\n model = None\n score_cv = None\n accuracy = None\n mlflow.end_run()\n\n return model, score_cv, accuracy\n\n\ndef run_model(file):\n\n mlflow.start_run(run_name=file)\n\n # Get data - log file name\n X, Y = get_data(file)\n X = preprocess_data(X)\n X_train, X_test, Y_train, Y_test, seed = split_data(X, Y)\n log_param(\"seed\", seed)\n\n # Get params - log them\n param_gamma, param_C = get_params()\n log_param(\"gamma\", param_gamma)\n log_param(\"C\", param_C)\n\n # Run model\n model, score_cv = make_model(X_train, Y_train, param_gamma, param_C)\n log_metric(\"score_cv\", score_cv)\n\n accuracy = get_scores(model, X_test, Y_test)\n log_metric(\"accuracy\", accuracy)\n\n # Save model into mlflow / make it accesible\n mlflow.sklearn.log_model(model, \"model\")\n\n r = get_commit('/home/melanie/Documents/code/mlops_pipeline')\n with open(\"outputs/git_info.txt\", \"w\") as f:\n f.write(f\"code used is project MLOPS_PIPELINE, commit {r}\")\n\n with open(\"outputs/test.txt\", \"w\") as f:\n f.write(\"Any kind of log on the the run should end up here to be easily accessible to any one, images, ...\")\n log_artifacts(\"outputs\")\n\n mlflow.end_run()\n\n return model, score_cv, accuracy\n\n\n\n\n","sub_path":"mlops_pipeline/mlflow_follow_up.py","file_name":"mlflow_follow_up.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"624125935","text":"from combination import Combination\nimport random\n\ndef schuiven(combinatie):\n attempts = 0\n maxattempts = 100\n while attempts < maxattempts:\n # kies een willekeurig huis (shuffle array en dan de 1e)\n random.shuffle(combinatie.houses)\n # bereken extra vrijstand van huis\n temp = combinatie.geefVrijstand(combinatie.houses[0], 0)\n if temp > 0:\n huis = combinatie.houses[0]\n hoek = combinatie.houses[0].hoekpunt\n # kies plaats om naar toe te schuiven\n newx = random.randint(hoek.x - temp, hoek.x + temp)\n newy = random.randint(hoek.y - temp, hoek.y + temp)\n while newx - huis.minVrij < 0 or newx + huis.width + huis.minVrij > combinatie.map.width:\n newx = random.randint(hoek.x - temp, hoek.x + temp)\n while newy - huis.minVrij < 0 or newy + huis.length + huis.minVrij > combinatie.map.length:\n newy = random.randint(hoek.y - temp, hoek.y + temp)\n # indien mogelijk: verplaats\n mogelijk = True\n for i in range(1, len(combinatie.houses)):\n xH2 = combinatie.houses[i].hoekpunt.x\n yH2 = combinatie.houses[i].hoekpunt.y\n #check if H2 left and right corners are within H1's x-range\n if (newx - huis.minVrij <= xH2 <= newx + huis.width + huis.minVrij) or (newx - huis.minVrij <= xH2+combinatie.houses[i].width <= newx + huis.width + huis.minVrij):\n #check if H2 top and bottom corners are within H1's y-range\n if (newy - huis.minVrij <= yH2 <= newy + huis.length + huis.minVrij) or (newy - huis.minVrij <= yH2+combinatie.houses[i].length <= newy + huis.length + huis.minVrij):\n mogelijk = False\n #check if H1 left and right corners are within H2's x-range\n if (xH2 - combinatie.houses[i].minVrij <= newx <= xH2 + combinatie.houses[i].width + combinatie.houses[i].minVrij) or (xH2 - combinatie.houses[i].minVrij <= newx+huis.width <= xH2 + combinatie.houses[i].width + combinatie.houses[i].minVrij):\n #check if H1 top and bottom corners are within H2's y-range\n if (yH2 - combinatie.houses[i].minVrij <= newy <= yH2+combinatie.houses[i].length + combinatie.houses[i].minVrij) or (yH2 - combinatie.houses[i].minVrij <= newy+huis.length <= yH2 + combinatie.houses[i].length + combinatie.houses[i].minVrij):\n mogelijk = False\n # checken van water om 'kruisingen' te voorkomen\n # betekent dat beide delen wel in elkaars bereik liggen, maar de punten zelf niet.\n if mogelijk == True:\n huis.hoekpunt.setPoint(newx,newy)\n return True\n else:\n # indien geen: opnieuw huis kiezen\n pass\n attempts += 1\n # bereken waarde; indien hoger, bewaren en opnieuw. Anders verwerpen en opnieuw\n return False\n","sub_path":"schuiven.py","file_name":"schuiven.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"507626606","text":"# coding: utf-8\nimport re\nimport os\nimport logging\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nimport xml.etree.ElementTree as ET\nimport time\n\nfrom django.conf import settings\n\nfrom ..models import Process, Error\n\n#Initialisation des logs\nlogger = logging.getLogger(__name__)\n\ndef test_localisation(librairies,rcr):\n for library in librairies:\n if rcr == library.attrib['rcr'] :\n return True\n return False\n\ndef exist_in_sudoc(ppns_list,process):\n \"\"\"Teste pour une liste de PPN et un RCR données si une localisation existe dans le SUDOC\n\n Args:\n ppns_list (array): liste de ppn\n process (objec): traitement pour lequel la liste doit être traitée conctient le rcr process.process_library.library_rcr\n \"\"\"\n \n rcr = process.process_library.library_rcr\n logger.info(\"Thread {} début\".format(ppns_list))\n # Préparation et envoie de la requête à l'ABES\n session = requests.Session()\n retry = Retry(connect=3, backoff_factor=0.5)\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('https://', adapter)\n r = session.request(\n method='GET',\n headers= {\n \"User-Agent\": \"outils_biblio/0.1.0\",\n \"Accept\": \"application/xml\"\n },\n url= 'https://www.sudoc.fr/services/where/15/{}.xml'.format(','.join(ppns_list)))\n try:\n r.raise_for_status()\n except requests.exceptions.HTTPError:\n logger.error(\"{} :: alma_to_sudoc :: HTTP Status: {} || Method: {} || URL: {} || Response: {}\".format(','.join(ppns_list), r.status_code, r.request.method, r.url, r.text))\n # Si le service ne répond pas pour la requête on créé une erreur pour chaque PPN\n for ppn in ppns_list :\n error = Error( error_ppn = ppn,\n error_type = 'ERREUR_REQUETE',\n error_process = process) \n error.save() \n #Traitement des résultats\n else:\n ppns_requetes = [] \n ppns_connus =[] #Liste des ppns retrouvés par le web service\n results = r.content.decode('utf-8')\n root = ET.fromstring(results)\n #Pour chaque résultat \n for result in root.findall(\".//result\"):\n # On récupère le PPN nettoyé\n ppn = result.attrib['ppn']\n # On l'ajoute à la liste des ppns retrouvés par le web service\n ppns_connus.append(ppn)\n # On regarde si une localisation existe pour le PPN \n is_located = test_localisation(result.findall(\".//library\"),rcr)\n if is_located :\n logger.debug(\"{} :: Existe\".format(ppn))\n else :\n error = Error( error_ppn = ppn,\n error_type = 'LOC_INCONNUE_SUDOC',\n error_process = process)\n error.save()\n logger.debug(\"{} :: N'Existe pas\".format(ppn))\n # On identifie les ppns inconnus du SUDOC\n","sub_path":"sudoc/services/alma_to_sudoc.py","file_name":"alma_to_sudoc.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"190196249","text":"\n\ndef time_limited(timeout=0.5, return_val=np.nan, use_sigalrm=True):\n '\\n Decorator for setting a timeout for pure-Python functions.\\n\\n If the function does not return within `timeout` seconds, the\\n value `return_val` is returned instead.\\n\\n On POSIX this uses SIGALRM by default. On non-POSIX, settrace is\\n used. Do not use this with threads: the SIGALRM implementation\\n does probably not work well. The settrace implementation only\\n traces the current thread.\\n\\n The settrace implementation slows down execution speed. Slowdown\\n by a factor around 10 is probably typical.\\n '\n if (POSIX and use_sigalrm):\n\n def sigalrm_handler(signum, frame):\n raise TimeoutError()\n\n def deco(func):\n\n def wrap(*a, **kw):\n old_handler = signal.signal(signal.SIGALRM, sigalrm_handler)\n signal.setitimer(signal.ITIMER_REAL, timeout)\n try:\n return func(*a, **kw)\n except TimeoutError:\n return return_val\n finally:\n signal.setitimer(signal.ITIMER_REAL, 0)\n signal.signal(signal.SIGALRM, old_handler)\n return wrap\n else:\n\n def deco(func):\n\n def wrap(*a, **kw):\n start_time = time.time()\n\n def trace(frame, event, arg):\n if ((time.time() - start_time) > timeout):\n raise TimeoutError()\n return None\n sys.settrace(trace)\n try:\n return func(*a, **kw)\n except TimeoutError:\n sys.settrace(None)\n return return_val\n finally:\n sys.settrace(None)\n return wrap\n return deco\n","sub_path":"Data Set/bug-fixing-1/0ddd3737f103a8861b74d6e55f5404fd32377a0e--bug.py","file_name":"0ddd3737f103a8861b74d6e55f5404fd32377a0e--bug.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"225543685","text":"\nimport tweepy, time, sys, random\nfrom random import randint\n \nargfile = str(\"liners.txt\")\n \n\n \n#enter the corresponding information from your Twitter application:\nCONSUMER_KEY = ''#keep the quotes, replace this with your consumer key\nCONSUMER_SECRET = ''#keep the quotes, replace this with your consumer secret key\nACCESS_KEY = ''#keep the quotes, replace this with your access token\nACCESS_SECRET = ''#keep the quotes, replace this with your access token secret\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\napi = tweepy.API(auth)\n \nfilename=open(argfile,'r')\nf=filename.readlines()\nfilename.close()\n \nwhile True:\n for line in f:\n curtime= time.strftime(\"%H:%M:%S\")\n curdate= time.strftime(\"%x\")\n api.update_status(\"{0}---{1}, {2}\".format(curdate,curtime,line)) \n TimeToSleep = randint(780,1200)\n time.sleep(TimeToSleep)#Tweet every 15 minutes","sub_path":"Twit.py","file_name":"Twit.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"79990907","text":"\"\"\"GateTemplate URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\n\nurlpatterns = [\n\n url(r'^$', 'gate.views.login_page'), #index\n url(r'^login/$', 'gate.views.login_page'), #Login\n url(r'^logout/$', 'gate.views.logout_page'), #Logout\n url(r'^enter/$', 'gate.views.enter'), #EnterScript\n url(r'^main/$', 'gate.views.load', {'page': 'main'}), #MainPage\n url(r'^addtiket/$', 'gate.views.load', {'page': 'addtiket'}), #AddPage\n url(r'^report/$', 'gate.views.load', {'page': 'report'}), #ReportPage\n url(r'^category/$', 'gate.views.load', {'page': 'category'}), #CategoryPage\n url(r'^users/$', 'gate.views.load', {'page': 'users'}), #UsersPage\n\n #Temp\n url(r'^add_tiket/$', 'gate.views.add_tiket'), #AddTiket\n\n #Admin\n url(r'^admin/', include(admin.site.urls)),\n\n #API\n url(r'^(?P\\w+)/api/category/$', 'gate.api.category'),\n url(r'^(?P\\w+)/api/item/$', 'gate.api.item'),\n url(r'^(?P\\w+)/api/report/$', 'gate.api.report'),\n url(r'^(?P\\w+)/api/status/(?P\\d+)/$', 'gate.api.status'),\n]\n","sub_path":"GateTemplate/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"507872619","text":"\n'''\nhttps://www.reddit.com/r/dailyprogrammer/comments/pih8x/easy_challenge_1/\n\nCreate a program that will ask the users name, age, and reddit username. have it tell them the information back, in the format:\n\nYour name is (blank), you are (blank) years old and your username is (blank).\n\nFor extra credit, have the program log this information in a file to be accessed later.\n\n'''\n\nnome = input(\"Qual o seu nome? \")\nidade = input(\"Qual sua idade? \")\nreddit = input(\"Qual o seu nick no Reddit? \")\n\nprint(\"Your name is {}, you are {} years old and your username is {}\".format(nome, idade, reddit))\n","sub_path":"easy/ch001.py","file_name":"ch001.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"364682269","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 31 12:55:41 2016\n\n@author: gopan\n\"\"\"\n\n\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport statsmodels.api as sm\n\n\"\"\"\nIn this optional exercise, you should complete the function called \npredictions(turnstile_weather). This function takes in our pandas \nturnstile weather dataframe, and returns a set of predicted ridership values,\nbased on the other information in the dataframe. \n\nIn exercise 3.5 we used Gradient Descent in order to compute the coefficients\ntheta used for the ridership prediction. Here you should attempt to implement \nanother way of computing the coeffcients theta. You may also try using a reference implementation such as: \nhttp://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.html\n\nOne of the advantages of the statsmodels implementation is that it gives you\neasy access to the values of the coefficients theta. This can help you infer relationships \nbetween variables in the dataset.\n\nYou may also experiment with polynomial terms as part of the input variables. \n\nThe following links might be useful: \nhttp://en.wikipedia.org/wiki/Ordinary_least_squares\nhttp://en.wikipedia.org/w/index.php?title=Linear_least_squares_(mathematics)\nhttp://en.wikipedia.org/wiki/Polynomial_regression\n\nThis is your playground. Go wild!\n\nHow does your choice of linear regression compare to linear regression\nwith gradient descent computed in Exercise 3.5?\n\nYou can look at the information contained in the turnstile_weather dataframe below:\nhttps://s3.amazonaws.com/content.udacity-data.com/courses/ud359/turnstile_data_master_with_weather.csv\n\ndef predictions(weather_turnstile):\n #\n # Your implementation goes here. Feel free to write additional\n # helper functions\n # \n # R2 is too low 0.035 in place of 0.4. Try get_dummies \n features = weather_turnstile[['rain', 'precipi', 'Hour', 'fog', 'meanwindspdi', 'mintempi','meantempi']]\n features = np.array(features)\n features = sm.add_constant(features) \n features = (features - np.mean(features))/ np.std(features)\n values = weather_turnstile['ENTRIESn_hourly']\n model = sm.OLS(values, features)\n fit = model.fit()\n prediction = np.dot(features, fit.params)\n return prediction\n\n\"\"\"\ndef calc_r2(prediction, values):\n sse = ((values - prediction)**2).sum()\n ssto = ((values - np.mean(values))**2).sum()\n r_squared = 1 - sse / ssto\n return r_squared\n\nweather_turnstile = pd.read_csv('turnstile_data_master_with_weather.csv')\nfeatures = weather_turnstile[['rain', 'precipi', 'Hour', \n 'fog', 'meanwindspdi', 'meantempi']]\nfeatures['rain2'] = weather_turnstile['rain']**2\n#features = weather_turnstile[['rain', 'precipi', 'Hour']] #0.029\n\ndummy_units = pd.get_dummies(weather_turnstile['UNIT'], prefix='unit')\nfeatures = features.join(dummy_units)\n\nsigma = features.std()\nfeatures = (features - features.mean())/ sigma\nif (sigma == 0).any():\n raise Exception(\"featue(s) have same values => std = 0\")\nvalues = weather_turnstile['ENTRIESn_hourly']\n\nfeatures = sm.add_constant(features) \n# features['ones'] = np.ones(len(values))\nfeatures = np.array(features)\nvalues = np.array(values)\n\nmodel = sm.OLS(values, features)\nfit = model.fit()\nprediction = np.dot(features, fit.params)\n\nr_squared = calc_r2(prediction, values)\nprint('R^2', r_squared)\n\n\nX = features\nbetaHat = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(values)\nprediction2 = np.dot(features, betaHat)\nr_squared = calc_r2(prediction2, values)\nprint('HAT:R^2', r_squared)\n\n'''\nin betHat [(X'X)^-1 X'] is the Moore–Penrose pseudoinverse of X. \nAlthough this equation is correct, and can work in many applications, \nit is not computationally efficient to invert the \nnormal equations matrix (the Gramian matrix). An exception occurs \nin numerical smoothing and differentiation where an analytical \nexpression is required. \nUse Cholesky decomposition, QR decomposition or SVD.\nOrthogonal decomposition methods of solving the least squares problem \nare slower than the normal equations method but are more \nnumerically stable because they avoid forming the product X'X.\n\nSVD method is the most computationally intensive, but is particularly \nuseful if the normal equations matrix, X'X, is very ill-conditioned \n(i.e. if its condition number multiplied by the machine's relative \nround-off error is appreciably large). In that case, including the \nsmallest singular values in the inversion merely adds numerical noise\nto the solution. This can be cured with the truncated SVD approach, \ngiving a more stable and exact answer, by explicitly setting to zero\nall singular values below a certain threshold and so ignoring them,\na process closely related to factor analysis.\n'''\n##################################\nimport numpy as np\nimport matplotlib.pyplot as plt\ninp = np.array([\n [1, 6],\n [2, 5],\n [3, 7],\n [4, 10]\n])\nm = len(inp)\nX = np.array([np.ones(m), inp[:, 0]]).T\ny = np.array(inp[:, 1]).reshape(-1, 1)\nbetaHat = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)\nprint(betaHat)\nplt.figure(1)\nxx = np.linspace(0, 5, 2)\nyy = np.array(betaHat[0] + betaHat[1] * xx)\nplt.plot(xx, yy.T, color='b')\nplt.scatter(inp[:, 0], inp[:, 1], color='r')\nplt.show()\n\n\n","sub_path":"statsmodel1.py","file_name":"statsmodel1.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"571262795","text":"# -*- coding: utf-8 -*-\n# https://bottlepy.org/docs/dev/tutorial.html\n# https://habrahabr.ru/post/221659/\n# https://habrahabr.ru/post/250831/\n# https://github.com/MicrosoftArchive/redis/releases\n\n\n# Базовая защита от дурака - всё, что в ключах не англоязычные буквы/цифры - заменяем на \"_\", что при обращении, что при записи. \n# Лучше вынести в отдельную функцию\n# 1. Реализовать на главной счетчик обращений, который будет храниться в Redis и увеличиваться при каждом заходе на главную\n# 2. Реализовать добавление значения\n# 3. Реализовать получение значения\n# 4. Реализовать вывод списка ключей\n# 5. Реализовать по аналогии удаление ключей - по ссылке /del/, в index() добавлены header, footer - куда можно будет писать что-то своё\n\n\nimport webbrowser\nfrom bottle import Bottle, run, request, template, get, post\nfrom redis import Redis\nimport re \n\nHOST = '127.0.0.1'\nPORT = '54321'\n\napp = Bottle()\nr = Redis(decode_responses=True) #перевод значений в код строки\n\ndef protection(key):\n return re.sub(r'\\W', '_', key, flags=re.A) \n\n@app.get('/')\ndef index():\n counter = r.incr(\"visitors\")\n vars = {'counter':counter,\n 'header':'Welcome!',\n 'footer':'Good Luck!'}\n return template('static/index.html', vars)\n\n@app.post('/set/')\ndef set_key():\n key = request.forms.get('key')\n value = request.forms.get('value')\n key = protection(key)\n r.set(key, value)\n response = \"added key: %s
value: %s\" % (key,value)\n return template('% rebase(\"static/index.html\")\\n'+response)\n\n@app.get('/get/')\ndef get_key(key):\n value = r.get(key)\n response = 'key: %s
value: %s'%(key,value)\n return template('% rebase(\"static/index.html\")\\n'+response)\n\n@app.get('/list')\ndef list_keys():\n keys_list = r.keys()\n response = ''\n for key in keys_list:\n response += ''%(key,key)\n return template('% rebase(\"static/index.html\")\\n'+response)\n\n@app.get('/del/')\ndef delete_key(key):\n key = protection(key)\n if r.exists(key):\n r.delete(key)\n response = \"deleted key: {}\".format(key)\n else:\n response = \"not key\"\n return template('% rebase(\"static/index.html\")\\n'+response)\n\nif __name__ == \"__main__\":\n webbrowser.open('http://%s:%s'%(HOST, PORT))\n run(app, host=HOST, port=PORT, reloader=True, debug=True)\n","sub_path":"2018/04/04_Kudrevatykh.py","file_name":"04_Kudrevatykh.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"411360491","text":"\"\"\"Jasper Yun - Student ID: 1731131\nExercise 2: Modular Arithmetic\nThis program is used to calculate the quotients and remainders of two integers given to the program by the user.\nThere is a menu option to choose different methods to calculate a mod n, or to exit the program.\"\"\"\n\n#Question 1:\n\"\"\"This function takes an input of two integers, a and d, and divides them to find the\nquotient and remainder. The division is performed by subtracting d from a until a < d. If a < 0,\nthen the division uses a + d until a > 0.\nThe output of the function is the quotient and remainder of the division given by q, r.\"\"\"\n\ndef Quotient(a,d):\n r=a\n q=0\n while (r>=d): ##if r >= d, we can keep subtracting r - d until r < d, at which point we will be finished the division\n r=r-d\n q=q+1\n while (r<0): ##if r < 0, then we need to keep adding r + d until r > 0, at which point we will necessarily have 0 <= r < d, and we will be done dividing\n r=r+d\n q=q-1\n return q,r ##I chose not to return a tuple so that I could make the remainder (result of menu option 3) more salient\n\n\n\n#Question 2:\n\"\"\"This function takes an input of integers a, d, and q. It divides a and d to find the\nquotient and remainder recursively. The input q is the quotient, which is set to zero initially.\nIf the input is a >= 0, then there are two cases:\n (1) a < d, then the function will return (q, a);\n (2) a >= d, then the function will call itself and perform the division using recursive subtraction.\nIf the input is a < 0, then there are also two cases:\n (1) a > d, then the function will return (q, a);\n (2) a <= d, then the function will call itself and perform the division using recursive addition.\nThe condition is that d > 0, since d != 0 and my function will not return the proper result if d < 0.\nThe outut is the quotient and remainder, given by q, a.\"\"\"\n\ndef RecursiveQuotient(a,d, q=0):\n if a >= 0:##for positive integer inputs\n if a < d:\n return (q,a) ##I return a tuple here because I only need the recursive function for option 2 of the menu, which needs to output quotient and remainder, (q, r)\n else:\n return RecursiveQuotient(a - d, d, q + 1)\n elif a < 0: ##for negative integer inputs\n if a > 0: ##a>0 will only occur once a + d is performed enough times \n return (q, a)\n else:\n return RecursiveQuotient(a + d, d, q - 1)\n\n\n\n###Extra function that I defined to make question 3 slightly easier\n\"\"\"This function is used to loop back the menu options. It technically does not have any parameters.\nIt provides the user with an option to return to the menu or exit the program based on user input.\nEntering 1 calls the Menu() function. Inputting 2 exits the program.\"\"\"\n\ndef Loop():\n print(\"\")\n print(\"Alright! That was easy, wasn't it?\")\n print(\"Here are two more options for you now:\")\n ans = int(input(\"Enter 1 if you would like to return to the menu. Enter 2 if you would like to exit the program. \"))\n while not ((ans==1) or (ans==2)): ##To prevent an input that is not 1 or 2\n ans = int(input(\"You must choose an option by entering 1 or 2. \"))\n if (ans == 1):\n Menu()\n if (ans == 2):\n print(\"\")\n print(\"Have a nice day! Goodbye!\")\n\n\n\n#Question 3:\n\"\"\"This function is a menu to choose how divide two integers, a and d. It does not have any parameters, but to continue the program the user needs to enter a value for \"choice\", either 1, 2, 3, or 4. These choices will lead the program to using\neither the standard quotient method defined in question 1, the recursive quotient defined in question 2, reducing\nan integer into a modulo n, or exiting the program. This function combines the two functions above, and the choices commence\none of the above functions.\"\"\"\n\ndef Menu():\n print(\"\") #Some blank space\n print(\"Here are your menu options:\")\n print(\"Enter 1 if you would like to divide two integers using the standard quotient.\")\n print(\"Enter 2 if you would like to use the recursive quotient.\")\n print(\"Enter 3 if you would like to reduce an integer a modulo n.\")\n print(\"Enter 4 if you would like to exit the program.\")\n choice = input(\"Please choose an option now. \")\n \n while not ((choice==\"1\") or (choice==\"2\") or (choice==\"3\") or (choice==\"4\")): ##To prevent the program from crashing if the input is not 1,2,3, or 4.\n choice = input(\"You must choose an option by inputting 1, 2, 3, or 4. \")\n choice = int(choice) ##change the input into an integer since I did not specify that d was an integer above so that I could properly deal with non-integer inputs for \"choice\" and prevent the program from crashing\n\n if (choice == 1): \n print(\"\")\n print(\"Great choice. Let's begin.\")\n a = int(input(\"Please choose an integer for a. \"))\n d = int(input(\"Please choose a nonzero integer for d to divide a. \"))\n while (d == 0 or d<0): ##to prevent errors: (1) we cannot divide by 0; (2) my function will not run properly if d < 0; (3) the assignment instructions also indicate that d > 0\n if d == 0:\n d = int(input(\"Hey! You should know that we do not divide by zero. Please choose another integer for d: \"))\n if d<0:\n d = int(input(\"Unfortunately, dividing by a negative number is not currently supported. Please choose another integer for d: \"))\n q,r = Quotient(a,d)\n print(\"The quotient and remainder of\", a,\"and\", d, \"are given by (q,r) = (\", q,\",\",r,\").\")\n Loop() ##to allow the user to loop back to the menu or quit\n\n if (choice == 2):\n print(\"\")\n print(\"Ahh, a bold move that is, using recursion. I like it!\")\n print(\"Let's begin with choosing the values.\")\n a = int(input(\"Please choose an integer for a. \"))\n d = int(input(\"Please choose a nonzero positive integer for d to divide a. \"))\n while (d==0 or d<0): ##to prevent errors: (1) we cannot divide by zero; (2) the function will not run properly if d < 0; (3) the assignment only requires that a, d > 0\n if d==0:\n d = int(input(\"Hey! You should remember that we cannot divide by zero. Please choose a different integer for d. \"))\n if d<0:\n d = int(input(\"Unfortunately, dividing by a negative integer is not currently supported by this program. Please choose a positive integer for d. \"))\n q,r = RecursiveQuotient(a,d)\n print(\"The quotient and remainder of\", a,\"and\", d, \"are given by (q,r) = (\", q,\",\",r,\").\")\n Loop()\n\n if (choice == 3):\n print(\"\")\n print(\"Alright! Let me do the work for you.\")\n a = int(input(\"Please choose the integer that you would like to reduce. \"))\n d = int(input(\"Please choose the modulus you would like to reduce in. \"))\n while (d==0 or d<0): ##to prevent errors: (1) we cannot divide by zero; (2) the function will not run properly if d < 0\n if d==0:\n d = int(input(\"Hey! You should remember that we cannot divide by zero. Please choose a different integer for d. \"))\n if d<0:\n d = int(input(\"Unfortunately, negative moduli are not currently supported by this program. Please choose a positive integer for d. \"))\n q,r = Quotient(a,d)\n print(\"The quotient and remainder of\", a,\"and\", d, \"are given by (q,r) = (\", q,\",\",r,\").\")\n print(\"Therefore,\", a, \"mod\", d, \"reduces to\", r,\".\")\n Loop()\n\n if (choice == 4):\n print(\"\")\n print(\"Have a nice day! Goodbye!\")\n\n\n\n##Some text to introduce the program before the menu options; they are placed here rather than in the Loop() so that they do not keep appearing every time we loop\nprint(\"Hello! Welcome to my modular arithmetic calculator.\")\nprint(\"This program will allow you to calculate the quotient and remainder of two values, a and d, when dividing a by d. You will choose a and d.\")\nprint(\"You may choose two different methods to calculate the quotient, or reduce an integer a modulo n.\")\nprint(\"\") #provide a line break before the menu options\n \nMenu() #to run the program\n","sub_path":"Assignments/A2-ModularArithmetic.py","file_name":"A2-ModularArithmetic.py","file_ext":"py","file_size_in_byte":8189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"197817302","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport json\nimport pickle\nfrom PIL import Image\nimport streamlit.components.v1 as components\nimport xgboost\nimport shap\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nimport os\n\n#Setting the page configuration\nsquare_icon = Image.open(os.path.abspath('Project/streamlit/images/skincare_square.jpeg'))\nlong_icon = Image.open(os.path.abspath('Project/streamlit/images/top_banner.png')) \nlong_bw = Image.open(os.path.abspath(\"Project/streamlit/images/bw_long.jpeg\"))\nsquare_logo = Image.open(os.path.abspath(\"Project/streamlit/images//teen_beauty.png\"))\nlogo = Image.open(os.path.abspath(\"Project/streamlit/images//logo_trans.png\"))\nend_icon = Image.open(os.path.abspath(\"Project/streamlit/images//lower_banner.png\"))\nst.set_page_config(\n page_title=\"Product and Ingredient Analysis\",\n page_icon=square_logo,\n layout=\"centered\",\n initial_sidebar_state=\"auto\")\n\n#loading necessary files\n@st.cache\ndef fetch_data(path):\n df = pd.read_json(path)\n return df\n\nprod_ingr_matrix1 = fetch_data('Project/data/processed_data/product_ingr_inventory.json')\ndot_prod= fetch_data('../data/processed_data/common_ingr.json')\nsim_df= fetch_data('../data/processed_data/cos_sim.json')\ndf_new = fetch_data('../data/processed_data/combined_data.json')\nx_complete = fetch_data('../data/train_test/x_complete.json')\ndf1 = fetch_data('../data/processed_data/pre_modelling_data.json')\n\n#st.write(df1.head())\n\n#functions \n@st.cache\ndef similar_prod(item, n=10, all_types = True):\n '''\n return the n most similar products\n '''\n tp = sim_df[item].sort_values(axis=0, ascending=False)\n tp = pd.DataFrame(tp)[0:n+1]\n tp.rename(columns={item:'cos_score'}, inplace=True)\n tp['cos_score']= np.round(tp['cos_score']*100,2)\n for i in list(tp.index):\n tp.loc[i, 'jac_score'] = np.round(jaccard_binary(np.array(prod_ingr_matrix1.loc[item]), np.array(prod_ingr_matrix1.loc[i]))*100,2)\n tp.loc[i, 'num_ingr'] = str(dot_prod[item][i])+'/'+ str(dot_prod[item][item])\n tp.loc[i, 'pricepervol'] = np.round(df_new[df_new['product_name']==i]['pricepervol'].values[0],2)\n tp.loc[i, 'product_type'] = df_new[df_new['product_name']==i]['product_type'].values[0]\n \n if all_types==True:\n return tp \n else:\n ptype = tp.loc[item, 'product_type']\n return tp.loc[tp['product_type']==ptype]\n\n@st.cache\ndef compare_ingr(i, item):\n '''\n Returns similarity between two products\n '''\n print(f'Similarity of {i} to {item}')\n tp =pd.DataFrame()\n tp.loc[i, 'cos_score']= np.round(sim_df[item][i]*100,2)\n tp.loc[i, 'jac_score'] = np.round(jaccard_binary(np.array(prod_ingr_matrix1.loc[item]), np.array(prod_ingr_matrix1.loc[i]))*100,2)\n #tp.loc[i, 'num_ingr'] = str(dot_prod[item][i])+'/'+ str(dot_prod[item][item])\n #tp.loc[i, 'pricepervol'] = np.round(df_new[df_new['product_name']==i]['pricepervol'].values[0],2)\n #tp.loc[i, 'product_type'] = df_new[df_new['product_name']==i]['product_type'].values[0]\n return tp\n\n@st.cache\ndef jaccard_binary(x,y):\n \"\"\"A function for finding the similarity between two binary vectors\"\"\"\n intersection = np.logical_and(x, y)\n union = np.logical_or(x, y)\n similarity = intersection.sum() / float(union.sum())\n return similarity\n\n# loading the trained model\npickle_in = open('../notebooks/xgb_final.pkl', 'rb') \nmodel = pickle.load(pickle_in)\n\ndef st_shap(plot, height=None):\n shap_html = f\"{shap.getjs()}{plot.html()}\"\n components.html(shap_html, height=height)\n\ndef explain_instance(prod, model, test_set):\n '''\n df1 - getting index \n '''\n idx= df1.loc[df1.product_name==prod].index[0]\n X = test_set.loc[[idx]]\n rand_pred = model.predict(X)\n rand_proba = list(model.predict_proba(X))\n st.markdown('***Model\\'s prediction***')\n st.write(f'{rand_pred[0]} ({np.round(max(rand_proba[0])*100,2)}% probability)')\n st.markdown('***Actual:***')\n st.write(f'{df1.price_category.loc[idx]} (${np.round(df1.pricepervol.loc[idx],2)} per oz)')\n\n\ndef show_shap(prod, model, test_set):\n '''\n \n '''\n idx= df1.loc[df1.product_name==prod].index[0]\n X = test_set.loc[[idx]]\n rand_pred = model.predict(X)\n rand_proba = list(model.predict_proba(X))\n\n #shap.initjs()\n explainer2 = shap.TreeExplainer(model)\n shap_values2 = explainer2.shap_values(test_set.loc[[idx]])\n shap_values = explainer2(X)\n class_names= ['average', 'cheap', 'expensive']\n for which_class in (1,0,2):\n st.write(f'{np.round(rand_proba[0][which_class]*100,2)}% likelihood of being {class_names[which_class]}')\n p= shap.force_plot(explainer2.expected_value[which_class], shap_values2[which_class], test_set.loc[[idx]])\n st_shap(p)\n\n\nproducts_list = list(set((prod_ingr_matrix1.index)))\n\n#Sidebar\nst.sidebar.image(logo, width= 325)\nst.sidebar.markdown('''\n## About\n*A simple user interface to allow you to explore the results of my machine learning model more easily*\n''')\nst.sidebar.markdown('This is still a work in progress but if you have any suggestions or comments, feel free to connect with me on LinkedIn or drop me an email.
Enjoy exploring the model!
', unsafe_allow_html=True)\n\nst.image(long_icon)\nst.markdown('''\n## Skincare Product Analysis\n### **What would you like to do?**\n''')\naction= st.radio('',['Analyse pricing','Find similar products', 'Compare to another product'])\nproduct = st.selectbox(\"Choose your product\", sorted(products_list), key='main')\n\n#must add explanations for each column\n\nif action=='Find similar products':\n num = st.slider(label='Number of products to return', min_value=3, max_value=25, value=10)\n restriction = st.checkbox(label='Show all product types', value=True)\n st.header('Similar products')\n st.table(similar_prod(product, num, restriction))\n\nif action=='Compare to another product':\n prod2 = st.selectbox(\"Compare to\", sorted(products_list), key='secondary')\n st.header('Comparison')\n st.table(compare_ingr(prod2, product))\n\nif action=='Analyse pricing':\n explain_instance(product, model, x_complete)\n my_expander = st.beta_expander(label='How did the model make this prediction?', expanded =True)\n with my_expander:\n '''**SHAP VALUES**'''\n show_shap(product, model, x_complete)\n\n \n expander = st.beta_expander(label='About the classification')\n with expander: \n '''**Classification criteria**'''\n expander.markdown('''\n - *cheap*: under $15 per oz \n - *average*: $15 - $56 per oz \n - *expensive*: over $56 per oz \n ''')\n#df1.product_name==prod\n\nst.image(end_icon)\n","sub_path":"Project/streamlit/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"432706549","text":"from django.shortcuts import get_object_or_404, render\nfrom .models import Listing\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .choices import bedroom_choices,states_choices,price_choices\n# Create your views here.\ndef index(request):\n #listings = Listing.objects.all()\n listings= Listing.objects.order_by('-price').filter(is_published=True)\n paginator= Paginator(listings,6)\n page= request.GET.get('page')\n listing_paginator= paginator.get_page(page)\n context={\n 'listings': listing_paginator\n \n \n }\n \n return render(request,'listings/listings.html',context)\n \n \n'''\nreturn render(request,'listings/listings.html',{\n \n 'name':'filipe'## this part will be substitute by context variable!!!\n })\n\n''' \n\n \ndef listing(request,listing_id):\n listing = get_object_or_404(Listing, pk = listing_id)\n \n context={'listing':listing}\n return render(request,'listings/listing.html',context)\n\ndef search(request):\n query_list= Listing.objects.order_by('-date_published')\n \n #for keywords coming from form;\n if 'keywords' in request.GET:\n keywords= request.GET['keywords']\n if keywords:\n print(keywords)\n query_list=query_list.filter(description__icontains=keywords)\n #for city coming from form;\n if 'city' in request.GET:\n city =request.GET['city']\n if city:\n query_list= query_list.filter(city__iexact=city)### exact(without 'i' in the beginning) if we want case sensitive!!!!\n #for state coming from form;\n if 'state' in request.GET:\n state =request.GET['state']\n if state:\n query_list= query_list.filter(state__iexact=state)\n #for state coming from form;\n if 'bedrooms' in request.GET:\n bedrooms =request.GET['bedrooms']\n if bedrooms:\n query_list= query_list.filter(bedrooms__lte=bedrooms)\n #for price coming from form;\n if 'price' in request.GET:\n price= request.GET['price']\n if price:\n query_list= query_list.filter(price__lte=price)\n context={\n 'bedroom_choices' : bedroom_choices,\n 'state_choices': states_choices,\n 'price_choices': price_choices,\n 'listings':query_list,\n 'values': request.GET ## we are saving all our request values !\n }\n return render(request,'listings/search.html',context)\n ","sub_path":"listings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"225271016","text":"# many rules (your puzzle input) are being enforced about bags and their contents;\r\n# bags must be color-coded and must contain specific quantities of other color-coded bags\r\n# You have a shiny gold bag. If you wanted to carry it in at least one other bag,\r\n# how many different bag colors would be valid for the outermost bag?\r\n# (In other words: how many colors can, eventually, contain at least one shiny gold bag?)\r\n\r\n# grab defaultdict so we can have absent keys as empty lists []\r\nfrom collections import defaultdict\r\n\r\n# input\r\nwith open('7.txt', 'r') as file:\r\n input = file.read()\r\n\r\n# turn the input into a list, one element is one rule\r\ninput_list = list(input.split('\\n'))\r\n\r\n# make an empty defaultdict to contain e.g. 'light olive' : [(2, 'drab blue'), (1, 'plaid purple')]\r\n# futureproofing bc part 2 will probably involve the numbers\r\n# if a key is missing, the list of bags it contains is []\r\nrules = defaultdict(list)\r\n\r\n# need to split up properly\r\nfor rule0 in input_list:\r\n # rule0 = 'light olive bags contain 2 drab blue bags, 1 plaid purple bag.'\r\n rule1 = rule0[:-1].split(' bags contain ')\r\n # ('light olive', '2 drab blue bags, 1 plaid purple bag')\r\n outer_col = rule1[0]\r\n # 'light olive'\r\n rule2 = rule1[1].split(', ')\r\n # ('2 drab blue bags', '1 plaid purple bag')\r\n numcol_list = []\r\n for numcol in rule2:\r\n if numcol == 'no other bags':\r\n break # nothing to add to numcol_list\r\n rule3 = numcol.split(' ')\r\n # ('2', 'drab', 'blue', 'bags')\r\n rule4 = (int(rule3[0]), rule3[1] + ' ' + rule3[2])\r\n # (2, 'drab blue')\r\n numcol_list.append(rule4)\r\n # [(2, 'drab blue')]\r\n # rule3 = [(2, 'drab blue'), (1, 'plaid purple')]\r\n rules[outer_col] = numcol_list\r\n # { ... 'light olive': [(2, 'drab blue'), (1, 'plaid purple')], ...}\r\n\r\n# gets list of all colours of bags in the dict\r\n# ['light chartreuse', 'dotted silver', ...]\r\ncols = list(rules)\r\n# will contain list of colours containing shiny gold\r\nhas_shiny_gold = []\r\n# will contain list of colours not containing shiny gold\r\nno_shiny_gold = []\r\n\r\n# gets colours the next level down\r\n# 'light olive' -> ['drab blue', 'plaid purple']\r\ndef contains_cols(col: str):\r\n numcols = rules[col]\r\n cols = []\r\n for numcol in numcols:\r\n cols.append(numcol[1])\r\n return cols\r\n\r\n# we will gradually remove colours\r\nwhile len(cols) > 0:\r\n outer_col = cols.pop(0) # pop off the first col in the list\r\n cols_inside = contains_cols(outer_col) # get the cols one level down\r\n while len(cols_inside) > 0: # while we still have cols inside\r\n if 'shiny gold' in cols_inside: # if we have shiny gold inside\r\n has_shiny_gold.append(outer_col) # add to output list\r\n break\r\n inner_col = cols_inside.pop(0) # pop first element from list\r\n if inner_col in no_shiny_gold: # if we've already confirmed it has no shiny gold\r\n continue # go to next element in list\r\n elif inner_col in has_shiny_gold: # if we've already confirmed it has a shiny gold\r\n has_shiny_gold.append(outer_col) # add to output list\r\n break # don't need to continue the while\r\n cols_inside = cols_inside + contains_cols(inner_col) # get the cols inside that\r\n else:\r\n # no break statement hit, cols_inside = 0\r\n # => does not contain shiny gold\r\n no_shiny_gold.append(outer_col)\r\n\r\nprint(len(has_shiny_gold))","sub_path":"7a.py","file_name":"7a.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"382484335","text":"\"\"\"\nParses and validates inputs for command line use\n\"\"\"\n\nimport random\nimport argparse\nimport time\nimport keylights\n\n\nkeyboard = {}\nkeyboard[\"ESC\"] = 0\nkeyboard[\"F1\"] = 1\nkeyboard[\"F2\"] = 2\nkeyboard[\"F3\"] = 3\nkeyboard[\"F4\"] =4\nkeyboard[\"F5\"] = 5\nkeyboard[\"F6\"] =6\nkeyboard[\"F7\"] =7\nkeyboard[\"F8\"] =8\nkeyboard[\"F9\"] =9\nkeyboard[\"F0\"] =10\nkeyboard[\"F\"] =11\nkeyboard[\"F2\"] =12\nkeyboard[\"DEL\"] =13\nkeyboard[\"TAB\"] =14\nkeyboard[\"Q\"] =15\nkeyboard[\"W\"] =16\nkeyboard[\"E\"] =17\nkeyboard[\"R\"] =18\nkeyboard[\"T\"] =19\nkeyboard[\"Y\"] =20\nkeyboard[\"U\"] =21\nkeyboard[\"I\"] =22\nkeyboard[\"O\"] =23\nkeyboard[\"P\"] =24\nkeyboard[\"[\"] =25\nkeyboard[\"]\"] =26\nkeyboard[\"BACKSLASH\"] =27\nkeyboard[\"CAPS\"] =28\nkeyboard[\"A\"] =29\nkeyboard[\"S\"] =30\nkeyboard[\"D\"] =31\nkeyboard[\"F\"] =32\nkeyboard[\"G\"] =33\nkeyboard[\"H\"] =34\nkeyboard[\"J\"] =35\nkeyboard[\"K\"] =36\nkeyboard[\"L\"] =37\nkeyboard[\";\"] =38\nkeyboard[\"'\"] =39\nkeyboard[\"ENTER\"] =40\nkeyboard[\"SHIFT\"] =41\nkeyboard[\"Z\"] =42\nkeyboard[\"X\"] =43\nkeyboard[\"C\"] =44\nkeyboard[\"V\"] =45\nkeyboard[\"B\"] =46\nkeyboard[\"N\"] =47\nkeyboard[\"M\"] =48\nkeyboard[\",\"] =49\nkeyboard[\".\"] =50\nkeyboard[\"/\"] =51\nkeyboard[\"SHIFT2\"] =52\nkeyboard[\"CTRL\"] =53\nkeyboard[\"WIN\"] =54\nkeyboard[\"ALT\"] =55\nkeyboard[\"SPACEBAR\"] =56\nkeyboard[\"ALT\"] =57\nkeyboard[\"FN\"] =58\nkeyboard[\"CTX\"] =59\nkeyboard[\"CTRL2\"] =60\nkeyboard[\"INS\"] =61\nkeyboard[\"HM\"] =62\nkeyboard[\"PU\"] =63\nkeyboard[\"DEL\"] =64\nkeyboard[\"END\"] =65\nkeyboard[\"PD\"] =66\nkeyboard[\"UP\"] =67\nkeyboard[\"LEFT\"] =68\nkeyboard[\"DOWN\"] =69\nkeyboard[\"RIGHT\"] =70\n\ndef main():\n \"\"\"\n Parse arguments and start application appropriately\n \"\"\"\n # TODO: Add parameter for a json object mapping key -> color\n # TODO: Add parameter to change only a single key\n parse = argparse.ArgumentParser(\n description='Change light color for switches of the Drevo Calibur keyboard')\n lightctl = keylights.Keylights()\n\n while True:\n lightctl.setkey(keyboard[\"E\"], (255,0,0))\n time.sleep(0.2);\n lightctl.setkey(keyboard[\"R\"], (255,255,0))\n time.sleep(0.2);\n lightctl.setkey(keyboard[\"W\"], (255,0,255))\n time.sleep(0.2);\n lightctl.setkey(keyboard[\"A\"], (25,0,255))\n time.sleep(0.2);\n lightctl.setkey(keyboard[\"N\"], (0,255,0))\n time.sleep(0.2);\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"drevo/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"27379766","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib.widgets import Slider\n\n\ndef plot_raw_data(data,chans=None,bad_coords= []):\n if chans is None:\n chans = range(data.shape[0])\n fig, ax = plt.subplots(figsize=(10,10))\n plt.subplots_adjust(bottom=0.25)\n for ch in chans:\n plt.plot(data[ch])\n plt.axis([0, 100000, -1000, 1000])\n for c in bad_coords:\n ax.axvspan(c[0],c[1],color='red',alpha=.5)\n axcolor = 'lightgoldenrodyellow'\n axpos = plt.axes([0.2, 0.1, 0.65, 0.03], facecolor=axcolor)\n spos = Slider(axpos, 'Pos', 0.1, len(data[0]))\n def update(val): #needed for slider function of plot_raw_data\n pos = spos.val\n ax.axis([pos,pos+50000,-500,500])\n fig.canvas.draw_idle()\n spos.on_changed(update)\n plt.show();\n\n \ndef plot_features(data):\n plts = data.shape[0]//20 +1 #we want 20 per plot\n xsize=10\n ysize=5\n fig=plt.figure()\n for k in range (0,plts):\n ax=fig.add_subplot(xsize,ysize,k+1)\n l = ax.plot(data[k*20:(k+1)*20])\n plt.axis([0, 1000, 0, 10])\n sframe = Slider(fig.add_subplot(50,1,50), 's', 0, len(data[0])-1, valinit=0)\n def update(val):\n frame = np.around(sframe.val)\n #l.set_data(readlist[k][frame,:,:])\n ax.axis([pos,pos+1000,0,10])\n sframe.on_changed(update)\n plt.show()\n\n\ndef plot_pc(pca,data):\n for p in range(pca.n_components):\n plt.plot(pca.transform(data)[:,p])\n plt.xlabel('Time (in w_size)')\n plt.ylabel('PC Value')\n plt.title('First %d principal components' % pca.n_components)\n plt.show()\n\n \n#get elbow curve. This also outputs the optimal n_components for the given desired explained variancce.\ndef __elbow_curve(datapart,expl_var_lim):\n components = range(1, datapart.shape[1] + 1)\n explained_variance = []\n #till where?\n lim=min(100, datapart.shape[1])\n count=0\n for component in tqdm(components[:lim]):\n pca = PCA(n_components=component)\n pca.fit(datapart)\n expl_var=sum(pca.explained_variance_ratio_)\n explained_variance.append(expl_var)\n count+=1\n if(expl_var>(expl_var_lim/100.)):\n optimal_no_comps=count\n break\n if(explained_variance[-1:][0]<(expl_var_lim/100.)):\n print('Could not explain more than %d %% of the variance. n_comps is set to match this. Consider increasing data range or lowering demanded explained variance' % expl_var*100)\n optimal_no_comps=components[-1:]\n sns_plot = sns.regplot(\n x=np.array(components[:count]), y=explained_variance,\n fit_reg=False).get_figure()\n return optimal_no_comps\n\n\n","sub_path":"vis/feature_vis.py","file_name":"feature_vis.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"61624782","text":"import pymysql.cursors\n\ndef sqlGet(path):\n\tif (path == 'getName'):\n\t\treturn getName();\n\treturn \"{}\";\n\ndef getName():\n\tconnection = pymysql.connect(host='192.168.1.110',\n\t\t\t\t\t\t\tuser='Preston',\n\t\t\t\t\t\t\tpasswd='password',\n\t\t\t\t\t\t\tdb='dbTest',\n\t\t\t\t\t\t\tcharset='utf8mb4',\n\t\t\t\t\t\t\tcursorclass=pymysql.cursors.DictCursor)\n\ttry:\n\t\twith connection.cursor() as cursor:\n\t\t\tsql = \"SELECT name FROM Test\"\n\t\t\tcursor.execute(sql, )\n\t\t\tresult = cursor.fetchone()\n\t\t\treturn result\n\tfinally:\n\t\tconnection.close();\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"55430667","text":"from pathlib import Path\nimport pickle\n\nfrom asyncbots.bot import SlackBot, register\nfrom asyncbots.command import MessageCommand\nfrom asyncbots.parsing import symbols\nfrom nltk import word_tokenize\nfrom pyparsing import CaselessLiteral, Optional, Word\n\nfrom lda.topics import Topics, copy_hyperparams\n\nTOPIC_PICKLE = Path('lda/topics.pkl')\nSAVE_PERIOD = 100\n\nclass TopicBot(SlackBot):\n def __init__(self, slack=None):\n self.name = 'Topics'\n self.expr = CaselessLiteral('topics') + Optional(symbols.channel_name.setResultsName('channel'))\n self.doc = 'Print a list of topics optionally restricted to a channel:\\n\\ttopics []'\n\n self._update_count = 0\n\n if TOPIC_PICKLE.exists():\n with TOPIC_PICKLE.open('rb') as f:\n self._global_topics, self._channel_topics = pickle.load(f)\n else:\n raise FileNotFoundError('Topics pickle does not exist')\n\n @register()\n async def command_topics(self, in_channel, user, parsed):\n if 'channel' in parsed and parsed['channel'] not in self._channel_topics:\n return MessageCommand(channel=in_channel, user=user, text='Channel {} not found'.format(parsed['channel']))\n\n topics = self._channel_topics[parsed['channel']] if 'channel' in parsed else self._global_topics\n return [MessageCommand(\n user=user,\n channel=in_channel,\n text='{}. {}'.format(i, ' '.join(t)))\n for i, t in enumerate(topics.top_words())\n ]\n\n @register(unfiltered=True)\n async def topic_update(self, in_channel, user, message):\n if in_channel not in self._channel_topics:\n self._channel_topics[in_channel] = copy_hyperparams(self._global_topics)\n\n tokenized = word_tokenize(message.strip().lower())\n self._global_topics.submit_message(tokenized)\n self._channel_topics[in_channel].submit_message(tokenized)\n\n if self._update_count % SAVE_PERIOD == 0:\n with TOPIC_PICKLE.open('wb') as f:\n pickle.dump((self._global_topics, self._channel_topics), f)\n","sub_path":"topic_bot.py","file_name":"topic_bot.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"536515287","text":"import os, argparse\nimport torch\nfrom torchvision import models\nimport torch.nn as nn\nfrom scipy import signal\nimport logging\nimport torch.optim as optim\nimport numpy as np\nimport random\nfrom sklearn.metrics import roc_auc_score\n\nrandom.seed(1)\nnp.random.seed(1)\ntorch.manual_seed(1)\n\nfrom train_utils import AgeDataHandler, init_visdom\nfrom base_utils import Params, set_logger, parse_soundfile\n\ndef compute_loss(batch, backward = False):\n if backward:\n model.train()\n else:\n model.eval()\n\n observations = []\n targets = torch.zeros(len(batch))\n for i, (soundfile, category) in enumerate(batch):\n Sxx = parse_soundfile(soundfile, timeframe, window_fn, features)\n observations.append(Sxx)\n targets[i] = 2.0*(category < 6) - 1 if category is not None else 0\n\n observations = torch.stack(observations)\n if cuda:\n observations = observations.cuda()\n targets = targets.cuda()\n\n outputs = model(observations)\n ## refer https://github.com/lukasruff/Deep-SVDD-PyTorch\n dist = torch.sum((outputs - _C_) ** 2, dim=1)\n losses = torch.where(targets == 0, dist, ETA * ((dist + eps) ** targets.float()) )\n loss = torch.mean(losses)\n if backward:\n loss.backward()\n return loss.detach().item() / len(batch)\n else:\n return loss.detach().item() / len(batch), dist.cpu().data.numpy().tolist(), (-1*targets).cpu().data.numpy().tolist()\n\ndef eval_model(val_data):\n total_loss, total_obs = 0, 0\n scores, targets = [], []\n for i, batch in enumerate(val_data):\n batch_loss, x,y = compute_loss(batch, backward = False)\n total_loss += batch_loss * len(batch)\n total_obs += len(batch)\n scores += x\n targets += y\n\n auc = -1.0\n if len(set(targets)) == 2:\n auc = roc_auc_score(targets, scores)\n return total_loss/total_obs, auc\n\ndef train(model, train_data, optimizer):\n best_auc, last_update= 0.0 , 0\n epoch, batch_seen = 0, 0\n auc, val_loss, norm = 0, np.finfo(np.float).max, -1.0\n continue_train = True\n while continue_train:\n epoch += 1\n scheduler.step(auc)\n avg_loss, avg_accuracy = 0.0, 0.0\n for i, batch in enumerate(train_data):\n optimizer.zero_grad()\n batch_loss = compute_loss(batch, backward = True)\n optimizer.step()\n\n print(batch_loss)\n avg_loss += batch_loss\n update_metrics(batch_loss, 0, key = 'train')\n\n batch_seen += 1\n if batch_seen % x_batches == 0:\n val_loss, auc = eval_model(val_data)\n update_metrics(val_loss, auc, key = 'val')\n log_metrics()\n logging.info(\"@Validation round:{}, auc:{:.5} val_loss:{:.5}\".format(batch_seen/x_batches, auc, val_loss))\n\n norm = 0\n for param in model.parameters():\n if param.requires_grad:\n norm += param.norm(2)\n plot_norm(torch.sqrt(norm))\n\n # save model\n if auc <= best_auc:\n last_update += 1\n else:\n best_auc = auc\n last_update = 0\n\n torch.save(model.state_dict(), os.path.join(MODELDIR, \"model.torch\"))\n model_state_tmp = dict(config=config, optimizer=optimizer.state_dict(), auc=auc, val_loss=val_loss, finished= not continue_train,\\\n train_acc=avg_accuracy/(batch_seen+1), train_loss= avg_loss/(batch_seen+1), epoch=epoch, batch_seen=batch_seen)\n\n model_state = {}\n if os.path.isfile(os.path.join(MODELDIR, \"model_training.state\")):\n model_state = torch.load(os.path.join(MODELDIR, \"model_training.state\"), map_location='cpu')\n model_state.update(model_state_tmp)\n torch.save(model_state, os.path.join(MODELDIR, \"model_training.state\"))\n\n if last_update > 1.0* params.lastupdate or np.isnan(val_loss) or epoch > epoch_limit:\n continue_train = False\n break\n\n logging.info(\"@epoch:{}, train loss:{:.2}, train accuracy:{:.2}, val loss:{:.2}, \\\n auc:{:.2}, param norm:{:.2}\".format(epoch,avg_loss/(batch_seen+1), avg_accuracy/(batch_seen+1), val_loss, auc, norm))\n\n model_state = torch.load(os.path.join(MODELDIR, \"model_training.state\"), map_location='cpu')\n model_state[\"curr_epoch\"] = epoch\n model_state[\"curr_train_loss\"], model_state[\"curr_train_acc\"], = avg_loss/(batch_seen+1), avg_accuracy/(batch_seen+1)\n model_state[\"last_update\"], model_state[\"finished\"] = last_update, not continue_train\n torch.save(model_state, os.path.join(MODELDIR, \"model_training.state\"))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-train_datadir\", help=\"training directory containing folders of soundfiles grouped in their classes e.g. .../age/\", required=True)\n parser.add_argument(\"-val_datadir\", help=\"validation directory containing folders of soundfiles grouped in their classes e.g. .../age/\", required=True)\n parser.add_argument(\"-cuda\", help=\"to run on cuda\", default = False)\n parser.add_argument(\"-pretrained\", help=\"to reload the preexisting model\", default = False)\n parser.add_argument(\"-modeldir\", help=\"directory to store the model. Should contain params.json\", default = \"\")\n args = parser.parse_args()\n\n cuda = eval(args.cuda) and torch.cuda.is_available() if args.cuda else False\n pretrained = args.pretrained\n MODELDIR = args.modeldir\n torch.save(dict(), os.path.join(MODELDIR, \"model_training.state\"))\n\n json_path = os.path.join(MODELDIR, \"params.json\")\n assert os.path.isfile(json_path), \"No cofiguration found at {}\".format(json_path)\n params = Params(json_path)\n\n set_logger(os.path.join(MODELDIR, \"train.log\"))\n\n def get_weight_vector():\n if params.dict.get(\"weightedloss\", False):\n return torch.Tensor([5,1,1,1,5,5,10])\n return None\n\n timeframe = params.timeframe\n windowfn = params.windowfn\n model_arch = params.modelarch\n lr = params.lr\n batch_size = params.batchsize\n x_batches = params.xbatches\n factor = params.schedulerfactor\n patience = params.schedulerpatience\n weight_decay = params.l2\n epoch_limit = params.epoch\n features=params.dict.get(\"features\", \"fft\")\n\n window_fn = signal.tukey(51, 0.5)\n if windowfn == \"gaussian\":\n window_fn = signal.gaussian(51, std=1)\n\n # load data\n train_data, val_data = AgeDataHandler(args.train_datadir, batch_size).train_val_split()\n logging.info(\"Number of training observations: {}\".format(len(train_data)))\n # import pdb; pdb.set_trace()\n # val_data = AgeDataHandler(args.val_datadir, batch_size)\n logging.info(\"Number of validation observations: {}\".format(len(val_data)))\n\n epoch_size = int(1.0*len(train_data)/batch_size) + 1\n env_name = params.job_name\n config = dict(lr= lr, batch_size=batch_size, cuda=cuda, \\\n epoch_size=epoch_size, train_data=len(train_data), val_data=len(val_data))\n config.update(params.dict)\n\n CLASSES = 2 # 0 normal; 1 abnormal\n FINAL_DIM=256\n if params.modelarch == \"resnet18\":\n model = models.resnet18(pretrained=False)\n model.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3,bias=False)\n model.fc = torch.nn.Linear(512, FINAL_DIM, bias = True)\n elif params.modelarch == \"resnet34\":\n model = models.resnet34(pretrained=False)\n model.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3,bias=False)\n model.fc = torch.nn.Linear(512, FINAL_DIM, bias = True)\n else:\n raise\n\n model.droprate=0.7\n if params.dict.get('optim',\"adam\") == \"adam\":\n optimizer = optim.Adam(model.parameters(), lr = lr, weight_decay=weight_decay)\n patience = 50\n elif params.optim == \"adamams\":\n optimizer = optim.Adam(model.parameters(), lr = lr, weight_decay=weight_decay, amsgrad=True)\n elif params.optim == \"sgd\":\n optimizer = optim.SGD(model.parameters(), lr = lr, momentum=0,weight_decay=weight_decay, nesterov=False)\n patience = 50\n elif params.optim == \"sgdnest\":\n optimizer = optim.SGD(model.parameters(), lr = lr, momentum=0.9,weight_decay=weight_decay, nesterov=True)\n patience = 50\n elif params.optim == \"rmsmom\":\n optimizer = optim.RMSprop(model.parameters(), lr = lr, weight_decay=weight_decay, momentum=0.9)\n elif params.optim == \"rms\":\n optimizer = optim.RMSprop(model.parameters(), lr = lr, weight_decay=weight_decay)\n\n if pretrained:\n assert os.path.isfile(\"{}/model.torch\".format(MODELDIR)), \"model not found\"\n model.load_state_dict(torch.load(\"{}/model.torch\".format(MODELDIR)))\n optimizer_state = torch.load(\"{}/model_training.state\".format(MODELDIR))['optimizer']\n optimizer.load_state_dict(optimizer_state)\n logging.info(\"Loading the pre-existing model at {}/model.torch\".format(MODELDIR))\n else:\n if os.path.exists(MODELDIR):\n logging.info(\"Writing in existing directory: {}\".format(MODELDIR))\n else:\n raise\n\n _C_ = torch.zeros(FINAL_DIM)\n if cuda:\n model = model.cuda()\n _C_ = _C_.cuda()\n\n # compute C\n eps = 1e-3\n ETA = 1.0\n n_samples = 0\n model.eval()\n with torch.no_grad():\n for c,batch in enumerate(train_data):\n observations = []\n for i, (soundfile, category) in enumerate(batch):\n Sxx = parse_soundfile(soundfile, timeframe, window_fn, features)\n observations.append(Sxx)\n\n observations = torch.stack(observations)\n if cuda:\n observations = observations.cuda()\n\n outputs = model(observations)\n n_samples += outputs.shape[0]\n _C_ += torch.sum(outputs, dim = 0)\n\n _C_ /= n_samples\n # If c_i is too close to 0, set to +-eps. Reason: a zero unit can be trivially matched with zero weights.\n _C_[(abs(_C_) < eps) & (_C_ < 0)] = -eps\n _C_[(abs(_C_) < eps) & (_C_ > 0)] = eps\n\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode=\"max\", factor=factor, patience=patience, verbose=True)\n update_metrics, log_metrics, plot_norm = init_visdom(env_name, config)\n\n train(model, train_data, optimizer)\n","sub_path":"train_anom.py","file_name":"train_anom.py","file_ext":"py","file_size_in_byte":10468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"314060003","text":"import numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dropout, Flatten, Dense\nfrom keras import applications\nfrom sklearn.metrics import pairwise_distances\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport matplotlib.pyplot as plt\nimport requests\nimport pandas as pd\nimport pickle\n\ndata = pd.read_pickle('pickels/16k_apperal_data_preprocessed')\n#data.head()\n\n# some of the brand values are empty. \n# Need to replace Null with string \"NULL\"\ndata['brand'].fillna(value=\"Not given\", inplace=True )\n\n# replace spaces with hypen\nbrands = [x.replace(\" \", \"-\") for x in data['brand'].values]\ntypes = [x.replace(\" \", \"-\") for x in data['product_type_name'].values]\ncolors = [x.replace(\" \", \"-\") for x in data['color'].values]\n\nbrand_vectorizer = CountVectorizer()\nbrand_features = brand_vectorizer.fit_transform(brands).tocsr()\n\ntype_vectorizer = CountVectorizer()\ntype_features = type_vectorizer.fit_transform(types).tocsr()\n\ncolor_vectorizer = CountVectorizer()\ncolor_features = color_vectorizer.fit_transform(colors).tocsr()\n\nfrom IPython.display import display, Image, SVG, Math, YouTubeVideo\n\ndef idf_w2v_brand_color_img(doc_id, w1, w2, w3, w4, num_results):\n bottleneck_features_train = np.load('16k_data_cnn_features.npy')\n asins = np.load('16k_data_cnn_feature_asins.npy')\n asins = list(asins)\n\n# load the original 16K dataset\n img_data = pd.read_pickle('pickels/16k_apperal_data_preprocessed')\n df_asins = list(img_data['asin'])\n\n # doc_id = asins.index(df_asins[doc_id])\n \n idf_w2v_dist = pairwise_distances(w2v_title_weight, w2v_title_weight[doc_id].reshape(1,-1))\n brand_dist = pairwise_distances(brand_features, brand_features[doc_id])\n type_dist = pairwise_distances(type_features, type_features[doc_id])\n color_dist = pairwise_distances(color_features, color_features[doc_id])\n img_dist = pairwise_distances(bottleneck_features_train, bottleneck_features_train[doc_id].reshape(1,-1))\n pairwise_dist = (w1 * idf_w2v_dist + w2 * (brand_dist + type_dist) + w3 * color_dist + w4 * img_dist)/float(w1 + w2 + w3 + w4)\n\n # np.argsort will return indices of 9 smallest distances\n indices = np.argsort(pairwise_dist.flatten())[0:num_results]\n #pdists will store the 9 smallest distances\n pdists = np.sort(pairwise_dist.flatten())[0:num_results]\n\n #data frame indices of the 9 smallest distace's\n df_indices = list(data.index[indices])\n \n\n for i in range(0, len(indices)):\n heat_map_w2v_brand(data['title'].loc[df_indices[0]],data['title'].loc[df_indices[i]], data['medium_image_url'].loc[df_indices[i]], indices[0], indices[i],df_indices[0], df_indices[i], 'weighted')\n print('ASIN :',data['asin'].loc[df_indices[i]])\n print('Brand :',data['brand'].loc[df_indices[i]])\n print('euclidean distance from input :', pdists[i])\n print('='*125)\n\nidf_w2v_brand_color_img(12566, 5, 4, 2, 1, 20) \n#Here 12566 is the product and 5, 4, 2, 1 are the weights given and 20 is num results\n# in the give heat map, each cell contains the euclidean distance between words i, j\n","sub_path":"exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"334022225","text":"# Libraries I have not created...\nfrom tkinter import *\nfrom tkinter import ttk\nfrom PIL import ImageTk, Image\nimport numpy as np\nimport pdb\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport matplotlib.pyplot as plt\nimport os\nfrom subprocess import check_output\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nimport datetime as DT\n# Libraries I have created...\nfrom initializations import * #all directories and constants defined here\nfrom read_routines import *\nfrom mutable_data_structs import define_MSC_structure\nfrom GUI_function import *\n\n\ndef close_program():\n root.quit()\n root.destroy()\n \ndef save_curtain_plot():\n if (os.name != 'nt'): # Linux/Unix\n cmd = 'cp '+ source_dir+'current_curtain.png ' + out_dir + \\\n 'curtain_chan_' + chan_sel.get() + '_' + str(DT.datetime.now().time())\n cmd_feedback = check_output(cmd, shell=True)\n print(cmd_feedback)\n print('Curtain should have been saved in '+out_dir)\n else: # Windows\n print('Nothing yet. Working on it...')\n pdb.set_trace()\n\ndef load_and_plot(*args):\n \n # Check user channel input for error\n\n selected_chan = int(chan_sel.get())\n if selected_chan not in range(1,6):\n print('Channel entered is outside selected range.')\n print('Please re-enter a channel number.')\n return None\n \n # Some declarations\n\n MCS_file_list = config_dir + 'MCS_file_list.txt'\n\n # Create file list using system commands.\n # Send different sys commands depending on OS.\n # At end of this block, a list should contain the full-path file names\n # of all MCS data files to loop thru.\n\n if (os.name != 'nt'): # Linux/Unix\n\t cmd = 'touch ' + MCS_file_list\n\t cmd_feedback = check_output(cmd, shell=True)\n\t cmd = 'rm ' + MCS_file_list\n\t cmd_feedback = check_output(cmd, shell=True)\n\t cmd = './make_file_list_unix ' + raw_dir + ' > ' + MCS_file_list\n\t cmd_feedback = check_output(cmd, shell=True)\n else: # Windows\n print('Nothing yet. Working on it...')\n pdb.set_trace()\t\n\n with open(MCS_file_list) as MCS_list_fobj:\n all_MCS_files = MCS_list_fobj.readlines()\n nMCS_files = len(all_MCS_files)\n\n # Read in the MCS (science) data\n\n first_read = 1\n r=0\n for MCS_file in all_MCS_files:\n MCS_file = MCS_file.rstrip()\n MCS_data_1file = read_in_raw_data(MCS_file)\n if first_read:\n first_read = 0\t\n # Put the parameters that won't change during 1 flight into variables\n nc = MCS_data_1file['meta']['nchans'][0]\n nb = MCS_data_1file['meta']['nbins'][0]\n nshots = MCS_data_1file['meta']['nshots'][0]\n vrT = MCS_data_1file['meta']['binwid'][0]\n vrZ = (vrT * c) / 2.0\n # declare data structure to hold all data. estimate tot # recs first\n tot_est_recs = int(rep_rate/nshots)*file_len_secs*nMCS_files\n MCS_struct = define_MSC_structure(nc,nb)\n MCS_data = np.zeros(tot_est_recs, dtype=MCS_struct)\n nr_1file = MCS_data_1file.shape[0]\n MCS_data[r:r+nr_1file] = MCS_data_1file\n r += nr_1file \n #NOTE: You could put conditional break\n # statement in this loop to read-in\n # data from time segment only.\n \n \n MCS_data = MCS_data[0:r]\n print('All MCS data are loaded.')\n\n # Prepare data for a plot\n\n samp_chan = MCS_data['counts'][:,selected_chan-1,:]\n if nhori not in range(1,100):\n print('Set a more reasonable averaging # in initialization file.')\n return None\n elif (nhori > 1):\n samp_chan = average_lidar_data(samp_chan,nhori,0)\n print('Finished averaging channel '+chan_sel.get()+' to '+ \\\n str(nhori) + ' profiles.')\n \n samp_chan = samp_chan.transpose()\n samp_chan = np.flipud(samp_chan) # reverse the order in columns (not rows)\n z = np.flipud(np.arange(0,nb*vrZ,vrZ))\n\n # Plot the data\n\n plt.clf()\n CPlot = make_curtain_plot_update_fig(samp_chan,nb,vrZ,z)\n canvas.show()\n \nroot = Tk()\nroot.title(\"Experiments\")\n\n# Frame to hold all button on RHS\nRHSframe = ttk.Frame(root, borderwidth=2)\nRHSframe.grid(column=0,row=0,stick=(N, W, E, S))\nRHSframe.rowconfigure(0,weight=1)\n\n# Image Canvas\nfig99 = plt.figure(99,figsize=(figW,figL))\ncanvas =FigureCanvasTkAgg(fig99,master=root)\ncanvas.show()\ncanvas.get_tk_widget().grid(column=1,row=0)\n\n# Buttons in RHS frame\nload_b = Button(RHSframe,text='Load & plot',command=load_and_plot)\nload_b.grid(column=0, row=0, sticky=W)\nsavcurt_b = Button(RHSframe,text='Save curtain',command=save_curtain_plot).grid(column=0, row=3, sticky=W)\nclose_b = Button(RHSframe,text='Exit',command=close_program).grid(column=0, row=4, sticky=W)\n\n# Text entry boxes in RHS frame\nchan_sel_l = ttk.Label(RHSframe, text='Selected channel').grid(column=0, row=1, sticky=S)\nchan_sel = StringVar()\nchan_entry = ttk.Entry(RHSframe, width=2, textvariable=chan_sel)\nchan_entry.insert(0,'1') # put in a default value\nchan_entry.grid(column=0, row=2, sticky=N)\n\n\n# The following commands tell the \"RHSframe\" how to change the shape of its\n# columns if the user resizes the window.\nfor child in RHSframe.winfo_children(): child.grid_configure(padx=5,pady=5)\n\n\nroot.mainloop()\n","sub_path":"L1A/GUI_exp.py","file_name":"GUI_exp.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"489772246","text":"\n\nfrom xai.brain.wordbase.adjectives._borderline import _BORDERLINE\n\n#calss header\nclass _BORDERLINES(_BORDERLINE, ):\n\tdef __init__(self,): \n\t\t_BORDERLINE.__init__(self)\n\t\tself.name = \"BORDERLINES\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"borderline\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_borderlines.py","file_name":"_borderlines.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"268880418","text":"import os\nimport sys\nimport unittest\n\nsys.path.insert(1, os.path.abspath(os.path.join(__file__, \"../..\")))\nimport base_test\nfrom selenium.common import exceptions\n\nclass BasicKeyboardInterfaceTest(base_test.WebDriverBaseTest):\n\n def test_ShouldAllowBasicKeyboardInput(self):\n self.driver.get(self.webserver.where_is(\"user_input/res/javascriptPage.html\"))\n\n keyReporter = self.driver.find_element_by_id(\"keyReporter\")\n\n self.driver.find_element_by_id(\"body\").send_keys(\"abc def\")\n\n self.assertEquals(\"abc def\", keyReporter.get_attribute(\"value\"))\n\n## def test_ShouldAllowSendingKeyDownOnly(self):\n## self.driver.get(self.webserver.where_is(\"user_input/res/javascriptPage.html\"))\n##\n## keysEventInput = self.driver.find_element_by_id(\"theworks\")\n##\n## IAction pressShift = actionProvider.KeyDown(keysEventInput, Keys.Shift).Build()\n##\n## keyLoggingElement = self.driver.find_element_by_id(\"result\")\n## logText = keyLoggingElement.text\n##\n## IAction releaseShift = actionProvider.KeyDown(keysEventInput, Keys.Shift).Build()\n##\n## self.assertTrue(logText.EndsWith(\"keydown\"), \"Key down event not isolated. Log text should end with 'keydown', got: \" + logText)\n\n## def test_ShouldAllowSendingKeyUp(self):\n## self.driver.get(self.webserver.where_is(\"user_input/res/javascriptPage.html\"))\n## keysEventInput = self.driver.find_element_by_id(\"theworks\")\n##\n## Actions actionProvider = new Actions(driver)\n## IAction pressShift = actionProvider.KeyDown(keysEventInput, Keys.Shift).Build()\n## pressShift.Perform()\n##\n## keyLoggingElement = self.driver.find_element_by_id(\"result\")\n##\n## eventsText = keyLoggingElement.Text\n## self.assertTrue(keyLoggingElement.Text.EndsWith(\"keydown\"), \"Key down should be isolated for this test to be meaningful. Event text should end with 'keydown', got events: \" + eventsText)\n##\n## IAction releaseShift = actionProvider.KeyUp(keysEventInput, Keys.Shift).Build()\n##\n## releaseShift.Perform()\n##\n## eventsText = keyLoggingElement.Text\n## self.assertTrue(keyLoggingElement.Text.EndsWith(\"keyup\"), \"Key up event not isolated. Event text should end with 'keyup', got: \" + eventsText)\n\n## def test_ShouldAllowSendingKeysWithShiftPressed(self):\n## self.driver.get(self.webserver.where_is(\"user_input/res/javascriptPage.html\"))\n##\n## keysEventInput = self.driver.find_element_by_id(\"theworks\")\n##\n## keysEventInput.click()\n##\n## Actions actionProvider = new Actions(driver)\n## IAction pressShift = actionProvider.KeyDown(keysEventInput, Keys.Shift).Build()\n## pressShift.Perform()\n##\n## IAction sendLowercase = actionProvider.send_keys(keysEventInput, \"ab\").Build()\n## sendLowercase.Perform()\n##\n## IAction releaseShift = actionProvider.KeyUp(keysEventInput, Keys.Shift).Build()\n## releaseShift.Perform()\n##\n## AssertThatFormEventsFiredAreExactly(\"focus keydown keydown keypress keyup keydown keypress keyup keyup\") \n##\n## self.assertEqual(\"AB\", keysEventInput.get_attribute(\"value\"))\n\n def test_ShouldAllowSendingKeysToActiveElement(self):\n self.driver.get(self.webserver.where_is(\"user_input/res/bodyTypingPage.html\"))\n\n self.driver.find_element_by_id(\"body\").send_keys(\"ab\")\n\n self.assertEqual(\"keypress keypress\", self.driver.find_element_by_id(\"body_result\").text.strip())\n self.assertEqual(\"\", self.driver.find_element_by_id(\"result\").text.strip())\n\n def test_ShouldAllowBasicKeyboardInputOnActiveElement(self):\n self.driver.get(self.webserver.where_is(\"user_input/res/javascriptPage.html\"))\n\n keyReporter = self.driver.find_element_by_id(\"keyReporter\")\n\n keyReporter.click()\n\n self.driver.find_element_by_id(\"body\").send_keys(\"abc def\")\n\n self.assertEqual(\"abc def\", keyReporter.get_attribute(\"value\"))\n \nif __name__ == \"__main__\":\n unittest.main()\n\n","sub_path":"webdriver/user_input/basic_keyboard_interface_test.py","file_name":"basic_keyboard_interface_test.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"39192563","text":"\"\"\"\nThis module contains the methods and classes to produce the encryption of messages.\n\"\"\"\n\nimport os\n\nfrom Crypto.Cipher import AES\nfrom secrets import token_bytes\n\nfrom parameters import N, ROOT_DIR\n\n\n# Size in bytes of each block supported by the cipher\nBLOCK_SIZE = AES.block_size\n\n# Size in bytes of the common Broadcast Key\nBROADCAST_KEY_SIZE = N * BLOCK_SIZE\n\n# File the common Broadcast Key is stored in\nBROADCAST_KEY_FILE = \"broadcast_key.pem\"\n\n\ndef _read_broadcast_key():\n \"\"\"Reads the common Broadcast Key from the proper file.\n :raises FileNotFoundError if the file doesn't exist\n :raises ValueError if the the length of the content of the file does not match BROADCAST_KEY_SIZE\n :return broadcast_key: the bytes sequence representing the common Broadcast Key\"\"\"\n with open(os.path.join(ROOT_DIR, BROADCAST_KEY_FILE), \"rb\") as f:\n broadcast_key = f.read()\n\n if not len(broadcast_key) == BROADCAST_KEY_SIZE:\n raise ValueError('Broadcast Key incorrent size')\n\n return broadcast_key\n\n\ndef _pad(msg):\n \"\"\"Pads a message with empty bytes in order to fit it as a proper input for the cipher.\n For example, if the message is 41 bytes long and the block size is 16 bytes, it will be padded with 7 bytes\"\"\"\n if not len(msg) % BLOCK_SIZE == 0:\n return msg + b'\\0' * (BLOCK_SIZE - len(msg) % BLOCK_SIZE)\n return msg\n\n\nclass Encryptor:\n \"\"\"Class containing parameters and methods to produce the encryption of messages\n :param key: the bytes sequence representing the private encryption key\n :param broadcast_key: the bytes sequence representing the common Broadcast Key\"\"\"\n\n __slots__ = ['__key', '__broadcast_key']\n\n def __init__(self, key):\n \"\"\"Class constructor\n :param key: the bytes sequence representing the private encryption key\"\"\"\n self.__key = key\n self.__broadcast_key = _read_broadcast_key()\n\n def encrypt(self, iv=None, msg=None):\n \"\"\"Produces the encryption of a message.\n :param iv: (Optional) the bytes sequence representing the Initialization Vector of the block cipher;\n if not specified, a new IV is created as a random bytes sequence\n :param msg: (Optional) the bytes sequence representing the message to encrypt;\n if not specified, the common Broadcast Key will be encrypted\n (note that the protocol states to always encrypt the Broadcast Key, with different private keys)\n :returns the concatenation of the IV and the ciphertext corresponding to the plaintext\"\"\"\n if msg is None:\n msg = self.__broadcast_key\n msg = _pad(msg)\n\n if iv is None:\n iv = token_bytes(AES.block_size)\n\n cipher = AES.new(self.__key, AES.MODE_CBC, iv)\n ciphertext = cipher.encrypt(msg)\n\n return iv + ciphertext\n\n\nclass Decryptor:\n \"\"\"Class containing parameters and methods to produce the decryption of ciphertexts\n :param key: the bytes sequence representing the private decryption key\n :param broadcast_key: the bytes sequence representing the common Broadcast Key\"\"\"\n\n __slots__ = ['__key', '__broadcast_key']\n\n def __init__(self, key):\n \"\"\"Class constructor\n :param key: the bytes sequence representing the private decryption key\"\"\"\n self.__key = key\n self.__broadcast_key = _read_broadcast_key()\n\n def decrypt(self, ciphertext):\n \"\"\"Produces the decryption of a ciphertext.\n :param ciphertext the bytes sequence representing the ciphertext to decrypt\n :returns the plaintext corresponding to the ciphertext\n :raises ValueError if the plaintext does not correspond to the common Broadcast Key\n (as the protocol states to always encrypt the Broadcast Key, with different private keys\"\"\"\n iv = ciphertext[:AES.block_size]\n cipher = AES.new(self.__key, AES.MODE_CBC, iv)\n plaintext = cipher.decrypt(ciphertext[AES.block_size:])\n\n if not plaintext == self.__broadcast_key:\n raise ValueError('Ciphertext not valid')\n\n return plaintext.rstrip(b'\\0')\n","sub_path":"TestCrypto/cipher.py","file_name":"cipher.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"260797158","text":"from lxml import html, etree\nfrom multiprocessing import Pool\nfrom requests import get as req\nimport time, json, logging\n\nlogging.basicConfig(\n # this logging stuff MIGHT go into a different file\n filename='pytor.log',\n level=logging.DEBUG,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n)\nlogger = logging.getLogger(__name__)\n\ndef eztv (q):\n results = []\n htmlstr = html.fromstring\n url = f'https://eztv.ag/search/{q}'\n tree = htmlstr(req(url, timeout=3).content)\n x = tree.xpath\n add = results.append\n items = list(zip(\n x('//tr[@name=\"hover\"]//a[@class=\"epinfo\"]/@title'),\n x('//tr[@name=\"hover\"]/td[4]/text()'),\n x('//tr[@name=\"hover\"]/td[6]//text()'),\n x('//tr[@name=\"hover\"]/td[3]/a[1]/@href'),\n x('//tr[@name=\"hover\"]/td[1]/a/@title')\n ))\n for item in items:\n seed, link, show = item[2:]\n if 'Other' not in show and seed != '-' and int(seed) > 0 and link[0:6] == 'magnet':\n add([\n item[0][:-(len(item[1]) + 3)],\n item[1],\n seed,\n '-',\n link,\n link[20:60]\n ])\n print('eztv processed successfully...')\n return results\n\ndef lime (q, cat):\n htmlstr = html.fromstring\n url = f'https://www.limetorrents.cc/search/{cat}/{q}/seeds/1/'\n tree = htmlstr(req(url, timeout=3).content)\n x = tree.xpath\n items = list(zip(\n x('//div[@class=\"tt-name\"]//a[2]/text()'),\n x('//td[@class=\"tdnormal\"][2]/text()'),\n x('//table[2]//td[@class=\"tdseed\"]/text()'),\n x('//table[2]//td[@class=\"tdleech\"]/text()'),\n x('//a[@class=\"csprite_dl14\"]/@href')\n ))\n print('lime processed successfully...')\n return [list(item) + [item[4][29:69]] for item in items if int(item[2]) > 0]\n\ndef rarbg (q, cat, token):\n url = 'https://torrentapi.org/pubapi_v2.php'\n payload = {\n 'mode': 'search',\n 'search_string': q,\n 'category': cat,\n 'limit': '100',\n 'sort': 'seeders',\n 'min_seeders': '1',\n 'format': 'json_extended',\n 'token': token\n }\n items = json.loads(req(url, timeout=3, params=payload).text)['torrent_results']\n print('rarbg processed successfully...')\n keys = ['title', 'size', 'seeders', 'leechers', 'download']\n return [[item[key] for key in keys] + [item['download'][20:60]] for item in items]\n\ndef tpb (q, cat):\n results = []\n htmlstr = html.fromstring\n url = f'https://thepiratebay.org/search/{q}/0/7/200/'\n tree = htmlstr(req(url, timeout=3).content)\n x = tree.xpath\n add = results.append\n sep = str.split\n items = list(zip(\n x('//a[@class=\"detLink\"]/text()'),\n x('//font[@class=\"detDesc\"]/text()'),\n x('//td[@align=\"right\"][1]/text()'),\n x('//td[@align=\"right\"][2]/text()'),\n x('//a[contains(@href, \"magnet\")]/@href'),\n x('//td[@class=\"vertTh\"]//a[2]/text()')\n ))\n low = str.lower\n for item in items:\n if cat in low(item[5]) and int(item[2]) > 0:\n add([\n item[0],\n sep(item[1], ', ')[1][5:-2] + 'B',\n item[2],\n item[3],\n item[4],\n item[4][20:60]\n ])\n print('tpb processed successfully...')\n return results\n\ndef zoo (q, cat):\n xmlstr = etree.fromstring\n url = f'https://zooqle.com/search?q={q}+category%3A{cat}&sd=d&fmt=rss&pg='\n pages = [req(url + str(p), timeout=3).content for p in [1, 2, 3]]\n trees = [xmlstr(page)[0] for page in pages]\n items = list(zip(\n [item[0].text for tree in trees for item in tree[8:]],\n [int(item[6].text) for tree in trees for item in tree[8:]],\n [item[9].text for tree in trees for item in tree[8:]],\n [item[10].text for tree in trees for item in tree[8:]],\n [item[8].text for tree in trees for item in tree[8:]],\n [item[7].text for tree in trees for item in tree[8:]]\n ))\n print('zoo processed successfully...')\n return [list(item) for item in items]\n\ndef filtor (tors, q):\n # if ascii(s) !== s: proceed || all(ord(char) < 128 for char in tname)\n flags = ['rus', 'fuck', 'anal', 'xxx']\n sep = str.split\n qs = sep(q, '+')\n low = str.lower\n seen = {}\n for tor in tors:\n tname, tseed, thash = low(tor[0]), tor[2], tor[5]\n try:\n tname.encode('ascii')\n words = sep(tname.replace('.', ' '), ' ')\n if thash not in seen or int(tseed) > int(seen[thash][2]):\n if all(flag not in words for flag in flags) and all(term in tname for term in qs):\n seen[thash] = tor\n except UnicodeEncodeError:\n continue\n print('filtor processed successfully...')\n return seen.values()\n\ndef run_func (f):\n func, args = f\n try:\n if type(args) != tuple:\n return func(args)\n return func(*args)\n except Exception as err:\n logging.debug(err, exc_info=True)\n return []\n\ndef search (q, cat):\n logger.info('beginning search')\n torlist = []\n ext = torlist.extend\n jtkn = req('https://torrentapi.org/pubapi_v2.php?get_token=get_token')\n token = json.loads(jtkn.text)['token']\n\n funcs = [\n (eztv, q),\n (lime, (q, cat)),\n (rarbg, (q, cat, token)),\n (tpb, (q, cat)),\n (zoo, (q, cat))\n ]\n pool = Pool(5)\n tormaps = pool.map(run_func, funcs)\n pool.close()\n pool.join()\n [ext(tormap) for tormap in tormaps]\n print('# of results (pre-filtor) = ' + str(len(torlist)))\n logger.info('search complete, attempting to run filtor...')\n try:\n results = filtor(torlist, q)\n print('# of results (post-filtor) = ' + str(len(results)))\n return results\n except Exception as e:\n logging.exception(e)\n\nt = time.time()\ntorrents = search('the+librarians', 'tv')\nprint(time.time() - t)\n\n# Torrent = [name, size, seed, peer, link, hash]\n#\n# sort by seeders\n# do byte conversions when putting in html\n# from math import floor, pow, log\n# if type(tor[1]) is int:\n# i = int(floor(log(int(b), 1024)))\n# str(round(int(b) / pow(1024, i), 2)) + ' ' + ('KB', 'MB', 'GB')[i]\n# torlock has a good selection, cats, sorting, and 75 per page all 0 seeds\n# leetx no magnets\n# magnetdl has sorting, cats, magnets, 40 per page, but results are iffy correct seeds\n# http://www.magnetdl.com/t/the-librarians/se/desc/","sub_path":"Python/pytor_multiprocessing.py","file_name":"pytor_multiprocessing.py","file_ext":"py","file_size_in_byte":6462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"22492228","text":"import bisect\nimport os\nimport pickle\n\n\npage_size = 512\n\nclass _NodeInTree(object):\n __buckets__ = [\"tree\", \"value\", \"children\"]\n\n def __init__(self, tree, value=None, children=None):\n self.tree = tree\n self.value = value or []\n \n self.children = children or []\n if self.children:\n assert len(self.value) + 1 == len(self.children)\n\n def __repr__(self):\n name = getattr(self, \"children\", 0) and \"Branch\" or \"Leaf\"\n return \"<%s %s>\" % (name, \", \".join(map(str, self.value)))\n\n def lateral(self, parent, parent_ind, dest, dest_ind):\n if parent_ind > dest_ind:\n dest.value.append(parent.value[dest_ind])\n if self.children:\n dest.children.append(self.children.pop(0))\n else:\n dest.value.insert(0, parent.value[parent_ind])\n parent.value[parent_ind] = self.value.pop()\n if self.children:\n dest.children.insert(0, self.children.pop())\n\n def contract(self, predecessor):\n parent = None\n if predecessor:\n parent, parent_ind = predecessor.pop()\n # try to lend to the left neighboring sibling\n if parent_ind:\n left_sib = parent.children[parent_ind - 1]\n if len(left_sib.value) < self.tree.order:\n self.lateral(\n parent, parent_ind, left_sib, parent_ind - 1)\n return\n\n # try the right neighbor\n if parent_ind + 1 < len(parent.children):\n right_sib = parent.children[parent_ind + 1]\n if len(right_sib.value) < self.tree.order:\n self.lateral(\n parent, parent_ind, right_sib, parent_ind + 1)\n return\n\n middle = len(self.value) // 2\n sibling, push = self.split()\n\n if not parent:\n parent, parent_ind = self.tree.BRANCH(\n self.tree, children=[self]), 0\n self.tree._root = parent\n\n # pass the median up to the parent\n parent.value.insert(parent_ind, push)\n parent.children.insert(parent_ind + 1, sibling)\n if len(parent.value) > parent.tree.order:\n parent.contract(predecessor)\n\n def expand(self, predecessor):\n parent, parent_ind = predecessor.pop()\n minm = self.tree.order // 2\n left_sib = right_sib = None\n\n # try to borrow from the right sibling\n if parent_ind + 1 < len(parent.children):\n right_sib = parent.children[parent_ind + 1]\n if len(right_sib.value) > minm:\n right_sib.lateral(parent, parent_ind + 1, self, parent_ind)\n return\n\n # try to borrow from the left sibling\n if parent_ind:\n left_sib = parent.children[parent_ind - 1]\n if len(left_sib.value) > minm:\n left_sib.lateral(parent, parent_ind - 1, self, parent_ind)\n return\n\n # consolidate with a sibling - try left first\n if left_sib:\n left_sib.value.append(parent.value[parent_ind - 1])\n left_sib.value.extend(self.value)\n if self.children:\n left_sib.children.extend(self.children)\n parent.value.pop(parent_ind - 1)\n parent.children.pop(parent_ind)\n else:\n self.value.append(parent.value[parent_ind])\n self.value.extend(right_sib.value)\n if self.children:\n self.children.extend(right_sib.children)\n parent.value.pop(parent_ind)\n parent.children.pop(parent_ind + 1)\n\n if len(parent.value) < minm:\n if predecessor:\n # parent is not the root\n parent.expand(predecessor)\n elif not parent.value:\n # parent is root, and its now empty\n self.tree._root = left_sib or self\n\n def split(self):\n middle = len(self.value) // 2\n median = self.value[middle]\n sibling = type(self)(\n self.tree,\n self.value[middle + 1:],\n self.children[middle + 1:])\n self.value = self.value[:middle]\n self.children = self.children[:middle + 1]\n return sibling, median\n\n def insert(self, ind, element, predecessor):\n self.value.insert(ind, element)\n if len(self.value) > self.tree.order:\n self.contract(predecessor)\n\n def remove(self, ind, predecessor):\n minm = self.tree.order // 2\n\n if self.children:\n # try promoting from the right subtree first,\n # but only if it won't have to resize\n add_ancestors = [(self, ind + 1)]\n descendent = self.children[ind + 1]\n while descendent.children:\n add_ancestors.append((descendent, 0))\n descendent = descendent.children[0]\n if len(descendent.value) > minm:\n predecessor.extend(add_ancestors)\n self.value[ind] = descendent.value[0]\n descendent.remove(0, predecessor)\n return\n\n # fall back to the left child\n add_ancestors = [(self, ind)]\n descendent = self.children[ind]\n while descendent.children:\n add_ancestors.append(\n (descendent, len(descendent.children) - 1))\n descendent = descendent.children[-1]\n predecessor.extend(add_ancestors)\n self.value[ind] = descendent.value[-1]\n descendent.remove(len(descendent.children) - 1, predecessor)\n else:\n self.value.pop(ind)\n if len(self.value) < minm and predecessor:\n self.expand(predecessor)\n\n\nclass Index_Btree(object):\n BRANCH = LEAF = _NodeInTree\n\n def __init__(self, order):\n self.order = order\n self._root = self._bottom = self.LEAF(self)\n\n def _path_to(self, element):\n curr = self._root\n ancestry = []\n\n while getattr(curr, \"children\", None):\n ind = bisect.bisect_left(curr.value, element)\n ancestry.append((curr, ind))\n if ind < len(curr.value) \\\n and curr.value[ind] == element:\n return ancestry\n curr = curr.children[ind]\n\n ind = bisect.bisect_left(curr.value, element)\n ancestry.append((curr, ind))\n present = ind < len(curr.value)\n present = present and curr.value[ind] == element\n\n return ancestry\n\n def _current(self, element, predecessor):\n last, ind = predecessor[-1]\n return ind < len(last.value) and last.value[ind] == element\n\n def insert(self, element, ):\n curr = self._root\n predecessor = self._path_to(element)\n node, ind = predecessor[-1]\n while getattr(node, \"children\", None):\n node = node.children[ind]\n ind = bisect.bisect_left(node.value, element)\n predecessor.append((node, ind))\n node, ind = predecessor.pop()\n node.insert(ind, element, predecessor)\n\n def search(self, element):\n curr = self._root\n if element in dict(self):\n return dict(self)[element]\n return None\n\n def remove(self, element):\n if self.search(element):\n element = [element, (self.search(element))]\n else:\n element = [element, None]\n curr = self._root\n predecessor = self._path_to(element)\n if self._current(element, predecessor):\n node, ind = predecessor.pop()\n node.remove(ind, predecessor)\n else:\n raise ValueError(\"%r not in %s\" % (element, self.__class__.__name__))\n\n \n\n def __contains__(self, element):\n return self._current(element, self._path_to(element))\n\n def __iter__(self):\n def _recurse(node):\n if node.children:\n for child, element in zip(node.children, node.value):\n for child_item in _recurse(child):\n yield child_item\n yield element\n for child_item in _recurse(node.children[-1]):\n yield child_item\n else:\n for element in node.value:\n yield element\n\n for element in _recurse(self._root):\n yield element\n\n \n\n def __repr__(self):\n def recurse(node, accum, depth):\n accum.append((\" \" * depth) + repr(node))\n for node in getattr(node, \"children\", []):\n recurse(node, accum, depth + 1)\n\n accum = []\n recurse(self._root, accum, 0)\n return \"\\n\".join(accum)\n\n\ndef insert_index_entry(table_name, column_name, key, value):\n file_list = os.listdir(data_dir)\n filename = str(table_name) + \"_\" + str(column_name) + \".ndx\"\n\n if filename not in file_list:\n \tdicti = {}\n \tdicti[key] = value\n \tinitialize_tree(table_name, column_name, dicti)\n else:\n tree = read_tree_from_file(table_name, column_name)\n tree.insert([key,value])\n write_tree_to_file(filename, tree)\n return \n\ndef remove_index_entry(table_name, column_name, key):\n file_list = os.listdir(data_dir)\n filename = str(table_name) + \"_\" + str(column_name) + \".ndx\"\n\n if filename not in file_list:\n \treturn False\n else:\n tree = read_tree_from_file(table_name, column_name)\n tree.remove(key)\n write_tree_to_file(filename, tree)\n return True\n\ndef initialize_tree(table_name, column_name, tree_values):\n\tnew_tree = Index_Btree(5)\n\tfor key, value in tree_values:\n\t\tnew_tree.insert([key, value])\n\tfilename = str(table_name) + \"_\" + str(column_name) + \".ndx\"\n\twrite_tree_to_file(filename, new_tree)\n\treturn\n\ndef write_tree_to_file(filename, new_tree):\n with open(filename, \"wb\") as f:\n pickle.dump(new_tree, f)\n return\n\n\ndef read_tree_from_file(table_name, column_name):\n filename = str(table_name) + \"_\" + str(column_name) + \".ndx\"\n with open(filename, \"rb\") as f:\n tree = pickle.load(f)\n return tree\n\ndef search(table_name, column_name, key):\n tree = read_tree_from_file(table_name, column_name)\n value = tree.search(key)\n return value\n\n# b = Index_Btree(5)\n# b.insert(['2', '5'])\n# b.insert(['7', '5'])\n# b.insert(['9', '5'])\n# b.insert(['3', '4'])\n# b.insert(['5', '4'])\n# b.insert(['1', '4'])\n# b.insert(['18', '4'])\n# b.insert(['11', '5'])\n# b.insert(['12', '5'])\n# b.insert(['13', '5'])\n# b.insert(['14', '4'])\n# b.insert(['15', '5'])\n# b.insert(['16', '5'])\n# b.insert(['17', '5'])\n# b.insert(['19', '4'])\n# print(b)\n# b.remove('17')\n# print(b)\n# print('\\n\\n')\n# value = b.search('11')\n# print(value)\n# print('\\n\\n\\n')\n# initialize_tree('test', 'test', b)\n# tree = read_tree_from_file('test', 'test')\n# tree.insert(['22','22'])\n# print(tree)\n","sub_path":"Index.py","file_name":"Index.py","file_ext":"py","file_size_in_byte":10895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"317289595","text":"#!/usr/bin/env python\nfrom __future__ import division, unicode_literals\n\nimport atexit\nimport base64\nimport httplib\nimport inspect\nimport json\nimport os\nimport re\nimport select\nimport signal\nimport socket\nimport ssl\nimport struct\nimport sys\nimport tempfile\nimport threading\nimport time\nimport zlib\n\nALL_MODULES = []\nALL_MODULES_CODE = '${ALL_CODE_LIST}'\nSCRIPT_NAME = b'${SCRIPT_NAME}'\nEXERCISE_DURATION = \"${EXERCISE_DURATION}\"\nMODULE_DELAYS = '${MODULE_DELAYS}'\n\n\nclass ModuleBase(object):\n VERSION = '0.1.0'\n\n def __init__(self, identification_banner):\n self._started = False\n self._finished = False\n self._banner = identification_banner\n\n @property\n def tags(self):\n return []\n\n @property\n def module_name(self):\n return self.__class__.__name__\n\n @property\n def needs_root(self):\n return False\n\n @property\n def finished(self):\n return self._finished\n\n @property\n def started(self):\n return self._started\n\n @property\n def relative_delay(self):\n # On a scale of 1 (least) to 100 (most) likely to get caught\n raise NotImplementedError('Specify an integer 0 <= relative_delay <= 100')\n\n @property\n def absolute_duration(self):\n # Number of seconds the module should wait\n # NOTE: This only affects computation of minimum test duration! You're responsible for sleeping!\n raise NotImplementedError('Specify an duration that the module expects to run')\n\n def util_childproc(self, fname=None, func=None, args=()):\n (r, w) = os.pipe()\n if os.fork() == 0:\n pid = os.fork()\n if pid == 0:\n if fname is not None:\n os.execv(fname, args)\n elif func is not None:\n func(*args)\n else:\n os.write(w, str(pid))\n sys.exit(0)\n os.wait()\n pid = int(os.read(r, 8))\n os.close(r)\n os.close(w)\n self.hec_logger('Created a new process', severity='info', process_id=pid)\n return pid\n\n def util_netconnect(self, host, timeout=60):\n def proxy(_sock, _host, _timeout):\n s = socket.socket()\n s.settimeout(_timeout)\n try:\n s.connect(_host)\n while True:\n r, _, _ = select.select([_sock, s], [], [], _timeout)\n if not r:\n raise Exception # reached timeout\n if s in r:\n if _sock.send(s.recv(1024)) <= 0:\n raise Exception # a socket closed\n if _sock in r:\n if s.send(_sock.recv(1024)) <= 0:\n raise Exception # a socket closed\n except:\n s.close()\n _sock.close()\n sys.exit()\n self.hec_logger('Creating outbound connection', severity='info', host=host)\n parent_sock, child_sock = socket.socketpair(socket.AF_UNIX)\n self.util_childproc(func=proxy, args=(child_sock, host, timeout))\n return parent_sock\n\n def util_orphanwait(self, pid, timeout=0):\n start = time.time()\n while True:\n if (time.time() - start > timeout) and timeout != 0:\n try:\n self.hec_logger('Timeout reached, killing process', severity='info', process_id=pid)\n os.kill(pid, signal.SIGINT)\n except Exception as e:\n self.hec_logger('Error killing process', process_id=pid, error=str(e))\n break\n try:\n os.kill(pid, 0)\n except OSError:\n self.hec_logger('Process no longer exists, exiting waitloop', severity='debug', pid=pid)\n break\n time.sleep(1)\n return\n\n def hec_logger(self, message, action='', severity='info', **kwargs):\n event = {\n 'project': '${PROJECT_NAME}',\n 'severity': severity,\n 'action': action,\n 'message': message,\n 'local_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n }\n event.update(kwargs)\n data = {\n 'source': self.module_name,\n 'host': socket.getfqdn(),\n 'sourcetype': 'smokeyjab:' + self.module_name,\n 'event': json.dumps(event)\n }\n headers = {'Authorization': 'Splunk ${SPLUNK_TOKEN}', 'Content-Type': 'application/json'}\n try:\n https = httplib.HTTPSConnection('${SPLUNK_HOST}', context=ssl._create_unverified_context())\n except:\n # \"context\" key must not be recognized (should be v2.7.9 but that doesn't seem to be strictly true)\n try:\n https = httplib.HTTPSConnection('${SPLUNK_HOST}')\n except:\n return\n https.request('POST', '/services/collector', body=json.dumps(data), headers=headers)\n\n def finish(self):\n self.hec_logger('', action='finish')\n self._finished = True\n\n def start(self):\n self.hec_logger('', action='start')\n self._started = True\n\n def run(self):\n # Your module functionality here\n raise NotImplementedError('Module functionality undefined')\n\nclass Utils(object):\n @staticmethod\n def routes():\n \"\"\" returns (iface, net address, subnet, gateway) tuple \"\"\"\n def lehex2ip(x):\n return socket.inet_ntoa(x.decode('hex')[::-1])\n with open('/proc/net/route') as f:\n for i, line in enumerate(f):\n if i == 0:\n continue\n line = line.split()\n yield (line[0], lehex2ip(line[1]), lehex2ip(line[7]), lehex2ip(line[2]))\n\n @staticmethod\n def subnet2list(ip, subnet):\n ipi, = struct.unpack(b'!I', socket.inet_aton(ip))\n maski, = struct.unpack(b'!I', socket.inet_aton(subnet))\n for i in range((ipi & maski) + 1, ipi | (maski ^ 0xffffffff)):\n yield socket.inet_ntoa(struct.pack(b'!I', i))\n\n @staticmethod\n def cidr2list(ip, cidr):\n ipi, = struct.unpack(b'!I', socket.inet_aton(ip))\n maski = (0xffffffff << (32-cidr)) & 0xffffffff\n for i in range((ipi & maski) + 1, ipi | (maski ^ 0xffffffff)):\n yield socket.inet_ntoa(struct.pack(b'!I', i))\n\n @staticmethod\n def iface2ip(iface):\n import socket, struct, fcntl\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack(b'256s', iface[:15])\n )[20:24])\n\n\ndef hide():\n with open('/proc/self/cmdline', 'rb') as f:\n cmdline = f.read()\n with open('/proc/self/maps') as f:\n maps = f.read()\n stack_start, stack_end = re.search(b'([0-9a-f]+)-([0-9a-f]+).*\\[stack\\]', maps).groups()\n with open('/proc/self/mem', 'rb+') as mem:\n mem.seek(int(stack_start, 16))\n stack = mem.read(int(stack_end, 16) - int(stack_start, 16))\n cmd_index = stack.find(cmdline)\n arg1_index = stack.find(b'\\x00', cmd_index) + 1\n newargs = SCRIPT_NAME + b'\\x00' * (len(cmdline) - len(SCRIPT_NAME))\n mem.seek(int(stack_start, 16) + arg1_index)\n mem.write(newargs)\n os.unlink(__file__)\n return\n\n\ndef load_modules(modules_string):\n exec (zlib.decompress(base64.b64decode(modules_string)), globals(), locals())\n is_root = (os.getuid() == 0) or (os.geteuid() == 0)\n for name, item in locals().items():\n if inspect.isclass(item) and issubclass(item, ModuleBase) and getattr(item, 'VERSION', -1) >= 0:\n plugin = item('${REDTEAM_TAG}')\n if plugin.needs_root and not is_root:\n plugin.hec_logger('Module requires root and we are not root: {0}'.format(plugin.module_name),\n severity='warning')\n continue\n ALL_MODULES.append(plugin)\n\n\ndef get_all_status():\n statuses = []\n for module in ALL_MODULES:\n statuses.append(module.finished)\n return statuses\n\n\ndef time_breakdown(_s):\n _s, s = divmod(int(_s), 60)\n _s, m = divmod(_s, 60)\n _s, h = divmod(_s, 24)\n return (_s, h, m, s)\n\n\ndef __start__():\n hide()\n load_modules(ALL_MODULES_CODE)\n main = ModuleBase('core')\n main.hec_logger('Starting framework', action='start', severity='info', num_modules=len(ALL_MODULES),\n pid=os.getpid())\n atexit.register(main.hec_logger, 'Framework is exiting', action='exit', severity='info', pid=os.getpid())\n for module in ALL_MODULES:\n wait_time = int(json.loads(MODULE_DELAYS).get(module.module_name, module.relative_delay/100.0*int(EXERCISE_DURATION)))\n threading.Timer(wait_time, module.run).start()\n main.hec_logger('Spawned a module thread'.format(module.module_name), severity='debug', ioc=module.module_name,\n delay='{0:>02}:{1:>02}:{2:>02}:{3:>02}'.format(*time_breakdown(wait_time)))\n while not all(get_all_status()):\n # reap/report zombies created by lazy coding... ;-)\n try:\n pid, ret, res = os.wait3(os.WNOHANG)\n if pid != 0:\n main.hec_logger('Cleaned up a zombie process', severity='warning', pid=pid)\n except OSError:\n pass\n # Sleep before polling to keep CPU usage down\n time.sleep(1)\n main.hec_logger('Terminating framework normally', action='finish', severity='info', pid=os.getpid())\n\n\nif __name__ == '__main__':\n __start__()\n","sub_path":"framework/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"257373866","text":"from time import strftime\nimport time\n\n# Read parameter file\n\n# File name and time\nexperimentName = raw_input('Enter file name: ')\nfileDate = strftime('%d-%m-%y')\nstart = time.time()\nstarttime = str(time.asctime(time.localtime(start)))\nfileName = ('/home/pi/ExperimentData/' + fileName + '--' + fileDate + '.csv')\n# Put file headers\nf = open(fileName , 'a')\nf.write('Experiment Start Time = ' + starttime + '\\n' )\nf.write('Experiment time' + ',' + 'Temp' + ',' + 'Ice Thickness' + ',' + 'Light Level' + ',' + 'Windspeed' + ',' + 'Freezer ON/OFF' + ',' + 'Lights ON/OFF' + ',' + 'Fans ON/OFF' + '\\n')\nf.close\n\n# Experiment loop\nfor x in range (0, 1):\n\t# Sensor inputs\n\t\n\t# Process\n\t\n\t# Set output\n\t\n\t# Save readings\n\telapsedTime = str(datetime.timedelta(seconds = int(\"%.0f\" % (time.time() - start))))\n\tf = open(fileName , 'a')\n\tf.write(elapsedTime + ',' + temp + ',' + iceThickness + ',' + lightlevel + ',' + windspeed + ',' + freezerPow + ',' + lightPow + ',' + fanPow + ',' + '\\n')\n\tf.close","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"411937767","text":"#!/usr/bin/env python\n\ndef is_prime(num, list):\n for item in list:\n if (num % item == 0):\n return False\n return True\n\nlist = []\ncurr = 1\nwhile(len(list) < 10001):\n curr = curr + 1\n if is_prime(curr, list):\n list.append(curr)\n\nprint (list[10000])\n","sub_path":"07/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"589415604","text":"balance = 0\n\n\ndef setBalance(amt):\n global balance\n balance = amt\n\n\ndef printBalance(): # Displays current balance as a money value with a heading\n print(balance)\ndef printLedgerLine(date, details, amount): # with items (and the balance) spaced and formatted\n print(\"{0:<15s}{1:<15s}{2:<15f}\".format(date,details,amount))\n\ndef deposit (date, details, amount): # Alter the balance and print ledger line\n global balance\n balance+=amount\n printLedgerLine(date, details, amount)\n\ndef withdraw(date, details, amount): # Alter the balance and print ledger line\n global balance\n balance -= amount\n printLedgerLine(date, details, amount)\n\nsetBalance(500)\nprintBalance()\nwithdraw(\"17-12-2012\", \"BP - petrol\", 72.50)\nwithdraw(\"19-12-2012\", \"Countdown\", 55.50)\nwithdraw(\"20-12-2012\", \"munchies\", 1.99)\nwithdraw(\"22-12-2012\", \"Vodafone\", 20)\ndeposit (\"23-12-2012\", \"Income\", 225)\nwithdraw(\"24-12-2012\", \"Presents\", 99.02)\nprintBalance()","sub_path":"pycharm/159171/workshop 9/banker.py","file_name":"banker.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"238813183","text":"from flask import Flask, request, g, jsonify, json\nfrom flask.ext.cors import CORS\nfrom flask_mail import Mail, Message\nfrom elasticsearch import Elasticsearch\nfrom datetime import datetime, timezone\n\nfrom error import APIError\n\napp = Flask(__name__)\n\n# TODO: test the behaviour over POST (with no doc_id) -- should just work\n# TODO: do server-side validation (JSON schema?)\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-put-mapping.html\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-percolate.html\n@app.route(\"/alerts/\", methods=[\"POST\", \"PUT\"])\n@app.route(\"/alerts//\", methods=[\"PUT\"])\ndef index_alert(doc_id=None):\n # grab the doc body if it exists\n body = request.get_json()\n\n # check required xavier fields (elastic fields will be checked downstream)\n # TODO: test when not sending a body, and when sending a body with a non-JSON content-type\n if body is None:\n raise APIError(\"Missing payload body\", status_code=400)\n\n if body[\"query\"] is None:\n raise APIError(\"Missing alert query\", status_code=400)\n if body[\"enabled\"] is None:\n raise APIError(\"Missing alert enabled flag\", status_code=400)\n if body[\"title\"] is None:\n raise APIError(\"Missing alert title\", status_code=400)\n\n alert_body = {\n \"query\": body[\"query\"],\n \"xavierAlertObjectMeta\": {\n \"title\": body[\"title\"],\n \"description\": body[\"description\"],\n \"enabled\": True,\n \"output\": body[\"output\"]\n }\n }\n\n try:\n index_res = _index(index=app.config[\"XAVIER_INDEX\"], doc_id=doc_id, doc_type=\".percolator\", body=alert_body, **g.params)\n except:\n # pass through any exceptions\n raise\n\n if index_res[\"created\"] == True:\n response_status = 201\n elif index_res[\"created\"] == False and index_res[\"_version\"] > 1:\n response_status = 200\n\n return jsonify(index_res), response_status\n\n# TODO: test the behaviour over POST (with no doc_id) -- should just work\n# this function allows you to create generic docs in elastic, with an option to percolate\n# as the doc is being created (ie. in real time). this is a convenience/helper function\n# so you can do a 2-in-1, create + percolate, instead of using the elastic\n# HTTP REST API to create and then percolate\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-put-mapping.html\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-percolate.html\n@app.route(\"/docs/\", methods=[\"POST\", \"PUT\"])\n@app.route(\"/docs////\", methods=[\"PUT\"])\ndef index_doc(index=None, doc_id=None, doc_type=None):\n response = None\n\n # grab the doc body if it exists\n body = request.get_json()\n\n # pop the percolate flag if it exists\n percolate = g.params.pop(\"percolate\", False)\n\n # pop the trigger flag if it exists\n trigger = g.params.pop(\"trigger\", False)\n\n try:\n index_res = _index(index=index, doc_id=doc_id, doc_type=doc_type, body=body, **g.params)\n except:\n # pass through any exceptions\n raise\n\n if index_res[\"created\"] == True:\n response_status = 201\n elif index_res[\"created\"] == False and index_res[\"_version\"] > 1:\n response_status = 200\n\n if percolate:\n percolate_res = _percolate(index=index, doc_id=doc_id, doc_type=doc_type, body=body, trigger=trigger, **g.params)\n response[\"percolate\"] = percolate_res\n response[\"index\"] = index_res\n else:\n response = index_res\n\n return jsonify(response), response_status\n\ndef _index(index, doc_id, doc_type, body, **params):\n # check required fields\n if index is None:\n raise APIError(\"Missing param 'index'\", status_code=400)\n if doc_id is None:\n raise APIError(\"Missing param 'doc_id'\", status_code=400)\n if doc_type is None:\n raise APIError(\"Missing param 'doc_type'\", status_code=400)\n if body is None:\n raise APIError(\"Missing payload body\", status_code=400)\n\n log_details = {}\n log_details[\"action\"] = \"indexing\"\n log_details[\"phase\"] = \"pre\"\n log_details[\"index\"] = index\n log_details[\"doc_id\"] = doc_id\n log_details[\"doc_type\"] = doc_type\n log_details[\"body\"] = body\n _log(log_details, level=\"info\")\n\n try:\n es_index_res = g.es_conn.index(index=index, id=doc_id, doc_type=doc_type, body=body, **params)\n except Exception as error:\n _handle_es_error(error)\n\n log_details = {}\n log_details[\"action\"] = \"indexing\"\n log_details[\"phase\"] = \"post\"\n log_details[\"es_res\"] = es_index_res\n _log(log_details, level=\"debug\")\n\n return es_index_res\n\n@app.route(\"/alerts/\", methods=[\"GET\"])\n@app.route(\"/alerts//\", methods=[\"GET\"])\ndef read_alert(doc_id=None):\n # grab the doc body if it exists\n body = request.get_json()\n\n # pop the count flag if it exists\n count = g.params.pop(\"count\", False)\n\n if count:\n # count all the percolator docs within the xavier index\n try:\n count = _count(index=app.config[\"XAVIER_INDEX\"], doc_type=\".percolator\", body=body, **g.params)\n except:\n # pass through any exceptions\n raise\n\n return jsonify(count)\n\n else:\n # search for all percolator docs within the associated index that match the query/search body\n try:\n matches = _search(index=app.config[\"XAVIER_INDEX\"], doc_id=doc_id, doc_type=\".percolator\", body=body, **g.params)\n except:\n # pass through any exceptions\n raise\n\n return jsonify(matches)\n\n@app.route(\"/docs/\", methods=[\"GET\"])\n@app.route(\"/docs///\", methods=[\"GET\"])\ndef read_doc(index=None, doc_id=None):\n # grab the doc body if it exists\n body = request.get_json()\n\n # search for all percolator docs within the associated index that match the query/search body\n try:\n matches = _search(index=index, doc_id=doc_id, body=body, **g.params)\n except:\n # pass through any exceptions\n raise\n\n return jsonify(matches)\n\n# a wrapper around search for general queries\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search.html\n@app.route(\"/search/\", methods=[\"GET\"])\n@app.route(\"/search//\", methods=[\"GET\"])\n@app.route(\"/search///\", methods=[\"GET\"])\n@app.route(\"/search////\", methods=[\"GET\"])\ndef search(index=\"_all\", doc_id=None, doc_type=None):\n # grab the doc body if it exists\n body = request.get_json()\n\n # search for all docs within the associated index that match the query/search body\n try:\n matches = _search(index=index, doc_id=doc_id, doc_type=doc_type, body=body, **g.params)\n except Exception:\n # pass through any exceptions\n raise\n\n return jsonify(matches)\n\ndef _search(index, doc_id, doc_type, body, **params):\n # check required fields\n if index is None:\n raise APIError(\"Missing param 'index'\", status_code=400)\n\n log_details = {}\n log_details[\"action\"] = \"searching\"\n log_details[\"phase\"] = \"pre\"\n log_details[\"index\"] = index\n log_details[\"doc_id\"] = doc_id\n log_details[\"doc_type\"] = doc_type\n log_details[\"body\"] = body\n _log(log_details, level=\"info\")\n\n # search by doc_id\n if doc_id is not None:\n try:\n es_res = g.es_conn.get(index=index, id=doc_id, **params)\n except Exception as error:\n _handle_es_error(error)\n\n # search by potential body, potential q, or return all docs\n elif doc_id is None:\n # grab the doc body if it exists\n if body is not None:\n params[\"body\"] = body\n\n try:\n es_res = g.es_conn.search(index=index, doc_type=doc_type, **params)\n except Exception as error:\n _handle_es_error(error)\n\n log_details = {}\n log_details[\"action\"] = \"searching\"\n log_details[\"phase\"] = \"post\"\n # log_details[\"es_res\"] = es_res\n _log(log_details, level=\"debug\")\n\n return es_res\n\ndef _count(index, doc_type, body, **params):\n # check required fields\n if index is None:\n raise APIError(\"Missing param 'index'\", status_code=400)\n\n log_details = {}\n log_details[\"action\"] = \"counting\"\n log_details[\"phase\"] = \"pre\"\n log_details[\"index\"] = index\n log_details[\"doc_type\"] = doc_type\n _log(log_details, level=\"info\")\n\n try:\n es_count_res = g.es_conn.count(index=index, doc_type=doc_type, source=body, **params)\n except Exception as error:\n _handle_es_error(error)\n\n log_details = {}\n log_details[\"action\"] = \"counting\"\n log_details[\"phase\"] = \"post\"\n log_details[\"es_res\"] = es_count_res\n _log(log_details, level=\"debug\")\n\n return es_count_res\n\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete.html\n@app.route(\"/alerts/\", methods=[\"DELETE\"])\n@app.route(\"/alerts//\", methods=[\"DELETE\"])\ndef delete_alert(doc_id=None):\n try:\n delete_res = _delete(index=app.config[\"XAVIER_INDEX\"], doc_id=doc_id, doc_type=\".percolator\", **g.params)\n except:\n # pass through any exceptions\n raise\n\n return jsonify(delete_res)\n\n# this deletes a specific doc by its id. supporting bulk deletes or delete by query is risky.\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete.html\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete-by-query.html\n@app.route(\"/docs/\", methods=[\"DELETE\"])\n@app.route(\"/docs////\", methods=[\"DELETE\"])\ndef delete_doc(index=None, doc_id=None, doc_type=None):\n try:\n delete_res = _delete(index=index, doc_id=doc_id, doc_type=doc_type, **g.params)\n except:\n # pass through any exceptions\n raise\n\n return jsonify(delete_res)\n\ndef _delete(index, doc_id, doc_type, **params):\n # check required fields\n if index is None:\n raise APIError(\"Missing param 'index'\", status_code=400)\n if doc_id is None:\n raise APIError(\"Missing param 'doc_id'\", status_code=400)\n if doc_type is None:\n raise APIError(\"Missing param 'doc_type'\", status_code=400)\n\n log_details = {}\n log_details[\"action\"] = \"deleting\"\n log_details[\"phase\"] = \"pre\"\n log_details[\"index\"] = index\n log_details[\"doc_id\"] = doc_id\n log_details[\"doc_type\"] = doc_type\n _log(log_details, level=\"info\")\n\n try:\n es_delete_res = g.es_conn.delete(index=index, doc_type=doc_type, id=doc_id, **params)\n except Exception as error:\n _handle_es_error(error)\n\n log_details = {}\n log_details[\"action\"] = \"deleting\"\n log_details[\"phase\"] = \"post\"\n log_details[\"es_res\"] = es_delete_res\n _log(log_details, level=\"debug\")\n\n return es_delete_res\n\n# send docs to percolate and get back the queries that match the doc\n# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-percolate.html\n@app.route(\"/percolate/\", methods=[\"GET\", \"POST\"])\n# this route is for percolating by doc in the body\n@app.route(\"/percolate///\", methods=[\"POST\"])\n# this route is for percolating by doc id\n@app.route(\"/percolate////\", methods=[\"GET\"])\n# in both cases, we need to provide the index and the doc type\ndef percolate(index=None, doc_id=None, doc_type=None):\n # grab the doc body if it exists\n body = request.get_json()\n\n # pop the trigger flag if it exists\n trigger = g.params.pop(\"trigger\", False)\n\n # pop the percolate_index if it exists\n # by default, xavier will assume that clients are percolating against\n # the xavier index. clients can override this behaviour by providing\n # their own percolate_index param. the default elastic behaviour is\n # to percolate against the supplied document's index.\n percolate_index = g.params.pop(\"percolate_index\", app.config[\"XAVIER_INDEX\"])\n\n try:\n matches = _percolate(index=index, doc_id=doc_id, doc_type=doc_type, body=body, percolate_index=percolate_index, trigger=trigger, **g.params)\n except:\n # pass through any exceptions\n raise\n\n return jsonify(matches)\n\ndef _percolate(index, doc_id, doc_type, body, percolate_index=None, trigger=False, **params):\n # check required fields\n if index is None:\n raise APIError(\"Missing param 'index'\", status_code=400)\n # one of doc_id or body should exist, but not both\n if doc_id is None and body is None:\n raise APIError(\"Missing param 'doc_id' or payload body\", status_code=400)\n elif doc_id is not None and body is not None:\n raise APIError(\"Found param 'doc_id' and payload body (only one must exist)\", status_code=400)\n\n # TODO: try to comment these out and see what happens if you just provide None to the API\n # if percolate_index is None:\n # percolate_index = index\n\n log_details = {}\n log_details[\"action\"] = \"percolating\"\n log_details[\"phase\"] = \"pre\"\n log_details[\"index\"] = index\n log_details[\"doc_id\"] = doc_id\n log_details[\"doc_type\"] = doc_type\n log_details[\"body\"] = body\n log_details[\"percolate_index\"] = percolate_index\n log_details[\"trigger\"] = trigger\n _log(log_details, level=\"info\")\n\n # percolate by doc_id\n if doc_id is not None and body is None:\n try:\n es_percolate_res = g.es_conn.percolate(index=index, id=doc_id, doc_type=doc_type, percolate_index=percolate_index, **params)\n except Exception as error:\n _handle_es_error(error)\n\n # percolate by doc_type and body\n elif doc_id is None and body is not None:\n doc_body = {\"doc\": body}\n try:\n es_percolate_res = g.es_conn.percolate(index=index, body=doc_body, doc_type=doc_type, **params)\n except Exception as error:\n _handle_es_error(error)\n\n log_details = {}\n log_details[\"action\"] = \"percolating\"\n log_details[\"phase\"] = \"post\"\n log_details[\"es_res\"] = es_percolate_res\n _log(log_details, level=\"debug\")\n\n if trigger:\n _trigger(matches=es_percolate_res[\"matches\"], doc_id=doc_id, body=body)\n\n return es_percolate_res\n\ndef _trigger(matches, doc_id, body):\n # fetch the percolator doc for each match\n for match in matches:\n # search for all percolator docs within the associated index that match the query/search body\n try:\n percolator_doc = _search(index=match[\"_index\"], doc_id=match[\"_id\"], doc_type=\".percolator\", body=body)\n except:\n # pass through any exceptions\n raise\n\n query = percolator_doc[\"_source\"][\"query\"]\n meta = percolator_doc[\"_source\"][\"xavierAlertObjectMeta\"]\n\n if meta[\"enabled\"]:\n log_details = {}\n log_details[\"action\"] = \"triggering\"\n log_details[\"percolator_id\"] = percolator_doc[\"_id\"]\n log_details[\"enabled\"] = meta[\"enabled\"]\n log_details[\"query\"] = query\n _log(log_details)\n\n # take action on the percolator doc outputs\n # to begin with, we are only doing emails (there will only be one)\n email_output = meta[\"output\"][0].get(\"email\", None)\n if email_output is not None:\n _email(email=email_output, percolator_id=percolator_doc[\"_id\"], query=query, meta=meta, doc_id=doc_id, body=body)\n\ndef _email(email, percolator_id, query, meta, doc_id, body):\n log_details = {}\n log_details[\"action\"] = \"emailing\"\n _log(log_details)\n\n msg = Message()\n msg.subject = _expand(email[\"subject\"], percolator_id=percolator_id, query=query, meta=meta, doc_id=doc_id, body=body)\n msg.recipients = email[\"to\"]\n msg.sender = email.get(\"from\", app.config[\"MAIL_DEFAULT_SENDER\"])\n msg.body = _expand(email[\"body\"], percolator_id=percolator_id, query=query, meta=meta, doc_id=doc_id, body=body)\n mail.send(msg)\n\n# expands the placeholders in the output fields to their actual values\ndef _expand(content, percolator_id, query, meta, doc_id, body):\n try:\n content = content.replace(\"$percolator_id$\", percolator_id)\n content = content.replace(\"$title$\", meta[\"title\"])\n content = content.replace(\"$description$\", meta[\"description\"])\n content = content.replace(\"$query$\", json.dumps(query, indent=2))\n\n # if either of these is null, consider looking up the doc to get the values\n if doc_id is not None:\n content = content.replace(\"$doc_id$\", doc_id)\n if body is not None:\n content = content.replace(\"$body$\", str(body))\n\n except Exception as e:\n log_details = {}\n log_details[\"error\"] = \"unable to expand placeholder\"\n log_details[\"detail\"] = str(e)\n _log(log_details, level=\"error\")\n pass\n\n return content\n\n# api ping to support heartbeat checking\n@app.route(\"/ping/\", methods=[\"GET\"])\ndef ping():\n ping_details = {\"status\": \"OK\"}\n return jsonify(ping_details)\n\n# detailed api health, elastic nodes and health\n@app.route(\"/\", methods=[\"GET\"])\n@app.route(\"/health/\", methods=[\"GET\"])\ndef health():\n # TODO: add more health details\n health_details = {\n \"xavier\": {\n \"api\": {\n \"health\": \"OK\"\n }\n }\n }\n\n try:\n # get the elastic cluster details from the standard elastic query params\n es_url = request.args.get(\"es_url\", None)\n es_conn = _get_elasticsearch_conn(es_url)\n\n es_health = es_conn.cluster.health()\n es_nodes = es_conn.nodes.info()\n\n # add elastic health details\n health_details[\"elastic\"] = {\n \"health\": es_health,\n \"nodes\": es_nodes\n }\n except TypeError:\n # the es_url query param has probably not been specified, so ignore the elastic health\n pass\n except Exception as es_error:\n _handle_es_error(es_error)\n\n return jsonify(health_details)\n\n@app.before_request\ndef _pre_process_request():\n # save the initial timestamp\n g.timestamp_start = datetime.now(timezone.utc)\n\n try:\n # get the request id from heroku\n g.request_id = request.headers[\"X-Request-ID\"]\n except KeyError:\n # the app is local or not on heroku, generate a random request_id instead\n import uuid\n random_id = str(uuid.uuid4()).replace(\"-\", \"\").lower()[:8]\n g.request_id = random_id\n\n # save a copy of the query params\n g.params = request.args.copy()\n\n # get the elastic cluster details from the standard elastic query params\n g.es_url = g.params.pop(\"es_url\", None)\n\n # log default/common details\n log_details = {}\n log_details[\"method\"] = request.method\n # TODO: fix, the headers are not serializeable to string\n # log_details[\"headers\"] = json.loads(request.headers)\n log_details[\"remote_addr\"] = request.remote_addr\n log_details[\"url\"] = request.url\n log_details[\"path\"] = request.path\n _log(log_details, category=\"traffic\")\n\n # ensure we have es_url for backend-related services\n if request.path != \"/\" and request.path != \"/ping/\":\n if g.es_url is None:\n raise APIError(\"Missing param 'es_url' for the Elastic server\", status_code=400)\n\n try:\n g.es_conn = _get_elasticsearch_conn(g.es_url)\n except:\n raise APIError(\"Could not connect to Elastic server'\", status_code=502)\n\n # ensure that the xavier index exists\n try:\n _ensure_index()\n except:\n raise APIError(\"Could not find or create Xavier index in Elastic server\", status_code=500)\n\n@app.after_request\ndef _post_process_request(response):\n log_details = {}\n log_details[\"duration\"] = _get_duration()\n log_details[\"response_status\"] = int(json.dumps(response.status_code))\n # response_status = int(json.dumps(response.status_code))\n # log_details[\"response_status\"] = response_status\n # if response_status >= 400:\n # log_details[\"response\"] = str(response)\n\n _log(log_details, category=\"traffic\")\n return response\n\n@app.errorhandler(APIError)\ndef _handle_api_error(error):\n log_details = {}\n log_details[\"response_status\"] = error.status_code\n\n # pass through error from elastic (upstream), as is\n if error.passthrough:\n log_details[\"error\"] = error.msg\n log_details[\"source\"] = \"elastic\"\n\n pt_error = error.to_dict()\n pt_error[\"error\"] = error.msg\n pt_error[\"source\"] = \"elastic\"\n response = jsonify(pt_error)\n else:\n log_details[\"error\"] = error.msg\n log_details[\"source\"] = \"xavier\"\n response = jsonify(error.to_dict())\n\n _log(log_details, level=\"error\", category=\"audit\")\n\n response.status_code = error.status_code\n return response\n\ndef _log(log_details, level=\"info\", category=\"audit\"):\n import os\n\n log_details[\"@timestamp\"] = datetime.now(timezone.utc).isoformat()\n log_details[\"type\"] = app.config[\"APP_NAME\"]\n log_details[\"category\"] = category\n log_details[\"pid\"] = os.getpid()\n log_details[\"request_id\"] = g.request_id\n log_details[\"es_url\"] = g.es_url\n\n # get the dyno id from heroku\n dyno = os.environ.get(\"DYNO\", None)\n if dyno is not None:\n log_details[\"dyno\"] = os.environ.get(\"DYNO\", None)\n\n # NOTE: SysLogHandler doesn't send messages in RFC3164 format, which is the\n # only format that logstash's syslog input supports. as such, the facility\n # and priority will be lost, and we will add an explicit log level field.\n if level == \"critical\":\n log_details[\"level\"] = \"critical\"\n app.logger.critical(json.dumps(log_details))\n elif level == \"error\":\n log_details[\"level\"] = \"error\"\n app.logger.error(json.dumps(log_details))\n elif level == \"warning\":\n log_details[\"level\"] = \"warning\"\n app.logger.warning(json.dumps(log_details))\n elif level == \"info\":\n log_details[\"level\"] = \"info\"\n app.logger.info(json.dumps(log_details))\n elif level == \"debug\":\n log_details[\"level\"] = \"debug\"\n app.logger.debug(json.dumps(log_details))\n\n# return processing duration in milliseconds\ndef _get_duration():\n now = datetime.now(timezone.utc)\n difference = (now - g.timestamp_start).microseconds / 1000\n return difference\n\ndef _get_elasticsearch_conn(es_url):\n # use certifi for CA certificates\n # import certifi\n\n # TODO: regex break up the es_url to get the individual attributes for secure audit logging, then:\n # example:\n # es = Elasticsearch(\n # ['localhost', 'otherhost'],\n # http_auth=('user', 'secret'),\n # port=443,\n # use_ssl=True,\n # verify_certs=True,\n # ca_certs=certifi.where(),\n # )\n\n es_conn = Elasticsearch([es_url])\n\n log_details = {}\n # log_details[\"es_host\"] = es_host\n # log_details[\"es_port\"] = es_port\n # log_details[\"es_url_prefix\"] = es_url_prefix\n # log_details[\"es_username\"] = es_username\n # log_details[\"es_use_ssl\"] = es_use_ssl\n # log_details[\"msg\"] = \"connected to '%s'\" % es_host\n log_details[\"es_url\"] = es_url\n log_details[\"action\"] = \"connecting\"\n _log(log_details, level=\"debug\")\n\n return es_conn\n\ndef _handle_es_error(es_error):\n # set the full error message for the audit log\n try:\n error_full = json.loads(str(es_error))\n except:\n error_full = str(es_error)\n\n # set the short error message for the http response\n # http://elasticsearch-py.readthedocs.org/en/latest/exceptions.html\n # first, set the error to the message returned by elastic\n try:\n error_msg = str(es_error.error)\n except:\n # if that fails, set the error to the dict returned by elastic\n try:\n error_msg = str(es_error.info)\n except:\n # if that fails, set the error to the json string returned by elastic\n try:\n error_msg = json.loads(str(es_error))\n except:\n # if that fails, set the error to the plain string returned by elastic\n error_msg = str(es_error)\n\n # set the status code for the http response\n try:\n if es_error.status_code == \"N/A\":\n error_status = 502\n else:\n error_status = es_error.status_code\n except:\n error_status = 502\n\n log_details = { \"error\": error_full, \"response_status\": error_status }\n _log(log_details, level=\"debug\")\n\n raise APIError(error_msg, status_code=error_status, passthrough=True)\n\ndef _ensure_index():\n try:\n es_check_res = g.es_conn.indices.exists(index=app.config[\"XAVIER_INDEX\"])\n\n # TODO: have a specific error response for when the elastic server is unreachable... test\n if not es_check_res:\n log_details = {}\n log_details[\"detail\"] = \"xavier index does not exist\"\n log_details[\"index\"] = app.config[\"XAVIER_INDEX\"]\n _log(log_details)\n\n # create a mapping to enable the _timestamp for alerts as part of the body\n # http://elasticsearch-py.readthedocs.org/en/latest/api.html#indices\n # http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html\n # test by adding to this to the query to get the _timestamp: ?fields=_timestamp,_source\n timestamp_mapping = {\n \"mappings\" : {\n \"_default_\" : {\n \"_timestamp\" : {\n \"enabled\": True,\n \"store\": True\n }\n }\n }\n }\n\n try:\n es_create_res = g.es_conn.indices.create(index=app.config[\"XAVIER_INDEX\"], body=timestamp_mapping)\n\n if not es_create_res[\"acknowledged\"]:\n log_details = {}\n log_details[\"error\"] = \"unable to create xavier index\"\n log_details[\"index\"] = app.config[\"XAVIER_INDEX\"]\n _log(log_details, level=\"critical\")\n else:\n log_details = {}\n log_details[\"action\"] = \"creating index\"\n log_details[\"phase\"] = \"post\"\n log_details[\"index\"] = app.config[\"XAVIER_INDEX\"]\n _log(log_details, level=\"debug\")\n\n except Exception as error:\n _handle_es_error(error)\n except Exception as error:\n _handle_es_error(error)\n\nif __name__ == \"__main__\":\n # import pydevd\n # pydevd.settrace()\n\n import os\n from syslog import LOG_LOCAL0\n\n app.config.from_object(os.environ[\"APP_CONFIG\"])\n\n cors = CORS(app)\n mail = Mail(app)\n\n # TODO: make the syslog handler optional\n # add a syslog log handler\n # NOTE: SysLogHandler doesn't send messages in RFC3164 format, which is the\n # only format that logstash's syslog input supports. as such, the facility\n # and priority will be lost, and we will add an explicit log level field.\n import logging\n from logging.handlers import SysLogHandler\n syslog_handler = SysLogHandler(address=(app.config[\"SYSLOG_HOST\"], app.config[\"SYSLOG_PORT\"]), facility=LOG_LOCAL0)\n # don't terminate syslog messages with a NUL byte\n syslog_handler.append_nul = False\n if app.debug:\n # when running in debug mode, show messages on all log levels\n syslog_handler.setLevel(logging.DEBUG)\n else:\n # otherwise, show messages on the 'warning' level or higher\n # this will ignore 'info' and 'debug'\n syslog_handler.setLevel(logging.WARNING)\n app.logger.addHandler(syslog_handler)\n\n # add some log details for the app\n log_details = {}\n log_details[\"@timestamp\"] = datetime.now(timezone.utc).isoformat()\n log_details[\"type\"] = app.config[\"APP_NAME\"]\n log_details[\"level\"] = \"info\"\n log_details[\"category\"] = \"audit\"\n log_details[\"action\"] = \"starting\"\n log_details[\"config\"] = app.config.copy()\n\n datehandler = lambda obj: \"$$$ TEST $$$\" if isinstance(obj, datetime) else None\n app.logger.info(json.dumps(log_details, default=datehandler))\n\n app.run(host=app.config[\"APP_HOST\"], port=app.config[\"APP_PORT\"])","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":28405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"63857812","text":"# -*- coding:utf-8 -*-\n\n\n# Given a 32-bit signed integer, reverse digits of an integer.\n#\n# Note:\n# Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.\n#\n# \n# Example 1:\n# Input: x = 123\n# Output: 321\n# Example 2:\n# Input: x = -123\n# Output: -321\n# Example 3:\n# Input: x = 120\n# Output: 21\n# Example 4:\n# Input: x = 0\n# Output: 0\n#\n# \n# Constraints:\n#\n#\n# \t-231 <= x <= 231 - 1\n#\n#\n\n\nclass Solution(object):\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n y=0\n s=1\n if(x<0):\n s=-1\n x=abs(x)\n while (x/10!=0):\n y=y*10+x%10\n x=x/10\n y=y*10+x%10\n if (y>=pow(2,31)):\n return 0\n else:\n return y*s\n","sub_path":"0007-reverse-integer/reverse-integer.py","file_name":"reverse-integer.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"599321106","text":"from itertools import chain\n\n\nfrom six import u\n\nfrom circuits import handler\n\nfrom circuits.protocols.irc import joinprefix, reply\nfrom circuits.protocols.irc import Message as _Message\n\nfrom circuits.protocols.irc.replies import ERR_NOSUCHNICK, ERR_NOSUCHCHANNEL\nfrom circuits.protocols.irc.replies import ERR_CANNOTSENDTOCHAN\n\n\nfrom ..plugin import BasePlugin\nfrom ..models import Channel, User\nfrom ..commands import BaseCommands\n\n\nclass Commands(BaseCommands):\n\n @handler(\"privmsg\", \"notice\")\n def on_privmsg_or_notice(self, event, sock, source, target, message):\n user = User.objects.filter(sock=sock).first()\n\n prefix = user.prefix or joinprefix(*source)\n\n if target and target[0] in (u(\"&\"), u(\"#\"),):\n channel = Channel.objects.filter(name=target).first()\n if channel is None:\n return ERR_NOSUCHCHANNEL(target)\n\n if u(\"n\") in channel.modes:\n if not user.oper and user not in channel.users:\n return ERR_CANNOTSENDTOCHAN(channel.name)\n\n if u(\"m\") in channel.modes:\n if not user.oper and user not in chain(channel.operators, channel.voiced):\n return ERR_CANNOTSENDTOCHAN(channel.name)\n\n self.notify(\n channel.users,\n _Message(u(\"PRIVMSG\"), target, message, prefix=prefix),\n user\n )\n else:\n user = User.objects.filter(nick=target).first()\n if user is None:\n return ERR_NOSUCHNICK(target)\n\n return reply(\n user.sock,\n _Message(\n event.name.upper(), target, message,\n prefix=prefix\n )\n )\n\n\nclass Message(BasePlugin):\n\n def init(self, *args, **kwargs):\n super(Message, self).init(*args, **kwargs)\n\n Commands(*args, **kwargs).register(self)\n","sub_path":"charla/plugins/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"235710078","text":"import sys, os\nsys.path.append(os.getcwd()) ## this lets python find src\nimport numpy as np\nimport matplotlib\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom chainconsumer import ChainConsumer\n#import healpy as hp\n#from healpy import Alm\nimport pickle, argparse\n#import logging\nfrom src.hierarchical import postprocess\nmatplotlib.rcParams.update(matplotlib.rcParamsDefault)\n\nif __name__ == '__main__':\n\n # Create parser\n parser = argparse.ArgumentParser(prog='postproc', usage='%(prog)s [options] rundir', description='run hierarchical postprocessing')\n\n # Add arguments\n parser.add_argument('rundir', metavar='rundir', type=str, help='The path to the run directory.')\n parser.add_argument('--outdir', metavar='outdir', type=str, help='The path to the output directory Defaults to rundir.',default=None)\n parser.add_argument('--model', metavar='model', type=str, help='Parameterized spatial model to use.', default='breivik2020')\n parser.add_argument('--Nwalkers', metavar='Nwalkers', type=int, help='Number of walkers.', default=50)\n parser.add_argument('--Nsamples', metavar='Nsamples', type=int, help='Number of desired samples.', default=10000)\n parser.add_argument('--Nburn', metavar='Nburn', type=int, help='Number of desired burn-in samples.', default=1000)\n parser.add_argument('--seed', metavar='seed', type=int, help='Desired seed for the rng.', default=None)\n parser.add_argument('--Nthread', metavar='Nthread', type=int, help='Number of desired cores for multiprocessing.', default=1)\n # execute parser\n args = parser.parse_args()\n\n\n paramfile = open(args.rundir + '/config.pickle', 'rb')\n ## things are loaded from the pickle file in the same order they are put in\n params = pickle.load(paramfile)\n inj = pickle.load(paramfile)\n parameters = pickle.load(paramfile)\n ## initualize the postprocessing class\n postprocessor = postprocess(args.rundir,params,inj,parameters)\n ## run the sampler\n sampler = postprocessor.hierarchical_sampler(model=args.model,Nwalkers=args.Nwalkers,Nsamples=args.Nsamples,Nburn=args.Nburn,rng=args.seed,Nthread=args.Nthread)\n ## plot\n chain = sampler.flatchain\n ## model use cases\n knowTrue = False\n if args.model=='breivik2020':\n npar=2\n post_parameters = ['$r_h$','$z_h$']\n ## deal with older config files and assign true values if known\n if 'fg_type' in inj.keys():\n if inj['fg_type'] == 'breivik2020':\n knowTrue = True\n truevals = [inj['rh'],inj['zh']]\n else:\n raise TypeError(\"Unknown model. Currently supported models: 'breivik2020'.\")\n cc = ChainConsumer()\n cc.add_chain(chain, parameters=post_parameters)\n cc.configure(smooth=False, kde=False, max_ticks=2, sigmas=np.array([1, 2]), label_font_size=18, tick_font_size=18, \\\n summary=False, statistics=\"max_central\", spacing=2, summary_area=0.95, cloud=False, bins=1.2)\n cc.configure_truth(color='g', ls='--', alpha=0.7)\n\n if knowTrue:\n fig = cc.plotter.plot(figsize=(16, 16), truth=truevals)\n else:\n fig = cc.plotter.plot(figsize=(16, 16))\n\n ## make axis labels to be parameter summaries\n sum_data = cc.analysis.get_summary()\n axes = np.array(fig.axes).reshape((npar, npar))\n\n # Adjust axis labels\n for ii in range(npar):\n ax = axes[ii, ii]\n\n # get the right summary for the parameter ii\n sum_ax = sum_data[post_parameters[ii]]\n err = [sum_ax[2] - sum_ax[1], sum_ax[1]- sum_ax[0]]\n\n if np.abs(sum_ax[1]) <= 1e-3:\n mean_def = '{0:.3e}'.format(sum_ax[1])\n eidx = mean_def.find('e')\n base = float(mean_def[0:eidx])\n exponent = int(mean_def[eidx+1:])\n mean_form = str(base) + ' \\\\times ' + '10^{' + str(exponent) + '} '\n else:\n mean_form = '{0:.3f}'.format(sum_ax[1])\n\n if np.abs(err[0]) <= 1e-2:\n err[0] = '{0:.4f}'.format(err[0])\n else:\n err[0] = '{0:.2f}'.format(err[0])\n\n if np.abs(err[1]) <= 1e-2:\n err[1] = '{0:.4f}'.format(err[1])\n else:\n err[1] = '{0:.2f}'.format(err[1])\n\n label = post_parameters[ii][:-1] + ' = ' + mean_form + '^{+' + err[0] + '}_{-' + err[1] + '}$'\n\n ax.set_title(label, {'fontsize':18}, loc='left')\n\n ## save\n if args.outdir is None:\n plt.savefig(args.rundir + '/postproc_corners.png', dpi=150)\n print(\"Posteriors plots printed in \" + args.rundir + \"/postproc_corners.png\")\n plt.close()\n np.savetxt(args.rundir+'/postprocessing_samples.txt',chain)\n else:\n plt.savefig(args.outdir + '/postproc_corners.png', dpi=150)\n print(\"Posteriors plots printed in \" + args.outdir + \"/postproc_corners.png\")\n plt.close()\n np.savetxt(args.outdir+'/postprocessing_samples.txt',chain)\n \n\n\n\n\n\n\n\n","sub_path":"blip/tools/hierarchical_postprocess.py","file_name":"hierarchical_postprocess.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"288624159","text":"from os import path\nimport datetime\n\n\ndef get_name_module(file_path):\n \"\"\"\n\n (string) -> string\n\n Function get name of file from path without file extension\n\n \"\"\"\n file_name = path.basename(file_path)\n idx = file_name.index('.')\n return file_name[:idx]\n\n\ndef logger_path_decorator(file_path='file1.log'):\n def logger_decorator(function):\n \"\"\"\n\n (address of function) -> address of function\n\n Function-decorator which logging to text file about input and output data and start time of execute of function\n\n\n \"\"\"\n\n def wrapper(*args, **kwargs):\n\n # If file exists then create file\n if not path.exists(file_path):\n with open(file_path, 'w', encoding='utf-8'):\n pass\n\n with open(file_path, 'a', encoding='utf-8') as file:\n lines = f\"{datetime.datetime.now()}: Вызов функции \\\"{function.__name__}\\\":\\n\"\n lines += f\"Аргументы функции \\\"{function.__name__}\\\":\\n\"\n for number, argument in enumerate(args, 1):\n lines += f\"аргумент №{number}: {argument}\\n\"\n for key, value in kwargs.items():\n lines += f\"аргумент \\\"{key}\\\": {value}\\n\"\n return_value = function(*args, **kwargs)\n lines += f\"Возвращаемое значение функции равно: {return_value}\\n\"\n file.writelines(lines)\n return return_value\n return wrapper\n return logger_decorator\n\n\n# Example 1\n@logger_path_decorator()\ndef function1_to_decorate(**kwargs):\n summa = 0\n for key, value in kwargs.items():\n summa += value\n return str(summa)\n\n# Example 2\n@logger_path_decorator()\ndef function2_to_decorate(*args):\n summa = 0\n for argument in args:\n summa += argument\n return str(summa)\n\n\nif __name__ == \"__main__\":\n function1_to_decorate(a=1, b=2, c=3)\n function2_to_decorate(1, 2, 3)\n\n\n\n","sub_path":"decorator_logger.py","file_name":"decorator_logger.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"199551744","text":"# -*- coding: utf-8 -*-\n\n\"\"\" My Input and Output IO clas/file\n\n\"\"\"\n#standard library imports\nimport os\nimport logging\n#related third party imports\nimport numpy as np\nfrom PIL import Image as PILImage\n#local application/library specific imports\n\n\nclass RnIo():\n \"\"\" My IO class\n \n \"\"\"\n \n def __init__(self, workspace = ''):\n \"\"\" IO initialisation\n \n \"\"\"\n self.workspace = workspace\n \n def write_nparray_csv(self, nparray, header = [], \n speichername = 'test.csv', \n delimiter = ';'):\n \"\"\" Write 2D nparray to ascii file\n \n nparray (nparray): 2D numpy data array\n header (arr): 1D python array of header\n speichername (str): name of file to write\n delimiter (str): delimiter which shall be used\n \n \"\"\"\n #Assertions\n try:\n assert(isinstance(nparray, np.ndarray))\n assert(isinstance(header, list))\n assert(isinstance(speichername, str))\n assert(isinstance(delimiter, str))\n except AssertionError:\n logging.error('ein paramter hat nicht das passende format')\n \n #Code\n filepath = self.workspace + speichername\n with open(filepath, 'wb') as f:\n #check if header exists\n if len(header) > 0:\n _row = ''\n for entry in header:\n _row += str(entry) + delimiter\n _row += '\\n'\n f.write(_row)\n \n for y in xrange(nparray.shape[0]):\n _row = ''\n for x in xrange(nparray.shape[1]):\n _row += str(nparray[y, x]) + delimiter\n _row += '\\n'\n f.write(_row)\n \n def read_csv_nparray(self, name = 'test.csv', \n header = False, \n delimiter = ';'):\n \"\"\" Reads csv file\n \n name (str): file name of file e.g. test.csv\n header (bool): if file has 1 line header set as True\n delimiter: delimiter of file\n \n Returns:\n header (arr)\n nparray\n \n \"\"\"\n _header = []\n _arr = []\n filepath = self.workspace + name\n with open(filepath, 'rb') as f:\n #read header\n if header == True:\n _row = f.readline()\n _header = _row.split(delimiter)\n _header.pop() #remove \\n element\n \n #read data\n for line in f.xreadlines():\n line = line.split(delimiter)\n line.pop() #remove new line char\n try:\n line = [float(x) for x in line] #convert string to float\n except ValueError:\n logging.error(\"\"\"coud no convert string to float, wrong data\n format ist given back!\"\"\")\n _arr.append(line)\n\n _arr = np.array(_arr) \n return _header, _arr\n \n def write_nparray_Image(self, nparray, name = 'test.bmp', normiert = True):\n \"\"\" Write an 2D/3D nparray as an Image\n \n nparray (numpy arra): 2D/3D Numpy array\n name (str): filename of image\n normiert (bool): if true the Image will be normalized\n \n \"\"\"\n filepath = self.workspace + name\n _image = PILImage.fromarray(nparray)\n \n if normiert == True:\n from PIL import ImageOps\n _image = ImageOps.autocontrast(_image, cutoff=0)\n \n _image.save(filepath)\n \n def read_Image_nparray(self, filepath):\n \"\"\" Reads Image with PIL and converts it to numpy array\n \n filepath (str): complete filepath to Image\n \n \"\"\"\n #with open(filepath, 'rb') as _fp:\n #_fp = open(filepath, 'rb')\n img = PILImage.open(filepath)\n #_img = _img.convert('L')\n #_fp.close()\n #_arr = np.array(img)\n arr = np.array(img)\n return arr\n \n \n def read_fits_nparray(self, name = 'test.fit', number = 0):\n \"\"\" Read .fits file from iStar camera\n \n name (str): file name\n number (int): number of hdulist (usually 0)\n \n Returns:\n _header (pyfits.header.Header): dictionary type something\n _arr (numpy.ndarray): numpy array\n \n \"\"\"\n import pyfits\n _file =self. workspace + name\n _fits = pyfits.open(_file)\n _header = _fits[number].header\n _arr = _fits[number].data\n return _header, _arr\n\n def read_prf_nparray(self, filepath):\n \"\"\" Read a prf spectrum file\n \n filepath (str): complete filepath to prf file\n \n Returns:\n _arr (numpy.ndarray): 2 D numpy array. first colum is index,\n second is intensity\n \n \"\"\"\n delimiter = '\\t'\n _arr = []\n with open(filepath, 'rb') as f:\n for line in f.xreadlines():\n line = line.split(delimiter)\n line[1] = line[1].rstrip('\\r\\n')\n #print line\n try:\n line = [float(x) for x in line] #convert string to float\n except ValueError:\n logging.error(\"\"\"coud no convert string to float, wrong data\n format ist given back!\"\"\")\n _arr.append(line)\n _arr = np.array(_arr) \n #print _arr\n return _arr\n \n def read_suaptxt_nparray(self, filepath):\n \"\"\" Reads txt file from suap\n \n filepath (str): complete filepath to prf file\n \n Returns:\n _arr (numpy.ndarray): 2 D numpy array. first colum is index,\n second is intensity\n \n \"\"\"\n delimiter = '\\t'\n _arr = []\n with open(filepath, 'rb') as f:\n for i, line in enumerate(f.xreadlines()):\n line = line.split(delimiter)\n if i >= 3:\n line[1] = line[1].rstrip('\\n')\n try:\n line = [float(x) for x in line] #convert string to float\n except ValueError:\n logging.error(\"\"\"coud no convert string to float, wrong data\n format ist given back!\"\"\")\n _arr.append(line)\n _arr = np.array(_arr) \n #print _arr\n return _arr\n \n def read_originPeaklist_nparray(self, filepath):\n \"\"\" Reads a peaklist (from origin exportet)\n \n filepath (str): complete filepath to prf file\n \n Returns:\n _arr (numpy.ndarray): 2 D numpy array. first colum is index,\n second is intensity\n \n \"\"\"\n delimiter = '\\t'\n _arr = []\n with open(filepath, 'rb') as f:\n for i, line in enumerate(f.xreadlines()):\n line = line.split(delimiter)\n line[1] = line[1].rstrip('\\r\\n')\n #komme zu punkt konversion\n line[0] = line[0].replace(',', '.')\n line[1] = line[1].replace(',', '.')\n try:\n line = [float(x) for x in line] #convert string to float\n except ValueError:\n logging.error(\"\"\"coud no convert string to float, wrong data\n format ist given back!\"\"\")\n _arr.append(line)\n \n _arr = np.array(_arr)\n #print _arr\n return _arr\n \n def write_nparray_txt(self, filepath, nparray, header = [], delimiter = '\\t'):\n \"\"\" Write an 2D numpy array to ascii file\n \n filepath (str): complete filepath for new file\n nparray (numpy.ndarray): 2D numpy array\n delimiter (str): optional delimiter parameter\n \n \"\"\"\n _nrows = nparray.shape[0]\n _ncolumns = nparray.shape[1]\n with open(filepath, 'wb') as f:\n #check if header exists\n if len(header) > 0:\n for row in header:\n _row = ''\n for item in row:\n _row += str(item) + delimiter\n _row += '\\n'\n f.write(_row)\n for y in xrange(_nrows):\n _row = ''\n for x in xrange(_ncolumns):\n _row += str(nparray[y, x]) + delimiter\n _row += '\\n'\n f.write(_row)\n \n \n\nif __name__ == \"__main__\":\n io = RnIo()\n path1 = 'D:/Raimund Buero/Python/SpyDev/Specfit/testdata/spectrum1.prf'\n path2 = 'D:/Raimund Buero/Python/SpyDev/Specfit/testdata/spectrum2.txt'\n path3 = 'D:/Raimund Buero/Python/SpyDev/Specfit/testdata/Peaklist.dat'\n #io.read_prf_nparray(path1)\n #io.read_suaptxt_nparray(path2)\n io.read_originPeaklist_nparray(path3)\n \n \n","sub_path":"rnio.py","file_name":"rnio.py","file_ext":"py","file_size_in_byte":9148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"622823164","text":"#\n# Copyright 2013 Urban Airship\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 re\nip = '0.0.0.0'\nkey_dir = 'keys'\nkey_configs = {\n 'a-server.example.com': {\n 'cidr_ranges': ['128.0.0.1/24'],\n },\n 'b-server.example.com': {\n 'cidr_ranges': ['0.0.0.0/0'],\n 'service': 'b-server',\n 'path': [re.compile(r\".*key$\"), lambda x: True]\n }\n}\n","sub_path":"padlocker/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"160937827","text":"# -*- coding: utf-8 -*-\n'''\nЗадание 7.3a\n\nСделать копию скрипта задания 7.3.\n\nДополнить скрипт:\n- Отсортировать вывод по номеру VLAN\n\n\nОграничение: Все задания надо выполнять используя только пройденные темы.\n\n'''\nmac = []\nwith open('CAM_table.txt') as f:\n for line in f:\n if 'DYNAMIC' in line:\n mac.append(line.replace(' DYNAMIC ','').strip())\nfor line in sorted(mac):\n print(line)\n","sub_path":"exercises/07_files/task_7_3a.py","file_name":"task_7_3a.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"215571127","text":"#########################################################\n### Analysis/Ray-tracing module for Bulk SPDC sources ###\n### Written by: Arian Stolk\t\t\t\t\t\t\t ###\n### Date: September 2017\t\t\t\t\t\t\t ###\n#########################################################\n\n###The goal of this project is to provide a tool that will allow the investigation of SPDC sources made of bulk non-linear crystals.###\n###Import library####\n\nfrom math import *\nimport random\nimport scipy\nimport numpy as np\nimport sympy as sp\nimport matplotlib\nimport collections\nfrom itertools import compress\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport time, sys\nfrom vpython import *\nimport multiprocessing as mp\n\n\ndebug=False\n################################################################################################################\ndef Sellmeier(coeff=[0,0,0,0],lam = 785):\n\t\"Takes the wavelength [nm] array lam and coeff and outputs the refractive index. Used for BBO and YVO4\"\n\tl=lam*1e-3\n\treturn np.sqrt(coeff[0]+(coeff[1])/((l)**2-coeff[2])-coeff[3]*(l)**2)\n\ndef dSellmeier(coeff=[0,0,0,0],lam = 785):\n\t\"Takes the wavelength [nm] array lam and coeff and outputs the derivate of refractive index with respect to wavelength. Used for BBO and YVO4\"\n\tc = coeff\n\treturn ((1e-6)*lam*(-c[3]-(c[1])/(c[2]-(1e-6)*lam**2)**2))/np.sqrt((c[0]-(1e-6)*c[3]*lam**2-(c[1])/(c[2]-(1e-6)*lam**2)))\n\ndef v_group(lam=785,n=1,dn=0):\n\t\"Takes the arrays lam, n and dn and outputs the array of group velocities\"\n\n\treturn (2.998e11)/(n-lam*dn)\n\ndef n_ext_effective(coeff=[0,0,0,0,0,0,0,0],theta=0,lam=785):\n\t\"takes the full sellmeier coefficients, the angle array theta and the wavelength array wavelength and outputs the refractive index in an array \"\n\tc=coeff\n\t# try:\n\t# \tprint(lam.shape,theta.shape)\n\t# except AttributeError:\n\t# \tpass\n\treturn ((np.sin(theta)/(c[4]+(c[5])/((lam*1e-3)**2-c[6])-(c[7])*(lam*1e-3)**2)**0.5)**2+(np.cos(theta)/(c[0]+(c[1])/((lam*1e-3)**2-c[2])-(c[3])*(lam*1e-3)**2)**0.5)**2)**(-0.5)\n\ndef dn_ext_effective(coeff=[0,0,0,0,0,0,0,0],theta=0,lam=785):\n\t\"takes the full sellmeier coefficients, the angle array theta and the wavelength array wavelength and outputs the derivate of the refractive index in an array \"\n\tc=coeff\n\treturn -((1e-6)*lam*(((c[1]+c[3]*(c[2]-(1e-6)*lam**2)**2)*np.cos(theta)**2)/(c[1]+(c[2]-(1e-6)*lam**2)*(-c[0]+(1e-6)*c[3]*lam**2))**2\\\n\t\t\t+(((c[5]+c[7]*(c[6]-(1e-6)*lam**2)**2)*np.sin(theta)**2)/(c[5]+(c[6]-(1e-6)*lam**2)*(-c[4]+(1e-6)*c[3]*lam**2))**2))\\\n\t\t\t/((np.cos(theta)**2)/(c[0]-(1e-6)*c[3]*lam**2-c[1]/(c[2]-(1e-6)*lam**2))+(np.sin(theta)**2)/(c[4]-(1e-6)*c[7]*lam**2-c[5]/(c[6]-(1e-6)*lam**2)))**(3/2))\n\ndef flatten(l):\n\t\"flattens list l to having only 1 dimension\"\n\tfor el in l:\n\t\tif isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):\n\t\t\tyield from flatten(el)\n\t\telse:\n\t\t\tyield el\n\ndef walkoff(theta=0,coeff=[0,0,0,0,0,0,0,0],lam=785,thickness=1):\n\t\"Takes the angle array theta, full Sellmeiercoeff, wavelength array lam [nm] and thickness array [mm] and returns the 1d value of the walkoff (SO NOT AN ARRAY) \"\n\n\t# if len(coeff)<8:\n\t# \tprint(\"Please provide all 8 Sellmeier coeffs\")\n\t# else:\n\tn_ord=Sellmeier(coeff[0:4],lam)\n\tn_ext=Sellmeier(coeff[4:8],lam)\n\treturn 0.5*thickness*(n_ext_effective(coeff=coeff,theta=theta,lam=lam)**2)*((n_ord**-2)-(n_ext**-2))*np.sin(2*theta)\n\ndef update_progress(progress):\n barLength = 10 # Modify this to change the length of the progress bar\n status = \"\"\n if isinstance(progress, int):\n progress = float(progress)\n if not isinstance(progress, float):\n progress = 0\n status = \"error: progress var must be float\\r\\n\"\n if progress < 0:\n progress = 0\n status = \"Halt...\\r\\n\"\n if progress >= 1:\n progress = 1\n status = \"Done...\\r\\n\"\n block = int(round(barLength*progress))\n text = \"\\rPercent: [{0}] {1}% {2}\".format( \"#\"*block + \"-\"*(barLength-block), progress*100, status)\n sys.stdout.write(text)\n sys.stdout.flush()\n\ndef phasefunction_vec(lpump=405,l_list=[785],theta_list=[0],coeff=[2.7359, 0.01878, 0.01822, 0.01354, 2.3753, 0.01224, 0.01667, 0.01516],cutangle=28.7991*np.pi/180,crystal_length=6,W=0.1):\n\t\"Input float of pump wavelength, and arrays size (1,n) of l_list, theta_list, cutangle and crystal_length output provides the array size (1,n) of the phasematching fucntion. \"\n\tc=coeff\n\t#create lists of pump,signal and idler wavelengths\n\n\tli=l_list*lpump/(l_list-lpump);\n\t#calculate the angular frequency from wavelength\n\twp,ws,wi = (2*np.pi)/lpump,(2*np.pi)/l_list,(2*np.pi)/li\n\n\t#calculate the ord/extraord refractive indices for the wavelenghts\n\tnop = Sellmeier(coeff=c[0:4],lam=lpump)\n\tnep = Sellmeier(coeff=c[4:8],lam=lpump)\n\tnos = Sellmeier(coeff=c[0:4],lam=l_list)\n\t# nes = Sellmeier(coeff=c[4:8],lam=l_list)\n\tnoi = Sellmeier(coeff=c[0:4],lam=li)\n\t# nei = Sellmeier(coeff=c[4:8],lam=li)\n\n\t#calculate the effective pump refractive index\n\tnpeff=np.sqrt(1/((np.cos(cutangle)/nop)**2+(np.sin(cutangle)/nep)**2))\n\tL=crystal_length\n\n\tthet_i=np.arcsin(nos*ws*np.sin(theta_list)/(noi*wi))\t\t\t\t\t\t\t\t\t\t\t#corresponding opening angle of the idler photon based on refractive indices\n\tdkz=npeff*wp-nos*ws*np.cos(theta_list)-noi*wi*np.cos(thet_i)\t\t\t\t\t\t\t\t\t#corresponding phase mismatch in z (propagationdirection) per unit length\n\tdky=-nos*ws*np.sin(theta_list)+noi*wi*np.sin(thet_i)\t\t\t\t\t\t\t\t\t\t\t#mismatch in pphase in y (direction perp to z) per unit length\n\tphi=np.exp(-((W*1e6)**2)*(np.square(dky))/2)*np.square(np.sin(0.5*dkz*L*1e6)/(0.5*dkz*L*1e6))\t#sinc2() func of the mismatch over the length of the crystal\n\n\treturn phi #(1,n) array\n\ndef dens_hist(data):\n \n\n #data definition\n xdat, ydat = data[0],data[1]\n \n x_range=np.array([-2,2])+np.mean(xdat)\n y_range=np.array([-2,2])+np.mean(ydat)\n xyrange = [x_range,y_range] # data range\n bins = [100,100] # number of bins\n thresh = 1 #density threshold\n\n # histogram the data\n hh, locx, locy = scipy.histogram2d(xdat, ydat, range=xyrange, bins=bins)\n posx = np.digitize(xdat, locx)\n posy = np.digitize(ydat, locy)\n\n #select points within the histogram\n ind = (posx > 0) & (posx <= bins[0]) & (posy > 0) & (posy <= bins[1])\n hhsub = hh[posx[ind] - 1, posy[ind] - 1] # values of the histogram where the points are\n xdat1 = xdat[ind][hhsub < thresh] # low density points\n ydat1 = ydat[ind][hhsub < thresh]\n hh[hh < thresh] = np.nan # fill the areas with low density by NaNs\n\n plt.imshow(np.flipud(hh.T),cmap='jet',extent=np.array(xyrange).flatten(), interpolation='none', origin='upper')\n plt.title(\"xmean i {0:.2f},xstd is {0:.2f} and ymean is{0:.2f}, ystd is {0:.2f}\".format(np.mean(xdat),np.std(xdat),np.mean(ydat),np.std(ydat)))\n plt.colorbar() \n plt.show()\n \n\n##################################################################################################################\nclass Visualization(object):\n\t\"Class used to visualize the outcome of a simulation\"\n\n\tdef __init__(self,**k):\n\t\tself.simulation\t\t\t\t= k.pop('simulation')\n\t\tself.complete_results\t\t=self.simulation.complete_results\n\t\tself.surface_pos\t\t\t=[x.fsurf for x in self.simulation.setup.elements]\n\t\tself.graph_open\t\t\t\t= False\n\n\n\tdef showtime(self,time_diff=False,bins=50,pos=0):\n\t\t\"this function shows the temporal results of the raytracing\"\n\t\t\n\t\tif pos < self.surface_pos[-1]:\n\t\t\tself.interpol_data(pos=pos)\n\t\t\tplot_data = self.dummy_surface\n\t\telse:\n\t\t\tprint(\"Please choose a position smaller than the end position of the simulation\")\n\n\n\t\tif not time_diff:\n\t\t\ttimelist=(1e15)*np.array([x[3][:] for x in plot_data])\n\n\t\telse:\n\t\t\tarrivtimes = (1e15)*np.array([x[3][:] for x in plot_data])\n\n\t\t\ttimelist = np.array([arrivtimes[0]-arrivtimes[1],arrivtimes[2]-arrivtimes[3]])\n\t\t\n\t\tplt.figure()\n\t\t\n\t\tfor i,times in enumerate(timelist):\n\t\t\tplt.hist(times,bins,alpha=0.5,label = \"Photons from crystal {}\".format([\"one\",\"two\"][i % 2]))\n\t\t\tprint(np.mean(times),len(times))\n\t\tplt.legend()\n\t\tplt.xlabel(\"D_arrival time between signal and idles [fs]\")\n\t\tplt.ylabel(\"Occurance\")\n\t\tplt.show()\n\n\tdef showpos(self,pos=0):\n\n\t\t\"this function shows the position results of the raytracing\"\n\t\tif pos < self.surface_pos[-1]:\n\t\t\tself.interpol_data(pos=pos)\n\t\t\tplot_data = self.dummy_surface\n\t\telse:\n\t\t\tprint(\"Please choose a position smaller than the end position of the simulation\")\n\n\t\tdata_list = [x[0][:].T[0:2] for x in plot_data]\n\t\n\t\tf,axarr = plt.subplots(2,2,figsize=(10,10))\n\t\t\n\t\tfor i,ax in enumerate(flatten(axarr)):\n\t\t\tax.clear()\n\t\t\tdata=data_list[i]\n\t\t\txdat, ydat = data[0],data[1]\n\t\t\tx_range=np.array([-2,2])+np.mean(xdat)\n\t\t\ty_range=np.array([-2,2])+np.mean(ydat)\n\t\t\txyrange = [x_range,y_range] # data range\n\t\t\tbins = [100,100] # number of bins\n\t\t\tthresh = 10\t #density threshold\n\n\t\t\t# histogram the data\n\t\t\thh, locx, locy = scipy.histogram2d(xdat, ydat, range=xyrange, bins=bins)\n\t\t\tposx = np.digitize(xdat, locx)\n\t\t\tposy = np.digitize(ydat, locy)\n\n\t\t\t#select points within the histogram\n\t\t\tind = (posx > 0) & (posx <= bins[0]) & (posy > 0) & (posy <= bins[1])\n\t\t\thhsub = hh[posx[ind] - 1, posy[ind] - 1] # values of the histogram where the points are\n\t\t\txdat1 = xdat[ind][hhsub < thresh] # low density points\n\t\t\tydat1 = ydat[ind][hhsub < thresh]\n\t\t\thh[hh < thresh] = np.nan # fill the areas with low density by NaNs\n\n\t\t\tax.imshow(np.flipud(hh.T),cmap='jet',extent=np.array(xyrange).flatten(), interpolation='none', origin='upper')\n\t\t\tax.set_title(\"xm ={:.2f}, xs ={:.2f}, ym = {:.2f}, ys ={:.2f}\".format(np.mean(xdat),np.std(xdat),np.mean(ydat),np.std(ydat)))\n\t\t\t# ax.set_fontsize(20)\n\t\t\t# ax.colorbar()\n\t\tplt.show()\n\n\tdef interpol_data(self,pos=0):\n\n\t\t[index_rsurf,rsurf_z]=[[i,x] for i,x in enumerate(self.surface_pos) if x >= pos ][0]\n\t\t[index_lsurf,lsurf_z]=[index_rsurf-1,self.surface_pos[index_rsurf-1]]\n\n\t\tscale=(pos-lsurf_z)/(rsurf_z-lsurf_z)\n\n\t\tself.dummy_surface=[[[] for i in range(5)] for j in range(4)]\n\n\t\tfor i,ray_list in enumerate(self.complete_results):\n\t\t\tfor j in [0,3]: #interpolate position and times\n\t\t\t\tarrays=np.split(ray_list[j],[index_lsurf,index_rsurf+1],axis=-1)[1]\n\t\t\t\tinterpolation_matrix = np.sum(np.array([(1-scale),scale])*arrays,axis=-1)\n\t\t\t\tself.dummy_surface[i][j]=interpolation_matrix\n\t\t\tfor j in [1,2,4]:#angles,wavelength and polarization dont need to be interpolated\n\t\t\t\tself.dummy_surface[i][j]=ray_list[j][...,index_lsurf]\n\n\tdef get_focus_pos(self,pos=0):\n\t\t\n\t\tif pos < self.surface_pos[-1]:\n\t\t\tself.interpol_data(pos=pos)\n\t\telse:\n\t\t\tprint(\"Please choose a position smaller than the end position of the simulation\")\n\n\t\txmeans=np.array(list(map(np.mean,[x[0][:].T[0] for x in self.dummy_surface])))\n\t\tymeans=np.array(list(map(np.mean,[x[0][:].T[1] for x in self.dummy_surface])))\n\t\treturn np.mean(np.array([xmeans,ymeans]),axis=1) \n\n\tdef filter_results(self,fibre_pos=np.array([0,0,0]),core_diam=0,Num_Ap=0):\n\t\t\"Filter function giving singles and coincidences that enter the fibre at fibre_pos with specified dimensions\"\n\n\t\tfilter_cond_match_list=[]\n\t\tself.singles=[]\n\t\tself.coincidences=[]\n\t\t\n\t\tpos = fibre_pos[-1]\n\n\t\tif pos < self.surface_pos[-1]:\n\t\t\tself.interpol_data(pos=pos)\n\t\telse:\n\t\t\tprint(\"Please choose a position smaller than the end position of the simulation\")\n\n\t\tfor ray_set in self.dummy_surface:\n\t\t\tpos = ray_set[0]\n\t\t\tangle = ray_set[1]\n\n\t\t\tfilter_cond_match=self.filter_func(pos,angle,fibre_pos=fibre_pos,core_diam=core_diam, Num_Ap = Num_Ap)\n\t\t\tfilter_cond_match_list.append(filter_cond_match)\n\n\t\t\tsingles_list = [ray[np.where(filter_cond_match)] for ray in ray_set[0:-1]]\n\t\t\tself.singles.append(singles_list)\n\n\t\tself.coincidences =[[x[np.where(np.logical_and(filter_cond_match_list[2*round(i/2.1)],filter_cond_match_list[2*round(i/2.1)+1]))] for x in ray_set[0:-1]] for i,ray_set in enumerate(self.dummy_surface)] #2*round(i/2.1) does (0,1,2,3) -> (0,0,2,2) to compare signal and idler\n\n\n\tdef filter_func(self,pos,angle,fibre_pos=np.array([0,0,0]),core_diam=0,Num_Ap=0):\n\n\t\t\"method called by filter_results to check if the rays fall in fibre pos with angle < NA\"\n\t\tcore_dist_check=np.linalg.norm(pos-fibre_pos,axis=1)optic_elements[1].bsurf: #check if ray is not already past this surface due to starting position\n\t\t\t#get optic elements from list\n\t\t\telement1=optic_elements[0]\n\t\t\telement2=optic_elements[1]\n\n\t\t\t#make (N,2) array of the refractive indices for before and after the surface\n\t\t\tnin=np.repeat(element1.getn(angle,lam),2,axis=1)\n\t\t\tnout=np.repeat(element2.getn(angle,lam),2,axis=1)\n\n\t\t\t#calculate the fraction needed for snells law and thin lens equation\n\t\t\tindexfract = (nin/nout)\t\t\n\n\t\t\t# print(nin,nout,ray.angles,ray.position,element1.position,element2.position)\n\t\t\t\n\t\t\tif hasattr(element1,\"ROC\"): #check if first element is lens, if yes use back surface ROC of element1\n\t\t\t\tposition_on_lens=(pos-element1.position)[:,0:2]\n\n\t\t\t\tif not element1.asphere:\t\t\t\t\t\n\t\t\t\t\tangles = np.arcsin(np.sin(angle)*(indexfract))+position_on_lens*((nin-nout)/(nout*element1.ROC[1]))\n\t\t\t\telse:\n\t\t\t\t\tdist_from_centre=np.linalg.norm(position_on_lens,axis=1)\n\t\t\t\t\tROClist=get_ROC_asphere(pos,element1.asph_coeff[1],element1.ROC[1])\n\t\t\t\t\tangles = np.arcsin(np.sin(angle)*(indexfract))+position_on_lens*((nin-nout)/(nout*element1.ROC[1]))\n\t\t\telif hasattr(element2,\"ROC\"): #check if second element is lens, if yes use front surface ROC of element2\n\t\t\t\tposition_on_lens=(pos-element2.position)[:,0:2]\n\t\t\t\tif not element2.asphere:\t\t\t\t\t\n\t\t\t\t\t# print(np.mean(position_on_lens))\n\t\t\t\t\tangles = np.arcsin(np.sin(angle)*(indexfract))+position_on_lens*((nin-nout)/(nout*element2.ROC[0]))\n\t\t\t\telse:\n\t\t\t\t\tdist_from_centre=np.linalg.norm(position_on_lens,axis=1)\n\t\t\t\t\tROClist=get_ROC_asphere(pos,element2.asph_coeff[0],element2.ROC[0])\n\t\t\t\t\tangles = np.arcsin(np.sin(angle)*(indexfract))+position_on_lens*((nin-nout)/(nout*element2.ROC[0]))\n\t\t\telse:#if not lenses, use snells law\n\t\t\t\tangles = np.arcsin(np.sin(angle)*(indexfract))\n\n\t\t\treturn angles\n\t\t\t\n\t\telse:\n\t\t\treturn angle\n\n\t\t\n\n\tdef translate(pos,angle,lam,optic_element):\n\t\t\"method for translating the rays throught the objects\"\n\n\t\tif not pos[0][2]>optic_element.bsurf: #check if ray is not already past this surface due to starting position\n\t\t\treturn optic_element.translate(pos,angle,lam)\n\t\telse:\n\t\t\treturn pos\n\t\t\n\t\tif debug:\n\t\t\tprint(\"I traced {} in {} to {}\".format(ray,optic_element,ray.position))\n\n\n\t\n\t\t\n\n\tdef get_SPDC_rayset_adv(self,Ntot=1,nr_crystals=1,pumpray=[],pump_waist=[0,0],pump_focus=[0,0],cutangle=28.8*np.pi/180,l_min=0,l_max=0,theta_min=0,theta_max=0,factor=0.1):\n\t\t\"This is a complex method that generates the starting positions/angles/wavelenght/polarization according to the Type-1 phasematching conditions in BBO\"\n\t\t#checks if the amount of trials is smaller than the maximum per loop: 10M.\n\t\tif Ntot<10000000:\n\t\t\tN=Ntot\n\t\telse:\n\t\t\tN=10000000\n\n\t\tNumber_of_cycles = int(ceil(Ntot/N)) #Number of cyles of 20M\n\n\t\tfinal_list = []\t\t\t\t\t\t#Initialization of list to store the cycles\n\n\t\tlpump=pumpray.wavelength \t\t\t#setting the wavelength and waists of the pump\n\t\tw0x=pump_waist[0]\n\t\tw0y=pump_waist[1]\n\n\t\tzR_pump_x=(np.pi*w0x**2)/(lpump*1e-6)#calculating the rayleigh ranges in x and y\n\t\tzR_pump_y=(np.pi*w0y**2)/(lpump*1e-6)\n\t\t\n\n\t\tfor i in range(Number_of_cycles):\n\n\t\t\t#generating large arrays of random numbers\n\n\t\t\trand_u = np.random.uniform(0,1,N)\t\t\t\t\t\t\t\t#used for calculating position along walkoff path of ray\n\t\t\t\n\t\t\trandN_l\t\t= np.random.uniform(l_min,2*lpump,N)\t\t\t\t#generating random wavelengths for singal_min to 2*pump wavelength (phasefunction is symmetric in 2*pump wavelength)\n\t\t\trandN_theta\t= np.random.uniform(theta_min,theta_max,N)\t\t\t#random opening angles \n\t\t\trand_check\t= np.random.uniform(0,1,N)\t\t\t\t\t\t\t#the random numbers used in the check for the rejection sampling (could these be reused?)\n\n\t\t\treturn_list=[]\n\n\t\t\tpumpray.position=np.array([0,0,0])\t\t\t\t\t\t\t\t#For all the cycles the pump starts at 0,0,0\n\n\t\t\tfor i in range(nr_crystals):#looping through all the crystals where downconversion happens\n\t\t\t\t\n\t\t\t\tcrystal=self.setup.crystals[i]\t#\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tpumpray.position = np.array([pumpray.position[0],pumpray.position[1],crystal.fsurf]) #downconversion begins at frontsurface\n\t\t\t\tw_beg=pumpray.position\n\n\t\t\t\tw_end=w_beg+crystal.getwalkoff_ray(pumpray)+np.array([0,0,crystal.thickness])\t\t#downconversion ends at begin + walkoff + thickness\n\t\t\t\tstart_pos = np.repeat(np.array([w_beg]),N,axis=0) + np.outer(rand_u,(w_end-w_beg))\t#the random starting pos is just a linear combination of these\n\n\t\t\t\t\n\t\t\t\tstart_z = (start_pos.T)[2]\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#the starting positions along the z axis\n\n\t\t\t\t#\"Introduce effects of gaussian pump\"\n\t\t\t\t\n\t\t\t\twzx,wzy = w0x*np.sqrt(1+((start_z-pump_focus[0])/zR_pump_x)**2),w0y*np.sqrt(1+((start_z-pump_focus[1])/zR_pump_y)**2)\t#for all z, there is a beam waist\n\n\t\t\t\tsx,sy=wzx,wzy\t\t\t#this beam waist is the standard deviation of the gaussian used for further sampling\n\t\t\t\n\t\t\t\tgauss_x=np.random.randn(1,N)*sx\t#random x position due to gaussian pump\n\t\t\t\tgauss_y=np.random.randn(1,N)*sy#random y position due to gaussian pump\n\n\t\t\t\tgauss_xy=np.concatenate((gauss_x,gauss_y)).T\n\n\t\t\t\tzpos_rel_wx=np.where(np.abs(-pump_focus[0]+start_z)>1e-9,(-pump_focus[0]+start_z),1e-9)\t#we want the z pos with respect to focus. np.where is used to remove all values smaller than 1e-9 to avoid dividing by 0\n\t\t\t\tzpos_rel_wy=np.where(np.abs(-pump_focus[1]+start_z)>1e-9,(-pump_focus[1]+start_z),1e-9)\n\n\t\t\t\tstart_angles_gauss=np.concatenate((-np.arcsin(gauss_x/(zpos_rel_wx+((zR_pump_x)**2)/(zpos_rel_wx))),-np.arcsin(gauss_y/(zpos_rel_wy+((zR_pump_y)**2)/(zpos_rel_wy))))).T #for ever (x,y) we can calculate propagation angles (a,b) using ROC(z) of the gaussian beam\n\n\t\t\t\t#\"Sampling the phasefunction for the N randomly generated angles. the weight will later be used to accept or reject samples. Factor is number <1, the smaller this number the smoother the distribution, but the more trys needed\"\n\t\t\t\t#TODO: need to choose which angle (a,b) it should add to the phasematching (currently always chooses a but it depends on crystal orientation)\n\t\t\t\tweight=factor*phasefunction_vec(l_list=randN_l,theta_list=randN_theta,lpump=lpump,cutangle=cutangle+(start_angles_gauss.T)[0],W = w0x)\n\n\t\t\t\t#reshape the gaussian coordinates x,y to the format [x,y,0] \n\t\t\t\tgauss_pad=np.zeros(start_pos.shape)\n\t\t\t\tgauss_pad[:gauss_xy.shape[0],:gauss_xy.shape[1]]=gauss_xy\n\n\t\t\t\t#put all the parameters so far (position, angles, wavelenght, opening_angle) in an array with length 100.000.0000 so we can select all the succesfull ones at once\n\t\t\t\tsampled_params=np.concatenate((start_pos+gauss_pad,start_angles_gauss,np.array([randN_l]).T,np.array([randN_theta]).T),axis=1)#list of important simulation parameters\n\n\t\t\t\tfinal_params=sampled_params[np.where(weight>rand_check)]#filters the sampled_params for the succesfully drawn samples\n\t\t\t\tNsuc=len(final_params)\n\n\t\t\t\t#extract the (position, angles, wavelenght, opening_angle) from the succesfull ones \n\t\t\t\t[ray_start,ray_angle,ls,opening_angle]=[final_params[:,0:3].T,final_params[:,3:5].T,final_params[:,5:6].T,final_params[:,6:7].T]\n\n\t\t\t\t#get idler wavelengths\n\t\t\t\tli = ls*(lpump)/(ls-lpump)\n\t\t\t\t\n\t\t\t\t#calculate actual propagation angles of signal and idler (rotationally symmetric in space due to ordidnary polarization)\n\t\t\t\trand_nr = np.random.uniform(0,1,len(final_params))\n\t\t\t\tazim=np.cos(rand_nr*np.pi)*opening_angle\n\t\t\t\thoriz=np.sign(azim)*np.sign(opening_angle)*np.sqrt(opening_angle**2 - azim**2)\n\n\t\t\t\tprop_angles=np.concatenate((azim,horiz)).T\n\t\t\t\t\n\n\t\t\t\t#Assembling the final list of parameters, combining all the angular and spatial effects\t\t\t\t\n\n\t\t\t\t#TODO:Need to automatically decide on polarization, depends on wavematching/crystal orientation\n\t\t\t\tSrays=[ray_start.T,(ray_angle.T+prop_angles),ls.T,np.full((Nsuc,1),'V',dtype=str)]\n\t\t\t\tIrays=[ray_start.T,(ray_angle.T-prop_angles),li.T,np.full((Nsuc,1),'V',dtype=str)]\n\t\t\t\t\n\t\t\t\treturn_list.append(Srays)\n\t\t\t\treturn_list.append(Irays)\n\n\t\t\t\tpumpray.position += crystal.getwalkoff_ray(pumpray) #update pumpray position for next crystal\n\n\t\t\tfinal_list.append(return_list) #update all the cycles\n\t\t\n\t\t\n\t\t#Create empty list the size of the list we want to return\n\t\tthe_result_list= [[[] for i in range(4)] for j in range(4)]\n\t\t\n\t\t#loop through all the elements of the empty list, filling them with the result of the individual cycles \n\t\t#THIS IS SLOW AND UGLY BUT I CANT FIND A BETTER WAY, maybe np.concatenate(final_list,axis=?)\t\n\t\tfor i in range(4):\n\t\t\tfor j in range(4):\n\t\t\t\tthe_result_list[i][j]=np.concatenate(tuple([final_list[k][i][j] for k in range(Number_of_cycles)]))\n\t\t\n\t\treturn the_result_list\n\n\n\tdef filter_results(self,fibre_pos=np.array([0,0,0]),core_diam=0,Num_Ap=0):\n\t\t\"Filter function giving singles and coincidences that enter the fibre at fibre_pos with specified dimensions\"\n\n\t\tfilter_cond_match_list=[]\n\t\tself.singles=[]\n\t\tself.coincidences=[]\n\n\t\tfor ray_set in self.complete_results:\n\t\t\tpos = ray_set[0]\n\t\t\tangle = ray_set[1]\n\n\t\t\tfilter_cond_match=self.filter_func(pos,angle,fibre_pos=fibre_pos,core_diam=core_diam, Num_Ap = Num_Ap)\n\t\t\tfilter_cond_match_list.append(filter_cond_match)\n\n\t\t\tsingles_list = [ray[np.where(filter_cond_match)] for ray in ray_set]\n\t\t\tself.singles.append(singles_list)\n\n\t\tself.coincidences =[[x[np.where(np.logical_and(filter_cond_match_list[2*round(i/2.1)],filter_cond_match_list[2*round(i/2.1)+1]))] for x in ray_set] for i,ray_set in enumerate(self.complete_results)] #2*round(i/2.1) does (0,1,2,3) -> (0,0,2,2) to compare signal and idler\n\n\n\tdef filter_func(self,pos,angle,fibre_pos=np.array([0,0,0]),core_diam=0,Num_Ap=0):\n\n\t\t\"method called by filter_results to check if the rays fall in fibre pos with angle < NA\"\n\t\tcore_dist_check=np.linalg.norm(pos-fibre_pos,axis=1) 0:\n\t\t\t\tself.elements.insert(0,Optic(name=\"Air_Begin\",material=\"Air\",position=np.array([0,0,(self.elements[0].fsurf)/2]),thickness=self.elements[0].fsurf))\n\t\t\tself.elements.insert(-1,Optic(name=\"Air_End\",material=\"Air\",position=np.array([0,0,self.elements[0].bsurf+2.5]),thickness=5))\n\n\t\telse:\n\t\t\tfor i in range(self.nr_elements-1,0,-1):\n\t\t\t\tgap = self.elements[i].fsurf - self.elements[i-1].bsurf\n\t\t\t\tif gap > 0:\n\t\t\t\t\tself.elements.insert(i,Optic(name=\"Air_after_{}\".format(self.elements[i].name),material=\"Air\",position=np.array([0,0,self.elements[i-1].bsurf+0.5*(self.elements[i].fsurf-self.elements[i-1].bsurf)]),thickness=gap))\n\t\t\tif self.elements[0].fsurf > 0:\n\t\t\t\tself.elements.insert(0,Optic(name=\"Air_Begin\",material=\"Air\",position=np.array([0,0,(self.elements[0].fsurf)/2]),thickness=self.elements[0].fsurf))\n\t\t\tself.elements.append(Optic(name=\"Air_End\",material=\"Air\",position=np.array([0,0,self.elements[-1].bsurf+2.5]),thickness=5))\n\t\n\tdef visualize(self,centre = [0,0,0]):\n\t\tboxes=[]\n\t\tfor elem in self.elements:\n\t\t\tboxes.append(box(pos=vec(0-centre[0],0-centre[1],elem.position[2]-centre[2]),size=vec(2,2,elem.thickness),opacity=0.3,color=elem.get_colour()))\n\t\treturn boxes \n\n\tdef group(self):\n\t\tlis=self.elements\n\t\tself.grouped_elements = [[lis[i],lis[i+1]] for i in range(0,len(lis)-1,1)]\n\n\nclass Ray(object):\n\t\"All instances of this class are monochromatic rays of light, resembling individual photons\"\n\n\tdef __init__(self,**k):\n\t\ttry:\n\t\t\tself.name \t\t\t= k.pop('name',\"ray\")\n\t\t\tself.position \t\t= np.array(k.pop('position'))\n\t\t\tself.angles \t\t= k.pop('angles')\n\t\t\tself.polarization\t= k.pop('polarization')\n\t\t\tself.wavelength\t\t= k.pop('wavelength')\n\t\t\tself.path\t\t\t= [self.position]\n\t\t\tself.time\t\t\t= [0]\n\t\texcept KeyError:\n\t\t\tprint('Please provide at least a name, position, angles, polarization and wavelength')\n\n\tdef showRay(self):\n\t\tprint(\"Position: {}, Angles: {}, Polarization: {}, Wavevlength: {}\".format(self.position,self.angles,self.polarization,self.wavelength))\n\n\tdef arrivaltime(self):\n\t\treturn np.sum(self.time)\n\n\nclass Optic(object):\n\t\"All instances of this class used to build a virtual setup that resembles the SPDC source that do NOT EMIT photons, but only act on them. E.G. non-linear crystals/lenses/HWP etc.\"\n\t\n\tdef __repr__(self):\n\t\treturn \"Optic_{}\".format(self.name)\n\n\tdef __init__(self,**k):\n\t\ttry:\n\t\t\tself.name \t\t= k.pop('name');\n\t\t\tself.material\t= k.pop('material',None)\n\t\t\tself.position\t= np.array(k.pop('position'))\n\t\t\tself.thickness \t= k.pop('thickness',0)\n\t\t\tself.fsurf \t\t= self.position[2] - 0.5*self.thickness\n\t\t\tself.bsurf \t\t= self.position[2] + 0.5*self.thickness\n\t\texcept KeyError:\n\t\t\tprint(\"Please provide at least a name, material, position to initiate an Optics object\")\n\n\tdef calcsurfaces(self):\n\t\tself.fsurf = self.position[2] - 0.5*self.thickness\n\t\tself.bsurf = self.position[2] + 0.5*self.thickness\n\n\tdef set_pol_flag(self,pol):\n\t\tself.ray_pol = pol\n\t\n\n\tdef showObject(self):\n\t\tprint (\"Name: {}, Material: {}, Position: {}\".format(self.name,self.material,self.position))\n\n\tdef get_colour(self):\n\t\t\"Gets colour for visualization as RGB Triplet\"\n\t\tcolour_dict={'BBO':vec(0,0,1),'YVO4':vec(0,1,0),'Air':vec(1,1,1)}\n\t\t\n\t\tcolour=colour_dict.pop(self.material,vec(1,1,1))\n\n\t\treturn colour\n\n\tdef getn(self,angle,lam):\n\n\t\tlamsq=(lam*1e-3)**-2\n\n\t\treturn 1+(0.05792105)/(238-lamsq)+(0.00167917)/(57.362-lamsq)\n\n\tdef getdn(self,angle,lam):\n\n\t\treturn -(3358.34)/(((57.362-(1e6)/lam**2)**2)*lam**3)-(115842)/(((238-(1e6)/lam**2)**2)*lam**3)\n\n\tdef translate(self,pos,angle,lam):\n\t\treturn (pos + np.array([np.tan(angle[:,0])*(self.thickness-(pos[:,2]-self.fsurf)),np.tan(angle[:,1])*(self.thickness-(pos[:,2]-self.fsurf)),(self.thickness-(pos[:,2]-self.fsurf))]).T)\n\n\nclass Crystal(Optic):\n\t\"All instances of this class (child of Optics), are objects that are (non-linear) crystals that act on the photons. They are all rectangular boxes that are made of a birefringent material\"\n\t\n\tmaterials \t=\t[\"BBO\",\"YVO4\"]\n\n\tselm_coeff \t= {\t\"BBO\" \t\t: \t[2.7359, 0.01878, 0.01822, 0.01354, 2.3753, 0.01224, 0.01667, 0.01516],\n \t\t\t\t\t\"YVO4\" \t\t: \t[3.77834, 0.069736, 0.04724, 0.0108133, 4.59905, 0.110534, 0.04813, 0.0122676]\n \t\t\t\t}\n\n\tdef __init__(self,**k):\n\t\ttry:\n\t\t\tself.orientation \t= k.pop('orientation')\n\t\t\tself.cutangle\t\t= k.pop('cutangle')\n\t\texcept KeyError:\n\t\t\tprint(\"Please provide at least orientation and cutangle to initiate a Crystal object\")\n\t\t\n\t\tsuper(Crystal,self).__init__(**k)\n\n\tdef getn(self,angle,lam):\n\n\t\t\t\t\n\t\tc=self.selm_coeff[self.material]\n\t\tlamb=lam\n\n\t\tif self.ray_pol == \"H\":\n\t\t\tif self.orientation in {\"left\",\"right\"}:\n\t\t\t\treturn (c[0]+(c[1])/((lamb*1e-3)**2-c[2])-c[3]*(lamb*1e-3)**2)**0.5\n\n\t\t\telse:\n\t\t\t\tif self.orientation is \"up\":\n\t\t\t\t\treturn n_ext_effective(coeff = c,theta = angle[:,[0]] - self.cutangle,lam=lamb)\n\n\t\t\t\telif self.orientation is \"down\":\n\t\t\t\t\treturn n_ext_effective(coeff = c,theta = angle[:,[0]] + self.cutangle,lam=lamb)\n\n\t\telif self.ray_pol == \"V\":\n\t\t\tif self.orientation in {\"up\",\"down\"}:\n\t\t\t\treturn (c[0]+(c[1])/((lamb*1e-3)**2-c[2])-c[3]*(lamb*1e-3)**2)**0.5\n\t\t\telse:\n\t\t\t\tif self.orientation is \"left\":\n\t\t\t\t\treturn n_ext_effective(coeff = c,theta = angle[:,[1]] - self.cutangle,lam=lamb)\n\n\t\t\t\telif self.orientation is \"right\":\n\t\t\t\t\treturn n_ext_effective(coeff = c,theta = angle[:,[1]] + self.cutangle,lam=lamb)\n\t\n\t\n\tdef getdn(self,angle,lam):\n\t\t\t\t\t\n\t\tc=self.selm_coeff[self.material]\n\t\tlamb=lam\n\n\t\tif self.ray_pol == \"H\":\n\t\t\tif self.orientation in {\"left\",\"right\"}:\n\t\t\t\treturn dSellmeier(coeff=c[0:4],lam=lamb)\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tif self.orientation is \"up\":\n\t\t\t\t\treturn dn_ext_effective(coeff=c,theta=self.cutangle-angle[:,[0]],lam=lamb)\n\n\t\t\t\telif self.orientation is \"down\":\t\t\t\t\t\n\t\t\t\t\treturn dn_ext_effective(coeff=c,theta=self.cutangle+angle[:,[0]],lam=lamb)\n\t\t\t\t\t\n\t\n\t\telif self.ray_pol == \"V\":\n\t\t\tif self.orientation in {\"up\",\"down\"}:\t\t\t\t\n\t\t\t\treturn dSellmeier(coeff=c[0:4],lam=lamb)\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tif self.orientation is \"left\":\t\t\t\t\t\n\t\t\t\t\treturn dn_ext_effective(coeff=c,theta=self.cutangle-angle[:,[1]],lam=lamb)\n\t\t\t\t\t\n\n\t\t\t\telif self.orientation is \"right\":\t\t\t\t\t\n\t\t\t\t\treturn dn_ext_effective(coeff=c,theta=self.cutangle+angle[:,[1]],lam=lamb)\n\t\t\t\t\t\n\n\tdef getwalkoff(self,pos,angle,lam):\n\n\t\t\n\t\tc=self.selm_coeff[self.material]\n\t\tN=len(lam)\n\t\tw_ret=np.zeros((N,3))\n\t\t\t\n\t\tif self.ray_pol == \"H\":\n\t\t\tif self.orientation == \"up\":\n\t\t\t\tw = walkoff(theta=self.cutangle-angle[:,[0]],coeff=c,lam=lam,thickness=self.thickness-(pos[:,[2]]-self.fsurf))\n\t\t\t\tw_ret[:,[0]] = w\n\t\t\t\treturn w_ret\n\t\t\telif self.orientation == \"down\":\n\t\t\t\tw = -1*walkoff(theta=self.cutangle+angle[:,[0]],coeff=c,lam=lam,thickness=self.thickness-(pos[:,[2]]-self.fsurf))\n\t\t\t\tw_ret[:,[0]] = w\n\t\t\t\treturn w_ret\n\t\t\telse:\n\t\t\t\treturn w_ret\n\t\telif self.ray_pol == \"V\":\n\t\t\tif self.orientation == \"left\":\n\t\t\t\tw = walkoff(theta=self.cutangle-angle[:,[1]],coeff=c,lam=lam,thickness=self.thickness-(pos[:,[2]]-self.fsurf))\n\t\t\t\tw_ret[:,[1]] = w\n\t\t\t\treturn w_ret\n\t\t\telif self.orientation == \"right\":\n\t\t\t\tw = -1*walkoff(theta=self.cutangle+angle[:,[1]],coeff=c,lam=lam,thickness=self.thickness-(pos[:,[2]]-self.fsurf))\n\t\t\t\tw_ret[:,[1]] = w\n\t\t\t\treturn w_ret\n\t\t\telse:\n\t\t\t\treturn w_ret\n\n\tdef getwalkoff_ray(self,ray):\n\n\t\tif not isinstance(ray,Ray):\n\t\t\traise Exception(\"Please provide me with a ray to calculate the walkoff for!\")\n\n\t\tc=self.selm_coeff[self.material]\n\n\t\t\t\n\t\tif ray.polarization == \"H\":\n\t\t\tif self.orientation == \"up\":\n\t\t\t\tw = walkoff(theta=self.cutangle-ray.angles[0],coeff=c,lam=ray.wavelength,thickness=self.thickness-(ray.position[2]-self.fsurf))\n\t\t\t\treturn np.array([w,0,0])\n\t\t\telif self.orientation == \"down\":\n\t\t\t\tw = -1*walkoff(theta=self.cutangle+ray.angles[0],coeff=c,lam=ray.wavelength,thickness=self.thickness-(ray.position[2]-self.fsurf))\n\t\t\t\treturn np.array([w,0,0])\n\t\t\telse:\n\t\t\t\tw = 0\n\t\t\t\treturn np.array([0,w,0])\n\t\telif ray.polarization == \"V\":\n\t\t\tif self.orientation == \"left\":\n\t\t\t\tw = walkoff(theta=self.cutangle-ray.angles[1],coeff=c,lam=ray.wavelength,thickness=self.thickness-(ray.position[2]-self.fsurf))\n\t\t\t\treturn np.array([0,w,0])\n\t\t\telif self.orientation == \"right\":\n\t\t\t\tw = -1*walkoff(theta=self.cutangle+ray.angles[1],coeff=c,lam=ray.wavelength,thickness=self.thickness-(ray.position[2]-self.fsurf))\n\t\t\t\treturn np.array([0,w,0])\n\t\t\telse:\n\t\t\t\tw = 0\n\t\t\t\treturn np.array([0,w,0])\n\n\n\tdef translate(self,pos,angle,lam):\n\t\t#returns the updated position array\n\t\twalkoff=self.getwalkoff(pos,angle,lam)\n\t\n\t\treturn (walkoff + pos + np.array([np.tan(angle[:,0])*(self.thickness-(pos[:,2]-self.fsurf)),np.tan(angle[:,1])*(self.thickness-(pos[:,2]-self.fsurf)),(self.thickness-(pos[:,2]-self.fsurf))]).T)\n\t\n\nclass Lens(Optic):\n\t\"All instances of this class (Child of optics) are objects that are curved surfaces (spherical) that act on the photons. One can have two different Radii of Curvature, so this field should be a vector\"\n\t\n\tmaterials \t= [\"N-SF6HT\",\"N-LAK22\"]\n\n\tselm_coeff \t= {\t\"N-SF6HT\" \t:\t[1.77931763, 0.0133714182, 0.338149866, 0.0617533621, 2.08734474, 174.01759],\n\t\t\t\t\t\"N-LAK22\" \t:\t[1.14229781, 0.00585778594, 0.535138441, 0.0198546147, 1.04088385, 100.834017]\n \t\t\t\t\t}\n\n\tdef __init__(self,**k):\n\t\tsuper(Lens,self).__init__(**k)\n\t\ttry:\n\t\t\tself.ROC \t\t= k.pop('ROC')\n\t\t\tself.centre \t= k.pop('centre')\n\t\t\tself.position \t= self.position+self.centre\n\t\t\tself.asphere\t= k.pop('apshere',False)\n\t\t\tif self.asphere:\n\t\t\t\tself.asph_coeff = k.pop('asph_coeff')\n\n\t\texcept KeyError:\n\t\t\tprint(\"Please provide at least ROC (Radii of Curvature) and centre position to initiate a Lens object, aspheric lenses need asph_coeff\")\n\t\n\tdef achromat(position=[],centre=[],f=0):\n\t\t\"Create achromat at position\"\n\t\tlens1=Lens(name='Lens1',material =\"N-SF6HT\",orientation=None,position=np.array(position)+np.array([0,0,-2.3/2]),thickness=2.3,ROC=[13.5,-10.6],centre=[centre[0],centre[1],0])\n\t\tlens2=Lens(name='Lens2',material =\"N-LAK22\",orientation=None,position=np.array(position)+np.array([0,0,+1.3/2]),thickness=1.3,ROC=[-10.6,-47.8],centre=[centre[0],centre[1],0])\n\t\tairf = Optic(name='Air_f',material=\"Air\",orientation = None, position = np.array(position)+np.array([0,0,1.3+(f-1.3)/2]),thickness=f-1.3)\n\n\t\treturn [lens1,lens2,airf]\n\n\tdef getn(self,angle,lam):\n\t\t\n\t\tc=self.selm_coeff[self.material]\n\t\tlamb=(1e-3)*lam\n\n\t\treturn (1+(c[0]*(lamb**2))/(lamb**2-c[1])+(c[2]*(lamb**2))/(lamb**2-c[3])+(c[4]*(lamb**2))/(lamb**2-c[5]))**(0.5)\n\n\tdef getdn(self,angle,lam):\n\n\t\tc=self.selm_coeff[self.material]\n\t\tlamb=lam*1e-3\n\t\n\t\treturn 1e-6*lamb*((-(c[0]*c[1])/(c[1]-lamb**2)**2-(c[2]*c[3])/(c[3]-lamb**2)**2-(c[4]*c[5])/(c[5]-lamb**2)**2)/np.sqrt(1+(c[0]*lamb**2)/(-c[1]+lamb**2)+(c[2]*lamb**2)/(-c[3]+lamb**2)+(c[4]*lamb**2)/(-c[5]+lamb**2)))\n\n\tdef translate(self,pos,angle,lam):\n\t\t\n\t\treturn (pos + np.array([np.tan(angle[:,0])*(self.thickness-(pos[:,2]-self.fsurf)),np.tan(angle[:,1])*(self.thickness-(pos[:,2]-self.fsurf)),(self.thickness-(pos[:,2]-self.fsurf))]).T)\n\t\n\tdef get_ROC_asphere(self,pos,coeffs,ROC):\n\t\t\"Calculate the ROC of an asphere, depending on the position of the ray to the lens\"\n\t\tc=coeffs\n\t\tY=np.norm(pos[0:2]-self.position[0:2],axis=1)\n\n\t\tsag=(Y**2)/(ROC*(1+np.sqrt(1-((1+c[0])*Y**2)/ROC**2)))+(c[1])*Y**2+(c[2])*Y**4+(c[3])*Y**6+(c[4])*Y**8+(c[5])*Y**10\n\n\t\treturn 0.5*sag+Y**2/(2*sag)\n\n\nclass HWP(Optic):\n\t\"All instances of this class (Child of optics) are objects that perform the mathematical operation of H->V and V->H for a certain wavelenth range\"\n\n\tdef __init__(self,**k):\n\t\ttry:\n\t\t\tself.cutoff=k.pop('cutoff')\n\t\texcept KeyError:\n\t\t\tprint(\"Please provide the cutoff wavelenght in nm for the HWP\")\n\n\t\tsuper(HWP,self).__init__(**k)\n\n\tdef show_cutoff(self):\n\t\tprint(\"I act on a waveplate for photons with wavelength above {}nm\".format(self.cutofff))\n\n\tdef propagate(self,pos,angle,lam):\n\n\t\tif np.all(lam > self.cutoff):\n\t\t\tif self.ray_pol == \"H\":\n\t\t\t\tself.ray_pol = \"V\"\n\t\t\telse:\n\t\t\t\tself.ray_pol = \"H\"\n\n\tdef translate(self,pos,angle,lam):\n\t\tself.propagate(pos,angle,lam)\n\n\t\treturn pos\n\t\t\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":45480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"576463939","text":"poll = {}\n\nwhile True:\n\n name = input('Could you gives us your name before we begin: ')\n\n if name == 'quit':\n break\n\n response = input('If you could go anywhere in this world,\\\n where would you go?\\n')\n \n \n print('\\n\\tIf you want to stop giving input type exit or quit')\n\n poll[name] = response\n\nfor key, value in poll.items():\n print('{} would love to visit: {}.'.format(key, value))\n \n","sub_path":"ex7-/7-10.py","file_name":"7-10.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"615324624","text":"from django.views.generic import ListView, DetailView\nfrom django.urls import reverse\nfrom django.http import Http404\nfrom django.shortcuts import render, redirect\nfrom . import models\n\n\nclass HomeView(ListView):\n \"\"\" HomeView Definition\"\"\"\n\n model = models.Room\n paginate_by = 10\n paginate_orphans = 5\n ordering = \"created\"\n\n\nclass RoomDetail(DetailView):\n model = models.Room\n template_name = \"\"\n\n\ndef room_detail(request, pk):\n try:\n room = models.Room.objects.get(pk=pk)\n return render(request, \"rooms/detail.html\", context={\"room\": room})\n except models.Room.DoesNotExist:\n raise Http404()\n # return redirect(reverse(\"core:home\"))\n","sub_path":"rooms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"27188960","text":"def is_sub(s):\n if len(s) >= 1:\n for word in s:\n if (s.count(word) > 1):\n return False\n return True\n else:\n return False\n\n\ndef get_substring(s):\n l = len(s)\n min = 3\n max = 0\n lst = list()\n for i in range(0, l):\n for j in range(i + 1, l + 1):\n sub = s[i:j]\n # print(sub)\n if is_sub(sub):\n if len(sub) > max:\n # print(sub)\n max = len(sub)\n lst.append(sub)\n if lst == []:\n return -1\n else:\n return lst[-1]\n\ns = input()\nss=get_substring(s)\nprint(len(ss))\n","sub_path":"SUMMER FS/14 may/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"78064069","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.interpolate as interpolate\nimport pickle\nimport my.util\n\n\n# 시험체별 기울기비 - 1 : 3.375 : 8 : 15.625 : 125 = h20:h30:h40:h50:h100\n\nwith open('data_new.pickle', 'rb') as f:\n data_new = pickle.load(f)\nwith open('elastic_limits.pickle', 'rb') as f:\n elastic_limits = pickle.load(f)\n\ncolor = {20: 'r', 30: 'g', 40: 'b', 50: 'c', 100: 'm'}\n\n\n# 하중-처짐 곡선을 총 3 부분으로 구성하고, 각 부분은 10개의 점으로 구성\n# 1. 선형 상향\n# 2. 비선형 상향\n# 3. 비선형 하향\n\nfor thk in data_new:\n fig, ax = plt.subplots(1, 1)\n for no in data_new[thk]:\n x = data_new[thk][no]['defl']\n y = data_new[thk][no]['load']\n indices = [0, elastic_limits[thk][no], np.argmax(y), y.size - 1]\n ax.plot(x, y, '.-')\n ax.plot(x[indices], y[indices], 'ro')\n ax.grid()\n plt.show()\n\n\nxymean = dict()\nndiv = 10\nnpt = 3 * ndiv + 1\nfor thk in data_new:\n xymean[thk] = dict()\n xymean[thk]['defl'] = np.zeros(npt)\n xymean[thk]['load'] = np.zeros(npt)\n\n plt.figure()\n for no in data_new[thk]:\n xymean[thk][no] = {'defl': np.zeros(npt), 'load': np.zeros(npt)}\n\n xy = np.loadtxt('T{:03d}({:1d}).csv'.format(thk, no), delimiter=',', skiprows=1, usecols=(1, 2))\n iis = my.util.get_increasing_index(xy[:, 0])\n xy = xy[iis, :]\n spl = interpolate.splrep(xy[:, 0], xy[:, 1], k=1)\n\n ids = [0, elastic_limits[thk][no], np.argmax(xy[:, 1]), xy.shape[0] - 1]\n xy4o = np.zeros((npt, 2))\n for i in range(0, 3):\n ii = np.s_[ids[i]:(ids[i + 1] + 1)]\n x = np.linspace(xy[ids[i], 0], xy[ids[i + 1], 0], ndiv + 1)\n y = interpolate.splev(x, spl, ext=1)\n xy4o[(i * ndiv):((i + 1) * ndiv + 1), 0] = x\n xy4o[(i * ndiv):((i + 1) * ndiv + 1), 1] = y\n\n xymean[thk][no]['defl'] = xy4o[:, 0]\n xymean[thk][no]['load'] = xy4o[:, 1]\n xymean[thk]['defl'] += xy4o[:, 0]\n xymean[thk]['load'] += xy4o[:, 1]\n# plt.plot(xy4o[:, 0], xy4o[:, 1], '.-')\n\n xymean[thk]['defl'] = xymean[thk]['defl'] / len(list(data_new[thk]))\n xymean[thk]['load'] = xymean[thk]['load'] / len(list(data_new[thk]))\n plt.plot(xymean[thk]['defl'], xymean[thk]['load'], 'ko-', markerfacecolor='None')\n plt.grid()\n plt.show()\n\n\nfig, ax = plt.subplots()\nfor thk in xymean:\n ax.plot(xymean[thk]['defl'], xymean[thk]['load'], 'ko-', markerfacecolor='None')\nax.grid()\nplt.show()\n\nwith open('data-mean.pickle', 'wb') as f:\n pickle.dump(xymean, f)\n\n\n# 초기 구성한 포인트\n# indices[20][1] = [0, 258, 1497, 2532]\n# indices[20][2] = [0, 128, 675, 1186]\n# indices[20][3] = [0, 119, 682, 1006]\n# indices[30][1] = [0, 138, 471, 1126]\n# indices[30][2] = [0, 143, 560, 1074]\n# indices[30][3] = [0, 144, 623, 1233]\n# indices[40][1] = [0, 155, 553, 1072]\n# indices[40][2] = [0, 174, 502, 1126]\n# indices[40][3] = [0, 173, 537, 1138]\n# indices[40][4] = [0, 175, 530, 1055]\n# indices[50][1] = [0, 197, 415, 1038]\n# indices[50][2] = [0, 195, 456, 1027]\n# indices[50][3] = [0, 188, 401, 1135]\n# indices[100][1] = [0, 256, 520, 947]\n# indices[100][2] = [0, 159, 301, 827]\n# indices[100][3] = [0, 156, 327, 909]\n","sub_path":"02 adjust-data/step4_get_mean_curve.py","file_name":"step4_get_mean_curve.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"515357244","text":"import numpy as np\n\nmean = [np.array([0] * 28 * 28)] * 10 # init\nvariance = [np.matrix([[0] * 28 * 28] * 28 * 28)] * 10\n\nw = [np.array([0] * 28 * 28)] * 10\nw0 = [0] * 10\n\n\ndef train():\n with open(\"train-labels.idx1-ubyte\", mode='rb') as trainLabelFile:\n with open(\"train-images.idx3-ubyte\", mode=\"rb\") as trainImageFile:\n trainLabelFile.seek(4) # jump over the magic number\n trainImageFile.seek(4)\n s1 = trainLabelFile.read(4) # the amount of items\n s2 = trainImageFile.read(4)\n number = int.from_bytes(s1, byteorder=\"big\")\n assert (number == int.from_bytes(s2, byteorder=\"big\")) # if the amount of images are equal\n\n number = int(number)\n rows = int.from_bytes(trainImageFile.read(4), byteorder=\"big\") # get rows and columns\n columns = int.from_bytes(trainImageFile.read(4), byteorder=\"big\")\n\n Images = [[0] * rows * columns] * number # data struct to save the data\n Labels = [0] * number\n\n for i in range(0, number): # get the data\n if i % 100 == 0:\n print(i)\n label = int.from_bytes(trainLabelFile.read(1), byteorder=\"big\")\n image = []\n for j in range(0, rows * columns):\n image.append(int.from_bytes(trainImageFile.read(1), byteorder=\"big\"))\n Labels[i] = label\n Images[i] = image\n\n total = [np.array([0] * rows * columns)] * 10 # init the total array\n totalVariance = [np.matrix([[0] * rows * rows] * columns * columns)] * 10\n\n for i in range(0, number): # get the mean\n if i % 100 == 0:\n print(i)\n label = Labels[i]\n total[label] = total[label] + Images[i]\n for i in range(0, 10):\n mean[i] = total[i] / number\n\n for i in range(0, number): # get the variance\n if i % 100 == 0:\n print(i)\n label = Labels[i]\n imageArray = np.array(Images[i])\n diff = imageArray - mean[label]\n diff.shape = (28 * 28, 1)\n totalVariance[label] = totalVariance[label] + diff.dot(np.transpose(diff))\n\n for i in range(0, 10):\n variance[i] = totalVariance[i] / number + variance[i]\n\n averageVariance = np.matrix([[0] * rows * rows] * columns * columns)\n for i in range(0, 10):\n averageVariance = averageVariance + variance[i]\n averageVariance = averageVariance / 10\n\n for i in range(0, 10):\n mean[i].shape = (28 * 28, 1)\n temp = np.linalg.pinv(averageVariance)\n w[i].shape = (28 * 28, 1)\n w[i] = temp.dot(mean[i])\n w0[i] = -0.5 * np.transpose(mean[i]).dot(temp).dot(mean[i])\n w[i] = np.transpose(w[i])\n\n\ndef test():\n with open(\"t10k-images.idx3-ubyte\", mode=\"rb\") as testImageFile:\n with open(\"t10k-labels.idx1-ubyte\", mode=\"rb\") as testLabelFile:\n testLabelFile.seek(4) # jump over the magic number\n testImageFile.seek(4)\n s1 = testLabelFile.read(4) # the amount of items\n s2 = testImageFile.read(4)\n number = int.from_bytes(s1, byteorder=\"big\")\n assert (number == int.from_bytes(s2, byteorder=\"big\")) # if the amount of images are equal\n\n number = int(number)\n rows = int.from_bytes(testImageFile.read(4), byteorder=\"big\") # get rows and columns\n columns = int.from_bytes(testImageFile.read(4), byteorder=\"big\")\n\n Images = [np.array([0] * rows * columns)] * number # data struct to save the data\n Labels = [0] * number\n\n for i in range(0, number): # get the data\n if i % 100 == 0:\n print(i)\n label = int.from_bytes(testLabelFile.read(1), byteorder=\"big\")\n image = []\n for j in range(0, rows * columns):\n image.append(int.from_bytes(testImageFile.read(1), byteorder=\"big\"))\n Labels[i] = label\n Images[i] = np.array(image)\n Images[i].shape = (28 * 28, 1)\n\n count = 0\n max_pos = 0\n count_every=[0]*10\n correct_every=[0]*10\n for i in range(0, number):\n max = float(\"-inf\")\n for j in range(0, 10):\n temp = w[j].dot(Images[i]) + w0[j]\n if temp > max:\n max = temp\n max_pos = j\n count_every[Labels[i]]+=1\n if max_pos == Labels[i]:\n count = count + 1\n correct_every[Labels[i]]+=1\n print(count / number)\n for i in range(0,10):\n print(\"the correctness of \"+str(i)+\" is \"+ str(correct_every[i]/count_every[i]))\n\n\nif __name__ == \"__main__\":\n train()\n test()\n","sub_path":"homework1/LDF.py","file_name":"LDF.py","file_ext":"py","file_size_in_byte":5094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"160797684","text":"with open('INGREDIENT.csv', 'r') as f:\n\twith open('INGREDIENT2.csv', 'w+') as f2:\n\t\twhile True:\n\t\t\tdata = f.readline()\n\t\t\tif not data:\n\t\t\t\tbreak\n\t\t\t\t\n\t\t\tdata = data.split(',')\n\t\t\tfor i in range(len(data)):\n\t\t\t\tdata[i] = data[i].replace(\",\", \"\")\n\n\t\t\tfor i in range(1, len(data)):\n\t\t\t\tf2.write(str(data[0]) + \",\" + data[i] + \"\\n\")\n\n","sub_path":"data/ingredient.py","file_name":"ingredient.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"599089430","text":"# -*- coding: utf-8 -*- \n# Author: bellawu\n# Date: 2021/3/8 15:18\n# File: vari_example.py\n# IDE: PyCharm\n\nimport tensorflow as tf\n\nstate = tf.Variable(0, name='counter')\none = tf.constant(1)\n\nnew_value = tf.add(state, one)\nupdate = tf.assign(state, new_value)\n\n# 如果定义Variable就一定要initialize\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as sess:\n sess.run(init)\n for _ in range(3):\n sess.run(update)\n print(sess.run(state))","sub_path":"base_tensorflow/vari_example.py","file_name":"vari_example.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"622647333","text":"\"\"\"\nFake It Til You Make It\n\"\"\"\nimport sys\nimport pygame\nfrom pygame.sprite import Group\nimport json\nfrom button import Button\nfrom settings import Settings\nimport display\nimport functions as gf\nfrom stats import Stats\nfrom player import Player\n\ndef run():\n\t#Initialize game, settings and create a screen object\n\tpygame.init()\t\n\tsettings = Settings()\n\tscreen_setup = display.build(settings)\n\tscreen = screen_setup[0]\n\tpygame.display.set_caption(\"Fake It Til You Make It\")\n\t\n\t#Change screen dims to match fullscreen dims\n\tsettings.screen_width = screen_setup[1]\n\tsettings.screen_height = screen_setup[2]\n\t\n\t#create variables for screen center\n\tscx = settings.screen_width/2\n\tscy = settings.screen_height/2\n\t\n\t#Make Main Menu\n\tbuttons = []\n\tplay_button = Button(settings, screen, \"NEW GAME\",\n\t\tscx-100, 500, 300,75,(0,0,0),None)\n\tquit_button = Button(settings, screen, \"QUIT\",\n\t\tscx-100, 600, 300,75,(0,0,0),None)\n\tbuttons.append(play_button)\n\tbuttons.append(quit_button)\n\t\n\t#Make Ingame Menu\n\tig_buttons = []\n\tinv_button = Button(settings, screen, \"INVENTORY\",\n\t\tsettings.screen_width*.2-100, 100,\n\t\t300,75,(0,0,0),None)\n\tcraft_button = Button(settings, screen, \"CRAFT\",\n\t\tsettings.screen_width*.35-100, 100,\n\t\t300,75,(0,0,0),None)\n\tbuild_button = Button(settings, screen, \"BUILD\",\n\t\tsettings.screen_width/2-100, 100,\n\t\t300,75,(0,0,0),None)\n\tcharacter_button = Button(settings, screen, \"CHARACTER\",\n\t\tsettings.screen_width*.65-100, 100,\n\t\t300,75,(0,0,0),None)\n\tmenu_button = Button(settings, screen, \"MENU\",\n\t\tsettings.screen_width*.8-100, 100,\n\t\t300,75,(0,0,0),None)\n\tig_buttons.append(inv_button)\n\tig_buttons.append(craft_button)\n\tig_buttons.append(build_button)\n\tig_buttons.append(character_button)\n\tig_buttons.append(menu_button)\n\t\n\t#Make Loot PIP menu\n\tlp_buttons = []\n\tlp_title = Button(settings, screen, \"\",\n\t\tscx-250, scy-200, 500,50,(0,0,0),None,20)\n\tlptake_button = Button(settings, screen, \"TAKE\",\n\t\tscx+25, scy-125, 200,50,(0,0,0),None,20)\n\tlpdesc_button = Button(settings, screen, \"\",\n\t\tscx+25, scy-50, 200,175,(0,0,0),None,10)\n\tlp_window = Button(settings, screen, \"\",\n\t\tscx-250, scy-150, 500,300,(100,100,100),None)\n\tlp_loot_window = Button(settings, screen, \"\",\n\t\tscx-225, scy-125, 200,250,(180,180,180),None)\n\tlp_loot = Button(settings, screen, \"\",\n\t\tscx-215, scy-115, 180,230,(250,250,250),None)\n\tlp_buttons.append(lp_title)\n\tlp_buttons.append(lp_window)\n\tlp_buttons.append(lptake_button)\n\tlp_buttons.append(lpdesc_button)\n\tlp_buttons.append(lp_loot_window)\n\tlp_buttons.append(lp_loot)\n\t\n\t#Create a stats instance\n\tstats = Stats(settings)\n\t\n\t#Create item groups\n\tplayer = Player(settings, screen)\n\tfurniture = Group()\n\titems = Group()\n\tloots = Group()\n\tcustomers = Group()\n\t\n\t#Create clock to stabilize framerate\n\tclock = pygame.time.Clock()\n\t\n\t#Initialize Global Variables\n\tday = 1\n\thour = 6\n\tminute = 0\n\t\n\twhile True:\n\t\tclock.tick(100)\n\t\tgf.check_events(\tsettings, screen, stats, buttons, \n\t\t\t\t\t\t\tig_buttons, lp_buttons, loots)\n\t\tgf.update_screen(\tsettings,screen, stats, buttons, ig_buttons, \n\t\t\t\t\t\t\tlp_buttons, player, loots)\nrun()\n\t\n","sub_path":"FITYMI.py","file_name":"FITYMI.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"136310634","text":"###############################################################\n# Modified from https://www.cnblogs.com/rxbook/p/7509530.html #\n# 脚本功能:根据视频或照片中的exif信息,按照日期重命名文件名 #\n###############################################################\nimport os\nimport time\nimport exifread\n\n\nMY_DATE_FORMAT = '%Y%m%d_%H%M%S'\n\n# SUFFIX_FILTER = ['.jpg', '.png', '.mpg', '.mp4', '.thm', '.bmp', '.jpeg', '.avi', '.mov']\nDELETE_FILTER = ['thumbs.db', 'sample.dat']\n\nVIDEO_LIST = ['.mp4', '.avi', '.mov']\nIMAGE_LIST = ['.jpg', '.png', '.mpg', '.thm', '.bmp', '.jpeg']\n# SUFFIX_FILTER = VIDEO_LIST + IMAGE_LIST\nSUFFIX_FILTER = ['.mp4']\n\n\ndef isFormatedFileName(filename):\n #判断是否已经是格式化过的文件名\n try :\n filename_nopath = os.path.basename(filename)\n f, e = os.path.splitext(filename_nopath)\n time.strptime(f, MY_DATE_FORMAT)\n return True\n except ValueError :\n return False\n\ndef isTargetedFileType(filename):\n #根据文件扩展名,判断是否是需要处理的文件类型\n filename_nopath = os.path.basename(filename)\n f, e = os.path.splitext(filename_nopath)\n if e.lower() in SUFFIX_FILTER :\n return True\n else :\n return False\n\ndef isDeleteFile(filename):\n #判断是否是指定要删除的文件\n filename_nopath = os.path.basename(filename)\n if filename_nopath.lower() in DELETE_FILTER :\n return True\n else :\n return False\n\ndef generateNewFileName(filename):\n #根据照片的拍照时间生成新的文件名(如果获取不到拍照时间,则使用文件的创建时间)\n try :\n if os.path.isfile(filename):\n fd = open(filename, 'rb')\n else :\n raise \"[%s] is not a file!\\n\" % filename\n except :\n raise \"unopen file [%s]\\n\" % filename\n\n data = exifread.process_file(fd)\n if data :\n #取得照片的拍摄日期\n try :\n t = data['EXIF DateTimeOriginal']\n #转换成 yyyymmdd_hhmmss的格式\n dateStr = str(t).replace(\":\", \"\")[: 10] + \"_\" + str(t)[11:].replace(\":\", \"\")\n except :\n pass\n\n #如果没有取得exif信息,则用图像文件的创建日期作为拍摄日期\n state = os.stat(filename)\n dateStr = time.strftime(MY_DATE_FORMAT, time.localtime(state[-2]))\n dirname = os.path.dirname(filename)\n filename_nopath = os.path.basename(filename)\n f, e = os.path.splitext(filename_nopath)\n if e.lower() in VIDEO_LIST:\n dateStr = 'VID_' + dateStr\n elif e.lower() in IMAGE_LIST:\n dateStr = 'IMG_' + dateStr\n newFileName = os.path.join(dirname, dateStr + e)\n return newFileName\n\ndef scandir(startdir):\n #遍历指定目录以及子目录,对满足条件的文件进行改名或删除处理\n os.chdir(startdir)\n for obj in os.listdir(os.curdir):\n if os.path.isfile(obj):\n if isTargetedFileType(obj) and isFormatedFileName(obj) == False :\n #对满足过滤条件的文件进行改名处理\n newFileName = generateNewFileName(obj)\n print(\"rename[%s] => [%s]\" % (obj, newFileName))\n os.rename(obj, newFileName)\n elif isDeleteFile(obj):\n #删除制定的文件\n print(\"delete[%s]: \" % obj)\n os.remove(obj)\n else :\n pass\n if os.path.isdir(obj):\n scandir(obj)\n os.chdir(os.pardir)\n\n\nif __name__ == \"__main__\" :\n path = r\"/Users/jackeroo/Desktop/Photos\"\n scandir(path)\n","sub_path":"Video_Photo_Rename_by_Date.py","file_name":"Video_Photo_Rename_by_Date.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"5106992","text":"# -*- coding: utf-8 -*-\r\nimport functools\r\nimport math\r\n\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch import nn\r\n\r\nfrom common.registry import registry\r\nfrom models.base_model import BaseModel\r\nfrom modules.layers import VGG_FeatureExtractor, ResNet_FeatureExtractor, AvgPooling_FeatureExtractor, SelfAttnLSTM_FeatureExtractor\r\nfrom modules.transformer import Transformer\r\nfrom transformers.modeling_bert import BertConfig\r\n\r\n@registry.register_model(\"ocr_transfm\")\r\nclass OCRTransfm(BaseModel):\r\n def __init__(self, config):\r\n super(OCRTransfm, self).__init__(config)\r\n self.Transfm_config = BertConfig(**self.config.transfm) #model config for ocr_transfm\r\n \r\n def build(self):\r\n self.backbone_transfm_modules = []\r\n self._build_feature_extractor()\r\n self._build_transformer()\r\n self._build_prediction()\r\n \r\n def _build_feature_extractor(self):\r\n backbone_map = {\"ResNet\": ResNet_FeatureExtractor, \"VGG\": VGG_FeatureExtractor}\r\n assert self.Transfm_config.backbone in backbone_map.keys(), f\"{self.Transfm_config.backbone} is not a supported visual feature extraction backbone\"\r\n self.vf_backbone = backbone_map[self.Transfm_config.backbone](3, self.Transfm_config.vf_dim) #input_channel: 3, output_channel: vf_dim\r\n self.backbone_transfm_modules.append({\"module\": self.vf_backbone, \"lr_scale\": self.Transfm_config.lr_ratio_backbone})\r\n backbone_holistic_map = {\"self_attn_LSTM\": SelfAttnLSTM_FeatureExtractor, \"avg_pooling\": AvgPooling_FeatureExtractor}\r\n self.holistic_backbone = backbone_holistic_map[self.Transfm_config.holistic_backbone](self.Transfm_config.vf_dim, self.Transfm_config.holistic_ndims)\r\n self.backbone_transfm_modules.append({\"module\": self.holistic_backbone, \"lr_scale\": self.Transfm_config.lr_ratio_holistic})\r\n \r\n def _build_transformer(self):\r\n \r\n self.transformer = Transformer(self.Transfm_config)\r\n self.backbone_transfm_modules.append({\"module\": self.transformer, \"lr_scale\": self.Transfm_config.lr_ratio_transformer})\r\n \r\n def _build_prediction(self):\r\n self.inter_linear1 = nn.Linear(self.Transfm_config.transfm_dims, self.Transfm_config.transfm_ntokens)\r\n \r\n def forward(self, sample_list):\r\n fwd_results = {}\r\n self._forward_feature_extractor(sample_list, fwd_results)\r\n self._forward_transformer_prediction(sample_list, fwd_results)\r\n results = {\"scores\": fwd_results[\"scores\"]} \r\n return results\r\n \r\n def _forward_feature_extractor(self, sample_list, fwd_results):\r\n img = sample_list.img_processed\r\n visual_features = self.vf_backbone(img)\r\n holistic_features = self.holistic_backbone(visual_features)\r\n fwd_results[\"visual_features\"] = visual_features\r\n fwd_results[\"holistic_features\"] = holistic_features\r\n \r\n def _forward_transformer_prediction(self, sample_list, fwd_results):\r\n if self.training:\r\n fwd_results[\"prev_inds\"] = sample_list.targets\r\n decoded_features = self.transformer(fwd_results[\"visual_features\"], fwd_results[\"holistic_features\"], fwd_results[\"prev_inds\"])\r\n fwd_results[\"decoded_features\"] = decoded_features[0]\r\n fwd_results[\"decoded_attns\"] = decoded_features[1] if self.Transfm_config.transfm_output_attns else None \r\n self._forward_prediction(sample_list, fwd_results)\r\n else:\r\n targets = torch.LongTensor(sample_list.targets)\r\n dec_step_num = targets.size(1)\r\n fwd_results[\"prev_inds\"] = torch.zeros_like(targets)\r\n fwd_results[\"prev_inds\"][:, 0] = targets[:, 0]\r\n for _ in range(dec_step_num):\r\n decoded_features = self.transformer(fwd_results[\"visual_features\"], fwd_results[\"holistic_features\"], fwd_results[\"prev_inds\"])\r\n fwd_results[\"decoded_features\"] = decoded_features[0]\r\n fwd_results[\"decoded_attns\"] = decoded_features[1] if self.Transfm_config.transfm_output_attns else None \r\n self._forward_prediction(sample_list, fwd_results)\r\n argmax_inds = fwd_results[\"scores\"].argmax(dim=-1)\r\n fwd_results[\"prev_inds\"][:, 1:] = argmax_inds[:, :-1] #transformer does not predict start_token, so fwd_results[\"scores\"][:, 0] is the score of the first non-start_token character\r\n \r\n def _forward_prediction(self, sample_list, fwd_results):\r\n scores = self.inter_linear1(fwd_results[\"decoded_features\"])\r\n fwd_results[\"scores\"] = scores #B x L x C \r\n \r\n def get_optimizer_parameters(self, config):\r\n optimizer_param_groups = []\r\n base_lr = config.optimizer.params.lr \r\n finetune_params_set = set()\r\n for m in self.backbone_transfm_modules:\r\n optimizer_param_groups.append({\"params\": list(m[\"module\"].parameters()), \"lr\": base_lr * m[\"lr_scale\"], })\r\n finetune_params_set.update(list(m[\"module\"].parameters()))\r\n remaining_params = [p for p in self.parameters() if p not in finetune_params_set]\r\n optimizer_param_groups.insert(0, {\"params\": remaining_params})\r\n return optimizer_param_groups\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n","sub_path":"models/ocr_transfm.py","file_name":"ocr_transfm.py","file_ext":"py","file_size_in_byte":5364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"212681008","text":"import logging.handlers\nimport os\n\n\nclass NoAdminNTEventLogHandler(logging.handlers.NTEventLogHandler):\n \"\"\"\n Modified version of the NTEventLogHandler that does not register the\n logger in the registry unless told to do so. This allows running the\n handler without administrator privileges.\n \"\"\"\n def __init__(self, appname, dllname=None, logtype=\"Application\",\n add_to_registry=False):\n logging.Handler.__init__(self)\n try:\n import win32evtlogutil, win32evtlog\n self.appname = appname\n self._welu = win32evtlogutil\n if not dllname:\n dllname = os.path.split(self._welu.__file__)\n dllname = os.path.split(dllname[0])\n dllname = os.path.join(dllname[0], r'win32service.pyd')\n self.dllname = dllname\n self.logtype = logtype\n if(add_to_registry):\n self._welu.AddSourceToRegistry(appname, dllname, logtype)\n self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE\n self.typemap = {\n logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,\n logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,\n logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,\n logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,\n logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,\n }\n except ImportError:\n print(\"The Python Win32 extensions for NT (service, event \"\\\n \"logging) appear not to be available.\")\n self._welu = None\n","sub_path":"admin/django/dafousers/logginghandlers.py","file_name":"logginghandlers.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"49290535","text":"import math\n\n# Første eksempel på en egendefinert klasse: Punkt\n#\n# Denne versjonen bruker properties for å sørge for at koordinatene ikke kan være negative. En property kan\n# brukes som om den var en instansvariabel (variabel definert i __init__)\nclass Punkt:\n # Konstruktør, denne skal lage objektet. self er objektet som blir\n # lagd. De andre parameterne er som for en funksjon\n def __init__(self, start_x=0, start_y=0):\n self.x = start_x\n self.y = start_y\n\n # Getter for egenskapen x. En getter er en metode som henter ut verdien til en egenskap\n @property\n def x(self):\n return self.__x\n\n # Setter for egenskapen x. Denne sjekker at x ikke kan være negativ . En setter er en metode som setter verdien\n # til en egenskap.\n @x.setter\n def x(self, ny_x):\n if ny_x > 0.0:\n self.__x = ny_x\n\n # Getter for egenskapen y\n @property\n def y(self):\n return self.__y\n\n # Setter for egenskapen y\n @y.setter\n def y(self, ny_y):\n if ny_y > 0.0:\n self.__y = ny_y\n\n # Metode for klassen Punkt.\n def flytt(self, delta_x, delta_y):\n self.x += delta_x\n self.y += delta_y\n\n def __str__(self):\n return \"Punkt: (\" + str(self.x) + \", \" + str(self.y) + \")\"\n\n\ndef flytt_til_midten(punkt1, punkt2):\n midt_x = (punkt1.x + punkt2.x)/2\n midt_y = (punkt1.y + punkt2.y)/2\n punkt1.x = midt_x\n punkt1.y = midt_y\n\n\nif __name__ == \"__main__\":\n punkt1 = Punkt(3, 4)\n print(str(punkt1))\n print(punkt1.x)\n punkt1.flytt(-2, 0)\n punkt2 = Punkt(12, 23)\n print(punkt2)\n punkt2.flytt(1, 1)\n print(punkt2)\n print(punkt1)\n flytt_til_midten(punkt1, punkt2)\n print(punkt1)\n punkt2.x = 3\n print(punkt2)\n punkt2.x = -3\n print(punkt2)\n\n\n","sub_path":"klasser_og_objekter/punkt_properties.py","file_name":"punkt_properties.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"82568848","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport csv, codecs, cStringIO\nimport json\nimport logging\nimport os\nimport re\nfrom collections import defaultdict\n\n# Script that cleans up budgettaire_tabellen_owb_201X_origineel.csv\n# files and writes the output to another .csv called\n# 'budgettaire_tabellen_owb_2015.csv' and the directory\n# 'budgettaire_tabellen_json' which contains a .json file holding the\n# values in a nested way for each combination of year,\n# uitgaven (U)/verplichtingen (V)/ontvangsten (O) and type of budget\n# (i.e., ontwerpbegroting/vastgestelde_begroting/\n# eerste_suppletoire_begroting/tweede_suppletoire_begroting/realisatie).\n# The .json files are hierarchically structured in the format used for\n# hierarchical visualisations by D3.js\n# (https://github.com/d3/d3-hierarchy/blob/master/README.md#hierarchy).\n\n# Classes to read and write UTF-8 .csv's\nclass UTF8Recoder:\n \"\"\"\n Iterator that reads an encoded stream and reencodes the input to UTF-8\n \"\"\"\n def __init__(self, f, encoding):\n self.reader = codecs.getreader(encoding)(f)\n\n def __iter__(self):\n return self\n\n def next(self):\n return self.reader.next().encode(\"utf-8\")\n\nclass UnicodeReader:\n \"\"\"\n A CSV reader which will iterate over lines in the CSV file \"f\",\n which is encoded in the given encoding.\n \"\"\"\n\n def __init__(self, f, dialect=csv.excel, encoding=\"utf-8\", **kwds):\n f = UTF8Recoder(f, encoding)\n self.reader = csv.reader(f, dialect=dialect, **kwds)\n\n def next(self):\n row = self.reader.next()\n return [unicode(s, \"utf-8\") for s in row]\n\n def __iter__(self):\n return self\n\nclass UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\",\n which is encoded in the given encoding.\n \"\"\"\n\n def __init__(self, f, dialect=csv.excel, encoding=\"utf-8\", **kwds):\n # Redirect output to a queue\n self.queue = cStringIO.StringIO()\n self.writer = csv.writer(self.queue, dialect=dialect, **kwds)\n self.stream = f\n self.encoder = codecs.getincrementalencoder(encoding)()\n\n def writerow(self, row):\n self.writer.writerow([s.encode(\"utf-8\") for s in row])\n # Fetch UTF-8 output from the queue ...\n data = self.queue.getvalue()\n data = data.decode(\"utf-8\")\n # ... and reencode it into the target encoding\n data = self.encoder.encode(data)\n # write to the target stream\n self.stream.write(data)\n # empty queue\n self.queue.truncate(0)\n\n def writerows(self, rows):\n for row in rows:\n self.writerow(row)\n\n\n# Create a directory to store logs of this script\nlog_dir = 'logs'\nif not os.path.exists(log_dir):\n os.mkdir(log_dir)\n\n# Initialize logger where we write the duplicate entries to\nlog_dup = logging.getLogger('overwrite_logger')\nlog_dup.addHandler(logging.FileHandler(log_dir + '/duplicate_hierarchies.log'))\n\n# Mapping of hoofdstuk indicator to the name of the hoofdstuk\nmapping = {\n \"A\": \"Infrastructuurfonds\",\n \"B\": \"Gemeentefonds\",\n \"C\": \"Provinciefonds\",\n \"F\": \"Diergezondheidsfonds\",\n \"H\": \"BES-fonds\",\n \"I\": \"De Koning\",\n \"IIA\": \"De Staten Generaal\",\n \"IIB\": \"Overige Hoge Colleges van Staat\",\n \"III\": \"Algemene Zaken\",\n \"IIIA\": \"Algemene Zaken\",\n \"IIIB\": \"Kabinet van de Koning\",\n \"IIIC\": \"Commissie van Toezicht betreffende de Inlichtingen- en Veiligheidsdienst\",\n \"IV\": \"Koninkrijksrelaties\",\n \"IXA\": \"Nationale Schuld\",\n \"IXB\": u\"Financiën\",\n \"J\": \"Deltafonds\",\n \"V\": \"Buitenlandse Zaken\",\n \"VII\": \"Binnenlandse Zaken en Koninkrijksrelaties\",\n \"VIII\": \"Onderwijs, Cultuur en Wetenschap\",\n \"VI\": \"Veiligheid en Justitie\",\n \"X\": \"Defensie\",\n \"XIII\": \"Economische Zaken\",\n \"XII\": \"Infrastructuur en Milieu\",\n \"XVII\": \"Buitenlandse Handel & Ontwikkelingssamenwerking\",\n \"XVIII\": \"Wonen en Rijksdienst\",\n \"XVI\": \"Volksgezondheid, Welzijn en Sport\",\n \"XV\": \"Sociale Zaken en Werkgelegenheid\",\n \"LVIII\": \"Diergezondheidsfonds\"\n}\n\n# Set up the datastructure for the .json output files\ntree = lambda: defaultdict(tree)\n\n# Log information on lines which would have overwritten an already\n# existing line in the json_data, because their hierarchy is the same\ndef print_existing(value, hierarchy_list, new_line):\n log_dup.warning(\"Found value %s at: '%s'\" % (value, \"' > '\".join(hierarchy_list)))\n log_dup.warning('Thus could not save: %s\\n' % (', '.join(new_line)))\n\n# Use the values in hierarchy_list to retrieve its value stored in\n# json_data. E.g., when hierarchy_list contains\n# [u'U', 'Koninkrijksrelaties', u'Nominaal en onvoorzien'] this function\n# will the value stored in\n# json_data[u'U']['Koninkrijksrelaties'][u'Nominaal en onvoorzien']\ndef get_dict_with_list(json_data, hierarchy_list):\n for k in hierarchy_list: json_data = json_data[k]\n return json_data\n\n# The same logic of get_dict_with_list to use hierarchy_list to traverse\n# json_data is used here to store a value instead of retrieving a value\ndef set_dict_with_list(json_data, hierarchy_list, value):\n for key in hierarchy_list[:-1]:\n json_data = json_data.setdefault(key, {})\n json_data[hierarchy_list[-1]] = value\n\n# Check if a value is already stored using this hierarchy_list of the\n# current line. get_dict_with_list can return three states. 1) it\n# returns empty, which means nothing is stored yet at this place in the\n# hierarchy, so the current line can be stored here. 2) it is not empty,\n# the current line and already stored information are printed for later\n# analysis as to why there is a collision. 3) a TypeError is returned,\n# which means that something is already stored in this hierarchy but at\n# a higher level. We still want to know what is stored there for\n# analysis, so we recursively call this function again using the\n# hierarchy_list one level up.\ndef already_exists(json_data, hierarchy_list, new_line, exists=False):\n try:\n if get_dict_with_list(json_data, hierarchy_list):\n print_existing(get_dict_with_list(json_data, hierarchy_list), hierarchy_list, new_line)\n return True\n elif exists:\n return True\n else:\n return False\n except TypeError:\n return already_exists(json_data, hierarchy_list[:-1], new_line, True)\n\n# This function starts by trying to save the line at its most detailed\n# level (omschrijving), but if this field is empty then it moves up one\n# level and tries the same. Checks are also in place to see if a line\n# will overwrite an already existing value in the hierarchy, in which\n# case the information is logged and the new line is discarded in favor\n# of the already saved line.\ndef store_json_data_recursively(json_data, hierarchy_list, new_line):\n if hierarchy_list[-1] or len(hierarchy_list) == 3:\n if already_exists(json_data, hierarchy_list, new_line):\n return\n set_dict_with_list(json_data, hierarchy_list, new_line[21])\n else:\n store_json_data_recursively(json_data, hierarchy_list[:-1], new_line)\n\n# Artikel names are not consistent, so the artikel numbers/codes are\n# used in this script. For human readability we do want to output the\n# artikel names in the JSON output. A mapping is created for each each\n# artikel number/code to the artikel name when an artikel is seen for\n# the first time.\nartikel_mapping = {}\n\n# Save lines in a hierarchically structured way. This requires recursion\n# as we need to find the most detailed level for which we can store a\n# value (e.g., some value are stored at the 'artikelonderdeel' level,\n# while others are stored at the 'omschrijving' level).\ndef store_json_data(json_data, uvo, hoofdstuk, artikel, new_line):\n hoofdstuk = mapping[hoofdstuk]\n # If the artikel number/code is not available in the mapping, then\n # add it together with the artikel name to the mapping\n if hoofdstuk + '_' + artikel not in artikel_mapping:\n artikel_mapping[hoofdstuk + '_' + artikel] = new_line[8]\n artikel = artikel_mapping[hoofdstuk + '_' + artikel]\n artikelonderdeel = new_line[15]\n subartikelonderdeel = new_line[16]\n uitsplitsing = new_line[17]\n omschrijving = new_line[18]\n store_json_data_recursively(json_data, [uvo, hoofdstuk, artikel, artikelonderdeel, subartikelonderdeel, uitsplitsing, omschrijving], new_line)\n\n# Perform all cleanup actions, see the comments for details\ndef clean(year):\n # This dictionary will be used to keep track of the largest total\n # value found for a certain artikel. If this artikel doesn't have\n # any detailed values then use this total value as its most detailed\n # value.\n dict_data = tree()\n # This dictionary will be used to store the data in a hierarchical\n # way in order to be exported to json\n json_data = tree()\n\n # All rows are doubled in 2016, so don't process a hoofdstuk if\n # we've seen it already\n seen = {}\n \n # Open the .csv files to read from and write to\n with open('budgettaire_tabellen_owb_%s_origineel.csv' % (year)) as IN, \\\n open('budgettaire_tabellen_owb_%s.csv' % (year), 'w') as OUT:\n budget_data = UnicodeReader(IN)\n writer = UnicodeWriter(OUT)\n # Retrieve the first line containing the column names\n column_names = budget_data.next()\n # Write the first line containing the column names to the .csv\n # file\n writer.writerow(column_names)\n\n seen_last_row = ''\n\n # Process each line of the input data\n line_count = 1\n for line in budget_data:\n line_count += 1\n # Store any changes to the line in new_line\n new_line = line\n\n # Remove leading and trailing whitespace from all fields\n new_line = [field.strip() for field in new_line]\n\n # Logic to tell if we've already seen a whole block of one\n # hoofdstuk in 2016 in order to skip the second block with\n # the same values\n if line[0] == '2016' and line[1] in seen:\n continue\n elif line[0] == '2016' and line[1] not in seen:\n if seen_last_row != line[1] and seen_last_row:\n seen[seen_last_row] = True\n seen_last_row = line[1]\n\n # This line contains years as values which is incorrect so\n # skip it in 2017\n if line_count == 1409 and line[0] == '2017':\n continue\n\n # Skip lines which don't have an artikel number/code; this\n # happens at least in line 162-164 in 2017\n if not new_line[6]:\n continue\n\n # The following two lines contain\n # 'V/U/O (Verplichtingen/Uitgaven/Ontvangsten)' instead of\n # 'V' as value in 2017\n if (line_count == 2313 or line_count == 2332) and line[0] == '2017':\n new_line[12] = 'V'\n # Sometimes lowercase values are used, 'u'/'v'/'o', convert them to upper case\n uvo = new_line[12].upper()\n\n # The input .csv files use just 'III' for three different\n # begrotingen, so correct these to the codes that are used\n # on rijksbegroting.nl, e.g.\n # http://rijksbegroting.nl/2017/voorbereiding/begroting,kst225610.html\n if new_line[3] == 'Algemene Zaken':\n new_line[1] = 'IIIA'\n elif new_line[3] == 'Kabinet van de Koning':\n new_line[1] = 'IIIB'\n elif new_line[3] == 'Commissie van Toezicht betreffende de Inlichtingen- en Veiligheidsdienst':\n new_line[1] = 'IIIC'\n\n # In 2017, the last 7/8 columns of lines 899-936 have\n # shifted one column to the right\n if line_count in range(899, 937) and line[0] == '2017':\n if new_line[19]:\n new_line[18] = new_line[19]\n new_line[19:] = new_line[20:]\n\n # Column T has a 'o' instead of a 0 in 2017\n if line_count == 2419 and line[0] == '2017':\n new_line[19] = '0'\n\n # Change line[3] to 'Overige Hoge Colleges van Staat en\n # Kabinetten van de Gouverneurs' instead of\n # 'Staten Generaal' in 2016 and 2017 for hoofdstuk IIB\n if new_line[1] == 'IIB' and (new_line[0] == '2016' or new_line[0] == '2017') and new_line[3] == 'Staten Generaal':\n new_line[3] = 'Overige Hoge Colleges van Staat en Kabinetten van de Gouverneurs'\n\n # In 2017, the 'Deltafonds' hoofdstuk value is 'A' instead\n # of 'J' in 2017\n if new_line[3] == 'Deltafonds' and new_line[0] == '2017':\n new_line[1] = 'J'\n\n # Remove lines containing either 'pm' ('pro memorie', i.e., the value is not (yet) known) or '%' or if it doesn't contain a number\n if not new_line[21] or 'pm' in new_line[21] or '%' in new_line[21] or not re.search(r'\\d', new_line[21]):\n continue\n\n # Remove the comma thousands separator\n val = new_line[21].replace(',', '')\n\n # 2015 uses badly formatted floats, so round those values\n if '.' in val:\n val = round(float(val))\n val = int(val)\n\n new_line[21] = unicode(val)\n\n artikel = new_line[6]\n hoofdstuk = new_line[1]\n\n # Don't output lines with a 'J' in column N as these are\n # (sub)totals which we don't need as we can calculate them\n # using the most detailed values. We do store the maximum\n # total values found as some artikelen don't have detailed\n # values so this total value will be the most detailed\n # value.\n if new_line[13] == 'J':\n if 'max_val' in dict_data[hoofdstuk][artikel][uvo]:\n if val > dict_data[hoofdstuk][artikel][uvo]['max_val']:\n dict_data[hoofdstuk][artikel][uvo]['max_val'] = val\n dict_data[hoofdstuk][artikel][uvo]['max_val_line'] = new_line\n else:\n dict_data[hoofdstuk][artikel][uvo]['max_val'] = val\n dict_data[hoofdstuk][artikel][uvo]['max_val_line'] = new_line\n # If column N has the value 'N', then this line contains a\n # detailed value so write it to the output .csv file and\n # also set the 'has_detailed_values' flag which shows that\n # this artikel has detailed values\n else:\n writer.writerow(new_line)\n\n # Store data for JSON export\n store_json_data(json_data, uvo, hoofdstuk, artikel, new_line)\n\n if 'has_detailed_values' not in dict_data[hoofdstuk][artikel][uvo]:\n dict_data[hoofdstuk][artikel][uvo]['has_detailed_values'] = True\n # Some artikelen don't have detailed values and only a total\n # value. If this is the case then write this line to the .csv\n # file as well, because it is the most detailed value.\n for hoofdstuk, hoofdstuk_values in dict_data.iteritems():\n for artikel, artikel_values in hoofdstuk_values.iteritems():\n for uvo, uvo_values in artikel_values.iteritems():\n if not 'has_detailed_values' in uvo_values:\n writer.writerow(uvo_values['max_val_line'])\n # Store data for JSON export\n store_json_data(json_data, uvo, hoofdstuk, artikel, uvo_values['max_val_line'])\n return json_data\n\n# Recursively iterate over all nested levels from json_data and save the\n# names and values in the hierarchically structured format\ndef recursively_extract(parent_item):\n if type(parent_item) == unicode:\n return u'found_leaf'\n item_list = []\n for item, item_value in parent_item.iteritems():\n child_item_return = recursively_extract(item_value)\n if child_item_return == u'found_leaf':\n item_list.append(\n {\n \"name\": item,\n \"value\": item_value\n }\n )\n if type(child_item_return) == list:\n item_list.append(\n {\n \"name\": item,\n \"children\": child_item_return\n }\n )\n return item_list\n\n## Save hierarchical JSON data\n# Loop over all years\nyears = ['2015', '2016', '2017']\nfor year in years:\n json_data = clean(year)\n\n # Directory name to save the .json files in\n dirname = 'budgettaire_tabellen_json'\n # Create the directory if it does not exist\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n # Loop over all hierarchies in the dictionary\n for uvo, uvo_values in json_data.iteritems():\n # Open a .json file for this combination of year, uvo and\n # budget_type (we currently only take ontwerpbegroting value\n # 't'/column N) to write to\n filename = '%s-%s-%s' % (year, uvo, 'ontwerpbegroting')\n with open('%s/%s.json' % (dirname, filename), 'w') as OUT:\n hoofdstuk_list = recursively_extract(uvo_values)\n out_data = { \n \"name\": filename,\n \"children\": hoofdstuk_list\n }\n json.dump(out_data, OUT, indent=4)\n\n# Save the created artikel mapping for logging purposes\nwith open(log_dir + '/artikel_mapping.json', 'w') as OUT:\n json.dump(artikel_mapping, OUT, indent=4, sort_keys=True)\n","sub_path":"budgettaire tabellen/convert_budgettaire_tabellen.py","file_name":"convert_budgettaire_tabellen.py","file_ext":"py","file_size_in_byte":17543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"308617838","text":"# coding=utf-8\n# summary:\n# author: Jianqiang Ren\n# date:\n\n\nimport tensorflow as tf\nimport argparse\nimport os\nimport cv2\nimport numpy as np\nfrom module import generator_resnet\nfrom collections import namedtuple\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--ckpt', dest='ckpt', type=str)\nparser.add_argument('--batch_size', dest='batch_size', type=int, default=1, help='# images in batch')\nparser.add_argument('--fine_size', dest='fine_size', type=int, default=256, help='then crop to this size')\nparser.add_argument('--ngf', dest='ngf', type=int, default=64, help='# of gen filters in first conv layer')\nparser.add_argument('--ndf', dest='ndf', type=int, default=64, help='# of discri filters in first conv layer')\nparser.add_argument('--input_nc', dest='input_nc', type=int, default=3, help='# of input image channels')\nparser.add_argument('--output_nc', dest='output_nc', type=int, default=3, help='# of output image channels')\n\nargs = parser.parse_args()\n\n\n\ndef freeze(ckpt_path):\n \n \n OPTIONS = namedtuple('OPTIONS', 'batch_size image_size \\\n gf_dim df_dim output_c_dim')\n options = OPTIONS._make((args.batch_size, args.fine_size,\n args.ngf, args.ndf, args.output_nc))\n \n \n inp_content_image = tf.placeholder(tf.float32, shape=(1, None, None, 3), name='input')\n \n \n out_image = generator_resnet(inp_content_image, options,name='generatorA2B')\n out_image = tf.identity(out_image, name='output')\n \n init_op = tf.global_variables_initializer()\n \n restore_saver = tf.train.Saver()\n \n with tf.Session() as sess:\n sess.run(init_op)\n restore_saver.restore(sess, ckpt_path)\n frozen_graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def,\n output_node_names=['output'])\n \n path = os.path.dirname(ckpt_path)\n with open(path + '/cyclegan.pb', 'wb') as f:\n f.write(frozen_graph_def.SerializeToString())\n\n\nif __name__ == '__main__':\n ckpt_path = args.ckpt\n freeze(ckpt_path)\n print('freeze done')","sub_path":"freeze.py","file_name":"freeze.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"329937715","text":"\"\"\"falsr_b\"\"\"\nimport os\nimport cv2\nimport paddle\n\nimport paddlehub as hub\n\nif paddle.is_compiled_with_cuda():\n paddle.set_device(\"gpu\")\n use_gpu = True\nelse:\n paddle.set_device(\"cpu\")\n use_gpu = False\n\n\ndef test_falsr_b_predict():\n \"\"\"falsr_b\"\"\"\n os.system(\"hub install falsr_b\")\n sr_model = hub.Module(name=\"falsr_b\")\n im = cv2.imread(\"low_pixel.jpeg\").astype(\"float32\")\n # visualization=True可以用于查看超分图片效果,可设置为False提升运行速度。\n res = sr_model.reconstruct(images=[im], visualization=True)\n print(res[0][\"data\"])\n os.system(\"hub uninstall falsr_b\")\n","sub_path":"models/PaddleHub/hub_all_func/all_module/all_falsr_b.py","file_name":"all_falsr_b.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"143232180","text":"from karapace.schema_reader import SchemaType, TypedSchema\nfrom karapace.serialization import SchemaRegistryClient\nfrom tests.utils import schema_avro_json\n\n\nasync def test_remote_client(registry_async_client):\n schema_avro = TypedSchema.parse(SchemaType.AVRO, schema_avro_json)\n reg_cli = SchemaRegistryClient()\n reg_cli.client = registry_async_client\n sc_id = await reg_cli.post_new_schema(\"foo\", schema_avro)\n assert sc_id >= 0\n stored_schema = await reg_cli.get_schema_for_id(sc_id)\n assert stored_schema == schema_avro, f\"stored schema {stored_schema.to_json()} is not {schema_avro.to_json()}\"\n stored_id, stored_schema = await reg_cli.get_latest_schema(\"foo\")\n assert stored_id == sc_id\n assert stored_schema == schema_avro\n","sub_path":"tests/integration/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"635596042","text":"from kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.properties import NumericProperty, ReferenceListProperty,\\\n ObjectProperty\nfrom kivy.vector import Vector\nfrom kivy.clock import Clock\nimport random\nfrom kivy.uix.image import Image\n\nclass Magnes(Widget):\n narysowany = NumericProperty(0)\n velocity_x = NumericProperty(0)\n velocity_y = NumericProperty(-3)\n velocity = ReferenceListProperty(velocity_x, velocity_y)\n pozycja_x = NumericProperty(0)\n pozycja_y = NumericProperty(0)\n pozycja = ReferenceListProperty(pozycja_x, pozycja_y)\n #magnet_image = ObjectProperty(Image())\n\n\n def przyspiesz(self):\n self.velocity_y -= 1\n\n def wyczysc(self, race):\n self.narysowany = 0\n self.pos = (random.randrange(race.width - self.width),race.height)\n self.velocity_y = -3\n\n def zderzenie(self, ball, race):\n if self.collide_widget(ball):\n self.narysowany = 0\n self.pos = (random.randrange(race.width - self.width),race.height)\n self.velocity_y = -3\n return True\n\n def move_obstacle(self, race):\n if self.narysowany == 0:\n self.pos = (random.randrange(race.width - self.width), race.height)\n self.size = (race.width * 4/10, race.height * 1/10)\n self.narysowany = 1\n self.pos = Vector(*self.velocity) + self.pos\n self.pozycja = self.pos\n if self.pozycja_y + self.height < 0:\n self.narysowany = 0\n\nclass Electron(Widget):\n score = NumericProperty(0)\n record = NumericProperty(0)\n #electron_image = ObjectProperty(Image())\n\nclass RaceGame(Widget):\n ball = ObjectProperty(None)\n magnes1 = ObjectProperty(None)\n magnes2 = ObjectProperty(None)\n magnes3 = ObjectProperty(None)\n move = NumericProperty(0)\n first_draw = NumericProperty(0)\n first_draw_magnes2 = NumericProperty(0)\n first_draw_magnes3 = NumericProperty(0)\n przyspieszenie_kulki = NumericProperty(5)\n przyrost_odleglosci = NumericProperty(1)\n poziom_przyspieszenia = NumericProperty(0)\n prog_przyspieszenia = NumericProperty(500)\n\n def update(self, dt):\n if self.ball.score > self.prog_przyspieszenia and self.poziom_przyspieszenia < 18:\n self.poziom_przyspieszenia += 1\n self.prog_przyspieszenia += 2000 * self.poziom_przyspieszenia\n self.magnes1.przyspiesz()\n self.magnes2.przyspiesz()\n self.magnes3.przyspiesz()\n self.przyrost_odleglosci += self.poziom_przyspieszenia\n self.przyspieszenie_kulki += 1\n\n\n Magnes.move_obstacle(self.magnes1, self)\n if self.magnes1.pozycja_y + self.magnes1.height / 2 < self.height * 2/3 or self.first_draw_magnes2 == 1:\n Magnes.move_obstacle(self.magnes2, self)\n self.first_draw_magnes2 = 1\n if self.magnes2.pozycja_y + self.magnes2.height / 2 < self.height * 2/3 or self.first_draw_magnes3 == 1:\n Magnes.move_obstacle(self.magnes3, self)\n self.first_draw_magnes3 = 1\n\n \"\"\"\n Czyszczenie ekranu po kolizji\n \"\"\"\n if Magnes.zderzenie(self.magnes1, self.ball, self)\\\n or Magnes.zderzenie(self.magnes2, self.ball, self)\\\n or Magnes.zderzenie(self.magnes3, self.ball, self):\n if self.ball.score > self.ball.record:\n self.ball.record = self.ball.score\n self.first_draw = 0\n self.first_draw_magnes2 = 0\n self.first_draw_magnes3 = 0\n Magnes.wyczysc(self.magnes1, self)\n Magnes.wyczysc(self.magnes2, self)\n Magnes.wyczysc(self.magnes3, self)\n self.przyrost_odleglosci = 1\n self.poziom_przyspieszenia = 0\n self.prog_przyspieszenia = 500\n\n if self.first_draw == 0:\n self.ball.score = 0\n self.ball.center_x = self.center_x\n self.first_draw = 1\n self.ball.center_y = self.center_y * 1/10\n self.ball.score += self.przyrost_odleglosci\n\n\n if self.move == 1 and self.ball.center_x > self.width - self.width + 25:\n if self.ball.center_x - self.przyspieszenie_kulki < self.width - self.width + 25:\n self.ball.center_x = self.width - self.width + 25\n else:\n self.ball.center_x -= self.przyspieszenie_kulki\n elif self.move == 2 and self.ball.center_x < self.width - 25:\n if self.ball.center_x + self.przyspieszenie_kulki > self.width - 25:\n self.ball.center_x = self.width - 25\n else:\n self.ball.center_x += self.przyspieszenie_kulki\n pass\n\n \"\"\"\n Reakcja na dotyk, reaguje na przytrzymanie\n \"\"\"\n def on_touch_down(self, touch):\n if touch.x < self.width / 2 and self.ball.center_x > self.width - self.width + 25:\n self.move = 1\n if touch.x > self.width / 2 and self.ball.center_x < self.width - 25:\n self.move = 2\n\n def on_touch_up(self, touch):\n self.move = 0\n\nclass RaceApp(App):\n def build(self):\n game = RaceGame()\n Clock.schedule_interval(game.update, 1.0 / 60.0)\n return game\n\n\nif __name__ == '__main__':\n RaceApp().run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"288592973","text":"import sys\n\n# input file\nf = open('testinput.txt', 'r')\nsys.stdin = f\n\ndef miniMaxSum(arr):\n t=0\n ar = sorted(arr)\n for i in ar:\n t += i\n print(*[t-ar[4],t-ar[0]])\n\n\nif __name__ == '__main__':\n arr = list(map(int, input().rstrip().split()))\n\n miniMaxSum(arr)\n","sub_path":"122---HackerRank/ProblemSolving/minimaxsum/minimaxsum.py","file_name":"minimaxsum.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"584594272","text":"from question_model import Question\nfrom data import question_data as data\nfrom quiz_brain import QuizBrain\n\n\ndef main():\n question_bank = []\n for e in data:\n question_bank.append(Question(e[\"text\"], e[\"answer\"]))\n quiz = QuizBrain(question_bank)\n while quiz.still_has_questions():\n quiz.next_question()\n print(\"You've completed the quiz!\")\n print(f\"Your final score was {quiz.score}/{quiz.question_number}\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Day_017/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"425867712","text":"#!/usr/bin/python\n#coding:utf-8\n\nimport cv2\nimport os\nimport sys\nimport argparse\n\nusage = 'Usage: python {} INPUT_FILE [--prefix ] [--dir ] [--help]'.format(__file__)\nparser = argparse.ArgumentParser(description='This script is to generate images from a video.',\n usage=usage)\nparser.add_argument('input_video', action='store', nargs=None, \n type=str, help='Input video.')\nparser.add_argument('-p', '--prefix', action='store', nargs='?',\n default='frame', type=str, help='Prefix of Output file name.')\nparser.add_argument('-d', '--dir', action='store', nargs='?',\n default='data', type=str, help='Directory of Output files.')\nparser.add_argument('-r', '--ratio', action='store',\n default=0.1, type=float, help='Ratio of test datum.')\nparser.add_argument('-w', '--width', action='store',\n default=-1, type=int, help='Width of images.')\nparser.add_argument('-g', '--height', action='store',\n default=-1, type=int, help='height of images.')\nargs = parser.parse_args()\n\n\nvidcap = cv2.VideoCapture(args.input_video)\nsuccess, image = vidcap.read()\ncount = 0\nfiles = []\nprint(\"Start to save images...\")\nwhile True:\n success, image = vidcap.read()\n if not success:\n break\n files.append(os.path.join(args.dir, \"%s_%07d.jpg\" % (args.prefix, count)))\n sys.stdout.write('\\rSave {}'.format(files[-1]))\n sys.stdout.flush()\n if args.width > 0:\n height, width = image.shape[0], image.shape[1]\n if args.height < 0:\n height = int(height * float(args.width) / width)\n else:\n height = args.height\n image = cv2.resize(image, (args.width, height))\n cv2.imwrite(files[-1], image)\n count += 1\n\ntrain_list_file = os.path.join(args.dir, \"train_list.txt\")\ntest_list_file = os.path.join(args.dir, \"test_list.txt\")\nratio = max(0.0, min(1.0, args.ratio))\nindex = int(len(files) * (1.0 - ratio))\nprint('\\nSave %s' % train_list_file)\nwith open(train_list_file, 'w') as f:\n f.write('\\n'.join(files[:index]))\nprint('Save %s' % test_list_file)\nwith open(test_list_file, 'w') as f:\n f.write('\\n'.join(files[index:]))\nprint(\"Done.\")\n","sub_path":"PredNet_scripts/generate_image.py","file_name":"generate_image.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"647283356","text":"# vim: ts=2:sw=2:tw=80:nowrap\n\nimport copy\nfrom logging import error, warn, debug, log, DEBUG, INFO, root as rootlog\nimport Pyro4\n\nfrom ....device import Device as Base\nfrom .....tools.signal_graphs import nearest_terminal\nfrom .....tools import cached\nfrom physical import unit\nimport nidaqmx\nimport numpy as np\n\n\nclass Task(Base):\n task_type = None\n task_class = None\n STATIC = 0\n WAVEFORM_SINGLE = 1\n WAVEFORM_CONTINUOUS = 2\n finite_end_clock = False # whether this task requires end-clock (see analog.py)\n\n def __init__(self, driver, device):\n Base.__init__(self, name='{d}/{tt}'.format(d=device,tt=self.task_type))\n self.task = None\n self.channels = dict()\n self.clocks = dict()\n self.clock_terminal = None\n self.use_case = None\n self.t_max = 0.0 * unit.s\n\n # first find the possible trigger and clock sources\n self.trig_sources = list()\n self.clock_sources = list()\n self.SCTB_sources = list()\n self.sources_to_native = dict()\n\n # make sure the strip off the leading 'ni' but leave the '/'\n clk = self.format_ni_terminal_name('SampleClock')\n trg = self.format_ni_terminal_name('StartTrigger')\n sctb= self.format_ni_terminal_name('SampleClockTimebase')\n\n lD = {clk:self.clock_sources, trg:self.trig_sources, sctb:self.SCTB_sources}\n\n for i in driver.rl.signal_route_map.items():\n l = lD.get( i[1][1], None )\n if l is not None:\n l.append( i[0][0] )\n self.sources_to_native[ i[0][0] ] = i[1][0]\n\n self.config = self.get_config_template()\n\n\n def __del__(self):\n self.clear()\n\n\n def clear(self):\n if self.task:\n debug( 'nidaqmx: clearing NIDAQmx task %s', self.task )\n del self.task\n self.task = None\n self.t_max = 0.0 * unit.s\n\n def format_ni_terminal_name(self, terminal):\n return self.name[len(self.prefix):] + '/' + terminal\n\n def add_channels(self):\n \"\"\"\n Sub-task types must override this for specific channel creation.\n \"\"\"\n # populate the task with output channels and accumulate the data\n for c in self.channels:\n warn( 'creating unknown NIDAQmx task/channel: %s/%s', self.task, c )\n self.task.create_channel(c.partition('/')[-1]) # cut off the prefix\n\n @cached.property\n def has_onboardclock(self):\n return self.onboardclock_name in self.clock_sources\n\n @cached.property\n def onboardclock_name(self):\n return self.name + '/' + 'SampleClock'\n\n def set_config(self, config=None, channels=None, signal_graph=None):\n do_rebuild = False\n if channels and self.channels != channels:\n self.channels = channels\n do_rebuild = True\n if config and self.config != config:\n self.config = config\n do_rebuild = True\n\n if not self.config['clock']['value']:\n self.clock_terminal = None\n else:\n if signal_graph:\n if self.config['clock']['value'] == self.onboardclock_name:\n # don't have to lookup anymore, since we know it is already the\n # onboard clock\n self.clock_terminal = 'OnboardClock'\n else:\n self.clock_terminal = \\\n self.sources_to_native[\n nearest_terminal( self.config['clock']['value'],\n set(self.clock_sources),\n signal_graph ) ]\n do_rebuild = True\n\n if do_rebuild:\n self._rebuild_task()\n\n def _rebuild_task(self):\n # rebuild the task\n self.clear()\n if not self.channels:\n return\n debug( 'nidaqmx: creating task: %s', self.name )\n self.task = self.task_class(self.name.replace('/','-'))\n self.use_case = None\n self.add_channels()\n\n # set persistent task properties\n # Not sure if we really need to worry about on-board memory\n # self.task.set_use_only_onboard_memory(\n # self.config['use-only-onboard-memory']['value'] )\n\n\n def set_clocks(self, clocks):\n \"\"\"\n If this is an analog device, this must be the onboard clock only.\n If this is a digital device, either an Onboard timer for the digital device\n (if supported) or aperiodic clock implemented by a digital line of a digital\n device.\n If this is a timing device, this must be one of the counters.\n \"\"\"\n if self.clocks != clocks:\n self.clocks = clocks\n\n\n def set_output(self, data):\n \"\"\"\n Sets a static value on each output channel of this task.\n \"\"\"\n if self.use_case in [ None, Task.STATIC ]:\n if self.use_case is not None:\n debug( 'nidaqmx: stopping task: %s', self.task )\n self.task.stop()\n else:\n self._rebuild_task()\n self.use_case = Task.STATIC\n\n debug( 'nidaqmx: configuring task for static output: %s', self.task )\n self.task.set_sample_timing( timing_type='on_demand',\n mode='finite',\n samples_per_channel=1 )\n if self.trig_sources:\n # this device _does_ accept triggers\n self.task.configure_trigger_disable_start()\n # get the data\n px = self.prefix\n chlist = ['{}/{}'.format(px,c) for c in self.task.get_names_of_channels()]\n assert set(chlist) == set( data.keys() ), \\\n 'NIDAQmx.set_output: mismatched channels'\n debug( 'nidaqmx: writing static data for channels: %s', chlist )\n if rootlog.getEffectiveLevel() <= (DEBUG-1):\n log(DEBUG-1, '%s', [ float(data[c]) for c in chlist ])\n self.task.write( [ data[c] for c in chlist ] )\n debug( 'nidaqmx: starting task: %s', self.task )\n self.task.start()\n\n\n def get_min_period(self):\n if self.has_onboardclock and self.task and self.channels:\n return unit.s / self.task.get_sample_clock_max_rate()\n return 0*unit.s\n\n\n def get_clock_rate(self):\n if not self.has_onboardclock:\n # It seems that if a device does not have an onboard clock, the call to\n # get_sample_clock_max_rate fails.\n # If this is ever an analog output device, this will probably fail since\n # the max-rate must be specified to program the DAC settling time.\n return 0\n if self.clock_terminal == 'OnboardClock':\n return self.clocks[ self.onboardclock_name ]['rate']['value']\n return self.task.get_sample_clock_max_rate()\n\n\n def set_waveforms(self, waveforms, clock_transitions, t_max, continuous):\n \"\"\"\n Set up the hardware for waveform output. This function does:\n 1. Sets sample clock properly.\n 2. Sets triggering.\n 3. Writes data to hardware buffers without auto_start.\n\n waveforms : see gui/plotter/{analog.py,digital.py} for format\n clock_transitions : dictionary of clocks to dict(ignore,transitions)\n t_max : maximum time of waveforms in units of time.\n \"\"\"\n if self.use_case in [None, Task.WAVEFORM_SINGLE, Task.WAVEFORM_CONTINUOUS]:\n if self.use_case is not None:\n debug( 'nidaqmx: stopping task: %s', self.task )\n self.task.stop()\n else:\n self._rebuild_task()\n if continuous:\n self.use_case = Task.WAVEFORM_CONTINUOUS\n else:\n self.use_case = Task.WAVEFORM_SINGLE\n\n if not self.clock_terminal:\n raise UserWarning('cannot start waveform without a output clock defined')\n\n\n my_clock = clock_transitions[ self.config['clock']['value'] ]\n dt_clk = my_clock['dt']\n transitions = list( my_clock['transitions'] )\n transitions.sort()\n\n if self.finite_end_clock and not continuous:\n # This task requires an additional clock pulse at the end of the sequence\n # in order for the hardware to properly notify the software of completion.\n # It is the responsibility of each driver to ensure that the last clock\n # transitions is ignored if the driver has already indicated to arbwave\n # that an extra clock pulse is required.\n transitions = transitions[:-1]\n\n # 1. Sample clock\n if continuous:\n mode = self.config['clock-settings']['mode']['value']\n else:\n mode = 'finite'\n\n clock_rate = self.get_clock_rate()\n min_dt = self.get_min_period()\n\n debug( 'nidaqmx: configuring task timing for waveform output: %s', self.task )\n if rootlog.getEffectiveLevel() <= (DEBUG-1):\n log(DEBUG-1,'self.task.configure_timing_sample_clock('\n 'source' '=%s,'\n 'rate' '=%s Hz,'\n 'active_edge' '=%s,'\n 'sample_mode' '=%s,'\n 'samples_per_channel=%s)',\n self.clock_terminal,\n clock_rate,\n self.config['clock-settings']['edge']['value'],\n mode,\n len(transitions),\n )\n self.task.configure_timing_sample_clock(\n source = self.clock_terminal,\n rate = clock_rate, # Hz\n active_edge = self.config['clock-settings']['edge']['value'],\n sample_mode = mode,\n samples_per_channel = len(transitions) )\n # 2. Triggering\n if not self.trig_sources:\n pass # this device does not accept triggers\n elif self.config['trigger']['enable']['value']:\n debug( 'nidaqmx: configuring task trigger for waveform output: %s', self.task )\n if rootlog.getEffectiveLevel() <= (DEBUG-1):\n log(DEBUG-1, 'self.task.configure_trigger_digital_edge_start('\n 'source=%s,edge=%s)',\n self.config['trigger']['source']['value'],\n self.config['trigger']['edge']['value'],\n )\n self.task.configure_trigger_digital_edge_start(\n source=self.config['trigger']['source']['value'],\n edge=self.config['trigger']['edge']['value'] )\n else:\n debug('nidaqmx: disabling trigger start for task: %s', self.task)\n self.task.configure_trigger_disable_start()\n # 3. Data write\n # 3a. Get data array\n # loop through each transition and accumulate a list of scans for each\n # channel for each transition.\n # probably need to do some rounding to the nearest clock pulse to ensure\n # that we only have pulses matched to the correct transition\n\n px = self.prefix\n chlist = ['{}/{}'.format(px,c) for c in self.task.get_names_of_channels()]\n assert set(chlist).issuperset( waveforms.keys() ), \\\n 'NIDAQmx.set_waveforms: mismatched channels'\n\n # get all the waveform data into the scans array. All remaining None values\n # mean that the prior value for the particular channels(s) should be kept\n # for that scan.\n n_channels = len(chlist)\n scans = dict.fromkeys( transitions )\n nones = [None] * n_channels\n for i in range( n_channels ):\n if chlist[i] not in waveforms:\n continue\n for wf_path, (encoding,group_trans) in waveforms[ chlist[i] ].items():\n assert encoding == 'step', \\\n 'non-step transition encoding for NIDAQmx: '+encoding\n for timestamp, value in group_trans:\n if not scans[timestamp]:\n scans[timestamp] = copy.copy( nones )\n scans[timestamp][i] = value\n\n # for now, if a channel does not have any data for t=0, we'll issue\n # an error and set the empty channel value at t=0 to zero.\n def zero_if_none(v, channel):\n if v is None:\n warn('NIDAQmx: missing starting value for channel (%s)--using 0',\n chlist[channel])\n return 0\n else:\n return v\n\n S0 = scans[ transitions[0] ]\n if S0 is None:\n # must be sharing a clock with another card. init all channels to zero\n last = scans[ transitions[0] ] = [0] * n_channels\n else:\n scans[ transitions[0] ] = [\n zero_if_none(v,i) for v,i in zip( S0, range(len(S0)) )\n ]\n last = scans[ transitions[0] ]\n\n if len(transitions) > 1:\n # NI seems to have problems with only one transition any way, but...\n diff_transitions = np.diff( transitions )\n min_transition = np.argmin( diff_transitions )\n if diff_transitions[min_transition] < round(min_dt/dt_clk):\n raise RuntimeError(\n '{name}: Samples too small for NIDAQmx at t={tl}->{t}: {dt}<({m}/{clk})'\n .format(name=self.name,\n tl=transitions[min_transition],\n t=transitions[min_transition+1],\n dt=diff_transitions[min_transition],\n m=min_dt, clk=dt_clk)\n )\n\n for t in transitions:\n t_array = scans[t]\n if t_array is None:\n # must be sharing a clock with another card. keep last values\n scans[t] = last\n else:\n for i in range( n_channels ):\n if t_array[i] is None:\n t_array[i] = last[i]\n last = t_array\n\n # now, we finally build the actual data to send to the hardware\n scans = [ scans[t] for t in transitions ]\n\n # 3b. Send data to hardware\n debug( 'nidaqmx: writing waveform data for channels: %s', chlist )\n debug( 'nidaqmx: NIDAQmx len(transitions/in) = %s, len(scans/out) = %s',\n len(transitions), len(scans) )\n if rootlog.getEffectiveLevel() <= (DEBUG-1):\n log(DEBUG-1, 'NIDAQmx task.write(, False, group_by_scan_number)' )\n log(DEBUG-1, ':' )\n for scan in scans:\n log(DEBUG-1, ' %s', np.array(scan).astype(float).tolist())\n self.task.write( scans, auto_start=False, layout='group_by_scan_number' )\n self.t_max = t_max\n\n @Pyro4.expose\n def start(self):\n if self.task:\n self.task.start()\n\n @Pyro4.expose\n def wait(self):\n if self.task:\n log(DEBUG-1,'NIDAQmx: waiting for task (%s) to finish...', self.task)\n log(DEBUG-1,'NIDAQmx: already done? %s', self.task.is_done())\n if self.use_case == Task.WAVEFORM_CONTINUOUS:\n raise RuntimeError('Cannot wait for continuous waveform tasks')\n try: self.task.wait_until_done( timeout = self.t_max.coeff*2 )\n except nidaqmx.libnidaqmx.NIDAQmxRuntimeError as e:\n debug('NIDAQmx: task.wait() timed out! finished=%s',\n self.task.is_done())\n log(DEBUG-1,'NIDAQmx: task (%s) finished', self.task)\n # may as well stop the task since we are finished\n self.stop()\n\n @Pyro4.expose\n def stop(self):\n if self.task:\n debug('nidaqmx: stopping task for %s', self)\n self.task.stop()\n\n @Pyro4.expose\n def get_config_template(self):\n C = {\n 'use-only-onboard-memory' : {\n 'value' : True,\n 'type' : bool,\n 'range' : None,\n },\n 'clock' : {\n 'value' : '',\n 'type' : str,\n 'range' : self.clock_sources,\n },\n 'clock-settings' : {\n 'mode' : {\n 'value' : 'continuous',\n 'type' : str,\n 'range' : [\n ('finite', 'Finite'),\n ('continuous', 'Continuous'),\n ('hwtimed', 'HW Timed Single Point'),\n ],\n },\n 'edge' : {\n 'value' : 'rising',\n 'type' : str,\n 'range' : [\n ('falling','Sample on Falling Edge of Trigger'),\n ('rising', 'Sample on Rising Edge of Trigger'),\n ],\n },\n 'Timebase' : {\n 'clock' : {\n 'value' : '', #FIXME: what should the default be? MasterTimebase?\n 'type' : str,\n 'range' : self.SCTB_sources,\n },\n },\n },\n }\n\n if self.trig_sources:\n C.update(\n trigger = {\n 'enable' : {\n 'value' : False,\n 'type' : bool,\n 'range' : None,\n },\n 'source' : {\n 'value' : '',\n 'type' : str,\n 'range' : self.trig_sources,\n },\n 'edge' : {\n 'value' : 'rising',\n 'type' : str,\n 'range' : [\n ('falling','Trigger on Falling Edge of Trigger'),\n ('rising', 'Trigger on Rising Edge of Trigger'),\n ],\n },\n },\n )\n return C\n","sub_path":"python/arbwave/backend/drivers/nidaqmx/task/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":15633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"403478584","text":"def delete_db(user_id, token, post_data, db, list_data):\n email = post_data['email']\n if len(list_data) == 0:\n return {'Error': 'invalid voter_id and token'}\n elif list_data[0]['user_id'] != user_id:\n return {'Error': 'invalid registered user_id'}\n elif list_data[0]['token'] != token:\n return {'Error': 'invalid registered token'}\n elif list_data[0]['role_name'] == 'admin':\n cur = db.cursor()\n query = \"SELECT * FROM crud_table where email = ('\" + str(email) + \"')\"\n cur.execute(query)\n fetch_table = cur.fetchall()\n list_table = []\n for table in fetch_table:\n dict_data = {'name': table[0], 'email': table[1], 'role_type': table[2], 'status': table[3]}\n list_table.append(dict_data)\n if len(list_table) == 0:\n return {'Error': 'invalid email'}\n elif list_table[0]['email'] == email:\n query = \"DELETE FROM crud_table WHERE email = ('\" + str(email) + \"')\"\n cur.execute(query)\n db.commit()\n return {\"User\": 'DELETED successfully'}\n else:\n return {'Error': 'you are not an registered admin to delete'}\n","sub_path":"package_data/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"103877072","text":"import pygame\n\n# Global constants\n\n# Colors\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\n\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\n\npygame.init()\n\ngameDisplay = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\npygame.display.set_caption('Slither')\n\n\ngameExit = False\nlead_x = 300\nlead_y = 300\nlead_x_change = 0\nlead_y_change = 0\nFPS = 30\n\nclock = pygame.time.Clock()\n\nwhile not gameExit:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameExit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n lead_x_change -= 2\n lead_y_change = 0\n if event.key == pygame.K_RIGHT:\n lead_x_change += 2\n lead_y_change = 0\n if event.key == pygame.K_UP:\n lead_y_change -= 2\n lead_x_change = 0\n if event.key == pygame.K_DOWN:\n lead_y_change += 2\n lead_x_change = 0\n if lead_x > SCREEN_WIDTH:\n lead_x = 0\n if lead_x < 0:\n lead_x = SCREEN_WIDTH\n if lead_y > SCREEN_HEIGHT:\n lead_y = 0\n if lead_y < 0:\n lead_y = SCREEN_HEIGHT\n\n lead_x += lead_x_change\n lead_y += lead_y_change\n\n gameDisplay.fill(BLUE)\n pygame.draw.rect(gameDisplay, RED, [lead_x, lead_y, 10, 10])\n pygame.display.update()\n\n clock.tick(FPS)\n\npygame.quit()\nquit()\n","sub_path":"src/second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"643292643","text":"import salem\nimport xarray as xr\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport pdb\n\nfpath = '/localscratch/wllf030/cornkle/obs_data/blob_maps_MSG/'\nfile = fpath + 'blob_map_90km_sum_18UTC.nc'\nfile2 = fpath + 'blob_map_30km_sum_18UTC.nc'\nfile3 = fpath + 'blob_map_90km_sum_3UTC.nc'\nfile4 = fpath + 'blob_map_30km_sum_3UTC.nc'\ntpath = '/users/global/cornkle/data/pythonWorkspace/proj_CEH/topo/gtopo_1min_afr.nc'\nspath = '/users/global/cornkle/C_paper/wavelet/figs/paper/'\n\ndiff30 = fpath + 'blob_map_30km_18-3UTRC_diff.nc'\ndiff90 = fpath + 'blob_map_90km_18-3UTRC_diff.nc'\n\nds = xr.open_dataarray(file)\ntop = xr.open_dataarray(tpath)\nds2 = xr.open_dataarray(file2)\nds3 = xr.open_dataarray(file3)\nds4 = xr.open_dataarray(file4)\n\nd30diff = xr.open_dataarray(diff30)\nd90diff = xr.open_dataarray(diff90)\n\n\nds.name = '100k'\nds2.name = '30k'\n\nds = ds.sel(lon=slice(-17.5,20), lat=slice(4.5,20)) # lake chad lon=slice(10,20), lat=slice(10,15)\nds2 = ds2.sel(lon=slice(-17.5,20), lat=slice(4.5,20)) # volta lon=slice(-10,8), lat=slice(4,10)\nds3 = ds3.sel(lon=slice(-17.5,20), lat=slice(4.5,20))\nds4 = ds4.sel(lon=slice(-17.5,20), lat=slice(4.5,20))\ntop = top.sel(lon=slice(-17.5,20), lat=slice(4.5,20))\n\ngrid = ds.salem.grid\nsrtm_on_ds = ds.salem.lookup_transform(top)\n\nds[ds == 0]=np.nan\nds2[ds2 == 0] =np.nan\nds3[ds3 == 0] =np.nan\nds4[ds4 == 0] =np.nan\n\n# ds[srtm_on_ds == 0]=np.nan\n# ds2[srtm_on_ds == 0] =np.nan\n# ds3[srtm_on_ds == 0] =np.nan\n# ds4[srtm_on_ds == 0] =np.nan\n\nperc = ds.quantile(0.99)\nperc2 =ds2.quantile(0.99)\nperc3 =ds3.quantile(0.99)\nperc4 =ds4.quantile(0.99)\n\n# perc = np.max(ds)\n# perc2 =np.max(ds2)\n# perc3 =np.max(ds3)\n# perc4 =np.max(ds4)\n\npercc = np.max([perc,perc3])\npercc1 = np.max([perc2, perc4])\n#\n# ds = (ds-1) / (percc- 1) # dim=['lon']\n# ds2 = (ds2-1) / (percc1- 1)\n# ds3 = (ds3-1) / (percc- 1)\n# ds4 = (ds4-1) / (percc1- 1)\n\n# dsr = (ds-1) / (perc- 1) # dim=['lon']\n# ds2r = (ds2-1) / (perc2- 1)\n# ds3r = (ds3-1) / (perc3- 1)\n# ds4r = (ds4-1) / (perc4- 1)\n#\n# dsr = dsr.where(ds<=1)\n# ds2r = ds2r.where(ds2<=1)\n# ds3r = ds3r.where(ds3<=1)\n# ds4r = ds4r.where(ds4<=1)\n\n# ds[ds.where(ds<=1)]=-999\n# ds2[ds2 > 1]=-999\n# ds3[ds3 > 1]=-999\n# ds4[ds4 > 1]=-999\n\n# fact90 = np.sum(ds3)/np.sum(ds)\n# fact30 = np.sum(ds4)/np.sum(ds2)\n#\n# dsr = ds *fact90\n# ds2r = ds2 * fact30\n# ds3r = ds3\n# ds4r = ds4\n\nmap = ds.salem.get_map(cmap='Greys')\nmap.set_shapefile(rivers=True)\n# read the ocean shapefile (data from http://www.naturalearthdata.com)\noceans = salem.read_shapefile(salem.get_demo_file('ne_50m_ocean.shp'),\n cached=True)\n\nlakes = salem.read_shapefile(salem.get_demo_file('ne_50m_lakes.shp'), cached=True)\nmap.set_shapefile(lakes, edgecolor='k', facecolor='none', linewidth=2,)\n\n\n\n\nf,((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2,figsize = (11,5.5))\n\n\n\nmap.set_plot_params(levels=[-40,-20, -10, 10, 20, 40], cmap='RdBu') #[-40,-20, -10, 10, 20, 40] [-0.6,-0.3, -0.15, 0.15, 0.3,0.6]\n#map.set_plot_params(levels=[-100,-75,-50,-40,-30,30,40,50,75,100], cmap='RdBu')\ndat = (ds.values - ds3.values)-7#/ds.values *100 #(d90diff-7)\n\nmap.set_data(dat)\nmap.set_lonlat_contours(add_ytick_labels=False)\nmap.visualize(ax=ax2, addcbar=False)\n\ndat = (ds2.values - ds4.values)*2-5#/ds2.values *100#(d30diff*2-5)\n\nmap.set_data(dat)\nmap.set_lonlat_contours(add_ytick_labels=True)\nmap.visualize(ax=ax1, addcbar=False) #title='<35km 1800UTC - 0300UTC',\nkw2 = map.get_colorbarbase_kwargs()\n\nfor tick in ax1.xaxis.get_major_ticks():\n tick.label.set_fontsize(8)\nfor tick in ax2.xaxis.get_major_ticks():\n tick.label.set_fontsize(8)\nfor tick in ax1.yaxis.get_major_ticks():\n tick.label.set_fontsize(8)\nfor tick in ax2.yaxis.get_major_ticks():\n tick.label.set_fontsize(8)\n\n\nzuse = map.set_topography(top, relief_factor=1.4)\nmap.set_lonlat_contours(add_ytick_labels=True)\nmap.set_plot_params(vmax=2000, cmap='topo')\nmap.set_data(zuse)\nmap.visualize(ax=ax3, addcbar=False) #, title='Topography'\nfor tick in ax3.yaxis.get_major_ticks():\n tick.label.set_fontsize(8)\nfor tick in ax3.xaxis.get_major_ticks():\n tick.label.set_fontsize(8)\nkw = map.get_colorbarbase_kwargs()\n\nax4.axis('off')\n\n\nfsiz = 14\nx = 0.02\nx2 = 0.48\nplt.annotate('a)', xy=(x, 0.95), xytext=(0, 4), size=fsiz, xycoords=('figure fraction', 'figure fraction'),\n textcoords='offset points')\nplt.annotate('b)', xy=(x2, 0.95), xytext=(0, 4), size=fsiz, xycoords=('figure fraction', 'figure fraction'),\n textcoords='offset points')\nplt.annotate('c)', xy=(x, 0.49), xytext=(0, 4), size=fsiz, xycoords=('figure fraction', 'figure fraction'),\n textcoords='offset points')\n\n\n\nplt.tight_layout()\n\nf.subplots_adjust(right=0.89)\n# cax = f.add_axes([0.95,0.55,0.025,0.4])\n# salem.DataLevels(ds, nlevels=8)\n# #kw1=salem.DataLevels.colorbarbase(cax, **kw1)\n# mpl.colorbar.ColorbarBase(cax, **kw1)\n\ncax = f.add_axes([0.90,0.60,0.017,0.32])\ndl=salem.DataLevels(ds, nlevels=8)\n#kw1=salem.DataLevels.colorbarbase(cax, **kw1)\ncb1 = mpl.colorbar.ColorbarBase(cax, label = 'Nocturnal | Afternoon', **kw2)\n#dl.set_extend(extend='both')\n#cb1.set_ticklabels(['']*6)\n#f.colorbar(cax).set_yticklabels(['','','','','',''])\n\n\ncax = f.add_axes([0.46,0.13,0.017,0.32])\nmpl.colorbar.ColorbarBase(cax, label='m', **kw)\n\nplt.savefig(spath+'/scales_map_abs.png', dpi=300)\n\n\nplt.close('all')\n","sub_path":"wavelet_paper/salem_map_basic_absOnly.py","file_name":"salem_map_basic_absOnly.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"437416893","text":"arr = input()\nn = len(arr)\nbase = [0] * n\nvisited = [False] * n\nresult_arr = []\n\ndef recur(cur, pre):\n if cur == n:\n temp = \"\"\n for i in range(n):\n temp += arr[base[i]]\n\n if temp in result_arr:\n return\n\n result_arr.append(temp)\n return\n\n else:\n for i in range(n):\n if visited[i]:\n continue\n\n if pre == arr[i]:\n continue\n\n visited[i] = True\n base[cur] = i\n recur(cur+1, arr[i])\n visited[i] = False\n\nrecur(0, -1)\nprint(len(result_arr))","sub_path":"week_004/week_004_1342.py","file_name":"week_004_1342.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"620813524","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nimport backpropagation as bp\n\n\ndef gaussian_training_vectors(features, means, sd, dim):\n \"\"\"Make a set of N training feature vectors for M classes in a k dimensional space.\n\n Arguments:\n classes {int} -- how many classes the problem has\n features {int} -- how many training feature vectors you want per mean\n means {dict} -- a dict for each class containing a list of means for the class\n sd {np.array} -- a numpy array of every class' standard deviation with floating entries\n dim {int} -- the dimension of the space and hence the feature vectors\n\n Returns:\n 3D np.array -- the set of training feature vectors in a 3D array\n \"\"\"\n s = 0\n classes = 0\n for element in means:\n s += len(means[element])\n xtr = np.zeros((features * s, dim))\n ytr = np.zeros((features * s,))\n index = 0\n for element in means:\n for mean in range(len(means[element])):\n for _ in range(features):\n ytr[index] = classes\n xtr[index, :] = np.random.multivariate_normal(\n means[element][mean], sd, 1)\n index += 1\n classes += 1\n return xtr, ytr\n\n\ndef logistic(x, a=1):\n \"\"\"Calculate the output from the logistic function.\n\n Arguments:\n x {array or float or int} -- the function parameter as either a numpy array or as int/float\n a {float} -- defaults to 1; a constant describing the slope of the function (larger number gives steeper slope)\n\n Returns:\n array/float -- the value of the logistic function in the same format as the function parameter x\n \"\"\"\n return 1 / (1 + np.exp(-a * x))\n\n\ndef d_logistic(x, a=1):\n \"\"\"Find the derivative of the logistic function.\n\n Arguments:\n x {array or float or int} -- the function parameter as either a numpy array or as int/float\n a {float} -- defaults to 1; a constant describing the slope of the function (larger number gives steeper slope)\n\n Returns:\n array or float -- the value of the total derivative of the logistic function in the same format as the function parameter x\n \"\"\"\n return a * logistic(x, a) * (1 - logistic(x, a))\n\n\ndef prob_4_2():\n \"\"\"Using the computer, generate four 2D Gaussian random sequences with\n Σ=[0.01, 0.0; 0.0, 0.01],\n ω_1:\n μ_1 = [0, 0].T,\n μ_2 = [1, 1].T,\n ω_2:\n μ_3 = [0, 1].T,\n μ_4 = [1, 0].T.\n Produce 100 xtr from each distribution. Use the batch mode backpropagation algorithm (p. 170) of\n sec. 4.6 to train a two-layer perceptron with two hidden neurons and one in the output.\n Let the activation function be the logistic one with\n a = 1.\n Plot the error curve as a function of iteration steps. Experiment yourselves with various\n values of the learning parameter μ. Once the algorithm has converged, produce 50 more\n vectors from each distribution and try to classify them using the weights you have obtained.\n What is the percentage classification error?\n \"\"\"\n features = 100 # number of feature vectors from each mean value/vector\n real_data = 50\n d = 2 # the dimension of the feature space\n means = {'1': [[0, 0], [1, 1]], '2': [[0, 1], [1, 0]]}\n sd = np.array([[0.01, 0.0], [0.0, 0.01]])\n xtr, ytr = gaussian_training_vectors(features, means, sd, d)\n xte, yte = gaussian_training_vectors(real_data, means, sd, d)\n\n L = 2\n\n # epoch_error = np.array([30, 28])\n accuracy = [.5, .5]\n\n nn = bp.NeuralNetwork(L=L, layer_dim=[2, 2, 1], i_num=2)\n\n count = 0\n while accuracy[-1] < 0.96 or np.abs(accuracy[-1] - accuracy[-2]) > 0.01:\n accuracy.append(nn.training(xtr, ytr, 2))\n count += 1\n if count > 10000:\n break\n\n print(f'Number of epochs before convergence: {count}')\n plot_surface(xte, yte, nn, accuracy)\n\n\ndef prob_4_10():\n means = {'1': [[0.4, 0.9], [2.0, 1.8], [2.3, 2.3], [2.6, 1.8]],\n '2': [[1.5, 1.0], [1.9, 1.0], [1.5, 3.0], [3.3, 2.6]]}\n features = 50\n d = 2\n sd = np.array([[0.008, 0.0], [0.0, 0.008]])\n xtr, ytr = gaussian_training_vectors(features, means, sd, d)\n\n L = 3\n layer_dim = [2, 3, 2, 1]\n\n epoch_error = np.array([30, 28])\n accuracy = [.5, .5]\n\n nn = bp.NeuralNetwork(L=L, layer_dim=layer_dim, i_num=2)\n nn.set_error_const(.006)\n\n count = 0\n threshold = 30000\n while accuracy[-1] < 0.96 or np.abs(accuracy[-1] - accuracy[-2]) > 0.01:\n # epoch_error = np.append(epoch_error, nn.training(xtr, ytr, 2)[0])\n accuracy.append(nn.training(xtr, ytr, 2))\n count += 1\n if count > threshold:\n print(f'No convergence after {count} epochs.')\n break\n\n if count < threshold + 1:\n print(f'Number of epochs before convergence: {count}')\n plot_surface(xtr, ytr, nn, accuracy)\n\n\ndef plot_surface(Xtr, Ytr, nn, accuracy):\n plt.figure()\n # plt.subplot(1, 3, 1)\n # plt.semilogy(np.abs(epoch_error))\n plt.subplot(1, 2, 1)\n plt.title('Accuracy')\n plt.plot(accuracy)\n plt.subplot(1, 2, 2)\n plt.title('Classification surface')\n # Generate a grid of datapoints.\n x1min = np.min(Xtr[:, 0])\n x1max = np.max(Xtr[:, 0])\n x1margin = 0.05 * (x1max - x1min)\n\n x2min = np.min(Xtr[:, 1])\n x2max = np.max(Xtr[:, 1])\n x2margin = 0.05 * (x2max - x2min)\n\n x1axis = np.linspace(x1min - x1margin, x1max + x1margin, 200)\n x2axis = np.linspace(x2min - x2margin, x2max + x2margin, 200)\n\n X1grid = np.tile(x1axis, (len(x2axis), 1)).T.reshape(-1, 1)\n X2grid = np.tile(x2axis, (1, len(x1axis))).reshape(-1, 1)\n\n Xgrid = np.concatenate((X1grid, X2grid), axis=1)\n\n f_x = nn.propagate_forward(Xgrid)\n\n # Plot contour\n X1grid = X1grid.reshape(len(x2axis), -1)\n X2grid = X2grid.reshape(-1, len(x1axis))\n f_x = f_x.reshape(len(x2axis), len(x1axis))\n\n # Plot decision boundary and margins\n plt.contour(X1grid, X2grid, f_x, levels=[0], linestyles=(\n 'solid'), linewidths=2, colors='k')\n\n plt.contourf(X1grid, X2grid, f_x, levels=np.linspace(\n np.min(f_x), np.max(f_x), 200), cmap='seismic')\n\n col = np.where(Ytr == 1.0, 'b', 'y')\n plt.scatter(Xtr[:, 0], Xtr[:, 1], c=col)\n\n plt.show()\n\n\nnp.random.seed(0)\n# prob_4_2()\nprob_4_10()\n","sub_path":"neural_network/main38.py","file_name":"main38.py","file_ext":"py","file_size_in_byte":6352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"239798116","text":"#! /usr/local/bin/python3\n\ndef checksum(filename):\n with open(filename) as f:\n sum = 0\n\n for line in f:\n values = line.split('\\t')\n values = list(map(int, values))\n\n for v in values:\n for w in values:\n if v != w and v % w == 0:\n sum += int(v / w) \n break\n\n return sum\n\ndef main():\n result = checksum(\"input.txt\")\n print(\"Checksum: \" + str(result))\n\nif __name__ == \"__main__\":\n main()","sub_path":"day-02/corruption-part-two.py","file_name":"corruption-part-two.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"324061983","text":"# Crash Course Text Project 1 - 3rd Iteration:\n\n''' This file will contain game functions to refactor the code in the program\n to make the main less lengthy and easier to follow the logic of it.\n \n The book discusses that refactoring will simplify the structure of the code\n making it easier to build upon.\n \n The author starts by creating a check_events function that will manage the\n events. This is to simplify run_game and isolate the event MGT loop.\n'''\nimport sys\n\nimport pygame\n\ndef check_events():\n \n ''' Respond to keypresses and mouse events. '''\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n \n''' Also creating an update screen function which will clean up the game loop\n by encapsulating the screen updating, the image drawing, and the flip\n to new screen refresh.\n'''\ndef update_screen(ai_settings, screen, ship):\n \n screen.fill(ai_settings.bg_color)\n ship.blitme()\n pygame.display.flip()","sub_path":"Python_Crash_Course_text/Crash_Course_Text_Projects/03_ver_Project_01/game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"615597960","text":"import sdp.scripts.load_nstx_exp_ref as nstx_exp\nimport sdp.scripts.FWR2D_NSTX_139047_Postprocess as fwrpp\nimport sdp.plasma.analysis as ana\nimport matplotlib.pyplot as plt\n\nimport pickle\nimport numpy as np\n\nwith open('/p/gkp/lshi/XGC1_NSTX_Case/FullF_XGC_ti191_output/ref_pos.pck','r') as f:\n ref_pos = pickle.load(f)\n\ndne_ana = ana.XGC_Density_Loader('/p/gkp/lshi/XGC1_NSTX_Case/FullF_XGC_ti191_output/dne_file.sav.npz')\n\n\nn_channel = 16\n\n#create the distance matrix, dx[i,j] is the absolute distance between the reflection points of i-th and j-th channel \ndx = np.absolute(np.zeros((n_channel,n_channel))+ref_pos[np.newaxis,:]-ref_pos[:,np.newaxis])\n\n#calculate cross-correlation matrix from synthetic signals\ncc_fwr = fwrpp.pp.Cross_Correlation_by_fft(fwrpp.ref2d_out)\ncc_fwr2 = fwrpp.pp.Cross_Correlation_by_fft(fwrpp.ref2d_amp2_out)\ncc_fwr01 = fwrpp.pp.Cross_Correlation_by_fft(fwrpp.ref2d_amp01_out)\ncc_3d = fwrpp.pp.Cross_Correlation_by_fft(fwrpp.ref3d_out)\n\ncs_fwr = fwrpp.pp.Self_Correlation(fwrpp.ref2d_out)\ncs_fwr2 = fwrpp.pp.Self_Correlation(fwrpp.ref2d_amp2_out)\ncs_fwr01 = fwrpp.pp.Self_Correlation(fwrpp.ref2d_amp01_out)\ncs_3d = fwrpp.pp.Self_Correlation(fwrpp.ref3d_out)\n\nprint('FWR data loaded')\n\n#calculate cross-correlation matrix from experimental signals, note that for our case, the simulated time slice is at t=0.632s, so we choose corresponding experimental data from 0.632-0.640, the total sample number is chosen to be 2000 because larger sample doesn't bring in any difference, since the increased samples are not statistical independent. \n\ncc_exp = nstx_exp.analyser.Cross_Correlation_by_fft(0.632,0.640,8000)\n#cc_exp_short = nstx_exp.analyser.Cross_Correlation_by_fft(0.634,0.6348,8000)\n\n#calculate coherent signal for all channels from NSTX. The result is an 2D array containing time series of coherent signal from all the channels.\n\ncs_exp = nstx_exp.analyser.Coherent_over_time(0.632,0.640,2e-5,1e-4)\nprint('nstx data loaded')\n\n#choose the channel ranges representing top/bottom part of pedestal, and center channels for each region. \ntop_center = 11\ntop_range = [8,12]\n\nbottom_center = 6\nbottom_range = [2,7]\n\n#pick chosen data from whole correlation matrices\n\nfwr_top=[]\nfwr2_top = []\nfwr01_top=[]\nfwr3d_top=[]\nexp_top = []\ndx_top=[]\ndef pick_top():\n global fwr_top,fwr2_top,exp_top,dx_top,fwr01_top,fwr3d_top\n fwr_top = np.absolute(cc_fwr[top_center,top_range[0]:top_range[1]])\n fwr2_top = np.absolute(cc_fwr2[top_center,top_range[0]:top_range[1]])\n fwr01_top = np.absolute(cc_fwr01[top_center,top_range[0]:top_range[1]])\n fwr3d_top = np.absolute(cc_3d[top_center,top_range[0]:top_range[1]])\n exp_top = np.absolute(cc_exp[top_center,top_range[0]:top_range[1]])\n dx_top = dx[top_center,top_range[0]:top_range[1]]\n\npick_top()\n\nfwr_bot=[]\nfwr2_bot=[]\nfwr01_bot = []\nfwr3d_bot = []\nexp_bot=[]\ndx_bot=[]\ndef pick_bottom():\n global fwr_bot,fwr2_bot,fwr01_bot,exp_bot,dx_bot,fwr3d_bot\n fwr_bot = np.absolute(cc_fwr[bottom_center,bottom_range[0]:bottom_range[1]])\n fwr2_bot = np.absolute(cc_fwr2[bottom_center,bottom_range[0]:bottom_range[1]])\n fwr01_bot = np.absolute(cc_fwr01[bottom_center,bottom_range[0]:bottom_range[1]])\n fwr3d_bot = np.absolute(cc_3d[bottom_center,bottom_range[0]:bottom_range[1]])\n exp_bot = np.absolute(cc_exp[bottom_center,bottom_range[0]:bottom_range[1]])\n dx_bot = dx[bottom_center,bottom_range[0]:bottom_range[1]]\n\npick_bottom()\n\n#fitting with gaussian(for bottom) and exponential(for top)\nxmax_t = 0\nxfit_t = 0\nfwr_fit_t = 0\nfwr2_fit_t = 0\nfwr01_fit_t = 0\nfwr3d_fit_t = 0\nexp_fit_t = 0\nfwr_t_a,fwr_t_sa = 0,0\nfwr2_t_a,fwr2_t_sa = 0,0\nfwr01_t_a,fwr01_t_sa = 0,0\nfwr3d_t_a,fwr3d_t_sa = 0,0\nexp_t_a,exp_t_sa = 0,0\n\nxgc_fit_t = 0\nxgc_t_a,xgc_t_sa = 0,0\nx_t,dne_c_t = 0,0\n\ndef fit_top():\n global fwr_t_a,fwr_t_sa,fwr2_t_a,fwr2_t_sa,fwr01_t_a,fwr01_t_sa,fwr3d_t_a,fwr3d_t_sa,exp_t_a,expt_sa,xmax_t,xfit_t,fwr_fit_t,fwr2_fit_t,exp_fit_t,fwr01_fit_t,fwr3d_fit_t,xgc_fit_t,xgc_t_a,xgc_t_sa,x_t,dne_c_t\n fwr_t_a,fwr_t_sa = fwrpp.pp.fitting_cross_correlation(fwr_top,dx_top,'exponential')\n fwr2_t_a,fwr2_t_sa = fwrpp.pp.fitting_cross_correlation(fwr2_top,dx_top,'exponential')\n fwr01_t_a,fwr01_t_sa = fwrpp.pp.fitting_cross_correlation(fwr01_top,dx_top,'exponential')\n fwr3d_t_a,fwr3d_t_sa = fwrpp.pp.fitting_cross_correlation(fwr3d_top,dx_top,'exponential')\n exp_t_a,exp_t_sa = fwrpp.pp.fitting_cross_correlation(exp_top,dx_top,'exponential')\n opt_t,x_t,dne_c_t = dne_ana.density_correlation(ref_pos[top_center],width = ref_pos[top_range[0]]-ref_pos[top_center])\n xgc_t_a,xgc_t_sa = opt_t\n \n xmax_t = 2*np.max((np.abs(fwr_t_a),np.abs(fwr2_t_a),np.abs(exp_t_a)))\n xfit_t = np.linspace(0,xmax_t,500)\n fwr_fit_t = fwrpp.pp.exponential_fit(xfit_t,fwr_t_a)\n fwr2_fit_t = fwrpp.pp.exponential_fit(xfit_t,fwr2_t_a)\n fwr01_fit_t = fwrpp.pp.exponential_fit(xfit_t,fwr01_t_a)\n fwr3d_fit_t = fwrpp.pp.exponential_fit(xfit_t,fwr3d_t_a)\n exp_fit_t = fwrpp.pp.exponential_fit(xfit_t,exp_t_a)\n xgc_fit_t = ana.gaussian_correlation_func(xfit_t,xgc_t_a)\n\nfit_top()\n\nxmax_b = 0\nxfit_b = 0\nfwr_fit_b = 0\nfwr2_fit_b = 0\nfwr01_fit_b = 0\nfwr3d_fit_b = 0\nexp_fit_b = 0\nfwr_b_a,fwr_b_sa = 0,0\nfwr2_b_a,fwr2_b_sa = 0,0\nfwr01_b_a,fwr01_b_sa = 0,0\nfwr3d_b_a,fwr3d_b_sa = 0,0\nexp_b_a,exp_b_sa = 0,0\n\nxgc_fit_b = 0\nxgc_b_a,xgc_b_sa = 0,0\nx_b,dne_c_b = 0,0\n\ndef fit_bot():\n global fwr_b_a,fwr_b_sa,fwr2_b_a,fwr2_b_sa,fwr01_b_a,fwr01_b_sa,fwr3d_b_a,fwr3d_b_sa,exp_b_a,expt_sa,xmax_b,xfit_b,fwr_fit_b,fwr2_fit_b,exp_fit_b,fwr01_fit_b,fwr3d_fit_b,xgc_fit_b,xgc_b_a,xgc_b_sa,x_b,dne_c_b\n fwr_b_a,fwr_b_sa = fwrpp.pp.fitting_cross_correlation(fwr_bot,dx_bot,'gaussian')\n fwr2_b_a,fwr2_b_sa = fwrpp.pp.fitting_cross_correlation(fwr2_bot,dx_bot,'gaussian')\n fwr01_b_a,fwr01_b_sa = fwrpp.pp.fitting_cross_correlation(fwr01_bot,dx_bot,'gaussian')\n fwr3d_b_a,fwr3d_b_sa = fwrpp.pp.fitting_cross_correlation(fwr3d_bot,dx_bot,'gaussian')\n exp_b_a,exp_b_sa = fwrpp.pp.fitting_cross_correlation(exp_bot,dx_bot,'gaussian')\n \n opt_b,x_b,dne_c_b = dne_ana.density_correlation(ref_pos[bottom_center],width = ref_pos[bottom_range[0]]-ref_pos[bottom_center])\n xgc_b_a,xgc_b_sa = opt_b\n \n xmax_b = 2*np.sqrt(np.max((np.abs(fwr_b_a),np.abs(fwr2_b_a),np.abs(exp_b_a))))\n xfit_b = np.linspace(0,xmax_b,500)\n fwr_fit_b = fwrpp.pp.gaussian_fit(xfit_b,fwr_b_a)\n fwr2_fit_b = fwrpp.pp.gaussian_fit(xfit_b,fwr2_b_a)\n fwr01_fit_b = fwrpp.pp.gaussian_fit(xfit_b,fwr01_b_a)\n fwr3d_fit_b = fwrpp.pp.gaussian_fit(xfit_b,fwr3d_b_a)\n exp_fit_b = fwrpp.pp.gaussian_fit(xfit_b,exp_b_a)\n xgc_fit_b = ana.gaussian_correlation_func(xfit_b,xgc_b_a)\nfit_bot()\n\nprint('fitting complete')\nprint('fitting curve ready. call plot() to plot. note that the default region is top, pass \"bottom\" as the argument to plot bottom region. ')\n#plot the data points and curves\n\ntotal_plot = 0\n\n#top data\ndef plot(region = 'top'):\n global total_plot\n #plt.figure()\n #total_plot += 1\n if(region == 'top'):\n plt.title('Cross-Correlation at Upper Pedestal,center_channel at {0:.4}m'.format(ref_pos[top_center]))\n plt.plot(dx_top,exp_top,'bs',label = 'exp data')\n plt.plot(dx_top,fwr_top,'ro',label = 'FWR data amp=1')\n plt.plot(dx_top,fwr2_top,'r^',label = 'FWR data amp=2')\n plt.plot(dx_top,fwr01_top,'r+',label = 'FWR data amp=0.1')\n plt.plot(xfit_t,exp_fit_t,'b-',label = 'exp exponential fit')\n plt.plot(xfit_t,fwr_fit_t,'r--',label = 'FWR fit')\n plt.plot(xfit_t,fwr2_fit_t,'r-.',label = 'FWR amp2 fit')\n plt.plot(xfit_t,fwr01_fit_t,'r:',label = 'FWR amp0.1 fit')\n plt.xlabel('distance from center channel reflection($m$)')\n plt.ylabel('cross-correlation')\n plt.legend(labelspacing = 0.2,prop = {'size':12})\n plt.tight_layout()\n elif(region == 'bottom'):\n plt.title('Cross-Correlation at Lower Pedestal,center_channel at {0:.4}m'.format(ref_pos[bottom_center]))\n plt.plot(dx_bot,exp_bot,'bs',label = 'exp data')\n plt.plot(dx_bot,fwr_bot,'ro',label = 'FWR data amp=1')\n plt.plot(dx_bot,fwr2_bot,'r^',label = 'FWR data amp=2')\n plt.plot(dx_bot,fwr01_bot,'r+',label = 'FWR data amp=0.1')\n plt.plot(xfit_b,exp_fit_b,'b-',label = 'exp gaussian fit')\n plt.plot(xfit_b,fwr_fit_b,'r--',label = 'FWR fit')\n plt.plot(xfit_b,fwr2_fit_b,'r-.',label = 'FWR amp2 fit')\n plt.plot(xfit_b,fwr01_fit_b,'r:',label = 'FWR amp0.1 fit')\n plt.xlabel('distance from center channel reflection($m$)')\n plt.ylabel('cross-correlation')\n plt.legend(labelspacing = 0.2,prop = {'size':12})\n plt.tight_layout()\n elif(region == '2d/3d_top'):\n plt.title('Cross-Correlation at Upper Pedestal,center_channel at {0:.4}m'.format(ref_pos[top_center]))\n plt.plot(dx_top,exp_top,'bs',label = 'exp data')\n plt.plot(dx_top,fwr_top,'ro',label = 'FWR2D data')\n plt.plot(dx_top,fwr3d_top,'r^',label = 'FWR3D data')\n plt.plot(xfit_t,exp_fit_t,'b-',label = 'exp exponential fit')\n plt.plot(xfit_t,fwr_fit_t,'r--',label = 'FWR2D fit')\n plt.plot(xfit_t,fwr3d_fit_t,'r-.',label = 'FWR3D fit')\n plt.xlabel('distance from center channel reflection($m$)')\n plt.ylabel('cross-correlation')\n plt.legend(labelspacing = 0.2,prop = {'size':12})\n plt.tight_layout()\n elif(region =='2d/3d_bot'):\n #plt.title('Cross-Correlation at Lower Pedestal,center_channel at {0:.4}m'.format(ref_pos[bottom_center]))\n plt.plot(dx_bot,exp_bot,'bs',label = 'exp data')\n plt.plot(dx_bot,fwr_bot,'go',label = 'FWR2D data')\n plt.plot(dx_bot,fwr3d_bot,'r^',label = 'FWR3D data')\n plt.plot(xfit_b,exp_fit_b,'b-')\n plt.plot(xfit_b,fwr_fit_b,'g--')\n plt.plot(xfit_b,fwr3d_fit_b,'r-.')\n plt.xlabel('$distance from center channel(mm)$')\n plt.ylabel('$\\gamma$')\n plt.legend(labelspacing = 0.2,prop = {'size':15})\n plt.tight_layout()\n elif(region == '3d_bot'):\n plt.title('2D/3D Cross-Correlation and XGC1 Density Correlation, Lower')\n plt.plot(dx_bot,fwr_bot,'ro',label = '2D')\n plt.plot(dx_bot,fwr3d_bot,'r^',label = '3D')\n plt.plot(x_b,dne_c_b,'bs',label = 'XGC')\n plt.plot(xfit_b,fwr_fit_b,'r-.',label = '2D fit')\n plt.plot(xfit_b,fwr3d_fit_b,'r--',label = '3D fit')\n plt.plot(xfit_b,xgc_fit_b,'b-',label = 'XGC fit')\n plt.xlabel('distance from center channel relfection($m$)')\n plt.ylabel('cross-corelation')\n plt.legend(labelspacing = 0.2,prop = {'size':12})\n plt.tight_layout()\n elif(region == '3d_top'):\n plt.title('2D/3D Cross-Correlation and XGC1 Density Correlation, Upper')\n plt.plot(dx_top,fwr_top,'ro',label = '2D')\n plt.plot(dx_top,fwr3d_top,'r^',label = '3D')\n plt.plot(x_t,dne_c_t,'bs',label = 'XGC')\n plt.plot(xfit_t,fwr_fit_t,'r-.',label = '2D fit')\n plt.plot(xfit_t,fwr3d_fit_t,'r--',label = '3D fit')\n plt.plot(xfit_t,xgc_fit_t,'b-',label = 'XGC fit')\n plt.xlabel('distance from center channel relfection($m$)')\n plt.ylabel('cross-corelation')\n plt.legend(labelspacing = 0.2,prop = {'size':12})\n plt.tight_layout()\n\ndef clear_all():\n global total_plot\n\n for i in range(total_plot):\n plt.close()\n\n\n\n\n# Coherent Signal comparison\n\n\n\n\n\n","sub_path":"src/python3/sdp/scripts/FWR_Postprocess/nstx_multichannel_analysis.py","file_name":"nstx_multichannel_analysis.py","file_ext":"py","file_size_in_byte":11408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"603289828","text":"from Crypto.Hash import MD5\nimport string\n\ns = []\ntarget = '7ecc19e1a0be36ba2c6f05d06b5d3058'\nprintable = string.printable\n\ndef getHash(s):\n return MD5.new(s).hexdigest()\n\ndef recursive(index, length):\n global s, printable\n if (index == length):\n cur = ''.join(s)\n if getHash(cur) == target:\n print(cur)\n exit()\n return\n\n for val in printable:\n s[index] = val\n recursive(index+1, length)\n\ndef solve(length):\n global s\n s = ['']*length\n print('Bruteforcing len=', length)\n recursive(0, length)\n\nfor i in range(1, 10):\n solve(i)\n","sub_path":"AnPham/Root-Me/Cryptanalysis/Hash-MD5/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"49859513","text":"import time\n\nfrom jina import __default_executor__\nfrom jina.helper import random_identity\nfrom jina.logging.predefined import default_logger\nfrom jina.parsers import set_pea_parser\nfrom jina.peapods.peas import BasePea\nfrom jina.peapods.zmq import Zmqlet\nfrom jina.types.message import Message\nfrom jina.types.request import Request\nfrom tests import validate_callback\n\n\nclass MockBasePeaNotRead(BasePea):\n def _post_hook(self, msg: 'Message') -> 'BasePea':\n super()._post_hook(msg)\n assert not msg.request.is_decompressed\n\n\nclass MockBasePeaRead(BasePea):\n def _post_hook(self, msg: 'Message') -> 'BasePea':\n super()._post_hook(msg)\n assert msg.request.is_decompressed\n\n\nargs1 = set_pea_parser().parse_args(\n [\n '--host-in',\n '0.0.0.0',\n '--host-out',\n '0.0.0.0',\n '--socket-in',\n 'PULL_CONNECT',\n '--socket-out',\n 'PUSH_CONNECT',\n '--timeout-ctrl',\n '-1',\n ]\n)\n\nargs2 = set_pea_parser().parse_args(\n [\n '--host-in',\n '0.0.0.0',\n '--host-out',\n '0.0.0.0',\n '--port-in',\n str(args1.port_out),\n '--port-out',\n str(args1.port_in),\n '--socket-in',\n 'PULL_BIND',\n '--socket-out',\n 'PUSH_BIND',\n '--timeout-ctrl',\n '-1',\n ]\n)\n\nargs3 = set_pea_parser().parse_args(\n [\n '--host-in',\n '0.0.0.0',\n '--host-out',\n '0.0.0.0',\n '--port-in',\n str(args1.port_out),\n '--port-out',\n str(args1.port_in),\n '--socket-in',\n 'PULL_BIND',\n '--socket-out',\n 'PUSH_BIND',\n '--uses',\n __default_executor__, # will NOT trigger use\n '--timeout-ctrl',\n '-1',\n ]\n)\n\n\ndef test_read_zmqlet():\n with MockBasePeaRead(args2), Zmqlet(args1, default_logger) as z:\n req = Request()\n req.request_id = random_identity()\n d = req.data.docs.add()\n d.tags['id'] = 2\n msg = Message(None, req, 'tmp', '')\n z.send_message(msg)\n\n\ndef test_not_read_zmqlet():\n with MockBasePeaNotRead(args3), Zmqlet(args1, default_logger) as z:\n req = Request()\n req.request_id = random_identity()\n d = req.data.docs.add()\n d.tags['id'] = 2\n msg = Message(None, req, 'tmp', '')\n z.send_message(msg)\n\n\ndef test_recv_message_zmqlet(mocker):\n zmqlet1 = Zmqlet(args1, default_logger)\n zmqlet2 = Zmqlet(args2, default_logger)\n req = Request()\n req.request_id = random_identity()\n doc = req.data.docs.add()\n doc.tags['id'] = 2\n msg = Message(None, req, 'tmp', '')\n\n def callback(msg_):\n assert msg_.request.docs[0].tags['id'] == msg.request.data.docs[0].tags['id']\n\n mock = mocker.Mock()\n zmqlet1.send_message(msg)\n time.sleep(1)\n zmqlet2.recv_message(mock)\n validate_callback(mock, callback)\n","sub_path":"tests/unit/test_is_read_message.py","file_name":"test_is_read_message.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"531723501","text":"import time, random\r\nimport pyautogui as pgui\r\nimport webbrowser as web\r\n\r\n# insert links to photos here as strings, ie 'https:\\\\image-location.com'\r\nlinks = []\r\n\r\n# make sure path is set to chrome, or change to preferred browser\r\nbrowserPath = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'\r\n\r\nwhile True:\r\n # shuffles list of links each time through to give a new order. remove this for static list\r\n random.shuffle(links)\r\n for i in range(len(links)):\r\n time.sleep(20) #change to 15\r\n web.get(browserPath).open(links[i])\r\n pgui.hotkey('ctrlleft', 'tab')\r\n pgui.hotkey('ctrlleft', 'w')","sub_path":"randomizedLinkOpener.py","file_name":"randomizedLinkOpener.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"501152652","text":"from xgboost import XGBClassifier, XGBRegressor\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.metrics import r2_score, accuracy_score\nimport pickle\nimport time\n\nx, y=load_iris(return_X_y=True)\n\nx_train, x_test, y_train, y_test=train_test_split(x, y, train_size=0.8)\n\nmodel=XGBClassifier(n_jobs=-1)\nmodel.fit(x_train, y_train)\nscore=model.score(x_test, y_test)\n\nprint('score :', score)\n\nthresholds=np.sort(model.feature_importances_)\nprint(thresholds)\nstart1=time.time()\n\nfor thresh in thresholds :\n selection=SelectFromModel(model, threshold=thresh, prefit=True)\n \n select_x_train=selection.transform(x_train)\n \n selection_model=XGBClassifier(n_jobs=-1)\n selection_model.fit(select_x_train, y_train)\n\n selec_x_test=selection.transform(x_test)\n y_predict=selection_model.predict(selec_x_test)\n\n score=r2_score(y_test, y_predict)\n\n print(\"Thresh=%.3f, n=%d, R2: %.2f%%\" %(thresh, select_x_train.shape[1], score*100.0))\n pickle.save(open(\"./save/xbg_save/iris.pickle.dat\", \"wb\"))\n\nend1=time.time() - start1\nprint(\"잡스 걸린 시간 : \", end1)\n\nprint(model.feature_importances_)\n\n\nmodel2=pickle.load(open(\"./save/xbg_save/iris.pickle.dat\", \"rb\"))\nprint(\"로드 완료\")\nacc2=model2.score(x_test, y_test)\nprint(\"acc : \", acc2)","sub_path":"Study/ml/m37_2_SFM_save_iris.py","file_name":"m37_2_SFM_save_iris.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"430604134","text":"# !/usr/bin/env python\r\n# -- coding: utf-8 --\r\n# @Time : 2020/6/12 13:01\r\n# @Author : liumin\r\n# @File : optimizer.py\r\nfrom copy import deepcopy\r\nimport torch\r\nimport torch.optim as optim\r\n\r\ndef parser_optimizer(cfg, model):\r\n # params = [p for p in model.parameters() if p.requires_grad]\r\n _params = []\r\n # filter(lambda p: p.requires_grad, model.parameters())\r\n for n, p in dict(model.named_parameters()).items():\r\n if p.requires_grad:\r\n _args = deepcopy(cfg.OPTIMIZER.BIAS_PARAMS if \"bias\" in n else cfg.OPTIMIZER.WEIGHT_PARAMS)\r\n _args.pop(\"data\")\r\n _params += [{\"params\": [p], \"lr\": cfg.INIT_LR, **_args}]\r\n if \"bias\" in n:\r\n _params[-1][\"lr\"] *= cfg.OPTIMIZER.BIAS_LR_MULTIPLIER or 1.0\r\n\r\n if cfg.OPTIMIZER.TYPE == \"SGD\":\r\n optimizer = optim.SGD(_params)\r\n elif cfg.OPTIMIZER.TYPE == \"Adam\":\r\n optimizer = optim.Adam(_params)\r\n elif cfg.OPTIMIZER.TYPE == 'RMSprop':\r\n optimizer = optim.RMSprop(_params)\r\n else:\r\n raise ValueError(\"Unsupported optimizer type: {}\".format(cfg.OPTIMIZER.TYPE))\r\n\r\n return optimizer\r\n","sub_path":"src/optimizers/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"105772297","text":"\"\"\"\nNumerical methods for solving diff eqs.\n\"\"\"\n\n\ndef euler_step(f, x0, y0, h):\n \"\"\"\n Perform a step of Euler's method.\n\n Args:\n f: the slope as a function of x, y.\n x0: the start x.\n y0: the start y.\n h: the step size.\n\n Returns:\n A tuple (x1, y1).\n \"\"\"\n slope = f(x0, y0)\n return x0 + h, y0 + h * slope\n\n\ndef rk2_step(f, x0, y0, h):\n \"\"\"\n Perform a step of rk2.\n\n Args:\n f: the slope as a function of x, y.\n x0: the start x.\n y0: the start y.\n h: the step size.\n\n Returns:\n A tuple (x1, y1).\n \"\"\"\n slope1 = f(x0, y0)\n slope2 = f(x0 + h, y0 + h * slope1)\n slope = (slope1 + slope2) / 2\n return x0 + h, y0 + h * slope\n\n\ndef rk3_step(f, x0, y0, h):\n \"\"\"\n Perform a step of RK3.\n\n Args:\n f: the slope as a function of x, y.\n x0: the start x.\n y0: the start y.\n h: the step size.\n\n Returns:\n A tuple (x1, y1).\n \"\"\"\n # https://people.revoledu.com/kardi/tutorial/ODE/Runge%20Kutta%203.htm\n k1 = f(x0, y0)\n k2 = f(x0 + 0.5 * h, y0 + 0.5 * h * k1)\n k3 = f(x0 + h, y0 - k1 * h + 2 * k2 * h)\n return x0 + h, y0 + h * (k1 + 4 * k2 + k3) / 6.0\n\n\ndef third_order_step(f, x0, y0, h):\n \"\"\"\n Perform a step of a third-order method I invented.\n\n See derivations/third_order.jpg.\n\n Args:\n f: the slope as a function of x, y.\n x0: the start x.\n y0: the start y.\n h: the step size.\n\n Returns:\n A tuple (x1, y1).\n \"\"\"\n a = 1.0 / 4.0\n b = 3.0 / 4.0\n c = 2.0 / 3.0\n # Get the exact initial slope.\n slope1 = f(x0, y0)\n # Use RK2 to get f(ch) + O(h^3)\n slope2 = f(x0 + c * h, y0 + c * h * slope1)\n slope3 = (slope1 + slope2) / 2\n # Get the slope at (ch, f(ch) + O(h^3)),\n # which is f'(ch) + O(h^3).\n slope4 = f(x0 + c * h, y0 + c * h * slope3)\n # Compute f(h) + O(h^4).\n return x0 + h, y0 + h * (a * slope1 + b * slope4)\n\n\ndef fourth_order_step(f, x0, y0, h):\n \"\"\"\n Perform a step of a fourth-order method I invented.\n\n See derivations/fourth_order_*.jpg.\n\n Args:\n f: the slope as a function of x, y.\n x0: the start x.\n y0: the start y.\n h: the step size.\n\n Returns:\n A tuple (x1, y1).\n \"\"\"\n third_a = 1.0 / 4.0\n third_b = 3.0 / 4.0\n third_c = 2.0 / 3.0\n\n fourth_a = 1.0 / 10.0\n fourth_b = 2.0 / 5.0\n fourth_c = 1.0 / 2.0\n fourth_d = 1.0 / 3.0\n fourth_e = 5.0 / 6.0\n\n # Get information needed for RK2.\n slope1 = f(x0, y0)\n slope2 = f(x0 + h, y0 + h * slope1)\n\n def second_order(step):\n b = (step ** 2) / 2.0\n a = step - b\n slope = a * slope1 + b * slope2\n return f(x0 + h * step, y0 + h * slope)\n\n def third_order(step):\n sub_step = third_c * step\n tmp_slope = second_order(sub_step)\n return f(x0 + h * step, y0 + h * step * (third_a * slope1 + third_b * tmp_slope))\n\n df_eh = third_order(fourth_e)\n df_dh = third_order(fourth_d)\n\n return x0 + h, y0 + h * (fourth_a * slope1 + fourth_b * df_eh + fourth_c * df_dh)\n\n\ndef numerical_solve(f, x0, y0, x1, h=0.01, step_fn=rk3_step):\n \"\"\"\n Numerically solve a differential equation.\n\n Args:\n f: the slope as a function of x, y.\n x0: the start x.\n y0: the start y.\n x1: the x to run until.\n h: the step size.\n step_fn: a function to take one step of the\n algorithm.\n\n Returns:\n An iterator of (x, y) tuples along the curve.\n \"\"\"\n x = x0\n y = y0\n yield (x, y)\n while x < x1:\n x, y = step_fn(f, x, y, h)\n yield (x, y)\n","sub_path":"diffeq/numerical.py","file_name":"numerical.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"185722723","text":"import re\r\nitems = [1, 5, 9, 24]\r\na = int(input(\"Search for a number ?\"))\r\nfor i in range(6):\r\n if a == items[i]:\r\n print(\"Found it! Position:\",i+1 )\r\n break\r\n else:\r\n print(\"Bruh,no !\")\r\n break\r\n\r\nprint(\"Sum is:\",sum(items))\r\nb = 0\r\nfor i in range(6):\r\n b=b + items[i]\r\nprint(b)\r\n\r\nc = input(\"Enter numbers, seperated by a space: \")\r\nsplit = c.split(\" \")\r\nd = 0\r\nfor n in split:\r\n d = d + int(n)\r\nprint(d)","sub_path":"minihack3.py","file_name":"minihack3.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"535833378","text":"from typing import List, Tuple, Dict\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom tqdm import tqdm\nfrom torch import Tensor\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom pathlib import Path\nimport cvae\nimport cgan\nimport utils\nimport dataloader\nimport scripts\nimport matplotlib.pyplot as plt\n\nimport os\nimport time\nimport random\nimport logging\nfrom logging import handlers\n\nlogging.info(torch.__version__)\n\ncfg = {\n 'data_path': '/hd/yx/WSY/UCY/students03/',\n 'model_params': {\n 'model_cnn': \"resnet18\",\n 'scene_weight': 640,\n 'scene_height': 480,\n 'history_num_frames': 8,\n 'history_delta_time': 0.25,\n 'future_num_frames': 12,\n 'model_name': \"CVGN\",\n 'lr_g': 1e-3,\n 'lr_d': 1e-4,\n 'checkpoint_path': '',\n 'train': True,\n 'predict': True,\n },\n 'train_data_loader': {\n 'batch_size': 40,\n 'shuffle': True,\n 'num_workers': 4,\n },\n 'valid_data_loader': {\n 'batch_size': 40,\n 'shuffle': True,\n 'num_workers': 4,\n },\n 'test_data_loader': {\n 'batch_size': 40,\n 'shuffle': False,\n 'num_workers': 4,\n 'sample_nums': 20,\n },\n 'train_params': {\n 'device': 1,\n 'epoch': 2000,\n 'checkpoint_steps': 100,\n 'valid_steps': 2,\n 'log_file_path': '../../log/train_log/cvgn_univ.log',\n 'tensorboard_path': '../../log/tensorboard/cvgn_univ/',\n 'omega': 0.0,\n 'epsilon': 1.0,\n }\n}\n\n\n# 生成器训练\ndef forward_g(scene, his_traj, targets, model_g, model_d, optimizer, scheduler, omega=1.0, epsilon=1.0):\n\n model_g.train()\n preds, conf, context, z_mean, z_var = model_g(scene, his_traj)\n traj_fake = utils.multi2single(preds, targets, conf, mode='best')\n score_fake = model_d(traj_fake.permute(1, 0, 2), context)\n # 判别loss + nll_loss + vae_loss\n g_loss = utils.g_loss(score_fake)\n # nll_loss = utils.pytorch_neg_multi_log_likelihood_batch(targets, preds, conf)\n vae_loss, ade_loss = cvae.loss_cvae(targets, preds, conf, z_mean, z_var)\n # loss = g_loss + nll_loss * omega + vae_loss * epsilon\n # loss = g_loss + nll_loss * omega + vae_loss * epsilon\n loss = g_loss + vae_loss * epsilon\n scheduler.step()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n return loss, vae_loss, ade_loss, preds, conf\n\n\n# 判别器训练\ndef forward_d(scene, his_traj, targets, model_g, model_d, optimizer, scheduler):\n\n model_d.train()\n preds, confidences, context, _, _ = model_g(scene, his_traj)\n traj_fake = utils.multi2single(preds, targets, confidences, mode='best')\n score_fake = model_d(traj_fake.permute(1, 0, 2), context)\n score_real = model_d(targets.permute(1, 0, 2), context)\n loss = utils.d_loss(score_real, score_fake)\n scheduler.step()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n return loss\n\n\nif __name__ == '__main__':\n # 训练日志\n logfile = cfg['train_params']['log_file_path']\n logger = logging.getLogger(logfile)\n logger.setLevel(level=logging.INFO)\n sh = logging.StreamHandler() # 往屏幕上输出\n th = handlers.TimedRotatingFileHandler(filename=logfile, when='D', encoding='utf-8')\n # logger.addHandler(sh) # 把对象加到logger里\n logger.addHandler(th)\n\n # 加载数据集,准备device\n DIR_INPUT = cfg[\"data_path\"]\n\n train_cfg = cfg[\"train_data_loader\"]\n train_dataset = dataloader.EthSceneDataset(os.path.join(cfg['data_path'], 'train'))\n train_dataloader = DataLoader(train_dataset, shuffle=train_cfg[\"shuffle\"],\n batch_size=train_cfg[\"batch_size\"], num_workers=train_cfg[\"num_workers\"],\n drop_last=True)\n\n valid_cfg = cfg[\"valid_data_loader\"]\n valid_dataset = dataloader.EthSceneDataset(os.path.join(cfg['data_path'], 'valid'))\n valid_dataloader = DataLoader(valid_dataset, shuffle=valid_cfg[\"shuffle\"], batch_size=valid_cfg[\"batch_size\"],\n num_workers=valid_cfg[\"num_workers\"], drop_last=True)\n\n test_cfg = cfg[\"test_data_loader\"]\n test_dataset = dataloader.EthSceneDataset(os.path.join(cfg['data_path'], 'test'))\n test_dataloader = DataLoader(test_dataset, shuffle=test_cfg[\"shuffle\"], batch_size=test_cfg[\"batch_size\"],\n num_workers=test_cfg[\"num_workers\"], drop_last=True)\n\n # world frame to camera frame 3*3单应性矩阵\n h_matrix = np.genfromtxt(DIR_INPUT + 'H.txt')\n\n device = cfg['train_params']['device']\n torch.cuda.set_device(device)\n\n tensorboard_file = cfg['train_params']['tensorboard_path']\n train_writer = SummaryWriter(tensorboard_file)\n\n # 建立模型\n generator = cvae.CVAE(cnn_model=cfg[\"model_params\"][\"model_cnn\"],\n channels=3, cont_dim=256, v_dim=2)\n discriminator = cgan.discriminator(h_dim=256, cont_dim=256)\n # load weight if there is a pretrained model\n checkpoint_path = cfg[\"model_params\"][\"checkpoint_path\"]\n if checkpoint_path:\n checkpoint = torch.load(checkpoint_path)\n generator.load_state_dict(checkpoint['model_state_dict_g'])\n discriminator.load_state_dict(checkpoint['model_state_dict_d'])\n logger.info(checkpoint_path, \"loaded\")\n generator.cuda()\n discriminator.cuda()\n\n learning_rate_g = cfg[\"model_params\"][\"lr_g\"]\n learning_rate_d = cfg[\"model_params\"][\"lr_d\"]\n optimizer_g = optim.Adam(generator.parameters(), lr=learning_rate_g)\n optimizer_d = optim.Adam(discriminator.parameters(), lr=learning_rate_d)\n\n scheduler_g = optim.lr_scheduler.StepLR(optimizer_g, step_size=3000, gamma=0.5)\n scheduler_d = optim.lr_scheduler.StepLR(optimizer_d, step_size=5000, gamma=0.8)\n logger.info(f'device {device}')\n torch.backends.cudnn.benchmark = True\n\n # train\n if cfg[\"model_params\"][\"train\"]:\n tr_it = iter(train_dataloader)\n tr_it_valid = iter(valid_dataloader)\n epochs = cfg[\"train_params\"][\"epoch\"]\n progress_bar = tqdm(range(1, len(train_dataloader)), mininterval=5.)\n losses_d = []\n losses_g = []\n model_name = cfg[\"model_params\"][\"model_name\"]\n checkpoint_steps = cfg['train_params']['checkpoint_steps']\n valid_steps = cfg['train_params']['valid_steps']\n t_start = time.time()\n torch.set_grad_enabled(True)\n best_valid = [0., 0.]\n omega = cfg['train_params']['omega']\n epsilon = cfg['train_params']['epsilon']\n i = 0\n for epoch_i in range(epochs):\n for _ in progress_bar:\n try:\n data = next(tr_it)\n except StopIteration:\n tr_it = iter(train_dataloader)\n data = next(tr_it)\n scene = data[0].to(device)\n scene = scene.permute(0, 3, 2, 1)\n his_traj = data[3].to(device)\n his_traj = his_traj.permute(1, 0, 2)\n targets = data[4].to(device)\n\n # 判别器训练\n loss_d = forward_d(scene.float(), his_traj.float(), targets.float(),\n generator, discriminator, optimizer_d, scheduler_d)\n loss_d = loss_d.item()\n losses_d.append(loss_d)\n train_writer.add_scalar('train/loss_d', loss_d, i)\n\n # 生成器训练\n loss_g, loss_vae, loss_ade, preds, confidences = forward_g(scene.float(), his_traj.float(),\n targets.float(), generator, discriminator,\n optimizer_g, scheduler_g,\n omega=omega, epsilon=epsilon)\n loss_g = loss_g.item()\n losses_g.append(loss_g)\n train_writer.add_scalar('train/loss_g', loss_g, i)\n # loss_nll = loss_nll.item()\n # train_writer.add_scalar('train_metrics/loss_nll', loss_nll, i)\n loss_vae = loss_vae.item()\n train_writer.add_scalar('train_metrics/loss_vae', loss_vae, i)\n loss_ade = loss_ade.item()\n train_writer.add_scalar('train_metrics/loss_ade', loss_ade, i)\n\n i += 1\n\n if i % checkpoint_steps == 0:\n mean_losses_d = np.mean(losses_d)\n losses_d = []\n train_writer.add_scalar('train_mean/mean_losses_d', mean_losses_d, i)\n mean_losses_g = np.mean(losses_g)\n losses_g = []\n train_writer.add_scalar('train_mean/mean_losses_g', mean_losses_g, i)\n\n timespent = (time.time() - t_start) / 60\n curr_lr_g = optimizer_g.param_groups[0]['lr']\n curr_lr_d = optimizer_d.param_groups[0]['lr']\n train_writer.add_scalar('lr/lr_g', curr_lr_g, i)\n train_writer.add_scalar('lr/lr_d', curr_lr_d, i)\n logger.info('epoch: {}, i: {}, loss_g(avg): {},'\n 'loss_d(avg): {}, time(min):{}'.format(epoch_i, i,\n mean_losses_g, mean_losses_d, timespent))\n\n # valid\n if epoch_i % valid_steps == 0:\n generator.eval()\n valid_ades = []\n valid_fdes = []\n valid_losses = []\n torch.set_grad_enabled(False)\n valid_progress_bar = tqdm(range(1, len(valid_dataloader)), mininterval=5.)\n for j in valid_progress_bar:\n try:\n data_valid = next(tr_it_valid)\n except StopIteration:\n tr_it_valid = iter(valid_dataloader)\n data_valid = next(tr_it_valid)\n scene_valid = data_valid[0].to(device)\n scene_valid = scene_valid.permute(0, 3, 2, 1)\n his_traj_valid = data_valid[3].to(device)\n his_traj_valid = his_traj_valid.permute(1, 0, 2)\n targets_valid = data_valid[4].to(device)\n pred_pixel, conf, context, z_mean, z_var = generator(scene_valid.float(), his_traj_valid.float())\n traj_fake_valid = utils.multi2single(pred_pixel, targets_valid.float(), conf, mode='best')\n score_fake = discriminator(traj_fake_valid.permute(1, 0, 2), context)\n g_loss_valid = utils.g_loss(score_fake)\n # nll_loss_valid = utils.pytorch_neg_multi_log_likelihood_batch(targets_valid, pred_pixel, conf)\n vae_loss_valid, min_l2_loss_valid = cvae.loss_cvae(targets_valid, pred_pixel, conf, z_mean, z_var)\n # loss = g_loss + nll_loss * omega + l2_loss * epsilon\n # valid_loss = g_loss_valid + nll_loss_valid * omega + vae_loss_valid * epsilon\n valid_loss = g_loss_valid + vae_loss_valid * epsilon\n # camera frame to world frame(meter)\n pred = torch.zeros_like(pred_pixel)\n for batch_index in range(pred_pixel.shape[0]):\n for modality in range(pred_pixel.shape[1]):\n for pos_index in range(pred_pixel.shape[2]):\n pred[batch_index][modality][pos_index] = torch.from_numpy(scripts.project(h_matrix,\n pred_pixel[batch_index][modality][pos_index].cpu()))\n # calculate metrics in world frame\n valid_ade = utils._average_displacement_error(data_valid[2].to(device), pred, conf, mode='best')\n valid_fde = utils._final_displacement_error(data_valid[2].to(device), pred, conf, mode='best')\n valid_loss = valid_loss.item()\n valid_ade = valid_ade.item()\n valid_fde = valid_fde.item()\n valid_losses.append(valid_loss)\n valid_ades.append(valid_ade)\n valid_fdes.append(valid_fde)\n mean_loss_valid = np.mean(valid_losses)\n mean_ade_valid = np.mean(valid_ades)\n mean_fde_valid = np.mean(valid_fdes)\n # 仅在模型提升时更新checkpoint\n if mean_ade_valid 0, \"nx must be positive\"\n\t\n\tu_initial = numpy.zeros((3,nx))\n\trho_L, vel_L, p_L = params[:3]\n\trho_R, vel_R, p_R = params[3:]\n\t\n\tdx = (b-a)/(nx-1)\n\ti_barrier = numpy.floor((barrier-a)/dx)\n\t\n\tu_initial[:, :i_barrier] = numpy.array([rho_L, rho_L*vel_L, rho_L*(p_L/((gamma-1)*rho_L) + 0.5*vel_L**2)]).reshape((3,1))\n\tu_initial[:, i_barrier:] = numpy.array([rho_R, rho_R*vel_R, rho_R*(p_R/((gamma-1)*rho_R) + 0.5*vel_R**2)]).reshape((3,1))\n\n\treturn u_initial\n\ndef compute_f(u):\n\t\"\"\"\n\tCompute the vector function f(u)\n\t\n\tParameters\n\t----------\n\tu\t: array of floats\n\t\t\t3 by n array of values of rho, rho*vel, rho*e_T\n\t\t\t\n\tReturns\n\t-------\n\tf\t\t: array of floats\n\t\t\t3 by n array with columns [rho*vel, rho*vel**2 + p, (rho*e_T + p)*vel]\n\t\t\twhere e_T = p/((gamma-1)*rho) + 0.5*vel**2\t\n\t\"\"\"\n\t\n\tf = numpy.zeros_like(u)\n\tp = (gamma - 1)*(u[2,:] - 0.5*(u[1,:]**2)/u[0,:])\n\tf[0,:] = u[1,:]\n\tf[1,:] = (u[1,:]**2)/u[0,:] + p\n\tf[2,:] = (u[1,:]/u[0,:])*(u[2,:] + p)\n\t\n\treturn f\n\t\ndef richtmyer(u, nt, dt, dx):\n\t\"\"\"\n\tComputes the solution to the 1D shock equation using the Richtmyer method\n\t\n\tParameters\n\t---------\n\tu\t\t: array of floats\n\t\t\t3 by nx array of initial values of [rho, u, p]'\n\tnt\t\t: int\n\t\t\tnumber of timesteps to compute over\n\tdt\t\t: float\n\t\t\ttime stepsize\n\tnx\t\t: int\n\t\t\tn\n\t\t\t\n\tReturns\n\t-------\n\tu_1, u2, u3 : arrays of floats\n\t\t\tnt by u_initial.shape[1] array of values of rho, u, p at each time and spatial value\n\t\"\"\"\n\n\tnx = u.shape[1]\n\t\n\tu1 = numpy.zeros((nt,nx))\n\tu2 = numpy.zeros((nt,nx))\n\tu3 = numpy.zeros((nt,nx))\n\tu1[:,:] = u[0,:].copy()\n\tu2[:,:] = u[1,:].copy()\n\tu3[:,:] = u[2,:].copy()\n\t\n\tf_n = compute_f(u)\n\tu_half = numpy.zeros((3,nx-1))\n\tf_half = numpy.zeros((3,nx-1))\n\tu_n = numpy.zeros_like(u)\n\tu_n[:,:] = u.copy()\n\t\n\tfor t in range(1,nt):\n\t\tu_half[:,:] = 0.5*(u[:,1:] + u[:,:-1]) - dt/(2.0*dx)*(f_n[:,1:] - f_n[:,:-1])\n\t\tf_half = compute_f(u_half)\n\t\tu_n[:,1:-1] = u[:,1:-1] - (dt/dx)*(f_half[:,1:] - f_half[:,:-1])\n\t\tu[:,:] = u_n.copy()\n\t\tf_n = compute_f(u_n)\n\t\tu1[t,:] = u[0,:].copy()\n\t\tu2[t,:] = u[1,:].copy()\n\t\tu3[t,:] = u[2,:].copy()\n\t\t\n\treturn u1,u2,u3\t\n\t\t \n\t\t\ndef main():\n\ta = -10.0\n\tb = 10.0\n\tbarrier = 0.0\n\tparams = numpy.array([1.,0.,100000., 0.125, 0., 10000.])\n\tdt = 0.0002\n\tnt = 51\n\tnx = 81\n\tdx = (b-a)/(nx-1)\n\n\t\n\t#compute index at x = 2.5 meters\n\ti = 5*nx/8\n\t\n\tu_initial = compute_u_i(a, b, barrier, nx, params)\n\tu1,u2,u3 = richtmyer(u_initial, nt, dt, dx)\n\n\tfig = pyplot.figure()\n\tax = pyplot.axes(xlim=(a,b), ylim=(0,5),xlabel=('Position'),ylabel=('Density'))\n\tline, = ax.plot([],[],color='#003366', lw=2)\n\n\tdef animate(data):\n\t\tx = numpy.linspace(a,b,nx)\n\t\ty = data\n\t\tline.set_data(x,y)\n\t\treturn line,\n\n\tanim = animation.FuncAnimation(fig, animate, frames=u1, interval=50)\n\tpyplot.show()\n\n\trho = u1[-1,i]\n\tvel = u2[-1,i]/rho\n\tpressure = (gamma-1)*(u3[-1,i] - 0.5*rho*vel**2)\n\tprint(vel)\n\tprint(pressure)\n\tprint(rho)\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"module3/sods.py","file_name":"sods.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"488395363","text":"import sys\nsys.stdin = open(\"문제1_input.txt\")\n\ndef baby_gin(num_lst):\n cnt = 0\n number = [0,0,0,0,0,0,0,0,0,0]\n # num_lst를 순회하면서\n for i in num_lst:\n # 해당 값을 1회 올린다.\n number[i] += 1\n # 모든 카운팅이 끝나고 난 후\n run = 0\n triplet = 0\n # number리스트를 순회하면서\n for j in number:\n # 트리플렛부터 먼저 검사한다\n if j == 3:\n triplet += 1\n cnt = 0\n # run을 검사한다\n # 만약 j번째 카드가 1개 있다면\n elif j == 1:\n # 카운트 횟수를 1회 올려준다.\n cnt += 1\n # 만약 카운트 횟수가 3에 도달했다면\n if cnt == 3:\n # run횟수를 1회 올려주고\n run += 1\n # 카운트 횟수를 초기화한다.\n cnt = 0\n # 연속되지 않았다면\n else:\n # 카운트 횟수를 0으로 해준다.\n cnt = 0\n\n # 베이비진�� 모든 경우의 수\n # run이 2회인 경우\n if run == 2:\n return 1\n # run이 1회이고 triplet이 1회인 경우\n elif run == 1 and triplet == 1:\n return 1\n # triplet이 2회인 경우\n elif triplet == 2:\n return 1\n else:\n return 0\n\n\n\n\n\nfor tc in range(1,int(input())+1):\n num = input()\n num_lst = list()\n for i in range(len(num)):\n num_lst.append(int(num[i]))\n num_lst.sort()\n print(\"#{} {}\".format(tc, baby_gin(num_lst)))","sub_path":"시험전용폴더/Algo1_구미_2반_최준성.py","file_name":"Algo1_구미_2반_최준성.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"238773757","text":"'''\nYou are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.\n\nFor example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.\nYou will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.\n\nReturn the least number of buses you must take to travel from source to target. Return -1 if it is not possible.\n\n \n\nExample 1:\n\nInput: routes = [[1,2,7],[3,6,7]], source = 1, target = 6\nOutput: 2\nExplanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.\nExample 2:\n\nInput: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12\nOutput: -1\n \n\nConstraints:\n\n1 <= routes.length <= 500.\n1 <= routes[i].length <= 105\nAll the values of routes[i] are unique.\nsum(routes[i].length) <= 105\n0 <= routes[i][j] < 106\n0 <= source, target < 106\n\n'''\n\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if target == source:\n return 0\n \n stops = {}\n times = -1\n \n for bus in range(len(routes)):\n for stop in routes[bus]:\n if not stop in stops:\n stops[stop] = [bus]\n else:\n stops[stop].append(bus)\n\n for bus in stops[source]:\n queue = deque()\n queue.append((bus, 1))\n visited = set()\n \n while queue:\n bus, cnt = queue.pop()\n if bus in visited:\n continue\n else:\n visited.add(bus)\n if target in routes[bus]:\n if times < 0:\n times = cnt\n else:\n times = min(times, cnt)\n else:\n cnt += 1\n for i in routes[bus]:\n for j in stops[i]:\n queue.appendleft((j, cnt))\n \n return times\n \n \n \n \n ","sub_path":"Python3/815. Bus Routes.py","file_name":"815. Bus Routes.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"321298132","text":"# -----------------------------------------------------------\n# Fit and evaluate a set of models\n# -----------------------------------------------------------\n\nimport argparse as arg\nfrom src.models.fitting import ModelFitter\nfrom sklearn.dummy import DummyClassifier # dummy classification to be used as a benchmark\nfrom sklearn.naive_bayes import MultinomialNB # Naive Bayes\nfrom sklearn.linear_model import LogisticRegression # Logistic Regression\n\n\ndef main(train_prop, min_doc_freq):\n\n # definitions of the models we want to run (going forward we may want to add some grid search stuff)\n target_models = {\n 'DummyClassifier': DummyClassifier(random_state=1),\n 'MultinomialNB': MultinomialNB(alpha=0.1),\n 'LogisticRegression': LogisticRegression()\n }\n\n model_fitter = ModelFitter(train_prop=train_prop, min_doc_freq=min_doc_freq, defined_models=target_models)\n model_fitter.evaluate_models()\n\n for model, score in model_fitter.evaluation_score.items():\n print(\"model {} has f1 score of {}\".format(model, score))\n\n\nif __name__ == '__main__':\n ap = arg.ArgumentParser()\n ap.add_argument('--train_prop', type=float, default=0.6, required=False, help='Training proportion')\n ap.add_argument('--min_doc_freq', type=int, default=5, required=False, help='Min document frequency')\n args = ap.parse_args()\n main(train_prop=args.train_prop, min_doc_freq=args.min_doc_freq)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"530677981","text":"###########################################################################\n#\n# Copyright 2019 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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#\n###########################################################################\n\norderDocumentsListResponse_Schema = [\n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"nextPageToken\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"kind\"\n }, \n {\n \"fields\": [\n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"orderId\"\n }, \n {\n \"fields\": {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"approvedByUserProfileIds\"\n }, \n \"type\": \"RECORD\", \n \"name\": \"approvedByUserProfileIds\", \n \"mode\": \"REPEATED\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"kind\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"subaccountId\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"DATE\", \n \"description\": \"\", \n \"name\": \"effectiveDate\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"DATETIME\", \n \"description\": \"\", \n \"name\": \"lastSentTime\"\n }, \n {\n \"fields\": {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"lastSentRecipients\"\n }, \n \"type\": \"RECORD\", \n \"name\": \"lastSentRecipients\", \n \"mode\": \"REPEATED\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"title\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"amendedOrderDocumentId\"\n }, \n {\n \"type\": \"BOOLEAN\", \n \"name\": \"signed\", \n \"mode\": \"NULLABLE\"\n }, \n [\n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"time\"\n }\n ], \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"advertiserId\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"projectId\"\n }, \n {\n \"type\": \"BOOLEAN\", \n \"name\": \"cancelled\", \n \"mode\": \"NULLABLE\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"PLANNING_ORDER_TYPE_CHANGE_ORDER, PLANNING_ORDER_TYPE_INSERTION_ORDER\", \n \"name\": \"type\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"id\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"accountId\"\n }\n ], \n \"type\": \"RECORD\", \n \"name\": \"orderDocuments\", \n \"mode\": \"REPEATED\"\n }\n]\n","sub_path":"starthinker/task/dcm_api/schema/orderDocumentsListResponse.py","file_name":"orderDocumentsListResponse.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"4474784","text":"import gc\nimport os\nimport time\nimport logging\nimport datetime\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nimport lightgbm as lgb\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import stats\nfrom sklearn.svm import NuSVR, SVR\nfrom catboost import CatBoostRegressor\nfrom sklearn.kernel_ridge import KernelRidge\nfrom scipy.signal import hann, hilbert, convolve\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\nfrom sklearn.model_selection import KFold, StratifiedKFold, RepeatedKFold, cross_val_score\nfrom sklearn.metrics import roc_auc_score, mean_absolute_error, mean_squared_error\nfrom sklearn.model_selection import GridSearchCV\nfrom tqdm import tqdm\n\nfrom GBDT import myhyperopt\n\n# settings\nwarnings.filterwarnings('ignore')\nnp.random.seed(2019)\nPATH = \"E:/kaggle/kaggle-Lanl_Earthquake_Prediction/\"\n\nclean_idx = [x for x in range(4194, 4651)]\n\n# logger\ndef get_logger():\n FORMAT = '[%(levelname)s]%(asctime)s:%(name)s:%(message)s'\n logging.basicConfig(format=FORMAT)\n logger = logging.getLogger('main')\n logger.setLevel(logging.DEBUG)\n return logger\n\n\nlogger = get_logger()\n\n\ndef read_train_data(nrows=4096):\n # load data\n logger.info('Start read data')\n train_df = pd.read_csv(PATH + 'input/train.csv', dtype={'acoustic_data': np.int16, 'time_to_failure': np.float64},\n nrows=nrows)\n return train_df\n\n\ndef load_feature_data():\n logger.info('Start read feature data')\n\n # train_X = pd.DataFrame()\n train_features = pd.read_csv(PATH + 'data_sample/train_features.csv')\n train_features1 = pd.read_csv(PATH + 'feature_select/train_features_aug_bigsmall.csv')\n\n # train_features_denoised = pd.read_csv(PATH + 'input/lanl-features/train_features_denoised.csv')\n # train_features_denoised.columns = [f'{i}_denoised' for i in train_features_denoised.columns]\n train_mfcc_features = pd.read_csv(PATH + 'input/lanl-features/mfcc_train40.csv')\n\n # train_X = pd.concat([train_features, train_features1,train_mfcc_features], axis=1) #train_mfcc_features\n\n train_X = train_features # .ix[0:4193,:]\n\n scaler = StandardScaler()\n scaler.fit(train_X)\n scaled_train_X = pd.DataFrame(scaler.transform(train_X), columns=train_X.columns)\n\n # test_X = pd.DataFrame()\n test_features = pd.read_csv(PATH + 'data_sample/test_features.csv')\n test_features1 = pd.read_csv(PATH + 'feature_select/test_features_aug_bigsmall.csv')\n # test_features_denoised = pd.read_csv(PATH + 'input/lanl-features/test_features_denoised.csv')\n # test_features_denoised.columns = [f'{i}_denoised' for i in test_features_denoised.columns]\n test_mfcc_features = pd.read_csv(PATH + 'input/lanl-features/mfcc_test40.csv')\n mfcccol = list(train_mfcc_features.columns)\n\n # test_X = pd.concat([test_features, test_features1,test_mfcc_features], axis=1).drop(['seg_id'], axis=1) #test_mfcc_features.drop(['seg_id'], axis=1) #\n test_X = test_features\n\n scaled_test_X = pd.DataFrame(scaler.transform(test_X), columns=test_X.columns)\n\n train_y = pd.read_csv(PATH + 'data_sample/y.csv') # .ix[0:4193]\n submission = pd.read_csv(PATH + 'input/sample_submission.csv', index_col='seg_id')\n\n return scaled_train_X, scaled_test_X, train_y, submission, mfcccol\n\n\ndef add_trend_feature(arr, abs_values=False):\n idx = np.array(range(len(arr)))\n if abs_values:\n arr = np.abs(arr)\n lr = LinearRegression()\n lr.fit(idx.reshape(-1, 1), arr)\n return lr.coef_[0]\n\n\ndef classic_sta_lta(x, length_sta, length_lta):\n sta = np.cumsum(x ** 2)\n # Convert to float\n sta = np.require(sta, dtype=np.float)\n # Copy for LTA\n lta = sta.copy()\n # Compute the STA and the LTA\n sta[length_sta:] = sta[length_sta:] - sta[:-length_sta]\n sta /= length_sta\n lta[length_lta:] = lta[length_lta:] - lta[:-length_lta]\n lta /= length_lta\n # Pad zeros\n sta[:length_lta - 1] = 0\n # Avoid division by zero by setting zero values to tiny float\n dtiny = np.finfo(0.0).tiny\n idx = lta < dtiny\n lta[idx] = dtiny\n return sta / lta\n\n\ndef create_features(seg_id, seg, X):\n xc = pd.Series(seg['acoustic_data'].values)\n zc = np.fft.fft(xc)\n\n X.loc[seg_id, 'mean'] = xc.mean()\n X.loc[seg_id, 'std'] = xc.std()\n X.loc[seg_id, 'max'] = xc.max()\n X.loc[seg_id, 'min'] = xc.min()\n\n # FFT transform values\n realFFT = np.real(zc)\n imagFFT = np.imag(zc)\n X.loc[seg_id, 'Rmean'] = realFFT.mean()\n X.loc[seg_id, 'Rstd'] = realFFT.std()\n X.loc[seg_id, 'Rmax'] = realFFT.max()\n X.loc[seg_id, 'Rmin'] = realFFT.min()\n X.loc[seg_id, 'Imean'] = imagFFT.mean()\n X.loc[seg_id, 'Istd'] = imagFFT.std()\n X.loc[seg_id, 'Imax'] = imagFFT.max()\n X.loc[seg_id, 'Imin'] = imagFFT.min()\n X.loc[seg_id, 'Rmean_last_5000'] = realFFT[-5000:].mean()\n X.loc[seg_id, 'Rstd__last_5000'] = realFFT[-5000:].std()\n X.loc[seg_id, 'Rmax_last_5000'] = realFFT[-5000:].max()\n X.loc[seg_id, 'Rmin_last_5000'] = realFFT[-5000:].min()\n X.loc[seg_id, 'Rmean_last_15000'] = realFFT[-15000:].mean()\n X.loc[seg_id, 'Rstd_last_15000'] = realFFT[-15000:].std()\n X.loc[seg_id, 'Rmax_last_15000'] = realFFT[-15000:].max()\n X.loc[seg_id, 'Rmin_last_15000'] = realFFT[-15000:].min()\n\n X.loc[seg_id, 'mean_change_abs'] = np.mean(np.diff(xc))\n X.loc[seg_id, 'mean_change_rate'] = np.mean(np.nonzero((np.diff(xc) / xc[:-1]))[0])\n X.loc[seg_id, 'abs_max'] = np.abs(xc).max()\n # X.loc[seg_id, 'abs_min'] = np.abs(xc).min()\n\n X.loc[seg_id, 'std_first_50000'] = xc[:50000].std()\n X.loc[seg_id, 'std_last_50000'] = xc[-50000:].std()\n X.loc[seg_id, 'std_first_10000'] = xc[:10000].std()\n X.loc[seg_id, 'std_last_10000'] = xc[-10000:].std()\n\n X.loc[seg_id, 'avg_first_50000'] = xc[:50000].mean()\n X.loc[seg_id, 'avg_last_50000'] = xc[-50000:].mean()\n X.loc[seg_id, 'avg_first_10000'] = xc[:10000].mean()\n X.loc[seg_id, 'avg_last_10000'] = xc[-10000:].mean()\n\n X.loc[seg_id, 'min_first_50000'] = xc[:50000].min()\n X.loc[seg_id, 'min_last_50000'] = xc[-50000:].min()\n X.loc[seg_id, 'min_first_10000'] = xc[:10000].min()\n X.loc[seg_id, 'min_last_10000'] = xc[-10000:].min()\n\n X.loc[seg_id, 'max_first_50000'] = xc[:50000].max()\n X.loc[seg_id, 'max_last_50000'] = xc[-50000:].max()\n X.loc[seg_id, 'max_first_10000'] = xc[:10000].max()\n X.loc[seg_id, 'max_last_10000'] = xc[-10000:].max()\n\n X.loc[seg_id, 'max_to_min'] = xc.max() / np.abs(xc.min())\n X.loc[seg_id, 'max_to_min_diff'] = xc.max() - np.abs(xc.min())\n X.loc[seg_id, 'count_big'] = len(xc[np.abs(xc) > 500])\n X.loc[seg_id, 'sum'] = xc.sum()\n\n X.loc[seg_id, 'mean_change_rate_first_50000'] = np.mean(np.nonzero((np.diff(xc[:50000]) / xc[:50000][:-1]))[0])\n X.loc[seg_id, 'mean_change_rate_last_50000'] = np.mean(np.nonzero((np.diff(xc[-50000:]) / xc[-50000:][:-1]))[0])\n X.loc[seg_id, 'mean_change_rate_first_10000'] = np.mean(np.nonzero((np.diff(xc[:10000]) / xc[:10000][:-1]))[0])\n X.loc[seg_id, 'mean_change_rate_last_10000'] = np.mean(np.nonzero((np.diff(xc[-10000:]) / xc[-10000:][:-1]))[0])\n\n X.loc[seg_id, 'q95'] = np.quantile(xc, 0.95)\n X.loc[seg_id, 'q99'] = np.quantile(xc, 0.99)\n X.loc[seg_id, 'q05'] = np.quantile(xc, 0.05)\n X.loc[seg_id, 'q01'] = np.quantile(xc, 0.01)\n\n X.loc[seg_id, 'abs_q95'] = np.quantile(np.abs(xc), 0.95)\n X.loc[seg_id, 'abs_q99'] = np.quantile(np.abs(xc), 0.99)\n X.loc[seg_id, 'abs_q05'] = np.quantile(np.abs(xc), 0.05)\n X.loc[seg_id, 'abs_q01'] = np.quantile(np.abs(xc), 0.01)\n\n X.loc[seg_id, 'trend'] = add_trend_feature(xc)\n X.loc[seg_id, 'abs_trend'] = add_trend_feature(xc, abs_values=True)\n X.loc[seg_id, 'abs_mean'] = np.abs(xc).mean()\n X.loc[seg_id, 'abs_std'] = np.abs(xc).std()\n\n X.loc[seg_id, 'mad'] = xc.mad()\n X.loc[seg_id, 'kurt'] = xc.kurtosis()\n X.loc[seg_id, 'skew'] = xc.skew()\n X.loc[seg_id, 'med'] = xc.median()\n\n X.loc[seg_id, 'Hilbert_mean'] = np.abs(hilbert(xc)).mean()\n X.loc[seg_id, 'Hann_window_mean'] = (convolve(xc, hann(150), mode='same') / sum(hann(150))).mean()\n X.loc[seg_id, 'classic_sta_lta1_mean'] = classic_sta_lta(xc, 500, 10000).mean()\n X.loc[seg_id, 'classic_sta_lta2_mean'] = classic_sta_lta(xc, 5000, 100000).mean()\n X.loc[seg_id, 'classic_sta_lta3_mean'] = classic_sta_lta(xc, 3333, 6666).mean()\n X.loc[seg_id, 'classic_sta_lta4_mean'] = classic_sta_lta(xc, 10000, 25000).mean()\n X.loc[seg_id, 'Moving_average_700_mean'] = xc.rolling(window=700).mean().mean(skipna=True)\n X.loc[seg_id, 'Moving_average_1500_mean'] = xc.rolling(window=1500).mean().mean(skipna=True)\n X.loc[seg_id, 'Moving_average_3000_mean'] = xc.rolling(window=3000).mean().mean(skipna=True)\n X.loc[seg_id, 'Moving_average_6000_mean'] = xc.rolling(window=6000).mean().mean(skipna=True)\n ewma = pd.Series.ewm\n X.loc[seg_id, 'exp_Moving_average_300_mean'] = (ewma(xc, span=300).mean()).mean(skipna=True)\n X.loc[seg_id, 'exp_Moving_average_3000_mean'] = ewma(xc, span=3000).mean().mean(skipna=True)\n X.loc[seg_id, 'exp_Moving_average_30000_mean'] = ewma(xc, span=6000).mean().mean(skipna=True)\n no_of_std = 2\n X.loc[seg_id, 'MA_700MA_std_mean'] = xc.rolling(window=700).std().mean()\n X.loc[seg_id, 'MA_700MA_BB_high_mean'] = (\n X.loc[seg_id, 'Moving_average_700_mean'] + no_of_std * X.loc[seg_id, 'MA_700MA_std_mean']).mean()\n X.loc[seg_id, 'MA_700MA_BB_low_mean'] = (\n X.loc[seg_id, 'Moving_average_700_mean'] - no_of_std * X.loc[seg_id, 'MA_700MA_std_mean']).mean()\n X.loc[seg_id, 'MA_400MA_std_mean'] = xc.rolling(window=400).std().mean()\n X.loc[seg_id, 'MA_400MA_BB_high_mean'] = (\n X.loc[seg_id, 'Moving_average_700_mean'] + no_of_std * X.loc[seg_id, 'MA_400MA_std_mean']).mean()\n X.loc[seg_id, 'MA_400MA_BB_low_mean'] = (\n X.loc[seg_id, 'Moving_average_700_mean'] - no_of_std * X.loc[seg_id, 'MA_400MA_std_mean']).mean()\n X.loc[seg_id, 'MA_1000MA_std_mean'] = xc.rolling(window=1000).std().mean()\n\n X.loc[seg_id, 'iqr'] = np.subtract(*np.percentile(xc, [75, 25]))\n X.loc[seg_id, 'q999'] = np.quantile(xc, 0.999)\n X.loc[seg_id, 'q001'] = np.quantile(xc, 0.001)\n X.loc[seg_id, 'ave10'] = stats.trim_mean(xc, 0.1)\n\n for windows in [10, 100, 1000]:\n x_roll_std = xc.rolling(windows).std().dropna().values\n x_roll_mean = xc.rolling(windows).mean().dropna().values\n\n X.loc[seg_id, 'ave_roll_std_' + str(windows)] = x_roll_std.mean()\n X.loc[seg_id, 'std_roll_std_' + str(windows)] = x_roll_std.std()\n X.loc[seg_id, 'max_roll_std_' + str(windows)] = x_roll_std.max()\n X.loc[seg_id, 'min_roll_std_' + str(windows)] = x_roll_std.min()\n X.loc[seg_id, 'q01_roll_std_' + str(windows)] = np.quantile(x_roll_std, 0.01)\n X.loc[seg_id, 'q05_roll_std_' + str(windows)] = np.quantile(x_roll_std, 0.05)\n X.loc[seg_id, 'q95_roll_std_' + str(windows)] = np.quantile(x_roll_std, 0.95)\n X.loc[seg_id, 'q99_roll_std_' + str(windows)] = np.quantile(x_roll_std, 0.99)\n X.loc[seg_id, 'av_change_abs_roll_std_' + str(windows)] = np.mean(np.diff(x_roll_std))\n X.loc[seg_id, 'av_change_rate_roll_std_' + str(windows)] = np.mean(\n np.nonzero((np.diff(x_roll_std) / x_roll_std[:-1]))[0])\n X.loc[seg_id, 'abs_max_roll_std_' + str(windows)] = np.abs(x_roll_std).max()\n\n X.loc[seg_id, 'ave_roll_mean_' + str(windows)] = x_roll_mean.mean()\n X.loc[seg_id, 'std_roll_mean_' + str(windows)] = x_roll_mean.std()\n X.loc[seg_id, 'max_roll_mean_' + str(windows)] = x_roll_mean.max()\n X.loc[seg_id, 'min_roll_mean_' + str(windows)] = x_roll_mean.min()\n X.loc[seg_id, 'q01_roll_mean_' + str(windows)] = np.quantile(x_roll_mean, 0.01)\n X.loc[seg_id, 'q05_roll_mean_' + str(windows)] = np.quantile(x_roll_mean, 0.05)\n X.loc[seg_id, 'q95_roll_mean_' + str(windows)] = np.quantile(x_roll_mean, 0.95)\n X.loc[seg_id, 'q99_roll_mean_' + str(windows)] = np.quantile(x_roll_mean, 0.99)\n X.loc[seg_id, 'av_change_abs_roll_mean_' + str(windows)] = np.mean(np.diff(x_roll_mean))\n X.loc[seg_id, 'av_change_rate_roll_mean_' + str(windows)] = np.mean(\n np.nonzero((np.diff(x_roll_mean) / x_roll_mean[:-1]))[0])\n X.loc[seg_id, 'abs_max_roll_mean_' + str(windows)] = np.abs(x_roll_mean).max()\n\n\ndef feature_engineering(train_df):\n # features engineering\n logger.info('Features engineering')\n rows = 150000\n segments = int(np.floor(train_df.shape[0] / rows))\n print(\"Number of segments: \", segments)\n train_X = pd.DataFrame(index=range(segments), dtype=np.float64)\n train_y = pd.DataFrame(index=range(segments), dtype=np.float64, columns=['time_to_failure'])\n\n # process train data\n logger.info('Process train data')\n for seg_id in range(segments):\n seg = train_df.iloc[seg_id * rows:seg_id * rows + rows]\n create_features(seg_id, seg, train_X)\n train_y.loc[seg_id, 'time_to_failure'] = seg['time_to_failure'].values[-1]\n\n scaler = StandardScaler()\n scaler.fit(train_X)\n scaled_train_X = pd.DataFrame(scaler.transform(train_X), columns=train_X.columns)\n\n # process test data\n logger.info('Process test data')\n submission = pd.read_csv(PATH + 'input/sample_submission.csv', index_col='seg_id')\n test_X = pd.DataFrame(columns=train_X.columns, dtype=np.float64, index=submission.index)\n\n for seg_id in test_X.index:\n seg = pd.read_csv(PATH + 'input/test/' + seg_id + '.csv')\n create_features(seg_id, seg, test_X)\n scaled_test_X = pd.DataFrame(scaler.transform(test_X), columns=test_X.columns)\n\n del train_df\n gc.collect()\n\n scaled_train_X.to_csv(PATH + 'GBDT/feature_extra/train_feature.csv', index=False)\n scaled_test_X.to_csv(PATH + 'GBDT/feature_extra/test_feature.csv', index=False)\n train_y.to_csv(PATH + 'GBDT/feature_extra/train_y.csv', index=False)\n\n return scaled_train_X, scaled_test_X, train_y, submission\n\n\ndef data_augmentation(train, aug_ratio=0.5):\n a = np.arange(0, train.shape[1]) #\n # initialise aug dataframe - remember to set dtype!\n train_aug = pd.DataFrame(index=train.index, columns=train.columns, dtype='float64')\n\n for i in tqdm(range(0, len(train))): # 样本数量4194\n # ratio of features to be randomly sampled\n AUG_FEATURE_RATIO = aug_ratio\n # to integer count\n AUG_FEATURE_COUNT = np.floor(train.shape[1] * AUG_FEATURE_RATIO).astype('int16')\n\n # randomly sample half of columns that will contain random values #如果是ndarray数组,随机样本在该数组获取(取数据元素),如果是整型数据随机样本生成类似np.arange(n)\n aug_feature_index = np.random.choice(train.shape[1], AUG_FEATURE_COUNT, replace=False)\n aug_feature_index.sort()\n\n # obtain indices for features not in aug_feature_index #\n feature_index = np.where(np.logical_not(np.in1d(a, aug_feature_index)))[0]\n\n # first insert real values for features in feature_index #将未被增强的特征按原始数据保存下来\n train_aug.iloc[i, feature_index] = train.iloc[i, feature_index]\n\n # random row index to randomly sampled values for each features #从原始样本中随机抽取与增强特征数量相同的样本 (即增强的特征只作用于部分样本)\n rand_row_index = np.random.choice(len(train), len(aug_feature_index), replace=True)\n\n # for each feature being randomly sampled, extract value from random row in train\n for n, j in enumerate(aug_feature_index): # 即增强的特征 只更新 n 个样本 n=增强特征数\n train_aug.iloc[i, j] = train.iloc[rand_row_index[n], j]\n\n return train_aug # 过采样产生的数据,将其与train_x拼接融合\n\n\ndef run_model_xgb(scaled_train_X, scaled_test_X, train_y, feature_col):\n logger.info('Run xgb model')\n n_fold = 10\n folds = KFold(n_splits=n_fold, shuffle=True, random_state=42)\n train_columns = feature_col\n random_seed = 4126\n predictions = np.zeros(len(scaled_test_X))\n preds_train = np.zeros(len(scaled_train_X))\n\n maes = []\n tr_maes = []\n\n for fold_, (trn_idx, val_idx) in enumerate(folds.split(scaled_train_X, train_y.values)):\n print('working fold %d' % fold_)\n strLog = \"fold {}\".format(fold_)\n print(strLog)\n\n X_tr, X_val = scaled_train_X.iloc[trn_idx], scaled_train_X.iloc[val_idx]\n y_tr, y_val = train_y.iloc[trn_idx], train_y.iloc[val_idx]\n\n clf = xgb.XGBRegressor(n_estimators=10000,\n learning_rate=0.1,\n max_depth=6,\n subsample=0.9,\n colsample_bytree=0.67,\n reg_lambda=1.0, # seems best within 0.5 of 2.0\n # gamma=1,\n random_state=random_seed,\n n_jobs=12,\n verbosity=-1)\n clf.fit(X_tr, y_tr)\n preds = clf.predict(scaled_test_X) # , num_iteration=model.best_iteration_)\n predictions += preds / folds.n_splits\n preds = clf.predict(scaled_train_X) # , num_iteration=model.best_iteration_)\n preds_train += preds / folds.n_splits\n\n preds = clf.predict(X_tr)\n mae = mean_absolute_error(y_tr, preds)\n print('Tr MAE: %.6f' % mae)\n maes.append(mae)\n\n preds = clf.predict(X_val)\n mae = mean_absolute_error(y_val, preds)\n print('MAE: %.6f' % mae)\n tr_maes.append(mae)\n\n\ndef run_model_lgbm(params, scaled_train_X, scaled_test_X, train_y, res):\n logger.info('Run lgbm model')\n n_fold = 5\n folds = KFold(n_splits=n_fold, shuffle=True, random_state=2013)\n # train_columns = feature_col\n\n scores = []\n\n oof = np.zeros(len(scaled_train_X))\n predictions = np.zeros(len(scaled_test_X))\n feature_importance_df = pd.DataFrame()\n\n\n feat = scaled_train_X.columns\n\n # run model\n # a = folds.split(scaled_train_X, train_y.values)\n for fold_, (trn_idx, val_idx) in enumerate(folds.split(scaled_train_X, train_y.values)):\n print(\"fold {}\".format(fold_))\n logger.info(\"fold {}\".format(fold_))\n\n val_idx = val_idx[val_idx < 4193]\n\n X_tr, X_val = scaled_train_X.iloc[trn_idx], scaled_train_X.iloc[val_idx]\n y_tr, y_val = train_y.iloc[trn_idx], train_y.iloc[val_idx]\n\n clf = lgb.LGBMRegressor(**params, n_estimators=200000, n_jobs=-1)\n\n clf.fit(X_tr, y_tr, eval_set=[(X_tr, y_tr), (X_val, y_val)], eval_metric='mae', verbose=1000,\n early_stopping_rounds=400)\n\n oof[val_idx] = clf.predict(X_val, num_iteration=clf.best_iteration_)\n # feature importance\n\n # fold_importance_df = pd.DataFrame()\n # fold_importance_df[\"Feature\"] = train_columns\n # fold_importance_df[\"importance\"] = clf.feature_importances_[:len(train_columns)]\n # fold_importance_df[\"fold\"] = fold_ + 1\n # feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)\n\n # predictions\n predictions += clf.predict(scaled_test_X, num_iteration=clf.best_iteration_) / folds.n_splits\n scores.append(mean_absolute_error(y_val, oof[val_idx]))\n res.ix[0,feat] = np.mean(scores)\n res.ix[1, feat] = np.std(scores)\n res.to_csv('998cv_rank.csv')\n\n # feature_importance_df = feature_importance_df.groupby(['Feature']).mean()\n # feature_importance_df.to_csv('E:/kaggle/kaggle-Lanl_Earthquake_Prediction/data_sample/feature_importance.csv')\n strLog = 'CV mean score: {0:.4f}, std: {1:.4f}.'.format(np.mean(scores), np.std(scores))\n print(strLog)\n logger.info(strLog)\n\n # return oof, predictions, feature_importance_df, mean_absolute_error(train_y.values, oof)\n\n\ndef plt_feature_importance(feature_importance_df):\n logger.info('Plot feature importance')\n cols = (feature_importance_df[[\"Feature\", \"importance\"]]\n .groupby(\"Feature\")\n .mean()\n .sort_values(by=\"importance\", ascending=False)[:200].index)\n best_features = feature_importance_df.loc[feature_importance_df.Feature.isin(cols)]\n # d_features = best_features.groupby(['Feature']).mean()\n # d_features.to_csv('best_features.csv')\n plt.figure(figsize=(14, 26))\n sns.barplot(x=\"importance\", y=\"Feature\", data=best_features.sort_values(by=\"importance\", ascending=False))\n plt.title('LightGBM Features (averaged over folds)')\n plt.tight_layout()\n plt.savefig('lgbm_importances.png')\n\n\ndef submit(submission, predictions, i):\n # submission\n logger.info('Submisison')\n submission.time_to_failure = predictions\n submission.to_csv('./Lightgbm_result/submission_' + str(i) + '_auc.csv', index=True)\n\n\ndef main(nrows=None):\n # train_df = read_train_data(nrows)\n # scaled_train_X, scaled_test_X, train_y, submission = feature_engineering(train_df)\n scaled_train_X, scaled_test_X, train_y, submission, mfcccols = load_feature_data()\n # feature_importance_df = pd.read_csv('feature_importance.csv')\n #\n # cols = list((feature_importance_df[[\"Feature\", \"importance\"]]\n # .groupby(\"Feature\")\n # .mean()\n # .sort_values(by=\"importance\", ascending=False)[:].index))[:200]\n # cols.extend(scaled_train_X.columns[-20:])\n # dd = pd.read_excel(PATH + 'input/lanl-features/features_select2.xlsx',header=None)\n # dd.columns = ['feat']\n # cols = list(dd['feat']) + list(mfcccols)\n\n # best_feat = pd.read_csv('best_features.csv')\n # best_feat1 = best_feat[best_feat['importance'] >= 1]\n # cols1 = list(best_feat1['feat'])\n\n # sele = pd.read_csv(PATH + '/feat_val/feat_auc_now998.csv').T\n # sele.columns = ['mean', 'std']\n # sele = sele.sort_values('mean', ascending=False)\n # selec = sele.copy()\n # sele_hold = sele[sele['mean'] < 0.8]\n # #\n # # # hold_auc = pd.Series(list(sele_hold.index))\n # # # hold_auc.to_csv('E:/kaggle/kaggle-Lanl_Earthquake_Prediction/feat_val/hold_feat.csv',index=False)\n # #\n # sele_hold = list(sele_hold.index)\n # cols = sele_hold\n #\n # #\n # scaled_train_X = scaled_train_X[cols]\n # scaled_test_X = scaled_test_X[cols]\n\n # l = [0.5]\n # res = []\n # for i in l:\n #\n # train_X_aug = data_augmentation(scaled_train_X,i)\n # train_y_aug = data_augmentation(train_y,i)\n # train_all = pd.concat([scaled_train_X, train_X_aug])\n # y_all = pd.concat([train_y, train_y_aug])\n\n # lgbm_params = myhyperopt.quick_hyperopt(train_all, y_all, 'lgbm', 2500)\n\n lgbm_params = {'num_leaves': 60,\n 'min_data_in_leaf': 79,\n 'objective': 'gamma',\n 'max_depth': -1,\n 'learning_rate': 0.02,\n \"boosting\": \"gbdt\",\n \"bagging_freq\": 5,\n \"bagging_fraction\": 0.8126672064208567,\n \"bagging_seed\": 1024,\n \"metric\": 'mae',\n \"verbosity\": -1,\n 'reg_alpha': 0.1302650970728192,\n 'reg_lambda': 0.3603427518866501,\n 'feature_fraction': 0.2,\n 'colsample_bytree': 1.0\n }\n\n features = scaled_train_X.columns\n res = pd.DataFrame(columns=features, index=[0, 1])\n\n for i in tqdm(range(len(features))):\n feat = features[i]\n pan = scaled_train_X[feat].unique()\n if len(pan) <= 30: continue\n\n run_model_lgbm(lgbm_params, scaled_train_X[[feat]], scaled_test_X[[feat]], train_y,\n res)\n\n # run_model_xgb(scaled_train_X,scaled_test_X, train_y,scaled_train_X.columns)\n # submit(submission, predictions, 'seed')\n # # res.append(mae)\n # plt_feature_importance(feature_importance)\n # plt.figure(figsize=(16, 8))\n # plt.plot(train_y, color='g', label='y_train')\n # plt.plot(oof, color='r', label='lgb')\n # plt.legend()\n # plt.title('Predictions vs actual')\n # plt.show()\n # print(res)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"adversarial_validation/feat_ligbm.py","file_name":"feat_ligbm.py","file_ext":"py","file_size_in_byte":24277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"465764295","text":"\n\n#calss header\nclass _OPERATIVE():\n\tdef __init__(self,): \n\t\tself.name = \"OPERATIVE\"\n\t\tself.definitions = [u'a worker, especially one who is skilled in working with their hands: ', u'a person who works secretly for an organization: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_operative.py","file_name":"_operative.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"316610176","text":"# log.py\n#\n#\n\n\"\"\" logging infrastructure. \"\"\"\n\n__copyright__ = \"Copyright 2015, Bart Thate\"\n\nfrom meds.defines import BOLD, BLA, BLUE, RED, GREEN, YELLOW, ENDC, homedir, logdir, datefmt, format, format_large, LEVELS\nfrom meds.misc import cdir, j\n\nimport logging.handlers\nimport logging\nimport os\n\nclass Formatter(logging.Formatter):\n\n def format(self, record):\n target = str(record.msg)\n if not target: target = \" \"\n if target[0] in [\">\", ]: target = \"%s%s%s%s\" % (BLUE, target[0], ENDC, target[1:])\n elif target[0] in [\"<\", ]: target = \"%s%s%s%s\" % (GREEN, target[0], ENDC, target[1:])\n elif target[0] in [\"!\", ]: target = \"%s%s%s%s\" % (BLUE, target[0], ENDC, target[1:])\n elif target[0] in [\"#\", ]: target = \"%s%s%s%s\" % (BLA, target[0], ENDC, target[1:])\n elif target[0] in [\"^\", ]: target = \"%s%s%s%s\" % (YELLOW, target[0], ENDC, target[1:])\n elif target[0] in [\"-\", ]: target = \"%s%s%s%s\" % (BOLD, target[0], ENDC, target[1:])\n elif target[0] in [\"&\", ]: target = \"%s%s%s%s\" % (RED, target[0], ENDC, target[1:])\n record.msg = target\n return logging.Formatter.format(self, record)\n\nclass FormatterClean(logging.Formatter):\n\n def format(self, record):\n target = str(record.msg)\n if not target: target = \" \"\n if target[0] in [\">\", \"<\", \"!\", \"#\", \"^\", \"-\", \"&\"]: target = target[2:]\n record.msg = target\n return logging.Formatter.format(self, record)\n\ndef log(level, error):\n l = LEVELS.get(str(level).lower(), logging.NOTSET)\n logging.log(l, error)\n\ndef loglevel(loglevel, colors=True):\n logger = logging.getLogger(\"\")\n if colors: formatter = Formatter(format, datefmt=datefmt)\n else: formatter = FormatterClean(format, datefmt=datefmt)\n level = LEVELS.get(str(loglevel).lower(), logging.NOTSET)\n filehandler = None\n logger.setLevel(level)\n if logger.handlers:\n for handler in logger.handlers: logger.removeHandler(handler)\n if not os.path.exists(logdir): cdir(logdir)\n try: filehandler = logging.handlers.TimedRotatingFileHandler(j(logdir, \"meds.log\"), 'midnight')\n except Exception as ex: logging.error(ex)\n ch = logging.StreamHandler()\n ch.setLevel(level)\n if colors: ch.setFormatter(formatter)\n else: ch.setFormatter(formatter)\n logger.addHandler(ch)\n if filehandler:\n ch.setFormatter(formatter)\n filehandler.setLevel(level)\n logger.addHandler(filehandler)\n global enabled\n enabled = True\n return logger\n","sub_path":"meds/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"487238565","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_policy import policy\n\nfrom neutron.conf.policies import base\n\n\nCOLLECTION_PATH = '/routers'\nRESOURCE_PATH = '/routers/{id}'\n\nACTION_POST = [\n {'method': 'POST', 'path': COLLECTION_PATH},\n]\nACTION_PUT = [\n {'method': 'PUT', 'path': RESOURCE_PATH},\n]\nACTION_DELETE = [\n {'method': 'DELETE', 'path': RESOURCE_PATH},\n]\nACTION_GET = [\n {'method': 'GET', 'path': COLLECTION_PATH},\n {'method': 'GET', 'path': RESOURCE_PATH},\n]\n\n\nrules = [\n policy.DocumentedRuleDefault(\n 'create_router',\n base.RULE_ANY,\n 'Create a router',\n ACTION_POST\n ),\n policy.DocumentedRuleDefault(\n 'create_router:distributed',\n base.RULE_ADMIN_ONLY,\n 'Specify ``distributed`` attribute when creating a router',\n ACTION_POST\n ),\n policy.DocumentedRuleDefault(\n 'create_router:ha',\n base.RULE_ADMIN_ONLY,\n 'Specify ``ha`` attribute when creating a router',\n ACTION_POST\n ),\n policy.DocumentedRuleDefault(\n 'create_router:external_gateway_info',\n base.RULE_ADMIN_OR_OWNER,\n 'Specify ``external_gateway_info`` information when creating a router',\n ACTION_POST\n ),\n policy.DocumentedRuleDefault(\n 'create_router:external_gateway_info:network_id',\n base.RULE_ADMIN_OR_OWNER,\n ('Specify ``network_id`` in ``external_gateway_info`` information '\n 'when creating a router'),\n ACTION_POST\n ),\n policy.DocumentedRuleDefault(\n 'create_router:external_gateway_info:enable_snat',\n base.RULE_ADMIN_ONLY,\n ('Specify ``enable_snat`` in ``external_gateway_info`` information '\n 'when creating a router'),\n ACTION_POST\n ),\n policy.DocumentedRuleDefault(\n 'create_router:external_gateway_info:external_fixed_ips',\n base.RULE_ADMIN_ONLY,\n ('Specify ``external_fixed_ips`` in ``external_gateway_info`` '\n 'information when creating a router'),\n ACTION_POST\n ),\n\n policy.DocumentedRuleDefault(\n 'get_router',\n base.RULE_ADMIN_OR_OWNER,\n 'Get a router',\n ACTION_GET\n ),\n policy.DocumentedRuleDefault(\n 'get_router:distributed',\n base.RULE_ADMIN_ONLY,\n 'Get ``distributed`` attribute of a router',\n ACTION_GET\n ),\n policy.DocumentedRuleDefault(\n 'get_router:ha',\n base.RULE_ADMIN_ONLY,\n 'Get ``ha`` attribute of a router',\n ACTION_GET\n ),\n\n policy.DocumentedRuleDefault(\n 'update_router',\n base.RULE_ADMIN_OR_OWNER,\n 'Update a router',\n ACTION_PUT\n ),\n policy.DocumentedRuleDefault(\n 'update_router:distributed',\n base.RULE_ADMIN_ONLY,\n 'Update ``distributed`` attribute of a router',\n ACTION_PUT\n ),\n policy.DocumentedRuleDefault(\n 'update_router:ha',\n base.RULE_ADMIN_ONLY,\n 'Update ``ha`` attribute of a router',\n ACTION_PUT\n ),\n policy.DocumentedRuleDefault(\n 'update_router:external_gateway_info',\n base.RULE_ADMIN_OR_OWNER,\n 'Update ``external_gateway_info`` information of a router',\n ACTION_PUT\n ),\n policy.DocumentedRuleDefault(\n 'update_router:external_gateway_info:network_id',\n base.RULE_ADMIN_OR_OWNER,\n ('Update ``network_id`` attribute of ``external_gateway_info`` '\n 'information of a router'),\n ACTION_PUT\n ),\n policy.DocumentedRuleDefault(\n 'update_router:external_gateway_info:enable_snat',\n base.RULE_ADMIN_ONLY,\n ('Update ``enable_snat`` attribute of ``external_gateway_info`` '\n 'information of a router'),\n ACTION_PUT\n ),\n policy.DocumentedRuleDefault(\n 'update_router:external_gateway_info:external_fixed_ips',\n base.RULE_ADMIN_ONLY,\n ('Update ``external_fixed_ips`` attribute of '\n '``external_gateway_info`` information of a router'),\n ACTION_PUT\n ),\n\n policy.DocumentedRuleDefault(\n 'delete_router',\n base.RULE_ADMIN_OR_OWNER,\n 'Delete a router',\n ACTION_DELETE\n ),\n\n policy.DocumentedRuleDefault(\n 'add_router_interface',\n base.RULE_ADMIN_OR_OWNER,\n 'Add an interface to a router',\n [\n {\n 'method': 'PUT',\n 'path': '/routers/{id}/add_router_interface',\n },\n ]\n ),\n policy.DocumentedRuleDefault(\n 'remove_router_interface',\n base.RULE_ADMIN_OR_OWNER,\n 'Remove an interface from a router',\n [\n {\n 'method': 'PUT',\n 'path': '/routers/{id}/remove_router_interface',\n },\n ]\n ),\n]\n\n\ndef list_rules():\n return rules\n","sub_path":"neutron/conf/policies/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":5309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"416559978","text":"from django.db import models\nfrom django.contrib.auth.models import Group\nfrom django.core import serializers\nfrom django.core.files.base import File\nfrom django.utils.timezone import now\n\nfrom periods.models import AcademicYear\nfrom university_structure.models import College\n\n#### For data dump\nimport tempfile\n\nimport os\nimport os.path\nfrom datetime import datetime\n\n\n######################################################################################################################\n####################### Committee Data\n\nclass Committee(models.Model):\n committee_id = models.BigAutoField(primary_key=True, verbose_name=\"Campus ID\")\n committee_name_ar = models.CharField(max_length=500, verbose_name=\"Committee Arabic Name\")\n committee_name_en = models.CharField(max_length=500, verbose_name=\"Committee Name\")\n committee_name_en_small = models.CharField(max_length=500, verbose_name='Committee Small Name',\n help_text='The small name and the academic year should be unique for a given committee')\n college = models.ForeignKey(College, on_delete=models.CASCADE, verbose_name='College')\n\n academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE, verbose_name='Academic Year',\n help_text='The small name and the academic year should be unique for a given committee')\n\n committee_head_group = models.ForeignKey(Group, verbose_name=\"Head Group\", on_delete=models.CASCADE,\n related_name='committees_heading', null=True, blank=True,\n help_text='Keep it blank to create a group automatically')\n committee_members_group = models.ForeignKey(Group, verbose_name=\"Members Group\", on_delete=models.CASCADE,\n related_name='committees_member', null=True, blank=True,\n help_text='Keep it blank to create a group automatically')\n committee_customers_group = models.ForeignKey(Group, verbose_name=\"Customers Group\", on_delete=models.CASCADE,\n related_name='committees_customer', null=True, blank=True,\n help_text='Keep it blank to create a group automatically')\n\n def __str__(self):\n return str(\n self.academic_year) + '| College__' + self.college.college_name_en_small + '| committee__' + self.committee_name_en_small\n\n def save(self, *args, **kwargs):\n if self.committee_head_group is None:\n _group = Group()\n _group.name = str(self) + '__head'\n _group.save()\n self.committee_head_group = _group\n\n if self.committee_members_group is None:\n _group = Group()\n _group.name = str(self) + '__members'\n _group.save()\n self.committee_members_group = _group\n\n if self.committee_customers_group is None:\n _group = Group()\n _group.name = str(self) + '__custmers'\n _group.save()\n self.committee_customers_group = _group\n\n super().save(*args, **kwargs)\n\n class Meta:\n ordering = ['college', 'academic_year', 'committee_name_en', ]\n verbose_name_plural = \"Committees\"\n verbose_name = \"Committee\"\n unique_together = [['committee_name_en_small', 'academic_year']]\n # constraints = [\n # models.UniqueConstraint(fields=['committee_name_en_small', 'academic_year'],\n # name='committee_academic_year'),\n # ]\n indexes = [\n models.Index(fields=['committee_name_ar', ]),\n models.Index(fields=['committee_name_en', ]),\n models.Index(fields=['committee_name_en_small', ]),\n models.Index(fields=['academic_year', ]),\n models.Index(fields=['college', ]),\n ]\n\n\n###############################################################################################\n######################### Data dump\n\n\ndef create_path(instance, filename):\n _datetime = datetime.now()\n _year = _datetime.strftime(\"%Y\")\n _mounth = _datetime.strftime(\"%m\")\n _day = _datetime.strftime(\"%d\")\n return 'dump/committees/{0}/{1}/{2}/{3}.json'.format(_year, _mounth, _day, filename)\n\n\nclass DataFile(models.Model):\n data_file_id = models.BigAutoField(primary_key=True)\n data_dump_date = models.DateTimeField(default=now, editable=False, blank=True)\n data_file_committee = models.FileField(upload_to=create_path, verbose_name='Committees Dump File',\n null=True, blank=True,\n help_text='Keep it blank to create a dump file automatically')\n\n def delete(self, *args, **kwargs):\n self.data_file_committee.delete()\n super().delete(*args, **kwargs)\n\n def save(self, *args, **kwargs):\n try:\n if os.path.isfile(self.data_file_committee.path):\n pass\n except:\n # save academic years\n fo1 = tempfile.NamedTemporaryFile()\n data = serializers.serialize(\"json\", Committee.objects.all())\n out = open(fo1.name, \"w\")\n out.write(data)\n out.close()\n self.data_file_committee.save(os.path.basename(fo1.name), File(fo1))\n\n super().save(*args, **kwargs)\n\n def __str__(self):\n return '[Committees] dump_' + str(self.data_dump_date)\n\n class Meta:\n ordering = ['data_dump_date']\n verbose_name_plural = \"Dumps\"\n verbose_name = \"Dump\"\n indexes = [\n models.Index(fields=['data_dump_date', ]),\n ]\n","sub_path":"committees/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"499344791","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom os.path import abspath, basename, dirname, join, normpath\n\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\n\n#BASE_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n########## PATH CONFIGURATION\n# Absolute filesystem path to the Django project directory:\nDJANGO_ROOT = dirname(dirname(abspath(__file__)))\n\nENV = os.environ.get('ENV', None)\n\nADMINS = (\n ('Nahuel Chaves', 'nahuel.chaves@gmail.com'),\n)\n\nMANAGERS = ADMINS\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'America/Argentina/Ushuaia'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'es'\n\nLOCALE_PATHS = (DJANGO_ROOT + '/configs/locale',)\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/var/www/example.com/media/\"\n#MEDIA_ROOT = BASE_ROOT + '/media/'\n\nMEDIA_ROOT = normpath(join(DJANGO_ROOT, 'media'))\nMEDIA_URL = '/media/'\n\n########## STATIC FILE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = normpath(join(DJANGO_ROOT, 'assets'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url\nSTATIC_URL = '/static/'\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n#STATIC_ROOT = BASE_ROOT + '/static/'\n\n# URL prefix for static files.\n#STATIC_URL = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n normpath(join(DJANGO_ROOT, 'static')),\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder'\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'im1mh^q^r@*p++w^8k%ke&cml_1rva5idpzon-e&ziiwy2-15o'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader'\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.gzip.GZipMiddleware',\n 'pipeline.middleware.MinifyHTMLMiddleware',\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n #Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'cent11.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'cent11.wsgi.application'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs\nTEMPLATE_DIRS = (\n normpath(join(DJANGO_ROOT, 'templates')),\n)\n\n\n\nDJANGO_APPS = (\n 'suit',\n 'suitlocale',\n 'suit_redactor',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'pipeline',\n 'debug_toolbar',\n 'model_utils',\n 'south',\n 'django_extensions',\n 'autocomplete_light',\n 'django_extensions',\n 'cities_light',\n 'bootstrap3',\n 'smuggler',\n\n)\n\n# Apps specific for this project go here.\nLOCAL_APPS = (\n 'academica',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps\nINSTALLED_APPS = DJANGO_APPS + LOCAL_APPS\n\nSESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n## Pipeline\n\nSTATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'\nPIPELINE_JS_COMPRESSOR = 'pipeline.compressors.slimit.SlimItCompressor'\nPIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.cssmin.CSSMinCompressor'\nPIPELINE_CSSMIN_BINARY = 'cssmin'\nPIPELINE_COMPILERS = (\n 'pipeline.compilers.sass.SASSCompiler',\n)\nPIPELINE_SASS_BINARY = '/usr/bin/sass'\n\nPIPELINE_CSS = {\n 'admin': {\n 'source_filenames':\n (\n 'stylesheets/admin.css',\n ),\n 'output_filename': 'stylesheets/admin.min.css',\n 'extra_context': {\n 'media': 'screen',\n },\n },\n}\n\nPIPELINE_JS = {\n 'core': {\n 'source_filenames':\n (\n 'javascript/jquery-1.10.2.js',\n ),\n 'output_filename': 'javascript/jquery-1.10.2.min.js',\n }\n}\n\nSUIT_CONFIG = {\n 'ADMIN_NAME': 'CENT 11',\n 'HEADER_DATE_FORMAT': 'l, d \\d\\e F Y', # Saturday, 16th March 2013\n 'LIST_PER_PAGE': 15,\n 'SEARCH_URL': '',\n 'MENU': (\n #'sites',\n {'label': 'Gestion',\n 'icon': 'icon-briefcase',\n 'models': (\n 'academica.estructura',\n 'academica.curso',\n 'academica.semestre',\n 'academica.hora',\n )},\n {'label': 'RRHH', 'icon':'icon-user', 'models': ('academica.persona', 'academica.documento')},\n '-',\n {'app': 'auth', 'label':'Seguridad', 'icon':'icon-lock', 'models': ('user', 'group')},\n\n {'label':\n 'Settings',\n 'icon': 'icon-cog',\n 'models': (\n 'academica.ciclo',\n 'academica.carrera',\n 'academica.materia',\n 'academica.rol',\n )},\n {'label':\n 'Ubicacion',\n 'icon': 'icon-map-marker',\n 'models': (\n 'cities_light.country',\n 'cities_light.region',\n 'cities_light.city',\n 'academica.barrio'\n )},\n {'label': 'Ayuda', 'icon':'icon-question-sign', 'url': '/admin/ayuda/'},\n ),\n}\n\nTEMPLATE_CONTEXT_PROCESSORS = TCP + (\n 'django.core.context_processors.request',\n)\n\nSOUTH_MIGRATION_MODULES = {\n 'cities_light': 'cities_light.south_migrations',\n}\n\n\n\nDATE_FORMAT = \"%d-%m-%Y\"\n\nCITIES_LIGHT_CITY_SOURCES = [\"http://download.geonames.org/export/dump/cities1000.zip\"]\n\nROSETTA_REQUIRES_AUTH = True\n\nBOOTSTRAP3 = {\n 'css_url': '/static/css/bootstrap.min.css',\n 'js_url': '/static/js/bootstrap.min.js',\n 'jquery_url': '/static/js/jquery-1.11.0.min.js',\n 'javascript_url': '/static/js/bootstrap.min.js',\n 'include_jquery': True\n}\n\nSITE_ID = 1\n\nif ENV == 'development' or ENV is None:\n IS_DEVELOPMENT = True\n from configs.dev import *\n\nelif ENV == 'profiling':\n IS_PROFILING = True\n from configs.prof import *\n\nelif ENV == 'production':\n IS_PRODUCTION = True\n from configs.prod import *\n","sub_path":"dev/cent11/configs/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":8225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"519966367","text":"# import necessary packages\nimport progressbar\n# import quaternion\nimport datetime\nimport argparse\nimport pandas as pd\nimport numpy as np\nimport os\n\n# import ros packages\nimport rosbag\nimport roslib\nimport rospy\n\n# import message types\nfrom sensor_msgs.msg import Joy #, CompressedImage\nfrom nav_msgs.msg import Odometry\n# from p2os_msgs.msg import SonarArray\n\ndef extract_data(args):\n ''' Extracts data from .bag file given. '''\n\n # open the bag file\n print('Loading .bag file')\n bag = rosbag.Bag(args['bag'], 'r')\n\n # assumption:\n # the matching message will have been received within 150 ms of the pivot message\n # this is used to narrow the search for the matching message\n t_tol = rospy.Duration(secs=0, nsecs=150000000) # 150000000 ns = 150 ms\n\n # start and end time for the data extraction\n start_at = rospy.Time(secs=int(bag.get_start_time()) + 1, nsecs=0) # 1 second offset for the start\n end_at = rospy.Time(secs=int(bag.get_end_time()) - 1, nsecs=0) # -1 second offset for the end\n\n # pose is the slowest topic\n pose_bagmsgs = bag.read_messages(topics='pose', start_time=start_at, end_time=end_at)\n\n # joy is faster and is out of sync, which is why a tolerance is needed\n joy_bagmsgs = bag.read_messages(topics='joy', start_time=start_at-t_tol, end_time=end_at+t_tol)\n\n # load the messages into memory\n print('Loading messages into memory')\n pose_bagmsgs = [p for p in pose_bagmsgs]\n joy_bagmsgs = [j for j in joy_bagmsgs]\n\n # last messages saved. this will be used to obtain incremental\n # measures and ground truth for joystick measures\n last_pose_msg = None\n last_joy_msg = None\n second_last_pose_msg = None\n second_last_joy_msg = None\n\n # setup the progress bar\n c = 0\n c_max = len(pose_bagmsgs)\n bar = progressbar.ProgressBar(max_value=c_max)\n\n # create pandas dataframe for the data\n data = pd.DataFrame(columns=[\n 'dtns', # 'dts', 'dtns'\n # 'dx', 'dy', 'dq.w', 'dq.z'\n 'x', 'y', ####\n 'vx', 'dvx', 'vz', 'dvz',\n 'jx', 'djx', 'jy', 'djy', # 'jb', 'djb'\n 'jx_gt', 'jy_gt' # 'jb_gt'\n ])\n\n # counter for the joy list\n joy_idx = 0\n\n # read messages from the pose topic\n print('Processing and saving data')\n for pose_bagmsg in pose_bagmsgs:\n\n # get the pose message and it's timestamp\n pose_msg = pose_bagmsg.message\n pose_t = pose_bagmsg.timestamp # pose_msg.header.stamp # when it was generated/captured\n\n # read from the joy topic\n joy_msg = None\n min_diff = rospy.Duration(secs=10, nsecs=0) # starting the minimum with 10 seconds\n for joy_bagmsg in joy_bagmsgs[joy_idx:]:\n joy_t = joy_bagmsg.timestamp # joy_bagmsg.message.header.stamp\n diff_t = abs(pose_t-joy_t)\n if diff_t < min_diff or joy_msg is None:\n joy_msg = joy_bagmsg.message\n min_diff = diff_t\n joy_idx += 1\n else:\n break\n\n # to proceed, we need a last message for pose and joy\n if last_pose_msg is not None and last_joy_msg is not None:\n\n # and we also need a second last to get the ground truth\n if second_last_pose_msg is not None and second_last_joy_msg is not None:\n\n # extract the relevant data from the messages\n row = {}\n\n # datetime\n row['datetime'] = datetime.datetime.fromtimestamp(pose_t.secs) \\\n + datetime.timedelta(microseconds=pose_t.nsecs//1000)\n\n # time\n ti = last_pose_msg.header.stamp - second_last_pose_msg.header.stamp\n # row['dts'] = ti.secs\n row['dtns'] = ti.nsecs\n\n # position\n '''\n po = second_last_pose_msg.pose.pose.position\n pn = last_pose_msg.pose.pose.position\n row['dx'] = pn.x - po.x\n row['dy'] = pn.y - po.y\n '''\n row['x'] = last_pose_msg.pose.pose.position.x\n row['y'] = last_pose_msg.pose.pose.position.y\n\n # orientation\n '''\n qo = second_last_pose_msg.pose.pose.orientation\n qn = last_pose_msg.pose.pose.orientation\n qo = np.quaternion(qo.w, qo.x, qo.y, qo.z)\n qn = np.quaternion(qn.w, qn.x, qn.y, qn.z)\n qi = qn/qo\n row['dq.w'] = qi.w\n row['dq.z'] = qi.z\n '''\n\n # velocity\n row['vx'] = last_pose_msg.twist.twist.linear.x\n row['dvx'] = last_pose_msg.twist.twist.linear.x - second_last_pose_msg.twist.twist.linear.x\n row['vz'] = last_pose_msg.twist.twist.angular.z\n row['dvz'] = last_pose_msg.twist.twist.angular.z - second_last_pose_msg.twist.twist.angular.z\n\n # joy (data)\n row['jx'] = last_joy_msg.axes[0]\n row['djx'] = last_joy_msg.axes[0] - second_last_joy_msg.axes[0]\n row['jy'] = last_joy_msg.axes[1]\n row['djy'] = last_joy_msg.axes[1] - second_last_joy_msg.axes[1]\n # row['jb'] = last_joy_msg.buttons[0]\n # row['djb'] = last_joy_msg.buttons[0] - second_last_joy_msg.buttons[0]\n\n # joy (ground-truth)\n row['jx_gt'] = joy_msg.axes[0]\n row['jy_gt'] = joy_msg.axes[1]\n # row['jb_gt'] = joy_msg.buttons[0]\n \n # append the row to the data\n data = data.append(pd.DataFrame(row, index=[0]), ignore_index=True, sort=False)\n\n # save the messages for the next iteration\n second_last_pose_msg = last_pose_msg\n second_last_joy_msg = last_joy_msg\n\n # save the messages for the next iteration\n last_pose_msg = pose_msg\n last_joy_msg = joy_msg\n\n # update the progress\n c += 1\n bar.update(c)\n\n # mark the processing as finished\n bar.finish()\n\n # save the data to disk\n set_folder = os.path.join('data', args['dest'], args['set'])\n if not os.path.isdir(set_folder):\n os.makedirs(set_folder)\n if args['append']:\n data = pd.concat([pd.read_csv(os.path.join(set_folder, 'data.csv')), data])\n data.to_csv(path_or_buf=os.path.join(set_folder, 'data.csv'), header=True, index=False)\n \n # close the bag file\n bag.close()\n\ndef main():\n ''' Main function. '''\n\n # setup the argument parser\n ap = argparse.ArgumentParser()\n ap.add_argument('--bag', type=str,\n help='path to bag file')\n ap.add_argument('--set', type=str,\n help='indicates set (train, val, test)')\n ap.add_argument('--dest', type=str,\n help='destination folder')\n ap.add_argument('--append', action='store_true',\n help='append data to existing .csv')\n args = vars(ap.parse_args())\n\n # print the arguments\n print('File: {}'.format(args['bag']))\n print('Set: {}'.format(args['set']))\n\n # extract the data from bag the file\n extract_data(args)\n\n# if it is the main file\nif __name__ == '__main__':\n main()\n","sub_path":"extract_data.py","file_name":"extract_data.py","file_ext":"py","file_size_in_byte":7204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"611397848","text":"#!/usr/bin/python3\n\"\"\"\nextend your Python script to export data in the JSON format\n\"\"\"\nimport json\nimport requests\n\nif __name__ == \"__main__\":\n set_id = set()\n request = requests.get(\"https://jsonplaceholder.typicode.com/posts\")\n data = request.json()\n for user in data:\n set_id.add(user.get(\"userId\"))\n file_export = {}\n url = \"https://jsonplaceholder.typicode.com/users/{}\"\n url1 = \"https://jsonplaceholder.typicode.com/todos?userId={}\"\n for user in set_id:\n rq_users = requests.get(url.format(user))\n rq_name = rq_users.json().get(\"username\")\n rq_users = requests.get(url1.format(user))\n data_request = rq_users.json()\n file_export['{}'.format(user)] = []\n for task in data_request:\n file_export['{}'.format(user)].append({\n \"task\": task.get('title'),\n 'completed': task.get('completed'),\n 'username': rq_name\n })\n with open('todo_all_employees.json', mode='w') as file:\n json.dump({int(x): file_export[x] for x in file_export.keys()},\n file, sort_keys=True)\n","sub_path":"0x15-api/3-dictionary_of_list_of_dictionaries.py","file_name":"3-dictionary_of_list_of_dictionaries.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"283726856","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/Kamaelia/Support/DVB/CRC.py\n# Compiled at: 2008-10-19 12:19:52\n\"\"\"CRC algorithm used to verify the integrity of data in DVB transport streams.\n\"\"\"\n\ndef __MakeCRC32(polynomial=79764919, initial=4294967295):\n \"\"\" MakeCRC32([polynomial][,inital]) -> (string -> 32bit CRC of binary string data)\n \n Returns a function that calculatees the 32 bit CRC of binary data in a\n string, using the specified CRC polynomial and initial value.\n \"\"\"\n xorvals = []\n for x in range(0, 256):\n crc = long(x) << 24\n for bit in range(7, -1, -1):\n z32 = crc >> 31\n crc = crc << 1\n if z32:\n crc = crc ^ polynomial\n crc = crc & 4294967295\n\n xorvals.append(crc & 4294967295)\n\n def fastcrc32(data):\n crc = 4294967295\n for byte in data:\n byte = ord(byte)\n xv = xorvals[(byte ^ crc >> 24)]\n crc = xv ^ (crc & 16777215) << 8\n\n return crc\n\n return fastcrc32\n\n\n__dvbcrc = __MakeCRC32(polynomial=79764919)\ndvbcrc = lambda data: not __dvbcrc(data)","sub_path":"pycfiles/Kamaelia-0.6.0-py2.5/CRC.py","file_name":"CRC.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"131781450","text":"#!/usr/bin/env python3\n\"\"\"\nthat builds a dense block as described in Densely\nConnected Convolutional Networks:\n\"\"\"\n\nimport tensorflow.keras as K\n\n\ndef dense_block(X, nb_filters, growth_rate, layers):\n \"\"\"\n ARGs:\n\n X is the output from the previous layer\n nb_filters is an integer representing the number of filters in X\n growth_rate is the growth rate for the dense block\n layers is the number of layers in the dense block\n\n Returns: The concatenated output of each layer within the\n Dense Block and the number of filters within the concatenated\n outputs, respectively\n \"\"\"\n shortcut = X\n kernel = K.initializers.he_normal()\n for i in range(layers):\n \"\"\"the bottleneck layers used for DenseNet-B\"\"\"\n \"\"\"\n DenseNet-B: 1x1 conv bottleneck before 3x3 conv\n \"\"\"\n\n \"\"\" bottleneck convolution block\"\"\"\n X = K.layers.BatchNormalization(axis=3)(shortcut)\n X = K.layers.Activation('relu')(X)\n inter_channel = growth_rate * 4\n X = K.layers.Conv2D(filters=(inter_channel),\n kernel_size=(1, 1),\n padding=\"same\",\n kernel_initializer=kernel)(X)\n \"\"\" end of bottleneck convolution block \"\"\"\n\n X = K.layers.BatchNormalization(axis=3)(X)\n X = K.layers.Activation('relu')(X)\n X = K.layers.Conv2D(filters=growth_rate,\n kernel_size=(3, 3),\n padding=\"same\",\n kernel_initializer=kernel)(X)\n\n shortcut = K.layers.Concatenate()([shortcut, X])\n nb_filters += growth_rate\n return shortcut, nb_filters\n","sub_path":"supervised_learning/0x08-deep_cnns/5-dense_block.py","file_name":"5-dense_block.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"147323634","text":"\n\"\"\"\nCompany Template\ndata is taken from database randomly\ndata set up into php file \n\"\"\"\nfrom random_address import randomAddress\nimport mysql.connector, shutil, random, os, uuid\n\ndef get_data_db():\n try:\n connection = mysql.connector.connect(host='34.66.139.63',\n database='content_db',\n user='root',\n password='secret',\n )\n\n sql_select_Query = \"SELECT * FROM company_content ORDER BY RAND() LIMIT 1\"\n cursor = connection.cursor()\n cursor.execute(sql_select_Query)\n # get all records\n record = cursor.fetchall()\n\n except mysql.connector.Error as e:\n print(\"Error reading data from MySQL table\", e)\n finally:\n if connection.is_connected():\n connection.close()\n cursor.close()\n print(\"MySQL connection is closed\")\n return record\n\ndef setCompanyTemplate(website_name, country, theme):\n\taddressInfo = randomAddress(country)\n\trow = get_data_db()\n\tif theme == \"dark\":\n\t\tfileName = f\"company_dark/source/config/config_cont.php\"\n\telse:\n\t\tfileName = f\"company_light/source/config/config_cont.php\"\n\n\tf = open(fileName,'w+')\n\tf.write(\"\")\n\tf.close()\n\n \ndef setNewsTemplate(contentRequest):\n\tfileName = f\"news_website/news/config.php\"\n\n\tf = open(fileName,'w+')\n\tf.write(\"\")\n\tf.close()\n\n\ndef setBlogTemplate(contentRequest):\n\tfileName = f\"blog_website/blog/app/includes/config.php\"\n\n\tf = open(fileName,'w+')\n\tf.write(\"\")\n\tf.close()","sub_path":"guiDocker/app/template_variables.py","file_name":"template_variables.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"31607761","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 6 08:29:52 2019\r\n\r\n@author: 19158\r\n\"\"\"\r\n\r\n# Adjacency list representation of graphs\r\nimport graph_AM as graph # Replace line 3 by this one to demonstrate adjacy maxtrix implementation\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nfrom scipy.interpolate import interp1d\r\n\r\nclass Edge:\r\n def __init__(self, dest, weight=1):\r\n self.dest = dest \r\n self.weight = weight\r\n \r\nclass Graph:\r\n # Constructor\r\n def __init__(self, vertices, weighted=False, directed = False):\r\n self.al = [[] for i in range(vertices)]\r\n self.weighted = weighted\r\n self.directed = directed\r\n self.representation = 'AL'\r\n \r\n def insert_edge(self,source,dest,weight=1):\r\n if source >= len(self.al) or dest>=len(self.al) or source <0 or dest<0:\r\n print('Error, vertex number out of range')\r\n elif weight!=1 and not self.weighted:\r\n print('Error, inserting weighted edge to unweighted graph')\r\n else:\r\n self.al[source].append(Edge(dest,weight)) \r\n if not self.directed:\r\n self.al[dest].append(Edge(source,weight))\r\n \r\n def delete_edge_(self,source,dest):\r\n i = 0\r\n for edge in self.al[source]:\r\n if edge.dest == dest:\r\n self.al[source].pop(i)\r\n return True\r\n i+=1 \r\n return False\r\n \r\n def delete_edge(self,source,dest):\r\n if source >= len(self.al) or dest>=len(self.al) or source <0 or dest<0:\r\n print('Error, vertex number out of range')\r\n else:\r\n deleted = self.delete_edge_(source,dest)\r\n if not self.directed:\r\n deleted = self.delete_edge_(dest,source)\r\n if not deleted: \r\n print('Error, edge to delete not found') \r\n \r\n \r\n def display(self):\r\n print('[',end='')\r\n for i in range(len(self.al)):\r\n print('[',end='')\r\n for edge in self.al[i]:\r\n print('('+str(edge.dest)+','+str(edge.weight)+')',end='')\r\n print(']',end=' ') \r\n print(']') \r\n \r\n def draw(self):\r\n scale = 30\r\n fig, ax = plt.subplots()\r\n for i in range(len(self.al)):\r\n for edge in self.al[i]:\r\n d,w = edge.dest, edge.weight\r\n if self.directed or d>i:\r\n x = np.linspace(i*scale,d*scale)\r\n x0 = np.linspace(i*scale,d*scale,num=5)\r\n diff = np.abs(d-i)\r\n if diff == 1:\r\n y0 = [0,0,0,0,0]\r\n else:\r\n y0 = [0,-6*diff,-8*diff,-6*diff,0]\r\n f = interp1d(x0, y0, kind='cubic')\r\n y = f(x)\r\n s = np.sign(i-d)\r\n ax.plot(x,s*y,linewidth=1,color='k')\r\n if self.directed:\r\n xd = [x0[2]+2*s,x0[2],x0[2]+2*s]\r\n yd = [y0[2]-1,y0[2],y0[2]+1]\r\n yd = [y*s for y in yd]\r\n ax.plot(xd,yd,linewidth=1,color='k')\r\n if self.weighted:\r\n xd = [x0[2]+2*s,x0[2],x0[2]+2*s]\r\n yd = [y0[2]-1,y0[2],y0[2]+1]\r\n yd = [y*s for y in yd]\r\n ax.text(xd[2]-s*2,yd[2]+3*s, str(w), size=12,ha=\"center\", va=\"center\")\r\n ax.plot([i*scale,i*scale],[0,0],linewidth=1,color='k') \r\n ax.text(i*scale,0, str(i), size=20,ha=\"center\", va=\"center\",\r\n bbox=dict(facecolor='w',boxstyle=\"circle\"))\r\n ax.axis('off') \r\n ax.set_aspect(1.0)\r\n \r\n#---------------------------------------------------------------------------------------------------\r\n \r\n def method1(self, binary_number): \r\n nums = list()\r\n for i in binary_number:\r\n nums.append(i)\r\n \r\n #nums[0] represents Fox --- nums[1] represents Chicken --- nums[2] represents Grain --- nums[3] represents me \r\n if nums[0] == '0' and nums[1] == '0' and nums[2] == '0' and nums[3] == '1': \r\n #I cant leave them alone\r\n return 0\r\n \r\n if (nums[0] == '0' and nums[1] == '0' and nums[3] == '1') or (nums[0] == '1' and nums[1] == '1' and nums[3] == '0'):\r\n #checking if fox and chicken are alone\r\n return 0\r\n \r\n if (nums[1] == '0' and nums[2] == '0' and nums[3] == '1') or (nums[1] == '1' and nums[2] == '1' and nums[3] == '0'):\r\n #checking if chicken and grain are alone\r\n return 0\r\n return nums\r\n \r\n \r\n def as_AM(self): #hugo\r\n for i in self.al:\r\n print(i)\r\n \r\n \r\n def problem(self):\r\n valid = 0\r\n list_of_valids = list()\r\n \r\n binar = '0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111'\r\n binar = binar.split(' ')\r\n \r\n for index in range(len(binar)):\r\n binary_number = binar[index]\r\n \r\n valid = self.method1(binary_number)\r\n \r\n if valid != 0:\r\n list_of_valids.append(valid)\r\n \r\n print(list_of_valids)\r\n gra = Graph(len(list_of_valids))\r\n g.insert_edge(0,1)\r\n \r\n return\r\n\r\n \r\n def as_EL(self):\r\n g = []\r\n for source in range(len(self.al)):\r\n for dest in range(len(self.al[source])):\r\n g.append([source,dest])\r\n return g\r\n ","sub_path":"graph_AL.py","file_name":"graph_AL.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"51254732","text":"import cv2\nimport time\n\n\nclass Video:\n def __init__(self, name=None, camera=0):\n super(Video, self).__init__()\n self.video = None\n self.total_frames = 0\n self.video_name = None\n self.frame = 0\n self.frame_pos = -1\n self.camera = camera\n\n def load(self, name, camera=0):\n self.video = cv2.VideoCapture(name)\n self.video_name = name\n self.camera = camera\n while not self.video.isOpened():\n print(\"Wait for the header...\\nVideo name :\", self.name)\n cv2.waitKey(1000)\n self.video = cv2.VideoCapture(name)\n self.frame = 0#158000\n self.frame_pos = -1\n self.video.set(cv2.CAP_PROP_POS_FRAMES, self.frame)\n self.total_frames = int(self.video.get(cv2.CAP_PROP_FRAME_COUNT))\n\n def set_position(self, pos):\n # pos = self.frame - pos\n # if pos < 0:\n # pos = 0\n self.frame = pos\n self.video.set(cv2.CAP_PROP_POS_FRAMES, pos)\n\n def take_point(self, index):\n if index < 0:\n index = 0\n self.frame = index\n return index\n\n def get_frames(self, block, step=1):\n frames = []\n flag = False\n for i in range(0, (block * step), step):\n self.video.set(cv2.CAP_PROP_POS_FRAMES, self.frame)\n flag, image = self.video.read()\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n # cv2.imshow('image',image)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n if not flag or self.frame_pos == self.video.get(cv2.CAP_PROP_POS_MSEC):\n raise IndexError\n else:\n frame = {'Index': self.frame, 'Image': image}\n frames.append(frame)\n self.frame += step\n self.frame_pos = self.video.get(cv2.CAP_PROP_POS_MSEC)\n return frames\n\n\n def get_frame(self, nb):\n flag = False\n dic = {}\n while flag == False:\n self.video.set(cv2.CAP_PROP_POS_FRAMES, self.frame + nb - 1)\n flag, image = self.video.read()\n if not flag:\n raise IndexError\n else:\n name = str(self.total_frames) + str(self.camera) + \".\" + str(self.frame)\n dic = {'Frame' : int(self.frame), 'Name' : name, 'Image': image}\n self.frame += nb\n break\n return dic\n\n\n def stop(self):\n self.video.release()\n","sub_path":"Sources/Common/Video.py","file_name":"Video.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"67670833","text":"import pandas as pd\r\nfrom strsimpy.jaro_winkler import JaroWinkler\r\njarowinkler = JaroWinkler()\r\n\r\ndf_species=pd.read_csv('../Datasets/species.csv', usecols=['Park Name', 'Common Names', 'Category', 'Occurrence', 'Record Status'])\r\n\r\n# -----------STRUCTURED DATA PREPROCESSING--------------\r\ndf_species=df_species[df_species[\"Record Status\"]==\"Approved\"]\r\ndf_species=df_species[df_species[\"Occurrence\"]==\"Present\"]\r\n\r\ndf_species['Common Names']=df_species['Common Names'].str.split(\",\")\r\ndf_species['Common Names']= df_species['Common Names'].map(lambda x: sorted(list(x))[0].strip())\r\n\r\n\r\n\r\n\r\ndf_species.loc[df_species['Common Names'].str.split().str.len() > 1, 'Common Names'] = df_species['Common Names'].str.split().str[-1]\r\n\r\ndf_species.drop_duplicates(inplace=True)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nuniq_np_sp=set(df_species['Park Name'].unique())\r\n\r\ndf_final=pd.read_csv('../Datasets/er_alltrails.csv')\r\nuniq_np_fin=set(df_final['national_park'].unique())\r\n\r\nintersec=uniq_np_sp.intersection(uniq_np_fin)\r\n\r\ndiff=uniq_np_sp.difference(intersec)\r\n\r\n# df_species['Park Name'].replace(\"Sequoia and Kings Canyon National Parks\", \"Sequoia National Park\", inplace=True)\r\n# a=sorted(uniq_np_fin)\r\n# df_species['Park Name'].replace(\"Katmai National Park and Preserve\", \"Katmai National Park\", inplace=True)\r\n\r\ndf_species['Park Name'].replace(\"Wrangell - St Elias National Park and Preserve\", \"Wrangell–St. Elias National Park and Preserve\", inplace=True)\r\n\r\n# df_species['Park Name'].replace(\"Denali National Park and Preserve\", \"Denali National Park, Alaska\", inplace=True)\r\n\r\n\r\n# -------ENTITY RESOLUTION-----------\r\ner_dict={}\r\nfor i in list(diff):\r\n pn=i.split()[0]\r\n for j in list(df_final['national_park'].unique()):\r\n if pn==j.split()[0]: #BLOCKING\r\n sim=jarowinkler.similarity(i,j)\r\n if i not in er_dict.keys():\r\n er_dict[i]=(j,sim)\r\n elif er_dict[i][1]my_thres:\r\n df_species['Park Name'].replace(key,value[0], inplace=True)\r\n\r\n\r\n# REMOVING THOSE NP NOT IN ALLTRAILS\r\nfor np in diff:\r\n df_species.drop(df_species.loc[df_species['Park Name']==np].index, inplace=True)\r\n\r\ndf_species.rename(columns={\"Park Name\":\"national_park\"}, inplace=True)\r\n\r\n\r\n\r\n\r\ndf_species.reset_index(inplace=True)\r\ndf_species.drop('index', axis=1, inplace=True)\r\n\r\ndf_species.to_csv('../Datasets/er_struct.csv', index=False) \r\n","sub_path":"Part2_DataCleaning_ER_IE/er_struct.py","file_name":"er_struct.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"571588944","text":"import collections\n\ndef tablePrint(data):\n for i, row in enumerate(data):\n for j, value in enumerate(row):\n print('%-8s' % round(value,3), end = ' ')\n print('\\n')\n \ndef dumpclean(obj):\n if type(obj) == dict or type(obj) == collections.OrderedDict:\n for k, v in obj.items():\n if hasattr(v, '__iter__'):\n print(k)\n dumpclean(v)\n else:\n print('%s : %-8s' % (k[:3], round(v,3)), end=\"\")\n print('\\n')\n elif type(obj) == list:\n for v in obj:\n if hasattr(v, '__iter__'):\n dumpclean(v)\n else:\n print(v)\n print('\\n')\n else:\n print(round(obj,3))\n \ndef objectListPrint(data):\n for i, row in enumerate(data):\n print(row)\n","sub_path":"hu/farago/eum2/calculator/Helper.py","file_name":"Helper.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"650277529","text":"import os\r\nfrom flask import Blueprint, Flask, render_template\r\nfrom flask import request\r\nfrom werkzeug.utils import secure_filename\r\nimport re\r\n\r\npdfsearch=Blueprint(\"pdfsearch\", __name__, static_folder=\"static\", template_folder=\"templates\")\r\n\r\nimport torch\r\nfrom transformers import AutoTokenizer, AutoModelForQuestionAnswering\r\n\r\nfrom pdfminer.high_level import extract_pages\r\nfrom pdfminer.layout import LTTextContainer\r\nfrom collections import OrderedDict\r\n\r\nname = \"mrm8488/bert-small-finetuned-squadv2\"\r\n\r\ntokenizer = AutoTokenizer.from_pretrained(name,)\r\n\r\nmodel = AutoModelForQuestionAnswering.from_pretrained(name)\r\n\r\nmodel.to('cuda')\r\n\r\ndef answer_question(question, answer_text):\r\n '''\r\n Takes a `question` string and an `answer` string and tries to identify \r\n the words within the `answer` that can answer the question. Prints them out.\r\n '''\r\n \r\n # tokenize the input text and get the corresponding indices\r\n token_indices = tokenizer.encode(question, answer_text)\r\n\r\n # Search the input_indices for the first instance of the `[SEP]` token.\r\n sep_index = token_indices.index(tokenizer.sep_token_id)\r\n\r\n seg_one = sep_index + 1\r\n\r\n # The remainders lie in the second segment.\r\n seg_two = len(token_indices) - seg_one\r\n \r\n # Construct the list of 0s and 1s.\r\n segment_ids = [0]*seg_one + [1]*seg_two\r\n\r\n # get the answer for the question\r\n start_scores, end_scores = model(torch.tensor([token_indices]), # The tokens representing our input combining question and answer.\r\n token_type_ids=torch.tensor([segment_ids])) # The segment IDs to differentiate question from answer\r\n\r\n # Find the tokens with the highest `start` and `end` scores.\r\n answer_begin = torch.argmax(start_scores)\r\n answer_end = torch.argmax(end_scores)\r\n\r\n # Get the string versions of the input tokens.\r\n indices_tokens = tokenizer.convert_ids_to_tokens(token_indices)\r\n \r\n answer = indices_tokens[answer_begin:answer_end+1]\r\n #remove special tokens\r\n answer = [word.replace(\"▁\",\"\") if word.startswith(\"▁\") else word for word in answer] #use this when using model \"twmkn9/albert-base-v2-squad2\"\r\n answer = \" \".join(answer).replace(\"[CLS]\",\"\").replace(\"[SEP]\",\"\").replace(\" ##\",\"\")\r\n \r\n return answer\r\n\r\nclass DocumentReader:\r\n def __init__(self, pretrained_model_name_or_path='mrm8488/bert-small-finetuned-squadv2'):\r\n self.READER_PATH = pretrained_model_name_or_path\r\n self.tokenizer = AutoTokenizer.from_pretrained(self.READER_PATH)\r\n self.model = AutoModelForQuestionAnswering.from_pretrained(self.READER_PATH)\r\n self.model = self.model.to('cuda')\r\n self.max_len = self.model.config.max_position_embeddings\r\n self.chunked = False\r\n\r\n def tokenize(self, question, text):\r\n self.inputs = self.tokenizer.encode_plus(question, text, add_special_tokens=True, return_tensors=\"pt\").to('cuda')\r\n self.input_ids = self.inputs[\"input_ids\"].tolist()[0]\r\n\r\n if len(self.input_ids) > self.max_len:\r\n self.inputs = self.chunkify()\r\n self.chunked = True\r\n\r\n def chunkify(self):\r\n \"\"\" \r\n Break up a long article into chunks that fit within the max token\r\n requirement for that Transformer model. \r\n\r\n Calls to BERT / RoBERTa / ALBERT require the following format:\r\n [CLS] question tokens [SEP] context tokens [SEP].\r\n \"\"\"\r\n\r\n # create question mask based on token_type_ids\r\n # value is 0 for question tokens, 1 for context tokens\r\n qmask = self.inputs['token_type_ids'].lt(1)\r\n qt = torch.masked_select(self.inputs['input_ids'], qmask)\r\n chunk_size = self.max_len - qt.size()[0] - 1 # the \"-1\" accounts for\r\n # having to add an ending [SEP] token to the end\r\n\r\n # create a dict of dicts; each sub-dict mimics the structure of pre-chunked model input\r\n chunked_input = OrderedDict()\r\n for k,v in self.inputs.items():\r\n q = torch.masked_select(v, qmask)\r\n c = torch.masked_select(v, ~qmask)\r\n chunks = torch.split(c, chunk_size)\r\n \r\n for i, chunk in enumerate(chunks):\r\n if i not in chunked_input:\r\n chunked_input[i] = {}\r\n\r\n thing = torch.cat((q, chunk))\r\n if i != len(chunks)-1:\r\n if k == 'input_ids':\r\n thing = torch.cat((thing, torch.tensor([102]).to('cuda')))\r\n else:\r\n thing = torch.cat((thing, torch.tensor([1]).to('cuda')))\r\n\r\n chunked_input[i][k] = torch.unsqueeze(thing, dim=0)\r\n return chunked_input\r\n\r\n def get_answer(self):\r\n if self.chunked:\r\n answer = ''\r\n for k, chunk in self.inputs.items():\r\n a = self.model(**chunk)\r\n\r\n\r\n answer_start_scores = a[0]\r\n answer_end_scores = a[1]\r\n answer_start = torch.argmax(answer_start_scores)\r\n answer_end = torch.argmax(answer_end_scores) + 1\r\n\r\n ans = self.convert_ids_to_string(chunk['input_ids'][0][answer_start:answer_end])\r\n if ans != '[CLS]':\r\n answer += ans + \" \"\r\n return answer\r\n else:\r\n a = self.model(**self.inputs)\r\n\r\n\r\n answer_start_scores = a[0]\r\n answer_end_scores = a[1] \r\n answer_start = torch.argmax(answer_start_scores) # get the most likely beginning of answer with the argmax of the score\r\n answer_end = torch.argmax(answer_end_scores) + 1 # get the most likely end of answer with the argmax of the score\r\n \r\n return self.convert_ids_to_string(self.inputs['input_ids'][0][\r\n answer_start:answer_end])\r\n\r\n def convert_ids_to_string(self, input_ids):\r\n return self.tokenizer.convert_tokens_to_string(self.tokenizer.convert_ids_to_tokens(input_ids))\r\n\r\nreader = DocumentReader(\"deepset/bert-base-cased-squad2\") \r\n\r\n@pdfsearch.route('/uploader', methods = ['GET', 'POST']) \r\n@pdfsearch.route('/pdfsearch', methods=['GET', 'POST'])\r\ndef index():\r\n \r\n if request.method == 'POST':\r\n f = request.files['file']\r\n f.filename = \"sample.pdf\"\r\n f.save(f.filename)\r\n form = request.form\r\n result = []\r\n # bert_abstract = form['paragraph']\r\n question = form['question']\r\n text = \"\"\r\n for page_layout in extract_pages(\"sample.pdf\"):\r\n for element in page_layout:\r\n if isinstance(element, LTTextContainer):\r\n res = element.get_text()\r\n res1 = re.sub(r'[^\\w\\s]', ' ', str(res))\r\n res1 = re.sub(r\"^\\s+|\\s+$\", \"\", res1) # leading and trailing spaces\r\n res1 = re.sub(' +', ' ', res1) #removing multiple spaces\r\n text+=res1\r\n reader.tokenize(question,text)\r\n result.append(question)\r\n result.append(reader.get_answer())\r\n return render_template(\"pdfsearch.html\",result = result)\r\n\r\n return render_template(\"pdfsearch.html\")\r\n","sub_path":"pdfsearch.py","file_name":"pdfsearch.py","file_ext":"py","file_size_in_byte":7173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"420985441","text":"from queue import Queue\n\nclass Node:\n\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n\nclass BinaryTree:\n def __init__(self, root = None):\n self.root = root\n\n def add(self, value):\n if self.root == None:\n self.root = Node(value)\n return\n cur_node = self.root\n while cur_node:\n\n #Go left\n if value == cur_node.value:\n return\n elif value < cur_node.value:\n if cur_node.left:\n cur_node = cur_node.left\n else:\n cur_node.left = Node(value)\n return\n else:\n if cur_node.right:\n cur_node = cur_node.right\n else:\n cur_node.right = Node(value)\n return\n \n def delete(self, value):\n cur_node = self.root\n self.root = self.delete_node(self.root, value)\n\n def delete_node(self, node, value):\n if node == None:\n return None\n\n # go left\n if value < node.value:\n node.left = self.delete_node(node.left, value)\n\n # go right\n elif value > node.value:\n node.right = self.delete_node(node.right, value)\n\n # this is the node to delete\n else:\n\n #if just has one child then put it in its place\n if node.left == None:\n node = node.right\n return node\n elif node.right == None:\n node = node.left\n return node\n\n #if has two children, then replace with smallest node above it\n min_value = self.min_value(node.right)\n node.value = min_value\n node.right = self.delete_node(node.right, min_value)\n return node\n\n def min_value(self, node):\n if node == None:\n return None\n while node.left:\n node = node.left\n return node.value \n\n def search(self, value):\n cur_node = self.root\n while cur_node:\n if cur_node.value == value:\n return True\n if value < cur_node.value:\n cur_node = cur_node.left\n else:\n cur_node = cur_node.right\n return False\n\n def level_order(self):\n queue = Queue()\n cur_node = self.root\n while cur_node:\n print(cur_node.value)\n if cur_node.left:\n queue.enqueue(cur_node.left)\n if cur_node.right:\n queue.enqueue(cur_node.right)\n cur_node = queue.dequeue()\n\n\n def in_order(self):\n if self.root:\n self.in_order_recur(self.root)\n\n def in_order_recur(self, node):\n if node.left:\n self.in_order_recur(node.left)\n print(node.value)\n if node.right:\n self.in_order_recur(node.right)\n\n def pre_order(self):\n if self.root:\n self.pre_order_recur(self.root)\n\n def pre_order_recur(self, node):\n print(node.value)\n if node.left:\n self.pre_order_recur(node.left)\n if node.right:\n self.pre_order_recur(node.right)\n\n def post_order(self):\n if self.root:\n self.pre_order_recur(self.root)\n\n def post_order_recur(self, node):\n if node.left:\n self.post_order_recur(node.left)\n if node.right:\n self.post_order_recur(node.right)\n print(node.value)\n\nif __name__ == '__main__':\n tree = BinaryTree()\n\n import numpy as np\n np.random.seed(1)\n random_nums = np.random.randint(0,20,size=(20,))\n for each in random_nums:\n tree.add(each)\n\n print('Level order traversal')\n tree.level_order()\n\n print('In order traversal')\n tree.in_order()\n\n print('\\nPre order traversal')\n tree.pre_order()\n\n print('\\nPost order traversal')\n tree.post_order()\n\n print(tree.search(5))\n print(tree.search(22))\n\n tree.delete(5)\n tree.delete(11)\n tree.delete(6)\n tree.delete(22)\n tree.delete(9)\n print('\\nIn order after deleting 5, 6, 9, 11')\n tree.in_order()\n\n for each in random_nums:\n tree.delete(each)\n\n print('\\nIn order after deleting all numbers')\n tree.in_order()\n","sub_path":"python/data_structures_algorithms/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"310064380","text":"import json\nimport Algorithmia\nimport os\nimport traceback\n\nALGORITHMIA_KEY = os.environ.get('ALGORITHMIA', False)\nALGORITHMIA_DATA_STORE_LOCATION =\\\n os.environ.get('ALGORITHMIA_DATA_STORE_LOCATION', False)\n\n\ndef run():\n f = open('../data/whisky.json', 'r')\n raw_json = f.read()\n f.close()\n\n whisky = json.loads(raw_json)\n\n output = []\n\n for url, data in whisky.iteritems():\n output.append(data['description'])\n\n input = [output, \"xxBeGiN142xx\", \"xxEnD142xx\",\n ALGORITHMIA_DATA_STORE_LOCATION]\n\n client = Algorithmia.client(ALGORITHMIA_KEY)\n\n try:\n algo = client.algo(\n 'ngram/GenerateTrigramFrequencies/0.1.1')\n except Exception as exception:\n print(traceback.format_exc(exception))\n print(\"Unable to upload data.\")\n\n\nif __name__ == \"__main__\":\n\n if not ALGORITHMIA_KEY:\n print('Please export your Algorithmia key using' +\n '\"export ALGORITHMIA=MY_KEY\"')\n run()\n","sub_path":"generate_trigram_data.py","file_name":"generate_trigram_data.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"335613950","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Date: 2019-07-15\n\nimport numpy as np \nfrom matplotlib import pyplot as plt\n\npi = np.pi\nsin = np.sin\ncos = np.cos\n\nt_min = -2*pi; t_max = 2*pi; t_steps = 200\nt = np.linspace( t_min, t_max, t_steps+1 )\n# sin and cos function with period T=5\nx1 = sin( 2*pi*t/5 )\nx2 = cos( 2*pi*t/5 )\n\nlines = plt.plot( t, x1 )\nplt.setp( lines, 'linewidth', 2.0, 'label', r'$sin(\\frac{2\\pi}{5} t)$' )\nlines = plt.plot( t, x2 )\nplt.setp( lines, 'linewidth', 2.0, 'label', r'$cos(\\frac{2\\pi}{5} t)$' )\nplt.xlabel( 'Time t' )\nplt.ylabel( 'x(t)' )\nplt.axis( [t_min, t_max, -1.25, 1.25] )\nplt.grid( True )\nplt.legend( bbox_to_anchor=(0.95, 1.1), loc='upper right' )\nplt.savefig( 'plot_6.png' )\n#plt.savefig( 'plot_6.pdf', format='pdf', bbox_inches='tight' )\nplt.show()\n\n\n##############################################################################\n","sub_path":"func_plot-2/test_plot-6.py","file_name":"test_plot-6.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"472742854","text":"# -*- coding: utf-8 -*-\n# prog-2-05.py\n\nimport pandas as pd\nimport numpy as np\nimport re\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\n# ニューラルネットワークの構築のためにインポート\nimport tensorflow as tf\nimport keras\nfrom keras.utils.np_utils import to_categorical\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Embedding, Input, Flatten\nfrom tensorflow.keras.layers import Activation, Reshape\nfrom tensorflow.keras.layers import Dense, Concatenate, Dropout\nfrom keras.layers.merge import concatenate\nfrom tensorflow.keras.optimizers import Adam\n# 可視化用にインポート\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n# 散布図のテキストラベル位置調整のため\nget_ipython().system('pip3 install adjustText')\nfrom adjustText import adjust_text\n# ラベルエンコーディングのためにインストール\nget_ipython().system('pip install category_encoders')\n# category_encodersをインポート\nimport category_encoders as cate_enc\nimport collections as colle\n\n# データの準備\ndef prepare():\n get_ipython().system('unzip travel-insurance.zip')\n\n# エンティティ埋め込みクラス\nclass EntityEmbedder:\n def __init__(self, input_dims, emb_dims, output_dim):\n # 各特徴量の入力次元数\n self.dims = input_dims\n # 各特徴量の埋め込み次元数\n self.embdims = emb_dims\n # 出力次元数(ラベルの種類数)\n self.output_dim = output_dim\n self.dropout_rate = 0.2\n self.activation = 'relu'\n self.optimizer = 'Adam'\n self.loss = 'binary_crossentropy'\n self.weights = None\n self.buildEmbModel()\n \n # モデルの構築(ラベルエンコーディング後のデータを入力)\n def buildEmbModel(self):\n inputs, embeds = [], []\n for i, (input_dim, emb_dim) in enumerate(zip(self.dims, self.embdims)):\n input_c = Input(shape=(1,), name='in{}'.format(i+1))\n # 埋め込み(Embedding)層の定義\n embed = Embedding(input_dim=input_dim, \n output_dim=emb_dim, \n input_length=None, \n name='emb{}'.format(i+1))(input_c)\n output = Reshape(\\\n target_shape=(emb_dim,))(embed)\n inputs.append(input_c) \n embeds.append(output)\n # 埋め込み層の出力を連結する\n out = Concatenate(name='conc_layer', axis=-1)(embeds) \n out = Dropout(self.dropout_rate)(out) \n # 隠れ層のユニット数\n hd = [8]\n for n in range(len(hd)): \n out = Dense(hd[n])(out) \n out = Activation(self.activation)(out)\n out = Dense(self.output_dim)(out)\n out = Activation('softmax')(out)\n self.model = Model(inputs=inputs, outputs=out)\n self.model.compile(optimizer=self.optimizer, \n loss=self.loss,\n metrics=['accuracy'])\n self.model.summary()\n\n # 学習を行うメソッド(入力ベクトルは特徴量の数だけある)\n def fit(self, X, y, epochs=30, shuffle=True, batch_size=5):\n self.model.fit( X, y, \n epochs = epochs, shuffle=shuffle, batch_size=batch_size, verbose=1)\n # 学習済みネットワークの重みを格納\n self.weights = self.model.get_weights()\n # 埋め込み層の出力を連結したベクトルを取得するための\n # メソッドを定義する\n inputs = [self.model.get_layer('in%d' % (i+1)).input for i in range(len(self.dims))] \n # 埋め込み層からの出力を連結する層の出力を取得\n self.get_hidden_out = Model(inputs=self.model.inputs, outputs=self.model.get_layer('conc_layer').output)\n\n # 順序エンコーディングベクトルovから\n # エンティティ埋め込みベクトルを取得して返す\n def get_vector(self, ov):\n vec = self.get_hidden_out(ov)\n return vec\n\n # 特徴量(列)番号(fid)とカテゴリーID(cid)を渡すと、\n # そのカテゴリの特徴量ベクトルを返す\n def get_embedding(self, fid, cid):\n emb = self.weights[fid][cid, :]\n return emb\n\n# クラスごとのデータ数をそろえる\ndef resampling(newX, y, lim, labels):\n fc = [0] * len(labels)\n nX, nY = [], []\n for i in range(len(y)):\n if fc[y[i]] == lim:\n continue\n fc[y[i]] += 1\n nX.append(newX[i])\n nY.append(y[i])\n return nX, nY\n\n# 前処理\n# データフレームの作成、クラスの偏りを修正\ndef preprocess():\n # 旅行者のクレームの有無のデータ\n df = pd.read_csv('travel insurance.csv', encoding='utf-8')\n print(df)\n features = ['Agency','Agency Type', 'Distribution Channel', \n 'Product Name', 'Destination']\n labels = [0,1]\n target_names=['No', 'Yes']\n df['Claim'].replace({'Yes':1, 'No':0}, inplace=True)\n # データの少ないクラスに合わせるため、\n # 各クラスのうち少数派クラスのデータ数をlimに格納\n y_bool = df['Claim'] == 1\n n_bool = df['Claim'] == 0\n lim = y_bool.sum()\n if y_bool.sum() > n_bool.sum():\n lim = n_bool.sum()\n y = df['Claim'].values\n df.drop('Claim', axis=1, inplace=True)\n df = pd.DataFrame(df, columns=features)\n df.fillna('N')\n n_features = len(df.columns)\n print('Num of Features {}'.format(n_features))\n return df, y, lim, labels, features, target_names\n\n# ラベルエンコーディング\ndef ordinal_encoding(df, features, lim, y, labels, encoder):\n input_dims = []\n newX = np.array([])\n # ラベルエンコーディングのクラスインスタンスを生成\n if encoder == None:\n encoder = cate_enc.OrdinalEncoder(cols=features, handle_unknown='value', handle_missing='value')\n df_enc = encoder.fit_transform(df)\n else:\n df_enc = encoder.fit_transform(df)\n newX = df_enc.values\n dl = {}\n for i in range(len(newX)):\n n = 0\n for j in range(len(newX[i])):\n if not n in dl:\n dl[n] = []\n dl[n].append(newX[i][j])\n n+=1\n for n,v in dl.items():\n cnt = colle.Counter(v)\n mc = cnt.most_common()\n kinds = len(mc)\n input_dims.append(kinds)\n # クラスの偏りを無くすために少数派クラスの\n # 件数limに揃える\n nX, nY = resampling(newX, y, lim, labels)\n # カテゴリのIDを0から開始するように変換する\n nX = np.array(nX)\n nX = np.reshape(nX, (len(nX), len(nX[0]),))\n nY = np.array(nY)\n nY = np.reshape(nY, (len(nY), 1, ))\n nX = np.asarray(list(map(lambda x: x-1, nX)))\n return nX, nY, input_dims, encoder\n\ndef conv_form(X, input_dims):\n nX = []\n for i,id in enumerate(input_dims):\n x = np.asarray(X[:,i], dtype=np.int32)\n x = np.asarray([j for j in x],\\\n dtype=np.int32).reshape((len(x),1))\n nX.append(x)\n return nX\n\n# エンティティ埋め込みの学習\ndef convertByEntityEmbedding(X_train, y_train, X_test, y_test, labels, input_dims):\n y_train = to_categorical(y_train, num_classes=len(labels))\n X_train = np.array(X_train)\n X_train = conv_form(X_train, input_dims)\n y_test = to_categorical(y_test, num_classes=len(labels))\n X_test = np.array(X_test)\n X_test = conv_form(X_test, input_dims)\n\n # 埋め込みベクトルの次元数を2に設定する\n emb_dims = []\n for id in input_dims:\n emb_dims.append(2)\n output_dim = len(labels)\n ee = EntityEmbedder(input_dims, emb_dims, output_dim)\n # epochs = 7 で学習\n ee.fit(X_train, y_train, epochs=7)\n # 学習したモデルから、埋め込みベクトルを取得する\n x_trainvect = ee.get_vector(X_train)\n x_testvect = ee.get_vector(X_test)\n return x_trainvect, x_testvect, y_train, y_test, ee\n\n# SVMによる評価(エンティティ埋め込み有り)\ndef predict_by_SVM(x_trainvect, x_testvect, y_train, y_test, target_names):\n y_train_new, y_test_new = [], []\n i = 0\n for yf in y_train:\n y_train_new.append(np.argmax(yf))\n for yf in y_test:\n y_test_new.append(np.argmax(yf))\n svm = SVC()\n svm.fit(x_trainvect, y_train_new)\n y_pred = svm.predict(x_testvect)\n print('---With entity embedding---')\n print(classification_report(y_test_new, y_pred,target_names=target_names))\n\n# SVMによる評価(エンティティ埋め込み無し)\ndef predict_by_SVM_withoutEE(X_train, X_test, y_train, y_test, target_names):\n y_train_new, y_test_new = [], []\n X_train = np.reshape(X_train, (len(X_train), len(X_train[0])))\n y_train = np.reshape(y_train, (len(y_train) ))\n X_test = np.reshape(X_test, (len(X_test), len(X_test[0])))\n y_test = np.reshape(y_test, (len(y_test) ))\n svm = SVC()\n svm.fit(X_train, y_train)\n y_pred = svm.predict(X_test)\n print('---Without entity embedding---')\n print(classification_report(y_test, y_pred, target_names=target_names))\n\n# エンティティ埋め込み結果を可視化\ndef makeGraph(data, texts, cate):\n if len(data) > 20:\n p = np.random.permutation(len(data))\n data = data[p[:20]]\n texts = texts[p[:20]]\n for (dim1,dim2,label) in zip(data[:,0], data[:,1], texts):\n plt.plot(dim1, dim2, '.' )\n ptxt = [plt.text(x, y, lb, ha='center', va='center') for x,y,lb in zip(data[:,0], data[:,1], texts)]\n adjust_text(ptxt, arrowprops=dict(arrowstyle='->', color='blue'))\n cate = re.sub(r'\\s+', '_', cate)\n plt.title('2D plot of feature: {}'.format(cate))\n plt.savefig('./data-fig_{}.png'.format(cate), dpi=400)\n plt.show()\ndef main():\n prepare()\n df, y, lim, labels, features, target_names = preprocess()\n # ラベルエンコーディングしたベクトル形式に変換\n X_train, X_test, y_train, y_test = train_test_split(\n \t\t\t\t\tdf.loc[:,features].values, y, train_size=0.9, random_state=10)\n df_train = pd.DataFrame(X_train, columns=features)\n cc = [0, 0]\n for yv in y_train:\n cc[yv] += 1\n lim_train = np.min(cc)\n X_train, y_train, input_dims_train, enc = ordinal_encoding(\n df_train, features, lim_train, y_train, labels, None)\n df_test = pd.DataFrame(X_test, columns=features)\n cc = [0, 0]\n for yv in y_test:\n cc[yv] += 1\n lim_test = np.min(cc)\n X_test, y_test, input_dims, _ = ordinal_encoding(\n df_test, features, \n lim_test, y_test, labels, enc)\n \n # エンティティ埋め込み無しで、SVMによる予測\n predict_by_SVM_withoutEE(X_train, X_test, \\\n y_train, y_test, target_names)\n # カテゴリ特徴量をラベルエンコーディングしたデータを\n # エンティティ埋め込みベクトルに変換するために\n # 教師あり学習を行い、エンティティ埋め込みベクトルを取得\n x_trainvect, x_testvect, y_train, y_test, ee = convertByEntityEmbedding(\n \t\t\t X_train, y_train, X_test, y_test, labels, input_dims_train)\n # SVMで学習・予測結果の評価\n predict_by_SVM(x_trainvect, x_testvect,\n y_train, y_test, target_names)\n # 各カテゴリの埋め込みベクトルを可視化する\n for i in range(len(features)):\n veclist, texts = [], []\n obm = enc.mapping[i]['mapping']\n for idx, kv in zip(obm.index, obm):\n if kv < 0:\n continue\n embv = ee.get_embedding(i, kv-1)\n veclist.append(embv)\n texts.append(idx)\n veclist = np.asarray(veclist, dtype=np.float32)\n texts = np.asarray(texts)\n makeGraph(veclist, texts, features[i])\n\nif __name__ == '__main__':\n main()","sub_path":"py/prog2-05.py","file_name":"prog2-05.py","file_ext":"py","file_size_in_byte":12058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"168949958","text":"#-Begin-preamble-------------------------------------------------------\n#\n# CERN\n#\n# European Organization for Nuclear Research\n#\n#\n# This file is part of the code:\n#\n# PyECLOUD Version 8.6.0\n#\n#\n# Main author: Giovanni IADAROLA\n# BE-ABP Group\n# CERN\n# CH-1211 GENEVA 23\n# SWITZERLAND\n# giovanni.iadarola@cern.ch\n#\n# Contributors: Eleonora Belli\n# Philipp Dijkstal\n# Lorenzo Giacomel\n# Lotta Mether\n# Annalisa Romano\n# Giovanni Rumolo\n# Eric Wulff\n#\n#\n# Copyright CERN, Geneva 2011 - Copyright and any other\n# appropriate legal protection of this computer program and\n# associated documentation reserved in all countries of the\n# world.\n#\n# Organizations collaborating with CERN may receive this program\n# and documentation freely and without charge.\n#\n# CERN undertakes no obligation for the maintenance of this\n# program, nor responsibility for its correctness, and accepts\n# no liability whatsoever resulting from its use.\n#\n# Program and documentation are provided solely for the use of\n# the organization to which they are distributed.\n#\n# This program may not be copied or otherwise distributed\n# without permission. This message must be retained on this and\n# any other authorized copies.\n#\n# The material cannot be sold. CERN should be given credit in\n# all references.\n#\n#-End-preamble---------------------------------------------------------\n\nfrom numpy import sqrt, exp, take\nfrom numpy.random import rand\nimport numpy as np\nfrom .sec_emission_model_ECLOUD import SEY_model_ECLOUD\nfrom scipy.constants import e as qe\n\ndef yield_fun2(E, costheta, Emax, del_max, R0, E0):\n\n s = 1.35\n\n del_max_tilde = del_max * exp(0.5 * (1. - costheta))\n E_max_tilde = Emax * (1. + 0.7 * (1. - costheta))\n\n x = E / E_max_tilde\n\n true_sec = del_max_tilde * (s * x) / (s - 1. + x**s)\n reflected = R0 * ((sqrt(E) - sqrt(E + E0)) / (sqrt(E) + sqrt(E + E0)))**2.\n\n delta = true_sec + reflected\n ref_frac = 0. * delta\n mask_non_zero = (delta > 0)\n ref_frac[mask_non_zero] = reflected[mask_non_zero] / delta[mask_non_zero]\n\n return delta, ref_frac\n\n\nclass SEY_model_ECLOUD_non_unif(SEY_model_ECLOUD):\n \n def __init__(self, chamb, Emax, del_max, R0, E0=150.,\n E_th=None, sigmafit=None, mufit=None,\n switch_no_increase_energy=0, thresh_low_energy=None, secondary_angle_distribution=None,\n ):\n\n if chamb.chamb_type != 'polyg':\n raise ValueError(\"\"\"ECLOUD_nunif can be used only with chamb_type='polyg'!!!\"\"\")\n\n self.E_th = E_th\n self.sigmafit = sigmafit\n self.mufit = mufit\n self.switch_no_increase_energy = switch_no_increase_energy\n self.thresh_low_energy = thresh_low_energy\n self.secondary_angle_distribution = secondary_angle_distribution\n\n if secondary_angle_distribution is not None:\n from . import electron_emission\n self.angle_dist_func = electron_emission.get_angle_dist_func(secondary_angle_distribution)\n else:\n self.angle_dist_func = None\n\n self.del_max_segments = np.float_(chamb.del_max_segments)\n self.R0_segments = np.float_(chamb.R0_segments)\n self.Emax_segments = np.float_(chamb.Emax_segments)\n\n self.del_max_segments[chamb.del_max_segments < 0.] = del_max\n self.R0_segments[chamb.R0_segments < 0.] = R0\n self.Emax_segments[chamb.Emax_segments < 0.] = Emax\n\n self.E0 = E0\n\n print('Secondary emission model: ECLOUD non uniform E0=%f'%self.E0)\n\n def SEY_process(self, nel_impact, E_impact_eV, costheta_impact, i_impact):\n\n Emax_mp = take(self.Emax_segments, i_impact)\n del_max_mp = take(self.del_max_segments, i_impact)\n R0_mp = take(self.R0_segments, i_impact)\n\n yiel, ref_frac = yield_fun2(E_impact_eV, costheta_impact, Emax_mp, del_max_mp, R0_mp, E0=self.E0)\n flag_elast = (rand(len(ref_frac)) < ref_frac)\n flag_truesec = ~(flag_elast)\n nel_emit = nel_impact * yiel\n\n return nel_emit, flag_elast, flag_truesec\n\n\nclass SEY_model_ECLOUD_non_unif_charging(SEY_model_ECLOUD_non_unif):\n \n def __init__(self, chamb, Emax, del_max, R0, E0=150.,\n E_th=None, sigmafit=None, mufit=None,\n switch_no_increase_energy=0, thresh_low_energy=None, secondary_angle_distribution=None, \n ):\n\n super(SEY_model_ECLOUD_non_unif_charging, self).__init__(chamb, Emax, del_max, R0, E0,\n E_th, sigmafit, mufit,\n switch_no_increase_energy, thresh_low_energy, secondary_angle_distribution, \n )\n print('Secondary emission model: ECLOUD non uniform E0=%f, with charging'%self.E0)\n \n self.chamb = chamb\n self.Q_segments = 0. * self.del_max_segments\n self.flag_charging = np.int_(chamb.flag_charging)>0\n self.Q_max_segments = np.float_(chamb.Q_max_segments)\n self.EQ_segments = np.float_(chamb.EQ_segments)\n self.tau_segments = np.float_(chamb.tau_segments)\n\n\n def SEY_process(self, nel_impact, E_impact_eV, costheta_impact, i_impact):\n \n Emax_mp = take(self.Emax_segments, i_impact)\n del_max_mp = take(self.del_max_segments, i_impact)\n R0_mp = take(self.R0_segments, i_impact)\n\n yiel, ref_frac = yield_fun2(E_impact_eV, costheta_impact, Emax_mp, del_max_mp, R0_mp, E0=self.E0)\n \n mask_charging = np.take(self.flag_charging, i_impact) \n if np.any(mask_charging):\n Q_charging = np.take(self.Q_segments, i_impact[mask_charging])\n Q_max = np.take(self.Q_max_segments, i_impact[mask_charging])\n EQ = np.take(self.EQ_segments, i_impact[mask_charging])\n \n Q_charging[Q_charging<0.] = 0.\n Q_charging[Q_charging>Q_max] = Q_max[Q_charging>Q_max]\n \n yiel[mask_charging] = yiel[mask_charging] * (1. - Q_charging/Q_max) + (1. - np.exp(-E_impact_eV[mask_charging]/EQ))*(Q_charging/Q_max)\n \n # This would preserve also the ener\n # ref_frac[mask_charging] = ref_frac[mask_charging] * (1. - Q_charging/Q_max) + Q_charging/Q_max\n \n flag_elast = (rand(len(ref_frac)) < ref_frac)\n flag_truesec = ~(flag_elast)\n \n nel_emit = nel_impact * yiel\n\n for i_edg, flag_Q in enumerate(self.flag_charging):\n\n if flag_Q:\n mask_impact_here = (i_impact == i_edg)\n n_impact_here = np.sum(nel_impact[mask_impact_here])\n n_emit_here = np.sum(nel_emit[mask_impact_here])\n\n self.Q_segments[i_edg] += (n_impact_here - n_emit_here)*(-qe)/self.chamb.L_edg[i_edg]\n\n return nel_emit, flag_elast, flag_truesec\n\n def SEY_model_evol(self, Dt): \n mask_evol = np.logical_and(self.flag_charging, self.tau_segments>0.)\n self.Q_segments[mask_evol]*=np.exp(-Dt/self.tau_segments[mask_evol])\n\n\n\n\n\n\n","sub_path":"sec_emission_model_ECLOUD_nunif.py","file_name":"sec_emission_model_ECLOUD_nunif.py","file_ext":"py","file_size_in_byte":7500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"319605811","text":"import numpy\nfrom PIL import Image\nfrom OpenGL.GL import (\n glGenTextures, glBindTexture, GL_TEXTURE_2D, glPixelStorei, glDeleteTextures,\n GL_UNPACK_ALIGNMENT, glTexParameterf, GL_TEXTURE_MIN_FILTER,\n GL_TEXTURE_MAG_FILTER, glTexImage2D, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR)\n\n\nclass TextureType:\n \"\"\"\n TextureType is a class extended by any class intending to be used like\n a Texture or TextureRegion.\n\n Extenders need to make sure these instance variables are set:\n\n :ivar width: The default draw width of the image (normally the width in\n pixels). This is used by SpriteBatch when no draw width is given.\n :ivar height: The default draw height of the image (normally the height in\n pixels). This is used by SpriteBatch when no draw height is given.\n :ivar textureId: This is the OpenGL texture id that contains the image.\n :ivar frame: This is the 'frame' value of an animation. If this is not a\n part of an animation, this should be None.\n :ivar u1: The u-coordinate of the left part of the image.\n :ivar v1: The v-coordinate of the top or bottom of the image. If the camera\n has the y-axis going down (default), v1 should be the top of the image.\n :ivar u2: The u-coordinate of the right part of the image.\n :ivar v2: The v-coordinate of the top or bottom of the image. This should\n be the side opposite of `v1`.\n :ivar widthPercent: A value between 0 and 1 that indicates how much width\n the region of the texture takes of the original. This value is used to\n calculate U values when subdividing a region.\n :ivar heightPercent: A value between 0 and 1 that indicates how much height\n the region of the texture takes of the original. This value is used to\n calculate V values when subdividing a region.\n :ivar xOffset: Offsets this texture when drawn on the image's x-axis.\n :ivar yOffset: Offsets this texture when drawn on the image's y-axis.\n :ivar patches: The patches to use when creating a NinePatch from this\n texture. If this is None, the patches for NinePatch will have to be\n provided manually. This list/tuple should be 4 items in the order of\n left, right, top, and bottom patch.\n \"\"\"\n\n def flip(self):\n \"\"\"Flip the image vertically.\"\"\"\n self.v1, self.v2 = self.v2, self.v1\n\n def subdivide(self, x, y, width, height, safety=True) -> 'sapol.g2d.TextureRegion':\n \"\"\"\n Subdivide this image into a new TextureRegion.\n\n :param x: The x-coordinate of the beginning of the subdivide relative\n to the left of the image.\n :param y: The y-coordinate of the beginning of the subdivide relative\n to the top of the image.\n :param width: The width of the subdivide. This value may be negative\n (resulting in a horizontally flipped selection).\n :param height: The height of the subdivide. This value may be negative\n (resulting in a vertically flipped selection).\n :param safety: Whether or not to allow going beyond the bounds of the\n image.\n :return: The newly created TextureRegion.\n :rtype: TextureRegion\n\n :raise ValueError: If the new subdivide goes beyond the bounds and\n safety is set to true.\n \"\"\"\n if safety:\n if x + width < 0 or x < 0:\n raise RuntimeError(\"Subdivide goes beyond the left of image.\")\n if x + width > self.width or x > self.width:\n raise RuntimeError(\"Subdivide goes beyond the right of image.\")\n if y + height < 0 or y < 0:\n raise RuntimeError(\"Subdivide goes beyond the top of image.\")\n if y + height > self.height or y > self.height:\n raise RuntimeError(\"Subdivide goes beyond the bottom of image.\")\n return TextureRegion(self, x, y, width, height)\n\n\nclass Texture(TextureType):\n \"\"\"\n Texture is the class to load a texture into OpenGL. This texture can\n be from a file or from data already loaded. All parameters are named-only.\n To load a texture you must have one of the following:\n\n :param filename: The path to the file to load.\n\n OR\n\n :param imageData: The image data to load the texture from.\n :param dataWidth: The width of the image data.\n :param dataHeight: The height of the image data.\n\n OR\n\n :param textureId: The id of the already loaded texture.\n :param forcedWidth: See below\n :param forcedHeight: See below\n\n You can also specify any of these parameters by name:\n\n :param forcedWidth: Force the width variable to this size.\n :param forcedHeight: Force the height variable to this size.\n :param minFilter: The OpenGL value for the minimize filter.\n :param magFilter: The OpenGL value for the maximize filter.\n :param flipped: Whether or not the image is flipped vertically. This is\n needed if the y-axis is down (Default: True).\n\n See :class:`TextureType` for instance\n variables.\n \"\"\"\n\n def __init__(self, *, imageData=None, dataWidth=None, dataHeight=None,\n filename=None, textureId=None, forcedWidth=None, forcedHeight=None,\n minFilter: None=GL_LINEAR, magFilter: None=GL_LINEAR,\n flipped=True, patches=None):\n if imageData is not None and filename is not None:\n raise ValueError(\n \"Both imageData and filename parameters given, only one permitted.\")\n self.widthPercent = 1\n self.heightPercent = 1\n self.patches = patches\n self.u1 = 0\n self.u2 = 1\n if not flipped:\n self.v1 = 1\n self.v2 = 0\n else:\n self.v1 = 0\n self.v2 = 1\n\n self.frame = None\n self.xOffset = 0\n self.yOffset = 0\n if filename is not None:\n image = Image.open(filename)\n imageData = numpy.array(list(image.getdata()), numpy.uint8)\n dataWidth = image.width\n dataHeight = image.height\n elif textureId is not None:\n self.textureId = textureId\n\n if forcedWidth is not None:\n self.width = forcedWidth\n else:\n raise ValueError(\"textureId requires forcedWidth parameter.\")\n\n if forcedHeight is not None:\n self.height = forcedHeight\n else:\n raise ValueError(\"textureId requires forcedHeight parameter.\")\n return\n elif imageData is None:\n raise ValueError(\"Texture initialized without imageData, filename,\"\n \" or textureId.\")\n elif dataWidth is None:\n raise ValueError(\"Cannot use imageData without dataWidth parameter.\")\n elif dataHeight is None:\n raise ValueError(\"Cannot use imageData without dataHeight parameter.\")\n\n if forcedWidth is not None:\n self.width = forcedWidth\n else:\n self.width = dataWidth\n\n if forcedHeight is not None:\n self.height = forcedHeight\n else:\n self.height = dataHeight\n\n self.textureId = glGenTextures(1)\n glBindTexture(GL_TEXTURE_2D, self.textureId)\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter)\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dataWidth, dataHeight, 0, GL_RGBA,\n GL_UNSIGNED_BYTE, imageData)\n\n def free(self):\n \"\"\"\n Free the image from memory. You can not use the image after freeing\n it. Any TextureRegions or anything relying on the same textureId will\n also no longer work.\n \"\"\"\n glDeleteTextures(self.textureId)\n\n\nclass TextureRegion(TextureType):\n \"\"\"\n TextureRegion contains data for a region along a normal Texture object.\n A TextureRegion allows one to display parts of a texture instead of the\n whole thing. Having one image full of many different regions to draw is\n more efficient than having a separate image for each.\n\n :param texture: The parent TextureType object.\n :param x: The x-coordinate of the left part of the image.\n :param y: The y-coordinate of the top or bottom part of the image. If\n either flipped is True or height is negative, this is the top of the\n image. If both or neither are true, this is the bottom of the image.\n :param width: The width of the new region in pixels.\n :param height: The height of the new region in pixels.\n\n The following parameters may be specified by name:\n\n :param flipped: Whether or not the image should be flipped vertically. If\n None is given, this will default to whether the parent object is flipped.\n :param frame: The frame value of this region. This is used for ordering\n frames in Animation.\n :param xOffset: Offsets this region when drawn on its x-axis.\n :param yOffset: Offsets this region when drawn on its y-axis.\n\n :ivar texture: The original texture object this region is made from.\n\n See :class:`TextureType` for more instance\n variables.\n \"\"\"\n\n def __init__(self, texture, x, y, width, height, *, frame=None,\n flipped=None, xOffset=0, yOffset=0, patches=None):\n self.texture = texture\n self.textureId = texture.textureId\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.frame = frame\n self.xOffset = xOffset\n self.yOffset = yOffset\n self.patches = patches\n\n self.u1 = x / texture.width\n self.v1 = y / texture.height\n self.u2 = (x + width) / texture.width\n self.v2 = (y + height) / texture.height\n self.widthPercent = width / texture.width\n self.heightPercent = height / texture.height\n\n if flipped is None:\n if texture.v1 > texture.v2:\n self.flip()\n elif flipped:\n self.flip()\n\n\nclass NinePatch:\n \"\"\"\n NinePatch splits a texture into 9 different 'patches' which are then stretched\n in different ways to fill an area. The corner patches are not stretched at all.\n The bottom and top middle patches are stretched horizontally. The left and\n right middle patches are stretched vertically. The center patch is stretched\n in both directions. Doing this allows a texture like the background of a\n button to fill an area, without looking weird or having to use a different\n texture for every button.\n\n NinePatch can either accept 1, 5, or 9 arguments:\n\n * If only 1 argument is provided, it is expected to extend TextureType, and\n to have its patches instance variable set.\n * If 5 arguments are provided, it is expected that the first extends TextureType,\n and the next for arugments are the left, right, top, and bottom patches\n in that order.\n * If 9 arguments are provided, it is expected that all nine arguments extend\n TextureType (normally these should be TextureRegions). These will be\n directly made to represent the 9 patches from left->right, top->bottom.\n \"\"\"\n\n def __init__(self, *args):\n if len(args) == 1:\n texture = args[0]\n if texture.patches is None:\n raise RuntimeError(\"To create a patch from a TextureType, it requires\"\n \" the TextureType to have the patches attribute set.\")\n args = (texture, *texture.patches)\n if len(args) == 5:\n texture = args[0]\n width = texture.width\n height = texture.height\n left, right, top, bottom = args[1], args[2], args[3], args[4]\n middleWidth = width - left - right\n middleHeight = height - top - bottom\n bottomOffset = height - bottom\n rightOffset = width - right\n # Patches are created from the upper left to the lower right:\n self._patches = [\n texture.subdivide(0, 0, left, top),\n texture.subdivide(left, 0, middleWidth, top),\n texture.subdivide(rightOffset, 0, right, top),\n texture.subdivide(0, top, left, middleHeight),\n texture.subdivide(left, top, middleWidth, middleHeight),\n texture.subdivide(rightOffset, top, right, middleHeight),\n texture.subdivide(0, bottomOffset, left, bottom),\n texture.subdivide(left, bottomOffset, middleWidth, bottom),\n texture.subdivide(rightOffset, bottomOffset, right, bottom)\n ]\n elif len(args) == 9:\n self._patches = list(args)\n else:\n raise RuntimeError(\"NinePatch expects 1, 5, or 9 arguments, got {}\"\n .format(len(args)))\n self._recalculateSides()\n\n def _recalculateSides(self):\n self._left = min(patch.width for patch in self._patches[::3])\n self._right = min(patch.width for patch in self._patches[2::3])\n self._top = min(patch.height for patch in self._patches[0:3])\n self._bottom = min(patch.height for patch in self._patches[6:9])\n\n def draw(self, spriteBatch: 'sapol.g2d.SpriteBatch', x, y, width, height, *,\n unpatchWidth=False, unpatchHeight=False, **kwargs):\n \"\"\"\n Draw the NinePatch.\n\n :param spriteBatch: The SpriteBatch to draw with.\n :param x: The x-location of the start of the patch.\n :param y: The y-location of the start of the patch.\n :param width: The width to fill.\n :param height: The height to fill.\n\n Must be provided by name:\n\n :param unpatchedWidth: Forces the width of the patch to not operate as\n normally. This will not draw the center patches and cause the left\n and right patches to be stretched to fill the space. This normally\n only happens if the width to fill is smaller than the NinePatch is\n made to fill.\n :param unpatchHeight: Forces the height of the patch to not operate as\n normally much like unpatchWidth.\n :param kwargs: Any extra arguments to pass to SpriteBatch's\n :py:meth:`draw()`.\n \"\"\"\n if width < self._left + self._right:\n unpatchWidth = True\n if height < self._top + self._bottom:\n unpatchHeight = True\n\n widths = None\n leftRightWidth = self._left + self._right\n if not unpatchWidth:\n widths = (self._left, width - leftRightWidth, self._right)\n else:\n widths = (width * self._left / leftRightWidth, 0,\n width * self._right / leftRightWidth)\n xOffsets = (0, widths[0], widths[0] + widths[1])\n if \"xOrigin\" in kwargs:\n xOffsets = tuple(oldOffset + kwargs[\"xOrigin\"] for oldOffset in xOffsets)\n del kwargs[\"xOrigin\"]\n\n heights = None\n topBottomHeight = self._top + self._bottom\n if not unpatchHeight:\n heights = (self._top, height - topBottomHeight, self._bottom)\n else:\n heights = (height * self._top / topBottomHeight, 0,\n height * self._bottom / topBottomHeight)\n yOffsets = (0, heights[0], heights[0] + heights[1])\n if \"yOrigin\" in kwargs:\n yOffsets = tuple(oldOffset + kwargs[\"yOrigin\"] for oldOffset in yOffsets)\n del kwargs[\"yOrigin\"]\n\n for i, patch in enumerate(self._patches):\n px = i % 3\n py = i // 3\n spriteBatch.draw(patch, x, y, xOrigin=-xOffsets[px], yOrigin=-yOffsets[py],\n width=widths[px], height=heights[py], **kwargs)\n","sub_path":"sapol/g2d/texture.py","file_name":"texture.py","file_ext":"py","file_size_in_byte":15847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"490540516","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef findContrastValue(xInput, xMin, xMax, yMin, yMax):\n\n # set to black if on left of stretched region\n if xInput < xMin:\n return 0;\n \n #squeeze values to right of region\n elif xInput > xMax:\n squeezedSlope = (255 - yMax)/(255 - xMax) * (xInput - xMax) + yMax\n return squeezedSlope\n\n #inside contrast range\n else :\n #caclulate slope for contrast\n stretchedSlope = (yMax - yMin)/(xMax - xMin) * (xInput - xMin) + yMin\n return stretchedSlope\n\n\n# Load an color image in grayscale\nimg = cv2.imread('/Users/eric/Desktop/CVProjects/ImProc/overview.jpg',0)\n\n#dim of original image\nwidth = np.size(img, 1)\nheight = np.size(img, 0)\n\n\n#initiate contrast images\ncontrast_img = np.zeros((height, width), np.uint8)\n\n#initiate histogram array\nhistogram = np.zeros((256))\n\nfor i in range(height) :\n for j in range(width):\n contrast_img[i][j] = findContrastValue(img[i][j], 210, 250, 140, 250)\n histogram[contrast_img[i][j]] += 1\n\nprint(width*height)\nprint(histogram.sum())\n\n#lab and show histogram\nplt.plot(img)\nplt.plot(histogram)\nplt.title(\"Intensity Histogram\")\nplt.ylabel(\"Amount of Pixlels\")\nplt.xlabel(\"Intensity\")\nplt.show()\n\n#show images\ncv2.imshow('image',img)\ncv2.imshow('contrast_image', contrast_img)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"CVPython/PythonFiles/contrast.py","file_name":"contrast.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"514697052","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport argparse\nimport logging\n\nimport numpy as np\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom torch.nn.utils import clip_grad_norm_\nfrom torch.backends import cudnn\n\nimport models\nimport load_so_data as so_data\n\navailable_models = {\n 'baseline_count': models.BaselineVAECount,\n # 'cd_linear_count': models.LinearParametricVAECount,\n # 'personalised_linear_count': models.LinearParametricPlusSteerParamVAECount,\n 'full_parameterised_count': models.FullParameterisedVAECount,\n 'full_personalised_parameterised_count': models.FullParameterisedPlusSteerParamVAECount,\n 'baseline_flow_count': models.NormalizingFlowBaseline,\n 'fp_flow_count': models.NormalizingFlowFP,\n 'full_personalised_normalizing_flow': models.NormalizingFlowFP_PlusSteer\n }\n\ndef isnan(x):\n return x != x\n\ndef raise_cuda_error():\n raise ValueError('You wanted to use cuda but it is not available. '\n 'Check nvidia-smi and your configuration. If you do '\n 'not want to use cuda, pass the --no-cuda flag.')\n\ndef setup_cuda(seed, device):\n if device.index:\n device_str = f\"{device.type}:{device.index}\"\n else:\n device_str = f\"{device.type}\"\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = device_str\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n # This does make things slower :(\n torch.backends.cudnn.benchmark = False\n\nloss_fn = lambda x1,x2,x3: models.ZeroInflatedPoisson_loss_function(x1,x2,x3)\n\ndef get_loader_params(args):\n # Loading Parameters\n loader_params = {\n 'batch_size': int(args.batch_size),\n 'shuffle': True,\n 'num_workers': 8\n }\n dset_params = {\n 'window_length': args.window_length,\n 'badge_focus': 'strunk_white',\n 'out_dim': 0,\n 'data_path': args.input,\n 'badge_threshold': 80,\n 'badges_to_avoid': [],\n 'ACTIONS': [0]\n }\n return loader_params, dset_params\n\ndef main(args):\n # TODO: add checkpointing\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n if not args.no_cuda and not use_cuda:\n raise_cuda_error()\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n if use_cuda:\n logging.info(f'Using device: {torch.cuda.get_device_name()}')\n\n # For reproducibility:\n # c.f. https://pytorch.org/docs/stable/notes/randomness.html\n if args.seed is None:\n args.seed = torch.randint(0, 2 ** 32, (1,)).item()\n logging.info(f'You did not set --seed, {args.seed} was chosen')\n\n if use_cuda:\n setup_cuda(args.seed, device)\n\n config_args = [str(vv) for kk, vv in vars(args).items()\n if kk in ['batch_size', 'lr', 'gamma', 'seed']]\n model_name = '_'.join(config_args)\n\n if not os.path.exists(args.output):\n logging.info(f'{args.output} does not exist, creating...')\n os.makedirs(args.output)\n\n loader_params, dset_params = get_loader_params(args=args)\n\n dset_train = so_data.StackOverflowDatasetIncCounts(\n dset_type='train',\n subsample=15000,\n **dset_params,\n self_initialise=True\n )\n scalers = dset_train.get_scalers()\n dset_valid = so_data.StackOverflowDatasetIncCounts(\n dset_type='validate',\n subsample=5000,\n centered=True,\n **dset_params,\n scaler_in=scalers[0],\n scaler_out=scalers[1])\n\n train_loader = DataLoader(dset_train, **loader_params)\n valid_loader = DataLoader(dset_valid, **loader_params)\n\n print(args.model_name)\n model_class = available_models[args.model_name]\n\n dset_shape = dset_train.data_shape\n model = model_class(\n obsdim=dset_shape[0] * dset_shape[1],\n outdim=dset_shape[0],\n device=device,\n proximity_to_badge=True\n ).to(device)\n\n model_name = 'strunk_white-' + args.model_name + \"-\" + model_name + '.pt'\n PATH_TO_MODEL = args.output+'/models/'+model_name\n\n if os.path.exists(PATH_TO_MODEL):\n model.load_state_dict(torch.load(PATH_TO_MODEL, map_location=device))\n\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\n scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=args.gamma)\n\n if not os.path.exists(f'{args.output}/logs/'):\n os.mkdir(f'{args.output}/logs/')\n\n log_fh = open(f'{args.output}/logs/{model_name}.log', 'w')\n best_loss = sys.float_info.max\n\n results_file = open(f'{args.output}/results.csv', 'a')\n results_file.write(f'{model_name},{args.batch_size},{args.lr},{args.gamma},'\n f'{args.seed},')\n\n count_valid_not_improving = 0\n\n for epoch in tqdm(range(1, args.epochs + 1), disable=use_cuda):\n\n loss = train(args, model, device, train_loader, optimizer, epoch)\n vld_loss = test(args, model, device, valid_loader)\n\n print(f'{epoch},{loss},{vld_loss}', file=log_fh)\n scheduler.step()\n\n results_file.write(f'{vld_loss},')\n\n if vld_loss < best_loss:\n # only save the model if it is performing better on the validation set\n best_loss = vld_loss\n torch.save(model.state_dict(),\n f\"{args.output}/models/{model_name}.best.pt\")\n count_valid_not_improving = 0\n\n # early stopping\n else:\n count_valid_not_improving += 1\n\n if count_valid_not_improving > args.early_stopping_lim:\n print(f'Early stopping implemented at epoch #: {epoch}')\n break\n\n results_file.write('\\n')\n torch.save(model.state_dict(), f\"{args.output}/models/{model_name}.final.pt\")\n\n results_file.close()\n log_fh.close()\n\ndef train(args, model, device, train_loader, optimizer, epoch):\n model.train()\n train_loss = 0\n correct = 0\n beta = 1\n\n for batch_idx, (data) in enumerate(train_loader):\n data = [d.to(device) for d in data]\n dat_in, dat_kern, dat_out, dat_prox, dat_badge_date = data\n\n optimizer.zero_grad()\n # Model computations\n recon_batch, latent_loss = model(dat_in,\n kernel_data=dat_kern,\n dob=dat_badge_date,\n prox_to_badge=dat_prox)\n loss = loss_fn(recon_batch, dat_out, beta * latent_loss)\n loss.backward()\n # TODO: clip grad norm here?\n optimizer.step()\n\n train_loss += loss.item()\n\n if batch_idx % args.log_interval == 0 and not args.quiet:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n return train_loss/len(train_loader.dataset)\n\ndef test(args, model, device, valid_loader):\n model.eval()\n test_loss = 0\n\n with torch.no_grad():\n for batch_idx, (data) in enumerate(valid_loader):\n data = [d.to(device) for d in data if type(d) == torch.Tensor]\n dat_in, dat_kern, dat_out, dat_prox, dat_badge_date = data\n\n recon_batch, latent_loss = model(dat_in,\n kernel_data=dat_kern,\n dob=dat_badge_date,\n prox_to_badge=dat_prox)\n\n loss = loss_fn(recon_batch, dat_out, latent_loss)\n test_loss += loss.item()\n\n test_loss /= len(valid_loader.dataset)\n print('\\nTest set: Average loss: {:.4f}'.format(test_loss))\n\n return test_loss\n\ndef construct_parser():\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch main script to run inference detailed here: '\n 'https://arxiv.org/abs/2002.06160'\n 'on the population of users who achieved Strunk & White')\n parser.add_argument('--batch-size', type=int, default=128, metavar='N',\n help='input batch size for training (default: 128)')\n parser.add_argument('--early-stopping-lim', type=int, default=10, metavar='N',\n help='Early stopping implemented after N epochs with no improvement '\n '(default: 10)')\n parser.add_argument('--test-batch-size', type=int, default=1000,\n metavar='N', help='input batch size for testing '\n '(default: 1000)')\n parser.add_argument('--epochs', type=int, default=1000, metavar='N',\n help='number of epochs to train (default: 1000)')\n parser.add_argument('--lr', type=float, default=0.001, metavar='LR',\n help='learning rate (default: 0.001)')\n parser.add_argument('--gamma', type=float, default=0.9, metavar='M',\n help='Learning rate step gamma (default: 0.9)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--quiet', action='store_true', default=False,\n help='Limits the about of output to std.out')\n parser.add_argument('--seed', type=int, default=None, metavar='S',\n help='random seed (default: random number)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status (default: 10)')\n parser.add_argument('--window-length', type=int, default=35, metavar='N',\n help='how long is the window that is considered before / after a badge (default: 35)')\n parser.add_argument('-M', '--model-name', default=\"full_personalised_normalizing_flow\", required=False,\n help='Choose the model to run')\n parser.add_argument('-i', '--input', required=True, help='Path to the input data for the model to read')\n parser.add_argument('-o', '--output', required=True, help='Path to the directory to write output to')\n return parser\n\nif __name__ == \"__main__\":\n parser = construct_parser()\n args = parser.parse_args()\n main(args)\n","sub_path":"src/main_strunk_white_count_data.py","file_name":"main_strunk_white_count_data.py","file_ext":"py","file_size_in_byte":10740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"299528920","text":"'''\nhttps://www.hackerrank.com/contests/w26/challenges/best-divisor\n'''\n\n#!/bin/python3\n\nimport sys\n\ndef getBestDivisor(n):\n maxSum = 1\n bestI = 1\n for i in range(1,n+1):\n if(isDivisor(i, n)):\n #print(i, \"isDivisor\")\n sum = calcSum(i)\n if(sum > maxSum):\n maxSum = sum\n bestI = i\n return bestI\n\ndef isDivisor(i, n):\n return (n % i == 0)\n\ndef calcSum(n):\n sum = 0\n while n > 0:\n sum += n%10\n n = (int)(n/10)\n #print (\"sum =\", sum)\n return sum\n\nn = int(input().strip())\nprint(getBestDivisor(n))","sub_path":"Contests/WeekOfCode26/BestDivisor.py","file_name":"BestDivisor.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"90588170","text":"#!/usr/bin/env python2\n\nimport biplist\nimport distutils.dir_util as distutils\nimport filecmp\nimport glob\nimport plistlib\nimport os.path\nimport shutil\n\n\nHOME_DIR = os.path.expanduser('~')\nCORE_PREFS_NAME = 'com.runningwithcrayons.Alfred-Preferences.plist'\nUSER_PREFS_NAME = 'Alfred.alfredpreferences'\nDEFAULT_USER_PREFS_DIR = os.path.join(\n HOME_DIR, 'Library', 'Application Support', 'Alfred 2')\nPKG_RESOURCES = ('icon.png', 'yvs/__init__.py', 'yvs/shared.py', 'yvs/data')\n\n\n# Get path to directory containing Alfred's user preferences\ndef get_user_prefs_dir():\n\n core_prefs = biplist.readPlist(\n os.path.join(HOME_DIR, 'Library', 'Preferences', CORE_PREFS_NAME))\n\n # If user is syncing their preferences using a syncing service\n if 'syncfolder' in core_prefs:\n return os.path.expanduser(core_prefs['syncfolder'])\n else:\n return DEFAULT_USER_PREFS_DIR\n\n\n# Get path to Alfred's user preferences file\ndef get_user_prefs_path():\n\n return os.path.join(get_user_prefs_dir(), USER_PREFS_NAME)\n\n\n# Get path to installed workflow\ndef get_workflow_path():\n\n yvs_packages = glob.glob(\n os.path.join(get_user_prefs_path(), 'workflows', '*', 'yvs'))\n\n if len(yvs_packages) == 0:\n raise OSError('YouVersion Suggest in not installed locally')\n\n return os.path.dirname(yvs_packages[0])\n\n\n# Get path to installed workflow's info.plist file\ndef get_workflow_info_path(workflow_path):\n\n return os.path.join(workflow_path, 'info.plist')\n\n\n# Parse the info.plist file at the given path\ndef get_workflow_info(info_path):\n\n return plistlib.readPlist(info_path)\n\n\n# Get the file content of a module withini the project\ndef get_module_content(module_name):\n\n filename = '{}.py'.format(module_name.replace('.', '/'))\n with open(filename, 'r') as file:\n return file.read()\n\n\n# Get the name of a module by parsing it from the module content\ndef get_module_name(module_content):\n\n first_line = module_content.split('\\n', 1)[0]\n module_name = first_line[1:].strip()\n return module_name\n\n\n# Update content of all scripts in workflow info object\ndef update_workflow_objects(info):\n\n updated_objects = False\n\n for obj in info['objects']:\n\n if 'script' in obj['config']:\n\n module_name = get_module_name(obj['config']['script'])\n new_module_content = get_module_content(module_name)\n\n if new_module_content != obj['config']['script']:\n obj['config']['script'] = new_module_content\n print('Updated {}'.format(module_name))\n updated_objects = True\n\n return updated_objects\n\n\n# Recursively check if two directories are exactly equal in terms of content\ndef dirs_are_equal(dir_path, dest_dir_path):\n\n dirs_cmp = filecmp.dircmp(dir_path, dest_dir_path)\n if len(dirs_cmp.left_only) > 0 or len(dirs_cmp.right_only) > 0:\n return False\n\n match, mismatch, errors = filecmp.cmpfiles(\n dir_path, dest_dir_path, dirs_cmp.common_files, shallow=False)\n if len(mismatch) > 0 or len(errors) > 0:\n return False\n\n for common_dir in dirs_cmp.common_dirs:\n new_dir_path = os.path.join(dir_path, common_dir)\n new_dest_dir_path = os.path.join(dest_dir_path, common_dir)\n if not dirs_are_equal(new_dir_path, new_dest_dir_path):\n return False\n\n return True\n\n\n# Check if resource (file or directory) is equal to destination resource\ndef resources_are_equal(resource_path, dest_resource_path):\n\n try:\n return dirs_are_equal(resource_path, dest_resource_path)\n except OSError:\n # Compare files if they are not directories\n try:\n return filecmp.cmp(resource_path, dest_resource_path)\n except OSError:\n # Resources are not equal if either does not exist\n return False\n\n\n# Copy package resource (file or directory) to corresponding destination path\ndef copy_resource(resource_path, dest_resource_path):\n\n try:\n distutils.copy_tree(resource_path, dest_resource_path)\n except distutils.DistutilsFileError:\n shutil.copy(resource_path, dest_resource_path)\n\n\n# Copy all package resources (files or directories) to installed workflow\ndef copy_pkg_resources(workflow_path):\n\n updated_resources = False\n\n for resource_path in PKG_RESOURCES:\n\n dest_resource_path = os.path.join(workflow_path, resource_path)\n # Only copy resources if content has changed\n if not resources_are_equal(resource_path, dest_resource_path):\n copy_resource(resource_path, dest_resource_path)\n print('Updated {}'.format(resource_path))\n updated_resources = True\n\n return updated_resources\n\n\n# Write info.plist object to file if content has updated\ndef save_info(info, info_path, updated_workflow=True):\n\n if updated_workflow:\n plistlib.writePlist(info, info_path)\n print('Updated info.plist')\n\n\ndef main():\n\n workflow_path = get_workflow_path()\n info_path = get_workflow_info_path(workflow_path)\n info = get_workflow_info(info_path)\n updated_objects = update_workflow_objects(info)\n updated_resources = copy_pkg_resources(workflow_path)\n updated_workflow = updated_objects or updated_resources\n save_info(info, info_path, updated_workflow)\n if updated_workflow:\n print('Updated workflow successfully')\n else:\n print('Workflow has not changed')\n\nif __name__ == '__main__':\n main()\n","sub_path":"utilities/update_workflow.py","file_name":"update_workflow.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"297831234","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n\n# use creds to create a client to interact with the Google Drive API\nscope = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']\ncreds = ServiceAccountCredentials.from_json_keyfile_name('evocative-tower-300912-dc0f7ff590fb.json', scope)\nclient = gspread.authorize(creds)\n\nsheet = client.open(\"Bröllopsplanering\").worksheets()[-1]\n\n# Extract and print all of the values\nlist_of_guests = sheet.get_all_values()\n\ntexed_list_of_guests = []\n\nfor i, (id, name, desc, table) in enumerate(list_of_guests):\n texed_list_of_guests.append(' \\\\noindent\\\\begin{minipage}{\\\\textwidth}\\\\centering\\\\scriptsize %s %s \\\\tiny \\\\\\\\ \\\\emph{%s}\\\\end{minipage} \\\\newline \\\\par \\n' % (id.replace('#', '\\#'), name, desc.replace('#', '\\#')))\n\n\nwith open('preamble.tex') as f:\n preamble = f.readlines()\n\nwith open('postamble.tex') as f:\n postamble = f.readlines()\n\nwith open('menu_to_print.tex', 'w') as f:\n f.writelines(preamble+texed_list_of_guests+postamble)\n\n\n","sub_path":"program/create_menu.py","file_name":"create_menu.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"638750282","text":"from django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\nfrom django.http.response import JsonResponse\nfrom django.contrib.auth.models import User\n\nfrom .serializer import UserSerializer\n\n@csrf_exempt\ndef UserApi(request, username=''):\n if request.method == \"GET\":\n user = User.objects.all()\n user_serializer = UserSerializer(user, many=True)\n return JsonResponse(user_serializer.data, safe=False)\n\n elif request.method == \"POST\":\n user = JSONParser().parse(request)\n user_serializer = UserSerializer(data=user)\n if user_serializer.is_valid():\n user_serializer.save()\n return JsonResponse(True, safe=False)\n return JsonResponse(False, safe=False)\n\n elif request.method == \"PUT\":\n user_data = JSONParser().parse(request)\n user = User.objects.get(username=user_data['username'])\n user_serializer = UserSerializer(user, data=user_data)\n if user_serializer.is_valid():\n user_serializer.save()\n return JsonResponse(True, safe=False)\n return JsonResponse(False, safe=False)\n\n elif request.method == \"DELETE\":\n user = User.objects.get(username=user_data['username'])\n user.delete()\n return JsonResponse(\"Record deleted successfully!\", safe=False)\n","sub_path":"backend/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"430112723","text":"import os\nimport sys\nimport csv\nimport pandas as pd\nimport numpy as np\nfrom data_types import get_dtypes_dict\n\ndef strip_flags(df, col):\n if col in df.columns:\n df[col] = df[col].replace(0, '')\n return df\n\ndef strip_value(df, val):\n \"\"\"Return data frame with \"unavailable\" numeric value removed\n \"\"\"\n df = df.replace(val, np.nan)\n df = df.round(3)\n return df\n\nif __name__ == '__main__':\n\n region = sys.argv[1]\n dtypes = get_dtypes_dict(region)\n flag_cols = [ 'r', 'u', 's', 't', 'mg', 'ch', 'm', 'e', 'c', 'bie' ]\n\n # Read the data dictionary from stdin\n data_df = pd.read_csv(sys.stdin, dtype=dtypes)\n\n # strip the value to create output\n output_df = strip_value(data_df, -999)\n for col in flag_cols:\n output_df = strip_flags(output_df, col)\n\n output_df.to_csv(sys.stdout, index=False)\n","sub_path":"scripts/strip_values.py","file_name":"strip_values.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"276919370","text":"\"\"\" Import all needed modules\"\"\"\nfrom PyQt5 import QtWidgets\nfrom view import Authorization_view\nfrom model import AuthorizationModel\n\n\nif __name__ == \"__main__\":\n\n def press_reg_button_reflect(local_ui: Authorization_view, local_model): # Interaction with clicked registration button\n local_model.registration_data(local_ui)\n local_model.new_window(True)\n\n\n def press_aut_button_reflect(local_ui: Authorization_view, local_model): # Interaction with clicked authorization button\n local_model.authorization(local_ui)\n local_model.new_window(False)\n local_model.clear_data(local_ui)\n\n\n\n import sys\n app = QtWidgets.QApplication(sys.argv)\n authorization = QtWidgets.QWidget()\n ui = Authorization_view(authorization)\n\n \"\"\" Components Events adding \"\"\"\n model = AuthorizationModel(ui)\n\n ui.registation_button.clicked.connect( lambda: press_reg_button_reflect(ui, model))\n\n ui.authorization_button.clicked.connect(lambda: press_aut_button_reflect(ui, model))\n\n authorization.show()\n sys.exit(app.exec_())\n\n","sub_path":"authorization_form/controler.py","file_name":"controler.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"487186198","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nAuteur : Stanislas Gueniffey(000377223)\r\nCours : INFO-F-106\r\nProjet : Partie 4\r\n\"\"\"\r\n\r\nfrom random import choice, random, randrange\r\n\r\n\r\ndef nameIsValid(name, otherNames):\r\n \"\"\"Fonction-reference pour determiner si un nom 'name' est valable et disponible\r\n etant donne l'ensemble des noms deja utilises otherNames.\"\"\"\r\n return (name.isalnum() and len(name)<25 and not(name in otherNames))\r\n\r\n \r\ndef saveNetwork(filename, netFrame):\r\n \"\"\"Prend en parametre un fichier filename ou le reseau doit etre sauvegarde.\r\n Ecrit dans ce fichier l'etat du reseau de netFrame\"\"\"\r\n netw_file = open(filename, 'w')\r\n \r\n for user in netFrame.getAllUsers(): #Itère sur ensemble des utilisateurs\r\n netw_file.write(str(user)) #Représentation en string de l'utilisateur\r\n netw_file.write(\"\\n\")\r\n \r\n netw_file.close()\r\n \r\n\r\ndef loadNetwork(filename, netFrame, simConfig):\r\n \"\"\"Prend en parametre un fichier filename decrivant le reseau a charger et l'instance\r\n de la classe gérant les parametres de simulation. Retourne un dictionnaire representant le\r\n reseau a charger et une liste des strings representant les statistiques des simulations \r\n effectuees auparavant. Un fichier corrompu entraine le retour d'element vides du meme type.\"\"\"\r\n errorFlag = False #Vrai si une erreur grave survient\r\n \r\n NETW = {} #DICT DE RETOUR {utilisateurs:{amis:configurations}{\"user_rumors\":rumeurs}}\r\n STATS = [] #LISTE DE RETOUR (lignes de statistiques)\r\n \r\n netw_file = open(filename, 'r')\r\n print(\"\\nNetwork loading...\")\r\n \r\n default_rumors = simConfig.defaultRumors\r\n default_config = simConfig.defaultConfig\r\n \r\n names = [] #Contient les noms d'utilisateurs dans l'ordre d'apparition\r\n configs = [] #Contient à l'index i une liste de tuples (nom d'un ami de i, config)\r\n \r\n ###LECTURE DU FICHIER###\r\n try:\r\n got_to_stats = False #Devient vrai quand on atteint l'en-tête statistique\r\n for line in netw_file.readlines():\r\n line = line.strip()\r\n if line == \"\": #En-tête statistiques atteinte\r\n got_to_stats = True\r\n \r\n elif len(line) > 2 and not got_to_stats: #Avant statistiques, lignes non \"vides\"\r\n lineData = line.split(':')\r\n userName = lineData[0].strip()\r\n \r\n if not nameIsValid(userName, NETW.keys()): #Evite les doublons & noms non valables\r\n print(\"User %s could not be added because its username was taken\"%userName)\r\n else:\r\n if len(lineData) == 2: #NOM + AMIS (rétrocompatibilité)\r\n userRumors = default_rumors\r\n friendsData = [data.strip() for data in lineData[1].split(';')]\r\n else: #NOM + RUMEURS + AMIS\r\n userRumors = eval(lineData[1])\r\n friendsData = [data.strip() for data in lineData[2].split(';')]\r\n \r\n #Encore les rumeurs dans le dictionnaire avec clé fixée != nom valable\r\n NETW[userName] = {\"user_rumors\":userRumors} #Ebauche de Network\r\n names.append(userName) #Structure temp. pour verifications\r\n \r\n conf_line = [] #Liste temp. a ajouter aux configs\r\n user_friends = set() #Ensemble des noms d'amis, pour éviter les doublons\r\n \r\n for data in friendsData: #data peut être NOM ou NOM + (CONFIG)\r\n try:\r\n friend_name, friend_config = data.split('(') #Retire déjà \"(\"\r\n \r\n except: #Si data = nom\r\n if nameIsValid(data, user_friends): #Si le nom est valable\r\n user_friends.add(data)\r\n conf_line.append((data, default_config)) #Param. par défaut\r\n \r\n else: #Si data = nom + (config)\r\n friend_name = friend_name.strip()\r\n if nameIsValid(friend_name, user_friends):#Si le nom est valable\r\n user_friends.add(friend_name)\r\n \r\n #Lit la configuration ([:-1] pour retirer parenthèse fermante)\r\n full_config = simConfig.expandConfig(friend_config[:-1])\r\n if full_config!=None: #Si la configuration est valable\r\n conf_line.append((friend_name, full_config))\r\n else: #Sinon, donne paramètres par défaut\r\n print(\"Default config had to be used for friends %s,%s\"%\\\r\n (userName, friend_name))\r\n conf_line.append((friend_name, default_config))\r\n \r\n configs.append(conf_line)\r\n \r\n elif got_to_stats: #Après en-tête statistiques\r\n STATS.append(line)\r\n except:\r\n print(\"Network file is corrupted or invalid\")\r\n errorFlag = True\r\n \r\n \r\n ###CREATION DU RESEAU & VERIFICATIONS###\r\n else:\r\n nbUsers = len(names) #Nombre d'utilisateurs\r\n if nbUsers == 0:\r\n print(\"Network file defines 0 users\")\r\n errorFlag = True\r\n else: #Si le nombre d'utilisateurs n'est pas nul\r\n \r\n for user_index in range(nbUsers): #Pour chaque utilisateur d'index user_index\r\n user_name = names[user_index]\r\n \r\n for friend_index in range(len(configs[user_index])): #Pour chacun de ses amis\r\n friend_name = configs[user_index][friend_index][0] #Nom de l'ami\r\n friend_conf = configs[user_index][friend_index][1] #Config. de l'amitié\r\n \r\n if friend_name not in NETW.keys(): #Ami n'existe pas\r\n print(\"%s's friend %s is not a user\"\\\r\n %(usr_names[user_index],friend_name))\r\n elif friend_name == user_name: #Amitié avec soi-même\r\n print(\"User %s can't be friend with himself\"%friend_name)\r\n else: #Tout va bien\r\n NETW[user_name][friend_name] = friend_conf #Encode l'amitié\r\n #Si l'amitié n'est pas (encore) symétrique, lui donne la config par défaut\r\n if user_name not in NETW[friend_name].keys():\r\n NETW[friend_name][user_name] = default_config\r\n \r\n print(\"\\nNetwork successfully loaded\")\r\n netw_file.close()\r\n return ({}, []) if errorFlag else (NETW, STATS)\r\n\r\n\r\ndef update(sim, netFrame, rumorType):\r\n \"\"\"Effectue les transmissions des rumeurs correspondant a une etape de la simulation dans le \r\n reseau represente par netFrame pour le type de rumeur rumorType et en fonction des parametres\r\n de la simulation contenus dans la classe sim.\r\n Retourne le nombre d'utilisateurs mis au courant de la rumeur pendant cette etape.\"\"\"\r\n \r\n ###CHOIX DES PERSONNES A INFORMER###\r\n peopleToInform = {} #cles= gens a informer; valeurs= dict{rumeur: raconteurs}\r\n \r\n for talker in netFrame.getAwareUsers(rumorType): #Pour chaque personne au courant\r\n allFriends = list(talker.getFriends()) #Ensemble des amis\r\n friends_chosen = [] #Amis choisis pour raconter la rumeur\r\n toldRumor = talker.getRumor(rumorType) #Rumeur connue\r\n \r\n if allFriends: #Si cette liste n'est pas vide\r\n if sim.curFriendChoice == \"random\": #Choisit un ami au hasard\r\n friends_chosen = [choice(allFriends)]\r\n else:#sim.curFriendChoice == \"random-d\" #Choisit un ami ne connaissant pas la rumeur\r\n unawareFriends = [friend for friend in allFriends if friend.isUnaware(rumorType)]\r\n if unawareFriends:\r\n friends_chosen = [choice(unawareFriends)] #Choice : erreur si liste vide\r\n else:\r\n friends_chosen = []\r\n \r\n for friend in friends_chosen:\r\n try: \r\n try:\r\n #Si toldRumor est déjà dans le dict. de friend\r\n peopleToInform[friend][toldRumor].append(talker)\r\n except:\r\n #Si toldRumor n'est pas dans le dict. de friend\r\n peopleToInform[friend][toldRumor] = [talker]\r\n except:\r\n #Si friend n'est pas dans les clés de peopleToInform\r\n peopleToInform[friend] = {toldRumor:[talker]} \r\n \r\n ###TRANSMISSION DE LA RUMEUR###\r\n newInformed = 0 #Nombre de nouveaux informes a ce tour\r\n \r\n for listener in peopleToInform.keys():\r\n for told_rumor in peopleToInform[listener].keys():\r\n for talker in peopleToInform[listener][told_rumor]:\r\n \r\n if sim.configIsGeneral(): #Configuration : parametres generaux\r\n error_prob, modif_type, update_rule = sim.getGlobalConfig()\r\n else: #Parametres individuels\r\n error_prob, modif_type = talker.getConfig(listener)[:2]#De transmission (A:B)\r\n update_rule = listener.getConfig(talker)[2] #De reception (B:A)\r\n \r\n #Decide de la version racontee par l'émetteur\r\n heard_rumor = alter_rumor(told_rumor, sim, modif_type, error_prob, rumorType)\r\n \r\n #Decide de la version retenue par le récepteur\r\n if listener.isUnaware(rumorType): #Si c'est sa premiere rumeur il la garde\r\n newInformed += 1\r\n listener.setRumor(heard_rumor, rumorType)\r\n else: #Sinon, ca depend des parametres de la simulation\r\n old_rumor = listener.getRumor(rumorType)\r\n new_rumor=choose_rumor(old_rumor, heard_rumor, sim, update_rule, rumorType)\r\n listener.setRumor(new_rumor, rumorType)\r\n\r\n return newInformed\r\n\r\n\r\ndef alter_rumor(rumor, sim, modif_type, modif_prob, rumorType):\r\n \"\"\"Effectue le changement de la rumeur rumor en fonction de son type rumorType et des\r\n parametres de transmission modif_type et modif_prob, avec l'aide de la classe sim contenant\r\n les donnees sur les limites de tailles des differents types de rumeurs.\"\"\"\r\n newRumor = rumor #\"Copie\" de la rumeur à modifier, cas \"none\"\r\n \r\n if modif_type != \"none\":\r\n if random() < modif_prob: #Si le RNG decide qu'il faut modifier la version\r\n \r\n if rumorType == 0: #RUMOR IS 'BINARY'\r\n if modif_type==\"incremental\":\r\n newRumor = (rumor+choice([1, -1]))%(2**sim.binarySize)#Modulo val.max\r\n else:#modif_type=='bitflip'\r\n newRumor = rumor ^ (2**randrange(sim.binarySize))#xor avec puiss. de 2\r\n \r\n else: #RUMOR IS 'CLUEDO'\r\n modRumor = list(rumor) #Rumeur en modification\r\n if modif_type==\"incremental\":\r\n modRumor[0] += choice([-1, 1])\r\n nbValues = len(modRumor)\r\n for i in range(nbValues): #Va parcourir les 3 valeurs du cluedo\r\n if modRumor[i] >= sim.cluedoSize[i]: #Si on a dépassé dans une catég.\r\n modRumor[i] = 0 \r\n modRumor[(i+1)%nbValues] += 1\r\n elif modRumor[i] < 0: #Si on est sous zéro adns une catégorie\r\n modRumor[i] = sim.cluedoSize[i]-1\r\n modRumor[(i+1)%nbValues] -= 1\r\n else:#modif_type=='bitflip'\r\n indexChanged = randrange(len(modRumor))\r\n newValue = randrange(sim.cluedoSize[indexChanged])\r\n modRumor[indexChanged] = newValue\r\n newRumor = tuple(modRumor)\r\n \r\n return newRumor\r\n\r\n\r\ndef choose_rumor(oldRumor, hrdRumor, sim, update_rule, rumorType):\r\n \"\"\"Choisit la version de la rumeur a retenir en fonction de update_rule, du type de la rumeur\r\n rumorType, de la version de la rumeur connue precedemment et de la nouvelle version transmise,\r\n sim contenant les donnees sur les limites de tailles des differents types de rumeurs.\"\"\"\r\n newRumor = oldRumor #Cas 'stable' : nouvelle rumeur reste la même\r\n \r\n if update_rule=='rewrite':\r\n newRumor = hrdRumor #Idem pour rumeur binaire ou cluedo\r\n \r\n elif update_rule=='mixture':\r\n \r\n if rumorType == 0: #RUMOR IS 'BINARY'\r\n old_bits = bin(oldRumor)[2:].zfill(sim.binarySize) #Bits de old version\r\n hrd_bits = bin(hrdRumor)[2:].zfill(sim.binarySize) #Bits de heard version\r\n new_bits = [] #Bits de new version\r\n for i in range(sim.binarySize):\r\n if old_bits[i] == hrd_bits[i]: #Bits identiques\r\n new_bits.append(old_bits[i])\r\n else: \r\n if random() < sim.keepSelfBitsProb: #Bit diffèrent, garde ancien\r\n new_bits.append(old_bits[i])\r\n else: #Bits diffèrent, garde nouveau\r\n new_bits.append(hrd_bits[i])\r\n newRumor = int(''.join(new_bits), 2) #Assemble les bits\r\n \r\n else: #RUMOR IS 'CLUEDO'\r\n old_bits = list(oldRumor) #Bits de old version\r\n hrd_bits = list(hrdRumor) #Bits de heard version\r\n new_bits = [] #Bits de new version\r\n for i in range(len(old_bits)):\r\n if old_bits[i] == hrd_bits[i]: #Bits identiques\r\n new_bits.append(old_bits[i])\r\n else:\r\n if random() < sim.keepSelfBitsProb: #Bits diffèrent, garde ancien\r\n new_bits.append(old_bits[i])\r\n else:\r\n new_bits.append(hrd_bits[i]) #Bits diffèrent, garde nouveau\r\n newRumor = tuple(new_bits) #Assemble les bits\r\n \r\n return newRumor\r\n","sub_path":"rumorFunctions.py","file_name":"rumorFunctions.py","file_ext":"py","file_size_in_byte":14975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"579816937","text":"from __future__ import print_function\nfrom setuptools import setup, find_packages\nfrom fake_rpi.version import __version__ as VERSION\nfrom build_utils import BuildCommand\nfrom build_utils import PublishCommand\nfrom build_utils import BinaryDistribution\n\n\nPACKAGE_NAME = 'fake_rpi'\nBuildCommand.pkg = PACKAGE_NAME\nPublishCommand.pkg = PACKAGE_NAME\nPublishCommand.version = VERSION\n\n\nsetup(\n\tauthor='Kevin Walchko',\n\tauthor_email='walchko@users.noreply.github.com',\n\tname=PACKAGE_NAME,\n\tversion=VERSION,\n\tdescription='A bunch of fake interfaces for development when not using the RPi or unit testing',\n\tlong_description=open('readme.rst').read(),\n\turl='http://github.com/walchko/{}'.format(PACKAGE_NAME),\n\tclassifiers=[\n\t\t'Development Status :: 4 - Beta',\n\t\t'Intended Audience :: Developers',\n\t\t'License :: OSI Approved :: MIT License',\n\t\t'Operating System :: OS Independent',\n\t\t'Programming Language :: Python :: 2.7',\n\t\t'Programming Language :: Python :: 3.6',\n\t\t'Topic :: Software Development :: Libraries',\n\t\t'Topic :: Software Development :: Libraries :: Python Modules',\n\t\t'Topic :: Software Development :: Libraries :: Application Frameworks'\n\t],\n\tlicense='MIT',\n\tkeywords=['raspberry', 'pi', 'fake', 'fake_rpi', 'i2c', 'spi', 'gpio', 'serial'],\n\tpackages=find_packages('.'),\n\tinstall_requires=['build_utils', 'numpy'],\n\tcmdclass={\n\t\t'make': BuildCommand,\n\t\t'publish': PublishCommand\n\t}\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"310449457","text":"# Solution to Project Euler Problem #31: Coin sums\n# Copyright (c) MarcinSkrobczynski\n\nALL_COINS = [1, 2, 5, 10, 20, 50, 100, 200]\n\n\ndef main(n: int, coins: list) -> int:\n different_ways = [1] + [0] * n\n for coin in coins:\n for i in range(len(different_ways) - coin):\n different_ways[i + coin] += different_ways[i]\n return different_ways[-1]\n\n\ndef solution() -> int:\n return main(200, ALL_COINS)\n\n\nif __name__ == \"__main__\":\n print(f\"{main(5, ALL_COINS)} => {main(5, ALL_COINS) == 4}\")\n print(f\"{main(200, ALL_COINS)}\")\n","sub_path":"solutions/problem_0031.py","file_name":"problem_0031.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"186152056","text":"import asyncio\nimport json\nfrom typing import AsyncGenerator, Optional, Type\nfrom unittest.mock import Mock\n\nimport h2\nimport h11\nimport pytest\n\nfrom hypercorn.asyncio.h2 import H2Server\nfrom hypercorn.config import Config\nfrom hypercorn.typing import ASGIFramework\nfrom .helpers import MockTransport\nfrom ..helpers import ChunkedResponseFramework, EchoFramework, PushFramework\n\nBASIC_HEADERS = [(\":authority\", \"hypercorn\"), (\":scheme\", \"https\")]\nBASIC_DATA = \"index\"\nFLOW_WINDOW_SIZE = 1\n\n\nclass MockConnection:\n def __init__(\n self,\n event_loop: asyncio.AbstractEventLoop,\n *,\n config: Config = Config(),\n framework: Type[ASGIFramework] = EchoFramework,\n upgrade_request: Optional[h11.Request] = None,\n ) -> None:\n self.transport = MockTransport()\n self.server = H2Server( # type: ignore\n framework, event_loop, config, self.transport, upgrade_request=upgrade_request\n )\n self.connection = h2.connection.H2Connection()\n if upgrade_request is not None:\n self.connection.initiate_upgrade_connection()\n else:\n self.connection.initiate_connection()\n\n def send_request(self, headers: list, settings: dict) -> int:\n self.connection.update_settings(settings)\n self.server.data_received(self.connection.data_to_send())\n stream_id = self.connection.get_next_available_stream_id()\n self.connection.send_headers(stream_id, headers)\n self.server.data_received(self.connection.data_to_send())\n return stream_id\n\n async def send_data(self, stream_id: int, data: bytes) -> None:\n self.connection.send_data(stream_id, data)\n self.server.data_received(self.connection.data_to_send())\n await asyncio.sleep(0) # Yield to allow the server to process\n\n async def end_stream(self, stream_id: int) -> None:\n self.connection.end_stream(stream_id)\n self.server.data_received(self.connection.data_to_send())\n await asyncio.sleep(0) # Yield to allow the server to process\n\n def close(self) -> None:\n self.connection.close_connection()\n self.server.data_received(self.connection.data_to_send())\n\n async def get_events(self) -> AsyncGenerator[h2.events.Event, None]:\n while True:\n await self.transport.updated.wait()\n events = self.connection.receive_data(self.transport.data)\n self.transport.clear()\n for event in events:\n if isinstance(event, h2.events.ConnectionTerminated):\n self.transport.close()\n elif isinstance(event, h2.events.DataReceived):\n self.connection.acknowledge_received_data(\n event.flow_controlled_length, event.stream_id\n )\n self.server.data_received(self.connection.data_to_send())\n yield event\n if self.transport.closed.is_set():\n break\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"headers, body\",\n [\n (BASIC_HEADERS + [(\":method\", \"GET\"), (\":path\", \"/\")], \"\"),\n (\n BASIC_HEADERS\n + [\n (\":method\", \"POST\"),\n (\":path\", \"/\"),\n (\"content-length\", str(len(BASIC_DATA.encode()))),\n ],\n BASIC_DATA,\n ),\n ],\n)\nasync def test_request(headers: list, body: str, event_loop: asyncio.AbstractEventLoop) -> None:\n connection = MockConnection(event_loop)\n stream_id = connection.send_request(headers, {})\n if body != \"\":\n await connection.send_data(stream_id, body.encode())\n await connection.end_stream(stream_id)\n response_data = b\"\"\n async for event in connection.get_events():\n if isinstance(event, h2.events.ResponseReceived):\n assert (b\":status\", b\"200\") in event.headers\n assert (b\"server\", b\"hypercorn-h2\") in event.headers\n assert b\"date\" in (header[0] for header in event.headers)\n elif isinstance(event, h2.events.DataReceived):\n response_data += event.data\n elif isinstance(event, h2.events.StreamEnded):\n connection.close()\n data = json.loads(response_data.decode())\n assert data[\"request_body\"] == body # type: ignore\n\n\n@pytest.mark.asyncio\nasync def test_protocol_error(event_loop: asyncio.AbstractEventLoop) -> None:\n connection = MockConnection(event_loop)\n connection.server.data_received(b\"broken nonsense\\r\\n\\r\\n\")\n assert connection.transport.closed.is_set() # H2 just closes on error\n\n\n@pytest.mark.asyncio\nasync def test_pipelining(event_loop: asyncio.AbstractEventLoop) -> None:\n connection = MockConnection(event_loop)\n streams = [\n connection.send_request(BASIC_HEADERS + [(\":method\", \"GET\"), (\":path\", \"/1\")], {}),\n connection.send_request(BASIC_HEADERS + [(\":method\", \"GET\"), (\":path\", \"/1\")], {}),\n ]\n for stream_id in streams:\n await connection.end_stream(stream_id)\n responses = 0\n async for event in connection.get_events():\n if isinstance(event, h2.events.ResponseReceived):\n responses += 1\n elif isinstance(event, h2.events.StreamEnded) and responses == 2:\n connection.close()\n assert responses == len(streams)\n\n\n@pytest.mark.asyncio\nasync def test_server_sends_chunked(event_loop: asyncio.AbstractEventLoop) -> None:\n connection = MockConnection(event_loop, framework=ChunkedResponseFramework)\n stream_id = connection.send_request(BASIC_HEADERS + [(\":method\", \"GET\"), (\":path\", \"/\")], {})\n await connection.end_stream(stream_id)\n response_data = b\"\"\n async for event in connection.get_events():\n if isinstance(event, h2.events.DataReceived):\n response_data += event.data\n elif isinstance(event, h2.events.StreamEnded):\n connection.close()\n assert response_data == b\"chunked data\"\n\n\n@pytest.mark.asyncio\nasync def test_initial_keep_alive_timeout(event_loop: asyncio.AbstractEventLoop) -> None:\n config = Config()\n config.keep_alive_timeout = 0.01\n server = H2Server(EchoFramework, event_loop, config, Mock())\n await asyncio.sleep(2 * config.keep_alive_timeout)\n server.transport.close.assert_called() # type: ignore\n\n\n@pytest.mark.asyncio\nasync def test_post_response_keep_alive_timeout(event_loop: asyncio.AbstractEventLoop) -> None:\n config = Config()\n config.keep_alive_timeout = 0.01\n connection = MockConnection(event_loop, config=config)\n stream_id = connection.send_request(BASIC_HEADERS + [(\":method\", \"GET\"), (\":path\", \"/1\")], {})\n connection.server.pause_writing()\n await connection.end_stream(stream_id)\n await asyncio.sleep(2 * config.keep_alive_timeout)\n assert not connection.transport.closed.is_set()\n connection.server.resume_writing()\n await asyncio.sleep(2 * config.keep_alive_timeout)\n assert connection.transport.closed.is_set()\n events = [event async for event in connection.get_events()]\n assert isinstance(events[-1], h2.events.ConnectionTerminated)\n\n\n@pytest.mark.asyncio\nasync def test_h2server_upgrade(event_loop: asyncio.AbstractEventLoop) -> None:\n upgrade_request = h11.Request(method=\"GET\", target=\"/\", headers=[(\"Host\", \"hypercorn\")])\n connection = MockConnection(event_loop, upgrade_request=upgrade_request)\n response_data = b\"\"\n async for event in connection.get_events():\n if isinstance(event, h2.events.ResponseReceived):\n assert (b\":status\", b\"200\") in event.headers\n assert (b\"server\", b\"hypercorn-h2\") in event.headers\n assert b\"date\" in (header[0] for header in event.headers)\n elif isinstance(event, h2.events.DataReceived):\n response_data += event.data\n elif isinstance(event, h2.events.StreamEnded):\n connection.close()\n\n\n@pytest.mark.asyncio\nasync def test_h2_flow_control(event_loop: asyncio.AbstractEventLoop) -> None:\n connection = MockConnection(event_loop)\n stream_id = connection.send_request(\n BASIC_HEADERS + [(\":method\", \"GET\"), (\":path\", \"/\")],\n {h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: FLOW_WINDOW_SIZE},\n )\n await connection.end_stream(stream_id)\n async for event in connection.get_events():\n if isinstance(event, h2.events.DataReceived):\n assert len(event.data) <= FLOW_WINDOW_SIZE\n elif isinstance(event, h2.events.StreamEnded):\n connection.close()\n\n\n@pytest.mark.asyncio\nasync def test_h2_push(event_loop: asyncio.AbstractEventLoop) -> None:\n connection = MockConnection(event_loop, framework=PushFramework)\n stream_id = connection.send_request(BASIC_HEADERS + [(\":method\", \"GET\"), (\":path\", \"/\")], {})\n await connection.end_stream(stream_id)\n push_received = False\n streams_received = 0\n async for event in connection.get_events():\n if isinstance(event, h2.events.PushedStreamReceived):\n assert (b\":path\", b\"/\") in event.headers\n assert (b\":method\", b\"GET\") in event.headers\n assert (b\":scheme\", b\"http\") in event.headers\n assert (b\":authority\", b\"hypercorn\") in event.headers\n push_received = True\n elif isinstance(event, h2.events.StreamEnded):\n streams_received += 1\n if streams_received == 2:\n connection.close()\n assert push_received\n","sub_path":"tests/asyncio/test_h2.py","file_name":"test_h2.py","file_ext":"py","file_size_in_byte":9390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"573303312","text":"#!/usr/bin/env python3\n# coding=utf-8\n\nimport datetime\nimport itertools\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport tempfile\nimport time\nfrom collections import defaultdict\nfrom pprint import pformat\nfrom typing import TextIO, Optional, Dict, Sequence\n\nimport click\nimport requests\n\nfrom lib.amazon import target_group_arn_for, get_autoscaling_group, get_releases, find_release, get_current_key, \\\n set_current_key, as_client, release_for, find_latest_release, get_all_current, remove_release, get_events_file, \\\n save_event_file, get_short_link, put_short_link, delete_short_link, list_short_links, delete_s3_links, \\\n get_autoscaling_groups_for, download_release_file, download_release_fileobj, log_new_build, list_all_build_logs, \\\n list_period_build_logs, get_ssm_param\nfrom lib.cdn import DeploymentJob\nfrom lib.env import Environment, Config\nfrom lib.instance import ConanInstance, AdminInstance, BuilderInstance, Instance, print_instances\nfrom lib.releases import Version\nfrom lib.ssh import run_remote_shell, exec_remote, exec_remote_all, exec_remote_to_stdout\n\nlogger = logging.getLogger('ce')\n\nRELEASE_FORMAT = '{: <5} {: <10} {: <10} {: <10} {: <14}'\nADS_FORMAT = '{: <5} {: <10} {: <20}'\nDECORATION_FORMAT = '{: <10} {: <15} {: <30} {: <50}'\n\n\n@click.group()\n@click.option(\"--env\", type=click.Choice([env.value for env in Environment]),\n default=Environment.STAGING.value, metavar='ENV',\n help='Select environment ENV')\n@click.option(\"--mosh/--no-mosh\", help='Use mosh to connect to hosts')\n@click.option(\"--debug/--no-debug\", help='Turn on debugging')\n@click.pass_context\ndef cli(ctx: click.Context, env: str, mosh: bool, debug: bool):\n ctx.obj = Config(env=Environment(env), use_mosh=mosh)\n if debug:\n logging.basicConfig(level=logging.DEBUG)\n else:\n logging.basicConfig(level=logging.INFO)\n logging.getLogger('boto3').setLevel(logging.WARNING)\n logging.getLogger('botocore').setLevel(logging.WARNING)\n\n\ndef pick_instance(cfg: Config):\n elb_instances = Instance.elb_instances(target_group_arn_for(cfg))\n if len(elb_instances) == 1:\n return elb_instances[0]\n while True:\n print_instances(elb_instances, number=True)\n inst = input('Which instance? ')\n try:\n return elb_instances[int(inst)]\n except (ValueError, IndexError):\n pass\n\n\ndef pick_instances(cfg: Config):\n return Instance.elb_instances(target_group_arn_for(cfg))\n\n\ndef sizeof_fmt(num, suffix='B'):\n for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:\n if abs(num) < 1024.0:\n return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f%s%s\" % (num, 'Yi', suffix)\n\n\ndef describe_current_release(cfg: Config):\n current = get_current_key(cfg)\n if not current:\n return \"none\"\n r = release_for(get_releases(), current)\n if r:\n return str(r)\n else:\n \"non-standard release with s3 key '{}'\".format(current)\n\n\ndef wait_for_autoscale_state(instance, state):\n logger.info(\"Waiting for %s to reach autoscale lifecycle '%s'...\", instance, state)\n while True:\n autoscale = instance.describe_autoscale()\n if not autoscale:\n logger.error(\"Instance is not longer in an ASG: stopping\")\n return\n cur_state = autoscale['LifecycleState']\n logger.debug(\"State is %s\", cur_state)\n if cur_state == state:\n logger.info(\"...done\")\n return\n time.sleep(5)\n\n\ndef get_events(cfg: Config):\n events = json.loads(get_events_file(cfg))\n if 'ads' not in events:\n events['ads'] = []\n if 'decorations' not in events:\n events['decorations'] = []\n if 'motd' not in events:\n events['motd'] = ''\n return events\n\n\ndef save_events(cfg: Config, events):\n save_event_file(cfg, json.dumps(events))\n\n\ndef wait_for_elb_state(instance, state):\n logger.info(\"Waiting for %s to reach ELB state '%s'...\", instance, state)\n while True:\n instance.update()\n instance_state = instance.instance.state['Name']\n if instance_state != 'running':\n raise RuntimeError('Instance no longer running (state {})'.format(instance_state))\n logger.debug(\"State is %s\", instance.elb_health)\n if instance.elb_health == state:\n logger.info(\"...done\")\n return\n time.sleep(5)\n\n\ndef are_you_sure(name: str, cfg: Config) -> bool:\n while True:\n typed = input(\n f'Confirm operation: \"{name}\" in env {cfg.env.value}\\nType the name of the environment to proceed: ')\n if typed == cfg.env.value:\n return True\n\n\ndef confirm_branch(release):\n branch = release.branch\n while True:\n typed = input('Confirm build branch \"{}\"\\nType the name of the branch: '.format(branch))\n if typed == branch:\n return True\n\n\ndef confirm_action(description):\n typed = input('{}: [Y/N]\\n'.format(description))\n return typed.upper() == 'Y'\n\n\ndef is_everything_awesome(instance):\n try:\n response = exec_remote(instance, ['curl', '-s', '--max-time', '2', 'http://127.0.0.1/healthcheck'])\n return response.strip() == \"Everything is awesome\"\n except subprocess.CalledProcessError:\n return False\n\n\ndef wait_for_healthok(instance):\n logger.info(\"Waiting for instance to be Online %s\", instance)\n sys.stdout.write('Waiting')\n while not is_everything_awesome(instance):\n sys.stdout.write('.')\n # Flush stdout so tmux updates\n sys.stdout.flush()\n time.sleep(10)\n print(\"Ok, Everything is awesome!\")\n\n\ndef restart_one_instance(as_group_name: str, instance: Instance, modified_groups: Dict[str, int]):\n instance_id = instance.instance.instance_id\n logger.info(\"Enabling instance protection for %s\", instance)\n as_client.set_instance_protection(AutoScalingGroupName=as_group_name,\n InstanceIds=[instance_id],\n ProtectedFromScaleIn=True)\n as_group = get_autoscaling_group(as_group_name)\n adjustment_required = as_group['DesiredCapacity'] == as_group['MinSize']\n if adjustment_required:\n logger.info(\"Group '%s' needs to be adjusted to keep enough nodes\", as_group_name)\n modified_groups[as_group['AutoScalingGroupName']] = as_group['DesiredCapacity']\n logger.info(\"Putting %s into standby\", instance)\n as_client.enter_standby(\n InstanceIds=[instance_id],\n AutoScalingGroupName=as_group_name,\n ShouldDecrementDesiredCapacity=not adjustment_required)\n wait_for_autoscale_state(instance, 'Standby')\n logger.info(\"Restarting service on %s\", instance)\n restart_response = exec_remote(instance, ['sudo', 'systemctl', 'restart', 'compiler-explorer'])\n if restart_response:\n logger.warning(\"Restart gave some output: %s\", restart_response)\n wait_for_healthok(instance)\n logger.info(\"Moving %s out of standby\", instance)\n as_client.exit_standby(\n InstanceIds=[instance_id],\n AutoScalingGroupName=as_group_name)\n wait_for_autoscale_state(instance, 'InService')\n wait_for_elb_state(instance, 'healthy')\n logger.info(\"Disabling instance protection for %s\", instance)\n as_client.set_instance_protection(AutoScalingGroupName=as_group_name,\n InstanceIds=[instance_id],\n ProtectedFromScaleIn=False)\n logger.info(\"Instance restarted ok\")\n\n\n@cli.command()\n@click.pass_obj\ndef admin(cfg: Config):\n \"\"\"Log in to the administrative instance.\"\"\"\n run_remote_shell(cfg, AdminInstance.instance())\n\n\n@cli.group()\ndef conan():\n \"\"\"Conan instance management commands.\"\"\"\n\n\n@conan.command(name='login')\n@click.pass_obj\ndef conan_login(cfg: Config):\n \"\"\"Log in to the conan instance.\"\"\"\n instance = ConanInstance.instance()\n run_remote_shell(cfg, instance)\n\n\n@conan.command(name='exec')\n@click.argument('remote_cmd', required=True, nargs=-1)\ndef conan_exec(remote_cmd: Sequence[str]):\n \"\"\"Execute the REMOTE_CMD on the conan instance.\"\"\"\n instance = ConanInstance.instance()\n exec_remote_to_stdout(instance, remote_cmd)\n\n\n@conan.command(name='restart')\ndef conan_restart():\n \"\"\"Restart the conan instance.\"\"\"\n instance = ConanInstance.instance()\n exec_remote(instance, [\"sudo\", \"service\", \"ce-conan\", \"restart\"])\n\n\n@conan.command(name='reloadwww')\ndef conan_reloadwww():\n \"\"\"Reload the conan web.\"\"\"\n instance = ConanInstance.instance()\n exec_remote(instance, [\"sudo\", \"git\", \"-C\", \"/home/ubuntu/ceconan/conanproxy\", \"pull\"])\n\n\n@cli.group()\ndef builder():\n \"\"\"Builder machine manipulation commands.\"\"\"\n\n\n@builder.command(name='login')\n@click.pass_obj\ndef builder_login(cfg: Config):\n \"\"\"Log in to the builder machine.\"\"\"\n instance = BuilderInstance.instance()\n run_remote_shell(cfg, instance)\n\n\n@builder.command(name='exec')\n@click.argument('remote_cmd', required=True, nargs=-1)\ndef builder_exec(remote_cmd: Sequence[str]):\n \"\"\"Execute REMOTE_CMD on the builder instance.\"\"\"\n instance = BuilderInstance.instance()\n exec_remote_to_stdout(instance, remote_cmd)\n\n\n@builder.command(name='start')\ndef builder_start():\n \"\"\"Start the builder instance.\"\"\"\n instance = BuilderInstance.instance()\n if instance.status() == 'stopped':\n print(\"Starting builder instance...\")\n instance.start()\n for _ in range(60):\n if instance.status() == 'running':\n break\n time.sleep(1)\n else:\n raise RuntimeError(\"Unable to start instance, still in state: {}\".format(instance.status()))\n for _ in range(60):\n try:\n r = exec_remote(instance, [\"echo\", \"hello\"])\n if r.strip() == \"hello\":\n break\n except subprocess.CalledProcessError as e:\n print(\"Still waiting for SSH: got: {}\".format(e))\n time.sleep(1)\n else:\n raise RuntimeError(\"Unable to get SSH access\")\n res = exec_remote(instance,\n [\"bash\", \"-c\", \"cd infra && git pull && sudo ./setup-builder-startup.sh\"])\n print(res)\n print(\"Builder started OK\")\n\n\n@builder.command(name='stop')\ndef builder_stop():\n \"\"\"Stop the builder instance.\"\"\"\n BuilderInstance.instance().stop()\n\n\n@builder.command(name='status')\ndef builder_status():\n \"\"\"Get the builder status (running or otherwise).\"\"\"\n print(\"Builder status: {}\".format(BuilderInstance.instance().status()))\n\n\n@cli.group()\ndef instances():\n \"\"\"Instance management commands.\"\"\"\n\n\n@instances.command(name='exec_all')\n@click.pass_obj\n@click.argument('remote_cmd', required=True, nargs=-1)\ndef instances_exec_all(cfg: Config, remote_cmd: Sequence[str]):\n \"\"\"Execute REMOTE_CMD on all the instances.\"\"\"\n if not are_you_sure(f'exec command {remote_cmd} in all instances', cfg):\n return\n\n print(\"Running '{}' on all instances\".format(' '.join(remote_cmd)))\n exec_remote_all(pick_instances(cfg), remote_cmd)\n\n\n@instances.command(name='login')\n@click.pass_obj\ndef instances_login(cfg: Config):\n \"\"\"Log in to one of the instances.\"\"\"\n instance = pick_instance(cfg)\n run_remote_shell(cfg, instance)\n\n\n@instances.command(name='restart_one')\n@click.pass_obj\ndef instances_restart_one(cfg: Config):\n \"\"\"Restart one of the instances.\"\"\"\n instance = pick_instance(cfg)\n as_instance_status = instance.describe_autoscale()\n if not as_instance_status:\n logger.error(\"Failed restarting %s - was not in ASG\", instance)\n return\n as_group_name = as_instance_status['AutoScalingGroupName']\n modified_groups: Dict[str, int] = {}\n try:\n restart_one_instance(as_group_name, instance, modified_groups)\n except RuntimeError as e:\n logger.error(\"Failed restarting %s - skipping: %s\", instance, e)\n\n\n@instances.command(name='start')\n@click.pass_obj\ndef instances_start(cfg: Config):\n \"\"\"Start up the instances.\"\"\"\n print(\"Starting version %s\", describe_current_release(cfg))\n exec_remote_all(pick_instances(cfg), ['sudo', 'systemctl', 'start', 'compiler-explorer'])\n\n\n@instances.command(name='stop')\n@click.pass_obj\ndef instances_stop(cfg: Config):\n \"\"\"Stop the instances.\"\"\"\n if cfg.env == Environment.PROD:\n print('Operation aborted. This would bring down the site')\n print('If you know what you are doing, edit the code in bin/lib/ce.py, function instances_stop_cmd')\n elif are_you_sure('stop all instances', cfg):\n exec_remote_all(pick_instances(cfg), ['sudo', 'systemctl', 'stop', 'compiler-explorer'])\n\n\n@instances.command(name='restart')\n@click.option('--motd', type=str, default='Site is being updated',\n help='Set the message of the day used during update', show_default=True)\n@click.pass_obj\ndef instances_restart(cfg: Config, motd: str):\n \"\"\"Restart the instances, picking up new code.\"\"\"\n if not are_you_sure('restart all instances with version {}'.format(describe_current_release(cfg)), cfg):\n return\n # Store old motd\n begin_time = datetime.datetime.now()\n events = get_events(cfg)\n old_motd = events['motd']\n events['motd'] = old_motd if motd == '' else motd\n save_events(cfg, events)\n modified_groups: Dict[str, int] = {}\n failed = False\n to_restart = pick_instances(cfg)\n\n for index, instance in enumerate(to_restart):\n logger.info(\"Restarting %s (%d of %d)...\", instance, index + 1, len(to_restart))\n as_instance_status = instance.describe_autoscale()\n if not as_instance_status:\n logger.warning(\"Skipping %s as it is no longer in the ASG\", instance)\n continue\n as_group_name = as_instance_status['AutoScalingGroupName']\n if as_instance_status['LifecycleState'] != 'InService':\n logger.warning(\"Skipping %s as it is not InService (%s)\", instance, as_instance_status)\n continue\n\n try:\n restart_one_instance(as_group_name, instance, modified_groups)\n except RuntimeError as e:\n logger.error(\"Failed restarting %s - skipping: %s\", instance, e)\n failed = True\n # TODO, what here?\n\n for group, desired in iter(modified_groups.items()):\n logger.info(\"Putting desired instances for %s back to %d\", group, desired)\n as_client.update_auto_scaling_group(AutoScalingGroupName=group, DesiredCapacity=desired)\n # Events might have changed, re-fetch\n events = get_events(cfg)\n events['motd'] = old_motd\n save_events(cfg, events)\n end_time = datetime.datetime.now()\n delta_time = end_time - begin_time\n print(f'Instances restarted in {delta_time.total_seconds()} seconds')\n sys.exit(1 if failed else 0)\n\n\n@instances.command(name='status')\n@click.pass_obj\ndef instances_status(cfg: Config):\n \"\"\"Get the status of the instances.\"\"\"\n print_instances(Instance.elb_instances(target_group_arn_for(cfg)), number=False)\n\n\n@cli.group()\ndef builds():\n \"\"\"Build manipulation commands.\"\"\"\n\n\n@builds.command(name=\"current\")\n@click.pass_obj\ndef builds_current(cfg: Config):\n \"\"\"Print the current release.\"\"\"\n print(describe_current_release(cfg))\n\n\ndef old_deploy_staticfiles(branch, versionfile):\n print(\"Deploying static files\")\n downloadfile = versionfile\n filename = 'deploy.tar.xz'\n remotefile = branch + '/' + downloadfile\n download_release_file(remotefile[1:], filename)\n os.mkdir('deploy')\n subprocess.call(['tar', '-C', 'deploy', '-Jxf', filename])\n os.remove(filename)\n subprocess.call(['aws', 's3', 'sync', 'deploy/out/dist/dist', 's3://compiler-explorer/dist/cdn'])\n subprocess.call(['rm', '-Rf', 'deploy'])\n\n\ndef deploy_staticfiles(release) -> bool:\n print(\"Deploying static files to cdn\")\n cc = f'public, max-age={int(datetime.timedelta(days=365).total_seconds())}'\n\n with tempfile.NamedTemporaryFile(suffix=os.path.basename(release.static_key)) as f:\n download_release_fileobj(release.static_key, f)\n with DeploymentJob(f.name, 'ce-cdn.net', version=release.version, cache_control=cc) as job:\n return job.run()\n\n\n@builds.command(name='set_current')\n@click.pass_obj\n@click.option('--branch', help='if version == latest, branch to get latest version from')\n@click.option('--raw/--no-raw', help='Set a raw path for a version')\n@click.argument('version')\ndef builds_set_current(cfg: Config, branch: Optional[str], version: str, raw: bool):\n \"\"\"Set the current version to VERSION for this environment.\n\n If VERSION is \"latest\" then the latest version (optionally filtered by --branch), is set.\n \"\"\"\n to_set = None\n release = None\n if raw:\n to_set = version\n else:\n setting_latest = version == 'latest'\n release = find_latest_release(branch) if setting_latest else find_release(\n Version.from_string(version))\n if not release:\n print(\"Unable to find version \" + version)\n if setting_latest and branch != '':\n print('Branch {} has no available versions (Bad branch/No image yet built)'.format(branch))\n elif are_you_sure('change current version to {}'.format(release.key), cfg) and confirm_branch(release):\n print(f'Found release {release}')\n to_set = release.key\n if to_set is not None:\n log_new_build(cfg, to_set)\n if release and release.static_key:\n if not deploy_staticfiles(release):\n print(\"...aborted due to deployment failure!\")\n sys.exit(1)\n else:\n old_deploy_staticfiles(branch, to_set)\n set_current_key(cfg, to_set)\n if release:\n print(\"Marking as a release in sentry...\")\n token = get_ssm_param(\"/compiler-explorer/sentryAuthToken\")\n result = requests.post(\n f\"https://sentry.io/api/0/organizations/compiler-explorer/releases/{release.version}/deploys/\",\n data=dict(environment=cfg.env.value),\n headers=dict(Authorization=f'Bearer {token}'))\n if not result.ok:\n raise RuntimeError(f\"Failed to send to sentry: {result} {result.content.decode('utf-8')}\")\n print(\"...done\", json.loads(result.content.decode()))\n\n\n@builds.command(name=\"rm_old\")\n@click.option('--dry-run/--no-dry-run', help='dry run only')\n@click.argument('max_age', type=int)\ndef builds_rm_old(dry_run: bool, max_age: int):\n \"\"\"Remove all but the last MAX_AGE builds.\"\"\"\n current = get_all_current()\n max_builds: Dict[str, int] = defaultdict(int)\n for release in get_releases():\n max_builds[release.version.source] = max(release.version.number, max_builds[release.version.source])\n for release in get_releases():\n if release.key in current:\n print(\"Skipping {} as it is a current version\".format(release))\n else:\n age = max_builds[release.version.source] - release.version.number\n if age > max_age:\n if dry_run:\n print(\"Would remove build {}\".format(release))\n else:\n print(\"Removing build {}\".format(release))\n remove_release(release)\n else:\n print(\"Keeping build {}\".format(release))\n\n\n@builds.command(name='list')\n@click.pass_obj\n@click.option('-b', '--branch', type=str, help='show only BRANCH (may be specified more than once)',\n metavar='BRANCH', multiple=True)\ndef builds_list(cfg: Config, branch: Sequence[str]):\n \"\"\"List available builds.\n\n The --> indicates the build currently deployed in this environment.\"\"\"\n current = get_current_key(cfg)\n releases = get_releases()\n filter_branches = set(branch)\n print(RELEASE_FORMAT.format('Live', 'Branch', 'Version', 'Size', 'Hash'))\n for _, releases in itertools.groupby(releases, lambda r: r.branch):\n for release in releases:\n if len(filter_branches) == 0 or release.branch in filter_branches:\n print(\n RELEASE_FORMAT.format(\n ' -->' if release.key == current else '',\n release.branch, str(release.version), sizeof_fmt(release.size), str(release.hash))\n )\n\n\n@builds.command(name='history')\n@click.option('--from', 'from_time')\n@click.option('--until', 'until_time')\n@click.pass_obj\ndef builds_history(cfg: Config, from_time: Optional[str], until_time: Optional[str]):\n \"\"\"Show the history of current versions for this environment.\"\"\"\n if from_time is None and until_time is None:\n if confirm_action(\n 'Do you want list all builds for {}? It might be an expensive operation:'.format(cfg.env.value)):\n list_all_build_logs(cfg)\n else:\n list_period_build_logs(cfg, from_time, until_time)\n\n\n@cli.group()\ndef ads():\n \"\"\"Community advert manipulation features.\"\"\"\n\n\n@ads.command(name='list')\n@click.pass_obj\ndef ads_list(cfg: Config):\n \"\"\"List the existing community adverts.\"\"\"\n events = get_events(cfg)\n print(ADS_FORMAT.format('ID', 'Filters', 'HTML'))\n for ad in events['ads']:\n print(ADS_FORMAT.format(ad['id'], str(ad['filter']), ad['html']))\n\n\n@ads.command(name='add')\n@click.pass_obj\n@click.option(\"--filter\", 'lang_filter', help='Filter to these languages (default all)', multiple=True)\n@click.argument(\"html\")\ndef ads_add(cfg: Config, lang_filter: Sequence[str], html: str):\n \"\"\"Add a community advert with HTML.\"\"\"\n events = get_events(cfg)\n new_ad = {\n 'html': html,\n 'filter': lang_filter,\n 'id': max([x['id'] for x in events['ads']]) + 1 if len(events['ads']) > 0 else 0\n }\n if are_you_sure('add ad: {}'.format(ADS_FORMAT.format(new_ad['id'], str(new_ad['filter']), new_ad['html'])), cfg):\n events['ads'].append(new_ad)\n save_event_file(cfg, json.dumps(events))\n\n\n@ads.command(name='remove')\n@click.pass_obj\n@click.option('--force/--no-force', help='Force remove (no confirmation)')\n@click.argument('ad_id', type=int)\ndef ads_remove(cfg: Config, ad_id: int, force: bool):\n \"\"\"Remove community ad number AD_ID.\"\"\"\n events = get_events(cfg)\n for i, ad in enumerate(events['ads']):\n if ad['id'] == ad_id:\n if force or \\\n are_you_sure('remove ad: {}'.format(ADS_FORMAT.format(ad['id'], str(ad['filter']), ad['html'])),\n cfg):\n del events['ads'][i]\n save_event_file(cfg, json.dumps(events))\n break\n\n\n@ads.command(name='clear')\n@click.pass_obj\ndef ads_clear(cfg: Config):\n \"\"\"Clear all community ads.\"\"\"\n events = get_events(cfg)\n if are_you_sure('clear all ads (count: {})'.format(len(events['ads'])), cfg):\n events['ads'] = []\n save_event_file(cfg, json.dumps(events))\n\n\n@ads.command(name='edit')\n@click.option(\"--filter\", 'lang_filter', help='Change filters to these languages', multiple=True)\n@click.option(\"--html\", help='Change html to HTML')\n@click.argument('ad_id', type=int)\n@click.pass_obj\ndef ads_edit(cfg: Config, ad_id: int, html: str, lang_filter: Sequence[str]):\n \"\"\"Edit community ad AD_ID.\"\"\"\n events = get_events(cfg)\n for i, ad in enumerate(events['ads']):\n if ad['id'] == ad_id:\n new_ad = {\n 'id': ad['id'],\n 'filter': lang_filter or ad['filter'],\n 'html': html or ad['html']\n }\n print('{}\\n{}\\n{}'.format(ADS_FORMAT.format('Event', 'Filter(s)', 'HTML'),\n ADS_FORMAT.format('TO', str(new_ad['filter']), new_ad['html'])))\n if are_you_sure('edit ad id: {}'.format(ad['id']), cfg):\n events['ads'][i] = new_ad\n save_event_file(cfg, json.dumps(events))\n break\n\n\n@cli.group()\ndef decorations():\n \"\"\"Manage the decorations (ok, Easter Eggs).\"\"\"\n\n\n@decorations.command(name='list')\n@click.pass_obj\ndef decorations_list(cfg: Config):\n events = get_events(cfg)\n print(DECORATION_FORMAT.format('Name', 'Filters', 'Regex', 'Decoration'))\n for dec in events['decorations']:\n print(DECORATION_FORMAT.format(dec['name'], str(dec['filter']), dec['regex'], json.dumps(dec['decoration'])))\n\n\ndef check_dec_args(regex, decoration):\n try:\n re.compile(regex)\n except re.error as re_err:\n raise RuntimeError(f\"Unable to validate regex '{regex}' : {re_err}\") from re_err\n try:\n decoration = json.loads(decoration)\n except json.decoder.JSONDecodeError as json_err:\n raise RuntimeError(f\"Unable to parse decoration '{decoration}' : {json_err}\") from json_err\n return regex, decoration\n\n\n@decorations.command(name='add')\n@click.pass_obj\n@click.option('--filter', 'lang_filter', help='filter for this language', multiple=True)\n@click.argument('name')\n@click.argument('regex')\n@click.argument('decoration')\ndef decorations_add(cfg: Config, lang_filter: Sequence[str], name: str, regex: str, decoration: str):\n \"\"\"\n Add a decoration called NAME matching REGEX resulting in json DECORATION.\n \"\"\"\n events = get_events(cfg)\n if name in [d['name'] for d in events['decorations']]:\n raise RuntimeError(f'Duplicate decoration name {name}')\n regex, decoration = check_dec_args(regex, decoration)\n\n new_decoration = {\n 'name': name,\n 'filter': lang_filter,\n 'regex': regex,\n 'decoration': decoration\n }\n if are_you_sure('add decoration: {}'.format(\n DECORATION_FORMAT.format(new_decoration['name'], str(new_decoration['filter']), new_decoration['regex'],\n json.dumps(new_decoration['decoration']))), cfg):\n events['decorations'].append(new_decoration)\n save_event_file(cfg, json.dumps(events))\n\n\n@decorations.command(name='remove')\n@click.pass_obj\n@click.option(\"--force/--no-force\", help=\"force without confirmation\")\n@click.argument('name')\ndef decorations_remove(cfg: Config, name: str, force: bool):\n \"\"\"Remove a decoration.\"\"\"\n events = get_events(cfg)\n for i, dec in enumerate(events['decorations']):\n if dec['name'] == name:\n if force or \\\n are_you_sure('remove decoration: {}'.format(\n DECORATION_FORMAT.format(dec['name'], str(dec['filter']), dec['regex'],\n json.dumps(dec['decoration']))), cfg):\n del events['decorations'][i]\n save_event_file(cfg, json.dumps(events))\n break\n\n\n@decorations.command(name='clear')\n@click.pass_obj\ndef decorations_clear(cfg: Config):\n \"\"\"Clear all decorations.\"\"\"\n events = get_events(cfg)\n if are_you_sure('clear all decorations (count: {})'.format(len(events['decorations'])), cfg):\n events['decorations'] = []\n save_event_file(cfg, json.dumps(events))\n\n\n@decorations.command(name='edit')\n@click.pass_obj\n@click.option('--filter', 'lang_filter', help='filter for this language', multiple=True)\n@click.option('--regex', help='match REGEX')\n@click.option('--decoration', help='evaluate to DECORATION (json syntax)')\n@click.argument('name')\ndef decorations_edit(cfg: Config, lang_filter: Sequence[str], name: str, regex: str, decoration: str):\n \"\"\"Edit existing decoration NAME.\"\"\"\n events = get_events(cfg)\n\n for i, dec in enumerate(events['decorations']):\n if dec['name'] == name:\n regex, decoration = check_dec_args(regex or dec['regex'],\n decoration or json.dumps(dec['decoration']))\n new_dec = {\n 'name': dec['name'],\n 'filter': lang_filter or dec['filter'],\n 'regex': regex,\n 'decoration': decoration\n }\n print('{}\\n{}\\n{}'.format(DECORATION_FORMAT.format('Name', 'Filters', 'Regex', 'Decoration'),\n DECORATION_FORMAT.format('TO', str(new_dec['filter']), new_dec['regex'],\n json.dumps(new_dec['decoration']))))\n if are_you_sure('edit decoration: {}'.format(dec['name']), cfg):\n events['decoration'][i] = new_dec\n save_event_file(cfg, json.dumps(events))\n break\n\n\n@cli.group(name='motd')\ndef motd_group():\n \"\"\"Message of the day manipulation functions.\"\"\"\n\n\n@motd_group.command(name='show')\n@click.pass_obj\ndef motd_show(cfg: Config):\n \"\"\"Prints the message of the day.\"\"\"\n events = get_events(cfg)\n print('Current motd: \"{}\"'.format(events['motd']))\n\n\n@motd_group.command(name='update')\n@click.argument('message', type=str)\n@click.pass_obj\ndef motd_update(cfg: Config, message: str):\n \"\"\"Updates the message of the day to MESSAGE.\"\"\"\n events = get_events(cfg)\n if are_you_sure('update motd from: {} to: {}'.format(events['motd'], message), cfg):\n events['motd'] = message\n save_event_file(cfg, json.dumps(events))\n\n\n@motd_group.command(name='clear')\n@click.pass_obj\ndef motd_clear(cfg: Config):\n \"\"\"Clears the message of the day.\"\"\"\n events = get_events(cfg)\n if are_you_sure('clear current motd: {}'.format(events['motd']), cfg):\n events['motd'] = ''\n save_events(cfg, events)\n\n\n@cli.group(name='events')\ndef events_group():\n \"\"\"Low-level manipulation of ads and events.\"\"\"\n\n\n@events_group.command(name='to_raw')\n@click.pass_obj\ndef events_to_raw(cfg: Config):\n \"\"\"Dumps the events file as raw JSON.\"\"\"\n print(get_events_file(cfg))\n\n\n@events_group.command(name='from_raw')\n@click.pass_obj\ndef events_from_raw(cfg: Config):\n \"\"\"Reloads the events file as raw JSON from console input.\"\"\"\n raw = input()\n save_event_file(cfg, json.dumps(json.loads(raw)))\n\n\n@events_group.command(name='to_file')\n@click.argument(\"file\", type=click.File(mode='w'))\n@click.pass_obj\ndef events_to_file(cfg: Config, file: TextIO):\n \"\"\"Saves the raw events file as FILE.\"\"\"\n file.write(get_events_file(cfg))\n\n\n@events_group.command(name='from_file')\n@click.argument(\"file\", type=click.File(mode='r'))\n@click.pass_obj\ndef events_from_file(cfg: Config, file: TextIO):\n \"\"\"Reads FILE and replaces the events file with its contents.\"\"\"\n new_contents = json.loads(file.read())\n if are_you_sure(f'load events from file {file.name}', cfg):\n save_event_file(cfg, new_contents)\n\n\n@cli.group()\ndef link():\n \"\"\"Link manipulation commands.\"\"\"\n\n\n@link.command(name='name')\n@click.pass_obj\n@click.argument(\"link_from\")\n@click.argument(\"link_to\")\ndef links_name(cfg: Config, link_from: str, link_to: str):\n \"\"\"Give link LINK_FROM a new name LINK_TO.\"\"\"\n if len(link_from) < 6:\n raise RuntimeError('from length must be at least 6')\n if len(link_to) < 6:\n raise RuntimeError('to length must be at least 6')\n base_link = get_short_link(link_from)\n if not base_link:\n raise RuntimeError('Couldn\\'t find base link {}'.format(link_from))\n base_link['prefix']['S'] = link_to[0:6]\n base_link['unique_subhash']['S'] = link_to\n base_link['stats']['M']['clicks']['N'] = '0'\n base_link['creation_ip']['S'] = '0.0.0.0'\n # It's us, so we don't care about \"anonymizing\" the time\n base_link['creation_date']['S'] = datetime.datetime.utcnow().isoformat()\n title = input('Link title: ')\n author = input('Author(s): ')\n if len(author) == 0:\n # We explicitly ignore author = . in the site code\n author = '.'\n project = input('Project: ')\n description = input('Description: ')\n base_link['named_metadata'] = {'M': {\n 'title': {'S': title},\n 'author': {'S': author},\n 'project': {'S': project},\n 'description': {'S': description}\n }}\n print('New link: {}'.format(pformat(base_link)))\n if are_you_sure('create new link named {}'.format(link_to), cfg):\n put_short_link(base_link)\n\n\n@link.command(name='update')\n@click.pass_obj\n@click.argument(\"link_from\")\n@click.argument(\"link_to\")\ndef links_update(cfg: Config, link_from: str, link_to: str):\n \"\"\"Update a link; point LINK_FROM to existing LINK_TO.\"\"\"\n if len(link_from) < 6:\n raise RuntimeError('from length must be at least 6')\n if len(link_to) < 6:\n raise RuntimeError('to length must be at least 6')\n base_link = get_short_link(link_from)\n if not base_link:\n raise RuntimeError('Couldn\\'t find base link {}'.format(link_from))\n link_to_update = get_short_link(link_to)\n if not link_to_update:\n raise RuntimeError('Couldn\\'t find existing short link {}'.format(link_to))\n link_to_update['full_hash'] = base_link['full_hash']\n print('New link: {}'.format(pformat(link_to_update)))\n if are_you_sure('update link named {}'.format(link_to), cfg):\n put_short_link(link_to_update)\n\n\n@link.command(name='maintenance')\n@click.option(\"--dry-run/--no-dry-run\", help=\"dry run only\")\n@click.pass_obj\ndef links_maintenance(cfg: Config, dry_run: bool):\n s3links, dblinks = list_short_links()\n s3keys_set = set()\n dbkeys_set = set()\n dbhashes_set = set()\n s3dirty_set = set()\n dbdirty_set = set()\n for page in s3links:\n for state in page['Contents']:\n if len(state['Key'][6:]) > 1:\n s3keys_set.add(state['Key'][6:])\n for page in dblinks:\n for item in page['Items']:\n unique_subhash = item['unique_subhash']['S']\n full_hash = item['full_hash']['S']\n dbkeys_set.add((unique_subhash, full_hash))\n dbhashes_set.add(full_hash)\n for dbkey in dbkeys_set:\n if dbkey[1] not in s3keys_set:\n dbdirty_set.add(dbkey)\n for s3key in s3keys_set:\n if s3key not in dbhashes_set:\n s3dirty_set.add(s3key)\n\n if are_you_sure('delete {} db elements:\\n{}\\n'.format(len(dbdirty_set), dbdirty_set), cfg) and not dry_run:\n for item in dbdirty_set:\n print('Deleting {}'.format(item))\n delete_short_link(item)\n if are_you_sure('delete {} s3 elements:\\n{}\\n'.format(len(s3dirty_set), s3dirty_set), cfg) and not dry_run:\n delete_s3_links(s3dirty_set)\n\n\ndef add_required_sub_parsers(parser, dest):\n sub_parser = parser.add_subparsers(dest=dest)\n sub_parser.required = True # docs say I can pass required=True in add_subparsers but that seems to be a lie\n return sub_parser\n\n\n@cli.group()\ndef environment():\n \"\"\"Environment manipulation commands.\"\"\"\n\n\n@environment.command(name='status')\n@click.pass_obj\ndef environment_status(cfg: Config):\n \"\"\"Gets the status of an environment.\"\"\"\n for asg in get_autoscaling_groups_for(cfg):\n print(f\"Found ASG {asg['AutoScalingGroupName']} with desired instances {asg['DesiredCapacity']}\")\n\n\n@environment.command(name='start')\n@click.pass_obj\ndef environment_start(cfg: Config):\n \"\"\"Starts up an environment by ensure its ASGs have capacity.\"\"\"\n for asg in get_autoscaling_groups_for(cfg):\n group_name = asg['AutoScalingGroupName']\n if asg['MinSize'] > 0:\n print(f\"Skipping ASG {group_name} as it has a non-zero min size\")\n continue\n prev = asg['DesiredCapacity']\n if prev:\n print(f\"Skipping ASG {group_name} as it has non-zero desired capacity\")\n continue\n print(f\"Updating {group_name} to have desired capacity 1 (from {prev})\")\n as_client.update_auto_scaling_group(AutoScalingGroupName=group_name, DesiredCapacity=1)\n\n\n@environment.command(name='refresh')\n@click.option(\"--min-healthy-percent\", type=click.IntRange(min=0, max=100), metavar='PERCENT',\n help='While updating, ensure at least PERCENT are healthy', default=75, show_default=True)\n@click.pass_obj\ndef environment_refresh(cfg: Config, min_healthy_percent: int):\n \"\"\"Refreshes an environment.\n\n This replaces all the instances in the ASGs associated with an environment with\n new instances (with the latest code), while ensuring there are some left to handle\n the traffic while we update.\"\"\"\n # TODO motd like the restart\n for asg in get_autoscaling_groups_for(cfg):\n group_name = asg['AutoScalingGroupName']\n if asg['DesiredCapacity'] == 0:\n print(f\"Skipping ASG {group_name} as it has a zero size\")\n continue\n describe_state = as_client.describe_instance_refreshes(\n AutoScalingGroupName=group_name\n )\n existing_refreshes = [x for x in describe_state['InstanceRefreshes'] if\n x['Status'] in ('Pending', 'InProgress')]\n if existing_refreshes:\n refresh_id = existing_refreshes[0]['InstanceRefreshId']\n print(f\" Found existing refresh {refresh_id} for {group_name}\")\n else:\n if not are_you_sure(f'Refresh instances in {group_name} with version {describe_current_release(cfg)}',\n cfg):\n return\n print(\" Starting new refresh...\")\n refresh_result = as_client.start_instance_refresh(\n AutoScalingGroupName=group_name,\n Preferences=dict(MinHealthyPercentage=min_healthy_percent)\n )\n refresh_id = refresh_result['InstanceRefreshId']\n print(f\" id {refresh_id}\")\n\n last_log = \"\"\n while True:\n time.sleep(5)\n describe_state = as_client.describe_instance_refreshes(\n AutoScalingGroupName=group_name,\n InstanceRefreshIds=[refresh_id]\n )\n refresh = describe_state['InstanceRefreshes'][0]\n status = refresh['Status']\n if status == 'InProgress':\n log = f\" {status}, {refresh['PercentageComplete']}%, \" \\\n f\"{refresh['InstancesToUpdate']} to update. \" \\\n f\"{refresh.get('StatusReason', '')}\"\n else:\n log = f\" Status: {status}\"\n if log != last_log:\n print(log)\n last_log = log\n if status in ('Successful', 'Failed', 'Cancelled'):\n break\n\n\n@environment.command(name='stop')\n@click.pass_obj\ndef environment_stop(cfg: Config):\n \"\"\"Stops an environment.\"\"\"\n if cfg.env == Environment.PROD:\n print('Operation aborted. This would bring down the site')\n print('If you know what you are doing, edit the code in bin/lib/ce.py, function environment_stop_cmd')\n elif are_you_sure('stop environment', cfg):\n for asg in get_autoscaling_groups_for(cfg):\n group_name = asg['AutoScalingGroupName']\n if asg['MinSize'] > 0:\n print(f\"Skipping ASG {group_name} as it has a non-zero min size\")\n continue\n prev = asg['DesiredCapacity']\n if not prev:\n print(f\"Skipping ASG {group_name} as it already zero desired capacity\")\n continue\n print(f\"Updating {group_name} to have desired capacity 0 (from {prev})\")\n as_client.update_auto_scaling_group(AutoScalingGroupName=group_name, DesiredCapacity=0)\n\n\ndef main():\n try:\n cli(prog_name='ce') # pylint: disable=unexpected-keyword-arg,no-value-for-parameter\n except (KeyboardInterrupt, SystemExit):\n # print empty line so terminal prompt doesn't end up on the end of some\n # of our own program output\n print()\n","sub_path":"bin/lib/ce.py","file_name":"ce.py","file_ext":"py","file_size_in_byte":39730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"456374848","text":"# -*- coding: utf-8 -*- \n\nimport sys\nimport snake\n\nfrom panda3d.core import Point2\n\nfrom direct.showbase.ShowBase import ShowBase\nfrom direct.task.Task import Task\n\nfrom settings import *\nfrom helpers import genLabelText, loadObject\nfrom collections import deque\n\nclass World( ShowBase ):\n def __init__ ( self ):\n ShowBase.__init__( self )\n\n self.disableMouse( )\n self.snake = snake.Snake( body=[ (-7, 1), (-8, 1), (-9, 1) ], dot=(-7, 1) )\n self.snake.gen_dot( )\n\n self.background = loadObject( \"background\", scale=9000, depth=200, transparency=False )\n self.gameboard = loadObject( \"background\", scale=39.5, depth=100, transparency=False )\n self.escape_text = genLabelText( \"ESC : Quit\", 0 )\n self.pause_text = genLabelText( \"SPACE: Pause\", 1)\n self.score = genLabelText( \"SCORE: %s\" % self.snake.get_score( ), 0, left=False )\n \n self.bricks = deque( )\n self.make_dot( )\n\n self.draw_snake( )\n self.accept( \"escape\", sys.exit )\n self.accept( \"enter\", self.restart )\n self.accept( \"arrow_up\", self.snake.turn, [ POS_Y ] )\n self.accept( \"arrow_down\", self.snake.turn, [ NEG_Y ] )\n self.accept( \"arrow_left\", self.snake.turn, [ NEG_X ] )\n self.accept( \"arrow_right\", self.snake.turn, [ POS_X ] )\n self.accept( \"space\", self.tooggle_pause )\n\n self.game_task = taskMgr.add( self.game_loop, \"GameLoop\" )\n self.game_task.last = 0\n self.period = 0.15\n self.pause = False\n\n def game_loop( self, task ):\n dt = task.time - task.last\n if not self.snake.alive: \n return task.done\n if self.pause:\n return task.cont\n elif dt >= self.period:\n task.last = task.time\n self.snake.move_forward( )\n self.snake.check_state( )\n self.update_snake( )\n self.update_dot( )\n self.update_score( )\n return task.cont\n else:\n return task.cont\n\n\n def draw_snake( self ):\n for point in self.snake.body:\n brick = loadObject( \"brick\", pos=Point2( point[ X ], point[ Y ] ) )\n self.bricks.append( brick )\n\n def update_snake( self ):\n try:\n for i in xrange( len( self.snake.body ) ):\n point = self.snake.body[ i ]\n brick = self.bricks[ i ]\n brick.setPos( point[ X ], SPRITE_POS, point[ Y ] )\n except IndexError:\n new_head = self.dot\n self.make_dot( )\n self.bricks.appendleft( new_head )\n\n def make_dot( self ):\n self.dot = loadObject( \"brick\", pos=Point2( self.snake.dot[ X ], self.snake.dot[ Y ] ) ) \n\n def update_dot( self ):\n x, y = self.dot.getX( ), self.dot.getZ( )\n if ( x, y ) != self.snake.dot:\n self.dot.setPos( self.snake.dot[ X ], SPRITE_POS, self.snake.dot[ Y ] )\n\n def update_score( self ):\n if self.score:\n self.score.removeNode( )\n self.score = genLabelText( \"Score: %s\" % self.snake.get_score( ), 0, left=False )\n\n def tooggle_pause( self ):\n if self.pause: self.pause = False\n else: self.pause = True\n\nw = World( )\nw.run( )\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"187364537","text":"import scipy.io.wavfile\nimport numpy as np\n\nfs = 44100 # Hz\ndur = 5 # sec\nfmin = 10 # Hz\nfmax = fs/4 # Hz\n\nt = np.arange(0,dur,1/fs,dtype=\"float32\")\nmodf = 0 #np.sin(t*4*2*np.pi)\nf = (t/np.max(t)*(fmax-fmin)+fmin)*(1+0.05*modf)\nx = np.sin(np.multiply(f,t)*2*np.pi)\n\nscipy.io.wavfile.write(\"sweep.wav\", fs, x)\n","sub_path":"makesweep.py","file_name":"makesweep.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"60676970","text":"#Rock, Paper, Scissors\nimport random, os\n\ndef clear_screen():\n '''\n Clear the screen after a match is over.\n '''\n os.system('CLS')\n\ndef prompt_user(count=0):\n '''Welcome message and gather user input.\n We are going to track how many times the user has played already and prompt accordingly.\n '''\n if count > 0:\n play_again = input(\"\\n\\nWould you like to play again (Yes or No)? \")\n\n if play_again.lower() == 'yes' or play_again.lower() == 'y':\n \tuser_select = input(\"\\nRock, Paper, or Scissors? \")\n elif play_again.lower() == 'no' or play_again.lower() == 'n':\n return play_again\n else:\n play_again = 'invalid'\n return play_again\n\n else:\n print(\"\\n\\nWelcome to Rock, Paper, Scissors!\")\n print(\"-\"*33)\n print(\"Your opponent, a random generator!\\n\\n\")\n user_select = input(\"Rock, Paper, or Scissors? \")\n\n return user_select\n\n\ndef game_match():\n '''\n Here we will take the user's input, randomly generate an opponent selection, and compare the randomly generated opponent selction to a dict of 'user wins' scenarios.\n '''\n count = 0\n wins = 0\n losses = 0\n ties = 0\n user_input = prompt_user(count)\n\n while user_input.lower() != 'no' and user_input.lower() != 'n':\n rand_options = ['rock', 'paper', 'scissors']\n user_win_cases = {'rock': 'scissors',\n 'paper': 'rock',\n 'scissors': 'paper'}\n rand_input = random.choice(rand_options)\n\n try:\n \tuser_win_cases[user_input.lower()]\n except KeyError:\n \tprint(\"\\nPlease enter a valid input and try again.\")\n \tuser_input = prompt_user(count)\n \tcontinue\n\n if rand_input.lower() == user_win_cases[user_input.lower()]:\n print(\"\\n\\nUser wins!\")\n print(\"-\"*10)\n print()\n print(\"User Choice: \"+user_input.lower())\n print(\"Random Gen. Choice: \"+rand_input.lower())\n print(\"-\"*28)\n print()\n count += 1\n wins += 1\n print(\"Your Wins: \"+str(wins))\n print(\"Your Losses: \"+str(losses))\n print(\"Your Ties: \"+str(ties))\n elif user_input.lower() == rand_input.lower():\n print(\"\\n\\nTie!\")\n count += 1\n ties += 1\n print(\"Your Wins: \"+str(wins))\n print(\"Your Losses: \"+str(losses))\n print(\"Your Ties: \"+str(ties))\n else:\n print(\"\\n\\nUser loses!\")\n print(\"-\"*11)\n print()\n print(\"User Choice: \"+user_input.lower())\n print(\"Random Gen. Choice: \"+rand_input.lower())\n count += 1\n losses += 1\n print(\"Your Wins: \"+str(wins))\n print(\"Your Losses: \"+str(losses))\n print(\"Your Ties: \"+str(ties))\n\n user_input = prompt_user(count)\n\n clear_screen()\n\ngame_match()\n","sub_path":"plain_rps.py","file_name":"plain_rps.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"114801436","text":"_base_ = './fastercnn_r50_fpn_crop.py'\nnorm_cfg = dict(type='BN', requires_grad=True)\nmodel = dict(\n pretrained='open-mmlab://resnest50',\n backbone=dict(\n type='ResNeSt',\n stem_channels=64,\n depth=50,\n radix=2,\n reduction_factor=4,\n avg_down_stride=True,\n num_stages=4,\n out_indices=(0, 1, 2, 3),\n frozen_stages=1,\n norm_cfg=norm_cfg,\n dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),\n stage_with_dcn=(False, True, True, True),\n norm_eval=True,\n style='pytorch'),\n roi_head=dict(\n bbox_head=dict(\n type='Shared4Conv1FCBBoxHead',\n conv_out_channels=256,\n norm_cfg=norm_cfg)))\n# # use ResNeSt img_norm\nimg_norm_cfg = dict(\n mean=[123.68, 116.779, 103.939], std=[58.393, 57.12, 57.375], to_rgb=True)\n\nwork_dir = 'work_dirs/faster_s50_baseline_v2_dcnv2'","sub_path":"configs/tile/fastercnn_s50_fpn_dcnv2.py","file_name":"fastercnn_s50_fpn_dcnv2.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"537455198","text":"#https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/\n\n# Remove duplicates from sorted array\n# 2.4\n# Given a sorted array, the task is to remove the duplicate elements from the array.\n#\n# Examples:\n#\n# Input : arr[] = {2, 2, 2, 2, 2}\n# Output : arr[] = {2}\n# new size = 1\n#\n# Input : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}\n# Output : arr[] = {1, 2, 3, 4, 5}\n# new size = 5\n\nclass Solution:\n def removeDuplicates(self, arr):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n\n \"\"\"\n if len(arr) == 0 or len(arr) == 1:\n return arr\n\n j = 0\n for i in range(len(arr)-1):\n if arr[i] != arr[i + 1]:\n arr[j] = arr[i]\n j += 1\n\n arr[j] = arr[-1]\n j += 1\n return j\n\n\n# Driver code\narr = [1, 2, 2, 3, 4, 4, 4, 5]\nn = len(arr)\n\n# removeDuplicates() returns\n# new size of array.\ns = Solution()\nj = s.removeDuplicates(arr)\n\n# Print updated array\nfor i in range(0, j):\n print(\" %d \"%(arr[i]), end = \" \")","sub_path":"Python Code/LeetCode/Array/Remove_duplicate.py","file_name":"Remove_duplicate.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"594899520","text":"#!/usr/bin/python3\n\"\"\" RESTful API for City object \"\"\"\nfrom flask import jsonify, abort, request\nfrom api.v1.views import app_views\nfrom models.base_model import BaseModel\nfrom models.state import State\nfrom models.city import City\nfrom models import storage\n\n\n@app_views.route('/states//cities', methods=['GET'],\n strict_slashes=False)\ndef get_cities(state_id):\n \"\"\"Retrieves all the City objects linked to a state_id \"\"\"\n state = storage.get(State, state_id)\n list_cities = []\n if state:\n for city in state.cities:\n list_cities.append(city.to_dict())\n return jsonify(list_cities)\n else:\n abort(404)\n\n\n@app_views.route('/cities/', methods=['GET'],\n strict_slashes=False)\ndef get_city(city_id):\n \"\"\" Retrieves a City object \"\"\"\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n return jsonify(city.to_dict())\n\n\n@app_views.route('/cities/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_city(city_id):\n \"\"\" Deletes a City object \"\"\"\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n empty_dict = {}\n city.delete()\n storage.save()\n return jsonify(empty_dict), 200\n\n\n@app_views.route('/states//cities', methods=['POST'],\n strict_slashes=False)\ndef create_city(state_id):\n \"\"\" Creates a City object \"\"\"\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n my_dict = request.get_json()\n if my_dict is None:\n abort(400, \"Not a JSON\")\n elif \"name\" not in my_dict:\n abort(400, \"Missing name\")\n my_dict[\"state_id\"] = state_id\n new_city = City(**my_dict)\n new_city.save()\n return jsonify(new_city.to_dict()), 201\n\n\n@app_views.route('/cities/',\n methods=['PUT'],\n strict_slashes=False)\ndef update_city(city_id):\n \"\"\"Update a City object\"\"\"\n if city_id:\n my_dict = request.get_json()\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n if my_dict is None:\n abort(400, \"Not a JSON\")\n for key, value in my_dict.items():\n if key not in [\"id\", \"created_at\", \"updated_at\"]:\n setattr(city, key, value)\n storage.save()\n return jsonify(city.to_dict()), 200\n","sub_path":"api/v1/views/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"508221531","text":"import tkinter as tk\r\nfrom tkinter import filedialog\r\n\r\ndef main():\r\n import time\r\n import os\r\n print(\"Welcome to the name Reorder Script!\")\r\n time.sleep(1) # delays for 1 seconds\r\n print(\"Locating Prompts\")\r\n time.sleep(0.6) # delays for 0.6 seconds\r\n print(\"Loading Modules\")\r\n time.sleep(1) # delays for 1 seconds\r\n print(\"Loading Filenames\")\r\n time.sleep(0.5) # delays for 0.5 seconds\r\n print(\"Scanning PC\")\r\n time.sleep(0.7) # delays for 0.7 seconds\r\n print(\"Planting Trojans\")\r\n time.sleep(0.2) # delays for 0.2 seconds\r\n print(\"Delaying Windows\")\r\n time.sleep(0.1) # delays for 0.1 seconds\r\n print(\"Corrupting Important Files\")\r\n time.sleep(2) # delays for 2 seconds\r\n os.system('cls')\r\n\r\n print(\"Please Identify The file You would Like to order\")\r\n time.sleep(2) # delays for 2 seconds\r\n\r\n\r\n#tk dialog script to open the open file dialog\r\n root = tk.Tk()\r\n root.withdraw()\r\n\r\n file_path = filedialog.askopenfilename()\r\n\r\n\r\n OpenFile = file_path\r\n\r\n Names = []\r\n\r\n with open(OpenFile, 'r') as filehandle:\r\n for line in filehandle:\r\n # remove linebreak which is the last character of the string\r\n CurrentName = line[:-1]\r\n\r\n # add item to the list\r\n Names.append(CurrentName)\r\n Names.sort()\r\n\r\n print(\"Sorted!\")\r\n time.sleep(2) # delays for 2 seconds\r\n print(\"Please Enter the Filename to save to\")\r\n time.sleep(2) # delays for 2 seconds\r\n\r\n#opens a save dialog and saves the information to that text file\r\n directory = filedialog.asksaveasfilename(defaultextension=\".txt\")\r\n with open(directory, 'w') as filehandle:\r\n for listitem in Names:\r\n filehandle.write('%s\\n' % listitem)\r\n time.sleep(2) # delays for 2 seconds\r\n print(\"WrittenSuccesfully\")\r\n time.sleep(2) # delays for 2 seconds\r\n print(\"Thank you for using this custom Script!\")\r\n time.sleep(2) # delays for 2\r\n print(\"Closing!\")\r\n time.sleep(2) # delays for 2 seconds\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"PythonreorderScript.py","file_name":"PythonreorderScript.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"440211019","text":"from util.factory import channel_factory\nfrom util.factory import DEFAULT_CHANNEL_INFO_DIRECTORY\nfrom util.factory import podcast_data_factory\n\nfrom podcast.files import download_location\nfrom podcast.models import Podcast\nfrom podcast.models import RadioDirectory\nfrom podcast.models import RequestedStatus\n\n\ndef test_download_location():\n podcast_data = Podcast(\n status=RequestedStatus(),\n data=podcast_data_factory(\n audio_link={\n 'length': u'0',\n 'href': u'http://feed.thisamericanlife.org/~r/talpodcast/~5/R0qvREKxypU/597.mp3', # noqa\n 'type': u'audio/mpeg',\n 'rel': u'enclosure',\n }))\n\n channel = channel_factory()\n\n actual = download_location(\n RadioDirectory('dir'),\n channel,\n podcast_data)\n\n expected = 'dir/{0}/597.mp3'.format(DEFAULT_CHANNEL_INFO_DIRECTORY)\n\n assert actual == expected\n","sub_path":"tests/files_test.py","file_name":"files_test.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"328213710","text":"'''\r\nCreated on 28.04.2017\r\n\r\n@author: Mr. Jones\r\n'''\r\nimport unittest\r\nfrom slimit.parser import Parser\r\nfrom jimplify.visitors import foldingvisitor\r\n\r\n\r\ndef decorator(cls):\r\n def make_test_function(input, expected):\r\n\r\n def test_func(self):\r\n self.assert_folding_objects(input, expected)\r\n\r\n return test_func\r\n\r\n for index, (input, expected) in enumerate(cls.TEST_CASES):\r\n func = make_test_function(input, expected)\r\n setattr(cls, 'test_case_%d' % index, func)\r\n\r\n return cls\r\n\r\n\r\n@decorator\r\nclass FoldingTestCase(unittest.TestCase):\r\n\r\n def assert_folding_objects(self, source, expected):\r\n parser = Parser()\r\n tree = parser.parse(source)\r\n uvisit = foldingvisitor.FoldingVisitor()\r\n uvisit.do(tree)\r\n print(tree.to_ecma())\r\n self.maxDiff = None\r\n self.assertSequenceEqual(tree.to_ecma(), expected)\r\n\r\n TEST_CASES = [\r\n ('var a = 3-2;','var a = 1;'),\r\n ('var a = 3-2+5-1+7;','var a = 12;')\r\n ]\r\n\r\n","sub_path":"Jimplify/jimplify/tests/test_folding.py","file_name":"test_folding.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"293068006","text":"from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nimport xlrd\nimport xlwt\n\ndata_path = \"D:\\MCM2020\\pacifier.xlsx\"\n\nanalyser = SentimentIntensityAnalyzer()\nf = xlwt.Workbook()\nwb = xlrd.open_workbook(filename=data_path)\nsheet1 = wb.sheet_by_index(0)\nsheet2 = f.add_sheet('page1', cell_overwrite_ok=True)\ncol_r = sheet1.col_values(12)\ncol_r2 = sheet1.col_values(13)\n\nfor i in range(0, len(col_r)):\n sheet2.write(i, 0, analyser.polarity_scores(str(col_r[i]) + str(col_r2[i]))['compound'])\n if not (i % 100):\n print(i)\n# score = analyser.polarity_scores(\"Disappointment with dryer. I purchased it because it was supposed to be quiet. It's every bit as loud as my old dryer. It's heavy, cumbersome, hard to manage. I kept turning it off because of the location of the buttons on the handle (I didn't have that problem with my old dryer). It kept sucking my hair in the motor area.
BUT, I do think there's something to this ion thing. My hair seemed softer and straighter - no frizzies. It also seemed to dry faster. So, I am now on a quest to find a ion dryer that is light, quiet and easy to manage - oh, and doesn't eat my hair.\")\n# print(score['compound'])\nf.save('D:\\\\MCM2020\\\\pacifier_sentiment.xls')\n","sub_path":"2a_Generate_Sentiment.py","file_name":"2a_Generate_Sentiment.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"180913270","text":"from scrapy import Spider, Request\nfrom carscom.items import CarscomItem\nimport re\n\nclass CarsSpider(Spider):\n\n\tname = 'cars_spider'\n\tallowed_urls = ['https://www.cars.com/']\n\tstart_urls = ['https://www.cars.com/for-sale/searchresults.action/?page=1&perPage=100&rd=30&searchSource=PAGINATION&showMore=false&sort=relevance&stkTypId=28881&zc=10001&userSetIxt=true']\n\n\tdef parse(self,response):\n\n\t\tglobal make_urls\n\n\t\tmake_lst = response.xpath('//*[@class=\"dimension facet mkId always-open-desktop\"]/ul')\n\n\t\tmake_id = make_lst.xpath('./li/input/@value').extract()\n\n\t\tmake_urls = ['https://www.cars.com/for-sale/searchresults.action/?mkId={}&page=1&perPage=100&rd=30&searchSource=GN_REFINEMENT&showMore=false&sort=relevance&stkTypId=28881&zc=10001&userSetIxt=true'.format(e) for e in make_id]\n\n\t\tfor make_u in make_urls:\n\t\t\tyield Request(url = make_u, callback = self.parse_make_urls)\n\n\n\n\tdef parse_make_urls(self, response):\n\n\t\ttotal_rec = re.sub(',', '', response.xpath('//*[@class=\"matchcount\"]/span/text()').extract_first())\n\t\tpage_nums = int(total_rec) // 100 \n\t\tpage_urls = []\n\n\t\tfor u in make_urls:\n\t\t\tpage_urls.extend([u.replace('page=1', 'page={}').format(n) for n in range(1, page_nums+1)])\n\n\n\t\tfor page_u in page_urls:\n\t\t\tyield Request(url = page_u, callback = self.parse_page_urls)\n\n\n\tdef parse_page_urls(self, response):\n\n\t\t# Scrap the urls of each car on the page\n\t\tvehicle_urls = response.xpath('//*[@class=\"shop-srp-listings__listing-container\"]/a/@href').extract()\n\n\t\tfor v_u in vehicle_urls:\n\t\t\tyield Request(url = 'https://www.cars.com' + v_u, callback = self.parse_vehicle_details)\n\n\n\tdef parse_vehicle_details(self, response):\n\n\t\tdetails = response.xpath('//*[@class=\"vdp-details-basics__list\"]')\n\t\tdet_lst = response.xpath('//*[@class=\"vdp-details-basics__list\"]/li/strong/text()').extract()\n\n\t\tfuel = ''\n\t\texter = ''\n\t\tcty = ''\n\t\tinter = ''\n\t\thwy = ''\n\t\tdrive = ''\n\t\ttran = ''\n\t\teng = ''\n\t\tmileage = ''\n\n\t\tfor i, e in enumerate(det_lst):\n\t\t\tif e == 'Fuel Type:':\n\t\t\t\tfuel = details.xpath('./li[%d]/span/text()'%(i+1)).extract_first()\n\t\t\telif e == 'Exterior Color:':\n\t\t\t\texter = details.xpath('./li[%d]/span/text()'%(i+1)).extract_first()\n\t\t\telif e == 'City MPG:':\n\t\t\t\tcty = details.xpath('./li[%d]/span/text()'%(i+1)).extract_first()\n\t\t\telif e == 'Interior Color:':\n\t\t\t\tinter = details.xpath('./li[%d]/span/text()'%(i+1)).extract_first()\n\t\t\telif e == 'Highway MPG:':\n\t\t\t\thwy = details.xpath('./li[%d]/span/text()'%(i+1)).extract_first()\n\t\t\telif e == 'Drivetrain:':\n\t\t\t\tdrive = details.xpath('./li[%d]/span/text()'%(i+1)).extract_first()\n\t\t\telif e == 'Transmission:':\n\t\t\t\ttran = details.xpath('./li[%d]/span/text()'%(i+1)).extract_first()\n\t\t\telif e == 'Engine:':\n\t\t\t\teng = details.xpath('./li[%d]/span/text()'%(i+1)).extract_first()\n\t\t\telif e == 'Mileage:':\n\t\t\t\tmileage = details.xpath('./li[%d]/span/text()'%(i+1)).extract_first()\n\n\t\ttitle = response.xpath('//h1[@class=\"cui-heading-2--secondary vehicle-info__title\"]/text()').extract_first()\n\t\tyear = re.search('\\d{4} [A-za-z- ]+ [A-za-z0-9-]+', response.xpath('//h1[@class=\"cui-heading-2--secondary vehicle-info__title\"]/text()').extract_first()).group().split()[0]\n\t\tmade = re.search('\\d{4} [A-za-z- ]+ [A-za-z0-9-]+', response.xpath('//h1[@class=\"cui-heading-2--secondary vehicle-info__title\"]/text()').extract_first()).group().split()[1]\n\t\tprice = response.xpath('//*[@class=\"vehicle-info__price\"]//text()').extract_first()\n\n\t\ttry:\n\t\t\tmodel = re.search('\\d{4} [A-za-z- ]+ [A-za-z0-9-]+', response.xpath('//h1[@class=\"cui-heading-2--secondary vehicle-info__title\"]/text()').extract_first()).group().split()[2]\n\t\texcept TypeError:\n\t\t\tmdoel = ''\n\n\t\ttry:\n\t\t\tslrzip = re.findall('\\d{5}', response.xpath('//*[@class=\"get-directions-link seller-details-location__text\"]/a/text()').extract_first())[0]\n\t\texcept TypeError:\n\t\t\tslrzip = ''\n\n\t\ttry:\n\t\t\tslreview = re.findall('(\\d.\\d|\\d)', response.xpath('//*[@class=\"rating__link rating__link--has-reviews\"]/text()').extract_first())[0]\n\t\texcept TypeError:\n\t\t\tslreview = ''\n\t\t\t\n\n\t\titem = CarscomItem()\n\t\titem['title'] = title\n\t\titem['year'] = year\n\t\titem['made'] = made\n\t\titem['model'] = model\n\t\titem['price'] = price\n\t\titem['slrzip'] = slrzip\n\t\titem['slreview'] = slreview\n\t\titem['fuel'] = fuel\n\t\titem['exter'] = exter\n\t\titem['cty'] = cty\n\t\titem['inter'] = inter\n\t\titem['hwy'] = hwy\n\t\titem['drive'] = drive\n\t\titem['tran'] = tran\n\t\titem['eng'] = eng\n\t\titem['mileage'] = mileage\n\n\t\tyield item","sub_path":"carscom/spiders/cars_spider.py","file_name":"cars_spider.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"380443845","text":"import random\n\nclass SearchTimeout(Exception):\n \"\"\"Subclass base exception for code clarity. \"\"\"\n pass\n\n\ndef custom_score(game, player):\n if game.is_loser(player):\n return float(\"-inf\")\n if game.is_winner(player):\n return float(\"inf\")\n own_moves = len(game.get_legal_moves(player))\n opp_moves = len(game.get_legal_moves(game.get_opponent(player)))\n return float(own_moves - 2*opp_moves)\n\n\ndef custom_score_2(game, player): # similar to custom_score but favors blocking opponents move after the board is half full\n if game.is_loser(player):\n return float(\"-inf\")\n if game.is_winner(player):\n return float(\"inf\")\n booster=0 #\n own_moves = game.get_legal_moves(player)\n opp_moves = game.get_legal_moves(game.get_opponent(player))\n if game.move_count>(game.width)*(game.height)/2:\n pref_moves=list(set(own_moves) & set(opp_moves))\n if len(pref_moves):\n booster=1\n return float(len(own_moves) - 2*len(opp_moves)+8*booster) # favors moves that limit opponent's choice\n\n\ndef custom_score_3(game, player): # in the begining of the game (for first 18 moves on 7*7 sized board) favors cells that are surrounded by blocked cells. \n if game.is_loser(player): # after first 18 moves seeks for blocking opponent move. together with improved_score.\n return float(\"-inf\")\n if game.is_winner(player):\n return float(\"inf\")\n occupied_neighbors_amount=0\n own_moves = game.get_legal_moves(player)\n opp_moves = game.get_legal_moves(game.get_opponent(player))\n if game.move_count<(game.width-4)*(game.height-4)*2: \n x,y=game.get_player_location(player)\n if x==0: xx=[0,1]\n elif x==game.width-1: xx=[game.width-2, game.width-1]\n else: xx=[x-1,x,x+1]\n if y==0: yy=[0,1]\n elif y==game.height-1: yy=[game.height-2, game.height-1]\n else: yy=[y-1,y,y+1]\n non_empty=[(i, j) for i in xx for j in yy if game._board_state[i + j * game.height] != 0]\n non_empty.remove((x,y))\n occupied_neighbors_amount=len(non_empty) # non-empty spaces\n else:\n if len(opp_moves)==1 and opp_moves[0] in own_moves: occupied_neighbors_amount=float('inf')\n return float(len(own_moves) - len(opp_moves)+6*occupied_neighbors_amount)\n\n\nclass IsolationPlayer:\n\n def __init__(self, search_depth=3, score_fn=custom_score, timeout=10.):\n self.search_depth = search_depth\n self.score = score_fn\n self.time_left = None\n self.TIMER_THRESHOLD = timeout\n\n\nclass MinimaxPlayer(IsolationPlayer):\n\n\n def get_move(self, game, time_left):\n self.time_left = time_left\n # Initialize the best move so that this function returns something\n # in case the search fails due to timeout\n legal_moves=game.get_legal_moves(self)\n if len(legal_moves):\n _, move=max([(self.score(game.forecast_move(m), self),m) for m in legal_moves])#argmax for scores at last depth\n best_move= move\n else: best_move=(-1,-1)\n try:\n # The try/except block will automatically catch the exception\n # raised when the timer is about to expire.\n best_move=self.minimax(game, self.search_depth)\n return best_move\n except SearchTimeout:\n pass \n\n def minimax(self, game, depth):\n if self.time_left() < self.TIMER_THRESHOLD:\n raise SearchTimeout()\n legal_moves=game.get_legal_moves(self) \n if len(legal_moves)==0:\n return (-1,-1)\n _, move=max([(self.min_value(game.forecast_move(m), depth-1),m) for m in legal_moves]) # argmax for recursive calls \n return move\n\n def max_value(self, game, depth):\n if self.time_left() < self.TIMER_THRESHOLD:\n raise SearchTimeout()\t\n if len(game.get_legal_moves(self))==0: #it appears as redundant check, but it does expedite solutions in some cases and improves tournament score\n return self.score(game, self)\n if depth:\n v=float('-inf')\n for a in game.get_legal_moves(self): # maximizing player\n v=max(v, self.min_value(game.forecast_move(a), depth-1))\n return v\n else: return self.score(game, self)\n\n def min_value(self, game, depth):\n if self.time_left() < self.TIMER_THRESHOLD:\n raise SearchTimeout()\n if len(game.get_legal_moves(game.get_opponent(self)))==0:\n return self.score(game, game.get_opponent(self))\n if depth:\n v=float('inf')\n for a in game.get_legal_moves(game.get_opponent(self)): #minimizing player\n v=min(v, self.max_value(game.forecast_move(a), depth-1))\n return v\n else: return self.score(game, self)\n\nclass AlphaBetaPlayer(IsolationPlayer):\n\n def get_move(self, game, time_left):\n self.time_left = time_left\n # Initialize the best move so that this function returns something\n # in case the search fails due to timeout\n legal_moves=game.get_legal_moves(self)\n if len(legal_moves):\n _, move=max([(self.score(game.forecast_move(m), self),m) for m in legal_moves])#argmax for scores at last depth\n best_move= move\n else: \n return (-1,-1)\n try:\n for self.search_depth in range(1, game.height*game.width+1):\n best_move=self.alphabeta(game, self.search_depth)\n except SearchTimeout:\n pass \n return best_move\n\n\n def alphabeta(self, game, depth, alpha=float(\"-inf\"), beta=float(\"inf\")):\n if self.time_left() < self.TIMER_THRESHOLD:\n raise SearchTimeout()\n max_v=float('-inf')\n for m in game.get_legal_moves(self):\n v=self.min_value(game.forecast_move(m), depth-1, alpha, beta)\n if v>=max_v:\n max_v=v\n best_move=m\n alpha=max(alpha, v)\n return best_move\n\n\n def max_value(self, game, depth, alpha, beta):\n v=float('-inf')\n if self.time_left() < self.TIMER_THRESHOLD:\n raise SearchTimeout()\t\n if len(game.get_legal_moves(self))==0:\n return self.score(game, self)\n if depth:\n for a in game.get_legal_moves(self): #maximizing player\n v=max(v, self.min_value(game.forecast_move(a), depth-1, alpha, beta))\n if v>= beta: \n return v\n alpha=max(alpha, v)\n return v\n else: return self.score(game, self) \n\n def min_value(self, game, depth, alpha, beta):\n if self.time_left() < self.TIMER_THRESHOLD:\n raise SearchTimeout()\n v=float('inf')\n if len(game.get_legal_moves(game.get_opponent(self)))==0:\n return self.score(game, self)\n if depth:\n for a in game.get_legal_moves(game.get_opponent(self)): #minimizing player\n v=min(v, self.max_value(game.forecast_move(a), depth-1, alpha, beta))\n if v<=alpha: return v\n beta=min(beta, v)\n return v\n else: return self.score(game, self)\n","sub_path":"game_agent.py","file_name":"game_agent.py","file_ext":"py","file_size_in_byte":7171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"625398303","text":"#!/usr/bin/env python3\n# Permet de lire/recevoir un message de la queue et d'afficher le contenu du msg\nimport pika\n\n# Etablie une conneixon avec le server RabbitMQ\nconnection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))\nchannel = connection.channel()\n\n# Create an hello queue sur laquelle notre message sera lu/reçue\n# on peut déclarer la queue n'importe quel nombre de fois, elle ne sera crée qu'une seule fois\nchannel.queue_declare(queue='rfe')\n\n# on définit un callback qui sera appelé(par pika) à chaque nouveau message inséré dans la file\n# et affichera le contenu du message\ndef callback(ch, method, properties, body):\n print(\" [x] Received %r\" % body)\n\n# Reçoit les message de la queue lorsqu'il y a en a\n# on indique à RabbitMQ que le callback définit ci dessus doit recevoir les messages de la queue 'hello'\n# on doit bien sur s'assurer que la queue existe avant de s'abonner à ce callback\nchannel.basic_consume(queue='hello',\n auto_ack=True,\n on_message_callback=callback)\n\n# On boucle en attendant les données et appelons le callback quand message reçu\nprint(' [*] Waiting for messages. To exit press CTRL+C')\nchannel.start_consuming()\n\n# On ferme la connexion\nconnection.close()","sub_path":"docker_file/flask/flasksrv/zmapp/test/receive_copy.py","file_name":"receive_copy.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"531262448","text":"\"\"\"\nThe Python standard library's 'calendar' module allows you to\nrender a calendar to your terminal.\nhttps://docs.python.org/3.6/library/calendar.html\n\nWrite a program that accepts user input of the form\n `14_cal.py month [year]`\n\n and does the following:\n\n - If the user doesn't specify any input, your program should\n print the calendar for the current month. The 'datetime'\n module may be helpful for this.\n \n - If the user specifies one argument, assume they passed in a\n month and render the calendar for that month of the current year.\n \n - If the user specifies two arguments, assume they passed in\n both the month and the year. Render the calendar for that\n month and year.\n \n - Otherwise, print a usage statement to the terminal indicating\n the format that your program expects arguments to be given.\n Then exit the program.\n\"\"\"\n\nimport sys\nimport calendar\nfrom datetime import datetime\n\n# If the user doesnt pass any argument in it just returns the calendar for their current year and month\nif len(sys.argv) == 1:\n theMonth = datetime.now().month\n theYear = datetime.now().year\n print(calendar.month(theYear, theMonth)) \n quit()\n\n# If the user passes in the month, we shall assume the year they want is the current calendar year\nelif len(sys.argv) == 2:\n theMonth = int(sys.argv[1])\n theYear = datetime.now().year\n print(calendar.month(theYear, theMonth))\n quit()\n\n# If the user passes in a month and year, we give them what they want.\nelif len(sys.argv) == 3:\n theMonth = int(sys.argv[1])\n theYear = int(sys.argv[2])\n print(calendar.month(theYear, theMonth))\n quit()\n\n# If the user passes in more than 3 arguments we give them a usage statement\nelif len(sys.argv) > 3:\n print(\"****USAGE**** \\n This program will do one of three things \\n 1. If it is ran it will return the current calendar for your month & year \\n 2. It will accept you passing in a month in the format of [01] without brackets, and will assume the year you want is the current year \\n 3. you can pass in a month in the format of [01] and a year in the format of [1999]. ex [02 1999] but without brackets. It will return the celandar for the respective monthand year. \")\n","sub_path":"src/14_cal.py","file_name":"14_cal.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"527406855","text":"import pylab\nimport random\nimport numpy as np\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\n\nfrom keras.models import Sequential\nfrom collections import deque\n\nEPISODES = 500\nACTION_SPACE = [0, 1]\nCOUNT = 50\nFLAG_MODEL = False\nTRAIN_START = 1000\nMEMORY_DEQUE = 2000\n\n\n# 게임환경\nclass GameEnv:\n\n\tdef __init__(self):\n\t\tself.score = 0\n\t\tself.arr_com = []\n\t\tself.seq = 0\n\t\tself.seq_end = COUNT\n\n\tdef initialize(self):\n\t\tself.score = 0\n\t\tself.arr_com = []\n\t\tself.seq = 0\n\t\tfor i in range(self.seq_end):\n\t\t\tself.arr_com.append(random.randrange(0, len(ACTION_SPACE)))\n\n\tdef get_state(self):\n\t\ta = np.array([self.arr_com[self.seq]])\n\t\treturn a\n\n\tdef is_end(self):\n\t\tif self.seq >= self.seq_end:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef step(self, mine):\n\t\tnow_score = self.score\n\t\tself.do_work(mine)\n\t\tnext_score = self.score\n\n\t\treward = next_score - now_score\n\t\tflag_end = self.is_end()\n\t\tnext_state = np.array([-1])\n\t\tnext_state = np.reshape(next_state, [1, 1])\n\n\t\tif flag_end == False:\n\t\t\tnext_state = self.get_state()\n\n\t\treturn next_state, reward, flag_end\n\n\tdef do_work(self, mine):\n\t\tif self.arr_com[self.seq] == mine:\n\t\t\tself.score += 1\n\n\t\tself.seq += 1\n\n\n# 신경망관리\nclass Agent:\n\n\tdef __init__(self):\n\t\tself.load_model = FLAG_MODEL\n\n\t\t# 0: 홀 1: 짝 \n\t\tself.action_space = ACTION_SPACE\n\t\tself.action_size = len(self.action_space)\n\t\tself.state_size = 1\n\t\tself.discount_factor = 0.99\n\t\tself.learning_rate = 0.001\n\n\t\tself.epsilon = 1.0\n\t\tself.epsilon_decay = 0.9999\n\t\tself.epsilon_min = 0.01\n\t\tself.batch_size = 64\n\t\tself.train_start = TRAIN_START\n\n\t\tself.model = self.build_model()\n\t\tself.model_target = self.build_model()\n\t\tself.update_model_target()\n\t\tself.memory = deque(maxlen=MEMORY_DEQUE)\n\n\t\tif self.load_model:\n\t\t\tself.model .load_weights('save_model/mdl_origin.h5')\n\t\t\tself.model_target .load_weights('save_model/mdl_target.h5')\n\n\tdef build_model(self):\n\t\tmodel = Sequential()\n\t\tmodel.add(Dense(10, input_dim=self.state_size, activation='relu', kernel_initializer='he_uniform'))\n\t\tmodel.add(Dense(10, activation='relu', kernel_initializer='he_uniform'))\n\t\tmodel.add(Dense(self.action_size, activation='linear', kernel_initializer='he_uniform'))\n\t\tmodel.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))\n\t\treturn model\n\n\tdef append_in_memory(self, state, mine, reward, next_state, flag_end):\n\t\tself.memory.append((state, mine, reward, next_state, flag_end))\n\n\tdef update_model_target(self):\n\t\tself.model_target.set_weights(self.model.get_weights())\n\n\tdef get_predict(self, state):\n\t\tif np.random.rand() <= self.epsilon:\n\t\t\treturn random.randrange(self.action_size)\n\t\telse:\n\t\t\tstate = np.float32(state)\n\t\t\tq_values = self.model.predict(state)\n\t\t\treturn np.argmax(q_values[0])\n\n\tdef train_model(self):\n\t\tif self.epsilon > self.epsilon_min:\n\t\t\tself.epsilon *= self.epsilon_decay\n\n\t\tmini_batch = random.sample(self.memory, self.batch_size)\n\n\t\tarr_state = np.zeros((self.batch_size, self.state_size))\n\t\tarr_state_next = np.zeros((self.batch_size, self.state_size))\n\t\tarr_mine, arr_reward, arr_flag_end = [], [], []\n\n\t\tfor i in range(self.batch_size):\n\t\t\tarr_state[i] = mini_batch[i][0]\n\t\t\tarr_mine.append(mini_batch[i][1])\n\t\t\tarr_reward.append(mini_batch[i][2])\n\t\t\tarr_state_next[i] = mini_batch[i][3]\n\t\t\tarr_flag_end.append(mini_batch[i][4])\n\n\t\tarr_predict = self.model.predict(arr_state)\n\t\tarr_predict_target = self.model_target.predict(arr_state_next)\n\n\t\tfor i in range(self.batch_size):\n\t\t\tarr_predict[i][arr_mine[i]] = arr_reward[i] + self.discount_factor * np.amax(arr_predict_target[i])\n# \t\t\tif i == 0:\n# \t\t\t\tprint(i,\"------------arr_reward[i]:\",arr_reward[i],\"self.discount_factor:\",self.discount_factor,\"np.amax(arr_predict_target[i]):\",arr_predict_target[i][0],arr_predict_target[i][1])\n\t\t\t\n\t\tself.model.fit(arr_state, arr_predict, batch_size=self.batch_size, epochs=1, verbose=0)\n\n\nif __name__ == \"__main__\":\n\tgameenv = GameEnv()\n\tagent = Agent()\n\n\tglobal_step = 0\n\tarr_score, arr_episode = [], []\n\n\tfor epi in range(EPISODES):\n\t\tflag_end = False\n\t\tscore = 0\n\t\tgameenv.initialize()\n\t\t\n\t\twhile not flag_end:\n\t\t\tglobal_step += 1\n\t\t\tnow_state = gameenv.get_state()\n\t\t\tnow_state = np.reshape(now_state, [1, 1])\n\t\t\tmine = agent.get_predict(now_state)\n\t\t\t\n\t\t\tnext_state, reward, flag_end = gameenv.step(mine)\n\n\t\t\tnext_state = np.reshape(next_state, [1, 1])\n\t\t\tagent.append_in_memory(now_state, mine, reward, next_state, flag_end)\n\n\t\t\tif len(agent.memory) >= agent.train_start:\n\t\t\t\tagent.train_model()\n\n# \t\t\tnow_state = next_state\n\t\t\tscore += reward\n\n\t\tif flag_end:\n\t\t\tagent.update_model_target()\n\t\t\tarr_score.append(score)\n\t\t\tarr_episode.append(epi)\n\t\t\tpylab.plot(arr_episode, arr_score, 'b')\n\t\t\tpylab.savefig(\"agent.png\")\n\t\t\tprint(\"episode: \", epi, \" global_step\", global_step, \" score: \", score, \" epsilon: \", agent.epsilon)\n\n\t\tif epi % 100 == 0:\n\t\t\tprint(\"save_weights\")\n\t\t\tagent.model.save_weights(\"save_model/mdl_origin.h5\")\n\t\t\tagent.model_target.save_weights(\"save_model/mdl_target.h5\")\n\t\t\tprint(agent.memory)\n\n","sub_path":"HELLOPYTHON/day17cifar/new_agent_holl.py","file_name":"new_agent_holl.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"478585804","text":"# -*- coding: utf-8 *-*\nfrom ContestSolver import ContestSolver\n\n\ndef parsegridline(chars):\n\tline = []\n\tfull = True\n\tfor char in chars:\n\t\tif char == 'X':\n\t\t\tline.append([1, 0])\n\t\telif char == 'O':\n\t\t\tline.append([0, 1])\n\t\telif char == 'T':\n\t\t\tline.append([1, 1])\n\t\telse:\n\t\t\tline.append([0, 0])\n\t\t\tfull = False\n\treturn full, line\n\n\ndef solver(case):\n\tgrid = []\n\tfull = True\n\tfor line in case[0:4]:\n\t\tnewfull, newline = parsegridline(line[0])\n\t\tgrid.append(newline)\n\t\tfull = full and newfull\n\n\tfor i in range(4):\n\t\tresult = [1, 1]\n\t\tfor j in range(4):\n\t\t\tresult[0] *= grid[i][j][0]\n\t\t\tresult[1] *= grid[i][j][1]\n\t\tif result == [1, 0]:\n\t\t\treturn [\"X won\"]\n\t\telif result == [0, 1]:\n\t\t\treturn [\"O won\"]\n\n\tfor j in range(4):\n\t\tresult = [1, 1]\n\t\tfor i in range(4):\n\t\t\tresult[0] *= grid[i][j][0]\n\t\t\tresult[1] *= grid[i][j][1]\n\t\tif result == [1, 0]:\n\t\t\treturn [\"X won\"]\n\t\telif result == [0, 1]:\n\t\t\treturn [\"O won\"]\n\n\tresult = [1, 1]\n\tfor i in range(4):\n\t\tresult[0] *= grid[i][i][0]\n\t\tresult[1] *= grid[i][i][1]\n\tif result == [1, 0]:\n\t\treturn [\"X won\"]\n\telif result == [0, 1]:\n\t\treturn [\"O won\"]\n\n\tresult = [1, 1]\n\tfor i in range(4):\n\t\tresult[0] *= grid[3 - i][i][0]\n\t\tresult[1] *= grid[3 - i][i][1]\n\tif result == [1, 0]:\n\t\treturn [\"X won\"]\n\telif result == [0, 1]:\n\t\treturn [\"O won\"]\n\n\tif full:\n\t\treturn [\"Draw\"]\n\telse:\n\t\treturn [\"Game has not completed\"]\n\nsolution = ContestSolver(solver)\n#solution.run(\"A-test\", test=True)\nsolution.run(\"A-small-attempt0\")\n#solution.run(\"A-large-practice\")\n","sub_path":"solutions_2453486_0/Python/robsci/A-TicTacToeTomek.py","file_name":"A-TicTacToeTomek.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"46895261","text":"a=int(input(\"Enter 3 numbers to compare\"))\nb=int(input())\nc=int(input())\n\nop=input(\"smallest/largest?\")\n\n\ndef larg(a,b,c):\n if(a>b) and (a>c):\n largest = a\n elif(b>a) and (b>c):\n largest = b\n else:\n largest = c\n print(\"largest is: \",largest)\n\ndef small(a,b,c):\n if(a 0:\n calibration = True\n \n aotfOrders.append(aotfOrder)\n \n aotfOrdersSorted = sorted(aotfOrders)\n \n \n if len(set(binningFactors)) == 1: #if more than one binning factor in the observation\n binningFactorSingle = binningFactors[0]\n windowHeightTotal = 24.0 / nSubdomains * (binningFactorSingle + 1)\n if np.round(windowHeightTotal) == windowHeightTotal:\n windowHeightTotal = int(windowHeightTotal)\n else:\n print(\"Binning rounding error row %i\" %rowIndex)\n else:\n if not silent: print(\"Binning error row %i\" %rowIndex)\n if not silent: print(binningFactors)\n errorFound = True\n \n \n if len(set(accumulations)) == 1: #if n accumulations is the same for all observations\n accumulationSingle = accumulations[0]\n else:\n if not silent: print(\"Accumulation error row %i\" %rowIndex)\n if not silent: print(accumulations)\n errorFound = True\n \n \n if len(set(integrationTimes)) == 1: #if more than one integration time in the observation\n integrationTimeSingle = integrationTimes[0]\n else:\n if not silent: print(\"Int time error row %i\" %rowIndex)\n if not silent: print(integrationTimes)\n errorFound = True\n \n \n if nSubdomains > 1: \n if sum(steppingIndices[1:6]) > 0:\n if not silent: print(\"Stpping error row %i\" %rowIndex)\n errorFound = True\n \n if not calibration:\n executionTime = calcExecutionTime(accumulationSingle, windowHeightTotal, integrationTimeSingle)\n executionTimeTotal = executionTime * nSubdomains\n \n if 650.0 < executionTimeTotal < 1000.0:\n rhythm = 1\n elif 1700.0 < executionTimeTotal < 2000.0:\n rhythm = 2\n elif 3400.0 < executionTimeTotal < 4000.0:\n rhythm = 4\n elif 7000.0 < executionTimeTotal < 8000.0:\n rhythm = 8\n elif 14000.0 < executionTimeTotal < 15000.0:\n rhythm = 15\n else:\n if not silent: print(\"Exec time error row %i\" %rowIndex)\n errorFound = True\n \n if not errorFound and not calibration:\n subdomainIndices.append(rowIndex)\n aotfOrdersAll.append(aotfOrdersSorted)\n integrationTimesAll.append(integrationTimeSingle)\n windowHeightAll.append(windowHeightTotal)\n rhythmAll.append(rhythm)\n \n copTableCombinations = {\"index\":subdomainIndices, \"orders\":aotfOrdersAll, \"integrationTime\":integrationTimesAll, \"rhythm\":rhythmAll, \"windowHeight\":windowHeightAll}\n return copTableCombinations\n\n\n\n\n \n\ndef findCopRowData(channel, copTableDict, columnNames, row, table=\"\"):\n# channel=\"so\"\n# columnName = \"science_3\"\n# row=1000\n \n\n \n if isinstance(row, list):\n if len(row)==1:\n row = int(row[0])\n else:\n print(\"Error: row number is a list\")\n\n if channel in [\"so\",\"lno\"]:\n aotfHeaders = {\"so\":copTableDict[\"soAotfHeaders\"], \"lno\":copTableDict[\"lnoAotfHeaders\"]}[channel]\n aotfList = {\"so\":copTableDict[\"soAotfList\"], \"lno\":copTableDict[\"lnoAotfList\"]}[channel]\n fixedHeaders = {\"so\":copTableDict[\"soFixedHeaders\"], \"lno\":copTableDict[\"lnoFixedHeaders\"]}[channel]\n fixedList = {\"so\":copTableDict[\"soFixedList\"], \"lno\":copTableDict[\"lnoFixedList\"]}[channel]\n scienceHeaders = {\"so\":copTableDict[\"soScienceHeaders\"], \"lno\":copTableDict[\"lnoScienceHeaders\"]}[channel]\n scienceList = {\"so\":copTableDict[\"soScienceList\"], \"lno\":copTableDict[\"lnoScienceList\"]}[channel]\n steppingHeaders = {\"so\":copTableDict[\"soSteppingHeaders\"], \"lno\":copTableDict[\"lnoSteppingHeaders\"]}[channel]\n steppingList = {\"so\":copTableDict[\"soSteppingList\"], \"lno\":copTableDict[\"lnoSteppingList\"]}[channel]\n subdomainHeaders = {\"so\":copTableDict[\"soSubdomainHeaders\"], \"lno\":copTableDict[\"lnoSubdomainHeaders\"]}[channel]\n subdomainList = {\"so\":copTableDict[\"soSubdomainList\"], \"lno\":copTableDict[\"lnoSubdomainList\"]}[channel]\n \n if table != \"\": #not used\n if table==\"aotf\":\n copTable = aotfList\n copTableHeader = aotfHeaders\n elif table==\"fixed\":\n copTable = fixedList\n copTableHeader = fixedHeaders\n elif table==\"science\":\n copTable = scienceList\n copTableHeader = scienceHeaders\n elif table==\"stepping\":\n copTable = steppingList\n copTableHeader = steppingHeaders\n elif table==\"subdomain\":\n copTable = subdomainList\n copTableHeader = subdomainHeaders\n else:\n print(\"Error: table unknown\")\n\n valuesOut = []\n for columnName in columnNames:\n columnIndex = findIndex(columnName,copTableHeader)\n valuesOut.append(copTable[int(row)][columnIndex])\n \n if len(valuesOut)==1:\n valuesOut = valuesOut[0]\n return valuesOut\n \n else:\n if channel in [\"so\",\"lno\"]:\n headers = [aotfHeaders,fixedHeaders,scienceHeaders,steppingHeaders,subdomainHeaders]\n lists = [aotfList,fixedList,scienceList,steppingList,subdomainList]\n elif channel == \"uvis\":\n headers = [copTableDict[\"uvisHeaders\"]]\n lists = [copTableDict[\"uvisList\"]]\n \n valuesOut = []\n for columnName in columnNames:\n value = []\n for headerIndex,header in enumerate(headers):\n if columnName in header:\n columnIndex = findIndex(columnName,header)\n # print(headerIndex)\n # print(columnIndex)\n value.append(lists[headerIndex][int(row)][columnIndex])\n \n if len(value) == 1:\n valuesOut.append(value[0])\n else:\n print(\"Error finding COP row\")\n \n if len(valuesOut)==1:\n valuesOut = valuesOut[0]\n return valuesOut\n\n\n\n\"\"\"find matching cop rows\"\"\"\ndef findCopRows(channel,copTableDict, orders,integrationTime,nRows,silent=False): #IntTime in ms!!\n \n subdomainList = {\"so\":copTableDict[\"soSubdomainList\"], \"lno\":copTableDict[\"lnoSubdomainList\"]}[channel]\n \n otherRows = []\n found=False\n for rowIndex,subdomainRow in enumerate(subdomainList):\n subdomainComment = subdomainRow[6]\n nFound = 0\n nSubdomains = 6 - subdomainRow.count(\"0\")\n for order in orders:\n if subdomainComment.find(\" %s \" %str(order)) > -1:\n nFound += 1\n \n if nFound == len(orders) and nSubdomains == len(orders):\n found=True\n if subdomainComment.find(\"=%sMS\" %str(integrationTime)) > -1:\n \n if subdomainComment.find(\"NROWS=%s\" %str(nRows)) > -1:\n if not silent: print(\"Matching row found: %i\" %rowIndex)\n if not silent: print(subdomainRow)\n return rowIndex\n else:\n otherRows.append(subdomainRow)\n else:\n otherRows.append(subdomainRow)\n \n if found:\n print(\"Orders found but integration time and/or number of rows not. Possible options are:\")\n for otherRow in otherRows:\n print(otherRow)\n return -1 #wrong integration time\n else:\n print(\"Orders not found\")\n print(orders)\n return -2 #order combination not found\n\n\n\n\n\"\"\"find matching cop rows\"\"\"\ndef findFixedCopRow(channel,copTableDict, centreRow,nRows,rhythm,silent=False): #IntTime in ms!!\n \n fixedList = {\"so\":copTableDict[\"soFixedList\"], \"lno\":copTableDict[\"lnoFixedList\"]}[channel]\n \n foundRows = []\n found=False\n for rowIndex,fixedRow in enumerate(fixedList):\n nFound = 0\n fixedHeight = int(fixedRow[0]) + 1\n fixedTop = int(fixedRow[1])\n fixedRhythm = int(fixedRow[6])\n \n if fixedHeight == nRows and fixedTop == centreRow - nRows/2 and fixedRhythm == rhythm:\n if not silent: print(\"Matching fixed row found: %i\" %rowIndex)\n if not silent: print(fixedRow)\n found=True\n nFound += 1\n foundRows.append(rowIndex)\n \n if found and len(foundRows)==1:\n return foundRows[0] #return the correct row\n elif found:\n if foundRows[0] == 0 and foundRows[1] == 9: #fudge to stop error when default values (at top of fixed cop table) are copies of other rows\n return foundRows[0] #return the first matching row\n elif foundRows[0] == 1 and foundRows[1] == 72: #fudge to stop error when default values (at top of fixed cop table) are copies of other rows\n return foundRows[0] #return the first matching row\n elif foundRows[0] == 2 and foundRows[1] == 81: #fudge to stop error when default values (at top of fixed cop table) are copies of other rows\n return foundRows[0] #return the first matching row\n\n elif foundRows[0] == 0 and foundRows[1] == 21: #fudge to stop error when default values (at top of fixed cop table) are copies of other rows\n return foundRows[0] #return the first matching row\n elif foundRows[0] == 1 and foundRows[1] == 11: #fudge to stop error when default values (at top of fixed cop table) are copies of other rows\n return foundRows[0] #return the first matching row\n elif foundRows[0] == 2 and foundRows[1] == 80: #fudge to stop error when default values (at top of fixed cop table) are copies of other rows\n return foundRows[0] #return the first matching row\n\n else:\n print(\"Warning: Multiple matching fixed rows found:\")\n for row in foundRows:\n print(row)\n print(fixedList[row][7])\n return foundRows[0] #\n else:\n print(\"Error: Fixed row not found\")\n return -999\n\n\n\n\"\"\"output text description of measurement given input rows\"\"\"\ndef getObservationDescription(channel, copTableDict, fixedRow, copRow, silent=False):\n if copRow == -1:\n return \"%s off\" %channel.upper()\n \n \n if channel in [\"so\",\"lno\"]:\n\n fixedRhythm = findCopRowData(channel,copTableDict, [\"rythm\"],fixedRow)\n fixedTop = findCopRowData(channel,copTableDict, [\"windowLeftTop\"],fixedRow)\n fixedHeight = findCopRowData(channel,copTableDict, [\"windowLineCount\"],fixedRow)\n \n sciencePointers = findCopRowData(channel,copTableDict, [\"science_1\",\"science_2\",\"science_3\",\"science_4\",\"science_5\",\"science_6\"],copRow)\n \n nSubdomains = 6 - sciencePointers.count(\"0\")\n if not silent: print(nSubdomains)\n \n if nSubdomains == 1: #check for stepping\n sciencePointer = sciencePointers[0]\n steppingPointer = findCopRowData(channel,copTableDict, [\"steppingPointer\"],sciencePointer)\n if steppingPointer != \"0\":\n steppingType,steppingSpeed,steppingCount,steppingValue = findCopRowData(channel,copTableDict, [\"steppingParameter\",\"stepSpeed\",\"stepCount\",\"stepValue\"],steppingPointer)\n aotfOrder = findCopRowData(channel,copTableDict, [\"aotfPointer\"],sciencePointer)\n aotfFrequency = findCopRowData(channel,copTableDict, [\"frequency\"],aotfOrder)\n integrationTime = np.int(findCopRowData(channel,copTableDict, [\"integrationTime\"],sciencePointer)) / 1000\n if steppingType==\"AOTF_IX\":\n observationText = \"Diffraction order stepping (fullscan): %i orders from %i to %i in steps of %s (%s order(s) per %s second(s))\" %(int(steppingCount),int(aotfOrder),int(aotfOrder)+int(steppingCount),int(steppingValue),int(steppingSpeed)+1,int(fixedRhythm))\n elif steppingType==\"WINDOW_TOP\":\n observationText = \"Detector window stepping: %i step(s) covering detector lines %i to %i (%s step(s) per %s second(s))\" %(int(steppingCount),int(fixedTop),int(fixedTop)+int(steppingCount)*int(steppingValue),int(steppingSpeed)+1,int(fixedRhythm))\n elif steppingType==\"INTEGRATION_TIME\":\n observationText = \"Detector integration time stepping: %i integration times from %i to %ims in steps of %ims for detector lines %i to %i (%s step(s) per %s second(s))\" %(int(steppingCount),int(integrationTime),int(integrationTime)*int(steppingCount)*int(steppingValue),int(steppingValue),int(fixedTop),int(fixedTop)+int(fixedHeight)+1,int(steppingSpeed)+1,int(fixedRhythm))\n elif steppingType==\"AOTF_FREQ\":\n observationText = \"AOTF frequency stepping (miniscan): %i frequencies from %i to %ikHz in steps of %ikHz (%s step(s) per %s second(s))\" %(int(steppingCount),int(aotfFrequency)/1000,int(aotfFrequency)/1000+int(steppingCount)*np.round(int(steppingValue)*8e4/2**32),np.round(int(steppingValue)*8e4/2**32),int(steppingSpeed)+1,int(fixedRhythm))\n elif nSubdomains == 0:\n print(\"Error: no subdomains\")\n stop()\n else:\n observationText = \"Science: orders \" \n integrationTimes = []\n for sciencePointer in sciencePointers[0:nSubdomains]:\n aotfOrder = findCopRowData(channel,copTableDict, [\"aotfPointer\"],sciencePointer)\n integrationTimes.append(findCopRowData(channel,copTableDict, [\"integrationTime\"],sciencePointer))\n observationText += \"#%s, \" %([int(aotfOrder) if aotfOrder != \"0\" else \"dark\"][0])\n if integrationTimes.count(integrationTimes[0]) == len(integrationTimes):\n observationText += \"with %ius integration time \" %int(integrationTimes[0])\n else:\n observationText += \"with variable integration times \"\n observationText += \"(%i orders per %i second(s) for detector lines %i to %i)\" %(nSubdomains,int(fixedRhythm),int(fixedTop),int(fixedTop)+int(fixedHeight)+1)\n if not silent: print(observationText)\n\n elif channel == \"uvis\":\n num_acqs, flag_register, binning_size, comments = findCopRowData(channel,copTableDict, [\"num_acqs\", \"flag_register\", \"binning_size\", \"comments\"],copRow)\n# observationText = \"%s -NumAcqsBetweenDarks=%s -FlagRegister=%s -BinningSize=%s\" %(comments, num_acqs, flag_register, binning_size)\n observationText = \"%s, Binning=%s\" %(comments.replace(\" - \",\",\").replace(\" -\",\",\" ).replace(\"-\",\", \"), binning_size)\n \n return observationText\n\n\n\n\n\ndef getObsParameters(observation_name, dictionary):\n if observation_name in list(dictionary.keys()):\n orders_out, inttime_out, rhythm_out, rows_out, channel_code = dictionary[observation_name]\n return sorted(orders_out), inttime_out, rhythm_out, rows_out, channel_code\n else:\n return [-999], -1, -1, -1, -1\n \n \n\ndef calcExecutionTime(number_accumulations, window_height, integration_time): #real number of rows (16, 20, 24), int time in milliseconds\n return ((number_accumulations+1.0) * ((integration_time * 1000.0) + 71.0 + 320.0 * window_height + 1000.0) + 337.0) / 1000.0\n\n\ndef uniqueDiffractionOrders(aotf_order_list):\n tuples = [tuple(i) for i in aotf_order_list]\n uniqueTuples = set(tuples)\n unique_orders = [list(i) for i in uniqueTuples]\n return unique_orders\n\n\n\n\"\"\"return dictionary containing COP rows and description of measurement given input dictionary containing observation parameters\"\"\"\ndef getCopRows(observationName, observationDict, copTableDict, copTableCombinationDict, centreDetectorLines, silent=False):\n\n diffractionOrders, integrationTime, rhythm, windowHeight, channelCode = getObsParameters(observationName, observationDict)\n if diffractionOrders[0] == -999:\n print(\"Observation name %s not found in dictionary\" %(observationName))\n return {}, [], -1, -1, -1, -1\n\n\n detectorCentreLine = centreDetectorLines[channelCode]\n copTableCombinations = copTableCombinationDict[channelCode]\n\n if channelCode in [0,1]:\n channel = {0:\"so\", 1:\"lno\"}[channelCode]\n else:\n print(\"Error: channel %i not defined\" %channelCode)\n\n\n \"\"\"do fixed table first\"\"\"\n fixedCopRow = findFixedCopRow(channel, copTableDict, detectorCentreLine, windowHeight, rhythm, silent=silent)\n if fixedCopRow == -999:\n print(\"Error: incorrect fixed row\")\n stop()\n \n \n \"\"\"then do subdomain table\"\"\"\n scienceCopRow = -999\n \n if type(diffractionOrders[0]) != int:\n if \"COP#\" in diffractionOrders[0]:\n scienceCopRow = int(diffractionOrders[0].split(\"#\")[1])\n# print(\"Manual mode: COP row %i\" %(scienceCopRow))\n else:\n print(\"Error: COP rows must be integers or must be specified manually e.g. COP#1\")\n stop()\n else:\n #look in cop tables for correct subdomain rows\n for indexCop, diffractionOrdersCop, integrationTimeCop, rhythmCop, windowHeightCop in zip(copTableCombinations[\"index\"], copTableCombinations[\"orders\"], copTableCombinations[\"integrationTime\"], copTableCombinations[\"rhythm\"], copTableCombinations[\"windowHeight\"]):\n if diffractionOrders == diffractionOrdersCop:\n if integrationTime == integrationTimeCop:\n if rhythm == rhythmCop:\n if windowHeight == windowHeightCop:\n scienceCopRow = indexCop\n \n \n if scienceCopRow < 0:\n print(\"Error: COP row 1 not found\")\n print(diffractionOrders)\n stop()\n \n #find description of observation\n description = getObservationDescription(channel, copTableDict, fixedCopRow, scienceCopRow, silent=True)\n outputDict = {\"scienceCopRow\":scienceCopRow, \"fixedCopRow\":fixedCopRow, \"copRowDescription\":description}\n \n return outputDict, diffractionOrders, integrationTime, rhythm, windowHeight, channelCode\n\n\n\n\n\n ","sub_path":"nomad_obs/cop_rows/cop_table_functions.py","file_name":"cop_table_functions.py","file_ext":"py","file_size_in_byte":23493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"441483551","text":"\"\"\"Configuration file.\"\"\"\n\n\nCONFIG_VERSION = \"0.7.0\" \n\n\n# ======================================================================================================================\n# ROBOT HARDWARE PROPERTIES\n# ======================================================================================================================\nCORK_TO_CAMERA_DISTANCE_X = 0 # # distance between camera and cork on the robot, X axis, relative, mm\nCORK_TO_CAMERA_DISTANCE_Y = 30 # distance between camera and cork on the robot, Y axis, relative, mm\n\n\n# ======================================================================================================================\n# NAVIGATION ROUTING SETTINGS\n# ======================================================================================================================\n#KP = 0.2 # for -10000 : *0.55 wheels turning degrees multiplier\n#KI = 0.0092 # fpr rpm-1000 : *0.91\nKP = {0.175: 0.2, 0.7: 0.11000000000000001, -0.175: 0.19, -0.7: 0.0360000000000001, 0: 0.2} \nKI = {0.175: 0.0092, 0.7: 0.008372000000000001, -0.175: 0.0092, -0.7: 0.000000001, 0: 0.092} \n\nMANEUVERS_FREQUENCY = 1 # seconds\n# max distance in mm-s of robot's deviation from planned moving vector\n# if dev. is bigger than this - robot will turn to it's planned moving vector\nCOURSE_SIDE_DEVIATION_MAX = 50 # max allowed robot's deviation from course im mm-s (threshold)\n# distance to stop in mm-s between robot and path ending point\n# (its a good idea to keep this value greater than allowed course deviation)\nWINDOW = float(\"inf\") # anyway, the integral is used for only some hundreds of time\n# AB moving vector used as A----A1--B, where A1 is point when robot starts moving to next point.\n# this determines A1-B distance\nMANEUVER_START_DISTANCE = {False:4000, True:4000} \nUSE_SPEED_LIMIT = True # when distance to target point is less than specified in the config\nDECREASE_SPEED_TRESHOLD = 5000 # millimeters\nSUM_ANGLES_HISTORY_MAX = 1000 # max value and min -value of sum(angles_history), should be positive here, in config\n# distance between sides of spiral robot movements, expected to be equal to working area width, may be any positive val\nSPIRAL_SIDES_INTERVAL = {False: 333, True: 3000} \nFIELD_REDUCE_SIZE = 200 # cut field's each side for this value, mms\nPREV_CUR_POINT_MIN_DIST = 100 # pass by cur points dist between them and prev point is lesser than this, mms\nFILTER_MAX_DIST = 5000 # maximum allowable distance between consecutive points (in millimeters)\nFILTER_MIN_DIST = 600 # minimum allowable distance between consecutive points (in millimeters)\n\n#Field creation with main\nUSE_EMERGENCY_FIELD_GENERATION = False # allows to generate field by moving forward for a given duration\nEMERGENCY_FIELD_SIZE = 45000 # mms; side of the area that will be created if emergency field creation is enabled\nEMERGENCY_MOVING_TIME = 10 # seconds of moving forward for vector getting\n\n#Continue mode\nCONTINUE_PREVIOUS_PATH = False\nPREVIOUS_PATH_POINTS_FILE = \"path_points.dat\"\nPREVIOUS_PATH_INDEX_FILE = \"path_index.txt\"\n\n#Cyril covid\nFAR_TARGET_THRESHOLD = {0.175: 25000, 0.7: 25000, -0.175: 25000, -0.7: 25000} # the output of the KP KI is boost if the target is far than this threshold\nFAR_TARGET_GAIN = {0.175: 1.15, 0.7: 1.15, -0.175: 1.15, -0.7: 1.15} # the output of the KP KI is boost by this muliplier if the target is far than the threshold\nCLOSE_TARGET_THRESHOLD = {0.175: 5000, 0.7: 5000, -0.175: 5000, -0.7: 5000} # the output of the KP KI is managed if the target is less than this threshold\nSMALL_RAW_ANGLE_SQUARE_THRESHOLD = {0.175: 100, 0.7: 100, -0.175: 100, -0.7: 100} # the output of the KP KI is calm by a muliplier if the raw angle is less than the threshold\nSMALL_RAW_ANGLE_SQUARE_GAIN = {0.175: 0.9, 0.7: 1, -0.175: 0.9, -0.7: 1} # the output of the KP KI is calm by this muliplier if the raw angle is less than the threshold\nBIG_RAW_ANGLE_SQUARE_THRESHOLD = {0.175: 625, 0.7: 625, -0.175: 625, -0.7: 625} # the output of the KP KI is boost by a muliplier if the raw angle is more than the threshold\nBIG_RAW_ANGLE_SQUARE_GAIN = {0.175: 1.35, 0.7: 1.35, -0.175: 1.35, -0.7: 1.35} # the output of the KP KI is boost by this muliplier if the raw angle is more than the threshold\n#OPEN_LOOP_TF_AMPLITUDES = [5, 5, 5*12/14, 5*12/17, 5*12/20, 5*12/23] # 2500 Sinus angle range when the servo system is in open loop\nOPEN_LOOP_TF_AMPLITUDES = [5*9/9, 5*9/13, 5*9/24, 5*9/28, 5*9/34, 5*9/40] # 10000 Sinus angle range when the servo system is in open loop\nOPEN_LOOP_TF_MAX_SAMPLES = [5, 7, 10, 15, 20, 40] #Sinus sampling range when the servo system is in open loop\nOPEN_LOOP_TF_FREQUENCIES = [1/5, 1/7, 1/10, 1/15, 1/20, 1/40] # Sinus frequency range when the servo system is in open loop\nOPEN_LOOP_FLAT = 9 # waiting time between two stimuli\nOPEN_LOOP_TF_MODE = True # mode enable a sinus angle drive on the robot \nSTRAIGHT_DIRECTION_INTEGRAL_DURATION = 10\nORIGIN_AVERAGE_SAMPLES = 5\nGPS_CLOCK_JITTER = 0.050\nPURSUIT_LIMIT = 3000 # length given in mm : at -2500rpm the deviation get correct after 3 meter path\n\nWHEELS_STRAIGHT_CHANGE_DIRECTION_OF_TRAVEL = True\n\n# ======================================================================================================================\n# PATH SETTINGS\n# ======================================================================================================================\n\n#Only one of the following three parameters must be true\nTRADITIONAL_PATH = True #Snail path\nBEZIER_CORNER_PATH = False #Snail path and use of bezier curve for turns\nFORWARD_BACKWARD_PATH = False #Path where the robot goes straight in extraction then reverses without extraction ....\n\n#This params work only if TRADITIONAL_PATH or BEZIER_CORNER_PATH are true. \nADD_FORWARD_BACKWARD_TO_END_PATH = True #Adds the path FORWARD_BACKWARD to complete the missing center.\n\n#This params work only if BEZIER_CORNER_PATH are true.\nNUMBER_OF_BEZIER_POINT = 10 #Allows to determine the number of points put in the bezier turn.\n\nTWO_POINTS_FOR_CREATE_FIELD = False\n\n# ======================================================================================================================\n# NAVIGATION TEST MODE SETTINGS\n# ======================================================================================================================\n\nNAVIGATION_TEST_MODE = False\nQUEUE_NAVIGATION_TEST_MODE = \"/queue_test_nav\"\nPOINT_A = [[46.1578135, -1.1341983], -0.175]\nPOINT_B = [[46.1574592, -1.1350758], -0.175]\n\n# ======================================================================================================================\n# EXTRACTION SETTINGS\n# ======================================================================================================================\nEXTRACTION_DEFAULT_METHOD = \"single_center_drop\" # or \"five_drops_near_center\"\nADDITIONAL_EXTRACTIONS_DISTANCE_X = 20 # mm\nADDITIONAL_EXTRACTIONS_DISTANCE_Y = 20 # mm\nAVOID_CORK_VIEW_OBSCURING = True # is True: adds offsets to control points to make a plant to be at the top half of the undistorted zone\nEXTRACTIONS_FULL_CYCLES = 2 # count of full extraction loops called after periphery NN detection (should be >= 1)\nSEEK_DELTA_DISTANCE = 25 # mm; if weed is lost after tuning/getting closer - we do 3 shifts for that value (down, left, right) and trying to find it\nMYOPIA_PATCH = True\n\n# ======================================================================================================================\n# PATHS SETTINGS\n# ======================================================================================================================\nINPUT_GPS_FIELD_FILE = \"field.txt\"\nOUTPUT_GPS_HISTORY_FILE = \"gps_history.txt\"\nDARKNET_LIB_DIR_PATH = \"/home/violette/field/darknet/\"\n\n# ======================================================================================================================\n# VESC SETTINGS\n# ======================================================================================================================\nVESC_PORT = \"/dev/ttyACM0\"\nVESC_BAUDRATE = 115200\nVESC_RPM_UI = -11500\nVESC_RPM_SLOW = -2500\nVESC_RPM_FAST = -10000 \nVESC_RPM_AUDIT = -10000\nVESC_MOVING_TIME = float(\"inf\")\nVESC_ALIVE_FREQ = 0.5 # freq of sending \"keep working\" signal to engines when moving\nVESC_CHECK_FREQ = 0.001 # freq of checking need to stop\nSTEP_FORWARD_TIME = 1 # step after extraction loops are done\nSTEP_FORWARD_RPM = -2000 # # step after extraction loops are done #-2500 à remettre\nFAST_TO_SLOW_RPM = 2500\nFAST_TO_SLOW_TIME = 5\n\nSI_SPEED_FWD = 0.175\nSI_SPEED_REV = -0.7\nMULTIPLIER_SI_SPEED_TO_RPM = -14285\n\n# ======================================================================================================================\n# GPS SETTINGS\n# ======================================================================================================================\nGPS_PORT = \"/dev/ttyTHS1\"\nGPS_BAUDRATE = 19200 \nGPS_POSITIONS_TO_KEEP = 1000\nNO_GPS_TIMEOUT = 15\nGPS_CHECK_IN_DEGRADED_MODE = 30 #Check if gps returned every GPS_CHECK_IN_DEGRADED_MODE navigation cycle.\n\n# ======================================================================================================================\n# SMOOTHIE SETTINGS\n# ======================================================================================================================\nSMOOTHIE_HOST = \"/dev/ttyACM1\" # smoothie's ip address for telnet or port for usb serial connector\nSMOOTHIE_BAUDRATE = 115200\nSMOOTHIE_BACKEND = 2 # 1 = telnet, 2 = serial\n\nX_MIN = 0\nX_MAX = 450 \nX_F_MIN = 0\nX_F_MAX = 20000\nX_COEFFICIENT_TO_MM = 1\n\nY_MIN = 0\nY_MAX = 220 \nY_F_MIN = 0\nY_F_MAX = 6000\nY_COEFFICIENT_TO_MM = 1\n\n# smoothie movement separation update\nALLOW_SEPARATE_XY_MOVEMENT = True\nXY_SEP_MOV_MAX_RATIO_THRESHOLD = 1\n\nZ_MIN = -float(\"inf\")\nZ_MAX = float(\"inf\")\nZ_F_MIN = 1\nZ_F_MAX = 2000 \nEXTRACTION_Z = 40 # drill version value\nZ_F_EXTRACTION_UP = 1500 \nZ_F_EXTRACTION_DOWN = 1850 \nZ_COEFFICIENT_TO_MM = 1 # not used yet\n\n# CALIBRATION\nUSE_X_AXIS_CALIBRATION = True\nUSE_Y_AXIS_CALIBRATION = True\nUSE_Z_AXIS_CALIBRATION = True\nUSE_A_AXIS_CALIBRATION = False\nUSE_B_AXIS_CALIBRATION = False\nUSE_C_AXIS_CALIBRATION = False\n\nX_AXIS_CALIBRATION_TO_MAX = False\nY_AXIS_CALIBRATION_TO_MAX = False\nZ_AXIS_CALIBRATION_TO_MAX = False \nA_AXIS_CALIBRATION_TO_MAX = None\nB_AXIS_CALIBRATION_TO_MAX = None\nC_AXIS_CALIBRATION_TO_MAX = None\n\nCALIBRATION_DISTANCE = 1000 # should be always positive, sign will be auto-defined using *_AXIS_CALIBRATION_TO_MAX flag key\nAFTER_CALIBRATION_AXIS_OFFSET = 0\nCORK_CALIBRATION_MIN_TIME = 3600 \n\n# NAVIGATION\nA_MIN = -5 \nA_MAX = 5 \nB_MIN = -float(\"inf\")\nB_MAX = float(\"inf\")\nC_MIN = -float(\"inf\")\nC_MAX = float(\"inf\")\n\nA_F_MIN = 1\nA_F_MAX = 4000 #default value 4000\nA_COEFFICIENT_TO_MM = 1\nA_F_UI = 1000 #default value 1000\n\nB_F_MIN = 1\nB_COEFFICIENT_TO_MM = 1\nB_F_MAX = 4000\n\nC_F_MIN = 1\nC_F_MAX = 1000\nC_COEFFICIENT_TO_MM = 1\n\nA_ONE_DEGREE_IN_SMOOTHIE = 2 # A axis\nA_DEGREES_PER_SECOND = 5 # A axis\nNAV_TURN_WHEELS_CENTER = 0\n\n# ======================================================================================================================\n# DETECTION SETTINGS\n# ======================================================================================================================\n\nALLOW_PRECISE_RESCAN = True\nALLOW_PRECISE_SINGLE_SCAN_BEFORE_PDZ = False\nEXTRACTION_TUNING_MAX_COUNT = 3 # Number of try to get closer to a plant\n\n# ======================================================================================================================\n# YOLO PERIPHERY NETWORK SETTINGS\n# ======================================================================================================================\nPERIPHERY_CONFIDENCE_THRESHOLD = 0.1 # Confidence threshold\nPERIPHERY_HIER_THRESHOLD = 0.5 # works only in darknet wrapper\nPERIPHERY_NMS_THRESHOLD = 0.4 # Non-maximum suppression threshold\nPERIPHERY_INPUT_SIZE = (416, 416)\nPERIPHERY_CONFIG_FILE = \"yolo/Y0016_416.cfg\"\nPERIPHERY_WEIGHTS_FILE = \"yolo/Y0016.weights\"\nPERIPHERY_CLASSES_FILE = \"yolo/Y0016.names\"\nPERIPHERY_DNN_BACKEND = 5 # cv.dnn: DNN_BACKEND_CUDA = 5; DNN_BACKEND_OPENCV = 3\nPERIPHERY_DNN_TARGET = 6 # cv.dnn: DNN_TARGET_CUDA = 6; DNN_TARGET_CUDA_FP16 = 7; DNN_TARGET_CPU = 0\nPERIPHERY_WRAPPER = 1 # 1 = darknet, 2 = opencv from darknet\nPERIPHERY_DATA_FILE = \"yolo/Y0016.data\" \n\n# ======================================================================================================================\n# YOLO PRECISE NETWORK SETTINGS\n# ======================================================================================================================\nPRECISE_CONFIDENCE_THRESHOLD = 0.1 # Confidence threshold\nPRECISE_HIER_THRESHOLD = 0.5 # works only in darknet wrapper\nPRECISE_NMS_THRESHOLD = 0.4 # Non-maximum suppression threshold\nPRECISE_INPUT_SIZE = (832, 832)\nPRECISE_CONFIG_FILE = \"yolo/Y0016_832.cfg\"\nPRECISE_WEIGHTS_FILE = \"yolo/Y0016.weights\"\nPRECISE_CLASSES_FILE = \"yolo/Y0016.names\"\nPRECISE_DATA_FILE = \"yolo/Y0016.data\" \nPRECISE_DNN_BACKEND = 5 # cv.dnn: DNN_BACKEND_CUDA = 5; DNN_BACKEND_OPENCV = 3\nPRECISE_DNN_TARGET = 6 # cv.dnn: DNN_TARGET_CUDA = 6; DNN_TARGET_CUDA_FP16 = 7; DNN_TARGET_CPU = 0\nPRECISE_WRAPPER = 1 # 1 = darknet, 2 = opencv from darknet\n\n\n# ======================================================================================================================\n# CAMERA SETTINGS\n# ======================================================================================================================\nCAMERA_W = 3280\nCAMERA_H = 2464\nAPPLY_IMAGE_CROPPING = True\nCROP_W_FROM = 498 \nCROP_W_TO = 2498 \nCROP_H_FROM = 160 \nCROP_H_TO = 1660 \nCAMERA_FRAMERATE = 8\nCAMERA_FLIP_METHOD = 0\nSCENE_CENTER_X = 1000 # 1576 for uncropped\nSCENE_CENTER_Y = 980 # 1104 for uncropped\nONE_MM_IN_PX = 5.2\nISP_DIGITAL_GAIN_RANGE_FROM = 4\nISP_DIGITAL_GAIN_RANGE_TO = 4\nGAIN_RANGE_FROM = 4\nGAIN_RANGE_TO = 4\nEXPOSURE_TIME_RANGE_FROM = 660000\nEXPOSURE_TIME_RANGE_TO = 660000\nAE_LOCK = True\nCV_APPLY_ROTATION = False\nCV_ROTATE_CODE = 2\nAPPLY_THREAD_BUFF_CLEANING = True\nBUFF_CLEANING_DELAY = 0 # seconds of waiting before frame reading; should be positive or zero; set to 0 if thread cleaning is used\n#WORKING_ZONE_POLY_POINTS = [[1000, 1145], [230, 1080], [245, 755], [340, 400], [640, 315], [1000, 270], [1360, 315], [1660, 400], [1755, 755], [1770, 1080]]\nUNDISTORTED_ZONE_RADIUS = 300\nDELAY_BEFORE_2ND_SCAN = 0.3 # delay in seconds after robot stop and before second scan (M=1)\nVIEW_ZONE_POLY_POINTS = [[387, 618], [439, 510], [556, 433], [670, 375], [808, 319], [982, 285], [1143, 279], [1293, 294], [1501, 339], [1635, 395], [1766, 473], [1816, 550], [1867, 637], [1881, 675], [1919, 795], [1942, 926], [1959, 1066], [1964, 1217], [1957, 1321], [1949, 1393], [1874, 1425], [1802, 1457], [1692, 1498], [1555, 1537], [1410, 1567], [1219, 1589], [1081, 1590], [944, 1590], [804, 1575], [679, 1552], [569, 1525], [423, 1475], [330, 1431], [277, 1399], [273, 1289], [279, 1131], [297, 976], [343, 780]]\n#WORKING_ZONE_POLY_POINTS = [[1000, 1145], [230, 1080], [245, 755], [340, 400], [640, 315], [1000, 270], [1360, 315], [1660, 400], [1755, 755], [1770, 1080]] \nWORKING_ZONE_POLY_POINTS = [[1000, 1050], [30, 1080], [45, 755], [40, 300], [640, 115], [1000, 70], [1360, 115], [1860, 300], [1955, 755], [1970, 1080]]\n# ======================================================================================================================\n# APP SETTINGS\n# ======================================================================================================================\nSAVE_DEBUG_IMAGES = False\nDEBUG_IMAGES_PATH = \"debug_images/\"\nALLOW_GATHERING = False\n\nROBOT_SN = \"SN003\" \nUI_LANGUAGE = \"en\"\nSLIDER_CREATE_FIELD_MIN = 15\nSLIDER_CREATE_FIELD_MAX = 150\nSLIDER_CREATE_FIELD_DEFAULT_VALUE = 25\nSLIDER_CREATE_FIELD_STEP = 1\n\nFRAME_SHOW = True\nSHARED_MEMORY_NAME_DETECTED_FRAME = \"/detected_frame\"\n\nAUDIT_MODE = False\nAUDIT_DIVIDER = 6\nAUDIT_OUTPUT_FILE = \"audit.txt\"\n\nSLOW_FAST_MODE = False\nSLOW_MODE_MIN_TIME = 3 # seconds\n\nVERBOSE = False\nLOG_ROOT_DIR = \"logs/\"\nSTATISTICS_OUTPUT_FILE = \"statistics.txt\"\nDATACOLLECTOR_SAVE_FILE = \"datacollection_save.dat\"\nDATA_GATHERING_DIR = \"gathered_data/\"\nLAST_ANGLE_WHEELS_FILE = \"last_angle_wheels.txt\"\nFILES_TO_KEEP_COUNT = 600\n\nQUEUE_NAME_UI_MAIN = \"/queue_ui_main\"\nQUEUE_NAME_UI_NOTIFICATION = \"/queue_ui_notification\"\n\nCONTINUOUS_INFORMATION_SENDING = True\nALIVE_SENDING_TIMEOUT = 1\n\n# ======================================================================================================================\n# DETECTION MANAGER SETTINGS\n# ======================================================================================================================\n\nCAMERA_POSITIONS = [(220, 0)] # smoothie global coordinates to take photos from for forming plants list. Format is (x, y)\nPDZ_DISTANCES = [{\"top\": 1000, \"bot\": 1000, \"left\": 1000, \"right\": 1000}] # precice detection zone sizes. At each camera position scan only plants inside this zone is added to extraction list\n#CAMERA_POSITIONS = [(150, 0), (300,0)] # smoothie global coordinates to take photos from for forming plants list. Format is (x, y)\n#PDZ_DISTANCES = [{\"top\": 750, \"bot\": 750, \"left\": 1000, \"right\": 350}, {\"top\": 750, \"bot\": 750, \"left\": 450, \"right\": 1000}] # precice detection zone sizes. At each camera position scan only plants inside this zone is added to extraction list\n# values are px count from scene center to. Format is {\"top\": int, \"bot\": int, \"left\": int, \"right\": int}\n\n\n# ======================================================================================================================\n# EXTRACTION MANAGER SETTINGS\n# ======================================================================================================================\n\nEXTRACTION_PATTERNS_OFFSET_MM = 20\nEXTRACTION_MAP_CELL_SIZE_MM = 10\nEXTRACTION_TRIES_PER_PLANT = 3 # defines how many times robot will try to extract plant or plants group in undist. zone\n# should be >= 1; expected value that equal to extraction strategies count so each of them can be applied\n\nAVOID_CORK_VIEW_OBSCURING_DIST_X = 10 # mm; offset size to \"remove\" corkscrew tube from camera-plant view\n# mm; offset size to \"remove\" corkscrew tube from camera-plant view, should be negative to move cork down and free view\nAVOID_CORK_VIEW_OBSCURING_DIST_Y = -10\n\nALLOW_DELTA_SEEKING = True # will try to move over supposed plant position if plant wasn't detected during approaching\n# False: seek over coordinates updated by cork obscuring patch; True: seek over original coordinates\nDELTA_SEEKING_IGNORE_OBSCURING = False\n\nDEBUG_MATRIX_FILE = False\nFILTER_EXTRACTED_PLANTS = True\nFILTER_EXT_PLANTS_TRIGGER_DIST = 25 # px; trigger distance for previous option key\n\n# ======================================================================================================================\n# PREDICTION SETTINGS\n# ======================================================================================================================\nZONE_THRESHOLD_DEGREE = [(436,5),(697,7),(796,17),(849,15),(953,6)]\n\n# ======================================================================================================================\n# NTRIP CLIENT SETTINGS\n# ======================================================================================================================\nNTRIP = False \nNTRIP_RESTART_TIMEOUT = 60\nNTRIP_USER = \"centipede\"\nNTRIP_PASSWORD = \"centipede\"\nNTRIP_CASTER = \"caster.centipede.fr\"\nNTRIP_PORT = 2101\nNTRIP_MOUNTPOINT = \"LIENSS\"\n\nNTRIP_OUTPUT_PORT = \"/dev/ttyACM1\"\nNTRIP_OUTPUT_BAUDRATE = 38400\n\nLEARN_GO_STRAIGHT = True\nLEARN_GO_STRAIGHT_UI = False\nMIN_PERPENDICULAR_GO_STRAIGHT = 100 # in mm\nVALUES_LEARN_GO_STRAIGHT = 40\nLEARN_GO_STRAIGHT_FILE = \"learn_go_straight.txt\"","sub_path":"config/config_v17_defaults.py","file_name":"config_v17_defaults.py","file_ext":"py","file_size_in_byte":19787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"318982104","text":"# Labs/Exceptions/DateBook.py\n#\n\nimport datetime\nimport time\n\nclass DateBook:\n\n def __init__(self, monthDate, events):\n self.monthDate = monthDate\n self.events = events\n self.__viewStartDate = self.__getFirstViewDate()\n self.__viewEndDate = self.__getLastViewDate()\n\n @property\n def events(self):\n return self.__events\n\n @events.setter\n def events(self, value):\n self.__events = value\n\n @events.deleter\n def events(self):\n del self.__events\n\n @property\n def monthDate(self):\n return self.__monthDate\n\n @monthDate.setter\n def monthDate(self, value):\n self.__monthDate = value\n\n @monthDate.deleter\n def monthDate(self):\n del self.__monthDate\n\n def __getFirstViewDate(self):\n\n # Determine the first date to display. Get the first day of the month, and then move backward\n # to the Sunday.\n\n monthStartDate = datetime.date(self.monthDate.year, self.monthDate.month, 1)\n return monthStartDate - datetime.timedelta(monthStartDate.isoweekday() % 7)\n\n def __getLastViewDate(self):\n\n # Find the last day of the month to display by getting the first day of the next month and backing up one day.\n\n month = self.monthDate.month % 12 + 1;\n if (month == 1):\n year = self.monthDate.year + 1\n else:\n year = self.monthDate.year\n\n monthEndDate = datetime.date(year, month, 1) - datetime.timedelta(1)\n\n # Get the last date to display.\n\n return monthEndDate + datetime.timedelta(6 - (monthEndDate.isoweekday() % 7))\n\n def renderCalendarView(self):\n\n # Add all of the days in the view to a list.\n\n currentDate = self.__viewStartDate\n today = datetime.date.today()\n oneDay = datetime.timedelta(1)\n\n print(\"\\033[0;37m\")\n\n while (currentDate <= self.__viewEndDate):\n for d in range(0, 7):\n if currentDate.month == self.monthDate.month and currentDate.day == 1:\n print(\"\\033[0m\", end=\"\")\n if currentDate == today:\n print(\"\\033[1m\", end=\"\")\n print(\"{:>2d}\".format(currentDate.day), end=\"\")\n if currentDate == today:\n print(\"\\033[0m\", end=\"\")\n if self.events.get(currentDate) != None and self.events.get(currentDate).date == currentDate:\n print(\"* \", end=\"\")\n else:\n print(\" \", end=\"\")\n currentDate = currentDate + oneDay\n if currentDate.month != self.monthDate.month and currentDate.day == 1:\n print(\"\\033[0;37m\", end=\"\")\n print(\"\")\n print(\"\\033[0m\")\n","sub_path":"Student_Files/Python/Labs/Exceptions/DateBook.py","file_name":"DateBook.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"404406818","text":"import Node\r\ndef selectionSort(list):\r\n '''selection sort algorithm\r\n\r\n selection sort algorithm for linked list with swaping pointer values\r\n '''\r\n currentpre=list.headNode() #node before current node\r\n current=currentpre.getNext() #current pionter of linked list\r\n\r\n #outer loop for selection sort\r\n while current!=None:\r\n minimum=current #selecting first node as minimum values node\r\n nextprev=current; #previous node for nextinner pointer\r\n beforesort=nextprev #previous not for the pointer with minimum value\r\n nextinner=current.getNext() #node for next inner loop of selection sort\r\n\r\n #inner loop of selection sort\r\n while nextinner!=None:\r\n\r\n if minimum.getData()>nextinner.getData(): #finding minimum value pointer\r\n beforesort=nextprev #setting values of pointer to minimum value pointer\r\n minimum=nextinner\r\n nextprev=nextinner\r\n nextinner=nextinner.getNext()\r\n\r\n\r\n #after the inner loop completion of cycle we will have all values in correnponding pointer\r\n #there are there condition of minimum value pointer\r\n #(i) current pointer is minimum value pointer in this case will do no swap\r\n #(ii) pointer pointed to minimum value pointer in this case if will be executed\r\n #(iii) pointer is some where else in the linked list in this case elif will be executed\r\n\r\n #case ii\r\n #pionter are next to each other in this we did not beforesort pointer because that is current pointer\r\n # and we did not next next pointer of current node here is code\r\n if current.getNext()==minimum :\r\n minimumNext=minimum.getNext() #pointer to next node pointed my minimum node\r\n currentpre.setNext(minimum) #nex pointer of pointer before the current node is to minimum node\r\n minimum.setNext(current) #set minimum next pointer of minimum node to current\r\n current.setNext(minimumNext) #set next pointer of current to next pointer pointed my my minimum pointer\r\n current=minimum #set current to minimum\r\n\r\n #case iii\r\n #in this case we need all four pointer we have created for swapping\r\n #i.e i) pre-pointer of current node ii)nex pointer of current node\r\n # iii)pre-pointer of sorted node iv) pointer pointed my sorted node\r\n #here is code for swapping\r\n elif current.getNext()!=minimum and current!=minimum:\r\n currentNext=current.getNext() #pointer pointed my the current node\r\n minimumNext=minimum.getNext() #pointer to next node pointed my minimum node\r\n currentpre.setNext(minimum) #set pre-current to minimum pointer\r\n minimum.setNext(currentNext) #set next pointer of minimum node to currentNext pointer\r\n beforesort.setNext(current) #setting pre pointer of sorted node to current pointer\r\n current.setNext(minimumNext) #current pointer next pointer set to next of minimumNext\r\n current=minimum #set current to minimum\r\n currentpre=current #set pre-current to current\r\n current=current.getNext() #set current to current ->next\r\n list.show()","sub_path":"AlgorithmsInPython/sorting algorithm with linked list/linkedSelectionSort.py","file_name":"linkedSelectionSort.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"262305929","text":"from futuquant import *\nimport pandas as pd\n#import TA-Lib\nimport talib\nimport sys\nfrom pymongo import MongoClient\nimport datetime\nimport math\nimport time\nimport re\nfrom datetime import date,timedelta\n# -*- coding: utf-8 -*-\n\nd_value_250_up=8\nd_value_250_down=-25 #250均线<-25\nd_value_1000=-10 #1000日均线<10\n\nyear_time=18*12*30*24*60*60\nmonth_time=30*24*60*60\nstock_time_close_250 = dict()\nstock_time_close_1000 = dict()\nstock_month_tick_count_250 = dict()\nstock_month_tick_count_1000 = dict()\n\nyear_stock_time_close_250 = dict()\nyear_stock_time_close_1000 = dict()\nyear_stock_tick_count_250 = dict()\nyear_stock_tick_count_1000 = dict()\n\n\nnew_year_price_ma250_rate = dict()\nnew_year_price_ma1000_rate = dict()\n\nnew_price_and_ma250_price = dict()\nnew_price_and_ma1000_price = dict()\n\ndef addzero(n): \n ''''' \n add 0 before 0-9 \n return 01-09 \n ''' \n nabs = abs(int(n)) \n if(nabs<10): \n return \"0\"+str(nabs) \n else: \n return nabs \n\ndef getyearandmonth(year,mon,n=0):\n global year_index\n #print(\"n:\",n)\n #now = datetime.now() \n #nextDay = now + timedelta(days = n*30)\n thisyear = int(year) \n thismon = int(mon) \n totalmon = thismon+n \n j = totalmon%12\n if(j==0):\n j=12\n year_index = year_index -1\n #print(\"year_index:\",year_index,\" j:\",j,\" n:\",n)\n j = addzero(j)\n #print(\"thisyear:\",thisyear,\" j:\",j)\n return (str(year_index),str(j))\n\ndef getseason(year,month,season=0):\n season_list = []\n #print \"before month:\",month\n if month%3 != 0:\n month = month - month%3\n print(\"after month:\",month)\n for cur in range(3*(season),3*(season+1)):\n cur_year,cur_month = getyearandmonth(year,month,cur+1)\n season_list.append(str(cur_year)+\"-\"+str(cur_month ))\n return season_list\n\ndef getyear(year,n_year=0):\n return str(year+n_year)\n\n\ndef print_guila_month_find_lowest_price_of_each_stock(stock_close_div,stock_close_div_begin_end,type):\n print(\"print_month_find_lowest_price_of_each_stock enter type:\",type)\n #for key,value in month_stock_close_div_begin_end.items():\n # print(\"month_stock_close_div_begin_end value:\",value,\" key:\",key)\n head = \"\"\n if type == 1:\n head = \"month_tick\"\n elif type == 2:\n head = \"year_tick\"\n\n for key,value in stock_close_div.items(): \n #print(\"print_month_find_lowest_price_of_each_stock value:\",value,\" key:\",key)\n sorted_dict = sorted(value.items(), key=lambda value:value[1])\n #print(\"print_month_find_lowest_price_of_each_stock sorted_dict:\",sorted_dict)\n print(\" ---------------------------------------------------------------time:\",key)\n current_div_count_best= 0\n current_div_count_better = 0\n current_div_count_worst = 0\n current_div_count_impossble = 0\n for key_name_rate_dict in sorted_dict:\n name = key_name_rate_dict[0]\n rate_info = key_name_rate_dict[1]\n if int(rate_info) > 7:\n current_div_count_best = current_div_count_best +1\n elif int(rate_info) >0 and int(rate_info) <7:\n current_div_count_better = current_div_count_better +1\n elif int(rate_info) <0 and int(rate_info) >-8:\n current_div_count_worst = current_div_count_worst +1\n elif int(rate_info) <= -8:\n current_div_count_impossble = current_div_count_impossble +1\n price = stock_close_div_begin_end[key][name]\n print(\"\",head,\" distribute current_div_count_best [7,~]:\",current_div_count_best,\" time:\",key)\n print(\"\",head,\" distribute current_div_count_better[0,7]:\",current_div_count_better,\" time:\",key)\n print(\"\",head,\" distribute current_div_count_worst:[-7,0]\",current_div_count_worst,\" time:\",key)\n print(\"\",head,\" distribute current_div_count_impossble[~,-7]:\",current_div_count_impossble,\" time:\",key)\n print(\"\",head,\" distribute-----------------------------\")\n\ndef print_month_find_lowest_price_of_each_stock(stock_close_div,stock_close_div_begin_end,type):\n print(\"print_month_find_lowest_price_of_each_stock enter type:\",type)\n #for key,value in month_stock_close_div_begin_end.items():\n # print(\"month_stock_close_div_begin_end value:\",value,\" key:\",key)\n head = \"\"\n if type == 1:\n head = \"month_tick\"\n elif type == 2:\n head = \"year_tick\"\n\n for key,value in stock_close_div.items(): \n #print(\"print_month_find_lowest_price_of_each_stock value:\",value,\" key:\",key)\n sorted_dict = sorted(value.items(), key=lambda value:value[1])\n #print(\"print_month_find_lowest_price_of_each_stock sorted_dict:\",sorted_dict)\n print(\" ------------------------------------------------------------------------------------------------------time:\",key)\n current_div_count_best= 0\n current_div_count_better = 0\n current_div_count_worst = 0\n current_div_count_impossble = 0\n count_num=0\n for key_name_rate_dict in sorted_dict:\n name = key_name_rate_dict[0]\n rate_info = key_name_rate_dict[1]\n rate_info = round(rate_info,2)\n if int(rate_info) > 7:\n current_div_count_best = current_div_count_best +1\n elif int(rate_info) >0 and int(rate_info) <7:\n current_div_count_better = current_div_count_better +1\n elif int(rate_info) <0 and int(rate_info) >-8:\n current_div_count_worst = current_div_count_worst +1\n elif int(rate_info) <= -8:\n current_div_count_impossble = current_div_count_impossble +1\n price = stock_close_div_begin_end[key][name]\n count_num = count_num +1\n print(\"\",head,\" tick_time:\",key,\" count:\",count_num,\" rate[begin-end]:\",rate_info,\" stock_name:\",name,\" price\",price)\n\nmonth_stock_close_div = dict()\nmonth_stock_close_div_begin_end = dict()\nyear_stock_close_div = dict()\nyear_stock_close_div_begin_end = dict()\n#month_stock_ranged_close_div = dict()\ndef month_find_lowest_price_of_each_stock(conn,code_stock_id,code_stock_name,start_time,end_time,cur_index,tick_time,stock_close_div,stock_close_div_begin_end,type):\n nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n head = \"code\"\n #print(\"cur_index:\",cur_index,\"---head:\",head,\" stock_info_each:\",stock_info_each,\" nowTime:\",nowTime,\" tick_time:\",tick_time)\n #code_stock_id = stock_info_each['code']#\"HK.00700\"\n #code_id = 'HK.00700'\n code_stock_id = code_stock_id.replace(\".\", \"\")\n #print(\"code_stock_id:\",code_stock_id)\n\n db = conn.stock_list\n time_value = re.compile(tick_time) #month\n #time_value = {\"$in\": [re.compile(\"2018-06\"), re.compile(\"2018-05\")]} #season\n #time_value = re.compile('2018') #year #{'$regex':tick_time}\n month_count = db[code_stock_id].find({\"time_key\":time_value},{\"time_key\":1,\"close\":1}).count()\n #print(\"month_count:\",month_count)\n if int(month_count) > 0 :\n stock_each = db[code_stock_id].find({\"time_key\":time_value},{\"time_key\":1,\"close\":1}).sort(\"time_key\")\n stock_each_list = list(stock_each[:])\n month_begin = stock_each_list[0][\"close\"]\n month_begin = round(month_begin,2)\n month_end = stock_each_list[month_count-1][\"close\"]\n month_end = round(month_end,2)\n month_div = 0\n if month_begin == month_begin and month_begin != 0:\n month_div = (month_end-month_begin)*100/month_begin\n #print(\"month_begin:\",month_begin,\" month_end:\",month_end,\" cacl div:\",month_div,\" code_stock_name:\",code_stock_name,\" time_value:\",time_value )\n #print(\"---------stock_each_list:\",stock_each_list)\n stock_each_ranged = db[code_stock_id].find({\"time_key\":time_value},{\"time_key\":1,\"close\":1}).sort(\"close\")\n stock_each_ranged_list = list(stock_each_ranged[:])\n month_begin_ranged = stock_each_ranged_list[0][\"close\"]\n month_end_ranged = stock_each_ranged_list[month_count-1][\"close\"]\n month_div_ranged =(month_end_ranged-month_begin_ranged)*100/month_begin_ranged\n #print(\"month_begin_ranged:\",month_begin_ranged,\" month_end_ranged:\",month_end_ranged,\" month_div_ranged:\", month_div_ranged)\n #print(\"---------stock_each_ranged_list:\",stock_each_ranged_list)\n #stock_name = code_stock_name#stock_info_each[\"stock_name\"]\n\n if tick_time in stock_close_div:\n if code_stock_name in stock_close_div[tick_time]:\n stock_close_div[tick_time].update({code_stock_name: month_div})\n else:\n stock_close_div[tick_time][code_stock_name] = month_div\n else:\n stock_close_div.update({tick_time:{code_stock_name: month_div}})\n\n start_price_end_price = \"month_start:\"+str(month_begin)+\" month_end:\"+str(month_end)\n if type==2:\n start_price_end_price = \"year_start:\"+str(month_begin)+\" year_end:\"+str(month_end)\n\n if tick_time in stock_close_div_begin_end:\n if code_stock_name in stock_close_div_begin_end[tick_time]:\n stock_close_div_begin_end[tick_time].update({code_stock_name: start_price_end_price})\n else:\n stock_close_div_begin_end[tick_time][code_stock_name] = start_price_end_price\n else:\n stock_close_div_begin_end.update({tick_time:{code_stock_name: start_price_end_price}})\n ##month_stock_ranged_close_div.update({stock_name:{tick_time: month_div_ranged}})\n '''\n else :\n if type ==1:\n print(\"not exist month_count:\",month_count,\" code:\",code_stock_id,\" tick_time:\",tick_time)\n elif type ==2:\n print(\"not exist year_count:\",month_count,\" code:\",code_stock_id,\" tick_time:\",tick_time)\n '''\n\n#db.stock_list.createIndex({\"time_key\":-1,\"close\":-1})\n\n\nif __name__ == '__main__':\n global year_index\n start_time= '1998-01-01'\n #end_time='2018-06-12'\n year_tick = 15\n month_tick = 12*year_tick\n if len(sys.argv) != 2:\n print(\"exit argv:\",sys.argv)\n sys.exit()\n if len(sys.argv) == 2:\n year = datetime.datetime.now().year\n month = datetime.datetime.now().month\n day = datetime.datetime.now().day\n end_time= str(year)+'-'+str(month)+'-'+str(day)\n start_time = str(year-year_tick)+'-'+str(month)+'-'+str(day)\n print(\"start_time:\",start_time,\" end_time:\",end_time)\n #quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n #get stock mongdb\n conn = MongoClient('127.0.0.1', 27017)\n db = conn.market\n db_zhishu_table_name = sys.argv[1]\n print(\"######db_zhishu_table_name:\",db_zhishu_table_name)\n stock_info_list = db[db_zhishu_table_name].find()\n #print(\"stock_info_list:\",stock_info_list)\n #-----------------month\n stock_list_data_pd = pd.DataFrame(list(stock_info_list))\n cur_index = 1\n for index,stock_info_each in stock_list_data_pd.iterrows():\n stock_name = stock_info_each[\"stock_name\"]\n code_stock_id = stock_info_each[\"code\"]\n print(\"***************************************************************cur_index:\",cur_index)\n print(\"stock_name:\",stock_name,\" code_stock_id:\",code_stock_id)\n #print (\"--month-----------month_tick:\",month_tick)\n year_index = year\n for cur_tick_time in range(0,month_tick):\n cur_year,cur_month = getyearandmonth(year,month,-cur_tick_time)\n tick_time = cur_year+\"-\"+cur_month\n #print(\"===========tick_time:\",tick_time)\n month_find_lowest_price_of_each_stock(conn,code_stock_id,stock_name,start_time,end_time,cur_index,tick_time,month_stock_close_div,month_stock_close_div_begin_end,1)\n #print (\"--year-----------year_tick:\",year_tick)\n year_index = year\n for cur_tick_time in range(0,year_tick):\n cur_year = getyear(year,-cur_tick_time)\n #year_index = year_index +1\n month_find_lowest_price_of_each_stock(conn,code_stock_id,stock_name,start_time,end_time,cur_index,cur_year,year_stock_close_div,year_stock_close_div_begin_end,2)\n cur_index = cur_index + 1\n\n #最近几年的没有年初到年末涨跌幅\n print_guila_month_find_lowest_price_of_each_stock(year_stock_close_div,year_stock_close_div_begin_end,2)\n print_guila_month_find_lowest_price_of_each_stock(month_stock_close_div,month_stock_close_div_begin_end,1)\n\n #最近几月的没有月初到月末涨跌幅\n print_month_find_lowest_price_of_each_stock(year_stock_close_div,year_stock_close_div_begin_end,2)\n print_month_find_lowest_price_of_each_stock(month_stock_close_div,month_stock_close_div_begin_end,1)\n\n\n print(\"-------cacl_end------\\n\")\n #quote_ctx.close()\n sys.exit()\n\n","sub_path":"src/year_spread/source/year_drop_range_spread.py","file_name":"year_drop_range_spread.py","file_ext":"py","file_size_in_byte":13256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"326633153","text":"import urllib.request,urllib.parse\nfrom bs4 import BeautifulSoup\n\nclass Header:\n mHeader = {\n \"User-Agent\" : \"Mozilla/5.0 (Windows NT 10.0; Win64; x64)\"\n }\n\nclass naver(Header):\n #sample https://sarch.naver.com/search.naver?&where=news&ie=utf8&query=%EB%B9%84%EB%A6%AC\n mUrl = \"http://search.naver.com/search.naver?\"\n mConn = None\n def httpConnet(self,word):\n params = {\n #\"sm\":\"tab_hty.top\",t\n \"where\":\"news\",\n \"ie\": \"utf8\",\n \"query\": word\n }\n params = urllib.parse.urlencode(params)\n try:\n Request = urllib.request.urlopen(self.mUrl+params)\n except:\n print(\"programe error\")\n exit(-1)\n return Request.read().decode(\"utf-8\")\n \n\n def getContext(self,str):\n soup = BeautifulSoup(str,\"html.parser\")\n dir = []\n for li in soup.find('ul', {'class':'type01'}).findAll('li'):\n link = li.find('dt')\n if link == None:\n continue\n link = link.find(\"a\")\n \n dir.append([link.get('href'),link.get(\"title\").replace(',',\" \")])\n return dir\n \n \n def getdata(self,word):\n data = self.httpConnet(word)\n dir = self.getContext(data)\n with open(word+\".csv\",'w') as f:\n for dir in dir:\n f.write(dir[0]+','+dir[1]+'\\n')\n\n \nclass News:\n object =None\n def __init__(self):\n pass\n\n def run(self):\n try:\n word = input(\"input : \")\n object = naver()\n object.getdata(word)\n except:\n print(\"rinechran@gmail.com\")\n exit(0)\n\n\ndef main():\n news = News()\n news.run()\n pass\n\nif __name__==\"__main__\":\n main()","sub_path":"naver_news.py","file_name":"naver_news.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"194904146","text":"from django.shortcuts import render, redirect\nfrom django.conf import settings\n\nfrom downtime.models import Period\n\ntry:\n from django.utils.deprecation import MiddlewareMixin\nexcept ImportError:\n MiddlewareMixin = object\n\n\nclass DowntimeMiddleware(MiddlewareMixin):\n def process_request(self, request):\n exempt_exact_urls = getattr(settings,\n 'DOWNTIME_EXEMPT_EXACT_URLS', None)\n if exempt_exact_urls:\n for url in exempt_exact_urls:\n if request.path == url:\n return None\n\n exempt_paths = getattr(settings, 'DOWNTIME_EXEMPT_PATHS', ('/admin',))\n for path in exempt_paths:\n if request.path.startswith(path):\n return None\n\n objects = Period.objects.is_down()\n\n if objects.count():\n # we are down.\n url_redirect = getattr(settings, 'DOWNTIME_URL_REDIRECT', None)\n if url_redirect:\n return redirect(url_redirect)\n else:\n return render(request, \"downtime/downtime.html\", status=503)\n","sub_path":"downtime/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"57021015","text":"\"\"\"FIXME: INCOMPLETE MODULE FOR MINECRAFT UTILITY REWRITE; DO NOT USE YET\n\nERROR CODES:\n 0: Cmnd success: User added or approved, or request sent\n-1: Benign error: Duplicate request which has been approved\n-2: Benign error: Duplicate request or approval\n-3:\n-4:\n-5:\n-6:\n-7: Malign error: Failed to access dbName or WhitelistFile\n-8: Malign error: User supplied invalid name\n-9: Malign error: Incomplete function (fault of developer)\n\"\"\"\n\nfrom collections import OrderedDict\nimport json\nfrom pathlib import Path\nfrom typing import Any, Dict, List, NewType, Type, Union\nfrom uuid import UUID\n\nimport requests\n\nfrom .embeds import minecraft_card, minecraft_suspension\nfrom ..exceptions import WhitelistError\nfrom ..grasslands import Peacock\n\nlog = Peacock()\n\n\ntype_entry_db: Type = NewType(\"DB Entry\", Dict[str, Union[bool, int, List[str], str]])\ntype_db: Type = NewType(\"Database\", List[type_entry_db])\n\n\n# The default profile for a new player being added to the database\n# (Do not use this for other stuff)\nPLAYERDEFAULT: type_entry_db = OrderedDict(\n [\n (\"name\", \"PLAYERNAME\"),\n (\"uuid\", \"00000000-0000-0000-0000-000000000000\"),\n (\"altname\", []),\n (\"discord\", 000000000000000000),\n (\"approved\", []),\n (\"submitted\", \"1970-01-01_00:00\"),\n (\"suspended\", 000),\n (\"operator\", 0),\n (\"notes\", []),\n ]\n)\n\n\ndef break_uid(uuid: str) -> str:\n \"\"\"Given an undashed UUID, break it into five fields.\"\"\"\n f = [hex(c)[2:] for c in UUID(uuid).fields]\n return \"-\".join(f[:3] + [f[3] + f[4], f[5]])\n\n\n# TODO: Implement\n# if ( # Yield each Entry if looking for something specific.\n# (pending is None or pending is bool(entry.get(\"approved\", [])))\n# and (\n# suspended is None\n# or (\n# suspended is True\n# and entry.get(\"suspended\", 0) not in (0, False, None)\n# )\n# or suspended is entry.get(\"suspended\", False)\n# )\n# ) or\n\n\ndef find(data: type_db, *params: str) -> List[type_entry_db]:\n out = []\n for entry in data:\n for p in params:\n if ( # Yield each Entry if any parameter...\n # ...Matches the Discord UUID.\n p == str(entry.get(\"discord\"))\n # ...Matches the Mojang UUID.\n or p.lower().replace(\"-\", \"\") == entry[\"uuid\"].lower().replace(\"-\", \"\")\n # ...Can be found in the Username History.\n or p.lower() in map(str.lower, entry[\"altname\"])\n ):\n out.append(entry)\n break\n return out\n\n\ndef id_from_name(uname_raw: str):\n \"\"\"Given a Minecraft Username, get its UUID.\"\"\"\n uname_low: str = uname_raw.lower()\n response = requests.get(\n \"https://api.mojang.com/users/profiles/minecraft/{}\".format(uname_low)\n )\n log.f(\"WLME_RESP\", str(response))\n if response.status_code == 200:\n return {\"code\": response.status_code, \"udat\": response.json()}\n else:\n return {\"code\": response.status_code}\n\n\nclass Interface:\n def __init__(self, client):\n self.client = client\n self.config = client.config\n self.ctx = None\n\n def __enter__(self) -> type_db:\n if self.ctx is not None:\n raise RuntimeError(\"Attempting to lock locked Whitelist.\")\n else:\n data: type_db = self.db_read()\n self.ctx = data\n return data\n\n def __exit__(self, exc_type, exc_value, traceback):\n if self.ctx is None:\n raise RuntimeError(\"Attempting to unlock unlocked Whitelist.\")\n else:\n self.db_write(self.ctx)\n self.ctx = None\n\n def cget(self, prop: str, default: Any = None) -> Any:\n \"\"\"Retrieve a value from the Configuration. Merely a shorthand.\"\"\"\n v = self.config.get(prop, default)\n return v\n\n @property\n def path_db(self) -> Path:\n return Path(self.cget(\"minecraftDB\", \"playerdb.json\"))\n\n @property\n def path_wl(self) -> Path:\n return Path(self.cget(\"minecraftWL\", \"whitelist.json\"))\n\n @property\n def path_op(self) -> Path:\n return Path(self.cget(\"minecraftOP\", \"ops.json\"))\n\n def db_read(self) -> type_db:\n try:\n with self.path_db.open(\"r\") as file_db:\n data: type_db = json.load(file_db, object_pairs_hook=OrderedDict)\n\n except OSError as e:\n # File does not exist: Pointless to continue.\n log.err(\"OSError on DB read: \" + str(e))\n raise WhitelistError(\"Cannot read PlayerDB file.\") from e\n\n return data\n\n def db_write(self, data):\n try:\n with self.path_db.open(\"w\") as file_db:\n # Save all the things.\n json.dump(data, file_db, indent=2)\n\n except OSError as e:\n # Cannot write file: Well this was all rather pointless.\n log.err(\"OSError on DB save: \" + str(e))\n raise WhitelistError(\"Cannot write PlayerDB file.\") from e\n\n def whitelist_rebuild(self, refreshall=False, refreshnet=False) -> int:\n \"\"\"Export the local database into the whitelist file itself. If Mojang\n ever changes the format of the server whitelist file, this is the\n function that will need to be updated.\n \"\"\"\n try:\n # Stage 0: Load the full database as ordered dicts, and the\n # whitelist as dicts.\n with self.path_db.open(\"r\") as file_db, self.path_wl.open(\"r\") as file_wl:\n data = json.load(file_db, object_pairs_hook=OrderedDict)\n if self.cget(\"minecraftStrictWL\", False):\n data_wl = []\n else:\n data_wl = json.load(file_wl)\n except OSError:\n # File does not exist: Pointless to continue.\n return 0\n data_op = [] # Op list is always strict.\n\n if refreshall:\n # Rebuild Index\n data_db = []\n # Stage 1: Make new DB.\n for applicant in data:\n # Stage 2: Find entries in old DB, import their stuff.\n entry_new = PLAYERDEFAULT.copy()\n entry_new.update(applicant)\n\n if refreshnet:\n # Stage 3, optional: Rebuild username history.\n name_history = requests.get(\n \"https://api.mojang.com/user/profiles/{}/names\".format(\n applicant[\"uuid\"].replace(\"-\", \"\")\n )\n )\n\n if name_history.status_code == 200:\n # Spy on their dark and shadowy past.\n entry_new.update(altname=[])\n for name in name_history.json():\n entry_new[\"altname\"].append(name[\"name\"])\n # Ensure the name is up to date.\n entry_new[\"name\"] = name[\"name\"]\n\n data_db.append(entry_new)\n with self.path_db.open(\"w\") as file_db:\n json.dump(data_db, file_db, indent=2)\n data = data_db\n\n for applicant in data:\n # Check everyone who has applied.\n app = next(\n (item for item in data_wl if item[\"uuid\"] == applicant[\"uuid\"]), False\n )\n # Is the applicant already whitelisted?\n if (\n app == False\n and len(applicant[\"approved\"]) > 0\n and not applicant[\"suspended\"]\n ):\n # Applicant is not whitelisted AND is approved AND is not\n # suspended, add them.\n data_wl.append({\"uuid\": applicant[\"uuid\"], \"name\": applicant[\"name\"]})\n elif app != False and applicant[\"suspended\"] and app in data_wl:\n # BadPersonAlert, remove them.\n data_wl.remove(app)\n\n # Is the applicant supposed to be an op?\n level = applicant.get(\"operator\", 0)\n applicant[\"operator\"] = level\n if level > 0:\n data_op.append(\n {\n \"uuid\": applicant[\"uuid\"],\n \"name\": applicant[\"name\"],\n \"level\": level,\n \"bypassesPlayerLimit\": False,\n }\n )\n\n log.f(\"wl+\", \"Refreshing Whitelist\")\n with self.path_op.open(\"w\") as file_op:\n json.dump(data_op, file_op, indent=2)\n with self.path_wl.open(\"w\") as file_wl:\n json.dump(data_wl, file_wl, indent=2)\n return 1\n\n\nclass Minecraft(object):\n def __init__(self, client):\n self.client = client\n self.config = client.config\n self.interface = Interface(client)\n\n def add_entry(self, entry: type_entry_db):\n raise NotImplementedError\n\n def get_entry(self, ident: str) -> List[type_entry_db]:\n raise NotImplementedError\n\n def edit(self, ident: str):\n \"\"\"Yield a search for Entries. Then pause with the Interface open, and\n wait until the Generator is resumed. Immediately after resume, the\n Interface will close, writing changes to the file.\n \"\"\"\n with self.interface as file:\n target = find(file, ident)\n yield target\n","sub_path":"petal/util/minecraft.py","file_name":"minecraft.py","file_ext":"py","file_size_in_byte":9328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"631638045","text":"# -*- coding: utf-8 -*-\n\n\n\"\"\"\nA Python interface for the Klout API.\n\nUse of PyKlout requires a Klout API key.\nYou can register and get a key at\n\n \n\n\nhttps://github.com/marcelcaraciolo/PyKlout\n\n\n\"\"\"\n\n\n__author__ = 'Marcel Caraciolo'\n__version__ = '0.1'\n\n\nimport urllib\nimport httplib\nimport json\nimport urllib2\n\nERROR_STATUS = {\n # \"200: \"OK: Success\", IS A GOOD STATUS\n 202: \"Accepted: Your request was accepted and the user was queued for processing.\",\n 401: \"Not Authorized: either you need to provide authentication credentials, or the credentials provided aren't valid.\",\n 403: \"Bad Request: your request is invalid, This is the status code returned if you've exceeded the rate limit or if you are over QPS.\",\n 404: \"Not Found: either you're requesting an invalid URI or the resource in question doesn't exist (ex: no such user in our system).\",\n 500: \"Internal Server Error: we did something wrong.\",\n 502: \"Bad Gateway: returned if Klout is down or being upgraded.\",\n 503: \"Service Unavailable: the Klout servers are up, but are overloaded with requests. Try again later.\",\n}\n\n\nclass KloutError(Exception):\n def __init__(self, code, msg):\n super(KloutError, self).__init__()\n self.code = code\n self.msg = msg\n\n def __str__(self):\n return repr(self)\n\n def __repr__(self):\n return '%i: %s' % (self.code, self.msg)\n\n\nclass Klout(object):\n '''\n Klout API Handler\n\n Parameters\n ----------\n api_key : string the Klout API Key.\n\n '''\n API_URL = 'api.klout.com'\n\n def __init__(self, api_key):\n self._api_key = api_key\n\n def _remove_empty_params(self, params):\n '''\n Remove all unused parameters\n\n Parameters\n ----------\n params: dict object\n A set of parameters key,value\n\n Returns\n --------\n The set of parameters as dict without empty parameters\n '''\n ret = {}\n for key in params:\n if not params[key] == None:\n ret[key] = params[key]\n\n return ret\n\n def make_api_call(self, url, query={}, body={}):\n '''\n Make the API Call to Klout\n\n Parameters\n ----------\n url: the url to call\n query: The GET parameters\n body: The POST parameters\n '''\n\n query = self._remove_empty_params(query)\n\n if 'key' not in query:\n query['key'] = self._api_key\n\n body = self._remove_empty_params(body)\n query_str = urllib.urlencode(query)\n body_str = urllib.urlencode(body)\n\n if len(query) > 0:\n if url.find('?') == -1:\n url = url + '?' + query_str\n else:\n url = url + '&' + query_str\n\n try:\n conn = httplib.HTTPConnection(self.API_URL)\n if body_str:\n conn.request('POST', url, body_str)\n else:\n conn.request('GET', url)\n resp = conn.getresponse()\n data = resp.read()\n data = json.loads(data)\n except httplib.HTTPException as err:\n msg = err.read() or ERROR_STATUS.get(err.code, err.message)\n raise KloutError(err.code, msg)\n except ValueError:\n if not data:\n msg = 'Empty response from Klout.'\n raise KloutError(200, msg)\n else:\n msg = 'Invalid response: %s' % data\n raise KloutError(503, msg)\n else:\n status = data.get(\"status\")\n if status in ERROR_STATUS:\n msg = ERROR_STATUS.get(status, \"Unknow Error\")\n raise KloutError(status, msg)\n\n if data.get('body', None):\n status = data.get(\"status\")\n msg = data['body']['error']\n raise KloutError(status, msg)\n\n return data\n\n def score(self, users):\n \"\"\"\n This method allows you to retrieve a Klout score\n\n Parameters\n ----------\n users: The usernames from whom fetching the scores\n\n Returns\n -------\n A list of tuples in the form [('user1', score1), ('user2', score2)...]\n Names are returned as unicode strings and scores as floats\n\n \"\"\"\n url = '/1/klout.json'\n\n if not users:\n raise KloutError(200, 'No topics returned.')\n\n if isinstance(users, (list, tuple)):\n users = ','.join(users)\n\n query = {'users': users}\n\n data = self.make_api_call(url, query)\n\n return [(r['twitter_screen_name'], r['kscore']) for r in data['users']]\n\n def users_show(self, users):\n \"\"\"\n This method allows you to retrieve the user objects\n\n Parameters\n ----------\n users: The usernames from whom fetching the scores\n\n Returns\n -------\n A dictionary with the returned data.\n\n \"\"\"\n url = '/1/users/show.json'\n\n if not users:\n raise KloutError(200, 'No Users')\n\n if isinstance(users, (list, tuple)):\n users = ','.join(users)\n\n query = {'users': users}\n\n data = self.make_api_call(url, query)\n\n return data['users']\n\n def users_topics(self, users):\n \"\"\"\n This method allows you to retrieve the top 3 topic objects\n\n Parameters\n ----------\n users: The usernames from whom fetching the top topics\n\n Returns\n -------\n A list of dicts in the form [{'username':['topic1', 'topic2', ..]}]\n usernames and topics are returned as unicode strings\n\n \"\"\"\n url = '/1/users/topics.json'\n\n if not users:\n raise KloutError(200, 'No Users')\n\n if isinstance(users, (list, tuple)):\n users = ','.join(users)\n\n query = {'users': users}\n\n data = self.make_api_call(url, query)\n\n data = data['users']\n\n return [{user['twitter_screen_name']:[topic for topic in user['topics']]} for user in data]\n\n def users_influenced_by(self, users):\n \"\"\"\n This method allows you to retrieve up to 5 user score pairs\n for users that are influenced by the given influencer\n\n Parameters\n ----------\n users: The usernames from it will fetch the influenced usernames\n\n Returns\n -------\n A list of dicts in the form [{'username':[('username',kscore), ('username2','kscore2'),...]}]\n usernames are returned as unicode strings and kscores as floats.\n\n \"\"\"\n url = '/1/soi/influenced_by.json'\n\n if not users:\n raise KloutError(0, 'No Users')\n\n if isinstance(users, (list, tuple)):\n users = ','.join(users)\n\n query = {'users': users}\n\n data = self.make_api_call(url, query)\n\n data = data['users']\n\n return [{user['twitter_screen_name']:[(influencer['twitter_screen_name'], influencer['kscore']) \\\n for influencer in user['influencers']]} for user in data]\n\n def users_influencer_of(self, users):\n \"\"\"\n This method allows you to retrieve up to 5 user score pairs\n for users that are influencers of the given user.\n\n Parameters\n ----------\n users: The usernames from it will fetch the influenced usernames\n\n Returns\n -------\n A list of dicts in the form [{'username':[('username',kscore), ('username2','kscore2'),...]}]\n usernames are returned as unicode strings and kscores as floats.\n \"\"\"\n url = self.API_URL + '/1/soi/influencer_of.json'\n\n if not users:\n raise KloutError(0, 'No Users')\n\n if isinstance(users, (list, tuple)):\n users = ','.join(users)\n\n query = {'users': users}\n\n data = self.make_api_call(url, query)\n\n data = data['users']\n\n return [{user['twitter_screen_name']:[(influencer['twitter_screen_name'], influencer['kscore']) \\\n for influencer in user['influencees']]} for user in data]\n","sub_path":"pyklout.py","file_name":"pyklout.py","file_ext":"py","file_size_in_byte":8053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"443490910","text":"# -*- coding: utf-8 -*-\nimport urllib.request\nfrom bottle import request, response\nfrom bottle import get, put, post, delete\n\n@get('/external/find/company/')\ndef find_empresa_webservice(cnpj):\n\tres = urllib.request.urlopen('http://www.receitaws.com.br/v1/cnpj/'+ cnpj)\n\tinfo = res.info()\n\tdata = res.read()\n\tres.close()\n\treturn data","sub_path":"controller/business/external.py","file_name":"external.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"470346923","text":"import requests\nimport json\nimport csv\n\nBigParserAccountEmail = \"neilpatelbigparser@gmail.com\"\nBigParserAccountPassword = \"HackTJ2017\"\nFileIDFromGrid = \"58d73444478af706507ad13c\"\n\nurl = \"https://www.bigparser.com/APIServices/api/common/login\"\ndata = {\n \"emailId\": BigParserAccountEmail,\n \"password\": BigParserAccountPassword,\n \"loggedIn\": True\n}\ndata_json = json.dumps(data)\nheaders = {'Content-type': 'application/json'}\nauthId = requests.post(url, data=data_json,headers=headers).json()['authId']\nprint(authId)\nurl = \"https://www.bigparser.com/connectors-api/api/apps/file/googleDrive/false\"\ndata = {\n\t\"fileIDs\" : [FileIDFromGrid]\n}\ndata_json = json.dumps(data)\nprint(data_json)\nheaders = {'Content-type': 'application/json', 'authId':authId}\n\nresponse = requests.put(url, data=data_json, headers=headers).json()\ntry:\n\turl = \"https://www.bigparser.com/connectors-api/api/apps/file/googleDrive/\" + response['requestId'] + \"/status\"\n\theaders = {'authId':authId}\n\tresponse = requests.get(url, headers=headers).json()\n\tprint(response)\nexcept KeyError:\n\tprint(\"Your Grid is already synced up to the most recent version of your Google Sheet\")\n\n\nurl2 = \"https://www.bigparser.com/APIServices/api/grid/headers?gridId=58d73446478af70572adf982\" \ntry:\n\theaders = {'authId':authId}\n\tresponse = requests.get(url2, headers=headers).json()\n\tprint(response)\nexcept KeyError:\n\tprint(\"Didn't work\")\n\nurl3 = \"https://www.bigparser.com/APIServices/api/query/table\"\ntry:\n\tdata2 = {\n\t\t\"gridId\": \"58d73446478af70572adf982\",\n\t\t\"rowCount\": 2042,\n\t\t\"tags\": [\n\t\t\t{\n\t\t\t\t\"columnName\": \"lat\"\n\t\t\t}\n\t\t]\n\t}\n\tdata2_json = json.dumps(data2)\n\theaders = {'authId':authId, 'Content-type': 'application/json'}\n\tresponse = requests.post(url3, headers=headers, data=data2_json).json()\nexcept KeyError:\n\tprint(\"Didn't work\")\n","sub_path":"Server/get_lat_long_data/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"207658835","text":"pirate_ship = [int(el) for el in input().split(\">\")]\nwarship_ship = [int(el) for el in input().split(\">\")]\n\nmax_health = int(input())\n\n\nwhile True:\n line = input()\n if line == \"Retire\":\n break\n command = line.split()[0]\n\n if command == \"Fire\":\n index = int(line.split()[1])\n damage = int(line.split()[2])\n if index in range(len(warship_ship)):\n warship_ship[index] -= damage\n if warship_ship[index] <= 0:\n print(\"You won! The enemy ship has sunken.\")\n exit(0)\n\n elif command == \"Defend\":\n start_index = int(line.split()[1])\n end_index = int(line.split()[2])\n damage = int(line.split()[3])\n\n for sections in range(start_index, end_index+1):\n pirate_ship[sections] -= damage\n if pirate_ship[sections] <= 0:\n print(\"You lost! The pirate ship has sunken.\")\n exit(0)\n\n elif command == \"Repair\":\n index = int(line.split()[1])\n health = int(line.split()[2])\n if index in range(len(pirate_ship)):\n if pirate_ship[index] + health <= max_health:\n pirate_ship[index] += health\n else:\n pirate_ship[index] = max_health\n\n elif command == \"Status\":\n counter = 0\n lowest = int(max_health * 0.2)\n for section in pirate_ship:\n if section < lowest:\n counter += 1\n print(f\"{counter} sections need repair.\")\n\nprint(f\"Pirate ship status: {sum(pirate_ship)}\")\nprint(f\"Warship status: {sum(warship_ship)}\")\n\n","sub_path":"python_fundamentals_september 2020/mid_exam/exam/03. war_ships.py","file_name":"03. war_ships.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"30441494","text":"import os\n\ndef checkFolders():\n\tcwd = os.getcwd()\n\tfor subJob in os.listdir(os.path.join(cwd, 'subJobs')):\n\t\tos.chdir(os.path.join(cwd, 'subJobs', subJob))\t\n\t\tprint(subJob + ': '),\n\t\t#cwd = os.getcwd()\n\t\tif os.path.isfile('plop.stdout') and not os.path.islink('4KUZ_localsamp.maegz'):\n\t\t\tprint('done')\n\t\telse:\n\t\t\tprint('')\n\t\tos.chdir(cwd)\n\ndef main():\n\tcheckFolders()\t\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"bkscripts/check_progress.py","file_name":"check_progress.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"653282246","text":"import os.path\nimport shutil\n\nIMAGE_DIR = \"../../caltech101\"\nSUBSET_DIR = \"caltech10\"\n\nTARGET_CATEGORY = [\"accordion\", \"bonsai\", \"cougar_face\", \"dalmatian\", \"dollar_bill\",\n \"euphonium\", \"hedgehog\", \"grand_piano\", \"Motorbikes\", \"yin_yang\", ]\n\nTOP = 50\n\nif not os.path.exists(SUBSET_DIR):\n os.mkdir(SUBSET_DIR)\n\nfor file in os.listdir(IMAGE_DIR):\n try:\n cat = file.split(\"-\")[0]\n num = int(file.split(\"_\")[1][0:4])\n except:\n continue\n\n if cat in TARGET_CATEGORY and num <= TOP:\n source_image = \"%s/%s\" %(IMAGE_DIR, file)\n dest_image = \"%s/%s\" % (SUBSET_DIR, file)\n shutil.copyfile(source_image, dest_image)\n\n","sub_path":"create_subset.py","file_name":"create_subset.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"335171588","text":"# -*- coding: utf-8 -*-\nimport os\nimport shutil\nimport json\n\nfrom pygltflib import GLTF2\nimport subprocess\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom furniture.models import Model3D, Product\nfrom django.db.models import Q\nfrom render.utils import execute_wait\n\nextensions = {'blend', 'glb', 'gltf', 'obj', 'x3d', 'fbx'}\n\nclass Command(BaseCommand):\n help = f\"read {extensions} and makes pair glb/blend and save it in tmp folder\"\n\n def add_arguments(self, parser):\n parser.add_argument('model_id', nargs=1, type=int, default=False)\n\n def handle(self, *args, **options):\n \"\"\"\n функция\n - копирует файл модели во временную папку\n - запускает blender со скриптом импорта модели\n \"\"\"\n try:\n model = Model3D.objects.get(pk=options['model_id'][0])\n upload_dir = os.path.join(settings.MEDIA_ROOT, 'tmp', 'furniture', 'test')\n os.makedirs(upload_dir, exist_ok=True)\n dest = os.path.join(upload_dir, f\"{model.name}.blend\")\n if not os.path.exists(model.blender_file):\n print(\"BLEND NOT EXISTS\")\n return\n # print('dest', dest)\n shutil.copy(model.blender_file, dest)\n cmd = [os.getenv('BLENDER'), dest, '--background', '-noaudio', '--python', 'blender/blender-import_model.py']\n for s in execute_wait(cmd):\n if 'ERROR:' in s or 'Exception' in s:\n # if 'WARNING:' in s or 'ERROR:' in s or 'Exception' in s or settings.DEBUG:\n self.stdout.write(f\"[blender] {s}\")\n with open(os.path.join(upload_dir, f\"{model.name}.json\"), \"r\") as f:\n info = json.loads(f.read())['meshes']\n _meshes = {m.name: {} for m in model.mesh_set.all()}\n for m in model.mesh_set.all():\n _meshes[m.name][m.material] = 4\n for mesh_info in info:\n meshname = mesh_info['name']\n if meshname not in _meshes:\n _meshes[meshname] = {}\n # \"materials\": [],\n # \"primitives\": [\n # {\n # \"material\": null,\n # \"faces\": 1,\n # \"uv_area\": 1.0,\n # \"gm_area\": 4.0,\n # \"density\": 0.5\n # }\n if not len(mesh_info['materials']):\n if None not in _meshes[meshname]:\n _meshes[meshname][None] = 0\n _meshes[meshname][mat] += 2\n else:\n for mat in mesh_info['materials']:\n if mat not in _meshes[meshname]:\n _meshes[meshname][mat] = 0\n _meshes[meshname][mat] += 2\n print('**_meshes**', _meshes)\n meshes = model.mesh_set.all()\n mesh_ids = [mesh.id for mesh in meshes]\n immutable = []\n hidden = [] # 0 2\n ok = [] # 4 2 *\n errors = []\n for mesh_info in info:\n # print(\">>\", mesh_info['name'], \", primitives:\", len(mesh_info['primitives']))\n pr = meshes.filter(name=mesh_info['name'])\n if not len(pr): # нет такого меша в базе\n # print(f\"{mesh_info['name']} not in db\")\n if len(mesh_info['materials']):\n immutable.append(mesh_info['name'])\n # print(\"immutable in all products\")\n else:\n hidden.append(mesh_info['name'])\n # print(\"hidden\")\n elif len(pr) == 1:\n # update DB\n m = pr[0]\n if len(mesh_info['materials']) == 1:\n if m.material:\n if m.material != mesh_info['materials'][0]:\n errors.append(f\"material {m.material} != {mesh_info['materials'][0]}\")\n else:\n m.material = mesh_info['materials'][0]\n if len(mesh_info['primitives']) == 1:\n prim = mesh_info['primitives'][0]\n if not m.area:\n m.area = prim['gm_area']\n m.uv_area = prim['uv_area']\n m.polygons = prim['faces']\n # print(\"SAVE NEW DATA\", mesh_info['name'], pr[0].area, pr[0].area, m.polygons)\n mesh_ids.remove(pr[0].id)\n ok.append(mesh_info['name'])\n else:\n errors.append(f\"в базе меш с таким именем один, а в модели {len(mesh_info['primitives'])}\")\n #print(\"ERROR\", errors[-1])\n else: # имеем дело с примитивами - смотрим на материалы\n for prim in mesh_info['primitives']:\n pr = pr.filter(material=prim['material'])\n if not len(pr):\n print(\"primitive ERROR, not in db\", prim['material'])\n immutable.append(f\"primitive {prim['material']} on {mesh_info['name']}\")\n else:\n # print(\"in db\", pr[0])\n ok.append(f\"primitive {prim['material']} on {mesh_info['name']}\")\n mesh_ids.remove(pr[0].id)\n if len(mesh_ids):\n errors.append(f\"there are meshes in the database that are not in the file model: {[(i, meshes.get(pk=i).name) for i in mesh_ids]}\")\n #print(\"ERROR - not existed meshes in db\", [(i, meshes.get(pk=i).name) for i in mesh_ids])\n self.stdout.write(f\"ok: {ok}, immutable: {immutable}, hidden: {hidden}\")\n if len(errors):\n self.stdout.write(f\"ERRORS: {errors}\")\n # self.stdout.write(\"management command completed\")\n\n except Exception as e:\n self.stdout.write(f\"!Exception: {repr(e)}\")\n raise\n finally:\n self.stdout.flush()\n","sub_path":"rendering/furniture/management/commands/analize_model.py","file_name":"analize_model.py","file_ext":"py","file_size_in_byte":6413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"1632032","text":"import dash\nimport dash_core_components as dcc\nimport dash_bootstrap_components as dbc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nfrom dash.exceptions import PreventUpdate\nimport dash_table\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nimport pandas as pd\nimport mysql.connector\nfrom datetime import datetime,timedelta\nimport classes\nimport ranEngDashboardStyles as styles\nimport ran_functions\n\napp = dash.Dash(__name__, title='RAN Dashboard', external_stylesheets=[dbc.themes.BOOTSTRAP])\nserver = app.server\n\n# DB Connection Parameters\ndbPara = classes.dbCredentials()\n# FTP Connection Parameters\nftpLogin = classes.ranFtpCredentials()\n# Data\nranController = classes.ranControllers()\nnetworkAlarmFilePath = \"/configuration_files/NBI_FM/{}/\".format(str(datetime.now().strftime('%Y%m%d')))\ntopWorstFilePath = \"/BSC/top_worst_report/\"\nzeroTrafficFilePath = \"/BSC/zero_traffic/\"\nneOosLineChartDf = pd.DataFrame(data={'time':[], 'counter':[]})\n\n# Styles\ntabStyles = styles.headerStyles()\nnetworkOverviewStyles = styles.networkOverviewTab()\nengDashboardStyles = styles.engDashboardTab()\ngraphSyles = styles.graphStyles()\ndataTableStyles = styles.topWorstTab()\nnetworkCheckStyles = styles.networkCheckTab()\ngraphColors = styles.NetworkWideGraphColors()\ngraphInsightStyles = styles.graphInsightTab()\ntxCheckStyles = styles.txCheckTab()\ngraphTitleFontSize = 14\n\napp.layout = html.Div(children=[\n # Header & tabbed menu\n html.Div(\n style = tabStyles.headerFlexContainer,\n children = [\n html.H4(\n id = 'dashboardTitle',\n children = 'RAN Dashboard',\n style = tabStyles.dashboardTitle\n ),\n dcc.Tabs(\n id = 'tabsContainer',\n value = 'Network Overview',\n children = [\n dcc.Tab(\n label = 'Network Overview', \n value = 'Network Overview', \n style = tabStyles.tabStyle,\n selected_style = tabStyles.tabSelectedStyle\n ),\n dcc.Tab(\n label = 'Engineering Dashboard', \n value = 'Engineering Dashboard', \n style = tabStyles.tabStyle,\n selected_style = tabStyles.tabSelectedStyle\n ),\n dcc.Tab(\n label = 'Top Worst Report', \n value = 'Top Worst Report', \n style = tabStyles.tabStyle,\n selected_style = tabStyles.tabSelectedStyle\n ),\n dcc.Tab(\n label = 'Network Check', \n value = 'Network Check', \n style = tabStyles.tabStyle,\n selected_style = tabStyles.tabSelectedStyle\n ),\n dcc.Tab(\n label = 'Graph Insight', \n value = 'Graph Insight', \n style = tabStyles.tabStyle,\n selected_style = tabStyles.tabSelectedStyle\n ),\n dcc.Tab(\n label = 'Tx Status', \n value = 'Tx Status', \n style = tabStyles.tabStyle,\n selected_style = tabStyles.tabSelectedStyle\n )\n ]\n )\n ]\n ),\n # Network Overview Tab\n html.Div(\n id = 'networkOverviewGridContainer',\n style = networkOverviewStyles.networkOverviewGridContainerStyle,\n children = [\n # BSC Dropdown\n html.Div(\n id = 'bscDropdownGridElement',\n style = networkOverviewStyles.bscDropdownGridElement,\n children = [\n dbc.DropdownMenu(\n children = [\n dcc.Checklist(\n id = 'bscDropdown',\n options = [\n {'label':'BSC_01_RRA', 'value':'BSC_01_RRA'},\n {'label':'BSC_02_STGO', 'value':'BSC_02_STGO'},\n {'label':'BSC_03_VM', 'value':'BSC_03_VM'},\n {'label':'BSC_04_VM', 'value':'BSC_04_VM'},\n {'label':'BSC_05_RRA', 'value':'BSC_05_RRA'},\n {'label':'BSC_06_STGO', 'value':'BSC_06_STGO'},\n {'label':'N/A', 'value':'N/A'}\n ],\n value = ['BSC_01_RRA', 'BSC_02_STGO', 'BSC_03_VM', 'BSC_04_VM', 'BSC_05_RRA', 'BSC_06_STGO'],\n labelStyle = {'display': 'block'}\n )\n ],\n label = 'BSC',\n color = 'primary'\n )\n ]\n ),\n # Logic Gate #1\n html.Div(\n id = 'gateOneDropdownGridElement',\n style = networkOverviewStyles.gateOneDropdownGridElement,\n children = [\n dcc.Dropdown(\n id = 'gateOneDropdown',\n options = [\n {'label':'AND', 'value':'AND'},\n {'label':'OR', 'value':'OR'}\n ],\n value = 'OR',\n clearable=False\n )\n ]\n ),\n # RNC Dropdown\n html.Div(\n id = 'rncDropdownGridElement',\n style = networkOverviewStyles.rncDropdownGridElement,\n children = [\n dbc.DropdownMenu(\n children = [\n dcc.Checklist(\n id = 'rncDropdown',\n options = [\n {'label':'RNC_01_RRA', 'value':'RNC_01_RRA'},\n {'label':'RNC_02_STGO', 'value':'RNC_02_STGO'},\n {'label':'RNC_03_VM', 'value':'RNC_03_VM'},\n {'label':'RNC_04_VM', 'value':'RNC_04_VM'},\n {'label':'RNC_05_RRA', 'value':'RNC_05_RRA'},\n {'label':'RNC_06_STGO', 'value':'RNC_06_STGO'},\n {'label':'RNC_07_VM', 'value':'RNC_07_VM'},\n {'label':'N/A', 'value':'N/A'}\n ],\n value = ['RNC_01_RRA', 'RNC_02_STGO', 'RNC_03_VM', 'RNC_04_VM', 'RNC_05_RRA', 'RNC_06_STGO', 'RNC_07_VM'],\n labelStyle = {'display': 'block'}\n )\n ],\n label = 'RNC',\n color = 'danger'\n )\n ]\n ),\n # Logic Gate #2\n html.Div(\n id = 'gateTwoDropdownGridElement',\n style = networkOverviewStyles.gateTwoDropdownGridElement,\n children = [\n dcc.Dropdown(\n id = 'gateTwoDropdown',\n options = [\n {'label':'AND', 'value':'AND'},\n {'label':'OR', 'value':'OR'}\n ],\n value = 'OR',\n clearable=False\n )\n ]\n ),\n # LTE RAT Dropdown\n html.Div(\n id = 'lteDropdownGridElement',\n style = networkOverviewStyles.lteDropdownGridElement,\n children = [\n dbc.DropdownMenu(\n children = [\n dcc.Checklist(\n id = 'lteDropdown',\n options = [\n {'label':'L1900', 'value':'L1900'},\n {'label':'AWS', 'value':'AWS'},\n {'label':'L850', 'value':'L850'},\n {'label':'L900', 'value':'L900'},\n {'label':'WTTX', 'value':'WTTX'},\n {'label':'N/A', 'value':'N/A'}\n ],\n value = ['L1900', 'AWS', 'L850', 'L900', 'WTTX'],\n labelStyle = {'display': 'block'}\n )\n ],\n label = 'LTE Bands',\n color = 'success',\n style = {'width':'100%'}\n )\n ]\n ),\n html.Div(\n id = 'mapGridElement',\n style = networkOverviewStyles.mapGridElement,\n children = [\n dcc.Graph(\n id = 'networkMap'\n )\n ]\n ),\n html.Div(\n id = 'gsmDistributionGraph',\n style = networkOverviewStyles.gsmDistGraphElement,\n children = [\n dcc.Graph(\n id = 'gsmPieChart'\n )\n ]\n ),\n html.Div(\n id = 'umtsDistributionGraph',\n style = networkOverviewStyles.umtsDistGraphElement,\n children = [\n dcc.Graph(\n id = 'umtsPieChart'\n )\n ]\n ),\n html.Div(\n id = 'lteDistributionGraph',\n style = networkOverviewStyles.lteDistGraphElement,\n children = [\n dcc.Graph(\n id = 'ltePieChart'\n )\n ]\n ),\n html.Div(\n id = 'neOosOverviewGraph',\n style = networkOverviewStyles.neOosOverviewGraphElement,\n children = [\n dcc.Graph(\n id = 'neOosOverviewChart'\n )\n ]\n )\n ]\n ),\n # Engineering Dashboard Tab\n html.Div(\n id = 'graphGridContainer',\n style = engDashboardStyles.graphGridContainerStyle,\n children = [\n html.Div(\n id = 'dataTypeDropdownGridElement',\n style = engDashboardStyles.dataTypeDropdownGridElement,\n children = [\n dcc.Dropdown(\n id = 'dataTypeDropdown',\n options = [\n {'label':'CS Call Setup Success Rate', 'value':'CS Call Setup Success Rate'}, \n {'label':'PS Call Setup Success Rate', 'value':'PS Call Setup Success Rate'}, \n {'label':'CS Drop Call Rate', 'value':'CS Drop Call Rate'}, \n {'label':'PS Drop Call Rate', 'value':'PS Drop Call Rate'}, \n {'label':'Assignment Success Rate', 'value':'Assignment Success Rate'}, \n {'label':'Location Update Success Rate', 'value':'Location Update Success Rate'}\n ],\n value = 'PS Drop Call Rate',\n style = {\n 'width': '100%', \n 'font-size': str(graphTitleFontSize) + 'px', \n 'text-align': 'center'\n }\n )\n ]\n ),\n html.Div(\n id = 'timeFrameDropdownGridElement',\n style = engDashboardStyles.timeFrameDropdownGridElement,\n children = [\n dcc.Dropdown(\n id='timeFrameDropdown',\n options=[\n {'label':'1 Day', 'value':'1'}, \n {'label':'3 Days', 'value':'3'}, \n {'label':'7 Days', 'value':'7'}, \n {'label':'30 Days', 'value':'30'}\n ],\n # value var is the default value for the drop down.\n value='1',\n style={\n 'width': '100%', \n 'font-size': str(graphTitleFontSize) + 'px', \n 'text-align': 'center'\n }\n )\n ]\n ),\n html.Div(\n className = 'gridElement',\n id = 'bscGraphContainer',\n style = engDashboardStyles.bscGraphContainer,\n children = [\n 'BSC Graph',\n dcc.Graph(\n id = 'bscGraph'\n )\n ]\n ),\n html.Div(\n className = 'gridElement',\n id = 'rncGraphContainer',\n style = engDashboardStyles.rncGraphContainer,\n children = [\n 'RNC Graph',\n dcc.Graph(\n id = 'rncGraph'\n )\n ]\n ),\n html.Div(\n className = 'gridElement',\n id = 'trxGraphContainer',\n style = engDashboardStyles.trxGraphContainer,\n children = [\n 'TRX Utilization',\n dcc.Graph(\n id = 'trxUsageGraph'\n )\n ]\n ),\n html.Div(\n className = 'gridElement',\n id = 'neOosGraphContainer',\n style = engDashboardStyles.neOosGraphContainer,\n children = [\n 'NE OOS',\n dcc.Graph(\n id = 'neOosGraph'\n )\n ]\n ),\n html.Div(\n className = 'gridElement',\n id = 'neOosLineChartContainer',\n style = engDashboardStyles.neOosLineChartContainer,\n children = [\n 'NE OOS',\n dcc.Graph(\n id = 'neOosLineChart'\n )\n ]\n ),\n html.Div(\n className = 'gridElement',\n style = engDashboardStyles.neOosListContainer,\n children = [\n html.H3('Top NE OOS'),\n dash_table.DataTable(\n id = 'neOosListDataTable',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell,\n sort_action = 'native'\n )\n ]\n )\n ]\n ),\n # Hidden datatable to store graph values\n html.Div(\n className = 'hiddenElement',\n style = {'display':'none'},\n children = [\n dash_table.DataTable(\n id = 'hiddenNeOosLineChartDatatable',\n columns = [{'name': i, 'id': i} for i in neOosLineChartDf.columns],\n data = neOosLineChartDf.to_dict('records')\n )\n ]\n ),\n # Top Worst Reports Tab\n html.Div(\n id = 'outerTopWorstReportFlexContainer',\n style = dataTableStyles.outerTopWorstReportFlexContainer,\n children = [\n # Inner Tab Container\n dcc.Tabs(\n id = 'innerTopWorstTabContainer',\n value = 'Daily Report',\n style = dataTableStyles.innerTopWorstTabContainer,\n children = [\n dcc.Tab(\n label = 'Daily Report',\n value = 'Daily Report',\n style = tabStyles.tabStyle,\n selected_style = tabStyles.tabSelectedStyle\n ),\n dcc.Tab(\n label = 'Zero Traffic',\n value = 'Zero Traffic',\n style = tabStyles.tabStyle,\n selected_style = tabStyles.tabSelectedStyle\n ),\n dcc.Tab(\n label = 'Records',\n value = 'Records',\n style = tabStyles.tabStyle,\n selected_style = tabStyles.tabSelectedStyle\n )\n ]\n ),\n # Daily Top Worst Reports\n html.Div(\n id = 'datatableGridContainer', \n style = dataTableStyles.datatableGridContainer,\n children = [\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('Top Worst LTE eRAB SR'),\n dash_table.DataTable(\n id = 'topWorst4GeRabSrTable',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('Top Worst LTE DCR'),\n dash_table.DataTable(\n id='topWorst4GDcrTable',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('Top Worst 3G PS CSSR'),\n dash_table.DataTable(\n id = 'topWorst3GPsCssrTable',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('Top Worst 3G CS CSSR'),\n dash_table.DataTable(\n id='topWorst3GCsCssrTable',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('Top Worst 3G PS DCR'),\n dash_table.DataTable(\n id='topWorst3GPsDcrTable',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('Top Worst 3G CS DCR'),\n dash_table.DataTable(\n id='topWorst3GCsDcrTable',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('Top Worst GSM CSSR'),\n dash_table.DataTable(\n id='topWorst2GSpeechCssrTable',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('Top Worst GSM DCR'),\n dash_table.DataTable(\n id='topWorst2GSpeechDcrTable',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n )\n ]\n ),\n # Zero Traffic Daily Reports\n html.Div(\n id = 'zeroTrafficGridContainer',\n style = dataTableStyles.zeroTrafficGridContainer,\n children = [\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('LTE DL Zero Traffic'),\n dash_table.DataTable(\n id = 'zeroTraffic4GDl',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('LTE UL Zero Traffic'),\n dash_table.DataTable(\n id = 'zeroTraffic4GUl',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('UMTS Voice Zero Traffic'),\n dash_table.DataTable(\n id = 'zeroTraffic3GVoice',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('UMTS HSDPA Zero Traffic'),\n dash_table.DataTable(\n id = 'zeroTraffic3GHsdpa',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('UMTS HSUPA Zero Traffic'),\n dash_table.DataTable(\n id = 'zeroTraffic3GHsupa',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n ),\n html.Div(\n className = 'datatableGridElement',\n children = [\n html.H3('GSM Zero Traffic'),\n dash_table.DataTable(\n id = 'zeroTraffic2G',\n style_header = dataTableStyles.style_header,\n style_cell = dataTableStyles.style_cell\n )\n ]\n )\n ]\n ),\n # Top Reports Records\n html.Div(\n id = 'topReportRecordGridContainer',\n style = dataTableStyles.topWorstRecordGridContainer,\n children = [\n html.Div(\n children = [\n html.H3('LTE eRAB SR Records'),\n html.Button('Add Entry', id = 'topWorst4GeRabSrRecordTableClicks', n_clicks = 0),\n dash_table.DataTable(\n id = 'topWorst4GeRabSrRecordTable',\n style_header = dataTableStyles.style_header,\n columns = [{'name': '', 'id': ''}],\n include_headers_on_copy_paste = True,\n editable = True,\n row_deletable = True\n ),\n html.Button('Submit', id = 'topWorst4GeRabSrRecordTableSubmit', n_clicks = 0),\n html.H3('LTE DCR Records'),\n html.Button('Add Entry', id = 'topWorst4GDcrRecordTableClicks', n_clicks = 0),\n dash_table.DataTable(\n id = 'topWorst4GDcrRecordTable',\n style_header = dataTableStyles.style_header,\n columns = [{'name': '', 'id': ''}],\n include_headers_on_copy_paste = True,\n editable = True,\n row_deletable = True\n ),\n html.Button('Submit', id = 'topWorst4GDcrRecordTableSubmit', n_clicks = 0),\n html.H3('3G PS CSSR Records'),\n html.Button('Add Entry', id = 'topWorst3GPsCssrRecordTableClicks', n_clicks = 0),\n dash_table.DataTable(\n id = 'topWorst3GPsCssrRecordTable',\n style_header = dataTableStyles.style_header,\n columns = [{'name': '', 'id': ''}],\n include_headers_on_copy_paste = True,\n editable = True,\n row_deletable = True\n ),\n html.Button('Submit', id = 'topWorst3GPsCssrRecordTableSubmit', n_clicks = 0),\n html.H3('3G CS CSSR Records'),\n html.Button('Add Entry', id = 'topWorst3GCsCssrRecordTableClicks', n_clicks = 0),\n dash_table.DataTable(\n id = 'topWorst3GCsCssrRecordTable',\n style_header = dataTableStyles.style_header,\n columns = [{'name': '', 'id': ''}],\n include_headers_on_copy_paste = True,\n editable = True,\n row_deletable = True\n ),\n html.Button('Submit', id = 'topWorst3GCsCssrRecordTableSubmit', n_clicks = 0),\n html.H3('3G PS DCR Records'),\n html.Button('Add Entry', id = 'topWorst3GPsDcrRecordTableClicks', n_clicks = 0),\n dash_table.DataTable(\n id = 'topWorst3GPsDcrRecordTable',\n style_header = dataTableStyles.style_header,\n columns = [{'name': '', 'id': ''}],\n include_headers_on_copy_paste = True,\n editable = True,\n row_deletable = True\n ),\n html.Button('Submit', id = 'topWorst3GPsDcrRecordTableSubmit', n_clicks = 0),\n html.H3('3G CS DCR Records'),\n html.Button('Add Entry', id = 'topWorst3GCsDcrRecordTableClicks', n_clicks = 0),\n dash_table.DataTable(\n id = 'topWorst3GCsDcrRecordTable',\n style_header = dataTableStyles.style_header,\n columns = [{'name': '', 'id': ''}],\n include_headers_on_copy_paste = True,\n editable = True,\n row_deletable = True\n ),\n html.Button('Submit', id = 'topWorst3GCsDcrRecordTableSubmit', n_clicks = 0),\n html.H3('GSM CSSR Records'),\n html.Button('Add Entry', id = 'topWorst2GSpeechCssrRecordTableClicks', n_clicks = 0),\n dash_table.DataTable(\n id = 'topWorst2GSpeechCssrRecordTable',\n style_header = dataTableStyles.style_header,\n columns = [{'name': '', 'id': ''}],\n include_headers_on_copy_paste = True,\n editable = True,\n row_deletable = True\n ),\n html.Button('Submit', id = 'topWorst2GSpeechCssrRecordTableSubmit', n_clicks = 0),\n html.H3('GSM DCR Records'),\n html.Button('Add Entry', id = 'topWorst2GSpeechDcrRecordTableClicks', n_clicks = 0),\n dash_table.DataTable(\n id = 'topWorst2GSpeechDcrRecordTable',\n style_header = dataTableStyles.style_header,\n columns = [{'name': '', 'id': ''}],\n include_headers_on_copy_paste = True,\n editable = True,\n row_deletable = True\n ),\n html.Button('Submit', id = 'topWorst2GSpeechDcrRecordTableSubmit', n_clicks = 0),\n ]\n )\n ]\n )\n ]\n ),\n # Network Check Tab\n html.Div(\n id = 'networkCheckGridContainer',\n style = networkCheckStyles.networkCheckGridContainer,\n children = [ \n html.Div(\n className = 'networkCheckGridElement',\n id = 'cssrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'lteDataCssrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'volteCssrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'lteVolteCssrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'dcrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'lteDataDcrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'volteDcrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'lteVolteDcrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'hsdpaCssrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'hsdpaCssrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'hsupaCssrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'hsupaCssrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'umtsCssrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'umtsCssrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'hsdpaDcrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'hsdpaDcrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'hsupaDcrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'hsupaDcrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'umtsDcrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'umtsDcrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'gsmCsCssrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'gsmCsCssrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'gsmPsDcrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'gsmPsCssrNetworkWideGraph'\n )\n ]\n ),\n html.Div(\n className = 'networkCheckGridElement',\n id = 'gsmCsDcrNetworkWideGraphGridElement',\n children = [\n dcc.Graph(\n id = 'gsmCsDcrNetworkWideGraph'\n )\n ]\n )\n ]\n ),\n # Graph Insight Tab\n html.Div(\n id = 'graphInsightFlexContainer',\n style = graphInsightStyles.graphInsightFlexContainer,\n children = [\n html.Div(\n id = 'graphInsightDropdownContainer',\n style = graphInsightStyles.graphInsightDropdownContainer,\n children = [\n dcc.Dropdown(\n id = 'graphInsightRat',\n style = graphInsightStyles.graphInsightRat,\n options = [\n {'label':'GSM', 'value':'GSM'},\n {'label':'UMTS', 'value':'UMTS'},\n {'label':'LTE', 'value':'LTE'}\n ],\n value = 'LTE'\n ),\n dcc.Dropdown(\n id = 'graphInsightGraphGroup',\n style = graphInsightStyles.graphInsightGraphGroup,\n value = 'None'\n ),\n dcc.Dropdown(\n id = 'graphInsightGraphType',\n style = graphInsightStyles.graphInsightGraphType,\n value = 'None'\n )\n ]\n ),\n html.Div(\n id = 'graphInsightGraphContainer',\n style = graphInsightStyles.graphInsightGraphContainer,\n children = [\n dcc.Graph(\n id = 'graphInsightGraph'\n )\n ]\n ),\n html.Div(\n dash_table.DataTable(\n id = 'graphInsightTable',\n columns = [{'name':'Parameter','id':'Parameter'}, {'name':'Last Week','id':'Last Week'}, {'name':'Current','id':'Current'}, {'name':'Delta','id':'Delta'}]\n )\n )\n ]\n ),\n # Tx Check Tab\n html.Div(\n id = 'txCheckGridContainer',\n style = txCheckStyles.txCheckGridContainer,\n children = [\n dcc.Graph(\n id = 'umtsNetworkPacketLossGraph'\n ),\n dcc.Graph(\n id = 'umtsNetworkDelayGraph'\n ),\n dcc.Graph(\n id = 'gsmNetworkPacketLossGraph'\n ),\n dcc.Graph(\n id = 'gsmNetworkDelayGraph'\n )\n ]\n ),\n dcc.Interval(\n id='dataUpateInterval', \n interval=300*1000, \n n_intervals=0\n )\n])\n\n# Callback to update Network Overview Tab\n@app.callback(\n [\n Output('networkMap', 'figure'),\n Output('gsmPieChart', 'figure'),\n Output('umtsPieChart', 'figure'),\n Output('ltePieChart', 'figure'),\n Output('neOosOverviewChart', 'figure')\n ],\n [\n Input('dataUpateInterval', 'n_intervals'),\n Input('tabsContainer', 'value'),\n Input('bscDropdown', 'value'),\n Input('rncDropdown', 'value'),\n Input('lteDropdown', 'value'),\n Input('gateOneDropdown', 'value'),\n Input('gateTwoDropdown', 'value')\n ],\n State('neOosListDataTable', 'data'),\n State('hiddenNeOosLineChartDatatable', 'data')\n)\ndef updateNetworkOverviewTab(interval, selectedTab, bscList, rncList, lteList, gateOneDropdown, gateTwoDropdown, neOosListDataTableData, hiddenNeOosLineChartDatatableValue):\n # Connect to DB\n mysqlConnector = mysql.connector.connect(user = dbPara.dbUsername, password = dbPara.dbPassword, host = dbPara.dbServerIp , database = dbPara.dataTable)\n # Connection must be buffered when executing multiple querys on DB before closing connection.\n mysqlPointer = mysqlConnector.cursor(buffered=True)\n if selectedTab == 'Network Overview':\n # NE OOS Graph\n startTime = (datetime.now() - timedelta(minutes=5)).strftime(\"%Y/%m/%d %H:%M:%S\")\n neOosLineChart = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n neOosPieChart, neOosLineChart, hiddenNeOosLineChartDatatableValue, neOosListDataTableData = ran_functions.neOosGraph(mysqlPointer, startTime, neOosLineChart, hiddenNeOosLineChartDatatableValue)\n neOosPieChart.update_layout(\n plot_bgcolor='#000000', \n paper_bgcolor='#000000', \n font_color='#FFFFFF', \n title_font_size=graphTitleFontSize, \n font_size=12, \n title='NE OOS Chart', \n margin=dict(l=10, r=10, t=40, b=10), \n legend=dict(orientation='h')\n )\n neOosPieChart.update_traces(\n textinfo = 'value',\n hoverinfo = 'all'\n )\n siteDataframe, bscPieChart, rncPieChart, ltePieChart = ran_functions.networkMapFunction(mysqlPointer, bscList, rncList, lteList, gateOneDropdown, gateTwoDropdown)\n neOosList = []\n # Check if dataframe is not empty first\n if str(type(neOosListDataTableData)) != '':\n # Loop through current NE OOS list\n for dic in neOosListDataTableData:\n tmpNE = dic['NE']\n # If the 2nd position is R or T, then we must remove the first 2 digits from the NE name (NR or LT scenarios)\n if tmpNE[1] == 'R' or tmpNE[1] == 'T':\n tmpNE = tmpNE[2:-1]\n else:\n tmpNE = tmpNE[1:-1]\n neOosList.append(tmpNE)\n # Add NE Status column\n siteDataframe['oos_status'] = 'Online'\n # Check in case there are no NE OOS\n if len(neOosList) > 0:\n for ne in neOosList:\n for i in range(len(siteDataframe['site'])):\n if siteDataframe['site'][i] == ne:\n siteDataframe['oos_status'][i] = 'Offline'\n map = px.scatter_mapbox(siteDataframe, lat='lat', lon='lon', hover_name='site', hover_data=['bsc', 'rnc'], zoom=7, color='oos_status')\n map.update_layout(\n mapbox_style='open-street-map',\n margin=dict(l=2, r=2, t=2, b=2)\n #height=450\n )\n map.update_traces(marker=dict(size=10))\n bscPieChart.update_layout(\n plot_bgcolor='#000000', \n paper_bgcolor='#000000', \n font_color='#FFFFFF', \n title_font_size=graphTitleFontSize, \n font_size=12, \n title='GSM Distribution Chart', \n margin=dict(l=10, r=10, t=40, b=10)\n )\n bscPieChart.update_traces(\n textinfo = 'value+percent',\n hoverinfo = 'all'\n )\n rncPieChart.update_layout(\n plot_bgcolor='#000000', \n paper_bgcolor='#000000', \n font_color='#FFFFFF', \n title_font_size=graphTitleFontSize, \n font_size=12, \n title='UMTS Distribution Chart', \n margin=dict(l=10, r=10, t=40, b=10)\n )\n rncPieChart.update_traces(\n textinfo = 'value+percent',\n hoverinfo = 'all'\n )\n ltePieChart.update_layout(\n plot_bgcolor='#000000', \n paper_bgcolor='#000000', \n font_color='#FFFFFF', \n title_font_size=graphTitleFontSize, \n font_size=12, \n title='LTE Band Distribution Chart', \n margin=dict(l=10, r=10, t=40, b=10)\n )\n ltePieChart.update_traces(\n textinfo = 'value+percent',\n hoverinfo = 'all'\n )\n # Close DB connection\n mysqlPointer.close()\n mysqlConnector.close()\n return map, bscPieChart, rncPieChart, ltePieChart, neOosPieChart\n else:\n # Close DB Connection\n mysqlPointer.close()\n mysqlConnector.close()\n # Used in case there is no update needed on callback\n raise PreventUpdate\n\n# Callback to update Engineering Dashboard Tab\n@app.callback(\n [\n Output('bscGraph', 'figure'), \n Output('rncGraph', 'figure'), \n Output('trxUsageGraph', 'figure'),\n Output('neOosGraph', 'figure'),\n Output('neOosLineChart', 'figure'),\n Output('hiddenNeOosLineChartDatatable', 'data'),\n Output('neOosListDataTable', 'columns'),\n Output('neOosListDataTable', 'data')\n ], \n [\n # We use the update interval function and both dropdown menus as inputs for the callback\n Input('dataUpateInterval', 'n_intervals'),\n Input('tabsContainer', 'value'),\n Input('timeFrameDropdown', 'value'),\n Input('dataTypeDropdown', 'value')\n ],\n State('hiddenNeOosLineChartDatatable', 'data')\n)\ndef updateEngDashboardTab(currentInterval, selectedTab, timeFrameDropdown, dataTypeDropdown, hiddenNeOosLineChartDatatableValue):\n # Connect to DB\n connectr = mysql.connector.connect(user = dbPara.dbUsername, password = dbPara.dbPassword, host = dbPara.dbServerIp , database = dbPara.dataTable)\n # Connection must be buffered when executing multiple querys on DB before closing connection.\n pointer = connectr.cursor(buffered=True)\n if selectedTab == 'Engineering Dashboard':\n # Instantiate the plots\n bscHighRefresh = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n rncHighRefresh = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n gsmGraphValueConversionDict = {'CS Call Setup Success Rate':'cssr', 'PS Call Setup Success Rate':'edgedlssr', 'CS Drop Call Rate':'dcr', 'PS Drop Call Rate':'edgedldcr', 'Assignment Success Rate':'assignmentsuccessrate', 'Location Update Success Rate':'luupdatesr'}\n umtsGraphValueConversionDict = {'CS Call Setup Success Rate':'csconnectionsuccessrate', 'PS Call Setup Success Rate':'psrtsuccessrate', 'CS Drop Call Rate':'csdropcallrate', 'PS Drop Call Rate':'psdropcallrate', 'Assignment Success Rate':'rrcconnectionsuccessrate', 'Location Update Success Rate':'pagingsuccessrate'}\n daysDelta = int(timeFrameDropdown)\n # starttime is the current date/time - daysdelta\n startTime = (datetime.now() - timedelta(days=daysDelta)).strftime(\"%Y/%m/%d %H:%M:%S\")\n bscHighRefresh = ran_functions.bscHighRefreshQuery(pointer, startTime, bscHighRefresh, ranController.bscNameList, gsmGraphValueConversionDict, dataTypeDropdown)\n # Set Graph background colores & title font size\n bscHighRefresh.update_layout(\n plot_bgcolor=graphSyles.plot_bgcolor, \n paper_bgcolor=graphSyles.paper_bgcolor, \n font_color=graphSyles.font_color, \n title_font_size=graphTitleFontSize,\n font_size=12,\n margin=dict(l=10, r=10, t=10, b=10),\n legend=dict(orientation='h')\n )\n rncHighRefresh = ran_functions.rncHighRefreshQuery(pointer, startTime, rncHighRefresh, ranController.rncNameList, umtsGraphValueConversionDict, dataTypeDropdown)\n # Set Graph background colores & title font size\n rncHighRefresh.update_layout(\n plot_bgcolor=graphSyles.plot_bgcolor, \n paper_bgcolor=graphSyles.paper_bgcolor, \n font_color=graphSyles.font_color, \n title_font_size=graphTitleFontSize,\n font_size=12,\n margin=dict(l=10, r=10, t=10, b=10),\n legend=dict(orientation='h')\n )\n # TRX Utilization Graph\n tempDataFrame = {'neName':[], 'ipPoolId':[], 'trxQty':[]}\n # Loop through BSC Names\n for ne in ranController.bscNameList:\n # Loop through Ip Pool ID range (10 - 12)\n for ippool in range(10,13):\n tempDataFrame['neName'].append(ne)\n # Must change ippool to string for the bar chart to display in group mode.\n tempDataFrame['ipPoolId'].append(str(ippool))\n pointer.execute('SELECT trxqty FROM ran_pf_data.trx_usage_data where lastupdate >= \\'' + datetime.now().strftime(\"%Y/%m/%d\") + '\\' and nename = \\'' + ne + '\\' and ippoolid = ' + str(ippool) + ' order by lastupdate desc;')\n queryPayload = pointer.fetchone()\n # Must check if query result is empty, to full with 0\n if queryPayload:\n # Take the latest value on the DB\n tempDataFrame['trxQty'].append(queryPayload[0])\n else:\n tempDataFrame['trxQty'].append(0)\n ipPoolReportDf = pd.DataFrame(tempDataFrame, columns = ['neName', 'ipPoolId', 'trxQty'])\n trxUsageGraph = px.bar(ipPoolReportDf, x='neName', y='trxQty', color='ipPoolId', barmode='group', template='simple_white')\n trxUsageGraph.update_layout(\n plot_bgcolor='#000000', \n paper_bgcolor='#000000', \n font_color='#FFFFFF', \n title_font_size=graphTitleFontSize,\n font_size=graphTitleFontSize,\n title='TRX Load per Interface'\n )\n # NE OOS Graph\n startTime = (datetime.now() - timedelta(minutes=5)).strftime(\"%Y/%m/%d %H:%M:%S\")\n neOosLineChart = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n neOosPieChart, neOosLineChart, hiddenNeOosLineChartDatatableValue, neOosListDataTableData = ran_functions.neOosGraph(pointer, startTime, neOosLineChart, hiddenNeOosLineChartDatatableValue)\n neOosPieChart.update_layout(\n plot_bgcolor='#000000', \n paper_bgcolor='#000000', \n font_color='#FFFFFF', \n title_font_size=graphTitleFontSize, \n font_size=12, \n title='NE OOS Chart', \n margin=dict(l=10, r=10, t=40, b=10), \n legend=dict(orientation='h')\n )\n neOosPieChart.update_traces(\n textinfo = 'value',\n hoverinfo = 'all'\n )\n # Set Graph background colores & title font size\n neOosLineChart.update_layout(\n plot_bgcolor=graphSyles.plot_bgcolor, \n paper_bgcolor=graphSyles.paper_bgcolor, \n font_color=graphSyles.font_color, \n title_font_size=graphTitleFontSize,\n margin=dict(l=10, r=10, t=10, b=10),\n )\n neOosListDataTableColumns = [{'name':'NE', 'id':'NE'}, {'name':'Reason', 'id':'Reason'}]\n # Close DB Connection\n pointer.close()\n connectr.close()\n return bscHighRefresh, rncHighRefresh, trxUsageGraph, neOosPieChart, neOosLineChart, hiddenNeOosLineChartDatatableValue, neOosListDataTableColumns, neOosListDataTableData\n else:\n # Close DB Connection\n pointer.close()\n connectr.close()\n # Used in case there is no update needed on callback\n raise PreventUpdate\n\n# Callback to update Top Worst Tab\n@app.callback(\n [\n Output('topWorst4GeRabSrTable', 'columns'),\n Output('topWorst4GeRabSrTable', 'data'),\n Output('topWorst4GeRabSrRecordTable', 'columns'),\n Output('topWorst4GDcrTable', 'columns'),\n Output('topWorst4GDcrTable', 'data'),\n Output('topWorst4GDcrRecordTable', 'columns'),\n Output('topWorst3GPsCssrTable', 'columns'),\n Output('topWorst3GPsCssrTable', 'data'),\n Output('topWorst3GPsCssrRecordTable', 'columns'),\n Output('topWorst3GCsCssrTable', 'columns'),\n Output('topWorst3GCsCssrTable', 'data'),\n Output('topWorst3GCsCssrRecordTable', 'columns'),\n Output('topWorst3GPsDcrTable', 'columns'),\n Output('topWorst3GPsDcrTable', 'data'),\n Output('topWorst3GPsDcrRecordTable', 'columns'),\n Output('topWorst3GCsDcrTable', 'columns'),\n Output('topWorst3GCsDcrTable', 'data'),\n Output('topWorst3GCsDcrRecordTable', 'columns'),\n Output('topWorst2GSpeechCssrTable', 'columns'),\n Output('topWorst2GSpeechCssrTable', 'data'),\n Output('topWorst2GSpeechCssrRecordTable', 'columns'),\n Output('topWorst2GSpeechDcrTable', 'columns'),\n Output('topWorst2GSpeechDcrTable', 'data'),\n Output('topWorst2GSpeechDcrRecordTable', 'columns')\n ], \n Input('tabsContainer', 'value')\n)\ndef updateTopWorstTab(selectedTab):\n # Ensure to refresh top worst tables only if that tab is selected\n if selectedTab == 'Top Worst Report':\n topWorstDirList = ran_functions.getFtpPathFileList(ftpLogin, topWorstFilePath)\n # Top Worst Reports Variables\n current2GTopWorstDcrFile = \"\"\n current2GTopWorstCssrFile = \"\"\n current3GTopWorstFile = \"\"\n current4GTopWorstFile = \"\"\n topWorstCurrentDate = str(datetime.now().strftime('%Y%m%d'))\n # find the latest file on the directory\n for file in topWorstDirList:\n if topWorstCurrentDate and \"2G\" and \"CSSR\" in file:\n current2GTopWorstCssrFile = file\n if topWorstCurrentDate and \"2G\" and \"DCR\" in file:\n current2GTopWorstDcrFile = file\n if topWorstCurrentDate and \"3G\" in file:\n current3GTopWorstFile = file\n if topWorstCurrentDate and \"LTE\" in file:\n current4GTopWorstFile = file\n # Open the latest files as dataframes\n current4GTopWorstDcrDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, topWorstFilePath, current4GTopWorstFile), sheet_name='TOP 50 Drop LTE', na_values='NIL')\n current4GTopWorsteRabSrDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, topWorstFilePath, current4GTopWorstFile), sheet_name='TOP 50 E-RAB Setup', na_values='NIL')\n current3GTopWorstDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, topWorstFilePath, current3GTopWorstFile), na_values=['NIL', '/0'])\n current2GTopWorstCssrDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, topWorstFilePath, current2GTopWorstCssrFile), sheet_name='Subreport 1', na_values='NIL')\n current2GTopWorstDcrDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, topWorstFilePath, current2GTopWorstDcrFile), sheet_name='Subreport 1', na_values='NIL')\n # Filter the selected columns\n topWorst4GeRabSrDataframe = current4GTopWorsteRabSrDataframe.filter(items = ['eNodeB Name', 'Cell FDD TDD Indication', 'Cell Name', 'E-RAB Setup Success Rate (ALL)[%](%)', 'Date'])\n # Fill N/A values as 0\n topWorst4GeRabSrDataframe = topWorst4GeRabSrDataframe.fillna(0)\n # Select top 10 results\n topWorst4GeRabSrDataframe = topWorst4GeRabSrDataframe.nsmallest(10, 'E-RAB Setup Success Rate (ALL)[%](%)')\n # Shape as a column list of dictionaries (Dash requirement)\n topWorst4GeRabSrColumns = [{'name': i, 'id': i} for i in topWorst4GeRabSrDataframe.columns]\n # Get the same column list, for the Records Tab\n topWorst4GeRabSrRecordColumns = topWorst4GeRabSrColumns.copy()\n topWorst4GeRabSrRecordColumns.append({'name': 'TTK', 'id':'TTK'})\n topWorst4GeRabSrRecordColumns.append({'name': 'Responsable', 'id':'Responsable'})\n\n topWorst4GDcrDataframe = current4GTopWorstDcrDataframe.filter(items = ['eNodeB Name', 'Cell FDD TDD Indication', 'Cell Name', 'Call Drop Rate (All)[%]', 'Date'])\n topWorst4GDcrDataframe = topWorst4GDcrDataframe.fillna(0)\n topWorst4GDcrDataframe = topWorst4GDcrDataframe.nlargest(10, 'Call Drop Rate (All)[%]')\n topWorst4GDcrColumns = [{'name': i, 'id': i} for i in topWorst4GDcrDataframe.columns]\n topWorst4GDcrRecordColumns = topWorst4GDcrColumns.copy()\n topWorst4GDcrRecordColumns.append({'name': 'TTK', 'id':'TTK'})\n topWorst4GDcrRecordColumns.append({'name': 'Responsable', 'id':'Responsable'})\n\n topWorst3GCsCssrDataframe = current3GTopWorstDataframe.filter(items = ['RNC Name', 'NodeB Name', 'Cell Name', 'HSDPA CSSR(%)', 'HSUPA CSSR(%)', 'Speech CSSR', 'Date'])\n topWorst3GCsCssrDataframe = topWorst3GCsCssrDataframe.fillna(0)\n topWorst3GCsCssrDataframe = topWorst3GCsCssrDataframe.nsmallest(10, 'Speech CSSR')\n topWorst3GCsCssrColumns = [{'name': i, 'id': i} for i in topWorst3GCsCssrDataframe.columns]\n topWorst3GCsCssrRecordColumns = topWorst3GCsCssrColumns.copy()\n topWorst3GCsCssrRecordColumns.append({'name': 'TTK', 'id':'TTK'})\n topWorst3GCsCssrRecordColumns.append({'name': 'Responsable', 'id':'Responsable'})\n \n topWorst3GPsCssrDataframe = current3GTopWorstDataframe.filter(items = ['RNC Name', 'NodeB Name', 'Cell Name', 'HSDPA CSSR(%)', 'HSUPA CSSR(%)', 'Total Fails', 'Date'])\n topWorst3GPsCssrDataframe = topWorst3GPsCssrDataframe.fillna(0)\n topWorst3GPsCssrDataframe = topWorst3GPsCssrDataframe.nlargest(10, 'Total Fails')\n topWorst3GPsCssrColumns = [{'name': i, 'id': i} for i in topWorst3GPsCssrDataframe.columns]\n topWorst3GPsCssrRecordColumns = topWorst3GPsCssrColumns.copy()\n topWorst3GPsCssrRecordColumns.append({'name': 'TTK', 'id':'TTK'})\n topWorst3GPsCssrRecordColumns.append({'name': 'Responsable', 'id':'Responsable'})\n \n topWorst3GCsDcrDataframe = current3GTopWorstDataframe.filter(items=['RNC Name', 'NodeB Name', 'Cell Name', 'Speech DCR(%)', 'HSDPA DCR(%)', 'HSUPA DCR(%)', 'Drops CS', 'Date'])\n topWorst3GCsDcrDataframe = topWorst3GCsDcrDataframe.fillna(0)\n topWorst3GCsDcrDataframe = topWorst3GCsDcrDataframe.nlargest(10, 'Drops CS')\n topWorst3GCsDcrColumns = [{'name': i, 'id': i} for i in topWorst3GCsDcrDataframe.columns]\n topWorst3GCsDcrRecordColumns = topWorst3GCsDcrColumns.copy()\n topWorst3GCsDcrRecordColumns.append({'name': 'TTK', 'id':'TTK'})\n topWorst3GCsDcrRecordColumns.append({'name': 'Responsable', 'id':'Responsable'})\n \n topWorst3GPsDcrDataframe = current3GTopWorstDataframe.filter(items=['RNC Name', 'NodeB Name', 'Cell Name', 'Speech DCR(%)', 'HSDPA DCR(%)', 'HSUPA DCR(%)', 'Drops PS', 'Date'])\n topWorst3GPsDcrDataframe = topWorst3GPsDcrDataframe.fillna(0)\n topWorst3GPsDcrDataframe = topWorst3GPsDcrDataframe.nlargest(10, 'Drops PS')\n topWorst3GPsDcrColumns = [{'name': i, 'id': i} for i in topWorst3GPsDcrDataframe.columns]\n topWorst3GPsDcrRecordColumns = topWorst3GPsDcrColumns.copy()\n topWorst3GPsDcrRecordColumns.append({'name': 'TTK', 'id':'TTK'})\n topWorst3GPsDcrRecordColumns.append({'name': 'Responsable', 'id':'Responsable'})\n \n topWorst2GSpeechCssrDataframe = current2GTopWorstCssrDataframe.filter(items = ['GBSC', 'Site Name', 'Cell Name', 'Call Setup Success Rate – Speech (%)', 'Date'])\n topWorst2GSpeechCssrDataframe = topWorst2GSpeechCssrDataframe.fillna(0)\n topWorst2GSpeechCssrDataframe = topWorst2GSpeechCssrDataframe.nsmallest(10, 'Call Setup Success Rate – Speech (%)')\n topWorst2GSpeechCssrColumns = [{'name': i, 'id': i} for i in topWorst2GSpeechCssrDataframe.columns]\n topWorst2GSpeechCssrRecordColumns = topWorst2GSpeechCssrColumns.copy()\n topWorst2GSpeechCssrRecordColumns.append({'name': 'TTK', 'id':'TTK'})\n topWorst2GSpeechCssrRecordColumns.append({'name': 'Responsable', 'id':'Responsable'})\n \n topWorst2GSpeechDcrDataframe = current2GTopWorstDcrDataframe.filter(items = ['GBSC', 'Site Name', 'Cell Name', 'Drop Call Rate – Speech (%)', 'Total Number of dropped Connections', 'Date'])\n topWorst2GSpeechDcrDataframe = topWorst2GSpeechDcrDataframe.fillna(0)\n topWorst2GSpeechDcrDataframe = topWorst2GSpeechDcrDataframe.nlargest(10, 'Total Number of dropped Connections')\n topWorst2GSpeechDcrColumns = [{'name': i, 'id': i} for i in topWorst2GSpeechDcrDataframe.columns]\n topWorst2GSpeechDcrRecordColumns = topWorst2GSpeechDcrColumns.copy()\n topWorst2GSpeechDcrRecordColumns.append({'name': 'TTK', 'id':'TTK'})\n topWorst2GSpeechDcrRecordColumns.append({'name': 'Responsable', 'id':'Responsable'})\n return topWorst4GeRabSrColumns, topWorst4GeRabSrDataframe.to_dict('records'), topWorst4GeRabSrRecordColumns, topWorst4GDcrColumns, topWorst4GDcrDataframe.to_dict('records'), topWorst4GDcrRecordColumns, topWorst3GPsCssrColumns, topWorst3GPsCssrDataframe.to_dict('records'), topWorst3GPsCssrRecordColumns, topWorst3GCsCssrColumns, topWorst3GCsCssrDataframe.to_dict('records'), topWorst3GCsCssrRecordColumns, topWorst3GPsDcrColumns, topWorst3GPsDcrDataframe.to_dict('records'), topWorst3GPsDcrRecordColumns, topWorst3GCsDcrColumns, topWorst3GCsDcrDataframe.to_dict('records'), topWorst3GCsDcrRecordColumns, topWorst2GSpeechCssrColumns, topWorst2GSpeechCssrDataframe.to_dict('records'), topWorst2GSpeechCssrRecordColumns, topWorst2GSpeechDcrColumns, topWorst2GSpeechDcrDataframe.to_dict('records'), topWorst2GSpeechDcrRecordColumns\n else:\n raise PreventUpdate\n\n# Callback to update Zero Traffic Tab\n@app.callback(\n [\n Output('zeroTraffic4GDl', 'columns'),\n Output('zeroTraffic4GDl', 'data'),\n Output('zeroTraffic4GUl', 'columns'),\n Output('zeroTraffic4GUl', 'data'),\n Output('zeroTraffic3GVoice', 'columns'),\n Output('zeroTraffic3GVoice', 'data'),\n Output('zeroTraffic3GHsdpa', 'columns'),\n Output('zeroTraffic3GHsdpa', 'data'),\n Output('zeroTraffic3GHsupa', 'columns'),\n Output('zeroTraffic3GHsupa', 'data'),\n Output('zeroTraffic2G', 'columns'),\n Output('zeroTraffic2G', 'data'),\n ], \n Input('innerTopWorstTabContainer', 'value')\n)\ndef updateZeroTrafficTab(selectedTab):\n if selectedTab == 'Zero Traffic':\n # Get Zero Traffic directory file list\n zeroTrafficDirList = ran_functions.getFtpPathFileList(ftpLogin, zeroTrafficFilePath)\n currentZeroTrafficFile = \"\"\n CurrentDate = str(datetime.now().strftime('%Y%m%d'))\n # Search for the current date on each filename on the directory\n for file in zeroTrafficDirList:\n if CurrentDate in file:\n currentZeroTrafficFile = file\n # Open all file tabs on dataframes\n zeroTraffic4GDlDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, zeroTrafficFilePath, currentZeroTrafficFile), sheet_name='Zero Traffic LTE DL', na_values='NIL')\n zeroTraffic4GDlDataframe = zeroTraffic4GDlDataframe.filter(items = ['eNodeB Name', 'Cell Name', 'LocalCell Id', 'Date'])\n zeroTraffic4GDlColumns = [{'name': i, 'id': i} for i in zeroTraffic4GDlDataframe.columns]\n\n zeroTraffic4GUlDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, zeroTrafficFilePath, currentZeroTrafficFile), sheet_name='Zero Traffic LTE UL', na_values='NIL')\n zeroTraffic4GUlDataframe = zeroTraffic4GUlDataframe.filter(items = ['eNodeB Name', 'Cell Name', 'LocalCell Id', 'Date'])\n zeroTraffic4GUlColumns = [{'name': i, 'id': i} for i in zeroTraffic4GUlDataframe.columns]\n\n zeroTraffic3GVoiceDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, zeroTrafficFilePath, currentZeroTrafficFile), sheet_name='Zero Traffic 3G Voice', na_values='NIL')\n zeroTraffic3GVoiceDataframe = zeroTraffic3GVoiceDataframe.filter(items = ['RNC', 'CELLNAME', 'CellId', 'Date'])\n zeroTraffic3GVoiceColumns = [{'name': i, 'id': i} for i in zeroTraffic3GVoiceDataframe.columns]\n\n zeroTraffic3GHsdpaDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, zeroTrafficFilePath, currentZeroTrafficFile), sheet_name='Zero Traffic HSDPA', na_values='NIL')\n zeroTraffic3GHsdpaDataframe = zeroTraffic3GHsdpaDataframe.filter(items = ['RNC', 'CELLNAME', 'CellId', 'Date'])\n zeroTraffic3GHsdpaColumns = [{'name': i, 'id': i} for i in zeroTraffic3GHsdpaDataframe.columns]\n\n zeroTraffic3GHsupaDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, zeroTrafficFilePath, currentZeroTrafficFile), sheet_name='Zero Traffic HSUPA', na_values='NIL')\n zeroTraffic3GHsupaDataframe = zeroTraffic3GHsupaDataframe.filter(items = ['RNC', 'CELLNAME', 'CellId', 'Date'])\n zeroTraffic3GHsupaColumns = [{'name': i, 'id': i} for i in zeroTraffic3GHsupaDataframe.columns]\n\n zeroTraffic2GDataframe = pd.read_excel(ran_functions.downloadFtpFile(ftpLogin, zeroTrafficFilePath, currentZeroTrafficFile), sheet_name='Zero Traffic 2G', na_values='NIL')\n zeroTraffic2GDataframe = zeroTraffic2GDataframe.filter(items = ['GBSC', 'Site Name', 'Cell Name', 'Date'])\n zeroTraffic2GColumns = [{'name': i, 'id': i} for i in zeroTraffic2GDataframe.columns]\n\n return zeroTraffic4GDlColumns, zeroTraffic4GDlDataframe.to_dict('records'), zeroTraffic4GUlColumns, zeroTraffic4GUlDataframe.to_dict('records'), zeroTraffic3GVoiceColumns, zeroTraffic3GVoiceDataframe.to_dict('records'), zeroTraffic3GHsdpaColumns, zeroTraffic3GHsdpaDataframe.to_dict('records'), zeroTraffic3GHsupaColumns, zeroTraffic3GHsupaDataframe.to_dict('records'), zeroTraffic2GColumns, zeroTraffic2GDataframe.to_dict('records')\n else:\n raise PreventUpdate\n\n# Callback to add rows on Top Worst Records Tab. This tab's datatable data param must be updated on this callback to avoid callback output duplication.\n@app.callback(\n [\n Output('topWorst4GeRabSrRecordTable', 'data'), \n Output('topWorst4GDcrRecordTable', 'data'),\n Output('topWorst3GPsCssrRecordTable', 'data'),\n Output('topWorst3GCsCssrRecordTable', 'data'),\n Output('topWorst3GPsDcrRecordTable', 'data'),\n Output('topWorst3GCsDcrRecordTable', 'data'),\n Output('topWorst2GSpeechCssrRecordTable', 'data'),\n Output('topWorst2GSpeechDcrRecordTable', 'data')\n ],\n [\n Input('topWorst4GeRabSrRecordTableClicks', 'n_clicks'),\n Input('topWorst4GDcrRecordTableClicks', 'n_clicks'),\n Input('topWorst3GPsCssrRecordTableClicks', 'n_clicks'),\n Input('topWorst3GCsCssrRecordTableClicks', 'n_clicks'),\n Input('topWorst3GPsDcrRecordTableClicks', 'n_clicks'),\n Input('topWorst3GCsDcrRecordTableClicks', 'n_clicks'),\n Input('topWorst2GSpeechCssrRecordTableClicks', 'n_clicks'),\n Input('topWorst2GSpeechDcrRecordTableClicks', 'n_clicks'),\n Input('innerTopWorstTabContainer', 'value')\n ],\n State('topWorst4GeRabSrRecordTable', 'columns'),\n State('topWorst4GDcrRecordTable', 'columns'),\n State('topWorst3GPsCssrRecordTable', 'columns'),\n State('topWorst3GCsCssrRecordTable', 'columns'),\n State('topWorst3GPsDcrRecordTable', 'columns'),\n State('topWorst3GCsDcrRecordTable', 'columns'),\n State('topWorst2GSpeechCssrRecordTable', 'columns'),\n State('topWorst2GSpeechDcrRecordTable', 'columns')\n)\ndef addRow(topWorst4GeRabSrRecordTableClicks, topWorst4GDcrRecordTableClicks, topWorst3GPsCssrRecordTableClicks, topWorst3GCsCssrRecordTableClicks, topWorst3GPsDcrRecordTableClicks, topWorst3GCsDcrRecordTableClicks, topWorst2GSpeechCssrRecordTableClicks, topWorst2GSpeechDcrRecordTableClicks, selectedInnerTab, topWorst4GeRabSrRecordTableColumns, topWorst4GDcrRecordTableColumns, topWorst3GPsCssrRecordTableColumns, topWorst3GCsCssrRecordTableColumns, topWorst3GPsDcrRecordTableColumns, topWorst3GCsDcrRecordTableColumns, topWorst2GSpeechCssrRecordTableColumns, topWorst2GSpeechDcrRecordTableColumns):\n if selectedInnerTab == 'Records':\n # Instantiate the callback context, to find the button ID that triggered the callback\n callbackContext = dash.callback_context\n # Get button ID\n button_id = callbackContext.triggered[0]['prop_id'].split('.')[0]\n # Connect to DB\n connectr = mysql.connector.connect(user = dbPara.dbUsername, password = dbPara.dbPassword, host = dbPara.dbServerIp , database = dbPara.recordsDataTable)\n # Connection must be buffered when executing multiple querys on DB before closing connection.\n pointer = connectr.cursor(buffered=True)\n # Fill datatable data with db table content\n table = 'topworst4gerabsrrecord'\n topWorst4GeRabSrRecordTableData = ran_functions.queryTopRecords(pointer, topWorst4GeRabSrRecordTableColumns, table)\n table = 'topworst4gdcrrecord'\n topWorst4GDcrRecordTableData = ran_functions.queryTopRecords(pointer, topWorst4GDcrRecordTableColumns, table)\n table = 'topworst3gpscssrrecord'\n topWorst3GPsCssrRecordTableData = ran_functions.queryTopRecords(pointer, topWorst3GPsCssrRecordTableColumns, table)\n table = 'topworst3gcscssrrecord'\n topWorst3GCsCssrRecordTableData = ran_functions.queryTopRecords(pointer, topWorst3GCsCssrRecordTableColumns, table)\n table = 'topworst3gpsdcrrecord'\n topWorst3GPsDcrRecordTableData = ran_functions.queryTopRecords(pointer, topWorst3GPsDcrRecordTableColumns, table)\n table = 'topworst3gcsdcrrecord'\n topWorst3GCsDcrRecordTableData = ran_functions.queryTopRecords(pointer, topWorst3GCsDcrRecordTableColumns, table)\n table = 'topworst2gcssrrecord'\n topWorst2GSpeechCssrRecordTableData = ran_functions.queryTopRecords(pointer, topWorst2GSpeechCssrRecordTableColumns, table)\n table = 'topworst2gdcrrecord'\n topWorst2GSpeechDcrRecordTableData = ran_functions.queryTopRecords(pointer, topWorst2GSpeechDcrRecordTableColumns, table)\n if button_id == 'topWorst4GeRabSrRecordTableClicks': \n topWorst4GeRabSrRecordTableData.append({column['id']: '' for column in topWorst4GeRabSrRecordTableColumns})\n if button_id == 'topWorst4GDcrRecordTableClicks':\n topWorst4GDcrRecordTableData.append({column['id']: '' for column in topWorst4GDcrRecordTableColumns})\n if button_id == 'topWorst3GPsCssrRecordTableClicks': \n topWorst3GPsCssrRecordTableData.append({column['id']: '' for column in topWorst3GPsCssrRecordTableColumns})\n if button_id == 'topWorst3GCsCssrRecordTableClicks':\n topWorst3GCsCssrRecordTableData.append({column['id']: '' for column in topWorst3GCsCssrRecordTableColumns})\n if button_id == 'topWorst3GPsDcrRecordTableClicks': \n topWorst3GPsDcrRecordTableData.append({column['id']: '' for column in topWorst3GPsDcrRecordTableColumns})\n if button_id == 'topWorst3GCsDcrRecordTableClicks':\n topWorst3GCsDcrRecordTableData.append({column['id']: '' for column in topWorst3GCsDcrRecordTableColumns})\n if button_id == 'topWorst2GSpeechCssrRecordTableClicks': \n topWorst2GSpeechCssrRecordTableData.append({column['id']: '' for column in topWorst2GSpeechCssrRecordTableColumns})\n if button_id == 'topWorst2GSpeechDcrRecordTableClicks':\n topWorst2GSpeechDcrRecordTableData.append({column['id']: '' for column in topWorst2GSpeechDcrRecordTableColumns})\n # Close DB Connection\n pointer.close()\n connectr.close()\n return topWorst4GeRabSrRecordTableData, topWorst4GDcrRecordTableData, topWorst3GPsCssrRecordTableData, topWorst3GCsCssrRecordTableData, topWorst3GPsDcrRecordTableData, topWorst3GCsDcrRecordTableData, topWorst2GSpeechCssrRecordTableData, topWorst2GSpeechDcrRecordTableData\n else:\n raise PreventUpdate\n\n# Callback to insert data to db (Top Worst Report Records)\n@app.callback(\n [\n # The output will be the button style, because a callback MUST have an output\n Output('topWorst4GeRabSrRecordTableSubmit', 'style'), \n Output('topWorst4GDcrRecordTableSubmit', 'style'), \n Output('topWorst3GPsCssrRecordTableSubmit', 'style'), \n Output('topWorst3GCsCssrRecordTableSubmit', 'style'), \n Output('topWorst3GPsDcrRecordTableSubmit', 'style'), \n Output('topWorst3GCsDcrRecordTableSubmit', 'style'), \n Output('topWorst2GSpeechCssrRecordTableSubmit', 'style'), \n Output('topWorst2GSpeechDcrRecordTableSubmit', 'style')\n ],\n [\n # Our triggers will be the submit buttons\n Input('topWorst4GeRabSrRecordTableSubmit', 'n_clicks'),\n Input('topWorst4GDcrRecordTableSubmit', 'n_clicks'),\n Input('topWorst3GPsCssrRecordTableSubmit', 'n_clicks'),\n Input('topWorst3GCsCssrRecordTableSubmit', 'n_clicks'),\n Input('topWorst3GPsDcrRecordTableSubmit', 'n_clicks'),\n Input('topWorst3GCsDcrRecordTableSubmit', 'n_clicks'),\n Input('topWorst2GSpeechCssrRecordTableSubmit', 'n_clicks'),\n Input('topWorst2GSpeechDcrRecordTableSubmit', 'n_clicks')\n ],\n # We must know the state of the datatable data\n State('topWorst4GeRabSrRecordTable', 'data'),\n State('topWorst4GeRabSrRecordTable', 'columns'),\n State('topWorst4GDcrRecordTable', 'data'),\n State('topWorst4GDcrRecordTable', 'columns'),\n State('topWorst3GPsCssrRecordTable', 'data'),\n State('topWorst3GPsCssrRecordTable', 'columns'),\n State('topWorst3GCsCssrRecordTable', 'data'),\n State('topWorst3GCsCssrRecordTable', 'columns'),\n State('topWorst3GPsDcrRecordTable', 'data'),\n State('topWorst3GPsDcrRecordTable', 'columns'),\n State('topWorst3GCsDcrRecordTable', 'data'),\n State('topWorst3GCsDcrRecordTable', 'columns'),\n State('topWorst2GSpeechCssrRecordTable', 'data'),\n State('topWorst2GSpeechCssrRecordTable', 'columns'),\n State('topWorst2GSpeechDcrRecordTable', 'data'),\n State('topWorst2GSpeechDcrRecordTable', 'columns')\n)\ndef insertData(topWorst4GeRabSrRecordTableSubmit, topWorst4GDcrRecordTableSubmit, topWorst3GPsCssrRecordTableSubmit, topWorst3GCsCssrRecordTableSubmit, topWorst3GPsDcrRecordTableSubmit, topWorst3GCsDcrRecordTableSubmit, topWorst2GSpeechCssrRecordTableSubmit, topWorst2GSpeechDcrRecordTableSubmit, topWorst4GeRabSrRecordTableData, topWorst4GeRabSrRecordTableColumns, topWorst4GDcrRecordTableData, topWorst4GDcrRecordTableColumns, topWorst3GPsCssrRecordTableData, topWorst3GPsCssrRecordTableColumns, topWorst3GCsCssrRecordTableData, topWorst3GCsCssrRecordTableColumns, topWorst3GPsDcrRecordTableData, topWorst3GPsDcrRecordTableColumns, topWorst3GCsDcrRecordTableData, topWorst3GCsDcrRecordTableColumns, topWorst2GSpeechCssrRecordTableData, topWorst2GSpeechCssrRecordTableColumns, topWorst2GSpeechDcrRecordTableData, topWorst2GSpeechDcrRecordTableColumns):\n # Instantiate the callback context, to find the button ID that triggered the callback\n callbackContext = dash.callback_context\n # Get button ID\n button_id = callbackContext.triggered[0]['prop_id'].split('.')[0]\n # Connect to DB\n connectr = mysql.connector.connect(user = dbPara.dbUsername, password = dbPara.dbPassword, host = dbPara.dbServerIp , database = dbPara.recordsDataTable)\n # Connection must be buffered when executing multiple querys on DB before closing connection.\n pointer = connectr.cursor(buffered=True)\n if button_id == 'topWorst4GeRabSrRecordTableSubmit':\n table = 'topworst4gerabsrrecord'\n ran_functions.insertDataTable(pointer, connectr, table, topWorst4GeRabSrRecordTableData)\n # Close DB Connection\n pointer.close()\n connectr.close()\n return {'backgroundColor': 'green'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}\n if button_id == 'topWorst4GDcrRecordTableSubmit':\n table = 'topworst4gdcrrecord'\n ran_functions.insertDataTable(pointer, connectr, table, topWorst4GDcrRecordTableData)\n # Close DB Connection\n pointer.close()\n connectr.close()\n return {'backgroundColor': '#e7e7e7'}, {'backgroundColor': 'green'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}\n if button_id == 'topWorst3GPsCssrRecordTableSubmit':\n table = 'topworst3gpscssrrecord'\n ran_functions.insertDataTable(pointer, connectr, table, topWorst3GPsCssrRecordTableData)\n # Close DB Connection\n pointer.close()\n connectr.close()\n return {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': 'green'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}\n if button_id == 'topWorst3GCsCssrRecordTableSubmit':\n table = 'topworst3gcscssrrecord'\n ran_functions.insertDataTable(pointer, connectr, table, topWorst3GCsCssrRecordTableData)\n # Close DB Connection\n pointer.close()\n connectr.close()\n return {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': 'green'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}\n if button_id == 'topWorst3GPsDcrRecordTableSubmit':\n table = 'topworst3gpsdcrrecord'\n ran_functions.insertDataTable(pointer, connectr, table, topWorst3GPsDcrRecordTableData)\n # Close DB Connection\n pointer.close()\n connectr.close()\n return {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': 'green'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}\n if button_id == 'topWorst3GCsDcrRecordTableSubmit':\n table = 'topworst3gcsdcrrecord'\n ran_functions.insertDataTable(pointer, connectr, table, topWorst3GCsDcrRecordTableData)\n # Close DB Connection\n pointer.close()\n connectr.close()\n return {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': 'green'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}\n if button_id == 'topWorst2GSpeechCssrRecordTableSubmit':\n table = 'topworst2gcssrrecord'\n ran_functions.insertDataTable(pointer, connectr, table, topWorst2GSpeechCssrRecordTableData)\n # Close DB Connection\n pointer.close()\n connectr.close()\n return {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': 'green'}, {'backgroundColor': '#e7e7e7'}\n if button_id == 'topWorst2GSpeechDcrRecordTableSubmit':\n table = 'topworst2gdcrrecord'\n ran_functions.insertDataTable(pointer, connectr, table, topWorst2GSpeechDcrRecordTableData)\n # Close DB Connection\n pointer.close()\n connectr.close()\n return {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': '#e7e7e7'}, {'backgroundColor': 'green'}\n raise PreventUpdate\n\n# Callback to update Network Check Tab\n@app.callback(\n [\n Output('gsmCsCssrNetworkWideGraph', 'figure'), \n Output('gsmPsCssrNetworkWideGraph', 'figure'), \n Output('gsmCsDcrNetworkWideGraph', 'figure'),\n Output('umtsCssrNetworkWideGraph', 'figure'),\n Output('hsdpaCssrNetworkWideGraph', 'figure'),\n Output('hsupaCssrNetworkWideGraph', 'figure'),\n Output('umtsDcrNetworkWideGraph', 'figure'),\n Output('hsdpaDcrNetworkWideGraph', 'figure'),\n Output('hsupaDcrNetworkWideGraph', 'figure'),\n Output('lteVolteDcrNetworkWideGraph', 'figure'),\n Output('lteDataDcrNetworkWideGraph', 'figure'),\n Output('lteVolteCssrNetworkWideGraph', 'figure'),\n Output('lteDataCssrNetworkWideGraph', 'figure')\n ],\n [\n Input('tabsContainer', 'value'),\n Input('dataUpateInterval', 'n_intervals')\n ]\n)\ndef updateNetworkCheckTab(selectedTab, currentInterval):\n if selectedTab == 'Network Check': \n # starttime is the current date/time - daysdelta\n startTime = 7\n # Connect to DB\n connectr = mysql.connector.connect(user = dbPara.dbUsername, password = dbPara.dbPassword, host = dbPara.dbServerIp , database = dbPara.dataTable)\n # Connection must be buffered when executing multiple querys on DB before closing connection.\n pointer = connectr.cursor(buffered=True)\n # Create plots\n gsmCsCssr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n gsmPsCssr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n gsmCsDcr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n umtsCssr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n hsdpaCssr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n hsupaCssr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n umtsDcr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n hsdpaDcr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n hsupaDcr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n lteVolteDcr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n lteDataDcr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n lteVolteCssr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n lteDataCssr = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n # Function to populate graph data\n lteVolteCssr, lteDataCssr, lteVolteDcr, lteDataDcr = ran_functions.populateLteGraphs(pointer, startTime, ranController.lteBandList, lteVolteCssr, lteDataCssr, lteVolteDcr, lteDataDcr)\n # Customize graph layout\n lteDataCssr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='LTE Data eRAB SSR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n lteVolteCssr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='VoLTE eRAB SSR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n lteDataDcr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='LTE Data DCR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n lteVolteDcr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='VoLTE DCR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n umtsCssr, hsdpaCssr, hsupaCssr, umtsDcr, hsdpaDcr, hsupaDcr = ran_functions.populateUmtsGraphs(pointer, startTime, ranController.rncNameList, umtsCssr, hsdpaCssr, hsupaCssr, umtsDcr, hsdpaDcr, hsupaDcr)\n hsdpaCssr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='HSDPA CSSR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n hsupaCssr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='HSUPA CSSR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n umtsCssr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='UMTS CSSR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n hsdpaDcr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='HSDPA DCR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n hsupaDcr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='HSUPA DCR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n umtsDcr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='UMTS DCR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n gsmCsCssr, gsmPsCssr, gsmCsDcr = ran_functions.populateGsmGraphs(pointer, startTime, ranController.bscNameList, gsmCsCssr, gsmPsCssr, gsmCsDcr)\n gsmCsCssr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='GSM CS CSSR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n gsmPsCssr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='GSM PS CSSR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n gsmCsDcr.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='GSM CS DCR'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n # Close DB connection\n pointer.close()\n connectr.close()\n return gsmCsCssr, gsmPsCssr, gsmCsDcr, umtsCssr, hsdpaCssr, hsupaCssr, umtsDcr, hsdpaDcr, hsupaDcr, lteVolteDcr, lteDataDcr, lteVolteCssr, lteDataCssr\n else:\n raise PreventUpdate\n\n#Callback to update Graph Insight Dropdown\n@app.callback(\n [\n Output('graphInsightGraphType', 'options'),\n Output('graphInsightGraphGroup', 'options')\n ],\n Input('graphInsightRat', 'value')\n)\ndef updateGraphInsightDropdown(selectedRAT):\n startTime = 7\n # Connect to DB\n connectr = mysql.connector.connect(user = dbPara.dbUsername, password = dbPara.dbPassword, host = dbPara.dbServerIp , database = dbPara.dataTable)\n # Connection must be buffered when executing multiple querys on DB before closing connection.\n pointer = connectr.cursor(buffered=True)\n #startTimeNetworkWide = (datetime.now()-timedelta(days=startTime)).strftime(\"%Y-%m-%d\")\n typeReturnList = ['None']\n groupReturnList = [{'label':'none', 'value':'none'}]\n ratTypeTable = ''\n tableColumn = ''\n if selectedRAT == 'LTE':\n ratTypeTable = 'ran_report_4g_report_network_wide'\n tableColumn = 'ltecellgroup'\n typeReturnList = [{'label':'LTE Data DCR', 'value':'LTE Data DCR'}, {'label':'LTE Data CSSR', 'value':'LTE Data CSSR'}, {'label':'VoLTE DCR', 'value':'VoLTE DCR'}, {'label':'VoLTE CSSR', 'value':'VoLTE CSSR'}]\n elif selectedRAT == 'UMTS':\n ratTypeTable = 'ran_report_3g_report_network_wide'\n tableColumn = 'rncname'\n typeReturnList = [{'label':'UMTS DCR', 'value':'UMTS DCR'}, {'label':'UMTS CSSR', 'value':'UMTS CSSR'}, {'label':'HSDPA DCR', 'value':'HSDPA DCR'}, {'label':'HSDPA CSSR', 'value':'HSDPA CSSR'}, {'label':'HSUPA DCR', 'value':'HSUPA DCR'}, {'label':'HSUPA CSSR', 'value':'HSUPA CSSR'}]\n else:\n ratTypeTable = 'ran_report_2g_report_network_wide'\n tableColumn = 'gbsc'\n typeReturnList = [{'label':'GSM CS CSSR', 'value':'GSM CS CSSR'}, {'label':'GSM PS CSSR', 'value':'GSM PS CSSR'}, {'label':'GSM CS DCR', 'value':'GSM CS DCR'}]\n # Execute query to get graph group list\n pointer.execute('SELECT ' + tableColumn + ' FROM ran_pf_data.' + ratTypeTable + ' group by ' + tableColumn + ';')\n queryRaw = pointer.fetchall()\n groupReturnList = [{'label':i[0], 'value':i[0]} for i in queryRaw]\n groupReturnList.append({'label':'All', 'value':'All'})\n # Close DB connection\n pointer.close()\n connectr.close()\n return typeReturnList, groupReturnList\n\n# Callback to update Graph Inisight Graph\n@app.callback(\n [\n Output('graphInsightGraph', 'figure'),\n Output('graphInsightTable', 'data')\n ],\n [\n Input('graphInsightGraphType', 'value'),\n Input('graphInsightGraphGroup', 'value')\n ]\n)\ndef updateGraphInsightGraph(selectedKPI, selectedGroup):\n startTime = 7\n graphInsightValueList = []\n graphInsightValueDict = {}\n # Connect to DB\n connectr = mysql.connector.connect(user = dbPara.dbUsername, password = dbPara.dbPassword, host = dbPara.dbServerIp , database = dbPara.dataTable)\n # Connection must be buffered when executing multiple querys on DB before closing connection.\n pointer = connectr.cursor(buffered=True)\n currentGraph = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n currentGraph, graphInsightValueDict = ran_functions.graphInsightQuery(currentGraph, startTime, selectedKPI, pointer, selectedGroup, graphInsightValueDict)\n # Set graph visual theme\n currentGraph.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n legend=dict(orientation='h'),\n title=dict(text=selectedKPI),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n graphInsightValueList.append(graphInsightValueDict)\n # Close DB connection\n pointer.close()\n connectr.close()\n return currentGraph, graphInsightValueList\n\n# Callback to update Network Check Tab\n@app.callback(\n [\n Output('umtsNetworkPacketLossGraph', 'figure'), \n Output('umtsNetworkDelayGraph', 'figure'), \n Output('gsmNetworkPacketLossGraph', 'figure'), \n Output('gsmNetworkDelayGraph', 'figure')\n ],\n [\n Input('tabsContainer', 'value'),\n Input('dataUpateInterval', 'n_intervals')\n ]\n)\ndef updateTxCheckTab(selectedTab, currentInterval):\n if selectedTab == 'Tx Status': \n # starttime is the current date/time - daysdelta\n startTime = 7\n # Connect to DB\n connectr = mysql.connector.connect(user = dbPara.dbUsername, password = dbPara.dbPassword, host = dbPara.dbServerIp , database = dbPara.dataTable)\n # Connection must be buffered when executing multiple querys on DB before closing connection.\n pointer = connectr.cursor(buffered=True)\n # Create plots\n umtsNetworkPacketLossGraph = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n umtsNetworkDelayGraph = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n gsmNetworkPacketLossGraph = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n gsmNetworkDelayGraph = make_subplots(rows = 1, cols = 1, shared_xaxes = True, shared_yaxes = True)\n umtsNetworkPacketLossGraph, umtsNetworkDelayGraph, gsmNetworkPacketLossGraph, gsmNetworkDelayGraph = ran_functions.queryTxData(pointer, startTime, ranController.bscNameList, ranController.rncNameList, umtsNetworkPacketLossGraph, umtsNetworkDelayGraph, gsmNetworkPacketLossGraph, gsmNetworkDelayGraph)\n umtsNetworkPacketLossGraph.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='UMTS Network Packet Loss'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n umtsNetworkDelayGraph.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='UMTS Network Delay'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n gsmNetworkPacketLossGraph.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='GSM Network Packet Loss'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n gsmNetworkDelayGraph.update_layout(\n plot_bgcolor=graphColors.plot_bgcolor, \n paper_bgcolor=graphColors.paper_bgcolor, \n font_color=graphColors.font_color, \n margin=dict(l=10, r=10, t=90, b=10),\n #legend=dict(orientation='h'),\n title=dict(text='GSM Network Delay'),\n title_font=dict(size=graphColors.graphTitleFontSize),\n legend_font_size=graphColors.legend_font_size\n )\n # Close DB connection\n pointer.close()\n connectr.close()\n return umtsNetworkPacketLossGraph, umtsNetworkDelayGraph, gsmNetworkPacketLossGraph, gsmNetworkDelayGraph\n else:\n raise PreventUpdate\n\n# Callback to hide/display selected tab\n@app.callback(\n [\n Output('networkOverviewGridContainer', 'style'),\n Output('graphGridContainer', 'style'),\n Output('outerTopWorstReportFlexContainer', 'style'),\n Output('networkCheckGridContainer', 'style'),\n Output('graphInsightFlexContainer', 'style'),\n Output('txCheckGridContainer', 'style')\n ], \n Input('tabsContainer', 'value')\n)\ndef showTabContent(currentTab):\n networkOverview = networkOverviewStyles.networkOverviewGridContainerStyle\n engDashboard = engDashboardStyles.graphGridContainerStyle\n topWorst = dataTableStyles.outerTopWorstReportFlexContainer\n networkCheck = networkCheckStyles.networkCheckGridContainer\n graphInsight = graphInsightStyles.graphInsightFlexContainer\n txCheck = txCheckStyles.txCheckGridContainer\n if currentTab == 'Network Overview':\n networkOverview['display'] = 'grid'\n engDashboard['display'] = 'none'\n topWorst['display'] = 'none'\n networkCheck['display'] = 'none'\n graphInsight['display'] = 'none'\n txCheck['display'] = 'none'\n return networkOverview, engDashboard, topWorst, networkCheck, graphInsight, txCheck\n elif currentTab == 'Engineering Dashboard':\n networkOverview['display'] = 'none'\n engDashboard['display'] = 'grid'\n topWorst['display'] = 'none'\n networkCheck['display'] = 'none'\n graphInsight['display'] = 'none'\n txCheck['display'] = 'none'\n return networkOverview, engDashboard, topWorst, networkCheck, graphInsight, txCheck\n elif currentTab == 'Top Worst Report':\n networkOverview['display'] = 'none'\n engDashboard['display'] = 'none'\n topWorst['display'] = 'flex'\n networkCheck['display'] = 'none'\n graphInsight['display'] = 'none'\n txCheck['display'] = 'none'\n return networkOverview, engDashboard, topWorst, networkCheck, graphInsight, txCheck\n elif currentTab == 'Network Check':\n networkOverview['display'] = 'none'\n engDashboard['display'] = 'none'\n topWorst['display'] = 'none'\n networkCheck['display'] = 'grid'\n graphInsight['display'] = 'none'\n txCheck['display'] = 'none'\n return networkOverview, engDashboard, topWorst, networkCheck, graphInsight, txCheck\n elif currentTab == 'Graph Insight':\n networkOverview['display'] = 'none'\n engDashboard['display'] = 'none'\n topWorst['display'] = 'none'\n networkCheck['display'] = 'none'\n graphInsight['display'] = 'flex'\n txCheck['display'] = 'none'\n return networkOverview, engDashboard, topWorst, networkCheck, graphInsight, txCheck\n else:\n networkOverview['display'] = 'none'\n engDashboard['display'] = 'none'\n topWorst['display'] = 'none'\n networkCheck['display'] = 'none'\n graphInsight['display'] = 'none'\n txCheck['display'] = 'grid'\n return networkOverview, engDashboard, topWorst, networkCheck, graphInsight, txCheck\n\n# Callback to hide/display Top Worst inner tabs\n@app.callback(\n [\n Output('datatableGridContainer', 'style'),\n Output('zeroTrafficGridContainer', 'style'),\n Output('topReportRecordGridContainer', 'style')\n ], \n Input('innerTopWorstTabContainer', 'value')\n)\ndef showTopWorstInnerTabContent(currentTab):\n topWorstDaily = dataTableStyles.datatableGridContainer\n zeroTrafficDaily = dataTableStyles.zeroTrafficGridContainer\n topWorstRecord = dataTableStyles.topWorstRecordGridContainer\n if currentTab == 'Daily Report':\n topWorstDaily['display'] = 'grid'\n zeroTrafficDaily['display'] = 'none'\n topWorstRecord['display'] = 'none'\n return topWorstDaily, zeroTrafficDaily, topWorstRecord\n elif currentTab == 'Zero Traffic':\n topWorstDaily['display'] = 'none'\n zeroTrafficDaily['display'] = 'grid'\n topWorstRecord['display'] = 'none'\n return topWorstDaily, zeroTrafficDaily, topWorstRecord\n else:\n topWorstDaily['display'] = 'none'\n zeroTrafficDaily['display'] = 'none'\n topWorstRecord['display'] = 'grid'\n return topWorstDaily, zeroTrafficDaily, topWorstRecord\n\nif __name__ == '__main__':\n app.run_server(debug=True, host='0.0.0.0', port='5006', dev_tools_silence_routes_logging=False)\n\n","sub_path":"ranEngDashboard.py","file_name":"ranEngDashboard.py","file_ext":"py","file_size_in_byte":99608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"22196234","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\nfrom .core import AbstractXMLRemoteModel\nfrom .. import serializers, errors, compat\nfrom ..compat import Enum\n\n\nclass TaskType(Enum):\n UnknownTask = 'UNKNOWN'\n SQLTask = 'SQL'\n\n\ndef _get_task_type(name):\n try:\n return TaskType(name)\n except ValueError:\n return TaskType.UnknownTask\n\n\nclass Task(AbstractXMLRemoteModel):\n\n __slots__ = 'name', 'comment', 'properties'\n\n _type_indicator = 'type'\n\n name = serializers.XMLNodeField('Name')\n type = serializers.XMLTagField('.', parse_callback=lambda s: _get_task_type(s.upper()))\n comment = serializers.XMLNodeField('Comment')\n properties = serializers.XMLNodePropertiesField('Config', 'Property',\n key_tag='Name', value_tag='Value')\n\n def __new__(cls, *args, **kwargs):\n typo = kwargs.get('type')\n\n if typo is not None:\n task_cls = globals().get(typo.name, cls)\n else:\n task_cls = cls\n\n return object.__new__(task_cls)\n\n def set_property(self, key, value):\n if self.properties is None:\n self.properties = compat.OrderedDict()\n self.properties[key] = value\n\n def serialize(self):\n if self.type == TaskType.UnknownTask:\n raise errors.OdpsError('Unknown task type')\n return super(Task, self).serialize()\n\n\ndef format_cdata(query):\n stripped_query = query.strip()\n if not stripped_query.endswith(';'):\n stripped_query += ';'\n return '' % stripped_query\n\n\nclass SQLTask(Task):\n __slots__ = '_anonymous_sql_task_name',\n\n _root = 'SQL'\n _anonymous_sql_task_name = 'AnonymousSQLTask'\n\n query = serializers.XMLNodeField('Query', serialize_callback=format_cdata)\n\n def __init__(self, **kwargs):\n if 'name' not in kwargs:\n kwargs['name'] = SQLTask._anonymous_sql_task_name\n super(SQLTask, self).__init__(**kwargs)\n\n def serial(self):\n if self.properties is None:\n self.properties = compat.OrderedDict()\n\n key = 'settings'\n if key not in self.properties:\n self.properties[key] = '{\"odps.sql.udf.strict.mode\": \"true\"}'\n\n return super(SQLTask, self).serial()\n\ntry:\n from ..internal.models.tasks import *\nexcept ImportError:\n pass\n","sub_path":"odps/models/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"648445934","text":"'''\nKevin Chen, James Marlin, Quoc Nguyen\n'''\n\nimport os\nimport json\n\ndef get_animes_imagepaths():\n '''\n Creates a dictionary where keys are\n the names of animes and values are\n the paths to their pictures. \n '''\n anime_imagespaths_dictionary = {}\n for images_root, letter_dir, images_files in os.walk('static/images/'):\n for anime in letter_dir:\n path = os.path.join(images_root, anime)\n for anime_folder_root, anime_folder_directories, anime_folder_files in os.walk(path):\n for current_file in anime_folder_files:\n anime_title = anime_folder_root.split('/')[-1]\n anime_imagespaths_dictionary[anime_title] = os.path.join(anime_folder_root, current_file) \n print(anime_title)\n return anime_imagespaths_dictionary\n\ndef put_dictionary_as_json():\n dictionary = get_animes_imagepaths()\n json_file = open('animes_imagepaths2.json', 'w')\n json_file.write(json.dumps(dictionary))\n\n#get_animes_imagepaths()\nput_dictionary_as_json()\n\n","sub_path":"image_related_functions.py","file_name":"image_related_functions.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"566220684","text":"import requests\nfrom bs4 import BeautifulSoup as BS\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\nimport sqlite3\nfrom selenium.webdriver.common.action_chains import ActionChains\n\noptions = Options()\noptions.headless = False\nsoccer_url = 'https://www.oddsportal.com/results/#soccer'\nbookmaker_url = 'https://www.oddsportal.com/bookmakers/'\nimport time\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0'\n}\ndb = 'oddsportal.db'\n\ndef main():\n browser = webdriver.Firefox(options=options)\n r = requests.get(soccer_url, headers=headers)\n html = BS(r.content, 'html.parser')\n body = html.select('table.table-main.sport')\n ligs = body[0].select('td')\n for lig in ligs:\n if len(lig.select('a'))>0:\n href_liga = lig.select('a')[0]['href']\n if href_liga.split('/')[1] == 'soccer':\n liga_request_allyears = requests.get('https://www.oddsportal.com' + href_liga, headers=headers)\n soup_liga = BS(liga_request_allyears.content, 'html.parser')\n years_menu = soup_liga.select('.main-menu2.main-menu-gray')\n years_pages = years_menu[0].select('a')\n browser.get('https://www.oddsportal.com' + years_pages[0]['href'])\n content_browser = browser.page_source\n soup_liga = BS(content_browser, 'html.parser')\n breadcrump = soup_liga.select('#breadcrumb')\n breadcrump_a = breadcrump[0].select('a')\n liga = breadcrump_a[3].text\n for page in years_pages:\n print(page['href'])\n browser.get('https://www.oddsportal.com' + page['href'])\n content_browser = browser.page_source\n soup_liga = BS(content_browser, 'html.parser')\n if len(soup_liga.select('#pagination')) == 0:\n matches = soup_liga.select('td.name.table-participant')\n else:\n matches = soup_liga.select('td.name.table-participant')\n max_page = soup_liga.select('#pagination')[0].select('a')[-1]['x-page']\n p = 2\n while p != int(max_page):\n browser.get('https://www.oddsportal.com' + page['href'] + '#/page/%s/' % str(p))\n content_browser = browser.page_source\n soup_liga = BS(content_browser, 'html.parser')\n matches += soup_liga.select('td.name.table-participant')\n p += 1\n for match in matches:\n match_url ='https://www.oddsportal.com' + match.select('a')[0]['href']\n print(match_url)\n browser.get(match_url)\n content_match = browser.page_source\n soup_liga = BS(content_match, 'html.parser')\n col_content = soup_liga.select('#col-content')\n name = col_content[0].select('h1')[0].text\n print(name)\n date = col_content[0].select('p.date')[0].text\n print(date)\n try:\n result = col_content[0].select('p.result')[0].text\n except IndexError:\n result = 'Canceled'\n print(result)\n breadcrump = soup_liga.select('#breadcrumb')\n breadcrump_a = breadcrump[0].select('a')\n sport = breadcrump_a[1].text\n country = breadcrump_a[2].text\n print(liga)\n print(sport)\n print(country)\n data_parsing = [name, match_url, date, result, sport, country, liga]\n if not add_game_in_db(data_parsing):\n continue\n table_odds = soup_liga.select('table.table-main.detail-odds')\n bets = table_odds[0].select('tr.lo')\n bets_dict = {}\n\n right_odds = table_odds[0].select('td.right.odds')\n right_odds_browser = browser.find_elements_by_css_selector('td.right.odds')\n\n for bet in bets:\n bookmaker = bet.select('a.name')[0].text\n print(bookmaker)\n right_odds_bet = bet.select('td.right.odds')\n odds_list = []\n for odd in right_odds_bet:\n try:\n if odd.select('div')[0]['onmouseout'] == \"delayHideTip()\":\n index = right_odds.index(odd)\n hov = ActionChains(browser).move_to_element(right_odds_browser[index])\n hov.perform()\n content_bet = browser.page_source\n soup = BS(content_bet, 'html.parser')\n help_box = soup.select('span.help')[0].text\n open_odds = help_box.split(' ')[-1]\n odds_list.append(open_odds)\n print(open_odds)\n except KeyError:\n open_odds = odd.select('div')[0].text\n odds_list.append(open_odds)\n print(open_odds)\n bets_dict[bookmaker] = odds_list\n print(bets_dict)\n add_bet_in_db(bets_dict,data_parsing)\n browser.quit()\n\n\n\n\n\ndef parsing_bookmaker():\n r = requests.get(bookmaker_url, headers=headers)\n html = BS(r.content, 'html.parser')\n bookmakers = html.select('a.no-ext') #\n for bookmaker in bookmakers:\n if bookmaker.text:\n add_bookmaker_in_db(bookmaker.text)\n\n\ndef add_game_in_db(data_parsing: list):\n con = sqlite3.connect('oddsportal.db')\n cur = con.cursor()\n query = 'SELECT name,url,date,result,sport,country,liga FROM game'\n cur.execute(query)\n data_game = [[el for el in name] for name in cur.fetchall()]\n if data_parsing in data_game:\n print('[INFO] %s игра уже есть в базе' % data_parsing[0])\n cur.close()\n con.close()\n return False\n else:\n cur.execute('INSERT INTO game (name,url,date,result,sport,country,liga) '\n 'VALUES(?,?,?,?,?,?,?)', data_parsing)\n con.commit()\n print('[INFO] игра %s добавлен в базу' % data_parsing[0])\n cur.close()\n con.close()\n return True\n\ndef add_bet_in_db(bets_dict:dict,data_parsing: list):\n con = sqlite3.connect('oddsportal.db')\n cur = con.cursor()\n query = 'SELECT id,name,url,date,result,sport,country,liga FROM game'\n cur.execute(query)\n data_game_dict = {}\n for game in cur.fetchall():\n data_game_dict[game[0]] = [el for el in game[1:]]\n key_game = None\n for key, item in data_game_dict.items():\n if item == data_parsing:\n key_game = key\n break\n for key, item in bets_dict.items():\n add_bookmaker_in_db(key)\n key_bookmaker = None\n query = 'SELECT * FROM bookmaker'\n cur.execute(query)\n data_bookmakers = [[el for el in bookmaker] for bookmaker in cur.fetchall()]\n for bookmaker in data_bookmakers:\n if bookmaker[1] == key:\n key_bookmaker = bookmaker[0]\n break\n data_out = [key_bookmaker, item[0], item[1], item[2], key_game]\n cur.execute('INSERT INTO bet (bookmaker_id,p1,x,p2,game_id) VALUES(?,?,?,?,?)', data_out)\n con.commit()\n print('[INFO] Ставка добавлена в базу')\n cur.close()\n con.close()\n\n\ndef add_bookmaker_in_db(name: str):\n con = sqlite3.connect('oddsportal.db')\n cur = con.cursor()\n query = 'SELECT * FROM bookmaker'\n cur.execute(query)\n data_name = [name[1] for name in cur.fetchall()]\n if name in data_name:\n print('[INFO] %s букмекер уже есть в базе' % name)\n else:\n cur.execute('INSERT INTO bookmaker (name) VALUES(?)', [name])\n con.commit()\n print('[INFO] Букмекер %s добавлен в базу' % name)\n cur.close()\n con.close()\n\nmain()\n\n\n# # for country in countrys:\n# # if str(country['style']) == 'display: table-row;':\n# # print(country['class'])\n# # print(len(countrys))\n# time.sleep(5)\n# browser.close()\n#main()","sub_path":"data_ repl.py","file_name":"data_ repl.py","file_ext":"py","file_size_in_byte":8975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"10363438","text":"#!/usr/bin/python3\nfrom flask import Flask, render_template\nfrom models import storage\nfrom models.state import State\nfrom models.city import City\napp = Flask(__name__)\n\n\n@app.route('/states')\ndef cities():\n my_list = storage.all(\"State\").values()\n return render_template('9-states.html', my_id=\"no_need\", my_ids=my_list)\n\n\n@app.route('/states/')\ndef city_ids(id):\n my_list = storage.all(\"State\").values()\n for x in my_list:\n if str(x.id) == id:\n found = x\n return render_template('9-states.html', my_id=found, my_ids=x)\n return render_template('9-states.html', my_id=\"None\", my_ids=x)\n\n\n@app.teardown_appcontext\ndef teardown(self):\n storage.close()\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=\"5000\")\n","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"541760373","text":"notas = []\r\n\r\ncantidad_notas = int(input('cantidad de notas: '))\r\n\r\nfor n in range(cantidad_notas):\r\n nota = float(input('nota No {}: '.format(n + 1)))\r\n notas.append(nota)\r\n\r\nsuma = 0\r\nfor nota in notas:\r\n suma += nota\r\n\r\npromedio = suma / len(notas)\r\nprint('tu promedio es {}'.format(promedio))\r\n\r\nif promedio < 11:\r\n print('jalaste :(')\r\nelse:\r\n print('aprobaste :)')\r\n","sub_path":"ppy/notas.py","file_name":"notas.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"606800655","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# This script contains only feature engineering and model training from which we obtain the best score.\n\n# In[ ]:\n\n\n#! pip install xgboost\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nimport xgboost as xgb\nimport re\n\nplt.style.use('seaborn')\npd.set_option('display.max_column',100)\n\n\n# In[ ]:\n\n\nTrainData = pd.read_csv('train.csv')\nTestData = pd.read_csv('test.csv')\nSessData = pd.read_csv('sessions.csv')\nSessData.rename(columns={'user_id':'id'},inplace = True)\n\n\n# In[ ]:\n\n\naction_type = pd.pivot_table(SessData, index = ['id'],columns = ['action_type'],values = 'secs_elapsed',aggfunc=len,fill_value=0).reset_index()\naction = pd.pivot_table(SessData, index = ['id'],columns = ['action'],values = 'secs_elapsed',aggfunc=len,fill_value=0).reset_index()\naction_detail = pd.pivot_table(SessData, index = ['id'],columns = ['action_detail'],values = 'secs_elapsed',aggfunc=len,fill_value=0).reset_index()\ndevice_type = pd.pivot_table(SessData, index = ['id'],columns = ['device_type'],values = 'secs_elapsed',aggfunc=len,fill_value=0).reset_index()\n\n\n# In[ ]:\n\n\naction_type['booking_response'] = action_type['booking_response'].apply(lambda x: 1 if x>0 else 0)\naction_type['-unknown-'] = action_type['-unknown-'].apply(lambda x: 1 if x>0 else 0)\n\naction_detail['pending'] = action_detail['pending'].apply(lambda x: 1 if x>0 else 0)\naction_detail['at_checkpoint'] = action_detail['at_checkpoint'].apply(lambda x: 1 if x>0 else 0)\n\n\n# In[ ]:\n\n\nDataCom = pd.concat((TrainData.drop('country_destination',axis=1),TestData),axis=0,ignore_index=True)\ndef set_age_group(x):\n if x < 40:\n return 'Young'\n elif x >=40 and x < 60:\n return 'Middle'\n elif x >= 60 and x <= 125:\n return 'Old'\n else:\n return 'Unknown'\n\n\ndef set_age(x):\n if x>=16 and x<=120:\n return x\n elif x<16:\n return np.nan\n elif x>120:\n if 2015-x>16 and 2015-x<110:\n return 2015-x\n else:\n return np.nan\n\ndef set_categorial_values(x):\n l = ['first_browser','affiliate_provider','first_device_type','affiliate_channel','first_affiliate_tracked','signup_app']\n thresold = [0.00]*10\n \n i = l.index(x)\n l1 = DataCom[x].value_counts(normalize=True)\n l2 = l1[l1>thresold[i]].index.tolist()\n return DataCom[x].apply(lambda x: x if x in l2 else 'diff')\n\ndef feature_engineering(df):\n df['DAC_year'] = np.vstack(df['date_account_created'].astype(str).apply(lambda x: list(map(int, x.split('-')))).values)[:,0]\n df['DAC_month'] = np.vstack(df['date_account_created'].astype(str).apply(lambda x: list(map(int, x.split('-')))).values)[:,1]\n df['DAC_day'] = np.vstack(df['date_account_created'].astype(str).apply(lambda x: list(map(int, x.split('-')))).values)[:,2]\n df['DAC_dayofweek'] = pd.to_datetime(df['date_account_created']).dt.dayofweek\n \n df['TFA_year'] = np.vstack(df.timestamp_first_active.astype(str).apply(lambda x: list(map(int, [x[:4],x[4:6],x[6:8],x[8:10],x[10:12],x[12:14]]))).values)[:,0]\n df['TFA_month'] = np.vstack(df.timestamp_first_active.astype(str).apply(lambda x: list(map(int, [x[:4],x[4:6],x[6:8],x[8:10],x[10:12],x[12:14]]))).values)[:,1]\n df['TFA_day'] = np.vstack(df.timestamp_first_active.astype(str).apply(lambda x: list(map(int, [x[:4],x[4:6],x[6:8],x[8:10],x[10:12],x[12:14]]))).values)[:,2]\n df['TFA_hour'] = np.vstack(df.timestamp_first_active.astype(str).apply(lambda x: list(map(int, [x[:4],x[4:6],x[6:8],x[8:10],x[10:12],x[12:14]]))).values)[:,3]\n \n df['DFB_year'] = np.vstack(df['date_first_booking'].fillna(-1).astype(str).apply(lambda x: -1 if x=='-1' else list(map(int,x.split('-')))[0] ))\n df['DFB_month'] = np.vstack(df['date_first_booking'].fillna(-1).astype(str).apply(lambda x: -1 if x=='-1' else list(map(int,x.split('-')))[1] ))\n df['DFB_day'] = np.vstack(df['date_first_booking'].fillna(-1).astype(str).apply(lambda x: -1 if x=='-1' else list(map(int,x.split('-')))[2] ))\n df['DFB_dayofweek'] = pd.to_datetime(df['date_first_booking']).dt.dayofweek\n \n df['lag'] = (pd.to_datetime(df.date_account_created)-pd.to_datetime(df.timestamp_first_active,format='%Y%m%d%H%M%S')).dt.days\n \n df['age'] = df['age'].apply(set_age)\n df['age_group'] = df['age'].apply(set_age_group)\n df['age'] = df['age'].fillna(-1)\n \n \n df['has_booked'] = df['date_first_booking'].fillna(-1).apply(lambda x: 0 if x==-1 else 1)\n df['first_affiliate_tracked'] = df['first_affiliate_tracked'].fillna('unknown')\n \n l = ['first_browser','affiliate_provider','first_device_type','affiliate_channel','first_affiliate_tracked','signup_app']\n for x in l:\n df[x] = set_categorial_values(x)\n \n ohe = ['gender', 'signup_method', 'language', 'affiliate_channel', 'affiliate_provider', \n 'first_affiliate_tracked', 'signup_app', 'first_device_type', 'first_browser','age_group']\n \n for x in ohe:\n combined_data,_ = pd.factorize(df[x],sort=True)\n combined_data = pd.Series(combined_data).astype('int32')\n df[x] = combined_data.values \n \n droplist = ['date_account_created','timestamp_first_active','date_first_booking','signup_method']\n df = df.drop(droplist,axis=1)\n \n df = pd.merge(df, action_type[['id','booking_response','-unknown-']], how='left', on='id')\n df = pd.merge(df, action[['id','requested', 'confirm_email', 'update', 'cancellation_policies']], how='left', on='id')\n df = pd.merge(df, action_detail[['id','pending', 'at_checkpoint']], how='left', on='id')\n \n df = df.set_index('id')\n \n return df\n\n\nDataCom = feature_engineering(DataCom)\n\n\n# In[ ]:\n\n\ny = TrainData['country_destination'] \nlabels = y.values\nle = LabelEncoder()\ny = pd.Series(le.fit_transform(labels)) \n\nX = DataCom[:TrainData.shape[0]] # encoded train data x \ndf_test = DataCom[TrainData.shape[0]:] # encoded test data\n\nx_train, x_test, y_train, y_test = train_test_split(X, y,random_state=31, train_size=0.80, stratify=y)\n\n\n# In[ ]:\n\n\nxgb3 = xgb.XGBClassifier(max_depth=4, learning_rate=0.01, n_estimators=75,\n objective='multi:softprob', subsample=0.6, colsample_bytree=0.6, seed=40,reg_lambda=0.5)\nxgb3.fit(X, y)\n\n\n# In[ ]:\n\n\nprob = xgb3.predict_proba(df_test)\nid_test = TestData['id']\n\nid_final_sub = [] \npred_final_sub = [] \nfor i in range(len(id_test)):\n idx = id_test[i]\n id_final_sub += [idx] * 3\n pred_final_sub += le.inverse_transform(np.argsort(prob[i])[::-1])[:3].tolist()\n\nsub = pd.DataFrame(np.column_stack((id_final_sub,pred_final_sub)), columns=['id', 'country_destination'])\nsub.to_csv('submission.csv',index=False)\n\n","sub_path":"Final Code/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":6876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"98938688","text":"from manage import *\nfrom models import *\nimport query\n\nclass OverviewHandler(AdminBaseHandler):\n\n def get(self):\n config = ndb.Key(Settings, 'config').get()\n if not config:\n config = Settings(id='config')\n due_date = config.due_date\n\n applicants, applications = query.get_all_overview()\n template_values = {\n 'applicants': applicants,\n 'applications': applications,\n 'admin_url': '/admin/overview',\n 'DUE_DATE': due_date\n }\n self.render_template('admin-overview.html', template_values)\n","sub_path":"manage/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"69634179","text":"'''\nDesafio 056\n\nDesenvolva um programa que leia o nome, idade e\nsexo de 4 pessoas. No final do programa, mostre:\n- A média de idade do grupo.\n- Qual é o nome do homem mais velho.\n- Quantas mulheres tem menos de 20 anos.\n'''\nsoma_idade = 0\nmaior_idade_homem = 0\nqtd_mulheres_menor_20 = 0\n\nfor i in range(1, 5):\n print(f'----- {i}ª PESSOA -----')\n nome = str(input('Nome: ')).strip()\n idade = int(input('Idade: '))\n sexo = str(input('Sexo [M/F]: ')).strip()\n\n # Soma das idades\n soma_idade += idade\n\n # Homem mais velho e seu nome\n if sexo in 'Mm' and idade > maior_idade_homem:\n maior_idade_homem = idade\n nome_homem_mais_velho = nome\n\n # Mulher com menos de 20 anos\n if sexo in \"Ff\" and idade < 20:\n qtd_mulheres_menor_20 += 1\n\n\nmedia_idade = soma_idade / 4\nprint(f'A média de idade do grupo é de {media_idade} anos')\nprint(f'O homem mais velho tem {maior_idade_homem} anos e chama-se {nome_homem_mais_velho}')\nprint(f'Ao todo são {qtd_mulheres_menor_20} mulheres com menos de 20 anos')\n","sub_path":"Curso em Video/Aula 13 - Estruturas de Repetição/Desafio056.py","file_name":"Desafio056.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"607852802","text":"############################################################################################\n############################# MAIN CODE FOR STUDENT LOANS PROJECT ##########################\n############################# MODEL WITH ONTHEJOB-S + mrisk ##########################\n############################################################################################\n\n############################################################################################\n############################# MAIN CODE FOR STUDENT LOANS PROJECT ##########################\n############################# MODEL WITH SEARCH ON THE JOB ##########################\n############################################################################################\n\n\nimport numpy as np\n#import sys\n#import os\n#import math\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n#import numpy.matlib\nfrom scipy.optimize import fsolve\n#from scipy.optimize import brentq\n#from scipy.interpolate import griddata\n#from scipy.interpolate import CubicSpline\nfrom scipy.optimize import root\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy import interpolate\nfrom scipy.interpolate import interpn\nfrom scipy.interpolate import griddata\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF, WhiteKernel, RationalQuadratic, ExpSineSquared, ConstantKernel as C\nimport warnings\n#from numpy import linalg as LA\nfrom numba import jit\nimport random\nimport pyipopt\nimport quantecon as qe\n\n\nfrom params import *\nfrom declare_arrays import *\n\n\n############################################################################################\n############################################################################################\n\n############################ DECLARATIONS : GENERAL USE FUNCTIONS ############################\n\ndef m_fun(theta):\n return 1 - np.exp(-eta * theta)\n\ndef m_funprime(theta):\n return eta * np.exp(-eta * theta)\n\ndef q_fun(theta):\n if (theta==0.0):\n return 1.0\n else:\n return (1 - np.exp(-eta * theta))/theta\n\ndef q_funprime(theta):\n if (theta==0.0):\n return 1.0\n else:\n return -np.exp(-eta * theta)*(np.exp(eta * theta)-eta*theta-1)/theta**2\n # -(1 / (theta ** 2)) + ((1+eta*theta) * np.exp(-eta * theta))/(theta**2)\n\ndef u(c):\n if nu == 1:\n return np.log(c)\n else:\n return (c ** (1 - nu)) / (1 - nu)\n\ndef uprime_inv(c):\n return c ** (-1 / nu)\n\ndef u_prime(c):\n return c ** (-nu)\n\ndef k_fun(y):\n return kappa*(y**gamma)/gamma\n\ndef k_funprime(y):\n return kappa*(y**(gamma-1))\n\ndef c_u(a, a_prime):\n return b + R * a - a_prime\n\ndef c_e(w, a, a_prime):\n return w + R * a - a_prime\n\ndef l_fun(dis):\n if np.abs(dis):\n dis = dis/np.abs(dis)\n return 1/(1+np.exp(-2*100*dis))\n\ndef l_fun_prime(dis):\n if np.abs(dis):\n dis = dis/np.abs(dis)\n return 2*100*np.exp(2*100*dis)/(1+np.exp(2*100*dis))**2\n\ndef g_fun(p, x):\n y = p*adj\n return x + phi*(y-x)*l_fun(y-x)\n\ndef g_fun_prime(p, x):\n y = p*adj\n return phi*l_fun(y-x) + phi*(y-x)*l_fun_prime(y-x)\n\ndef t_fun(p, x):\n y = p*adj\n if (y sitk.Image:\n pass\n\n\nclass ComposeTransform(Transform):\n\n def __init__(self, transforms) -> None:\n super().__init__()\n self.transforms = transforms\n\n def __call__(self, img: sitk.Image) -> sitk.Image:\n for transform in self.transforms:\n img = transform(img)\n return img\n\n\nclass RescaleIntensity(Transform):\n\n def __init__(self, min=0, max=65535) -> None:\n super().__init__()\n self.min = min\n self.max = max\n\n def __call__(self, img: sitk.Image) -> sitk.Image:\n return sitk.RescaleIntensity(img, self.min, self.max)\n\n\nclass Resample(Transform):\n\n def __init__(self, new_spacing: tuple) -> None:\n super().__init__()\n self.new_spacing = new_spacing\n\n def __call__(self, img: sitk.Image) -> sitk.Image:\n size, spacing, origin, direction = img.GetSize(), img.GetSpacing(), img.GetOrigin(), img.GetDirection()\n\n scale = [ns / s for ns, s in zip(self.new_spacing, spacing)]\n new_size = [int(sz/sc) for sz, sc in zip(size, scale)]\n # new_origin = [o / sc for o, sc in zip(origin, scale)]\n\n resampler = sitk.ResampleImageFilter()\n resampler.SetSize(new_size)\n # resampler.SetTransform(sitk.Transform())\n resampler.SetInterpolator(sitk.sitkLinear)\n resampler.SetOutputDirection(direction)\n # resampler.SetOutputOrigin(new_origin) # misfitted image when using adapted origin\n resampler.SetOutputOrigin(origin)\n resampler.SetOutputSpacing(self.new_spacing)\n\n return resampler.Execute(img)\n\n\nclass MergeLabel(Transform):\n\n def __init__(self, to_combine: dict) -> None:\n super().__init__()\n # to_combine is a dict with keys -> new label and values -> list of labels to merge\n self.to_combine = to_combine\n\n def __call__(self, img: sitk.Image) -> sitk.Image:\n np_img = sitk.GetArrayFromImage(img)\n merged_img = np.zeros_like(np_img)\n\n for new_label, labels_to_merge in self.to_combine.items():\n merged_img[np.in1d(np_img.ravel(), labels_to_merge, assume_unique=True).reshape(np_img.shape)] = new_label\n\n out_img = sitk.GetImageFromArray(merged_img)\n out_img.CopyInformation(img)\n return out_img\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='data preparation for the MIALab')\n parser.add_argument(\n '--data_dir',\n type=str,\n required=True,\n help='the path to the dataset'\n )\n\n args = parser.parse_args()\n main(args.data_dir)\n","sub_path":"bin/prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":8760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"421269739","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport datetime\nimport khayyam\nfrom base_app.classes.debug import Debug\nfrom base_app.models.mongodb.base_model import MongodbModel, BaseModel\nfrom base_app.models.mongodb.user.general_info.general_info import UserModel\n\n__author__ = 'Morteza'\n\n\nclass NewsReportBrokenModel(BaseModel):\n def __init__(self, _id=None, news=None, title=None, user=None, text=None, link=None):\n BaseModel.__init__(self)\n self.id = _id\n self.news = news\n self.user = user\n self.text = text\n self.title = title\n self.link = link\n self.result = {'value': {}, 'status': False}\n\n def save(self):\n try:\n __body = {\n 'news': self.news,\n 'user': self.user,\n 'text': self.text,\n 'title': self.title,\n 'link': self.link,\n 'date': datetime.datetime.now(),\n }\n self.result['value'] = MongodbModel(collection='news_report_broken', body=__body).insert()\n self.result['status'] = True\n return self.result\n except:\n Debug.get_exception(sub_system='admin', severity='error', tags='mongodb > save', data='collection > subject')\n return self.result\n\n def get_all(self, _page=1, _size=20):\n try:\n __body = {}\n r = MongodbModel(collection='news_report_broken', body=__body, page=_page, size=_size).get_all_pagination()\n ls = []\n for i in r:\n i['date'] = khayyam.JalaliDatetime(i['date']).strftime('%Y/%m/%d %H:%M:%S')\n try:\n i['full_name'] = UserModel(_id=i['user']).get_one()['value']['full_name']\n except:\n i['full_name'] = ''\n ls.append(i)\n self.result['value'] = ls\n self.result['status'] = True\n return self.result\n except:\n Debug.get_exception(sub_system='admin', severity='error', tags='mongodb > get_all', data='collection > news_report_broken')\n return self.result\n\n @staticmethod\n def get_count_all():\n try:\n __body = {}\n r = MongodbModel(collection='news_report_broken', body=__body).count()\n if r:\n return r\n return 0\n except:\n Debug.get_exception(sub_system='admin', severity='error', tags='mongodb > get_all', data='collection > news_report_broken')\n return 0\n\n def delete(self):\n try:\n __body = {\"_id\": self.id}\n r = MongodbModel(collection='news_report_broken', body=__body).delete()\n self.result['value'] = r\n self.result['status'] = True\n except:\n Debug.get_exception(sub_system='admin', severity='error', tags='mongodb > get_all', data='collection > news_report_broken')\n return self.result","sub_path":"base_app/models/mongodb/news_report_broken/news_report_broken.py","file_name":"news_report_broken.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"612471075","text":"#!/usr/bin/python\nimport roslib\nimport rospy\nimport math as m\nfrom matplotlib.pyplot import *\nfrom geometry_msgs.msg import PoseStamped\nfrom geometry_msgs.msg import WrenchStamped\nfrom geometry_msgs.msg import Quaternion\nfrom std_msgs.msg import Float32\nimport numpy as np\nimport kalman as K\nimport tf\n\npub_r = rospy.Publisher(\"/direction/right_arm_estimate\", PoseStamped)\npub_r_t = rospy.Publisher(\"/direction/right_arm\", PoseStamped)\npub_l = rospy.Publisher(\"/direction/left_arm\", PoseStamped)\npub_theta_hat = rospy.Publisher(\"/theta_estimate\", Float32)\npub_mag_force = rospy.Publisher(\"/mag_force\", Float32)\n\nR_wrench = WrenchStamped()\nL_wrench = WrenchStamped()\nR_dir = PoseStamped()\nR_dir_t = PoseStamped()\nL_dir = PoseStamped()\ntheta_pub = Float32()\nmag_force = Float32()\nsave_arrays = True\n\n#--- Arrays to store values\nTHETA = np.array([])\nTHETA_2q = np.array([])\nTHETA_hat = np.array([])\nmag_FORCE = np.array([])\nKK_gain = np.array([])\nPP = np.array([])\nFx = np.array([])\nFy = np.array([])\nFz = np.array([])\nTx = np.array([])\nTy = np.array([])\nTz = np.array([])\n\n\n#--- Kalman Filter initial values\nxhat_0 = 1.57 # start estimate at pi/2 for theta\nP_0 = 1\nfirst_estimate = 1\nxhat = 0\nP = 0\nK_gain = 0\ntheta_euler = 0\nestimation_started = 0\nprint_once = 0\n\ndef r_direction_callback(msg):\n global first_estimate, xhat, P, theta_euler, K_gain, estimation_started, print_once\n global THETA, THETA_hat, THETA_2q, PP, KK_gain, Fx, Fy, Fz, Tx, Ty, Tz, mag_FORCE\n R_wrench = msg\n N_force = m.sqrt((m.pow(R_wrench.wrench.force.x, 2) + m.pow(R_wrench.wrench.force.z, 2)))\n \n if save_arrays == True:\n # --- Collect Fx, Fy and Fz to plot later --\n Fx = np.append(Fx, R_wrench.wrench.force.x)\n Fy = np.append(Fy, R_wrench.wrench.force.y)\n Fz = np.append(Fz, R_wrench.wrench.force.z)\n Tx = np.append(Tx, R_wrench.wrench.torque.x)\n Ty = np.append(Ty, R_wrench.wrench.torque.y)\n Tz = np.append(Tz, R_wrench.wrench.torque.z) \n mag_FORCE = np.append(mag_FORCE, N_force)\n # -----------------------------------------\n\n # --- Create new frame for publishing theta -----\n br_r = tf.TransformBroadcaster()\n br_r.sendTransform((0, 0, 0),\n tf.transformations.quaternion_from_euler(0.0, 1.57, 0.0),\n rospy.Time.now(),\n \"ft_transform_r\",\n \"r_gripper_motor_accelerometer_link\")\n # ----------------------------------------------\n \n if abs(R_wrench.wrench.torque.x) > 0.2 or estimation_started == 1:\n if estimation_started == 0:\n print(\"Someone started to hold the object!\")\n estimation_started = 1\n\n \n #theta = m.acos(R_wrench.wrench.force.x / N_force)\n # Fx_n = R_wrench.wrench.force.x/N_force\n # Fy_n = R_wrench.wrench.force.y/N_force\n # theta_n = m.acos(Fx_n)\n theta_r = m.atan2(R_wrench.wrench.force.z, R_wrench.wrench.force.x)\n if theta_r < 0:\n theta_r_2q = theta_r + m.pi\n else:\n theta_r_2q = theta_r\n if save_arrays == True:\n THETA = np.append(THETA, theta_r)\n THETA_2q = np.append(THETA_2q, theta_r_2q)\n\n # --- Theta_hat estimation with Kalman Filter ---\n if first_estimate == 1:\n (xhat, P, K_gain) = K.Kalman_Filter(theta_r_2q, xhat_0, P_0)\n first_estimate = 0\n \n else:\n (xhat, P, K_gain) = K.Kalman_Filter(theta_r_2q, xhat, P)\n if save_arrays == True:\n KK_gain = np.append(KK_gain, K_gain)\n PP = np.append(PP, P)\n THETA_hat = np.append(THETA_hat, xhat)\n # --- Publish Theta, mag_force for change_detection node ---\n theta_pub = xhat\n mag_force = N_force\n pub_theta_hat.publish(theta_pub)\n pub_mag_force.publish(mag_force)\n # ----------------------------------------------\n\n # --- Publish Theta from Force Measurements ---\n # Note: Theta is published negative for visualization\n R_dir.header.frame_id = 'ft_transform_r' \n theta_euler = xhat\n quat = tf.transformations.quaternion_from_euler(0.0, -theta_euler, 0.0)\n R_dir.pose.orientation.x = quat[0]\n R_dir.pose.orientation.y = quat[1]\n R_dir.pose.orientation.z = quat[2]\n R_dir.pose.orientation.w = quat[3]\n pub_r.publish(R_dir)\n # ---------------------------------------------\n\n # --- Publish estimated Theta -----------------\n # Note: Theta is published negative for visualization\n R_dir_t.header.frame_id = 'ft_transform_r' \n quat = tf.transformations.quaternion_from_euler(0.0, -theta_r, 0.0)\n R_dir_t.pose.orientation.x = quat[0]\n R_dir_t.pose.orientation.y = quat[1]\n R_dir_t.pose.orientation.z = quat[2]\n R_dir_t.pose.orientation.w = quat[3]\n pub_r_t.publish(R_dir_t) \n # ---------------------------------------------\n else:\n if estimation_started == 0:\n if print_once == 0:\n print(\"No one is holding the object\")\n print_once = 1\n else:\n if print_once == 1:\n print(\"Someone stopped holding the object! \\n Estimation has STOPPED\")\n print_once = 2\n return\n\ndef l_direction_callback(msg):\n L_wrench = msg\n br_l = tf.TransformBroadcaster()\n br_l.sendTransform((0, 0, 0),\n tf.transformations.quaternion_from_euler(0.0, 1.57, 0.0),\n rospy.Time.now(),\n \"ft_transform_l\",\n \"l_gripper_motor_accelerometer_link\")\n theta_l = m.atan2(L_wrench.wrench.force.z, L_wrench.wrench.force.x)\n ## -- 0 deg= 0 rad; 90 = pi/2; 180 = pi; 270 = -pi/2\n## if theta_l > 0:\n## theta_r += m.pi\n## rospy.loginfo(\"Theta: %f\", theta_r)\n L_dir.header.frame_id = 'ft_transform_l'\n quat_l = tf.transformations.quaternion_from_euler(0.0, theta_l, 0.0)\n \n L_dir.pose.orientation.x = quat_l[0]\n L_dir.pose.orientation.y = quat_l[1]\n L_dir.pose.orientation.z = quat_l[2]\n L_dir.pose.orientation.w = quat_l[3]\n \n pub_l.publish(L_dir) \n \n return\n\ndef direction_estimate():\n rospy.init_node('direction_estimate', anonymous=True)\n rospy.Subscriber(\"/ft_transformed/rig_arm\", WrenchStamped, r_direction_callback)\n #rospy.Subscriber(\"/ft_transformed/lef_arm\", WrenchStamped, l_direction_callback)\n\n rospy.spin()\n return\n\n \nif __name__ == '__main__':\n\n direction_estimate()\n\n try:\n rate = rospy.Rate(10.0)\n while not rospy.is_shutdown():\n\n rate.sleep()\n\n except KeyboardInterrupt:\n pass\n if save_arrays == True:\n raw_input(\"Press any key to see plot of theta\")\n X_axis = np.linspace(0,(len(THETA)-1),len(THETA))\n X_axis_F = np.linspace(0,(len(Fx)-1),len(Fx))\n print('len(X_axis)',len(X_axis))\n print('len(X_axis_F)',len(X_axis_F))\n freq = 1000\n # Create the ground truth vectors for plotting\n # theta_r_corner = 2.1\n # theta_l_corner = 1.038\n # gnd_truth = np.ones(18662)\n # gnd_truth[0:9331] = m.pi/2\n # gnd_truth[9331:18662] = theta_r_corner\n # x_gnd = X_axis[0:18662]\n # gnd_truth[18662:30001] = theta_l_corner\n # gnd_truth[30001:-1] = m.pi/2\n #angle1 = np.ones(10*freq) * m.pi/2\n #gnd_truth = np.append(gnd_truth, angle1)\n #angle2 = np.ones(10*freq) * m.pi/4\n \n \n \n # figure(1)\n # plot(x_gnd, THETA_2q[0:18662], 'g'), title('THETA_2q'), ylabel('[rad]')\n # plot(x_gnd, THETA_hat[0:18662], 'r'), title('THETA_hat'), ylabel('[rad]') \n # plot(x_gnd, gnd_truth, '--k'), title('Estimator of direction'), ylabel('[rad]')\n # legend(('Direction from measurements','Result of Kalman Filter, vStd = 20', 'Ground truth'),'lower right')\n \n figure(2)\n # #plot(X_axis, THETA, 'b'), title('THETA'), ylabel('[rad]')\n plot(X_axis, THETA_2q, 'g'), title('THETA_2q'), ylabel('[rad]')\n plot(X_axis, THETA_hat, 'r'), title('THETA_hat'), ylabel('[rad]')\n legend(('THETA_2q', 'Estimated THETA'),'upper right')\n\n figure(3) \n subplot(411)\n plot(X_axis_F, Fx, 'r'), title('Fx'), ylabel('[N]')\n subplot(412)\n plot(X_axis_F, Fy, 'g'), title('Fy'), ylabel('[N]')\n subplot(413)\n plot(X_axis_F, Fz, 'b'), title('Fz'), ylabel('[N]')\n subplot(414)\n plot(X_axis_F, mag_FORCE, 'b'), title('mag_FORCE'), ylabel('[N]')\n\n figure(4) \n subplot(311)\n plot(X_axis_F, Tx, 'r'), title('Tx'), ylabel('[Nm]')\n subplot(312)\n plot(X_axis_F, Ty, 'g'), title('Ty'), ylabel('[Nm]')\n subplot(313)\n plot(X_axis_F, Tz, 'b'), title('Tz'), ylabel('[Nm]')\n\n \n ## plot(X_axis, mag_FORCE, 'r'), title(\"Magnitude of Force\")\n\n # figure(\"Kalman Filter\")\n # subplot(211)\n # plot(X_axis, KK_gain),title(\"Kalman Gain for theta\")\n # subplot(212)\n # plot(X_axis, np.sqrt(PP)),title(\"Covariance for theta\")\n \n show()\n\n","sub_path":"scripts/direction_estimate.py","file_name":"direction_estimate.py","file_ext":"py","file_size_in_byte":9094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"546199259","text":"from __future__ import print_function\n\nimport datetime\nimport sys\nimport threading\nimport time\n\nimport usb1\n\nfrom LikeAG13 import G13Lcd, G13_KEYS, LedColors, MissingG13Error\n\n\nclass TerminalUI(object):\n BASE_X, BASE_Y = 0, 10\n scale_x, scale_y = 64, 32\n\n def __init__(self):\n self.prev_x, self.prev_y = 0, 0\n self.prev_keys = {k: 1 for k in G13_KEYS}\n\n def init_stick(self):\n self.reset()\n sys.stdout.write('-' * (self.scale_x + 2) + '\\n')\n for l in range(self.scale_y):\n sys.stdout.write('|' + ' ' * self.scale_x + '|\\n')\n sys.stdout.write('-' * (self.scale_x + 2) + '\\n')\n\n def reset(self):\n self.goto(0, 0)\n\n def goto(self, x, y):\n sys.stdout.write('\\033[%s;%sH' % (self.BASE_Y + y, self.BASE_X + x))\n\n def down(self, num):\n sys.stdout.write('\\033[%sB' % num)\n\n def right(self, num):\n sys.stdout.write('\\033[%sC' % num)\n\n def print_at(self, x, y, s):\n self.goto(x + 1, y + 1)\n sys.stdout.write(s)\n\n def flush(self):\n sys.stdout.flush()\n\n def print_stick(self, x, y):\n x /= 4\n y /= 8\n\n self.print_at(self.prev_x + 1, self.prev_y, ' ')\n self.print_at(x + 1, y, 'x')\n\n self.prev_x, self.prev_y = x, y\n\n def clear_keys(self):\n if not any(self.prev_keys.values()):\n return\n for i in range(5):\n self.print_at(0, self.scale_y + 1 + i, ' ' * (4 * 8))\n\n def set_key(self, key, value):\n if self.prev_keys[key] != value:\n idx = G13_KEYS.index(key)\n y = self.scale_y + 1 + idx / 8\n x = (idx % 8) * 4\n if value:\n out = key\n else:\n out = ' '\n self.print_at(x, y, out)\n\n self.prev_keys[key] = value\n\n\ndef try_get_g13():\n try:\n g13_instance = G13Lcd()\n return g13_instance\n except MissingG13Error:\n print('No G13 found.')\n sys.exit(1)\n\n\ndef lcd_only_ui():\n g13 = try_get_g13()\n\n g13.draw_image('x.png', scale=0.2, offset=(200, 0))\n\n start = time.time()\n\n try:\n while True: # for i in range(300):\n g13.print_time()\n t = 1 / (time.time() - start)\n time.sleep(1 - (time.time() % 1))\n start = time.time()\n g13.set_led_mode(int(time.time() % 16))\n g13.set_color((255, 0, 0))\n time.sleep(0.1)\n g13.set_led_mode(int(time.time() % 16))\n g13.set_color((255, 255, 255))\n except Exception as e:\n print(e)\n except KeyboardInterrupt:\n print('^C')\n finally:\n g13.close()\n return\n\n\ndef lcd_only_ui_colors():\n g13 = try_get_g13()\n\n g13.draw_image('x.png', scale=0.2, offset=(200, 0))\n\n g13.set_led_mode(16)\n\n try:\n while True: # for i in range(300):\n\n # YELLOW\n g13.print_text('255 0 0')\n g13.set_color_from_rgb(255, 0, 0)\n time.sleep(1)\n\n # WHITE\n g13.print_text('WHITE')\n g13.set_color_from_rgb(180, 180, 180)\n time.sleep(1)\n\n # TEAL\n g13.print_text('0 255 0')\n g13.set_color_from_rgb(0, 255, 0)\n time.sleep(1)\n\n # PINK\n g13.print_text('PINK')\n g13.set_color_from_rgb(200, 200, 200)\n time.sleep(1)\n\n # MAGENTA\n g13.print_text('MAGENTA')\n g13.set_color_from_rgb(40, 30, 200)\n time.sleep(1)\n\n # # LIGHTS OUT\n # g13.print_text('0 0 0')\n # g13.set_color_from_rgb(0, 0, 0)\n # time.sleep(1)\n\n for value0 in range(0, 255, 5):\n for value1 in range(0, 255, 5):\n for value2 in range(0, 255, 5):\n\n g13.print_text('{} {} {}'.format(value0, value1, value2))\n g13.set_color_from_rgb(value0, value1, value2)\n time.sleep(0.1)\n try:\n keypress = g13.get_key_press_bytes()\n if keypress is not None:\n print(keypress)\n except Exception as ex:\n print(ex)\n\n\n #\n # parsed_version = g13.parse_keys()\n # if parsed_version is not None:\n # print('parsed version: ')\n # print(parsed_version)\n\n # g13.print_text('AQUA')\n # g13.set_color_from_named_color(LedColors.AQUA)\n # time.sleep(1)\n #\n # g13.print_text('BLUE')\n # g13.set_color_from_named_color(LedColors.BLUE)\n # time.sleep(1)\n #\n # g13.print_text('FUSCHIA')\n # g13.set_color_from_named_color(LedColors.FUSCHIA)\n # time.sleep(1)\n #\n # g13.print_text('GREEN')\n # g13.set_color_from_named_color(LedColors.GREEN)\n # time.sleep(1)\n #\n # g13.print_text('LIME')\n # g13.set_color_from_named_color(LedColors.LIME)\n # time.sleep(1)\n #\n # g13.print_text('MAROON')\n # g13.set_color_from_named_color(LedColors.MAROON)\n # time.sleep(1)\n #\n # g13.print_text('PINK')\n # g13.set_color_from_named_color(LedColors.PINK)\n # time.sleep(1)\n #\n # g13.print_text('PURPLE')\n # g13.set_color_from_named_color(LedColors.PURPLE)\n # time.sleep(1)\n #\n # g13.print_text('RED')\n # g13.set_color_from_named_color(LedColors.RED)\n # time.sleep(1)\n #\n # g13.print_text('YELLOW')\n # g13.set_color_from_named_color(LedColors.YELLOW)\n # time.sleep(1)\n #\n\n except Exception as e:\n print(e)\n except KeyboardInterrupt:\n print('^C')\n finally:\n g13.close()\n return\n\ndef std_out_ui():\n g13 = try_get_g13()\n ui = TerminalUI()\n ui.init_stick()\n try:\n while True:\n try:\n keys = g13.get_key_press_bytes()\n\n g13.print_stick(keys.stick_x, keys.stick_y)\n ui.print_stick(keys.stick_x, keys.stick_y)\n\n parse_keys(ui, keys)\n\n ui.flush()\n g13.write_lcd_bg()\n except usb1.USBError as e:\n if e.value == -7:\n pass\n except Exception as e:\n print(e)\n except KeyboardInterrupt:\n print('^C')\n finally:\n g13.close()\n\n\ndef parse_keys(ui, keys):\n if not any(keys.keys):\n ui.clear_keys()\n return\n\n for i, key in enumerate(G13_KEYS):\n b = keys.keys[i / 8]\n ui.set_key(key, b & 1 << (i % 8))\n\n\nif __name__ == '__main__':\n lcd_only_ui_colors()\n","sub_path":"examples/ui_example.py","file_name":"ui_example.py","file_ext":"py","file_size_in_byte":6982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"335626765","text":"# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.\n# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation.\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 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 json\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom lean.commands.create_project import (DEFAULT_CSHARP_MAIN, DEFAULT_CSHARP_NOTEBOOK, DEFAULT_PYTHON_MAIN,\n DEFAULT_PYTHON_NOTEBOOK)\nfrom lean.models.api import QCLanguage, QCLiveResults, QCProject\n\n\ndef create_fake_lean_cli_directory() -> None:\n \"\"\"Creates a directory structure similar to the one created by `lean init` with a Python and a C# project.\"\"\"\n (Path.cwd() / \"data\").mkdir()\n\n files = {\n (Path.cwd() / \"lean.json\"): \"\"\"\n{\n // data-folder documentation\n \"data-folder\": \"data\"\n}\n \"\"\",\n (Path.cwd() / \"Python Project\" / \"main.py\"): DEFAULT_PYTHON_MAIN.replace(\"$NAME$\", \"PythonProject\"),\n (Path.cwd() / \"Python Project\" / \"research.ipynb\"): DEFAULT_PYTHON_NOTEBOOK,\n (Path.cwd() / \"Python Project\" / \"config.json\"): json.dumps({\n \"algorithm-language\": \"Python\",\n \"parameters\": {}\n }),\n (Path.cwd() / \"CSharp Project\" / \"Main.cs\"): DEFAULT_CSHARP_MAIN.replace(\"$NAME$\", \"CSharpProject\"),\n (Path.cwd() / \"CSharp Project\" / \"research.ipynb\"): DEFAULT_CSHARP_NOTEBOOK,\n (Path.cwd() / \"CSharp Project\" / \"config.json\"): json.dumps({\n \"algorithm-language\": \"CSharp\",\n \"parameters\": {}\n }),\n (Path.cwd() / \"CSharp Project\" / \"CSharp Project.csproj\"): \"\"\"\n\n \n Debug\n AnyCPU\n net5.0\n 9\n bin/$(Configuration)\n false\n CS0618\n \n \n \n \n\n \"\"\"\n }\n\n for path, content in files.items():\n path.parent.mkdir(parents=True, exist_ok=True)\n with open(path, \"w+\") as file:\n file.write(content)\n\n\ndef create_api_project(id: int, name: str) -> QCProject:\n \"\"\"Creates a fake API project response.\"\"\"\n return QCProject(\n projectId=id,\n organizationId=\"123\",\n name=name,\n description=\"Description\",\n modified=datetime.now(),\n created=datetime.now(),\n language=QCLanguage.Python,\n collaborators=[],\n leanVersionId=10500,\n leanPinnedToMaster=True,\n parameters=[],\n liveResults=QCLiveResults(eStatus=\"Unknown\"),\n libraries=[]\n )\n","sub_path":"tests/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"628116857","text":"#!/usr/bin/python3\n\"\"\" This is a script that starts a Flask web application.\n Listening on 0.0.0.0\n - port 5000\n\"\"\"\n\n\nfrom models import State\nfrom models import storage\nfrom flask import abort, render_template, Flask\napp = Flask(__name__)\napp.url_map.strict_slashes = False\n\n\n@app.route('/states_list')\ndef display_states():\n ''' Display a HTML page with States\n '''\n states = storage.all(\"State\")\n return render_template('7-states_list.html', states=states)\n\n\n@app.teardown_appcontext\ndef tear_down(self):\n ''' Teardown\n '''\n storage.close()\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"web_flask/7-states_list.py","file_name":"7-states_list.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"549499789","text":"from __future__ import division, print_function\nimport sys\nsys.path.append('.')\nsys.path.append('modules/question_generator')\nsys.path.append('modules/vocab_seq')\nfrom vocab_seq import Vocab_Seq\nimport nltk\nfrom nltk.corpus import wordnet\nimport gensim\nimport util\nfrom util.data import vg_load_annotation\nfrom collections import Counter\nimport numpy as np\nimport h5py\nimport os\n\n\ndef create_attribute_label_from_attribute():\n # anno_att, anno_obj, anno_image = vg_load_annotation(['attribute', 'object', 'image'])\n anno_att, = vg_load_annotation(['attribute'])\n attributes = [att for obj in anno_att.values() for att in obj['attributes']]\n attribute_counter = Counter(attributes).most_common()\n attribute_1000, count_1000 = zip(*(attribute_counter[0:1000]))\n s = sum(count_1000)\n print('num sample: %d' % s)\n percent_1000 = [c / s for c in count_1000]\n\n util.io.save_json({'attribute': attribute_1000, 'count': count_1000, 'precent': percent_1000},\\\n 'temp/obj_attribute_counting.json')\n\ndef create_attribute_label_from_region():\n qa_region_corpus_file = 'data/vqg/cache/qa_region_attribute_corpus.json'\n\n if os.path.isfile(qa_region_corpus_file):\n print('load qa region corpus ...')\n qa_region_corpus = util.io.load_json(qa_region_corpus_file)\n else:\n print('create qa region corpus ...')\n anno_qa, anno_qa_region, qa_to_region, region_list = \\\n vg_load_annotation(['qa', 'region_30_enlarge', 'qa_to_region_30', 'region_list'])\n region_list = {unicode(img['id']):img for img in region_list}\n\n qa_region_corpus = dict.fromkeys(anno_qa.keys())\n n = 0\n num_qa = len(anno_qa)\n for qa_id, qa in anno_qa.iteritems():\n sentences = []\n sentences.append(qa['answer'])\n region_qa = anno_qa_region[qa_to_region[qa_id]]\n bbox_qa = np.array([region_qa['x'], region_qa['y'], region_qa['x']+region_qa['width'], \\\n region_qa['y']+region_qa['height']], dtype = np.float32)\n\n regions = region_list[unicode(qa['image_id'])]['regions']\n bbox_rg = np.array([[rg['x'], rg['y'], rg['x']+rg['width'], rg['y']+rg['height']] for rg in regions],\\\n dtype = np.float32)\n overlap = util.image.compute_iou(bbox_rg, bbox_qa)\n for i, rg in enumerate(regions):\n if overlap[i] > 0.5:\n sentences.append(rg['phrase'])\n qa_region_corpus[qa_id] = sentences\n n += 1\n if n % 100 == 0:\n print('create corpus: %.2f%%' % (100 * n / num_qa))\n\n util.io.save_json(qa_region_corpus, qa_region_corpus_file)\n\n ######################################\n\n attribute_count_file = 'data/vqg/cache/region_attribute_pos_counting_3gram.json'\n attribute_corpus_file = 'data/vqg/cache/attribute_corpus_3gram.json'\n restart = False\n if not restart and os.path.isfile(attribute_count_file) and os.path.isfile(attribute_corpus_file):\n print('load region attributes ...')\n count_data = util.io.load_json(attribute_count_file)\n attribute = count_data['attribute']\n count = count_data['count']\n # attribute_corpus = util.io.load_json(attribute_corpus_file)\n else:\n print('extract region attributes ...')\n wnl = nltk.WordNetLemmatizer()\n stopwords = nltk.corpus.stopwords.words('english')\n stopwords_part = stopwords[0:stopwords.index('of')] + stopwords[(stopwords.index('under')+1)::]\n punc = Vocab_Seq.punctuations + ['\\'s']\n omitted_words = dict.fromkeys(stopwords_part + punc)\n synonym_dict = {u'grey': u'gray', u'racquet': u'racket', u'airplane': u'plane', u'cell phone': u'cellphone', \\\n u'blond': u'blonde', u'day time': u'daytime'}\n # u'two':u'mto', u'three':u'mto',u'four':u'mto',u'five':u'mto',u'six':u'mto',\\\n # u'2':u'mto',u'3':u'mto',u'4':u'mto',u'5':u'mto',u'6':u'mto', u'1': u'one'}\n # m_t_o means 'more than one'\n pos_mapping = Vocab_Seq.pos_mapping\n pos_mapping['CD'] = 'CD'\n\n # def _language_normalize(sent):\n # token = nltk.word_tokenize(unicode(sent).lower())\n # token = [wnl.lemmatize(w, wordnet.NOUN) for w in token if w not in omitted_words]\n # token = [wnl.lemmatize(w, wordnet.VERB) for w in token]\n # token = [wnl.lemmatize(w, wordnet.ADJ) for w in token]\n # token = [wnl.lemmatize(w, wordnet.ADV) for w in token]\n # sent = ' '.join(token)\n # for original_word, target_word in synonym_dict.iteritems():\n # sent = sent.replace(original_word, target_word)\n # return sent\n def _word_normalize(w):\n w = wnl.lemmatize(w, wordnet.NOUN)\n w = wnl.lemmatize(w, wordnet.VERB)\n w = wnl.lemmatize(w, wordnet.ADJ)\n w = wnl.lemmatize(w, wordnet.ADV)\n return w\n\n def _get_n_gram(sent, max_n):\n sent = unicode(sent).lower()\n for o_w, t_w in synonym_dict.iteritems():\n sent = sent.replace(o_w, t_w)\n token = nltk.pos_tag(nltk.word_tokenize(sent))\n token = [(_word_normalize(w), pos_mapping.get(p,p))\\\n for (w,p) in token if w not in omitted_words]\n if len(token) == 0:\n return []\n for i_w, (w, p) in enumerate(token):\n if p == 'CD':\n if w == '1' or w == 'one':\n token[i_w] = ('one', 'CD')\n elif w == '0' or w == 'zero':\n token[i_w] = ('zero', 'CD')\n else:\n token[i_w] = ('more_than_one', 'CD')\n \n grams = token[:]\n words, poss = zip(*token)\n for n in xrange(2, max_n+1):\n for j in xrange(0, len(token)-n+1):\n # grams.append(' '.join(token[j:(j+n)]))\n grams.append((' '.join(words[j:(j+n)]), ' '.join(poss[j:(j+n)])))\n return grams\n\n word_pos_list = []\n attribute_corpus = {}\n max_word_num = 3\n for i, qa_id in enumerate(qa_region_corpus.keys()):\n corpus = qa_region_corpus[qa_id]\n grams = []\n for sent in corpus:\n # sent = _language_normalize(sent)\n grams += _get_n_gram(sent, max_word_num)\n grams = list(set(grams))\n word_pos_list += grams\n attribute_corpus[qa_id] = grams\n if i % 100 == 0:\n print('counting attribute: %.2f%%' % (i*100/len(qa_region_corpus)))\n\n\n stopwords_dict = dict.fromkeys(stopwords)\n attribute_pos_counter = Counter(word_pos_list).most_common()\n # attribute_pos_counter = [a for a in attribute_pos_counter if a[0][0].split(' ')[0] not in stopwords_dict]\n\n attribute_counter = {}\n for (att, pos), c in attribute_pos_counter:\n if att not in attribute_counter:\n attribute_counter[att] = [pos, c]\n else:\n attribute_counter[att][1] += c\n attribute_counter = [((att, pos), c) for att, (pos, c) in attribute_counter.iteritems()]\n attribute_counter.sort(reverse = True, key = lambda x:x[1])\n\n attribute, count = zip(*(attribute_counter[0:10000]))\n util.io.save_json({'attribute': attribute, 'count': count}, attribute_count_file)\n util.io.save_json(attribute_corpus, attribute_corpus_file)\n\n ##########################\n # attribute = [(att, pos, c) for (att, pos), c in zip(attribute, count)]\n # attribute_dict = {}\n # for att in attribute:\n # if att[1] not in attribute_dict:\n # attribute_dict[att[1]] = [att]\n # else:\n # attribute_dict[att[1]].append(att)\n # pos_list = [(p, sum([att[2] for att in att_list])) \\\n # for p, att_list in attribute_dict.iteritems()]\n # pos_list.sort(reverse = True, key = lambda x:x[1])\n # output_list = []\n # for pos, c in pos_list:\n # if len(attribute_dict[pos]) >= 5:\n # att_top_5 = attribute_dict[pos][0:5]\n # else:\n # att_top_5 = attribute_dict[pos] + ['NONE'] * (5-len(attribute_dict[pos]))\n\n # output_list.append('%s\\t%d\\t%s\\t%s\\t%s\\t%s\\t%s' % ((pos, c) + tuple(att_top_5)))\n # util.io.save_str_list(output_list, 'data/vqg/cache/attribute_type.txt')\n # util.io.save_str_list(output_list, './attribute_type.txt')\n\n ############################\n\n\ndef create_attribute_dataset(set_name):\n assert(set_name in ['train', 'val', 'test'])\n dataset_filename = 'data/vqg/training_data/attribute/attribute_label_%s.h5' % set_name\n attribute_list_file = 'data/vqg/training_data/attribute/attribute_list_1.0.json'\n # dataset_filename = 'data/vqg/training_data/attribute/attribute_label_noNN_%s.h5' % set_name\n # attribute_list_file = 'data/vqg/training_data/attribute/attribute_list_noNN_1.0.json'\n\n # anno_qa, = vg_load_annotation(['qa'])\n qa_id_list = util.io.load_str_list('data/vqg/splits/vg_qa_split_%s.txt' % set_name)\n \n print('loading attribute corpus and attribute list...')\n attribute_corpus = util.io.load_json('data/vqg/cache/attribute_corpus_3gram.json')\n \n # if os.path.isfile(attribute_list_file):\n if False:\n attribute_list = util.io.load_json(attribute_list_file)\n assert(len(attribute_list) == 3000)\n print('load attribute_list from %s' % attribute_list_file)\n else:\n attribute_count = util.io.load_json('data/vqg/cache/region_attribute_pos_counting_3gram.json')\n attribute_type_list = util.io.load_str_list('data/vqg/training_data/attribute/attribute_type_list.txt')\n attribute_list = [[unicode(att), unicode(pos), count] for (att, pos), count in \\\n zip(attribute_count['attribute'], attribute_count['count']) if pos in attribute_type_list]\n attribute_list = attribute_list[0:3000]\n util.io.save_json(attribute_list, attribute_list_file)\n # attribute_dict = {'_'.join(att):i for i, att in enumerate(attribute_list)}\n\n # num_qa = len(qa_id_list)\n # data = np.zeros((num_qa, 3001), dtype = np.float32)\n\n # for i, qa_id in enumerate(qa_id_list):\n # corpus = attribute_corpus[qa_id]\n # for att in corpus:\n # idx = attribute_dict.get('_'.join(att), -1)\n # data[i, idx] = 1\n # if i % 100 == 0:\n # print('create %s attribute label: %.2f%%' % (set_name, i*100/num_qa))\n\n # h5_dataset = h5py.File(dataset_filename, 'w')\n # dataset = h5_dataset.create_dataset('attribute_1000', shape = (num_qa, 1000), dtype = np.float32)\n # dataset[:] = data[:, 0:1000]\n # dataset = h5_dataset.create_dataset('attribute_2000', shape = (num_qa, 2000), dtype = np.float32)\n # dataset[:] = data[:, 0:2000]\n # dataset = h5_dataset.create_dataset('attribute_3000', shape = (num_qa, 3000), dtype = np.float32)\n # dataset[:] = data[:, 0:3000]\n # h5_dataset.close()\n\n\nif __name__ == '__main__':\n # create_attribute_label_from_attribute()\n # create_attribute_label_from_region()\n create_attribute_dataset(sys.argv[1])\n\n # util.data.split_h5_file('data/vqg/training_data/attribute/attribute_label_train.h5',5)\n\n","sub_path":"modules/answer_predictor/create_attribute_label.py","file_name":"create_attribute_label.py","file_ext":"py","file_size_in_byte":11341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"505636531","text":"from datetime import datetime, timedelta\nfrom typing import List\n\nimport models.measurement\nimport schemas.measurement\nimport sqlalchemy as db\nfrom db.database import Base\nfrom db.workbench_helper import WorkbenchHelper\nfrom models.measurement import Measurement\nfrom sqlalchemy.orm import Session\n\n\nclass LoggingDatabase:\n # replace the user, password, hostname and database according to your configuration according to your information\n engine = db.create_engine(\n \"postgresql://read_write:simplepass1098@localhost:5432/logging\", echo=False\n )\n\n def __init__(self):\n self.connection = self.engine.connect()\n\n def create_tables(self):\n Base.metadata.create_all(self.engine)\n\n def get_all_measurements(self) -> List[Measurement]:\n self.session = Session(bind=self.connection)\n measurements: List[Measurement] = self.session.query(Measurement).all()\n\n for meas in measurements:\n print(meas)\n\n return measurements\n\n def get_by_query(self, query):\n fetchQuery = self.connection.execute(f\"SELECT * FROM {query}\")\n query_data = fetchQuery.fetchall()\n\n for data in query_data:\n print(data)\n\n return query_data\n\n def insert_measurement(\n self, measurement: schemas.measurement.MeasurementCreate\n ) -> models.measurement.Measurement:\n session = Session(bind=self.connection)\n db_measurement = models.measurement.Measurement(**measurement.dict())\n session.add(db_measurement)\n session.commit()\n\n return db_measurement\n\n def get_measurements_since_date(self, since_date: datetime) -> List[Measurement]:\n session = Session(bind=self.connection)\n measurements: List[Measurement] = session.query(Measurement).filter(\n Measurement.d_datetime > since_date\n ).order_by(Measurement.d_datetime.asc()).all()\n\n return measurements\n\n def get_measurements_in_last_timedelta(self, period: timedelta):\n since_date = WorkbenchHelper.get_datetime_now_to_nearest_sec() - period\n return self.get_measurements_since_date(since_date)\n\n\nif __name__ == \"__main__\":\n loggingDb = LoggingDatabase()\n results = loggingDb.get_by_query(\"public.measurements\")\n results = loggingDb.get_all_measurements()\n","sub_path":"workbench_web/backend/app/app/crud/measurement.py","file_name":"measurement.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"398098393","text":"import os.path\n\nfrom jinja2 import (\n Environment,\n FileSystemLoader,\n)\n\nimport random\n\n\ndef random_string():\n \"\"\"\n 生成一个随机的字符串\n \"\"\"\n seed = 'bdjsdlkgjsklgelgjelgjsegker234252542342525g'\n s = ''\n for i in range(16):\n # 这里 len(seed) - 2 是因为我懒得去翻文档来确定边界了\n random_index = random.randint(0, len(seed) - 2)\n s += seed[random_index]\n return s\n\n\ndef initialized_environment():\n path = os.path.join(os.path.dirname(__file__), 'templates')\n # 创建一个加载器, jinja2 会从这个目录中加载模板\n loader = FileSystemLoader(path)\n # 用加载器创建一个环境, 有了它才能读取模板文件\n e = Environment(loader=loader)\n return e\n\n\nclass GuaTemplate:\n # 初始化只执行一次(用类变量实现)\n e = initialized_environment()\n\n @classmethod\n def render(cls, filename, *args, **kwargs):\n # 调用 get_template() 方法加载模板并返回\n template = cls.e.get_template(filename)\n # 用 render() 方法渲染模板\n # 可以传递参数\n return template.render(*args, **kwargs)\n\n\ndef error(request, code=404):\n \"\"\"\n 根据 code 返回不同的错误响应\n 目前只有 404\n \"\"\"\n # 之前上课我说过不要用数字来作为字典的 key\n # 但是在 HTTP 协议中 code 都是数字似乎更方便所以打破了这个原则\n e = {\n 404: b'HTTP/1.x 404 NOT FOUND\\r\\n\\r\\nNOT FOUND
',\n }\n return e.get(code, b'')\n\n\ndef formatted_header(headers, code=200):\n \"\"\"\n Content-Type: text/html\n Set-Cookie: user=gua\n \"\"\"\n header = 'HTTP/1.1 {} OK GUA\\r\\n'.format(code)\n header += ''.join([\n '{}: {}\\r\\n'.format(k, v) for k, v in headers.items()\n ])\n return header\n\n\ndef redirect(url, headers=None):\n \"\"\"\n 浏览器在收到 302 响应的时候\n 会自动在 HTTP header 里面找 Location 字段并获取一个 url\n 然后自动请求新的 url\n \"\"\"\n h = {\n 'Location': url,\n }\n if headers is None:\n headers = h\n else:\n headers.update(h)\n # 302 状态码的含义, Location 的作用\n # 注意, 没有 HTTP body 部分\n header = formatted_header(headers, 302)\n r = header + '\\r\\n'\n return r.encode()\n\n\ndef html_response(body, headers=None):\n h = {\n 'Content-Type': 'text/html',\n }\n if headers is None:\n headers = h\n else:\n headers.update(h)\n header = formatted_header(headers)\n r = header + '\\r\\n' + body\n return r.encode()\n\n\ndef static(request):\n \"\"\"\n 静态资源的处理函数, 读取图片并生成响应返回\n \"\"\"\n filename = request.query.get('file', 'doge.gif')\n path = 'static/' + filename\n with open(path, 'rb') as f:\n header = b'HTTP/1.x 200 OK\\r\\n\\r\\n'\n img = header + f.read()\n return img\n\n\ndef route_dict():\n \"\"\"\n 路由字典\n key 是路由(路由就是 path)\n value 是路由处理函数(就是响应)\n \"\"\"\n d = {\n '/': all,\n '/static': static,\n }\n return d\n","sub_path":"8.18/mario_python/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"486002376","text":"#创建二级子进程避免僵尸 \n#成为孤儿就不会成为僵尸\nimport os \nfrom time import sleep\nimport sys\n\ndef f1():\n sleep(3)\n print('第一件事')\n\ndef f2():\n sleep(4)\n print('第二件事')\n\n\npid = os.fork()\n\nif pid < 0:\n print('error')\n\nelif pid == 0:\n #创建二级子进程\n p = os.fork()\n if p == 0:\n f2()\n\n else:\n os._exit()\n # sys.exit()\n\n\n\nelse:\n os.wait()#等待一级子进程退出\n f1()\n\n\n#相当于多进程了\n","sub_path":"网络/pythonNet/day5/forkfujincheng.py","file_name":"forkfujincheng.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"83213668","text":"\"\"\"\nCreated by Sam Henly, somewhere in Washington, 2017\n\nFunctions to classify images as photos and/or as graphics.\n\nScheme\n\n\"\"\"\n\nimport sys\nsys.path.insert(0, '/home/sam/thesisOutput/stats/')\nsys.path.insert(0, '/home/sam/thesisOutput/postgres/')\nimport pandas as pd\nimport image_feature_retrieval, os, utility, time, pickle, shutil\nimport stat_management as sm\nimport sklearn.preprocessing as prep\nimport db_core_functions as db\nimport numpy as np\nfrom multiprocessing import Queue, Process\nimport ibank_map as imap\nimport sklearn.decomposition.pca as pca\n\n\ndef get_classified_image_features():\n \"\"\"Pull image features for classified images from aspasia.\"\"\"\n\n dataDirectory = '/Blackbird/graphics/'\n featureData = {}\n featureTable = 'image$common_features'\n\n for subdir in ['graphic','photo','mix']:\n\n images = os.listdir(dataDirectory + subdir)\n featureData[subdir] = image_feature_retrieval.pull_image_features(images, featureTable) \n\n photoOnlyDic = {'graphic' : 0,\n 'mix' : 0,\n 'photo' : 1}\n graphicOnlyDic = {'graphic': 1,\n 'mix' : 0,\n 'photo' : 0}\n\n for imageClass in featureData.keys():\n featureData[imageClass]['graphic_only'] = graphicOnlyDic[imageClass]\n featureData[imageClass]['photo_only'] = photoOnlyDic[imageClass]\n\n return pd.concat([x for x in featureData.values()])\n\n\ndef get_bw_columns():\n \"\"\"\n Return list of columns that should be present in all images,\n even those with only L band.\n \"\"\"\n\n return ['phash', 'pixels', 'height', 'width', 'aspect_ratio',\n 'l01_frac_empty_bn', 'l01_minbn_01pct_px', 'l01_minbn_05pct_px',\n 'l01_minbn_10pct_px', 'l01_minbn_25pct_px', 'l01_px_share_001bn',\n 'l01_px_share_005bn', 'l01_px_share_010bn', 'l01_px_share_025bn',\n 'l01_px_share_050bn', 'l01_px_share_100bn', 'l_cdf008',\n 'l_cdf016', 'l_cdf024', 'l_cdf032', 'l_cdf040', 'l_cdf048',\n 'l_cdf056', 'l_cdf064', 'l_cdf072', 'l_cdf080', 'l_cdf088',\n 'l_cdf096', 'l_cdf104', 'l_cdf112', 'l_cdf120', 'l_cdf128',\n 'l_cdf136', 'l_cdf144', 'l_cdf152', 'l_cdf160', 'l_cdf168',\n 'l_cdf176', 'l_cdf184', 'l_cdf192', 'l_cdf200', 'l_cdf208',\n 'l_cdf216', 'l_cdf224', 'l_cdf232', 'l_cdf240', 'l_cdf248',\n 'l_entropy_r3_cdf000', 'l_entropy_r3_cdf001',\n 'l_entropy_r3_cdf005', 'l_entropy_r3_cdf010',\n 'l_entropy_r3_cdf025', 'l_entropy_r3_cdf050',\n 'l_entropy_r3_cdf075', 'l_entropy_r3_cdf100',\n 'l_entropy_r3_cdf150', 'l_entropy_r3_cdf200',\n 'l_entropy_r3_cdf250', 'l_entropy_r3_cdf300',\n 'l_entropy_r3_cdf350', 'l_entropy_r3_cdf400',\n 'l_entropy_r3_cdf450', 'l_entropy_r3_cdf500',\n 'l_entropy_r3_cdf550', 'l_entropy_r3_cdf600',\n 'l_entropy_r3_kurt', 'l_entropy_r3_mean', 'l_entropy_r3_obs',\n 'l_entropy_r3_sdev', 'l_entropy_r3_skew', 'l_entropy_r6_cdf000',\n 'l_entropy_r6_cdf001', 'l_entropy_r6_cdf005',\n 'l_entropy_r6_cdf010', 'l_entropy_r6_cdf025',\n 'l_entropy_r6_cdf050', 'l_entropy_r6_cdf075',\n 'l_entropy_r6_cdf100', 'l_entropy_r6_cdf150',\n 'l_entropy_r6_cdf200', 'l_entropy_r6_cdf250',\n 'l_entropy_r6_cdf300', 'l_entropy_r6_cdf350',\n 'l_entropy_r6_cdf400', 'l_entropy_r6_cdf450',\n 'l_entropy_r6_cdf500', 'l_entropy_r6_cdf550',\n 'l_entropy_r6_cdf600', 'l_entropy_r6_kurt',\n 'l_entropy_r6_mean', 'l_entropy_r6_obs', 'l_entropy_r6_sdev',\n 'l_entropy_r6_skew', 'l_kurt', 'l_mean', 'l_sdev', 'l_skew',\n 'graphic_only', 'photo_only']\n\n\ndef process_raw_features(imageFeatures, popLabels = False):\n \"\"\"Split imageFeatures into bw/color set, process a bit.\"\"\"\n\n # get rid of bands column\n del imageFeatures['bands']\n\n # get set of columns that should be present in all images\n bwColumns = get_bw_columns()\n if popLabels:\n bwColumns.remove('graphic_only')\n bwColumns.remove('photo_only')\n\n # split data into black and white frame,\n # color frame\n bwData = imageFeatures[bwColumns].dropna()\n colorData = imageFeatures.dropna()\n\n # identify images that were originally color in bw dataset\n colorPhashes = set(colorData.phash.unique())\n bwData['originally_color'] = bwData.phash.apply(lambda x: int(x in colorPhashes))\n\n # return data\n return colorData, bwData\n\n\ndef make_graphics_data_sets():\n \"\"\"Create two project Datasets.\"\"\"\n\n colorX, bwX = process_raw_features(get_classified_image_features())\n\n colorY = colorX[['graphic_only','photo_only']]\n bwY = bwX[['graphic_only','photo_only']]\n\n for dSet in [colorX, bwX]:\n del dSet['graphic_only']\n del dSet['photo_only']\n del dSet['phash']\n\n subsets = {'photo': [[], 'photo_only'],\n 'graphic': [[], 'graphic_only']}\n\n XScaler = prep.StandardScaler\n\n description = \"Dataset containing features from image$common_features.\" \\\n \"\\nImages in this project are originally in color, with additional \"\\\n \"features extracted after originals were \"\\\n \"converted to black and white.\\nProject aims to classify images as \"\\\n \"purely graphical (or not) and purely photographic (or not).\"\n sm.prepare_dataset(colorX, colorY, 'cgraphics',\n description,\n subsets = subsets,\n XScaler = XScaler,\n testSize = 0.15)\n\n description = \"Dataset containing features from image$common_features.\" \\\n \"\\nImages in this project are either originally black and white or \"\\\n \"converted to black and white.\\nProject aims to classify images as \"\\\n \"purely graphical (or not) and purely photographic (or not).\"\n sm.prepare_dataset(bwX, bwY, 'bwgraphics',\n description,\n subsets = subsets,\n XScaler = XScaler,\n testSize = 0.15)\n\n pcaObj = pca.PCA()\n pcaObj.fit(colorX)\n description = \"Dataset containing features from image$common_features.\" \\\n \"\\nImages in this project are originally in color, with additional \"\\\n \"features extracted after originals were \"\\\n \"converted to black and white.\\nProject aims to classify images as \"\\\n \"purely graphical (or not) and purely photographic (or not).\"\\\n \"\\n\\nCovariates are transformed via default PCA.\"\n sm.prepare_dataset(pd.DataFrame(pcaObj.transform(colorX)), colorY, 'cgraphics_pca',\n description,\n subsets = subsets,\n XScaler = XScaler,\n pcaX = pcaObj,\n testSize = 0.15)\n\n pcaObj = pca.PCA()\n pcaObj.fit(bwX)\n description = \"Dataset containing features from image$common_features.\" \\\n \"\\nImages in this project are either originally black and white or \"\\\n \"converted to black and white.\\nProject aims to classify images as \"\\\n \"purely graphical (or not) and purely photographic (or not).\"\\\n \"\\n\\nCovariates are transformed via default PCA.\"\n sm.prepare_dataset(pd.DataFrame(pcaObj.transform(bwX)), bwY, 'bwgraphics_pca',\n description,\n subsets = subsets,\n XScaler = XScaler,\n pcaX=pcaObj,\n testSize = 0.15)\n\n\n\ndef fit_some_models():\n \"\"\"Fit a bunch of pre-specified classifiers on photo data.\"\"\"\n\n models = [sm.qd_gradiant_boost,\n sm.qd_sgd,\n sm.qd_logit,\n sm.qd_svm_classifier,\n sm.qd_random_forest_classifier,\n sm.test_constrained_adaboost]\n\n modelNameRoots = ['qd_rfClassifier',\n 'qd_svmCClassifier',\n 'qd_logitCVClassifier',\n 'qd_sdgCClassifier',\n 'qd_gbCClassifier',\n 'tc_adaBoost']\n\n projectNames = ['cgraphics', 'bwgraphics', 'cgraphics_pca', 'bwgraphics_pca']\n subsets = ['photo','graphic']\n\n for projectName in projectNames:\n for subset in subsets:\n for model in models:\n model(projectName, subset)\n modelNames = [x + '_%s' % subset for x in modelNameRoots]\n sm.CombinedWeightedModels(projectName, 'combined_%s' %subset,\n modelNames, 'classifier', subset = subset)\n\ndef print_model_fit(project):\n \"\"\"Print out fit for all models in project.\"\"\"\n\n modelDirectory = sm.model_directory(project)\n models = [pickle.load(modelDirectory + x ) for x in os.listdir(modelDirectory) if '.pickle' in x]\n\n for model in models:\n model.print_fit()\n\n\n\n#################################################################################################33\n\ndef classify_everything(modCut, startCut = 0):\n \"\"\"Pull all features + classify.\"\"\"\n\n def prep_data_for_prediction(rawPull):\n\n colorData, bwData = process_raw_features(rawPull, popLabels=True)\n colorData = colorData.set_index('phash')\n bwData = bwData.set_index('phash')\n\n dataSets = {'color': colorData, 'bw': bwData}\n\n return dataSets\n\n def scale_predict(model, data):\n \"\"\"Scale and make prediction.\"\"\"\n if model.XScaler is not None:\n return model.predict_c(model.XScaler.transform(data))\n return model.predict_c(data)\n\n def classify_task(data, outQueue, models):\n \"\"\"Classify images.\"\"\"\n\n data = prep_data_for_prediction(data)\n\n # get some useful indices and prepare export data frames\n cIndex = data['color'].index\n bwIndex = data['bw'].index\n colorOut = pd.DataFrame(index=cIndex)\n bwOut = pd.DataFrame(index = bwIndex)\n\n # make predictions\n for model in models.keys():\n modelObj = models[model]\n if model[0] == 'c':\n colorOut[model] = pd.Series(scale_predict(modelObj, data['color']), index=cIndex)\n else:\n bwOut[model] = pd.Series(scale_predict(modelObj, data['bw']), index=bwIndex)\n\n # make output dictionary for color images with empty dicts for bw-only images\n colorDict = colorOut.to_dict(orient = 'index')\n colorDict.update({x : {} for x in set(bwIndex)-set(cIndex)})\n\n # prepare . . . mostly . . . output\n mess = {'color': colorDict,\n 'bw' : bwOut.to_dict(orient='index'),\n 'phashes' : set(bwIndex)}\n\n # convert messy output to list of dicts for upload, and return to queue\n outQueue.put(process_dictionary_mess(mess))\n\n def get_models():\n \"\"\"Load models for predicting each of four variables of interest.\"\"\"\n\n models = dict()\n models['color_photo'] = sm.load_model('cgraphics', 'qd_gbCClassifier_photo')\n models['color_graphic'] = sm.load_model('cgraphics', 'qd_gbCClassifier_graphic')\n models['bw_photo'] = sm.load_model('bwgraphics', 'qd_gbCClassifier_photo')\n models['bw_graphic'] = sm.load_model('bwgraphics', 'qd_gbCClassifier_graphic')\n\n return models\n\n def process_dictionary_mess(d):\n \"\"\"\n Handle some preliminary output from classify_task;\n convert to list of dicts.\n \"\"\"\n\n dList = [{'phash':x} for x in d['phashes']]\n for x in dList:\n phash = x['phash']\n x.update(d['bw'][phash])\n x.update(d['color'][phash])\n\n return dList\n\n def process_cut(rawPull, models):\n \"\"\"Take result of one pull; process + upload.\"\"\"\n\n nWorkers = max(2, utility.get_thread_capacity() - 2)\n dataSets = [pd.DataFrame(x, columns = rawPull.columns) for x in np.array_split(rawPull, nWorkers)]\n\n outQueue = Queue()\n workers = [Process(target=classify_task, args=(dataSets[i], outQueue, models,)) for i in range(nWorkers)]\n\n for worker in workers:\n worker.start()\n\n # gather output\n outCount = 0\n outDicts = []\n while outCount < nWorkers:\n while not outQueue.empty():\n outDicts.extend(outQueue.get())\n outCount += 1\n time.sleep(4)\n\n # upload\n db.load_dictionaries(outDicts, 'image$graphic_classification')\n\n # load models and prepare list classification slices\n models = get_models()\n cuts = list(range(modCut))[startCut:]\n\n # truncate the table\n db.query(\"TRUNCATE TABLE image$graphic_classification;\")\n\n # classify and load each slice of the image features\n for cut in cuts:\n utility.feedback('Starting cut {0!s} of {1!s}.'.format(cut, modCut-1))\n process_cut(image_feature_retrieval.pull_image_features_by_mod(modCut, cut, 'image$common_features'),\n models)\n\n\n#################################################################################################33\n\ndef get_some_classified_images(chunk, summaryOnly = False):\n \"\"\"Get a bunch of images that were classified.\"\"\"\n\n def move_images_update_completed_phashes(condition, phashes, movedPhashes,\n archiveFolder, projectDirectory):\n \"\"\"Move files identified by queries w/o redundnacy.\"\"\"\n\n # get a list of files to be moved by condition\n # these files should not have already been moved\n filesToMove = [archiveFolder + x for x in os.listdir(archiveFolder)\n if utility.clean_phash(x) in phashes[condition] - movedPhashes]\n\n # make sure directory exists . . .\n targetDirectory = '{0}to_sort/{1}/'.format(projectDirectory, condition)\n if not os.path.isdir(targetDirectory):\n os.mkdir(targetDirectory)\n\n # move the files to specified condition directory\n for file in filesToMove:\n shutil.move(file, targetDirectory)\n\n # update set of moved hashes\n movedPhashes.update(phashes[condition])\n\n projectDirectory = '/Blackbird/graphics/'\n archiveBase = '/Carsomyr/image_bank/archives/0016/'\n\n # parameters for sorting images\n unsureThreshold = \"0.1\" # images w/ class probability for photo or graphic at 0.5 +/-\n # unsureThreshold are categorized as unsure\n confusionThreshold = \"0.3\" # \"confusion\" if pr(graphic) & pr(photo) both > confusionThreshold\n\n # bad/good cases\n conditions = {'unsure': \"(abs(0.5-color_photo) < {0} OR abs(0.5-bw_photo) < {0} OR \"\\\n \"abs(0.5-color_graphic) < {0} OR abs(0.5-bw_graphic) < {0});\".format(unsureThreshold),\n 'confused': \"((color_photo > {0} AND color_graphic > {0}) OR \"\\\n \"(bw_photo > {0} AND bw_graphic > {0}));\".format(confusionThreshold),\n 'photo_confident': '(round(color_photo)::int = 1 AND round(bw_photo)::int = 1);',\n 'graphic_confident': '(round(color_graphic)::int = 1 AND round(bw_graphic)::int = 1);'}\n\n\n # run query to get interesting images from photo subset\n # get phashes for those images\n phashes = {}\n print('Classifications of photos for chunk {0!s}:'.format(chunk))\n for condition, queryCondition in conditions.items():\n query = \"SELECT phash FROM image$graphic_classification WHERE \" \\\n \"abs(floor(phash/(10^16))) = {0!s} and {1};\".format(chunk, queryCondition)\n phashes[condition] = set([x for x in db.query(query)['phash']])\n print(condition,':',len(phashes[condition]))\n\n if summaryOnly:\n return None\n\n # extract an archive containing (most of) those images\n archivePaths = ['{1}{0!s}.tar.gz'.format(chunk, archiveBase)]\n archiveDir = '{0}to_sort/inbound/'.format(projectDirectory)\n archiveFolder = imap.archive_batch(archiveList = archivePaths, archiveDir=archiveDir)[0]\n\n # move files of interest\n movedPhashes = set()\n for condition in conditions.keys():\n move_images_update_completed_phashes(condition, phashes, movedPhashes,\n archiveFolder, projectDirectory)\n # remove archives\n imap.remove_completed_folders(archiveDir)\n\n#if __name__ == '__main__':\n\n # get_some_classified_images(481, summaryOnly = True)\n # get_some_classified_images(150, summaryOnly = True)\n #\n #make_graphics_data_sets()\n #fit_some_models()\n #classify_everything()\n\n # get_some_classified_images(481, summaryOnly = True)\n #get_some_classified_images(153)\n","sub_path":"photo_classification.py","file_name":"photo_classification.py","file_ext":"py","file_size_in_byte":16799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"634636986","text":"#\n# Description : MODEL INTERFACE WEB\n#\n# Author : J.P\n# Date : 26/06/2021\n# Version : 1.0\n#\n#\n# Example 1 : TBD\n#\n\nimport sys\nfrom PySide2 import QtCore, QtGui, QtWidgets\nimport numpy as np\n\n\nclass window(QtWidgets.QDialog):\n def __init__(self, parent=None):\n\n QtWidgets.QDialog.__init__(self,parent)\n\n # == Window Config. ==\n self.matrix_line_nb = 8\n if int(sys.argv[1]) < 1 or int(sys.argv[1]) > 8 :\n sys.exit(\"ARGV ERROR - argv[1] must be between [1:8]\")\n else:\n self.matrix_nb = int(sys.argv[1])\n self.grid = np.zeros([self.matrix_line_nb,8*self.matrix_nb], dtype=bool)\n self.grid_layout = QtWidgets.QGridLayout()\n self.setLayout(self.grid_layout)\n # ====================\n\n # == Set Checkboxes ==\n for j in range (0, self.matrix_line_nb):\n for i in range (0, 8*self.matrix_nb):\n check_btn = QtWidgets.QCheckBox()\n self.grid_layout.addWidget(check_btn,j,i)\n # ===================\n\n # == Set Fields Registers Configuration ==\n # self.field_decod_mode = QtWidgets.QLineEdit(\"\")\n # self.text_decod_mode = QtWidgets.QLabel(\"Decode Mode : \")\n \n # self.field_intensity = QtWidgets.QLineEdit(\"\")\n # self.text_intensity = QtWidgets.QLabel(\"Intensity : \")\n \n # self.field_scan_limit = QtWidgets.QLineEdit(\"\")\n # self.text_scan_limit = QtWidgets.QLabel(\"Scan Limit : \")\n \n # self.field_shutdown = QtWidgets.QLineEdit(\"\")\n # self.text_shutdown = QtWidgets.QLabel(\"Shutdown : \")\n \n # self.field_display_test = QtWidgets.QLineEdit(\"\")\n # self.text_display_test = QtWidgets.QLabel(\"Display Test : \")\n \n # self.grid_layout.addWidget(self.field_decod_mode, 8, 8*self.matrix_nb + 1)\n # self.grid_layout.addWidget(self.text_decod_mode, 8, 8*self.matrix_nb)\n\n # self.grid_layout.addWidget(self.field_intensity, 9, 8*self.matrix_nb + 1)\n # self.grid_layout.addWidget(self.text_intensity, 9, 8*self.matrix_nb)\n\n # self.grid_layout.addWidget(self.field_scan_limit, 10, 8*self.matrix_nb + 1)\n # self.grid_layout.addWidget(self.text_scan_limit, 10, 8*self.matrix_nb)\n \n # self.grid_layout.addWidget(self.field_shutdown, 11, 8*self.matrix_nb + 1)\n # self.grid_layout.addWidget(self.text_shutdown, 11, 8*self.matrix_nb)\n \n # self.grid_layout.addWidget(self.field_display_test, 12, 8*self.matrix_nb + 1)\n # self.grid_layout.addWidget(self.text_display_test, 12, 8*self.matrix_nb)\n\n # self.field_decod_mode.setText(\"00\")\n # self.field_intensity.setText(\"00\")\n # self.field_scan_limit.setText(\"00\")\n # self.field_shutdown.setText(\"00\")\n # self.field_display_test.setText(\"00\")\n \n # =======================================\n\n # == Set Fields Memory File Configuration ==\n # self.field_instance_path = QtWidgets.QLineEdit(\"\")\n # self.text_instance_path = QtWidgets.QLabel(\"Instance : \")\n # self.grid_layout.addWidget(self.field_instance_path, 13, 8*self.matrix_nb + 1)\n # self.grid_layout.addWidget(self.text_instance_path, 13, 8*self.matrix_nb)\n # self.field_instance_path.setText(\"/tb_top/i_dut/tdpram_inst_0/v_ram\")\n\n # self.field_memory_size = QtWidgets.QLineEdit(\"\")\n # self.text_memory_size = QtWidgets.QLabel(\"Memory Size : \")\n # self.grid_layout.addWidget(self.field_memory_size, 14, 8*self.matrix_nb + 1)\n # self.grid_layout.addWidget(self.text_memory_size, 14, 8*self.matrix_nb)\n # self.field_memory_size.setText(\"256\")\n\n # self.field_data_size = QtWidgets.QLineEdit(\"\")\n # self.text_data_size = QtWidgets.QLabel(\"Memory Size (in bits) : \")\n # self.grid_layout.addWidget(self.field_data_size, 15, 8*self.matrix_nb + 1)\n # self.grid_layout.addWidget(self.text_data_size, 15, 8*self.matrix_nb)\n # self.field_data_size.setText(\"16\")\n\n # self.field_file_name = QtWidgets.QLineEdit(\"\")\n # self.text_file_name = QtWidgets.QLabel(\"File Name : \")\n # self.grid_layout.addWidget(self.field_file_name, 16, 8*self.matrix_nb + 1)\n # self.grid_layout.addWidget(self.text_file_name, 16, 8*self.matrix_nb)\n # self.field_file_name.setText(\"max7219_ram.mem\")\n \n # ==========================================\n\n # == Bouton Inversion CheckBoxes Matrix ==\n self.__boutonInvCheckbox = QtWidgets.QPushButton(\"Inverser CheckBox\")\n self.grid_layout.addWidget(self.__boutonInvCheckbox, 17, 8*self.matrix_nb)\n self.__boutonInvCheckbox.clicked.connect(self.inv_checkbox)\n # =============================\n\n # == Set boutons generer ==\n self.__boutonGenerer = QtWidgets.QPushButton(\"Generer\")\n self.grid_layout.addWidget(self.__boutonGenerer, 18, 8*self.matrix_nb)\n self.__boutonGenerer.clicked.connect(self.generer_mem)\n\n #self.boutonGenCst = QtWidgets.QPushButton(\"Generer Constant\")\n #self.grid_layout.addWidget(self.boutonGenCst, 18, 8*self.matrix_nb + 1)\n #self.boutonGenCst.clicked.connect(self.generer_cst)\n # ========================\n\n # == DEBUG ==\n #print(dir(self.field_display_test))\n # ===========\n\n self.setWindowTitle(\"Memory Generator\")\n\n\n # Function : GetCheckboxes states\n def get_checkbox_states(self):\n for j in range(self.matrix_line_nb):\n for i in range(8*self.matrix_nb):\n item = self.grid_layout.itemAtPosition(j,i)\n self.widget = item.widget()\n self.grid[j][i] = self.widget.isChecked()\n\n \n # Function : Inversion de l'etat des checkboxes\n def inv_checkbox(self):\n for j in range(self.matrix_line_nb):\n for i in range(8*self.matrix_nb):\n item = self.grid_layout.itemAtPosition(j,i)\n widget = item.widget()\n self.grid[j][i] = widget.isChecked()\n\n if self.grid[j][i] == True :\n widget.setChecked(False)\n else:\n widget.setChecked(True)\n\n\n\n def generer_mem(self):\n print(self.grid)\n\n\n # Convert grid to a list[0:63]\n self.get_checkbox_states()\n matrix_out = np.zeros([64], int)\n\n list_out = []\n line_tmp = []\n\n for nb_line in range(0, 8):\n \n line_tmp = []\n for nb_col_i in range(0, 8*self.matrix_nb):\n if(self.grid[nb_line][nb_col_i] == True):\n line_tmp.append(1)\n else:\n line_tmp.append(0)\n list_out.append(line_tmp)\n\n \n\n print(list_out)\n # Generation of Memory file Function\n # def generer_mem(self):\n # #print(\"Generer Mem fctn\")\n\n # self.digit_7_matrix_n = []\n # self.digit_6_matrix_n = []\n # self.digit_5_matrix_n = []\n # self.digit_4_matrix_n = []\n # self.digit_3_matrix_n = []\n # self.digit_2_matrix_n = []\n # self.digit_1_matrix_n = []\n # self.digit_0_matrix_n = []\n \n # # Creates Array\n # for i in range (0, self.matrix_nb):\n # self.digit_7_matrix_n.append(\"\")\n # self.digit_6_matrix_n.append(\"\")\n # self.digit_5_matrix_n.append(\"\")\n # self.digit_4_matrix_n.append(\"\")\n # self.digit_3_matrix_n.append(\"\")\n # self.digit_2_matrix_n.append(\"\")\n # self.digit_1_matrix_n.append(\"\")\n # self.digit_0_matrix_n.append(\"\")\n \n # # == Save in self.grid the state of checkboxes\n # self.get_checkbox_states()\n \n # # == Fill Matrix af DIGITn Registers\n # for j in range (0, self.matrix_line_nb):\n # for i in range(0, self.matrix_nb):\n # self.digit_7_matrix_n[i] = self.digit_7_matrix_n[i] + (\"1\" if self.grid[j][i*8] else \"0\")\n # self.digit_6_matrix_n[i] = self.digit_6_matrix_n[i] + (\"1\" if self.grid[j][i*8 + 1] else \"0\")\n # self.digit_5_matrix_n[i] = self.digit_5_matrix_n[i] + (\"1\" if self.grid[j][i*8 + 2] else \"0\")\n # self.digit_4_matrix_n[i] = self.digit_4_matrix_n[i] + (\"1\" if self.grid[j][i*8 + 3] else \"0\")\n # self.digit_3_matrix_n[i] = self.digit_3_matrix_n[i] + (\"1\" if self.grid[j][i*8 + 4] else \"0\")\n # self.digit_2_matrix_n[i] = self.digit_2_matrix_n[i] + (\"1\" if self.grid[j][i*8 + 5] else \"0\")\n # self.digit_1_matrix_n[i] = self.digit_1_matrix_n[i] + (\"1\" if self.grid[j][i*8 + 6] else \"0\")\n # self.digit_0_matrix_n[i] = self.digit_0_matrix_n[i] + (\"1\" if self.grid[j][i*8 + 7] else \"0\")\n \n\n # for i in range (0, self.matrix_nb):\n # print(self.digit_7_matrix_n[i])\n # print(self.digit_6_matrix_n[i])\n # print(self.digit_5_matrix_n[i])\n # print(self.digit_4_matrix_n[i])\n # print(self.digit_3_matrix_n[i])\n # print(self.digit_2_matrix_n[i])\n # print(self.digit_1_matrix_n[i])\n # print(self.digit_0_matrix_n[i])\n\n\n #print()\n \n #self.write_file()\n\n\n # def write_file(self):\n\n # # == Data to Writes in Memory ==\n # wdata = []\n\n # # Init WDATA list\n # for i in range(0, int(self.field_memory_size.text())):\n # wdata.append(\"0000\")\n\n # for i in range (0, int(self.field_memory_size.text())): #5*self.matrix_nb):\n\n # # == Gestion Configuration Registres ==\n # if i < 1*self.matrix_nb :\n # if i == 1*self.matrix_nb - 1 :\n # wdata[i] = \"19\" + self.field_decod_mode.text()\n # else :\n # wdata[i] = \"09\" + self.field_decod_mode.text()\n \n # elif i >= 1*self.matrix_nb and i < 2*self.matrix_nb :\n # if i == 2*self.matrix_nb - 1 :\n # wdata[i] = \"1A\" + self.field_intensity.text()\n # else:\n # wdata[i] = \"0A\" + self.field_intensity.text()\n \n # elif i >= 2*self.matrix_nb and i < 3*self.matrix_nb :\n # if i == 3*self.matrix_nb - 1 :\n # wdata[i] = \"1B\" + self.field_scan_limit.text()\n # else:\n # wdata[i] = \"0B\" + self.field_scan_limit.text()\n \n # elif i >= 3*self.matrix_nb and i < 4*self.matrix_nb :\n # if i == 4*self.matrix_nb - 1 : \n # wdata[i] = \"1C\" + self.field_shutdown.text()\n # else:\n # wdata[i] = \"0C\" + self.field_shutdown.text()\n \n # elif i >= 4*self.matrix_nb and i < 5*self.matrix_nb :\n # if i == 5*self.matrix_nb - 1 :\n # wdata[i] = \"1F\" + self.field_display_test.text()\n # else:\n # wdata[i] = \"0F\" + self.field_display_test.text()\n # # ====================================\n\n # # == Gestion DIGIT pour affichage Matrix ==\n\n # # Write Digit 0\n # elif i >= 5*self.matrix_nb and i < 6*self.matrix_nb :\n # if i == 6*self.matrix_nb - 1 :\n # wdata[i] = \"11\" + format(int( (self.digit_0_matrix_n[self.matrix_nb - 1 - (i - 5*self.matrix_nb)]), 2), '02x')\n # else:\n # wdata[i] = \"01\" + format(int( (self.digit_0_matrix_n[self.matrix_nb - 1 - (i - 5*self.matrix_nb)]), 2), '02x')\n\n # # Write Digit 1\n # elif i >= 6*self.matrix_nb and i < 7*self.matrix_nb :\n # if i == 7*self.matrix_nb - 1 :\n # wdata[i] = \"12\" + format(int( (self.digit_1_matrix_n[self.matrix_nb - 1 - (i - 6*self.matrix_nb)]), 2), '02x')\n # else:\n # wdata[i] = \"02\" + format(int( (self.digit_1_matrix_n[self.matrix_nb - 1 - (i - 6*self.matrix_nb)]), 2), '02x')\n\n # # Write Digit 2\n # elif i >= 7*self.matrix_nb and i < 8*self.matrix_nb :\n # if i == 8*self.matrix_nb - 1 :\n # wdata[i] = \"13\" + format(int( (self.digit_2_matrix_n[self.matrix_nb - 1 - (i - 7*self.matrix_nb)]), 2), '02x')\n # else:\n # wdata[i] = \"03\" + format(int( (self.digit_2_matrix_n[self.matrix_nb - 1 - (i - 7*self.matrix_nb)]), 2), '02x')\n\n # # Write Digit 3\n # elif i >= 8*self.matrix_nb and i < 9*self.matrix_nb :\n # if i == 9*self.matrix_nb - 1 :\n # wdata[i] = \"14\" + format(int( (self.digit_3_matrix_n[self.matrix_nb - 1 - (i - 8*self.matrix_nb)]), 2), '02x')\n # else:\n # wdata[i] = \"04\" + format(int( (self.digit_3_matrix_n[self.matrix_nb - 1 - (i - 8*self.matrix_nb)]), 2), '02x')\n\n # # Write Digit 4\n # elif i >= 9*self.matrix_nb and i < 10*self.matrix_nb :\n # if i == 10*self.matrix_nb - 1 :\n # wdata[i] = \"15\" + format(int( (self.digit_4_matrix_n[self.matrix_nb - 1 - (i - 9*self.matrix_nb)]), 2), '02x')\n # else:\n # wdata[i] = \"05\" + format(int( (self.digit_4_matrix_n[self.matrix_nb - 1 - (i - 9*self.matrix_nb)]), 2), '02x')\n\n # # Write Digit 5\n # elif i >= 10*self.matrix_nb and i < 11*self.matrix_nb :\n # if i == 11*self.matrix_nb - 1 :\n # wdata[i] = \"16\" + format(int( (self.digit_5_matrix_n[self.matrix_nb - 1 - (i - 10*self.matrix_nb)]), 2), '02x')\n # else:\n # wdata[i] = \"06\" + format(int( (self.digit_5_matrix_n[self.matrix_nb - 1 - (i - 10*self.matrix_nb)]), 2), '02x')\n\n # # Write Digit 6\n # elif i >= 11*self.matrix_nb and i < 12*self.matrix_nb :\n # if i == 12*self.matrix_nb - 1 :\n # wdata[i] = \"17\" + format(int( (self.digit_6_matrix_n[self.matrix_nb - 1 - (i - 11*self.matrix_nb)]), 2), '02x')\n # else:\n # wdata[i] = \"07\" + format(int( (self.digit_6_matrix_n[self.matrix_nb - 1 - (i - 11*self.matrix_nb)]), 2), '02x')\n\n # # Write Digit 7\n # elif i >= 12*self.matrix_nb and i < 13*self.matrix_nb :\n # if i == 13*self.matrix_nb - 1 :\n # wdata[i] = \"18\" + format(int( (self.digit_7_matrix_n[self.matrix_nb - 1 - (i - 12*self.matrix_nb)]), 2), '02x')\n # else:\n # wdata[i] = \"08\" + format(int( (self.digit_7_matrix_n[self.matrix_nb - 1 - (i - 12*self.matrix_nb)]), 2), '02x')\n \n \n # =========================================\n # =============================\n \n \n\n # f = open(self.field_file_name.text(), \"w\")\n # f.writelines(\"// memory data file (do not edit the following line - required for mem load use)\\n\")\n # f.writelines(\"// instance=\" + self.field_instance_path.text() + \"\\n\")\n # f.writelines(\"// format=mti addressradix=d dataradix=h version=1.0 wordsperline=1\\n\")\n # for i in range(0, int(self.field_memory_size.text())):\n # # /!\\ : Ajout des espaces pas bien gere\n # if len(str(i)) == 1 :\n # f.writelines(\" \" + str(i) + \": \" + wdata[i] + \"\\n\")\n # elif len(str(i)) == 2 :\n # f.writelines(\" \" + str(i) + \": \" + wdata[i] + \"\\n\")\n # else :\n # f.writelines(str(i) + \": \" + wdata[i] + \"\\n\")\n \n \n # f.close()\n\n # Generation of a VHD file with a Constant wich contain the pattern of the Matrix\n # def generer_cst(self):\n # print(\"Generer Constant Def\")\n # data_array = []\n # data_array_int = []\n # data_array_final = []\n # tmp = 0\n # #offset = 7# Initial Offset\n\n # # INIT Array\n # for i in range(8*self.matrix_nb):\n # data_array_int.append(\"\")\n # data_array_final.append(\"\")\n \n # #print(\"data array int : %s \\n\" % (data_array_int) )\n \n # self.get_checkbox_states()\n # for i in range(8*self.matrix_nb):\n # data_array.append(\"\")\n # #data_array_int.append(\"\")\n # data_array[i] = str(int(self.grid[0][i])) + str(int(self.grid[1][i])) + str(int(self.grid[2][i])) + str(int(self.grid[3][i])) \n # data_array[i] = data_array[i] + str(int(self.grid[4][i])) + str(int(self.grid[5][i])) + str(int(self.grid[6][i])) + str(int(self.grid[7][i]))\n\n \n # tmp = (int(self.grid[0][i]) << 7) | (int(self.grid[1][i]) << 6) | (int(self.grid[2][i]) << 5) | (int(self.grid[3][i]) << 4) \n # data_array_int[i] = hex(tmp | (int(self.grid[4][i]) << 3) | (int(self.grid[5][i]) << 2) | (int(self.grid[6][i]) << 1 ) | (int(self.grid[7][i])))\n # #print(\"tmp : %s \\n\\n\" %(tmp) )\n # tmp = 0\n \n # print(\"data array int for SCROLLER RAM: %s \\n\" % (data_array_int) )\n # #print(type(data_array_int[0]))\n\n # #print(\"data array : %s \\n \" %(data_array) )\n \n # f = open(\"constant_gen.vhd\", \"w\")\n # f.writelines(\"type t_cst_array is array (0 to %d) of std_logic_vector(7 downto 0);\\n\" %(self.matrix_nb * 8 - 1))\n # f.writelines(\"constant C_CST_0 : t_cst_array := (\\n\")\n # for i in range(0, self.matrix_nb * 8):\n # if (i < self.matrix_nb * 8 - 1):\n # f.writelines(\" %s => x\\\"%s\\\",\\n\" %(i , format(int(data_array[i], 2), '02x') ) )\n # else:\n # f.writelines(\" %s => x\\\"%s\\\"\\n\" %(i , format(int(data_array[i], 2), '02x') ) )\n # f.writelines(\");\") \n # f.close()\n\n # # Data array final update\n # #offset = 0\n # #for i in range(8*self.matrix_nb):\n # #data_array_final[i*8 + 7 - offset] = str(data_array_int[i])\n # #print(\"i : %d\\n\" %(i) )\n # #print(\"offset : %d\\n\" %(offset) )\n # #print(\"(offset*8 - 1) - i : %d\\n\" %((offset*8 - 1) - i) )\n # #if i == :\n # # offset = (i*8 - 1)\n\n\n\n # #print(data_array_final)\n\n # digit_7_matrix_n = []\n # digit_6_matrix_n = []\n # digit_5_matrix_n = []\n # digit_4_matrix_n = []\n # digit_3_matrix_n = []\n # digit_2_matrix_n = []\n # digit_1_matrix_n = []\n # digit_0_matrix_n = []\n \n # # Creates Array\n # for i in range (0, self.matrix_nb):\n # digit_7_matrix_n.append(\"\")\n # digit_6_matrix_n.append(\"\")\n # digit_5_matrix_n.append(\"\")\n # digit_4_matrix_n.append(\"\")\n # digit_3_matrix_n.append(\"\")\n # digit_2_matrix_n.append(\"\")\n # digit_1_matrix_n.append(\"\")\n # digit_0_matrix_n.append(\"\")\n \n # # == Save in self.grid the state of checkboxes\n # self.get_checkbox_states()\n # tmp_d7 = 0\n # tmp_d6 = 0\n # tmp_d5 = 0\n # tmp_d4 = 0\n # tmp_d3 = 0\n # tmp_d2 = 0\n # tmp_d1 = 0\n # tmp_d0 = 0\n \n # # == Fill Matrix af DIGITn Registers\n # for j in range (0, self.matrix_nb):\n\n\n # # Get Collumn 0 (D7 (Mi))\n # tmp_d7 = (int(self.grid[0][j*8]) << 7) | (int(self.grid[1][j*8]) << 6) | (int(self.grid[2][j*8]) << 5) | (int(self.grid[3][j*8]) << 4) \n # tmp_d7 = hex(tmp_d7 | (int(self.grid[4][j*8]) << 3) | (int(self.grid[5][j*8]) << 2) | (int(self.grid[6][j*8]) << 1 ) | (int(self.grid[7][j*8])))\n # digit_7_matrix_n[self.matrix_nb - 1 - j] = tmp_d7\n\n # #print(\"tmp_d7 : %s \\n\" %(tmp_d7) )\n\n \n # # Get Collumn 1 (D6 (Mi))\n # tmp_d6 = (int(self.grid[0][j*8 + 1]) << 7) | (int(self.grid[1][j*8 + 1]) << 6) | (int(self.grid[2][j*8 + 1]) << 5) | (int(self.grid[3][j*8 + 1]) << 4) \n # tmp_d6 = hex(tmp_d6 | (int(self.grid[4][j*8 + 1]) << 3) | (int(self.grid[5][j*8 + 1]) << 2) | (int(self.grid[6][j*8 + 1]) << 1 ) | (int(self.grid[7][j*8 + 1])))\n # digit_6_matrix_n[self.matrix_nb - 1 - j] = tmp_d6\n\n # #print(\"tmp_d6 : %s \\n\" %(tmp_d6) )\n\n # # Get Collumn 2 (D5 (Mi))\n # tmp_d5 = (int(self.grid[0][j*8 + 2]) << 7) | (int(self.grid[1][j*8 + 2]) << 6) | (int(self.grid[2][j*8 + 2]) << 5) | (int(self.grid[3][j*8 + 2]) << 4) \n # tmp_d5 = hex(tmp_d5 | (int(self.grid[4][j*8 + 2]) << 3) | (int(self.grid[5][j*8 + 2]) << 2) | (int(self.grid[6][j*8 + 2]) << 1 ) | (int(self.grid[7][j*8 + 2])))\n # digit_5_matrix_n[self.matrix_nb - 1 - j] = tmp_d5\n\n # # Get Collumn 3 (D4 (Mi))\n # tmp_d4 = (int(self.grid[0][j*8 + 3]) << 7) | (int(self.grid[1][j*8 + 3]) << 6) | (int(self.grid[2][j*8 + 3]) << 5) | (int(self.grid[3][j*8 + 3]) << 4) \n # tmp_d4 = hex(tmp_d4 | (int(self.grid[4][j*8 + 3]) << 3) | (int(self.grid[5][j*8 + 3]) << 2) | (int(self.grid[6][j*8 + 3]) << 1 ) | (int(self.grid[7][j*8 + 3])))\n # digit_4_matrix_n[self.matrix_nb - 1 - j] = tmp_d4\n\n # # Get Collumn 4 (D3 (Mi))\n # tmp_d3 = (int(self.grid[0][j*8 + 4]) << 7) | (int(self.grid[1][j*8 + 4]) << 6) | (int(self.grid[2][j*8 + 4]) << 5) | (int(self.grid[3][j*8 + 4]) << 4) \n # tmp_d3 = hex(tmp_d3 | (int(self.grid[4][j*8 + 4]) << 3) | (int(self.grid[5][j*8 + 4]) << 2) | (int(self.grid[6][j*8 + 4]) << 1 ) | (int(self.grid[7][j*8 + 4])))\n # digit_3_matrix_n[self.matrix_nb - 1 - j] = tmp_d3\n\n # # Get Collumn 5 (D2 (Mi))\n # tmp_d2 = (int(self.grid[0][j*8 + 5]) << 7) | (int(self.grid[1][j*8 + 5]) << 6) | (int(self.grid[2][j*8 + 5]) << 5) | (int(self.grid[3][j*8 + 5]) << 4) \n # tmp_d2 = hex(tmp_d2 | (int(self.grid[4][j*8 + 5]) << 3) | (int(self.grid[5][j*8 + 5]) << 2) | (int(self.grid[6][j*8 + 5]) << 1 ) | (int(self.grid[7][j*8 + 5])))\n # digit_2_matrix_n[self.matrix_nb - 1 - j] = tmp_d2\n\n # # Get Collumn 6 (D1 (Mi))\n # tmp_d1 = (int(self.grid[0][j*8 + 6]) << 7) | (int(self.grid[1][j*8 + 6]) << 6) | (int(self.grid[2][j*8 + 6]) << 5) | (int(self.grid[3][j*8 + 6]) << 4) \n # tmp_d1 = hex(tmp_d1 | (int(self.grid[4][j*8 + 6]) << 3) | (int(self.grid[5][j*8 + 6]) << 2) | (int(self.grid[6][j*8 + 6]) << 1 ) | (int(self.grid[7][j*8 + 6])))\n # digit_1_matrix_n[self.matrix_nb - 1 - j] = tmp_d1\n\n # # Get Collumn 7 (D0 (Mi))\n # tmp_d0 = (int(self.grid[0][j*8 + 7]) << 7) | (int(self.grid[1][j*8 + 7]) << 6) | (int(self.grid[2][j*8 + 7]) << 5) | (int(self.grid[3][j*8 + 7]) << 4) \n # tmp_d0 = hex(tmp_d0 | (int(self.grid[4][j*8 + 7]) << 3) | (int(self.grid[5][j*8 + 7]) << 2) | (int(self.grid[6][j*8 + 7]) << 1 ) | (int(self.grid[7][j*8 + 7])))\n # digit_0_matrix_n[self.matrix_nb - 1 - j] = tmp_d0\n\n \n # tmp_d7 = 0\n # tmp_d6 = 0\n # tmp_d5 = 0\n # tmp_d4 = 0\n # tmp_d3 = 0\n # tmp_d2 = 0\n # tmp_d1 = 0\n # tmp_d0 = 0\n\n # #print(\"\\n digit_7_matrix_n : %s \\n\" % (digit_7_matrix_n) )\n # #print(\"\\n digit_6_matrix_n : %s \\n\" % (digit_6_matrix_n) )\n # #print(\"\\n digit_5_matrix_n : %s \\n\" % (digit_5_matrix_n) )\n # #print(\"\\n digit_4_matrix_n : %s \\n\" % (digit_4_matrix_n) )\n # #print(\"\\n digit_3_matrix_n : %s \\n\" % (digit_3_matrix_n) )\n # #print(\"\\n digit_2_matrix_n : %s \\n\" % (digit_2_matrix_n) )\n # #print(\"\\n digit_1_matrix_n : %s \\n\" % (digit_1_matrix_n) )\n # #print(\"\\n digit_0_matrix_n : %s \\n\" % (digit_0_matrix_n) )\n \n # final_array = []\n\n # for i in range(0, 8*self.matrix_nb):\n # final_array.append(\"\")\n\n # for i in range(0, self.matrix_nb):\n # final_array[i] = digit_0_matrix_n[i]\n # final_array[i + 1*self.matrix_nb] = digit_1_matrix_n[i]\n # final_array[i + 2*self.matrix_nb] = digit_2_matrix_n[i]\n # final_array[i + 3*self.matrix_nb] = digit_3_matrix_n[i]\n # final_array[i + 4*self.matrix_nb] = digit_4_matrix_n[i]\n # final_array[i + 5*self.matrix_nb] = digit_5_matrix_n[i]\n # final_array[i + 6*self.matrix_nb] = digit_6_matrix_n[i]\n # final_array[i + 7*self.matrix_nb] = digit_7_matrix_n[i]\n\n\n # print(\"\\n\\nFinal array for STATIC RAM : %s\\n\" %(final_array))\n # #print(len(final_array))\n \n \n # # Save the status of checkboxes in order to load a specific pattern\n # def save_state_checkboxes(self):\n # print(\"Save States checkboxes\")\n\n\n\napp = QtWidgets.QApplication(sys.argv)\ndialog = window()\ndialog.exec_()\n","sub_path":"UART/scripts/model_interface_web/mem_gen.py","file_name":"mem_gen.py","file_ext":"py","file_size_in_byte":25048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"541140193","text":"\n\nfrom xai.brain.wordbase.nouns._brontosaurus import _BRONTOSAURUS\n\n#calss header\nclass _BRONTOSAURUSES(_BRONTOSAURUS, ):\n\tdef __init__(self,): \n\t\t_BRONTOSAURUS.__init__(self)\n\t\tself.name = \"BRONTOSAURUSES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"brontosaurus\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_brontosauruses.py","file_name":"_brontosauruses.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"577954106","text":"#/usr/bin/python\nfrom __future__ import print_function\nimport sys\nimport time\nimport rosbag\nfrom sets import Set\nimport numpy as np\nimport subprocess, yaml\nimport os\nimport xml.etree.ElementTree as ET\nimport re\nfrom xml.dom import minidom\n\ndef determine(xml_tree):\n\tcomment_div = \"\" % \"other\"\n\tnew_tree = ET.ElementTree()\n\tnew_root = ET.Element('root')\n\tnew_tree._setroot(new_root)\n\troot = xml_tree.getroot()\n\tfor child in root.iter(\"PPT\"):\n\t\tprint(child.find(\"PPTNAME\").text)\n\t\tans = raw_input(\"Useful? y/n: \")\n\t\tif('n' in ans):\n\t\t\troot.remove(child)\n\treturn xml_tree\n\ndef main():\n\t#first arg: property file\n\t# second arg: \n\toutput_filename=sys.argv[1].split(\".\")\n\txml_filehead=output_filename[0]\n\n\t#handle CL args\n\tregrouped_filename=xml_filehead+\"_usefulppts.xml\"\n\n\t#process .inv xml\n\tprint(\"Parsing \"+str(sys.argv[1]))\n\txml_tree = ET.parse(sys.argv[1])\n\tregrouped_xml_tree = determine(xml_tree)\n\troot = regrouped_xml_tree.getroot()\n\t#regrouped_xml_string.write(regrouped_filename, encoding=\"utf-8\", pretty_print=True)\n\n\txmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=\" \")\n\twith open(regrouped_filename, \"w\") as f:\n\t\tf.write(xmlstr)\n\tprint(\"Regrouped .xml file: \"+regrouped_filename)\n\nif __name__ == \"__main__\":\n # execute only if run as a script \n main()\n","sub_path":"clean_bags/determine_useful_ppts.py","file_name":"determine_useful_ppts.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"364959226","text":"import subprocess\nimport pynvim\nimport requests\nimport json\n\n\n@pynvim.plugin\nclass Hub(object):\n def __init__(self, nvim):\n self.nvim = nvim\n self.tmp_ctags_path = \"/tmp/{}.tags\"\n self.server_url = 'http://localhost:1337/{}'\n self.terminal_buf_id = 0\n\n @pynvim.autocmd('BufEnter', pattern='*.hub', sync=True)\n def autocmd_bufenter(self):\n \"\"\"\n This function is primarily for generating and loading ctags to the\n current nvim instance to enable convenient way to use our applications\n \"\"\"\n try:\n # Asking the server for installed applications\n r = requests.get(self.server_url.format('applications'))\n loaded_applications = r.json()\n for application in loaded_applications:\n ctags_path = self.tmp_ctags_path.format(application)\n self.generate_absolute_python_ctags(loaded_applications[application], ctags_path)\n self.load_ctags(ctags_path)\n except Exception as e:\n self.out(\"Hub: exception ({})\".format(str(e)))\n\n @pynvim.function('HubFunc')\n def function_handler(self, args):\n try:\n # Extract all information we might need.\n nvim_buffer = self.nvim.current.buffer\n\n # Current possion\n cursor_line = self.nvim.call('line', '.')\n cursor_column = self.nvim.call('col', '.')\n quickfix = self.nvim.call('getqflist')\n\n # Selection\n selected_start_line = self.nvim.call('getpos',\"'<\")[1]\n selected_start_column = self.nvim.call('getpos',\"'<\")[2]\n selected_end_line = self.nvim.call('getpos',\"'>\")[1]\n selected_end_column = self.nvim.call('getpos',\"'>\")[2]\n\n json_to_send = {\n 'nvim_buffer': '\\n'.join(nvim_buffer[:]),\n 'cursor_line': cursor_line,\n 'cursor_column': cursor_column,\n 'selected_start_line': selected_start_line,\n 'selected_start_column': selected_start_column,\n 'selected_end_line': selected_end_line,\n 'selected_end_column': selected_end_column\n }\n r = requests.post(self.server_url.format('execute'), json=json_to_send)\n self.out(str(r.status_code))\n self.out(str(r.text))\n except Exception as e:\n self.out(\"Hub: exception ({})\".format(str(e)))\n\n @pynvim.function('HubLaunchTerminal')\n def spawn_terminal_handler(self, args):\n try:\n command = args[0]\n\n # split to spawn te terminal\n self.nvim.command(\"split\")\n # create new buffer to put the terminal in.\n self.nvim.command(\"enew\")\n\n # keep track of the terminal buffer id\n self.terminal_buf_id = self.nvim.call('bufnr','%')\n\n # launch terminal with on_exit handler\n termopen_args = {'on_exit': 'HubTerminalOnExit'}\n self.nvim.call('termopen', command, termopen_args)\n\n # enter insert mode int terminal\n self.nvim.command(\"normal i\")\n except Exception as e:\n self.out(\"Hub: exception ({})\".format(str(e)))\n\n @pynvim.function('HubTerminalOnExit')\n def terminal_on_exit_handler(self, args):\n job_id = args[0]\n code = args[1]\n event = args[2]\n terminal_lines = self.nvim.call('nvim_buf_get_lines', self.terminal_buf_id, 0, -1, False)\n\n # self.out('\\n'.join(terminal_lines))\n self.nvim.command(\"close\")\n\n def out(self, message):\n message = message.replace(\"\\\"\", \"\\\\\\\"\")\n self.nvim.command(f\"echo \\\"{message}\\\"\")\n\n def set_quickfix_list(self, quickfix_list):\n \"\"\"\n [\n {\n 'filename':'',\n 'lnum': '',\n 'text': ''\n }\n ]\n \"\"\"\n self.nvim.call('setqflist', quickfix_list)\n\n def modify_buffer(self, buffer_number, lines):\n self.nvim.call('nvim_buf_set_lines', buffer_number, 0, -1, 0, lines)\n\n def load_ctags(self, ctags_path):\n self.nvim.command(f\"set tags+={ctags_path}\")\n\n def generate_absolute_python_ctags(self, project_path, ctags_path):\n p = subprocess.Popen(\n [\n \"ctags\",\n \"--python-kinds=-i\",\n \"-f\",\n ctags_path,\n \"-R\",\n project_path\n ], \n cwd=\"/\")\n p.wait()\n\n def generate_absolute_ctags(self, project_path, ctags_path):\n p = subprocess.Popen(\n [\n \"ctags\",\n \"-f\",\n ctags_path,\n \"-R\",\n project_path\n ], \n cwd=\"/\")\n p.wait()\n","sub_path":"vim_client/hub.py","file_name":"hub.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"90077767","text":"#===================================================================#\n# Tool Name: FVS Test Module #\n# Version: 0.2 #\n# Edit by: Chris Liu 2017/05/27 #\n#===================================================================#\nfrom Module.common import *\n\nglobal TOOL_NAME\nTOOL_NAME = \"FVS Test Module\"\n\nglobal VER\nVER = \"0.2\"\n#===============================================================================\ndef Check_LED():\n\t'''Visual Check LEDs Function'''\n\n\tflag = False\n\n\tret = input(\"Press y/n for LED Function!!\\n\").strip().lower()\n\n\tif(ret == \"y\"):\n\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_LED Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_LED Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_BIOS():\n\t'''Check BIOS Version'''\n\n\tflag = False\n\n\tcmd = \"%s \\\"Get-WmiObject %s | format-list\\\"\"%(POWERSHELL, \"Win32_BIOS\")\n\tret = Input_CMD_OS(cmd)\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"SMBIOSBIOSVersion\" in i and \"1.4.17\" in i):\n\t\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_BIOS Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_BIOS Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_Service_Tag():\n\t'''Check Service Tag'''\n\n\tflag = False\n\n\tcmd = \"%s \\\"Get-WmiObject %s | format-list\\\"\"%(POWERSHELL, \"Win32_BIOS\")\n\tret = Input_CMD_OS(cmd)\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"SerialNumber\" in i and \"H2C1GC2\" in i):\n\t\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_Service_Tag Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_Service_Tag Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef main():\n\ttest_items = [\n\t\t(\"Check_BIOS\", Check_BIOS),\n\t\t(\"Check_Service_Tag\", Check_Service_Tag),\n\t\t(\"Check_LED\", Check_LED),\n\t]\n\n\ttest_sequence = Argument_Parser(TOOL_NAME, VER, OrderedDict(test_items))\n\n\tBanner(\"%s, By Foxconn CESBG-EPDI-TE, Version: %s\"%(TOOL_NAME, VER))\n\tGet_PPID()\n\tConfig_Parser(VER)\n\n\tFVS_Test(test_sequence)\n#===============================================================================\nif(__name__ == \"__main__\"):\n\ttry:\n\t\tmain()\n\texcept Exception as e:\n\t\tprint(\"ERROR: %s\"%(str(e)))\n\t\tsys.exit(-1)\n\tsys.exit(0)\n","sub_path":"FVS/TEST.py","file_name":"TEST.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"181056717","text":"import data_loader as dl\nimport matplotlib.pyplot as plt\n\n\nfolder = '/home/shenghua/dl-cell-counting/mt-cell-train-data/dataset/'\n\n#imageFileName = folder + 'imageSet.dat'\n#densityFileName = folder + 'densitySet.dat'\n\nimageFileName = folder + 'realImages.dat'\ndensityFileName = folder + 'realDensities.dat'\n\n# x = dl.train_load(imageFileName)\n# y = dl.truth_load(densityFileName)\n\nx = dl.train_data_load(imageFileName,(512,512),10)\ny = dl.truth_data_load(densityFileName,(512,512),10)\n\nfig = plt.figure()\n\nax = fig.add_subplot(1,2,1)\nax.imshow(x[0,:,:])\nax.set_title('Synthetic images')\nax = fig.add_subplot(1,2,2)\nax.imshow(y[0,:,:])\nax.set_title('Density map')\nplt.show()\n\n\nplt.ion()\nfig = plt.figure()\nfor i in range(len(x)):\n\tax = fig.add_subplot(1,2,1)\n\tax.imshow(x[i])\n\tax = fig.add_subplot(1,2,2)\n\tax.imshow(y[i])\n\tplt.pause(0.5)\n\t\nimport keras.backend as K\nlr=0.0005\nmodel=cg.layer9_cnn()\nsgd = SGD(lr=lr, decay=1e-4, momentum=0.9, nesterov=True)\nmodel.compile(loss='mean_squared_error', optimizer=sgd)\n# model.compile(loss='mean_squared_error', optimizer=sgd, metrics=['accuracy'])\n","sub_path":"dl-counting/data_check.py","file_name":"data_check.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"571952962","text":"import xlrd\nimport csv\n\n# CONSTANTS\nCUST_CODE = 2\nKRA_PIN = 5\nEMAIL = 12\nPHONE = 13\n\n\ndef read_data():\n workbook = xlrd.open_workbook(\"./customerdata.xls\")\n sheet = workbook.sheet_by_index(0)\n data = [sheet.row_values(rowx) for rowx in range(sheet.nrows)]\n return data\n\n\ndef find_duplicate_customer_pins(data):\n ALL_CUSTOMERS_BY_PIN = {}\n # DUPLICATE_CUSTOMERS_BY_PIN = {}\n\n for d in data:\n if(d[KRA_PIN] is not \"\"):\n if d[KRA_PIN] in ALL_CUSTOMERS_BY_PIN:\n ALL_CUSTOMERS_BY_PIN[d[KRA_PIN]].append(d[CUST_CODE])\n # if d[KRA_PIN] in DUPLICATE_CUSTOMERS_BY_PIN:\n # DUPLICATE_CUSTOMERS_BY_PIN[d[KRA_PIN]] += 1\n # else:\n # DUPLICATE_CUSTOMERS_BY_PIN[d[KRA_PIN]] = 2\n else:\n ALL_CUSTOMERS_BY_PIN[d[KRA_PIN]] = [d[CUST_CODE]]\n\n return ALL_CUSTOMERS_BY_PIN\n\n\ndef find_duplicate_customer_codes(data):\n ALL_CUSTOMERS_BY_CUST_CODE = {}\n DUPLICATE_CUSTOMER_CODES = []\n\n for d in data:\n if d[CUST_CODE] in ALL_CUSTOMERS_BY_CUST_CODE:\n DUPLICATE_CUSTOMER_CODES.append(d[CUST_CODE])\n else:\n ALL_CUSTOMERS_BY_CUST_CODE[d[CUST_CODE]] = d\n\n return DUPLICATE_CUSTOMER_CODES\n\n\ndef find_duplicate_emails(data):\n ALL_CUSTOMERS_BY_EMAIL = {}\n DUPLICATE_EMAIL_ADDRESSES = []\n DUPLICATE_RESULTS = {}\n\n for d in data:\n split_emails = d[EMAIL].split(',')\n for email in split_emails:\n if email in ALL_CUSTOMERS_BY_EMAIL:\n if email not in DUPLICATE_EMAIL_ADDRESSES:\n DUPLICATE_EMAIL_ADDRESSES.append(email)\n ALL_CUSTOMERS_BY_EMAIL[email].append(d)\n else:\n ALL_CUSTOMERS_BY_EMAIL[email] = [d]\n\n for dup in DUPLICATE_EMAIL_ADDRESSES:\n curDup = ALL_CUSTOMERS_BY_EMAIL[dup]\n for customer in curDup:\n for cust2 in curDup:\n if cust2 is customer:\n continue\n\n if customer[2] not in DUPLICATE_RESULTS:\n DUPLICATE_RESULTS[customer[2]] = []\n\n if cust2[2] not in DUPLICATE_RESULTS[customer[2]]:\n DUPLICATE_RESULTS[customer[2]].append(cust2[2])\n\n return DUPLICATE_RESULTS\n\n\ndef find_duplicate_phone_numbers(data):\n ALL_CUSTOMERS_BY_PHONE = {}\n DUPLICATE_PHONE_NUMBERS = []\n DUPLICATE_RESULTS = {}\n\n for d in data:\n split_phone_numbers = d[PHONE].split(',')\n for phone in split_phone_numbers:\n if phone in ALL_CUSTOMERS_BY_PHONE:\n if phone not in DUPLICATE_PHONE_NUMBERS:\n DUPLICATE_PHONE_NUMBERS.append(phone)\n ALL_CUSTOMERS_BY_PHONE[phone].append(d)\n else:\n ALL_CUSTOMERS_BY_PHONE[phone] = [d]\n\n for dup in DUPLICATE_PHONE_NUMBERS:\n curDup = ALL_CUSTOMERS_BY_PHONE[dup]\n for customer in curDup:\n for cust2 in curDup:\n if cust2 is customer:\n continue\n\n if customer[2] not in DUPLICATE_RESULTS:\n DUPLICATE_RESULTS[customer[2]] = []\n\n if cust2[2] not in DUPLICATE_RESULTS[customer[2]]:\n DUPLICATE_RESULTS[customer[2]].append(cust2[2])\n\n # for dup in DUPLICATE_RESULTS:\n # print(str(dup))\n\n return DUPLICATE_RESULTS\n\n\ndef output(pins, codes, emails, phones):\n output = \">>> Below are duplicate customers based on their customer codes, emails and phone numbers\"\n\n output += \"\\n\\n>>> Duplicate Customers by Customer KRA Pin\\n\\n\"\n for pin in pins:\n output += pin + \"\\n\"\n\n # output += \"\\n\\n>>> Duplicate Customers by Customer Codes\\n\\n\"\n # for code in codes:\n # output += code + \"\\n\"\n\n # output += \"\\n\\n>>> Duplicate Customers by Email Address\\n\\n\"\n # for email in emails:\n # output += email + \": \" + str(emails[email]) + \"\\n\"\n\n # output += \"\\n\\n>>> Duplicate Customers by Phone Numbers\\n\\n\"\n # for phone in phones:\n # output += phone + \": \" + str(phones[phone]) + \"\\n\"\n\n text_file = open(\"duplicates.txt\", \"w\")\n text_file.write(output)\n text_file.close()\n\n\ndef unique_duplicates(emails, phones):\n print('unique duplicates')\n UNIQUE_DUPLICATES = {}\n for email in emails:\n if email not in UNIQUE_DUPLICATES:\n UNIQUE_DUPLICATES[email] = emails[email]\n\n for phone in phones:\n if phone not in UNIQUE_DUPLICATES:\n UNIQUE_DUPLICATES[phone] = phones[phone]\n\n output = \">>> Unique Duplicates across Email and Phone\\n\\n\"\n for dup in UNIQUE_DUPLICATES:\n output += dup + \": \" + str(UNIQUE_DUPLICATES[dup]) + \"\\n\"\n\n text_file = open(\"unique_duplicates.txt\", \"w\")\n text_file.write(output)\n text_file.close()\n\n\ndef print_duplicate_customers_by_pins(customersByKRA):\n with open('duplicate_by_kra.csv', mode='w') as csv_file:\n fieldnames = ['kra_pin', 'cust_1', 'cust_2', 'cust_3', 'cust_4', 'cust_5', 'cust_6', 'cust_7', 'cust_8', 'cust_9', 'cust_10',\n 'cust_11', 'cust_12', 'cust_13', 'cust_14', 'cust_15', 'cust_16', 'cust_17', 'cust_18', 'cust_19', 'cust_20', 'cust_21', 'cust_22', 'cust_23']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n\n writer.writeheader()\n for kra in customersByKRA:\n data = {}\n data['kra_pin'] = kra\n for dup in range(0, 22):\n keyName = 'cust_' + str(dup+1)\n if len(customersByKRA[kra]) < dup+1:\n data[keyName] = \"\"\n else:\n data[keyName] = customersByKRA[kra][dup]\n writer.writerow(data)\n\n\ndef __main__():\n print('>>> read data')\n data = read_data()\n\n print('>>> find duplicate customer codes')\n # duplicate_customer_by_codes = find_duplicate_customer_codes(data)\n # RESULTS FOR ALL DUPLICATE CUSTOMER CODES: ['CCP0013263', 'CKS0000112', 'CLU0003919', 'CGI0000436', 'CMT0001267', 'CAI0000001', 'CFR0000422', 'CFN0000337', 'CFN0000896']\n\n print('>>> find duplicate customer pins')\n duplicate_customer_by_pins = find_duplicate_customer_pins(data)\n print_duplicate_customers_by_pins(duplicate_customer_by_pins)\n\n # print('>>> find duplicate email addresses')\n # duplicate_customers_by_emails = find_duplicate_emails(data)\n\n # print('>>> find duplicate phone numbers')\n # duplicate_customers_by_phone = find_duplicate_phone_numbers(data)\n\n # output(duplicate_customer_by_pins, duplicate_customer_by_codes,\n # duplicate_customers_by_emails, duplicate_customers_by_phone)\n\n # unique_duplicates(duplicate_customers_by_emails,\n # duplicate_customers_by_phone)\n print('>>> finished')\n\n\n__main__()\n\n# ALLEMAILS = {}\n# REPEATEDEMAILS = {}\n\n# for d in data:\n# splitEmails = d[EMAIL].split(\",\")\n# # print(splitEmails)\n# for email in splitEmails:\n# email = email.lower()\n# if email.find('purchases@silverstone.co.ke') >= 0:\n# print(str(d[CUST_CODE]) + ' ' + str(d[EMAIL]))\n\n# # if email in ALLEMAILS:\n# # # print('d[custcode]: ' + d[CUST_CODE] +\n# # # ' ALLEMAILS[email]: ' + ALLEMAILS[email][CUST_CODE])\n# # if d[CUST_CODE] is not ALLEMAILS[email][CUST_CODE]:\n# # print('cust codes dont match? ' +\n# # d[CUST_CODE] + ' ' + ALLEMAILS[email][CUST_CODE] + ' ' + email)\n# # # REPEATEDEMAILS[email] = d\n# # # # print('repeated emails: ' + email)\n# # else:\n# # print('cust codes match? ' +\n# # d[CUST_CODE] + ' ' + ALLEMAILS[email][CUST_CODE] + ' ' + email)\n# # # # same customer code, don't add\n# # # print('same cust code: ' + email)\n# # else:\n# # ALLEMAILS[email] = d\n# # ALLEMAILS\n\n# print(data[1][EMAIL])\n\n\n# thoughts:\n# - most accounts have multiple phone numbers or multiple email addresses\n# - many accounts have multiple people from the same company - is there a\n# way to handle companies differently if there's one \"bill\"\n# - some customers like CFN0000896 are duplicate entries (Silverstone Tyres (K) LTD)\n","sub_path":"sortByKra/sortCustomers.py","file_name":"sortCustomers.py","file_ext":"py","file_size_in_byte":8217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"332695510","text":"import bpy\r\nimport os\r\nimport logging\r\nimport math\r\nimport bmesh\r\nimport copy\r\ndef alert_error(title,message):\r\n def draw(self,context):\r\n self.layout.label(text=str(message))\r\n bpy.context.window_manager.popup_menu(draw,title=title,icon='ERROR')\r\n\r\nzero_roll_list=[\"Head\",\"Neck_Middle\",\"Neck\",\"LowerBody\",\"UpperBody\",\"UpperBody2\",\"spine.001\",\"UpperBody3\",\"Leg_L\",\"Leg_R\",\"Knee_L\",\"Knee_R\",\"Ankle_L\",\"Ankle_R\",\"toe.L\",\"toe.R\"]\r\n\r\n\r\n\r\ndef quad(rad):\r\n degree=rad*180/math.pi\r\n degree= degree % 360\r\n if degree <= 90:\r\n Quadrant = 1\r\n else:\r\n if degree <= 180:\r\n Quadrant = 2\r\n else:\r\n if degree <= 270:\r\n Quadrant = 3\r\n else:\r\n if degree <= 360:\r\n Quadrant = 4\r\n\r\n return Quadrant\r\n\r\ndef check_arm():\r\n global mmd_arm\r\n global mmd_bones_list\r\n\r\n mmd_arm=bpy.context.object\r\n have_rigify=False\r\n for addon in bpy.context.preferences.addons:\r\n if addon.module==\"rigify\":\r\n have_rigify=True\r\n if mmd_arm==None:\r\n logging.info(\"未选择骨骼!\")\r\n alert_error(\"提示\",\"未选择骨骼!\")\r\n return(False)\r\n if have_rigify==False:\r\n logging.info(\"检测到未开启rigify,已自动开启\")\r\n alert_error(\"提示\",\"检测到未开启rigify,已自动开启\")\r\n bpy.ops.preferences.addon_enable(module=\"rigify\")\r\n if \"_arm\" not in mmd_arm.name:\r\n logging.info(\"所选对象不是MMD骨骼!\")\r\n alert_error(\"提示\",\"所选对象不是MMD骨骼!\")\r\n return(False)\r\n elif mmd_arm.parent==None:\r\n logging.info(\"所选对象不是MMD骨骼!\")\r\n alert_error(\"提示\",\"所选对象不是MMD骨骼!\")\r\n return(False) \r\n elif mmd_arm.name.replace(\"_arm\",\"\") != mmd_arm.parent.name:\r\n logging.info(\"所选对象不是MMD骨骼!\")\r\n alert_error(\"提示\",\"所选对象不是MMD骨骼!\")\r\n return(False) \r\n bpy.ops.mmd_tools.translate_mmd_model(dictionary='INTERNAL', types={'BONE'}, modes={'MMD', 'BLENDER'})\r\n mmd_bones_list=mmd_arm.data.bones.keys()\r\n if \"UpperBodyB\" in mmd_bones_list:\r\n mmd_arm.data.bones[\"UpperBodyB\"].name=\"UpperBody2\"\r\n mmd_bones_list=mmd_arm.data.bones.keys()\r\n\r\n return (True)\r\n\r\n#Outdated methods\r\ndef fix_axial_simple():\r\n\r\n global mmd_arm\r\n global mmd_bones_list\r\n fix_bone_list=[\r\n \"Thumb0_L\",\"Thumb1_L\",\"Thumb2_L\",\"Thumb0_R\",\"Thumb1_R\",\"Thumb2_R\",\"IndexFinger1_L\",\"IndexFinger1_R\",\"IndexFinger2_L\",\"IndexFinger2_R\",\"IndexFinger3_L\",\"IndexFinger3_R\",\r\n \"MiddleFinger1_L\",\"MiddleFinger1_R\",\"MiddleFinger2_L\",\"MiddleFinger2_R\",\"MiddleFinger3_L\",\"MiddleFinger3_R\",\"RingFinger1_L\",\"RingFinger1_R\",\"RingFinger2_L\",\"RingFinger2_R\",\"RingFinger3_L\",\"RingFinger3_R\",\r\n \"LittleFinger1_L\",\"LittleFinger1_R\",\"LittleFinger2_L\",\"LittleFinger2_R\",\"LittleFinger3_L\",\"LittleFinger3_R\",\"Shoulder_L\",\"Shoulder_R\",\"Arm_L\",\"Arm_R\",\"Elbow_L\",\"Elbow_R\",\"Wrist_L\",\"Wrist_R\"\r\n ]\r\n p_operate_bones=[\r\n \"IndexFinger1_L\",\"IndexFinger2_L\",\"IndexFinger3_L\",\r\n \"MiddleFinger1_L\",\"MiddleFinger2_L\",\"MiddleFinger3_L\",\"RingFinger1_L\",\"RingFinger2_L\",\"RingFinger3_L\",\r\n \"LittleFinger1_L\",\"LittleFinger2_L\",\"LittleFinger3_L\",\"LittleFinger3_R\"]\r\n n_operate_bones=[\r\n \"IndexFinger1_R\",\"IndexFinger2_R\",\"IndexFinger3_R\",\r\n \"MiddleFinger1_R\",\"MiddleFinger2_R\",\"MiddleFinger3_R\",\"RingFinger1_R\",\"RingFinger2_R\",\"RingFinger3_R\",\r\n \"LittleFinger1_R\",\"LittleFinger2_R\",\"LittleFinger3_R\"]\r\n bpy.ops.armature.select_all(action='DESELECT')\r\n for name in fix_bone_list:\r\n if name in mmd_bones_list:\r\n mmd_arm.data.edit_bones[name].select=True\r\n bpy.ops.armature.calculate_roll(type='GLOBAL_NEG_Y')\r\n for name in p_operate_bones:\r\n if name in mmd_bones_list:\r\n mmd_arm.data.edit_bones[name].roll+=math.pi/2\r\n for name in n_operate_bones:\r\n if name in mmd_bones_list:\r\n mmd_arm.data.edit_bones[name].roll-=math.pi/2\r\n \r\n alert_error(\"提示\",\"轴向修正完成\")\r\n\r\n#Outdated methods\r\ndef fix_axial():\r\n global mmd_arm\r\n L_first_quadrant_list=[\r\n \"IndexFinger1_L\",\"IndexFinger2_L\",\"IndexFinger3_L\",\r\n \"MiddleFinger1_L\",\"MiddleFinger2_L\",\"MiddleFinger3_L\",\"RingFinger1_L\",\"RingFinger2_L\",\"RingFinger3_L\",\r\n \"LittleFinger1_L\",\"LittleFinger2_L\",\"LittleFinger3_L\",\"Shoulder_L\",\"Arm_L\",\"Elbow_L\"\r\n ]\r\n L_second_quadrant_bones_list=[\"Thumb0_L\",\"Thumb1_L\",\"Thumb2_L\",\"Wrist_L\"]\r\n R_first_quadrant_bones_list=[\r\n \"IndexFinger1_R\",\"IndexFinger2_R\",\"IndexFinger3_R\",\r\n \"MiddleFinger1_R\",\"MiddleFinger2_R\",\"MiddleFinger3_R\",\"RingFinger1_R\",\"RingFinger2_R\",\"RingFinger3_R\",\r\n \"LittleFinger1_R\",\"LittleFinger2_R\",\"LittleFinger3_R\",\"Shoulder_R\",\"Arm_R\",\"Elbow_R\"\r\n ]\r\n R_second_quadrant_bones_list=[\"Thumb0_R\",\"Thumb1_R\",\"Thumb2_R\",\"Wrist_R\"]\r\n\r\n for name in zero_roll_list:\r\n if name in mmd_bones_list:\r\n bone=mmd_arm.data.edit_bones[name]\r\n bone.roll=0\r\n\r\n for name in L_first_quadrant_list:\r\n if name in mmd_bones_list:\r\n bone=mmd_arm.data.edit_bones[name]\r\n roll=bone.roll\r\n old_quadrant=quad(roll)\r\n if old_quadrant==4:\r\n roll+=math.pi/2\r\n elif old_quadrant==3:\r\n roll+=math.pi\r\n elif old_quadrant==2:\r\n roll-=math.pi/2\r\n bone.roll=roll\r\n for name in L_second_quadrant_bones_list:\r\n if name in mmd_bones_list:\r\n bone=mmd_arm.data.edit_bones[name]\r\n roll=bone.roll\r\n old_quadrant=quad(roll)\r\n if old_quadrant==4:\r\n roll+=math.pi\r\n elif old_quadrant==3:\r\n roll-=math.pi/2\r\n elif old_quadrant==1:\r\n roll+=math.pi/2\r\n bone.roll=roll\r\n for name in R_first_quadrant_bones_list:\r\n if name in mmd_bones_list:\r\n bone=mmd_arm.data.edit_bones[name]\r\n roll=bone.roll\r\n old_quadrant=quad(roll)\r\n if old_quadrant==3:\r\n roll+=math.pi/2\r\n elif old_quadrant==2:\r\n roll+=math.pi\r\n elif old_quadrant==1:\r\n roll-=math.pi/2\r\n bone.roll=roll\r\n for name in R_second_quadrant_bones_list:\r\n if name in mmd_bones_list:\r\n bone=mmd_arm.data.edit_bones[name]\r\n roll=bone.roll\r\n old_quadrant=quad(roll)\r\n if old_quadrant==1:\r\n roll+=math.pi\r\n elif old_quadrant==4:\r\n roll-=math.pi/2\r\n elif old_quadrant==2:\r\n roll+=math.pi/2\r\n bone.roll=roll\r\n\r\n for name in L_first_quadrant_list+L_second_quadrant_bones_list:\r\n if name in mmd_bones_list:\r\n R_name=name.replace(\"_L\",\"_R\")\r\n if R_name in mmd_bones_list:\r\n mmd_arm.data.edit_bones[R_name].roll=-mmd_arm.data.edit_bones[name].roll\r\n alert_error(\"提示\",\"轴向修正完成\")\r\n\r\n#load Stance Pose\r\ndef load_pose():\r\n my_dir = os.path.dirname(os.path.realpath(__file__))\r\n vpd_file = os.path.join(my_dir, \"MMR_Rig_pose.vpd\")\r\n print(my_dir)\r\n print(vpd_file)\r\n bpy.ops.mmd_tools.import_vpd(filepath=vpd_file, files=[{\"name\":\"MMR_Rig_pose.vpd\", \"name\":\"MMR_Rig_pose.vpd\"}], directory=my_dir)\r\n\r\ndef add_constraint_execute():\r\n\r\n length=len(constraints_from)\r\n bpy.ops.object.mode_set(mode = 'EDIT')\r\n for i in range(length):\r\n From = constraints_from[i]\r\n To = constraints_to[i]\r\n parent_name=From + '_parent'\r\n parent_bone=rig.data.edit_bones.new(name=parent_name)\r\n parent_bone.head=mmd_arm2.data.edit_bones[From].head\r\n parent_bone.tail=mmd_arm2.data.edit_bones[From].tail\r\n parent_bone.roll=mmd_arm2.data.edit_bones[From].roll\r\n parent_bone.parent=rig.data.edit_bones[To]\r\n\r\n bpy.ops.object.mode_set(mode = 'POSE')\r\n for i in range(length):\r\n From = constraints_from[i]\r\n To = constraints_to[i]\r\n con= mmd_arm.pose.bones[From].constraints\r\n for c in con:\r\n c.mute=True\r\n parent_name=From + '_parent'\r\n rig.data.bones[parent_name].hide=True\r\n COPY_TRANSFORMS=con.new(type='COPY_TRANSFORMS')\r\n COPY_TRANSFORMS.target = rig\r\n COPY_TRANSFORMS.subtarget = parent_name\r\n COPY_TRANSFORMS.name=\"rel_transforms\"\r\n COPY_TRANSFORMS.mix_mode = 'REPLACE'\r\n COPY_TRANSFORMS.owner_space = 'WORLD'\r\n COPY_TRANSFORMS.target_space = 'WORLD'\r\n\r\ndef add_constraint(To,From,rotation=True):\r\n\r\n if From in mmd_bones_list:\r\n if rotation:\r\n constraints_from.append(From)\r\n constraints_to.append(To)\r\n else:\r\n COPY_LOCATION=mmd_arm.pose.bones[From].constraints.new(type='COPY_LOCATION')\r\n COPY_LOCATION.target = rig\r\n COPY_LOCATION.subtarget = To\r\n COPY_LOCATION.name=\"rel_location\"\r\n mmd_arm.data.bones[From].hide=False\r\n\r\ndef RIG(context):\r\n\r\n\r\n global mmd_arm\r\n global mmd_arm2\r\n global mmd_bones_list\r\n global rig\r\n global constraints_from\r\n global constraints_to\r\n\r\n scene=context.scene\r\n mmr_property=scene.mmr_property\r\n\r\n my_dir = os.path.dirname(os.path.realpath(__file__))\r\n rigify_blend_file = os.path.join(my_dir, \"MMR_Rig.blend\")\r\n\r\n if check_arm()==False:\r\n return{False}\r\n\r\n #建立骨骼关系字典\r\n mmd_bones_dict_j={}\r\n mmd_bones_dict_e={}\r\n for bone in mmd_arm.pose.bones:\r\n bone.bone.hide=True\r\n if bone.mmd_bone.name_e not in mmd_bones_dict_e:\r\n mmd_bones_dict_e[bone.mmd_bone.name_e]=bone.name\r\n if bone.mmd_bone.name_j not in mmd_bones_dict_j:\r\n mmd_bones_dict_j[bone.mmd_bone.name_j]=bone.name\r\n\r\n load_pose()\r\n\r\n bpy.ops.object.mode_set(mode = 'OBJECT')\r\n mmd_arm2=mmd_arm.copy()\r\n context.collection.objects.link(mmd_arm2)\r\n mmd_arm2.data=mmd_arm.data.copy()\r\n bpy.ops.object.select_all(action='DESELECT')\r\n bpy.context.view_layer.objects.active=mmd_arm2\r\n bpy.ops.object.mode_set(mode = 'POSE')\r\n bpy.ops.pose.armature_apply(selected=False)\r\n bpy.ops.object.mode_set(mode = 'OBJECT')\r\n\r\n rigify_arm_name=\"MMR_Rig_relative\"\r\n\r\n #导入metarig骨骼\r\n #import metarig armature\r\n rigify_arm=None\r\n with bpy.data.libraries.load(rigify_blend_file) as (data_from, data_to):\r\n data_to.objects = [name for name in data_from.objects if rigify_arm_name == name]\r\n for obj in data_to.objects:\r\n context.collection.objects.link(obj)\r\n rigify_arm=obj\r\n\r\n rigify_bones_list=rigify_arm.data.bones.keys()\r\n exist_bones=list(set(mmd_bones_list).intersection(rigify_bones_list))\r\n\r\n\r\n \r\n\r\n bpy.ops.object.select_all(action='DESELECT')\r\n bpy.context.view_layer.objects.active=rigify_arm\r\n bpy.ops.object.mode_set(mode = 'EDIT')\r\n bpy.ops.armature.select_all(action='DESELECT')\r\n\r\n #修正只有两节拇指骨骼的模型\r\n if \"Thumb1_L\" in exist_bones:\r\n if mmd_arm.data.bones[\"Thumb1_L\"].parent.name !=\"Thumb0_L\":\r\n rigify_arm.data.edit_bones.remove(rigify_arm.data.edit_bones[\"Thumb2_L\"])\r\n '''rigify_arm.data.edit_bones[\"Thumb2_L\"].select=True\r\n bpy.ops.armature.delete()'''\r\n rigify_arm.data.edit_bones[\"Thumb1_L\"].name='Thumb2_L'\r\n rigify_arm.data.edit_bones[\"Thumb0_L\"].name='Thumb1_L'\r\n\r\n if \"Thumb1_R\" in exist_bones:\r\n if mmd_arm.data.bones[\"Thumb1_R\"].parent.name !=\"Thumb0_R\":\r\n rigify_arm.data.edit_bones.remove(rigify_arm.data.edit_bones[\"Thumb2_R\"])\r\n '''rigify_arm.data.edit_bones[\"Thumb2_R\"].select=True\r\n bpy.ops.armature.delete()'''\r\n rigify_arm.data.edit_bones[\"Thumb1_R\"].name='Thumb2_R'\r\n rigify_arm.data.edit_bones[\"Thumb0_R\"].name='Thumb1_R'\r\n\r\n rigify_bones_list=rigify_arm.data.edit_bones.keys()\r\n\r\n #调整约束以匹配骨骼\r\n bpy.ops.object.mode_set(mode = 'POSE')\r\n for name in rigify_bones_list:\r\n bone=rigify_arm.pose.bones[name]\r\n parent_bone=None\r\n parent_bone=bone.parent\r\n if parent_bone!=None:\r\n parent_bone.constraints['stretch'].target=mmd_arm2\r\n parent_bone.constraints['stretch'].subtarget=name\r\n parent_bone.constraints[\"stretch\"].rest_length = parent_bone.length\r\n if name in exist_bones:\r\n bone.constraints['location'].target=mmd_arm2\r\n bone.constraints['location'].subtarget=bone.name\r\n else:\r\n bone.constraints['location'].mute=True\r\n bone.constraints['stretch'].mute=True\r\n\r\n '''vector_list=[]\r\n scale_list=[]\r\n for bone in rigify_arm.data.edit_bones:\r\n vector=[bone.tail[0]-bone.head[0],bone.tail[1]-bone.head[1],bone.tail[2]-bone.head[2]]\r\n scale=1\r\n if bone.parent!=None:\r\n scale=bone.length/bone.parent.length\r\n vector_list.append(vector)\r\n scale_list.append(scale)\r\n\r\n for i in range(len(rigify_arm.data.edit_bones)):\r\n bone=rigify_arm.data.edit_bones[i]\r\n name=bone.name\r\n parent_bone=bone.parent\r\n mmd_bone=mmd_arm2.pose.bone[name]\r\n if name in exist_bones:\r\n bone.head=mmd_bone.head\r\n if len(bone.children)==0:\r\n vector=vector_list[i]\r\n bone.tail=[bone.head[0]+vector[0],bone.head[1]+vector[1],bone.head[2]+vector[2]]\r\n if parent_bone!=None:\r\n bone.length=parent_bone.length*scale_list[i]'''\r\n\r\n\r\n #spine.001,Neck_Middle是多余骨骼\r\n rigify_arm.pose.bones['spine.001'].constraints[\"location\"].mute=True\r\n rigify_arm.pose.bones['spine.001'].constraints[\"stretch\"].mute=True\r\n\r\n rigify_arm.pose.bones['Neck_Middle'].constraints[\"location\"].mute=True\r\n rigify_arm.pose.bones['Neck_Middle'].constraints[\"stretch\"].mute=True\r\n\r\n rigify_arm.pose.bones['Neck'].constraints['stretch'].subtarget='Head'\r\n\r\n rigify_arm.pose.bones['LowerBody'].constraints[\"stretch\"].subtarget='UpperBody'\r\n rigify_arm.pose.bones[\"LowerBody\"].constraints[\"location\"].head_tail = 1\r\n\r\n rigify_arm.pose.bones['UpperBody2'].constraints[\"stretch\"].subtarget='UpperBody2'\r\n rigify_arm.pose.bones[\"UpperBody2\"].constraints[\"stretch\"].head_tail = 1\r\n\r\n rigify_arm.pose.bones['Ankle_L'].constraints[\"stretch\"].subtarget='ToeTipIK_L'\r\n\r\n rigify_arm.pose.bones['Ankle_R'].constraints[\"stretch\"].subtarget='ToeTipIK_R'\r\n \r\n rigify_arm.pose.bones['Head'].constraints['location'].target=mmd_arm\r\n rigify_arm.pose.bones['Head'].constraints['location'].subtarget='Head'\r\n scale=mmd_arm.data.bones['Head'].length/rigify_arm.data.bones['Head'].length\r\n rigify_arm.pose.bones['Head'].scale=[scale,scale,scale]\r\n rigify_arm.pose.bones['Head'].constraints['stretch'].target=mmd_arm\r\n rigify_arm.pose.bones['Head'].constraints['stretch'].subtarget='Head'\r\n rigify_arm.pose.bones['Head'].constraints[\"stretch\"].head_tail = 1\r\n #rigify_arm.pose.bones['Head'].constraints[\"stretch\"].rest_length = rigify_arm.data.bones['Head'].length\r\n\r\n rigify_arm.pose.bones['Wrist_L'].constraints[\"stretch\"].mute=True\r\n rigify_arm.pose.bones['Wrist_R'].constraints[\"stretch\"].mute=True\r\n\r\n rigify_arm.pose.bones['ToeTipIK_L'].constraints[\"stretch\"].mute=True\r\n rigify_arm.pose.bones['ToeTipIK_R'].constraints[\"stretch\"].mute=True\r\n\r\n #调整缺失UpperBody2情况\r\n no_UpperBody2=False\r\n if 'UpperBody2' not in exist_bones and 'UpperBody' in exist_bones:\r\n no_UpperBody2=True\r\n rigify_arm.pose.bones['UpperBody'].scale[0] = 0.0001\r\n rigify_arm.pose.bones['UpperBody'].scale[1] = 0.0001\r\n rigify_arm.pose.bones['UpperBody'].scale[2] = 0.0001\r\n rigify_arm.pose.bones['UpperBody'].constraints['location'].mute=True\r\n rigify_arm.pose.bones['UpperBody'].constraints['stretch'].mute=True\r\n rigify_arm.pose.bones['UpperBody2'].constraints['location'].subtarget='UpperBody'\r\n rigify_arm.pose.bones['UpperBody2'].constraints['stretch'].subtarget='UpperBody'\r\n rigify_arm.pose.bones['UpperBody2'].constraints['location'].mute=False\r\n rigify_arm.pose.bones['UpperBody2'].constraints['stretch'].mute=False\r\n\r\n bpy.ops.pose.armature_apply(selected=False)\r\n bpy.ops.pose.select_all(action='SELECT')\r\n bpy.ops.pose.constraints_clear()\r\n\r\n bpy.ops.object.mode_set(mode = 'OBJECT')\r\n mmd_arm2.select=True\r\n bpy.ops.object.mode_set(mode = 'EDIT')\r\n\r\n #修正末端骨骼长度\r\n rigify_arm.data.edit_bones[\"Thumb2_L\"].length=rigify_arm.data.edit_bones[\"Thumb1_L\"].length\r\n rigify_arm.data.edit_bones[\"Thumb2_R\"].length=rigify_arm.data.edit_bones[\"Thumb1_R\"].length\r\n rigify_arm.data.edit_bones[\"IndexFinger3_L\"].length=rigify_arm.data.edit_bones[\"IndexFinger2_L\"].length\r\n rigify_arm.data.edit_bones[\"IndexFinger3_R\"].length=rigify_arm.data.edit_bones[\"IndexFinger2_R\"].length\r\n rigify_arm.data.edit_bones[\"MiddleFinger3_L\"].length=rigify_arm.data.edit_bones[\"MiddleFinger2_L\"].length\r\n rigify_arm.data.edit_bones[\"MiddleFinger3_R\"].length=rigify_arm.data.edit_bones[\"MiddleFinger2_R\"].length\r\n rigify_arm.data.edit_bones[\"RingFinger3_L\"].length=rigify_arm.data.edit_bones[\"RingFinger2_L\"].length\r\n rigify_arm.data.edit_bones[\"RingFinger3_R\"].length=rigify_arm.data.edit_bones[\"RingFinger2_R\"].length\r\n rigify_arm.data.edit_bones[\"LittleFinger3_L\"].length=rigify_arm.data.edit_bones[\"LittleFinger2_L\"].length\r\n rigify_arm.data.edit_bones[\"LittleFinger3_R\"].length=rigify_arm.data.edit_bones[\"LittleFinger2_R\"].length\r\n rigify_arm.data.edit_bones[\"ToeTipIK_L\"].length=rigify_arm.data.edit_bones[\"Ankle_L\"].length/2\r\n rigify_arm.data.edit_bones[\"ToeTipIK_R\"].length=rigify_arm.data.edit_bones[\"Ankle_R\"].length/2\r\n rigify_arm.data.edit_bones[\"Wrist_L\"].length=rigify_arm.data.edit_bones[\"Elbow_L\"].length/4\r\n rigify_arm.data.edit_bones[\"Wrist_R\"].length=rigify_arm.data.edit_bones[\"Elbow_R\"].length/4\r\n\r\n #匹配眼睛骨骼\r\n if 'Eye_L' in mmd_bones_list and 'Eye_R' in mmd_bones_list:\r\n eye_L=rigify_arm.data.edit_bones['eye.L']\r\n mmd_eye_L=mmd_arm2.data.edit_bones['Eye_L']\r\n eye_L.head[2]=mmd_eye_L.head[2]\r\n eye_L.head[0]=max(mmd_eye_L.head[0],mmd_eye_L.tail[0])\r\n eye_L.head[1]=min(mmd_eye_L.head[1],mmd_eye_L.tail[1])\r\n eye_L.tail=eye_L.head\r\n eye_L.tail[1]-=0.1\r\n\r\n eye_R=rigify_arm.data.edit_bones['eye.R']\r\n mmd_eye_R=mmd_arm2.data.edit_bones['Eye_R']\r\n eye_R.head[2]=mmd_eye_R.head[2]\r\n eye_R.head[0]=min(mmd_eye_R.head[0],mmd_eye_R.tail[0])\r\n eye_R.head[1]=min(mmd_eye_R.head[1],mmd_eye_R.tail[1])\r\n eye_R.tail=eye_R.head\r\n eye_R.tail[1]-=0.1\r\n\r\n invert_eyes=False\r\n if eye_L.head[0]4:\r\n bm.faces.remove(f)'''\r\n #删除多余边\r\n #remove extra edge\r\n for e in bm.edges:\r\n true_edge=False\r\n for i in edge_index:\r\n if e.verts[0].index in i and e.verts[1].index in i:\r\n true_edge=True\r\n break\r\n if true_edge==False:\r\n bm.edges.remove(e)\r\n bm.faces.ensure_lookup_table()\r\n\r\n #尝试标记出头发,飘带\r\n #try mark hair or ribbon vertex\r\n\r\n '''bm.to_mesh(mesh)\r\n bpy.ops.object.mode_set(mode = 'EDIT')\r\n bpy.ops.mesh.select_all(action='DESELECT')\r\n bpy.ops.mesh.select_mode(type='EDGE')\r\n bpy.ops.mesh.select_non_manifold(extend=False, use_wire=True, use_boundary=False, use_multi_face=False, use_non_contiguous=False, use_verts=False)\r\n bpy.ops.mesh.select_linked(delimit=set())\r\n bpy.ops.object.mode_set(mode = 'OBJECT')\r\n bm.clear()\r\n bm.from_mesh(mesh)'''\r\n\r\n ribbon_verts=[v for v in bm.verts if v.is_wire]\r\n if mmr_property.extend_ribbon:\r\n boundary_verts=set(ribbon_verts)\r\n boundary_verts2=[]\r\n while len(boundary_verts) != 0:\r\n boundary_verts2.clear()\r\n for v in boundary_verts:\r\n for e in v.link_edges:\r\n for v2 in e.verts:\r\n if v2 not in ribbon_verts:\r\n ribbon_verts.append(v2)\r\n boundary_verts2.append(v2)\r\n boundary_verts=set(boundary_verts2)\r\n boundary_verts2.clear()\r\n\r\n all_ribbon=True\r\n for f in bm.faces:\r\n ribbon_face=False\r\n for v in f.verts:\r\n if v in ribbon_verts:\r\n ribbon_face=True\r\n if ribbon_face==False:\r\n all_ribbon=False\r\n\r\n #标记出特殊边和点\r\n #These are special edge and vertex\r\n\r\n up_edges=[]\r\n down_edges=[]\r\n side_edges=[]\r\n up_verts=[]\r\n down_verts=[]\r\n side_verts=[]\r\n\r\n #标出头部,尾部,飘带顶点\r\n #try mark head,tail,ribbon vertex\r\n bm.verts.ensure_lookup_table()\r\n bm.edges.ensure_lookup_table()\r\n for i in range(len(bm.verts)):\r\n v=bm.verts[i]\r\n bone=bones_list[i]\r\n if bone.bone.use_connect==False and v.is_boundary:\r\n up_verts.append(v)\r\n elif bone.parent not in bones_list:\r\n up_verts.append(v)\r\n elif len(bone.children)==0:\r\n down_verts.append(v)\r\n elif bone.children[0] not in bones_list:\r\n down_verts.append(v)\r\n if v in ribbon_verts and mmr_property.cloth_convert_mod==1 or mmr_property.cloth_convert_mod==2:\r\n v.co=bone.tail\r\n\r\n #标出头部,尾部,飘带边\r\n #try mark head,tail,ribbon edge\r\n for i in range(len(bm.edges)):\r\n e=bm.edges[i]\r\n vert1=e.verts[0]\r\n vert2=e.verts[1]\r\n if e.is_boundary:\r\n if vert1 in up_verts and vert2 in up_verts:\r\n up_edges.append(e)\r\n elif vert1 in down_verts and vert2 in down_verts:\r\n down_edges.append(e)\r\n else:\r\n side_edges.append(e)\r\n if e.verts[0] not in side_verts:\r\n side_verts.append(e.verts[0])\r\n if e.verts[1] not in side_verts:\r\n side_verts.append(e.verts[1])\r\n\r\n #延长头部顶点 \r\n #extend root vertex\r\n new_up_verts=[None for i in range(len(bm.verts))]\r\n new_down_verts=[None for i in range(len(bm.verts))]\r\n for v in up_verts:\r\n new_location=bones_list[v.index].head\r\n if mmr_property.cloth_convert_mod==1 and v not in ribbon_verts or mmr_property.cloth_convert_mod==3:\r\n for e in v.link_edges:\r\n if e not in up_edges:\r\n if e.verts[0]==v:\r\n new_location=v.co*2-e.verts[1].co\r\n else:\r\n new_location=v.co*2-e.verts[0].co\r\n break\r\n new_vert=bm.verts.new(new_location,v)\r\n new_edge=bm.edges.new([v,new_vert])\r\n\r\n deform_layer = bm.verts.layers.deform.active\r\n if deform_layer != None:\r\n deform_vert = v[deform_layer]\r\n for i in skin_vertex_groups_index:\r\n if i in deform_vert:\r\n deform_vert[i]=0\r\n\r\n new_up_verts[v.index]=new_vert\r\n if v in side_verts:\r\n side_verts.append(new_vert)\r\n side_edges.append(new_edge)\r\n\r\n #延长尾部顶点\r\n #extend tail vertex\r\n for v in down_verts:\r\n if v not in up_verts:\r\n new_location=[0,0,0]\r\n for e in v.link_edges:\r\n if e not in down_edges:\r\n if e.verts[0]==v:\r\n new_location=v.co*2-e.verts[1].co\r\n else:\r\n new_location=v.co*2-e.verts[0].co\r\n break\r\n new_vert=bm.verts.new(new_location,v)\r\n new_edge=bm.edges.new([v,new_vert])\r\n new_down_verts[v.index]=new_vert\r\n if v in side_verts:\r\n side_verts.append(new_vert)\r\n side_edges.append(new_edge)\r\n\r\n for e in up_edges:\r\n vert1=e.verts[0]\r\n vert2=e.verts[1]\r\n vert3=new_up_verts[vert2.index]\r\n vert4=new_up_verts[vert1.index]\r\n if vert3 != None and vert4 != None:\r\n bm.faces.new([vert1,vert2,vert3,vert4])\r\n\r\n\r\n for e in down_edges:\r\n vert1=e.verts[0]\r\n vert2=e.verts[1]\r\n vert3=new_down_verts[vert2.index]\r\n vert4=new_down_verts[vert1.index]\r\n if vert3 != None and vert4 != None:\r\n bm.faces.new([vert1,vert2,vert3,vert4])\r\n \r\n #延长侧边顶点\r\n #extend side vertex\r\n bm.verts.index_update( ) \r\n bm.faces.ensure_lookup_table()\r\n new_side_verts=[None for i in range(len(bm.verts))]\r\n for v in side_verts:\r\n for e in v.link_edges:\r\n if e not in side_edges:\r\n if e.verts[0]==v:\r\n new_location=v.co*2-e.verts[1].co\r\n else:\r\n new_location=v.co*2-e.verts[0].co\r\n break\r\n new_vert=bm.verts.new(new_location,v)\r\n new_side_verts[v.index]=new_vert\r\n\r\n for e in side_edges:\r\n vert1=e.verts[0]\r\n vert2=e.verts[1]\r\n vert3=new_side_verts[vert2.index]\r\n vert4=new_side_verts[vert1.index]\r\n if vert3 != None and vert4 != None:\r\n bm.faces.new([vert1,vert2,vert3,vert4])\r\n\r\n bm.verts.ensure_lookup_table()\r\n bmesh.ops.recalc_face_normals(bm,faces=bm.faces)\r\n bm.normal_update()\r\n\r\n #挤出飘带顶点\r\n #extrude ribbon edge\r\n new_extrude_verts=[None for i in range(len(bm.verts))]\r\n for v in bm.verts[:]:\r\n if v.is_wire:\r\n new_location=[v.co[0],v.co[1]+0.01,v.co[2]]\r\n new_vert=bm.verts.new(new_location,v)\r\n new_extrude_verts[v.index]=new_vert\r\n else:\r\n v.co[0]-=v.normal[0]*mean_radius\r\n v.co[1]-=v.normal[1]*mean_radius\r\n v.co[2]-=v.normal[2]*mean_radius\r\n\r\n bm.verts.ensure_lookup_table()\r\n bm.edges.ensure_lookup_table()\r\n for e in bm.edges[:]:\r\n if e.is_wire:\r\n vert1=e.verts[0]\r\n vert2=e.verts[1]\r\n vert3=new_extrude_verts[vert2.index]\r\n vert4=new_extrude_verts[vert1.index]\r\n if vert3 != None and vert4 != None:\r\n bm.faces.new([vert1,vert2,vert3,vert4])\r\n\r\n #删除孤立顶点\r\n #remove single vertex\r\n bm.verts.ensure_lookup_table()\r\n bm.edges.ensure_lookup_table()\r\n\r\n '''for v in bm.verts[:]:\r\n if len(v.link_edges)==0:\r\n bm.verts.remove(v)\r\n\r\n bm.verts.ensure_lookup_table()'''\r\n bm.to_mesh(mesh)\r\n\r\n bpy.ops.object.mode_set(mode = 'EDIT')\r\n bpy.ops.mesh.select_all(action='SELECT')\r\n bpy.ops.mesh.normals_make_consistent(inside=False)\r\n bpy.ops.object.mode_set(mode = 'OBJECT')\r\n\r\n for obj in joints:\r\n bpy.data.objects.remove(obj)\r\n for obj in side_joints:\r\n bpy.data.objects.remove(obj)\r\n\r\n deform_vertex_group=mmd_mesh_object.vertex_groups.new(name='mmd_cloth_deform')\r\n\r\n cloth_obj.display_type = 'WIRE'\r\n\r\n mod=cloth_obj.modifiers.new('mmd_cloth_subsurface','SUBSURF')\r\n mod.levels = mmr_property.subdivide\r\n mod.render_levels = mmr_property.subdivide\r\n mod.boundary_smooth = 'PRESERVE_CORNERS'\r\n mod.show_only_control_edges = False\r\n\r\n\r\n mod=cloth_obj.modifiers.new('mmd_cloth_skin','ARMATURE')\r\n mod.object = mmd_arm\r\n mod.vertex_group = \"mmd_cloth_pin\"\r\n\r\n mod=cloth_obj.modifiers.new('mmd_cloth','CLOTH')\r\n mod.settings.vertex_group_mass = \"mmd_cloth_pin\"\r\n\r\n mod=cloth_obj.modifiers.new('mmd_cloth_smooth','CORRECTIVE_SMOOTH')\r\n mod.smooth_type = 'LENGTH_WEIGHTED'\r\n mod.rest_source = 'BIND'\r\n bpy.ops.object.correctivesmooth_bind(modifier=\"mmd_cloth_smooth\")\r\n if mmr_property.subdivide==0:\r\n mod.show_viewport = False\r\n\r\n bpy.context.view_layer.objects.active=mmd_mesh_object\r\n\r\n #写入形变权重或骨骼约束\r\n #Add weight or constrain\r\n #准备阶段\r\n # preparation\r\n unnecessary_vertex_groups: type.List[bpy.types.VertexGroup] = []\r\n mmd_mesh: bpy.types.Mesh = mmd_mesh_object.data\r\n mmd_bm: bmesh.types.BMesh = bmesh.new()\r\n mmd_bm.from_mesh(mmd_mesh)\r\n\r\n mmd_bm.verts.layers.deform.verify()\r\n deform_layer = mmd_bm.verts.layers.deform.active\r\n\r\n for i in range(rigid_bodys_count):\r\n v=bm.verts[i]\r\n obj=rigid_bodys[i]\r\n bone=bones_list[i]\r\n name=bone.name\r\n if v in ribbon_verts and mmr_property.cloth_convert_mod==1 or mmr_property.cloth_convert_mod==2 :\r\n line_vertex_group=cloth_obj.vertex_groups.new(name=name)\r\n line_vertex_group.add([i],1,'REPLACE')\r\n for c in bone.constraints:\r\n bone.constraints.remove(c)\r\n con=bone.constraints.new(type='STRETCH_TO')\r\n con.target = cloth_obj\r\n con.subtarget = name\r\n con.rest_length = bone.length\r\n else:\r\n from_vertex_group = mmd_mesh_object.vertex_groups[name]\r\n from_index = from_vertex_group.index\r\n unnecessary_vertex_groups.append(from_vertex_group)\r\n\r\n vert: bmesh.types.BMVert\r\n for vert in mmd_bm.verts:\r\n deform_vert: bmesh.types.BMDeformVert = vert[deform_layer]\r\n if from_index not in deform_vert:\r\n continue\r\n\r\n to_index = deform_vertex_group.index\r\n deform_vert[to_index] = deform_vert.get(to_index, 0.0) + deform_vert[from_index]\r\n \r\n bpy.data.objects.remove(obj)\r\n\r\n mmd_bm.to_mesh(mmd_mesh)\r\n mmd_bm.free()\r\n for vertex_group in unnecessary_vertex_groups:\r\n mmd_mesh_object.vertex_groups.remove(vertex_group)\r\n\r\n if all_ribbon == False and mmr_property.cloth_convert_mod!=2:\r\n bpy.context.view_layer.objects.active=mmd_mesh_object\r\n mod=mmd_mesh_object.modifiers.new('mmd_cloth_deform','SURFACE_DEFORM')\r\n mod.target = cloth_obj\r\n mod.vertex_group = deform_vertex_group.name\r\n bpy.ops.object.surfacedeform_bind(modifier=mod.name)\r\n\r\n bm.free()\r\n\r\ndef export_vmd(context,vmd_path,rigify_arm,scale,use_pose_mode,set_action_range,start_frame,end_frame):\r\n PMX_list=[\r\n '全ての親','センター','下半身','上半身','上半身2','首','頭','両目','左目','右目',\r\n '左足','左足IK','左つま先IK','右足','右足IK','右つま先IK',\r\n '左肩','左腕','左ひじ','左手首','右肩','右腕','右ひじ','右手首',\r\n '左親指0','左親指1','左親指2',\r\n '左人指1','左人指2','左人指3',\r\n '左中指1','左中指2','左中指3',\r\n '左薬指1','左薬指2','左薬指3',\r\n '左小指1','左小指2','左小指3',\r\n '右親指0','右親指1','右親指2',\r\n '右人指1','右人指2','右人指3',\r\n '右中指1','右中指2','右中指3',\r\n '右薬指1','右薬指2','右薬指3',\r\n '右小指1','右小指2','右小指3'\r\n ]\r\n\r\n if rigify_arm.type!='ARMATURE':\r\n return(False)\r\n if vmd_path==None:\r\n return(False)\r\n\r\n bpy.ops.object.mode_set(mode = 'OBJECT')\r\n bpy.ops.object.select_all(action='DESELECT')\r\n #复制骨骼\r\n #duplicate armature\r\n mmd_arm=None\r\n for obj in rigify_arm.children[0].children:\r\n if obj.type=='ARMATURE':\r\n mmd_arm=obj\r\n break\r\n if mmd_arm==None:\r\n return(False)\r\n\r\n mmd_arm2=mmd_arm.copy()\r\n context.collection.objects.link(mmd_arm2)\r\n bpy.ops.object.select_all(action='DESELECT')\r\n bpy.context.view_layer.objects.active=mmd_arm2\r\n mmd_arm2.select=True\r\n print(vmd_path)\r\n\r\n if set_action_range:\r\n start_frame1=start_frame\r\n end_frame1=end_frame\r\n else:\r\n rigify_action=rigify_arm.animation_data.action\r\n if rigify_action ==None:\r\n return(False)\r\n start_frame1=rigify_action.frame_range[0]\r\n end_frame1=rigify_action.frame_range[1]\r\n\r\n bpy.ops.object.mode_set(mode = 'POSE')\r\n bpy.ops.pose.select_all(action='SELECT')\r\n\r\n for bone in mmd_arm2.pose.bones:\r\n if bone.mmd_bone.name_j in PMX_list:\r\n bone.bone.select=True\r\n else:\r\n bone.bone.select=False\r\n\r\n bpy.ops.nla.bake(frame_start=start_frame1, frame_end=end_frame1, only_selected=True, visual_keying=True,clear_constraints=True, bake_types={'POSE'})\r\n bpy.ops.object.mode_set(mode = 'OBJECT')\r\n bpy.ops.mmd_tools.export_vmd(filepath=vmd_path,scale=scale, use_pose_mode=use_pose_mode,use_frame_range=False)\r\n bpy.data.objects.remove(mmd_arm2)\r\n\r\n return(True)","sub_path":"MikuMikuRig/MMR_Core.py","file_name":"MMR_Core.py","file_ext":"py","file_size_in_byte":75962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"131480352","text":"import logging\n\nfrom django.utils.translation import ugettext as _\nfrom django.utils.translation import ugettext_lazy as lazy_\n\n# Choices for POLLER_PING_INTERVAL and POLLER_SNMP_INTERVAL settings\npoller_interval_choices = (\n (1, '1 ' + _('minute')),\n (2, '2 ' + _('minutes')),\n (3, '3 ' + _('minutes')),\n (4, '4 ' + _('minutes')),\n (5, '5 ' + _('minutes')),\n (10, '10 ' + _('minutes')),\n (20, '20 ' + _('minutes')),\n (30, '30 ' + _('minutes')),\n)\n\n# Choices for SNMP_TIMEOUT setting\nsnmp_timeout_choices = (\n (500, '0.5 ' + _('second')),\n (1000, '1.0 ' + _('second')),\n (1500, '1.5 ' + _('seconds')),\n (2000, '2.0 ' + _('seconds')),\n (3000, '3.0 ' + _('seconds')),\n (4000, '4.0 ' + _('seconds')),\n)\n\n# Choices for SNMP_RETRIES setting\nsnmp_retries_choices = (\n (0, '0 ' + _('times')),\n (1, '1 ' + _('time')),\n (2, '2 ' + _('times')),\n (3, '3 ' + _('times')),\n (4, '4 ' + _('times')),\n (5, '5 ' + _('times')),\n)\n\n# DB Log Handler log levels\nlog_level_choices = (\n (logging.INFO, lazy_('Information')),\n (logging.WARNING, lazy_('Warning')),\n (logging.ERROR, lazy_('Error')),\n (logging.FATAL, lazy_('Fatal')),\n (logging.DEBUG, lazy_('Debug')),\n)","sub_path":"sentinel/system/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"572320749","text":"\nfrom trajectory.messages import AxisConfig, OutVal, OutMode\nfrom trajectory.proto import SyncProto\n\n\ndef rpm_to_usps(rpm, usteps, steps_per_rotation=200):\n \"\"\"Return the number of microsteps per second at full velocity\"\"\"\n rps = rpm / 60 # rotations per second\n fsps = rps * steps_per_rotation # Full steps per second\n usps = fsps * usteps\n return usps\n\n\ndef make_axes(rpm, accel, usteps=1, steps_per_rotation=200,\n output_mode=OutMode.OUTPUT, highval=OutVal.HIGH):\n \"rpm is target RPM. acell is, I think, the time in sec to reach full velocity. \"\n s = rpm_to_usps(rpm, usteps)\n\n mx = ( highval, output_mode, s, s / accel) # Max Velocity , Max Acceleration\n\n _axes = {\n 'x': (18, 19, 20, *mx), # X Waist, Axis 0\n 'y': (21, 22, 23, *mx), # Y Shoulder 1, Axis 1\n 'z': (5, 6, 7, *mx), # Z Shoulder 2, Axis 2\n 'a': (15, 16, 17, *mx), # A Elbow, Axis 3\n 'b': (8, 9, 10, *mx), # B Wrist 1, Axis 4\n 'c': (2, 3, 4, *mx), # C Wrist 2, Axis 5\n }\n\n\n return {\n \"axes1\": [AxisConfig(0, *_axes['a'])],\n \"axesb\": [AxisConfig(0, *_axes['b'])],\n \"axesz\": [AxisConfig(0, *_axes['z'])],\n \"axes2\": [AxisConfig(0, *_axes['a']), AxisConfig(1, *_axes['z'])],\n \"axes3\": [AxisConfig(0, *_axes['a']), AxisConfig(1, *_axes['z']), AxisConfig(2, *_axes['b'])],\n \"axes6\": [AxisConfig(i, *e) for i, e in enumerate(_axes.values())],\n \"x_1sec\": rpm_to_usps(rpm, usteps),\n \"mspr\": usteps * steps_per_rotation, # microsteps per rotation\n \"axes\": _axes\n }\n\nimport unittest\n\nclass TestStepper(unittest.TestCase):\n # Determines wether the steppers are enables with an output value of high or low\n # Different for different stepper drivers\n ENABLE_OUTPUT = False\n\n def setUp(self) -> None:\n pass\n\n def tearDown(self) -> None:\n pass\n\n def init(self, packet_port, encoder_port, v=800, axes_name='axes1', usteps=16, a=.1,\n highvalue=OutVal.HIGH, outmode=OutMode.OUTPUT_OPENDRAIN,\n segment_pin=27, limit_pint=29, period=4,\n use_encoder=True):\n\n d = make_axes(v, a, usteps=usteps, steps_per_rotation=200,\n highval=highvalue, output_mode=outmode)\n\n p = SyncProto(packet_port, encoder_port if use_encoder else None)\n p.encoder_multipliers[0] = 1 + (1 / 3)\n\n p.config(period, segment_pin, limit_pint, False, False, axes=d[axes_name]);\n\n p.mspr = d['mspr']\n p.x_1sec = d['x_1sec']\n\n return p\n","sub_path":"trajectory/trajectory/test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"56631483","text":"__author__ = 'gambler'\nclass Solution:\n def solve(self):\n N = ar[0]\n J = ar[1]\n divline = \" 3 4 5 6 7 8 9 10 11\\n\"\n di = dict()\n if N==16:\n even = [2,4,6,8,10,12,14]\n odd = [1,3,5,7,9,11,13]\n for e in even:\n for o in odd:\n ans = list('1' + 14*'0' + '1')\n ans[e] = '1'\n ans[o] = '1'\n val = \"\".join(ans)\n di[val] = 1\n fout.write(val + divline)\n fout.write(\"1000000000000001\"+divline)\n else:\n even = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30]#,32,34,36,38,40,42,44,46,48]\n odd = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29]#,31,33,35,37,39,41,43,45,47,49]\n for e1 in even:\n for o1 in odd:\n for e2 in even:\n for o2 in odd:\n ans = list('1' + 30*'0' + '1')\n ans[e1] = '1'\n ans[o1] = '1'\n ans[e2] = '1'\n ans[o2] = '1'\n val = \"\".join(ans)\n di[val] = 1\n fout.write(val + divline)\n if len(di)==499:\n break\n if len(di)==499:\n break\n if len(di)==499:\n break\n if len(di)==499:\n break\n fout.write(\"10000000000000000000000000000001\"+divline)\n #print len(di)\n\n\n\n#fin = open(\"/Users/gambler/Documents/pycharm/input.txt\", \"r\")\nfin = open(\"/Users/gambler/Documents/pycharm/C-small-attempt0.in\", \"r\")\nfout = open(\"/Users/gambler/Documents/pycharm/output.txt\", \"w\")\ncases = int(fin.readline().strip())\ns = Solution()\nfor case in range(cases):\n ar = map(int, fin.readline().strip().split())\n fout.write(\"Case #\"+str(case+1)+\":\\n\")\n s.solve()\n\nfin.close()\nfout.close()\n","sub_path":"codes/CodeJamCrawler/16_0_3/theGamblerRises/CoinJam.py","file_name":"CoinJam.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"222042965","text":"import requests\nimport bs4\n\n\ndef extraccionDatos(url):\n contenido = \"\"\n page = requests.get(url).text\n soup = bs4.BeautifulSoup(page, 'html.parser')\n titulo = str(soup.h1.string)\n contenido = contenido + titulo + \" \"\n try:\n subtitulo = str(soup.find(id=\"article-summary\").string)\n contenido = contenido + subtitulo + \" \"\n listaTexto = soup.find(itemprop=\"articleBody\").contents\n for i in range(0, len(listaTexto)):\n contenido += listaTexto[i].text\n except:\n next\n return contenido\n","sub_path":"ExtraccionTexto.py","file_name":"ExtraccionTexto.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"490337777","text":"from django.contrib.auth.decorators import login_required\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import render\nfrom plotly.offline import plot\nfrom plotly import graph_objects as graphs\n\nfrom .utils import get_books_reviewed_by_month, get_xlsx_data_list_of_books_reviewed\n\n\n@login_required\ndef profile(request):\n user = request.user\n permissions = user.get_all_permissions()\n # Get the books reviewed in different months this year\n books_by_month = get_books_reviewed_by_month(user.username)\n # Initialize the Axis for graphs, X-Axis is months, Y-axis is books read.\n # Since `books_by_month` only contain months that actually have values,\n # we initialize all `books_read` for every month to 0.\n months = [i + 1 for i in range(12)]\n books_read = [0 for _ in range(12)]\n # Set the value for books read per month on Y-Axis\n for num_books_read in books_by_month:\n list_index = num_books_read['date_created__month'] - 1\n books_read[list_index] = num_books_read['book_count']\n\n # Generate a scatter plot HTML\n figure = graphs.Figure()\n scatter = graphs.Scatter(x=months, y=books_read)\n figure.add_trace(scatter)\n figure.update_layout(xaxis_title=\"Month\", yaxis_title=\"No. of books read\")\n plot_html = plot(figure, output_type='div')\n\n return render(\n request,\n 'profile.html',\n {'user': user, 'permissions': permissions, 'books_read_plot': plot_html},\n )\n\n\n@login_required\ndef download_user_book_data(request):\n xlsx_data = get_xlsx_data_list_of_books_reviewed(request.user.username)\n response = HttpResponse(content_type='application/vnd.ms-excel')\n response['Content-Disposition'] = 'attachment; filename=books_reviewed.xlsx'\n response.write(xlsx_data)\n return response\n","sub_path":"bookr/bookr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"570194951","text":"def get_breadcrumb(category):\n \"\"\"\n 获取面包屑导航\n :param category: 商品类别\n :return: 面包屑导航字典\n \"\"\"\n breadcrumb = dict(\n cat1='',\n cat2='',\n cat3=''\n )\n\n # 当前类别为三级\n breadcrumb['cat3'] = category.name\n breadcrumb['cat2'] = category.parent.name\n breadcrumb['cat1'] = category.parent.parent.name\n\n return breadcrumb","sub_path":"meiduo_mall/apps/goods/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"46429886","text":"import math\n\nimport numpy as np\nimport gym\nfrom gym import wrappers\n\nimport environments\nfrom agents.dqn.dqn import *\n\n# for debug\nfrom gym import logger\n# logger.set_level(10)\n\n\nTIME_STEP = 0.005\n\ndef main():\n env = gym.make('LidarBat-v0')\n # env = gym.make('CartPole-v0')\n # env = gym.make('Pendulum-v0')\n # env = gym.make('BipedalWalker-v2')\n env = wrappers.Monitor(env, 'data/env_test_videos', force=True)\n for i_episode in range(5):\n observation = env.reset()\n for t in range(1000):\n print(f'----step {t}----')\n # print(f'bat angle: {env.bat.angle *180 / math.pi:2f} [degree]')\n print('observation:')\n print(observation)\n action = env.action_space.sample()\n action[0] = 0\n # action[1] = math.pi/2\n # action[2] = 0.9\n # action[3] = 0\n print(f'action: {action}')\n observation, reward, done, info = env.step(action)\n print(f'reward: {reward}')\n print(f'done: {done}')\n # print(f'time: {env.t:2f} [sec]')\n if done:\n print(f\"Episode finished after {t+1} timesteps\")\n break\n env.reset()\n env.close()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"628521381","text":"import requests\nfrom random import choice\nimport pyfiglet\n\nheader = pyfiglet.figlet_format('DAD JOKE !!')\nurl = 'https://icanhazdadjoke.com/search'\n\ndef game(header, url):\n\tprint(header)\n\n\tuser_input = input('What would you like to search for ? Enter (quit) to quit the game! ')\n\n\tres = requests.get(\n\t\turl, \n\t\theaders= {'accept': 'application/json'},\n\t\tparams = {'term': user_input}\n\t\t).json()\n\n\tnum_jokes = res['total_jokes']\n\tresults = res['results']\n\t\n\n\twhile user_input != 'quit':\n\n\t\tif num_jokes > 1:\n\t\t\tprint (f\"I found {num_jokes} jokes about {user_input}. Here's one: \")\n\t\t\tprint (choice(results)['joke'])\n\t\telif num_jokes == 1:\n\t\t\tprint(f\"I found One joke about {user_input}. \")\n\t\t\tprint (results[0][\"joke\"])\n\t\telse:\n\t\t\tprint( \"Sorry I couldn't find a joke with your term\")\n\n\t\tuser_input = input('What would you like to search for ? Enter (quit) to quit the game! ')\n\n\n\nif __name__ == '__main__':\n\tgame(header, url)\n","sub_path":"jokes.py","file_name":"jokes.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"492428304","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[153]:\n\n\nimport numpy as np\nimport random\nimport math\nimport sys\nimport collections\nfrom numpy.random import seed\nseed(1)\nif len(sys.argv) != 5:\n sys.exit() \nX = np.genfromtxt(sys.argv[1],delimiter=\",\")\n\n\n# In[154]:\n\n\nm = X.shape[0]\n\n\n# In[155]:\n\n\nprev_labels = np.zeros(m)\n\n\n# In[156]:\n\n\nk = int(sys.argv[2])\nr = int(sys.argv[3])\niterations = 0\n\n\n# In[157]:\n\n\nOverall_Q = sys.maxsize\nwhile(iterations < r):\n Centroids = {}\n counter = 1\n Centroids[counter] = X[random.randint(1, m)]\n \n #Compute the Centroids\n while(counter < k):\n Max_Dist = -sys.maxsize - 1 \n for i in range(m):\n val_dist = 0\n Sum_dist = 0\n for key in Centroids:\n val = X[i] - Centroids.get(key)\n val_dist = np.sum(val**2)\n Sum_dist = Sum_dist + val_dist\n if(Sum_dist >= Max_Dist):\n Max_Dist = Sum_dist\n Coordinates = X[i] \n counter = counter + 1\n Centroids[counter] = Coordinates \n \n #Running the iterations for Convergence\n while True: \n #Assign the labels based on distance to each centroids \n Labels = np.zeros(m)\n for i in range(m):\n Min_Distance = sys.maxsize\n for c in range(1,len(Centroids.keys())+1):\n temp = X[i] - Centroids.get(c)\n temp_dist = np.sum(temp**2)\n if (temp_dist <= Min_Distance):\n Min_Distance = temp_dist\n Labels[i] = c \n if(collections.Counter(Labels) == collections.Counter(prev_labels)): \n break;\n else: \n Temp_Labels = np.reshape(Labels,(m,1))\n Overall = np.concatenate((X,Temp_Labels),axis=1) \n last_col = Overall.shape[1] - 1\n \n #Compute the Quantization Error based on the Clusters\n Overall_Error = 0\n for i in range(m):\n Sum_d = 0\n val = Overall[i][last_col]\n Computation = Centroids.get(val)\n for j in range(last_col):\n Sum_d = Sum_d + (Computation[j] - Overall[i][j])**2\n Overall_Error = Overall_Error + Sum_d\n \n #Compute the New Centroids\n Unique_vals,count_vals = np.unique(Overall[:,last_col], return_counts=True)\n Centroids = {}\n for i in range(len(Unique_vals)):\n Dat_subset = Overall[Overall[:,last_col]==Unique_vals[i]]\n Mean_subset = np.mean(Dat_subset[:,0:last_col],axis = 0)\n Centroids[Unique_vals[i]] = Mean_subset \n prev_labels = Labels\n if(Overall_Error < Overall_Q):\n Overall_Q = Overall_Error\n final_labels = Labels\n iterations = iterations + 1\nprint(Overall_Q)\nnp.savetxt(sys.argv[4], final_labels, delimiter =',')\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"kmeanspp.py","file_name":"kmeanspp.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"102727201","text":"import os,time,xlrd,sys\n# 为了将多个地址合并在一起需要导入Reduce包\nfrom functools import reduce\n# 导入本地库\nsys.path.append(r\"..\")\nimport Lib.LF as Com\n\nclass GetAddr():\n time.sleep(1)\n # 定义当前路径\n if getattr(sys, 'frozen', False):\n CurrentPath = os.path.dirname(sys.executable)\n elif __file__:\n CurrentPath = os.path.dirname(__file__)\n else:\n CurrentPath = os.getcwd()\n Sta = []\n SQLiteDataBaseFile = \"AGEO.db\"\n SQLiteDataBase = os.path.join(CurrentPath, SQLiteDataBaseFile)\n\n def __init__(self,SQLiteDataBase,Sta):\n self.SQLiteDataBase = SQLiteDataBase\n self.Sta = Sta\n\n def By(self,Mode,Code):\n\n if Mode == 'code':\n Addr = Com.Infra.SQLite3(SQL=\"select Addr from JsSrvAGEOMaster WHERE Code = '%s'\" % Code,\n Data=None, Database=GetAddr.SQLiteDataBase, NumberOfRow=0, OutPutType='List')\n if Addr == []:return False\n else:\n print(\"[**]通过Code查询地址成功\")\n return Addr[0]\n\n if Mode == 'codename':\n Addr = Com.Infra.SQLite3(\n SQL=\"select Addr from JsSrvAGEOMaster WHERE CodeName = '%s'\" % Code,\n Data=None, Database=GetAddr.SQLiteDataBase, NumberOfRow=0, OutPutType='List')\n if Addr == []:\n return False\n else:\n print(\"[**]通过CodeName查询地址成功\")\n return Addr[0]\n","sub_path":"ACTA.py","file_name":"ACTA.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"272060816","text":"list1 = [12,-7,5,64,-14]\n\nfor j in list1:\n if j>=0:\n print(j,end=\", \")\nprint(\"\\n\")\nlist2 = [12,14,-95,3]\nlist3=[]\n\nfor i in list2:\n if i>=0:\n list3.append(i)\n\nprint(list3) \n \n","sub_path":"positivenumber.py","file_name":"positivenumber.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"384955756","text":"import heapq\n\nclass Recursive_Best_First:\n\n def __init__(self,expand, goal_test, heuristic, root):\n self.expand = expand\n self.goal_test = goal_test\n self.heuristic = heuristic\n self.root = root\n\n\n def search(self):\n return self.search(self.root, float('inf'))\n\n\n def search(self,root,f_limit):\n # The node we are at is the goal state return a solution\n if self.goal_test(root): self.constructsolution(root)\n\n successors = self.expand(root)\n\n if len(successors) == 0: return 'Failure',float('inf') # this node is a failure\n\n for s in successors:\n s.fcost = max(s.gcost + s.hcost, root.fcost)\n heapq.heapify(successors)\n while len(successors) > 0:\n best = heapq.heappop(successors) # get the best cost so far\n if best.fcost > f_limit: return 'Failure', best.fcost\n alternative = successors[0].fcost # get the second best\n result,best.fcost = self.search(best, min(f_limit, alternative))\n if result != 'Failure': return result\n return 'Failure', float('inf')\n\n\n\n def constructsolution(self, node):\n solution = []\n cur_node = node\n while cur_node != None:\n solution.append(cur_node)\n cur_node = cur_node.parent\n return solution\n","sub_path":"search/rbfs.py","file_name":"rbfs.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"411887014","text":"\"\"\"add computational level to lambda\n\nRevision ID: e527d9001345\nRevises: e809b7eb2bcc\nCreate Date: 2018-12-13 19:52:56.453443\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'e527d9001345'\ndown_revision = 'e809b7eb2bcc'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n level = postgresql.ENUM('COMPUTABLE', 'QUERYABLE', 'LEARNABLE', name='level', create_type=False)\n level.create(op.get_bind())\n op.add_column('lambdas', sa.Column('level', level, nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('lambdas', 'level')\n op.execute(\"DROP TYPE level;\")\n # ### end Alembic commands ###\n","sub_path":"superset/migrations/versions/e527d9001345_add_computational_level_to_lambda.py","file_name":"e527d9001345_add_computational_level_to_lambda.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"527575755","text":"# This file is part of QSM-blender-addons.\n# \n# QSM-blender-addons 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# QSM-blender-addons 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 QSM-blender-addons. If not, see .\n\nbl_info = {\n \"name\": \"Tree model (QSM) and leaf model (L-QSM) importer\",\n \"category\": \"Learnbgame\",\n \"author\": \"Markku Åkerblom\",\n \"version\": (0, 8, 0),\n \"blender\": (2, 79 ,0),\n \"location\": \"View 3D > Tool Shelf > QSM\",\n \"description\": \"Addon that imports Quantitative Structure Models as either individual cylinders, or as continuous surfaces. A branch is either a collection of Bezier line segments (cylinders) or a Bezier curve. Each type of Bezier curve is lofted by applying a bevel object such as a Bezier circle. The add-on can also import leaf models in Wavefront OBJ format. A single leaf should be either a triangle or a rectangle.\",\n 'support': 'TESTING',\n}\n\nimport bpy\nimport sys\nimport os\nimport math\nimport bmesh\nimport mathutils\nfrom mathutils import Vector, Matrix\nimport datetime\nimport numpy as np\nfrom random import uniform\n\n# Print progress in the console every Nth row.\ndef print_progress(NLine, iLine, d, last):\n \n # Current percentage with precision d.\n p = float(math.floor(d*iLine/NLine))/d\n\n # Display if first line, or if percentage has changed.\n if iLine == 0 or p > last:\n\n # Update last percentage.\n last = p\n\n # Number of digits in line count.\n w = len(str(NLine))\n\n # Message string.\n msg = \"Processing line %\" + str(w) + \"i of %i (%2i%%)\"\n\n # Format message with current numbers.\n msg = msg % (iLine+1, NLine,p*100)\n\n # Display message.\n sys.stdout.write(msg + chr(8) * len(msg))\n sys.stdout.flush()\n\n return last\n\nclass QSMPanel(bpy.types.Panel):\n \"\"\"Creates a Panel in the scene context of the properties editor\"\"\"\n\n bl_label = \"QSM Import\"\n bl_idname = \"SCENE_PT_qsm\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'TOOLS'\n bl_category = \"QSM\"\n bl_context = \"objectmode\"\n\n # Layout of the QSM import panel.\n def draw(self, context):\n\n layout = self.layout\n scene = context.scene\n settings = scene.qsmImportSettings\n\n # Data variable for searching materials.\n data = bpy.data\n\n # Import mode as a button selector.\n row = layout.row()\n row.prop(settings, \"qsmImportMode\", expand=True)\n \n \n # Input file.\n row = layout.row()\n row.prop(settings, \"qsm_file_path\")\n\n # Stem material select.\n row = layout.row()\n row.prop_search(settings, \"qsmStemMaterial\", data, \"materials\")\n\n # Branch material select.\n row = layout.row()\n row.prop_search(settings, \"qsmBranchMaterial\", data, \"materials\")\n\n layout.separator()\n\n # Branch separation.\n row = layout.row()\n row.prop(settings, \"qsmSeparation\")\n\n #layout.separator()\n\n # UI elements for mesh objects.\n if settings.qsmImportMode == 'mesh_cylinder':\n\n # Vertex count inputs.\n row = layout.row()\n layout.label(\"Vertex count:\")\n\n row = layout.row(align=True)\n row.prop(settings,\"qsmVertexCountMin\", text='Min')\n row.prop(settings,\"qsmVertexCountMax\", text='Max')\n\n # UI elements for bezier objects.\n elif settings.qsmImportMode == 'bezier_cylinder' or \\\n settings.qsmImportMode == 'bezier_branch':\n\n # Bevel object generation.\n row = layout.row()\n row.prop(settings, \"qsmGenerateBevelObject\")\n\n if not settings.qsmGenerateBevelObject:\n\n # Bevel object selector.\n row = layout.row()\n row.prop_search(settings, \"qsmBevelObject\", scene, \"objects\")\n \n layout.separator()\n\n # Colormap update button.\n if settings.qsmImportMode == 'mesh_cylinder':\n row = layout.row()\n row.operator(\"qsm.update_colourmap\")\n\n # Import buttons.\n row = layout.row()\n row.operator(\"qsm.qsm_import\")\n\n\n\n \nclass LeafModelPanel(bpy.types.Panel):\n \"\"\"Creates a Panel in the scene context of the properties editor\"\"\"\n\n bl_label = \"Leaf model import\"\n bl_idname = \"SCENE_PT_leaf_model\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'TOOLS'\n bl_category = 'QSM'\n bl_context = \"objectmode\"\n\n # Layout of the leaf model import panel.\n def draw(self, context):\n\n layout = self.layout\n scene = context.scene\n settings = scene.leafModelImportSettings\n\n # Data variable for searching materials.\n data = bpy.data\n\n # Input data type.\n row = layout.row()\n row.prop(settings, \"importType\", expand=False)\n \n # Input file.\n row = layout.row()\n row.prop(settings, \"leaf_model_file_path\")\n\n # Bevel object selector.\n row = layout.row()\n row.prop_search(settings, \"leafModelMaterial\", data, \"materials\") \n\n layout.separator()\n\n\n if settings.importType == 'obj_ext':\n\n # Boolean: generate vertex colors.\n row = layout.row()\n row.prop(settings, \"vertexColorGeneration\")\n\n # Color source.\n if settings.vertexColorGeneration:\n row = layout.row()\n row.prop(settings, \"vertexColorMode\", expand=False)\n\n # Boolean: generate shapekeys.\n row = layout.row()\n row.prop(settings, \"shapekeyGeneration\")\n\n # Boolean: generate UVs.\n row = layout.row()\n row.prop(settings, \"leafUvGeneration\")\n\n if settings.leafUvGeneration:\n layout.separator()\n\n # Dropdown: UV type.\n row = layout.row()\n row.prop(settings, \"leafUvType\", expand=False)\n\n if settings.leafUvType == 'custom':\n\n # Mesh selector: UV source mesh.\n row = layout.row()\n row.prop_search(settings, \"leafUvSource\", bpy.data, \"meshes\")\n\n layout.separator()\n \n # Import button.\n row = layout.row()\n row.operator(\"leaf.import_leaves\")\n\n\n\n\nclass ImportLeafModel(bpy.types.Operator):\n \"\"\"Import leaves as planes\"\"\"\n\n bl_idname = \"leaf.import_leaves\"\n bl_label = \"Import leaf model\"\n\n def import_obj(self, file_path):\n\n # Use built-in OBJ-importer with fixed parameters.\n bpy.ops.import_scene.obj \\\n (\n filepath=file_path,\n axis_forward='Y',\n axis_up='Z',\n filter_glob=\"*.obj;*.mtl\",\n use_edges=True,\n use_smooth_groups=True,\n use_split_objects=False,\n use_split_groups=False,\n use_groups_as_vgroups=False,\n use_image_search=False,\n split_mode='OFF',\n global_clamp_size=0\n )\n\n # Get imported objects, assumed to be selected.\n return bpy.context.selected_objects[:]\n\n def import_ext_obj(self, file_path, fShapeKeyGeneration, fVertexColor, color_mode):\n\n # Array of base vertices.\n base_vert = []\n # Array of base faces.\n base_face = []\n\n # Flag: vertex addition completed.\n fVertDone = False\n # Flag: face addition completed.\n fFaceDone = False\n # Flag: read vertex colors from file.\n fFromFile = False\n # Flag: randomize vertex colors.\n fRandomColor = False\n\n # Number of added base vertices.\n NVert = 0\n # Number of added face vertices.\n NFace = 0\n # Number of added leaves.\n NLeaf = 0\n\n # Resulting object.\n ob = None\n\n # Name of shape key for growth animation.\n GrowthName = 'ReverseGrowth'\n\n # Set boolean flags for simplicity.\n if color_mode == 'from_file':\n fFromFile = True\n elif color_mode == 'random':\n fRandomColor = True\n else:\n # Otherwise, ensure that vertex colors are not\n # added if color mode is unknown.\n fVertexColor = False\n\n with open(file_path) as lines:\n\n # Number of lines in input file.\n NLine = sum(1 for line in lines)\n\n # Last displayed percentage.\n PLast = 0\n\n # Number of digits to use in object naming.\n NDigit = len(str(NLine))\n \n # Return to file beginning for second iteration.\n lines.seek(0)\n \n # Iterate over rows in input file.\n for iLine, line in enumerate(lines):\n\n # Split row into parameters.\n params = line.split(' ',1)\n\n # Ignore rows with too few parameters.\n if len(params) > 2:\n continue\n \n # Print progress in the console every nth row.\n PLast = print_progress(NLine, iLine, 10, PLast)\n\n # Type of line.\n\n # Base vertex.\n if params[0] == 'v':\n\n # If vertex adding has been closed,\n # ignore further vertex lines.\n if fVertDone:\n continue\n\n # Get vertex coordinates.\n co = params[1].split()\n\n # Should have three coordinates.\n if len(co) != 3:\n continue\n\n # Append new base vertex.\n base_vert.append(np.array([float(co[0]), float(co[1]), float(co[2])]))\n\n # Increase base vertex count.\n NVert += 1\n\n # Base face.\n elif params[0] == 'f':\n\n # If face adding has been closed,\n # ignore further face lines.\n if fFaceDone:\n continue\n\n # Close vertex adding.\n if not fVertDone:\n fVertDone = True\n\n # Indices of face vertices.\n ind = params[1].split()\n\n # Faces have to have at least three vertices.\n if len(ind) < 3:\n continue\n\n # Append new face.\n base_face.append(np.array([int(x)-1 for x in ind]))\n\n # Increase base face count.\n NFace += 1\n\n # Leaf transformation parameters.\n elif params[0] == 'L':\n\n # Close vertex and face adding.\n if not fFaceDone:\n fFaceDone = True\n fVertDone = True\n\n # If no geometry, unable to create leaf.\n if NVert == 0 or NFace == 0:\n self.report({'ERROR_INVALID_INPUT'}, \\\n 'Input file missing vertices or faces.')\n break\n\n # Transformation configuration.\n config = params[1].split()\n\n # Line should have at least 15 parameters.\n if len(config) < 15:\n continue\n\n # Check that vertex color values are present in file,\n # if vertex color generation active.\n # Otherwise, ignore line.\n if fVertexColor and fFromFile:\n if len(config) < 18:\n continue\n\n # Increase leaf count.\n NLeaf += 1\n\n # Initialize object and mesh data, and optionally\n # shape key and color map layers.\n if NLeaf == 1:\n\n # Create mesh.\n me = bpy.data.meshes.new('LeafModel')\n\n # Create object.\n ob = bpy.data.objects.new('LeafModel',me)\n\n # Bmesh.\n bm = bmesh.new()\n\n if fShapeKeyGeneration:\n # Add default shape key.\n ob.shape_key_add('Basis')\n # Additional shape key for growth animation.\n sk = bm.verts.layers.shape.new(GrowthName)\n\n if fVertexColor:\n # Create new layer for colourmap.\n cl = bm.loops.layers.color.new(\"Color\")\n\n if fShapeKeyGeneration:\n # Start point of twig used for growth animation.\n twig_start = tuple([float(x) for x in config[0:3]])\n\n # Leaf parameters.\n leaf_start = np.array([float(x) for x in config[3:6]])\n leaf_dir = np.array([float(x) for x in config[6:9]])\n leaf_normal = np.array([float(x) for x in config[9:12]])\n leaf_scale = np.array([float(x) for x in config[12:15]])\n\n # Get vertex color value if necessary.\n if fVertexColor:\n # Additional color elements should be present on line.\n if fFromFile:\n vert_color = [float(x) for x in config[15:18]]\n # Generate random 3-element array from uniform distribution.\n elif fRandomColor:\n vert_color = [uniform(0,1) for x in \"rgb\"]\n\n\n # Scaling.\n vert = np.multiply(base_vert,leaf_scale)\n\n # Coordinate change matrix.\n E = np.array([np.cross(leaf_normal, leaf_dir), leaf_dir, leaf_normal])\n\n # Rotation.\n vert = np.dot(vert, E)\n\n # Transition.\n vert += leaf_start\n\n # Added vertices.\n bm_vert = []\n\n # Add vertices to bmesh.\n for v in vert:\n\n # Add vertex.\n bv = bm.verts.new(tuple(v))\n \n if fShapeKeyGeneration:\n # Set shape key value.\n bv[sk] = twig_start\n\n # Append to list.\n bm_vert.append(bv)\n\n # Convert to numpy array for easy indexing.\n bm_vert = np.array(bm_vert)\n\n # Iterate over face indices in base.\n for f in base_face:\n\n # Create new face to mesh.\n bf = bm.faces.new(tuple(bm_vert[f]))\n\n # If vertex color information is present in the input file\n # add color layer and assign color for each vertex.\n if fVertexColor:\n for loop in bf.loops:\n loop[cl] = vert_color\n \n\n # Unknown line type.\n else:\n continue\n\n if ob is not None:\n\n # Bind bmesh to mesh.\n bm.to_mesh(me) \n\n # Link object to scene.\n scene = bpy.context.scene\n scene.objects.link(ob)\n\n # Set as active and selected.\n scene.objects.active = ob\n ob.select = True\n\n # Return a list of objects for compatibility\n # with OBJ-importer.\n return [ob]\n else:\n # Return empty array if no object was created.\n return []\n \n # Operator for importing leaf model.\n def execute(self, context):\n\n print('Importing leaves.')\n\n # Current scene for reading parameters for importing. \n scene = context.scene\n settings = scene.leafModelImportSettings\n \n # Path to input file.\n filestr = settings.leaf_model_file_path\n\n # Check for empty filepath.\n if len(filestr) == 0:\n self.report({'ERROR_INVALID_INPUT'},'Missing input file path.')\n print('Cancelled.')\n return {'CANCELLED'}\n\n # Convert to absolute path.\n file_path = bpy.path.abspath(filestr)\n\n # Check that file exists.\n if not os.path.isfile(file_path):\n self.report({'ERROR_INVALID_INPUT'},'No file with given path.')\n print('Cancelled.')\n return {'CANCELLED'}\n\n # Check if UVs are to be generated.\n fUvGeneration = settings.leafUvGeneration\n\n if fUvGeneration:\n if settings.leafUvType == 'custom':\n SourceName = settings.leafUvSource\n\n UvSource = bpy.data.meshes.get(SourceName)\n\n if not UvSource:\n self.report({'ERROR_INVALID_INPUT'}, \\\n 'Custom UV generation selected, but UV mesh not found.')\n print('Cancelled.')\n return {'CANCELLED'}\n\n # Record start time.\n start = datetime.datetime.now()\n \n # Format of input data.\n import_type = settings.importType\n\n # Import using built-in OBJ-importer.\n if import_type == 'obj':\n leaf_objects = self.import_obj(file_path)\n\n # Import using custom extended OBJ-format.\n elif import_type == 'obj_ext':\n # Check if shape keys are to be generated.\n fShapeKeyGeneration = settings.shapekeyGeneration\n\n # Check if vertex colors should be assigned.\n fVertexColor = settings.vertexColorGeneration\n\n # Vertex color mode.\n color_mode = settings.vertexColorMode\n\n leaf_objects = self.import_ext_obj(file_path, \\\n fShapeKeyGeneration, \\\n fVertexColor, \\\n color_mode)\n\n # If import generated no objects, stop execution.\n if len(leaf_objects) == 0:\n self.report({'ERROR_INVALID_INPUT'},'No leaf object generated!')\n return {'CANCELLED'}\n\n # Selected material for leaves.\n matname = settings.leafModelMaterial\n\n # Check if material selected.\n if len(matname) == 0:\n print('No material set.')\n mat = None\n else:\n # Try to get material by input name.\n mat = bpy.data.materials.get(matname)\n\n # Print warning if does not exist.\n if not mat:\n print('Material not found.')\n\n # Flag: skip UV generation due to input errors.\n fSkipUv = False\n \n if fUvGeneration:\n\n # Name of the UV map to be created. Using \"Overlapping\" because\n # all leaves are overlayed in UV coordinates, to allow simple \n # UV mapping of a single leaf image.\n MapName = 'Overlapping'\n\n leafUvType = settings.leafUvType\n\n \n if leafUvType == 'isosceles_triangle':\n # UV vertex locations for a isosceles triangle.\n uv_verts = [Vector((1,0)), Vector((0.5,1)), Vector((0,0))]\n \n elif leafUvType == 'square':\n # UV vertex locations for a square.\n uv_verts = [Vector((1,0)), Vector((1,1)),Vector((0,1)), Vector((0,0))]\n\n elif leafUvType == 'custom':\n\n # Initialize array.\n uv_verts = []\n\n # Copy local (x,y)-coordinates of source mesh.\n for v in UvSource.vertices:\n x = v.co[0]\n y = v.co[1]\n uv_verts.append(Vector((x,y))) \n\n else:\n # Otherwise, the selection is illegal.\n self.report({'WARNING'},'Unknown UV generation type selected. UV generation skipped.')\n fSkipUv = True\n\n # Number of vertices in input UV map.\n NVert = len(uv_verts)\n \n \n\n # Iterate over selected objects.\n for obj in leaf_objects:\n \n # Mesh of selected object.\n me = obj.data\n\n # Set material if exists.\n if mat:\n me.materials.append(mat)\n\n # UV map creation.\n if fUvGeneration and not fSkipUv: \n \n # Create new UV map.\n me.uv_textures.new(MapName)\n \n # Create a bmesh from mesh data for UV map manipulation.\n bm = bmesh.new()\n bm.from_mesh(me)\n \n # Create UV layer.\n uv_layer = bm.loops.layers.uv[0]\n \n # Initialize lookup table.\n bm.faces.ensure_lookup_table()\n \n # Number of leaves.\n NFace = len(bm.faces)\n\n # Iterate over leaves.\n for iFace in range(NFace):\n\n # Number of vertices in face.\n NFaceVert = len(bm.faces[iFace].loops)\n \n # Iterate over vertices in leaf.\n for iVert in range(NFaceVert):\n \n # Index of current vertex modulo set number of vertices.\n uv_index = iVert%NVert\n # Set UV map vertex to coordinate given by above index.\n bm.faces[iFace].loops[iVert][uv_layer].uv = uv_verts[uv_index]\n \n # Update mesh data.\n bm.to_mesh(me)\n \n # Record end time.\n end = datetime.datetime.now()\n\n # Compute duration.\n delta = end - start\n\n # Format duration as string.\n timestr = \"{:.1f}\".format(delta.total_seconds())\n\n # Print duration.\n print('Done is ' + timestr + ' seconds.')\n\n return {'FINISHED'}\n\n\nclass ImportQSM(bpy.types.Operator):\n \"\"\"Import QSM as a collection of individual cylinders\"\"\"\n\n bl_idname = \"qsm.qsm_import\"\n bl_label = \"Import\"\n\n def createQSMParent(self, scene):\n\n # Create empty parent object for the resulting object(s).\n EmptyParent = bpy.data.objects.new('TreeParent', None)\n EmptyParent.empty_draw_size = 1\n EmptyParent.empty_draw_type = 'PLAIN_AXES'\n EmptyParent.location = Vector((0.0,0.0,0.0))\n \n # Link empty to scene.\n scene.objects.link(EmptyParent)\n\n # Return parent object.\n return EmptyParent\n\n # Function to create mesh cylinder by copying the data\n # of a base object, and then transforming it.\n def addMeshCylinder(self, baseobj, cp, rot, h, r):\n\n # Copy base object and data.\n ob = baseobj.copy()\n ob.data = baseobj.data.copy()\n\n # Translate to center point.\n ob.location = cp\n\n # Scale to match cylinder radius and length.\n ob.scale = (r,r,h)\n\n # Set rotation.\n ob.rotation_euler = rot\n\n # Link new object to scene.\n bpy.context.scene.objects.link(ob)\n\n # Return new object.\n return ob\n\n # Function to import a QSM as mesh cylinders.\n def import_as_mesh_cylinders(self, context, file_path, EmptyParent, \n fBranchSeparation,\n matStem, matBranch):\n\n print('Importing QSM as mesh cylinders.')\n \n # Current scene to read properties.\n scene = context.scene\n settings = scene.qsmImportSettings\n \n # Number of imported branches.\n NBranch = 0\n # Index of last branch in input file.\n iLastBranch = 0\n\n # Flag: should the cylinder index be stored in a vertex layer.\n # Allows updating vertex colour afterwards.\n fIdColor = True\n\n # Minimum vertex count in cylinder rings.\n vmin = settings.qsmVertexCountMin\n # Maximum vertex count.\n vmax = settings.qsmVertexCountMax\n\n # Number of different vertex counts.\n vcount = vmax - vmin + 1\n\n # Initialize list of base objects that will be copied for optimization.\n baseobj = []\n\n # Generate a base object for each vertex count.\n for v in range(0,vcount):\n\n # Number of vertices in the rings of the current base object cylinder.\n nvert = vmin+v\n\n # Add a cylinder primitive with the built-in operator.\n bpy.ops.mesh.primitive_cylinder_add(vertices=nvert,\n radius=1,\n depth=1,\n end_fill_type='NGON',\n view_align=False,\n enter_editmode=False,\n location=(0.0,0.0,0.0),\n rotation=(0.0,0.0,0.0))\n\n # Get newly generated base object.\n ob = context.selected_objects[0]\n # Deselect.\n ob.select = False\n\n # Get mesh data of base object.\n me = ob.data\n\n # Translation vector.\n point = Vector((0.0,0.0,-0.5))\n\n # Move base object so that the starting point is at the origin.\n mat = Matrix.Translation(ob.matrix_world.translation - point)\n me.transform(mat)\n\n # Update mesh data.\n me.update()\n # Do opposite transition in object mode to get object origin corrected.\n ob.matrix_world.translation = point\n\n # Create bmesh object to set the shading of the envelope faces as smooth.\n bm = bmesh.new() \n bm.from_mesh(me)\n\n # Iterate over the faces other than the last two which are the caps.\n for f in bm.faces[-(nvert+2):]:\n if f.select:\n if len(f.verts) == 4:\n # Set shading smooth.\n f.smooth = True\n\n # Update mesh data and delete bmesh.\n bm.to_mesh(me)\n bm.free()\n\n # Add base object to list.\n baseobj.append(ob)\n\n # Minimum vertex count must be at least three.\n if vmin < 3:\n vmin = 3\n\n # Maximum count must be greater than the minimum.\n if vmax < vmin:\n vmax = vmin\n\n with open(file_path) as lines:\n \n # File line count.\n NLine = 0\n\n # Last displayed percentage.\n PLast = 0\n\n # Iterate through the file rows, recording the count and \n # minimum and maximum radius values.\n for line in lines:\n\n # Increase counter.\n NLine = NLine + 1\n\n # Split file line into parameter array.\n params = line.split()\n\n # Ignore rows with too few parameters.\n if len(params) < 9:\n continue\n\n # Get radius parameter of row.\n r = float(params[8])\n\n # Initialize min and max on first row.\n if NLine == 1:\n rmin = r\n rmax = r\n else:\n # Update extremes if necessary.\n if r < rmin:\n rmin = r\n if r > rmax:\n rmax = r\n \n # Number of digits to use in object naming.\n NDigit = len(str(NLine))\n \n # Return to file beginning for second iteration.\n lines.seek(0)\n\n # List of objects that are later joined to form either a branch or the full QSM.\n allobj = []\n\n # Index of current cylinder.\n iCyl = 0\n \n # Iterate over rows in input file.\n for iLine, line in enumerate(lines):\n\n # Split row into parameters.\n params = line.split()\n\n # Ignore rows with too few parameters.\n if len(params) < 9:\n continue\n\n # Increase number of cylinders.\n iCyl += 1\n \n # Print progress in the console every nth row.\n PLast = print_progress(NLine, iLine, 10, PLast)\n\n # Store parameters.\n iBranch = int(float(params[0]))\n sp = Vector((float(params[1]), float(params[2]), float(params[3])))\n ax = Vector((float(params[4]), float(params[5]), float(params[6])))\n h = float(params[7])\n r = float(params[8])\n\n # Convert axis to Euler rotation.\n rot = ax.to_track_quat('Z', 'Y').to_euler()\n\n # Select number of vertices based on linear interpolation of radius.\n nvert = vmin + (vmax-vmin)*(r-rmin)/(rmax-rmin)\n # Convert result to an integer by rounding.\n nvert = int(round(nvert))\n\n # Index of base object based on vertex count.\n iObj = nvert - vmin\n\n # Flag: file contains an additional row to use as colourmap values.\n fVertColor = False\n\n # Check if extra column for colourmap exists.\n if len(params) > 9:\n fVertColor = True\n VertColor = float(params[9])\n if len(params) > 11:\n VertColor = Vector((float(params[9]), float(params[10]), float(params[11])))\n\n # If this is the first branch, or the index differs form the previous row.\n if NBranch == 0 or iBranch != iLastBranch:\n\n # Update index of previous branch.\n iLastBranch = iBranch\n # Increase branch count.\n NBranch += 1\n\n # If multiple objects are created, use unique object and mesh names\n # by numbering them.\n if fBranchSeparation:\n meshname = \"branch_\" + str(NBranch).zfill(NDigit)\n objname = \"branch_\" + str(NBranch).zfill(NDigit)\n else:\n meshname = \"qsm_mesh\"\n objname = \"qsm\"\n\n # Start a new branch if this is the first one, or if the user\n # has selected to separate branches.\n if NBranch == 1 or fBranchSeparation:\n\n # If separate branches and not the first one.\n if NBranch > 1:\n\n # Select all objects in last branch.\n for ob in allobj:\n ob.select = True\n\n # Set one of them as active.\n scene.objects.active = allobj[0]\n # Join the objects.\n bpy.ops.object.join()\n # Apply object scale.\n bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)\n # Deselect resulting object.\n allobj[0].select = False\n # Initialize array for next branch.\n allobj = []\n \n # Add current cylinder by copying and modifying the base object.\n ob = self.addMeshCylinder(baseobj[iObj],sp,rot,h,r)\n \n # Set name and parent.\n ob.name = objname\n ob.parent = EmptyParent\n\n # Get mesh data.\n me = ob.data\n # Set mesh name.\n me.name = meshname\n\n # Add stem material to object if it is the first branch,\n # or if branch material is not set (same material for all branches),\n # and if stem material is set.\n if iBranch == 1 or not matBranch:\n if matStem:\n me.materials.append(matStem)\n \n # Add branch material if material is set and it is different from the\n # stem material.\n if matBranch and (matStem != matBranch):\n me.materials.append(matBranch)\n\n # No need to change object even though the branch index changed.\n else:\n ob = self.addMeshCylinder(baseobj[iObj],sp,rot,h,r)\n\n # Still on same branch index.\n else:\n ob = self.addMeshCylinder(baseobj[iObj],sp,rot,h,r)\n\n # Add new object to list of cylinders in current branch.\n allobj.append(ob)\n\n # Get mesh data of new cylinder.\n me = ob.data\n # Create a bmesh object for colourmap creation from mesh data.\n bm = bmesh.new() \n bm.from_mesh(me)\n\n # If cylinder ID should be stored on the model.\n if fIdColor:\n # Get or create new layer for index colouring.\n layer = bm.verts.layers.int.get(\"CylinderId\")\n if not layer:\n layer = bm.verts.layers.int.new(\"CylinderId\")\n \n # Iterate over mesh vertices and set index colouring value to\n # index of the cylinder.\n for v in bm.verts:\n v[layer] = iCyl\n\n # If vertex colour information is present in the input file\n # add colour layer and assign colour for each vertex.\n if fVertColor:\n # Get or create new layer for input colourmap.\n colors = bm.loops.layers.color.get(\"Color\")\n if not colors:\n colors = bm.loops.layers.color.new(\"Color\")\n \n # Iterate over vertices and set vertex colour by\n # repeating the input value three times.\n for v in bm.verts:\n for loop in v.link_loops:\n if len(VertColor) > 1:\n loop[colors] = VertColor\n else:\n loop[colors] = [VertColor] * 3\n\n # Update mesh data and delete bmesh.\n bm.to_mesh(me)\n bm.free()\n \n # Select all cylinders of last object.\n for ob in allobj:\n ob.select = True\n\n # Set active object.\n scene.objects.active = allobj[0]\n\n # Join all cylinders in list.\n bpy.ops.object.join()\n # Apply object scale.\n bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)\n\n\n # As clean-up, remove the base objects and their mesh data.\n for ob in baseobj:\n scene.objects.unlink(ob)\n bpy.data.objects.remove(ob)\n\n return {'FINISHED'}\n\n\n # Function to import a QSM as Bezier cylinders.\n def import_as_bezier_cylinders(self, context, file_path, EmptyParent, fBranchSeparation, \n matStem, matBranch, BevelObject):\n\n print('Importing QSM as Bezier cylinders.')\n \n # Current scene to read properties.\n scene = context.scene\n \n # Number of branches.\n NBranch = 0\n # Index of last branch.\n iLastBranch = 0\n\n # Length of right and left control handles.\n len_r = 0.45\n len_l = 0.45\n\n with open(file_path) as lines:\n \n # Count number of lines in file.\n NLine = sum(1 for line in lines)\n \n # Number of digits to use in object naming.\n NDigit = len(str(NLine))\n \n # If file did not have any lines.\n if NLine <= 0:\n self.report({'ERROR_INVALID_INPUT'},'Selected file is empty.')\n return {'CANCELLED'}\n\n # Return to file beginning.\n lines.seek(0)\n\n # Last displayed percentage.\n PLast = 0\n \n # Iterate over file rows.\n for iLine, line in enumerate(lines):\n\n # Split row into parameters.\n params = line.split()\n\n # Ignore rows with too few parameters.\n if len(params) < 9:\n continue\n \n # Print progress in the console every nth row.\n PLast = print_progress(NLine, iLine, 10, PLast)\n\n # Get cylinder parameters.\n iBranch = int(float(params[0]))\n sp = (float(params[1]), float(params[2]), float(params[3]))\n ax = (float(params[4]), float(params[5]), float(params[6]))\n h = float(params[7])\n r = float(params[8])\n\n # If the first branch or branch index has changed.\n if NBranch == 0 or iBranch != iLastBranch:\n\n # Update last index.\n iLastBranch = iBranch\n # Increase branch count.\n NBranch += 1\n\n # If multiple objects are created, use unique object and mesh names\n # by numbering them.\n if fBranchSeparation:\n curvename = \"branch_\" + str(NBranch).zfill(NDigit)\n objname = \"branch_\" + str(NBranch).zfill(NDigit)\n else:\n curvename = \"qsm_curve\"\n objname = \"qsm\"\n\n # Start a new branch if this is the first one, or if the user\n # has selected to separate branches.\n if NBranch == 1 or fBranchSeparation:\n\n # Create Bezier curve for new branch.\n curvedata = bpy.data.curves.new(name=curvename, type='CURVE')\n curvedata.dimensions = '3D'\n # Set bevel object.\n curvedata.bevel_object = BevelObject\n curvedata.use_fill_caps = True\n\n # Add stem material to object if it is the first branch,\n # or if branch material is not set (same material for all branches),\n # and if stem material is set.\n if iBranch == 1 or not matBranch:\n if matStem:\n curvedata.materials.append(matStem)\n \n # Add branch material if material is set and it is different from the\n # stem material.\n if matBranch and (matStem != matBranch):\n curvedata.materials.append(matBranch)\n\n # Create new object with the curve data.\n objectdata = bpy.data.objects.new(objname, curvedata)\n # Position to origin.\n objectdata.location = (0,0,0)\n # Parent to created empty.\n objectdata.parent = EmptyParent\n # Link to scene.\n bpy.context.scene.objects.link(objectdata)\n # Set as selected.\n objectdata.select = True\n\n # For each cylinder add a new Bezier spline into the curve data.\n polyline = curvedata.splines.new('BEZIER')\n # Add an extra point to have two in total.\n polyline.bezier_points.add(1)\n # Set order to one as the cylinder axis will be linear.\n polyline.resolution_u = 1\n\n # Create the starting (i == 0) and ending (i == 1) points of the spline.\n for i in (0,1):\n\n # Position on axis (0 = bottom, 1 = top).\n hf = i\n\n # Position of curve point.\n co = [sp_i+h*ax_i*hf for sp_i,ax_i in zip(sp,ax)]\n # Position of left handle.\n left = [sp_i+h*ax_i*hf-len_l*ax_i*h for sp_i,ax_i in zip(sp,ax)]\n # Position of right handle.\n right = [sp_i+h*ax_i*hf+len_r*ax_i*h for sp_i,ax_i in zip(sp,ax)]\n\n # Set Bezier curve point properties.\n polyline.bezier_points[i].co = co\n polyline.bezier_points[i].handle_left = left\n polyline.bezier_points[i].handle_right = right\n\n # Set curve point radius.\n polyline.bezier_points[i].radius = r\n\n # Assign proper materials from the splots.\n if iBranch == 1:\n if matStem:\n polyline.material_index = 0\n else:\n if matBranch or matStem:\n polyline.material_index = len(curvedata.materials)\n\n # Set curve resolution.\n polyline.resolution_u = 1\n polyline.use_endpoint_u = True\n\n\n # Function to add a branch-level Bezier spline to the given\n # curve data, from the given cylinder parameters.\n def addBezierCurve(self,curvedata, SP, AX, H, R):\n \n\n # Number of curve points = cylinder count + start point + end point.\n NPoint = len(R) + 2\n\n # Create new spline.\n polyline = curvedata.splines.new('BEZIER')\n # Add curve points to get NPoint points.\n polyline.bezier_points.add(NPoint - 1)\n\n # Iterate over cylinders in the input parameter lists.\n for i in range(0,NPoint):\n\n # Base of first cylinder.\n if i == 0:\n # Use normal radius.\n rf = 1 # Radius scaler\n # Point at the bottom of the cylinder.\n hf = 0 # Position along cylinder axis.\n j = 0 # Index of curve point.\n\n # Shorter handles as there are more than one curve point\n # \"on\" the first cylinder.\n len_r = 0.25 # Length of right handle.\n len_l = 0.25 # Length of left handle.\n\n # Tip of last cylinder.\n elif i == NPoint - 1:\n # Taper to 10% of radius.\n rf = 0.1\n # Point at the end of the cylinder.\n hf = 1\n # Last curve point.\n j = len(SP) - 1\n\n # Shorter handles as there are more than one curve point\n # \"on\" the last cylinder.\n len_l = 0.25\n len_r = 0.25\n\n # Curve points in the middle of the cylinders.\n else:\n # Normal radius.\n rf = 1\n # Point at the center of cylinder.\n hf = 0.5\n j = i - 1\n\n # Normal handle length, unless its the left handle of the\n # first cylinder, or the right handle of the last cylinder.\n len_r = 0.45\n len_l = 0.45\n\n # Middle of the first cylinder.\n if i == 1:\n len_l = 0.25\n\n # Middle of the last cylinder.\n if i == NPoint - 2:\n len_r = 0.25\n\n # Get parameters of current cylinder.\n sp = SP[j] # Start point\n ax = AX[j] # Axis\n h = H[j] # Length\n r = R[j] # Radius\n\n # Compute curve point location.\n co = [sp_i+h*ax_i*hf for sp_i,ax_i in zip(sp,ax)]\n # And handle locations.\n left = [sp_i+h*ax_i*hf-len_l*ax_i*h for sp_i,ax_i in zip(sp,ax)]\n right = [sp_i+h*ax_i*hf+len_r*ax_i*h for sp_i,ax_i in zip(sp,ax)]\n\n # Set curve point properties and radius.\n polyline.bezier_points[i].co = co\n polyline.bezier_points[i].handle_left = left\n polyline.bezier_points[i].handle_right = right\n polyline.bezier_points[i].radius = r*rf\n\n # Set curve resolution based on the number of curve points. \n # At most the resolution can be 10.\n polyline.resolution_u = min(NPoint - 2,10)\n polyline.use_endpoint_u = True\n\n # Return new spline.\n return polyline\n\n\n \n # Function to import a QSM as branch-level bevelled Bezier curves.\n def import_as_bezier_curves(self, context, file_path, EmptyParent, \n fBranchSeparation,\n matStem, matBranch, BevelObject):\n\n print('Importing QSM as Bezier curves.')\n \n # Current scene to read properties.\n scene = context.scene\n \n # Number of branches.\n NBranch = 0\n # Index of last branch.\n iLastBranch = 0\n\n # Initialize arrays to collect branch cylinder parameters.\n sp = []\n ax = []\n h = []\n r = []\n\n with open(file_path) as lines:\n \n # Count number of lines in file.\n NLine = sum(1 for line in lines)\n \n # Number of digits to use in object naming.\n NDigit = len(str(NLine))\n \n # If file had any rows.\n if NLine > 0:\n\n # If multiple objects are created, use unique object and mesh names\n # by numbering them.\n if fBranchSeparation:\n curvename = \"branch_\" + str(1).zfill(NDigit)\n objname = \"branch_\" + str(1).zfill(NDigit)\n else:\n curvename = \"qsm_curve\"\n objname = \"qsm\"\n\n # Create new curve to hold splines.\n curvedata = bpy.data.curves.new(name=curvename, type='CURVE')\n curvedata.dimensions = '3D'\n # Set bevel object and fill caps.\n curvedata.bevel_object = BevelObject\n curvedata.use_fill_caps = True\n\n # Add stem material to first object.\n if matStem:\n curvedata.materials.append(matStem)\n \n # Add branch material to first object if present.\n if matBranch and (matStem != matBranch):\n curvedata.materials.append(matBranch)\n\n # Create new object with curve data.\n objectdata = bpy.data.objects.new(objname, curvedata)\n # Set position to origin.\n objectdata.location = (0,0,0)\n # Parent to created empty.\n objectdata.parent = EmptyParent\n # Set selected.\n objectdata.select = True\n\n # Link to scene.\n scene.objects.link(objectdata)\n\n # Otherwise the file was empty.\n else:\n self.report({'ERROR_INVALID_INPUT'},'Selected file is empty.')\n return {'CANCELLED'}\n \n # Move back to file beginning.\n lines.seek(0)\n\n # Last displayed percentage.\n PLast = 0\n \n # Iterate over file rows.\n for iLine, line in enumerate(lines):\n\n # Split row into parameters.\n params = line.split()\n\n # Ignore rows with too few parameters.\n if len(params) < 9:\n continue\n\n # Print progress in the console every nth row.\n PLast = print_progress(NLine, iLine, 10, PLast)\n\n # Get cylinder parameters.\n iBranch = int(float(params[0]))\n\n # On first branch.\n if NBranch < 1:\n # Set count to one.\n NBranch = 1\n # Set last index to first index.\n iLastBranch = iBranch\n\n\n # If new branch begins, complete the last branch.\n if iBranch != iLastBranch:\n\n # Add new spline with the cylinder parameter arrays.\n polyline = self.addBezierCurve(curvedata, sp, ax, h, r)\n\n # If the branch index of the branch to complete is one,\n # assign stem material.\n if iLastBranch == 1:\n polyline.material_index = 0\n # Otherwise, assign last material slot, which is stem\n # material if its the only material and branch material\n # if it is present.\n else:\n polyline.material_index = len(curvedata.materials)\n\n # Update last branch to current value.\n iLastBranch = iBranch\n # Increase branch count.\n ++NBranch\n\n # Empty parameter arrays.\n sp[:] = []\n ax[:] = []\n h[:] = []\n r[:] = []\n\n # If branches are separated, create new object with a\n # name based on index.\n if fBranchSeparation:\n curvename = \"branch_\" + str(NBranch).zfill(NDigit)\n objname = \"branch_\" + str(NBranch).zfill(NDigit)\n\n # New curve data.\n curvedata = bpy.data.curves.new(name=curvename, type='CURVE')\n curvedata.dimensions = '3D'\n curvedata.bevel_object = BevelObject\n curvedata.use_fill_caps = True\n\n # Add branch material to rest of the objects if present.\n if matBranch:\n curvedata.materials.append(matBranch)\n # Otherwise use stem material if given.\n elif matStem:\n curvedata.materials.append(matStem)\n\n # New object with curve data.\n objectdata = bpy.data.objects.new(objname, curvedata)\n # Position to origin.\n objectdata.location = (0,0,0)\n # Parent to empty.\n objectdata.parent = EmptyParent\n # Set selected.\n objectdata.select = True\n\n # Link to current scene.\n scene.objects.link(objectdata)\n\n\n # Append cylinder parameters from current file row to parameter\n # arrays.\n sp.append( (float(params[1]), float(params[2]), float(params[3])) )\n ax.append( (float(params[4]), float(params[5]), float(params[6])) )\n h.append( float(params[7]) )\n r.append( float(params[8]) )\n\n # Complete final branch.\n polyline = self.addBezierCurve(curvedata, sp, ax, h, r)\n\n # If the branch index of the branch to complete is one,\n # assign stem material.\n if iBranch == 1:\n polyline.material_index = 0\n # Otherwise, assign last material slot, which is stem\n # material if its the only material and branch material\n # if it is present.\n else:\n polyline.material_index = len(curvedata.materials)\n\n\n # Main function of the QSM import operator. \n def execute(self,context):\n\n # Record start time to compute duration.\n start = datetime.datetime.now()\n\n # Current scene for properties.\n scene = context.scene\n settings = scene.qsmImportSettings\n\n # Path to input file.\n filestr = settings.qsm_file_path\n\n # Check for empty filepath.\n if len(filestr) == 0:\n self.report({'ERROR_INVALID_INPUT'},'Missing input file path.')\n print('Cancelled.')\n return {'CANCELLED'}\n\n # Convert to absolute path.\n file_path = bpy.path.abspath(filestr)\n\n # Check that file exists.\n if not os.path.isfile(file_path):\n self.report({'ERROR_INVALID_INPUT'},'No file with given path.')\n print('Cancelled.')\n return {'CANCELLED'}\n\n # Import mode: mesh / bezier\n mode = settings.qsmImportMode\n # Flag: separate objects for each branch.\n fBranchSeparation = settings.qsmSeparation\n\n # Create empty parent for QSM object(s).\n EmptyParent = self.createQSMParent(scene)\n\n # If curve-based mode, check that bevel object is given and\n # exists.\n if mode == 'bezier_cylinder' or mode == 'bezier_branch':\n\n if settings.qsmGenerateBevelObject:\n\n # Get bevel object by name. This object is set as the bevel object\n # of all the Bezier curves.\n bpy.ops.curve.primitive_bezier_circle_add(radius=1,\n view_align=False, \n enter_editmode=False, \n location=(0, 0, 0))\n\n # Selected object is the added curve.\n BevelObject = context.selected_objects[0]\n\n # Bevel object name.\n BevelObject.name = 'BevelObject'\n BevelObject.parent = EmptyParent\n BevelObject.data.resolution_u = 5\n else:\n # Bevel object name.\n bevel_object_name = settings.qsmBevelObject\n # Get bevel object by name. This object is set as the bevel object\n # of all the Bezier curves.\n BevelObject = bpy.data.objects.get(bevel_object_name)\n\n # Check that bevel object exists.\n if not BevelObject:\n self.report({'ERROR_INVALID_INPUT'},'Missing bevel object.')\n print('Cancelled.')\n return {'CANCELLED'}\n\n # Check that the object is a curve object.\n if BevelObject.type != 'CURVE':\n self.report({'ERROR_INVALID_INPUT'},'Bevel object has to be a curve.')\n print('Cancelled.')\n return {'CANCELLED'}\n\n # Get stem material name.\n matname = settings.qsmStemMaterial\n\n # Check that values is not empty.\n if len(matname) == 0:\n # Warn that no material set.\n print('No stem material set.')\n matStem = None\n else:\n # Try to get material with given name.\n matStem = bpy.data.materials.get(matname)\n\n # Warn if not found.\n if not matStem:\n print('Stem material not found.')\n\n # Get branch material name.\n matname = settings.qsmBranchMaterial\n\n # Check that values is not empty.\n if len(matname) == 0:\n print('No branch material set.')\n matBranch = None\n else:\n # Try to get material with given name.\n matBranch = bpy.data.materials.get(matname)\n\n # Warn if not found.\n if not matBranch:\n print('Branch material not found.')\n\n # Mesh cylinder.\n if mode == 'mesh_cylinder':\n self.import_as_mesh_cylinders(context, file_path, EmptyParent, \n fBranchSeparation,\n matStem, matBranch)\n # Cylinder-level Bezier curves.\n elif mode == 'bezier_cylinder':\n self.import_as_bezier_cylinders(context, file_path, EmptyParent, \n fBranchSeparation,\n matStem, matBranch, BevelObject)\n # Branch-level Bezier curves.\n elif mode == 'bezier_branch':\n self.import_as_bezier_curves(context, file_path, EmptyParent, \n fBranchSeparation,\n matStem, matBranch, BevelObject)\n\n # Record end time.\n end = datetime.datetime.now()\n # Compute duration.\n delta = end - start\n # Format duration as string.\n timestr = \"{:.1f}\".format(delta.total_seconds())\n\n # Display import duration in the console.\n sys.stdout.write(\"Processing finished in \" + timestr + \" sec\" + \" \"*100+\"\\n\")\n sys.stdout.flush()\n\n return {'FINISHED'}\n\n\n# Operator for updating the colourmap information of a mesh based QSM object,\n# without re-importing the geometry.\nclass UpdateMeshQSMColorMap(bpy.types.Operator):\n \"\"\"Read colourmap values from file and update selected mesh object vertex colors\"\"\"\n\n bl_idname = \"qsm.update_colourmap\"\n bl_label = \"Update colourmap\"\n\n # Main function of the colourmap update operator.\n def execute(self,context):\n\n print('Importing QSM as Bezier cylinders.')\n\n # Record start time to compute duration.\n start = datetime.datetime.now()\n \n # Current scene for properties.\n scene = context.scene\n settings = scene.qsmImportSettings\n\n # Object to update should be selected.\n ob = bpy.context.selected_objects[0]\n\n # If no selection or selected object is not a mesh.\n if not ob:\n self.report({'ERROR_INVALID_INPUT'},'No object selected.')\n return {'CANCELLED'}\n elif ob.type != 'MESH':\n self.report({'ERROR_INVALID_INPUT'},'Selected object is not a mesh.')\n return {'CANCELLED'}\n\n # Path to input file.\n file_path = bpy.path.abspath(settings.qsm_file_path)\n\n # Check that file exists.\n if not os.path.isfile(file_path):\n self.report({'ERROR_INVALID_INPUT'},'No file with given path.')\n print('Cancelled.')\n return {'CANCELLED'}\n\n # Mesh data of selected object.\n me = ob.data\n # Create bmesh object for data modification.\n bm = bmesh.new()\n bm.from_mesh(me)\n\n # Get integer layer that contains cylinder ID information,\n # crucial for updating.\n layer = bm.verts.layers.int.get(\"CylinderId\")\n\n # If layer does not exist, unable to update.\n if not layer:\n self.report({'ERROR_INVALID_INPUT'},'Selected object does not contain cylinder id info.')\n return {'CANCELLED'}\n\n with open(file_path) as lines:\n \n # Count number of lines in file.\n NLine = sum(1 for line in lines)\n \n # Number of digits to use in object naming.\n NDigit = len(str(NLine))\n \n # Return to file beginning.\n lines.seek(0)\n\n # (Vector) array to hold colourmap values of each cylinder.\n CylinderColors = []\n \n # Iterate over file rows.\n for iLine, line in enumerate(lines):\n\n # Split cylinder parameter on current row.\n params = line.split()\n\n # Ignore rows with too few parameters.\n if len(params) < 9:\n continue\n \n # Display progress every 100th row.\n if iLine == 0 or iLine%100 == 1:\n msg = \"Processing line %i of %i\" % (iLine+1, NLine)\n sys.stdout.write(msg + chr(8) * len(msg))\n sys.stdout.flush()\n\n # Append new colourmap value to array.\n if len(params) > 11:\n CylinderColors.append(Vector((float(params[9]), float(params[10]), float(params[11]))))\n else:\n CylinderColors.append(float(params[9]))\n\n # Get colour layer that holds colourmap data.\n colors = bm.loops.layers.color.get(\"Color\")\n # If layer does not exist, create new.\n if not colors:\n colors = bm.loops.layers.color.new(\"Color\")\n \n # Iterate over vertices in mesh.\n for v in bm.verts:\n\n # Cylinder index is read from CylinderId layer.\n iCyl = v[layer]\n\n # Update colour layer with new colour value.\n for loop in v.link_loops:\n if len(CylinderColors[iCyl-1]) > 1:\n loop[colors] = CylinderColors[iCyl-1]\n else:\n loop[colors] = [CylinderColors[iCyl-1]] * 3\n\n # Update mesh data.\n bm.to_mesh(me)\n # Free bmesh.\n bm.free()\n\n # Record end time.\n end = datetime.datetime.now()\n # Compute duration.\n delta = end - start\n # Format duration as string.\n timestr = \"{:.1f}\".format(delta.total_seconds())\n\n # Display import duration in the console.\n sys.stdout.write(\"Processing finished in \" + timestr + \" sec\" + \" \"*len(msg)+\"\\n\")\n sys.stdout.flush()\n\n return {'FINISHED'}\n\n\ndef min_update(self, context):\n mi = context.scene.qsmImportSettings.qsmVertexCountMin\n ma = context.scene.qsmImportSettings.qsmVertexCountMax\n\n if mi > ma:\n context.scene.qsmImportSettings.qsmVertexCountMax = mi\n\ndef max_update(self, context):\n mi = context.scene.qsmImportSettings.qsmVertexCountMin\n ma = context.scene.qsmImportSettings.qsmVertexCountMax\n\n if mi > ma:\n context.scene.qsmImportSettings.qsmVertexCountMin = ma\n\nclass QsmImportSettings(bpy.types.PropertyGroup):\n\n # Import mode variable.\n qsmImportMode = bpy.props.EnumProperty \\\n (\n name=\"QSM Import Mode\",\n description=\"Import mode determines the resulting object type\",\n items=[\n (\"mesh_cylinder\", \"Mesh cylinder\", \"Cylinder-level mesh elements\"),\n (\"bezier_cylinder\", \"Bezier cylinder\", \"Cylinder-level Bezier curves\"),\n (\"bezier_branch\", \"Bezier branch\", \"Branch-level Bezier curves\"),\n ]\n )\n\n # Flag: add new bezier circle as bevel object\n qsmGenerateBevelObject = bpy.props.BoolProperty \\\n (\n name = \"Create bevel object\",\n description = \"If checked, a new object will be created as the bevel object of all branches.\",\n default = True,\n subtype = 'NONE',\n )\n\n # Bevel object for curve based modes.\n qsmBevelObject = bpy.props.StringProperty \\\n (\n name=\"Bevel Object\",\n description=\"Object that is asigned as the bevel object of each curve\",\n )\n\n # Name of the stem material.\n qsmStemMaterial = bpy.props.StringProperty \\\n (\n name=\"Stem material\",\n description=\"Material to apply to stem after import\"\n )\n\n # Name of the branch material.\n qsmBranchMaterial = bpy.props.StringProperty \\\n (\n name=\"Branch material\",\n description=\"Material to apply to branches after import\"\n )\n\n # Flag: separate object for each branch.\n qsmSeparation = bpy.props.BoolProperty \\\n (\n name = \"Branch separation\",\n description = \"If enabled each branch results in a separate object.\",\n default = False,\n subtype = 'NONE',\n )\n\n # Path to input file with cylinder parameters.\n qsm_file_path = bpy.props.StringProperty \\\n (\n name = \"Input file\",\n default = \"\",\n description = \"TXT-file containing the cylinder parameters\",\n subtype = 'FILE_PATH'\n )\n\n # Minimum cylinder ring vertex count.\n qsmVertexCountMin = bpy.props.IntProperty \\\n (\n name = \"Vertex count minimum\",\n default = 16,\n min = 3,\n max = 50,\n subtype = 'NONE',\n description = \"Minimum number of vertices in mesh cylinders\",\n update = min_update\n )\n\n # Minimum and maximum cylinder ring vertex count.\n qsmVertexCountMax = bpy.props.IntProperty \\\n (\n name = \"Vertex count maximum\",\n default = 16,\n min = 3,\n max = 50,\n subtype = 'NONE',\n description = \"Maximum number of vertices in mesh cylinders\",\n update = max_update\n )\n\nclass LeafModelImportSettings(bpy.types.PropertyGroup):\n\n # Dropdown: UV map types.\n importType = bpy.props.EnumProperty \\\n (\n name=\"Import format\",\n description=\"Format of import data\",\n items=[\n (\"obj\", \"Wavefront OBJ\", \"Wavefront OBJ\"),\n (\"obj_ext\", \"Exteded OBJ\", \"Exteded OBJ with transition parameters\"),\n ]\n )\n\n # Path to input file with leaf model parameters.\n leaf_model_file_path = bpy.props.StringProperty \\\n (\n name = \"Input file\",\n default = \"\",\n description = \"TXT-file containing the leaf parameters\",\n subtype = 'FILE_PATH'\n )\n\n # Name of the leaf material.\n leafModelMaterial = bpy.props.StringProperty \\\n (\n name=\"Material\",\n description=\"Material to apply to object(s) after import\"\n )\n\n # Leaf model vertex count.\n leaf_model_vertex_count = bpy.props.IntProperty \\\n (\n name = \"Vertex count\",\n default = 4,\n min = 3,\n max = 4,\n description = \"Number of vertices in a single leaf\",\n subtype = 'UNSIGNED'\n )\n\n # Flag: vertex color generation.\n vertexColorGeneration = bpy.props.BoolProperty \\\n (\n name = \"Assign vertex colors\",\n description = \"Input file contains color values that should be assigned to resulting vertices\",\n default = False,\n subtype = 'NONE',\n )\n\n vertexColorMode = bpy.props.EnumProperty \\\n (\n name=\"Color source\",\n description=\"Source of vertex colors\",\n items=[\n (\"from_file\", \"From file\", \"Read from file\"),\n (\"random\", \"Randomize\", \"Randomize values\"),\n ]\n )\n\n # Flag: shape key generation for animation.\n shapekeyGeneration = bpy.props.BoolProperty \\\n (\n name = \"Generate shape keys\",\n description = \"Generate shapekeys for growth animation\",\n default = False,\n subtype = 'NONE',\n )\n\n # Leaf UV\n\n # Flag: generate UV map for leaves.\n leafUvGeneration = bpy.props.BoolProperty \\\n (\n name = \"Generate UV map\",\n description = \"Generate UV map for imported leaves.\",\n default = False,\n subtype = 'NONE',\n )\n\n # Dropdown: UV map types.\n leafUvType = bpy.props.EnumProperty \\\n (\n name=\"UV map type\",\n description=\"Leaf UV map type\",\n items=[\n (\"isosceles_triangle\", \"Isosceles triangle\", \"Isosceles triangle\"),\n (\"square\", \"Unit square\", \"Unit square\"),\n (\"custom\", \"Custom\", \"Custom vertices from object\"),\n ]\n )\n\n # Mesh to base UV map on.\n leafUvSource = bpy.props.StringProperty \\\n (\n name=\"UV mesh data\",\n description=\"Object to base the generated UV map on.\",\n )\n\ndef register():\n\n # QSM settings class.\n bpy.utils.register_class(QsmImportSettings)\n\n # Leaf model settings class.\n bpy.utils.register_class(LeafModelImportSettings)\n\n # Pointer to store all QSM import settings.\n bpy.types.Scene.qsmImportSettings = bpy.props.PointerProperty \\\n (\n type=QsmImportSettings\n )\n\n # Pointer to store all leaf model import settings.\n bpy.types.Scene.leafModelImportSettings = bpy.props.PointerProperty \\\n (\n type=LeafModelImportSettings\n )\n\n # Register classes.\n\n # Update colourmap operator.\n bpy.utils.register_class(UpdateMeshQSMColorMap)\n # QSM import operator.\n bpy.utils.register_class(ImportQSM)\n # Leaf import operator.\n bpy.utils.register_class(ImportLeafModel)\n # QSM panel\n bpy.utils.register_class(QSMPanel)\n # Leaf panel.\n bpy.utils.register_class(LeafModelPanel)\n\n\n\n\n\n\n\ndef unregister():\n # Delete custom properties from scene.\n del bpy.types.Scene.qsmImportSettings\n del bpy.types.Scene.leafModelImportSettings\n\n # Unregister classes.\n bpy.utils.unregister_class(LeafModelPanel)\n bpy.utils.unregister_class(QSMPanel)\n bpy.utils.unregister_class(ImportQSM)\n bpy.utils.unregister_class(UpdateMeshQSMColorMap)\n bpy.utils.unregister_class(ImportLeafModel)\n bpy.utils.unregister_class(QsmImportSettings)\n bpy.utils.unregister_class(LeafModelImportSettings)\n\n\n\n\n\n\nif __name__ == \"__main__\":\n register()\n","sub_path":"All_In_One/addons/qsm_leaf_import.py","file_name":"qsm_leaf_import.py","file_ext":"py","file_size_in_byte":69782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"216554839","text":"from datetime import datetime\r\nfrom django import forms\r\nfrom django.contrib.auth.models import User\r\nfrom post.models import Post, Comment, Reply, Tag\r\nfrom django.utils.html import strip_tags\r\n\r\nclass PostFullForm(forms.ModelForm):\r\n author = forms.ModelChoiceField(queryset=User.objects.all(),required=False)\r\n title = forms.CharField(min_length=6,required=True)\r\n text = forms.CharField(required=True)\r\n cover = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': False}),required=False)\r\n status = forms.CharField(min_length=1,max_length=1,required=True)\r\n tags = forms.ModelChoiceField(queryset=User.objects.all(),required=False)\r\n notes = forms.CharField(required=False)\r\n\r\n class Meta:\r\n model = Post\r\n fields = ('title','author','text','cover','status','tags','notes')\r\n\r\nclass SlugForm(forms.Form):\r\n slug = forms.CharField(required=True)\r\n\r\nclass PostForm(forms.ModelForm):\r\n title = forms.CharField(min_length=6,required=True)\r\n text = forms.CharField(required=True)\r\n status = forms.CharField(min_length=1,max_length=1,required=True)\r\n cover = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': False}),required=False)\r\n author = forms.ModelChoiceField(queryset=User.objects.all(),required=False)\r\n\r\n def clean_text(self):\r\n text = strip_tags(self.cleaned_data['text'])\r\n if len(text) is 0:\r\n raise forms.ValidationError(\"This field is required.\")\r\n elif len(text) < 30:\r\n raise forms.ValidationError(\"Ensure this value has at least 30 characters (it has \"+str(len(text))+\").\")\r\n return self.cleaned_data['text']\r\n\r\n class Meta:\r\n model = Post\r\n fields = ('title','text','status','cover','author','notes')\r\n\r\nclass AddCommentForm(forms.Form):\r\n text = forms.CharField(label='text')\r\n class Meta:\r\n model = Comment\r\n fields = ('text')\r\n\r\nclass AddReplyForm(forms.Form):\r\n text = forms.CharField(label='text')\r\n class Meta:\r\n model = Reply\r\n fields = ('text')\r\n\r\nclass CommentForm(forms.Form):\r\n comment_for = forms.IntegerField(widget=forms.HiddenInput())\r\n text = forms.CharField(label='text',)\r\n created_on = forms.DateField(label='created_on',)\r\n username = forms.CharField(label='username',)\r\n\r\nclass ReplyForm(forms.Form):\r\n comment_for = forms.IntegerField(widget=forms.HiddenInput())\r\n comment_by = forms.IntegerField(widget=forms.HiddenInput())\r\n text = forms.CharField(label='text',)\r\n created_on = forms.DateField(label='created_on',)\r\n username = forms.CharField(label='username',)\r\n\r\nclass SearchPostForm(forms.Form):\r\n slug = forms.CharField(label='slug',widget=forms.TextInput(attrs={'class' : 'form-control','placeholder' : 'Slug'}))\r\n\r\nclass ReportForm(forms.Form):\r\n report=forms.CharField(widget=forms.Textarea(attrs={'class' : 'form-control','placeholder':'Enter Report Description'}))\r\n","sub_path":"post/api/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"589823568","text":"from tqdm import tqdm\nfrom collections import Counter\nfrom itertools import combinations\nfrom nltk.stem import PorterStemmer\nimport joblib \nfrom sklearn.metrics import silhouette_score, davies_bouldin_score\nfrom sklearn.metrics.pairwise import euclidean_distances\n\nimport imp\nimport copy\nimport pickle\nimport multiprocessing\n\nimport numpy as np\nimport pandas as pd\nimport utils as my_utils\nimport ELJST_script_unigram as lda\nimport matplotlib.pyplot as plt\n \ngrid = [['amazon_home_20000', 'bert_attention_all', 5],\n ['amazon_home_20000', 'bert_attention_all', 25],\n ['amazon_home_20000', 'bert_attention_all', 50]]\n\n\ndef process_sampler(inp):\n \n dataset_name = inp[0]\n embedding_name = inp[1]\n n_topics = inp[2]\n \n print(dataset_name, embedding_name, \"entered\")\n\n dataset = pd.read_pickle(\"datasets/\" + dataset_name + \"_dataset\")\n \n min_df = 5\n max_df = .5\n maxIters = 20\n\n beta = .01\n gamma = 10\n lambda_param = 1.0\n n_sentiment = dataset.sentiment.unique().shape[0]\n\n alpha = 0.1/n_topics * np.ones(n_topics)\n gamma = [gamma/(n_topics*n_sentiment)]*n_sentiment\n\n similar_words = []\n \n if embedding_name == \"noembeds\":\n print(dataset_name+\"_\"+embedding_name, \"Created Embeddings\")\n similar_words = [{} for i in range(dataset.shape[0])]\n else:\n print(dataset_name+\"_\"+embedding_name, \"Loaded Embeddings\")\n similar_words = pickle.load(open(\"resources/\" + dataset_name + \"_\" + embedding_name + \".pickle\",\"rb\"))\n \n for s in similar_words:\n for i in s.keys():\n k = list(set(s[i]))\n if i in k:\n k.remove(i)\n s[i] = k\n\n sampler = lda.SentimentLDAGibbsSampler(n_topics, alpha, beta, gamma, numSentiments=n_sentiment, SentimentRange = n_sentiment, max_df = max_df, min_df = min_df, lambda_param = lambda_param)\n \n sampler._initialize_(reviews = dataset.text.tolist(), labels = dataset.sentiment.tolist())\n\n try:\n sampler.run(name=dataset_name+\"_\"+embedding_name+\"_\"+str(n_topics)+\"topics\", reviews=dataset.text.tolist(), labels=dataset.sentiment.tolist(), \n similar_words=similar_words, mrf=True, maxIters=maxIters, debug=False)\n\n joblib.dump(sampler, \"dumps/Uni_sampler_\" + dataset_name + \"_\" + embedding_name+\"_\"+str(n_topics)+\"topics\")\n print(dataset_name+\"_\"+embedding_name+\"_\"+str(n_topics)+\"topics\", \"dumped\") \n except Exception as e:\n print(e)\n print(dataset_name+\"_\"+embedding_name+\"_\"+str(n_topics)+\"topics\", \"failed\")\n \npool = multiprocessing.Pool(40)\npool.map(process_sampler, grid)\npool.close()\n\n# process_sampler(grid[0])","sub_path":"nosampler_uni.py","file_name":"nosampler_uni.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"486992205","text":"#!/usr/bin/env python3\n'''\nSHORT DESCRIPTION\nUse the GMT 6 program earthtide to create a solid earth tide map of the area\n described by the given georeferenced file.\n\nFUTURE IMPROVEMENTS\n\nTESTING STATUS\nTested.\n'''\n\n### IMPORT MODULES ---\nimport argparse\nimport os\nimport matplotlib.pyplot as plt\nfrom IOsupport import load_gdal_dataset, load_gdal_datasets\nfrom GeoFormatting import get_raster_size, parse_transform\nfrom Viewing import raster_multiplot\n\n\n### PARSER ---\nDescription = '''Create a solid earth tide map of the area covered by a given map data set\nusing the GMT 6 program earthtide.\n\nFormat solid Earth command\ne.g., \"gmt earthtide -T2018-06-18T12:00:00 -GXXsolidtides_%s.grd -Ce,n,v -R80/90/30/40 -I15s\"\n'''\n\nExamples = ''''''\n\n\ndef createParser():\n parser = argparse.ArgumentParser(description=Description,\n formatter_class=argparse.RawTextHelpFormatter, epilog=Examples)\n\n InputArgs = parser.add_argument_group('INPUTS')\n InputArgs.add_argument('-f','--filename', dest='dsName', type=str, required=True,\n help='Filename of file for which tides are to be calculated.')\n InputArgs.add_argument('-d','--date', dest='date', type=str, required=True,\n help='Date on which the tides are to be calculated (fmt YYYYMMDD).')\n InputArgs.add_argument('-t','--time', dest='time', type=str, required=True,\n help='Time at which the tides are to be calculated (fmt HHmmSS).')\n\n OutputArgs = parser.add_argument_group('OUTPUTS')\n OutputArgs.add_argument('-o','--outName', dest='outName', type=str, default='Out', \n help='Output name.')\n OutputArgs.add_argument('-v','--verbose', dest='verbose', action='store_true', \n help='Verbose mode.')\n OutputArgs.add_argument('-p','--plot', dest='plot', action='store_true', \n help='Plot inputs and outputs.')\n return parser\n\ndef cmdParser(iargs = None):\n parser = createParser()\n return parser.parse_args(args=iargs)\n\n\n\n### TIDE MAP ---\nclass create_tide_map:\n def __init__(self, dsName, date, time, outName, verbose=False):\n '''\n Create one or more tide maps using GMT 6's earthtide functionality.\n This class \n\n Inherits\n os\n IOsupport: load_gdal_dataset, load_gdal_datasets\n GeoFormatting: get_raster_size, parse_transform\n Viewing: raster_multiplot\n '''\n # Parameters\n self.verbose = verbose\n\n # Extract spatial parameters from data set\n self.__get_spatial_data__(dsName)\n\n # Format date and time\n self.__format_date_time__(date, time)\n\n # Format outname\n self.__format_outname__(outName)\n\n # Create tide maps\n self.__create_tide_maps__()\n\n\n def __get_spatial_data__(self, dsName):\n '''\n Retrieve the necessary spatial information (bounds and resolution) from\n the specified GDAL-compatible data set.\n '''\n if self.verbose == True: print('Retrieving data set bounds and resolution')\n\n # Load GDAL data set\n DS = load_gdal_dataset(dsName)\n tnsf = DS.GetGeoTransform()\n M, N = get_raster_size(DS)\n\n # Parse geographic info\n geo = parse_transform(tnsf, M, N, verbose=inps.verbose)\n\n # Format geo string\n self.geoStr = '{left:f}/{right:f}/{bottom:f}/{top:f}'.format(**geo.__dict__)\n\n # Format resolution string\n self.resStr = '{:f}'.format(geo.dx)\n\n # Report if requested\n if self.verbose == True:\n print('--> Geo string: {:s}'.format(self.geoStr))\n print('--> Res string: {:s}'.format(self.resStr))\n\n\n def __format_date_time__(self, date, time):\n '''\n Format date into YYYY-MM-DD and time into HH:MM:SS format.\n '''\n if self.verbose == True: print('Formatting date and time')\n\n # Format date\n date = '{:s}-{:s}-{:s}'.format(date[0:4], date[4:6], date[6:8])\n\n # Format time\n time = '{:s}:{:s}:{:s}'.format(time[0:2], time[2:4], time[4:6])\n\n # Format datetime string\n self.datetimeStr = '{:s}T{:s}'.format(date, time)\n\n # Report if requested\n if self.verbose == True:\n print('date: {:s}\\ntime: {:s}'.format(date, time))\n print('--> Datetime string: {:s}'.format(self.datetimeStr))\n\n\n def __format_outname__(self, outName):\n '''\n Convert output name to GMT format.\n '''\n if self.verbose == True: print('Formatting outname')\n\n # Format outname\n self.outNameStr = '{:s}_%s.grd'.format(outName)\n\n # Report if requested\n if self.verbose == True:\n print('--> Output string: {:s}'.format(self.outNameStr))\n\n\n def __create_tide_maps__(self):\n '''\n Leverage GMT 6 to create solid Earth tide maps.\n '''\n if self.verbose == True: print('Creating solid Earth tide maps')\n \n # Format command string\n commandStr = 'gmt earthtide -T{datetimeStr:s} -G{outNameStr:s} -R{geoStr:s} -I{resStr:s} -Ce,n,v'.\\\n format(**self.__dict__)\n\n # Report if requested\n if self.verbose == True: print('full command:\\n{:s}'.format(commandStr))\n\n # Run command\n os.system(commandStr)\n\n # Report completion if requested\n if self.verbose == True: print('Tide maps generated.')\n\n\n def plot(self):\n '''\n Plot output tide maps.\n '''\n # Format tide map names\n etide = self.outNameStr.replace('%s', 'e')\n ntide = self.outNameStr.replace('%s', 'n')\n vtide = self.outNameStr.replace('%s', 'v')\n\n # Load data sets\n datasets = load_gdal_datasets([etide, ntide, vtide])\n\n # Plot data sets\n raster_multiplot(datasets.values(), ncols=3,\n cbarOrient='horizontal',\n titles=['east', 'north', 'vertical'])\n\n\n\n### MAIN ---\nif __name__ == '__main__':\n ## Inputs\n # Gather arguments\n inps = cmdParser()\n\n\n ## Tide maps\n tideMap = create_tide_map(dsName=inps.dsName,\n date=inps.date, time=inps.time,\n outName=inps.outName,\n verbose=inps.verbose)\n\n # Plot if requested\n if inps.plot == True:\n tideMap.plot()\n\n plt.show()","sub_path":"bin/compute_earthtide.py","file_name":"compute_earthtide.py","file_ext":"py","file_size_in_byte":6224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"148686498","text":"\"\"\"\n509. Fibonacci Number\n\nThe Fibonacci numbers, commonly denoted F(n) form a sequence, called the \nFibonacci sequence, such that each number is the sum of the two preceding ones,\nstarting from 0 and 1. That is,\n F(0) = 0, F(1) = 1\n F(N) = F(N - 1) + F(N - 2), for N > 1.\nGiven N, calculate F(N).\n\nExample 1:\nInput: 2\nOutput: 1\nExplanation: F(2) = F(1) + F(0) = 1 + 0 = 1.\n\nExample 2:\nInput: 3\nOutput: 2\nExplanation: F(3) = F(2) + F(1) = 1 + 1 = 2.\n\nExample 3:\nInput: 4\nOutput: 3\nExplanation: F(4) = F(3) + F(2) = 2 + 1 = 3.\n \nNote:\n0 ≤ N ≤ 30.\n\nSubmission Info:\n Runtime: 32ms, faster than 94.66%\n Memory Usage: 13.1MB, less than 73.69%\n\"\"\"\n\nclass Solution:\n def fib(self, N: int) -> int:\n fibonacci = [1, 1, 0]\n \n if N <= 2:\n return fibonacci[N - 1]\n \n for i in range(2, N):\n fibonacci[2] = fibonacci[0] + fibonacci[1]\n fibonacci[0] = fibonacci[1]\n fibonacci[1] = fibonacci[2]\n return fibonacci[-1]","sub_path":"0509. Fibonacci Number.py","file_name":"0509. Fibonacci Number.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"617043465","text":"name = input('Enter your name:')\nfor i in name:\n print(i.upper())\nsum = ''\ncondition = True\nwhile condition:\n string = input('Please enter any string: ')\n if string!='quit':\n sum+=string\n \n elif string=='quit':\n print(sum)\n break\n","sub_path":"loops/example4.py","file_name":"example4.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"370334579","text":"import adv_test\nimport adv\nfrom slot.a import *\n\ndef module():\n return Rodrigo\n\nclass Rodrigo(adv.Adv):\n a1 = ('a',0.08,'hp70')\n conf ={}\n conf['slot.a'] = TSO()+BN()\n\n\nif __name__ == '__main__':\n conf = {}\n conf['acl'] = \"\"\"\n `s1\n `s2\n `fs, seq=3 and cancel\n \"\"\"\n adv_test.test(module(), conf, verbose=0)\n\n","sub_path":"adv/rodrigo.py","file_name":"rodrigo.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"12157813","text":"from flask import Flask, jsonify, request\nfrom database import db_session, Produto, Tag\nfrom os import getenv\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = getenv('SECRET_KEY')\n\n\n@app.route('/find')\ndef find():\n from clarifai.rest import ClarifaiApp\n\n url = request.args['imageUrl']\n app = ClarifaiApp(api_key=getenv('CLARIFAI_KEY'))\n\n model = app.models.get(model_id='produtos')\n response = model.predict_by_url(url=url)\n concept = response['outputs'][0]['data']['concepts']\n concept = concept[0]\n\n if concept['value'] < 0.4:\n return jsonify({\n \"redirect_to_blocks\": [\"return\"]\n })\n\n obj = db_session.query(Produto).filter_by(clarifai_id=concept['name']).first()\n resp = {\n \"messages\": obj.message\n }\n return jsonify(resp)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"553335377","text":"\nimport sqlite3\nfrom os.path import join, split\n\ndef dictionary_factory(cursor, row):\n \"\"\"\n Create a dictionary from rows in a cursor result.\n The keys will be the column names.\n :param cursor: A cursor from which a query row has just been fetched\n :param row: The query row that was fetched\n :return: A dictionary associating column names to values\n \"\"\"\n col_names = [d[0].lower() for d in cursor.description]\n return dict(zip(col_names, row))\n\ndef get_connection():\n dirname = split(__file__)[0]\n filename = join(dirname, \"measures.sqlite\")\n conn = sqlite3.connect(filename)\n conn.row_factory = dictionary_factory # note: no parentheses\n return conn\n\n\n\ndef do_command(cmd, args=[]):\n conn = get_connection()\n try:\n crs = conn.cursor()\n crs.execute(cmd, args)\n rtval = crs.fetchall()\n conn.commit()\n return rtval\n finally:\n conn.close()\n\ndef do_insert(cmd, args=[]):\n conn = get_connection()\n try:\n crs = conn.cursor()\n crs.execute(cmd, args)\n rtval = crs.lastrowid\n conn.commit()\n return rtval\n finally:\n conn.close()\n\n# def do_command_no_return(cmd, args=[]):\n# conn = get_connection()\n# try:\n# crs = conn.cursor()\n# crs.execute(cmd, args)\n# conn.commit()\n# finally:\n# conn.close()\n","sub_path":"Assignment 6/Resources/assign06_test/db_util/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"400831046","text":"import os\nimport numpy as np\nimport pandas as pd\nimport lightgbm as lgb\nfrom .model import Model\nfrom .util import Util\n\n# LightGBM\nclass ModelLGB(Model):\n\n def train(self, tr_x, tr_y, va_x=None, va_y=None):\n # データのセット\n isvalid = va_x is not None\n lgb_train = lgb.Dataset(tr_x, tr_y)\n if isvalid:\n lgb_valid = lgb.Dataset(va_x, va_y)\n\n # ハイパーパラメータの設定\n params = dict(self.params)\n # num_round = params.pop('num_round')\n\n # 学習\n if isvalid:\n self.model = lgb.train(params, lgb_train, valid_sets=lgb_valid)\n else:\n self.model = lgb.train(params, lgb_train)\n\n # if isvalid:\n # early_stopping_rounds = params.pop('early_stopping_rounds')\n # watchlist = [(dtrain, 'train'), (dvalid, 'eval')]\n # self.model = xgb.train(params, dtrain, num_round, evals=watchlist,\n # early_stopping_rounds=early_stopping_rounds)\n # else:\n # watchlist = [(dtrain, 'train')]\n # self.model = xgb.train(params, dtrain, num_round, evals=watchlist)\n\n\n def predict(self, te_x):\n return self.model.predict(te_x, num_iteration=self.model.best_iteration)\n\n\n def save_model(self):\n model_path = os.path.join('../models/lgb', f'{self.run_fold_name}.model')\n os.makedirs(os.path.dirname(model_path), exist_ok=True)\n Util.dump(self.model, model_path)\n\n\n def load_model(self):\n model_path = os.path.join('../models/lgb', f'{self.run_fold_name}.model')\n self.model = Util.load(model_path)","sub_path":"scripts/sample/models/model_lgb.py","file_name":"model_lgb.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"148832015","text":"import os\n\ndef file_reader():\n file_open = open(\"file.txt\",\"r\")\n files = file_open.read().splitlines()\n file_open.close()\n del files[-1]\n return files\n\ndef file_writer():\n os.system('ls /tmp> file.txt')\nfile_writer()\nfor i in file_reader():\n print(i)\n","sub_path":"list_file.py","file_name":"list_file.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"435632354","text":"#########################################################################\n# #\n# HexGrid Constructor (Python Version) #\n# This constructor script calculates and generates the hexgrid #\n# temperature layer on top of the map. #\n# Due to performance and function duration, the original function #\n# is divided into smaller parts. Easier to monitor and add logs. #\n# #\n#########################################################################\nimport turfpy.measurement as turf\nfrom turfpy.transformation import union\nfrom geojson import Feature, Polygon, FeatureCollection, Point\nimport datetime as dte\nimport json, math\n\n\n# get default hexgrid\ndef get_hexgrid(filename):\n\n # filepath = 'gsod/posts/blanks/' + filename\n # filepath = 'BatchCompute/data' + filename\n with open(filename, 'r') as readfile:\n hexgrid = json.load(readfile)\n\n return hexgrid\n\n\n# get the default hexgrid, compute the polygons and centroids\ndef hexgrid_constructor(bbox, cellSide, stations, levels, mid_lat):\n\n # set variables, declare hexGrid\n bbox = ','.join([str(b) for b in bbox]).replace(',', '_')\n filename = 'blank_HexGrid' + bbox + 'r' + str(cellSide) + '.json'\n hexGrid = get_hexgrid(filename)\n centroids = []\n hexGridDict = {}\n tempDict = {}\n\n # loop thru hexgrid to get centroids\n s1 = dte.datetime.now()\n for hex in hexGrid['features']:\n centroid_id = 'P' + ','.join([str(round(c, 6)) for c in hex['centroid']['geometry']['coordinates']])\n centroid_id = centroid_id.replace('P-', 'N').replace(',', '_').replace('-', 'n')\n # print(centroid_id)\n hexGridDict[centroid_id] = {\n 'station': {'0': 0},\n 'rings': [],\n }\n tempDict[centroid_id] = {\"temperature\": -1}\n centroids.append(Feature(geometry=Point(hex['centroid']['geometry']['coordinates'])))\n centroid_set = FeatureCollection(centroids)\n e1 = dte.datetime.now()\n\n # loop through stations and assign it to the hexGrid\n station_centroids = []\n print(\"Set Hexagon Tiles:\", str((e1 - s1).total_seconds()), \"seconds\")\n s2 = dte.datetime.now()\n print(\"Number of Stations:\", len(stations))\n for idx, station in enumerate(stations):\n station_coord = Feature(geometry=Point(stations[idx]['geometry']['coordinates']))\n\n # print something every 100 to show it is still running\n if idx % 100 == 0:\n print(\"Centroids: \", len(station_centroids), \", idx: \", idx)\n\n lat = stations[idx]['geometry']['coordinates'][1]\n cellSide_convert = convert_distance(cellSide, lat, mid_lat) * 1.05 # 5% error\n closest_hex = find_closest_polygon(station_coord, centroid_set, cellSide_convert)\n if closest_hex['properties']['distanceToPoint'] > (cellSide * 2):\n pass\n else:\n # assign that hex the station\n coord = 'P' + ','.join([str(round(c, 6)) for c in closest_hex['geometry']['coordinates']])\n coord = coord.replace('P-', 'N').replace(',', '_').replace('-', 'n')\n # print(hexGridDict[coord])\n hexGridDict[coord]['station'] = station\n tempDict[coord]['temperature'] = stations[idx]['properties']['TMAX'] # TMAX USED HERE #############!!!!!!\n station_centroids.append(Feature(geometry=Point(closest_hex['geometry']['coordinates'])))\n\n e2 = dte.datetime.now()\n print(\"Assign Stations:\", str((e2 - s2).total_seconds()), \"seconds\")\n\n # add rings\n s1 = dte.datetime.now()\n for idx, hex in enumerate(hexGridDict):\n stations_set = FeatureCollection(station_centroids.copy())\n\n centroid_coord = hex.replace('N', '-').replace('P', '').replace('_', ',').replace('n', '-')\n centroid_coord = [float(c) for c in centroid_coord.split(',')]\n\n # print something every 1000 to show it is still running\n if idx % 1000 == 0:\n print(\"Ring Searching: \", idx)\n\n # get all the '0's and ignore the stations\n if '0' in hexGridDict[hex]['station']:\n # get closest stations in recursive function\n rings = get_closest_stations(centroid_coord, stations_set, tempDict, cellSide, mid_lat, 0, 1, levels)\n # print(len(stations_set['features']), idx)\n # if idx == 0:\n # print(\"First Coord:\", centroid_coord)\n if not rings:\n # no results\n # if idx == 12417:\n # print('No Results', rings, centroid_coord)\n pass\n else:\n hexGridDict[hex]['rings'] = rings\n # print('Rings', idx, centroid_coord, hexGridDict[hex]['rings']) # , stations_set)\n e1 = dte.datetime.now()\n print(\"Adding Rings:\", str((e1 - s1).total_seconds()), \"seconds\")\n\n # re - calculate temps and deploy the rings, then stations\n # heat_check = 0\n for idx, hex in enumerate(hexGridDict):\n if ('0' in hexGridDict[hex]['station']) and (len(hexGridDict[hex]['rings']) > 0):\n\n # get \"highest\" ring_level, e.g. level 1 is highest\n ring_level = hexGridDict[hex]['rings'][0]['ring_level']\n acc_temp = 0\n total_acc = 0\n\n # average out the overlaps\n for ring in hexGridDict[hex]['rings']:\n if ring['ring_level'] == ring_level:\n acc_temp += ring['temperature']\n total_acc += 1\n avg_temp = acc_temp / total_acc\n\n hexGrid['features'][idx]['properties'] = {\n 'temperature': avg_temp\n }\n elif not ('0' in hexGridDict[hex]['station']):\n # this is a weather station\n hexGrid['features'][idx]['properties'] = hexGridDict[hex]['station']['properties'].copy()\n hexGrid['features'][idx]['properties']['temperature'] = \\\n (hexGrid['features'][idx]['properties']['TMAX'] + 40) / 80\n else:\n # this is not weather station and outside all rings\n '''\n if heat_check == 0:\n heat_check += 1\n print(\"Heat Check\")\n '''\n hexGrid['features'][idx]['properties'] = {\n 'temperature': -1\n }\n e2 = dte.datetime.now()\n print(\"Deploying Temperatures:\", str((e2 - e1).total_seconds()), \"seconds\")\n\n return hexGrid\n\n\n# ACTUAL nearest point -- edited the source code from turfpy library\ndef actual_nearest_point(target_point: Feature, points: FeatureCollection) -> Feature:\n\n if not target_point:\n raise Exception(\"target_point is required\")\n\n if not points:\n raise Exception(\"points is required\")\n\n min_dist = float(\"inf\")\n best_feature_index = 0\n\n def _callback_feature_each(pt, feature_index):\n nonlocal min_dist, best_feature_index\n distance_to_point = turf.distance(target_point, pt)\n # print(distance_to_point)\n if float(distance_to_point) < min_dist:\n best_feature_index = feature_index\n min_dist = distance_to_point\n # print(min_dist)\n return True\n\n actual_feature_each(points, _callback_feature_each)\n\n nearest = points[\"features\"][best_feature_index]\n nearest[\"properties\"][\"featureIndex\"] = best_feature_index\n nearest[\"properties\"][\"distanceToPoint\"] = min_dist\n return nearest\n\n\n# ACTUAL feature each loop -- edited the source code from turfpy library\ndef actual_feature_each(geojson, callback):\n if geojson[\"type\"] == \"Feature\":\n callback(geojson, 0)\n elif geojson[\"type\"] == \"FeatureCollection\":\n for i in range(0, len(geojson[\"features\"])):\n # print(callback(geojson[\"features\"][i], i))\n if not callback(geojson[\"features\"][i], i):\n break\n\n\n# adated from actual_nearest_point -- find the first polygon that it is in\ndef find_closest_polygon(target_point: Feature, points: FeatureCollection, cellSide) -> Feature:\n\n if not target_point:\n raise Exception(\"target_point is required\")\n\n if not points:\n raise Exception(\"points is required\")\n\n min_dist = 10000000 # cellSide * 1.05\n best_feature_index = 0\n\n def _callback_feature_each(pt, feature_index):\n nonlocal min_dist, best_feature_index\n distance_to_point = turf.distance(target_point, pt)\n # print(distance_to_point)\n if float(distance_to_point) <= cellSide:\n best_feature_index = feature_index\n min_dist = distance_to_point\n # print(min_dist)\n return False # return False will break the loop once inside a polygon\n return True\n\n actual_feature_each(points, _callback_feature_each)\n\n nearest = points[\"features\"][best_feature_index]\n nearest[\"properties\"][\"featureIndex\"] = best_feature_index\n nearest[\"properties\"][\"distanceToPoint\"] = min_dist\n return nearest\n\n\n# adated from actual_nearest_point -- find the next closest ring polygon\ndef find_next_ring(target_point: Feature, points: FeatureCollection, min_dist, max_dist) -> Feature:\n\n if not target_point:\n raise Exception(\"target_point is required\")\n\n if not points:\n raise Exception(\"points is required\")\n\n found_dist = 10000000 # something super big, float(\"inf\")\n best_feature_index = 0\n\n def _callback_feature_each(pt, feature_index):\n nonlocal found_dist, best_feature_index\n distance_to_point = turf.distance(target_point, pt)\n # print(distance_to_point)\n if (float(distance_to_point) >= min_dist) and (float(distance_to_point) < max_dist):\n best_feature_index = feature_index\n found_dist = distance_to_point\n # print(min_dist)\n return False # return False will break the loop once inside a polygon\n return True\n\n actual_feature_each(points, _callback_feature_each)\n\n nearest = points[\"features\"][best_feature_index]\n nearest[\"properties\"][\"featureIndex\"] = best_feature_index\n nearest[\"properties\"][\"distanceToPoint\"] = found_dist\n return nearest\n\n\n# Get Closest Weather Stations -- recursive\ndef get_closest_stations(coord, the_stations, tempDict, cellSide, mid_lat, loops, level, max_level):\n\n '''\n if level == 1:\n adj_min_dist = convert_distance(cellSide, coord[1], mid_lat)\n adj_max_dist = convert_distance(cellSide * math.sqrt(3) * level, coord[1], mid_lat)\n else:\n '''\n # above or below mid_lat\n hyp_dist = cellSide * math.sqrt(3) * level\n if coord[1] >= mid_lat:\n # above mid_lat -- convert shortest distance\n adj_max_dist = max(hyp_dist, convert_distance(hyp_dist, coord[1], mid_lat)) # hyp_dist\n adj_min_dist = min(cellSide * level, convert_distance(cellSide * level, coord[1], mid_lat))\n else:\n adj_max_dist = max(hyp_dist, convert_distance(hyp_dist, coord[1], mid_lat))\n adj_min_dist = convert_distance(cellSide * level, coord[1], mid_lat)\n\n # account for 2% error\n get_min_dist = float(round_decimals_down(min(adj_max_dist, adj_min_dist), 6)) * 0.98\n get_max_dist = float(round(max(adj_max_dist, adj_min_dist), 6)) * 1.02\n\n # find next ring\n closest_station = find_next_ring(coord, the_stations, get_min_dist, get_max_dist)\n # closest_station = actual_nearest_point(coord, the_stations)\n\n # get feature index and distance\n feature_index = closest_station['properties']['featureIndex']\n distance = closest_station['properties']['distanceToPoint']\n new_stations = the_stations.copy()\n\n # DEBUG:\n '''\n if (coord[0] == -125.773062) and (coord[1] == 24.149234):\n print(closest_station, distance, level, get_min_dist, get_max_dist, len(new_stations['features']))\n if (coord[0] == -123.710315) and (coord[1] == 44.009509):\n f1 = Feature(geometry=Point((-123.710315, 44.009509)))\n f2 = Feature(geometry=Point((-123.710315, 43.775858)))\n get_distance = turf.distance(f1, f2)\n print(feature_index, get_distance, level, get_min_dist, get_max_dist, len(new_stations['features']))\n \n if (coord[0] == -96.894608) and (coord[1] == 33.728896):\n f1 = Feature(geometry=Point((-96.636765, 33.845721)))\n f2 = Feature(geometry=Point((-96.894608, 33.728896)))\n get_distance = turf.distance(f1, f2)\n print(feature_index, get_distance, level, get_min_dist, get_max_dist, len(new_stations['features']))\n '''\n\n # get station coord to assign temperature\n station_coord = 'P' + ','.join([str(round(c, 6)) for c in closest_station['geometry']['coordinates']])\n station_coord = station_coord.replace('P-', 'N').replace(',', '_').replace('-', 'n')\n\n if (loops > 7) or (level > max_level):\n return False\n elif (float(round(distance, 6)) < get_max_dist) and \\\n (float(round(distance, 6)) >= get_min_dist) and (len(new_stations['features']) > 1):\n # remove that from list\n new_stations['features'].pop(feature_index)\n\n # recursive call to get next closest station\n next_closest = get_closest_stations(coord, new_stations, tempDict, cellSide, mid_lat, loops+1, level, max_level)\n coord_dict = [{\n 'ring_level': level,\n 'temperature': (tempDict[station_coord]['temperature'] + 40 + (-1 * level)) / 80\n }]\n # print(coord_dict, coord, distance, get_min_dist, get_max_dist)\n\n if not next_closest:\n pass\n else:\n coord_dict.extend(next_closest)\n return coord_dict\n elif loops <= 7:\n # else if loops less than 7 but not satisfy above -- increase the level\n next_closest = get_closest_stations(coord, new_stations, tempDict, cellSide,\n mid_lat, loops + 1, level + 1, max_level)\n # don't process coord_dict; just next_closest if not false\n if not next_closest:\n return False\n else:\n return next_closest\n else:\n return False\n\n\n# convert the distance based on the latitude and reference latitude\ndef convert_distance(distance, lat, middle_lat):\n\n # find pixel distance of the distance at the middle latitude\n \n km_per_pixel = 40075 * math.cos(middle_lat * math.pi / 180) / math.pow(2, 12)\n pixel_distance = distance / km_per_pixel\n\n # now use pixel distance to convert it to the distance at the needed latitude\n km_per_pixel = 40075 * math.cos(lat * math.pi / 180) / math.pow(2, 12)\n return pixel_distance * km_per_pixel\n\n\n# round decimals down\ndef round_decimals_down(number:float, decimals:int=2):\n \"\"\"\n Returns a value rounded down to a specific number of decimal places.\n \"\"\"\n if not isinstance(decimals, int):\n raise TypeError(\"decimal places must be an integer\")\n elif decimals < 0:\n raise ValueError(\"decimal places has to be 0 or more\")\n elif decimals == 0:\n return math.ceil(number)\n\n factor = 10 ** decimals\n return math.floor(number * factor) / factor\n","sub_path":"BatchCompute/data/hexgrid_constructor.py","file_name":"hexgrid_constructor.py","file_ext":"py","file_size_in_byte":15132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"243569673","text":"\"\"\"\n计算各城市商家运营数据情况\n\"\"\"\nimport pandas as pd\nfrom datetime import datetime\ntimes = datetime.now().strftime('%Y-%m-%d')\n\nfilename = '沙县各商家运营数据.xlsx'\nsheet_name = pd.ExcelFile(filename).sheet_names # print(sheet_name) # ['沙县', '安陆', '丹江口'] 返回值是列表\nb_name = input('请输入您需要查询的商家名称:')\nfor sheet in sheet_name:\n if sheet == '12月':\n gmv = 2257444.8\n order = 55475\n agent_money = 219801.25\n different_rate = 0.0099\n df01 = pd.read_excel(filename, sheet)\n # df[['col2', 'col3']] = df[['col2', 'col3']].apply(pd.to_numeric)\n # 将百分数转化为小数\n # df01 = df01.where(df01.notnull(), 0) # 把所有为空的列的值改为None\n df01.ix[df01['非顾客原因异常订单率'] == '-', '非顾客原因异常订单率'] = 0 # 刷选\n df01['非顾客原因异常订单率'] = df01['非顾客原因异常订单率'].str.strip('%').astype(float) / 100\n df01 = df01.drop(['是否有双证'], axis=1) # 删除列\n df01 = df01.drop(['是否签署SD合作协议'], axis=1) # 删除列\n df01 = df01.drop(['一级品类'], axis=1) # 删除列\n df01 = df01.drop(['二级品类'], axis=1) # 删除列\n df01 = df01.drop(['代理商名称'], axis=1) # 删除列\n df01 = df01.drop(['商家ID'], axis=1) # 删除列\n df01 = df01.drop(['配送方式'], axis=1) # 删除列\n df01 = df01.drop(['实际��付交易额'], axis=1) # 删除列\n # df01 = df01.drop(['配送方式'], axis=1) # 删除列\n df01['原价交易额贡献占比'] = 0 # 可以增加新的列\n df01['原价交易额贡献占比'] = df01.apply(lambda x: df01['原价交易额'] / gmv)\n df01['原价交易额贡献占比'] = df01['原价交易额贡献占比'].apply(lambda x: format(x, '.2%'))\n df01['订单数贡献占比'] = 0\n df01['订单数贡献占比'] = df01.apply(lambda x: df01['订单数'] / order)\n df01['订单数贡献占比'] = df01['订单数贡献占比'].apply(lambda x: format(x, '.2%'))\n df01['代补金额贡献占比'] = 0\n df01['代补金额贡献占比'] = df01.apply(lambda x: df01['代理商补贴金额'] / agent_money)\n df01['代补金额贡献占比'] = df01['代补金额贡献占比'].apply(lambda x: format(x, '.2%'))\n df01['非异贡献占比'] = 0\n df01['非异贡献占比'] = df01.apply(lambda x: df01['非顾客原因异常订单率'] / different_rate)\n df01['非异贡献占比'] = df01['非异贡献占比'].apply(lambda x: format(x, '.2%'))\n # 排序 一定要记得先将数据转化成 int类型\n # df01.sort_values([\"原价交易额贡献占比\", \"订单数贡献占比\", '代补金额贡献占比', '非异贡献占比'], ascending=False)\n df01[\"订单数\"] = df01[\"订单数\"].astype(\"int\") # 强制转化类型\n # inplace表示再排序的时候是否生成一个新的dataframe 结构\n df01.sort_values([\"原价交易额贡献占比\"], inplace=True, ascending=False)\n # df01 = df01.head(30) # 取前30行数据\n df01.set_index(['外卖组织结构'], inplace=True)\n data01 = df01[df01['商家名称'] == b_name] # 魏记骨汤麻辣烫\n print(data01)\n # url = 'C:/Users/王颖/Desktop/'\n # df01.to_excel(url + '沙县11月各商家数据明细.xlsx')\n if sheet == '11月':\n gmv = 2160776.78\n order = 54250\n agent_money = 182178.55\n different_rate = 0.0107\n df02 = pd.read_excel(filename, sheet)\n # df[['col2', 'col3']] = df[['col2', 'col3']].apply(pd.to_numeric)\n # 将百分数转化为小数\n # df01 = df01.where(df01.notnull(), 0) # 把所有为空的列的值改为None\n df02.ix[df02['非顾客原因异常订单率'] == '-', '非顾客原因异常订单率'] = 0 # 刷选\n df02['非顾客原因异常订单率'] = df02['非顾客原因异常订单率'].str.strip('%').astype(float) / 100\n df02 = df02.drop(['是否有双证'], axis=1) # 删除列\n df02 = df02.drop(['是否签署SD合作协议'], axis=1) # 删除列\n df02 = df02.drop(['一级品类'], axis=1) # 删除列\n df02 = df02.drop(['二级品类'], axis=1) # 删除列\n df02 = df02.drop(['代理商名称'], axis=1) # 删除列\n df02 = df02.drop(['商家ID'], axis=1) # 删除列\n df02 = df02.drop(['配送方式'], axis=1) # 删除列\n df02 = df02.drop(['实际支付交易额'], axis=1) # 删除列\n # df01 = df01.drop(['配送方式'], axis=1) # 删除列\n df02['原价交易额贡献占比'] = 0 # 可以增加新的列\n df02['原价交易额贡献占比'] = df02.apply(lambda x: df02['原价交易额']/gmv)\n df02['原价交易额贡献占比'] = df02['原价交易额贡献占比'].apply(lambda x: format(x, '.2%'))\n df02['订单数贡献占比'] = 0\n df02['订单数贡献占比'] = df02.apply(lambda x: df02['订单数'] / order)\n df02['订单数贡献占比'] = df02['订单数贡献占比'].apply(lambda x: format(x, '.2%'))\n df02['代补金额贡献占比'] = 0\n df02['代补金额贡献占比'] = df02.apply(lambda x: df02['代理商补贴金额'] / agent_money)\n df02['代补金额贡献占比'] = df02['代补金额贡献占比'].apply(lambda x: format(x, '.2%'))\n df02['非异贡献占比'] = 0\n df02['非异贡献占比'] = df02.apply(lambda x: df02['非顾客原因异常订单率'] / different_rate)\n df02['非异贡献占比'] = df02['非异贡献占比'].apply(lambda x: format(x, '.2%'))\n # 排序 一定要记得先将数据转化成 int类型\n # df01.sort_values([\"原价交易额贡献占比\", \"订单数贡献占比\", '代补金额贡献占比', '非异贡献占比'], ascending=False)\n df02[\"订单数\"] = df02[\"订单数\"].astype(\"int\") # 强制转化类型\n # inplace表示再排序的时候是否生成一个新的dataframe 结构\n df02.sort_values([\"原价交易额贡献占比\"], inplace=True, ascending=False)\n df02 = df02.head(30)\n df02.set_index(['外卖组织结构'], inplace=True)\n data02 = df02[df02['商家名称'] == b_name] # 魏记骨汤麻辣烫\n print(data02)\n # url = 'C:/Users/王颖/Desktop/'\n # df01.to_excel(url + '沙县11月各商家数据明细.xlsx')\n\n if sheet == '10月':\n gmv = 2300995.2\n order = 56908\n agent_money = 191680.21\n different_rate = 0.0094\n df03 = pd.read_excel(filename, sheet)\n # df[['col2', 'col3']] = df[['col2', 'col3']].apply(pd.to_numeric)\n # 将百分数转化为小数\n # df01 = df01.where(df01.notnull(), 0) # 把所有为空的列的值改为None\n df03.ix[df03['非顾客原因异常订单率'] == '-', '非顾客原因异常订单率'] = 0 # 刷选\n df03['非顾客原因异常订单率'] = df03['非顾客原因异常订单率'].str.strip('%').astype(float) / 100\n df03 = df03.drop(['是否有双证'], axis=1) # 删除列\n df03 = df03.drop(['是否签署SD合作协议'], axis=1) # 删除列\n df03 = df03.drop(['一级品类'], axis=1) # 删除列\n df03 = df03.drop(['二级品类'], axis=1) # 删除列\n df03 = df03.drop(['代理商名称'], axis=1) # 删除列\n df03 = df03.drop(['商家ID'], axis=1) # 删除列\n df03 = df03.drop(['配送方式'], axis=1) # 删除列\n df03 = df03.drop(['实际支付交易额'], axis=1) # 删除列\n # df01 = df01.drop(['配送方式'], axis=1) # 删除列\n df03['原价交易额贡献占比'] = 0 # 可以增加新的列\n df03['原价交易额贡献占比'] = df03.apply(lambda x: df03['原价交易额'] / gmv)\n df03['原价交易额贡献占比'] = df03['原价交易额贡献占比'].apply(lambda x: format(x, '.2%'))\n df03['订单数贡献占比'] = 0\n df03['订单数贡献占比'] = df03.apply(lambda x: df03['订单数'] / order)\n df03['订单数贡献占比'] = df03['订单数贡献占比'].apply(lambda x: format(x, '.2%'))\n df03['代补金额贡献占比'] = 0\n df03['代补金额贡献占比'] = df03.apply(lambda x: df03['代理商补贴金额'] / agent_money)\n df03['代补金额贡献占比'] = df03['代补金额贡献占比'].apply(lambda x: format(x, '.2%'))\n df03['非异贡献占比'] = 0\n df03['非异贡献占比'] = df03.apply(lambda x: df03['非顾客原因异常订单率'] / different_rate)\n df03['非异贡献占比'] = df03['非异贡献占比'].apply(lambda x: format(x, '.2%'))\n # 排序 一定要记得先将数据转化成 int类型\n # df01.sort_values([\"原价交易额贡献占比\", \"订单数贡献占比\", '代补金额贡献占比', '非异贡献占比'], ascending=False)\n df03[\"订单数\"] = df03[\"订单数\"].astype(\"int\") # 强制转化类型\n # inplace表示再排序的时候是否生成一个新的dataframe 结构\n df03.sort_values([\"原价交易额贡献占比\"], inplace=True, ascending=False)\n df03 = df03.head(30)\n df03.set_index(['外卖组织结构'], inplace=True)\n data03 = df03[df03['商家名称'] == b_name] # 魏记骨汤麻辣烫\n # url = 'C:/Users/王颖/Desktop/'\n # df01.to_excel(url + '沙县11月各商家数据明细.xlsx')\n if sheet == '9月':\n gmv = 2055899.15\n order = 50911\n agent_money = 174015.28\n different_rate = 0.0132\n df04 = pd.read_excel(filename, sheet)\n # df[['col2', 'col3']] = df[['col2', 'col3']].apply(pd.to_numeric)\n # 将百分数转化为小数\n # df01 = df01.where(df01.notnull(), 0) # 把所有为空的列的值改为None\n df04.ix[df04['非顾客原因异常订单率'] == '-', '非顾客原因异常订单率'] = 0 # 刷选\n df04['非顾客原因异常订单率'] = df04['非顾客原因异常订单率'].str.strip('%').astype(float) / 100\n df04 = df04.drop(['是否有双证'], axis=1) # 删除列\n df04 = df04.drop(['是否签署SD合作协议'], axis=1) # 删除列\n df04 = df04.drop(['一级品类'], axis=1) # 删除列\n df04 = df04.drop(['二级品类'], axis=1) # 删除列\n df04 = df04.drop(['代理商名称'], axis=1) # 删除列\n df04 = df04.drop(['商家ID'], axis=1) # 删除列\n df04 = df04.drop(['配送方式'], axis=1) # 删除列\n df04 = df04.drop(['实际支付交易额'], axis=1) # 删除列\n # df01 = df01.drop(['配送方式'], axis=1) # 删除列\n df04['原价交易额贡献占比'] = 0 # 可以增加新的列\n df04['原价交易额贡献占比'] = df04.apply(lambda x: df04['原价交易额'] / gmv)\n df04['原价交易额贡献占比'] = df04['原价交易额贡献占比'].apply(lambda x: format(x, '.2%'))\n df04['订单数贡献占比'] = 0\n df04['订单数贡献占比'] = df04.apply(lambda x: df04['订单数'] / order)\n df04['订单数贡献占比'] = df04['订单数贡献占比'].apply(lambda x: format(x, '.2%'))\n df04['代补金额贡献占比'] = 0\n df04['代补金额贡献占比'] = df04.apply(lambda x: df04['代理商补贴金额'] / agent_money)\n df04['代补金额贡献占比'] = df04['代补金额贡献占比'].apply(lambda x: format(x, '.2%'))\n df04['非异贡献占比'] = 0\n df04['非异贡献占比'] = df04.apply(lambda x: df04['非顾客原因异常订单率'] / different_rate)\n df04['非异贡献占比'] = df04['非异贡献占比'].apply(lambda x: format(x, '.2%'))\n # 排序 一定要记得先将数据转化成 int类型\n # df01.sort_values([\"原价交易额贡献占比\", \"订单数贡献占比\", '代补金额贡献占比', '非异贡献占比'], ascending=False)\n df04[\"订单数\"] = df04[\"订单数\"].astype(\"int\") # 强制转化类型\n # inplace表示再排序的时候是否生成一个新的dataframe 结构\n df04.sort_values([\"原价交易额贡献占比\"], inplace=True, ascending=False)\n df04 = df04.head(30)\n df04.set_index(['外卖组织结构'], inplace=True)\n data04 = df04[df04['商家名称'] == b_name] # 魏记骨汤麻辣烫\n # url = 'C:/Users/王颖/Desktop/'\n # df01.to_excel(url + '沙县11月各商家数据明细.xlsx')\n if sheet == '8月':\n gmv = 2692068.51\n order = 65329\n agent_money = 219326.55\n different_rate = 0.0156\n df05 = pd.read_excel(filename, sheet)\n # df[['col2', 'col3']] = df[['col2', 'col3']].apply(pd.to_numeric)\n # 将百分数转化为小数\n # df01 = df01.where(df01.notnull(), 0) # 把所有为空的列的值改为None\n df05.ix[df05['非顾客原因异常订单率'] == '-', '非顾客原因异常订单率'] = 0 # 刷选\n df05['非顾客原因异常订单率'] = df05['非顾客原因异常订单率'].str.strip('%').astype(float) / 100\n df05 = df05.drop(['是否有双证'], axis=1) # 删除列\n df05 = df05.drop(['是否签署SD合作协议'], axis=1) # 删除列\n df05 = df05.drop(['一级品类'], axis=1) # 删除列\n df05 = df05.drop(['二级品类'], axis=1) # 删除列\n df05 = df05.drop(['代理商名称'], axis=1) # 删除列\n df05 = df05.drop(['商家ID'], axis=1) # 删除列\n df05 = df05.drop(['配送方式'], axis=1) # 删除列\n df05 = df05.drop(['实际支付交易额'], axis=1) # 删除列\n # df01 = df01.drop(['配送方式'], axis=1) # 删除列\n df05['原价交易额贡献占比'] = 0 # 可以增加新的列\n df05['原价交易额贡献占比'] = df05.apply(lambda x: df05['原价交易额'] / gmv)\n df05['原价交易额贡献占比'] = df05['原价交易额贡献占比'].apply(lambda x: format(x, '.2%'))\n df05['订单数贡献占比'] = 0\n df05['订单数贡献占比'] = df05.apply(lambda x: df05['订单数'] / order)\n df05['订单数贡献占比'] = df05['订单数贡献占比'].apply(lambda x: format(x, '.2%'))\n df05['代补金额贡献占比'] = 0\n df05['代补金额贡献占比'] = df05.apply(lambda x: df05['代理商补贴金额'] / agent_money)\n df05['代补金额贡献占比'] = df05['代补金额贡献占比'].apply(lambda x: format(x, '.2%'))\n df05['非异贡献占比'] = 0\n df05['非异贡献占比'] = df05.apply(lambda x: df05['非顾客原因异常订单率'] / different_rate)\n df05['非异贡献占比'] = df05['非异贡献占比'].apply(lambda x: format(x, '.2%'))\n # 排序 一定要记得先将数据转化成 int类型\n # df01.sort_values([\"原价交易额贡献占比\", \"订单数贡献占比\", '代补金额贡献占比', '非异贡献占比'], ascending=False)\n df05[\"订单数\"] = df05[\"订单数\"].astype(\"int\") # 强制转化类型\n # inplace表示再排序的时候是否生成一个新的dataframe 结构\n df05.sort_values([\"原价交易额贡献占比\"], inplace=True, ascending=False)\n df05 = df05.head(30)\n df05.set_index(['外卖组织结构'], inplace=True)\n data05 = df05[df05['商家名称'] == b_name] # 魏记骨汤麻辣烫\n # url = 'C:/Users/王颖/Desktop/'\n # df01.to_excel(url + '沙县11月各商家数据明细.xlsx')\n if sheet == '7月':\n gmv = 2627850.44\n order = 63877\n agent_money = 221700.17\n different_rate = 0.0184\n df06 = pd.read_excel(filename, sheet)\n # df[['col2', 'col3']] = df[['col2', 'col3']].apply(pd.to_numeric)\n # 将百分数转化为小数\n # df01 = df01.where(df01.notnull(), 0) # 把所有为空的列的值改为None\n df06.ix[df06['非顾客原因异常订单率'] == '-', '非顾客原因异常订单率'] = 0 # 刷选\n df06['非顾客原因异常订单率'] = df06['非顾客原因异常订单率'].str.strip('%').astype(float) / 100\n df06 = df06.drop(['是否有双证'], axis=1) # 删除列\n df06 = df06.drop(['是否签署SD合作协议'], axis=1) # 删除列\n df06 = df06.drop(['一级品类'], axis=1) # 删除列\n df06 = df06.drop(['二级品类'], axis=1) # 删除列\n df06 = df06.drop(['代理商名称'], axis=1) # 删除列\n df06 = df06.drop(['商家ID'], axis=1) # 删除列\n df06 = df06.drop(['配送方式'], axis=1) # 删除列\n df06 = df06.drop(['实际支付交易额'], axis=1) # 删除列\n # df01 = df01.drop(['配送方式'], axis=1) # 删除列\n df06['原价交易额贡献占比'] = 0 # 可以增加新的列\n df06['原价交易额贡献占比'] = df06.apply(lambda x: df06['原价交易额'] / gmv)\n df06['原价交易额贡献占比'] = df06['原价交易额贡献占比'].apply(lambda x: format(x, '.2%'))\n df06['订单数贡献占比'] = 0\n df06['订单数贡献占比'] = df06.apply(lambda x: df06['订单数'] / order)\n df06['订单数贡献占比'] = df06['订单数贡献占比'].apply(lambda x: format(x, '.2%'))\n df06['代补金额贡献占比'] = 0\n df06['代补金额贡献占比'] = df06.apply(lambda x: df06['代理商补贴金额'] / agent_money)\n df06['代补金额贡献占比'] = df06['代补金额贡献占比'].apply(lambda x: format(x, '.2%'))\n df06['非异贡献占比'] = 0\n df06['非异贡献占比'] = df06.apply(lambda x: df06['非顾客原因异常订单率'] / different_rate)\n df06['非异贡献占比'] = df06['非异贡献占比'].apply(lambda x: format(x, '.2%'))\n # 排序 一定要记得先将数据转化成 int类型\n # df01.sort_values([\"原价交易额贡献占比\", \"订单数贡献占比\", '代补金额贡献占比', '非异贡献占比'], ascending=False)\n df06[\"订单数\"] = df06[\"订单数\"].astype(\"int\") # 强制转化类型\n # inplace表示再排序的时候是否生成一个新的dataframe 结构\n df06.sort_values([\"原价交易额贡献占比\"], inplace=True, ascending=False)\n df06 = df06.head(30)\n df06.set_index(['外卖组织结构'], inplace=True)\n data06 = df06[df06['商家名称'] == b_name] # 魏记骨汤麻辣烫\n # url = 'C:/Users/王颖/Desktop/'\n # df01.to_excel(url + '沙县11月各商家数据明细.xlsx')\n\n# 将多个dataframe合并成一个dataframe, 这两条数据的列名称是完全一样\nurl = 'C:/Users/王颖/Desktop/'\ndf = pd.concat([data01, data02, data03, data04, data05, data06])\ndf.to_excel(url + '沙县11月各商家数据明细.xlsx')\n# 将多个dataframe数据写入同一个Excel的不同sheet中\n# url = 'C:/Users/王颖/Desktop/'\n# with pd.ExcelWriter(url+\"沙县各商家运营情况.xlsx\") as writer:\n# df01.to_excel(writer, sheet_name='沙县12月')\n# df02.to_excel(writer, sheet_name='沙县11月')\n# df03.to_excel(writer, sheet_name='沙县10月')\n# df04.to_excel(writer, sheet_name='沙县9月')\n# df05.to_excel(writer, sheet_name='沙县8月')\n# df06.to_excel(writer, sheet_name='沙县7月')\n\n\n\n","sub_path":"execl_计算历史数据单个商家的营业详情.py","file_name":"execl_计算历史数据单个商家的营业详情.py","file_ext":"py","file_size_in_byte":19265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"312610424","text":"import math\nimport numpy as np\nimport random as rnd\n\nstr_bold = '\\033[1m'\nstr_reset = '\\033[0m'\nstr_blue_bg = '\\033[44m'\nstr_white_font = '\\033[37m'\n\n\ndef L2(a, b):\n s = a.size\n if s != b.size:\n raise ValueError(\"Arrays must be of equal size.\")\n q = 0\n for i in range(s):\n q += (a[i] - b[i])**2\n return math.sqrt(q)\n\n\ndef L1(a, b):\n s = a.size\n if s != b.size:\n raise ValueError(\"Arrays must be of equal size.\")\n q = 0\n for i in range(s):\n q += abs(a[i] - b[i])\n return q\n\n\ndef findMinMax(data):\n rows, columns = data.shape\n minima = np.full(columns, -1, dtype=float)\n maxima = np.full(columns, -1, dtype=float)\n for i in range(rows):\n for j in range(columns):\n if minima[j] > data[i][j] or minima[j] < 0:\n minima[j] = data[i][j]\n if maxima[j] < data[i][j] or maxima[j] < 0:\n maxima[j] = data[i][j]\n return minima, maxima\n\n\ndef kmeans(data, k=1, update_threshold=0, maximum_iterations=-1, distance_func=L2, verbose=False):\n column_count = len(data.columns)\n record_count = len(data.values)\n k_means = []\n # cluster indices for every record\n c_indices = np.zeros(record_count, dtype=np.uint8)\n # distance to cluster for every record\n c_distances = np.full(record_count, -1, dtype=float)\n update_count = 1\n\n # initialize clusters\n for _ in range(k):\n new_k = np.zeros(column_count)\n for j in range(column_count):\n new_k[j] = rnd.random()\n k_means.append(new_k)\n cluster_count = len(k_means)\n # begin grouping process\n clusters_were_updated = True\n updated_list = [False for i in range(len(k_means))]\n while clusters_were_updated and (update_count < maximum_iterations if maximum_iterations > 0 else True):\n # print cluster values\n if verbose == True:\n print(\"K = %i, update %i\" % (k, update_count))\n for c in range(len(k_means)):\n if updated_list[c]:\n print(str_bold + str_blue_bg + str_white_font, end='')\n print(\"C%i : \" % (c+1), end='')\n for i in range(k_means[c].size):\n print(\"%7.2f\" % (k_means[c][i]), end='')\n print(str_reset, end='')\n print()\n # measure distances, update group if necessary\n update_count += 1\n clusters_were_updated = False\n for record_index in range(record_count):\n for cluster_index in range(cluster_count):\n distance = distance_func(\n data.values[record_index], k_means[cluster_index])\n if distance < c_distances[record_index] or c_distances[record_index] < 0:\n c_distances[record_index] = distance\n c_indices[record_index] = cluster_index\n # update clusters\n updated_list = [False for i in range(len(k_means))]\n for i in range(cluster_count):\n updated_cluster = np.zeros(column_count, dtype=float)\n item_count = 0\n for j in range(record_count):\n if c_indices[j] == i:\n item_count += 1\n for m in range(column_count):\n updated_cluster[m] += data.iloc[j, m]\n if item_count > 0:\n for m in range(column_count):\n updated_cluster[m] /= item_count\n if distance_func(updated_cluster, k_means[i]) > update_threshold:\n k_means[i] = updated_cluster\n clusters_were_updated = True\n updated_list[i] = True\n return c_indices, k_means\n","sub_path":"Patrones/Final/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"445993744","text":"import torch\nimport pytorch_lightning as pl\nfrom torch import nn, mean, optim\nfrom copy import deepcopy\n\nfrom typing import Any, Dict\nfrom torch.optim.optimizer import Optimizer\nimport torchmetrics\nimport models\nfrom models.loss_functions import EVM\nfrom models.metrics import BERMetric, QFactor\nfrom data.transform_1d_2d import transform_to_1d\nfrom math import sqrt\n\n# import plotly.express as px\n# from plotly.offline import plot\nimport matplotlib.pyplot as plt\n\nclass ConvNet_regressor(pl.LightningModule):\n def __init__(\n self, \n seq_len: int,\n pulse_width: float,\n z_end: float,\n dim_t: int,\n decision_level: float,\n \n in_features: int,\n bias = False,\n\n optimizer:str = 'Adam',\n optimizer_kwargs: Dict[str, Any] = {'lr':1e-4},\n scheduler: str = 'StepLR',\n scheduler_kwargs: Dict[str, Any] = {'step_size':10},\n criterion: str = 'EVM',\n ):\n '''\n in_features (int) - number of input features in model\n bias (bool) - whether to use bias in linear layers or not.\n \n optimizer (str) - name of optimizer (ex. \"Adam\", \"SGD\")\n optimizer_kwargs (dict) - parameters of optimizer (ex. {'lr':1e-4})\n scheduler (str) - name of scheduler that will be used\n scheduler_kwargs (dict) - parameters of scheduler\n criterion (str) - Loss function that will be used for training. \"MSE\" or \"EVM\"\n '''\n \n\n super().__init__()\n\n self.optimizer = optimizer\n self.optimizer_kwargs = optimizer_kwargs\n self.scheduler = scheduler\n self.scheduler_kwargs = scheduler_kwargs\n\n self.net = ConvNet(in_features, bias)\n \n self.loss_type = criterion\n \n if criterion == 'MSE':\n self.criterion = nn.MSELoss()\n elif criterion == 'EVM':\n self.criterion = EVM()\n \n self.seq_len = seq_len\n self.pulse_width = pulse_width\n self.z_end = z_end\n self.dim_t = dim_t\n \n self.t_end = ((seq_len - 1)//2 + 1) * pulse_width \n tMax = self.t_end + 4*sqrt(2*(1 + z_end**2))\n tMin = -tMax\n dt = (tMax - tMin) / dim_t\n self.t = torch.linspace(tMin, tMax-dt, dim_t)\n self.t_window = [torch.abs(self.t + self.t_end).argmin(),\n torch.abs(self.t - self.t_end).argmin()]\n \n self.ber = BERMetric(decision_level=decision_level,\n pulse_number=seq_len,\n pulse_width=pulse_width,\n t=self.t + self.t_end + 0.5*pulse_width,\n t_window=self.t_window)\n\n\n def forward(self, x):\n if len(x.shape) == 4 and x.shape[0] == 1:\n x = x.squeeze(dim=0)\n x = x.permute(2, 0, 1)\n real = x.real\n imag = x.imag\n real, imag = self.net(real, imag)\n return (real + 1j*imag).unsqueeze(1).permute(1, 2, 0)\n\n\n def training_step(self, batch, batch_idx):\n data, target = batch\n preds = self.forward(data)\n \n preds = transform_to_1d(preds)\n target = transform_to_1d(target)\n \n if self.loss_type == 'MSE':\n loss_real = self.criterion(preds.real, target.real)\n loss_imag = self.criterion(preds.imag, target.imag)\n loss = loss_real + loss_imag\n elif self.loss_type == 'EVM':\n loss = self.criterion(preds, target)\n \n self.log(\"loss_train\", loss, prog_bar = False, logger = True)\n return {\"loss\": loss, \"preds\": preds, \"target\": target}\n\n\n def validation_step(self, batch, batch_idx):\n data, target = batch\n preds = self.forward(data)\n\n preds = transform_to_1d(preds)\n target = transform_to_1d(target)\n \n if self.loss_type == 'MSE':\n loss_real = self.criterion(preds.real, target.real)\n loss_imag = self.criterion(preds.imag, target.imag)\n loss = loss_real + loss_imag\n elif self.loss_type == 'EVM':\n loss = self.criterion(preds, target)\n \n self.log(\"loss_val\", loss, prog_bar = False, logger = True)\n return {'preds':preds , 'target': target}\n\n\n def configure_optimizers(self):\n OptimizerClass = getattr(optim, self.optimizer)\n SchedulerClass = getattr(optim.lr_scheduler, self.scheduler)\n opt = OptimizerClass(self.parameters(), **self.optimizer_kwargs)\n sch = SchedulerClass(opt, **self.scheduler_kwargs)\n\n return [opt], [sch]\n\n\n def training_epoch_end(self, outputs):\n preds = torch.cat([r['preds'] for r in outputs], dim=0)\n target = torch.cat([r['target'] for r in outputs], dim=0)\n\n self.ber.update(preds.squeeze(1), target.squeeze(1))\n ber_value = self.ber.compute()\n q_factor = QFactor(ber_value)\n self.log('Q_factor_train', q_factor, prog_bar = True, logger = True)\n \n # nt1 = torch.abs(self.t - 0.5 * self.pulse_width).argmin()\n # nt2 = torch.abs(self.t - 8.5 * self.pulse_width).argmin()\n # fig, ax = plt.subplots(1, 1)\n # ax.plot(self.t[nt1:nt2], target[0,0,nt1:nt2].cpu().real, label='Target')\n # ax.plot(self.t[nt1:nt2], preds[0,0,nt1:nt2].detach().cpu().real, label='Predicted')\n # ax.set_xlabel('Time')\n # ax.set_ylabel('Re(E)')\n # self.logger.experiment.add_figure('prediction_train', fig, global_step=self.current_epoch)\n\n def validation_epoch_end(self, outputs):\n preds = torch.cat([r['preds'] for r in outputs], dim=0)\n target = torch.cat([r['target'] for r in outputs], dim=0)\n\n self.ber.update(preds.squeeze(1), target.squeeze(1))\n ber_value = self.ber.compute()\n q_factor = QFactor(ber_value)\n self.log('Q_factor_val', q_factor, prog_bar = True, logger = True)\n \n nt1 = torch.abs(self.t - 0.5 * self.pulse_width).argmin()\n nt2 = torch.abs(self.t - 8.5 * self.pulse_width).argmin()\n fig, ax = plt.subplots(1, 1, dpi=150)\n ax.plot(self.t[nt1:nt2], target[0,0,nt1:nt2].cpu().real, label='Target')\n ax.plot(self.t[nt1:nt2], preds[0,0,nt1:nt2].detach().cpu().real, label='Predicted')\n ax.set_xlabel('Time')\n ax.set_ylabel('Re(E)')\n self.logger.experiment.add_figure('prediction_val', fig, global_step=self.current_epoch)\n # fig = px.line(x=self.t[nt1:nt2], y=target[0,0,nt1:nt2].real, title='Target', labels={'x':'Time', 'y':'real E'})\n # plot(fig)\n # fig = px.line(x=self.t[nt1:nt2], y=preds[0,0,nt1:nt2].detach().real, title='Predicted', labels={'x':'Time', 'y':'real E'})\n # plot(fig)\n\n def get_configuration(self):\n '''\n Returns dict of str with current configuration of the model.\n Can be used for Logger.\n '''\n configuration = {\n 'activation': self.net.activation_name, \n 'criterion': str(self.criterion.__repr__())[:-2],\n 'optimizer': self.optimizer,\n 'optimizer_param': str(self.optimizer_kwargs)[1:-1], \n 'scheduler': self.scheduler,\n 'scheduler_param': str(self.scheduler_kwargs)[1:-1]\n }\n return configuration\n\n\nclass ConvNet(nn.Module):\n '''\n Model with 1D-CNN architecture\n Inspired from https://discuss.pytorch.org/t/cnn-architecture-for-short-time-series-data/99814\n '''\n \n def __init__(self, in_features: int, bias=False, activation='ReLU'):\n '''\n @num_classes - number of features in input vector\n @bias - whether to use bias for convolutional layers or not\n @activation - the activation function used after each conv layer\n '''\n super(ConvNet, self).__init__()\n \n # Activation function\n self.activation_name = activation\n ActivationClass = getattr(nn, activation)\n \n self.real_model = nn.Sequential(\n nn.Conv1d(1, 3, kernel_size=3, stride=1, padding=1, bias=bias),\n nn.BatchNorm1d(3),\n ActivationClass(),\n nn.MaxPool1d(kernel_size=3, stride=1, padding=1),\n nn.Dropout(0.3),\n \n nn.Conv1d(3, 5, kernel_size=3, stride=1, padding=1, bias=bias),\n nn.BatchNorm1d(5),\n ActivationClass(),\n nn.Dropout(0.3),\n \n nn.Conv1d(5, 5, kernel_size=3, stride=1, padding=1, bias=bias),\n nn.BatchNorm1d(5),\n ActivationClass(),\n \n nn.Dropout(0.3)\n )\n \n self.imag_model = deepcopy(self.real_model)\n self.real_fc = nn.Linear(in_features, in_features)\n self.imag_fc = nn.Linear(in_features, in_features)\n \n \n def forward(self, real, imag):\n real = self.real_model(real)\n real = mean(real, dim = 1)\n real = self.real_fc(real)\n \n imag = self.imag_model(imag)\n imag = mean(imag, dim = 1)\n imag = self.imag_fc(imag)\n \n return real, imag","sub_path":"models/convnet.py","file_name":"convnet.py","file_ext":"py","file_size_in_byte":9146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"320764617","text":"\"\"\"\nKavita Amin \n12/1/2017\n\nAssignment: Build a mini game that helps a ninja make some money! \nWhen you start the game, your ninja should have 0 gold. \nThe ninja can go to different places (farm, cave, house, casino) and earn different amounts of gold. \nIn the case of a casino, your ninja can earn or LOSE up to 50 golds. \n\n\"\"\"\n\nfrom flask import Flask, render_template, session, redirect, request\nimport random\nfrom datetime import datetime\n\napp = Flask(__name__)\napp.secret_key = \"key\"\n\n@app.route('/')\ndef index(): \n\n if \"gold\" not in session: \n session[\"gold\"] = 0\n\n if \"activities\" not in session: \n session[\"activities\"] = [] \n\n return render_template(\"index.html\")\n\n\n\n@app.route('/process_money', methods=[\"POST\"])\ndef process_money(): \n \n time = str(datetime.now())\n\n if request.form[\"building\"] == \"farm\": \n farmEarnings = random.randint(10, 20)\n session[\"gold\"] += farmEarnings\n session[\"activities\"].append(\"Earned {} golds from the farm! ({}) \".format(farmEarnings,time))\n elif request.form[\"building\"] == \"cave\":\n caveEarnings = random.randint(5, 10)\n session[\"gold\"] += caveEarnings\n session[\"activities\"].append(\"Earned {} golds from the cave! ({}) \".format(caveEarnings,time))\n elif request.form[\"building\"] == \"house\": \n houseEarnings = random.randint(2, 5)\n session[\"gold\"] += houseEarnings\n session[\"activities\"].append(\"Earned {} golds from the house! ({}) \".format(houseEarnings,time))\n elif request.form[\"building\"] == \"casino\": \n winOrLose = random.randint(0,1)\n if winOrLose == 0: \n casinoLoss = random.randint(0,50)\n session[\"gold\"]-= casinoLoss\n session[\"activities\"].append(\"Entered a casino and lost {} golds. ({}) \".format(casinoLoss, time))\n elif winOrLose == 1: \n casinoWin = random.randint(0, 50)\n session[\"gold\"] += casinoWin\n session[\"activities\"].append(\"Entered a casino and won {} golds. ({}) \".format(casinoWin, time))\n\n return redirect('/')\n\napp.run(debug=True)\n","sub_path":"ninja_gold/ninja_gold.py","file_name":"ninja_gold.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"57437507","text":"\r\nimport pyglet\r\nfrom pyglet.gl import *\r\nfrom pyglet.window import key\r\nfrom math import *\r\n\r\n\r\nwindow = pyglet.window.Window()\r\n\r\n'''\r\ntext_label = pyglet.text.Label('OTHELLO',\r\n font_name='Comic Sans',\r\n font_size=50,\r\n x=window.width // 2, y=window.height // 2 + 200,\r\n anchor_x='center', anchor_y='center')\r\n'''\r\n\r\n\r\n@window.event\r\ndef on_draw():\r\n\r\n window.clear()\r\n\r\n #text_label.draw()\r\n\r\n posx, posy = 0, 0\r\n sides = 32\r\n radius = 15\r\n\r\n\r\n for a in range(0,280,35):\r\n for b in range(0,280,35):\r\n spelar_position = [190+a, 370-b]\r\n glBegin(GL_POLYGON)\r\n for i in range(100):\r\n cosine = radius * cos(i * 2 * pi / sides) + posx\r\n sine = radius * sin(i * 2 * pi / sides) + posy\r\n glVertex2f(spelar_position[0]+cosine, spelar_position[1]+sine)\r\n glEnd()\r\n\r\n\r\n\r\n\r\npyglet.app.run()","sub_path":"othello.py","file_name":"othello.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"549853013","text":"import os\nfrom PIL import Image\nimport pickle\nimport numpy as np\nimport tensorflow as tf\nfrom keras.datasets import mnist\nfrom keras.utils import to_categorical\nfrom keras import optimizers, regularizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nwith open('C:\\\\Users\\\\Nina\\\\PycharmProjects\\\\test\\\\venv\\\\X_Train2.data', 'rb') as filehandle:\n # read the data as binary data stream\n X_Train = pickle.load(filehandle)\n\nwith open('C:\\\\Users\\\\Nina\\\\PycharmProjects\\\\test\\\\venv\\\\Y_Train2.data', 'rb') as filehandle:\n # read the data as binary data stream\n Y_Train = pickle.load(filehandle)\n\nwith open('C:\\\\Users\\\\Nina\\\\PycharmProjects\\\\test\\\\venv\\\\Meta2.data', 'rb') as filehandle:\n # read the data as binary data stream\n Meta = pickle.load(filehandle)\n\nX_Train = X_Train.reshape(X_Train.shape[0], X_Train.shape[1], X_Train.shape[2], 1)\n\nX_Train = X_Train/255\nY_Train = to_categorical(Y_Train)\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, kernel_size=(3, 3), strides=(1, 1), activation='relu',\n kernel_regularizer=regularizers.l2(0.001),\n input_shape=(X_Train.shape[1],\n X_Train.shape[2], 1),\n padding=\"same\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1)))\n\nmodel.add(Conv2D(16, kernel_size=(3, 3), strides=(1, 1), activation='relu', kernel_regularizer=regularizers.l2(0.001),\n padding=\"same\"))\nmodel.add(Conv2D(16, kernel_size=(3, 3), strides=(1, 1), activation='relu', kernel_regularizer=regularizers.l2(0.001),\n padding=\"same\"))\n# model.add(Conv2D(32, kernel_size=(3, 3), strides=(1, 1), activation='relu', kernel_regularizer=regularizers.l2(0.001),\n# padding=\"same\"))\n\n#model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1)))\n\n#model.add(Conv2D(16, kernel_size=(3, 3), strides=(1, 1), activation='relu', kernel_regularizer=regularizers.l2(0.001),\n# padding=\"same\"))\n#model.add(Conv2D(16, kernel_size=(3, 3), strides=(1, 1), activation='relu', kernel_regularizer=regularizers.l2(0.001),\n# padding=\"same\"))\n\n# model.add(Conv2D(16, kernel_size=3, activation='relu'))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2, activation='softmax'))\n\nsgd = optimizers.SGD(lr=0.01, momentum=0.0001, nesterov=True)\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n# model.compile(optimizer=sgd, loss='mean_squared_error', metrics=['accuracy'])\n\n# model.fit(X_Train, Y_Train, validation_data=(X_Train, Y_Train), epochs=3)\nX_test = X_Train[0:291]\nX_test = X_test.reshape(X_test.shape[0], X_test.shape[1], X_test.shape[2], 1)\ny_test = Y_Train[0:291]\nmodel.fit(X_Train, Y_Train,validation_data=(X_Train, Y_Train), epochs=30, batch_size=10, shuffle=True)\n\nmodel.save('my_model.h5')\n","sub_path":"2020_02 Quantifying Thin-film Defects using Machine Vision/DeepThin model/train_cnn_2.py","file_name":"train_cnn_2.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"43667372","text":"#!/usr/bin/env python\n# coding=utf-8\n# Author: bloke\n# Project: 地名分级显示\n\nimport requests\nimport re\nimport sys\n\n\ndef get_place(url, place_re): #获取数据\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \\\n Maxthon/5.1.1.1000 Chrome/55.0.2883.75 Safari/537.36'\n }\n response = requests.get(url, headers=headers)\n try:\n data = place_re.findall(response.text)[0]\n return(data)\n except IndexError as e:\n return(None)\n\n\nurl = 'https://www.douban.com/note/290487992/'\nplace_re = re.compile(r'(.*?)
', re.S)\ndata = get_place(url, place_re)\nif not data: sys.exit()\nthe_data = re.findall(r'(直辖市):(.*?)
(\\S{1,2}地区)
(.*?)
(\\S{1,2}地区)
(.*?)
(\\S{1,2}地区)
(.*?)
(\\S{1,2}地区)
(.*?)
(\\S{1,2}地区)
(.*?)
(\\S{1,2}地区)
(.*?)
港澳台', data, re.S)\nprovinces = the_data[0]\nprovinces_dict = {}\n\nfor num in range(2, len(provinces), 2): # 返回 地区、省、市 字典\n child_dict = {}\n child_data = provinces[num+1].split('
')\n if len(child_data) >= 1:\n for item in child_data:\n city, district = item.split(':')\n child_dict[city] = district\n else:\n provinces_dict[provinces[num]] = child_dict\n else:\n provinces_dict[provinces[num]] = provinces[num+1]\n\nprovince_list = list(provinces_dict.keys())\nwhile 1:\n for num, province in enumerate(province_list): # 列出地区\n print(str(num) + ' : ' + province)\n else:\n print('-- Usage: q to exit; num to join. --')\n select_province = input('Input Prevince: ').strip()\n if not select_province:\n continue\n if select_province == 'q':\n sys.exit(0)\n try:\n select_province = int(select_province)\n if select_province in range(len(province_list)):\n city_dict = provinces_dict[province_list[select_province]]\n if isinstance(city_dict, dict):\n city_list = list(city_dict.keys())\n while 1:\n for city_num, city_name in enumerate(city_list): # 列出省份\n print(str(city_num) + ' : ' + city_name)\n else:\n print('-- Usage: q to exit; b to go up; num to join. --')\n select_district = input('Input City: ').strip()\n if select_district == 'q':\n sys.exit(0)\n elif select_district == 'b':\n break\n try:\n select_district = int(select_district)\n if select_district in range(len(city_list)):\n for the_district in city_dict[city_list[select_district]].split(): # 列出市区\n print(the_district)\n else:\n print('-- Usage: q to exit; b to go up. --')\n while 1:\n the_select = input('Input: ').strip()\n if the_select == 'q':\n sys.exit(0)\n elif the_select == 'b':\n break\n else:\n continue\n except SystemExit as e: # 捕获 sys.exit 抛出的 SystemExit 异常\n sys.exit(0)\n except:\n continue\n except ValueError as e:\n continue\n","sub_path":"module1/place_name.py","file_name":"place_name.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"40507454","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport copy\n\nimport httpretty\nimport mock\n\nfrom openstack import exceptions\nfrom openstack import resource\nfrom openstack import session\nfrom openstack.tests import base\nfrom openstack.tests import fakes\nfrom openstack import transport\n\nfake_name = 'rey'\nfake_id = 99\nfake_attr1 = 'lana'\nfake_attr2 = 'del'\n\nfake_resource = 'fake'\nfake_resources = 'fakes'\nfake_arguments = {'name': 'rey'}\nfake_base_path = '/fakes/%(name)s/data'\nfake_path = '/fakes/rey/data'\n\nfake_data = {'id': fake_id,\n 'name': fake_name,\n 'attr1': fake_attr1,\n 'attr2': fake_attr2}\nfake_body = {fake_resource: fake_data}\n\n\nclass FakeResource(resource.Resource):\n\n resource_key = fake_resource\n resources_key = fake_resources\n base_path = fake_base_path\n\n allow_create = allow_retrieve = allow_update = True\n allow_delete = allow_list = allow_head = True\n\n name = resource.prop('name')\n first = resource.prop('attr1')\n second = resource.prop('attr2')\n\n\nclass ResourceTests(base.TestTransportBase):\n\n TEST_URL = fakes.FakeAuthenticator.ENDPOINT\n\n def setUp(self):\n super(ResourceTests, self).setUp()\n self.transport = transport.Transport(accept=transport.JSON)\n self.auth = fakes.FakeAuthenticator()\n self.session = session.Session(self.transport, self.auth)\n\n @httpretty.activate\n def test_empty_id(self):\n self.stub_url(httpretty.GET, path=[fake_path], json=fake_body)\n obj = FakeResource.new(**fake_arguments)\n obj.get(self.session)\n\n self.assertEqual(fake_id, obj.id)\n self.assertEqual(fake_name, obj['name'])\n self.assertEqual(fake_attr1, obj['attr1'])\n self.assertEqual(fake_attr2, obj['attr2'])\n\n self.assertEqual(fake_name, obj.name)\n self.assertEqual(fake_attr1, obj.first)\n self.assertEqual(fake_attr2, obj.second)\n\n @httpretty.activate\n def test_create(self):\n self.stub_url(httpretty.POST, path=fake_path, json=fake_body)\n\n obj = FakeResource.new(name=fake_name,\n attr1=fake_attr1,\n attr2=fake_attr2)\n\n obj.create(self.session)\n self.assertFalse(obj.is_dirty)\n\n last_req = httpretty.last_request().parsed_body[fake_resource]\n\n self.assertEqual(3, len(last_req))\n self.assertEqual(fake_name, last_req['name'])\n self.assertEqual(fake_attr1, last_req['attr1'])\n self.assertEqual(fake_attr2, last_req['attr2'])\n\n self.assertEqual(fake_id, obj.id)\n self.assertEqual(fake_name, obj['name'])\n self.assertEqual(fake_attr1, obj['attr1'])\n self.assertEqual(fake_attr2, obj['attr2'])\n\n self.assertEqual(fake_name, obj.name)\n self.assertEqual(fake_attr1, obj.first)\n self.assertEqual(fake_attr2, obj.second)\n\n @httpretty.activate\n def test_get(self):\n self.stub_url(httpretty.GET, path=[fake_path, fake_id], json=fake_body)\n obj = FakeResource.get_by_id(self.session, fake_id,\n path_args=fake_arguments)\n\n self.assertEqual(fake_id, obj.id)\n self.assertEqual(fake_name, obj['name'])\n self.assertEqual(fake_attr1, obj['attr1'])\n self.assertEqual(fake_attr2, obj['attr2'])\n\n self.assertEqual(fake_name, obj.name)\n self.assertEqual(fake_attr1, obj.first)\n self.assertEqual(fake_attr2, obj.second)\n\n @httpretty.activate\n def test_head(self):\n self.stub_url(httpretty.HEAD, path=[fake_path, fake_id],\n name=fake_name,\n attr1=fake_attr1,\n attr2=fake_attr2)\n obj = FakeResource.head_by_id(self.session, fake_id,\n path_args=fake_arguments)\n\n self.assertEqual(fake_name, obj['name'])\n self.assertEqual(fake_attr1, obj['attr1'])\n self.assertEqual(fake_attr2, obj['attr2'])\n\n self.assertEqual(fake_name, obj.name)\n self.assertEqual(fake_attr1, obj.first)\n self.assertEqual(fake_attr2, obj.second)\n\n @httpretty.activate\n def test_update(self):\n new_attr1 = 'attr5'\n new_attr2 = 'attr6'\n fake_body1 = copy.deepcopy(fake_body)\n fake_body1[fake_resource]['attr1'] = new_attr1\n\n self.stub_url(httpretty.POST, path=fake_path, json=fake_body1)\n self.stub_url(httpretty.PATCH,\n path=[fake_path, fake_id],\n json=fake_body)\n\n obj = FakeResource.new(name=fake_name,\n attr1=new_attr1,\n attr2=new_attr2)\n obj.create(self.session)\n self.assertFalse(obj.is_dirty)\n self.assertEqual(new_attr1, obj['attr1'])\n\n obj['attr1'] = fake_attr1\n obj.second = fake_attr2\n self.assertTrue(obj.is_dirty)\n\n obj.update(self.session)\n self.assertFalse(obj.is_dirty)\n\n last_req = httpretty.last_request().parsed_body[fake_resource]\n self.assertEqual(1, len(last_req))\n self.assertEqual(fake_attr1, last_req['attr1'])\n\n self.assertEqual(fake_id, obj.id)\n self.assertEqual(fake_name, obj['name'])\n self.assertEqual(fake_attr1, obj['attr1'])\n self.assertEqual(fake_attr2, obj['attr2'])\n\n self.assertEqual(fake_name, obj.name)\n self.assertEqual(fake_attr1, obj.first)\n self.assertEqual(fake_attr2, obj.second)\n\n @httpretty.activate\n def test_delete(self):\n self.stub_url(httpretty.GET, path=[fake_path, fake_id], json=fake_body)\n self.stub_url(httpretty.DELETE, [fake_path, fake_id])\n obj = FakeResource.get_by_id(self.session, fake_id,\n path_args=fake_arguments)\n\n obj.delete(self.session)\n\n last_req = httpretty.last_request()\n self.assertEqual('DELETE', last_req.method)\n self.assertEqual('/endpoint/fakes/rey/data/99', last_req.path)\n\n @httpretty.activate\n def test_list(self):\n results = [fake_data.copy(), fake_data.copy(), fake_data.copy()]\n for i in range(len(results)):\n results[i]['id'] = fake_id + i\n\n self.stub_url(httpretty.GET,\n path=[fake_path],\n json={fake_resources: results})\n\n objs = FakeResource.list(self.session, marker='x',\n path_args=fake_arguments)\n\n self.assertIn('marker=x', httpretty.last_request().path)\n self.assertEqual(3, len(objs))\n\n for obj in objs:\n self.assertIn(obj.id, range(fake_id, fake_id + 3))\n self.assertEqual(fake_name, obj['name'])\n self.assertEqual(fake_name, obj.name)\n self.assertIsInstance(obj, FakeResource)\n\n def test_attrs(self):\n obj = FakeResource()\n\n try:\n obj.name\n except AttributeError:\n pass\n else:\n self.fail(\"Didn't raise attribute error\")\n\n try:\n del obj.name\n except AttributeError:\n pass\n else:\n self.fail(\"Didn't raise attribute error\")\n\n\nclass FakeResponse:\n def __init__(self, response):\n self.body = response\n\n\nclass TestFind(base.TestCase):\n NAME = 'matrix'\n ID = 'Fishburne'\n\n def setUp(self):\n super(TestFind, self).setUp()\n self.mock_session = mock.Mock()\n self.mock_get = mock.Mock()\n self.mock_session.get = self.mock_get\n self.matrix = {'id': self.ID}\n\n def test_name(self):\n self.mock_get.side_effect = [\n FakeResponse({FakeResource.resources_key: []}),\n FakeResponse({FakeResource.resources_key: [self.matrix]})\n ]\n\n result = FakeResource.find(self.mock_session, self.NAME,\n path_args=fake_arguments)\n\n self.assertEqual(self.ID, result.id)\n p = {'fields': 'id', 'name': self.NAME}\n self.mock_get.assert_called_with(fake_path, params=p, service=None)\n\n def test_id(self):\n resp = FakeResponse({FakeResource.resources_key: [self.matrix]})\n self.mock_get.return_value = resp\n\n result = FakeResource.find(self.mock_session, self.ID,\n path_args=fake_arguments)\n\n self.assertEqual(self.ID, result.id)\n p = {'fields': 'id', 'id': self.ID}\n self.mock_get.assert_called_with(fake_path, params=p, service=None)\n\n def test_nameo(self):\n self.mock_get.side_effect = [\n FakeResponse({FakeResource.resources_key: []}),\n FakeResponse({FakeResource.resources_key: [self.matrix]})\n ]\n FakeResource.name_attribute = 'nameo'\n\n result = FakeResource.find(self.mock_session, self.NAME,\n path_args=fake_arguments)\n\n FakeResource.name_attribute = 'name'\n self.assertEqual(self.ID, result.id)\n p = {'fields': 'id', 'nameo': self.NAME}\n self.mock_get.assert_called_with(fake_path, params=p, service=None)\n\n def test_dups(self):\n dup = {'id': 'Larry'}\n resp = FakeResponse({FakeResource.resources_key: [self.matrix, dup]})\n self.mock_get.return_value = resp\n\n self.assertRaises(exceptions.DuplicateResource, FakeResource.find,\n self.mock_session, self.NAME)\n\n def test_nada(self):\n resp = FakeResponse({FakeResource.resources_key: []})\n self.mock_get.return_value = resp\n\n self.assertRaises(exceptions.ResourceNotFound, FakeResource.find,\n self.mock_session, self.NAME)\n\n def test_no_name(self):\n self.mock_get.side_effect = [\n FakeResponse({FakeResource.resources_key: []}),\n FakeResponse({FakeResource.resources_key: [self.matrix]})\n ]\n FakeResource.name_attribute = None\n\n self.assertRaises(exceptions.ResourceNotFound, FakeResource.find,\n self.mock_session, self.NAME)\n\n def test_repr_name(self):\n FakeResource.resource_name = 'foo'\n self.assertEqual('foo: {}', repr(FakeResource()))\n FakeResource.resource_name = None\n FakeResource.resource_key = None\n self.assertEqual('FakeResource: {}', repr(FakeResource()))\n FakeResource.resource_key = fake_resource\n self.assertEqual(fake_resource + ': {}', repr(FakeResource()))\n\n def test_id_attribute(self):\n faker = FakeResource(fake_data)\n self.assertEqual(fake_id, faker.id)\n faker.id_attribute = 'name'\n self.assertEqual(fake_name, faker.id)\n faker.id_attribute = 'attr1'\n self.assertEqual(fake_attr1, faker.id)\n faker.id_attribute = 'attr2'\n self.assertEqual(fake_attr2, faker.id)\n faker.id_attribute = 'id'\n self.assertEqual(fake_id, faker.id)\n","sub_path":"openstack/tests/test_resource.py","file_name":"test_resource.py","file_ext":"py","file_size_in_byte":11363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"557102482","text":"#!/usr/bin/python3\n\"\"\"a class Square that manages: size\n\"\"\"\n\n\nclass Node:\n \"\"\"a class Node\n \"\"\"\n def __init__(self, data, next_node=None):\n self.data = data\n self.next_node = next_node\n\n @property\n def data(self):\n return self.__data\n\n @data.setter\n def data(self, value):\n if value is None:\n self.__data = value\n else:\n if not isinstance(value, int):\n raise TypeError('data must be an integer')\n else:\n self.__data = value\n\n @property\n def next_node(self):\n return self.__next_node\n\n @next_node.setter\n def next_node(self, value):\n if not value:\n self.__next_node = value\n else:\n if not isinstance(value, Node):\n raise TypeError('next_node must be a Node object')\n else:\n self.__next_node = value\n\n\nclass SinglyLinkedList:\n \"\"\"a class SinglyLinkedList\n \"\"\"\n def __init__(self):\n self.__head = Node(None)\n\n def __str__(self):\n ss = \"\"\n cur = self.__head\n if cur.data is not None:\n while cur.next_node is not None:\n ss += str(cur.data)\n ss += '\\n'\n cur = cur.next_node\n ss += str(cur.data)\n ss += '\\n'\n return ss[:-1]\n\n def sorted_insert(self, value):\n new = Node(value)\n cur = self.__head\n if cur is None:\n self.__head = new\n elif cur.data is None:\n cur.data = value\n else:\n if value <= cur.data:\n new.next_node = self.__head\n self.__head = new\n else:\n while cur.next_node is not None:\n if value < cur.next_node.data:\n break\n cur = cur.next_node\n new.next_node = cur.next_node\n cur.next_node = new\n","sub_path":"0x06-python-classes/100-singly_linked_list.py","file_name":"100-singly_linked_list.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"502537964","text":"from math import sin, cos\n\n\nclass log():\n def __init__(self, fileName):\n self.fileName = fileName\n self._file = open(fileName, 'w+')\n self._file.write(\n 'Time(s) pitch(rad) yaw(rad) roll(rad) pitchspeed(rad/s) yawspeed(rad/s) rollspeed(rad/s) pn(m) pe(m) alt[MSL](m) vnorth[NED](m/s) veast[NED](m/s) vdown[NED](m/s) xacc(m/s^2) yacc(m/s^2) zacc(m/s^2) IAS(m/s) AOA() Sideslip() RCch1() RCch2() RCch3() RCch4()\\n')\n\n def addEntry(self, state, delta, sensors, time):\n text = '{time} {theta} {psi} {phi} {q} {r} {p} {pn} {pe} {h} {vNorth} {vEast} {vDown} {xacc} {yacc} {zacc} {Va} {alpha} {beta} {delta_a} {delta_e} {delta_t} {delta_r}'\n text = text.format(time=time, theta=state.theta, psi=state.psi, phi=state.phi, q=state.q, r=state.r, p=state.p, pn=state.pn,\n pe=state.pe, h=state.h, vNorth=state.Vg * cos(state.chi) * cos(state.gamma), vEast=state.Vg * sin(state.chi) * cos(state.gamma),\n vDown=-state.Vg * sin(state.gamma), xacc=sensors.accel_x, yacc=sensors.accel_y, zacc=sensors.accel_z, Va=state.Va, alpha=state.alpha, beta=state.beta, delta_a=delta.aileron,\n delta_e=delta.elevator, delta_t=delta.throttle, delta_r=delta.rudder)\n self._file.write(text + '\\n')\n\n def closeLog(self):\n self._file.close()\n","sub_path":"UAV-P2/Raspberry_Pi/tools/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"77982805","text":"\"\"\"Plot Sverdrup transport meridional section computed from wind stress\"\"\"\nfrom __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt ; plt.close('all')\nimport os\n\nimport poppy.grid\nimport phdpy.sverdrup\n\nfrom phdpy import settings\n\n\ndef _lon0str(lon0):\n return '{:.0f}W'.format(-lon0) if lon0<0 else '{:.0f}E'.format(lon0)\n\ndef plot_sverdrup_transport_section(dsids,region,lon0,tautimes=-1,\n plotmap=False,savefig=False):\n \"\"\"Plot Sverdrup Transport Meridional Section\"\"\"\n fig,ax = plt.subplots()\n\n title = 'Sverdrup transport meridional section at {}'.format(_lon0str(lon0))\n ax.set_title(title)\n\n for dsid in dsids:\n # check whether the data of one dsid should be \n # interpolated to the grid of another\n dsidfull = dsid\n dsid = dsidfull.split('_int_')[0]\n try:\n inttofname = settings.datafiles[dsidfull.split('_int_')[1]]\n except IndexError:\n inttofname = None\n except KeyError:\n raise\n\n # get sverdrup transport\n lon0_rewrap = settings.region_lon0[region]\n lon,lat,psi = phdpy.sverdrup.get_psi(settings.datafiles[dsid],\n region=region,tautimes=tautimes,lon0_rewrap=lon0_rewrap,\n interpolate_to_grid_from_file=inttofname)\n\n # get landmask\n # mask also everything north of 60N, where the grid becomes funny\n landmask_regular = psi.mask | (lat>60)\n\n # find section\n meanlon = np.mean(np.ma.masked_where(landmask_regular,lon),axis=0)\n i0 = np.argmin(np.abs(np.mod(meanlon,360)-np.mod(lon0,360)))\n lon0_comp = meanlon[i0]\n latax = lat[:,i0]\n\n psi_section = psi[:,i0]\n if np.all(psi_section.mask): raise ValueError('All values in psi_section are masked!')\n\n # add a map of the section\n if plotmap and dsid == dsids[0]:\n subax = _add_subplot_axes(ax,[0.6, 0.02, 0.3, 0.3])\n subax.pcolormesh(psi)\n subax.axvline(i0,0.1,0.9,color='0.5',ls=settings.lineplotfmt[dsid]['ls'])\n subax.autoscale(tight=True)\n subax.axis('off')\n #subax.pcolormesh(np.mod(meanlon,360),latax,psi)\n #subax.axvline(lon0_comp,**settings.lineplotfmt[dsid])\n #subax.yaxis.set_visible(False)\n #subax.tick_params(axis='both', direction='in')\n #subax.get_xaxis().tick_bottom()\n\n # plot psi section\n ax.plot(latax,psi_section,label=dsidfull,**settings.lineplotfmt[dsid])\n\n\n ax.set_ylabel('Sverdrup Transport (Sv)')\n ax.grid(True)\n #ax.set_xlim(-80,60)\n ax.legend(loc=0)\n ax.set_xlabel('latitude')\n ax.set_xlim(settings.lataxlim[region])\n\n if savefig:\n figname = os.path.join(settings.figdir,'sverdrup_transport',\n 'sverdrup_transport_section_{}_at_{}_{}'.format(region,_lon0str(lon0),'_'.join(dsids)))\n fig.savefig(figname+'.png',dpi=300)\n else:\n plt.show()\n\n\ndef _add_subplot_axes(ax,rect,axisbg='w'):\n fig = ax.figure\n box = ax.get_position()\n width = box.width\n height = box.height\n inax_position = ax.transAxes.transform(rect[0:2])\n transFigure = fig.transFigure.inverted()\n infig_position = transFigure.transform(inax_position) \n x = infig_position[0]\n y = infig_position[1]\n width *= rect[2]\n height *= rect[3] \n subax = fig.add_axes([x,y,width,height],axisbg=axisbg)\n x_labelsize = subax.get_xticklabels()[0].get_size()\n y_labelsize = subax.get_yticklabels()[0].get_size()\n x_labelsize *= rect[2]**0.5\n y_labelsize *= rect[3]**0.5\n subax.xaxis.set_tick_params(labelsize=x_labelsize)\n subax.yaxis.set_tick_params(labelsize=y_labelsize)\n return subax\n\nif __name__ == '__main__':\n \n defaults = dict( \n dsids = ['x3','x1','x010'],\n region = 'Indo-Pacific',\n lon0 = 180,\n tautimes = -1,\n )\n\n import argparse\n parser = argparse.ArgumentParser(description=\"Plot Sverdrup transport computed from wind stress\")\n parser.add_argument('-d','--dsids',type=(lambda s: s.split(',')),help='dataset IDs, separated by comma')\n parser.add_argument('-r','--region',type=str,help='region')\n parser.add_argument('-l','--lon0',type=float,help='Longitude at which to draw the meridional section')\n parser.add_argument('--tautimes',type=int,choices=[-1,1],help='factor to multiply tau by')\n parser.add_argument('-m',dest='plotmap',action='store_true',help='set this to plot a map of the section')\n parser.add_argument('-s',dest='savefig',action='store_true',help='set this to save the figure')\n\n parser.set_defaults(**defaults)\n args = parser.parse_args()\n \n plot_sverdrup_transport_section(**vars(args))\n","sub_path":"wind_driven_circulation/sverdrup_transport_sections.py","file_name":"sverdrup_transport_sections.py","file_ext":"py","file_size_in_byte":4738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"191441953","text":"from fastapi import FastAPI\nfrom starlette.middleware.cors import CORSMiddleware\n\nfrom identify.api.api_v1.api import api_router\n\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=['*'],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\napp.include_router(api_router)\n\n\nif __name__ == '__main__':\n import uvicorn\n uvicorn.run(app, host='0.0.0.0', port=9009)\n","sub_path":"identify/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"456908730","text":"# -*- coding: utf-8 -*-\nimport sys\n\ndef main():\n #ここに関数記述\n f = open(sys.argv[1],'r')\n f1 = open('make/col1.txt','w')\n f2 = open('make/col2.txt','w')\n for line in f:\n line = line.split('\\t')\n f1.write(line[0] + '\\n')\n f2.write(line[1])\n f.close()\n f1.close()\n f2.close()\n \nif(__name__=='__main__'):\n main()\n","sub_path":"003.py","file_name":"003.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"264175031","text":"import pygame\r\nimport sys\r\nimport Jogo\r\nimport Print\r\nimport InterfaceInicial\r\nimport InterfaceDificuldade\r\nimport InterfaceFinal\r\nimport InterfaceDefenições\r\nimport InterfaceCores\r\nimport InterfaceSelectCores\r\nimport files\r\nimport InterfaceResultados\r\nimport Results\r\n\r\n# Ecra para definir a fase que o jogo representra\r\n# INICIO = 1\r\n# DEFENIÇÕES = 2\r\n# SKILL = 3\r\n# JOGO = 4\r\n# FINAL = 5\r\n# CORES = 6\r\n# SELECT_CORES = 7\r\necra = 1\r\n\r\n# Tamanho do ecra\r\nTAMANHO = 880\r\npygame.init()\r\nscreen = pygame.display.set_mode((TAMANHO, TAMANHO))\r\ngame_over = False\r\npygame.display.set_caption(\"Definitely Not Sudoku\")\r\nicon = pygame.image.load('Images/Logo.png')\r\npygame.display.set_icon(icon)\r\n\r\n# Variaveis de inicialização\r\ndificuldade = 35\r\nn_select = False\r\ntimes = 1\r\nstrart_time = -times\r\nbotoes_jogo = [False, False, False, False]\r\nbotoes_inicio = [False, False, False, False, False, False]\r\nbotoes_defenicao = [False, True, True, True, False]\r\nbotoes_dificuldade = [False, False, False, False, False, False]\r\nbotoes_cores = [False, False, False, False, False, False, False]\r\nbotoes_select_cores = [False, False, False, False, False, False, False, False, False, False, False]\r\nbotoes_fim = [False, False]\r\nbotoes_resultados = [False, False]\r\ninicio = True\r\nresult = \"Erro\"\r\nswitch_white = False\r\n\r\n# Variaveis de jogo\r\nerrados = []\r\nmat = []\r\nalterados = []\r\njogo = []\r\ncoluna = 0\r\nlinha = 0\r\ntempo = 0\r\nbest_results = Results.ler_resultados()\r\n\r\n# Cores\r\nfirst = 1\r\nsecond = 0\r\nthird = 4\r\nfourth = 7\r\n\r\ndefenicoes = files.gera_def(first, second, third, fourth, switch_white, dificuldade, botoes_defenicao[1], botoes_defenicao[2], botoes_defenicao[3])\r\ndefenicoes = files.ler_def(defenicoes)\r\nfirst, second, third, fourth, switch_white, dificuldade, botoes_defenicao[1], botoes_defenicao[2], botoes_defenicao[3] = files.act_def(defenicoes)\r\n\r\nwrong = botoes_defenicao[1]\r\nhelps = botoes_defenicao[2]\r\nfix = botoes_defenicao[3]\r\n\r\n# Carrega corres botoes\r\nbase, alternativo, small_base, small_alternativo, mini_base, mini_alternativo, small_third, mini_third, small_fourth, \\\r\n mini_fourth = Print.carrega_cores(first, second, third, fourth)\r\ncolour = mini_base\r\ntela_cor = 0\r\n\r\n# Ciclo do jogo\r\nwhile not game_over:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n\r\n base, alternativo, small_base, small_alternativo, mini_base, mini_alternativo, small_third, mini_third,\\\r\n small_fourth, mini_fourth = Print.carrega_cores(first, second, third, fourth)\r\n cor_letras = Print.print_fundo(screen, switch_white)\r\n\r\n if ecra == 1:\r\n # Ecra inicial do jogo\r\n inicio = True\r\n ecra, game_over = InterfaceInicial.strart(screen, botoes_inicio, ecra, base, alternativo, game_over, first, second,\r\n third, fourth, switch_white, dificuldade, wrong, helps, fix)\r\n elif ecra == 2:\r\n # Menu das defenições\r\n wrong, helps, fix, ecra = InterfaceDefenições.defenicoes(screen, botoes_defenicao, ecra, dificuldade, base,\r\n alternativo, small_base, small_alternativo,\r\n switch_white)\r\n elif ecra == 3:\r\n # Menu das dificuldades\r\n dificuldade, ecra = InterfaceDificuldade.imprime_dificuldade(screen, dificuldade, botoes_dificuldade, base,\r\n alternativo, switch_white)\r\n elif ecra == 4:\r\n # Jogo\r\n mat, n_select, colour, jogo, linha, coluna, botoes_jogo, errados, alterados, strart_time, times, \\\r\n inicio, ecra, tempo, result, best_results = Jogo.sudoku(screen, event, n_select, colour, linha, coluna, alterados,\r\n errados, mat, jogo, botoes_jogo, strart_time, times, wrong,\r\n helps, fix, dificuldade, inicio, ecra, tempo, small_base,\r\n small_alternativo, mini_base, mini_alternativo, mini_third,\r\n mini_fourth, switch_white, cor_letras, best_results)\r\n elif ecra == 5:\r\n # Ecra no fim do jogo\r\n ecra, game_over = InterfaceFinal.final(screen, botoes_fim, ecra, result, tempo, game_over, base,\r\n alternativo, switch_white, cor_letras)\r\n elif ecra == 6:\r\n # Ecra de escolha de cores\r\n ecra, tela_cor, switch_white = InterfaceCores.i_cores(screen, botoes_cores, ecra, base, alternativo, tela_cor, small_base,\r\n small_alternativo, small_third, small_fourth, switch_white)\r\n elif ecra == 7:\r\n # Ecra de escolha de uma cor\r\n ecra, tela_cor, first, second, third, fourth = InterfaceSelectCores.i_select_cores(screen,\r\n botoes_select_cores,\r\n ecra, base, alternativo,\r\n tela_cor, first, second,\r\n third, fourth,\r\n switch_white)\r\n elif ecra == 8:\r\n ecra, best_results = InterfaceResultados.resultados(screen, botoes_resultados, ecra, base, alternativo, switch_white, best_results, cor_letras)\r\n\r\n pygame.display.update()\r\n","sub_path":"Pyton/Sudoku/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"256249335","text":"import sys\nimport os\nsys.path.append(\".\")\nfrom pokemon import pokemon\n\ndef get_pokemon_from_file(filename):\n pokemon_list = []\n file = open(filename,\"r\")\n text = file.read()\n file.close()\n lines = text.split(\"\\n\")\n for line in lines:\n new_poke = pokemon()\n if new_poke.get_from_string(line):\n pokemon_list.append(new_poke)\n return pokemon_list\n\npoke_list = \"../Additional_files/pokemon_list.txt\"\nsprites_dir = \"../Additional_files/pokemon_sprites/\"\nshiny_sprites_dir = \"../Additional_files/shiny_pokemon_sprites/\"\npokemon_list = get_pokemon_from_file(poke_list)\nexceptions = {}\nexceptions[\"083\"] = \"farfetchd\"\nexceptions[\"083G\"] = \"farfetchd-galar\"\nexceptions[\"029\"] = \"nidoran-f\"\nexceptions[\"032\"] = \"nidoran-m\"\nexceptions[\"122\"] = \"mr-mime\"\nexceptions[\"122G\"] = \"mr-mime-galar\"\nexceptions[\"439\"] = \"mime-jr\"\nexceptions[\"669\"] = \"flabebe\"\nexceptions[\"772\"] = \"type-null\"\nexceptions[\"865\"] = \"sirfetchd\"\nexceptions[\"866\"] = \"mr-rime\"\nexceptions[\"785\"] = \"tapu-koko\"\nexceptions[\"786\"] = \"tapu-lele\"\nexceptions[\"787\"] = \"tapu-bulu\"\nexceptions[\"788\"] = \"tapu-fini\"\nekeys = exceptions.keys()\nfor poke in pokemon_list:\n region = \"\"\n old_name = None\n for key in ekeys:\n if key == poke.national_number:\n old_name = exceptions[key]\n break\n if old_name == None:\n old_name = poke.name.lower()\n if poke.regional_variant():\n region = \"-\" + poke.region.lower()\n old_name = old_name + region\n try:\n os.rename(sprites_dir+old_name+\".png\", sprites_dir+poke.national_number+\".png\")\n except FileNotFoundError:\n pass\n try:\n os.rename(shiny_sprites_dir+old_name+\".png\", shiny_sprites_dir+poke.national_number+\".png\")\n except FileNotFoundError:\n pass","sub_path":"python_scripts/rename_iamges.py","file_name":"rename_iamges.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"113803207","text":"import requests,os,hashlib,time,pandas\nfrom propertiesUtil import Properties\nfrom params import Params\nfrom lxml import html\nfrom urllib import parse\n\nproxy = {'http:':'127.0.0.1:8888'}\nlogin_postUrl = 'http://10.2.3.58:808/webadmin/user_admlogin.do'\nlogout_postUrl = 'http://10.2.3.58:808/webadmin/user_admlogout.do'\nlogin_qaptchaUrl = 'http://10.2.3.58:808/front/ajax_getMathValidCode.do'\ndomain_url = 'http://10.2.3.58:808/webadmin/user_adm.do'\naddinfo_url = 'http://10.2.3.58:808/webadmin/article_addinfo.do'\nupload_url = 'http://10.2.3.58:808/webadmin/article/upload.jsp'\nsaveupload_url= 'http://10.2.3.58:808/webadmin/article_addinfo.do'\nsearch_url= 'http://10.2.3.58:808/webadmin/article.do?id=6406407&prevContact=&contact=&groupId=0&siteId=0'\nprops = Properties('upload.properties').getProperties()\nBETA=props.get('beta','')\nerrors=[]\n\n\ndef log(msg):\n print('%s>: --------->%s...........'%(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()),msg))\n#登录\ndef login(s):\n # 验证码\n s.post(login_qaptchaUrl, data=Params.QAPTCHA())\n # 登录请求\n r = s.post(login_postUrl,data=Params.LOGINDATA(props['user'],props['password']))\n return r.text=='login'\n\n#根节点id\ndef getnodeids(s,title):\n r = s.post(search_url,data=Params.SEARCHDATA(title))\n #print(r.content)\n root = html.etree.HTML(r.content)\n nodeids = root.xpath('//td/input[@name=\"id\"]/@value')\n return nodeids\n\ndef uploadexcel(s):\n rowdatas = pandas.read_excel(os.path.join(props['dirpath'], props['excelfile']))\n uploads=[]\n for vin, fdjcj, clxh, fdjxh, xxgkbh, fdjbh in zip(rowdatas[' VIN[Title]'], rowdatas['发动机厂家[Name]'],\n rowdatas['车型[Single1]'], rowdatas['发动机型号[Single2]'],\n rowdatas['信息公开编号[Single3]'], rowdatas['发动机编号[Single4]']):\n nodeids = getnodeids(s, vin)\n if len(nodeids)>0:\n errors.append('%s已存在%s条记录,插入失败'%(vin,len(nodeids)))\n continue\n rowdata = Params.CREATEROW(vin, fdjcj, clxh, fdjxh, xxgkbh, fdjbh)\n r = s.post(addinfo_url,data=rowdata,allow_redirects=False)\n if(r.headers['Location'] == 'article.do?id=6406407&groupId=0&siteId=0'):\n nodeids = getnodeids(s,vin)\n if len(nodeids) == 1:\n uploads.append((str(vin),nodeids[0],clxh))\n continue\n errors.append('%s数据插入失败'%(vin))\n return uploads\n\ndef uploadwordpdf(s,uploads):\n success=[]\n for vin,nodeid,clxh in uploads:\n lbjpath=os.path.join(props['hbgjlbjpath'],clxh)\n wordfile1=os.path.join(lbjpath,'环保关键零部件.doc')\n wordfile2=os.path.join(lbjpath,'环保关键零部件.docx')\n pdffile=os.path.join(props['dirpath'],'PDF/%s.pdf'%(vin))\n wordfile=wordfile2\n if os.path.exists(wordfile2):\n wordfile = wordfile2\n elif os.path.exists(wordfile1):\n wordfile = wordfile1\n else:\n errors.append('%s丢失Word文件!' % wordfile)\n continue\n if os.path.exists(pdffile) == False:\n errors.append('%s丢失Pdf文件' % pdffile)\n continue\n\n # 上传pdf文件\n with open(pdffile, 'rb') as f:\n filename = '%s.pdf' % (vin)\n files = {'myfile': (filename, f, 'application/octet-stream')}\n r = s.post(upload_url, data=Params.UPFILEDATA(filename), files=files)\n filepath = r.text\n if filepath.find('/photos/') != -1:\n # pdf文件绑定\n r = s.post(saveupload_url, data=Params.UPFILESAVE('%s%s'%(BETA,vin), filepath, nodeid),allow_redirects=False)\n if r.status_code != 302:\n errors.append('%s pdf上传失败!' % (vin))\n else:\n success.append(vin)\n else:\n errors.append('%s pdf上传失败!' % (vin))\n\n # 上传word文件\n with open(wordfile, 'rb') as f:\n if wordfile == wordfile1:\n filename = '环保关键零部件.doc'\n else:\n filename = '环保关键零部件.docx'\n files = {'myfile': (parse.quote(filename), f, 'application/octet-stream')}\n r = s.post(upload_url, data=Params.UPFILEDATA(filename), files=files)\n filepath = r.text.strip()\n if filepath.find('/photos/') != -1:\n # word文件绑定\n r = s.post(saveupload_url, data=Params.UPFILESAVE('%s环保关键零部件' % (BETA), filepath, nodeid),\n allow_redirects=False)\n if r.status_code != 302:\n errors.append('%s word上传失败!' % (vin))\n else:\n success.append(vin)\n else:\n errors.append('%s word上传失败!' % (vin))\n success = set(filter(lambda x:success.count(x)==2,success))\n return success\n\ndef uploadWormWork():\n s = requests.session()\n s.headers.update({'User-Agent': 'User-Agent:Mozilla/5.0(WindowsNT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1'})\n s.proxies = proxy\n try:\n #step1 用户登录\n log('%s开始登录' % props['user'])\n if login(s)==False:\n raise Exception('用户/密码名错误')\n log('%s登录成功' % props['user'])\n #step2 导入数据\n log('开始导入excel数据')\n uploads = uploadexcel(s)\n log('excel导入结束')\n #step3 上传文件\n log('开始上传文件')\n success = uploadwordpdf(s,uploads)\n log('文件上传结束')\n #step4 打印结果\n log('处理结果:处理成功%s条数据'%(len(success)))\n if len(errors)==0:\n log('数据全部处理成功!')\n else:\n for error in errors:\n log(error)\n except Exception as e:\n log('发生异常,提前结束:')\n log(e)\n\n finally:\n s.get(logout_postUrl,allow_redirects=False)\n log('%s登出'%props['user'])\n s.close()\n\nif __name__ == '__main__':\n uploadWormWork()","sub_path":"python/epAutoUpload.py","file_name":"epAutoUpload.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"248480526","text":"from builtins import object\nimport cgi\nimport cherrypy\nimport logging\nimport splunk.util\nfrom decorator import decorator\n\nlogger = logging.getLogger('splunk.appserver.mrsparkle.lib.message')\n\nQUEUE_SESSION_KEY = 'queue'\nQUEUE_INFO_LEVEL = 'info'\nQUEUE_ERROR_LEVEL = 'error'\n\n\n\ndef get_session_queue():\n \"\"\"\n Creates or returns une pickled session Queue object with a key of QUEUE_SESSION_KEY\n \"\"\"\n sess = cherrypy.session\n if QUEUE_SESSION_KEY in sess:\n return sess.get(QUEUE_SESSION_KEY)\n else:\n sess[QUEUE_SESSION_KEY] = SessionQueue()\n return sess[QUEUE_SESSION_KEY]\n\n@decorator\ndef save_to_session(fn, self, *a, **kw):\n '''Simple decorator that ensures cherrypy's session gets re-written.'''\n ret_val = fn(self, *a, **kw)\n cherrypy._test_session_has_changed = True\n if (hasattr(cherrypy, 'session')):\n if self.isChanged():\n cherrypy.session.acquire_lock()\n if hasattr(cherrypy.session, 'changed'):\n cherrypy.session.changed = True\n cherrypy.session[QUEUE_SESSION_KEY] = self\n \n return ret_val\n\n\ndef send_client_message(level, msg):\n '''Mechanism for sending a message to the client from the server.'''\n cherrypy.response.headers['X-Splunk-Messages-Available'] = 1\n get_session_queue().add(level, msg)\n\n\nclass Queue(object):\n \"\"\"\n A dead simple container for storing temporary system messages categorized by level.\n \"\"\"\n\n def __init__(self):\n self.queue = []\n self.changed = False\n\n def isChanged(self):\n return self.changed\n\n def add(self, level, message):\n \"\"\"\n Add a message to a list with a specified level.\n Order is perserved.\n Args:\n level: The level marker for the message.\n message: The message string to store.\n \"\"\"\n logger.debug('adding level:%s, message:%s' % (level, message))\n self.changed = True\n self.queue.append({'message': message, 'time': splunk.util.getISOTime(), 'level': level})\n\n def get_level(self, level, delete=True):\n \"\"\"\n Retrieve a list of messages based on a specified level.\n Args:\n level: The level cagegory for a list of messages.\n delete: Delete the list of messages from this level after retrieval.\n \"\"\" \n matches = []\n items = self.queue[:]\n for item in items:\n if item['level'] is level:\n matches.append(item)\n if delete:\n self.queue.pop(self.queue.index(item))\n if matches:\n self.changed = delete\n else:\n self.changed = False\n return matches \n \n def get_levels(self):\n \"\"\"\n Retrieve a sorted list of distinct message levels stored in the queue.\n \"\"\" \n levels = []\n for item in self.queue:\n levels.append(item['level'])\n uniques = sorted(set(levels))\n return uniques\n \n def get_len(self, level=None):\n \"\"\"\n Retrieve the length of messages based on a specified level or the length of all messages combined.\n Args:\n level: The level cagegory for a list of messages.\n \"\"\" \n if level is None:\n return len(self.queue)\n else:\n return len(self.get_level(level, delete=False))\n \n def get_all(self, delete=True):\n \"\"\"\n Retrieve the entire message list.\n Args:\n delete: Delete the entire message list entries after retrieval.\n \"\"\" \n self.changed = False\n queue = self.queue[:]\n if delete and self.queue:\n self.changed = True\n self.queue = []\n return queue\n\n def fifo(self, delete=True):\n \"\"\"\n First in first out (fifo) - retrieve the first message in the list.\n Args:\n delete: Delete the message list entry after retrieval.\n \"\"\"\n if len(self.queue) is 0:\n self.changed = False\n return None\n if delete:\n self.changed = True\n queue = self.queue\n else:\n self.changed = False\n queue = self.queue[:]\n return queue.pop(0)\n \n def lifo(self, delete=True): \n \"\"\"\n Last in first out (lifo) - retrieve the last message in the list.\n Args:\n delete: Delete the message list entry after retrieval.\n \"\"\"\n if len(self.queue) is 0:\n self.changed = False\n return None\n if delete:\n self.changed = True\n queue = self.queue\n else:\n self.changed = False\n queue = self.queue[:]\n return queue.pop()\n\n\n\nclass SessionQueue(Queue):\n '''\n A mirror of the Queue object that ensures if it's stored in a modified\n Cherrypy session, the session is properly rewritten when necessary.\n '''\n\n def __init__(self):\n Queue.__init__(self)\n\n @save_to_session\n def add(self, level, message):\n super(SessionQueue, self).add(level, message)\n\n @save_to_session\n def get_level(self, level, delete=True):\n return super(SessionQueue, self).get_level(level, delete)\n \n @save_to_session\n def get_all(self, delete=True):\n return super(SessionQueue, self).get_all(delete)\n\n @save_to_session\n def fifo(self, delete=True):\n return super(SessionQueue, self).fifo(delete)\n \n @save_to_session \n def lifo(self, delete=True): \n return super(SessionQueue, self).lifo(delete)\n\n\nif __name__ == '__main__':\n\n import unittest\n \n class QueueTests(unittest.TestCase):\n\n def testQueue(self):\n queue = Queue()\n queue.add(\"notice\", \"notice string1\")\n queue.add(\"notice\", \"notice string2\")\n queue.add(\"notice\", \"notice string3\")\n\n self.assert_(len(queue.get_levels()) is 1)\n self.assert_(queue.get_levels()[0] is \"notice\")\n self.assert_(queue.get_len(level=\"notice\") is 3)\n self.assert_(queue.get_len() is 3)\n self.assert_(len(queue.get_level(\"notice\")) is 3)\n self.assert_(len(queue.get_level(\"notice\")) is 0)\n self.assert_(queue.get_len(level=\"notice\") is 0)\n self.assert_(queue.get_len() is 0)\n \n queue.add(\"notice\", \"notice string1\")\n queue.add(\"notice\", \"notice string2\")\n queue.add(\"notice\", \"notice string3\")\n\n self.assert_(len(queue.get_level(\"notice\", delete=False)) is 3)\n self.assert_(len(queue.get_level(\"notice\")) is 3)\n self.assert_(len(queue.get_level(\"notice\")) is 0)\n\n queue.add(\"notice\", \"notice string1\")\n queue.add(\"notice\", \"notice string2\")\n queue.add(\"notice\", \"notice string3\")\n queue.add(\"message\", \"message string1\")\n queue.add(\"message\", \"message string2\")\n queue.add(\"message\", \"message string3\")\n queue.add(\"message\", \"message string4\")\n\n self.assert_(len(queue.get_levels()) is 2)\n self.assert_(queue.get_levels().index(\"notice\") is 1)\n self.assert_(queue.get_levels().index(\"message\") is 0)\n self.assert_(queue.get_len(level=\"notice\") is 3)\n self.assert_(queue.get_len(level=\"message\") is 4)\n self.assert_(queue.get_len() is 7)\n\n messages = queue.get_all()\n\n self.assert_(queue.get_len(level=\"notice\") is 0)\n self.assert_(queue.get_len(level=\"message\") is 0)\n self.assert_(queue.get_len() is 0)\n self.assert_(len(messages) is 7)\n self.assert_(len(queue.get_level(\"notice\")) is 0)\n self.assert_(len(queue.get_level(\"message\")) is 0)\n\n queue.add(\"notice\", \"notice string1\")\n queue.add(\"notice\", \"notice string2\")\n queue.add(\"notice\", \"notice string3\")\n queue.add(\"message\", \"message string1\")\n queue.add(\"message\", \"message string2\")\n queue.add(\"message\", \"message string3\")\n queue.add(\"message\", \"message string4\")\n\n self.assert_(queue.get_len(level=\"notice\") is 3)\n self.assert_(queue.get_len(level=\"message\") is 4)\n self.assert_(queue.get_len() is 7)\n\n messages = queue.get_all(delete=False)\n\n self.assert_(queue.get_len(level=\"notice\") is 3)\n self.assert_(queue.get_len(level=\"message\") is 4)\n self.assert_(queue.get_len() is 7)\n self.assert_(len(messages) is 7)\n self.assert_(len(queue.get_level(\"notice\")) is 3)\n self.assert_(len(queue.get_level(\"message\")) is 4)\n\n queue = Queue()\n queue.add(\"notice\", \"notice string1\")\n queue.add(\"notice\", \"notice string2\")\n queue.add(\"notice\", \"notice string3\")\n\n self.assert_(queue.fifo(delete=False)['message'] is \"notice string1\")\n self.assert_(queue.fifo(delete=True)['message'] is \"notice string1\")\n self.assert_(queue.fifo(delete=True)['message'] is \"notice string2\")\n self.assert_(queue.fifo(delete=True)['message'] is \"notice string3\")\n self.assert_(queue.fifo(delete=True) is None)\n\n queue = Queue()\n queue.add(\"notice\", \"notice string1\")\n queue.add(\"notice\", \"notice string2\")\n queue.add(\"notice\", \"notice string3\")\n\n self.assert_(queue.lifo(delete=False)['message'] is \"notice string3\")\n self.assert_(queue.lifo(delete=True)['message'] is \"notice string3\")\n self.assert_(queue.lifo(delete=True)['message'] is \"notice string2\")\n self.assert_(queue.lifo(delete=True)['message'] is \"notice string1\")\n self.assert_(queue.lifo(delete=True) is None)\n\n class QueueTestsChanged(unittest.TestCase):\n \n def setUp(self):\n self.queue = Queue()\n self.assert_(self.queue.isChanged() is False)\n\n self.queue.add(\"notice\", \"notice string1\")\n self.assert_(self.queue.isChanged() is True)\n\n def testQueueChangedGetLevel(self):\n #get_level\n self.queue.get_level(\"notice\", False)\n self.assert_(self.queue.isChanged() is False)\n self.queue.get_level(\"notice\", True)\n self.assert_(self.queue.isChanged() is True)\n self.queue.get_level(\"notice\")\n self.assert_(self.queue.isChanged() is False)\n\n self.queue.add(\"notice\", \"notice string1\")\n self.assert_(self.queue.isChanged() is True)\n self.queue.get_level(\"message\", True)\n self.assert_(self.queue.isChanged() is False)\n self.queue.get_level(\"notice\", True)\n self.assert_(self.queue.isChanged() is True)\n\n def testQueueChangedGetAll(self):\n #get_level\n self.queue.get_all(False)\n self.assert_(self.queue.isChanged() is False)\n self.queue.get_all(True)\n self.assert_(self.queue.isChanged() is True)\n self.queue.get_all()\n self.assert_(self.queue.isChanged() is False)\n\n def testQueueChangedFifo(self):\n #get_level\n self.queue.add(\"notice\", \"notice string2\")\n self.queue.add(\"notice\", \"notice string3\")\n\n self.assert_(self.queue.fifo(delete=False)['message'] == \"notice string1\")\n self.assert_(self.queue.isChanged() is False)\n self.assert_(self.queue.fifo(delete=True)['message'] == \"notice string1\")\n self.assert_(self.queue.isChanged() is True)\n self.assert_(self.queue.fifo(delete=True)['message'] == \"notice string2\")\n self.assert_(self.queue.isChanged() is True)\n self.assert_(self.queue.fifo(delete=True)['message'] == \"notice string3\")\n self.assert_(self.queue.isChanged() is True)\n self.assert_(self.queue.fifo(delete=True) is None)\n self.assert_(self.queue.isChanged() is False)\n\n def testQueueChangedLifo(self):\n #get_level\n self.queue.add(\"notice\", \"notice string2\")\n self.queue.add(\"notice\", \"notice string3\")\n\n self.assert_(self.queue.lifo(delete=False)['message'] == \"notice string3\")\n self.assert_(self.queue.isChanged() is False)\n self.assert_(self.queue.lifo(delete=True)['message'] == \"notice string3\")\n self.assert_(self.queue.isChanged() is True)\n self.assert_(self.queue.lifo(delete=True)['message'] == \"notice string2\")\n self.assert_(self.queue.isChanged() is True)\n self.assert_(self.queue.lifo(delete=True)['message'] == \"notice string1\")\n self.assert_(self.queue.isChanged() is True)\n self.assert_(self.queue.lifo(delete=True) is None)\n self.assert_(self.queue.isChanged() is False)\n\n\n class SessionQueueTests(unittest.TestCase):\n \n def setUp(self):\n self.queue = SessionQueue()\n\n cherrypy._test_session_has_changed = False\n\n def tearDown(self):\n self.assert_(cherrypy._test_session_has_changed is True)\n self.queue = None\n\n def testSessionQueueAdding(self):\n self.queue.add('error', 'foo')\n\n def testSessionQueueGetLevel(self):\n self.queue.get_level('error')\n\n def testSessionQueueGetAll(self):\n self.queue.get_all()\n\n def testSessionQueueFifo(self):\n self.queue.fifo()\n \n def testSessionQueueLifo(self):\n self.queue.lifo()\n\n\n loader = unittest.TestLoader()\n suites = []\n suites.append(loader.loadTestsFromTestCase(QueueTests))\n suites.append(loader.loadTestsFromTestCase(QueueTestsChanged))\n suites.append(loader.loadTestsFromTestCase(SessionQueueTests))\n unittest.TextTestRunner(verbosity=2).run(unittest.TestSuite(suites))\n\n","sub_path":"appserver/mrsparkle/lib/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":13980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"358793360","text":"import os\nimport sys\nimport logging\nimport threading\nimport queue\nimport json\nfrom datetime import datetime\nfrom contextlib import contextmanager\n\nimport fire\n\nimport fluxx\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\n\nDEFAULT_LOG_DIR = './logs'\nDEFAULT_THREAD_COUNT = 5\nDEFAULT_PER_PAGE = 100\n\n\n@contextmanager\ndef write_operation(instance, model, threads):\n \"Initialize queue, read input, start and end threads.\"\n json_data = sys.stdin.read()\n records = json.loads(json_data)\n\n if 'records' in records:\n records = records['records']\n\n yield records\n\n q = queue.Queue()\n for i, record in enumerate(records):\n item = {\n 'index': i,\n 'model': model,\n 'record': record\n }\n q.put(item)\n\n for _ in range(threads):\n worker = FluxxThread(q, instance)\n worker.daemon = True\n worker.start()\n\n q.join()\n\n\nclass FluxxThread(threading.Thread):\n\n \"\"\"Spawns a new thread performing Fluxx API\n create and update requests.\"\"\"\n\n def __init__(self, queue, instance):\n self.q = queue\n self.client = fluxx.FluxxClient.from_env(instance)\n\n super().__init__()\n\n def run(self):\n while True:\n item = self.q.get()\n\n index = item.get('index')\n model = item.get('model').lower()\n record = item.get('record')\n method = record.get('method').upper()\n\n try:\n record_id = record.pop('id', None)\n log_msg = 'Input line {}: {}d record '.format(index, method.title())\n\n if method == 'CREATE':\n created = self.client.create(model, record)\n log.info(log_msg + str(created['id']))\n\n elif method == 'UPDATE':\n updated = self.client.update(model, record_id, record)\n log.info(log_msg + str(updated['id']))\n\n elif method == 'DELETE':\n deleted = self.client.delete(model, record_id)\n log.info(log_msg + str(deleted['id']))\n else:\n log.info(log_msg + 'Method not specified')\n\n except NotImplementedError:\n log.error('Process method not implemented.')\n\n except fluxx.FluxxError as error:\n log.error(error)\n\n finally:\n self.q.task_done()\n\n\nclass FluxxCLI(object):\n\n \"\"\"Command line interface to this API wrapper, reads and writes JSON.\"\"\"\n\n def __init__(self, instance, log_dir=DEFAULT_LOG_DIR):\n self.instance = instance\n\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n log_file = '{}_{}.log'.format(instance, datetime.now().strftime('%x %X').replace('/', '-'))\n log_path = os.path.join(log_dir, log_file)\n\n # add file handler to module level logger\n handler = logging.FileHandler(log_path, delay=True)\n log.addHandler(handler)\n\n def list(self, model, cols, page=1, per_page=DEFAULT_PER_PAGE):\n \"\"\"Return a list of records according to the Page and PerPage\n settings. Page must be greater than 0.\n\n :model: The Fluxx ModelObject you wish to query\n :page: Section of the total list to retrieve, must be greater than 0.\n :per_page: Number of records to return per page.\n :returns: None\n\n \"\"\"\n\n client = fluxx.FluxxClient.from_env(self.instance)\n records = client.list(model, cols=list(cols), page=page, per_page=per_page)\n\n sys.stdout.write(str(json.dumps(records)))\n\n def create(self, model, threads=DEFAULT_THREAD_COUNT):\n \"\"\"Creates each record provided in the list.\n\n :model: The Fluxx Model Object you wish to create.\n :returns: None\n\n \"\"\"\n\n with write_operation(self.instance, model, threads) as records:\n for record in records:\n record['method'] = 'CREATE'\n\n def update(self, model, threads=DEFAULT_THREAD_COUNT):\n \"\"\"Updates each record provided in the list.\n Each record must have an id.\n\n :model: The Fluxx Model Object you wish to update.\n :returns: None\n\n \"\"\"\n\n with write_operation(self.instance, model, threads) as records:\n for i, record in enumerate(records):\n record['method'] = 'UPDATE'\n\n def delete(self, model, threads=DEFAULT_THREAD_COUNT):\n \"\"\"Deletes each record provided in the list.\n Each record must have an id.\n\n :model: The Fluxx Model Object you wish to update.\n :returns: None\n\n \"\"\"\n\n with write_operation(self.instance, model, threads) as records:\n for i, record in enumerate(records):\n record['method'] = 'DELETE'\n\n def upsert(self, model, threads=DEFAULT_THREAD_COUNT):\n \"\"\"Creates or updates a each record provided in the list.\n The non-null status of the 'id' attribute of every record determines\n whether it will be created or updated, with None value IDs defaulting\n to creation.\n\n :model: The Fluxx ModelObject you wish to create.\n :returns: None\n\n \"\"\"\n\n with write_operation(self.instance, model, threads) as records:\n for i, record in enumerate(records):\n if 'id' in record:\n record['method'] = 'UPDATE'\n else:\n record['method'] = 'CREATE'\n\n\ndef main():\n fire.Fire(FluxxCLI)\n","sub_path":"fluxx/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":5499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"126547161","text":"from typing import List, Tuple, Any\nfrom contextlib import suppress\nfrom nboost.types import Request, Response, Choice\nfrom nboost.helpers import load_json, dump_json\nfrom nboost.exceptions import MissingQuery\nfrom nboost.codex.base import BaseCodex\n\n\nclass ESCodex(BaseCodex):\n \"\"\"Elasticsearch Codex\"\"\"\n SEARCH_PATH = '/.*/_search'\n\n def parse_query(self, request: Request) -> Tuple[Any, bytes]:\n \"\"\"try to get query from query params, then body\"\"\"\n body = load_json(request.body)\n\n # search for query in body\n if body:\n with suppress(KeyError):\n field, query = body['query']['match'].popitem()\n if isinstance(query, dict):\n query = query['query']\n return field, query.encode()\n\n # search for query in url\n with suppress(KeyError):\n field, *query = request.url.query['q'].split(':')\n return field, ':'.join(query).encode()\n\n raise MissingQuery\n\n def multiply_request(self, request: Request) -> Tuple[int, List[str]]:\n \"\"\"Multiply size of Elasticsearch query\"\"\"\n body = load_json(request.body)\n\n topk = request.url.query.pop('size', None)\n correct_cids = request.url.query.pop('nboost', None)\n\n # search for topk in body\n if body:\n correct_cids = body.pop('nboost', correct_cids)\n topk = body.pop('size', topk)\n\n topk = 10 if topk is None else int(topk)\n\n if body:\n body['size'] = topk * self.multiplier\n request.body = dump_json(body)\n else:\n request.url.query['size'] = str(topk * self.multiplier)\n\n correct_cids = correct_cids.split(',') if correct_cids else None\n return topk, correct_cids\n\n def parse_choices(self, response: Response, field: str) -> List[Choice]:\n \"\"\"Parse out Elasticsearch hits\"\"\"\n body = load_json(response.body)\n hits = body.get('hits', {'hits': []})['hits']\n return [Choice(\n hit['_id'], # cid\n hit['_source'][field].encode() # body\n ) for hit in hits]\n\n def reorder_response(self, request, response, ranks):\n \"\"\"Reorder Elasticsearch hits\"\"\"\n body = load_json(response.body)\n body['_nboost'] = '⚡NBOOST'\n\n body['hits']['hits'] = [body['hits']['hits'][rank] for rank in ranks]\n\n jkwargs = {'ensure_ascii': False}\n if 'pretty' in request.url.query:\n jkwargs.update({'indent': 2})\n\n response.body = dump_json(body, **jkwargs)\n","sub_path":"nboost/codex/es.py","file_name":"es.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"639817213","text":"# ---------------------------------------------------------------------\n# Cisco.IOS.get_ipv6_neighbor\n# ---------------------------------------------------------------------\n# Copyright (C) 2007-2012 The NOC Project\n# See LICENSE for details\n# ---------------------------------------------------------------------\n\n# Python modules\nimport re\n\n# NOC modules\nfrom noc.core.script.base import BaseScript\nfrom noc.sa.interfaces.igetipv6neighbor import IGetIPv6Neighbor\n\n\nclass Script(BaseScript):\n name = \"Cisco.IOS.get_ipv6_neighbor\"\n interface = IGetIPv6Neighbor\n\n rx_line = re.compile(\n r\"^(?P[0-9a-fA-F:\\.]+)\\s+\"\n r\"\\d+\\s+\"\n r\"(?P[0-9a-f]{4}\\.[0-9a-f]{4}\\.[0-9a-f]{4})\\s+\"\n r\"(?P\\S+)\\s+\"\n r\"(?P\\S+)\\s*$\"\n )\n\n s_map = {\n \"INCMP\": \"incomplete\",\n \"REACH\": \"reachable\",\n \"STALE\": \"stale\",\n \"DELAY\": \"delay\",\n \"PROBE\": \"probe\",\n }\n\n def execute_cli(self, vrf=None, **kwargs):\n # Get states\n cmd = \"show ipv6 neighbor\"\n r = self.cli(cmd, list_re=self.rx_line)\n # Remap states\n for n in r:\n n[\"state\"] = self.s_map[n[\"state\"]]\n return r\n","sub_path":"sa/profiles/Cisco/IOS/get_ipv6_neighbor.py","file_name":"get_ipv6_neighbor.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"604928313","text":"#\n# Copyright (c) 2016 Intel Corporation\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\nfrom retry import retry\n\nfrom modules.constants import TapComponent as TAP\nfrom modules.markers import components\nfrom modules.tap_logger import step\nfrom modules.tap_object_model import PlatformSnapshot\n\nlogged_components = (TAP.platform_snapshot,)\npytestmark = [components.platform_snapshot]\n\n\nclass TestSnapshot:\n\n @retry(AssertionError, tries=10, delay=3)\n def _get_new_snapshot(self, snapshots_before):\n step(\"Get new snapshot after triggering\")\n snapshots_after = PlatformSnapshot.api_get_snapshots()\n assert len(snapshots_after) > len(snapshots_before)\n return snapshots_after[0]\n\n def test_compare_snapshot_and_version(self):\n step(\"Get snapshots\")\n snapshots = PlatformSnapshot.api_get_snapshots()\n step(\"Get version\")\n version = PlatformSnapshot.api_get_version()\n assert snapshots[0] == version\n\n def test_trigger_snapshot(self):\n step(\"Get snapshots\")\n snapshots_before = PlatformSnapshot.api_get_snapshots()\n step(\"Get version\")\n version_before = PlatformSnapshot.api_get_version()\n step(\"Trigger new snapshot\")\n PlatformSnapshot.api_trigger_snapshots()\n new_snapshot = self._get_new_snapshot(snapshots_before=snapshots_before)\n step(\"Get new versions\")\n version_after = PlatformSnapshot.api_get_version()\n assert version_before != version_after\n assert new_snapshot == version_after\n","sub_path":"project/tests/test_functional/platform_snapshot/test_platform_snapshot.py","file_name":"test_platform_snapshot.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"527226575","text":"from flask import Blueprint\nfrom flask import render_template\nfrom models import User, Text\nfrom Txt.forms import EditTextForm\nfrom flask import request\nfrom app import db\n\ntxt = Blueprint('Txt', __name__, template_folder='templates', static_folder='static')\n\n@txt.route('/User-')\ndef txt_main(email):\n user = User.query.filter(User.email==email).first()\n print(user) \n texts = user.texts\n return render_template('texts.html', texts = texts)\n\n@txt.route('/Text-', methods = ['POST', 'GET'])\ndef text(id):\n t_object = Text.query.filter(Text.id==id).first()\n if request.method == 'POST':\n form = EditTextForm(formdata = request.form, obj = t_object)\n form.populate_obj(t_object)\n db.session.commit()\n form = EditTextForm(obj=t_object)\n name = form.name\n text = form.text\n return render_template('edit_text.html', form = form, t_object = t_object, text = text, name = name)","sub_path":"Txt/blueprint.py","file_name":"blueprint.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"572235918","text":"import requests\r\nimport urllib.parse\r\nimport re\r\n\r\nrequestedResults = 0\r\n\r\ndef bingSearch(query):\r\n headers = {\r\n \"Host\":\"www.bing.com\",\r\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36\",\r\n \"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\"\r\n \r\n }\r\n r = requests.get(\"https://www.bing.com/search?q=\" + urllib.parse.quote(f\"{query}\"), headers=headers, stream=True)\r\n return str(r.content)\r\n\r\ndef findQuizletMatches(webResponse):\r\n matches = re.findall(r\"