diff --git "a/6519.jsonl" "b/6519.jsonl" new file mode 100644--- /dev/null +++ "b/6519.jsonl" @@ -0,0 +1,735 @@ +{"seq_id":"151760640","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# placeholder.py --- short description\n#\n# Copyright (C) 2010 Martin Marcher \n#\n# Version:\n# Keywords:\n# Author: Martin Marcher \n# Maintainer: Martin Marcher \n# URL: http://\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation files\n# (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge,\n# publish, distribute, sublicense, and/or sell copies of the Software,\n# and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n__docformat__ = u'restructuredtext en'\n\n\nimport os\nimport sys\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageColor\nfrom PIL import ImageFont\nfrom PIL import ImageOps\n\n\nget_color = lambda name: ImageColor.getrgb(name)\n\nclass PlaceHolderImage(object):\n \"\"\"Create an image useable for wireframing websites.\n \"\"\"\n\n def __init__(self, width, height, path,\n fg_color=get_color('black'),\n bg_color=get_color('grey'),\n text=None,\n font=u'Verdana.ttf',\n fontsize=42,\n encoding=u'unic',\n mode='RGBA',\n fmt=u'PNG'):\n\n self.path = path\n self.width = width\n self.height = height\n self.size = width, height\n self.bg_color = bg_color\n self.fg_color = fg_color\n self.text = text if text else '{0}x{1}'.format(width, height)\n self.font = font\n self.fontsize = fontsize\n self.encoding = encoding\n self.mode = mode\n self.fmt = fmt\n\n def save_image(self):\n try:\n font = ImageFont.truetype(self.font, size=self.fontsize, encoding=self.encoding)\n except IOError:\n font = ImageFont.load_default()\n\n result_img = Image.new(self.mode, self.size, self.bg_color)\n\n text_size = font.getsize(self.text)\n text_img = Image.new(\"RGBA\", self.size, self.bg_color)\n\n #position for the text:\n left = self.size[0] / 2 - text_size[0] / 2\n top = self.size[1] / 2 - text_size[1] / 2\n\n drawing = ImageDraw.Draw(text_img)\n drawing.text((left, top),\n self.text,\n font=font,\n fill=self.fg_color)\n\n txt_img = ImageOps.fit(text_img, self.size, method=Image.BICUBIC, centering=(0.5, 0.5))\n\n result_img.paste(txt_img)\n txt_img.save(self.path, self.fmt)\n\n\n\n\n","sub_path":"placeholder/placeholder.py","file_name":"placeholder.py","file_ext":"py","file_size_in_byte":3274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"284427853","text":"import multiprocessing as mp\nimport pandas as pd\nimport time\nfrom math import ceil\nimport snowflake.connector\nfrom sqlalchemy.dialects import registry\nregistry.register('snowflake', 'snowflake.sqlalchemy', 'dialect')\n\n\ndef test(start, end, total_limit):\n cursor = snowflake.connector.connect(\n user='',\n account='',\n password='',\n warehouse='',\n database='',\n schema=''\n ).cursor()\n sql = f\"select pos, chrstart, chrstop, qual, ref, an, crf, dp, gc, mq, mq0, ns, qd, rfgq_all from (\" \\\n f\"select row_number() over (order by 1) as row_num, * from (select * from WGS_SAMPLE_WGS limit {total_limit})) \" \\\n f\"where row_num >={start} and row_num <{end + 1}\"\n cursor.execute(sql)\n df = cursor.fetch_pandas_all()\n return df\n\n\nif __name__ == '__main__':\n processes = 12\n total_limit = 50_000_000\n print(f'running {total_limit} rows with {processes} processes')\n nums = list(range(0, total_limit + int(ceil(total_limit / processes)), int(ceil(total_limit / processes))))\n arg_list = [(nums[i], nums[i+1], total_limit) for i in range(len(nums) - 1)]\n pool = mp.Pool(processes=processes)\n t0 = time.time()\n tasks = [pool.apply_async(test, args) for args in arg_list]\n results = pd.concat([p.get() for p in tasks]).groupby(\"REF\").sum()\n print(f\"df creation + groupby + sum time: {round(time.time() - t0, 3)}\")\n","sub_path":"multiprocessing_pyarrow_test.py","file_name":"multiprocessing_pyarrow_test.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"412513068","text":"from django.db import models\nfrom datetime import datetime, timedelta\n\nfrom .verify import *\n\n# Create your models here.\n\nclass User(models.Model):\n # id : integer\n ROLES = (\n ('U', 'User'),\n ('A', 'Admin'),\n ('M', 'Moderator')\n )\n\n first_name = models.CharField(max_length=30)\n last_name = models.CharField(max_length=30)\n email = models.CharField(max_length=50)\n student_id = models.CharField(max_length=7, unique=True) # 1305011 style\n password = models.CharField(max_length=30)\n mobile_no = models.CharField(max_length=11, null=True, blank=True)\n address = models.CharField(max_length=100, null=True, blank=True)\n profile_picture = models.ImageField(upload_to='profile_picture/', default='profile_picture/default-user.png')\n role = models.CharField(max_length=1, default='U', choices=ROLES)\n\n def __str__(self):\n return self.student_id\n\n def save(self, *args, **kwargs):\n if (verifyUser(self)):\n super(User, self).save(*args, **kwargs)\n else:\n raise Exception\n 'user information is invalid'\n\n\n\nclass Author(models.Model):\n # id : integer\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n\n\nclass Book(models.Model):\n # id : integer\n APROVAL_STATUSES = (\n ('P', 'Pending'),\n ('A', 'Approved'),\n )\n name = models.CharField(max_length=50)\n authors = models.ManyToManyField(Author)\n categories = models.ManyToManyField(Category, blank=True)\n cover_picture = models.ImageField(upload_to='book_picture/', default='book_picture/default-book.png')\n approval_status = models.CharField(max_length=1, default='A', choices=APROVAL_STATUSES)\n\n @property\n def author_list(self):\n list = \"\"\n for author in self.authors.all():\n list = list + author.name + ', '\n return list[:-2]\n\n def __str__(self):\n return self.name\n\n\nclass Product(models.Model):\n # id : integer\n PRINT_STATUSES = (\n ('A', 'American'),\n ('I', 'Indian'),\n ('P', 'Photocopy'),\n )\n CONDITIONS = (\n ('G', 'Good'),\n ('M', 'Medium'),\n ('B', 'Bad'),\n )\n CONFIRMATIONS = (\n ('N', 'No Confirmation'),\n ('O', 'Owner Confirmed'),\n ('R', 'Receiver Confirmed'),\n ('B', 'Both Side Confirmation'),\n )\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\n book = models.ForeignKey(Book, on_delete=models.CASCADE)\n print_status = models.CharField(max_length=1, null=True, blank=True, choices=PRINT_STATUSES)\n condition = models.CharField(max_length=1, null=True, blank=True, choices=CONDITIONS)\n edition = models.IntegerField(null=True, blank=True)\n price = models.IntegerField(default=0)\n date_time = models.DateTimeField(default=datetime.now, blank=True)\n confirmation = models.CharField(max_length=1, null=True, blank=True, choices=CONFIRMATIONS)\n\n @property\n def serial_count(self):\n return Serial.objects.filter(product=self).count()\n\n class Meta:\n unique_together = ((\"owner\", \"book\"),)\n\n def __str__(self):\n return self.book.name + ' from ' + self.owner.student_id\n\n def save(self, *args, **kwargs):\n if (verifyProduct(self)):\n super(Product, self).save(*args, **kwargs)\n else:\n raise Exception\n 'product information is invalid'\n\n @property\n def isBooked(self):\n return Product.objects.filter(currentholder__product_id=self.id).count() == 1\n\n def condition_verbose(self):\n return dict(Product.CONDITIONS)[self.condition]\n\n def print_status_verbose(self):\n return dict(Product.PRINT_STATUSES)[self.print_status]\n\n\nclass Serial(models.Model):\n product = models.ForeignKey(Product, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n serial_no = models.IntegerField()\n\n class Meta:\n unique_together = ((\"product\", \"user\"),)\n\n def __str__(self):\n return self.product.book.name + ' - ' + self.user.student_id + ' - ' + str(self.serial_no)\n\n def save(self, *args, **kwargs):\n if (self.serial_no > 0):\n super(Serial, self).save(*args, **kwargs)\n else:\n raise Exception\n 'serial information is invalid'\n\n\nclass CurrentHolder(models.Model):\n # serial = models.ForeignKey(Serial, on_delete=models.CASCADE)\n product = models.ForeignKey(Product, on_delete=models.CASCADE, unique=True)\n holder = models.ForeignKey(User, on_delete=models.CASCADE)\n date_time = models.DateTimeField(default=datetime.now, blank=True)\n\n @property\n def last_time(self):\n return self.date_time + timedelta(days=3)\n\n def __str__(self):\n return self.product.book.name + ' - ' + self.holder.student_id\n\n\nclass Notification(models.Model):\n NOTIFICATIONS = (\n ('CH', 'Current Holding'),\n ('TH', 'Timeout Holding'),\n ('BB', 'Book Booked'),\n )\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n product = models.ForeignKey(Product, null=True, blank=True, on_delete=models.CASCADE)\n title = models.CharField(max_length=50)\n text = models.CharField(max_length=100)\n link = models.CharField(max_length=100, null=True, blank=True)\n type = models.CharField(max_length=2, choices=NOTIFICATIONS)\n date_time = models.DateTimeField(default=datetime.now, blank=True)\n\n def __str__(self):\n return self.user.student_id + ' - ' + self.type","sub_path":"userapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"624401131","text":"def matrix_to_dic(filepath):\n filein = open(filepath, \"r\")\n char_list = filein.readline().rstrip().split()\n value_list = []\n for line in filein:\n value_list.append(line.rstrip().split()[1:])\n filein.close()\n score_dic = {}\n for i in range(len(char_list)):\n for j in range(len(char_list)):\n curr_key = char_list[i] + char_list[j]\n score_dic[curr_key] = int(value_list[i][j])\n return score_dic\n\n\ndef score_seq(seq1, seq2, score_dic):\n tot_score = 0\n for i in range(len(seq1)):\n curr_pair = seq1[i] + seq2[i]\n curr_score = score_dic[curr_pair]\n tot_score += curr_score\n return tot_score\n\n\nmatrix_file = \"../data/blosum.txt\"\nsample_seq1 = \"ARND\"\nsample_seq2 = \"ARND\"\nblosum = matrix_to_dic(matrix_file)\nscore = score_seq(sample_seq1, sample_seq2, blosum)\nprint(score)\n","sub_path":"python_unibo/scripts/blosum_score.py","file_name":"blosum_score.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"86835740","text":"#!/usr/local/bin/python3\n# -*- coding:utf-8 -*-\n\"\"\"\n@author: \n@file: 50. Pow(x, n).py\n@time: 2020/5/11 08:56\n@desc: \n\"\"\"\nfrom typing import List\n\"\"\"\n实现 pow(x, n) ,即计算 x 的 n 次幂函数。\n\n示例 1:\n\n输入: 2.00000, 10\n输出: 1024.00000\n示例 2:\n\n输入: 2.10000, 3\n输出: 9.26100\n示例 3:\n\n输入: 2.00000, -2\n输出: 0.25000\n解释: 2-2 = 1/22 = 1/4 = 0.25\n说明:\n\n-100.0 < x < 100.0\nn 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。\n\"\"\"\n\nclass Solution:\n def myPow(self, x: float, n: int) -> float:\n # 递归 + 快速幂\n # def quickPow(N):\n # if N == 0:\n # return 1\n # y = quickPow(N//2)\n # return y * y if not N % 2 else y * y * x\n # return quickPow(n) if n >= 0 else 1.0 / quickPow(-n)\n #\n # if n == 0:\n # return 1\n # if n == 1:\n # return x\n # res = 1\n # tmp_n = abs(n)\n # while tmp_n:\n # if tmp_n & 1:\n # res *= x\n # x *= x\n # tmp_n >>= 1\n # return res if n > 0 else 1/res\n\n\n ans = 1\n a_n = abs(n)\n while a_n:\n if a_n & 1:\n ans *= x\n x *= x\n a_n >>= 1\n return ans if n > 0 else 1 / ans\n\n\n\n\na = Solution().myPow(2,10)\nprint(a)","sub_path":"bit_operation/50. Pow(x, n).py","file_name":"50. Pow(x, n).py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8539351","text":"from __future__ import absolute_import\nfrom .exceptions import BadValueError\n\n\ndef check_type(obj, item_type, message):\n if obj is None:\n return item_type()\n elif not isinstance(obj, item_type):\n raise BadValueError(message)\n else:\n return obj\n\n\nclass SimpleDict(dict):\n \"\"\"\n Re-implements destructive methods of dict\n to use only setitem and getitem and delitem\n \"\"\"\n def update(self, E=None, **F):\n for dct in (E, F):\n if dct:\n for key, value in dct.items():\n self[key] = value\n\n def clear(self):\n for key in self.keys():\n del self[key]\n","sub_path":"jsonobject/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"361217161","text":"import numpy as np\r\nimport random\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nfrom JobDataExtraction import JobDataExtraction\r\nfrom os import listdir, walk, getcwd\r\nfrom os.path import isfile, join\r\nimport pickle\r\nfrom datetime import datetime\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.datasets import make_regression\r\nfrom sklearn import svm\r\nfrom sklearn import linear_model\r\n\r\nseed = 128 \r\nrng = np.random.RandomState(seed)\r\n\r\ndef batch_creator(batch_size, dataset_length, dataset_name, nParam, train_x, train_y):\r\n #\"\"\"Create batch with random samples and return appropriate format\"\"\"\r\n batch_mask = rng.choice(dataset_length, batch_size)\r\n \r\n batch_x = eval(dataset_name + '_x')[[batch_mask]].reshape(-1, nParam)\r\n #batch_x = preproc(batch_x)\r\n \r\n if dataset_name == 'train':\r\n batch_y = train_y[batch_mask] \r\n return batch_x, batch_y\r\n\r\ndef ArrayShuffle(vect):\r\n for i in range(len(vect)):\r\n r=random.randint(0,i)\r\n swap = vect[i]\r\n vect[i] = vect[r]\r\n vect[r] = swap\r\n return vect\r\n\r\n### Load training examples\r\nExtractObj = JobDataExtraction() \r\n \r\n# Get all Job data of interest\r\nDataDir = 'C:\\\\Users\\\\SCatheline\\\\OneDrive - Schlumberger\\\\Testing Project\\\\MUZIC\\\\Nahomi Project\\\\Completed'\r\n\r\nSubDir = [f for f in listdir(DataDir) if not isfile(join(DataDir, f))]\r\nfor DiR in SubDir:\r\n ExtractObj.AddJob(DataDir+ '\\\\' +DiR)\r\n\r\n#Add communication data from the MuzicJob Analysis tool\r\nComDir = \"C:\\\\Users\\\\SCatheline\\\\OneDrive - Schlumberger\\\\Testing Project\\\\MUZIC\\Matlab code\\\\Statistical Analysis\\\\JobDataExtraction\\\\JobData\"\r\n\r\nSubDir = [f for f in listdir(ComDir) if not isfile(join(ComDir, f))]\r\nfor DiR in SubDir:\r\n ExtractObj.AddComData(ComDir+ '\\\\' +DiR) \r\n\r\nExtractObj.CreateDictTraining()\r\n\r\nExtractObj.CleanTrainingEx()\r\n\r\nFileCompress = 'C:\\\\Users\\\\SCatheline\\\\OneDrive - Schlumberger\\\\Testing Project\\\\MUZIC\\\\Nahomi Project\\\\Completed\\\\ToolCompression.txt'\r\nExtractObj.CompressFeatures(FileCompress)\r\n\r\nFeatureMat = ExtractObj.FeatureTrainMat\r\nOutputVect = ExtractObj.OutputTrainVect\r\n\r\n## Rescale data so that the max of each column is 1 (max = 1)\r\nfor i in range(FeatureMat.shape[1]):\r\n FeatureMat[:,i] = FeatureMat[:,i]/max(abs(FeatureMat[:,i]))\r\n \r\nnParam = FeatureMat.shape[1]\r\ntrain_x = FeatureMat\r\ntrain_y = OutputVect\r\n\r\n### Separate training and validationb data\r\n#Shuffle the exemple vector\r\nshuffle = np.linspace(0,train_x.shape[0]-1,train_x.shape[0],dtype=int)\r\n\r\nshuffle = ArrayShuffle(shuffle)\r\n \r\nsplit_size = int(train_x.shape[0]*0.70)\r\n\r\ntrain_x, val_x = train_x[shuffle[:split_size]][:], train_x[shuffle[split_size:]][:]\r\ntrain_y, val_y = train_y[shuffle[:split_size]][:], train_y[shuffle[split_size:]][:]\r\n\r\ntrain_y =np.ravel(train_y)\r\nval_y =np.ravel(val_y)\r\n\r\n## Random Forest regression\r\nprint('\\n')\r\nprint('Start regression')\r\nregr = RandomForestRegressor(max_depth=10, random_state=0,verbose=1,n_estimators=10,n_jobs=-1)\r\nregr.get_params()\r\n#regr.set_params(n_estimators=10)\r\nregr.fit(train_x, train_y)\r\nprint('\\n')\r\nprint(regr.feature_importances_)\r\n\r\noutTrain = regr.predict(train_x)\r\nMeanErrorTrain = np.mean(abs(outTrain-train_y))\r\nprint('Mean training error random forest: {0}'.format(MeanErrorTrain))\r\nprint('\\n')\r\noutVal= regr.predict(val_x)\r\nMeanErrorVal = np.mean(abs(outVal-val_y))\r\nprint('Mean validation error random forest: {0}'.format(MeanErrorVal))\r\nprint('\\n')\r\n\r\n#fig1=plt.figure()\r\n#plt.plot(outTrain,'-r')\r\n#plt.plot(train_y,'-b')\r\n#\r\n# \r\n#fig2=plt.figure()\r\n#plt.plot(outVal,'-r')\r\n#plt.plot(val_y,'-b')\r\n#\r\n#fig3=plt.figure()\r\n#plt.plot(abs(outVal-val_y),'-r')\r\n\r\n\r\n\r\n### Evaluate SVM\r\nclf = svm.NuSVR(kernel='rbf')\r\nclf.fit(train_x, train_y)\r\n\r\noutTrainSVM = clf.predict(train_x)\r\n\r\nMeanErrorTrainSVM = np.mean(abs(outTrainSVM-train_y))\r\nprint('Mean training error SVM: {0}'.format(MeanErrorTrainSVM))\r\nprint('\\n')\r\noutValSVM= clf.predict(val_x)\r\nMeanErrorValSVM = np.mean(abs(outValSVM-val_y))\r\nprint('Mean validation error SVM: {0}'.format(MeanErrorValSVM))\r\nprint('\\n')\r\n\r\n\r\n### Evaluate linear model\r\n#reg = linear_model.Lasso(alpha = 0.1) #(36/22%)\r\n#reg = linear_model.BayesianRidge() #(22/22%)\r\nreg = linear_model.Ridge (alpha = .5) #(22/21%)\r\n#reg = linear_model.LinearRegression() #(20/20%)\r\nreg.fit(train_x, train_y)\r\n\r\noutTrainlinear = reg.predict(train_x)\r\n\r\nMeanErrorTrainlinear= np.mean(abs(outTrainlinear-train_y))\r\nprint('Mean training error linear: {0}'.format(MeanErrorTrainlinear))\r\nprint('\\n')\r\noutVallinear= clf.predict(val_x)\r\nMeanErrorVallinear = np.mean(abs(outVallinear-val_y))\r\nprint('Mean validation error linear: {0}'.format(MeanErrorVallinear))\r\nprint('\\n')\r\n\r\n\r\n##\r\na=regr.feature_importances_\r\nprint('\\n')\r\nfor i in range(len(a)):\r\n print('{0} | {1:0.2f}%'.format(ExtractObj.FeatureTrainingDict['Name'][i],a[i]*100))","sub_path":"ML Python examples/PredictComRandomForest.py","file_name":"PredictComRandomForest.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"55895457","text":"import time\nimport numpy as np\n\nclass Search():\n F3_F2 = [0, 60]\n F2_F1 = [20, 40]\n F1_B1c = [0, 30] \n st = [False]*5\n f = [1, 2, 0, 1, 2]\n\n def __init__(self, results_53, results_35): \n self.results_53 = results_53\n self.results_35 = results_35\n self.lens = [len(results_35), len(results_53)]\n self.search_primers = []\n\n def get_primers(self):\n return self.search_primers\n\n def nucls(self, result1, result2):\n \"\"\" Проверка, что весь набор лежит в диапазоне 280 нуклеотидов \"\"\"\n if result2[0] - result2[1][1] - result1[0] <= 280:\n return True\n return False\n\n def check(self, primer1, result1, result2, dist):\n \"\"\" Проверка праймеров на условия (расстояние) \"\"\"\n nuclsnum = self.nucls(primer1, result2)\n if not nuclsnum:\n return False\n\n if result2[0] - result2[1][1] - result1[0] > dist[0]:\n if result2[0] - result2[1][1] - result1[0] <= dist[1]:\n if result1[1][0] == result2[1][0] or abs(result1[1][1] - result2[1][1]) > 3: \n return 2\n else:\n return True\n else:\n return False\n \n return 2\n\n def start_search_set(self):\n \"\"\" Запуск создания наборов \"\"\"\n for f_ind in range(self.lens[0]):\n self.st = [False]*5\n self.set_primers(sc=1, indexes=[f_ind, 0, 0, 0, 0, 0])\n\n def set_primers(self, sc, indexes):\n \"\"\" Основной алгоритм \"\"\"\n for ind in range(self.f[sc-1], self.lens[sc % 2]):\n if sc % 2 == 0:\n step = self.check(self.results_53[indexes[0]], self.results_53[indexes[sc-1]], self.results_35[ind], self.F2_F1)\n else:\n if sc == 1:\n step = self.check(self.results_53[indexes[0]], self.results_53[indexes[sc-1]], self.results_53[ind], self.F3_F2)\n elif sc == 3:\n step = self.check(self.results_53[indexes[0]], self.results_35[indexes[sc-1]], self.results_53[ind], self.F1_B1c)\n else:\n step = self.check(self.results_53[indexes[0]], self.results_35[indexes[sc-1]], self.results_35[ind], self.F3_F2)\n\n if step == 1:\n if not self.st[sc-1]:\n self.f[sc-1] = ind\n self.st[sc-1] = True\n \n indexes[sc] = ind\n\n if sc == 5:\n self.search_primers.append(indexes)\n else:\n self.set_primers(sc+1, indexes)\n elif not step:\n return None\n \n return None","sub_path":"search_algorithms/searchclass.py","file_name":"searchclass.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"194272764","text":"import paramiko\r\nfrom cloudshell.helpers.scripts import cloudshell_scripts_helpers as helper\r\nimport re\r\n\r\nRES_ID = None\r\nRES_NAME = None\r\nAPI = None\r\n\r\ndef _ssh_write(ssh, channel, command):\r\n\r\n channel.send(command)\r\n\r\n\r\n\r\ndef _ssh_read(ssh, channel, prompt_regex):\r\n\r\n rv = ''\r\n\r\n while True:\r\n # self.channel.settimeout(30)\r\n\r\n r = channel.recv(2048)\r\n\r\n if r:\r\n rv += r\r\n if rv:\r\n t = rv\r\n t = re.sub(r'(\\x9b|\\x1b)[[?;0-9]*[a-zA-Z]', '', t)\r\n t = re.sub(r'(\\x9b|\\x1b)[>=]', '', t)\r\n t = re.sub('.\\b', '', t) # not r''\r\n else:\r\n t = ''\r\n if not r or len(re.findall(prompt_regex, t)) > 0:\r\n rv = t\r\n if rv:\r\n rv = rv.replace('\\r', '\\n')\r\n\r\n return rv\r\n\r\n\r\ndef _ssh_command(ssh, channel, command, prompt_regex):\r\n global RES_ID\r\n global RES_NAME\r\n global API\r\n if API:\r\n API.WriteMessageToReservationOutput(RES_ID,\r\n RES_NAME + ' sending command \"' + command + '\"')\r\n _ssh_write( ssh, channel, command + '\\n')\r\n rv = _ssh_read( ssh, channel, prompt_regex)\r\n if '\\n%' in rv.replace('\\r', '\\n'):\r\n es = 'CLI error message: ' + rv\r\n\r\n raise Exception(es)\r\n if API:\r\n API.WriteMessageToReservationOutput(RES_ID,\r\n '-- command \" complete')\r\n return rv\r\n\r\nresource_context = helper.get_resource_context_details()\r\nreservation_context = helper.get_reservation_context_details()\r\nRES_ID = reservation_context.id\r\nRES_NAME = resource_context.name\r\nAPI = helper.get_api_session()\r\nsession = paramiko.SSHClient()\r\nsession.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\nsession.connect(resource_context.address, 22, 'root','amdocs')\r\n\r\nchannel = session.invoke_shell()\r\nprompt = '.*]#'\r\n_ssh_command(session, channel, 'mkdir -p /stage', prompt)\r\n_ssh_command(session, channel, 'scp root@10.53.212.107:/stage/BSR9.9/sdb/* /stage/', '.*yes/no.*')\r\n_ssh_command(session, channel, 'yes','.*password.*')\r\n_ssh_command(session, channel, 'amdocs','.*]#')\r\n_ssh_command(session, channel, 'scp root@10.53.212.105:/stage/iso/* /stage/', '.*yes/no.*')\r\n_ssh_command(session, channel, 'yes','.*password.*')\r\n_ssh_command(session, channel, 'amdocs', '.*]#')\r\n","sub_path":"scripts/Python/SDBpulll.py","file_name":"SDBpulll.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"139063799","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2010 Smile (). All Rights Reserved\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp import api, fields, models, _\nfrom openerp.exceptions import Warning\nfrom openerp.tools.safe_eval import safe_eval as eval\n\n\nclass AuditLog(models.Model):\n _name = 'audit.log'\n _description = 'Audit Log'\n _order = 'create_date desc'\n\n name = fields.Char('Resource Name', size=256, compute='_get_name')\n create_date = fields.Datetime('Date', readonly=True)\n user_id = fields.Many2one('res.users', 'User', required=True, readonly=True)\n model_id = fields.Many2one('ir.model', 'Object', required=True, readonly=True)\n res_id = fields.Integer('Resource Id', readonly=True)\n method = fields.Char('Method', size=64, readonly=True)\n data = fields.Text('Data', readonly=True)\n data_html = fields.Html('HTML Data', readonly=True, compute='_render_html')\n\n @api.one\n def _get_name(self):\n if self.model_id and self.res_id:\n record = self.env[self.model_id.model].browse(self.res_id).exists()\n if record:\n self.name = record.display_name\n else:\n data = eval(self.data or '{}')\n rec_name = self.env[self.model_id.model]._rec_name\n if rec_name in data['new']:\n self.name = data['new'][rec_name]\n elif rec_name in data['old']:\n self.name = data['old'][rec_name]\n else:\n self.name = 'id=%s' % self.res_id\n else:\n self.name = ''\n\n @api.multi\n def _get_fields_by_name(self):\n self.ensure_one()\n model = self.env[self.model_id.model]\n fields_by_model = {}\n for field in model._inherit_fields:\n fields_by_model.setdefault(model._inherit_fields[field][3], []).append(field)\n fields_by_model[model._name] = list(set(model._fields.keys()) - set(model._inherit_fields.keys()))\n fields_by_name = {}\n for model in fields_by_model:\n field_recs = self.env['ir.model.fields'].sudo().search([('model_id.model', '=', model),\n ('name', 'in', fields_by_model[model])])\n fields_by_name.update(dict([(field.name, field) for field in field_recs]))\n return fields_by_name\n\n @api.model\n def _format_value(self, field, value):\n if not value and field.ttype not in ('boolean', 'integer', 'float'):\n return ''\n if field.ttype == 'selection':\n selection = self.env[field.model]._fields[field.name].selection\n if callable(selection):\n selection = selection(self.env[field.model])\n return dict(selection).get(value, value)\n if field.ttype == 'many2one' and value:\n return self.env[field.relation].browse(value).exists().display_name or value\n if field.ttype == 'reference' and value:\n res_model, res_id = value.split(',')\n return self.env[res_model].browse(int(res_id)).exists().display_name or value\n if field.ttype in ('one2many', 'many2many') and value:\n return ', '.join([self.env[field.relation].browse(rec_id).exists().display_name or str(rec_id)\n for rec_id in value])\n if field.ttype == 'binary' and value:\n return '<binary data>'\n return value\n\n @api.multi\n def _get_content(self):\n content = []\n data = eval(self.data or '{}')\n fields_by_name = self._get_fields_by_name()\n for fname in set(data['new'].keys() + data['old'].keys()):\n if fname in fields_by_name:\n field = fields_by_name[fname]\n old_value = self._format_value(field, data['old'].get(fname, ''))\n new_value = self._format_value(field, data['new'].get(fname, ''))\n content.append((field.field_description, old_value, new_value))\n return content\n\n @api.one\n def _render_html(self):\n thead = ''\n for head in (_('Field'), _('Old value'), _('New value')):\n thead += '%s' % head\n thead = '%s' % thead\n tbody = ''\n for line in self._get_content():\n row = ''\n for item in line:\n row += '%s' % item\n tbody += '%s' % row\n tbody = '%s' % tbody\n self.data_html = '%s%s
' % (thead, tbody)\n\n @api.multi\n def unlink(self):\n raise Warning(_('You cannot remove audit logs!'))\n","sub_path":"smile_audit/models/audit_log.py","file_name":"audit_log.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"55973283","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 8 14:01:20 2016\r\n\r\n@author: Vladislav\r\n\"\"\"\r\n\r\nimport datasets\r\nimport constants\r\nimport math\r\n\r\nfrom probabilitiesTools import calculateHistogramForDataset, printHistogramsComparison\r\n\r\ndef calculateLettersAveragePositionsForDataset(dataset):\r\n lettersCount = {}\r\n lettersAveragePositions = {}\r\n \r\n for character in constants.ALLOWED_CHARACTERS:\r\n lettersCount[character] = 0\r\n lettersAveragePositions[character] = 0\r\n\r\n print(\"Calculating letters average positions...\")\r\n \r\n for word in dataset:\r\n length = len(word)\r\n for position in range(0, length):\r\n letter = word[position]\r\n relativePosition = position / max(1, length-1)\r\n lettersCount[letter] += 1\r\n lettersAveragePositions[letter] += relativePosition \r\n \r\n for letter in lettersCount:\r\n lettersAveragePositions[letter] /= lettersCount[letter]\r\n\r\n return lettersAveragePositions\r\n\r\ndef calculateWordDistanceL1FromAverage(lettersAveragePositions, word):\r\n distance = 0.0\r\n for position in range(0, len(word)):\r\n letter = word[position]\r\n relativePosition = position / max(1, len(word)-1)\r\n value = relativePosition - lettersAveragePositions[letter]\r\n distance += abs(value)\r\n return distance\r\n \r\ndef calculateWordDistanceL2FromAverage(lettersAveragePositions, word):\r\n distance = 0.0\r\n for position in range(0, len(word)):\r\n letter = word[position]\r\n relativePosition = position / max(1, len(word)-1)\r\n value = relativePosition - lettersAveragePositions[letter]\r\n distance += value*value \r\n return math.sqrt(distance)\r\n \r\nPROBABILITY_THRESHOLDS = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95]\r\ndataset = datasets.loadTrainingPositiveDatasetFromFile()\r\nlettersAveragePositions = calculateLettersAveragePositionsForDataset(dataset)\r\n\r\ndef wordDistanceClassifier(lettersProbabilities, word):\r\n distanceL1 = calculateWordDistanceL1FromAverage(lettersProbabilities,\r\n word)\r\n distanceL2 = calculateWordDistanceL2FromAverage(lettersProbabilities,\r\n word)\r\n return [distanceL1, distanceL2]\r\n\r\ndef getLettersAveragePositions():\r\n return lettersAveragePositions\r\n \r\ndef wordPositionsDistanceFeature(word):\r\n return wordDistanceClassifier(lettersAveragePositions, word)\r\n \r\nif __name__ == \"__main__\":\r\n \r\n print(\"Calculating distances for positive dataset...\")\r\n histogram1 = calculateHistogramForDataset(dataset, lettersAveragePositions, PROBABILITY_THRESHOLDS, wordDistanceClassifier)\r\n \r\n datasetNeg = datasets.loadTrainingNegativeDatasetFromFile()\r\n print(\"Calculating distances for negative dataset...\")\r\n histogram2 = calculateHistogramForDataset(datasetNeg, lettersAveragePositions, PROBABILITY_THRESHOLDS, wordDistanceClassifier)\r\n \r\n printHistogramsComparison(dataset, datasetNeg, histogram1, histogram2)\r\n\r\n print(\"Done\")","sub_path":"submissions/5748a97463905b3a11d97ca6/src/lettersPositionsDistance.py","file_name":"lettersPositionsDistance.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"455178024","text":"def pairwise_probability_calculation(p_a, p_b):\n pr_a = 1 / float((10 ** -(p_a.rating - p_b.rating) / float(400)) + 1)\n\n win_p_a = pr_a\n lose_p_b = pr_a\n win_p_b = 1 - pr_a\n lose_p_a = 1 - pr_a\n\n return {\n p_a.player_id: {\n 'win': win_p_a,\n 'lose': lose_p_a\n },\n p_b.player_id: {\n 'win': win_p_b,\n 'lose': lose_p_b\n }\n }\n","sub_path":"core/modules/probability.py","file_name":"probability.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"188548023","text":"# this file is deprecated pretty much \nclass Game:\n def __init__(self):\n self.role = \"game\"\n\n def attack_handler(self, anActor, target):\n damageDealt = 0\n atk = anActor.attack()\n if target.status == \"defending\":\n damageDealt = atk - target.defPoints\n else:\n damageDealt = atk\n target.hp -= damageDealt\n return check_status(anActor)\n # for situations where there is damage coming in from a non attacking obj\n\n def defend_handler(self, anActor, incomingDmg):\n damageDealt = 0\n if anActor.status == \"defending\":\n damageDealt = anActor.defPoints - incomingDmg\n return check_status(anActor)\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"312064649","text":"from glob import glob\nimport vtk\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom numpy.linalg import solve\nfrom matplotlib import pyplot as plt\nfrom sklearn import linear_model\n\ndef get_range_image(path,outFileName,angle,factor):\n reader = vtk.vtkSTLReader()\n reader.SetFileName(path)\n \n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(reader.GetOutputPort())\n actor = vtk.vtkActor()\n actor.SetMapper(mapper)\n \n myTrans = vtk.vtkTransform()\n myTrans.RotateX(angle)\n #myTrans.Translate(0,0,100)\n actor.SetUserTransform(myTrans)\n \n renderer = vtk.vtkRenderer()\n renderWindow = vtk.vtkRenderWindow()\n renderWindow.AddRenderer(renderer)\n renderWindowInteractor = vtk.vtkRenderWindowInteractor()\n renderWindowInteractor.SetRenderWindow(renderWindow)\n renderer.AddActor(actor)\n renderer.SetBackground(0,0,0)\n renderWindow.Render()\n \n #renderWindowInteractor.Start()\n #Create Depth Map\n filt = vtk.vtkWindowToImageFilter()\n imageWriter = vtk.vtkBMPWriter()\n scale = vtk.vtkImageShiftScale()\n filt.SetInput(renderWindow)\n filt.SetScale(factor)\n filt.SetInputBufferTypeToZBuffer()\n #filt.Update()\n \n scale.SetOutputScalarTypeToUnsignedChar()\n scale.SetInputConnection(filt.GetOutputPort())\n scale.SetShift(0)\n scale.SetScale(-255)\n \n #write image data to hard disk\n imageWriter.SetFileName(outFileName)\n imageWriter.SetInputConnection(scale.GetOutputPort())\n imageWriter.Write()\n \ndef SobelEdgeDetection(image_data,thresh):\n _,gray = cv2.threshold(image_data,thresh,255,cv2.THRESH_TOZERO)\n \n lap = cv2.Laplacian(gray,cv2.CV_64F)\n binary_mask1 = np.zeros_like(lap)\n binary_mask1[lap<0]=1\n \n p = cv2.Sobel(gray,cv2.CV_64F,1,0)\n q = cv2.Sobel(gray,cv2.CV_64F,0,1)\n sobx = np.uint8(np.absolute(p))\n soby = np.uint8(np.absolute(q))\n \n #calculate magnitude\n gradmag = np.sqrt(p**2+q**2)\n gradmag[np.where(gradmag==0)] +=0.0001\n sx = cv2.Sobel(q/gradmag,cv2.CV_64F,0,1)\n sy = cv2.Sobel(q/gradmag,cv2.CV_64F,1,0)\n cx = cv2.Sobel(p/gradmag,cv2.CV_64F,0,1)\n cy = cv2.Sobel(p/gradmag,cv2.CV_64F,1,0)\n D = np.sqrt(sx**2+sy**2+cx**2+cy**2)\n mean_overall = np.mean(D)\n std_overall = np.std(D)\n thresh = mean_overall+std_overall\n binary_mask2 = np.zeros_like(D)\n binary_mask2[D>thresh]=1\n \n sobel = cv2.bitwise_or(sobx,soby)\n binary_mask0 = np.zeros_like(D)\n binary_mask0[sobel>(np.mean(sobel)+np.std(sobel))] = 1\n \n sobel_d2 = cv2.bitwise_and(binary_mask1,D)\n sobel_d2 = cv2.bitwise_and(binary_mask2,sobel_d2)\n sobel_edge = cv2.bitwise_and(binary_mask0,sobel_d2)\n \n blank_rgb_image = np.zeros((image_data.shape[0],image_data.shape[1],3),np.uint8)\n blank_rgb_image[np.where(sobel_edge==0)] = (255,255,255)\n blank_rgb_image[np.where(sobel_edge==1)] = (0,0,0)\n \n \"\"\"\n cv2.imshow(\"final image\",blank_rgb_image)\n cv2.waitKey(0)\n blank_rgb_image[np.where(sobel_d2==0)]=(255,255,255)\n blank_rgb_image[np.where(sobel_d2==1)]=(0,0,0)\n cv2.imshow(\"middle image\",blank_rgb_image)\n cv2.waitKey(0)\n \n \n plt.subplot(121),plt.imshow(sobel_d2,cmap=\"gray\")\n plt.title(\"middle edge\"),plt.xticks([]),plt.yticks([])\n plt.subplot(122),plt.imshow(sobel_edge,cmap=\"gray\")\n plt.title(\"fial edge\"),plt.xticks([]),plt.yticks([])\"\"\"\n \n return sobel_d2\n\ndef da_polynomial(x,D,W):\n ratio = x/W\n if abs(ratio)>0.5:\n if ratio<0:\n ratio = -0.5\n else:\n ratio = 0.5\n return 3.0314*D*(ratio+0.5)**0.8*(0.5-ratio)**0.8\n\ndef solve_poly(times,x_array,y_array,alpha):\n m = len(x_array)\n A = np.ones(m).reshape((m,1))\n for index in range(times):\n A = np.hstack([A,(x_array**(index+1)).reshape((m,1))])\n A = alpha.reshape((alpha.shape[0],1))*A\n y_array = alpha*y_array\n X = solve(np.dot(A.T,A),np.dot(A.T,y_array.T))\n #print(X)\n return X\n\ndef SKRidge(alpha,x,y,times):\n m = len(x)\n X = x.reshape((m,1))\n for index in range(times):\n X = np.hstack([X,(x**(index+2)).reshape((m,1))])\n reg = linear_model.Ridge(alpha=1.0,max_iter=5000)\n reg.fit(X,y,sample_weight = alpha)\n W = np.hstack([reg.intercept_,reg.coef_])\n return W\n\ndef calculate_single_point(x,W):\n X = np.ones(1)\n times = len(W)-1\n for ind in range(times):\n X = np.hstack([X,(x**(ind+1))])\n return np.sum(W*X)\n\ndef spokes(k,x0,y0,y):\n x = -k*(y-y0)+x0\n if x<0:\n return int(np.floor(x))\n else:\n return int(np.ceil(x))\n \ndef draw_inspection_spokes(intensity,x0,y0,k,rgb_image,xmax,xmin,ymax,ymin,xcentral,ycentral):\n searchy = y0\n maxin = 150\n ridge_point=()\n if x0xcentral:\n right = xmax\n left = xcentral\n else:\n right = xmax\n left = xmin\n #if flag==1:\n while searchyleft:\n color = intensity[searchy,searchx]\n if color > 150:\n rgb_image[searchy,searchx] = (0,255,0)\n if color>maxin:\n maxin = color\n ridge_point = (searchx,searchy) \n else:\n break \n searchy+=1 \n searchy = y0-1\n while searchy>ymin:\n searchx = spokes(k,x0,y0,searchy)\n if searchx left:\n color = intensity[searchy,searchx]\n if color> 150:\n rgb_image[searchy,searchx]= (0,255,0)\n if color>maxin:\n maxin = color\n ridge_point = (searchx,searchy)\n else:\n break\n searchy-=1\n if len(ridge_point)!=0:\n rgb_image[ridge_point[1],ridge_point[0]]=(255,0,0)\n return ridge_point\n\ndef CurveFitting(deep_image,image_data,outpath):\n x_array = np.where(image_data==1)[1]\n xmin = np.min(x_array)\n xmax = np.max(x_array)\n xm = int(np.floor((xmax+xmin)/2.0))\n Width = xmax-xmin\n y_array = np.where(image_data==1)[0]\n ymin = np.min(y_array)\n ymax = np.max(y_array)\n Deep = ymax-ymin\n i = ymin\n j = ymax\n pred_ym = ymin\n while i<=ymax and j>=ymin:\n for divi in range(-3,4):\n if image_data[i,xm+divi]==1:\n pred_ym = i\n break\n if image_data[j,xm+divi]==1:\n pred_ym = j\n break\n i+=1\n j-=1\n if abs(pred_ym-ymin)=xmin:\n if image_data[origin_y,i]==1:\n origin_x = i\n break\n if image_data[origin_y,j]==1:\n origin_x = j\n break\n i+=1\n j-=1\n #print(\"Origin x,Origin y,xm,pred_ym:\",origin_x,origin_y,xm,pred_ym)\n alpha = 1/(abs(x_array-origin_x)+1)\n W = SKRidge(alpha,x_array-origin_x,abs(y_array-origin_y),3)\n #W = solve_poly(3,x_array-origin_x,abs(y_array-origin_y),alpha)\n rgb_image = np.zeros((image_data.shape[0],image_data.shape[1],3),np.uint8)\n rgb_image[np.where(image_data==0)] = (255,255,255)\n rgb_image[np.where(image_data==1)] = (0,0,0)\n rgb_image[:,xm] = (255,0,0)\n \n count = 0\n new_ridge_x = []\n new_ridge_y = []\n new_ridge_points=[]\n \n #Divide teeth into three parts:1/3 && 2/3\n ridge_rgb = rgb_image\n left_region = int(origin_x-(origin_x-xmin)*2/3)\n right_region = int(origin_x+(xmax-origin_x)*2/3)\n step = 0\n starts = [xmin,left_region,right_region]\n ends = [left_region,right_region,xmax]\n while step<3:\n for xcor in range(starts[step],ends[step]+1):\n if step!=1:\n curve_x = xcor-xm\n curve_y = da_polynomial(curve_x,Deep,Width)\n if flag==1:\n pano_y = ymax-int(curve_y)\n else:\n pano_y = ymin+int(curve_y)\n point = (xcor,pano_y)\n if point not in new_ridge_points:\n new_ridge_points.append(point)\n new_ridge_x.append(xcor)\n new_ridge_y.append(pano_y)\n else:\n curve_x = xcor-origin_x\n curve_y = calculate_single_point(curve_x,W)\n if flag==2:\n pano_y1 = origin_y-int(curve_y)\n else:\n pano_y1 = origin_y+int(curve_y)\n if count%3==0 and xcor!=xmin and xcor!=xmax:\n next_y = calculate_single_point(curve_x+3,W)\n if flag==2:\n next_y = origin_y-next_y\n else:\n next_y = origin_y+next_y\n ki = (next_y-pano_y1)/3.0\n new_ridge_point = draw_inspection_spokes(deep_image,xcor,pano_y1,ki,rgb_image,xmax,xmin,ymax,ymin,origin_x,origin_y)\n if new_ridge_point not in new_ridge_points and len(new_ridge_point)!=0:\n new_ridge_points.append(new_ridge_point)\n new_ridge_x.append(new_ridge_point[0])\n new_ridge_y.append(new_ridge_point[1])\n #ridge_rgb[new_ridge_point[1],new_ridge_point[0]]=(0,0,255)\n count+=1 \n step+=1\n new_xarray = np.array(new_ridge_x)\n new_yarray = np.array(new_ridge_y)\n new_alpha = 1/(abs(new_xarray-origin_x)+1)\n \n reg1_coef = SKRidge(new_alpha,new_xarray-origin_x,abs(new_yarray-origin_y),4)\n for xcor in range(xmin,xmax+1):\n curve_x = xcor-origin_x\n curve_y = calculate_single_point(curve_x,reg1_coef)\n if flag==2:\n pano_y1 = origin_y-int(curve_y)\n else:\n pano_y1 = origin_y+int(curve_y)\n rgb_image[pano_y1,xcor] = (0,0,255)\n cv2.imwrite(outpath,rgb_image)\n return reg1_coef\n\nif __name__=='__main__':\n base_path = '../data/'\n base_paths = [base_path+\"2016/*\",base_path+\"2017/*\"]\n factor = 3\n poly_params={}\n for bp in base_paths:\n dieNames = glob(bp)\n for dieName in dieNames:\n file_list = glob(dieName+\"/*.stl\")\n for filePath in file_list:\n fileName = filePath.split(\"/\")[-1].split(\".\")[0]\n label_ud = fileName.split(\" \")[-1][0]\n if label_ud =='s':\n angle= -83\n thresh = 150\n elif label_ud=='x':\n angle= 90\n thresh=150\n else:\n continue\n outPath = filePath.replace(\".stl\",\".bmp\")\n outCurveImage = filePath.replace(\".stl\",\"_da.jpg\")\n print(\"FileName: \",fileName)\n get_range_image(filePath,outPath,angle,factor)\n bmp_data = cv2.imread(outPath,0)\n sobel_edge = SobelEdgeDetection(bmp_data,thresh)\n W = CurveFitting(bmp_data,sobel_edge,outCurveImage) \n caseName = dieName.split('/')[-1]+\" \"+label_ud\n if caseName not in poly_params:\n poly_params[caseName]={}\n label_ba = int(fileName.split(\" \")[-1][1])\n if label_ba==0:\n poly_params[caseName]['be'] = W[0]\n poly_params[caseName]['bd'] = W[1]\n poly_params[caseName]['bc'] = W[2]\n poly_params[caseName]['bb'] = W[3]\n poly_params[caseName]['ba'] = W[4]\n elif label_ba==1:\n poly_params[caseName]['ae'] = W[0]\n poly_params[caseName]['ad'] = W[1]\n poly_params[caseName]['ac'] = W[2]\n poly_params[caseName]['ab'] = W[3]\n poly_params[caseName]['aa'] = W[4] \n #break\n #break\n data_table = pd.DataFrame.from_dict(poly_params,orient='index')\n data_table.to_csv(\"../data/dental_arch_params.csv\")","sub_path":"DentalArch/prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":12158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"185313465","text":"#!/usr/bin/env python\n\nimport sys\nimport time\nimport smach\nimport math\nimport random\nimport rospy\n\nimport robot_smach_states as states\nimport robot_smach_states.util.designators as ds\nimport robot_skills.util.msg_constructors as msgs\n\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom openface_ros.face_recognizer import FaceRecognizer\n# from skybiometry_ros import Skybiometry\nfrom image_recognition_msgs.msg import FaceProperties\nfrom image_recognition_msgs.srv import GetFaceProperties\nfrom robot_smach_states.util.startup import startup\nfrom robot_skills.util.kdl_conversions import VectorStamped\nfrom robocup_knowledge import load_knowledge\n\ntimeout = 10\n\n\nalign_path = '~/openface/models/dlib/shape_predictor_68_face_landmarks.dat'\nnet_path = '~/openface/models/openface/nn4.small2.v1.t7'\n\n\n# key = '69efefc20c7f42d8af1f2646ce6742ec'\n# secret = '5fab420ca6cf4ff28e7780efcffadb6c'\n\n\nclass DetectCrowd(smach.State):\n def __init__(self, robot):\n smach.State.__init__(self, outcomes=['succeeded', 'failed'], output_keys=['crowd_data'])\n self.robot = robot\n self._bridge = CvBridge()\n self._face_recognizer = FaceRecognizer(align_path, net_path)\n # self._skybiometry = Skybiometry(key, secret)\n\n def execute(self, userdata):\n tries = 3\n detections = self.recognize(tries)\n\n crowd_data = self.describe_crowd(detections)\n userdata.crowd_data = crowd_data\n\n return 'succeeded'\n\n def recognize(self, tries):\n number_of_people = 0\n best_detection = None\n\n sentences = [\"You are all looking great today! Keep looking in my camera!\",\n \"I like it when everybody is staring at me; being in the center of attention!\"]\n\n for i in range(0, tries):\n self.robot.speech.speak(sentences[i % (tries - 1)], block=False)\n image = self.get_shot()\n face_rois = self.get_faces(image)\n\n if len(face_rois) > number_of_people:\n number_of_people = len(face_rois)\n best_image = image\n best_detection = face_rois\n\n imgs = []\n if best_detection:\n for face_recognition in best_detection:\n cv2_img = best_image[face_recognition.roi.y_offset:face_recognition.roi.y_offset + face_recognition.roi.height,\n face_recognition.roi.x_offset:face_recognition.roi.x_offset + face_recognition.roi.width]\n imgmsg = self._bridge.cv2_to_imgmsg(cv2_img, 'bgr8')\n imgs.append(imgmsg)\n\n rospy.loginfo('Calling Skybiometry...')\n\n try:\n # face_properties = self._skybiometry.get_face_properties(imgs, timeout)\n get_face_properties = rospy.ServiceProxy('/get_face_properties', GetFaceProperties)\n face_properties_response = get_face_properties(imgs)\n face_properties = face_properties_response.properties_array\n except Exception as e:\n rospy.logerr(str(e))\n self.robot.speech.speak('API call failed, is there internet?')\n return [None]*number_of_people\n\n face_log = '\\n - '.join([''] + [repr(s) for s in face_properties])\n rospy.loginfo('face_properties:%s', face_log)\n return face_properties\n\n\n def get_shot(self):\n z = 1.5\n self.robot.head.look_at_point(VectorStamped(100, 0, z, self.robot.robot_name + \"/base_link\"))\n self.robot.head.wait_for_motion_done()\n time.sleep(1)\n\n image =self.robot.head.get_image()\n return self._bridge.imgmsg_to_cv2(image, 'bgr8')\n\n def get_faces(self, image):\n\n faces = self._face_recognizer.recognize(image)\n\n rospy.loginfo(\"Faces: %s\", faces)\n\n return faces\n\n\n def describe_crowd(self, detections):\n num_males = 0\n num_females = 0\n num_women = 0\n num_girls = 0\n num_men = 0\n num_boys = 0\n num_elders = 0\n\n if not all(detections):\n rospy.loginfo('making a random guess for %d people', len(detections))\n if len(detections) > 2:\n num_males = 1 + random.randrange(len(detections) - 2)\n else:\n num_males = 1\n num_females = len(detections) - num_males\n else:\n for d in detections:\n if d.gender == FaceProperties.MALE:\n if d.age < 18:\n num_boys +=1\n elif d.age > 60:\n num_elders +=1\n else:\n num_men += 1\n else:\n if d.age < 18:\n num_girls +=1\n elif d.age > 60:\n num_elders +=1\n else:\n num_women += 1\n\n num_males = num_boys + num_men\n num_females = num_girls + num_women\n\n self.robot.speech.speak(\"There are %d males and %d females in the crowd\" % (num_males, num_females))\n\n return {\n \"males\": num_males,\n \"men\": num_men,\n \"boys\": num_boys,\n \"females\": num_females,\n \"women\": num_women,\n \"girls\": num_girls,\n \"children\": num_boys + num_girls,\n \"adults\": num_men + num_women,\n \"elders\": num_elders,\n \"crowd_size\": num_females + num_males + num_elders\n }\n\n\n\n# Standalone testing -----------------------------------------------------------------\n\nclass TestDetectCrowd(smach.StateMachine):\n def __init__(self, robot):\n smach.StateMachine.__init__(self, outcomes=['Done','Aborted'])\n\n with self:\n smach.StateMachine.add('INITIALIZE',\n states.Initialize(robot),\n transitions={'initialized': 'DETECT_CROWD',\n 'abort': 'Aborted'})\n\n smach.StateMachine.add(\"DETECT_CROWD\",\n DetectCrowd(robot),\n transitions={'succeeded': 'Done',\n 'failed': 'Aborted'})\n\nif __name__ == \"__main__\":\n rospy.init_node('speech_person_recognition_exec')\n\n startup(TestDetectCrowd, challenge_name=\"challenge_spr\")\n","sub_path":"challenge_spr/src/challenge_spr_states/detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":6337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"426545884","text":"#!/usr/bin/env python\n\nfrom copy import copy\nfrom enum import Enum\nfrom collections import Counter\n\n\nclass Opcode(Enum):\n ADD = 1\n MULT = 2\n INPUT = 3\n OUTPUT = 4\n JUMP_IF_TRUE = 5\n JUMP_IF_FALSE = 6\n LESS_THAN = 7\n EQUALS = 8\n SET_REL = 9\n HALT = 99\n\n\nclass IntcodeProgram:\n def __init__(self, memory, input_vals):\n self.m = copy(memory) + [0] * 1_000_000\n # current location of instruction pointer\n self.ip = 0\n self.inputs = input_vals\n self.relative_base = 0\n\n def get(self, mode):\n val = None\n # position mode\n if mode == 0:\n addr = self.m[self.ip]\n val = self.m[addr]\n # immediate mode\n elif mode == 1:\n val = self.m[self.ip]\n # relative mode\n elif mode == 2:\n addr = self.relative_base + self.m[self.ip]\n val = self.m[addr]\n else:\n raise ValueError(f'received invalid parameter get mode: {mode}')\n self.ip += 1\n return val\n\n def set(self, mode, val):\n # position mode\n if mode == 0:\n addr = self.m[self.ip]\n self.m[addr] = val\n # relative mode\n elif mode == 2:\n addr = self.relative_base + self.m[self.ip]\n self.m[addr] = val\n else:\n raise ValueError(f'received invalid parameter set mode: {mode}')\n self.ip += 1\n\n def add_inputs(self, new_inputs):\n self.inputs += new_inputs\n\n def run(self):\n complete = False\n outputs = []\n\n param_lens = {\n Opcode.ADD: 3,\n Opcode.MULT: 3,\n Opcode.INPUT: 1,\n Opcode.OUTPUT: 1,\n Opcode.JUMP_IF_TRUE: 2,\n Opcode.JUMP_IF_FALSE: 2,\n Opcode.LESS_THAN: 3,\n Opcode.EQUALS: 3,\n Opcode.SET_REL: 1,\n Opcode.HALT: 0,\n }\n\n while self.ip < len(self.m):\n instruction = self.m[self.ip]\n opcode = Opcode(instruction % 100)\n param_modes = self._get_modes(instruction // 100, param_lens[opcode])\n\n self.ip += 1\n\n if opcode == Opcode.ADD:\n self.set(\n param_modes[2],\n self.get(param_modes[0]) + self.get(param_modes[1])\n )\n elif opcode == Opcode.MULT:\n self.set(\n param_modes[2],\n self.get(param_modes[0]) * self.get(param_modes[1])\n )\n elif opcode == Opcode.INPUT:\n if len(self.inputs) == 0:\n self.ip -= 1\n break\n input_val = self.inputs.pop(0)\n self.set(\n param_modes[0],\n input_val\n )\n elif opcode == Opcode.OUTPUT:\n outputs.append(self.get(param_modes[0]))\n elif opcode == Opcode.JUMP_IF_TRUE:\n condition = self.get(param_modes[0])\n dest = self.get(param_modes[1])\n if condition:\n self.ip = dest\n elif opcode == Opcode.JUMP_IF_FALSE:\n condition = self.get(param_modes[0])\n dest = self.get(param_modes[1])\n if not condition:\n self.ip = dest\n elif opcode == Opcode.LESS_THAN:\n self.set(\n param_modes[2],\n int(self.get(param_modes[0]) < self.get(param_modes[1]))\n )\n elif opcode == Opcode.EQUALS:\n self.set(\n param_modes[2],\n int(self.get(param_modes[0]) == self.get(param_modes[1]))\n )\n elif opcode == Opcode.SET_REL:\n self.relative_base += self.get(param_modes[0])\n elif opcode == Opcode.HALT:\n complete = True\n break\n else:\n raise ValueError(f'received invalid opcode: {opcode}')\n return outputs, complete\n\n def _get_modes(self, mode_digits, num):\n modes = []\n for _ in range(num):\n mode = mode_digits % 10\n mode_digits //= 10\n modes.append(mode)\n return modes\n\n\ndef main():\n with open('13.txt', 'r') as file:\n memory = [int(v) for v in file.readline().strip().split(',')]\n\n print(f'part1: {part1(memory)}')\n print(f'part2: {part2(memory)}')\n\ndef part1(memory):\n program = IntcodeProgram(memory, [])\n outputs, _ = program.run()\n\n # map of location tuples (x, y) to their tile\n states = {}\n for start in range(0, len(outputs), 3):\n location = tuple(outputs[start:start+2])\n state = outputs[start+2]\n states[location] = state\n\n state_counts = Counter(states.values())\n return state_counts[2]\n\ndef get_joystick_move(ball, paddle):\n if ball == paddle:\n return 0\n elif ball < paddle:\n return -1\n else:\n return 1\n\ndef part2(memory):\n # update memory address 0 to play for free\n memory[0] = 2\n\n program = IntcodeProgram(memory, [])\n outputs, complete = program.run()\n\n # map of location tuples (x, y) to their tile\n states = {}\n while not complete:\n # process outputs\n while len(outputs) >= 3:\n location, tile, outputs = tuple(outputs[0:2]), outputs[2], outputs[3:]\n states[location] = tile\n if tile == 4:\n ball = location[0]\n if tile == 3:\n paddle = location[0]\n # get new input\n program.add_inputs([get_joystick_move(ball, paddle)])\n # run game again\n next_outputs, complete = program.run()\n outputs += next_outputs\n\n while len(outputs) >= 3:\n location, tile, outputs = tuple(outputs[0:2]), outputs[2], outputs[3:]\n states[location] = tile\n\n return states[(-1, 0)]\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"63863396","text":"from pathlib import Path\n\nimport dash_core_components as dcc\nimport dash_html_components as html\n\nfrom ...api_doc import ApiDoc\nfrom ...helpers import ExampleContainer, HighlightedSource\nfrom ...metadata import get_component_metadata\nfrom .placement import tooltips as tooltips_placement\nfrom .tooltip import tooltip\n\nHERE = Path(__file__).parent\n\nsource = (HERE / \"tooltip.py\").read_text()\nplacement_source = (HERE / \"placement.py\").read_text()\n\ncontent = [\n html.H2(\"Tooltip\", className=\"display-4\"),\n html.P(\n dcc.Markdown(\n \"Use the `Tooltip` component to add Bootstrap style tooltips to \"\n \"your app, with no callbacks required.\"\n ),\n className=\"lead\",\n ),\n html.H4(\"Basic example\"),\n html.P(\n dcc.Markdown(\n \"To use the `Tooltip` component, simply add it to the layout of \"\n \"your app, and give it the id of a component in your layout that \"\n \"you would like to use as the target. When the user hovers over \"\n \"the target component, the tooltip will display. There is no need \"\n \"to write any callbacks.\"\n )\n ),\n html.P(\n dcc.Markdown(\n \"In the below example we use a `html.Span` component to target a \"\n \"particular word in a piece of text.\"\n )\n ),\n ExampleContainer(tooltip),\n HighlightedSource(source),\n html.H4(\"Placement\"),\n html.P(\n dcc.Markdown(\n \"Use the `placement` argument to control the placement of the \"\n \"tooltip. The basic options are `'auto'`, `'top'`, `'left'`, \"\n \"`'right'`, `'bottom'`. You can additionally add `-start` or \"\n \"`-end` to any of these options, e.g. `'top-start'`.\"\n )\n ),\n ExampleContainer(tooltips_placement),\n HighlightedSource(placement_source),\n ApiDoc(get_component_metadata(\"src/components/Tooltip.js\")),\n]\n","sub_path":"docs/components_page/components/tooltip/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"376045310","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: scripts/client/gui/impl/pub/view_impl.py\nimport typing\nfrom frameworks.wulf import View, ViewEvent, Window\nfrom gui.impl.gen.resources import R\nfrom gui.impl.pub.context_menu_window import ContextMenuWindow, ContextMenuContent\nfrom gui.impl.pub.pop_over_window import PopOverWindow\nfrom gui.impl.pub.tooltip_window import SimpleToolTipWindow, ToolTipWindow, AdvancedToolTipWindow\nfrom helpers import dependency\nfrom skeletons.gui.impl import IGuiLoader\nfrom soft_exception import SoftException\n\nclass ViewImpl(View):\n __slots__ = ()\n gui = dependency.descriptor(IGuiLoader)\n\n def createToolTipContent(self, event, contentID):\n return None\n\n def createPopOverContent(self, event):\n return None\n\n def createContextMenuContent(self, event):\n return None\n\n def createToolTip(self, event):\n window = None\n if event.contentID == R.views.simpleTooltipContent():\n window = SimpleToolTipWindow(event, self.getParentWindow())\n elif event.contentID == R.views.simpleTooltipHtmlContent():\n window = SimpleToolTipWindow(event, self.getParentWindow(), useHtmlText=True)\n elif event.contentID == R.views.advandcedTooltipContent():\n normalContent = event.getArgument('normalContent')\n advancedContent = event.getArgument('advancedContent')\n window = AdvancedToolTipWindow(self.getParentWindow(), self.createToolTipContent(event, normalContent), self.createToolTipContent(event, advancedContent))\n else:\n content = self.createToolTipContent(event, event.contentID)\n if content is not None:\n window = ToolTipWindow(content, self.getParentWindow())\n if window is not None:\n window.load()\n window.move(event.mouse.positionX, event.mouse.positionY)\n return window\n\n def createPopOver(self, event):\n content = self.createPopOverContent(event)\n window = None\n if content is not None:\n if not isinstance(content, PopOverViewImpl):\n raise SoftException('PopOver content should be derived from PopOverViewImpl.')\n window = PopOverWindow(event, content, self.getParentWindow())\n window.load()\n return window\n\n def createContextMenu(self, event):\n content = self.createContextMenuContent(event)\n window = None\n if content is not None:\n if not isinstance(content, ContextMenuContent):\n raise SoftException('Context menu content should be derived from ContextMenuContent.')\n window = ContextMenuWindow(content, self.getParentWindow())\n window.load()\n window.move(event.mouse.positionX, event.mouse.positionY)\n return window\n\n\nclass PopOverViewImpl(ViewImpl):\n __slots__ = ()\n\n @property\n def isCloseBtnVisible(self):\n return True\n","sub_path":"source/res/scripts/client/gui/impl/pub/view_impl.py","file_name":"view_impl.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"319060102","text":"__author__ = \"Hamza BENJELLOUN & Omar BENCHEKROUN\"\r\n\r\ndef extract_matrix():\r\n A = list(map(float, input().split()))\r\n B = list(map(float, input().split()))\r\n pi = list(map(float, input().split()))\r\n O = list(map(int, input().split()))\r\n for m in [A,B,pi]:\r\n m[0] = int(m[0])\r\n m[1] = int(m[1])\r\n return A, B, pi, O\r\n\r\n\r\ndef product(A,B):\r\n #return product AxB, matrixes are formatted as given\r\n assert A[1]==B[0]\r\n prod = [A[0],B[1]]\r\n for i in range(int(A[0])):\r\n for j in range(int(B[1])):\r\n r = 0\r\n for k in range(int(A[1])):\r\n r += A[i*int(A[1])+k+2] * B[k*int(B[1])+j+2]\r\n prod.append(r)\r\n return prod\r\n\r\ndef mat2str(A):\r\n l = [str(int(A[0])), str(int(A[1]))]\r\n for i in range(2, len(A)):\r\n l.append(str(round(A[i],5)))\r\n return \" \".join(l)\r\n","sub_path":"Hidden_Markov_model/kth.ai.hmm1/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"617254935","text":"\n\"\"\"This script nuke all key pairs\"\"\"\n\nimport boto3\n\nEC2 = boto3.client('ec2')\n\ndef nuke_all_key_pair(logger):\n \"\"\"\n ec2 function for nuke all key pairs\n \"\"\"\n\n #### Nuke all volumes ####\n response = EC2.describe_key_pairs()\n\n for keypair in response['KeyPairs']:\n\n # Nuke all ec2 key pair\n EC2.delete_key_pair(KeyName=keypair['KeyName'])\n logger.info(\"Nuke Key Pair %s\", keypair['KeyName'])\n","sub_path":"package/compute/key_pair.py","file_name":"key_pair.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"483313351","text":"#!/usr/bin/python -tt\nimport unittest\nimport totpcgi\nimport pyotp\nimport time\nimport json\nimport sys\nimport os\n\nsecrets_dir = 'test/secrets'\nstatus_dir = 'test/status'\n\nclass GATest(unittest.TestCase):\n\n def cleanStatus(self, user='valid'):\n status_file = os.path.join(status_dir, '%s.json' % user)\n if os.access(status_file, os.R_OK):\n os.unlink(status_file)\n\n def setCustomStatus(self, status, user='valid'):\n status_file = os.path.join(status_dir, '%s.json' % user)\n fh = open(status_file, 'w')\n json.dump(status, fh, indent=4)\n fh.close()\n\n def setUp(self):\n # Remove any existing status files for user \"valid\"\n self.cleanStatus()\n\n def tearDown(self):\n self.cleanStatus()\n\n def getValidUser(self):\n return totpcgi.GAUser('valid', secrets_dir, status_dir)\n\n def testValidSecretParsing(self):\n gau = self.getValidUser()\n\n self.assertEqual(gau.totp.secret, 'VN7J5UVLZEP7ZAGM',\n 'Secret read from valid.totp did not match')\n self.assertEqual(gau.user, 'valid', \n 'User did not match')\n self.assertEqual(gau.rate_limit, (4, 40),\n 'RATE_LIMIT did not parse correctly')\n self.assertEqual(gau.window_size, 18,\n 'WINDOW_SIZE did not parse correctly')\n\n scratch_tokens = [88709766,11488461,27893432,60474774,10449492]\n\n self.assertItemsEqual(scratch_tokens, gau.scratch_tokens)\n\n def testInvalidSecretParsing(self):\n with self.assertRaises(totpcgi.UserFileError):\n totpcgi.GAUser('invalid', secrets_dir, status_dir)\n\n def testInvalidUsername(self):\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, \n 'invalid characters'):\n gau = totpcgi.GAUser('../../etc/passwd', secrets_dir, status_dir)\n\n def testNonExistentValidUser(self):\n with self.assertRaises(totpcgi.UserNotFound):\n gau = totpcgi.GAUser('bob@example.com', secrets_dir, status_dir)\n \n def testValidToken(self):\n gau = self.getValidUser()\n totp = pyotp.TOTP(gau.totp.secret)\n token = totp.now()\n self.assertEqual(gau.verify_token(token), 'Valid token used')\n\n # try using it again\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'been used once'):\n gau.verify_token(token)\n\n # and again, to make sure it is preserved in status\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'been used once'):\n gau.verify_token(token)\n\n def testWindowSize(self):\n gau = self.getValidUser()\n totp = pyotp.TOTP(gau.totp.secret)\n # get a token from 60 seconds ago\n past_token = totp.at(int(time.time())-60)\n future_token = totp.at(int(time.time())+60)\n\n # this should fail\n gau.window_size = 0\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Not a valid token'):\n gau.verify_token(past_token)\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Not a valid token'):\n gau.verify_token(future_token)\n\n # this should work\n gau.window_size = 10\n self.assertEqual(gau.verify_token(past_token), \n 'Valid token within window size used')\n self.assertEqual(gau.verify_token(future_token), \n 'Valid token within window size used')\n\n def testRateLimit(self):\n gau = self.getValidUser()\n\n # just in case the lightning strikes at that very number\n if gau.now_token == 555555:\n token = '555556'\n else:\n token = '555555'\n\n # We now fail 4 times consecutively\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Not a valid token'):\n gau.verify_token(token)\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Not a valid token'):\n gau.verify_token(token)\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Not a valid token'):\n gau.verify_token(token)\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Not a valid token'):\n gau.verify_token(token)\n\n # We should now get a rate-limited error\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Rate-limit'):\n gau.verify_token(token)\n\n # Same with a valid token\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Rate-limit'):\n gau.verify_token(gau.now_token)\n\n # Make sure we recover from rate-limiting correctly\n old_timestamp = gau.now_timestamp-(31+(gau.rate_limit[1]*10))\n status = {\n 'fail_timestamps': [\n old_timestamp,\n old_timestamp,\n old_timestamp,\n old_timestamp\n ],\n 'success_timestamps': [],\n 'used_scratch_tokens': []\n }\n self.setCustomStatus(status)\n\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Not a valid token'):\n gau.verify_token(token)\n\n # Valid token should work, too\n self.setCustomStatus(status)\n self.assertEqual(gau.verify_token(gau.now_token), 'Valid token used')\n \n def testInvalidToken(self):\n gau = self.getValidUser()\n # just in case the lightning strikes at that very number\n if gau.now_token == 555555:\n token = '555556'\n else:\n token = '555555'\n\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'Not a valid token'):\n gau.verify_token(token)\n\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'too long'):\n self.cleanStatus()\n gau.verify_token('12345678910')\n\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, 'not an integer'):\n self.cleanStatus()\n gau.verify_token('WAKKA')\n\n with self.assertRaisesRegexp(totpcgi.VerifyFailed,\n 'Not a valid scratch-token'):\n gau.verify_token('11112222')\n\n def testScratchTokens(self):\n gau = self.getValidUser()\n\n ret = gau.verify_token('88709766')\n self.assertEqual(ret, 'Scratch-token used')\n\n # try using it again\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, \n 'Scratch-token already used once'):\n gau.verify_token('88709766')\n\n # try using another token\n ret = gau.verify_token('11488461')\n self.assertEqual(ret, 'Scratch-token used')\n\n # use first one again to make sure it's preserved in the status file\n with self.assertRaisesRegexp(totpcgi.VerifyFailed, \n 'Scratch-token already used once'):\n gau.verify_token('88709766')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"408248375","text":"#coding=gbk\r\nimport socket\r\n\r\n#创建socket,指定IP地址类型和通信类型\r\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n\r\n#绑定本机\r\ns.bind(('',8888))\r\n\r\n#监听端口\r\ns.listen()\r\nprint(\"服务器启动\")\r\n\r\n#等待客户端\r\nconn,addr = s.accept()\r\n\r\n#客户端连接成功\r\nprint(addr)\r\n\r\n#接受客户端数据\r\ndata = conn.recv(1024)\r\nprint(\"从客户端接受的消息:{0}\".format(data.decode()))\r\n\r\n#给客户端发送数据\r\nconn.send(\"你好\".encode())\r\n\r\n#释放资源\r\nconn.close()\r\ns.close()","sub_path":"Python/网络编程/sever.py","file_name":"sever.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"240961418","text":"\nclass MethodList(list):\n def __init__(self, tbl_dictionary, interface):\n self.tbl_dictionary = tbl_dictionary\n\n\n for i in self.tbl_dictionary['interfaces'][interface]['methods']:\n self.append(i)\n\n\ndef main():\n import pprint\n import os\n from test_func import test_table\n\n os.environ['LB-TESTING'] = '1'\n methods = MethodList(test_table(), 'app')\n\n assert type(methods) == MethodList\n #print('methond', methods)\n assert methods == ['upsert', 'select']\n\n os.environ['LB-TESTING'] = '0'\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"_app/list_methods.py","file_name":"list_methods.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"38233125","text":"from wallet import Category, Record\n\nfrom pymongo import MongoClient\n\nCATEGORIES_COLLECTION = 'categories'\nRECORDS_COLLECTION = 'records'\n\nclass WalletStore:\n\n def __init__(self, mongo_host, mongo_port, mongo_db):\n client = MongoClient(host=mongo_host, port=mongo_port)\n db = client[mongo_db]\n self.categories = db[CATEGORIES_COLLECTION]\n self.records = db[RECORDS_COLLECTION]\n\n def put_categories(self, categories):\n categories_dicts = [self.__serialize(category) for category in categories]\n result = self.categories.insert_many(categories_dicts)\n return len(result.inserted_ids)\n\n def put_records(self, records):\n records_dicts = [self.__serialize(record) for record in records]\n result = self.records.insert_many(records_dicts)\n return len(result.inserted_ids)\n\n def __serialize(self, obj):\n return dict((k, v) for k, v in obj.__dict__.items() if v is not None)\n","sub_path":"store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"190418463","text":"#converts VCF from Stacks:populations to fineStructureRAD format\r\n#sys.args = [vcf_in] [CSV_master_location_file] [txt_out]\r\n#NB DOES NOT CONSIDER PHASED DATA - see fineRADstructure manual\r\n\r\nimport sys, pandas as pd\r\n\r\ndef main():\r\n g = open(sys.argv[3],'w')\r\n taxa = taxList(sys.argv[1])\r\n isls = popper(taxa, sys.argv[2])\r\n setIsls = set(isls)\r\n #for taxon list with no root names it will name each taxon with a population name (and integer)\r\n for i in setIsls:\r\n cnt, cnt2 = 0, 1\r\n for j in isls:\r\n if i == j:\r\n isls[cnt] = j+repr(cnt2)\r\n cnt2 += 1\r\n cnt += 1\r\n for isl in isls[:-1]: g.write(isl+'\\t')\r\n g.write(isls[-1]+'\\n')\r\n #convert VCF to fineStr format\r\n for line in open(sys.argv[1]):\r\n if line[0] != '#':\r\n als, z = [], line.strip().split('\\t')\r\n als.append(z[3])\r\n for _ in z[4].split(','): als.append(_) #all alt alleles\r\n if len(als) > 8: continue #from 9th column onwards\r\n for t in z[9:-1]:\r\n if t[:3] == './.': #id missing data\r\n g.write('\\t')\r\n continue\r\n elif t[0] == t[2]: #or write allele nucleotides\r\n g.write(als[int(t[0])] + '\\t')\r\n continue\r\n elif t[0] != t[2]:\r\n g.write('{}/{}\\t'.format(als[int(t[0])], als[int(t[2])]))\r\n continue\r\n if z[-1][:3] == './.': #deal with line endings\r\n g.write('\\t\\n')\r\n continue\r\n elif z[-1][0] == z[-1][2]:\r\n g.write('{}\\n'.format(als[int(z[-1][0])]))\r\n continue\r\n elif z[-1][0] != z[-1][2]:\r\n g.write(als[int(z[-1][0])] + '/'+als[int(z[-1][2])] + '\\n')\r\n continue\r\n g.close()\r\n\r\n#extract taxon list from VCF file\r\ndef taxList(vcfFile):\r\n taxa=[]\r\n for line in open(vcfFile):\r\n z=line.strip().split('\\t')\r\n if line.startswith('#CHROM'):\r\n [taxa.append(tax.strip()) for tax in z if z.index(tax) > 8]\r\n break\r\n return taxa\r\n\r\n#determine population\r\ndef popper(taxList, datFile):\r\n isls, file = [None] * len(taxList), pd.read_csv(datFile)\r\n for tax in taxList:\r\n if tax in list(file['dna_extraction_code']): # i.e. header = dna_extraction_code\r\n isls[taxList.index(tax)]=file['location'][list(file['dna_extraction_code']).index(tax)] #appropriate index of location for taxon\r\n return isls\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"vcf2fineStr.py","file_name":"vcf2fineStr.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"26900356","text":"#!/usr/bin/env python3\n\nimport sys, os, ntpath\nfrom pycparser.pycparser import parse_file, c_parser, mermaid_generator\n\nhave_end_types = (\"If\", \"FuncDef\", \"While\", \"For\", \"DoWhile_Do\")\nhave_multi_cond_types = (\"If\")\nmulti_cond_subtypes = (\"If-True\", \"If-False\")\nconnect_to_start_types = (\"Continue\")\nconnect_to_end_types = (\"Break\")\nforce_function_end_types = (\"Return\")\n\ncurrent_func = None\ncall_stack = []\n\ndef call_stack_append(node):\n if len(call_stack) == 0 or node not in call_stack:\n call_stack.append(node)\n\ndef call_stack_pop(node=None):\n if node == None:\n return call_stack.pop()\n else:\n if node not in call_stack:\n return\n else:\n while(call_stack[-1] != node):\n call_stack.pop()\n return call_stack.pop()\n\ndef generate_end_id(node):\n if node == None: return\n if node.end_id != None:\n return node.end_id\n if node.type == \"If\":\n node.end_id = node_id(node).replace(\"If\", \"EndIf\")\n if node.type == \"FuncDef\":\n node.end_id = node_id(node).replace(\"FuncDef\", \"EndFuncDef\")\n if node.type == \"While\":\n node.end_id = node_id(node).replace(\"While\", \"EndWhile\")\n if node.type == \"For\":\n node.end_id = node_id(node).replace(\"For\", \"EndFor\")\n if node.type == \"DoWhile_Do\":\n node.end_id = node_id(node.children[-1])\n return node.end_id\n\ndef generate_end_node_content(node):\n if node == None: return\n if node.end_content != None:\n return node.end_content\n if node.type == \"If\":\n node.end_content = generate_end_id(node) + node_surround(node)[0] + \"\\\"\" + \"End If\" + \"\\\"\" + node_surround(node)[1]\n if node.type == \"FuncDef\":\n node.end_content = generate_end_id(node) + node_surround(node)[0] + \"\\\"\" + \"End Function\" + \"\\\"\" + node_surround(node)[1]\n if node.type == \"While\":\n node.end_content = generate_end_id(node) + node_surround(node)[0] + \"\\\"\" + \"End While\" + \"\\\"\" + node_surround(node)[1]\n if node.type == \"For\":\n node.end_content = generate_end_id(node) + node_surround(node)[0] + \"\\\"\" + \"End For\" + \"\\\"\" + node_surround(node)[1]\n if node.type == \"DoWhile_Do\":\n node.end_content = node.children[-1].content\n return node.end_content\n\ndef node_type(node):\n if node == None: return \"None\"\n if is_if_branch(node) or is_root(node):\n return node.type\n elif type(node) is str:\n string = node\n else:\n string = node.content\n\n a = string.strip().split('_')\n try:\n int(a[2])\n return a[1]\n except:\n return '_'.join(a[1:2])\n\ndef node_id(node):\n if node == None: return \"None\"\n if type(node) is str:\n string = node\n else:\n string = node.content\n return string.split('[')[0].split('(')[0].split('{')[0]\n\n\ndef node_surround(node):\n try:\n return node.surround\n except:\n return None\n\ndef node_str(node):\n try:\n return node.content[len(node_id(node))+2:-3].strip()\n except:\n return node\n\ndef is_if_true_branch(node):\n try:\n return (node.type == \"If-True\")\n except:\n return False\n\ndef is_if_false_branch(node):\n try:\n return (node.type == \"If-False\")\n except:\n return False\n\ndef is_if_branch(node):\n return (is_if_false_branch(node) or is_if_true_branch(node))\n\ndef is_root(node):\n try:\n return (node.type == \"root\")\n except:\n return False\n\ndef generate_call_tree(filename):\n \"\"\" Simply use the c_generator module to emit a parsed AST.\n \"\"\"\n ast = parse_file(filename\n , clean_code=True, clean_comments=True, clean_macros=False\n , use_cpp=True\n , cpp_path='clang'\n , cpp_args=['-E', '-Wno-macro-redefined', '-I'+os.path.dirname(os.path.abspath(__file__))+r'/pycparser/utils/fake_libc_include', '-nostdinc']\n )\n\n #ast.show()\n generator = mermaid_generator.MermaidGenerator()\n tree = generator.get_call_tree(ast)\n return tree\n\ndef link(node1, node2, cond=None, filter_loop=True):\n if type(node1) is str:\n node_1_id = node1\n else:\n if node_type(node1) in multi_cond_subtypes: return\n node_1_id = node_id(node1)\n if type(node2) is str:\n node_2_id = node2\n else:\n if node_type(node2) in multi_cond_subtypes: return\n node_2_id = node_id(node2)\n if filter_loop and (node_1_id == node_2_id):\n return\n if not cond:\n print(\"%s --> %s\" % (node_1_id, node_2_id))\n else:\n print(\"%s -- %s --> %s\"% (node_1_id, cond, node_2_id))\n\ndef print_nodes(tree):\n print(\"%% [Node]: \" + node_id(tree) + \" Type: \" + node_type(tree) + \" Str: \" + node_str(tree))\n s = str(tree.content).strip()\n if not is_if_branch(tree) and not is_root(tree):\n print(s)\n if tree.type in have_end_types:\n print(generate_end_node_content(tree))\n for i in tree.children:\n print_nodes(i)\n\ndef iterative_print_links(tree, last_node, cond=None, function_end=None):\n global call_stack\n if len(tree.children) > 0:\n # print(\"%% Iterate over normal stmt\")\n # (before) --> (current tree)\n if node_type(tree) in multi_cond_subtypes:\n link(last_node, tree.children[0], cond=cond)\n elif node_type(last_node) in have_end_types:\n link(tree.children[0], generate_end_id(last_node), cond=cond)\n else:\n link(tree, tree.children[0], cond=cond)\n\n # (current tree) --> (current tree)\n for i in range(1, len(tree.children)):\n if (tree.children[i - 1].type not in have_end_types):\n link(tree.children[i - 1], tree.children[i])\n else:\n link(generate_end_id(tree.children[i - 1]), tree.children[i])\n\n # inside every node\n for i in tree.children:\n print_links(i, tree, function_end=function_end)\n\n # print_links(tree.children[0], tree, call_stack=call_stack, function_end=function_end)\n # for i in range(1, len(tree.children)):\n # print_links(tree.children[i], tree.children[i - 1], call_stack=call_stack, function_end=function_end)\n else:\n if node_type(last_node) not in have_end_types:\n link(tree, last_node)\n\n\ndef search_last_call(node):\n last_call = node\n # if last_call.type in have_end_types:\n # return generate_end_id(last_call)\n while len(last_call.children) > 0:\n if last_call.children[-1].type in have_end_types:\n last_call = generate_end_id(last_call.children[-1])\n break\n else:\n last_call = last_call.children[-1]\n print(\"%% Last call: \" + node_str(last_call))\n return last_call\n\ndef print_links(tree, last_node, function_end=None):\n # print(\"%% Got node type: \"+str(node_type(tree)))\n global current_func\n global call_stack\n\n for i in call_stack:\n print(\"%% [Call Stack] \" + node_str(i))\n\n if node_type(tree) == \"root\":\n for i in tree.children:\n print_links(i, tree)\n return\n\n elif node_type(tree) == \"FuncDef\" and len(tree.children) > 0:\n print(\"%% FuncDef start\")\n call_stack_append(tree)\n current_func = tree\n iterative_print_links(tree, last_node, function_end=tree)\n func_last_call_node = search_last_call(tree)\n if node_type(func_last_call_node) not in force_function_end_types:\n link(func_last_call_node, generate_end_id(tree))\n print(\"%% FuncDef end\")\n call_stack_pop(tree)\n current_func = None\n return\n\n elif node_type(tree) == \"If\":\n call_stack_append(tree)\n if_end_node_id = generate_end_id(tree)\n print('%% If node: ' + node_id(tree))\n # If-True\n print('%% If-True')\n # link(tree, tree.children[0].children[0], \"Tree\")\n iterative_print_links(tree.children[0], tree, \"True\")\n if_true_end_node = search_last_call(tree.children[0])\n print('%% If-True->end: ' + node_id(tree) + node_id(if_true_end_node))\n link(if_true_end_node, if_end_node_id)\n\n # If-False\n print('%% If-False')\n if len(tree.children) > 1: # we got a else\n iterative_print_links(tree.children[1], tree, \"False\")\n if_false_end_node = search_last_call(tree.children[1])\n print('%% If-False->end: ' + node_id(tree) + node_id(if_false_end_node))\n link(if_false_end_node, if_end_node_id)\n else: # no else\n link(tree, if_end_node_id, \"False\")\n\n call_stack_pop(tree)\n # for i in range(2, len(tree.children)):\n # iterative_print_links(tree.children[i], tree, call_stack=call_stack)\n return\n\n elif node_type(tree) == \"While\":\n call_stack_append(tree)\n print(\"%% While start\")\n iterative_print_links(tree, last_node)\n # link(search_last_call(tree), generate_end_id(tree))\n print(\"%% While end\")\n call_stack_pop(tree)\n link(search_last_call(tree), generate_end_id(tree))\n return\n\n elif node_type(tree) == \"For\":\n call_stack_append(tree)\n print(\"%% For start\")\n iterative_print_links(tree, last_node)\n link(search_last_call(tree), generate_end_id(tree))\n link(generate_end_id(tree), tree)\n print(\"%% For end\")\n call_stack_pop(tree)\n return\n\n elif node_type(tree) == \"DoWhile_Do\":\n call_stack_append(tree)\n print(\"%% DoWhile start\")\n iterative_print_links(tree, last_node)\n link(generate_end_id(tree), tree)\n print(\"%% DoWhile end\")\n call_stack_pop(tree)\n return\n\n elif node_type(tree) in connect_to_start_types:\n link(tree, call_stack[-1])\n return\n\n elif node_type(tree) in connect_to_end_types:\n link(tree, generate_end_id(call_stack[-1]))\n return\n\n\n elif node_type(tree) in force_function_end_types:\n link(tree, generate_end_id(current_func))\n return\n\n # normal\n call_stack_append(tree)\n iterative_print_links(tree, last_node)\n call_stack_pop(tree)\n\n\ndef print_mermaid_graph(tree):\n print(\"graph TB\")\n print(r\"%% \" + \"Nodes\")\n print_nodes(tree)\n print(r\"%% \" + \"Links\")\n print_links(tree, tree)\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n print(r\"%% \" + ntpath.basename(sys.argv[1]))\n print(r\"%% \" + \"Generated by c-flowchart\")\n tree = generate_call_tree(sys.argv[1])\n print_mermaid_graph(tree)\n else:\n print(\"Please provide a filename as argument\")\n","sub_path":"mermaid_graph.py","file_name":"mermaid_graph.py","file_ext":"py","file_size_in_byte":10541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"413607255","text":"import networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\n#needed to be done only once\r\n#G=nx.erdos_renyi_graph(10,0.5)\r\n#nx.write_gml(G,'random_graph.gml')\r\n\r\ndef set_all_B(G):\r\n for each in G.nodes():\r\n G.node[each]['action']='B'\r\n\r\ndef set_A(G,list1):\r\n for each in list1:\r\n G.node[each]['action']='A'\r\n\r\ndef get_colors(G):\r\n list1=[]\r\n for each in G.nodes():\r\n if G.node[each]['action']=='B':\r\n list1.append('red')\r\n else:\r\n list1.append('green')\r\n return list1\r\n\r\ndef find_neigh(node1,action,G):\r\n num=0\r\n for each in G.neighbors(node1):\r\n if G.node[each]['action']==action:\r\n num+=1\r\n return num\r\n\r\ndef recalculate_options(G):\r\n dict1={}\r\n # Payoff(A)=a=4\r\n # Payoff(A)=b=3\r\n a=4\r\n b=3\r\n for each in G.nodes():\r\n num_A=find_neigh(each,'A',G)#finds neighbour of current node that accepted action A\r\n num_B=find_neigh(each,'B',G)\r\n \r\n payoff_A=a*num_A\r\n payoff_B=b*num_B\r\n \r\n if payoff_A>=payoff_B:\r\n dict1[each]='A'\r\n else:\r\n dict1[each]='B'\r\n return dict1\r\n \r\ndef reset_node_attributes(G,action_dict):\r\n for each in action_dict:\r\n G.node[each]['action']=action_dict[each]\r\n\r\nG=nx.read_gml('random_graph.gml')\r\n\r\n#every node will have an attribute action and value of the action=B\r\nset_all_B(G)\r\n\r\nlist1=[3,7]#initial adopting nodes\r\nset_A(G,list1)\r\n\r\ncolors=get_colors(G)\r\nnx.draw(G,node_color=colors,node_size=800,with_labels=1)\r\nplt.show()\r\n\r\naction_dict=recalculate_options(G)#dictionary with nodes as keys and their action as values\r\n\r\nreset_node_attributes(G,action_dict)\r\ncolors=get_colors(G)\r\nnx.draw(G,node_color=colors,node_size=800,with_labels=1)\r\nplt.show()","sub_path":"src/Week 7-Cascading Behaviour in Networks and coding 4 big ideas/basecode.py","file_name":"basecode.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"4576172","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom employee.models import EmployeeProfileInfo\n\nclass EmployeeForm(forms.ModelForm):\n class Meta():\n model = User\n fields = ('first_name','email',)\n\nclass EmployeeProfileInfoForm(forms.ModelForm):\n class Meta():\n model = EmployeeProfileInfo\n fields = ('profile_pic','age','phone','address')\n\n widgets = {\n 'phone':forms.TextInput(attrs={'class':'textinputclass'}),\n 'address':forms.Textarea(attrs={'class':'editable'})\n }\n","sub_path":"alms/employee/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"353713448","text":"\n\nfrom xai.brain.wordbase.adjectives._wise import _WISE\n\n#calss header\nclass _WISEST(_WISE, ):\n\tdef __init__(self,): \n\t\t_WISE.__init__(self)\n\t\tself.name = \"WISEST\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"wise\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_wisest.py","file_name":"_wisest.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"483526331","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Linear_layer:\n def __init__(self, input_dimension, output_dimension, learning_rate):\n self.learning_rate = learning_rate\n # Random initialization of weight and bias\n # Xavier initialization: weight (mean = 0 and variance = 2/(input_dimension + output_dimension)\n self.weight = np.random.randn(input_dimension,output_dimension)*np.sqrt(1/input_dimension)\n #self.weight = np.random.normal(loc=0.0, scale = (2/(input_dimension+output_dimension))**0.5, size = (input_dimension,output_dimension))\n #self.weight = np.ones((input_dimension,output_dimension))\n self.bias = np.zeros(output_dimension)[None,:]\n \n def forward(self,input_of_Linear_layer):\n # output = input*W+b\n # input shape = batch_size * input_dimension\n # output shape = batch_size * out_dimension\n # weight shape = input_dimentsion * output_dimension\n # bias shape = 1 * output_dimension\n \n return np.dot(input_of_Linear_layer,self.weight) + self.bias\n\n def backward(self,input_of_Linear_layer,df_over_doutput):\n # using the chain rule: df/dinput = df/doutput * doutput/dinput\n # doutput/dinput = weight.T\n df_over_dinput = np.dot(df_over_doutput, self.weight.T)\n \n # df/dweight = doutput/dweight * df/doutput\n # doutput/dweight = input.T\n df_over_dweight = np.dot(input_of_Linear_layer.T, df_over_doutput)\n\n df_over_dbias = np.mean(df_over_doutput, axis=0)[None,:]\n \n\n # Updata weight and bias using GD\n self.weight = self.weight - self.learning_rate * df_over_dweight\n self.bias = self.bias - self.learning_rate * df_over_dbias\n \n return df_over_dinput\n\nclass ReLU:\n def forward(self, input_of_ReLU):\n return np.maximum(input_of_ReLU,0) \n\n \n def backward(self, input_of_ReLU, df_over_doutput):\n # df_over_dinput = np.zeros(df_over_doutput.shape)\n\n \n # [rows, cols] = df_over_dinput.shape\n # for i in range(rows):\n # for j in range(cols):\n # if input_of_ReLU[i][j]<0:\n # df_over_dinput[i][j] = 0.0\n # else:\n # df_over_dinput[i][j] = df_over_doutput[i][j]\n\n return (input_of_ReLU > 0) * df_over_doutput\n\n\nclass Leaky_ReLU:\n def __init__(self, initial_gamma, learning_rate):\n self.learning_rate = learning_rate\n self.gamma = initial_gamma\n\n def forward(self, input_of_Leaky_ReLU):\n return np.maximum(input_of_Leaky_ReLU,0) + self.gamma * np.minimum(input_of_Leaky_ReLU,0)\n\n\n def backward(self, input_of_Leaky_ReLU, df_over_doutput):\n df_over_dgamma = np.mean(np.sum(np.minimum(input_of_Leaky_ReLU, 0) * df_over_doutput, axis = 1))\n self.gamma = self.gamma - self.learning_rate * df_over_dgamma\n if self.gamma < 0 :\n self.gamma = 0\n df_over_dinput = (input_of_Leaky_ReLU > 0) * df_over_doutput + self.gamma * (input_of_Leaky_ReLU <= 0) * df_over_doutput\n return df_over_dinput\n\n\n\ndef softmax(input_of_softmax):\n input_exp = np.exp(input_of_softmax - np.max(input_of_softmax, 1)[:, None]) \n return input_exp / np.sum(input_exp, axis=-1)[:, None]\n\n\ndef logsumexp(Z):\n Zmax = np.max(Z,axis=1)[:, None]\n return Zmax + np.log(np.sum(np.exp(Z - Zmax), axis=1))[:, None] \n\n\ndef mean_cost_crossentropy(input_of_softmax, reference_label):\n reference_matrix = np.zeros(input_of_softmax.shape, dtype = int)\n for i in range(len(reference_label)):\n reference_matrix[i][reference_label[i]] = 1\n return - np.mean(np.sum(input_of_softmax*reference_matrix, 1)[:, None] - logsumexp(input_of_softmax))\n\ndef calculate_dmean_cost_crossentropy_over_dinputofSoftmax(input_of_softmax,reference_label):\n reference_matrix = np.zeros(input_of_softmax.shape, dtype = int)\n for i in range(len(reference_label)):\n reference_matrix[i][reference_label[i]] = 1\n return (-reference_matrix + softmax(input_of_softmax))/input_of_softmax.shape[0]\n\n\n\n\ndef forward(nn, input_of_nn):\n output_of_each_layer = []\n current_input = input_of_nn\n for i in range(len(nn)):\n output_of_each_layer.append(nn[i].forward(current_input))\n current_input = output_of_each_layer[-1] #nn[i].forward(current_input)\n return output_of_each_layer\n\n# def forward2(nn, input_of_nn):\n# output_of_each_layer = []\n# current_input = input_of_nn\n# output_of_each_layer.append(nn[0].forward(current_input))\n# current_input = output_of_each_layer[-1] \n# output_of_each_layer.append(ReLU().forward(current_input))\n# current_input = output_of_each_layer[-1] \n\n\n# # for layer in nn:\n# # output_of_each_layer.append(layer.forward(current_input))\n# # current_input = output_of_each_layer[-1]\n \n# return output_of_each_layer[0]\n\ndef predict(nn,input_of_nn):\n result_matrix = forward(nn,input_of_nn)[-1]\n return (np.argmax(result_matrix,axis =1))\n\n\ndef train(nn,input_of_nn,reference_label):\n\n input_of_each_layer = [input_of_nn]+forward(nn,input_of_nn)\n input_of_softmax = input_of_each_layer[-1]\n \n mean_cost = mean_cost_crossentropy(input_of_softmax,reference_label)\n dmean_cost_over_dinput_of_softmax = calculate_dmean_cost_crossentropy_over_dinputofSoftmax(input_of_softmax,reference_label)\n dmean_cost_over_dcurrent_input = dmean_cost_over_dinput_of_softmax\n\n for i in range(len(nn)):\n layer_index = len(nn)-1-i\n\n layer = nn[layer_index]\n \n dmean_cost_over_dcurrent_input = layer.backward(input_of_each_layer[layer_index],dmean_cost_over_dcurrent_input) \n \n return mean_cost\n\n\n\n\n\n\n\ntransform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n\n\ntrain_and_validation_set = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,download=True, transform=transform)\n\ntrain_percentage = 0.95\nnp.random.seed(42)\ntrain_val_split = np.random.permutation(len(train_and_validation_set))\ntrainset = torch.utils.data.Subset(train_and_validation_set,train_val_split[:int(train_percentage*len(train_and_validation_set))])\nvalset = torch.utils.data.Subset(train_and_validation_set,train_val_split[int(train_percentage*len(train_and_validation_set)):])\n\n#print(len(trainset))\n\n#trainset, valset = torch.utils.data.random_split(train_and_validation_set, [int(0.95*len(train_and_validation_set)), len(train_and_validation_set)-int(0.95*len(train_and_validation_set))])\n\n# x = [0,0,0,0,0,0,0,0,0,0]\n# print(len(x))\n# for i in range(45000):\n# x[trainset.__getitem__(i)[1]] += 1\n\n# for i in range(5000):\n# x[valset.__getitem__(i)[1]] += 1\n# print (x)\n\n\n\nlr = 0.02\ninitial_gamma = 0.1\nneural_network = []\nneural_network.append(Linear_layer(3*32*32,1000,lr))\nneural_network.append(Leaky_ReLU(initial_gamma,lr))\n#neural_network.append(ReLU())\n\n\nneural_network.append(Linear_layer(1000,500,lr))\nneural_network.append(Leaky_ReLU(initial_gamma,lr))\n#neural_network.append(ReLU())\n\nneural_network.append(Linear_layer(500,200,lr))\nneural_network.append(Leaky_ReLU(initial_gamma,lr))\n#neural_network.append(ReLU())\n\nneural_network.append(Linear_layer(200,100,lr))\nneural_network.append(Leaky_ReLU(initial_gamma,lr))\n#neural_network.append(ReLU())\n\nneural_network.append(Linear_layer(100,50,lr))\nneural_network.append(Leaky_ReLU(initial_gamma,lr))\n#neural_network.append(ReLU())\n\nneural_network.append(Linear_layer(50,20,lr))\nneural_network.append(Leaky_ReLU(initial_gamma,lr))\n#neural_network.append(ReLU())\n\nneural_network.append(Linear_layer(20,10,lr))\n\n\ntrain_acc = []\nval_acc = []\ntest_acc = []\nmean_cost = []\ngamma_list = []\ngamma_list.append(initial_gamma)\nsize_of_batch_train = 128\nsize_of_batch_val = 100\nsize_of_batch_test = 100\nnumber_of_epoch = 200\nfor epoch in range(number_of_epoch):\n i = 0\n \n trainloader = torch.utils.data.DataLoader(trainset, batch_size=size_of_batch_train, shuffle=True, num_workers=0)\n for train_data in trainloader:\n train_images, train_labels = train_data\n train_input = train_images.view(-1,3*32*32).numpy()\n train_output = train_labels.numpy()\n train(neural_network,train_input,train_output)\n\n i = i + 1\n if i%int(len(trainset)/(size_of_batch_train*4)) == 0:\n print('Epoch No.%d training %f finished' %(epoch+1, i*size_of_batch_train/len(trainset)))\n #dloss_over_dinput_of_softmax = (calculate_dmean_cost_crossentropy_over_dinputofSoftmax(forward(neural_network,train_input)[-1], train_output))\n #print(dloss_over_dinput_of_softmax[0])\n #dloss_over_dinput_of_linear = (neural_network[-1].backward(forward(neural_network, train_input)[-2],dloss_over_dinput_of_softmax))\n #print(dloss_over_dinput_of_linear[0])\n \n #dloss_over_dinput_of_relu = (neural_network[-2].backward(forward(neural_network, train_input)[-3],dloss_over_dinput_of_linear))\n #print(dloss_over_dinput_of_relu[0])\n\n\n #print((forward(neural_network, train_input)[0])[0])\n #print((forward(neural_network, train_input)[1])[0])\n #print((neural_network[0].forward(train_input))[0])\n #print(neural_network[1].gamma)\n if isinstance(neural_network[1], Leaky_ReLU):\n gamma_list.append(neural_network[1].gamma)\n\n\n total_cost = 0\n train_correct = 0\n train_total = len(trainset)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=size_of_batch_train, shuffle=False, num_workers=0)\n for train_data in trainloader:\n train_images, train_labels = train_data\n train_input = train_images.view(-1,3*32*32).numpy()\n train_output = train_labels.numpy()\n train_correct += (np.sum(predict(neural_network, train_input) == train_output))\n total_cost += size_of_batch_train * mean_cost_crossentropy(forward(neural_network, train_input)[-1], train_output)\n mean_cost.append(total_cost/len(trainset))\n train_acc.append(train_correct/train_total)\n\n val_correct = 0\n val_total = len(valset)\n valloader = torch.utils.data.DataLoader(valset, batch_size=size_of_batch_val, shuffle=False, num_workers=0)\n for val_data in valloader:\n val_images, val_labels = val_data\n val_input = val_images.view(-1,3*32*32).numpy()\n val_output = val_labels.numpy()\n val_correct += (np.sum(predict(neural_network, val_input) == val_output))\n \n val_acc.append(val_correct/val_total)\n\n test_correct = 0\n test_total = len(testset)\n testloader = torch.utils.data.DataLoader(testset, batch_size=size_of_batch_test, shuffle=False, num_workers=0)\n for test_data in testloader:\n test_images, test_labels = test_data\n test_input = test_images.view(-1,3*32*32).numpy()\n test_output = test_labels.numpy()\n test_correct += (np.sum(predict(neural_network, test_input) == test_output))\n \n test_acc.append(test_correct/test_total)\n\nprint(gamma_list)\nprint(mean_cost)\nprint(train_acc)\nprint(val_acc)\nprint(test_acc)\n\n\n\nplt.figure()\nplt.plot([i+1 for i in range(number_of_epoch)], train_acc,marker='*', label='train accuracy', color = 'blue')\nplt.plot([i+1 for i in range(number_of_epoch)], val_acc, marker='o',label='validation accuracy', color = 'black')\n\n#plt.plot([i+1 for i in range(number_of_epoch)], test_acc,marker = 'v',label='test accuracy', color = 'red')\nplt.grid()\nplt.legend(loc = 'lower right')\nplt.yticks(np.arange(0,1.1,0.1))\ntitle1 = 'Learning Rate: ' + str(lr) + ' Batch Size: ' + str(size_of_batch_train)\nplt.title(title1)\nplt.xlabel('Training Epoch')\nplt.ylabel('Accuracy')\n\n\n\nplt.figure()\nplt.plot([i+1 for i in range(number_of_epoch)], mean_cost)\nplt.grid()\nplt.xlabel('Training Epoch')\nplt.ylabel('Mean Cost')\n\nif isinstance(neural_network[1], Leaky_ReLU):\n plt.figure()\n plt.plot(gamma_list)\n plt.grid()\n plt.xlabel('Training Epoch')\n plt.ylabel('Learnable Parameter Gamma')\nplt.show()\n\n\n\n# testloader = torch.utils.data.DataLoader(testset, batch_size=size_of_batch_test, shuffle=False, num_workers=0)\n# test_input = []\n# test_output = []\n# for test_data in testloader:\n# test_images, test_labels = test_data\n# test_input = test_input + test_images.view(-1,3*32*32).numpy().tolist()\n# test_output = test_output + test_labels.numpy().tolist()\n# test_input = np.array(test_input)\n# test_output = np.array(test_output)\n# print(np.mean(predict(neural_network,test_input)==test_output))\n\n\n\n","sub_path":"p3/project3_mlp.py","file_name":"project3_mlp.py","file_ext":"py","file_size_in_byte":12778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"405514659","text":"# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------\n# Copyright © 2012, RedJack, LLC.\n# All rights reserved.\n#\n# Please see the COPYING file in this distribution for license details.\n# ----------------------------------------------------------------------\n\nfrom __future__ import absolute_import\n\nimport os\nimport os.path\nimport sys\nimport yaml\n\nimport buzzy.utils\nimport buzzy.version\nimport buzzy.yaml\nfrom buzzy.errors import BuzzyError\n\n\n#-----------------------------------------------------------------------\n# Command-line options\n\nforce = False\nforce_all = False\nverbosity = 0\nversion = buzzy.version.version\n\n\n#-----------------------------------------------------------------------\n# Environment files\n\nclass EnvironmentVersion(buzzy.yaml.Fields):\n def ask(self, name, prompt, default=None, validate=None):\n if not hasattr(self, name) or getattr(self, name) is None:\n while True:\n if default is None:\n sys.stdout.write(\"%s \" % prompt)\n else:\n sys.stdout.write(\"%s [%s] \" % (prompt, default))\n\n sys.stdout.flush()\n result = sys.stdin.readline().rstrip()\n if result == \"\":\n if default is None:\n continue\n else:\n result = default\n\n if validate is not None:\n if not validate(result):\n continue\n\n setattr(self, name, result)\n return\n\n @classmethod\n def upgrade_from(cls, env, prev):\n self = cls()\n for field_name, _ in self.all_fields():\n if hasattr(prev, field_name):\n setattr(self, field_name, getattr(prev, field_name))\n self.version = prev.version + 1\n self.upgrade_new_fields(env, prev)\n return self\n\n\nclass Environment(object):\n env_path = \".buzzy\"\n\n def is_current_version(self, version):\n return version == len(self.versions)-1\n\n def update(self):\n env_filename = os.path.join(self.env_path, self.env_filename)\n if os.path.exists(env_filename):\n env = self.load(False)\n else:\n env = self.versions[0]()\n env.version = 0\n\n while not self.is_current_version(env.version):\n next_class = self.versions[env.version + 1]\n env = next_class.upgrade_from(self, env)\n\n self.save(env)\n\n def load(self, check_version=True):\n env_filename = os.path.join(self.env_path, self.env_filename)\n\n try:\n env_file = open(env_filename, \"r\")\n content = yaml.safe_load(env_file)\n except IOError:\n raise BuzzyError(\"Please run \\\"buzzy configure\\\" first.\")\n\n version = content[\"version\"]\n if check_version and not self.is_current_version(version):\n raise BuzzyError \\\n (\"Outdated configuration, please rerun \\\"buzzy configure\\\".\")\n\n env_class = self.versions[version]\n result = env_class.from_yaml(content, content)\n # Most of the time this will be already set, but let's make sure.\n result.version = version\n return result\n\n def save(self, env):\n env_class = self.versions[env.version]\n content = env_class.to_yaml(env)\n\n try:\n buzzy.utils.makedirs(self.env_path)\n env_filename = os.path.join(self.env_path, self.env_filename)\n env_file = open(env_filename, \"w\")\n yaml.dump(content, env_file, default_flow_style=False)\n except IOError as e:\n raise BuzzyError(str(e))\n\n\n#-----------------------------------------------------------------------\n# Default environment schema\n\ndef validate_path(path):\n if not os.path.exists(path):\n print(\"%s does not exist.\" % path)\n return False\n else:\n return True\n\n\nclass Environment_0(EnvironmentVersion):\n def __init__(self):\n self.version = 0\n\n\nclass Environment_1(EnvironmentVersion):\n def fields(self):\n yield \"version\"\n yield \"build_dir\"\n yield \"package_dir\"\n yield \"recipe_database\"\n\n def upgrade_new_fields(self, env, prev):\n self.ask(\"recipe_database\", \"Where is your recipe database?\",\n validate=validate_path)\n self.ask(\"build_dir\", \"Where should I build packages?\",\n default=os.path.join(env.env_path, \"build\"))\n\n\nclass Environment_2(EnvironmentVersion):\n def fields(self):\n yield \"version\"\n yield \"build_dir\"\n yield \"repo_name\"\n yield \"repo_dir\"\n yield \"recipe_database\"\n\n def upgrade_new_fields(self, env, prev):\n if prev.package_dir is None:\n self.ask(\"repo_dir\", \"Where should I put the packages that I build?\",\n default=os.path.join(env.env_path, \"packages\"))\n else:\n self.repo_dir = prev.package_dir\n\n self.ask(\"repo_name\",\n \"What is the name of the package repository that I produce?\")\n\n\nclass Environment_3(EnvironmentVersion):\n def fields(self):\n yield \"version\"\n yield \"build_dir\"\n yield \"email\"\n yield \"name\"\n yield \"repo_name\"\n yield \"repo_dir\"\n yield \"recipe_database\"\n\n def upgrade_new_fields(self, env, prev):\n try:\n import pwd\n import socket\n pwd_entry = pwd.getpwuid(os.getuid())\n default_email = \"%s@%s\" % (pwd_entry[0], socket.getfqdn())\n default_name = pwd_entry[4].split(\",\")[0]\n except ImportError:\n default_email = None\n default_name = None\n\n self.ask(\"name\",\n \"What is the name of the person or organization \"\n \"responsible for these packages?\",\n default=default_name)\n self.ask(\"email\",\n \"What is the email address of the person or organization \"\n \"responsible for these packages?\",\n default=default_email)\n\n\nclass DefaultEnvironment(Environment):\n versions = [\n Environment_0,\n Environment_1,\n Environment_2,\n Environment_3,\n ]\n\n env_filename = \"config.yaml\"\n\n\nenv = None\n\ndef load_env(check_version=True):\n global env\n env = DefaultEnvironment().load(check_version)\n\n\ndef configure_env():\n DefaultEnvironment().update()\n","sub_path":"buzzy/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"52215856","text":"from flask import Flask,render_template,request\r\nimport pickle\r\n\r\n# Load the Multinomial Naive Bayes model and CountVectorizer object from disk\r\nfilename = 'spam-sms-mnb-model.pkl'\r\nclassifier = pickle.load(open(filename, 'rb'))\r\ncv = pickle.load(open('cv-transform.pkl','rb'))\r\napp = Flask(__name__)\r\n\r\n@app.route('/',methods=['GET','POST'])\r\ndef home():\r\n return render_template('index.html')\r\n\r\n@app.route('/prediction',methods=['POST'])\r\ndef predict():\r\n if request.method=='POST':\r\n message=request.form['message']\r\n data=[message]\r\n vect=cv.transform(data).toarray()\r\n mypred=classifier.predict(vect)\r\n return render_template('result.html',result=mypred)\r\nif __name__=='__main__':\r\n app.run(debug=True)\r\n\r\n\r\n\r\n\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"23820684","text":"import math\n\nfrom aiohttp.web import HTTPNotFound\nfrom sqlalchemy import func\n\n\nasync def get_record_by_id(conn, type_record, record_id):\n result = await conn.execute(\n type_record.select().where(type_record.c.id == record_id)\n )\n\n return await result.fetchone()\n\n\nasync def get_paginated_records(conn, query, page, model):\n count_query = query.with_only_columns([func.count(model.c.id)]).order_by(None)\n count_recors = await conn.scalar(count_query)\n total_pages = math.ceil(float(count_recors)/10)\n\n pagination = {\n 'total_pages': total_pages\n }\n\n records = await conn.execute(\n query.offset((page - 1) * 10).limit(10)\n )\n\n return {\n \"data\": records,\n \"pagination\": pagination\n }\n\n\nasync def fetch_one_or_404(model):\n res = await model.fetchone()\n\n if not res:\n raise HTTPNotFound()\n\n return res\n","sub_path":"content/views/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"556456699","text":"from unis.models import *\nfrom unis.runtime import Runtime\nfrom unis.rest import UnisReferenceError\nfrom unis.models.lists import UnisCollection\nimport itertools\n\n\ndef commit(target):\n collections = [\"ports\", \"nodes\", \"links\", \"paths\", \"networks\", \n \"domains\", \"topologies\", \"exnodes\", \"extents\"]\n unordered = filter(lambda x: x not in collections, target.collections)\n collections.extend(unordered)\n for collection in collections:\n for item in getattr(target, collection):\n item.commit()\n\ndef node(rt, name):\n node = Node({\"name\": name})\n rt.insert(node)\n return node\n\ndef port(rt, node=None):\n name = node.name if node else \"ORPHANED\"\n port = Port({\"name\": \":\".join([name, \"port1\"])})\n rt.insert(port)\n if node: node.ports = [port]\n return port\n\ndef link(rt, mapping):\n left = next(rt.ports.where({\"name\": \":\".join([mapping[0], \"port1\"])}))\n right = next(rt.ports.where({\"name\": \":\".join([mapping[1], \"port1\"])}))\n link = Link({\"name\": \"--\".join([left.name, right.name]), \n \"directed\": False, \n \"endpoints\": [left, right]})\n rt.insert(link)\n return link\n \ndef domain(rt, name):\n nodes = list(rt.nodes.where(lambda x: x.name == name))\n ports = list(rt.ports.where(lambda x: x.name.startswith(name)))\n links = list(rt.links.where(lambda x: x.endpoints[0].name.startswith(name)))\n domain = Domain({\"name\": name, \"nodes\": nodes, \"ports\": ports, \"links\":links})\n rt.insert(domain)\n return domain\n\ndef topology(rt, name, ports, nodes, links, domains):\n topo = Topology({\"name\": name, \"ports\": ports, \n \"nodes\": nodes, \"links\": links, \n \"domains\": domains})\n rt.insert(topo)\n\n\n\ndef osiris(url):\n with Runtime(url) as rt:\n domain_names = [\"IU\", \"WSU\", \"MSU\", \"CHIC\", \"SALT\", \n \"SC16\", \"IU-Crest\", \"UMich\", \"Cloudlab\"]\n link_map = [(\"IU\", \"CHIC\"), (\"UMich\", \"CHIC\"), (\"WSU\", \"CHIC\"), \n (\"MSU\", \"CHIC\"), (\"CHIC\", \"SALT\"), (\"Cloudlab\", \"SALT\"), \n (\"SC16\", \"SALT\"), (\"SC16\", \"UMich\"), (\"SC16\", \"IU-Crest\")]\n nodes = [node(rt, d) for d in domain_names]\n ports = [port(rt, n) for n in nodes]\n links = [link(rt, l) for l in link_map]\n domains = [domain(rt, d) for d in domain_names]\n topology(rt, \"OSiRIS\", nodes, ports, links, domains)\n commit(rt)\n\n\n\ndef ring_spur(url, ring, spurs):\n def name(link, spur): return \"Node-{0}-{1}\".format(link, spur)\n \n node_names = [name(i, j)\n for j in range(spurs)\n for i in range(ring)]\n ring_links = [(name(i,0), name((i+1)%ring, 0))\n for i in range(ring)]\n spur_links = [(name(i,j), name(i, 0))\n for j in range(1, spurs)\n for i in range(ring)]\n \n link_map = list(itertools.chain(ring_links, spur_links))\n\n with Runtime(url) as rt:\n nodes = [node(rt, d) for d in node_names]\n ports = [port(rt, n) for n in nodes]\n links = [link(rt, l) for l in link_map]\n domain = Domain({\"name\": \"ring-domain\", \"nodes\": nodes, \"ports\": ports, \"links\": links})\n rt.insert(domain)\n topology(rt, \"ring\", nodes, ports, [], [domain])\n commit(rt)\n\ndef orphaned_items(url):\n with Runtime(url) as rt:\n n = node(rt, \"in-orpaned-domain\")\n p = port(rt, n)\n domain = Domain({\"name\": \"orphaned-domain\", \"nodes\": [n], \"ports\": [p]})\n rt.insert(domain) \n \n n = node(rt, \"orphaned-node\")\n p = port(rt)\n commit(rt)\n \ndef main():\n import sys\n import argparse\n \n parser = argparse.ArgumentParser(description=\"Topology builder for test topologies in UNIS\")\n parser.add_argument('unis', \n help=\"Address of the UNIS to connect to (must include http://)\")\n parser.add_argument('-t', '--topology', default=\"osiris\", required=False,\n choices=[\"all\", \"osiris\", \"ring\", \"orphans\"], \n help=\"Topology name to build.\")\n parser.add_argument('-r', \"--ring\", default=10, type=int,\n help=\"Circumferernce of a ring to build (for ring only)\")\n parser.add_argument('-s', \"--spur\", default=3, type=int,\n help=\"Length of spurs to build (for ring only)\")\n\n args = parser.parse_args(sys.argv[1:])\n \n if args.topology == \"osiris\" or args.topology == \"all\":\n print(\"Building osiris\")\n osiris(args.unis)\n print(\"Done!\\n\")\n \n if args.topology == \"ring\" or args.topology == \"all\":\n print(\"Building ring/spur with {0} circumference and spurs of length {1}\".format(args.ring, args.spur))\n ring_spur(args.unis, args.ring, args.spur)\n print(\"Done!\\n\")\n \n if args.topology == \"orphans\" or args.topology == \"all\":\n print(\"Building orphans\")\n orphaned_items(args.unis)\n print(\"Done!\\n\")\n \nif __name__ == \"__main__\": \n main()\n\n","sub_path":"build_topologies.py","file_name":"build_topologies.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"264119807","text":"import random\nguesses_made = 0\nname = input(' Привет как тебяя зовут? \\n ')\nnumber = random.randint(1, 40)\nprint('Отлично, {0}, я загадала число между 1 и 40. Сможешь угадать?'.format(name))\nwhile guesses_made < 6:\n guess = int(input('Введите число:'))\n guesses_made += 1\n if guess < number:\n print('Твое число меньше того, что я загадал.')\n if guess > number:\n break\nif guess == number:\n print(' О ты {0} Ты угадал мое число использовав {1} попыток'.format(name , guesses_made))\nelse:\n print(' А вот и не угадал) Я загадал число {0}'.format(number))\n","sub_path":"lisson7/domashka.py","file_name":"domashka.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"613879086","text":"import tensorflow as tf\nimport numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\nfrom model import Model, image_width, image_height\nfrom styx_msgs.msg import TrafficLight\n\n# Start\nprint(\"Running on TensorFlow \" + str(tf.__version__))\n\n# Set configuration\ntrain_data_dir = 'train'\nvalidation_data_dir = 'validation'\nnb_train_samples = 890\nnb_validation_samples = 160\nepochs = 50\nbatch_size = 16\n\n# Compile\nmodel = Model()\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nprint(model.summary())\n\n# Shear, zoom, and flip training data\ntrain_datagen = ImageDataGenerator(\n rescale=1.0 / 255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\n# Just rescale color for test data\ntest_datagen = ImageDataGenerator(rescale=1.0 / 255)\n\n# Predefine classes\nclasses = ['red', 'yellow', 'green', 'none']\nprint(\"Classes: \" + str(TrafficLight.RED) + \", \" + str(TrafficLight.YELLOW) + \", \" + str(TrafficLight.GREEN) + \", \" + str(TrafficLight.UNKNOWN) + \" = \" + str(classes))\n\n# Training data\nprint(\"Training:\")\ntrain_generator = train_datagen.flow_from_directory(\n train_data_dir,\n classes=classes,\n target_size=(image_width, image_height),\n batch_size=batch_size,\n class_mode='categorical')\n\n# Validation data\nprint(\"Validation:\")\nvalidation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n classes=classes,\n target_size=(image_width, image_height),\n batch_size=batch_size,\n class_mode='categorical')\n \n# Callbacks\ncheckpoint = ModelCheckpoint(filepath='./model_checkpoint.h5', verbose=1, save_best_only=True)\nlr_reducer = ReduceLROnPlateau(factor=np.sqrt(0.1), cooldown=0, patience=5, min_lr=0.5e-6)\ncallbacks = [checkpoint, lr_reducer]\n\n# Train\nmodel.fit_generator(\n train_generator,\n steps_per_epoch = nb_train_samples // batch_size,\n validation_data = validation_generator,\n validation_steps = nb_validation_samples // batch_size,\n epochs=epochs,\n callbacks=callbacks)\n\n# Save\nmodel.save_weights('model.h5')\n\n\n","sub_path":"ros/src/tl_detector/light_classification/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"290903511","text":"#!/usr/bin/env python\n#\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Michael A.G. Aivazis\n# California Institute of Technology\n# (C) 1998-2005 All Rights Reserved\n#\n# \n#\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n\n\nfrom pyre.components.Component import Component\n\n\nclass Launcher(Component):\n\n\n class Inventory(Component.Inventory):\n\n import pyre.inventory\n\n nodes = pyre.inventory.int(\"nodes\", default=0)\n nodelist = pyre.inventory.slice(\"nodelist\")\n\n\n def launch(self):\n raise NotImplementedError(\"class '%s' must override 'launch'\" % self.__class__.__name__)\n\n\n def __init__(self, name):\n Component.__init__(self, name, facility=\"launcher\")\n self.nodes = 0\n self.nodelist = None\n return\n\n\n def _configure(self):\n self.nodes = self.inventory.nodes\n self.nodelist = self.inventory.nodelist\n return\n\n\n# version\n__id__ = \"$Id: Launcher.py,v 1.1.1.1 2005/03/08 16:13:30 aivazis Exp $\"\n\n# End of file \n","sub_path":"pythia-0.8/packages/mpi/mpi/Launcher.py","file_name":"Launcher.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"107336816","text":"\"\"\"\n@File : tid2013_input.py\n@Time : 2017/6/22 \n@Author : Chen Huang\n@Update : \n@Discription : convert original data to standard tensorflow data '.tfrecords';\n generate image and label batch.\n\"\"\"\n\n\n# from __future__ import unicode_literals\n# from __future__ import print_function\n# from __future__ import division\n\nimport os\nimport gzip\nimport numpy\nimport PIL.Image as Image\n\nfrom tensorflow.python.platform import gfile\nimport tensorflow as tf\n\n# dirs\nDATA_DIR = '../data'\nLOG_DIR = '../logs'\n\n# path of mnist\nDIR = 'D:/Data'\nDATABASE = 'tid2013'\nMOS_PATH = DIR + '/' + DATABASE + '/mos_with_names.txt'\nREF_PATH = DIR + '/' + DATABASE + '/reference_images/'\nDIS_PATH = DIR + '/' + DATABASE + '/distorted_images/'\n\n# information of mnist\nHEIGHT = 384\nWIDTH = 512\nDEPTH = 3\n\nPATCH_SIZE = 32\nNUM_PATCHES_PER_IMAGE = 32\n\nTRAIN_DATA_NUM = 15\nVAL_DATA_NUM = 5\nTEST_DATA_NUM = 5\nNUM_PER_IMAGE = 5*24\n\ndef _read32(bytestream):\n dt = numpy.dtype(numpy.uint32).newbyteorder('>')\n return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]\n\n\ndef dense_to_one_hot(labels_dense, num_classes):\n \"\"\"Convert class labels from scalars to one-hot vectors.\"\"\"\n num_labels = labels_dense.shape[0]\n index_offset = numpy.arange(num_labels) * num_classes\n labels_one_hot = numpy.zeros((num_labels, num_classes))\n labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\n return labels_one_hot\n\n\ndef extract_images(f):\n \"\"\"Extract the images into a 4D uint8 numpy array [index, y, x, depth].\n\n Args:\n :param f: file object. a file object that can be passed into a gzip reader.\n\n Returns:\n :return data: A 4D uint8 numpy array [index, y, x, depth].\n\n Raises:\n :exception ValueError: If the bytestream does not start with 2051.\n \"\"\"\n print('Extracting', f.name)\n with gzip.GzipFile(fileobj=f) as bytestream:\n magic = _read32(bytestream)\n if magic != 2051:\n raise ValueError('Invalid magic number %d in MNIST image file: %s' %\n (magic, f.name))\n num_images = _read32(bytestream)\n rows = _read32(bytestream)\n cols = _read32(bytestream)\n buf = bytestream.read(rows * cols * num_images)\n data = numpy.frombuffer(buf, dtype=numpy.uint8)\n data = data.reshape(num_images, rows, cols, 1)\n\n return data\n\n\ndef extract_labels(f, one_hot=False, num_classes=10):\n \"\"\"Extract the labels into a 1D uint8 numpy array [index].\n\n Args:\n :param f: file object. A file object that can be passed into a gzip reader.\n :param one_hot: bool. Does one hot encoding for the result.\n :param num_classes: int. Number of classes for the one hot encoding.\n\n Returns:\n :returns labels: ndarray. a 1D uint8 numpy array.\n\n Raises:\n :exception ValueError: If the bystream doesn't start with 2049.\n \"\"\"\n print('Extracting', f.name)\n with gzip.GzipFile(fileobj=f) as bytestream:\n magic = _read32(bytestream)\n if magic != 2049:\n raise ValueError('Invalid magic number %d in MNIST label file: %s' %\n (magic, f.name))\n num_items = _read32(bytestream)\n buf = bytestream.read(num_items)\n labels = numpy.frombuffer(buf, dtype=numpy.uint8)\n if one_hot:\n return dense_to_one_hot(labels, num_classes)\n\n return labels\n\n\ndef load_img(path, gray_scale=False):\n \"\"\" Load image and convert to Image object.\n\n Args:\n :param path:str. the path of the image file.\n :param gray_scale:bool. gray or color.\n\n Return:\n :return img:Image object. an instance of Image object.\n \"\"\"\n img = Image.open(path)\n if gray_scale:\n img = img.convert('L')\n else:\n img = img.convert('RGB')\n\n return img\n\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef _float_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef convert_to(x, y, z, filename):\n \"\"\"Converts data to tfrecords.\n\n Args:\n :param x, y: list - [img1, img2, ...].\n img: ndarray.\n :param name: str. \n \"\"\"\n if not gfile.Exists(filename):\n print('Writing', filename)\n writer = tf.python_io.TFRecordWriter(filename)\n for index in range(NUM_PER_IMAGE):\n image_x = x[index].tostring()\n image_y = y[index].tostring()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'label': _float_feature(z[index]),\n 'image_x': _bytes_feature(image_x),\n 'image_y': _bytes_feature(image_y)\n }))\n writer.write(example.SerializeToString())\n writer.close()\n\n\ndef load_data():\n \"\"\"Load database, convert to Examples and write the result to TFRecords.\"\"\"\n # Load data\n text_file = open(MOS_PATH, \"r\")\n lines = text_file.readlines()\n text_file.close()\n\n ref_img_set = []\n dis_img_set = []\n mos_set = []\n for line in lines:\n mos, name = line.rstrip().split(' ', 2) # (5.51, i01_01_1.bmp)\n ref_name = name.split('_')[0] + '.bmp' # i01.bmp\n\n path = REF_PATH + ref_name.lower()\n ref_img_set.append(numpy.asarray(load_img(path, gray_scale=False), dtype=numpy.uint8)) # ndarray(0,255)\n path = DIS_PATH + name.lower()\n dis_img_set.append(numpy.asarray(load_img(path, gray_scale=False), dtype=numpy.uint8))\n mos_set.append(float(mos))\n\n # Convert to Examples and write the result to TFRecords.\n for i in range(TRAIN_DATA_NUM+VAL_DATA_NUM+TEST_DATA_NUM):\n x = [ref_img_set[j] for j in numpy.arange(i * NUM_PER_IMAGE, (i + 1) * NUM_PER_IMAGE)]\n y = [dis_img_set[j] for j in numpy.arange(i * NUM_PER_IMAGE, (i + 1) * NUM_PER_IMAGE)]\n z = [mos_set[j] for j in numpy.arange(i * NUM_PER_IMAGE, (i + 1) * NUM_PER_IMAGE)]\n\n # import matplotlib.pyplot as plt\n # plt.figure('subplot')\n # plt.subplot(2, 2, 1)\n # plt.imshow(ref_img_set[0] / 255.0)\n # plt.subplot(2, 2, 2)\n # plt.imshow(dis_img_set[0] / 255.0)\n # plt.subplot(2, 2, 3)\n # plt.imshow(ref_img_set[4] / 255.0)\n # plt.subplot(2, 2, 4)\n # plt.imshow(dis_img_set[4] / 255.0)\n # plt.show()\n\n if not gfile.Exists(os.path.join(DATA_DIR)):\n os.makedirs(os.path.join(DATA_DIR))\n\n filename = os.path.join(DATA_DIR, 'image_' + str(i) + '.tfrecords')\n convert_to(x, y, z, filename)\n\n\ndef read_and_decode(filename_queue):\n \"\"\"Reads and parses examples from data files .tfrecords.\n\n Args:\n :param filename_queue: queue. A queue of strings with the filenames to read from. \n\n Returns:\n :return result: DataRecord. An object representing a single example, with the following fields:\n label: an int32 Tensor.\n image_x, image_y: a [height*width*depth] uint8 Tensor with the image data.\n \"\"\"\n\n class DataRecord(object):\n pass\n\n result = DataRecord()\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n features = tf.parse_single_example(\n serialized_example,\n # Defaults are not specified since both keys are required.\n features={\n 'label': tf.FixedLenFeature([], tf.float32),\n 'image_x': tf.FixedLenFeature([], tf.string),\n 'image_y': tf.FixedLenFeature([], tf.string),\n })\n\n # Convert from a scalar string tensor to a uint8 tensor\n result.image_x = tf.decode_raw(features['image_x'], tf.uint8)\n result.image_y = tf.decode_raw(features['image_y'], tf.uint8)\n result.image_x.set_shape([HEIGHT*WIDTH*DEPTH])\n result.image_y.set_shape([HEIGHT*WIDTH*DEPTH])\n\n # Convert label from a scalar uint8 tensor to an int32 scalar.\n result.label = features['label']\n\n return result\n\n\ndef _generate_image_and_label_batch(image, label, min_queue_examples,\n batch_size, shuffle):\n \"\"\"Construct a queued batch of images and labels.\n\n Args:\n :param image: tuple - (image_x, image_y). \n imagex, image_y: 3-D Tensor of [height, width, 3] of type.float32.\n :param label: 1-D Tensor of type.float32\n :param min_queue_examples: int32, minimum number of samples to retain \n in the queue that provides of batches of examples.\n :param batch_size: Number of images per batch.\n :param shuffle: boolean indicating whether to use a shuffling queue.\n\n Returns:\n :return images_x, images_y: Images. 4D tensor of [batch_size, height, width, 3] size.\n :return labels: Labels. 1D tensor of [batch_size] size.\n \"\"\"\n # Create a queue that shuffles the examples, and then\n # read 'batch_size' images + labels from the example queue.\n num_preprocess_threads = 8\n if shuffle:\n images_x, images_y, label_batch = tf.train.shuffle_batch(\n [image[0], image[1], label],\n batch_size=batch_size,\n num_threads=num_preprocess_threads,\n capacity=min_queue_examples + 3 * batch_size,\n min_after_dequeue=min_queue_examples)\n else:\n images_x, images_y, label_batch = tf.train.batch(\n [image[0], image[1], label],\n batch_size=batch_size,\n num_threads=num_preprocess_threads,\n capacity=min_queue_examples + 3 * batch_size)\n\n # Display the training images in the visualizer.\n tf.summary.image('batch_images_x', tensor=images_x, max_outputs=4)\n tf.summary.image('batch_images_y', tensor=images_y, max_outputs=4)\n\n return images_x, images_y, label_batch\n\n\ndef random_sample(images_x, images_y, patch_size, num_patches):\n \"\"\"random sample patch pairs from image pairs.\n \n Args:\n :param images_x, images_y: tensor - (batch_size, height, width, depth). \n :param patch_size: int. \n :param num_patches: int. we crop num_patches patches from each image pair.\n \n Returns:\n :return patches_x, patches_y: tensor - (batch_size*num_patches, patch_size, patch_size, depth). \n \"\"\"\n patches_x = []\n patches_y = []\n\n images_xy = tf.concat([images_x, images_y], axis=3)\n for i in range(images_x.get_shape()[0].value):\n for j in range(num_patches):\n # Randomly crop a [height, width] section of the image.\n patch_xy = tf.random_crop(images_xy[i, :, :, :], [patch_size, patch_size, DEPTH*2])\n\n patches_x.append(patch_xy[:, :, :3])\n patches_y.append(patch_xy[:, :, 3:])\n\n patches_x = tf.convert_to_tensor(value=patches_x, dtype=tf.float32, name='sampled_patches_x')\n patches_y = tf.convert_to_tensor(value=patches_y, dtype=tf.float32, name='sampled_patches_y')\n\n return patches_x, patches_y\n\n\ndef distorted_inputs(filenames, batch_size):\n \"\"\"Construct distorted input for training using the Reader ops.\n\n Args:\n :param filenames: list - [str1, str2, ...].\n :param batch_size: int. \n\n Returns:\n :returns: tuple - (patches_x, patches_y, labels).\n patches_x, patches_y: tensors - (batch_size*num_patches, patch_size, patch_size, depth). \n lables: tensors - (batch_size).\n \"\"\"\n for f in filenames:\n if not tf.gfile.Exists(f):\n raise ValueError('Failed to find file: ' + f)\n\n with tf.variable_scope('input'):\n # Create a queue that produces the filenames to read.\n filename_queue = tf.train.string_input_producer(string_tensor=filenames)\n\n # Even when reading in multiple threads, share the filename queue.\n result = read_and_decode(filename_queue)\n\n # OPTIONAL: Could reshape into a image and apply distortionshere.\n reshaped_image_x = tf.reshape(result.image_x, [HEIGHT, WIDTH, DEPTH])\n reshaped_image_y = tf.reshape(result.image_y, [HEIGHT, WIDTH, DEPTH])\n\n # Convert from [0, 255] -> [-0.5, 0.5] floats.\n distorted_image_x = tf.cast(reshaped_image_x, tf.float32) * (1. / 255) - 0.5\n distorted_image_y = tf.cast(reshaped_image_y, tf.float32) * (1. / 255) - 0.5\n\n # # Randomly flip the image horizontally.\n # distorted_image = tf.image.random_flip_left_right(distorted_image)\n #\n # # Because these operations are not commutative, consider randomizing\n # # the order their operation.\n # distorted_image = tf.image.random_brightness(distorted_image,\n # max_delta=63)\n # distorted_image = tf.image.random_contrast(distorted_image,\n # lower=0.2, upper=1.8)\n #\n # # Subtract off the mean and divide by the variance of the pixels.\n # distorted_image = tf.image.per_image_standardization(distorted_image)\n #\n # # Set the shapes of tensors.\n # distorted_image.set_shape([patch_size, patch_size, result.depth])\n # result.label.set_shape([1])\n label = result.label\n\n # Ensure that the random shuffling has good mixing properties.\n min_queue_examples = 1000\n print('Filling queue with %d mnist images before starting to train or validation. '\n 'This will take a few minutes.' % min_queue_examples)\n\n # Generate a batch of images and labels by building up a queue of examples.\n images_x, images_y, labels = \\\n _generate_image_and_label_batch(image=(distorted_image_x, distorted_image_y), label=label,\n min_queue_examples=min_queue_examples,\n batch_size=batch_size,\n shuffle=True)\n\n # Random crop patches from images\n patches_x, patches_y = random_sample(images_x, images_y, PATCH_SIZE, NUM_PATCHES_PER_IMAGE)\n\n # Display the training images in the visualizer.\n tf.summary.image('patches_x', tensor=patches_x, max_outputs=4)\n tf.summary.image('patches_y', tensor=patches_y, max_outputs=4)\n\n return patches_x, patches_y, labels\n\n\ndef inputs(filenames, batch_size):\n \"\"\"Construct input without distortion for MNIST using the Reader ops.\n\n Args:\n :param filenames: list - [str1, str2, ...].\n :param batch_size: int. \n\n Returns:\n :returns: tuple - (images, labels).\n images: tensors - [batch_size, height*width*depth].\n lables: tensors - [batch_size].\n \"\"\"\n for f in filenames:\n if not tf.gfile.Exists(f):\n raise ValueError('Failed to find file: ' + f)\n\n with tf.variable_scope('input_evaluation'):\n # Create a queue that produces the filenames to read.\n filename_queue = tf.train.string_input_producer(string_tensor=filenames)\n\n # Even when reading in multiple threads, share the filename\n # queue.\n result = read_and_decode(filename_queue)\n\n # OPTIONAL: Could reshape into a image and apply distortionshere.\n reshaped_image_x = tf.reshape(result.image_x, [HEIGHT, WIDTH, DEPTH])\n reshaped_image_y = tf.reshape(result.image_y, [HEIGHT, WIDTH, DEPTH])\n\n # Convert from [0, 255] -> [-0.5, 0.5] floats.\n image_x = tf.cast(reshaped_image_x, tf.float32) * (1. / 255) - 0.5\n image_y = tf.cast(reshaped_image_y, tf.float32) * (1. / 255) - 0.5\n label = result.label\n\n # Ensure that the random shuffling has good mixing properties.\n min_queue_examples = 500\n print('Filling queue with %d mnist images before starting to train or validation. '\n 'This will take a few minutes.' % min_queue_examples)\n\n # Generate a batch of images and labels by building up a queue of examples.\n images_x, images_y, labels = \\\n _generate_image_and_label_batch(image=(image_x, image_y), label=label,\n min_queue_examples=min_queue_examples,\n batch_size=batch_size,\n shuffle=True)\n\n # Random crop patches from images\n patches_x, patches_y = random_sample(images_x, images_y, PATCH_SIZE, NUM_PATCHES_PER_IMAGE)\n\n return patches_x, patches_y, labels","sub_path":"src/tid2013_input.py","file_name":"tid2013_input.py","file_ext":"py","file_size_in_byte":16473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"220499248","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 7 08:52:18 2017\n\n@author: nabil\n\"\"\"\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom lxml import etree\nfrom bs4 import BeautifulSoup\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nimport os\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nimport pandas as pd\nfrom scipy.sparse import csr_matrix\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nimport string\n\n\n \n \n\"\"\"\n # Importation des données\n \n\"\"\"\n\ndef extraction_words(doc):\n \n soup = BeautifulSoup(doc)\n # Transcription extraction\n words = \"\" \n for p in soup.find_all('word'):\n if(p.get_text() != \" {fw} \" and len(p.get_text())>3): \n words=words+\" \"+p.get_text()\n \n return words \n\n\ndef open_doc(path):\n ### Corpus qui contient tout les documents\n corpus = []\n \n files= os.listdir(path)\n \n for file in files: # files == target['nom']\n chemin = path+file\n doc = open(chemin).read()\n words = extraction_words(doc)\n corpus.append(words)\n \n return corpus \n\n\n\ndef tokenize(text):\n text = ''.join([ch for ch in text if ch not in string.punctuation])\n tokens = nltk.word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n lemmes = [lemmatizer.lemmatize(token) for token in tokens]\n return [l for l in lemmes if len(l) > 2]\n\n# Extracting features from text files\ndef run(corpus):\n #trans_tf_dfs = []\n count_vect = CountVectorizer(tokenizer=tokenize, stop_words='english')\n X = count_vect.fit_transform(corpus)\n \n # TF-IDF\n tfidf_transformer = TfidfTransformer()\n X_tfidf = tfidf_transformer.fit_transform(X)\n #trans_tf_dfs \n return X_tfidf,X\n\n\"\"\"\nProbleme de l'extraction \n\n\"\"\"\ndef export_transTFIDF(data,path_out):\n\n #Export Data\n path_output = path_out\n ## videos\n data.to_csv(path_output + \"transTFIDF.csv\",sep = \";\")\n \n\n# MAIN\n \npath = '/Users/nabil/Desktop/TER_Challenge/DEV_M2SID_LIMSI_ASR/'\ncorpus = open_doc(path)\nX_TfIdf , Vect = run(corpus)\n\n\nfiles= os.listdir(path)\nX = X_TfIdf.todense()\ntrans_TFIDF = pd.DataFrame(X,index=(f for f in files))#, columns = Vect.get_feature_names())#,columns=Vect.todense().get_feature_names())\n \n\npath_out = '/Users/nabil/Desktop/TER_Challenge/'\ntrans_TFIDF.to_csv(path_out + \"transTFIDF.csv\",sep = \";\")\n\n\n\n","sub_path":"Scripts/transcription_TFIDF.py","file_name":"transcription_TFIDF.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"284566008","text":"import datetime\nimport json\nimport logging\nimport os\nimport subprocess\n\nfrom concurrent.futures import TimeoutError\nimport google.cloud.logging\nfrom google.cloud import pubsub_v1\n\n\nclass HugoRunner:\n def __init__(self, project_id, subscription_id, notification_topic, bucket_in, bucket_out, publish_script, timeout=None):\n self.project_id = project_id\n self.subscription_id = subscription_id\n self.notification_topic = notification_topic\n self.bucket_in = bucket_in\n self.bucket_out = bucket_out\n self.publish_script = publish_script\n\n self.timeout = timeout\n\n self.publisher = pubsub_v1.PublisherClient()\n self.notification_topic_path = self.publisher.topic_path(\n project_id, notification_topic)\n\n def notify(self, payload, update):\n logging.info(f\"Notify :{payload}, {update}.\")\n\n _payload = {**payload, **update}\n\n data = json.dumps(_payload).encode(\"utf-8\")\n\n notification = self.publisher.publish(\n self.notification_topic_path, data)\n logging.info(notification.result())\n\n def run_build(self, payload):\n buildId = payload['buildId']\n environment = payload['environment']\n website = payload['website']\n theme = payload['theme']\n\n output = subprocess.run(f'{self.publish_script} {environment} {website} {self.bucket_in} {self.bucket_out} {buildId} {theme}',\n capture_output=True,\n shell=True,\n text=True,\n executable='/bin/bash',\n env={\"PATH\": \"/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games\"}\n )\n return {\n 'returncode': output.returncode,\n 'stderr': output.stderr,\n 'stdout': output.stdout,\n 'args': output.args\n }\n\n def callback(self, message):\n try:\n logging.info(f\"Received {message.data}.\")\n\n message.ack()\n payload = json.loads(message.data)\n\n self.notify(payload, {'status': 'running'})\n result = self.run_build(payload)\n\n timestamp = int(datetime.datetime.now().timestamp() * 1000)\n\n self.notify(payload, {\n 'output': result,\n 'status': 'succeded' if result['returncode'] == 0 else 'failed',\n 'endDate': timestamp\n })\n except Exception as ex:\n logging.error(ex)\n\n def receive_publish_request(self):\n subscriber = pubsub_v1.SubscriberClient()\n\n subscription_path = subscriber.subscription_path(\n self.project_id, self.subscription_id)\n\n streaming_pull_future = subscriber.subscribe(\n subscription_path, callback=self.callback)\n\n logging.info(f\"Listening for messages on {subscription_path}..\\n\")\n # Wrap subscriber in a 'with' block to automatically call close() when done.\n with subscriber:\n try:\n # When `timeout` is not set, result() will block indefinitely,\n # unless an exception is encountered first.\n streaming_pull_future.result(timeout=self.timeout)\n except TimeoutError:\n streaming_pull_future.cancel()\n\n\nif __name__ == \"__main__\":\n\n client = google.cloud.logging.Client()\n client.get_default_handler()\n client.setup_logging()\n\n project_id = os.environ.get('PUBSUB_PROJECT')\n subscription_id = os.environ.get('PUBSUB_PUBLISH_SUBSCRIPTION')\n publish_topic_name = os.environ.get('PUBSUB_PUBLISH_TOPIC')\n notify_topic_name = os.environ.get('PUBSUB_NOTIFY_TOPIC')\n bucket_in = os.environ.get('BUCKET_INPUT')\n bucket_out = os.environ.get('BUCKET_OUTPUT')\n publish_script = os.environ.get('PUBLISH_SCRIPT')\n\n runner = HugoRunner(project_id, subscription_id,\n notify_topic_name, bucket_in, bucket_out, publish_script)\n\n logging.info(\n f\"project_id: {project_id} \\nsubscription_id: {subscription_id}\\npublish_topic_name: {publish_topic_name}\\nBucket in : {bucket_in}\\nBucket out : {bucket_out}\")\n\n runner.receive_publish_request()\n receive_publish_request(\n project_id, subscription_id, timeout=None)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"434731761","text":"#!/usr/bin/python3\nfrom modules.gsheet.GSheet import GSheet\nimport json\n\n\nconf_path = \"./conf/gsheet/gsheet.json\"\n\ndef load_conf():\n\tconf = None\n\twith open(conf_path) as f:\n\t\tconf = json.load(f)\n\n\treturn conf\n\nif __name__ == \"__main__\":\n\tgsheet = GSheet()\n\tconf = load_conf()\n\n\tgsheet.gsheet_file = conf['spreadSheet']\n\tgsheet.work_sheet = conf['worksheet']\n\tgsheet.credential_path = conf['credentialPath']\n\n\tgsheet.create_connection()\n\tdata = gsheet.get_all_data()\n\tprint(data)\n\n\t# gsheet.append_row([\"java\", 100])\n\t# data = gsheet.get_all_data()\n\t# print(data)\n\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"288677506","text":"import copy\nimport gdspy\nimport numpy as np\nfrom operator import add, sub\nfrom recordclass import recordclass\n\nimport gds_tools as gtools\n\nclass GDStructure:\n\n def __init__(self, structure, endpoints, endpoint_dims, endpoint_directions = None, method = None, args = {}):\n \"\"\"Define class to store structures in\n\n Args:\n structure (gdspy.Path()): gdspy description of object (i.e. ouput of gdspy.PolyPath()).\n endpoints (dict): positions of the endpoints to which you connect other structures.\n endpoint_dims (dict): dimensions of the endpoints (width/height/etc.), to be used for connecting e.g. transmission lines.\n endpoint_directions ([type], optional): [description]. Defaults to None.\n method ([type], optional): [description]. Defaults to None.\n args (dict, optional): [description]. Defaults to {}.\n \"\"\"\n\n self.type = 'GDStructure'\n self.structure = structure\n self.endpoints = endpoints\n self.endpoint_dims = endpoint_dims\n self.endpoint_directions = endpoint_directions\n self.compound = []\n self.prev = {}\n self.next = {}\n self.method = method\n\n self.__args_tuple__ = recordclass('args', args.keys())\n self.args = self.__args_tuple__(**args)\n\n self.gen = self.generate\n\n def generate(self):\n if self.method != None:\n return self.method(**self.args.__dict__)\n else:\n raise TypeError('This GDStructure does not support the .generate() method (yet)')\n\n def copy(self):\n \"\"\"Makes a new copy of the structure,\n i.e. allocates new memory and copies the data contents to it.\n\n Returns:\n gds_tools.GDStructure: pointer of copy of original\n \"\"\"\n\n # Create deepcopy of self and return the copy\n # Do not copy.deepcopy(self) directly, as this will also copy the connections and screw things up\n # Instead, just fill a new instance of the class with copies of relevant internal structure\n new_obj = gtools.classes.GDStructure(copy.deepcopy(self.structure), copy.deepcopy(self.endpoints), copy.deepcopy(self.endpoint_dims), copy.deepcopy(self.endpoint_directions))\n\n compound = []\n for i, c in enumerate(self.compound):\n c_copy = c.copy()\n compound.append(c_copy)\n new_obj.next[i] = c_copy\n\n new_obj.compound = compound\n\n return new_obj\n\n #==================\n # Rotate structure \\\\\n #=========================================================================\n # When rotating, all endpoints need to move wih the rotation, ||\n # for this reason we need our own rotation function. ||\n # ||\n # Arguments: rad : amount of radians to rotate ||\n # signal_from : tells linked structure who sent command ||\n #=========================================================================\n def rotate(self, rad, signal_from = None):\n\n if not isinstance(signal_from, list):\n signal_from = [signal_from]\n\n # Rotate the structure with standard gdspy .rotation() function\n if self not in signal_from:\n signal_from.append(self)\n self.structure.rotate(rad)\n\n # Rotate the endpoints\n for i in self.endpoints:\n self.endpoints[i] = tuple(gtools.funcs.VecRot(rad, self.endpoints[i]))\n if self.endpoint_directions:\n self.endpoint_directions[i] += rad\n\n # Rotate all connected structures\n for i in self.prev:\n if self.prev[i] not in signal_from and self.prev:\n signal_from.append(self.prev[i])\n self.prev[i].rotate(rad, signal_from = signal_from)\n\n for i in self.next:\n if self.next[i] not in signal_from and self.next:\n signal_from.append(self.next[i])\n self.next[i].rotate(rad, signal_from = signal_from)\n\n return self\n\n #=====================\n # Get structure layer \\\\\n #=========================================================================\n # Gdspy has some inconsistencies in how it stores layers, this getter ||\n # function should make life easier to obtain the layer of the object ||\n # stored in self.structure ||\n #=========================================================================\n def getlayer(self):\n return self.structure.layers[0] if hasattr(self.structure, 'layers') else (self.structure.layer if hasattr(self.structure, 'layer') else 0)\n\n #=====================\n # Translate structure \\\\\n #=========================================================================\n # Arguments: delta : vector (x, y) how much you want to move ||\n # signal_from : tells linked structure who sent command ||\n #=========================================================================\n def translate(self, delta, signal_from = None):\n\n if not isinstance(signal_from, list):\n signal_from = [signal_from]\n\n # Translate structure with standard gdspy .translate() function\n if self not in signal_from:\n signal_from.append(self)\n self.structure.translate(delta[0], delta[1])\n\n # Translate all the endpoints\n for i in self.endpoints:\n self.endpoints[i] = tuple(map(add, self.endpoints[i], delta))\n\n # Translate all connected structures\n for i in self.prev:\n if self.prev[i] not in signal_from and self.prev:\n signal_from.append(self.prev[i])\n self.prev[i].translate(delta, signal_from = signal_from)\n\n for i in self.next:\n if self.next[i] not in signal_from and self.next:\n signal_from.append(self.next[i])\n self.next[i].translate(delta, signal_from = signal_from)\n\n return self\n\n #=====================\n # Mirror structure \\\\\n #=========================================================================\n # Arguments: p1, p2 : p1 and p2 are (x, y) coords forming ||\n # the mirror line ||\n #=========================================================================\n def mirror(self, p1, p2, signal_from = None):\n\n if not isinstance(signal_from, list):\n signal_from = [signal_from]\n\n # Mirror the gdspy shape\n if self not in signal_from:\n signal_from.append(self)\n self.structure.mirror(p1, p2 = p2)\n\n # Process the endpoints\n for k, v in self.endpoints.items():\n\n p1 = list(p1)\n p2 = list(p2)\n\n if p1[0] == p2[0]:\n p1[0] += 1E-20\n\n if p1[1] == p2[1]:\n p1[1] += 1E-20\n\n # y = ax + c : mirror line\n a = (p2[1] - p1[1]) / (p2[0] - p1[0])\n c = p1[1] - a * p1[0]\n d = (v[0] + (v[1] - c)*a) / (1 + a**2)\n\n v2x = 2*d - v[0]\n v2y = 2*d*a - v[1] + 2*c\n\n self.endpoints[k] = (v2x, v2y)\n\n # Ripple through all connected shapes\n for i in self.prev:\n if self.prev[i] not in signal_from and self.prev:\n signal_from.append(self.prev[i])\n self.prev[i].mirror(p1, p2, signal_from = signal_from)\n\n for i in self.next:\n if self.next[i] not in signal_from and self.next:\n signal_from.append(self.next[i])\n self.next[i].mirror(p1, p2, signal_from = signal_from)\n\n return self\n\n #=================\n # Heal connection \\\\\n #=========================================================================\n # When connection endpoints, there is always a little space that is not ||\n # overlapped. This function will fill this overlap. ||\n # ||\n # Arguments: endpoint : (x, y) center of healer ||\n # (optional) npoints : number of points to use for boundary ||\n #=========================================================================\n def heal(self, endpoint, npoints = 100, r = 'auto', layer = None, datatype = None):\n\n if type(r) == str and r == 'auto':\n r = self.endpoint_dims[endpoint] / 2\n\n healer = gtools.heal.circle(r, self.endpoints[endpoint], npoints = npoints, layer = layer if layer != None else self.getlayer(), datatype = datatype if datatype != None else self.structure.datatypes[0])\n\n self.prev['HEAL_' + endpoint] = healer\n self.compound += [healer]\n\n return self\n\n #===================\n # Connect structure \\\\\n #=========================================================================\n # Arguments: ep_self : reference to A, B, C, etc. ||\n # name of endpoint of this structure ||\n # to : GDStructure class input to which to connect ||\n # ep_to : endpoint to which to connect to ||\n # offset : (x, y) offset from target endpoints ||\n # obj_link: use Python object reference for linked list ||\n # entry rather than endpoint key ||\n #=========================================================================\n def connect(self, ep_self, to, ep_to, offset = (0, 0), obj_link = False, rotate = True):\n\n # Rotate to correct orientation\n if self.endpoint_directions != None and to.endpoint_directions != None and self.endpoint_directions and to.endpoint_directions and rotate:\n self.rotate((to.endpoint_directions[ep_to] - self.endpoint_directions[ep_self] - np.pi) % (2 * np.pi))\n\n # Move to connect endpoints\n delta = tuple(map(sub, to.endpoints[ep_to], self.endpoints[ep_self]))\n delta = tuple(map(add, delta, offset))\n self.mov(delta)\n\n # Update linked list\n if not obj_link:\n to.next[ep_to] = self\n self.prev[ep_self] = to\n else:\n to.next[self] = self\n self.prev[to] = to\n\n return self\n\n #======================\n # Disconnect structure \\\\\n #=========================================================================\n # Only removes the references in the linked lists ||\n #=========================================================================\n def disconnect(self):\n\n for e in self.endpoints:\n if e in self.next:\n for ne in self.next[e].endpoints:\n if ne in self.next[e].prev and self.next[e].prev[ne] == self:\n del self.next[e].prev[ne]\n del self.next[e]\n if e in self.prev:\n for pe in self.prev[e].endpoints:\n if pe in self.prev[e].next and self.prev[e].next[pe] == self:\n del self.prev[e].next[pe]\n del self.prev[e]\n\n return self\n\n # Aliases\n rot = rotate\n mov = translate\n con = connect\n dis = disconnect\n","sub_path":"gds_tools/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":11400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"288533967","text":"# import the necessary packages\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nimport cv2\nimport numpy as np\n\n# initialize the camera and grab a reference to the raw camera capture\ncamera = PiCamera()\ncamera.resolution = (160*1, 120*1)\ncamera.framerate = 30\ncamera.exposure_mode = 'off'\nrawCapture = PiRGBArray(camera, size=(160*1, 120*1))\n\n# allow the camera to warmup\ntime.sleep(0.1)\nkey = None\nbg = None\n\nframeCount = 0\nthrs = 0.09\net = 0\n\nmax_area = 0\n \ndef edges(frame, thresh):\n\tframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n\tsobelx = cv2.Sobel(frame, cv2.CV_32F, 1, 0, ksize=1)\n\tsobely = cv2.Sobel(frame, cv2.CV_32F, 0, 1, ksize=1)\n\tmag = np.power(np.power(sobelx,2) + np.power(sobely,2),1/2)\n\n\t# processing on edge image\n\tframe = cv2.blur(mag,(3,3))\n\t#frame = cv2.medianBlur(frame,5)\n\n\t# thresholding\n\tmm = (np.amax(frame) * thresh)\n\tframe = (mm < frame)\n\tframe = np.float32(frame)\n\treturn frame\n \ndef draw_box(img, y, x, h=5, w=5, color=1):\n\tout = np.copy(img)\n\tfor r in range(-1*h,h):\n\t\tyi=y+r\n\t\tif yi >= 0 and yi < img.shape[0]:\n\t\t\tfor c in range(-1*w,w):\n\t\t\t\txi = x+c\n\t\t\t\tif xi >= 0 and xi < img.shape[1]:\n\t\t\t\t\tout[yi,xi] = color\n\treturn out\n\n\n# capture frames from the camera\nfor frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n\t# grab the raw NumPy array representing the image, then initialize the timestamp\n\t# and occupied/unoccupied text\n\traw_image = frame.array\n\t\n\t# LPF\n\timage = cv2.blur(raw_image, (3,3))\n\t\n\timage = edges(image, thrs)\n\timage = (image - np.amin(image))/(np.amax(image)-np.amin(image)) \n\timage[image < 0.1] = 0\n\n\t\n\tif key == ord(\"b\"):\n\t\tbg = image \n\t\tnbg = 1\n\tif key == ord(\"n\"):\n\t\tbg = image/(nbg+1) + bg*nbg/(nbg+1) \n\t\tnbg += 1\n\tif key == ord(\"q\"):\n\t\tbreak\n \n\n\tif type(bg) != type(None):\n\t\timage = image - bg\n\timage[image < et] = 0\n\timage = image * 255\n\timage = image.astype(np.uint8)\n\t\n\tM = cv2.moments(image)\n\tif M['m00'] == 0:\n\t\tcx = 0\n\t\tcy = 0\n\telse:\n\t\tcx = int(M['m10']/M['m00'])\n\t\tcy = int(M['m01']/M['m00'])\n\timage = draw_box(image,cy,cx,color=125)\n\t\t\n\t\n\timage = cv2.resize(image, (160*4,120*4), fx=0, fy=0, interpolation = cv2.INTER_NEAREST)\n\tcv2.imshow(\"Frame\", image)\n\tkey = cv2.waitKey(1) & 0xFF\n\trawCapture.truncate(0)\n","sub_path":"project/runOnPi/below.py","file_name":"below.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"433436016","text":"import datetime as dt\n\nfrom currency_retrieve.backends import NbuBackend, PrivatBackend\nfrom currency_retrieve.exceptions import InvalidBackendAlias, CurrencyRetrieveException\n\n\nclass CurrencyService:\n backends = {\n NbuBackend.alias: NbuBackend,\n PrivatBackend.alias: PrivatBackend,\n }\n\n def download(self, backend_alias, start_date, end_date, currencies=None):\n backend_cls = self.backends.get(backend_alias, None)\n if backend_cls is None:\n raise InvalidBackendAlias('Invalid backend alias: {}'.format(backend_alias))\n\n backend = backend_cls()\n result = backend.extract(start_date, end_date, currencies)\n\n return result\n\n\nservice = CurrencyService()\n\nend_date = dt.date.today()\nstart_date = end_date - dt.timedelta(days=3)\n\ntry:\n data = service.download('nbu', start_date, end_date)\n privat_data = service.download('privat', start_date, end_date)\nexcept InvalidBackendAlias as e:\n print(e)\nexcept Exception as e:\n print(e)\nelse:\n print(data)\n print(privat_data)\nfinally:\n print('finally')\n","sub_path":"currency_retrieve/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"99109605","text":"# -*- coding: UTF-8 -*-\n#最长重复子数组 动态规划\ndef findLength(A, B):\n n = len(A)\n m = len(B)\n res = 0\n dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if B[i - 1] == A[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n res = max(res, dp[i][j])\n return res\n# print(findLength([1,2,3,2,1], [3,2,1,4,7]))\n\n# 爬楼梯 0级\ndef climbStairs(n):\n dp = {}\n dp[1] = 1\n dp[2] = 2\n for i in range(1+2,n+1): # n>=3执行\n dp[i] = dp[i-1] + dp[i-2]\n return dp[n]\nprint(climbStairs(2))\n\n# 最大子序和\ndef maxSubArray(nums):\n for i in range(1,len(nums)):\n nums[i] = max(nums[i-1]+nums[i],nums[i]) #[-2, 1, -2, 4, 3, 5, 6, 1, 5] or nums[i] += max(nums[i - 1], 0)\n return max(nums)\n# print(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))\n\n# 买卖股票的最佳时机 II\ndef maxProfit(prices):\n profit = 0\n for i in range(len(prices)):\n for j in range(i + 1, len(prices)):\n profit = max(profit, prices[j] - prices[i])\n return profit\n# print(maxProfit([7, 1, 5, 3, 6, 4]))\n\n# 买卖股票的最佳时机 II\ndef maxProfitt(prices):\n profit = 0\n for i in range(1, len(prices)):\n tmp = prices[i] - prices[i - 1]\n if tmp > 0:\n profit += tmp\n return profit\n# print(maxProfitt([7, 1, 5, 3, 6, 4]))\n\n# 打家劫舍\ndef rob1(nums):\n if not nums: return 0\n if len(nums) == 1: return nums[0]\n dp = [0] * len(nums)\n dp[0] = nums[0]\n dp[1] = max(nums[0], nums[1])\n for i in range(2, len(nums)):\n dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])\n return dp[len(nums) - 1]\n# print(rob1([2,1,4,5,3,1,1,3]))\n\n# 按摩师\ndef massage(nums):\n if not nums: return 0\n if len(nums) == 1: return nums[0]\n dp = [0] * (len(nums) + 2)\n res = 0\n for i in range(2, len(nums) + 2):\n dp[i] = max(dp[i - 2] + nums[i - 2], dp[i - 1])\n res = max(res, dp[i])\n return res\n# print(massage([2,1,4,5,3,1,1,3]))\n\n# 杨辉三角\ndef generate(numRows):\n dp=[[0]*n for n in range(1,numRows+1)]\n for i in range(numRows):\n dp[i][0]=dp[i][-1]=1\n for i in range(0,numRows):\n for j in range(i+1):\n if(dp[i][j]==0):\n dp[i][j]=dp[i-1][j-1]+dp[i-1][j]\n return dp\n# print(generate(5))\n\n# 最小的k个数\ndef getLeastNumbers(arr, k):\n arr.sort()\n return arr[:k]\n# print(getLeastNumbers([3,2,1], 2))\n\n# 最后一块石头的重量\ndef lastStoneWeight(stones):\n while len(stones)>=2:\n stones.sort()\n stones.append(stones.pop()-stones.pop())\n return stones[0]\n# print(lastStoneWeight([2,7,4,1,8,1]))\n\n# 滑动窗口的最大值\ndef maxSlidingWindow(nums, k):\n res = []\n if not nums:\n return res\n if k <=0:\n return res\n for i in range(0,len(nums)-k+1):\n res.append(max(nums[i:i+k]))\n return res\n# print(maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3))\n\n#词典中最长的单词\ndef longestWord(words):\n words.sort(key = lambda x: (-len(x), x)) #['banana', 'apple', 'apply', 'appl', 'app', 'ap', 'a']\n for word in words:\n for i in range(1, len(word)+1):\n if word[:i] not in words:\n break\n else:\n return word\n# print(longestWord([\"a\", \"banana\", \"app\", \"appl\", \"ap\", \"apply\", \"apple\"]))\n#words.sort() #['a', 'ap', 'app', 'appl', 'apple', 'apply', 'banana']\n#words.sort(key = lambda x: (len(x), x)) #['a', 'ap', 'app', 'appl', 'apple', 'apply', 'banana']\n#words.sort(key = lambda x: (-len(x), x)) #['banana', 'apple', 'apply', 'appl', 'app', 'ap', 'a']\n\n# 有效的字母异位词\ndef isAnagram(s, t):\n if len(s) != len(t):\n return False\n if sorted(s) != sorted(t):\n return False\n return True\n# print(isAnagram(\"anagram\", \"nagaram\"))\n\n# 数组的相对排序\ndef relativeSortArray(arr1, arr2):\n res = []\n for i in arr2:\n while i in arr1:\n res.append(i)\n arr1.remove(i)\n return res + sorted(arr1)\n# print(relativeSortArray([2,3,1,3,2,4,6,7,9,2,19], [2,1,4,3,9,6]))\n\n# 按奇偶排序数组 II 偶奇偶奇 设两个列表,最后合并一个列表\ndef sortArrayByParityII(A):\n even = []\n odd = []\n res = []\n for x in A:\n if x % 2 == 0:\n even.append(x)\n else:\n odd.append(x)\n for i in range(len(even)):\n res.append(even[i])\n res.append(odd[i])\n return res\n# print(sortArrayByParityII([4,2,5,7]))\n\n# 非递增顺序的最小子序列 10+9>3+4+8\ndef minSubsequence(nums):\n nums.sort()\n res = []\n while len(nums) > 0:\n res.append(nums.pop())\n if sum(res) > sum(nums):\n return res\n# print(minSubsequence([4,3,10,9,8]))\n\n# 合并区间\ndef merge(intervals):\n intervals.sort()\n res = []\n for i in intervals:\n if not res:\n res.append(i)\n elif res[-1][-1] < i[0]: # 3<2 res最后最大值小于新最小值\n res.append(i)\n else:\n res[-1][-1] = max(res[-1][-1], i[-1]) # 3<2 3=3or6\n return res\n# print(merge([[1,3],[2,6],[8,10],[15,18]]))\n\n# 宝石与石头\ndef numJewelsInStones(J, S):\n return sum(s in J for s in S)\n# print(numJewelsInStones(\"aA\", \"aAAbbbb\"))\n\n# 快速排序 O(nlogn)# 从数据集中选取一个基准,然后让数据集的每个元素和基准值比较,\n# 小于基准值的元素放入左边分区大于基准值的元素放入右边分区,\n# 最后以左右两边分区为新的数据集进行递归分区,直到只剩一个元素。\ndef quick_sort(arr):\n if len(arr) < 2:\n return arr\n mid = arr[len(arr) // 2] # 选取基准,随便选哪个都可以,选中间的便于理解\n left, right = [], [] # 定义基准值左右两个数列\n arr.remove(mid) # 从原始数组中移除基准值\n for i in arr:\n if i >= mid: # 大于基准值放右边\n right.append(i)\n else:\n left.append(i) # 小于基准值放左边\n return quick_sort(left) + [mid] + quick_sort(right) # 使用迭代进行比较 a.concat(b)\n# 对大规模数据集进行快排,当分区的规模达到一定小时改用插入排序,插入排序在小数据规模时排序性能较好。\n# print(quick_sort([64, 34, 25, 12, 22, 11, 90]))\n\n# 冒泡排序 时间复杂度: O(N^(1-2)); 空间复杂度: O(1)\n# # 重复比较两个元素,顺序错误就交换\ndef bubbleSort(arr):\n for i in range(len(arr)):\n for j in range(0, len(arr)-1-i):\n if arr[j] > arr[j+1]: # 前>后\n arr[j], arr[j+1] = arr[j+1], arr[j] # 换位\n return arr\n# print(bubbleSort([64, 34, 25, 12, 22, 11, 90]))\n\n# 插入排序 时间复杂度: O(N^(1-2)); 空间复杂度: O(1)\n# 构建有序序列,对于未排序数据,在已排序序列中key从后向前扫描,找到相应位置并插入。\ndef insertionSort(arr): \n for i in range(1, len(arr)): \n key = arr[i] \n j = i-1\n while j >=0 and key < arr[j] : \n arr[j+1] = arr[j] \n j -= 1\n arr[j+1] = key \n return arr\n# print(insertionSort([64, 34, 25, 12, 22, 11, 90]))\n\n#两数之和\ndef twoSum1(nums, target):\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i,j]\n return []\n# print(twoSum1([2, 7, 11, 15], 9)) #[0,1]\n\n#两数之和 II - 输入有序数组 --双指针\ndef twoSum2(numbers, target):\n if(not numbers): return []\n left=0\n right=numbers.index(numbers[-1])\n while(lefttarget):\n right=right-1\n else:\n left=left+1\n return None\n# print(twoSum2([2, 7, 11, 15], 9))\n\n# 两个数组的交集,不重复\ndef intersection1(nums1, nums2):\n a = set(nums1)&set(nums2)\n return list(a)\n# print(intersection1([4,9,9,5], [9,4,9,8,4]))\n\n# 两个数组的交集,重复,双指针\ndef intersection2(nums1, nums2):\n nums1.sort()\n nums2.sort()\n i,j = 0,0\n res = []\n if len(nums1) == 0 or len(nums2) == 0:\n return []\n while i < len(nums1) and j < len(nums2):\n if nums1[i] == nums2[j]:\n res.append(nums1[i])\n i += 1\n j += 1\n elif nums1[i] < nums2[j]:\n i += 1\n else:\n j += 1\n return res\n# print(intersection2([1,2,2,1], [2,2]))\n\n#合并排序的数组\ndef mergee(A, m, B, n):\n A[m:] = B\n A.sort()\n return A\n# print(mergee([1,2,3,0,0,0], 3, [2,5,6], 3))\n\n# 删除排序数组中的重复项\ndef removeDuplicates(nums):\n stack=[]\n for i in nums:\n if i not in stack:\n stack.append(i)\n return stack\n# print(removeDuplicates([1,1,2]))\n\n# 数组中重复的数字\ndef findRepeatNumber(nums):\n count = set() #比list快\n for i in nums:\n if i in count:\n return i\n else:\n count.add(i)\n\n# 移除元素\ndef removeElement(nums, val):\n try:\n while True:\n nums.remove(val)\n except:\n return nums\n# print(removeElement([0,1,2,2,3,0,4,2], 2))\n\n# 加一\ndef plusOne(digits):\n s=\"\"\n for i in digits:\n s += str(i)\n return list(map(int,str(int(s)+1))) #str转list\n# print(plusOne([9,9,9,9]))\n\n# 搜索插入位置\ndef searchInsert(nums, target):\n nums.append(target)\n nums.sort()\n return nums.index(target)\n# print(searchInsert([1,3,5,6], 5))\n\n# 移动零\ndef moveZeroes(nums):\n for i in range(len(nums)):\n if nums[i]==0:\n nums.remove(nums[i])\n nums.append(0)\n return nums\n# print(moveZeroes([0,1,0,3,12]))\n\n# 拼写单词\nimport collections\ndef countCharacters(words, chars):\n ccc = collections.Counter(chars) # Counter({'a': 2, 't': 1, 'c': 1, 'h': 1})\n ans = 0\n for word in words:\n wcc = collections.Counter(word) # Counter({'c': 1, 'a': 1, 't': 1})\n for i in wcc: # Counter({'b': 1, 't': 1})\n if ccc[i] < wcc[i]: # Counter({'h': 1, 'a': 1, 't': 1})\n break # Counter({'e': 2, 't': 1, 'r': 1})\n else:\n ans += len(word)\n return ans\n# print(countCharacters([\"cat\",\"bt\",\"hat\",\"tree\"], \"atach\"))\n\n# 最长回文串\nimport collections\ndef longestPalindrome(s):\n length=0\n mid=0\n dic=collections.Counter(s) #Counter({'c': 4, 'd': 2, 'a': 1, 'b': 1})\n for i in dic.values(): #dict_values([1, 1, 4, 2])\n if i%2==0: #偶数个全加上\n length += i\n else: #奇数加i-1,中间加1\n length += i-1\n mid=1\n return length + mid\n# print(longestPalindrome(\"abccccdd\"))\n\n# 快乐数\ndef isHappy(n):\n only=set()\n def loop(n):\n if n in only: #循环\n return False\n value = sum(int(i)**2 for i in str(n)) #1*1 + 9*9\n if value == 1:\n return True\n only.add(n) #{19} {82, 19} {82, 19, 68}\n return loop(value)\n return loop(n)\n# print(isHappy(19))\n\n# 在排序数组中查找数字 I\ndef search(nums, target):\n res=[]\n for i in nums:\n if i ==target:\n res.append(i)\n return len(res)\n# print(search([5,7,7,8,8,10], 8))\n\n# 统计有序矩阵中的负数\ndef countNegatives(grid):\n return str(grid).count('-')\n# print(countNegatives([[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]))\n\n#分割平衡字符串\ndef balancedStringSplit(s):\n balance = 0\n count = 0\n for i in s:\n if i == 'L':\n balance +=1\n elif i == 'R':\n balance -=1\n if balance == 0:\n count += 1\n return count\n# print(balancedStringSplit(\"RLRRLLRLRL\"))\n\n#判断子序列 (双指针)\ndef isSubsequence(s, t): \n si = ti = 0\n while sis[-1]: #最小胃口>最大饼干\n return 0\n while gi(n/2) 出现次数超过一半的数字\ndef majorityElement(nums):\n nums.sort()\n return nums[len(nums)//2] #中位数\n# print(majorityElement([2,2,1,1,1,2,2]))\n\n#只出现一次的数字 abbccdd\ndef singleNumber(nums):\n sum1=sum(nums) #[4,1,2,1,2]\n sum2=sum(set(nums)) #{1, 2, 4}*2\n result=2*sum2-sum1\n return result\n# print(singleNumber([4,1,2,1,2]))\n\n#汉明距离\ndef hammingDistance(x, y):\n return bin(x ^ y).count('1')\n# print(hammingDistance(1, 4)) #1:0b1 4:0b100 1^4:0b101\n\n#2的幂\ndef isPowerOfTwo(n):\n return n>0 and bin(n).count('1')==1\n# print(isPowerOfTwo(42))\n\n#缺失数字 哈希表\ndef missingNumber(nums):\n for n in range(len(nums) + 1):\n if n not in nums:\n return n\n# print(missingNumber([9,6,4,2,3,5,7,0,1]))\n\n#二进制中1的个数\ndef hammingWeight(n):\n return str(n).count('1')\n# print(hammingWeight(1011))\n\n# 将数字变成 0 的操作次数 偶/2,奇-1\ndef numberOfSteps (num):\n if num==0:\n return 0\n if num%2==0:\n return 1 + numberOfSteps(num//2)\n else:\n return 1 + numberOfSteps(num-1)\n# print(numberOfSteps (14)) #1+1+1+1+1+1+0\n\n#找不同t 由 s 重排,然后随机添加一个字母\ndef findTheDifference(s, t):\n for i in t:\n if t.count(i)-s.count(i)==1:\n return i\n# print(findTheDifference(\"abcd\", \"abcde\"))\n\n# x 的平方根,取整\nimport math\ndef mySqrt(x):\n return int(math.sqrt(x))\n# print(mySqrt(1000))\n","sub_path":"test/笔试/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":14783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"86358723","text":"import pandas as pd\nimport numpy as np\nimport argparse\nimport os\nimport sys\nsys.path.append('../flare')\nfrom src import datagen\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport yaml\nfrom torch.utils.data import Dataset\nimport torch.optim as optim\nimport torchvision.transforms as T\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom torch.utils.data import DataLoader\n\nfrom skorch import NeuralNetClassifier\nfrom skorch.utils import noop\nfrom skorch.callbacks import EpochScoring, BatchScoring\nfrom sklearn.metrics import f1_score, roc_auc_score,make_scorer\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\nfrom skorch import helper\n\nfrom scipy.stats import expon\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport scoring\nimport pickle\nimport ipdb\nimport skorch\nfrom sklearn.model_selection import StratifiedKFold\nimport models\n\nclass Dataset_Clf(Dataset):\n def __init__(self, data):\n X = []\n Y = []\n for k,v in data.items(): \n feat_patient = [visit.data['test_scores'] + visit.data['covariates'] for _,visit in data[k].visits.items()]\n # feat_patient = [visit.data['img_features'] for _,visit in data[k].visits.items()]\n label_patient = [visit.data['labels'] for _, visit in data[k].visits.items()]\n feat_patient = np.vstack(feat_patient)\n label_patient = np.vstack(label_patient)\n\n Y.append(label_patient) \n X.append(feat_patient)\n\n self.Y = np.squeeze(np.vstack(Y))\n self.X = np.vstack(X)\n\n def __len__(self):\n \"\"\" \n Returns the number of unique patient ids in the directory\n \"\"\"\n return self.X.shape[0]\n\n def __getitem__(self, index):\n return torch.FloatTensor(self.X[index]), self.Y[index]\n\n def return_all(self):\n return self.X.astype(np.float32),torch.LongTensor(self.Y)\n\ndef main(debug, n_iter,config_file,exp_id):\n with open('models/models.yaml') as f:\n model_dict = yaml.load(f, Loader=yaml.FullLoader)\n\n with open(config_file) as f:\n config = yaml.load(f,Loader=yaml.FullLoader)\n\n main_exp_dir = os.path.join(config['output_dir'], exp_id)\n if(not os.path.exists(main_exp_dir)):\n os.mkdir(main_exp_dir)\n\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n \n patient_path = 'patients_clf.pckl' \n\n if os.path.exists(patient_path):\n with open(patient_path, 'rb') as f:\n src_data = pickle.load(f)\n else:\n print(config['data'])\n src_data = datagen.get_data(**config['data'])\n with open(patient_path, 'wb') as f:\n pickle.dump(src_data, f)\n \n data_train = {key : src_data[key] \\\n for key in src_data['train_ids'] if key in src_data}\n data_val = {key : src_data[key] \\\n for key in src_data['test_ids'] if key in src_data}\n\n dataset_train = Dataset_Clf(data_train)\n dataset_val = Dataset_Clf(data_val)\n\n dataset_val = helper.predefined_split(dataset_val)\n\n f1_scorer = make_scorer(scoring.f1_score, average = 'macro')\n f1 = EpochScoring(scoring=f1_scorer,lower_is_better=False)\n \n model_name = config['model'].pop('name')\n model = eval(model_dict[model_name])\n\n if(debug):\n clf_net = NeuralNetClassifier(\n model, \n max_epochs=1,\n batch_size=64,\n device = device,\n callbacks = [f1],\n train_split = dataset_val,\n optimizer=torch.optim.Adam,\n criterion=nn.CrossEntropyLoss,\n **config['model'],\n **config['skorch'])\n # **{'iterator_train__drop_last': True,\n # 'iterator_valid__drop_last': True,\n # 'module__num_output': 1000,\n # 'module__num_input': 656}\n \n\n params = {\n 'optimizer__lr': expon(scale = .001),\n 'optimizer__weight_decay': expon(scale = .001)\n }\n\n else:\n clf_net = NeuralNetClassifier(\n model, \n device = device,\n callbacks = [f1],\n batch_size = 64,\n max_epochs = 40,\n optimizer=torch.optim.Adam,\n criterion=nn.CrossEntropyLoss,\n **config['model'],\n **config['skorch'])\n \n params = {\n # 'max_epochs': [30,35,40,50,70],\n # 'batch_size': [32,64],\n 'optimizer__lr': expon(scale = .001),\n 'optimizer__weight_decay': expon(scale=.001)\n }\n\n# X,Y = dataset.return_all()\n\n# search = RandomizedSearchCV(clf_net, params, refit=True, cv=3, scoring=f1_scorer, verbose=1, n_iter=n_iter)\n\n# print('Search!')\n\n clf_net.fit(dataset_train, y=None)\n # print(search.best_score_, search.best_params_)\n # create_loss_graphs(search,main_exp_dir,debug)\n\ndef create_loss_graphs(search, out_dir, debug):\n total_loss_train = search.best_estimator_.history[:,'train_loss'] \n\n total_loss_valid = search.best_estimator_.history[:,'valid_loss'] \n epochs = [i for i in range(len(search.best_estimator_.history))]\n\n if(not debug):\n txtstr = '\\n'.join((\n r'$\\mathrm{lr}=%.8f$' % (search.best_params_['optimizer__lr'], ),\n r'$\\mathrm{wd}=%.8f$' % (search.best_params_['optimizer__weight_decay'], ),\n r'$\\mathrm{epochs}=%d$' % (search.best_params_['max_epochs'], ),\n r'$\\mathrm{bsize}=%d$' % (search.best_params_['batch_size'], )))\n\n else:\n txtstr = '\\n'.join((\n r'$\\mathrm{lr}=%.8f$' % (search.best_params_['optimizer__lr'], ),\n r'$\\mathrm{wd}=%.8f$' % (search.best_params_['optimizer__weight_decay'], )))\n\n # Set up bounding box parameters\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n\n f = plt.figure()\n axes = f.add_subplot(1,1,1)\n\n plt.plot(epochs, total_loss_train, c='g', label = 'Train Loss')\n plt.plot(epochs, total_loss_valid, c='r', label = 'Validation Loss')\n plt.title('Train and Test Loss Curves')\n plt.xlabel('epochs')\n plt.ylabel('loss')\n plt.legend()\n\n # Place text box with best parameters\n plt.text(0.85,0.72,txtstr, ha = 'center', va = 'center', transform=axes.transAxes, bbox=props)\n plt.savefig(out_dir + '/train_v_train.png', dpi = 300)\n plt.close()\n\nif __name__=='__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--debug', type=int, default=0)\n parser.add_argument('--n_iter', type=int, default=30)\n parser.add_argument('--config_file', type=str, default='../configs/simplified.yaml')\n parser.add_argument('--exp_id', type=str, default='debug')\n args = parser.parse_args()\n main(args.debug,args.n_iter,args.config_file,args.exp_id)\n","sub_path":"run_tadpole.py","file_name":"run_tadpole.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"109939572","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.contrib.auth.views import login, logout\n\n\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n url(r'^', include('apps.accounts.urls', namespace=\"accounts\")),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^requests/', include('apps.rlogger.urls', namespace=\"requests\")),\n url(r'^accounts/login/$', login,\n {'template_name': 'accounts/login_base.html',\n 'extra_context': {'next': '/accounts/edit/'}}),\n url(r'^accounts/logout/$', logout, {'next_page': '/'}),\n)\n\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nif settings.DEBUG:\n urlpatterns += \\\n static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"_42cc_test_dustin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"520559643","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\n\nclass ExpertModule(nn.Module):\n\n def __init__(self, field_center, out_dim):\n super(ExpertModule, self).__init__()\n assert field_center.dim() == 1, 'invalid shape : {:}'.format(field_center.shape)\n self.register_buffer('field_center', field_center.clone())\n self.fc = nn.Linear(field_center.numel(), out_dim)\n\n def forward(self, semantic_vec):\n input_offsets = semantic_vec - self.field_center\n response = F.relu(self.fc(input_offsets))\n return response\n\n\nclass CooperationModule(nn.Module):\n\n def __init__(self, field_centers, out_dim):\n super(CooperationModule, self).__init__()\n self.individuals = nn.ModuleList()\n assert field_centers.dim() == 2, 'invalid shape : {:}'.format(field_centers.shape)\n self.out_dim = out_dim\n for i in range(field_centers.shape[0]):\n layer = ExpertModule(field_centers[i], out_dim)\n self.individuals.append( layer )\n\n def forward(self, semantic_vec):\n responses = [indiv(semantic_vec) for indiv in self.individuals]\n feature_anchor = sum(responses)\n return feature_anchor\n\n\nclass RelationModule(nn.Module):\n \"\"\"docstring for RelationNetwork\"\"\"\n def __init__(self, in_C, hidden_C):\n super(RelationModule, self).__init__()\n self.fc1 = nn.Linear(in_C, hidden_C)\n self.fc2 = nn.Linear(hidden_C, 1)\n\n def forward(self, image_feats, attributes):\n batch, feat_dim = image_feats.shape\n cls_num, at_dim = attributes.shape\n image_feats_ext = image_feats.view(batch, 1, -1).expand(batch, cls_num, feat_dim)\n batch_attFF_ext = attributes.view(1, cls_num, -1).expand(batch, cls_num, feat_dim)\n relation_pairs = torch.cat((image_feats_ext, batch_attFF_ext), dim=2)\n\n x = F.relu(self.fc1(relation_pairs))\n outputs = torch.sigmoid(self.fc2(x))\n return outputs.view(batch, cls_num)\n","sub_path":"lib/networks/Baselines.py","file_name":"Baselines.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"293150934","text":"cmds = {\n '출력': 'print',\n '만약': 'if',\n '같다': '==',\n '같거나오른쪽이크다': \"<=\",\n '같거나왼쪽이크다': '>=',\n '오른쪽이크다': '<',\n '왼쪽이크다': '>',\n '이다': 'is',\n '이게아니다': 'else',\n '받아라': 'input',\n '더해라': '+',\n '빼라': '-',\n '해봐!': 'try',\n '이오류가나면': 'except',\n '대괄호열어': '[',\n '대괄호닫아': ']',\n '괄호열어': '(',\n '괄호닫아': ')',\n '함수': 'def',\n '가져와': 'import',\n '으로': 'as',\n '로부터': 'from',\n '함께': 'with',\n '하는동안': 'while',\n '참': 'True',\n '거짓': 'False',\n '를위해': 'for',\n '안에': 'in',\n '반점': ',',\n '점': '.',\n '렌': 'len',\n '없음': 'None',\n '반': 'class',\n '어기다려': 'await',\n '어동기화': 'async',\n '로시작한다': 'startswith',\n '앍그스': 'args',\n '캬앍그스': 'kwargs',\n '그리고': 'and',\n '단절': 'break',\n '계속': 'continue',\n '없': 'del',\n '이게아니고이거다': 'elif',\n '드디어': 'finally',\n '글로벌': 'global',\n '는': '=',\n '람다': 'lambda',\n '불': 'bool',\n '버퍼': 'buffer',\n '바이트어래이': 'bytearray',\n '바이트들': 'bytes',\n '사전': 'dict',\n '소수': 'float',\n '정수': 'int',\n '목록': 'list',\n '길다': 'long',\n '객체': 'object',\n '범위': 'range',\n '세트': 'set',\n '일부분': 'slice',\n '문자열': 'str',\n '튜플': 'tuple',\n '유니코드': 'unicode',\n '엑스범위': 'xrange',\n '__가져와__': '__import__',\n '모든': 'all',\n '아무': 'any',\n '적용하다': 'apply',\n '아스키': 'ascii',\n '주석': '#',\n '자기자신': 'self',\n '중괄호열어': '{',\n '중괄호닫아': '}',\n '무시': 'pass',\n '소리질러': 'raise',\n '넘겨': 'return',\n '또는': 'or',\n '아니다': 'not',\n '양보': 'yield'\n}\n","sub_path":"nkpy/vars.py","file_name":"vars.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"550749690","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 23 19:55:03 2019\n\n@author: sumche\n\"\"\"\n#Source: https://github.com/meetshah1995/pytorch-semseg/blob/master/ptsemseg/loss/loss.py\nimport torch\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\n#from utils.data_utils import up_scale_tensors\n\ndef cross_entropy2d(input, target, weight=None, size_average=True):\n target = target.long()\n n, c, h, w = input.size()\n if len(target.size())==2 and n==1:\n ht, wt = target.size()\n elif len(target.size())==3 and n>1:\n nt, ht, wt = target.size()\n else:\n raise ValueError('Check size of inputs and targets')\n\n #Handle inconsistent size between input and target\n if h != ht and w != wt: # upsample labels\n input = F.interpolate(input, size=(ht, wt), mode=\"bilinear\", align_corners=True)\n input = input.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)\n target = target.view(-1)\n loss = F.cross_entropy(\n input, target, weight=weight, ignore_index=255)\n return loss\n\n\ndef multi_scale_cross_entropy2d(input, target, weight=None, size_average=True, scale_weight=None):\n if not isinstance(input, tuple):\n return cross_entropy2d(input=input, target=target, weight=weight, size_average=size_average)\n\n # Auxiliary training for PSPNet [1.0, 0.4] and ICNet [1.0, 0.4, 0.16]\n if scale_weight is None: # scale_weight: torch tensor type\n n_inp = len(input)\n scale = 0.4\n scale_weight = torch.pow(scale * torch.ones(n_inp), torch.arange(n_inp).float()).to(\n target.device\n )\n\n loss = 0.0\n for i, inp in enumerate(input):\n loss = loss + scale_weight[i] * cross_entropy2d(\n input=inp, target=target, weight=weight, size_average=size_average\n )\n\n return loss\n\n\ndef bootstrapped_cross_entropy2d(input, target, K, weight=None, size_average=True):\n\n batch_size = input.size()[0]\n\n def _bootstrap_xentropy_single(input, target, K, weight=None, size_average=True):\n\n n, c, h, w = input.size()\n input = input.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)\n target = target.view(-1)\n loss = F.cross_entropy(\n input, target, weight=weight, reduce=False, size_average=False, ignore_index=250\n )\n\n topk_loss, _ = loss.topk(K)\n reduced_topk_loss = topk_loss.sum() / K\n\n return reduced_topk_loss\n\n loss = 0.0\n # Bootstrap from each image not entire batch\n for i in range(batch_size):\n loss += _bootstrap_xentropy_single(\n input=torch.unsqueeze(input[i], 0),\n target=torch.unsqueeze(target[i], 0),\n K=K,\n weight=weight,\n size_average=size_average,\n )\n return loss / float(batch_size)\n\ndef huber_loss(input, target, weight=None, size_average=True):\n if input.size() !=target.size():\n input = input.permute(0,2,3,1).squeeze()\n return F.smooth_l1_loss(input, target)\n\ndef mae_loss(input, target, weight=None, size_average=True):\n if input.size() !=target.size():\n input = input.permute(0,2,3,1).squeeze()\n return F.l1_loss(input, target)\n\ndef mse_loss(input, target, weight=None, size_average=True):\n if input.size() !=target.size():\n input = input.permute(0,2,3,1).squeeze()\n return F.mse_loss(input, target)\n\ndef instance_loss(input, target, weight=None, size_average=True):\n #target[target==0] = 0.1\n if input.size() !=target.size():\n input = input.permute(0,2,3,1).squeeze()\n target = target.squeeze()\n return F.l1_loss(input, target,reduction='mean')#/non_zeros\n\n \n \n\n","sub_path":"utils/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"232370543","text":"x = 2\ny = 7\nz = 10\n\nif x > y:\n print(x, 'is greater than', y)\nif x < y:\n print(x, 'is less than', y)\nif x != y & y != z:\n print(True)\n\n#cannot do this → TypeError: '<' not supported between instances of 'int' and 'str'\n# if x < '2':\n# print(x)\n\nif z > y > x :\n print('True again')","sub_path":"Variables_Loops_Statements/ifStatements.py","file_name":"ifStatements.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"332282683","text":"# -*- coding: utf-8 -*-\nfrom bs4 import BeautifulSoup as BS\nfrom urllib2 import urlopen \n\ndef croller():\n baseUrl = 'http://info.finance.naver.com/marketindex/exchangeList.nhn'\n html = urlopen(baseUrl)\n\n bs = BS(html) \n return bs\n\n# a = raw_input('county name ? : ').decode('utf-8')\n\n# print \"exchange rate is \" + str(dic[a])\n\ndef returnCountry():\n bs = croller()\n country_list = []\n country = bs.select('td.tit')\n\n for i in range(0,len(country)) :\n country_list.append(country[i].text.split()[1])\n\n country_list.insert(0,'KRW')\n\n return country_list\n\ndef returnSale():\n bs = croller()\n sale_list = []\n sale = bs.select('td.sale')\n\n for i in range(0,len(sale)) :\n sale_list.append(float(sale[i].text.replace(',','').strip()))\n sale_list.insert(0,1000)\n return sale_list\n","sub_path":"module/croller.py","file_name":"croller.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"122718464","text":"import os\nfrom pathlib import Path\nfrom queue import Queue\nfrom typing import Dict, List, Union\n\nfrom watchdog.observers import Observer\n\nfrom .selective_file_event_handler import LoggingSelectiveEventHandler\nfrom .watch_values import WatchConfig, WatchPath\n\n\nclass DirWatchDog():\n def __init__(self, wc_or_paths: Union[WatchConfig, List[Dict]], que: Queue) -> None:\n if isinstance(wc_or_paths, WatchConfig):\n self.wc = wc_or_paths\n else:\n self.wc = WatchConfig(wc_or_paths)\n self.save_me = True\n self.observers: List[Observer] = []\n self.que = que\n\n def wait_seconds(self, seconds: int) -> None:\n for obs in self.observers:\n obs.join(seconds)\n\n def watch(self, initialize=False) -> None:\n if initialize:\n for item in self.wc.watch_paths:\n wp: WatchPath = item\n for current_dir, \\\n __dirs_under_current_dir, \\\n files_under_current_dir in os.walk(wp.path, topdown=False):\n\n paths_under_current_dir: List[Path] = [\n Path(current_dir, f) for f in files_under_current_dir]\n for p in paths_under_current_dir:\n if not wp.ignored(str(p), p.is_dir()):\n self.que.put(p)\n\n for wp in self.wc.watch_paths:\n event_handler = LoggingSelectiveEventHandler(\n self.que, wp)\n path_to_observe: str = str(wp.path.resolve())\n assert Path(path_to_observe).exists()\n observer = Observer()\n observer.schedule(event_handler, path_to_observe,\n recursive=wp.recursive)\n observer.start()\n self.observers.append(observer)\n\n def stop_watch(self):\n for obs in self.observers:\n obs.stop()\n\n\n# dir_watch_dog: Optional[DirWatchDog] = None\n# def start_watchdog(watch_pathes: List[Dict], data_queue: Queue) -> DirWatchDog:\n# wc: WatchConfig = WatchConfig(watch_pathes)\n# d_watch_dog = DirWatchDog(wc, data_queue)\n# d_watch_dog.watch()\n# return d_watch_dog\n","sub_path":"wfc/dir_watcher/dir_watcher_dog.py","file_name":"dir_watcher_dog.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"303217220","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.autograd import Variable\n\nimport argparse\nimport tqdm\nimport numpy as np\n\nfrom sklearn.metrics import confusion_matrix\n\nfrom datasets import dataset_char, dataset_word\nfrom models import char_cnn, recurrent_cnn, char_vgg, char_res\nfrom configs import config_char_cnn, config_char_vgg, config_char_res\nfrom configs import config_word_rcnn\nfrom configs import config_tweets, config_uci_news, config_ag_news, config_ag_news_test, config_tweets_test\n\nparser = argparse.ArgumentParser(description='DL Final Project.')\n\nparser.add_argument('--type', type=str, help='type for (char, word)')\nparser.add_argument('--model', type=str, help='type for (rcnn, cnn, vgg, res)')\nparser.add_argument('--dataset', type=str, help='dataset for (tweets, news, ag, ag_test)')\nparser.add_argument('--mode', type=str, help='train or test', default='train')\n\nn_class = None\ntable = None\n\ncuda_on = torch.cuda.is_available()\n\ndef run(args):\n if args.dataset == 'tweets':\n dataset_config = config_tweets.dataset_config\n elif args.dataset == 'news':\n dataset_config = config_uci_news.dataset_config\n elif args.dataset == 'ag':\n dataset_config = config_ag_news.dataset_config\n elif args.dataset == 'ag_test':\n args.dataset = 'ag'\n dataset_config = config_ag_news_test.dataset_config\n elif args.dataset == 'tweets_test':\n args.dataset = 'tweets'\n dataset_config = config_tweets_test.dataset_config\n else:\n raise ValueError('unknown dataset: ' + args.dataset)\n\n global n_class\n n_class = len(dataset_config['table'])\n\n global table\n table = dataset_config['table']\n\n if args.type == 'char':\n # dataset\n dataset = dataset_char.CharDataset\n # configuration\n if args.model == 'cnn':\n config = config_char_cnn\n model = char_cnn.CharCNN\n elif args.model == 'vgg':\n config = config_char_vgg\n model = char_vgg.CharVgg\n elif args.model == 'res':\n config = config_char_res\n model = char_res.CharRes\n\n # adjust output channels size\n config.model_config['fc_layers'][-1][1] = n_class\n\n elif args.type == 'word':\n # dataset\n dataset = dataset_word.WordDataset\n\n if args.model == 'rcnn':\n # configuration\n config = config_word_rcnn \n # model\n model = recurrent_cnn.RCNN\n\n \n # adjust output channels size\n config.model_config['label_dim'] = n_class\n\n else:\n raise ValueError('unknown type type: ' + args.type)\n\n if args.mode == 'train':\n\n # data loader\n print('loading dataset')\n train_set = dataset(config=dataset_config, mode='train')\n train_loader = DataLoader(train_set, batch_size=config.train_config['batch'], shuffle=True, num_workers=1)\n\n eval_set = dataset(config=dataset_config, mode='eval')\n eval_loader = DataLoader(eval_set, batch_size=config.train_config['batch'], shuffle=True, num_workers=1)\n\n # model\n net = model(config=config.model_config)\n if cuda_on:\n net = net.cuda()\n\n # optimizer\n optimizer = optim.SGD(net.parameters(), lr=config.train_config['lr'], momentum=config.train_config['momentum'])\n\n # criterion\n criterion = nn.NLLLoss()\n\n n_epochs = config.train_config['epochs']\n\n loss = np.zeros(n_epochs)\n train_acc = np.zeros(n_epochs)\n val_acc = np.zeros(n_epochs)\n\n # train\n if config.file_config['pretrained']:\n net.load_state_dict(torch.load(config.file_config['model'] + '_' + args.dataset + '.py'))\n\n for epoch in range(config.train_config['epochs']):\n print('epoch: ', epoch)\n\n torch.save(net.state_dict(), config.file_config['model'] + '_' + args.dataset + '.py')\n \n loss[epoch] = (train(train_loader, net, optimizer, criterion))\n\n train_acc[epoch] = (validate(train_loader, net, 'train'))\n val_acc[epoch] =(validate(eval_loader, net, 'val'))\n\n save_arr(loss, config.file_config['loss'] + '_' + args.dataset)\n save_arr(train_acc, config.file_config['acc'] + '_' + 'train' + '_' + args.dataset)\n save_arr(val_acc, config.file_config['acc'] + '_' + 'val' + '_' + args.dataset)\n\n\n elif args.mode == 'test':\n test_set = dataset(config=dataset_config, ratio=1.0)\n test_loader = DataLoader(test_set, batch_size=config.train_config['batch'], shuffle=True, num_workers=1) \n\n net = model(config=config.model_config)\n if cuda_on:\n net = net.cuda()\n\n model_path = config.file_config['model'] + '_' + args.dataset + '.py'\n\n if cuda_on:\n net.load_state_dict(torch.load(model_path))\n else:\n net.load_state_dict(torch.load(model_path))\n # net.load_state_dict(torch.load(model_path, map_location=lambda storage, location: 'cpu'))\n \n validate(test_loader, net)\n\ndef train(loader, net, optimizer, criterion):\n # Training\n print('Training')\n\n running_loss = 0\n\n tbar = tqdm.tqdm(total=len(loader)) # hard code\n\n batch = 0\n\n for batch_idx, sample in enumerate(loader):\n\n tbar.update(1)\n\n feature, target = sample['feature'], sample['target']\n feature, target = Variable(feature).float(), Variable(target).long()\n\n if cuda_on:\n feature = feature.cuda()\n target = target.cuda()\n\n if feature.size() == 1:\n continue\n \n optimizer.zero_grad()\n\n # 2. forward\n output = net(feature)\n \n # 3. loss\n loss = criterion(output, target)\n\n # if batch < 100 and args.type == 'word':\n # batch += 1\n # continue\n\n # 4. backward\n loss.backward()\n\n # 5. optimize\n optimizer.step()\n\n running_loss += loss.data[0]\n\n tbar.close()\n\n print('Training loss: ', running_loss)\n\n return running_loss\n\n\ndef validate(loader, net, mode=None):\n # validate\n print('Validate')\n\n vbar = tqdm.tqdm(total=len(loader))\n\n c_mat = np.zeros((n_class, n_class), dtype=np.integer)\n\n for batch_idx, sample in enumerate(loader):\n \n vbar.update(1)\n\n feature, target = sample['feature'], sample['target']\n feature, target = Variable(feature).float(), Variable(target).long()\n\n if cuda_on:\n feature, target = feature.cuda(), target.cuda()\n\n if feature.size() == 1:\n continue\n\n output = net(feature)\n\n _, index = output.max(1)\n\n c_mat += confusion_matrix(target.cpu().data.numpy(), \n index.cpu().data.numpy(),\n list(range(0, n_class)))\n\n vbar.close()\n\n positive = np.trace(c_mat)\n negative = np.sum(c_mat) - positive\n acc = np.float(positive) / np.float(positive + negative)\n\n print(c_mat)\n\n print(mode, 'acc: ', acc, 'positive: ', positive, 'negative: ', negative)\n\n return acc\n\n\ndef save_arr(data, filename):\n print(filename)\n f = open(filename, 'wb')\n np.save(f, data)\n f.close()\n\n\ndef load_arr(filename):\n print(filename)\n f = open(filename, 'rb')\n data = np.load(f)\n f.close()\n return data\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n\n run(args)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"166006214","text":"import numpy as np\nfrom scipy.fftpack import fft, ifft\nimport matplotlib.pyplot as plt\nimport scipy.signal as signal\n\n\nN1 = 16\nN2 = 128\nfs = 10**9\n##fft equvalent 8192\n\nf1 = fs/16*0.6\n#f1 = 70*10**6\nf2 = 230*10**6\nf3 = 340*10**6\nf4 = 480*10**6\n\n\n\nsig_len = 2**15\nt = np.arange(sig_len)*1.0/fs\n\nsig = 1*np.sin(2*np.pi*f1*t)+1./4*np.sin(2*np.pi*f2*t)+1./16*np.sin(2*np.pi*f3*t)+1./128*np.sin(2*np.pi*f4*t)\n\n\n#sig = signal.hilbert(sig)\n\n##plot input signal\n\nspect = fft(sig[0:16384])\nfreqs = np.linspace(0,fs/2,16384/2)\nplt.figure()\nplt.plot(freqs/10**6, 20*np.log10(np.abs(spect[0:8192])))\nplt.title('signal spectrum')\n\n\n#compute fir values\n\nband = [0, 1.*fs/N1/2]\ntrans_width = 1.*fs/(N1*4*2)\nn_taps = 512\nedges = [band[0], band[1], band[1]+trans_width, 0.5*fs]\ntaps = signal.remez(n_taps, edges, [1, 0], Hz=fs)\n\nw, h = signal.freqz(taps, [1], worN=2000)\n\n##plot filter response\nplt.figure()\nplt.title('Filter response')\nplt.plot(0.5*fs/10**6*w/np.pi, 20*np.log10(np.abs(h)))\n\n\n### generate the taps of the pfb filter\npfb_taps = taps.reshape(n_taps/N1, N1)\n\n#plot taps\n\"\"\"\nplt.figure()\nplt.title('PFB taps response')\nfor i in range(N1):\n w, h = signal.freqz(pfb_taps[:,i], [1], worN=2000)\n plt.plot(0.5*fs/10**6*w/np.pi, 20*np.log10(np.abs(h)), label=('tap'+str(i)))\nplt.legend()\n \n\"\"\"\n\n\nsignal_taps = sig.reshape(sig_len/N1, N1)\ntaps_len = pfb_taps.shape[0]\ndata_pfb = np.zeros([N1, signal_taps.shape[0]-pfb_taps.shape[0]], dtype=complex)\n\nfor i in range(signal_taps.shape[0]-pfb_taps.shape[0]):\n data_pfb[:,i] = np.sum(pfb_taps*signal_taps[i:taps_len+i,:], axis=0)\n \n\ndata_out = ifft(data_pfb, axis=0)\n\n\nspect_bands = 20*np.log10(fft(data_out[:,0:1024], axis=1))\nspect_bands_aux = spect_bands.copy()\nspect_bands[1:,0:512] = np.flip(spect_bands_aux[1:,:512], axis=1)\nspect_bands[1:,512:] = spect_bands_aux[1:,512:][:,::-1]\n\n\n\n\ndf = fs/N1/10.**6\nband = np.zeros([16, 1024])\n\n\ndef plot_band(ind):\n freq = np.linspace(df*(ind-0.5), df*(ind+.5), 1024, endpoint=False)\n if(ind%2==0):\n plt.plot(freq, spect_bands[ind,:])\n else:\n plt.plot(freq, spect_bands[ind,:])\n plt.show()\n\n\nplt.figure()\nfor i in range(9):\n plot_band(i)\n \n##Las bandas estan overlappeadas... k=0 va de 0, fs/(N1*2), \n##k1 = va de 0, fs/N1 y asi va avanzando\n## para hacerlo facil toma bw=fs/N\n## banda1 : (0, bw/2)\n## banda2 : (0, bw)\n## banda3 : (bw:2bw) ...etc..\n\n## a todo esto todas las bandas estan invertidas al paraecer\n## eso es por usar la fft en vez de la ifft\n\n##parece q esto tmb esta mal...\n","sub_path":"pfb2.py","file_name":"pfb2.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"55723573","text":"import nltk,random\nfrom utils.text_filters import get_all_words,remove_noise\nfrom pathlib import Path\nnltk.data.path.append(Path(__file__).parents[1] / 'resources')\nfrom nltk.corpus import twitter_samples, stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk import FreqDist, classify, NaiveBayesClassifier\n\ndef get_tweets_for_model(cleaned_tokens_list):\n for tweet_tokens in cleaned_tokens_list:\n yield dict([token, True] for token in tweet_tokens)\n\nif __name__ == \"__main__\":\n\n #positive_tweets = twitter_samples.strings('positive_tweets.json')\n #negative_tweets = twitter_samples.strings('negative_tweets.json')\n #text = twitter_samples.strings('tweets.20150430-223406.json')\n #tweet_tokens = twitter_samples.tokenized('positive_tweets.json')[0]\n\n stop_words = stopwords.words('english')\n\n positive_tweet_tokens = twitter_samples.tokenized('positive_tweets.json')\n negative_tweet_tokens = twitter_samples.tokenized('negative_tweets.json')\n\n positive_cleaned_tokens_list = []\n negative_cleaned_tokens_list = []\n\n for tokens in positive_tweet_tokens:\n positive_cleaned_tokens_list.append(remove_noise(tokens, stop_words))\n\n for tokens in negative_tweet_tokens:\n negative_cleaned_tokens_list.append(remove_noise(tokens, stop_words))\n\n all_pos_words = get_all_words(positive_cleaned_tokens_list)\n\n freq_dist_pos = FreqDist(all_pos_words)\n print(freq_dist_pos.most_common(10))\n\n positive_tokens_for_model = get_tweets_for_model(positive_cleaned_tokens_list)\n negative_tokens_for_model = get_tweets_for_model(negative_cleaned_tokens_list)\n\n positive_dataset = [(tweet_dict, \"Positive\")\n for tweet_dict in positive_tokens_for_model]\n\n negative_dataset = [(tweet_dict, \"Negative\")\n for tweet_dict in negative_tokens_for_model]\n\n dataset = positive_dataset + negative_dataset\n\n random.shuffle(dataset)\n\n train_data = dataset[:7000]\n test_data = dataset[7000:]\n\n classifier = NaiveBayesClassifier.train(train_data)\n\n print(\"Accuracy is:\", classify.accuracy(classifier, test_data))\n\n print(classifier.show_most_informative_features(10))\n\n#custom text analysis\n custom_tweet = \"I cannot forward my phone number even though i used to be able to. Emailed support and got no response\"\n custom_tokens = remove_noise(word_tokenize(custom_tweet))\n print(custom_tweet, classifier.classify(dict([token, True] for token in custom_tokens)))","sub_path":"sentiment_analysis/supervised_sentiment_analyser_twitter_corpus.py","file_name":"supervised_sentiment_analyser_twitter_corpus.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"28266774","text":"# -*- coding: iso-8859-15 -*-\r\n# ----------------------------------------------------------------------------\r\n# Copyright (c) 2020, L. Siegwald, F. Foata, B. Berger\r\n#\r\n# Distributed under the terms of the Modified BSD License.\r\n#\r\n# The full license is in the file LICENSE, distributed with this software.\r\n# ----------------------------------------------------------------------------\r\n\r\nimport os\r\nimport shutil\r\nimport subprocess\r\nfrom q2_types.feature_data import DNAFASTAFormat, AlignedDNAFASTAFormat\r\n\r\n\r\n# Inspired from https://github.com/qiime2/q2-alignment/blob/master/q2_alignment/_mafft.py\r\ndef run_mothur(cmd, verbose=True):\r\n if verbose:\r\n print(\"Running external command line application. This may print \"\r\n \"messages to stdout and/or stderr.\")\r\n print(\"The command being run is below. This command cannot \"\r\n \"be manually re-run as it will depend on temporary files that \"\r\n \"no longer exist.\")\r\n print(\"\\nCommand:\", end=' ')\r\n print(cmd, end='\\n\\n')\r\n subprocess.run(cmd, check=True, shell=True)\r\n\r\n\r\ndef align_mothur(sequences: DNAFASTAFormat,\r\n reference: AlignedDNAFASTAFormat) -> AlignedDNAFASTAFormat:\r\n reference_fp = str(reference)\r\n sequences_fp = str(sequences)\r\n # Escape hyphens in input names so mothur does not get upset\r\n sequences_escaped_fp = sequences_fp.replace(\"-\", \"\\-\")\r\n result = AlignedDNAFASTAFormat()\r\n\r\n cmd = \"mothur \\\"#set.dir(debug={0});\" \\\r\n \"align.seqs(fasta={1}, reference={2});\\\"\".format(\r\n os.path.dirname(sequences_fp), sequences_escaped_fp, reference_fp)\r\n run_mothur(cmd)\r\n # Path to output file is in alignment_fp defined below:\r\n mother_alignment_fp = os.path.splitext(sequences_fp)[0] + \".align\"\r\n\r\n # copy the mothur output alignment to the AlignedDNAFASTAFormat filepath\r\n shutil.copyfile(mother_alignment_fp, str(result))\r\n\r\n # once the file is in place, just return the AlignedDNAFASTAFormat object\r\n return result\r\n","sub_path":"q2_moulinette/_align_mothur.py","file_name":"_align_mothur.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"71954583","text":"#caesercipher with DEQUE REPLACEMENT\r\n#Only replace alphabet: lower<->lower, upper<->upper\r\n#The nice thing about this method is that str.translate is very very fast,\r\n#and the dictionary you provide it ensures that nothing EXCEPT what you personally define will be touched.\r\n#None of these list.index calls that take forever, everything is hashed and done quickly. \r\n#It's also useful because for k > 26, it still works! caesercipher(\"abc\",27) -> 'bcd'\r\n\r\nfrom collections import deque\r\nfrom copy import copy # just to save time\r\ndef caesercipher(string, k):\r\n upper = deque(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\r\n lower = deque(\"abcdefghijklmnopqrstuvwxyz\")\r\n resultupper = copy(upper)\r\n resultupper.rotate(-k)\r\n resultlower = copy(lower)\r\n resultlower.rotate(-k)\r\n dict_for_trans = dict(zip(upper,resultupper))\r\n dict_for_trans.update(dict(zip(lower,resultlower)))\r\n transdict = str.maketrans(dict_for_trans)\r\n return string.translate(transdict)","sub_path":"cookbook/caesercipher.py","file_name":"caesercipher.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"257521934","text":"#!/usr/bin/python\n# coding: utf-8\nfrom sys import stdin, stdout\n\nt=int(raw_input())\nfor i in xrange(t):\n arr=list(raw_input())\n length=len(arr)\n n=length/2\n tmp=0\n for j in xrange(n):\n if(arr[j]=='.'):\n arr[j]=arr[length-(j+1)]\n else:\n if(arr[length-(j+1)]=='.'):\n arr[length-(j+1)]=arr[j]\n if(arr[j]=='.'):\n arr[j]=arr[length-(j+1)]='a'\n if(arr[j]!=arr[length-(j+1)]):\n tmp=1\n break\n if(tmp):\n stdout.write(\"-1\")\n else:\n if(length&1 and arr[n]=='.'):\n arr[n]='a'\n for j in arr:\n stdout.write(j)\n stdout.write(\"\\n\")\n\n\n'''\n\nChef likes strings a lot but he likes palindromic strings even more. Today he found an old string s in his garage. The string is so old that some of its characters have faded and are \nunidentifiable now. Faded characters in the string are represented by '.' whereas other characters are lower case Latin alphabets i.e ['a'-'z'].\n\nChef being the palindrome lover decided to construct the lexicographically smallest palindrome by filling each of the faded character ('.') with a lower case Latin alphabet. Can you \nplease help him completing the task?\n\nInput\nFirst line of input contains a single integer T denoting the number of test cases. T test cases follow.\nFirst and the only line of each case contains string s denoting the old string that chef has found in his garage.\n\nOutput\nFor each test case, print lexicographically smallest palindrome after filling each faded character - if it possible to construct one. Print -1 otherwise.\n\nConstraints\n1 ≤ T ≤ 50\n1 ≤ |s| ≤ 12345\nString s consists of ['a'-'z'] and '.' only.\n\nSubtasks\nSubtask #1 (47 points)\n1 ≤ T ≤ 50, 1 ≤ |S| ≤ 123\n\nSubtask #2 (53 points)\n1 ≤ T ≤ 50, 1 ≤ |S| ≤ 12345\n\nExample\nInput\n3\na.ba\ncb.bc\na.b\n\nOutput\nabba\ncbabc\n-1\n\nExplanation\nIn example 1, you can create a palindrome by filling the faded character by 'b'.\nIn example 2, you can replace the faded character by any character from 'a' to 'z'. We fill it by 'a', as it will generate the lexicographically smallest palindrome.\nIn example 3, it is not possible to make the string s a palindrome.\n\n'''","sub_path":"codechef/Lexopal.py","file_name":"Lexopal.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"242989738","text":"'''\n# Task\n\nGiven a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the\nmaximum number of consecutive 1's in n's binary representation.\n\n# Input Format\n\nA single integer, n.\n\n# Constraints\n\n1 <= n <= 10^6\n\n# Output Format\n\nPrint a single base-10 integer denoting the maximum number of consecutive 1's in the binary representation of n.\n\n# Sample Input 1\n 5\n# Sample Output 1\n 1\n\n# Sample Input 2\n 13\n# Sample Output 2\n 2\n\n# Explanation\n\nSample Case 1:\nThe binary representation of 5 is 101, so the maximum number of consecutive 1's is 1.\n\nSample Case 2:\nThe binary representation of 13 is 1101, so the maximum number of consecutive 1's is 2.\n'''\n\n\ndef decimal_to_binary(decimal_num):\n binary_list = []\n\n while decimal_num > 1:\n binary_list.append(decimal_num % 2)\n decimal_num = decimal_num // 2\n\n if decimal_num == 1:\n binary_list.append(decimal_num)\n\n return binary_list\n\n\ndef consecutive_ones(base_10_num):\n binary_rep = decimal_to_binary(base_10_num)[::-1]\n count = 0\n max_ones = 0\n for ele in binary_rep:\n if ele == 1:\n count += 1\n else:\n count = 0\n \n if count > max_ones:\n max_ones = count\n\n return max_ones\n\n\nprint(consecutive_ones(13))\n","sub_path":"day10_binary_numbers.py","file_name":"day10_binary_numbers.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"29602605","text":"\nimport cv2\nimport pickle\n\nimport keras\nfrom imutils.video import WebcamVideoStream\nimport tensorflow\n\nclass VideoCamera(object):\n def __init__(self):\n self.stream = WebcamVideoStream(src=0).start()\n\n def __del__(self):\n self.stream.stop()\n\n def get_frame(self):\n image = self.stream.read()\n image = cv2.resize(image, (224, 224))\n img=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n li = ['chaya', 'manja', 'queany', 'rakesh', 'sam', 'sankalpa', 'sapana', 'shradda', 'shreya', 'sowmya', 'suprabha', 'swathi', 'thrupthi', 'vaishali', 'vaishu']\n haar = cv2.CascadeClassifier('C:\\\\haarcascades\\\\haarcascade_eye.xml')\n haar1 = cv2.CascadeClassifier('C:\\\\haarcascades\\\\haarcascade_frontalface_default.xml')\n eyes = haar.detectMultiScale(img)\n face = haar1.detectMultiScale(img)\n model=keras.models.load_model('C:\\\\Users\\\\User\\\\OneDrive\\\\Documents\\\\FaceRecognitionFlask\\\\facerecognition.h5')\n y_pred = int(model.predict_classes(image.reshape(1, 224, 224, 3)))\n #y_pred1 = model1.predict_classes(image.reshape(1, 224, 224, 3))\n name = li[y_pred]\n for (top, right, bottom, left) in eyes:\n startX = int(left)\n startY = int(top)\n endX = int(right)\n endY = int(bottom)\n cv2.rectangle(image, (startX, startY), (startX+endX, startY+endY), (0, 255, 0), 2)\n for (top, right, bottom, left) in face:\n startX = int(left)\n startY = int(top)\n endX = int(right)\n endY = int(bottom)\n cv2.rectangle(image, (startX, startY), (startX+endX, startY+endY), (0, 255, 0), 2)\n cv2.putText(image, name, (endX - 80, endY - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)\n data = []\n ret,jpeg=cv2.imencode('.jpg',image)\n data.append(jpeg.tobytes())\n data.append(name)\n return data\n","sub_path":"Face_recognition flask/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"539121560","text":"#tensorboard --logdir==training:logs --host=127.0.0.1:6006\n# linear regression\n\nimport tensorflow as tf\nimport numpy as np\n\nlearning_rate = 0.01\nfilename_queue = tf.train.string_input_producer(['data-01-test-score.csv','data-02-test-score.csv'], shuffle=False, name='filename_queue')\nreader = tf.TextLineReader()\nkey, value = reader.read(filename_queue)\n\n# Default values, in case of empty columns. Also specifies the type of the\n# decoded result.\nrecord_defaults = [[0.], [0.], [0.], [0.]]\nxy = tf.decode_csv(value, record_defaults=record_defaults)\n\n# collect batches of csv in\ntrain_x_batch, train_y_batch = \\\n tf.train.batch([xy[0:-1], xy[-1:]], batch_size=10)\n\n# placeholders for a tensor that will be always fed.\nX = tf.placeholder(tf.float32, shape=[None, 3])\nY = tf.placeholder(tf.float32, shape=[None, 1])\n\nwith tf.name_scope('layer1'):\n W1 = tf.Variable(tf.random_normal([3, 10]), name='weight1')\n b1 = tf.Variable(tf.random_normal([10]), name='bias')\n L1 = tf.add(tf.matmul(X, W1), b1)\n\nwith tf.name_scope('layer2'):\n W2 = tf.Variable(tf.random_normal([10, 1]), name='weight2')\n b2 = tf.Variable(tf.random_normal([1]), name='bias2')\n\nwith tf.name_scope('optimizer'):\n hypothesis = tf.add(tf.matmul(L1, W2), b2)\n cost = tf.reduce_mean(tf.square(hypothesis - Y))\n optimizer = tf.train.AdamOptimizer(learning_rate)\n train = optimizer.minimize(cost)\n tf.summary.scalar('cost', cost)\n\nsummary = tf.summary.merge_all()\n\n# Launch the graph in a session.\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n# Start populating the filename queue.\ncoord = tf.train.Coordinator()\nthreads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\nwriter = tf.summary.FileWriter('./logs')\nwriter.add_graph(sess.graph)\n\nfor step in range(2000):\n x_batch, y_batch = sess.run([train_x_batch, train_y_batch])\n cost_val, hy_val, _ = sess.run([cost, hypothesis, train], feed_dict={X: x_batch, Y: y_batch})\n if step % 500 == 0:\n print(step, \"Cost: \", cost_val, \"\\nPrediction:\\n\", hy_val)\n s, _ = sess.run([summary, train], feed_dict={X: x_batch, Y: y_batch})\n writer.add_summary(s, global_step=None)\n\ncoord.request_stop()\ncoord.join(threads)\n\n# Ask my score\nprint(\"Your score will be \",\n sess.run(hypothesis, feed_dict={X: [[100, 70, 101]]}))\n\nprint(\"Other scores will be \",\n sess.run(hypothesis, feed_dict={X: [[60, 70, 110], [90, 100, 80]]}))\n\n","sub_path":"lin_regression2/lin_regression2/lin_regression2.py","file_name":"lin_regression2.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"457429982","text":"import random\nfrom general import *\n\ndef flip_coin(x,y):\n\tstarter = rand(1,3) # this is then passed below to decide whether the ball will be kicked or recieved. \n\tmethod = rand(1,3) # 1 tehe ball will be kicked by the team who won above, 2 they opt to recieve the ball from the opoosing team\n\n\tif starter == 1:\n\t\tstarter = x\n\t\topposing_starter = y\n\telse:\n\t\tstarter = y\n\t\topposing_starter = x\t\t\n\t\n\tif method==1:\n\t\tmethod = 'kick'\n\telse: \n\t\tmethod = 'recieve'\n\n\treturn starter,opposing_starter,method\n\n\n\n\n","sub_path":"bin/python/libs/minor_events.py","file_name":"minor_events.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"459460576","text":"#!/usr/bin/env python\n\n##############################################################################\n##\n## This file is part of Sardana\n##\n## http://www.sardana-controls.org/\n##\n## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain\n##\n## Sardana is free software: you can redistribute it and/or modify\n## it under the terms of the GNU Lesser General Public License as published by\n## the Free Software Foundation, either version 3 of the License, or\n## (at your option) any later version.\n##\n## Sardana is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n## GNU Lesser General Public License for more details.\n##\n## You should have received a copy of the GNU Lesser General Public License\n## along with Sardana. If not, see .\n##\n##############################################################################\n\nimport time\nfrom taurus.external import unittest\nfrom sardana.pool.poolmeasurementgroup import PoolMeasurementGroup\nfrom sardana.pool.test import (FakePool, createPoolController,\n createPoolMeasurementGroup,\n createPoolCounterTimer, dummyCounterTimerConf01,\n dummyPoolCTCtrlConf01,\n dummyMeasurementGroupConf01)\n\nclass PoolMeasurementGroupTestCase(unittest.TestCase):\n \"\"\"Class used for an acquisition done by a Measurement Group with a\n dummyCounterTimer channel. The Measurement Group runs with a freshly created\n fake Pool which does not depends on the Sardana Pool.\n \"\"\"\n\n def setUp(self):\n \"\"\"Setup:\n - Use resources for Controller, CounterTimer and MeasurementGroup\n features.\n - Create Controller, CounterTimer and MeasurementGroup.\n \"\"\"\n pool = FakePool()\n\n pc = createPoolController(pool, dummyPoolCTCtrlConf01)\n pct = createPoolCounterTimer(pool, pc, dummyCounterTimerConf01)\n\n pc.add_element(pct)\n pool.add_element(pc)\n pool.add_element(pct)\n\n self.pmg = createPoolMeasurementGroup(pool, dummyMeasurementGroupConf01)\n self._pct = pct # keep a reference to use it in test_acquisition\n\n def test_init(self):\n \"\"\"check that the PoolMeasurementGroup is correctly instantiated\"\"\"\n msg = 'PoolMeasurementGroup constructor does not create ' +\\\n 'PoolMeasurementGroup instance'\n self.assertIsInstance(self.pmg, PoolMeasurementGroup, msg)\n\n def test_acquisition(self):\n \"\"\"Test acquisition using the created measurement group without\n using a Sardana pool.\"\"\"\n msg = 'Pool Measurement Group does not acquire'\n integ_time = 1\n self.pmg.set_integration_time(integ_time)\n self.pmg.start_acquisition()\n\n acq = self.pmg.get_acquisition()._ct_acq\n # 'acquiring..'\n while acq.is_running():\n time.sleep(0.05)\n values = acq.raw_read_value_loop()\n self.assertEqual(values[self._pct].value, integ_time, msg)\n\n def tearDown(self):\n unittest.TestCase.tearDown(self)\n self.pmg = None\n self._pct = None\n","sub_path":"src/sardana/pool/test/test_ctacquisition.py","file_name":"test_ctacquisition.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"340259583","text":"import pytest\nfrom thefuck.rules.java import match, get_new_command\nfrom tests.utils import Command\n\n\n@pytest.mark.parametrize('command', [\n\tCommand(script='java foo.java'),\n\tCommand(script='java bar.java')])\ndef test_match(command):\n\tassert match(command, None)\n\n\n@pytest.mark.parametrize('command, new_command', [\n\t(Command('java foo.java'), 'java foo'),\n\t(Command('java bar.java'), 'java bar')])\ndef test_get_new_command(command, new_command):\n\tassert get_new_command(command, None) == new_command\n","sub_path":"tests/rules/test_java.py","file_name":"test_java.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"508597241","text":"# Copyright 2014 Google Inc. All Rights Reserved.\n\"\"\"Command for deleting autoscalers.\"\"\"\n\n\nfrom googlecloudsdk.api_lib.compute import autoscaler_utils as util\nfrom googlecloudsdk.api_lib.compute import base_classes\nfrom googlecloudsdk.calliope import exceptions as calliope_exceptions\nfrom googlecloudsdk.core import log\nfrom googlecloudsdk.third_party.apitools.base.py import exceptions\n\n\nclass DeleteAutoscaler(base_classes.BaseCommand): # BaseAsyncMutator\n \"\"\"Delete Autoscaler instances.\"\"\"\n\n @staticmethod\n def Args(parser):\n parser.add_argument('names', help='Autoscalers names.', nargs='+')\n\n def Run(self, args):\n log.warn('Please use instead [gcloud compute instance-groups '\n 'managed stop-autoscaling].')\n client = self.context['autoscaler-client']\n messages = self.context['autoscaler_messages_module']\n resources = self.context['autoscaler_resources']\n try:\n request = messages.AutoscalerAutoscalersDeleteRequest()\n for autoscaler in args.names:\n autoscaler_ref = resources.Parse(\n autoscaler, collection='autoscaler.autoscalers')\n request.autoscaler = autoscaler_ref.autoscaler\n request.project = autoscaler_ref.project\n request.zone = autoscaler_ref.zone\n result = client.autoscalers.Delete(request)\n operation_ref = resources.Create(\n 'autoscaler.zoneOperations',\n operation=result.name,\n autoscaler=request.autoscaler,\n )\n util.WaitForOperation(client, operation_ref,\n 'Deleting Autoscaler instance')\n log.DeletedResource(autoscaler_ref)\n except exceptions.HttpError as error:\n raise calliope_exceptions.HttpException(util.GetErrorMessage(error))\n except ValueError as error:\n raise calliope_exceptions.HttpException(error)\n","sub_path":"google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/autoscaler/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"208236924","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2015 Nokia Siemens Networks. All rights reserved.\n#\n#\n\n\"\"\"The unit test is for check_disk_rw.\"\"\"\n\n__author__ = [\n '\"Mason\" '\n]\n\nimport unittest\nfrom unittest.mock import MagicMock\nimport os\nimport glob\nimport sys\n\n(root_path, file_name) = os.path.split(os.path.abspath(__file__))\n(root_path, file_name) = os.path.split(root_path)\n(root_path, file_name) = os.path.split(root_path)\nsys.path.append(root_path + \"/Nagios/libexec/\")\nfrom check_disk_rw import CheckDiskRW\n\nclass TestCheckDiskRW(unittest.TestCase):\n rootpath = os.path.split(os.path.abspath(__file__))\n def tearDown(self):\n tempFileList = glob.glob('MB_check_rw*')\n for file_index in range(len(tempFileList)):\n os.remove(tempFileList[file_index])\n \n def test_read_fine_and_write_fine(self):\n check_disk_rw = CheckDiskRW('./')\n self.assertEqual(check_disk_rw.check(), 0)\n \n def test_read_wrong_and_write_fine(self):\n check_disk_rw = CheckDiskRW('./')\n exists_fun_obj = os.path.exists\n os.path.exists = MagicMock(return_value=False)\n self.assertEqual(check_disk_rw.check(), 1)\n os.path.exists = exists_fun_obj\n \n def test_read_fine_and_write_wrong(self):\n check_disk_rw = CheckDiskRW('./')\n remove_fun_obj = os.remove \n os.remove = MagicMock(return_value=False)\n self.assertEqual(check_disk_rw.check(), 1)\n os.remove = remove_fun_obj\n \nif __name__ == \"__main__\":\n unittest.main()\n \n","sub_path":"test/scripts/test_check_disk_rw.py","file_name":"test_check_disk_rw.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249460580","text":"from flask import Flask\n\nfrom hivemind.config import config\n\napp = Flask(__name__)\n\napp.config.update(config)\n\nif 'VIEW_CONFIG' in app.config:\n # Allow view config access in templates\n app.jinja_env.globals['VIEW_CONFIG'] = app.config['VIEW_CONFIG']\nelse:\n app.jinja_env.globals['VIEW_CONFIG'] = {}\n\napp.secret_key = app.config[\"SESSION_KEY\"]\n\nfrom hivemind import views # noqa F401, E402\n","sub_path":"hivemind/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"266967659","text":"\n# import f0lib\nimport numpy as np\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nfrom scipy import stats\nimport scipy\nfrom python_speech_features import mfcc\nfrom scipy.signal import lfilter\nfrom f0Lib import getF0\n\n\n# BEGIN TASK 0 #\n\nfig, ax = plt.subplots(nrows=4, ncols=1)\n\n# 1. Load the 'speech_sample'\nexerciseData = sio.loadmat('lab2_data.mat')\nspeechSample = exerciseData['speech_sample'].reshape(-1)\n# 2. Declare the source sampling frequency, and the target sampling frequency.\n# 2.1 Source sampling frequency\nfs_source = 48000\n\n# 2.2 Target sampling frequency\n# Target frequency\nfs_down = 11025\n\nspeechLength = len(speechSample) / fs_source\n\n# #. Downsample the speech sample\nspeech_resampled = signal.resample(speechSample, int(\n np.round(speechLength * fs_down)))\n\n# 4. Visualize the downsampled speech signal.\n# 4.1 Creating the corresponding time vector, whose length is same to the length to the given signal.\n# You can use np.linspace() function to perform this. For example\n\n# 4.2 Plot your result\n# ax[0].plot(speechSample)\nax[0].plot(np.linspace(0, speechLength, len(speech_resampled)),\n speech_resampled, label='Downsampled Signal')\n\n# END TASK 0 #\n\n# BEGIN TASK 1 #\n\n# BEGIN TASK 1.1 #\n\n# 1. Pre-emphasize your resampled signal.\n# 1.1 Define the polynomial of your fitler\n# filter coefficients b, which is the numerator\n# filter coefficients a, which is the denominator\ncoef = 0.98\nb = np.array([1., -coef], speech_resampled.dtype)\na = np.array([1.], speech_resampled.dtype)\npreEmphasizedSample = signal.lfilter(b, a, speech_resampled)\n\n# ax[0].plot(np.linspace(0, speechLength, len(speech_resampled)),\n# preEmphasizedSample, label='Pre-emphasized Signal')\n\n# 2. Extract the mfcc coefficient by callying the mfcc() function\n# remeber to set the pre-emphasize argument to 0 since the signal has been pre-emphasized.\nframeLen = int(2 ** np.floor(np.log2(0.03 * fs_down)))\nmfccContour = mfcc(preEmphasizedSample,\n samplerate=fs_down,\n winlen=float(frameLen)/fs_down,\n winstep=float(frameLen)/(2*fs_down),\n numcep=12,\n preemph=0)\n\n# 3. Plot the 12 mfcc contours\nfor k in range(0, len(mfccContour)):\n ax[1].plot(np.linspace(0, speechLength,\n len(mfccContour[k])), mfccContour[k])\n\n# 4. Calculate the mean for each contour.\nmean_mfccContour = np.mean(\n mfccContour, axis=tuple(range(mfccContour.ndim - 1)))\n\n# Why do we need to pre-emphasize the speech signal before computing the MFCC feature?\n\n# The first step is to apply a pre-emphasis filter on the signal to amplify the high\n# frequencies. A pre-emphasis filter is useful in several ways: (1) balance the frequency\n# spectrum since high frequencies usually have smaller magnitudes compared to lower\n# frequencies, (2) avoid numerical problems during the Fourier transform operation\n# and (3) may also improve the Signal-to-Noise Ratio (SNR).\n# Pre-emphasis often used for loudness equalization\n\n# END TASK 1.1 #\n\n# BEGIN TASK 1.2 #\n\n# 1. Define a hamming window\n# 1.1 Calculate the window length, which the number of frames within 0.01s\n# number of non-overlapping _full_ frames\nwindow_length = int(np.round(0.01 * fs_down))\n\n# 1.2 Define the hamming window using signal.hamming()\nhamming_window = signal.windows.hamming(window_length)\n\n# 2. Calculate the short time energy (STE) contour by convolve the hamming window and the squared signal,\n# using the scipy.signal.convolve() function\nx12 = signal.convolve(speech_resampled ** 2, hamming_window)\n\n# 3. Clip half window of frames from both the beginning and end of the STE contour\nclip = int(np.ceil(window_length / 2))\nx12 = x12[clip:-clip]\n\n# 4. Visualize the final STE contour.\nax[2].plot(np.linspace(0, speechLength, len(x12)), x12)\n\n# 5. Calculate the 5 distribution parameter feature the of STE contour\nmean_ste = np.mean(x12)\nstd_ste = np.std(x12)\nten_perc_ste = np.percentile(x12, 10)\nninty_perc_ste = np.percentile(x12, 90)\nkurtosis_ste = stats.kurtosis(x12)\n\n# END TASK 1.2 #\n\n# BEGIN TASK 1.3 #\n\n# 1. Extract the f0 contour\nf0, _, T_ind, _ = getF0(speech_resampled, fs_down)\n\n# 2. Visualize the f0 contour\nax[3].plot(T_ind[:, 0] / fs_down, f0)\n\n# 3. Calculate these distribution parameter features\nmean_f0 = np.mean(f0)\nstd_f0 = np.std(f0)\nten_perc_f0 = np.percentile(f0, 10)\nninty_perc_f0 = np.percentile(f0, 90)\nkurtosis_f0 = stats.kurtosis(f0)\n\n# END TASK 1.3 #\n\n# BEGIN TASK 1.4 #\n\n# 1. Segmenting the voiced and unvoiced speech segements.\n# 1.1 Example on extracting voiced segment lengths\nframesInd_voiced = np.where(f0 > 0)[0]\ndiff = framesInd_voiced[1:] - framesInd_voiced[0:-1]\nvoiceToUnviceInd = np.where(diff > 1)[0]\nvoice_seg_num = len(voiceToUnviceInd) + 1\nvoice_seg_lengths = np.zeros(voice_seg_num)\ntmp = framesInd_voiced[0]\n\nfor i in range(voice_seg_num - 1):\n voice_seg_lengths[i] = framesInd_voiced[voiceToUnviceInd[i]] - tmp + 1\n tmp = framesInd_voiced[voiceToUnviceInd[i] + 1]\n\nvoice_seg_lengths[-1] = framesInd_voiced[-1] - tmp + 1\n\n#####################################################################\n###################################################################\n# 1.2 Extract unvoiced segment lengths.\nframesInd_unvoiced = np.where(f0 == 0)[0]\ndiff = framesInd_unvoiced[1:] - framesInd_unvoiced[0:-1]\nind = np.where(diff > 1)[0]\nunvoiced_seg_num = len(ind) + 1\nunvoiced_seg_lengths = np.zeros(unvoiced_seg_num)\ntmp = framesInd_unvoiced[0]\n\nfor i in range(unvoiced_seg_num - 1):\n unvoiced_seg_lengths[i] = framesInd_unvoiced[ind[i]] - tmp + 1\n tmp = framesInd_unvoiced[ind[i] + 1]\n\nunvoiced_seg_lengths[-1] = framesInd_unvoiced[-1] - tmp + 1\n\n# 2. Calculate the means and SDs of both Voiced and Unvoiced segment lengths\nmean_voiced = np.mean(voice_seg_lengths)\nmean_unvoiced = np.mean(unvoiced_seg_lengths)\n\nstd_voiced = np.std(voice_seg_lengths)\nstd_unvoiced = np.std(unvoiced_seg_lengths)\n\n# 3. Calculate the voicing ratio.\nvoicing_ratio = np.sum(voice_seg_lengths) / np.sum(unvoiced_seg_lengths)\n\n# END TASK 1.4 #\n\n# START TASK 1.5 #\n\n# 1. Print the 12 MFCC coefficients\nprint('--- 12 MFCC coefficients ---')\nfor k in range(0, len(mean_mfccContour)):\n print('{}: {}'.format(k, mean_mfccContour[k]))\nprint('')\n\n# 2. Print the distribution paremeter feature of the STE contour\nprint('--- Distribution paremeters of the STE contour ---')\nprint(\n 'mean_ste: ', mean_ste, '\\n'\n 'std_ste: ', std_ste, '\\n'\n 'ten_perc_ste: ', ten_perc_ste, '\\n'\n 'ninty_perc_ste: ', ninty_perc_ste, '\\n'\n 'kurtosis_ste: ', kurtosis_ste, '\\n'\n)\n\n# 3. Print the distribution parameter feature of the F0 contour\nprint('--- Distribution paremeters of the F0 contour ---')\nprint(\n 'mean_f0: ', mean_f0, '\\n'\n 'std_f0: ', std_f0, '\\n'\n 'ten_perc_f0: ', ten_perc_f0, '\\n'\n 'ninty_perc_f0: ', ninty_perc_f0, '\\n'\n 'kurtosis_f0: ', kurtosis_f0, '\\n'\n)\n\n# 3. Print the 5 prodosic features\nprint('--- 5 prodosic features ---')\nprint(\n 'mean_voiced: ', mean_voiced, '\\n'\n 'mean_unvoiced: ', mean_unvoiced, '\\n'\n 'std_voiced: ', std_voiced, '\\n'\n 'std_unvoiced: ', std_unvoiced, '\\n'\n 'voicing_ratio: ', voicing_ratio, '\\n'\n)\n# END TASK 1.4 #\n\n# END TASK 1 #\n\nfig.tight_layout()\nplt.show()\n","sub_path":"Exercise 2/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":7310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"194750466","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nimport sys\nimport seaborn as sns\nsys.path.append('../../../../scripts/')\nfrom fig_settings import configure_fig_settings\nsys.path.append('../../scripts/')\nfrom observabledata import ObservableData\nfrom readparams import ReadParams\n\n\nif __name__==\"__main__\":\n\n configure_fig_settings()\n\n width = 3.37\n height = width*1.25\n\n\n k24 = '0.1'\n gamma = '0.04'\n omega = sys.argv[1]\n\n scan = {}\n scan['\\\\gamma_s']=gamma\n scan['k_{24}']=k24\n scan['\\\\omega']=omega\n\n Larray = np.linspace(0,1000,num=101,endpoint=True)\n Larray[0] = 1.0\n\n\n youngs = np.copy(Larray)*0\n breaks = np.copy(Larray)*0\n\n colors = sns.color_palette(\"hls\",len(Larray))\n\n Lambdas = list(map(str,Larray))\n\n loadsuf = [\"K_{33}\",\"k_{24}\",\"\\\\Lambda\",\"\\\\omega\",\"\\\\gamma_s\"]\n savesuf = [\"K_{33}\",\"k_{24}\",\"\\\\omega\",\"\\\\gamma_s\"]\n\n #observable_list = [\"E\",\"R\",\"delta\",\"surfacetwist\",\"stress\"]\n observable_list = [\"youngs\",\"breaks\"]#,\"delta\",\"surfacetwist\"]\n\n\n\n fig = plt.figure()\n fig.set_size_inches(width,height)\n\n ax = {}\n\n for i,observable in enumerate(observable_list):\n\n ax[observable] = fig.add_subplot(2,1,i+1)\n\n\n\n\n for js,Lambda in enumerate(Lambdas):\n\n scan['\\\\Lambda']=Lambda\n\n\n obsfwd = ObservableData([\"strain\"],scan_dir='scanforward',scan=scan,loadsuf=loadsuf,\n savesuf=savesuf)\n #obsfwd.sort_observables()\n #obsfwd.remove_duplicates()\n\n if obsfwd.E()[0] > 1e299:\n print(\"bad calculation at Lambda = \",Lambda)\n Larray[js] = np.nan\n continue\n strains = obsfwd.data[:,0]\n stresses = np.gradient(obsfwd.E(),strains)\n stresses[0] = 0.0\n youngs[js] = (stresses[1]-stresses[0])/(strains[1]-strains[0])\n\n breaks[js] = strains[np.argmax(stresses[stresses==stresses])]*100\n print(Lambda,breaks[js]) \n \n ax[\"youngs\"].plot(Larray,youngs,'o-')\n ax[\"youngs\"].set_ylabel(r\"$Y$\")\n ax[\"youngs\"].set_xscale('log')\n ax[\"youngs\"].set_yscale('log')\n ax[\"breaks\"].plot(Larray,breaks,'o-')\n ax[\"breaks\"].set_ylabel(r\"$\\epsilon_{\\mathrm{max}}\\times100\\%$\")\n ax[\"breaks\"].set_xlabel(r\"$\\Lambda$\")\n ax[\"breaks\"].set_xscale('log')\n\n fig.subplots_adjust(left=0.2,right=0.8,bottom=0.1,top=0.95,hspace=0.05)\n fig.savefig(obsfwd.observable_sname(\"youngs-vs-Lambda\",plot_format=\"pdf\"))\n\n plt.show()\n\n\n\n\n\n\n\n\n","sub_path":"gradient_descent_new/experiments/2019-03-27/OLDfigure4-pfc-paper/youngs_vs_Lambda.py","file_name":"youngs_vs_Lambda.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"99111057","text":"def kMeans(dataSet, k, distMeas=distEuclid, createCent=randCent):\n m = shape(dataSet)[0]\n clusterAssment = zeros((m,2))#create mat to assign data points \n #to a centroid, also holds SE of each point\n centroids = createCent(dataSet, k)\n clusterChanged = True\n while clusterChanged:\n clusterChanged = False\n for i in range(m):#for each data point assign it to the closest centroid\n minDist = inf; minIndex = -1\n for j in range(k):\n distJI = distMeas(centroids[j,:],dataSet[i,:])\n if distJI < minDist:\n minDist = distJI; minIndex = j\n if clusterAssment[i,0] != minIndex: clusterChanged = True\n clusterAssment[i,:] = minIndex,minDist**2\n # print centroids\n for cent in range(k):#recalculate centroids\n ptsInClust = dataSet[nonzero(clusterAssment[:,0]==cent)[0]] #get all the point in this cluster - Note: this was incorrect in the original distribution.\n if(len(ptsInClust)!=0):\n centroids[cent,:] = mean(ptsInClust, axis=0) #assign centroid to mean - Note condition was added 10/28/2013\n return centroids, clusterAssment\n","sub_path":"week7/new_test.py","file_name":"new_test.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"87010442","text":"# Computer Science 1XA3 Final Project\n# Paul Warnick\n# 1300963\n# Description : A program that creates a binary search tree out of user inputed values, then preforms multiple operations on that tree\n\n#----------------------------------------------------------------------------#\n\nclass binary_search_tree(): \n\n \"\"\"A class used to initialize a blank tree, with methods that: create \n and print a binary search tree in list form, search that tree for values \n inputed by the user, finds and displays the max and minimum value of the\n the tree, outputs a sorted and reversed list of all the values in the tree\n and lastly allows the user to insert and delete a number from the tree\"\"\"\n \n def __init__(self, T = []): # initializes the tree to a black list when the class is called\n\n self.tree = T # sets the tree list to self.tree\n\n def getTree(self, T): # prints the list form of the tree from a give list by using recursion to split the tree up into smaller and bigger lists\n\n binarysearchtree = binary_search_tree() # calls the modules only class and sets it to a variable\n self.tree = T # sets the inputed list to a variable \n smalllist = [] # creates the variable for small list\n biglist = [] # same but for big list\n self.flist = [] # same thing for the final list\n \n if (self.tree != []): # checks to make sure the inputed list is not empty to prevent an error\n\n key = self.tree[0] # sets the key value to the first value of the inputed list\n self.flist.append(key) # makes the first value of the tree list the original key\n\n for i in range(1, len(self.tree)): # a loop that runs for the length of the inputed list but sets i to 1 instead of 0\n \n if (key > self.tree[i]): # checks if each value of the tree list is less than the first key values\n\n smalllist.append(self.tree[i]) # makes a list of all the values less than the key\n \n elif (key <= self.tree[i]): # same as above if statement but for all the values bigger or equal to the key\n\n biglist.append(self.tree[i]) # appends them to the big list\n\n self.flist.append(binarysearchtree.getTree(smalllist)) # appends each value of the final list in proper order using recursion by appending a list of sorted values to the first index of the tree\n self.flist.append(binarysearchtree.getTree(biglist)) # does the same but for the right side of the tree or the second position in the tree list once it hits an empty list it returns the whole final list\n \n return(self.flist) # returns the final list which is a tree in list form of the user inputed values\n\n def searchTree(self, key, usertree): # searches the tree for a value inputed by the user\n\n self.tree = usertree # sets variable for the values of the tree\n self.value = key # sets variable for the key value the user is looking for\n\n found = self.tree.count(self.value) # if the key is in the tree found will become the number of times it is found\n \n if (found >= 1): # if the value was found the method returns 0\n\n return(0)\n\n else: # otherwise it returns -1\n\n return(-1)\n\n def minimumTree(self, usertree): # displays the minimum value of the tree\n\n binarysearchtree = binary_search_tree() # calls the class\n run = 0 # a break condition for the while loop\n self.tree = binarysearchtree.getTree(usertree) # creates a binary search tree in list form with the user given values\n\n while run == 0: # happens while break condtion is true\n\n if (self.tree[1] == []): # checks if the second value of the tree list is empty\n\n run = 1 # breaks the while loop\n\n return(self.tree[0]) # returns the first value of the list which would be the minimum\n\n else:\n\n self.tree = self.tree[1] # sets the second value of the tree list to the new tree list, basically running down the left side of the tree until hitting a empty list (minimum value)\n\n def maximumTree(self, usertree): # this entire method does the same as the above one but for the right side of the tree (or the maximum value)\n\n binarysearchtree = binary_search_tree()\n run = 0\n self.tree = binarysearchtree.getTree(usertree)\n\n while run == 0:\n\n if (self.tree[2] == []):\n\n run = 1\n return(self.tree[0])\n\n else:\n\n self.tree = self.tree[2]\n\n def increasing_orderTree(self, usertree): # outputs a sorted list of all the keys in the tree\n\n self.tree = usertree # sets the user inputed list to a variable\n \n self.tree.sort() # sorts that list for smallest to greatest\n\n return(self.tree) # returns the sorted list\n\n def decreasing_orderTree(self, usertree): # same as above but in reverse\n\n self.tree = usertree # sets the user list values\n self.tree.sort() # sorts the list just in case it hasn't already been sorted\n self.tree.reverse() # reverses the already sorted \n\n return(self.tree) # returns the reversed list\n\n def insertTree(self, ins, usertree): # inserts a user given value in the the tree list at the correct spot\n\n binarysearchtree = binary_search_tree() # calls the class\n self.insert = ins # variable for the inserted value\n self.tree = usertree # variable for the tree\n self.tree.append(self.insert) # appends the user value to the end of the tree list\n\n return(binarysearchtree.getTree(usertree)) # simply runs the get tree method which will automatically sort the list into a binary search tree and returns it\n\n def deleteTree(self, dele, usertree): # deletes a user given value from the tree then reforms the tree with the remaing values\n\n binarysearchtree = binary_search_tree() # calls the class\n self.delete = dele # variable for the deleted value\n self.tree = usertree # variable for the users list of values\n\n try: # trys the below code and if an error occurs the value is not in the list\n\n index = self.tree.index(self.delete) # finds the index of the element the user is looking for in the list of values\n self.tree.pop(index) # removes the value at that index\n\n print(\"\\nThe new tree with the deleted value is:\\n\\n\",binarysearchtree.getTree(self.tree)) # prints the new tree without the deleted value by recalling the get tree method\n\n except: # runs if an error occured\n\n print(\"\\nSorry the given value was not found in the tree!\") # tell the user what happened\n\ndef main(): # main function that allows the use of every method in the above class\n\n try: # ensures that the program will continue to run if the user incorrectly inputs something\n\n binarysearchtree = binary_search_tree() # calls the class\n usertree = input(\"\\nPlease enter the numbers of your Binary Search Tree seperated by spaces: \").split() # takes the user inputed values and splits them into a list of strings\n \n for i in range(len(usertree)): # runs for the length of that list\n\n usertree[i] = eval(usertree[i]) # turns each value at each index into an int instead of a string\n\n print(\"\\nThe Binary Search Tree of the given values is:\\n\\n\",binarysearchtree.getTree(usertree)) # prints the binary search tree in list form\n print(\"\\nMinimum tree value:\", binarysearchtree.minimumTree(usertree)) # displays the minimum value of the tree\n print(\"\\nMaximum tree value:\", binarysearchtree.maximumTree(usertree)) # same for the maximum\n\n key = eval(input(\"\\nPlease enter a number you would like to search for in the tree: \")) # asks the user for the key they would like to find in the tree\n intree = binarysearchtree.searchTree(key,usertree) # calls the search tree method, if the value is in the tree it will return 0 if not it will return -1\n\n if (intree == 0): # if the value is found\n\n print(\"\\nThe value\", key, \"is in the tree!\") # displays that it was found to the user\n\n else: # if the value was not found\n\n print(\"\\nThe value\", key, \"is not in the tree!\") # also displays the result to the user\n\n insert = eval(input(\"\\nPlease enter a value you would like to insert into the tree: \")) # takes the value the user wants to insert into the list\n\n print(\"\\nThe new tree with the inserted value is:\\n\\n\",binarysearchtree.insertTree(insert,usertree)) # using the insert tree method it prints the new tree with the new value\n\n delete = eval(input(\"\\nPlease enter a value you would like to delete in the tree: \")) # askes the user which value they would like to delete\n\n binarysearchtree.deleteTree(delete,usertree) # uses the delete tree method to delete the give value and print the new tree without it\n\n print(\"\\nA sorted list of all the elements of the inputed tree is:\\n\\n\",binarysearchtree.increasing_orderTree(usertree)) # prints an sorted list of all the keys of the tree by calling teh increasing order method\n print(\"\\nThe reverse of that list is:\\n\\n\",binarysearchtree.decreasing_orderTree(usertree)) # same as above but outputs a reversed order list\n\n except: # just in case the user inputs something wrong\n\n print(\"\\nSomething went wrong! Please try again.\\n\") # displays an error message\n\n main() # re-runs main to restart the program\n\nmain() # runs main which runs the entire program","sub_path":"1XA3-Python-Final-Project/FinalProject.py","file_name":"FinalProject.py","file_ext":"py","file_size_in_byte":9635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"398404963","text":"# Write a program that opens a file called \"my-file.txt\", then prints\n# each line from the file.\n# If the program is unable to read the file (for example it does not exist),\n# then it should print the following error message: \"Unable to read file: my-file.txt\"\n\ntry:\n f = open(\"my-file.txt\")\n content = f.readlines()\n print(content)\nexcept FileNotFoundError:\n print(\"Cannot open the file!\")","sub_path":"week-02/day-2/exercises-w2d2/read_files/print_each_line.py","file_name":"print_each_line.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"263434438","text":"import urllib\nimport csv\nimport re\nimport datetime\nimport vobject\nimport pytz\n\nurl = \"http://data.edmonton.ca/api/views/uqbx-yqac/rows.csv\"\ntimezone = pytz.timezone(\"US/Mountain\")\n\nclass Schedule:\n def __init__(self, zone):\n first = True\n daypat = re.compile(\"^Day (.)\")\n datepat = re.compile(\"(..)/(..)/(....)\")\n\n self.Dates = []\n self.Zone = zone\n\n for row in csv.reader(urllib.urlopen(url)):\n if (not first) & (len(row) >= 3):\n name = row[0]\n day = int(daypat.match(row[1]).group(1))\n\n if (name == zone.Name) & (day == zone.Day):\n m = datepat.match(row[2])\n\n month, day, year = int(m.group(1)), int(m.group(2)), int(m.group(3))\n\n self.Dates.append(datetime.date(year, month, day))\n\n first = False\n\n def toical(self):\n cal = vobject.iCalendar()\n cal.add('x-wr-calname').value = \"Edmonton Garbage Schedule, %s\" % self.Zone.Name\n cal.add('x-wr-timezone').value = \"America/Denver\"\n\n for date in self.Dates:\n event = cal.add('vevent')\n event.add('summary').value = \"Garbage Pickup\"\n event.add('dtstart').value = date\n\n return cal.serialize()\n","sub_path":"sch.py","file_name":"sch.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"612057271","text":"from Game import Game\n\nclass Hangman(Game):\n \n def __init__(self, requirement, name, award, rules, questions):\n super().__init__(requirement, name, award, rules, questions)\n \n def game_begins(self, player):\n \n self.choose_random_question()\n self.define_current_clues()\n\n win = False\n man = ['''\n ___\n |\n |\n |\n _|____''',\n '''\n ___\n | O\n |\n |\n _|____''',\n '''\n ___\n | O\n | |\n |\n _|____''',\n '''\n ___\n | O\n | |\n | /\n _|____''',\n '''\n ___\n | O\n | |\n | / \\\\\n _|____''',\n '''\n ___\n | O\n | /|\n | / \\\\\n _|____''',\n '''\n ___\n | O/\n | /|\n | / \\\\\n _|____'''\n ]\n man_appearance = 0\n \n word_spaces = []\n for letter in self.current_question['answer']:\n word_spaces.append('_')\n \n print(f\"\\n👀SOBRE LA PALABRA: {self.current_question['question']}👀\\n\")\n \n while player.get_lives() > 0 and man_appearance < (len(man)-1): #si man_appearance (que es el índice de la imagen del ahorcado que se muestra) llega a la última imagen (len(man) -1 ya que en las listas se cuenta a partir del 0) ya perdió y por tanto se sale del loop del juego \n \n if '_' not in word_spaces: #si ya no quedan espacios en blanco, entonces el jugador adivinó todas las letras y ganó\n win = True\n break\n \n print(\"\\n\\n\",*word_spaces)\n print(man[man_appearance])\n \n self.ask_for_clues(player)\n \n guess = input(\"\\nLetra: \").upper()\n if len(guess) == 1 and guess in self.current_question['answer'].upper(): #si lo que adivinó el usuario es de un caracter y el mismo está en la respuesta, entonces pudo adivinar una letra de la palabra (o haber colocado una letra que ya ha adivinado)\n if guess not in word_spaces:\n print(\"✔️¡Adivinaste!✔️\")\n guess_indices = []\n for i, letter in enumerate(self.current_question['answer'].upper()): \n if letter == guess:\n guess_indices.append(i) #con esto, nos permite guardar en cuáles posiciones está la letra que adivinó la persona, para luego reemplazar los espacios vacíos (\"_\") con la letra determinada.\n for index in guess_indices:\n word_spaces[index] = guess\n else:\n print(\"👀La letra ingresada ya fue jugada👀\")\n else:\n print(\"❌Lo ingresado no forma parte de la palabra❌\")\n player.lose_lives(0.25)\n man_appearance += 1\n\n\n print(man[man_appearance]) \n print(\"\\n\", *word_spaces)\n\n self.win_or_lose(player, win)\n","sub_path":"Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"474382293","text":"import re\nimport jieba\nfrom jieba.finalseg import cut\nimport pandas as pd\n\nchinese = '[\\u4e00-\\u9fa5]+' #提取中文汉字的pattern\n\n\ndef LoadStopWords(file_path = '../中文停用词词表.txt'):\n \"\"\"\n 加载中文停用词列表\n file_path:停用词表所在路径\n \"\"\"\n stopwords = []\n with open(file_path,'r') as f:\n text = f.readlines()\n for line in text:\n stopwords.append(line[:-2])#去换行符\n return stopwords\n\n\ndef DeleteStopWrods(g_list,stop_words):\n \"\"\"\n 删除中文停词\n g_lst:分词结果\n stop_words:分词结果\n \"\"\"\n stop_words.append('电影') # 电影多次出现且意义不大\n outcome = []\n for term in g_list:\n if term not in stop_words:\n outcome.append(term)\n return outcome\n\ndef Cutter(comments,stop_words):\n \"\"\"\n 功能:中文分词主函数\n comment_list:评论列表\n stop_words:中文停用词表\n \"\"\"\n cut_string = \"\" #分词结果字符串\n for comment in comments:\n comment = \"\".join(re.findall(chinese,comment))\n if comment != \"\":\n seg_list = jieba.cut(comment)\n comment = \" \".join(DeleteStopWrods(seg_list,stop_words))\n cut_string += comment + ' '\n \n return cut_string\n\nif __name__ == '__main__':\n pass","sub_path":"maoyan_movie_comment/chinese_process.py","file_name":"chinese_process.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"364683286","text":" # To find the max of dictionary values \nimport FindLenght\ndef Max(values):\n\n values_count = FindLenght.count(values) \n one = values[0] \n two = values[1] \n if (one > two): \n max = one \n else: \n max = two \n i = 2 \n while(i!=values_count): \n if (values[i]>max): \n max = values[i] \n i += 1 \n return max \n\n#values = [5,2,4,7,3,5]\n#print(Max(values))","sub_path":"26.Find_kth_Largest_ele/Max.py","file_name":"Max.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"551117914","text":"from flask import render_template,request,redirect,url_for, abort, flash\nfrom . import main\nfrom flask_login import login_required,current_user\nfrom .forms import PostsForm,CommentsForm,UpdateProfile,SubscribeForm\nfrom ..models import Posts,Comments,User,Subscribe\nfrom .. import photos, db\nfrom datetime import datetime\n\n@main.route('/')\n# @login_required\ndef home():\n\n '''\n View root page function that returns the general news sources by category\n '''\n # message = \"Hello World\"\n title=\"Terabyte\"\n posts = Posts.query.order_by('-id').all()\n \n \n\n message= 'Welcome to the Blog'\n # return \"Hello, World\"\n return render_template('home.html',title=title,message=message,posts=posts,user=current_user)\n\n@main.route('/user/')\ndef profile(uname):\n user = User.query.filter_by(username = uname).first()\n\n if user is None:\n abort(404)\n\n return render_template(\"profile/profile.html\", user = user)\n@main.route('/user//update',methods = ['GET','POST'])\n@login_required\ndef update_profile(uname):\n user = User.query.filter_by(username = uname).first()\n if user is None:\n abort(404)\n\n form = UpdateProfile()\n\n if form.validate_on_submit():\n user.bio = form.bio.data\n\n db.session.add(user)\n db.session.commit()\n\n return redirect(url_for('.profile',uname=user.username))\n\n return render_template('profile/update.html',form =form)\n\n@main.before_request\ndef before_request():\n if current_user.is_authenticated:\n current_user.last_seen = datetime.utcnow()\n db.session.commit()\n\n@main.route('/post/new',methods = ['GET','POST'])\n@login_required\ndef new_post():\n '''\n View pitch function that returns the pitch page and data\n '''\n form = PostsForm()\n\n if form.validate_on_submit() and form.category.data != 'Select':\n body = form.body.data\n category = form.category.data\n title = form.title.data\n\n new_post = Posts(body=body,category=category,title=title,user_id=current_user.id)\n new_post.save_post()\n flash('Your post has been created!', 'success')\n return redirect(url_for('main.home'))\n\n return render_template('new_post.html', pitch_form = form)\n@main.route(\"/pitch//update\", methods=['GET', 'POST'])\n@login_required\ndef update_post(id):\n post = Posts.query.get_or_404(id)\n if post.user != current_user:\n abort(403)\n form = PostsForm()\n if form.validate_on_submit():\n post.title = form.title.data\n post.body = form.body.data\n db.session.commit()\n flash('Your post has been updated!', 'success')\n return redirect(url_for('.post',id=post.id))\n elif request.method == 'GET':\n form.title.data = post.title\n form.body.data = post.body\n return render_template('new_post.html', title='Update Post',\n pitch_form=form)\n\n@main.route(\"/pitch//delete\", methods=['POST'])\n@login_required\ndef delete_post(id):\n post = Posts.query.get_or_404(id)\n if post.user != current_user:\n abort(403)\n db.session.delete(post)\n db.session.commit()\n flash('Your post has been deleted!', 'success')\n return redirect(url_for('main.home'))\n\n\n@main.route(\"/pitch/comment//delete\", methods=['POST'])\n@login_required\ndef delete_comment(id):\n comment = Comments.query.get_or_404(id)\n\n db.session.delete(comment)\n db.session.commit()\n flash('Comment has been deleted!', 'success')\n return redirect(url_for('main.home'))\n\n@main.route(\"/pitch//full\")\ndef post(id):\n post = Posts.query.get_or_404(id)\n return render_template('post.html', title=post.title, post=post)\n\n\n@main.route('/pitch/',methods = ['GET', 'POST'])\n@login_required\ndef comment(id):\n\n comments_form = CommentsForm()\n # pitch = Pitches.query.get(pitch_id)\n posts = Posts.query.filter_by(id=id).first()\n print(posts)\n if comments_form.validate_on_submit():\n comment = comments_form.comment.data\n\n new_comment = Comments(the_comment=comment,posts_id=posts.id, user_id = current_user.id)\n db.session.add(new_comment)\n db.session.commit()\n\n comments_list = Comments.query.filter_by(posts_id=id).order_by(\"-id\")\n print(comments_list)\n\n return render_template('comments.html', comments_form=comments_form,comments_list=comments_list)\n\n@main.route('/subscribe',methods=[\"GET\",\"POST\"])\ndef subscribe():\n form=SubscribeForm()\n\n if form.validate_on_submit():\n subscriber = Subscribe(name=form.name.data,email=form.email.data)\n db.session.add(subscriber)\n db.session.commit()\n flash('You have sucessfully subscribed to get notifications.')\n return redirect(url_for('main.home'))\n title = 'Subscribe'\n return render_template('subscribe.html',subscribe_form=form)\n\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"485191715","text":"# -*- coding: utf-8 -*-\n'''\n======================Welcome to Python====================\n/-********Have a good time.********-/\n\nFILE NAME:\nAUTHOR: Eden·Gabriel \nDATE: Dec-21-Thu/2018 15:38:39 \nVERSION: V-1.0\nDESCRIPTION:\n自适应阈值\n'''\n\nimport numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\nimg = cv2.imread('E:\\\\A_BOOM_LEARNING_EDEN_GABRIEL\\\\2018.12.19start_opencv+python\\\\Images\\\\shudu.png')\nimg = cv2.medianBlur(img,5)\n\nimg_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\nret,img_thre1 = cv2.threshold(img_gray,50,255,cv2.THRESH_BINARY)\nimg_thre2 = cv2.adaptiveThreshold(img_gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,\n cv2.THRESH_BINARY,15,2)\nimg_thre3 = cv2.adaptiveThreshold(img_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv2.THRESH_BINARY,11,2)\nimg_thre4 = cv2.adaptiveThreshold(img_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv2.THRESH_BINARY,15,2)\n\n\ntitles = ['Original','Original_gray','Threshold','ADPTIVE_THRESH_MEAN',\n 'ADPTIVE_THRESH_GAUSSIAN','ADPTIVE_THRESH_GAUSSIAN1']\nimgs = [img,img_gray,img_thre1,img_thre2,img_thre3,img_thre4]\n\nfor i in range(6):\n plt.subplot(2,3,i+1),plt.imshow(imgs[i],'gray')\n plt.title(titles[i])\n plt.xticks([]),plt.yticks([])\n\nplt.show()\n","sub_path":"图像阈值2_自适应阈值.py","file_name":"图像阈值2_自适应阈值.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"515241285","text":"from app import config\nfrom app.db.Datastore import Datastore\n\nfrom app.items.Profile import Profile\n\n#\n# Setup Datastore\n#\ndatastore = Datastore()\ndatastore.setup()\n\n#\n# Setup Default Profile\n#\ndefaultProfile = Profile(config.default_profile)\ndefaultprofileId = datastore.addProfile(defaultProfile)\n\n#\n# Setup Application Config\n#\ninitialConfig = {\n 'downloads_folder' : config.export_folder,\n 'default_profile' : defaultprofileId,\n 'export_format' : config.export_format\n}\n\nfor k, v in initialConfig.iteritems():\n if datastore.getConfig(k) == None:\n datastore.addConfig(k, v)\n","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"158994540","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 20 10:13:57 2019\r\n\r\n@author: Johnny Tsao\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport sys\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom matplotlib import cm\r\nfrom numpy import linalg as la\r\n\r\n\r\nr0 = 0.7878973648236\r\ndef rhs(x,y):\r\n return -np.ones_like(x)\r\n\r\ndef solution(x,y):\r\n sol = np.heaviside(-level(x,y),1)*(1 + 0.25*(r0**2 - XYtoR(x,y)**2))\r\n return sol\r\n\r\ndef XYtoR(x,y):\r\n return np.sqrt(x**2+y**2)\r\n\r\ndef get_theta(u,u_next):\r\n return np.abs(u)/(np.abs(u)+np.abs(u_next))\r\n\r\ndef get_effective_beta(beta_p,beta_m,theta):\r\n ret = beta_p * beta_m / (beta_p * theta + beta_m * (1-theta))\r\n return ret\r\n\r\ndef level(x,y):\r\n return np.array(XYtoR(x,y) - r0)\r\n\r\ndef norm_mesh(x,y):\r\n ret_l = np.sqrt(x**2 + y**2)\r\n ret_x = x / ret_l\r\n ret_y = y / ret_l\r\n \r\n return ret_x, ret_y\r\n\r\ndef L_n_norm(error, n=2):\r\n error_n = np.power(error, n)\r\n average_n = np.sum(error_n) / len(error_n.flatten())\r\n average = np.power(average_n, 1./n)\r\n return average\r\n\r\ndef L_n_norm_frame(error,frame, n=2):\r\n num = np.sum(frame)\r\n error_n = np.power(error, n) * frame\r\n average_n = np.sum(error_n) / num\r\n average = np.power(average_n, 1./n)\r\n return average\r\n\r\ndef poisson_solver(iterNum, N_grid = 101, beta_p=1, plot = False):\r\n # grid dimension\r\n grid_min = -1.\r\n grid_max = 1.\r\n # grid spacing\r\n h = (grid_max - grid_min) / (N_grid- 1) \r\n \r\n # define arrays to hold the x and y coordinates\r\n xy = np.linspace(grid_min,grid_max,N_grid)\r\n xmesh, ymesh = np.meshgrid(xy,xy)\r\n \r\n # solution\r\n u = np.zeros_like(xmesh)\r\n \r\n #level grid\r\n phi = level(xmesh,ymesh)\r\n \r\n # normal\r\n r_temp = XYtoR(xmesh, ymesh) + 10**-13\r\n n1, n2 = xmesh/r_temp, ymesh/r_temp\r\n \r\n # the source on the rhs\r\n #source = np.zeros_like(u)\r\n source = np.zeros_like(xmesh)\r\n \r\n isOut = np.array(np.greater(phi,0.0),dtype = int)\r\n source += (1.0 - isOut) * rhs(xmesh, ymesh)\r\n \r\n \r\n beta_p = beta_p\r\n beta_m = 1.\r\n beta_x = np.zeros_like(xmesh[:,1:])\r\n beta_y = np.zeros_like(ymesh[1:,:])\r\n \r\n# a_jump = a+ - a-\r\n a_mesh = -np.ones_like(xmesh)\r\n# b_jump = beta+ * u_n+ - beta- * u_n-\r\n b_mesh = -beta_m * -(XYtoR((xmesh),(ymesh)))\r\n \r\n \r\n isOutx1 = np.array(np.greater(phi[:,1:],0.0),dtype = int)\r\n isOutx2 = np.array(np.greater(phi[:,:-1],0.0),dtype = int)\r\n isOuty1 = np.array(np.greater(phi[1:,:],0.0),dtype = int)\r\n isOuty2 = np.array(np.greater(phi[:-1,:],0.0),dtype = int)\r\n \r\n# step is 1 if k+1 is out and k is in\r\n# step is -1 if k is out and k+1 is in\r\n# step is 0 if both out or in\r\n xstep = isOutx1 - isOutx2\r\n ystep = isOuty1 - isOuty2\r\n \r\n xstep_p = np.array(np.greater( xstep,0.0),dtype = int)\r\n xstep_m = np.array(np.greater(-xstep,0.0),dtype = int)\r\n \r\n ystep_p = np.array(np.greater( ystep,0.0),dtype = int)\r\n ystep_m = np.array(np.greater(-ystep,0.0),dtype = int)\r\n \r\n theta_x = get_theta(phi[:,:-1],phi[:,1:])\r\n theta_y = get_theta(phi[:-1,:],phi[1:,:])\r\n \r\n beta_eff_x = np.zeros_like(beta_x)\r\n beta_eff_y = np.zeros_like(beta_y)\r\n \r\n beta_eff_x += xstep_p * get_effective_beta(beta_p,beta_m,theta_x)\r\n beta_eff_x += xstep_m * get_effective_beta(beta_m,beta_p,theta_x)\r\n beta_eff_y += ystep_p * get_effective_beta(beta_p,beta_m,theta_y)\r\n beta_eff_y += ystep_m * get_effective_beta(beta_m,beta_p,theta_y)\r\n \r\n a_jump_x = a_mesh[:,:-1] * (1-theta_x) + a_mesh[:,1:] * theta_x\r\n a_jump_y = a_mesh[:-1,:] * (1-theta_y) + a_mesh[1:,:] * theta_y\r\n \r\n b_jump_x = b_mesh[:,:-1]*(1-theta_x)*n1[:,:-1] + b_mesh[:,1:]*theta_x*n1[:,1:]\r\n b_jump_y = b_mesh[:-1,:]*(1-theta_y)*n2[:-1,:] + b_mesh[1:,:]*theta_y*n2[1:,:]\r\n# first additional term\r\n source[:,:-1] += a_jump_x * beta_eff_x*xstep/h**2\r\n source[:, 1:] += -a_jump_x * beta_eff_x*xstep/h**2\r\n source[:-1,:] += a_jump_y * beta_eff_y*ystep/h**2\r\n source[ 1:,:] += -a_jump_y * beta_eff_y*ystep/h**2\r\n \r\n# theta_x_k = (1. + (1. - 2*theta_x)*xstep)/2.\r\n# theta_x_kp1 = (1. - (1. - 2*theta_x)*xstep)/2.\r\n# theta_y_k = (1. + (1. - 2*theta_y)*ystep)/2.\r\n# theta_y_kp1 = (1. - (1. - 2*theta_y)*ystep)/2.\r\n beta_x_k = ((beta_p + beta_m) + (beta_p - beta_m)*xstep)/2\r\n beta_x_kp1 = ((beta_p + beta_m) - (beta_p - beta_m)*xstep)/2\r\n beta_y_k = ((beta_p + beta_m) + (beta_p - beta_m)*ystep)/2\r\n beta_y_kp1 = ((beta_p + beta_m) - (beta_p - beta_m)*ystep)/2\r\n \r\n# second additional term\r\n# source[:-1,:] += (b_jump_x*n1[:-1,:] * beta_eff_x * xstep / h) * (theta_x/beta_x_k)\r\n# source[1:,:] += (b_jump_x*n1[ 1:,:] * beta_eff_x * xstep / h) * ((1-theta_x)/beta_x_kp1)\r\n# source[:,:-1] += (b_jump_y*n2[:,:-1] * beta_eff_y * ystep / h) * (theta_y/beta_y_k)\r\n# source[:,1:] += (b_jump_y*n2[:, 1:] * beta_eff_y * ystep / h) * ((1-theta_y)/beta_y_kp1)\r\n source[:,:-1] += (b_jump_x * beta_eff_x * xstep / h) * ((1-theta_x)/beta_x_k)\r\n source[:, 1:] += (b_jump_x * beta_eff_x * xstep / h) * (theta_x/beta_x_kp1)\r\n source[:-1,:] += (b_jump_y * beta_eff_y * ystep / h) * ((1-theta_y)/beta_y_k)\r\n source[ 1:,:] += (b_jump_y * beta_eff_y * ystep / h) * (theta_y/beta_y_kp1)\r\n \r\n isBoundary_x = np.abs(xstep)\r\n isBoundary_y = np.abs(ystep)\r\n \r\n beta_x += beta_eff_x * isBoundary_x\r\n beta_x += isOutx2 * (1-isBoundary_x) * beta_p\r\n beta_x += (1-isOutx2) * (1-isBoundary_x) * beta_m\r\n beta_y += beta_eff_y * isBoundary_y\r\n beta_y += isOuty2 * (1-isBoundary_y) * beta_p\r\n beta_y += (1-isOuty2) * (1-isBoundary_y) * beta_m\r\n \r\n beta_sum = beta_x[1:-1,:-1] + beta_x[1:-1,1:] + beta_y[:-1,1:-1] + beta_y[1:,1:-1]\r\n \r\n \r\n #record data\r\n iterNum_array = []\r\n maxDif_array = []\r\n L2Dif_array = []\r\n for i in range(iterNum):\r\n if(i % int(iterNum/100) < 0.1):\r\n dif = np.abs(u-solution(xmesh,ymesh))\r\n L2Dif = L_n_norm_frame(dif,(1-isOut),2)\r\n maxDif = np.max(dif*(1-isOut))\r\n iterNum_array.append(i)\r\n maxDif_array.append(maxDif)\r\n L2Dif_array.append(L2Dif)\r\n sys.stdout.write(\"\\rProgress: %4g%%\" % (i *100.0/iterNum))\r\n sys.stdout.flush()\r\n # enforce boundary condition\r\n # sol = solution1(xmesh, ymesh)\r\n sol = solution(xmesh, ymesh)\r\n u[ 0, :] = sol[ 0, :] # y = y top\r\n u[-1, :] = sol[-1, :] # y = y bottom\r\n u[ :, 0] = sol[ :, 0] # x = x left\r\n u[ :,-1] = sol[ :,-1] # x = x right\r\n \r\n u_new = np.copy(u)\r\n \r\n \r\n \r\n \r\n # update u according to Jacobi method formula\r\n # https://en.wikipedia.org/wiki/Jacobi_method\r\n del_u = u[1:-1,2:]*beta_x[1:-1,1:] + u[1:-1,0:-2]*beta_x[1:-1,0:-1] +\\\r\n u[2:,1:-1]*beta_y[1:,1:-1] + u[0:-2,1:-1]*beta_y[0:-1,1:-1]\r\n u_new[1:-1,1:-1] = -h**2/beta_sum * (source[1:-1,1:-1] - del_u/h**2)\r\n \r\n u = u_new * (1-isOut)\r\n print(\"\")\r\n \r\n # error analysis between the solution and analytical solution\r\n dif = np.abs(u-solution(xmesh,ymesh))\r\n L2Dif = L_n_norm_frame(dif,(1-isOut),2)\r\n maxDif = np.max(dif*(1-isOut))\r\n print (\"N = %d maximum difference after %d iterations was %g\" % (N_grid, iterNum, maxDif))\r\n print (\"N = %d L^2 difference after %d iterations was %g\" % (N_grid, iterNum, L2Dif))\r\n if(plot):\r\n# plt.matshow(phi)\r\n# plt.colorbar()\r\n# plt.matshow(theta_x*(1-isOutx2))\r\n# plt.colorbar()\r\n# plt.matshow(theta_y*(1-isOuty2))\r\n# plt.colorbar()\r\n# #2D color plot of the max difference\r\n fig_dif = plt.figure(\"poisson solution max difference %d iterations\" % iterNum)\r\n plt.title(\"poisson solver error\")\r\n plt.xlabel(\"x\")\r\n plt.ylabel(\"y\")\r\n plt.pcolor(xmesh, ymesh, (solution(xmesh, ymesh) - u)/(solution(xmesh, ymesh)+1.0e-17))\r\n plt.colorbar()\r\n# fig_dif.savefig(\"max_dif_%d.png\" % iterNum)\r\n \r\n# #2D color plot of the max difference\r\n# fig_dif = plt.figure(\"poisson solution max difference %d iterations\" % iterNum)\r\n# plt.title(\"poisson solver analytical solution\")\r\n# plt.xlabel(\"x\")\r\n# plt.ylabel(\"y\")\r\n# plt.pcolor(xmesh, ymesh, solution(xmesh, ymesh))\r\n# plt.colorbar()\r\n \r\n #2D color plot of the max difference\r\n# fig_dif = plt.figure(\"poisson solution max difference %d iterations\" % iterNum)\r\n# plt.title(\"poisson solver result\")\r\n# plt.xlabel(\"x\")\r\n# plt.ylabel(\"y\")\r\n# plt.pcolor(xmesh, ymesh,u)\r\n# plt.colorbar()\r\n \r\n #3D plot of the analytic solution\r\n fig_an = plt.figure(\"poisson analytic solution %d iterations\" % iterNum)\r\n ax_an = fig_an.gca(projection='3d')\r\n ax_an.set_title(\"analytic solution\")\r\n surf_an = ax_an.plot_surface(xmesh, ymesh, solution(xmesh, ymesh), cmap=cm.coolwarm)\r\n fig_an.colorbar(surf_an)\r\n# fig_an.savefig(\"analytic_plot_%d.png\" % iterNum)\r\n \r\n #3D plot of the numerical result\r\n fig = plt.figure(\"poisson result %d iterations\" % iterNum)\r\n ax = fig.gca(projection='3d')\r\n ax_an.set_title(\"result\")\r\n surf = ax.plot_surface(xmesh, ymesh, u, cmap=cm.coolwarm)\r\n fig.colorbar(surf)\r\n# fig.savefig(\"sol_plot_%d.png\" % iterNum)\r\n \r\n #3D plot of the error\r\n fig_an = plt.figure(\"poisson error %d iterations\" % iterNum)\r\n ax_an = fig_an.gca(projection='3d')\r\n ax_an.set_title(\"error\")\r\n surf_an = ax_an.plot_surface(xmesh, ymesh, ((u-solution(xmesh, ymesh))/(solution(xmesh, ymesh)+1.0e-17))*(1-isOut), cmap=cm.coolwarm)\r\n fig_an.colorbar(surf_an)\r\n \r\n plt.show()\r\n return iterNum_array, maxDif_array, L2Dif_array\r\n\r\nif(__name__ == \"__main__\"):\r\n ##generate poisson solver with 10000 iterations\r\n plt.close(\"all\")\r\n# iterNum_array = [51,101,151,201,251,301]\r\n# iterNum_array = [21,41,81,161,321]\r\n iterNum_array = [101]\r\n plot_iterNum = []\r\n plot_L2Dif = []\r\n plot_maxDif = []\r\n for idx in iterNum_array:\r\n iterNum, maxDif, L2Dif = poisson_solver(2*(idx-1)**2,idx,10000,True)\r\n plot_iterNum.append(iterNum)\r\n plot_L2Dif.append(L2Dif)\r\n plot_maxDif.append(maxDif)\r\n plt.figure()\r\n for i in range(len(iterNum_array)):\r\n plt.plot(plot_iterNum[i],np.log(plot_L2Dif[i]))\r\n \r\n\r\n\r\n","sub_path":"tests/test_Poisson.py","file_name":"test_Poisson.py","file_ext":"py","file_size_in_byte":10568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"264785852","text":"\n\nfrom xai.brain.wordbase.nouns._samaritan import _SAMARITAN\n\n#calss header\nclass _SAMARITANS(_SAMARITAN, ):\n\tdef __init__(self,): \n\t\t_SAMARITAN.__init__(self)\n\t\tself.name = \"SAMARITANS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"samaritan\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_samaritans.py","file_name":"_samaritans.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"578276619","text":"import json\nimport os\nimport numpy as np\nfrom decorator import __init__\n\nfrom keras.callbacks import Callback\nfrom sklearn.metrics import f1_score, recall_score, precision_score\n\n\nclass ResumeTrainingCallback(Callback):\n\n \"\"\"\n Save a configuration file wth the last epoch trained and the path of the model file.\n This configuration file will be used to resume the model training.\n \"\"\"\n\n def __init__(self, configFilePath, modelFilePath, foldNumber, alreadyTrainedEpochs=0):\n self.configFilePath = configFilePath\n self.modelFilePath = modelFilePath\n self.foldNumber = foldNumber\n self.alreadyTrainedEpochs = alreadyTrainedEpochs\n\n def on_epoch_end(self, epoch, logs={}):\n with open(self.configFilePath, 'w') as configFileHandler:\n json.dump({\"epoch\": (epoch+1)+self.alreadyTrainedEpochs, \"filepath\":self.modelFilePath,\n \"fold\":self.foldNumber}, configFileHandler)\n return\n\n\n# Validation metrics callback: validation precision, recall and F1\n# Some of the code was adapted from https://medium.com/@thongonary/how-to-compute-f1-score-for-each-epoch-in-keras-a1acd17715a2\nclass Metrics(Callback):\n\n def __init__(self, val_data):\n self.val_data = val_data\n\n def on_train_begin(self, logs={}):\n self.val_f1s = []\n self.val_recalls = []\n self.val_precisions = []\n\n def on_epoch_end(self, epoch, logs={}):\n # 5.4.1 For each validation batch\n predicted = []\n trueClasses = []\n for i in range(len(self.val_data)):\n data = self.val_data[i]\n r = self.model.predict_classes(data[0])\n r = r.flatten()\n predicted.extend(r)\n trueClasses.extend(data[1])\n\n val_f1 = round(f1_score(trueClasses, predicted), 4)\n val_recall = round(recall_score(trueClasses, predicted), 4)\n val_precis = round(precision_score(trueClasses, predicted), 4)\n\n self.val_f1s.append(val_f1)\n self.val_recalls.append(val_recall)\n self.val_precisions.append(val_precis)\n\n # Add custom metrics to the logs, so that we can use them with\n # EarlyStop and csvLogger callbacks\n logs[\"val_f1\"] = val_f1\n logs[\"val_recall\"] = val_recall\n logs[\"val_precis\"] = val_precis\n\n print(\"— val_f1: {} — val_precis: {} — val_recall {}\".format(\n val_f1, val_precis, val_recall))\n return","sub_path":"keras_callbacks.py","file_name":"keras_callbacks.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"76042628","text":"import os\nimport unittest\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flaskr import create_app\nfrom models import setup_db, Question, Category\n\n\nclass TriviaTestCase(unittest.TestCase):\n \"\"\"This class represents the trivia test case\"\"\"\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app()\n self.client = self.app.test_client\n self.database_name = \"trivia_test\"\n self.database_path = \"postgres://{}:{}@{}/{}\".format(\n 'postgres', '11112015', 'localhost:5432', self.database_name\n )\n\n setup_db(self.app, self.database_path)\n\n # binds the app to the current context\n with self.app.app_context():\n self.db = SQLAlchemy()\n self.db.init_app(self.app)\n # create all tables\n self.db.create_all()\n\n def tearDown(self):\n \"\"\"Executed after reach test\"\"\"\n pass\n\n \"\"\"\n TODO\n Write at least one test for each test\n for successful operation and for expected errors.\n \"\"\"\n # test get categories\n def test_get_categories(self):\n res = self.client().get('/categories')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(len(data['categories']))\n self.assertTrue(data['total_categories'])\n\n def test_404_sent_requesting_non_existing_category(self):\n res = self.client().get('/categories/10000')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'Not found')\n\n def test_get_paginated_questions(self):\n res = self.client().get('/questions')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(len(data['questions']))\n self.assertTrue(data['total_questions'])\n self.assertEqual(data['current_category'], None)\n self.assertTrue(len(data['categories']))\n\n def test_404_sent_requesting_questions_beyond_valid_page(self):\n res = self.client().get('/questions?page=1000')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'Not found')\n\n def test_delete_question(self):\n question = Question(\n question='new question',\n answer='new answer',\n difficulty=1,\n category=1\n )\n question.insert()\n question_id = question.id\n\n res = self.client().delete(f'/questions/{question_id}')\n data = json.loads(res.data)\n\n question = Question.query.filter(\n Question.id == question_id\n ).one_or_none()\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertEqual(data['deleted'], question_id)\n self.assertTrue(data['total_questions'])\n self.assertTrue(len(data['questions']))\n self.assertEqual(question, None)\n\n def test_422_question_creation_fails(self):\n res = self.client().delete('/questions/1000')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 422)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'Not processable')\n\n # def test_404_if_question_does_not_exist(self):\n # res = self.client().delete('/questions/1000')\n # data = json.loads(res.data)\n\n # self.assertEqual(res.status_code, 404)\n # self.assertEqual(data['success'], False)\n # self.assertEqual(data['message'], 'Not found')\n\n def test_add_question(self):\n new_question = {\n 'question': 'new question',\n 'answer': 'new answer',\n 'difficulty': 1,\n 'category': 1\n }\n total_questions_before = len(Question.query.all())\n res = self.client().post('/questions', json=new_question)\n data = json.loads(res.data)\n total_questions_after = len(Question.query.all())\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data[\"success\"], True)\n self.assertEqual(total_questions_after, total_questions_before + 1)\n\n def test_422_add_question_fails(self):\n new_question = {\n 'question': 'new question',\n 'answer': 'new answer',\n 'category': 1\n }\n res = self.client().post('/questions', json=new_question)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 422)\n self.assertEqual(data[\"success\"], False)\n self.assertEqual(data[\"message\"], \"Not processable\")\n\n def test_search_questions(self):\n new_search = {'searchTerm': 'a'}\n res = self.client().post('/questions/search', json=new_search)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertIsNotNone(data['questions'])\n self.assertIsNotNone(data['total_questions'])\n\n def test_404_search_questions(self):\n new_search = {\n 'searchTerm': '',\n }\n res = self.client().post('/questions/search', json=new_search)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data[\"success\"], False)\n self.assertEqual(data[\"message\"], \"Not found\")\n\n def test_get_questions_by_category(self):\n res = self.client().get('/categories/1/questions')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(len(data['questions']))\n self.assertTrue(data['total_questions'])\n self.assertTrue(data['current_category'])\n\n def test_404_get_questions_by_category_non_existing(self):\n res = self.client().get('/categories/c/questions')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data[\"success\"], False)\n self.assertEqual(data[\"message\"], \"Not found\")\n\n def test_play_quiz_questions(self):\n request_data = {\n 'previous_questions': [2, 4],\n 'quiz_category': {\n 'type': 'History',\n 'id': '4'\n }\n }\n response = self.client().post('/quizzes', json=request_data)\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['question'])\n self.assertNotEqual(data['question']['id'], 2)\n self.assertNotEqual(data['question']['id'], 4)\n self.assertEqual(data['question']['category'], '4')\n\n def test_422_play_quiz_fails(self):\n new_quiz_round = {'previous_questions': []}\n res = self.client().post('/quizzes', json=new_quiz_round)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 422)\n self.assertEqual(data[\"success\"], False)\n self.assertEqual(data[\"message\"], \"Not processable\")\n\n\n# Make the tests conveniently executable\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"backend/test_flaskr.py","file_name":"test_flaskr.py","file_ext":"py","file_size_in_byte":7380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"14874954","text":"import re\r\n\r\n# str = ' c332 st123 z132 up f1200 '\r\n#c1 st1 z1 up f2, z2 forward f3\r\n#case2 st2 z3 down f4, z4 left f5\r\n#c3 b1 t123\r\n# eg.\r\n# c3 st1 b1 t1 f7\r\n# c4 st1 z2 down f3, z3 down f5\r\n# c5 st1 z1 forward f1\r\n# c6 st1 z2 up f4, z3 up f6, z1 back f6\r\n\r\n\r\nclass ZLine:\r\n\r\n def __init__(self,_zline):\r\n self.Str=_zline\r\n self.StN = 'xxx'\r\n self.ZNs = []\r\n self.Motions = []\r\n\r\n self.BNs = []\r\n self.BMotions = [] #only on or off\r\n\r\n self.Fehler = []\r\n self.Case = 'xxx'\r\n self.extract(_zline)\r\n\r\n def regular(self, str):\r\n str = str.lower()\r\n str = re.sub(r',+|(\\s+)', r' ', str)\r\n str = re.sub(r'\\sz(\\d+)', r', z\\1', str)\r\n str = re.sub(r'\\sb(\\d+)', r', b\\1', str)\r\n str = str + ','\r\n return str\r\n\r\n def extract(self, str):\r\n str = self.regular(str)\r\n self.StN = re.compile(r'.*st?(\\d+).*').match(str).group(1)\r\n cmatch = re.compile(r'.*c(ase)?\\s*(?P\\d+)').match(str)\r\n if cmatch:\r\n self.Case = cmatch.group('Case')\r\n\r\n zstrls=re.compile(r'\\bz\\d+.*?,').findall(str)\r\n\r\n for zstr in zstrls:\r\n zmatch = re.compile(r'.*z(?P\\d+)\\s+(?P\\w+)').match(zstr)\r\n self.ZNs.append(zmatch.group('ZN'))\r\n\r\n self.Motions.append(re.sub(r'^(up|down|left|right|back)$',r'\\1ward', zmatch.group('Motion')))\r\n\r\n fmatch = re.compile(r'.*f(ehler)?\\s*(?P\\d+)').match(zstr)\r\n if fmatch:\r\n self.Fehler.append(fmatch.group('Fehler'))\r\n else:\r\n self.Fehler.append('xxx')\r\n\r\n nbstrls=re.compile(r'\\bb\\d+.*?,').findall(str)\r\n\r\n for nbstr in nbstrls:\r\n bmatch = re.compile(r'.*b(?P\\d+)\\s+(?P\\w+)').match(nbstr)\r\n self.BNs.append(bmatch.group('BN'))\r\n self.BMotions.append(bmatch.group('BMotion'))\r\n\r\n fmatch = re.compile(r'.*f(ehler)?\\s*(?P\\d+)').match(nbstr)\r\n if fmatch:\r\n self.Fehler.append(fmatch.group('Fehler'))\r\n else:\r\n self.Fehler.append('xxx')\r\n \r\n def neg_motion(self, motion):\r\n dict = {'forward':'backward', 'backward':'forward', 'upward' : 'downward', 'downward' : 'upward',\r\n 'leftward' : 'rightward', 'rightward': 'leftward', 'open': 'close', 'close': 'open'}\r\n return dict[motion]\r\n # case 3:\r\n # if (M_.MaStepEn)\r\n # {\r\n # if (E_St10_B1_4_good_parts_ejector_in_front && !E_St10_B1_2_good_parts_ejector_back )\r\n # {\r\n # Step[SEQ] + +;\r\n # }\r\n # }\r\n #\r\n # // Main Air Off\r\n # MainAir[MainAirValve] = false;\r\n #\r\n # // Assign outputs\r\n # A.St10_Y1_2_good_parts_ejector_backward = false;\r\n # A.St10_Y1_4_good_parts_ejector_forward = true;\r\n #\r\n # // Assign errors\r\n # if (M_Error_Search)\r\n # {\r\n # if (!E_St10_B1_4_good_parts_ejector_in_front | | E_St10_B1_2_good_parts_ejector_back) Fehler(PRG1, ErrorNum, 1, 0);\r\n # }\r\n # break;\r\n def formatted_code(self, zbins, nbins, zouts):\r\n bpairs = []\r\n zpairs = []\r\n\r\n nbpairs = []\r\n\r\n i=0\r\n for z in self.ZNs:\r\n if zouts.search(self.StN, z, self.Motions[i]).Ztype == 'not gripper':\r\n #bp[0]:type, gripper or not gripper\r\n #bp[1]:positive motion if not girrper or time on if is griiper\r\n #bp[2]:negative motion or noting if is gripper\r\n #bp[3]:fehler number if not gripper or nothing if is gripper\r\n bpair=['not gripper']\r\n temp = zbins.search(self.StN, z, self.Motions[i])\r\n bpair.append(zbins.search(self.StN, z, self.Motions[i]).Var)\r\n bpair.append(zbins.search(self.StN, z, self.neg_motion(self.Motions[i])).Var)\r\n bpair.append(self.Fehler[i])\r\n bpairs.append(bpair)\r\n\r\n zpair=['not gripper']\r\n zpair.append(zouts.search(self.StN, z, self.Motions[i]).Var)\r\n zpair.append(zouts.search(self.StN, z, self.neg_motion(self.Motions[i])).Var)\r\n zpairs.append(zpair)\r\n\r\n elif zouts.search(self.StN, z, self.Motions[i]).Ztype == 'gripper':\r\n #zp[0]:type, gripper or not gripper\r\n #zp[1]:positive motion\r\n #zp[2]:negative motion\r\n #zp[3]:Isettimer if is gripper or nothing if not gripper\r\n timevar = 'T_St' + self.StN + '_Z' + z + '_' + zouts.search(self.StN, z, self.Motions[i]).ZName\r\n bpair=['gripper']\r\n bpair.append('Time('+timevar+')')\r\n bpair.append(self.Fehler[i])\r\n bpairs.append(bpair)\r\n\r\n zpair=['gripper']\r\n zpair.append(zouts.search(self.StN, z, self.Motions[i]).Var)\r\n zpair.append(zouts.search(self.StN, z, self.neg_motion(self.Motions[i])).Var)\r\n zpair.append('ISetTimer('+timevar + ', M_.MaRun && Step[SEQ] == ' + self.Case + ');')\r\n zpairs.append(zpair)\r\n i = i + 1\r\n\r\n i = 0\r\n for nb in self.BNs:\r\n #nbp[0]:type reserved\r\n #nbp[1]:condition\r\n timevar = 'T_St' + self.StN + '_B' +nbins.search(self.StN,nb).BN+'_'+ nbins.search(self.StN,nb).BName\r\n nbpair = ['normal sensor'] #reserved\r\n nbpair.append('Time('+timevar+')')\r\n nbpair.append(self.Fehler[i])\r\n\r\n bmotionsymbol = ''\r\n fehlerbmotionsymbol = '!'\r\n if self.BMotions[i] == 'off':\r\n bmotionsymbol = '!'\r\n fehlerbmotionsymbol = ''\r\n nbpair.append('ISetTimer('+timevar + ', '+bmotionsymbol +nbins.search(self.StN,nb).Var + ' && MaRun && Step[SEQ] == ' + self.Case + ');') #remarkremark\r\n nbpair.append(fehlerbmotionsymbol + nbins.search(self.StN,nb).Var)\r\n nbpairs.append(nbpair)\r\n i = i + 1\r\n\r\n\r\n\r\n eincond=''\r\n ainout=''\r\n einfehler=''\r\n\r\n i = 1\r\n for bp in bpairs:\r\n if i==len(bpairs) and len(nbpairs)==0:\r\n if bp[0]=='gripper':\r\n eincond =eincond+ bp[1]\r\n else:\r\n eincond =eincond+ bp[1] + ' && !' + bp[1]\r\n einfehler = einfehler + ' if(!' + bp[1] + ' || ' + bp[2] +') Fehler(PRG1, ErrorNum, ' + bp[3] + ', 0);\\n'\r\n\r\n else:\r\n if bp[0]=='gripper':\r\n eincond =eincond+ bp[1] + ' &&\\n' + ' '\r\n else:\r\n eincond =eincond+ bp[1] + ' && !' + bp[2] + ' &&\\n' + ' '\r\n einfehler = einfehler + ' if(!' + bp[1] + ' || ' + bp[2] +') Fehler(PRG1, ErrorNum, ' + bp[3] + ', 0);\\n'\r\n\r\n i = i+1\r\n\r\n for zp in zpairs:\r\n if zp[0]=='gripper':\r\n ainout = ainout + zp[1] + ' = true; \\n ' + zp[2] + ' = false;\\n\\n' + ' '\r\n ainout = ainout + zp[3] +' \\n\\n '\r\n else:\r\n ainout = ainout + zp[1] + ' = true; \\n ' + zp[2] + ' = false;\\n' + ' '\r\n\r\n i = 1\r\n for nbp in nbpairs:\r\n if i == len(nbpairs):\r\n eincond = eincond + nbp[1]\r\n else:\r\n eincond = eincond + nbp[1] + ' &&\\n' + ' '\r\n\r\n ainout = ainout + nbp[3] +'\\n '\r\n einfehler = einfehler + ' if(' + nbp[4] +') Fehler(PRG1, ErrorNum, ' + nbp[2] + ', 0);\\n'\r\n i = i+1\r\n\r\n\r\n\r\n ccode = ' case ' + self.Case + ':' + '\\n' +\\\r\n ' if (M_.MaStepEn)\\n' +\\\r\n ' {\\n' +\\\r\n ' if(' + eincond +')\\n {\\n'+' Step[SEQ]++;\\n }\\n' +\\\r\n ' }\\n\\n' +\\\r\n ' MainAir[MainAirValve] = false;\\n\\n' +\\\r\n ' '+ainout +'\\n' +\\\r\n ' if (M_Error_Search)\\n {\\n' +\\\r\n einfehler +\\\r\n ' }\\n\\n'\r\n\r\n return ccode\r\n\r\n def formate_Z(self, zbins, nbins, zouts):\r\n pass\r\n\r\n def formate_B(self, zbins, nbins, zouts):\r\n pass\r\n\r\n def display(self):\r\n return 'self.Str: ' + self.Str+' self.StN: ' + self.StN + ' self.CylinderN: ' + self.ZN +\\\r\n ' self.Motion:' + self.Motion + ' self.Fehler: ' + self.Fehler + ' self.Case: ' + self.Case","sub_path":"CodingTools/CTDef/zline.py","file_name":"zline.py","file_ext":"py","file_size_in_byte":8582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"200514084","text":"\"\"\"\n Project I Numerical Analysis II\n By Cristian Cardona\n Group Santiago, Chris, Cristian.\n @instructor: Xiaojing Ye, Math & Stat, Georgia State University\n\"\"\"\n\n# import commonly used package\nimport numpy as np\n\nimport exmp_fn # import a collection of example functions from textbook\n\n# ======================================\n# Modified Euler Method\n\ndef Moulton(def_fn, a, b, ya, N):\n\n \n # defining function and true solution of an example function\n sol = exmp_fn.exmp3_sol\n\n \"\"\"\n Test the Runge Kutta 4th Order to solve\n initial value problem y'=f(t,y) with t in [a,b] and y(a) = ya.\n Step size h is computed according to input number of mesh points N\n \"\"\"\n f = def_fn\n\n h = (b - a) / N # step size\n\n t = np.arange(a, b + h, h) # all mesh points t=(t_0, t_1, ..., t_N)\n\n y = np.zeros((N + 1, 1)) # Approximations at mesh points\n \n\n \n y[0] = ya # set initial value y(t_0) = ya\n # Main code\n \n # compute exact solution for comparison\n z = sol(t)\n \n y[1] = z[1]\n y[2]= z[2]\n\n \n# 0 -9\n m =0\n\n for i in range(2, N):\n tauZ = t[m] # current mesh point t i =0 \n tauOne = t[m+1]\n tauTwo = t[m+2]\n tauThree = t[m+3]\n \n wZero = y[m] # current value y(t) actual value\n wOne = z[m+1]\n wTwo =z[m+2]\n wThree = z[m+3] \n \n y[i+1] = wTwo + (h/24)*(9*f(tauThree,wThree)+19*f(tauTwo,wTwo)-\n 5*f(tauOne,wOne)+f(tauZ,wZero))\n \n m = m +1\n \n \n \n \n # compute y at next time point t \n # y[i + 1] = y[i] + (h/2) *(f(tau, w) + f(tau2, w + h *f(tau, w)))\n \n\n return (t,y)","sub_path":"naTwo.py","file_name":"naTwo.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"489705937","text":"#ingrsar 5 enteros, una segunda función debe recibir una lista\n# y retornar el mayor y el menor valor de la lista. \n#desde el bloque principal del programa llamar a ambas funciones\n\n\ndef carga_lista():\n li=[]\n for x in range(5):\n valor=int(input(\"Ingrese valor:\"))\n li.append(valor)\n return li\n \ndef retornar_mayormenor(li):\n ma=li[0]\n me=li[0]\n for x in range(1, len(li)):\n if li[x]>ma:\n ma=li[x]\n else:\n if li[x]alphabet,value-->freq\n d[i]=v\n #dd is the sorted dict of d based on the values\n #lambda is used for dict.values() sort\n #reverse--->desc order\n dd=sorted(d.items(),key=lambda kv:kv[1],reverse=True) \n #dict dd (each key value pair is stored as a tuple) is iterated over \n for i in dd:\n print(i[0],\"=\",i[1],end=\" \")\n\ns=input(\"Please enter a string:\").lower()\nmost_frequent(s) \n","sub_path":"functions_freq.py","file_name":"functions_freq.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"456344828","text":"from odoo import api, fields, models, _\nfrom odoo.addons import decimal_precision as dp\nfrom odoo.exceptions import UserError, ValidationError\nfrom odoo.tools import float_round, pycompat\n\nfrom itertools import groupby\n\nclass MrpBom(models.Model):\n\n _inherit = 'mrp.bom'\n\n image_small_id = fields.Binary(related='product_tmpl_id.image_small', string='Image Small', compute='_compute_images', inverse='_set_image_small')\n\n item_code = fields.Char(related='product_tmpl_id.barcode', string='Item Code')\n\n\nclass MrpBomLine(models.Model):\n\n _inherit = 'mrp.bom.line'\n\n image_small_id = fields.Binary(related='product_id.image_small', string='Image Small', compute='_compute_images', inverse='_set_image_small')\n\n\nclass ReportBomStructure(models.AbstractModel):\n _inherit = 'report.mrp.report_bom_structure'\n\n product_id = fields.Many2one('product.product', 'Product D')\n\n def _get_bom(self, bom_id=False, product_id=False, line_qty=False, line_id=False, level=False):\n bom = self.env['mrp.bom'].browse(bom_id)\n bom_quantity = line_qty\n if line_id:\n current_line = self.env['mrp.bom.line'].browse(int(line_id))\n bom_quantity = current_line.product_uom_id._compute_quantity(line_qty, bom.product_uom_id)\n # Display bom components for current selected product variant\n if product_id:\n product = self.env['product.product'].browse(int(product_id))\n else:\n product = bom.product_id or bom.product_tmpl_id.product_variant_id\n if product:\n attachments = self.env['mrp.document'].search(['|', '&', ('res_model', '=', 'product.product'),\n ('res_id', '=', product.id), '&', ('res_model', '=', 'product.template'), ('res_id', '=', product.product_tmpl_id.id)])\n else:\n product = bom.product_tmpl_id\n attachments = self.env['mrp.document'].search([('res_model', '=', 'product.template'), ('res_id', '=', product.id)])\n if bom.product_qty != 0.0:\n operations = self._get_operation_line(bom.routing_id, float_round(bom_quantity / bom.product_qty, precision_rounding=1, rounding_method='UP'), 0)\n lines = {\n 'bom': bom,\n 'bom_qty': bom_quantity,\n 'bom_prod_name': product.name,\n 'currency': self.env.user.company_id.currency_id,\n 'product': product,\n 'code': bom and self._get_bom_reference(bom) or '',\n 'price': product.uom_id._compute_price(product.standard_price, bom.product_uom_id) * bom_quantity,\n 'total': sum([op['total'] for op in operations]),\n 'level': level or 0,\n 'operations': operations,\n 'operations_cost': sum([op['total'] for op in operations]),\n 'attachments': attachments,\n 'operations_time': sum([op['duration_expected'] for op in operations]),\n 'image': product.image_small,\n 'qty_available': product.qty_available,\n 'product_qty': bom.product_qty,\n 'stock_value': round(product.qty_available) * round(product.standard_price),\n 'item_code': product.barcode,\n 'link': product.id,\n }\n components, total, total_svalue = self._get_bom_lines(bom, bom_quantity, product, line_id, level)\n lines['components'] = components\n lines['total'] += total\n lines['total_svalue'] = total_svalue\n lines['sorting_data'] = self._sorting_data(components, lines.get('bom_qty'), lines.get('qty_available'))\n return lines\n return None\n\n def _get_bom_lines(self, bom, bom_quantity, product, line_id, level):\n components = []\n total = 0\n for line in bom.bom_line_ids:\n line_quantity = (bom_quantity / (bom.product_qty or 1.0)) * line.product_qty\n if line._skip_bom_line(product):\n continue\n price = line.product_id.uom_id._compute_price(line.product_id.standard_price, line.product_uom_id) * line_quantity\n if line.child_bom_id:\n factor = line.product_uom_id._compute_quantity(line_quantity, line.child_bom_id.product_uom_id) / line.child_bom_id.product_qty\n sub_total = self._get_price(line.child_bom_id, factor, line.product_id)\n else:\n sub_total = price\n sub_total = self.env.user.company_id.currency_id.round(sub_total)\n components.append({\n 'prod_id': line.product_id.id,\n 'prod_name': line.product_id.name,\n 'code': line.child_bom_id and self._get_bom_reference(line.child_bom_id) or '',\n 'prod_qty': line_quantity,\n 'prod_uom': line.product_uom_id.name,\n 'prod_cost': self.env.user.company_id.currency_id.round(price),\n 'parent_id': bom.id,\n 'line_id': line.id,\n 'level': level or 0,\n 'total': sub_total,\n 'child_bom': line.child_bom_id.id,\n 'child_bom_data': self._get_bom(bom_id=line.child_bom_id.id, product_id=line.child_bom_id.product_id.id),\n 'phantom_bom': line.child_bom_id and line.child_bom_id.type == 'phantom' or False,\n 'attachments': self.env['mrp.document'].search(['|', '&',\n ('res_model', '=', 'product.product'), ('res_id', '=', line.product_id.id), '&', ('res_model', '=', 'product.template'), ('res_id', '=', line.product_id.product_tmpl_id.id)]),\n 'image': line.product_id.image_small,\n 'qty_available': line.product_id.qty_available,\n 'prod_price': line.product_id.standard_price,\n 'product_qty': line.product_qty,\n 'stock_value': line.product_id.qty_available * line.product_id.standard_price,\n 'item_code': line.product_id.barcode,\n 'link': line.product_id.id,\n 'parent_qty': bom.product_tmpl_id.qty_available,\n 'get_sap': line.product_id.product_tmpl_id.restock_type,\n 'action_ind': 0,\n 'parent_con': 0,\n })\n total += sub_total\n components_stock_value = sum([component.get('stock_value') for component in components])\n \n return components, total, components_stock_value,\n\n def _build_data(self, components, arr=[], level=0):\n level += 1\n list_bom = arr\n if isinstance(components, dict):\n components = components.get('components')\n for item in components:\n list_bom.append({\n 'level': level, \n 'name': item[\"prod_name\"], \n 'child_bom':item[\"child_bom\"], \n 'parent_id': item['parent_id'],\n 'image_id': item['image'],\n 'link': item['link'],\n 'product_qty': item['product_qty'],\n 'prod_qty': item['prod_qty'],\n 'qty_available': item['qty_available'],\n 'prod_uom': item['prod_uom'],\n 'prod_price': item['prod_price'],\n 'stock_value': item['stock_value'],\n 'total': item['total'],\n 'parent_qty': item['parent_qty'],\n 'get_sap': item['get_sap'],\n 'action_ind': item['action_ind'],\n 'parent_con': item['parent_con'],\n })\n if item[\"child_bom_data\"]:\n self._build_data(item[\"child_bom_data\"], list_bom, level)\n\n return list_bom\n\n def _get_parent(self, data, parent_id):\n for d in range(len(data)):\n if data[d][\"child_bom\"] == parent_id:\n return data[d]\n\n def _sorting_data(self, components, bom_qty, qty_available):\n data = self._build_data(components, arr = [])\n data.sort(key=lambda key: key.get('level'))\n tmpParentId = data[0][\"parent_id\"]\n arr = []\n obj = {'name': None, 'level': None, 'child': [], 'par_prod_qty': None,}\n arrParent = []\n for d in range(len(data)):\n # level1 = data[d]['product_qty'] * (bom_qty - qty_available) \n if data[d]['level']:\n data[d]['prod_qty'] = data[d]['product_qty'] * bom_qty\n data[d]['total'] = data[d]['prod_qty'] * data[d]['prod_price']\n data[d]['action_ind'] = data[d]['qty_available'] - data[d]['prod_qty'] \n if data[d][\"child_bom\"]:\n arrParent.append(data[d])\n if tmpParentId == data[d][\"parent_id\"]:\n obj[\"child\"].append(data[d])\n else:\n if data[d-1][\"level\"] != 1:\n parentData = self._get_parent(arrParent, tmpParentId)\n if parentData is not None:\n obj[\"name\"] = parentData[\"name\"]\n obj[\"level\"] = data[d-1][\"level\"]\n obj[\"par_prod_qty\"] = parentData[\"prod_qty\"]\n arr.append(obj)\n obj = {'child': []}\n obj[\"child\"].append(data[d])\n tmpParentId = data[d][\"parent_id\"]\n if d + 1 == len(data):\n parentData = self._get_parent(arrParent, tmpParentId)\n if parentData is not None:\n obj[\"name\"] = parentData[\"name\"]\n obj[\"level\"] = data[d-1][\"level\"]\n obj[\"par_prod_qty\"] = parentData[\"prod_qty\"]\n arr.append(obj) \n return arr\n \n \n","sub_path":"models/mrp_boms.py","file_name":"mrp_boms.py","file_ext":"py","file_size_in_byte":9603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"384877490","text":"from parserCommon import parse_inline, parse_inline_markdown\n\n\ndef load():\n front = []\n end = [footnote]\n return (front, end)\n\n\ndef load_markdown():\n front = []\n end = [footnote_markdown]\n return (front, end)\n\n\ndef footnote(acc):\n if 'footnote' not in acc:\n return ''\n else:\n parsed = '
    \\n'\n for n in xrange(len(acc['footnote'])):\n\n parsed += '
  1. %s
  2. \\n' % (\n n + 1, parse_inline(acc['footnote'][n], acc), n + 1)\n parsed += '
\\n'\n return parsed\n\n\ndef footnote_markdown(acc):\n if 'footnote' not in acc:\n return ''\n else:\n parsed = ''\n for n in xrange(len(acc['footnote'])):\n parsed += '[^%d]: %s\\n' % (n + 1,\n parse_inline_markdown(acc['footnote'][n], acc))\n return parsed\n","sub_path":"wiki/wikiPostProcessors.py","file_name":"wikiPostProcessors.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"103722510","text":"\"\"\"\nGiven an array where elements are sorted in ascending order,\nconvert it to a height balanced BST.\n\nSource: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/#/description\n\"\"\"\n\n\n# Constructor for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef traverse(rootnode):\n thislevel = [rootnode]\n while thislevel:\n nextlevel = list()\n for n in thislevel:\n print(n.val)\n if n.left: nextlevel.append(n.left)\n if n.right: nextlevel.append(n.right)\n print(\" \")\n thislevel = nextlevel\n\n\n# DO NOT CHANGE THIS CLASS\nclass Solution(object):\n def sortedArrayToBST(self, nums):\n \t#YOUR CODE GOES HERE\n if len(nums) ==0:\n return None\n \n root = TreeNode(None)\n len_list = len(nums)\n start_index = int(len_list/2)\n root.val = TreeNode(nums[start_index])\n num1 = nums[:start_index]\n num2 = nums[start_index+1:]\n root.left = self.sortedArrayToBST(num1)\n root.right = self.sortedArrayToBST(num2)\n\n return root \n \t##\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n\n#Please come up with your own testcases below:\nif __name__ == \"__main__\":\n test = [1,2,3,4,5,6,7]\n x = Solution()\n print(\"The list of arrays are\", test)\n print (\"The tree structure is:\")\n binary_search_tree = x.sortedArrayToBST(test)\n traverse(binary_search_tree)\n","sub_path":"problem_6/Fellow Codes Go Here/Lily_Xu.py","file_name":"Lily_Xu.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"652486274","text":"import json\nimport shared\n\nimport projective\nimport field\nimport affine\nimport jacobi\n\n\ndef _read_sage_params_from_file(file_path):\n with open(file_path) as f:\n return json.load(f)\n\n\ndef _read_sage_params_from_stdin():\n return json.loads(input())\n\n\ndef set_curve_params(args):\n if args.stdin:\n raw_json = _read_sage_params_from_stdin()\n else:\n raw_json = _read_sage_params_from_file(args.path)\n\n a, b, *_ = raw_json[\"invariants\"]\n base_point = raw_json[\"basePoint\"]\n field_order = raw_json[\"fieldOrder\"]\n curve_order = raw_json[\"curveOrder\"]\n curve_params = shared.CurveParams(\n base_point=shared.CurveBasePoint(*base_point),\n a=a,\n b=b,\n field_order=field_order,\n curve_order=curve_order,\n )\n projective.set_curve_params(curve_params)\n affine.set_curve_params(curve_params)\n jacobi.set_curve_params(curve_params)\n field.set_modulus(field_order)\n return curve_params, int(raw_json[\"bitLength\"])\n","sub_path":"list_5/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8918127","text":"\nimport numpy as np\nimport visTools.src.aux.convolutions.cython_convs as cc\n\n# In[7]:\n\n\ndef conv_octave_cython(im,g,stride=1,C=3):\n im = im[:,np.newaxis,:,:]\n\n N,_,H,W = im.shape\n _,h,w = g.shape\n\n h_pad = int((H*(stride-1)-stride+h)/2)\n w_pad = int((W*(stride-1)-stride+w)/2)\n\n ii = np.zeros((N,H*W))\n for t,i in enumerate(im):\n img = i[np.newaxis,:,:]\n cols = cc.im2col_cython(img, h, w, h_pad,stride)\n gg = g[t].flatten()\n ii[t]=np.matmul(cols.T,gg)\n return ii.reshape(-1,H,W)\n","sub_path":"visTools/src/aux/convolutions/convolution.py","file_name":"convolution.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"196721925","text":"# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport paddle.fluid as fluid\nimport math\n\nuser_profile_dim = 65\ndense_feature_dim = 3\n\ndef ctr_deepfm_dataset(dense_feature, context_feature, context_feature_fm, label,\n embedding_size, sparse_feature_dim):\n def dense_fm_layer(input, emb_dict_size, factor_size, fm_param_attr):\n\n first_order = fluid.layers.fc(input=input, size=1)\n emb_table = fluid.layers.create_parameter(shape=[emb_dict_size, factor_size],\n dtype='float32', attr=fm_param_attr)\n\n input_mul_factor = fluid.layers.matmul(input, emb_table)\n input_mul_factor_square = fluid.layers.square(input_mul_factor)\n input_square = fluid.layers.square(input)\n factor_square = fluid.layers.square(emb_table)\n input_square_mul_factor_square = fluid.layers.matmul(input_square, factor_square)\n\n second_order = 0.5 * (input_mul_factor_square - input_square_mul_factor_square)\n return first_order, second_order\n\n\n dense_fm_param_attr = fluid.param_attr.ParamAttr(name=\"DenseFeatFactors\",\n initializer=fluid.initializer.Normal(\n scale=1 / math.sqrt(dense_feature_dim)))\n dense_fm_first, dense_fm_second = dense_fm_layer(\n dense_feature, dense_feature_dim, 16, dense_fm_param_attr)\n\n\n def sparse_fm_layer(input, emb_dict_size, factor_size, fm_param_attr):\n\n first_embeddings = fluid.layers.embedding(\n input=input, dtype='float32', size=[emb_dict_size, 1], is_sparse=True)\n first_order = fluid.layers.sequence_pool(input=first_embeddings, pool_type='sum')\n\n nonzero_embeddings = fluid.layers.embedding(\n input=input, dtype='float32', size=[emb_dict_size, factor_size],\n param_attr=fm_param_attr, is_sparse=True)\n summed_features_emb = fluid.layers.sequence_pool(input=nonzero_embeddings, pool_type='sum')\n summed_features_emb_square = fluid.layers.square(summed_features_emb)\n\n squared_features_emb = fluid.layers.square(nonzero_embeddings)\n squared_sum_features_emb = fluid.layers.sequence_pool(\n input=squared_features_emb, pool_type='sum')\n\n second_order = 0.5 * (summed_features_emb_square - squared_sum_features_emb)\n return first_order, second_order\n\n sparse_fm_param_attr = fluid.param_attr.ParamAttr(name=\"SparseFeatFactors\",\n initializer=fluid.initializer.Normal(\n scale=1 / math.sqrt(sparse_feature_dim)))\n\n #data = fluid.layers.data(name='ids', shape=[1], dtype='float32')\n sparse_fm_first, sparse_fm_second = sparse_fm_layer(\n context_feature_fm, sparse_feature_dim, 16, sparse_fm_param_attr)\n\n def embedding_layer(input):\n return fluid.layers.embedding(\n input=input,\n is_sparse=True,\n # you need to patch https://github.com/PaddlePaddle/Paddle/pull/14190\n # if you want to set is_distributed to True\n is_distributed=False,\n size=[sparse_feature_dim, embedding_size],\n param_attr=fluid.ParamAttr(name=\"SparseFeatFactors\",\n initializer=fluid.initializer.Uniform()))\n\n sparse_embed_seq = list(map(embedding_layer, context_feature))\n\n concated_ori = fluid.layers.concat(sparse_embed_seq + [dense_feature], axis=1)\n concated = fluid.layers.batch_norm(input=concated_ori, name=\"bn\", epsilon=1e-4)\n\n deep = deep_net(concated)\n\n predict = fluid.layers.fc(input=[deep, sparse_fm_first, sparse_fm_second, dense_fm_first, dense_fm_second], size=2, act=\"softmax\",\n param_attr=fluid.ParamAttr(initializer=fluid.initializer.Normal(\n scale=1 / math.sqrt(deep.shape[1])), learning_rate=0.01))\n\n #similarity_norm = fluid.layers.sigmoid(fluid.layers.clip(predict, min=-15.0, max=15.0), name=\"similarity_norm\")\n\n cost = fluid.layers.cross_entropy(input=predict, label=label)\n\n avg_cost = fluid.layers.reduce_sum(cost)\n accuracy = fluid.layers.accuracy(input=predict, label=label)\n auc_var, batch_auc_var, auc_states = \\\n fluid.layers.auc(input=predict, label=label, num_thresholds=2 ** 12, slide_steps=20)\n return avg_cost, auc_var, batch_auc_var, accuracy, predict\n\n\ndef deep_net(concated, lr_x=0.0001):\n fc_layers_input = [concated]\n fc_layers_size = [400, 400, 400]\n fc_layers_act = [\"relu\"] * (len(fc_layers_size))\n\n for i in range(len(fc_layers_size)):\n fc = fluid.layers.fc(\n input=fc_layers_input[-1],\n size=fc_layers_size[i],\n act=fc_layers_act[i],\n param_attr=fluid.ParamAttr(learning_rate=lr_x * 0.5))\n\n fc_layers_input.append(fc)\n #w_res = fluid.layers.create_parameter(shape=[353, 16], dtype='float32', name=\"w_res\")\n #high_path = fluid.layers.matmul(concated, w_res)\n\n #return fluid.layers.elementwise_add(high_path, fc_layers_input[-1])\n return fc_layers_input[-1]","sub_path":"PaddleRec/ctr/Paddle_baseline_KDD2019/networks/network_confv6.py","file_name":"network_confv6.py","file_ext":"py","file_size_in_byte":5735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"617309908","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/cgecore/blaster/blaster.py\n# Compiled at: 2020-04-01 11:09:31\n# Size of source mod 2**32: 28018 bytes\nfrom __future__ import division\nimport sys, os, time, random, re, subprocess\nfrom Bio.Blast import NCBIXML\nfrom Bio import SeqIO\nimport collections\n\nclass Blaster:\n\n def __init__(self, inputfile, databases, db_path, out_path='', min_cov=0.6, threshold=0.9, blast='blastn', cut_off=True, max_target_seqs=50000, reuse_results=False, allowed_overlap=0):\n min_cov = 100 * float(min_cov)\n threshold = 100 * float(threshold)\n self.gene_align_query = dict()\n self.gene_align_homo = dict()\n self.gene_align_sbjct = dict()\n self.results = dict()\n self.results['excluded'] = dict()\n for db in databases:\n db_file = '%s/%s.fsa' % (db_path, db)\n tmp_out_path = '%s/tmp' % out_path\n out_file = '%s/out_%s.xml' % (tmp_out_path, db)\n os.makedirs(tmp_out_path, exist_ok=True)\n os.chmod(tmp_out_path, 509)\n if os.path.isfile(out_file) and os.access(out_file, os.R_OK) and reuse_results:\n print('Found ' + out_file + ' skipping DB.')\n out, err = ('', '')\n else:\n cmd = \"%s -subject %s -query %s -out %s -outfmt '5' -perc_identity %s -max_target_seqs %s -dust 'no'\" % (\n blast, db_file, inputfile,\n out_file, threshold, max_target_seqs)\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = process.communicate()\n try:\n result_handle = open(out_file, 'r')\n except IOError:\n sys.exit('Error: BLAST did not run as expected. The expected output file, {}, did not exist.\\nBLAST finished with the following response:\\n{}\\n{}'.format(os.path.abspath(out_file), out.decode('utf-8'), err.decode('utf-8')))\n\n if os.stat(out_file).st_size == 0:\n sys.exit('Error: BLAST did not run as expected. The output file {} was empty.\\nBLAST finished with the following response:\\n{}\\n{}'.format(os.path.abspath(out_file), out.decode('utf-8'), err.decode('utf-8')))\n blast_records = NCBIXML.parse(result_handle)\n gene_results = dict()\n best_hsp = dict()\n gene_split = collections.defaultdict(dict)\n self.gene_align_query[db] = dict()\n self.gene_align_homo[db] = dict()\n self.gene_align_sbjct[db] = dict()\n for blast_record in blast_records:\n blast_record.alignments.sort(key=lambda align: max(int(hsp.identities) for hsp in align.hsps), reverse=True)\n query = blast_record.query\n for alignment in blast_record.alignments:\n best_e_value = 1\n best_bit = 0\n start_hsp = 0\n end_hsp = 0\n for hsp in alignment.hsps:\n if hsp.expect < best_e_value or hsp.bits > best_bit:\n tmp = alignment.title.split(' ')\n sbjct_header = tmp[1]\n print('Found: {}'.format(sbjct_header))\n bit = hsp.bits\n sbjct_length = alignment.length\n sbjct_start = hsp.sbjct_start\n sbjct_end = hsp.sbjct_end\n gaps = hsp.gaps\n query_string = str(hsp.query)\n homo_string = str(hsp.match)\n sbjct_string = str(hsp.sbjct)\n contig_name = query.replace('>', '')\n query_start = hsp.query_start\n query_end = hsp.query_end\n HSP_length = len(query_string)\n perc_ident = int(hsp.identities) / float(HSP_length) * 100\n strand = 0\n coverage = (int(HSP_length) - int(gaps)) / float(sbjct_length)\n perc_coverage = (int(HSP_length) - int(gaps)) / float(sbjct_length) * 100\n cal_score = perc_ident * coverage\n hit_id = '%s:%s..%s:%s:%f' % (\n contig_name, query_start, query_end,\n sbjct_header, cal_score)\n if sbjct_start > sbjct_end:\n tmp = sbjct_start\n sbjct_start = sbjct_end\n sbjct_end = tmp\n query_string = self.reversecomplement(query_string)\n homo_string = homo_string[::-1]\n sbjct_string = self.reversecomplement(sbjct_string)\n strand = 1\n if cut_off and perc_coverage > 20 or cut_off is False:\n best_hsp = {'evalue': hsp.expect, \n 'sbjct_header': sbjct_header, \n 'bit': bit, \n 'perc_ident': perc_ident, \n 'sbjct_length': sbjct_length, \n 'sbjct_start': sbjct_start, \n 'sbjct_end': sbjct_end, \n 'gaps': gaps, \n 'query_string': query_string, \n 'homo_string': homo_string, \n 'sbjct_string': sbjct_string, \n 'contig_name': contig_name, \n 'query_start': query_start, \n 'query_end': query_end, \n 'HSP_length': HSP_length, \n 'coverage': coverage, \n 'cal_score': cal_score, \n 'hit_id': hit_id, \n 'strand': strand, \n 'perc_coverage': perc_coverage}\n if best_hsp:\n save = 1\n if gene_results:\n tmp_gene_split = gene_split\n tmp_results = gene_results\n save, gene_split, gene_results = self.compare_results(save, best_hsp, tmp_results, tmp_gene_split, allowed_overlap)\n if save == 1:\n print('Saving: {}'.format(hit_id))\n gene_results[hit_id] = best_hsp\n\n result_handle.close()\n keys = list(gene_results.keys())\n for hit_id in keys:\n hit = gene_results[hit_id]\n perc_coverage = hit['perc_coverage']\n if hit['sbjct_header'] in gene_split and len(gene_split[hit['sbjct_header']]) > 1:\n new_length = self.calculate_new_length(gene_split, gene_results, hit)\n hit['split_length'] = new_length\n perc_coverage = new_length / float(hit['sbjct_length']) * 100\n if perc_coverage >= min_cov:\n if hit['coverage'] == 1:\n self.gene_align_query[db][hit_id] = hit['query_string']\n self.gene_align_homo[db][hit_id] = hit['homo_string']\n self.gene_align_sbjct[db][hit_id] = hit['sbjct_string']\n elif hit['coverage'] != 1:\n for seq_record in SeqIO.parse(db_file, 'fasta'):\n if seq_record.description.replace(' ', '') == hit['sbjct_header'].replace(' ', ''):\n start_seq = str(seq_record.seq)[:int(hit['sbjct_start']) - 1]\n end_seq = str(seq_record.seq)[int(hit['sbjct_end']):]\n self.gene_align_sbjct[db][hit_id] = start_seq + hit['sbjct_string'] + end_seq\n break\n\n contig = ''\n for seq_record in SeqIO.parse(inputfile, 'fasta'):\n if seq_record.description.replace(' ', '') == hit['contig_name'].replace(' ', ''):\n contig = str(seq_record.seq)\n break\n\n query_seq, homo_seq = self.get_query_align(hit, contig)\n self.gene_align_query[db][hit_id] = query_seq\n self.gene_align_homo[db][hit_id] = homo_seq\n else:\n del gene_results[hit_id]\n if hit['sbjct_header'] in gene_split:\n del gene_split[hit['sbjct_header']]\n\n if gene_results:\n self.results[db] = gene_results\n else:\n self.results[db] = 'No hit found'\n\n @staticmethod\n def reversecomplement(seq):\n trans = str.maketrans('ATGC', 'TACG')\n return seq.translate(trans)[::-1]\n\n @staticmethod\n def compare_results(save, best_hsp, tmp_results, tmp_gene_split, allowed_overlap):\n \"\"\"\n Function for comparing hits and saving only the best hit\n \"\"\"\n hit_id = best_hsp['hit_id']\n new_start_query = best_hsp['query_start']\n new_end_query = best_hsp['query_end']\n new_start_sbjct = int(best_hsp['sbjct_start'])\n new_end_sbjct = int(best_hsp['sbjct_end'])\n new_score = best_hsp['cal_score']\n new_db_hit = best_hsp['sbjct_header']\n new_contig = best_hsp['contig_name']\n new_HSP = best_hsp['HSP_length']\n keys = list(tmp_results.keys())\n for hit in keys:\n hit_data = tmp_results[hit]\n old_start_query = hit_data['query_start']\n old_end_query = hit_data['query_end']\n old_start_sbjct = int(hit_data['sbjct_start'])\n old_end_sbjct = int(hit_data['sbjct_end'])\n old_score = hit_data['cal_score']\n old_db_hit = hit_data['sbjct_header']\n old_contig = hit_data['contig_name']\n old_HSP = hit_data['HSP_length']\n remove_old = 0\n if new_db_hit == old_db_hit:\n if old_contig != new_contig and new_db_hit in tmp_gene_split and hit_id not in tmp_gene_split[new_db_hit]:\n tmp_gene_split[new_db_hit][hit_id] = 1\n elif new_start_sbjct < old_start_sbjct or new_end_sbjct > old_end_sbjct:\n tmp_gene_split[old_db_hit][hit_id] = 1\n if hit not in tmp_gene_split[old_db_hit]:\n tmp_gene_split[old_db_hit][hit] = 1\n if new_contig == old_contig:\n pass\n print('Same contig: {} == {}'.format(new_contig, old_contig))\n print('\\t{} vs {}'.format(new_db_hit, old_db_hit))\n hit_union_length = max(old_end_query, new_end_query) - min(old_start_query, new_start_query)\n hit_lengths_sum = old_end_query - old_start_query + (new_end_query - new_start_query)\n overlap_len = hit_lengths_sum - hit_union_length\n if overlap_len < allowed_overlap:\n print('\\tignore overlap ({}): {}'.format(overlap_len, new_db_hit))\n continue\n print('\\toverlap found ({}): {}'.format(overlap_len, new_db_hit))\n if old_start_query == new_start_query and old_end_query == new_end_query:\n if best_hsp['perc_ident'] > hit_data['perc_ident']:\n remove_old = 1\n if new_db_hit in tmp_gene_split and hit_id not in tmp_gene_split[new_db_hit]:\n tmp_gene_split[new_db_hit][hit_id] = 1\n else:\n if best_hsp['perc_ident'] == hit_data['perc_ident']:\n if new_db_hit in tmp_gene_split and hit_id not in tmp_gene_split[new_db_hit]:\n tmp_gene_split[new_db_hit][hit_id] = 1\n else:\n save = 0\n if new_db_hit in tmp_gene_split and hit_id in tmp_gene_split[new_db_hit]:\n del tmp_gene_split[new_db_hit][hit_id]\n break\n elif hit_union_length <= hit_lengths_sum:\n print('\\t{} <= {}'.format(hit_union_length, hit_lengths_sum))\n print('\\t\\tScores: {} cmp {}'.format(new_score, old_score))\n if new_score > old_score:\n remove_old = 1\n if new_db_hit in tmp_gene_split and hit_id not in tmp_gene_split[new_db_hit]:\n tmp_gene_split[new_db_hit][hit_id] = 1\n if new_score == old_score:\n if int(best_hsp['perc_coverage']) == int(hit_data['perc_coverage']) and new_HSP > old_HSP:\n remove_old = 1\n else:\n if int(best_hsp['perc_coverage']) == int(hit_data['perc_coverage']) and old_HSP > new_HSP:\n save = 0\n elif int(best_hsp['perc_coverage']) == int(hit_data['perc_coverage']) and old_HSP == new_HSP:\n pass\n if new_db_hit in tmp_gene_split and hit_id not in tmp_gene_split[new_db_hit]:\n tmp_gene_split[new_db_hit][hit_id] = 1\n else:\n if new_db_hit in tmp_gene_split and hit_id in tmp_gene_split[new_db_hit]:\n del tmp_gene_split[new_db_hit][hit_id]\n save = 0\n break\n if remove_old == 1:\n del tmp_results[hit]\n if old_db_hit in tmp_gene_split and hit in tmp_gene_split[old_db_hit]:\n del tmp_gene_split[old_db_hit][hit]\n\n return (\n save, tmp_gene_split, tmp_results)\n\n @staticmethod\n def calculate_new_length(gene_split, gene_results, hit):\n \"\"\"\n Function for calcualting new length if the gene is split on\n several contigs\n \"\"\"\n first = 1\n for split in gene_split[hit['sbjct_header']]:\n new_start = int(gene_results[split]['sbjct_start'])\n new_end = int(gene_results[split]['sbjct_end'])\n if first == 1:\n new_length = int(gene_results[split]['HSP_length'])\n old_start = new_start\n old_end = new_end\n first = 0\n continue\n if new_start < old_start:\n new_length = new_length + (old_start - new_start)\n old_start = new_start\n if new_end > old_end:\n new_length = new_length + (new_end - old_end)\n old_end = new_end\n\n return new_length\n\n @staticmethod\n def get_query_align(hit, contig):\n \"\"\"\n Function for extracting extra seqeunce data to the query\n alignment if the full reference length are not covered\n \"\"\"\n query_seq = hit['query_string']\n homo_seq = hit['homo_string']\n sbjct_start = int(hit['sbjct_start'])\n sbjct_end = int(hit['sbjct_end'])\n query_start = int(hit['query_start'])\n query_end = int(hit['query_end'])\n length = int(hit['sbjct_length'])\n if sbjct_start != 1:\n missing = sbjct_start - 1\n if query_start >= missing and hit['strand'] != 1 or hit['strand'] == 1 and missing <= len(contig) - query_end:\n if hit['strand'] == 1:\n start_pos = query_end\n end_pos = query_end + missing\n chars = contig[start_pos:end_pos]\n chars = Blaster.reversecomplement(chars)\n else:\n start_pos = query_start - missing - 1\n end_pos = query_start - 1\n chars = contig[start_pos:end_pos]\n query_seq = chars + str(query_seq)\n else:\n if hit['strand'] == 1:\n if query_end == len(contig):\n query_seq = '-' * missing + str(query_seq)\n else:\n start_pos = query_end\n chars = contig[start_pos:]\n chars = Blaster.reversecomplement(chars)\n query_seq = '-' * (missing - len(chars)) + chars + str(query_seq)\n else:\n if query_start < 3:\n query_seq = '-' * missing + str(query_seq)\n else:\n end_pos = query_start - 2\n chars = contig[0:end_pos]\n query_seq = '-' * (missing - len(chars)) + chars + str(query_seq)\n spaces = ' ' * missing\n homo_seq = str(spaces) + str(homo_seq)\n if sbjct_end < length:\n missing = length - sbjct_end\n if missing <= len(contig) - query_end and hit['strand'] != 1 or hit['strand'] == 1 and query_start >= missing:\n if hit['strand'] == 1:\n start_pos = query_start - missing - 1\n end_pos = query_start - 1\n chars = contig[start_pos:end_pos]\n chars = Blaster.reversecomplement(chars)\n else:\n start_pos = query_end\n end_pos = query_end + missing\n chars = contig[start_pos:end_pos]\n query_seq = query_seq + chars\n else:\n if hit['strand'] == 1:\n if query_start < 3:\n query_seq = query_seq + '-' * missing\n else:\n end_pos = query_start - 2\n chars = contig[0:end_pos]\n chars = Blaster.reversecomplement(chars)\n query_seq = query_seq + chars + '-' * (missing - len(chars))\n else:\n if query_end == len(contig):\n query_seq = query_seq + '-' * missing\n else:\n start_pos = query_end\n chars = contig[start_pos:]\n query_seq = query_seq + chars + '-' * (missing - len(chars))\n spaces = ' ' * int(missing)\n homo_seq = str(homo_seq) + str(spaces)\n return (\n query_seq, homo_seq)","sub_path":"pycfiles/cgen-2020.1.tar/blaster.cpython-35.py","file_name":"blaster.cpython-35.py","file_ext":"py","file_size_in_byte":18842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"61014039","text":"# Copyright (C) 2016 Cuckoo Foundation.\n# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org\n# See the file 'docs/LICENSE' for copying permission.\nimport types\nimport os.path\nimport shlex\nimport requests\nfrom datetime import datetime\n# from urlparse import urlparse\nimport time\nimport warnings\nimport socket\nimport sys\n# from types import ListType\n# from bsddb.dbtables import _data\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n import pymisp\nfrom pymisp.tools import GenericObjectGenerator\nfrom pymisp.mispevent import MISPObjectReference\n# from cuckoo.common.abstracts import Report\n# from cuckoo.common.exceptions import CuckooProcessingError\n\nclass MISP(Report):\n \"\"\"Enrich MISP with Cuckoo results.\"\"\"\n \n def get_misp_template(self,_type):\n try:\n _template_id = [x['ObjectTemplate']['id'] for x in self.misp.get_object_templates_list() if x['ObjectTemplate']['name'] == _type]\n except IndexError:\n valid_types = \", \".join([x['ObjectTemplate']['name'] for x in pymisp.get_object_templates_list()])\n print (\"Template for type %s not found! Valid types are: %s\" % (type, valid_types))\n exit()\n return _template_id[0] \n\n def create_cuckoo_file(self, _f, _type):\n _object = GenericObjectGenerator(_type)\n \n _object.add_attribute(\"md5\", value=_f[\"md5\"])\n _object.add_attribute(\"sha256\", value=_f[\"sha256\"])\n _object.add_attribute(\"sha512\", value=_f[\"sha512\"])\n _object.add_attribute(\"ssdeep\", value=_f[\"ssdeep\"])\n _object.add_attribute(\"filename\", value=_f[\"name\"])\n _object.add_attribute(\"mimetype\", value=_f[\"type\"])\n _object.add_attribute(\"size-in-bytes\", value=_f[\"size\"])\n return [_object]\n \n def save_url_content(selfself,_url, _sha256):\n\n url_content_folder='/home/admin1/cuckoo/malware_binaries'\n try:\n r = requests.get(_url, timeout=30)\n _type = r.headers['content-type']\n pu = urlparse(_url)\n pfn1 = '%s.%s'%(pu.netloc,pu.path)\n pfn = pfn1.replace('/','--')\n fn = 'MALWARE_FROM_%s.%s'%(pfn,_sha256)\n \n if _type == 'application/octet-stream':\n with open(os.path.join(url_content_folder, fn), 'wb') as oo:\n oo.write(r.content)\n# print('binary')\n elif 'text/html' in _type:\n with open(os.path.join(url_content_folder, fn), 'w') as oo:\n oo.write(r.text)\n else:\n print('------------------%s not treated'%_type)\n# print(r.headers['content-type'])\n rdict = {'_type': 'returns %s'%_type,'_timestamp':str(datetime.utcnow().replace(microsecond=0))}\n return rdict\n # except requests.exceptions.Timeout as e:\n # print(e)\n # # Maybe set up for a retry, or continue in a retry loop\n # except requests.exceptions.TooManyRedirects as e:\n # print(e)\n # Tell the user their URL was bad and try a different one\n except requests.exceptions.RequestException as e:\n print('--URL %s not accessible:\\n %s'%(_url,e))\n return None\n\n def add_url(self, _f, _fuuid,_sha256):\n\n obj_list=[]\n misp_type = 'url'\n _obj = GenericObjectGenerator(misp_type)\n full_url = \"%s://%s%s\" % (_f[\"protocol\"], _f[\"host\"], _f[\"uri\"])\n _obj.add_attribute(\"url\", value=full_url)\n _obj.add_attribute(\"host\", value=_f['host'])\n _obj.add_attribute(\"query_string\", value=_f['request'])\n _obj.add_attribute(\"resource_path\", value=_f['uri'])\n _obj.add_reference(referenced_uuid=_fuuid, relationship_type=\"exfiltrates_to\")\n \n rurl=self.save_url_content(full_url, _sha256)\n if rurl is not None:\n _obj.add_attribute(\"last-seen\", value=rurl['_timestamp'])\n _obj.add_attribute(\"text\", value=rurl['_type'])\n obj_list.append(_obj)\n \n return(obj_list)\n\n def complete_dom_ip(self,_d,_i):\n whitelist = [\n \"www.msftncsi.com\", \"dns.msftncsi.com\",\n \"teredo.ipv6.microsoft.com\", \"time.windows.com\",\"spynet2.microsoft.com\",\n \"192.168.56.1\",\"224.0.0.252\", \"239.255.255.250\", \"192.168.56.255\"\n ] \n # First check if the domain or ip are whitelisted\n if all(y not in whitelist for y in [_d,_i]):\n# print(_d, _i)\n # Now resolve domain name if ip is empty\n try:\n if _i == '' and _d != '':\n _i = socket.gethostbyname(_d)\n elif _i != '' and _d == '':\n _d = socket.gethostbyaddr(_i)\n except (socket.gaierror, socket.herror) as err:\n print('----- Nao resolveu %s - %s'%(_d,_i))\n return (_d,_i)\n else:\n# print('---Whitelisted: %s - %s'%(_d,_i))\n #whitelisted\n return (None, None)\n \n \n def add_protos(self, _f, _fuuid):\n objs_to_add = []\n# print(_f)\n d, i = self.complete_dom_ip('', _f['dst'])\n # If any d or i is whitelisted, complete_dom_ip returns None, None. Then, return empty list so no object is added\n if any(x is None for x in [d,i]):\n return objs_to_add\n if type(d) == tuple:\n d = d[0]\n p = _f['dport']\n# print(d,i,p)\n # if both ip and domain are non-empty, create domain_ip misptype\n if all(x != '' for x in [d,i]):\n misp_type = 'domain-ip'\n _obj = GenericObjectGenerator(misp_type)\n _obj.add_attribute(\"domain\", value=d)\n _obj.add_attribute(\"ip\", value=i)\n _obj.add_reference(referenced_uuid=_fuuid, relationship_type=\"communicates-with\")\n objs_to_add.append(_obj)\n # Adding only domain as attribute, as there is no object for only domain \n elif d != '' and i == '':\n event = self.misp.get_event(_evt_id)\n r = self.misp.add_named_attribute(event, 'domain', d)\n \n # Adding only ip as attribute, as there is no object for only ip\n elif d == '' and i != '':\n event = self.misp.get_event(_evt_id)\n r = self.misp.add_named_attribute(event, 'ip-dst', i)\n return objs_to_add\n# \n def add_domain_ip(self, _f, _fuuid,_evt_id):\n objs_to_add = []\n \n obj_list=[]\n for item in _f:\n d, i = self.complete_dom_ip(item['domain'], item['ip'])\n \n # If any d or i is whitelisted, complete_dom_ip returns None, None. Then, return empty list so no object is added\n if any(x is None for x in [d,i]):\n return objs_to_add\n \n print('tupleDI: %s - %s'%(d,i))\n # if both ip and domain are non-empty, create domain_ip misptype\n if all(x != '' for x in [d,i]):\n misp_type = 'domain-ip'\n _obj = GenericObjectGenerator(misp_type)\n _obj.add_attribute(\"domain\", value=d)\n _obj.add_attribute(\"ip\", value=i)\n _obj.add_reference(referenced_uuid=_fuuid, relationship_type=\"communicates-with\")\n objs_to_add.append(_obj)\n # Adding only domain as attribute, as there is no object for only domain \n elif d != '' and i == '':\n event = self.misp.get_event(_evt_id)\n r = self.misp.add_named_attribute(event, 'domain', d)\n \n # Adding only ip as attribute, as there is no object for only ip\n elif d == '' and i != '':\n event = self.misp.get_event(_evt_id)\n r = self.misp.add_named_attribute(event, 'ip-dst', i)\n return objs_to_add\n# \n # add list of objects to misp event\n def add_to_misp(self, e, o):\n for obj in o:\n# print('-----Adding:%s'%obj)\n tid = self.get_misp_template(obj['name'])\n r = self.misp.add_object(e, tid, obj)\n self.check_for_errors(r)\n\n for refs in obj.ObjectReference:\n q = self.misp.add_object_reference(refs)\n self.check_for_errors(q)\n\n def check_for_errors(self,_d):\n if 'errors' in _d.keys():\n print('Error: %s'%_d['errors'])\n sys.exit('error in adding to misp')\n \n elif 'Object' in _d.keys():\n _name = _d['Object']['name']\n _objid = _d['Object']['id']\n _evtid = _d['Object']['event_id']\n print(\"Successfully added object %s (%s) to event %s\"%(_name.upper(),_objid, _evtid ))\n elif 'ObjectReference' in _d.keys():\n _name = _d['ObjectReference']['relationship_type']\n _objid = _d['ObjectReference']['object_id']\n _refid = _d['ObjectReference']['referenced_id']\n _evtid = _d['ObjectReference']['event_id']\n print(\"Successfully added objref %s %s %s to event %s\"%( _name.upper(), _objid, _refid, _evtid ))\n\n def run(self, results):\n \"\"\"Submits results to MISP.\n @param results: Cuckoo results dict.\n \"\"\"\n #url = self.options.get(\"url\")\n #apikey = self.options.get(\"apikey\")\n #mode = shlex.split(self.options.get(\"mode\") or \"\")\n url = 'https://10.61.193.46'\n apikey = 'u9mh7YBo4CnDrk0nOLMhAwK1W9kpcLJqAF0zDGrw'\n mode = 'hashes'\n \n task=6\n obj_to_add=[]\n \n if not url or not apikey:\n raise CuckooProcessingError(\n \"Please configure the URL and API key for your MISP instance.\"\n )\n self.misp = pymisp.PyMISP(url, apikey, False, \"json\")\n \n cuckoo_task_id = results['info']['analysis_path'].rsplit('/',1)[1]\n cuckoo_file_sha256 = results['target']['file']['sha256']\n cuckoo_file_name = results['target']['file']['name']\n cuckoo_alternative_file_name = ''\n \n existing_reports = self.misp.search_all(cuckoo_file_sha256)\n# existing_reports = self.misp.search('value', cuckoo_file_sha256,'a')\n resp = existing_reports['response']\n# print(len(existing_reports))\n if len(resp) > 0:\n# print(existing_reports)\n for rep in resp:\n if 'Attribute' in rep['Event'].keys():\n for attr in rep['Event']['Attribute']:\n # OBS: If the file has the same hash byt different filenames, filename is not being stored yet. Need to find an object for that\n if attr['type'] == 'filename|sha256' and attr['value'].split('|',1)[1] == cuckoo_file_sha256:\n if attr['value'].split('|',1)[0] == cuckoo_file_name:\n _evt = rep['Event']['id']\n print('Event %s already contains file with the same name%s\\n'%(_evt, cuckoo_file_sha256))\n else:\n _evt = rep['Event']['id']\n cuckoo_alternative_file_name = attr['value'].split('|',1)[0]\n\n event = self.misp.get_event(_evt)\n r = self.misp.add_named_attribute(event, 'filename|sha256', '%s|%s'%(cuckoo_alternative_file_name, cuckoo_file_sha256))\n # TRY search instead of search_all with param = value OR filename|sha256 and search .\n # INVESTIGATE IF IT IS NECESSARY TO DO THE SAME TO SEARCH WITHIN OBJECTS\n\n\n return\n \n event = self.misp.new_event(\n# distribution=self.misp.distributions.all_communities,\n# threat_level_id=self.misp.threat_level.undefined,\n# analysis=self.misp.analysis.completed,\n # info=\"Cuckoo Sandbox analysis #%d\" % self.task[\"id\"],\n info=\"Cuckoo Sandbox analysis #%d\"%int(cuckoo_task_id),\n )\n evt_id = event['Event']['id']\n event = self.misp.get_event(evt_id)\n r = self.misp.add_named_attribute(event, 'filename|sha256', '%s|%s'%(cuckoo_file_name, cuckoo_file_sha256))\n \n # Add file analysed\n if results.get(\"target\", {}).get(\"file\", {}):\n f = results[\"target\"][\"file\"]\n misp_type = 'file'\n template_id = self.get_misp_template(misp_type)\n returned_objs = self.create_cuckoo_file(f,misp_type)\n # Only 1 obj returning here\n for obj in returned_objs:\n r = self.misp.add_object(evt_id, template_id, obj)\n file_uuid = r['Object']['uuid']\n self.check_for_errors(r)\n duplicate_list=[] \n proto_list = ['tcp','udp', 'irc', 'smtp', 'smtp_ex']\n for proto in proto_list:\n for f in results.get(\"network\", {}).get(proto, []):\n if len(f) > 0 and tuple((f['dst'],f['dport'])) not in duplicate_list: \n duplicate_list.append((f['dst'],f['dport']))\n returned_objs = self.add_protos(f, file_uuid)\n# if returned_objs is None:\n# continue\n self.add_to_misp(evt_id, returned_objs)\n \n\n # Add domain-ip or only domain or only ip to misp\n f = results.get(\"network\", {}).get(\"domains\", [])\n if len(f) > 0:\n returned_objs = self.add_domain_ip(f, file_uuid, evt_id)\n self.add_to_misp(evt_id, returned_objs)\n \n\n\n # Add URL \n for protocol in (\"http_ex\", \"https_ex\"):\n for f in results.get(\"network\", {}).get(protocol, []):\n if len(f) > 0:\n returned_objs = self.add_url(f, file_uuid, cuckoo_file_sha256)\n self.add_to_misp(evt_id, returned_objs)\n \n \nfolder='/home/admin1/srcc/oraculo/dados/cuckoo'\ninput_file = 'cuckoo_extract.json'\noutput_file = 'cuckoo_filt.json'\ncr = json.load(open(os.path.join(folder,input_file),'r'))\ni1 = MISP()\ni1.run(cr)","sub_path":"tests/misp_odl.py","file_name":"misp_odl.py","file_ext":"py","file_size_in_byte":14093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"181903946","text":"# -*- coding: utf-8 -*-\n'''@author: Rayment\n @version: 1.0\n @note: 实现扫雷游戏(2011-9-20)\n 测试环境:python2.5.2\n'''\nimport sys\nimport random\nimport string\n\nclass MineSweeping():\n '''扫雷主程序\n '''\n\n def __init__(self):\n '''初始化函式\n '''\n \n self.ROW = 8\n self.LINE = 8\n self.SCORE = 0 #扫雷得分\n self.MineNum = 15 #地雷总数\n self.xy_list= [[0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0]]\n \n \n def iniData(self):\n '''x,y坐标初始状态值函数\n 0-没有地雷;1-有地雷\n '''\n \n #游戏开始前所有数值归零\n for l in range(self.LINE):\n for r in range(self.ROW):\n self.xy_list[l][r]= 0\n \n Max = self.MineNum\n for x in range(self.LINE):\n for y in range(self.ROW):\n if 0 > Max:\n self.xy_list[x][y]= 0\n else:\n #为了增加地雷分布范围,选择0到4随机数\n if 1 == random.randint(0,4):\n self.xy_list[x][y]= 1\n Max = Max - 1\n \n \n def getX(self):\n '''获得x坐标值\n @return : 返回x坐标值\n @type : int\n '''\n sys.stdout.write('X=')\n xRet = input()\n while xRet=='' or (False == self.isNumber(xRet))\\\n or 0>int(xRet) or int(xRet)>self.ROW -1:\n print('Wrong number!(please input 0-7)')\n sys.stdout.write('X=')\n xRet = input()\n return int(xRet)\n \n \n def getY(self):\n '''获得y坐标值\n @return : 返回y坐标值\n @type : int\n '''\n sys.stdout.write('Y=')\n yRet = input()\n while yRet=='' or (False == self.isNumber(yRet))\\\n or 0>int(yRet) or int(yRet)>self.LINE -1:\n print('Wrong number!(please input 0-7)')\n sys.stdout.write('Y=')\n yRet = input()\n return int(yRet)\n \n \n def isNumber(self,strVal):\n '''检查是否数值\n @param : 需检查的字符串\n @type : str\n '''\n \n nums = string.digits\n for i in strVal:\n if i not in nums:\n return False\n return True\n \n\n def checkMine(self,xPos,yPos):\n '''检查输入坐标是否有雷\n 0-没有地雷;1-有地雷;2-已经清扫\n @param 1: x坐标\n @type : int\n @param 2: y坐标\n @type : int\n @return : 0-没有地雷;1-有地雷;2-已经清扫\n @rtype : int\n '''\n if 0 == self.xy_list[xPos][yPos]:\n self.xy_list[xPos][yPos] = 2\n return 0\n elif 2 == self.xy_list[xPos][yPos]:\n return 2\n else:\n return 1\n \n \n def play(self):\n '''游戏运行函数\n '''\n self.display(1)\n self.SCORE = 0\n self.iniData()\n #print self.xy_list\n while(1):\n x = self.getX()\n y = self.getY()\n while(2 == self.checkMine(x,y)):\n print('values of x,y had inputed,please input new values!')\n x = self.getX()\n y = self.getY()\n if 1 == self.checkMine(x,y):\n self.end()\n break\n else:\n self.display(2)\n self.SCORE = self.SCORE + 1\n \n \n def end(self):\n '''游戏结束函数\n '''\n \n self.display(3)\n print('+======================+')\n print('+ Game Over +')\n print('+======================+')\n print(' Your score is: %d '%(self.SCORE))\n \n\n def display(self,kind):\n '''图形输出函数\n @param:1-初始;2-运行;3-结束\n @type:int\n '''\n if kind==1:\n print('+======================+')\n print('+ Game Start +')\n print('+======================+')\n print('*-----------------*')\n for i in range(self.LINE):\n print('|', end = ' ')\n for k in range(self.ROW):\n print('口', end = ' ')\n print('|')\n print('*-----------------*')\n print('Please input values of x,y(0-7):')\n elif kind==2:\n #输出已经清扫位置\n print('*-----------------*')\n for i in range(self.LINE):\n print('|', end = ' ')\n for k in range(self.ROW):\n if 2 == self.xy_list[i][k]:\n count = self.getCount(i,k)\n print(count, end = ' ')\n else:\n print('口', end = ' ')\n print('|')\n print('*-----------------*')\n print('Please input values of x,y(0-7):') \n else:\n #输出所有的地雷与已经清扫位置\n print('*-----------------*')\n for i in range(self.LINE):\n print('|', end = ' ')\n for k in range(self.ROW):\n if 2 == self.xy_list[i][k]:\n count = self.getCount(i,k)\n print(count, end = ' ')\n elif 1== self.xy_list[i][k]:\n print('X', end = ' ')\n else:\n print('口', end = ' ')\n print('|')\n print('*-----------------*')\n def getCount(self,n,m):\n count = 0\n if n == 0:\n line = [n, n+1]\n elif n == (self.LINE - 1):\n line = [n-1, n]\n else:\n line = [n-1, n, n+1]\n if m == 0:\n row = [m, m+1]\n elif m == (self.ROW - 1):\n row = [m-1, m]\n else:\n row = [m-1, m, m+1]\n for i in line:\n for k in row:\n if 1 == self.xy_list[i][k]:\n count += 1\n return count\n\n \n \n\nif __name__ == '__main__':\n '''自测试\n '''\n ms = MineSweeping()\n while(1):\n ms.play()\n print('\\n----------------------------------------------')\n print('Quit game press \\'q\\',otherwise press other key!')\n print('----------------------------------------------')\n inputVal = input()\n if 'q' == inputVal:\n break\n","sub_path":"test/saolei.py","file_name":"saolei.py","file_ext":"py","file_size_in_byte":6847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"128065843","text":"import argparse\nimport sys\nimport matplotlib\nfrom pathlib import Path\n#matplotlib.use(\"Qt5agg\")\n#matplotlib.use(\"TkAgg\")\nimport gym\nimport gridworld\nimport torch\nfrom utils import *\nfrom torch.utils.tensorboard import SummaryWriter\nfrom explorer import *\nfrom memory import *\nfrom utils import *\nimport torch.optim as optim\nfrom DQN_GOAL import *\nimport numpy as np\n\n\nif __name__ == '__main__':\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n config = load_yaml('./configs/config_random_gridworld.yaml')\n\n freqTest = config[\"freqTest\"]\n freqSave = config[\"freqSave\"]\n nbTest = config[\"nbTest\"]\n\n env = gym.make(config[\"env\"])\n # \n env.setPlan(\"gridworld/gridworldPlans&Goals/plan2Multi.txt\", {0: -0.001, 3: 1, 4: 1, 5: -1, 6: -1})\n\n tstart = str(time.time())\n tstart = tstart.replace(\".\", \"_\")\n outdir = \"./XP/\" + config[\"env\"] + \"/DQNG/\" + tstart\n\n\n env.seed(config[\"seed\"])\n np.random.seed(config[\"seed\"])\n torch.manual_seed(config[\"seed\"])\n\n episode_count = config[\"nbEpisodes\"]\n ob = env.reset()\n #=======================================================================================\n ### explorer\n explorer = Epsilon_Greedy(env.action_space, 0.2 )\n #explorer = UCB(env.action_space)\n #explorer = Greedy(env.action_space)\n agent = DQNGAgent(env,config, explorer, device ,buffer_size = int(1e6), gamma=0.99, alpha = 1e-3, b= 1000, update_frequency= 1000, test = False )\n #==============================================================================================\n print(\"Saving in \" + outdir)\n os.makedirs(outdir, exist_ok=True)\n save_src(os.path.abspath(outdir))\n write_yaml(os.path.join(outdir, 'info.yaml'), config)\n writer = SummaryWriter(outdir)\n\n rsum = 0\n mean = 0\n verbose = True\n itest = 0\n reward = 0\n done = False\n mem_temp = []\n \n effective_episodes = 1\n for i in range(episode_count):\n if i % int(config[\"freqVerbose\"]) == 0 :\n verbose = True\n else:\n verbose = False\n\n if i % freqTest == 0 and i >= freqTest: ##### Same as train for now\n print(\"Test time! \")\n mean = 0\n agent.test = True\n\n if i % freqTest == nbTest and i > freqTest:\n print(\"End of test, mean reward=\", mean / nbTest)\n itest += 1\n writer.add_scalar(\"reward\", mean / nbTest, itest)\n agent.test = False\n\n if i % freqSave == 0:\n agent.save(outdir + \"/save_\" + str(i))\n\n j = 0\n if verbose:\n env.render()\n \n # sample the goal for the forthcoming episode\n goal, _ = env.sampleGoal()\n goal = agent.featureExtractor.getFeatures(goal)\n ob = agent.featureExtractor.getFeatures(ob)\n while True:\n if verbose:\n env.render()\n # one action wrt to the current agent\n action = agent.act(ob, goal, reward, done)\n # new observation + featurize\n new_ob, _, _, _ = env.step(action)\n new_ob = agent.featureExtractor.getFeatures(new_ob)\n # done if we attained the goal\n done = (new_ob == goal).all()\n # sparse rewards\n reward = 1.0 if done else -0.1\n \n \n # filling the buffer\n # [old_st, old_at, old_goal, new_st, new_goal, reward, done]\n agent.buffer.store((ob, action, goal, new_ob, reward, done))\n agent.stored_transitions += 1\n \n # next iteration\n ob = new_ob\n j += 1\n rsum += reward\n \n if done or j >= 100 :\n print(\"epsiode = \" + str(i) + \" | rsum=\" + str(rsum) + \", \" + str(j))\n mean += rsum\n rsum = 0\n ob = env.reset()\n break\n env.close()\n","sub_path":"tme14/test_DQNG.py","file_name":"test_DQNG.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"470851720","text":"import boto3\n\n\ndef new_queue(sqs, name):\n\n # Create the queue. This returns an SQS.Queue instance\n queue = sqs.create_queue(QueueName=name)\n print(queue.url)\n return\n\n\ndef get_queue(sqs):\n # Get the queue. This returns an SQS.Queue instance\n queue = sqs.get_queue_by_name(QueueName='test')\n print(queue.url)\n print(queue.attributes.get('DelaySeconds'))\n\n queue_name = queue.attributes['QueueArn'].split(':')[-1]\n print(queue_name)\n\n return queue\n\n\ndef send_message(queue):\n # Create a new message\n response = queue.send_message(MessageBody='world')\n # The response is NOT a resource, but gives you a message ID and MD5\n print(response.get('MessageId'))\n print(response.get('MD5OfMessageBody'))\n\n\ndef custom_message(queue):\n # custom attributes in message\n queue.send_message(MessageBody='boto3', MessageAttributes={\n 'Author': {\n 'StringValue': 'Daniel',\n 'DataType': 'String'\n }\n })\n\n return\n\n\ndef batch_message(queue):\n response = queue.send_messages(Entries=[\n {\n 'Id': '1',\n 'MessageBody': 'world'\n },\n {\n 'Id': '2',\n 'MessageBody': 'boto3',\n 'MessageAttributes': {\n 'Author': {\n 'StringValue': 'Daniel',\n 'DataType': 'String'\n }\n }\n }\n ])\n\n # Print out any failures\n print(response.get('Failed'))\n\n\ndef my_json_message(queue):\n\n message = 'pdf file'\n bucket_name = 'ccm-test-2'\n file_name = 'f-00987654321.pdf'\n\n response = queue.send_messages(Entries=[\n {\n 'Id': '1',\n 'MessageBody': message,\n 'MessageAttributes': {\n 'Bucket': {\n 'StringValue': bucket_name,\n 'DataType': 'String'\n },\n 'Key': {\n 'StringValue': file_name,\n 'DataType': 'String'\n }\n }\n }\n\n ])\n\n return response\n\n\ndef process_messages(queue):\n # Process messages by printing out body and optional author name\n for message in queue.receive_messages(MessageAttributeNames=['Author']):\n print('Next message:')\n print(message)\n print(message.body)\n # Get the custom author message attribute if it was set\n author_text = ''\n if message.message_attributes is not None:\n author_name = message.message_attributes.get('Author').get('StringValue')\n if author_name:\n author_text = ' ({0})'.format(author_name)\n\n # Print out the body and author (if set)\n print('Hello, {0}!{1}'.format(message.body, author_text))\n\n # Let the queue know that the message is processed\n message.delete()\n return\n\n\ndef process_my_msg(queue):\n for message in queue.receive_messages(MessageAttributeNames=['All']):\n print(message)\n\n # Get the custom author message attribute if it was set\n bucket = ''\n key = ''\n\n print('Message body: {}'.format(message.body))\n print('Message Id: {}'.format(message.message_id))\n\n if message.message_attributes is not None:\n bucket = message.message_attributes.get('Bucket').get('StringValue')\n key = message.message_attributes.get('Key').get('StringValue')\n print('Bucket is {}, file is {}'.format(bucket, key))\n\n # Let the queue know that the message is processed\n message.delete()\n return\n\n\nif __name__ == '__main__':\n\n sqs = boto3.resource('sqs')\n # new_queue(sqs=sqs, name='test')\n\n Q = get_queue(sqs)\n # send_message(queue=Q)\n\n my_json_message(Q)\n # process_my_msg(Q)\n\n # Q.purge()\n","sub_path":"Trials/sqs/sqs_trials.py","file_name":"sqs_trials.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"578956020","text":"#!/usr/bin/env python\n#coding:utf-8\n\nimport socket\nimport SocketServer\nimport ssl\nimport threading\nimport random\nimport json\nimport errno\n\nssl_sockets = []\nCONNECTION_NUM = 5\nCONFIG_FILE = 'config.json'\nserver_ip = None\nserver_port = None\n\n\nclass Encoder(SocketServer.DatagramRequestHandler):\n \n def handle(self):\n global ssl_sockets\n global server_ip\n global server_port\n random.seed()\n i = random.randint(0, CONNECTION_NUM - 1)\n ssl_socket, lock = ssl_sockets[i]\n data, sock = self.request\n with lock:\n try:\n ssl_socket.sendall(data)\n data = ssl_socket.recv(64*1024)\n except socket.error as error:\n if error.errno == errno.WSAECONNRESET:\n remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ssl_socket = ssl.wrap_socket(remote, ssl_version=ssl.PROTOCOL_TLSv1)\n l = (server_ip, server_port)\n ssl_socket.connect(l)\n ssl_sockets[i] = ssl_socket, threading.RLock(),\n else:\n raise\n sock.sendto(data, self.client_address)\n\n\ndef main():\n global ssl_sockets\n global server_ip\n global server_port\n\n with open(CONFIG_FILE, 'rb') as f:\n o = json.load(f)\n f.close()\n server_ip = o['client']['server-ip']\n server_port = o['server']['listen-port']\n listen_ip = o['client']['listen-ip']\n listen_port = o['client']['listen-port']\n \n for i in xrange(0, CONNECTION_NUM):\n remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ssl_socket = ssl.wrap_socket(remote, ssl_version=ssl.PROTOCOL_TLSv1)\n l = (server_ip, server_port)\n ssl_socket.connect(l)\n ssl_sockets.append((ssl_socket, threading.RLock()))\n\n server = SocketServer.ThreadingUDPServer((listen_ip, listen_port), Encoder)\n server.serve_forever()\n\nif __name__ == '__main__':\n main()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"186816607","text":"__author__ = 'lslacker'\n# -*- coding: utf-8 -*-\nimport argparse\nfrom mssqlwrapper import DB, TempTable\nimport logging\nimport helper\nimport datetime\nfrom itertools import repeat\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_investment_id(db, investment_code):\n\n return db.get_one_value('''\n select stockID\n from vewEquities\n where stockCode=?\n ''', investment_code) if get_investment_id else None\n\n\ndef delists(db, investment_code, recommendation, investment_type_id, approved_by):\n today = datetime.date.today()\n today = today.strftime('%Y-%m-%d')\n helper.backup_table(db, 'ExternalData..tblStockEarningsDividends')\n helper.backup_table(db, 'ExternalData..tblStockEarnings')\n investment_codes = investment_code.split(',')\n investment_ids = [get_investment_id(db, x) for x in investment_codes]\n params = (zip(investment_ids, investment_codes, repeat(recommendation), repeat(investment_type_id), repeat(today), repeat(approved_by)))\n return any([delist(db, *param) for param in params])\n\n\ndef delist(db, investment_id, investment_code, recommendation, investment_type_id, date, approved_by):\n\n query = '''\\\n prcInvestmentRecommendationPut @InvestmentID={investment_id}, @isActive=0\n ;\n prcInvestmentRecommendationPut @InvestmentID={investment_id}, @recommendation='{recommendation}',\n @InvestmentTypeID={investment_type_id}, @ApprovedDate='{date}',\n @FromDate='{date}',\n @ApprovedBy='{approved_by}',\n @isActive=1\n ;\n delete from ExternalData..tblStockEarningsDividends\n where StockEarningsID in (\n select StockEarningsID\n from ExternalData..tblStockEarnings\n where investmentcode='{investment_code}')\n ;\n delete from ExternalData..tblStockEarnings\n where investmentcode='{investment_code}'\n '''.format(investment_id=investment_id,\n investment_code=investment_code,\n recommendation=recommendation,\n investment_type_id=investment_type_id,\n date=date,\n approved_by=approved_by)\n for q in query.split(';'):\n logger.info('Executing:\\n{}'.format(q))\n count = db.execute(q)\n logger.info(count)\n return count\n\ndef consoleUI():\n parser = argparse.ArgumentParser(description='Merge multiple csv files into excel file, each csv')\n parser.add_argument('--server', default=r'MEL-TST-001\\WEBSQL', help='Database Server')\n parser.add_argument('--database', default=r'Lonsec', help='Database Name')\n parser.add_argument('-v', '--verbose', action='count', default=0)\n parser.add_argument('--recommendation', help='Recommendation. Check tblRecommendation for Name', required=True, default='Ceased Coverage')\n parser.add_argument('--investment-type-id', help='Investment Type ID. Default: 2 (Direct Equity)', required=True, type=int, default='2')\n parser.add_argument('--approved-by', help='Approved By', required=True)\n parser.add_argument('--dry-run', help='An excel file (normally from Jen Lee)', action='store_true')\n parser.add_argument('--investment-code', help='Investment Code aka Stock Code', required=True)\n\n\n a = parser.parse_args()\n\n if a.verbose > 1:\n logging.basicConfig(level=logging.INFO)\n\n connection_string1 = r'Driver={{SQL Server Native Client 11.0}};Server={server};Database={database};' \\\n 'Trusted_Connection=yes;'.format(server=a.server, database=a.database)\n\n db = DB.from_connection_string(connection_string1)\n if a.verbose > 1:\n db.debug = True\n\n logger.info(delists(db, a.investment_code, a.recommendation, a.investment_type_id, a.approved_by))\n\n if not a.dry_run:\n logger.info('Commit changes')\n db.commit()\n else:\n logger.info('All changes did not commit')\n\nif __name__ == '__main__':\n consoleUI()\n","sub_path":"stock_recommendation_ceased.py","file_name":"stock_recommendation_ceased.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"607566988","text":"import os\nimport time\nimport urllib.request\nimport queue as Queue\nfrom selenium import webdriver\n\n\ndef createFolder(directory):\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print('Error: Creating Directory.' + directory)\n\n#입력\nuser = input('계정 이름을 입력하세요:')\nbase = 'https://www.instagram.com'\nurl = base + '/' + user\ndownloaded_directory = './downloaded/' + user + '/'\n\ncreateFolder(downloaded_directory)\n\ndriver = webdriver.Chrome(r'./dev/chromedriver.exe')\ndriver.set_window_position(-10000,0)\n\ndriver.get(url)\ndriver.implicitly_wait(7)\nbefore = time.time()\n\nposition = driver.execute_script(\"return window.pageYOffset;\")\ntemp = list()\nlist_del = list()\nwhile True:\n \n driver.execute_script(\"window.scrollTo(0,document.body.scrollHeight);\")\n if time.time() - before > 0.2:\n ###\n posts = driver.find_elements_by_tag_name('a')\n\n #링크 정리\n #temp = list()\n #list_del = list()\n\n for post in posts:\n try:\n temp.append(post.get_attribute('href'))\n except:\n pass\n \n \n ###\n\n if time.time() - before > 3.5:\n if position == driver.execute_script(\"return window.pageYOffset;\"):\n break\n else:\n position = driver.execute_script(\"return window.pageYOffset;\")\n before = time.time()\n\ndriver.execute_script('window.scrollTo(0,0);')\n\ntemp = list(set(temp))\n\n\n\n#링크 정리\niter = 0\nfor i in temp:\n if not '/p/' in i:\n list_del.append(iter)\n iter += 1\nfor i in reversed(list_del):\n del temp[i]\n\n\n\n\n#저장\nfile_order = 0\nfile_name = '.jpg'\nfor i in temp:\n driver.get(i)\n #driver.implicitly_wait(0.5)\n imgs_temp = driver.find_elements_by_tag_name('img')\n for img_temp in imgs_temp:\n if '/s150x150' in img_temp.get_attribute('src'):\n continue\n urllib.request.urlretrieve(img_temp.get_attribute('src'),downloaded_directory + str(file_order) + file_name)\n file_order += 1\n\ndriver.quit()\n\nif file_order == 0:\n print('계정이 없거나 비공개된 계정입니다.')","sub_path":"insta_downloader_buildTools/InstaDownloader.py","file_name":"InstaDownloader.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"140234506","text":"import imaplib\nimport imaplib_connect\nfrom imaplib_list_parse import parse_list_response\n\nwith imaplib_connect.open_connection() as c:\n typ, mbox_data = c.list()\n for line in mbox_data:\n flags, delimiter, mbox_name = parse_list_response(line)\n c.select('\"{}\"'.format(mbox_name), readonly=True)\n typ, msg_ids = c.search(\n None,\n '(FROM \"Doug\" SUBJECT \"Example message 2\")',\n )\n print(mbox_name, typ, msg_ids)\n\n","sub_path":"src/lesson_email/imaplib_search_from.py","file_name":"imaplib_search_from.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8687172","text":"'''\nCreated on Mar 16, 2017\n\n@author: Veera\n'''\nfrom boid import *\nfrom weightslider import WeightSlider\nfrom PyQt5.QtWidgets import QWidget, QGraphicsScene, QGraphicsView, QHBoxLayout, QVBoxLayout, QLabel\nfrom PyQt5.Qt import Qt, QGraphicsRectItem\n\nclass SimulationLayout(QWidget):\n\n def __init__(self, boids_number):\n \n super(SimulationLayout, self).__init__()\n self.boids_number = boids_number\n self.boids = []\n # Lisataan haluttu maara boid-yksiloita listaan\n for i in range(self.boids_number):\n self.boids.append(Boid())\n self.buildLayout()\n \n self.ws = DEFAULT_S\n self.wa = DEFAULT_A\n self.wc = DEFAULT_C\n \n \n def buildLayout(self):\n \n self.sld1 = WeightSlider('Separation', DEFAULT_S, RANGE_S)\n self.sld1.slider.valueChanged.connect(lambda: get_ws(self.sld1.slider.value()))\n \n self.sld2 = WeightSlider('Alignment', DEFAULT_A, RANGE_A)\n self.sld2.slider.valueChanged.connect(lambda: get_wa(self.sld2.slider.value()))\n \n self.sld3 = WeightSlider('Cohesion', DEFAULT_C, RANGE_C)\n self.sld3.slider.valueChanged.connect(lambda: get_wc(self.sld3.slider.value()))\n \n scene = self.setScene()\n self.view = QGraphicsView(scene)\n self.view.adjustSize()\n \n # Estetaan scroll barit\n self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n \n self.vertical = QVBoxLayout()\n self.horizontal1 = QHBoxLayout()\n self.horizontal2 = QHBoxLayout()\n \n self.horizontal1.addWidget(self.view)\n self.vertical.addLayout(self.horizontal1)\n # Lisataan ikkunaan graphicsviewin alapuolelle kolme painokerroin-slideria\n self.horizontal2.addWidget(self.sld1)\n self.horizontal2.addWidget(self.sld2)\n self.horizontal2.addWidget(self.sld3)\n \n self.vertical.addWidget(QLabel('Adjust parameters'))\n self.vertical.addLayout(self.horizontal2)\n \n self.setLayout(self.vertical)\n \n def setScene(self):\n # Lisaa parven yksilot sceneen\n scene = QGraphicsScene()\n scene.setSceneRect(0, 0, SCENE_WIDTH, SCENE_HEIGHT)\n scene.addItem(QGraphicsRectItem(0, 0, SCENE_WIDTH, SCENE_HEIGHT))\n for boid in self.boids:\n scene.addItem(boid)\n boid.setGraphics()\n boid.updatePosVector()\n\n return scene\n \n \n \n ","sub_path":"src/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"437369029","text":"import numpy as np\n\nimport keras\nfrom keras.datasets import mnist\nfrom keras.layers import Dense, Flatten, Dropout\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.models import Sequential\nfrom keras.models import model_from_json\n\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\n\nclass KerasVGG(object):\n \"\"\"A simple CNN model implemented using the Tensorflow estimator API\"\"\"\n\n def __init__(self, model_input_dim_height, model_input_dim_width, model_input_channels, n_classes, model_dir,\n additional_args={}):\n super(KerasVGG, self).__init__()\n self.model_input_dim_height = model_input_dim_height\n self.model_input_dim_width = model_input_dim_width\n self.model_input_channels = model_input_channels\n self.n_classes = n_classes\n self.model_dir = model_dir\n\n # model specific variables\n # Training Parameters\n\n if (\"learning_rate\" in additional_args):\n self.learning_rate = additional_args[\"learning_rate\"]\n else:\n self.learning_rate = 0.001\n print(\"using default of \" + str(self.learning_rate) + \" for \" + \"learning_rate\")\n\n if (\"dropout\" in additional_args):\n self.dropout = additional_args[\"dropout\"]\n else:\n self.dropout = 0.25\n print(\"using default of \" + str(self.dropout) + \" for \" + \"dropout\")\n\n self.model = None\n self.InitaliseModel(model_dir=self.model_dir)\n\n ### Required Model Functions\n def InitaliseModel(self, model_dir=\"model_dir\"):\n opts = tf.GPUOptions(allow_growth=True)\n conf = tf.ConfigProto(gpu_options=opts)\n # trainingConfig = tf.estimator.RunConfig(session_config=conf)\n set_session(tf.Session(config=conf))\n\n self.model = self.BuildModel(self.model_input_dim_height, self.model_input_dim_width, self.model_input_channels, self.n_classes,self.dropout)\n \n\n def TrainModel(self, train_x, train_y, batch_size, num_steps, val_x= None, val_y=None):\n if (type(train_x) != dict):\n input_dict = {\"input\": train_x}\n else:\n input_dict = train_x\n\n self.model.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adam(lr=self.learning_rate),\n metrics=['accuracy'])\n\n if(val_x is not None and val_y is not None):\n self.model.fit(train_x, train_y,\n batch_size=batch_size,\n epochs=num_steps,\n verbose=1,\n validation_data=(val_x, val_y))\n else:\n self.model.fit(train_x, train_y,\n batch_size=batch_size,\n epochs=num_steps,\n verbose=1)\n\n\n def EvaluateModel(self, eval_x, eval_y, batch_size):\n if (type(eval_x) != dict):\n input_dict = {\"input\": eval_x}\n else:\n input_dict = eval_x\n\n # Train the Model\n return self.model.evaluate(eval_x,eval_y, batch_size=batch_size)\n\n\n def Predict(self, predict_x):\n if (type(predict_x) != dict):\n input_dict = {\"input\": predict_x}\n else:\n input_dict = predict_x\n\n \n predictions = self.model.predict(predict_x)\n print(\"[np.argmax(prediction) for prediction in predictions]\",[np.argmax(prediction) for prediction in predictions])\n return [np.argmax(prediction) for prediction in predictions]\n\n\n def SaveModel(self, save_dir):\n model_json = self.model.to_json()\n with open(save_dir, \"w\") as json_file:\n json_file.write(model_json)\n print(\"Saved model to:\"+ str(self.model_dir))\n\n\n def LoadModel(self, load_dir):\n loaded_model_json = \"\"\n with open(load_dir, 'r') as f:\n loaded_model_json = f.read()\n \n loaded_model = model_from_json(loaded_model_json)\n print(\"Loaded model from:\"+ str(self.model_dir))\n\n ### Model Specific Functions\n def BuildModel(self, model_input_dim_height, model_input_dim_width, model_input_channels, n_classes,dropout):\n model = Sequential()\n \n model.add(Conv2D(32, (3, 3), activation='relu', input_shape=[model_input_dim_height, model_input_dim_width, model_input_channels], name=\"conv_1\"))\n model.add(Conv2D(32, (3, 3), activation='relu', name=\"conv_2\"))\n model.add(MaxPooling2D(pool_size=(2, 2),name=\"max_pool_1\"))\n model.add(Dropout(dropout,name=\"dropout_1\"))\n\n model.add(Conv2D(64, (3, 3), activation='relu', name=\"conv_3\"))\n model.add(Conv2D(64, (3, 3), activation='relu', name=\"conv_4\"))\n model.add(MaxPooling2D(pool_size=(2, 2),name=\"max_pool_2\"))\n model.add(Dropout(dropout,name=\"dropout_2\"))\n\n model.add(Flatten(name=\"feature_vector_1\"))\n model.add(Dense(256, activation='relu',name=\"fully_connected_1\"))\n model.add(Dropout(dropout,name=\"dropout_3\"))\n model.add(Dense(n_classes, activation='softmax',name=\"class_prob\"))\n return model\n \n\n \n def GetLayerByName(self,name):\n print(\"GetLayerByName - not implemented\")\n \n def FetchAllVariableValues(self):\n print(\"FetchAllVariableValues - not implemented\")\n\n\nif __name__ == '__main__':\n from tensorflow.examples.tutorials.mnist import input_data\n\n mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=False)\n\n model_input_dim_height = 28\n model_input_dim_width = 28\n model_input_channels = 1\n n_classes = 10\n learning_rate = 0.001\n\n batch_size = 128\n num_train_steps = 200\n\n additional_args = {\"learning_rate\": learning_rate}\n\n cnn_model = KerasCNN(model_input_dim_height, model_input_dim_width, model_input_channels, n_classes,\n model_dir=\"mnist\", additional_args=additional_args)\n\n verbose_every = 10\n for step in range(verbose_every, num_train_steps + 1, verbose_every):\n print(\"\")\n print(\"training\")\n print(\"step:\", step)\n cnn_model.TrainModel(mnist.train.images, mnist.train.labels, batch_size, verbose_every)\n print(\"\")\n\n print(\"evaluation\")\n print(cnn_model.EvaluateModel(mnist.test.images[:128], mnist.test.labels[:128], batch_size))\n print(\"\")\n\n print(cnn_model.Predict(mnist.test.images[:5]))\n\n print(mnist.test.labels[:5])\n","sub_path":"models/archived_depricated_models/keras_vgg/keras_vgg.py","file_name":"keras_vgg.py","file_ext":"py","file_size_in_byte":6317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"482970392","text":"import os\nimport yaml\nimport packaging.version\nimport subprocess\n\n\n\ndef main():\n packages = set()\n files = subprocess.run([\"git\", \"show\", \"--first-parent\", \"--name-only\", r'--pretty=\"format:%n\"'], capture_output=True, text=True)\n for line in files.stdout.splitlines():\n parts = line.split(\"/\")\n if len(parts) >= 4:\n packages.add(parts[1] + \"/\" + parts[2])\n for line in packages:\n package = line.split(\"/\")[0]\n version = None\n folder = line.split(\"/\")[1]\n with open(os.path.join(\"recipes\", package, \"config.yml\"), \"r\") as file:\n config = yaml.safe_load(file)\n for v in config[\"versions\"]:\n if config[\"versions\"][v][\"folder\"] != folder:\n continue\n try:\n if not version or packaging.version.Version(v) > packaging.version.Version(version):\n version = v\n except packaging.version.InvalidVersion:\n print(\"Error parsing version %s for package %s\" % (v, package))\n\n if version:\n command = [\"conan\", \"export\", os.path.join(\"recipes\", package, folder), \"%s/%s@\" % (package, version)]\n p = subprocess.run(command, check=False)\n\nif __name__ == \"__main__\":\n # execute only if run as a script\n main()\n","sub_path":".github/runlint.py","file_name":"runlint.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"431847940","text":"# On our special chessboard, two bishops attack each other if they share the same diagonal.\n# This includes bishops that have another bishop located between them,\n# i.e. bishops can attack through pieces.\n#\n# You are given N bishops, represented as (row, column) tuples on a M by M chessboard.\n# Write a function to count the number of pairs of bishops that attack each other.\n# The ordering of the pair doesn't matter: (1, 2) is considered the same as (2, 1).\n#\n# For example, given M = 5 and the list of bishops:\n#\n# (0, 0)\n# (1, 2)\n# (2, 2)\n# (4, 0)\n# The board would look like this:\n#\n# [b 0 0 0 0]\n# [0 0 b 0 0]\n# [0 0 b 0 0]\n# [0 0 0 0 0]\n# [b 0 0 0 0]\n\n# [0 0 0 0 0 0]\n# [0 b 0 0 0 b]\n# [0 0 b 0 0 0]\n# [0 0 0 b 0 0]\n# [0 0 0 0 0 0]\n# [0 b 0 0 0 b]\n# You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and 4.\n#\n\nfrom collections import defaultdict\n\nTOP_LEFT_TO_BOTTOM_RIGHT = 0\nTOP_RIGHT_TO_BOTTOM_LEFT = 1\n\nbishops = [(0, 0), (1, 2), (2, 2), (4, 0)]\nb = [(1, 1), (1, 5), (3, 3), (5, 1), (5, 5)]\n\n\ndef combos(num):\n return num * (num - 1) // 2\n\n\ndef pairs(bishops, m):\n counts = defaultdict(int)\n for r, c in bishops:\n top_lr, top_lc = (r - min(r, c), c - min(r, c))\n top_rr, top_rc = (r - min(r, m - c), c + min(r, m - c))\n\n counts[top_lr, top_lc, TOP_LEFT_TO_BOTTOM_RIGHT] += 1\n counts[top_rr, top_rc, TOP_RIGHT_TO_BOTTOM_LEFT] += 1\n return sum(combos(c) for c in counts.values())\n\n\n# print(pairs(bishops, 5))\n\n# to solve this brute force will be to calculate for a single bishop how many bishops lies\n# in its diagonal and repeat this for all this will be O(N^2) and will barely pass 3 subtasks\n#\n# now another way can be to store the data. We can notice that the bishops lie in the same diagonal\n# if:\n# there sum of x and y-axis are same.\n# there difference of x and y-axis are same.\n#\n# so we make a map and just store the frequence for each\n# map[x+y]++\n# map[x-y]++\n#\n# and after that looping over the map and count the number of ways a pair can be chosen from\n# a set of pairs, suppose the number of pairs is n so nC2 is the number of ways a\n# pair can be chosen thus count+=n*(n-1)/2\n#\n\n# This can be solved using two maps and time complexity is O(logN)\ndef pair_bishops_attack(bishops, m):\n map1 = {}\n map2 = {}\n for bishop in bishops:\n x = bishop[0]\n y = bishop[1]\n xplusy = x + y\n xminusy = x - y\n if map1.get(xplusy, 0):\n map1[xplusy] += 1\n else:\n map1[xplusy] = 1\n\n if map2.get(xminusy, 0):\n map2[xminusy] += 1\n else:\n map2[xminusy] = 1\n\n count = 0\n for val1 in map1.values():\n count += combos(val1)\n\n for val2 in map2.values():\n count += combos(val2)\n\n return count\n\n# print(pair_bishops_attack(bishops, 5))\n\nprint(pair_bishops_attack(b, 6))\nprint(pair_bishops_attack(bishops, 6))\n\nprint('pair ' + str(pairs(b, 6)))\nprint('pair ' + str(pairs(bishops, 5)))\n\n\n# This is brute force way to solve problem. Time complexity is O(n^2)\ndef is_attacking1(bishop0, bishop1):\n r0, c0 = bishop0\n r1, c1 = bishop1\n return abs(r1 - r0) == abs(c1 - c0)\n\n\ndef pairs1(bishops, m):\n count = 0\n for i, bishop0 in enumerate(bishops):\n for j, bishop1 in enumerate(bishops[i + 1:]):\n count += is_attacking1(bishop0, bishop1)\n return count\n\n\n# print(pairs1(b, 5))\n","sub_path":"python/problems/68_number_of_bishop_attack_each_others.py","file_name":"68_number_of_bishop_attack_each_others.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"569169767","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 2 22:30:47 2021\n\n@author: rodger\n\"\"\"\n\nimport cv2\nimport numpy as np\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport PIL\nfrom PIL import Image\n\nimg_path = './a.jpg'\n# img = Image.load_img(img_path, grayscale=True)\n# img_array = Image.img_to_array(img)\nimg = cv2.imread(img_path)\n# cv2.imwrite('testimg1.jpg', img_array);\n\n# 圖片灰階\ngrayscaleimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n# plt.imshow(grayscaleimg,cmap='gray')\n\n\n# 圖片二值化\nret, binary = cv2.threshold(grayscaleimg, 110, 255, cv2.THRESH_BINARY) # 110這個數字可改\n# plt.imshow(binary,cmap='Greys',interpolation='None')\nrawimg = binary - binary[0,1] #有這欄 圖的最低就會變成0 圖會變成黑底白字\n# plt.imshow(rawimg)\n\n# counting non-zero value by row , axis y\nrow_nz = []\nfor row in rawimg.tolist():\n row_nz.append(len(row) - row.count(0))\n#plt.plot(row_nz)\n\n\nidx=np.array(row_nz)>(max(row_nz)/4) #截出上下的範圍\nnp.where(idx==1)[0][0],np.where(idx==1)[0][-1]\nup_y=np.where(idx==1)[0][-1] #上界\ndown_y=np.where(idx==1)[0][0] #下界\nrawimg1=rawimg[down_y:up_y,]\n# plt.imshow(rawimg1)\n\n# counting non-zero value by column, x axis\ncol_nz = []\nfor col in rawimg1.T.tolist():\n col_nz.append(len(col) - col.count(0))\nplt.plot(col_nz)\n\nidy=np.not_equal(col_nz,0)\nrecord_y=[] #如果有八個數字,裡面應該要有九個格子(一開始找出七個,前後插入變九個)\nfor i in range(0,(len(np.where(idy==1)[0])-1)):\n # 如果下一個數是0就略過,直到找到下一個數不是0的位置\n if(np.where(idy==1)[0][i+1]-np.where(idy==1)[0][i]==1):\n pass\n else:\n record_y.append(np.where(idy==1)[0][i])\n\n# 插入第一個非0位置跟最後一個非0的位置\nrecord_y.insert(0,np.where(idy==1)[0][0])\nrecord_y.append(np.where(idy==1)[0][-1])\n\n# 檢查數字\nrm_id=[]\nif len(record_y)>9:\n for j in range(0,len(record_y)-1):\n temp=np.array(col_nz[record_y[j]:record_y[j+1]])\n #如果只是雜訊,就刪掉\n if sum(temp>(max(col_nz)/4))==0:\n rm_id.append(record_y[j+1])\n\nfor x in rm_id:\n record_y.remove(x)\n \nfor i in range(0,len(record_y)-1):\n a=binary[down_y:up_y,record_y[i]:record_y[i+1]]\n a=cv2.resize(a, (50, 50), interpolation=cv2.INTER_CUBIC)\n # img_name='rodger.jpg'\n # cv2.imwrite(img_name,a)\n plt.imshow(a)","sub_path":"dataargument/oldmain.py","file_name":"oldmain.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"353150283","text":"import time\nfrom rllab.algos.base import RLAlgorithm\nimport rllab.misc.logger as logger\nfrom sandbox.rocky.tf.policies.base import Policy\nimport tensorflow as tf\nfrom sandbox.ours.sampler.env_batch_sampler import EnvBatchSampler\nfrom rllab.sampler.utils import rollout\n\nfrom sandbox.ours.sampler import ModelVectorizedSampler, RandomVectorizedSampler, EnvVectorizedSampler\n\n\nclass ModelBatchPolopt(RLAlgorithm):\n \"\"\"\n Base class for batch sampling-based policy optimization methods.\n This includes various policy gradient methods like vpg, npg, ppo, trpo, etc.\n \"\"\"\n\n def __init__(\n self,\n env,\n policy,\n dynamics_model,\n baseline,\n scope=None,\n n_itr=500,\n start_itr=0,\n batch_size_env_samples=5000,\n batch_size_dynamics_samples=40000,\n initial_random_samples=None,\n max_path_length=500,\n discount=0.99,\n gae_lambda=1,\n dynamic_model_max_epochs=(1000, 1000),\n num_gradient_steps_per_iter=10,\n retrain_model_when_reward_decreases=True,\n reset_policy_std=False,\n reinit_model_cycle=0,\n plot=False,\n pause_for_plot=False,\n center_adv=True,\n positive_adv=False,\n store_paths=False,\n whole_paths=True,\n fixed_horizon=False,\n sampler_cls=None,\n sampler_args=None,\n force_batch_sampler=False,\n **kwargs\n ):\n \"\"\"\n :param env: Environment\n :param policy: Policy\n :param dynamics_model: Dynamics Model\n :param baseline: Baseline\n :param scope: Scope for identifying the algorithm. Must be specified if running multiple algorithms\n simultaneously, each using different environments and policies\n :param n_itr: Number of iterations.\n :param start_itr: Starting iteration.\n :param batch_size_env_samples: Number of samples from the environment per iteration.\n :param batch_size_dynamics_samples: Number of (imaginary) samples from the dynamics model\n :param initial_random_samples: either None -> use initial policy to sample from env\n or int: number of random samples at first iteration to train dynamics model\n if provided, in the first iteration no samples from the env are generated\n with the policy\n :param max_path_length: Maximum length of a single rollout.\n :param discount: Discount.\n :param gae_lambda: Lambda used for generalized advantage estimation.\n :param dynamic_model_epochs: (2-tuple) number of epochs to train the dynamics model\n (n_epochs_at_first_iter, n_epochs_after_first_iter)\n :param num_gradient_steps_per_iter: number of policy gradients steps before retraining dynamics model\n :param retrain_model_when_reward_decreases: (boolean) if true - stop inner gradient steps when performance decreases\n :param reset_policy_std: whether to reset the policy std after each iteration\n :param reinit_model_cycle: number of iterations before re-initializing the dynamics model (if 0 the dynamic model is not re-initialized at all)\n :param plot: Plot evaluation run after each iteration.\n :param pause_for_plot: Whether to pause before contiuing when plotting.\n :param center_adv: Whether to rescale the advantages so that they have mean 0 and standard deviation 1.\n :param positive_adv: Whether to shift the advantages so that they are always positive. When used in\n conjunction with center_adv the advantages will be standardized before shifting.\n :param store_paths: Whether to save all paths data to the snapshot.\n \"\"\"\n self.env = env\n self.policy = policy\n self.dynamics_model = dynamics_model\n self.baseline = baseline\n self.scope = scope\n self.n_itr = n_itr\n self.start_itr = start_itr\n self.batch_size = batch_size_env_samples\n self.batch_size_dynamics_samples = batch_size_dynamics_samples\n self.initial_random_samples = initial_random_samples\n self.max_path_length = max_path_length\n self.discount = discount\n self.gae_lambda = gae_lambda\n self.dynamic_model_max_epochs = dynamic_model_max_epochs\n self.num_gradient_steps_per_iter = num_gradient_steps_per_iter\n self.retrain_model_when_reward_decreases = retrain_model_when_reward_decreases\n self.plot = plot\n self.pause_for_plot = pause_for_plot\n self.center_adv = center_adv\n self.positive_adv = positive_adv\n self.store_paths = store_paths\n self.whole_paths = whole_paths\n self.fixed_horizon = fixed_horizon\n self.reset_policy_std = reset_policy_std\n self.reinit_model = reinit_model_cycle\n\n # sampler for the environment\n if sampler_cls is None:\n if self.policy.vectorized and not force_batch_sampler:\n sampler_cls = EnvVectorizedSampler\n else:\n sampler_cls = BatchSampler #TODO: use batch sampler rather than Vectorized Sampler\n if sampler_args is None:\n sampler_args = dict()\n self.env_sampler = sampler_cls(self, **sampler_args)\n\n # sampler for (imaginary) rollouts with the estimated dynamics model\n self.model_sampler = ModelVectorizedSampler(self)\n\n if self.initial_random_samples:\n self.random_sampler = RandomVectorizedSampler(self)\n else:\n self.random_sampler = None\n\n self.init_opt()\n\n def start_worker(self):\n self.env_sampler.start_worker()\n self.model_sampler.start_worker()\n\n if self.initial_random_samples:\n self.random_sampler.start_worker()\n\n def shutdown_worker(self):\n self.env_sampler.shutdown_worker()\n self.model_sampler.shutdown_worker()\n\n def obtain_env_samples(self, itr, log=True):\n return self.env_sampler.obtain_samples(itr, log=log, log_prefix='EnvSampler-')\n\n def obtain_model_samples(self, itr, log=False):\n return self.model_sampler.obtain_samples(itr, log=log)\n\n def obtain_random_samples(self, itr, log=False):\n assert self.random_sampler is not None\n assert self.initial_random_samples is not None\n return self.random_sampler.obtain_samples(itr, num_samples=self.initial_random_samples, log=log, log_prefix='EnvSampler-')\n\n def process_samples_for_dynamics(self, itr, paths):\n return self.model_sampler.process_samples(itr, paths, log=False)\n\n def process_samples_for_policy(self, itr, paths, log=True, log_prefix='DynTrajs-', return_reward=False):\n return self.env_sampler.process_samples(itr, paths, log=log, log_prefix=log_prefix, return_reward=return_reward)\n\n def train(self, sess=None):\n created_session = True if (sess is None) else False\n if sess is None:\n sess = tf.Session()\n sess.__enter__()\n\n self.initialize_unitialized_variables(sess)\n\n self.all_paths = []\n\n self.start_worker()\n start_time = time.time()\n n_env_timesteps = 0\n\n for itr in range(self.start_itr, self.n_itr):\n itr_start_time = time.time()\n\n with logger.prefix('itr #%d | ' % itr):\n\n # get rollouts from the env\n\n if self.initial_random_samples and itr == 0:\n logger.log(\"Obtaining random samples from the environment...\")\n new_env_paths = self.obtain_random_samples(itr, log=True)\n\n n_env_timesteps += self.initial_random_samples\n logger.record_tabular(\"n_timesteps\", n_env_timesteps)\n\n self.all_paths.extend(new_env_paths)\n samples_data_dynamics = self.random_sampler.process_samples(itr, self.all_paths, log=True, log_prefix='EnvTrajs-') # must log in the same way as the model sampler below\n else:\n if self.reset_policy_std:\n logger.log(\"Resetting policy std\")\n self.policy.set_std()\n logger.log(\"Obtaining samples from the environment using the policy...\")\n new_env_paths = self.obtain_env_samples(itr)\n\n n_env_timesteps += self.batch_size\n logger.record_tabular(\"n_timesteps\", n_env_timesteps)\n\n self.all_paths.extend(new_env_paths)\n logger.log(\"Processing environment samples...\")\n # first processing just for logging purposes\n self.model_sampler.process_samples(itr, new_env_paths, log=True, log_prefix='EnvTrajs-')\n\n samples_data_dynamics = self.process_samples_for_dynamics(itr, self.all_paths)\n\n epochs = self.dynamic_model_max_epochs[min(itr, len(self.dynamic_model_max_epochs) - 1)]\n # fit dynamics model\n if self.reinit_model and itr % self.reinit_model == 0:\n self.dynamics_model.reinit_model()\n epochs = self.dynamic_model_max_epochs[0]\n logger.log(\"Training dynamics model for %i epochs ...\" % (epochs))\n self.dynamics_model.fit(samples_data_dynamics['observations_dynamics'],\n samples_data_dynamics['actions_dynamics'],\n samples_data_dynamics['next_observations_dynamics'],\n epochs=epochs, verbose=True)\n\n for gradient_itr in range(self.num_gradient_steps_per_iter):\n # get imaginary rollouts\n logger.log(\"Policy Gradient Step %i of %i - Obtaining samples from the dynamics model...\"%(gradient_itr, self.num_gradient_steps_per_iter))\n new_model_paths = self.obtain_model_samples(itr)\n\n logger.log(\"Policy Gradient Step %i of %i - Processing dynamics model samples...\"%(gradient_itr, self.num_gradient_steps_per_iter))\n samples_data_model, mean_reward = self.process_samples_for_policy(itr, new_model_paths, log='reward', log_prefix='%i-DynTrajs-'%gradient_itr, return_reward=True)\n\n if gradient_itr == 0:\n prev_rolling_reward_mean = mean_reward\n rolling_reward_mean = mean_reward\n else:\n prev_rolling_reward_mean = rolling_reward_mean\n rolling_reward_mean = 0.8 * rolling_reward_mean + 0.2 * mean_reward # update rolling mean\n\n # stop gradient steps when mean_reward decreases\n if self.retrain_model_when_reward_decreases and rolling_reward_mean < prev_rolling_reward_mean:\n logger.log(\n \"Stopping policy gradients steps since rolling mean reward decreased from %.2f to %.2f\" % (\n prev_rolling_reward_mean, rolling_reward_mean))\n # complete some logging stuff\n for i in range(gradient_itr + 1, self.num_gradient_steps_per_iter):\n logger.record_tabular('%i-DynTrajs-AverageReturn' % i, 0.0)\n break\n\n logger.log(\"Policy Gradient Step %i of %i - Optimizing policy...\"%(gradient_itr, self.num_gradient_steps_per_iter))\n self.optimize_policy(itr, samples_data_model, log=False)\n\n\n logger.log(\"Saving snapshot...\")\n params = self.get_itr_snapshot(itr, samples_data_model) # , **kwargs)\n if self.store_paths:\n params[\"paths\"] = samples_data_model[\"paths\"]\n logger.save_itr_params(itr, params)\n logger.log(\"Saved\")\n logger.record_tabular('Time', time.time() - start_time)\n logger.record_tabular('ItrTime', time.time() - itr_start_time)\n logger.dump_tabular(with_prefix=False)\n if self.plot:\n rollout(self.env, self.policy, animated=True, max_path_length=self.max_path_length)\n if self.pause_for_plot:\n input(\"Plotting evaluation run: Press Enter to \"\n \"continue...\")\n self.shutdown_worker()\n if created_session:\n sess.close()\n\n def log_diagnostics(self, paths):\n self.env.log_diagnostics(paths)\n self.policy.log_diagnostics(paths)\n self.baseline.log_diagnostics(paths)\n\n def init_opt(self):\n \"\"\"\n Initialize the optimization procedure. If using tensorflow, this may\n include declaring all the variables and compiling functions\n \"\"\"\n raise NotImplementedError\n\n def get_itr_snapshot(self, itr, samples_data):\n \"\"\"\n Returns all the data that should be saved in the snapshot for this\n iteration.\n \"\"\"\n raise NotImplementedError\n\n def optimize_policy(self, itr, samples_data, log=True, log_prefix=''):\n raise NotImplementedError\n\n def initialize_unitialized_variables(self, sess):\n uninit_variables = []\n for var in tf.global_variables():\n # note - this is hacky, may be better way to do this in newer TF.\n try:\n sess.run(var)\n except tf.errors.FailedPreconditionError:\n uninit_variables.append(var)\n\n sess.run(tf.variables_initializer(uninit_variables))","sub_path":"sandbox/ours/algos/ModelTRPO/model_batch_polopt.py","file_name":"model_batch_polopt.py","file_ext":"py","file_size_in_byte":13772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"463775705","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('profiles', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='profile',\n name='data_criacao',\n field=models.DateTimeField(default=datetime.datetime.now, verbose_name='Data de cria\\xe7\\xe3o', blank=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"projeto_multisite/profiles/migrations/0002_profile_data_criacao.py","file_name":"0002_profile_data_criacao.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"22500108","text":"# from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework import status,views\nfrom django.db import transaction\nfrom event.models import Event,EventShop\nfrom .serializers import EventSerializer, EventListSerializer ,InformSerializer\nfrom .filter import EventFilter\nfrom rest_framework.parsers import JSONParser,MultiPartParser,FormParser,FileUploadParser\n\nfrom utils.service import UnitWorkService\n\nimport json\n\nfrom apiv1 import ndy_signal\n\nclass EventListApiView(views.APIView):\n parser_classes = (JSONParser,MultiPartParser,FormParser,FileUploadParser,)\n \n # 一覧\n @transaction.atomic\n def get(self,request,*args,**kwargs):\n # event= Event.objects.get_queryset().active().filter(email = request.user.id)\n if(request.user.is_anonymous):return Response(status.HTTP_403_FORBIDDEN)\n\n event= Event.objects.filter(ndy_user = request.user.uuid).active()\n\n \n serializer = EventListSerializer(instance=event,many=True)\n # serializer.is_valid(raise_exception=True)\n return Response(serializer.data,status.HTTP_200_OK)\n\n @transaction.atomic\n def post(self,request,*args,**kwargs):\n # if(request.user.is_anonymous):return Response(status.HTTP_403_FORBIDDEN)\n # req_data = request.data\n serializer = EventSerializer(data=request.data,requestUser=request.user)\n\n if(serializer.reqestUser is None):return Response(status.HTTP_403_FORBIDDEN)\n\n serializer.is_valid(raise_exception=True)\n #anonymous判定\n # req_user = request.user if request.user is not None else None\n # serializer.save(ndy_user = req_user)\n event = serializer.save()\n\n # serializer.send_conoha(**request.data)\n\n # イベント登録シグナルに送信\n ndy_signal.event_registered.send(\n sender=self.__class__, \n event=event,\n password=serializer._event_password\n )\n return Response(status.HTTP_201_CREATED)\n\nclass InformApiView(views.APIView):\n def post(self,request,*args,**kwargs):\n serializer = InformSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n\n #anonymous判定\n req_user = request.user if request.user is not None else None\n serializer.save(ndy_user = req_user)\n \n posttingObj =serializer.validated_data\n posttingObj['email'] = req_user.email if req_user is not None else None\n\n UnitWorkService.informPostMail(posttingObj)\n # serializer.send_conoha(**request.data)\n\n return Response(status.HTTP_201_CREATED)\n\nclass EventRetrieveApiView(views.APIView):\n # 詳細\n def get(self,request,event_id,*args,**kwargs):\n event = Event.objects.get(event_id=event_id)\n serializer = EventSerializer(instance=event)\n return Response(serializer.data,status.HTTP_200_OK)\n\n def put(self,request,event_id,*args,**kwargs):\n event = Event.objects.get(event_id=event_id)\n # event.__class__.objects.update(email=2)\n serializer = EventSerializer(instance=event,data=request.data)\n serializer.is_valid()\n serializer.save()\n return Response(status.HTTP_200_OK)\n\n def patch(self,request,event_id,*args,**kwargs):\n event = Event.objects.get(event_id=event_id)\n serializer = EventSerializer(instance=event,data=request.data,partial=True)\n serializer.is_valid()\n serializer.save()\n return Response(status.HTTP_200_OK)\n\n def delete(self,request,event_id,*args,**kwargs):\n event= Event.objects.filter(event_id=event_id).delete()\n serializer = EventListSerializer(instance=event,many=True)\n return Response(serializer.data,status.HTTP_204_NO_CONTENT)","sub_path":"back/NDY/apiv1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"182969168","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\nimport torch.nn as nn\nimport torch\nimport torch.nn.functional as F\nimport numpy\nfrom torch.autograd import Variable\nfrom src.lsp import train_lsp\n#import max \nbatch=2\ndef weight_init(m):\n if isinstance(m, nn.Linear):\n nn.init.kaiming_normal(m.weight)\n\ndef l2_norm(x1,x2):\n out=torch.dist(x1,x2)\n return out\nclass Linear(nn.Module):\n def __init__(self, linear_size, p_dropout):\n super(Linear, self).__init__()\n self.l_size = linear_size\n\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout(p_dropout)\n\n self.w1 = nn.Linear(self.l_size, self.l_size)\n self.batch_norm1 = nn.BatchNorm1d(self.l_size)\n\n self.w2 = nn.Linear(self.l_size, self.l_size)\n self.batch_norm2 = nn.BatchNorm1d(self.l_size)\n\n def forward(self, x):\n y = self.w1(x)\n y = self.batch_norm1(y)\n y = self.relu(y)\n yx = self.dropout(y)\n \n y = self.w2(yx)\n y = self.batch_norm2(y)\n y = self.relu(y)\n y = self.dropout(y)\n \n out = x + y\n\n return out,yx,y\n \n\nclass LinearModel(nn.Module):\n def __init__(self,\n num_2d_coords,\n num_3d_coords,\n num_3d_coord,\n linear_size,\n num_stage,\n p_dropout,\n predict_scale,\n scale_range,\n unnorm_op,\n unnorm_init):\n super(LinearModel, self).__init__()\n\n self.linear_size = linear_size\n self.p_dropout = p_dropout\n self.num_stage = num_stage\n\n self.scale_range = scale_range\n self.unnorm_op = unnorm_op\n self.predict_scale = predict_scale\n\n # 2d joints\n self.input_size = num_2d_coords\n # 3d joints\n self.output_size = num_3d_coords\n\n # process input to linear size\n self.w1 = nn.Linear(self.input_size, self.linear_size)\n self.batch_norm1 = nn.BatchNorm1d(self.linear_size)\n\n self.linear_stages = []\n for l in range(num_stage):\n self.linear_stages.append(Linear(self.linear_size, self.p_dropout))\n self.linear_stages = nn.ModuleList(self.linear_stages)\n\n # post processing\n self.w2 = nn.Linear(self.linear_size, self.output_size)\n\n # weights that predict the scale of the image\n self.ws = nn.Linear(self.linear_size, 1)\n # sigmoid that makes sure the resulting scale is positive\n self.sigmoid = nn.Sigmoid()\n\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout(self.p_dropout)\n # self.mult = nn.Parameter(torch.ones(1)*unnorm_init)\n self.mult = nn.Parameter(torch.ones(num_3d_coords)*unnorm_init)\n #自加的处理过程\n self.w3=Linear(self.linear_size,self.p_dropout)\n self.w4=nn.Linear(self.output_size,self.linear_size)\n \n #self.w5=nn.Linear(self.linear_size,self.linear_size)\n self.w6=nn.Linear(self.linear_size,1)\n self.n1=nn.Linear(2*3,self.linear_size)\n self.n2=nn.Linear(2*2,self.linear_size)\n #网络投影的方式\n self.p=nn.Linear(self.linear_size,self.input_size)\n \n def base(self,x,sig):\n if sig==3:\n output =self.n1(x)\n else:\n output= self.n2(x)\n output = self.batch_norm1(output)\n output = self.relu(output)\n output = self.dropout(output)\n return output\n \n def forward(self, x): \n # pre-processing\n #将给定的姿态的按照语义信息分组(先考虑Lsp数据集)\n g1=x[:,0:2*3]\n g2=x[:,6:2*6]\n g3=x[:,2*6:2*9]\n g4=x[:,2*9:2*12]\n g5=x[:,2*12:2*14]\n out1=self.base(g1,3)\n out2=self.base(g2,3)\n out3=self.base(g3,3)\n out4=self.base(g4,3)\n out5=self.base(g5,2)\n y1=(out1+out2+out3+out4+out5)/5\n #########################################\n #y = self.w1(x)\n #y = self.batch_norm1(y)\n #y = self.relu(y)\n #y1 =self.dropout(y)\n \n \n #自加处理过程\n y2,F1,F2=self.w3(y1)\n new_out=self.w2(y2)#生成的中间三维姿态[8,42]\n #添加一个分支用于生成权重参数w\n #使用了三个层的二维特征\n w1=self.w6(y1)\n w2=self.w6(F1)\n w3=self.w6(F2)\n #w1=w1/w1+w2+w3\n #w2=w2/w1+w2+w3\n #w3=w3/w1+w2+w3\n #针对身体的8个关节点做进一步优化\n y=self.w4(new_out)\n # linear layers\n for i in range(self.num_stage):\n y3,_,_ = self.linear_stages[i](y)\n #loss=nn.MSELoss()\n #print(y3.shaph_e) \n att1=w1*l2_norm(y1,y3)\n att2=w2*l2_norm(F1,y3)\n att3=w3*l2_norm(F2,y3)\n att1_1=1-self.sigmoid(att1)\n att2_1=1-self.sigmoid(att2)\n att3_1=1-self.sigmoid(att3)\n y=y3+att1_1*y1+att2_1*F1+att3_1*F2\n out=self.w2(y)#[batch,16*3]\n ###############################当前的投影,基于尺度的正交投影方式\n h_out=self.w4(out)\n h_out,_,_=self.w3(h_out)\n #print('验证',h_out.shape)\n scale=self.p(h_out)#生成的二维姿态\n #print('验证维度', scale.shape) \n #########################################\n \n # apply the unnormalization parameters to the output\n if self.unnorm_op:\n out =out*self.mult\n \n # predict the scale :that will multiply the poses\n # scale = self.scale_range * self.sigmoid(self.ws(y))\n #########################################\n ''' \n hm1=torch.Tensor(batch,14,16,16).cuda()\n for i in range (batch):\n for j in range(14):\n for k in range(16):\n hm1[i,j,:,k]=hm[i,j,:,k]*scale[0,:]\n for t in range(16):\n hm1[i,j,t,:]=hm[i,j,t,:]*scale[1,:]\n '''\n #######################################\n #return hm1, out , scale \n \n return out , scale ,new_out\n","sub_path":"5-31/src/model_youwenti.py","file_name":"model_youwenti.py","file_ext":"py","file_size_in_byte":6119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"242395969","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom Product.models import Product\n\n# Create your models here.\n\n\nclass Vuln(models.Model):\n name = models.CharField('漏洞名称', max_length=100)\n location = models.CharField('位置', max_length=300, blank=True, null=True)\n type_main = models.CharField('漏洞大类', max_length=20)\n type_detail = models.CharField('漏洞小类', max_length=20)\n risk_level = models.IntegerField('威胁级别', choices=(\n (1, '低'), (2, '中'), (3, '高'), (4, '待定')), default=4)\n status = models.IntegerField('状态', choices=(\n (0, '提交'), (1, '已忽略'), (2, '已确认'), (3, '修复中'), (4, '复测中'), (5, '已修复')), default=0)\n content = models.TextField('详情')\n product = models.ForeignKey(Product, verbose_name='相关产品')\n post_user = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n null=True,\n blank=True,\n related_name='+',\n verbose_name='漏洞提交者')\n fixer = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n null=True,\n blank=True,\n related_name='+',\n verbose_name='修复者')\n checker = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n null=True,\n blank=True,\n related_name='+',\n verbose_name='审核者')\n post_time = models.DateTimeField('提交时间', auto_now_add=True)\n confirm_time = models.DateTimeField('确认时间', null=True, blank=True)\n start_fix_time = models.DateTimeField('开始修复时间', null=True, blank=True)\n send_to_recheck_time = models.DateTimeField(\n '复测提交时间', null=True, blank=True)\n fixed_time = models.DateTimeField('确认修复时间', null=True, blank=True)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = '漏洞'\n verbose_name_plural = '漏洞'\n","sub_path":"Vuln/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"368328696","text":"import logging\nimport time\n\nimport pygame\nfrom pygame.locals import *\n\nfrom .schedule import Scheduler\n\n\nclass Window(object):\n def __init__(self, width, height, flags=0):\n self.log = logging.getLogger('Windw')\n self.log.info('++ Creating new window object ({},{})'.format(width,\n height))\n self.width = width\n self.height = height\n pygame.init()\n self.screen = pygame.display.set_mode((width, height), flags)\n self.running = True\n # Stack stuff\n self.last_state = None\n self.state_stack = []\n # Stuff for FPS calc\n self.frame_count = 0\n self.update_count = 0\n self.fps = 0\n self.ups = 0\n # Schedule and timing stuff\n self.scheduler = Scheduler()\n self.gfx_timer = self.scheduler.new_updates_timer(60)\n self.update_timer = self.scheduler.new_updates_timer(100)\n self.last_time = pygame.time.get_ticks()\n self.last_fps_time = self.last_time\n\n def push_state(self, state_cls, *args, **kwargs):\n state = state_cls(self, *args, **kwargs)\n ss_len = len(self.state_stack)\n if ss_len > 0:\n top_state = self.state_stack[ss_len-1]\n top_state.on_state_lose_focus()\n self.log.info('>> Pushing: {}'.format(state.name))\n self.state_stack.append(state)\n\n def pop_state(self, state=None):\n # Check to selectively remove a state from the stack rather than pop it\n if state is not None:\n self.state_stack.remove(state)\n self.log.info('<< Popped: {}'.format(state.name))\n return state\n # Call the change in focus\n popped_state = self.state_stack.pop()\n popped_state.on_state_lose_focus()\n self.log.info('<< Popped: {}'.format(popped_state.name))\n return popped_state\n\n def run(self):\n while self.running:\n # Check if state stack is empty\n if len(self.state_stack) == 0:\n self.running = False\n break\n\n ss_len = len(self.state_stack)\n top_state = self.state_stack[ss_len-1]\n\n # Check to see if the top state has changed and call focus\n if top_state is not self.last_state:\n self.last_state = top_state\n top_state.on_state_gain_focus()\n\n # Send events to or state\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n top_state.on_keydown(event)\n elif event.type == KEYUP:\n top_state.on_keyup(event)\n elif event.type == QUIT:\n self.log.info('Caught WM_QUIT')\n top_state.on_quit()\n elif event.type == ACTIVEEVENT:\n if event.gain == 1:\n top_state.on_window_gain_focus()\n else:\n top_state.on_window_lose_focus()\n elif event.type == MOUSEMOTION:\n top_state.on_mouse_motion(event)\n elif event.type == MOUSEBUTTONDOWN:\n top_state.on_mouse_button_down(event)\n elif event.type == MOUSEBUTTONUP:\n top_state.on_mouse_button_up(event)\n elif event.type == VIDEORESIZE:\n top_state.on_window_resize(event)\n else:\n self.log.info('Unhandled event: {}'.format(event))\n\n # calc delta time and call update\n current_time = pygame.time.get_ticks()\n delta_time = (current_time - self.last_time)\n self.scheduler.update(current_time, delta_time)\n\n any_update = False\n if self.update_timer.should_update():\n top_state.on_update(delta_time)\n self.update_count += 1\n any_update = True\n self.last_time = current_time\n\n # Call draw\n if self.gfx_timer.should_update():\n self.frame_count += 1\n top_state.on_draw()\n any_update = True\n\n if current_time > (self.last_fps_time + 1000):\n self.fps = self.frame_count\n self.ups = self.update_count\n self.last_fps_time = current_time\n self.frame_count = 0\n self.update_count = 0\n fps_label = 'fps:{} ups:{}'.format(self.fps, self.ups)\n # self.log.info(fps_label)\n\n if any_update is False:\n pygame.time.wait(10)\n pygame.quit()\n","sub_path":"knuckle/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"622557645","text":"import os\n\nfrom ledger.stores.file_store import FileStore\n\n\nclass TextFileStore(FileStore):\n def __init__(self, dbDir, dbName, isLineNoKey: bool=False,\n storeContentHash: bool=True, ensureDurability: bool=True):\n # This is the separator between key and value\n self.delimiter = \"\\t\"\n self.lineSep = os.linesep\n super().__init__(dbDir, dbName, isLineNoKey, storeContentHash,\n ensureDurability)\n self._initDB(dbDir, dbName)\n\n def _initDB(self, dbDir, dbName):\n super()._initDB(dbDir, dbName)\n self.dbPath = os.path.join(os.path.expanduser(dbDir), dbName)\n self.dbFile = open(self.dbPath, mode=\"a+\")\n\n def _getLines(self):\n return (line.strip(self.lineSep) for line in\n self.dbFile if len(line.strip(self.lineSep)) != 0)\n","sub_path":"ledger/stores/text_file_store.py","file_name":"text_file_store.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"466496323","text":"#!/usr/bin/env python\n# coding: utf-8\n# export LC_ALL=en_US.utf-8\n# export LANG=en_US.utf-8\n# uvicorn ProductCompareFast:app --reload\n\nimport pandas as pd\nfrom fastapi import FastAPI, File, UploadFile, Response\nfrom sqlalchemy import create_engine\n\napp = FastAPI()\n\napp.__doc__ = \"Instantiate FastAPI object. This is entry point for api.\"\n\n\"\"\"Allowed extension for batch load is just csv. It can be further improved by adding more.\"\"\"\nALLOWED_EXTENSIONS = {'csv'}\n\"\"\"Api will interact with mysql database. Here we are using pymysql as connector.\"\"\"\ndb_connection_str = 'mysql+pymysql://root:admin@2020@mysql/ProductCompare'\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\nallowed_file.__doc__ = \"Filter out only supported file format.\"\n\n\n@app.get(\"/match/{productName}/{category}\")\nasync def match(product_name, category):\n sql = \"\"\"select pro_name,cat_name,description,price,rating,url,web_name from ProductCompare.product_description a \n join ProductCompare.category b on a.cat_id = b.cat_id\n join ProductCompare.products c on a.pro_id = c.pro_id\n join ProductCompare.review d on a.rew_id = d.rew_id \n where lower(pro_name) like lower('%\"\"\" + product_name + \"\"\"%') and \n lower(cat_name) like lower('%\"\"\" + category + \"\"\"%') order by rating DESC\"\"\"\n db_connection = create_engine(db_connection_str)\n output = pd.read_sql(sql, db_connection)\n return output\n\n\nmatch.__doc__ = \"\"\"Provide search result based on product name and category. \nIt calls database and return pandas dataframe, which is basically json. Since it is async method, \nit is highly capable of handling multiple request at a time.\"\"\"\n\n\ndef read(table):\n db_connection = create_engine(db_connection_str)\n df = pd.read_sql_table(table, con=db_connection)\n db_connection.dispose()\n return df\n\n\nread.__doc__ = \"Helper method to read table from mysql database. It uses sqlAlchemy as connector.\"\n\n\ndef write(data, table):\n db_connection = create_engine(db_connection_str)\n data.to_sql(name=table, con=db_connection, if_exists='append', index=False)\n db_connection.dispose()\n\n\nwrite.__doc__ = \"Helper method to write pandas dataframe into mysql database. It uses sqlAlchemy as connector.\"\n\n\n@app.post(\"/push/{object}\")\nasync def push(object):\n return Response(\"Yet to implement.\", status_code=400)\n\n\npush.__doc__ = \"Provide endpoint to insert single product into database. It is yet to implement.\"\n\n\n@app.get(\"/pull/{object}\")\nasync def pull(object):\n return Response(\"Yet to implement\", status_code=400)\n\n\npush.__doc__ = \"Provide endpoint to pull single product into database. It is yet to implement.\"\n\n\n@app.post(\"/batchLoad/\")\nasync def batchLoad(file: UploadFile = File(...)):\n if file and allowed_file(file.filename):\n read_products = await readFile(file)\n category = await insertData(read_products, \"category\", [\"cat_name\"])\n products = await insertData(read_products, \"products\", [\"pro_name\", \"web_name\"])\n review = await insertData(read_products, \"review\", [\"review\", \"rating\"])\n\n description = read_products.merge(category, how='inner', on=['cat_name']). \\\n merge(products, how='inner', on=['pro_name', 'web_name']). \\\n merge(review, how='inner', on=['review', 'rating'])[\n ['pro_id', 'cat_id', 'rew_id', 'price', 'description', 'url']]\n\n await insertData(description, \"product_description\",\n ['pro_id', 'cat_id', 'rew_id', 'price', 'description', 'url'])\n return Response(\"Products loaded successfully.\")\n else:\n return Response(\"Sorry. We are working hard on adding new file types, but as of now please use csv.\",\n status_code=400)\n\n\nbatchLoad.__doc__ = \"\"\"Provide endpoint to batch import multiple products into database. \nIt uses pandas for data selection and normalization. It insert into category, product, review to get numerical value \ncorresponds to their categorical value and uses them to create product_description table. As of now only csv support \nprovide for batch load. In future it can be expandable to other extensions as well.\"\"\"\n\n\nasync def readFile(file):\n data = pd.DataFrame(list(map(lambda s: s.decode(\"utf-8\").replace(\"\\n\", \"\").split(\",\"), file.file.readlines())))\n headers = data.iloc[0]\n read_products = pd.DataFrame(data.values[1:], columns=headers)[['product_name', \"price\", \"rating\",\n \"category\", \"product_description\",\n \"customer_reviews\", \"url\", \"website\"]]. \\\n rename(columns={\"category\": \"cat_name\", \"product_name\": \"pro_name\", \"customer_reviews\": \"review\",\n \"website\": \"web_name\", \"product_description\": \"description\"})\n return read_products\n\n\nreadFile.__doc__ = \"\"\"This is helper function of batchload. This function read input data csv/file in pandas and select \n only useful columns. It also rename it to make it generic for future join conditions.\"\"\"\n\n\nasync def insertData(data, table, cols):\n new_cat = data[cols].drop_duplicates(). \\\n merge(read(table)[cols].drop_duplicates(), on=cols, how='left', indicator=True). \\\n query(\"_merge=='left_only'\")\n del new_cat[\"_merge\"]\n write(new_cat, table)\n df = read(table)\n return df\n\n\ninsertData.__doc__ = \"\"\"This is helper function of batchload. This function check for new metadata value from \nincoming data and update relevant table into database. \"\"\"\n","sub_path":"ProductCompareService/ProductCompareFast.py","file_name":"ProductCompareFast.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"138004786","text":"\"\"\"\n\nSmallest sequence with given Primes\nProblem Description\n\nGiven three prime number(A, B, C) and an integer D. Find the first(smallest) D integers which have only A, B, C or a combination of them as their prime factors.\n\n\n\nProblem Constraints\n1 <= A, B, C <= 10000\n\n1 <= D <= 100000\n\n\n\nInput Format\nFirst argument is an integer A.\nSecond argument is an integer B.\nThird argument is an integer C.\nFourth argument is an integer D.\n\n\n\nOutput Format\nReturn an integer array of size D, denoting the first D integers described above.\n\nNOTE: The sequence should be sorted in ascending order\n\n\n\nExample Input\nInput 1:\n\n A = 2\n B = 3\n C = 5\n D = 5\nInput 2:\n\n A = 3\n B = 2\n C = 7\n D = 3\n\n\nExample Output\nOutput 1:\n\n [2, 3, 4, 5, 6]\nOutput 2:\n\n [2, 3, 4]\n\n\nExample Explanation\nExplanation 1:\n\n 4 = A * A ( 2 * 2 ), 6 = A * B ( 2 * 3 )\nExplanation 2:\n\n 2 has only prime factor 2. Similary 3 has only prime factor 3. 4 = A * A ( 2 * 2 )\n\n\"\"\"\n\n\nclass Solution:\n\t# @param A : integer\n\t# @param B : integer\n\t# @param C : integer\n\t# @param D : integer\n\t# @return a list of integers\n\tdef solve(self, A, B, C, D):\n\t ans = [0]*(D+1)\n\t ans[0] = 1\n\t \n\t first = 0\n\t second = 0\n\t third = 0\n\t \n\t for i in range(1, D+1):\n\t ans[i] = min(ans[first]*A , ans[second]*B, ans[third]*C)\n\t \n\t if ans[i] == ans[first]*A:\n\t first += 1\n\t \n\t if ans[i] == ans[second]*B:\n\t second += 1\n\t \n\t if ans[i] == ans[third]*C:\n\t third += 1\n\t \n\t return ans[1:]\n\t \n","sub_path":"Graph/Smallest sequence with given Primes.py","file_name":"Smallest sequence with given Primes.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"200616801","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('authors/addbook/', views.add_toAuthor),\n path('books/addauthor/', views.add_toBook),\n path('authors/add', views.addAuthor),\n path('books/add', views.addBook),\n path('authors/', views.authorDetails),\n path('books/', views.bookDetails),\n path('authors', views.showAuthors),\n path('', views.index),\n]","sub_path":"Books_Authors_APP/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249093057","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport logging\nfrom logging import info, debug\nimport optparse\nfrom glob import glob\nfrom subprocess import call, check_call\nimport vcfnp\nimport numpy as np\n\n\ndef build_arrays(vcf_fn, region, samples=None, force=False, ploidy=1, fields=['AD'], arities=dict(AD=2), progress=10000, calldata_file_suffix='.calldata.npy'):\n \n variants_array_fn = vcf_fn + '.' + region.replace('-:', '_') + '.variants.npy'\n if force or not os.path.exists(variants_array_fn):\n print >>sys.stderr, 'building', variants_array_fn\n V = vcfnp.variants(vcf_fn, region=region, progress=progress,\n fields=['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'num_alleles', 'is_snp', 'svlen', 'CODING', 'NS', 'UQ', 'DP'],\n dtypes=[('CHROM', 'S12'), ('POS', '>sys.stderr, 'skipping', variants_array_fn \n \n # info_array_fn = vcf_fn + '.' + region.replace('-:', '_') + '.info.npy'\n # if force or not os.path.exists(info_array_fn):\n # print >>sys.stderr, 'building', info_array_fn\n # I = vcfnp.info(vcf_fn, region=region, progress=progress, fields=['NS', 'UQ', 'CODING', 'DP', 'AD'], vcf_types={'DP': 'Integer', 'AD': 'Integer'}, arities={'AD': 2})\n # np.save(info_array_fn, I)\n # else:\n # print >>sys.stderr, 'skipping', info_array_fn\n #\n calldata_array_fn = vcf_fn + '.' + region.replace('-:', '_') + calldata_file_suffix\n if force or not os.path.exists(calldata_array_fn):\n print >>sys.stderr, 'building', calldata_array_fn\n C = vcfnp.calldata(vcf_fn, region=region, progress=progress, ploidy=ploidy, fields=fields, arities=arities, samples=samples)\n np.save(calldata_array_fn, C)\n else:\n print >>sys.stderr, 'skipping', calldata_array_fn\n\ndef main(options, args):\n \n # init task index\n if options.task_index is not None:\n task = options.task_index\n elif 'SGE_TASK_ID' in os.environ:\n task = int(os.environ['SGE_TASK_ID'])\n else:\n raise Exception('could not determine task index; %s', options)\n \n info('begin')\n \n # chromosomes\n chromosomes = ['Pf3D7_%02d_v3' % i for i in range(1, 15)]\n\n # dereference task index to chromosome\n chrom = chromosomes[task-1]\n info(chrom)\n \n # load samples\n samples = np.loadtxt(options.sample_fn, dtype='a15')\n \n # load array\n build_arrays(options.vcf_fn, region=chrom, samples=samples, calldata_file_suffix=options.calldata_file_suffix)\n \n # done\n info('end')\n \n \nif __name__ == '__main__':\n\n # handle command line options\n parser = optparse.OptionParser()\n # N.B., use either -I or -i -s depending on whether input BAM has been split by chromosome or not\n parser.add_option('-v', '--vcf-file', dest='vcf_fn', metavar='FILE', default=None,\n help='input vcf file')\n parser.add_option('-s', '--sample-file', dest='sample_fn', metavar='FILE',\n help='file of samples to be loaded, text, one sample per line')\n parser.add_option('-c', '--calldata-file-suffix', dest='calldata_file_suffix', metavar='FILE',\n default='.calldata.npy',\n help='suffix for calldata numpy files')\n parser.add_option('-n', '--task-index', dest='task_index', metavar='INTEGER',\n default=None, type='int',\n help='override task index (otherwise obtained via environment variable)')\n parser.add_option('-l', '--log-level', dest='log_level', metavar='LEVEL',\n default='DEBUG',\n help='logging level')\n options, args = parser.parse_args()\n \n # init logging\n logging.basicConfig(level=getattr(logging, options.log_level.upper()),\n format='[%(levelname)s] [%(filename)s] %(asctime)s %(message)s')\n\n main(options, args)\n \n","sub_path":"scripts/cluster/steps/build_numpy_arrays_4_0.py","file_name":"build_numpy_arrays_4_0.py","file_ext":"py","file_size_in_byte":4669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"211077881","text":"# envia lectura al servidor\r\n# sudo timedatectl set-timezone America/Bogota\r\nimport socket\r\nimport json\r\n\r\ndef http_get(url):\r\n _, _, host, path = url.split('/', 3)\r\n host = 'myfinan.com'\r\n addr = socket.getaddrinfo(host, 8085)[0][-1]\r\n s = socket.socket()\r\n s.connect(addr)\r\n print(addr, path)\r\n s.send(bytes('GET /%s HTTP/1.0\\r\\nHost: %s\\r\\n\\r\\n' % (path, host), 'utf8'))\r\n result = ''\r\n while True:\r\n data = s.recv(100)\r\n if data:\r\n result = result + str(data, 'utf8')\r\n else:\r\n break\r\n s.close()\r\n return result\r\n\r\ndef grabaMovimiento(IDlector, codigo, fecha, concepto, preciov, precioc, cantidad):\r\n# def agregaLecturaI(email, clave, IDlector, concepto, cb, cantidad, precioc, preciov, fecha):\r\n http_get(\"http://myfinan.com:8085/function/GrabaMovimientoI('oscartienda@gmail.com','oscar',%s,'%s','%s', %s, %s,%s,'%s')?pagina=invadmov\" \r\n % (IDlector, concepto, codigo, cantidad, precioc, preciov, fecha))\r\n\r\n# grabaMovimiento(1, '62230012457', '2019-10-13', 's', 600, 500, 1) # nuevo\r\ngrabaMovimiento(1, '62230012452', '2019-10-13', 's', 600, 500, 1) # galleta ritz\r\n# agregaLectura(1, '702914164009', '2019-10-14', 's', 700, 600, 1) # chocoramo mini\r\n","sub_path":"py/lector/p3.py","file_name":"p3.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"293021352","text":"__author__ = 'mohammadreza'\n\n# AN AI PROJECT\n# PLZ INSTALL PYTHON 2.6 AND SVMLIB + BINDINGS\n\nimport re\nimport csv\nimport pickle\nimport svm\nfrom svmutil import *\n\n_stopwordFileName = \"stopwords.txt\"\n\ndef preProcess(tweet):\n #to lower case\n tweet = tweet.lower()\n #remove links\n tweet = re.sub('((www\\.[^\\s]+)|(https?://[^\\s]+))','',tweet)\n #remove @'s\n tweet = re.sub('@[^\\s]+','',tweet)\n #remove additional white spaces\n tweet = re.sub('[\\s]+', ' ', tweet)\n #Replace #tag with tag\n tweet = re.sub(r'#([^\\s]+)', r'\\1', tweet)\n tweet = tweet.strip('\\'\"')\n return (tweet)\n\ndef simplifyLongWords(w):\n #simplify words with more than 2 recurring characters \"salaaaaaaam\" ,\"salaaaam\" , \"salaaaaaaaaaam\" ===> \"salaam\"\n pattern = re.compile(r\"(.)\\1{1,}\", re.DOTALL)\n return (pattern.sub(r\"\\1\\1\", w))\ndef save_classifier(classifier):\n f = open(\"savedClassifier\", 'wb')\n pickle.dump(classifier, f)\n f.close()\n\ndef load_classifier():\n f = open(\"savedClassifier\", 'rb')\n classifier = pickle.load(f)\n f.close()\n return classifier\n\ndef getStopWords():\n stopwords = []\n for line in open(_stopwordFileName).readlines():\n stopwords.append(line.strip(\"\\n\"))\n return (stopwords)\nstopwords = getStopWords()\n\ndef getFeatures(tweet):\n v = [] #feature vector\n bagOfWords = tweet.split()\n for word in bagOfWords :\n word = simplifyLongWords(word)\n word = word.strip('\\'\"?.,.')\n startsWithAZ = re.search(r\"^[a-zA-Z][a-zA-Z0-9]*$\", word)\n if(word in stopwords or startsWithAZ == None):\n continue\n else :\n v.append(word.lower())\n return v\n\n\n\n#### START OF PROGRAM\nprint(\"......INITIATING THE SENTI BOT ....\")\nprint(\"- CODED BY MOHAMMAD REZA BARAZESH -\")\nprint(\"___________ AL73rnA _______________\")\n####\nlearningSet = csv.reader(open(\"learning.csv\"))\nAllFeatures = []\nAllTweets = []\n\ndef featureVector(tweet):\n tweet_words = set(tweet)\n features = {}\n for word in AllFeatures:\n features[word] = (word in tweet_words)\n return features\n\n\nAllFeatures = list(set(AllFeatures)) # feture list\n###\nprint(\"-Training a new classifier ...\")\nprint(\"-Reading Learning set file\")\n###\nfor line in learningSet :\n sentiment = line[0]\n tweet = line[1]\n processedTweet = preProcess(tweet)\n tweetFeatures = getFeatures(processedTweet)\n AllFeatures.extend(tweetFeatures)\n AllTweets.append((tweetFeatures,sentiment))\n###\n\n\n### START OF SVM TRAINING\n\n\ndef getSVMFeatureVectorAndLabels(tweets, featureList):\n sortedFeatures = sorted(featureList)\n map = {}\n feature_vector = []\n labels = []\n for t in tweets:\n label = 0\n map = {}\n #Initialize empty map\n for w in sortedFeatures:\n map[w] = 0\n\n tweet_words = t[0]\n tweet_opinion = t[1]\n #Fill the map\n for word in tweet_words:\n #process the word (remove repetitions and punctuations)\n word = replaceTwoOrMore(word)\n word = word.strip('\\'\"?,.')\n #set map[word] to 1 if word exists\n if word in map:\n map[word] = 1\n #end for loop\n values = map.values()\n feature_vector.append(values)\n if(tweet_opinion == 'positive'):\n label = 0\n elif(tweet_opinion == 'negative'):\n label = 1\n elif(tweet_opinion == 'neutral'):\n label = 2\n labels.append(label)\n #return the list of feature_vector and labels\n return {'feature_vector' : feature_vector, 'labels': labels}\n#end\n\n#Train the SVM\nresult = getSVMFeatureVectorandLabels(AllTweets, AllFeatures)\nproblem = svm_problem(result['labels'], result['feature_vector'])\n#'-q' DONT SIDPLAY CONSOLE OUTPUT\nparam = svm_parameter('-q')\nparam.kernel_type = LINEAR\nclassifier = svm_train(problem, param)\nsvm_save_model(classifierDumpFile, classifier)\n\n#Test the classifier\ntest_feature_vector = getSVMFeatureVector(test_tweets, featureList)\n#p_labels contains the final labeling result\np_labels, p_accs, p_vals = svm_predict([0] * len(test_feature_vector),test_feature_vector, classifier)","sub_path":"sentibotSVM.py","file_name":"sentibotSVM.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"212406596","text":"import pandas as pd\nimport requests\nimport json\nimport time\n\ndf = pd.read_csv('data/challenger_match_V2.csv')\ngames = df['gameId'].unique()\nind = 0\n\n# PLAYER_LIMIT = 20\nPLAYER_LIMIT = 5000\nplayers_to_follow = []\nregion = 'kr'\n\napi_key = input(\"API KEY: \")\n\nwhile (len(players_to_follow) < PLAYER_LIMIT):\n request_url = 'https://' + region + '.api.riotgames.com/lol/match/v4/matches/' + str(games[ind]) + '?api_key=' + api_key\n x = requests.get(request_url)\n print(x.status_code)\n while x.status_code == 429: # to go rapidfire...\n time.sleep(float(x.headers['Retry-After']))\n x = requests.get(request_url) # retry\n\n # only put in good results\n if x.status_code == 200:\n x = x.json()\n print(len(players_to_follow))\n for obj in x[\"participantIdentities\"]:\n summonerName = obj[\"player\"][\"summonerName\"]\n print(summonerName)\n if summonerName not in players_to_follow: \n players_to_follow.append(summonerName)\n else:\n pass\n \n ind += 1\n\nprint(players_to_follow)\nprint(len(players_to_follow))\n\n#####################################################################################################################################################################################\n#####################################################################################################################################################################################\n\nimport pandas as pd\nimport xlrd\nimport requests\nimport json\n\n### for each player, get their accountId\ndef get_player_matches(name):\n request_url = 'https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/' + name + '?api_key=' + api_key\n x = requests.get(request_url)\n if x.status_code == 200:\n return x.json()['accountId']\n return None\n\ndef get_matchlist(accountId):\n if accountId is None:\n return None\n \n request_url = 'https://euw1.api.riotgames.com/lol/match/v4/matchlists/by-account/' + accountId + '?api_key=' + api_key\n x = requests.get(request_url)\n if x.status_code == 200:\n x = x.json()\n else:\n return None\n\n result = []\n MAX_MATCHES = 15\n # MAX_MATCHES = 10\n for match in x['matches']:\n if len(result) == MAX_MATCHES: # cap it at 15, don't wanna overload api (and my brain)\n return result\n\n # [TODO] only filter timestamps during touranment time (ex. lck, lpl)\n region = match['platformId']\n game_id = match['gameId']\n result.append((region, game_id))\n \n return result\n\n# automate pulling match data from matchURL\nimport time\ndef get_match_data(matchlist):\n if matchlist is None:\n return []\n \n result = []\n for region, match_id in matchlist:\n request_url = 'https://' + region + '.api.riotgames.com/lol/match/v4/matches/' + str(match_id) + '?api_key=' + api_key\n print(request_url)\n x = requests.get(request_url)\n \n while x.status_code == 429: # to go rapidfire...\n print(\"headers:\", x.headers)\n time.sleep(float(x.headers['Retry-After']))\n x = requests.get(request_url) # retry\n\n # only put in good results\n if x.status_code == 200:\n result.append(x)\n print(len(result))\n else:\n pass\n\n return result\n\n# pull together different parts of the request\n# pull participant username to main stats\ndef compile_participant_data(request, summonerName):\n participant_mapping = request[\"participantIdentities\"]\n participant_detail = request[\"participants\"]\n \n # participant_mapping for SELF ONLY\n mapping = next((item for item in participant_mapping if item[\"player\"][\"summonerName\"] == summonerName), None)\n if mapping is None:\n return None\n\n id = mapping[\"participantId\"]\n p_data = next(item for item in participant_detail if item[\"participantId\"] == id)\n p_data[\"summonerName\"] = mapping[\"player\"][\"summonerName\"]\n\n return p_data\n\n# flatten into stats we can use\ndef flatten(data, participant):\n # utility\n def if_true(condition, true, false=None):\n if condition: \n return true\n return true\n def select_properties(quals, select_from, prefix=''):\n result = {}\n for item in quals: \n\n # ensure key is there, if not signal taht isn't there\n if item not in select_from:\n result[prefix+item] = \"NaN\"\n return result\n\n # convert bools to 1 or 0\n if isinstance(select_from[item], bool):\n select_from[item] = int(select_from[item] == True)\n result[prefix+item] = select_from[item]\n return result\n\n stats = participant[\"stats\"]\n props = [\n \"item0\", \n \"item1\", \n \"item2\", \n \"item3\", \n \"item4\", \n \"item5\", \n \"item6\",\n \"perk0\",\n \"perk0Var1\", \n \"perk0Var2\",\n \"perk0Var3\", \n \"perk1\",\n \"perk1Var1\", \n \"perk1Var2\",\n \"perk1Var3\", \n \"perk2\",\n \"perk2Var1\", \n \"perk2Var2\",\n \"perk2Var3\", \n \"perk3\",\n \"perk3Var1\", \n \"perk3Var2\",\n \"perk3Var3\", \n \"perk4\",\n \"perk4Var1\", \n \"perk4Var2\",\n \"perk4Var3\", \n \"perk5\",\n \"perk5Var1\", \n \"perk5Var2\",\n \"perk5Var3\",\n \"perkPrimaryStyle\",\n \"perkSubStyle\",\n \"statPerk1\",\n \"statPerk2\", \n ]\n qualt_stats = select_properties(props, stats)\n props = [\n \"summonerName\",\n \"championId\",\n \"spell1Id\", \n \"spell2Id\",\n ]\n qualt_stats.update(select_properties(props, participant))\n props = [\n \"role\",\n \"lane\" \n ]\n qualt_stats.update(select_properties(props, participant[\"timeline\"]))\n\n props = [\n \"win\", # bool\n \"kills\",\n \"deaths\",\n \"assists\",\n \"largestKillingSpree\",\n \"largestMultiKill\",\n \"killingSprees\",\n \"longestTimeSpentLiving\",\n \"doubleKills\",\n \"tripleKills\",\n \"quadraKills\",\n \"pentaKills\",\n \"unrealKills\",\n \"totalDamageDealt\",\n \"magicDamageDealt\",\n \"physicalDamageDealt\",\n \"trueDamageDealt\",\n \"largestCriticalStrike\",\n \"totalDamageDealtToChampions\",\n \"magicDamageDealtToChampions\",\n \"physicalDamageDealtToChampions\",\n \"trueDamageDealtToChampions\",\n \"totalHeal\",\n \"totalUnitsHealed\",\n \"damageSelfMitigated\",\n \"damageDealtToObjectives\",\n \"damageDealtToTurrets\",\n \"visionScore\",\n \"timeCCingOthers\",\n \"totalDamageTaken\",\n \"magicalDamageTaken\",\n \"physicalDamageTaken\",\n \"trueDamageTaken\",\n \"goldEarned\",\n \"goldSpent\",\n \"turretKills\",\n \"inhibitorKills\",\n \"totalMinionsKilled\",\n \"neutralMinionsKilled\",\n \"neutralMinionsKilledTeamJungle\",\n \"neutralMinionsKilledEnemyJungle\",\n \"totalTimeCrowdControlDealt\",\n \"champLevel\",\n \"visionWardsBoughtInGame\",\n \"sightWardsBoughtInGame\",\n \"wardsPlaced\",\n \"wardsKilled\",\n \"firstBloodKill\",\n \"firstBloodAssist\",\n \"firstTowerKill\",\n \"firstTowerAssist\",\n \"firstInhibitorKill\",\n \"firstInhibitorAssist\",\n ]\n metrics = select_properties(props, stats)\n\n props = [\n \"0-10\",\n \"10-20\",\n \"20-30\",\n ]\n participant_key = [\"creepsPerMinDeltas\", \"xpPerMinDeltas\", \"goldPerMinDeltas\", \"xpDiffPerMinDeltas\", \"damageTakenPerMinsDeltas\", \"damageTakenDiffPerMinsDeltas\"]\n for key in participant_key: \n if key in participant[\"timeline\"]:\n metrics.update(select_properties(props, participant[\"timeline\"][key], key))\n else:\n metrics.update({\n key + \"0-10\": \"NaN\",\n key + \"10-20\": \"NaN\",\n key + \"20-30\": \"NaN\",\n })\n\n return (qualt_stats, metrics)\n\ndef pj(inp):\n print(json.dumps(inp, indent=2))\n\n#####################################################################################################################################################################################\n\ndef write_summoner_to_csv(summonerName, has_headers):\n accountId = get_player_matches(summonerName)\n # print(accountId)\n if accountId is None:\n return\n\n matchlist = get_matchlist(accountId)\n # print(matchlist)\n\n data = get_match_data(matchlist)\n # print(data)\n\n writeable = []\n writeableq = [] # qualitative values (not used for clustering)\n\n for first_match in data:\n first_match = first_match.json()\n match_data = compile_participant_data(first_match, summonerName)\n if match_data is None:\n continue\n\n flattened = flatten(first_match, match_data)\n\n # write quant data\n base = {\n \"summonerName\": flattened[0][\"summonerName\"]\n } \n base.update(flattened[1])\n writeable.append(base)\n\n # write qual data\n base = {\n \"summonerName\": flattened[0][\"summonerName\"]\n }\n base.update(flattened[0])\n writeableq.append(base)\n\n # print(writeable)\n # print(writeableq)\n\n # put into csv\n import csv\n def to_csv(row, filepath):\n with open(filepath, 'a') as f: # Just use 'w' mode in 3.x\n w = csv.DictWriter(f, row.keys())\n w.writerow(row)\n\n if not has_headers:\n ### write header\n with open('write_quant_challenger.csv', 'w') as f: # Just use 'w' mode in 3.x\n w = csv.DictWriter(f, writeable[0].keys())\n w.writeheader()\n with open('write_qual_challenger.csv', 'w') as f: # Just use 'w' mode in 3.x\n w = csv.DictWriter(f, writeableq[0].keys())\n w.writeheader()\n\n ### write data\n for match in writeable:\n to_csv(match, 'write_quant_challenger.csv')\n\n\n\n\n ### write qualitative data\n\n # conversions for qualitative data (ids in riot system) to filtering\n def process_champion_data(id):\n x = requests.get('https://cdn.communitydragon.org/10.25.1/champion/' + str(id) + '/data')\n return x.json()[\"name\"]\n\n # championName = process_champion_data(83)\n # print(championName)\n\n def process_item_data(item_number):\n f = open('cdragon_en_US/item.json') \n items = json.load(f)\n\n # catch nonexistent lul\n if str(item_number) not in items[\"data\"]: \n return \"NaN\"\n\n return items[\"data\"][str(item_number)][\"name\"]\n\n # itemName = process_item_data(3153)\n # print(itemName)\n\n def process_perk_data(perkData): # [perk1, perk1Var1, perk1Var2, perk1Var3]\n # edge case\n if perkData == 0:\n return \"\"\n\n f = open('cdragon_en_US/runesReforged.json') \n runes = json.load(f)\n # flatten\n flattened = []\n # print(\"flatten\")\n # print(json.dumps(runes, indent=2))\n for i in range(len(runes)):\n for elem in runes[i][\"slots\"]: \n flattened += elem[\"runes\"]\n\n # print(json.dumps(flattened, indent=2))\n result = next((x for x in flattened if x[\"id\"] == perkData), None)\n\n # catch nonexistent lul\n if result is None:\n return 'NaN'\n\n return result[\"key\"]\n\n # perkName = process_perk_data(8237)\n # print(perkName)\n\n def process_spell_data(spell_id):\n f = open('cdragon_en_US/summoner.json') \n summoner_metadata = json.load(f)\n # flatten\n flattened = []\n # print(\"flatten\")\n # print(json.dumps(summoner_metadata[\"data\"], indent=2))\n result = next((summoner_metadata[\"data\"][i] for i in summoner_metadata[\"data\"] if summoner_metadata[\"data\"][i][\"key\"] == str(spell_id)), None)\n # print('result', result)\n\n if result is None:\n return 'NaN'\n \n return result[\"name\"]\n\n # spellName = process_spell_data(12)\n # print(spellName)\n\n # replace item names\n for match in writeableq:\n props = ['item0', 'item1', 'item2', 'item3', 'item4', 'item5', 'item6']\n for key in range(len(props)):\n item_id = props[key]\n if item_id not in match:\n continue\n match[item_id] = process_item_data(match[item_id])\n \n props = [\n 'perk0', 'perk0Var1', 'perk0Var2', 'perk0Var3', \n 'perk1', 'perk1Var1', 'perk1Var2', 'perk1Var3', \n 'perk2', 'perk2Var1', 'perk2Var2', 'perk2Var3', \n 'perk3', 'perk3Var1', 'perk3Var2', 'perk3Var3',\n 'perk4', 'perk4Var1', 'perk4Var2', 'perk4Var3',\n 'perk5', 'perk5Var1', 'perk5Var2', 'perk5Var3',\n 'perkPrimaryStyle',\n 'perkSubStyle',\n 'statPerk1', 'statPerk2'\n ]\n for key in range(len(props)):\n perk_id = props[key]\n if perk_id not in match:\n continue\n match[perk_id] = process_perk_data(match[perk_id])\n\n props = [\n 'championId'\n ]\n for key in range(len(props)):\n champ_id = props[key]\n if champ_id not in match:\n continue\n match[champ_id] = process_champion_data(match[champ_id])\n\n props = [\n 'spell1Id',\n 'spell2Id'\n ]\n for key in range(len(props)):\n spell_id = props[key]\n if spell_id not in match:\n continue\n match[spell_id] = process_spell_data(match[spell_id])\n\n # perform write operation\n for match in writeableq:\n to_csv(match, 'write_qual_challenger.csv')\n\n#####################################################################################################################################################################################\n\n# df = pd.read_csv('league_pro_matches_data/2019-spring-match.csv')\n# players_to_follow = df['player'].unique()\n\n# manually map everything holy moly\n# server_mappings = {\n# 'Fnatic': 'eu1'\n# }\n\n# create script to automate riot api sample requests and fill in csv\n# api_key = input(\"API KEY: \")\n\n# summonerName = 'Bwipo'\nhas_headers = False\n\nfor summonerName in players_to_follow:\n write_summoner_to_csv(summonerName, has_headers)\n has_headers = True\n","sub_path":"riot_to_csv.py","file_name":"riot_to_csv.py","file_ext":"py","file_size_in_byte":14584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"232563751","text":"# dataset settings\n# D5 in the config name means the whole dataset is divided into 5 folds\n# We only use one fold for efficient experiments\ndataset_type = 'WaymoDataset'\n# data_root = 's3://openmmlab/datasets/detection3d/waymo/kitti_format/'\ndata_root = 'data/waymo/kitti_format/'\n\n# Example to use different file client\n# Method 1: simply set the data root and let the file I/O module\n# automatically infer from prefix (not support LMDB and Memcache yet)\n\n# data_root = 's3://openmmlab/datasets/detection3d/waymo/kitti_format/'\n\n# Method 2: Use backend_args, file_client_args in versions before 1.1.0\n# backend_args = dict(\n# backend='petrel',\n# path_mapping=dict({\n# './data/': 's3://openmmlab/datasets/detection3d/',\n# 'data/': 's3://openmmlab/datasets/detection3d/'\n# }))\nbackend_args = None\n\nclass_names = ['Car', 'Pedestrian', 'Cyclist']\nmetainfo = dict(classes=class_names)\n\npoint_cloud_range = [-74.88, -74.88, -2, 74.88, 74.88, 4]\ninput_modality = dict(use_lidar=True, use_camera=False)\ndb_sampler = dict(\n data_root=data_root,\n info_path=data_root + 'waymo_dbinfos_train.pkl',\n rate=1.0,\n prepare=dict(\n filter_by_difficulty=[-1],\n filter_by_min_points=dict(Car=5, Pedestrian=10, Cyclist=10)),\n classes=class_names,\n sample_groups=dict(Car=15, Pedestrian=10, Cyclist=10),\n points_loader=dict(\n type='LoadPointsFromFile',\n coord_type='LIDAR',\n load_dim=6,\n use_dim=[0, 1, 2, 3, 4],\n backend_args=backend_args),\n backend_args=backend_args)\n\ntrain_pipeline = [\n dict(\n type='LoadPointsFromFile',\n coord_type='LIDAR',\n load_dim=6,\n use_dim=5,\n backend_args=backend_args),\n dict(type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True),\n # dict(type='ObjectSample', db_sampler=db_sampler),\n dict(\n type='RandomFlip3D',\n sync_2d=False,\n flip_ratio_bev_horizontal=0.5,\n flip_ratio_bev_vertical=0.5),\n dict(\n type='GlobalRotScaleTrans',\n rot_range=[-0.78539816, 0.78539816],\n scale_ratio_range=[0.95, 1.05]),\n dict(type='PointsRangeFilter', point_cloud_range=point_cloud_range),\n dict(type='ObjectRangeFilter', point_cloud_range=point_cloud_range),\n dict(type='PointShuffle'),\n dict(\n type='Pack3DDetInputs',\n keys=['points', 'gt_bboxes_3d', 'gt_labels_3d'])\n]\ntest_pipeline = [\n dict(\n type='LoadPointsFromFile',\n coord_type='LIDAR',\n load_dim=6,\n use_dim=5,\n backend_args=backend_args),\n dict(\n type='MultiScaleFlipAug3D',\n img_scale=(1333, 800),\n pts_scale_ratio=1,\n flip=False,\n transforms=[\n dict(\n type='GlobalRotScaleTrans',\n rot_range=[0, 0],\n scale_ratio_range=[1., 1.],\n translation_std=[0, 0, 0]),\n dict(type='RandomFlip3D'),\n dict(\n type='PointsRangeFilter', point_cloud_range=point_cloud_range)\n ]),\n dict(type='Pack3DDetInputs', keys=['points'])\n]\n# construct a pipeline for data and gt loading in show function\n# please keep its loading function consistent with test_pipeline (e.g. client)\neval_pipeline = [\n dict(\n type='LoadPointsFromFile',\n coord_type='LIDAR',\n load_dim=6,\n use_dim=5,\n backend_args=backend_args),\n dict(type='Pack3DDetInputs', keys=['points']),\n]\n\ntrain_dataloader = dict(\n batch_size=2,\n num_workers=2,\n persistent_workers=True,\n sampler=dict(type='DefaultSampler', shuffle=True),\n dataset=dict(\n type='RepeatDataset',\n times=2,\n dataset=dict(\n type=dataset_type,\n data_root=data_root,\n ann_file='waymo_infos_train.pkl',\n data_prefix=dict(\n pts='training/velodyne', sweeps='training/velodyne'),\n pipeline=train_pipeline,\n modality=input_modality,\n test_mode=False,\n metainfo=metainfo,\n # we use box_type_3d='LiDAR' in kitti and nuscenes dataset\n # and box_type_3d='Depth' in sunrgbd and scannet dataset.\n box_type_3d='LiDAR',\n # load one frame every five frames\n load_interval=5,\n backend_args=backend_args)))\nval_dataloader = dict(\n batch_size=1,\n num_workers=1,\n persistent_workers=True,\n drop_last=False,\n sampler=dict(type='DefaultSampler', shuffle=False),\n dataset=dict(\n type=dataset_type,\n data_root=data_root,\n data_prefix=dict(pts='training/velodyne', sweeps='training/velodyne'),\n ann_file='waymo_infos_val.pkl',\n pipeline=eval_pipeline,\n modality=input_modality,\n test_mode=True,\n metainfo=metainfo,\n box_type_3d='LiDAR',\n backend_args=backend_args))\n\ntest_dataloader = dict(\n batch_size=1,\n num_workers=1,\n persistent_workers=True,\n drop_last=False,\n sampler=dict(type='DefaultSampler', shuffle=False),\n dataset=dict(\n type=dataset_type,\n data_root=data_root,\n data_prefix=dict(pts='training/velodyne', sweeps='training/velodyne'),\n ann_file='waymo_infos_val.pkl',\n pipeline=eval_pipeline,\n modality=input_modality,\n test_mode=True,\n metainfo=metainfo,\n box_type_3d='LiDAR',\n backend_args=backend_args))\n\nval_evaluator = dict(\n type='WaymoMetric',\n ann_file='./data/waymo/kitti_format/waymo_infos_val.pkl',\n waymo_bin_file='./data/waymo/waymo_format/gt.bin',\n data_root='./data/waymo/waymo_format',\n backend_args=backend_args,\n convert_kitti_format=False)\ntest_evaluator = val_evaluator\n\nvis_backends = [dict(type='LocalVisBackend')]\nvisualizer = dict(\n type='Det3DLocalVisualizer', vis_backends=vis_backends, name='visualizer')\n","sub_path":"configs/_base_/datasets/waymoD5-3d-3class.py","file_name":"waymoD5-3d-3class.py","file_ext":"py","file_size_in_byte":5853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"307664061","text":"from time import time\n\n\n# Первый вариант декоратора для измерения времени выполнения рекурсивной функции\ndef fun_exec_time_v1(function, currently_evaluating=None):\n if currently_evaluating is None:\n currently_evaluating = set()\n\n def wrapper_function(*args, **kwargs):\n if function in currently_evaluating:\n return function(*args, **kwargs)\n\n t1 = time()\n currently_evaluating.add(function)\n try:\n value = function(*args, **kwargs)\n finally:\n currently_evaluating.remove(function)\n t2 = time()\n print('time taken', t2 - t1)\n return value\n return wrapper_function\n\n\n# Второй вариант декоратора для измерения времени выполнения рекурсивной функции\ndef fun_exec_time_v2(function):\n is_evaluating = False\n\n def wrapper_function(*args, **kwargs):\n nonlocal is_evaluating\n if is_evaluating:\n return function(*args, **kwargs)\n\n t1 = time()\n is_evaluating = True\n try:\n value = function(*args, **kwargs)\n finally:\n is_evaluating = False\n t2 = time()\n print(f'time taken for function {function.__name__}:', t2 - t1)\n return value\n return wrapper_function\n\n\n@fun_exec_time_v2\ndef fib_rec(n: int):\n if n <= 1:\n return n\n return fib_rec(n-1) + fib_rec(n-2)\n\n\n@fun_exec_time_v2\ndef fib_dynamic(n: int):\n if n <= 1:\n return n\n x = y = 1\n for i in range(3, n+1):\n x, y = x + y, x\n return x\n\n\nprint(fib_rec(30))\nprint(fib_dynamic(35000))\n","sub_path":"dynamic_prog/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"223540493","text":"# encoding=utf8\n__author__ = \"Lukas Voegtle\"\n__email__ = \"voegtlel@tf.uni-freiburg.de\"\n\nimport numpy as np\n\n\ndef init_random_uniform(X_lower, X_upper, N, rng=None):\n \"\"\"\n Samples N data points uniformly.\n\n Parameters\n ----------\n X_lower: np.ndarray (D)\n Lower bounds of the input space\n X_upper: np.ndarray (D)\n Upper bounds of the input space\n N: int\n The number of initial data points\n\n Returns\n -------\n np.ndarray(N,D)\n The initial design data points\n \"\"\"\n if rng is None:\n rng = np.random.RandomState(np.random.randint(0, 10000))\n n_dims = X_lower.shape[0]\n return np.array([rng.uniform(X_lower, X_upper, n_dims) for _ in range(N)])\n","sub_path":"RoBO/build/lib.linux-x86_64-2.7/robo/initial_design/init_random_uniform.py","file_name":"init_random_uniform.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"446700218","text":"\"\"\"\n Pick star and call back\n Used by menu_bar.py\n\"\"\"\nfrom abc import ABC, abstractmethod\n\nimport matplotlib\n\nfrom abism.front import artist\nfrom abism.front import AnswerReturn as AR\n\nfrom abism.back import Strehl\n\nfrom abism.plugin.stat_rectangle import show_statistic\nfrom abism.plugin.profile_line import show_profile\n\nfrom abism.util import log, get_root, get_state, AsyncWorker\n\n\nclass Pick(ABC):\n \"\"\"Class for a connection:\n image event -> operation (then result display)\n Note: disconnection is not generic:\n sometime a matplotlit callback_id\n sometime a cutom artist\n \"\"\"\n def __init__(self):\n log(3, 'Pick: creating a', self.__class__.__name__, 'instance')\n self.canvas = get_root().frame_image.get_canvas()\n self.figure = get_root().frame_image.get_figure()\n self.ax = self.figure.axes[0]\n self.rectangle = None\n # Boolean: is work over\n self.done = False # Value('done', False)\n\n @abstractmethod\n def connect(self):\n \"\"\"Canvas may have changed\"\"\"\n log(3, 'Pick: connecting a', self.__class__.__name__, 'instance')\n self.canvas = get_root().frame_image.get_canvas()\n self.figure = get_root().frame_image.get_figure()\n self.ax = self.figure.axes[0]\n\n @abstractmethod\n def disconnect(self): pass\n\n @abstractmethod\n def work(self, obj):\n \"\"\"Work in the backend (can ba async)\n :param obj: <- event (usually)\n \"\"\"\n\n @abstractmethod\n def on_done(self):\n \"\"\"Return result to frontend (in tk main loop)\"\"\"\n\n def launch_worker(self, obj):\n \"\"\"Launch worker async\"\"\"\n get_state().reset_answers()\n AsyncWorker(lambda: self.work(obj), self.on_done, timeout=10).run()\n\n def on_rectangle(self, eclick, erelease):\n \"\"\"Param: the extreme coord of the human drawn rectangle\"\"\"\n # Log && Save\n click = eclick.xdata, eclick.ydata\n release = erelease.xdata, erelease.ydata\n get_state().l_click = [click, release]\n\n # Log\n log(3, \"Rectangle click_________________\\n\"\n 'between:', click, 'and', release)\n\n # If null rectangle -> make middle click\n if (click[0] - release[0]) * (click[1] - release[1]) < 9:\n log(3, 'Rectangle incomplete, crafting a fake middle click here')\n x, y = click\n event = matplotlib.backend_bases.MouseEvent(\n 'button_press_event', get_root().frame_image.get_canvas(),\n x, y, button=2)\n event.xdata, event.ydata = x, y\n event.inaxes = True\n self.pick_event(event)\n return\n\n self.rectangle = (\n int(click[1]), int(release[1]),\n int(click[0]), int(release[0])\n )\n\n # Work\n self.launch_worker(None)\n\n\n def pick_event(self, event):\n \"\"\"For mouse click PickOne or rectangle\"\"\"\n # Left click -> avoid shadowing rectangle selection\n if not event.inaxes or event.button == 1:\n return\n\n if get_root().frame_image.is_toolbar_active():\n log(0, 'WARNING: Zoom or Pan actif, '\n 'please unselect its before picking your object')\n return\n\n if event.button == 2:\n # Reamining button 2 -> Save bounds <- click +/- 15\n log(1, 'Making a selection 30 pixels around', event)\n self.rectangle = (\n event.ydata - 20, event.ydata + 20,\n event.xdata - 20, event.xdata + 20)\n\n self.launch_worker(None)\n\n\nclass PickNo(Pick):\n \"\"\"Void class to do nothing\"\"\"\n def connect(self): pass\n def disconnect(self): pass\n def work(self, obj): pass\n def on_done(self): pass\n\n\nclass PickOne(Pick):\n \"\"\"Pick One Star\n This button should be green and the zoom button of the image toolbar\n unpressed. If it is pressed, clik again on it. You then have to draw a\n rectangle aroung the star to mesure the strehl ratio around this star. A\n first fit will be computed in the rectangle you've just drawn. Then the\n photometry of the star will be computed according to the photometry and\n background measurement type you chose in 'MoreOption' in the file menu. By\n default, the photometry is processed in a 99% flux rectangle. And the\n background, in 8 little rectangles around the star.\n The fit is necessary to get the maximum, the peak of the psf that will be\n compared to the diffraction pattern. You can set to assess the photometry\n of the object with the fit. A Moffat fit type is chosen by default. but\n you can change it with the button FitType. I recommend you to use a\n Gaussian for Strehl <5%, A Moffat for intermediate Strehl and a Bessel for\n strehl>60%.\"\n \"\"\"\n def __init__(self):\n super().__init__()\n self.rectangle_selector = None\n\n # The id of connection (alias callback), to be disabled\n self.id_callback = None\n self.done = False\n\n def connect(self):\n super().connect()\n log(0, \"\\n\\n\\n________________________________\\n|Pick One|:\\n\"\n \" 1/Draw a rectangle around your star with left button\\n\"\n \" 2/Click on star 'center' with right button\")\n self.rectangle_selector = matplotlib.widgets.RectangleSelector(\n self.ax,\n self.on_rectangle, drawtype='box',\n rectprops=dict(facecolor='green', edgecolor='black',\n alpha=0.5, fill=True),\n button=[1], # 1/left, 2/center , 3/right\n )\n self.canvas.mpl_connect(\n 'button_press_event', self.pick_event)\n\n def disconnect(self):\n log(3, 'PickOne disconnect')\n if self.rectangle_selector:\n self.rectangle_selector.set_active(False)\n self.rectangle_selector = None\n if self.id_callback:\n self.canvas.mpl_disconnect(self.id_callback)\n self.id_callback = None\n\n def work(self, obj):\n \"\"\"obj is None\"\"\"\n Strehl.strehl_one(self.rectangle)\n\n def on_done(self):\n AR.show_answer()\n\n\nclass PickBinary(Pick):\n \"\"\"Binary System\n If Binary button is green, make two click on a binary system : one on each\n star. A Binary fit will be processed. This is still in implementation.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.id_callback = None\n self.star1 = self.star2 = None\n self.is_parent = False\n\n def connect(self):\n super().connect()\n if not self.is_parent:\n log(0, \"\\n\\n\\n______________________________________\\n\"\n \"|Binary| : Make 2 clicks, one per star-------------------\")\n self.id_callback = self.canvas.mpl_connect(\n 'button_press_event', self.connect_second)\n self.canvas.get_tk_widget()[\"cursor\"] = \"target\"\n\n\n def disconnect(self):\n try:\n self.canvas.mpl_disconnect(self.id_callback)\n except:\n pass\n self.canvas.get_tk_widget()[\"cursor\"] = \"\"\n\n\n def connect_second(self, event):\n \"\"\"Second callback\"\"\"\n # Check in: click in image\n if not event.inaxes or not event.button == 1:\n return\n log(0, \"1st point : \", event.xdata, event.ydata)\n\n # Save first click\n self.star1 = [event.ydata, event.xdata]\n\n # Disconnect first click\n self.canvas.mpl_disconnect(self.id_callback)\n\n # Connect second click\n self.id_callback = self.canvas.mpl_connect(\n 'button_press_event', self.connect_third)\n\n\n def connect_third(self, event):\n \"\"\"After second click (final), do real work\"\"\"\n if not event.inaxes: return\n log(0, \"2nd point : \", event.xdata, event.ydata)\n\n # Save second click\n self.star2 = [event.ydata, event.xdata]\n\n # Disconnect second click & Restore cursor\n self.canvas.mpl_disconnect(self.id_callback)\n self.canvas.get_tk_widget()[\"cursor\"] = \"\"\n\n # Save to state\n get_state().l_click = [self.star1, self.star2]\n\n # Work\n self.launch_worker(None)\n\n # Prepare next\n self.star1 = self.star2 = None\n self.connect()\n\n\n def work(self, obj):\n Strehl.BinaryStrehl(self.star1, self.star2)\n\n def on_done(self):\n AR.show_answer()\n\n\nclass PickTightBinary(PickBinary):\n \"\"\"Binary that are close so the fit is harder\"\"\"\n def __init__(self):\n super().__init__()\n self.is_parent = True\n\n def connect(self):\n log(0, \"\\n\\n\\n______________________________________\\n\"\n \"|TightBinary| : Make 2 clicks, one per star, be precise, \"\n \"the parameters will be more constrained-------------------\")\n super().connect()\n get_state().aniso = False\n get_state().same_psf_var = True\n\n\n def work(self, obj):\n Strehl.TightBinaryStrehl(self.star1, self.star2)\n\n\nclass PickStat(Pick):\n \"\"\"Draw a rectangle\"\"\"\n def __init__(self):\n super().__init__()\n self.rectangle_selector = None\n\n def disconnect(self):\n if self.rectangle_selector:\n self.rectangle_selector.set_active(False)\n self.rectangle_selector = None\n\n def connect(self):\n super().connect()\n log(0, \"\\n\\n\\n________________________________\\n\"\n \"|Pick Stat| : draw a rectangle around a region and ABISM \"\n \"will give you some statistical information \"\n \"computed in the region-------------------\")\n self.rectangle_selector = matplotlib.widgets.RectangleSelector(\n self.ax,\n self.on_rectangle, drawtype='box',\n rectprops=dict(facecolor='red', edgecolor='black', alpha=0.5, fill=True))\n\n def work(self, obj): pass\n\n def on_done(self):\n show_statistic(self.rectangle)\n\n\nclass PickProfile(Pick):\n \"\"\"Linear Profile, cutted shape of a source\n Draw a line on the image. Some basic statistics on the pixels cutted by\n your line will be displayed in the 'star frame'. And a Curve will be\n displayed on the 'fit frame'. A pixel is included if the distance of its\n center is 0.5 pixel away from the line. This is made to prevent to many\n pixels stacking at the same place of the line\\n\\n.\" Programmers, an\n 'improvement' can be made including pixels more distant and making a mean\n of the stacked pixels for each position on the line.\"\n \"\"\"\n def __init__(self):\n super().__init__()\n self.artist_profile = None\n self.point1 = self.point2 = (0, 0)\n\n def connect(self):\n super().connect()\n self.artist_profile = artist.Profile(\n get_root().frame_image.get_figure(),\n get_root().frame_image.get_figure().axes[0],\n callback=self.launch_worker\n )\n\n def disconnect(self):\n if self.artist_profile:\n self.artist_profile.Disconnect()\n self.artist_profile.RemoveArtist()\n self.artist_profile = None\n\n def work(self, obj):\n self.point1 = [obj.point1[0], obj.point1[1]]\n self.point2 = [obj.point2[0], obj.point2[1]]\n\n def on_done(self):\n get_state().l_click = [self.point1, self.point2]\n show_profile(self.point1, self.point2)\n\n\nclass PickEllipse(Pick):\n \"\"\"Not used\"\"\"\n def __init__(self):\n super().__init__()\n self.artist_ellipse = None\n\n self.bind_enter_id = None\n\n\n def connect(self):\n super().connect()\n log(0, \"\\n\\n\\n________________________________\\n\"\n \"|Pick Ellipse| : draw an ellipse around isolated object\\n\"\n \"ABISM will perform the photometry in this ellipse\\n\"\n \"Bind: eXpand, rOtate, changeU, changeV (minor a major axes)\\n\"\n \" left, down, up, right or h, j, k, l\\n\"\n \" Upper case to increase, lower to decrease\")\n\n self.artist_ellipse = artist.Ellipse(\n self.figure,\n self.ax,\n array=get_state().image.im0,\n callback=lambda: self.launch_worker(None)\n )\n\n # Bind mouse enter -> focus (for key)\n tk_fig = self.canvas.get_tk_widget()\n self.bind_enter_id = tk_fig.bind('', lambda _: tk_fig.focus_set())\n\n\n def disconnect(self):\n # Undraw\n if self.artist_ellipse:\n self.artist_ellipse.Disconnect()\n self.artist_ellipse.RemoveArtist()\n self.artist_ellipse = None\n\n # Unbind\n if self.bind_enter_id:\n tk_fig = self.canvas.get_tk_widget()\n tk_fig.unbind('', self.bind_enter_id)\n\n\n def work(self, _):\n Strehl.EllipseEventStrehl(self.artist_ellipse)\n\n def on_done(self):\n AR.show_answer()\n","sub_path":"abism/front/pick.py","file_name":"pick.py","file_ext":"py","file_size_in_byte":12763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"209828759","text":"\nimport pywt\nimport numpy as np\nimport pyedflib\nimport nolds\nfrom tqdm import tqdm\n\nmax_nt = 30 # length of time segment in seconds\nall_features = [\"Power\", \"SampE\"]\n\nmaster_channel_list = [\"Fp1\",\"Fp2\",\"F7\",\"F3\",\"Fz\",\"F4\",\"F8\",\"T7\",\"C3\",\"Cz\",\n \"C4\",\"T8\",\"P7\",\"P3\",\"Pz\",\"P4\",\"P8\",\"O1\",\"O2\"]\n\ndef power(y): return np.sum(y**2)/y.size\ndef sampE(y): return nolds.sampen(y)\n\nfunction_dict = {\"Power\": power,\"SampE\":sampE}\n\nclass Data:\n\n def __init__(self, filepath, max_nt):\n self.wavelet, self.mode = 'db4','cpd'\n self.D = {}\n self.data,self.channelNames,self.srate = self.extract_time_series(filepath,max_nt)\n self.levels = 2 \n ## Nick swapped this from self.levels = self._set_levels() to 2 for simplicity.\n #self._set_levels()\n self.nbands = self.levels+1\n\n def _set_levels(self):\n # Determine the number of levels required so that the lowest level approximation is roughly the\n # delta band (freq range 0-4 Hz)\n if self.srate <= 128: levels = 4\n elif self.srate <= 256: levels = 5\n elif self.srate <= 512: levels = 6\n elif self.srate <= 1024: levels = 7\n \n return levels\n\n def extract_time_series(self,filepath,max_nt=30):\n print(f'Processing {filepath}')\n f = pyedflib.EdfReader(filepath) # read the edf file\n\n channelNames = f.getSignalLabels() # channelnames (note that channels = Signals)\n srate = f.getSampleFrequency(3) # sampling rate\n n = f.signals_in_file # number of signals\n data = np.zeros((n, f.getNSamples()[0]))\n for i in np.arange(n):\n data[i, :] = f.readSignal(i) # shitty implementation of pyedflib\n nt = max_nt*srate # number of time periods\n m1 = 0 # start time\n m2 = m1 + nt # end time\n data = data[:,m1:m2] # truncating data to the max number of time periods (in s)\n return data,channelNames,srate\n\n def _features_settings(self,chnls,all_features):\n print('Setting features....')\n w = pywt.Wavelet(self.wavelet)\n for c, ch in enumerate(self.channelNames):\n\n if ch in chnls:\n self.D[ch] = {}\n m = np.mean(self.data[c])\n a_orig = self.data[c]-m # the original signal, initially, de-meaned\n a = a_orig\n\n rec_a,rec_d = [] ,[] # all the approximations and details\n\n for i in range(self.nbands):\n (a, d) = pywt.dwt(a, w, self.mode)\n f = pow(np.sqrt(2.0), i+1)\n rec_a.append(a/f)\n rec_d.append(d/f)\n\n # Use the details and last approximation to create all the power-of-2 freq bands\n self.f_labels,self.freqband = ['A0'],[a_orig] # A0 is the original signal\n fs = [self.srate]\n f = fs[0]\n N = len(a_orig)\n\n for j,r in enumerate(rec_d):\n freq_name = 'D' + str(j+1)\n self.f_labels.append(freq_name)\n self.freqband.append(r[0:N]) # wavelet details for this band\n fs.append(f)\n f = f/2.0\n\n # We need one more\n f = f/2.0\n fs.append(f)\n\n # Keep only the last approximation\n j = len(rec_d)-1\n freq_name = 'A' + str(j+1)\n self.f_labels.append(freq_name)\n self.freqband.append(rec_a[j]) # wavelet approximation for this band\n\n for f in all_features:\n self.D[ch][f] = {}\n\n def compute_features(self, all_features, chnls, function_dict):\n self._features_settings(chnls, all_features)\n print('Computing Non RQA features....')\n self._compute_nonrqa_features(all_features, chnls, function_dict)\n\n\n def _compute_nonrqa_features(self,all_features,chnls,function_dict):\n #--------------------------------------------------------------------\n # Compute features such as Power, Sample Entropy, Hurst parameter, DFA, Lyapunov exponents on each of the frequency bands\n #--------------------------------------------------------------------\n nonrqa_features = ['Power','SampE']\n for c, ch in enumerate(tqdm(self.channelNames)):\n if ch in chnls:\n for i, y in enumerate(self.freqband):\n for feat in nonrqa_features:\n if feat in all_features:\n self.D[ch][feat][self.f_labels[i]] = function_dict[feat](y)\n\n## EOF ##\n\nt = Data('/Users/ncross/git/EEGPlatform/data/sample/20180422095733_B9-2-2 2yr.edf', 30)\nt.compute_features(all_features,master_channel_list,function_dict)\nprint(t.D)\n\n## EOF\n","sub_path":"Documentation/newProcess.py","file_name":"newProcess.py","file_ext":"py","file_size_in_byte":5005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"633178532","text":"import urllib.request\nfrom bs4 import BeautifulSoup\n\nurl='https://tieba.baidu.com/p/5653680140'\nurl=input('请输入网页:例如(https://tieba.baidu.com/p/5653680140)---')\n\nreq=urllib.request.urlopen(url)\nresponse=req.read()\nhtml=response.decode('utf-8')\nbs=BeautifulSoup(response,'lxml')\nget_author=bs.find_all('div',class_='d_author')\nget_all=bs.find_all('div',class_='d_post_content j_d_post_content ')\nall_txt=[]\nall_author=[]\ntitle=str(bs.title)[7:-8].split('【')[0]\nname=title+'_c'+'.txt'\nfor data in get_author:\n author=data.get_text()#encode('utf-8')\n author=author.splitlines(False)#删除换行\n new_author=[]\n for data in author:#删除列表中的空格\n if data==''or data==' ':\n #print('删除列表中的空格')\n pass\n else:\n new_author.append(data)\n new_author=new_author[0]\n all_author.append(new_author)\nprint(all_author)\nwith open(name,'w')as f:\n f.write('贴名:'+title+'\\r\\n')\n for i in range(len(all_author)):\n f.write(str(i+1)+'楼-'+all_author[i]+'\\r\\n')\n \nf.close()\n","sub_path":"py-demo/爬取贴吧帖子/main_v1.0.1.py","file_name":"main_v1.0.1.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"281661454","text":"# -*- coding: utf-8 -*-\n\n# inspired by https://github.com/khazhyk/dango.py's AttributeStore cog\n\nimport json\nfrom typing import Any, Union\n\nimport discord\n\nfrom mousey import Cog, Mousey\nfrom mousey.utils import TypeMap\n\n\nclass Storage(Cog):\n \"\"\"\n Persistent key: value store with Redis caching.\n\n Each user/guild/channel has it's own value, this can simply be accessed by passing the object.\n \"\"\"\n\n def __init__(self, mousey: Mousey):\n super().__init__(mousey)\n\n self.map = TypeMap()\n\n self.map.register(discord.Guild, 'guild')\n self.map.register(discord.abc.User, 'user') # abc.User because discord.Member doesn't inherit from User\n\n async def update(self, key: Any, **updates):\n name = self.map.lookup(key)\n return await self._update(name, key.id, **updates)\n\n async def get(self, key: Any) -> dict:\n name = self.map.lookup(key)\n return await self._get(name, key.id)\n\n async def delete(self, key: Any):\n name = self.map.lookup(key)\n return await self._delete(name, key.id)\n\n async def _update(self, name: str, idx: int, **updates):\n value = await self._get(name, idx)\n\n value.update(**updates)\n value = json.dumps(value)\n\n await self._update_redis(name, idx, value)\n await self._update_db(name, idx, value)\n\n async def _update_redis(self, name: str, idx: int, value: str):\n await self.redis.set(f'mousey:storage:{name}:{idx}', value)\n\n async def _update_db(self, name: str, idx: int, value: str):\n await self.db.execute(\n 'INSERT INTO storage (name, idx, stored) VALUES ($1, $2, $3) '\n 'ON CONFLICT (name, idx) DO UPDATE SET stored = $3',\n name,\n idx,\n value,\n )\n\n async def _get(self, name: str, idx: int) -> dict:\n value = await self._get_redis(name, idx)\n if value is not None:\n return value\n\n value = await self._get_db(name, idx)\n await self._update_redis(name, idx, json.dumps(value))\n\n return value\n\n async def _get_redis(self, name: str, idx: int) -> Union[dict, None]:\n value = await self.redis.get(f'mousey:storage:{name}:{idx}')\n if value is None:\n return\n\n return json.loads(value)\n\n async def _get_db(self, name: str, idx: int) -> dict:\n value = await self.db.fetchval('SELECT stored FROM storage WHERE name = $1 AND idx = $2', name, idx)\n if value is None:\n return {}\n\n return json.loads(value)\n\n async def _delete(self, name: str, idx: int):\n await self._delete_redis(name, idx)\n await self._delete_db(name, idx)\n\n async def _delete_redis(self, name: str, idx: int):\n await self.redis.delete(f'mousey:storage:{name}:{idx}')\n\n async def _delete_db(self, name: str, idx: int):\n await self.db.execute('DELETE FROM storage WHERE name = $1 AND idx = $2', name, idx)\n\n\ndef setup(mousey: Mousey):\n mousey.add_cog(Storage(mousey))\n","sub_path":"mousey/ext/core/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"81503771","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nimport math\r\nfrom scipy import optimize as op\r\n\r\ndef calibration(motionAs, motionBs):\r\n '''\r\n 使用li算法解AX=YB的方程,求解手眼标定\r\n :param motionAs: list> A 来自handineye.motion_axyb或者是handtoeye.motion_axyb\r\n :param motionBs: list> B 来自handineye.motion_axyb或者是handtoeye.motion_axyb\r\n :return: X:handineye中为机器基底到标定板的变换 handtoeye:机器臂基底到相机的变换\r\n Y:handineye中为相机到机器臂末端的变换 handtoeye:标定板到机械臂末端的变化\r\n '''\r\n T = np.zeros([9, 9])\r\n n= len(motionAs)\r\n Ra = []\r\n Ta = []\r\n Tb = []\r\n A = np.zeros([12*n,24])\r\n b = np.zeros([12*n,1])\r\n for i in range(n):\r\n AA = motionAs[i]\r\n BB = motionBs[i]\r\n Ra = AA[:3,:3]\r\n ta = AA[:3,3]\r\n Rb = BB[:3,:3]\r\n tb = BB[:3,3]\r\n A[12*i:12*i+9,0:18] = np.append(np.kron(Ra,np.identity(3)),np.kron(-np.identity(3),Rb.T),1)\r\n # t = np.append(np.kron(np.identity(3),tb.T),np.append(-Ra,np.identity(3),1),1)\r\n A[12*i+9:12*(i+1),9:24]= np.append(np.kron(np.identity(3),tb.T),np.append(-Ra,np.identity(3),1),1)\r\n b[12*i+9:12*(i+1)] = np.array([ta]).T\r\n x = np.linalg.lstsq(A,b, rcond=-1)[0]\r\n X = np.reshape(x[0:9,:],[3,3],order=\"F\").T\r\n U,S,VT = np.linalg.svd(X)\r\n X = np.dot(U,VT)\r\n if np.linalg.det(X)<0:\r\n X = np.dot(U,np.dot(np.diag([1,1,-1]),VT))\r\n X = np.append(np.append(X,x[18:21,:],1),np.array([[0,0,0,1]]),0)\r\n Y = np.reshape(x[9:18,:], [3, 3],order=\"F\").T\r\n U, S, VT = np.linalg.svd(Y)\r\n Y = np.dot(U , VT)\r\n if np.linalg.det(Y) < 0:\r\n Y = np.dot(U,np.dot(np.diag([1,1,-1]),VT))\r\n Y = np.append(np.append(Y, x[21:24,:], 1), np.array([[0, 0, 0, 1]]), 0)\r\n return X,Y","sub_path":"method/li.py","file_name":"li.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"633313176","text":"\"\"\"\n The MIT License (MIT)\n\n Copyright (c) 2015 Erik Soma\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to\n deal in the Software without restriction, including without limitation the\n rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n sell copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n IN THE SOFTWARE.\n\"\"\"\n\n__all__ = ['clean', 'get_default_include_paths', 'get_default_macros']\n\n# python standard libary\nimport os\nimport subprocess\nimport tempfile\n\ndef get_va_list_size():\n with tempfile.NamedTemporaryFile(delete=False) as f:\n f.write(\"\"\"\n #include \n #include \n int main()\n {\n printf(\"%u\", sizeof(__builtin_va_list));\n }\n \"\"\".encode('utf8'))\n result = subprocess.run(\n ['gcc', '-xc', f.name, '-o', 'valistsize'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n os.remove(f.name)\n if result.returncode != 0:\n raise RuntimeError(result.stderr.decode('utf8'))\n result = subprocess.run('valistsize', stdout=subprocess.PIPE)\n os.remove('valistsize.exe' if os.name == 'nt' else 'valistsize')\n return int(result.stdout.decode('utf8'))\n\ndef clean(preprocessed_c):\n index = 0\n open = 0\n preprocessed_c = preprocessed_c.replace(\n '__builtin_va_list __gnuc_va_list',\n 'char __gnuc_va_list[{0}]'.format(get_va_list_size())\n )\n preprocessed_c = preprocessed_c.replace('__restrict__', '')\n while True:\n index = preprocessed_c.find('__attribute__', index)\n if index == -1:\n break\n newline = preprocessed_c.rfind('\\n', 0, index)\n if preprocessed_c[newline + 1] == '#':\n index += 1\n continue\n for i, c in enumerate(preprocessed_c[index:]):\n if c == '(':\n open += 1\n elif c == ')':\n open -= 1\n if open == 0:\n i += 1\n preprocessed_c = preprocessed_c[:index] + preprocessed_c[index + i:]\n index -= i\n break\n return preprocessed_c\n\ndef get_default_include_paths():\n with tempfile.NamedTemporaryFile(delete=False) as f:\n pass\n result = subprocess.run(\n ['gcc', '-E', '-v', '-xc', f.name],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n os.remove(f.name)\n if result.returncode == 0:\n include_directories = None\n lines = result.stderr.decode('utf8').split('\\n')\n for line in lines:\n if line.startswith('#include '):\n include_directories = []\n continue\n if line.startswith('End of search list.'):\n break\n if include_directories is not None:\n include_directories.append(line.strip())\n return include_directories\n else:\n raise RuntimeError(result.stderr.decode('utf8'))\n\ndef get_default_macros():\n with tempfile.NamedTemporaryFile(delete=False) as f:\n pass\n result = subprocess.run(\n ['gcc', '-dM', '-E', '-xc', f.name],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n os.remove(f.name)\n if result.returncode == 0:\n return result.stdout.decode('utf8')\n else:\n raise RuntimeError(result.stderr.decode('utf8'))\n","sub_path":"toe/compilers/gcc.py","file_name":"gcc.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"46085452","text":"from __future__ import division\nimport time\nimport numpy as np\nimport pandas as pd\n\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1000)\n\ndef normalizeTrainDF(dataFrame):\n dfNormalized = dataFrame.copy()\n colList = list(dataFrame.columns)\n \n for col in range(len(colList)):\n colMean = dataFrame[colList[col]].mean()\n colStd = dataFrame[colList[col]].std()\n \n dfNormalized[colList[col]] = (dataFrame[colList[col]] - colMean)/colStd\n \n return dfNormalized\n\ndef normalizeTestDF(testDataFrame, trainDataFrame):\n\n dfNormalized = testDataFrame.copy()\n colList = list(testDataFrame.columns)\n\n for col in range(len(colList)):\n colMean = trainDataFrame[colList[col]].mean()\n colStd = trainDataFrame[colList[col]].std()\n \n dfNormalized[colList[col]] = (testDataFrame[colList[col]] - colMean)/colStd\n\n return dfNormalized\n \n\ndef getAllDistanceDF(trainDF , testDF):\n indexCounter = 0;\n appenedData = []\n for row in testDF.itertuples(index=False, name='Pandas'):\n\n distanceSeries = calculateEculidDist(trainDF, row)\n testRowIndexList = [indexCounter]*np.shape(distanceSeries.values)[0]\n\n indexCounter += 1\n \n listToAddInFinalDF = { 'trainRowIndex' : np.array(distanceSeries.index) , 'distance': distanceSeries.values, 'testRowIndex' : testRowIndexList}\n dfEachTestRowDistance = pd.DataFrame(listToAddInFinalDF)\n appenedData.append(dfEachTestRowDistance)\n \n distanceDF = pd.concat(appenedData, axis=0)\n \n return distanceDF\n \ndef calculateEculidDist(trainDF , testRow):\n \n tmp = (((trainDF.sub( testRow, axis=1))**2).sum(axis=1))**0.5\n tmp.sort_values(axis=0, ascending=True, inplace=True)\n\n \n return tmp\n\nstartTime = time.clock()\ntrainDF = pd.read_csv(\"spam_train.csv\")\ntestDF = pd.read_csv(\"spam_test.csv\")\n\ntestDF.drop(testDF.columns[0] , axis=1, inplace=True)\n\ntrainLable = trainDF[['class']].copy()\ntestLable = testDF[['Label']].copy()\n\ntrainDF.drop('class' , axis=1, inplace=True)\ntestDF.drop('Label' , axis=1, inplace=True)\n\nzScroreTime = time.clock()\ntrainDFNormalized = normalizeTrainDF(trainDF) \ntestDFNormalized = normalizeTestDF(testDF,trainDF)\n \ndistanceDF = getAllDistanceDF(trainDFNormalized , testDFNormalized)\ndistanceTime = time.clock()\n\nkValuesList= [1,5,11,21,41,61,81,101,201,401]\n\naccuracyList = []\nfor kValue in range(len(kValuesList)) :\n loopStartTime = time.clock()\n indexCounter = 0\n predictedLabel = []\n for row in testDFNormalized.itertuples(index=False, name='Pandas'):\n distanceDFForRow = distanceDF[ distanceDF['testRowIndex'] == indexCounter]\n\n nnIndex = distanceDFForRow.loc[:(kValuesList[kValue] - 1) ,'trainRowIndex']\n \n tmp = trainLable.iloc[nnIndex]['class'].value_counts()\n \n predictedLabel.append(tmp.idxmax())\n indexCounter += 1\n \n tmpList = {'Label' : predictedLabel}\n predictedTestLabel = pd.DataFrame(tmpList)\n\n differenceLabel = testLable.sub(predictedTestLabel , axis=1)\n\n accurateClassCount = len(differenceLabel[ differenceLabel['Label'] ==0 ])\n\n accuracyPercent = accurateClassCount/testLable['Label'].count()*100\n\n print('The test accuracy for ' ,kValuesList[kValue] , 'is ' , (accurateClassCount/testLable['Label'].count())*100, '%' )\n \n accuracyList.append(accuracyPercent)\n\ntempDict = {'KValue' : kValuesList, 'Accuray %' : accuracyList}\naccuracyDF = pd.DataFrame(tempDict)\n \n","sub_path":"python/Question1_B.py","file_name":"Question1_B.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"529592915","text":"\"\"\"getIpAddress of ESP8266.\"\"\"\n\n\nimport network\nimport ubinascii\n\n\ndef healthCheck():\n \"\"\"Get the IpAddress of ESP8266.\"\"\"\n sta_if = network.WLAN(network.STA_IF)\n if sta_if.active():\n if sta_if.isconnected():\n ipAddr = sta_if.ifconfig()\n mac = ubinascii.hexlify(network.WLAN().config('mac'), ':').decode()\n else:\n print(\"ESP8266 is not connected.\")\n else:\n print(\"Activate the ESP8266 STA Mode.\")\n return(mac, ipAddr[0])\n\n\nif __name__ == \"__main__\":\n print(healthCheck())\n","sub_path":"simpleUtilities/getIPAddr.py","file_name":"getIPAddr.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"457418918","text":"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport json\n\ndf = pd.read_csv('../resources/sales_data.csv')\nprofit_list = df['total_profit'].values\nmonths = df['month_number'].values\nplt.figure()\nplt.plot(months, profit_list, label='Month-wise Profit data of last year')\nplt.xlabel('Month number')\nplt.ylabel('Profit [$]')\nplt.xticks(months)\nplt.title('Company profit per month')\nplt.yticks([100e3, 200e3, 300e3, 400e3, 500e3])\nplt.show()\n\n\ndf = pd.read_csv('../resources/sales_data.csv')\nprofit_list = df['total_profit'].values\nmonths = df['month_number'].values\nplt.figure()\nplt.plot(months, profit_list, label='Profit data of last 1 year', color='r', marker='o', markerfacecolor='k',\n linestyle='--', linewidth=3)\nplt.xlabel('Month Number')\nplt.ylabel('Profit in dollar')\nplt.legend(loc='lower right')\nplt.title('Company Sales data of last year')\nplt.xticks(months)\nplt.yticks([100e3, 200e3, 300e3, 400e3, 500e3])\nplt.show()\n\n\ndf = pd.read_csv('../resources/sales_data.csv')\nmonths = df['month_number'].values\nface_cream_sales_data = df['facecream'].values\nface_wash_sales_data = df['facewash'].values\ntooth_paste_sales_data = df['toothpaste'].values\nbathing_soap_sales_data = df['bathingsoap'].values\nshampoo_sales_data = df['shampoo'].values\nmoisturizer_sales_data = df['moisturizer'].values\nplt.figure()\nplt.plot(months , face_cream_sales_data ,label='Face cream Sales Data', marker='o', linewidth=3)\nplt.plot(months , face_wash_sales_data ,label='Face wash Sales Data', marker='o', linewidth=3)\nplt.plot(months , tooth_paste_sales_data ,label='ToothPaste Sales Data', marker='o', linewidth=3)\nplt.plot(months , bathing_soap_sales_data ,label='Bathing Soap Sales Data', marker='o', linewidth=3)\nplt.plot(months , shampoo_sales_data ,label='Shampoo Sales Data', marker='o', linewidth=3)\nplt.plot(months , moisturizer_sales_data ,label='Moisturizer Sales Data', marker='o', linewidth=3)\nplt.xlabel('Month Number')\nplt.ylabel('Sales units in number')\nplt.legend(loc='upper left')\nplt.xticks(months)\nplt.yticks([1e3, 2e3, 4e3, 6e3, 8e3, 10e3, 12e3, 15e3, 18e3])\nplt.title('Sales data')\nplt.show()\n\n\ndf = pd.read_csv('../resources/sales_data.csv')\nmonths = df['month_number'].tolist()\ntooth_paste_sales_data = df['toothpaste'].values\nplt.figure()\nplt.scatter(months , tooth_paste_sales_data , label='Tooth paste sales data')\nplt.xlabel('Month Number')\nplt.ylabel('Number of units sold')\nplt.legend(loc='upper left')\nplt.title('Tooth paste sales data')\nplt.xticks(months)\nplt.grid(True, linewidth=0.5, linestyle='--')\nplt.show()\n\ndf = pd.read_csv('../resources/sales_data.csv')\nmonths = df['month_number'].tolist()\nbathing_soap_sales_data = df['bathingsoap'].tolist()\nplt.bar(months , bathing_soap_sales_data)\nplt.xlabel('Month Number')\nplt.ylabel('Sales units in number')\nplt.xticks(months)\nplt.grid(True, linewidth=0.5, linestyle=\"--\")\nplt.title('Bathing soap sales data')\nplt.savefig('sales_data_of_bathing_soap.png', dpi=150)\nplt.show()\n\nfolder_in=''\ndf = pd.read_csv(folder_in + 'sales_data.csv')\nprofit_list = df['total_profit'].values\nplt.figure()\nprofit_range = [150e3, 175e3, 200e3, 225e3, 250e3, 300e3, 350e3]\nplt.hist(profit_list , profit_range , label='Profit data')\nplt.xlabel('profit range [$]')\nplt.ylabel('Actual Profit [$]')\nplt.legend(loc='upper left')\nplt.xticks(profit_range)\nplt.title('Profit data')\nplt.show()\n\n\nfolder_in=''\ndf = pd.read_csv(folder_in + 'sales_data.csv')\nmonths = df['month_number'].values\nbathing_soap = df['bathingsoap'].values\nface_wash_sales_data = df['facewash'].values\nf, axs = plt.subplots(2, 1, sharex=True)\naxs[0].plot(months, bathing_soap, label='Bathing soap Sales Data',color='k', marker='o', linewidth=3)\naxs[0].set_title('Sales data of a Bathing soap')\naxs[0].grid(True, linewidth=0.5, linestyle='--')\naxs [0]. legend ()\naxs[1].plot(months, face_wash_sales_data, label='Face Wash Sales Data',color='r', marker='o', linewidth=3)\naxs[1].set_title('Sales data of a face wash')\naxs[1].grid(True, linewidth=0.5, linestyle='--')\naxs[1].legend()\nplt.xticks(months)\nplt.xlabel('Month Number')\nplt.ylabel('Sales units in number')\nplt.show()\n\n\n\n\njson_obj = '{ \"Name\":\"David\", \"Class\":\"I\", \"Age\":6 }'\npython_obj = json.loads(json_obj)\nprint('\\nJSON data:')\nprint(python_obj)\nprint('\\nName:', python_obj['Name'])\nprint('Class:', python_obj['Class'])\nprint('Age:', python_obj['Age'])\n\n\npython_obj = { 'name': 'David','class': 'I','age': 6 }\nprint(type(python_obj))\n# convert into JSON:\nj_data = json.dumps(python_obj)\n# result is a JSON string:\nprint(j_data)\n\npython_dict = {'name': 'David', 'age': 6, 'class': 'I'}\npython_list = ['Red', 'Green', 'Black']\npython_str = 'Python Json'\npython_int = 1234\npython_float = 21.34\npython_t = True\n\n\npython_f = False\npython_n = None\njson_dict = json.dumps(python_dict)\njson_list = json.dumps(python_list)\njson_str = json.dumps(python_str)\njson_num1 = json.dumps(python_int)\njson_num2 = json.dumps(python_float)\njson_t = json.dumps(python_t)\njson_f = json.dumps(python_f)\njson_n = json.dumps(python_n)\nprint('json dict:', json_dict)\nprint('jason list:', json_list)\nprint('json string:', json_str)\nprint('json number1:', json_num1)\nprint('json number2:', json_num2)\nprint('json true:', json_t)\nprint('json false:', json_f)\nprint('json null:', json_n)\n\nj_str = {'4':5, '6': 7, '1': 3, '2': 4}\nprint('Original String:', j_str)\nprint('\\nJSON data:')\nprint(json.dumps(j_str, sort_keys=True, indent=4))\n\n\nwith open('../resources/states.json') as f:\n state_data = json.load(f)\nprint('Original JSON keys: ', [state.keys()for state in state_data['states']][0])\nfor state in state_data['states']:\n del state['area_codes']\nprint('\\nModified JSON keys: ', [state.keys() for state in state_data['states']][0])\nwith open('new_states.json', 'w') as f:\n json.dump(state_data, f, indent=2)\nwith open('new_states.json') as f:\n state_data = json.load(f)\nprint('\\nReloaded JSON keys: ', [state.keys() for state in state_data['states']][0])","sub_path":"Lab2/Esercizi.py","file_name":"Esercizi.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"570749632","text":"from flask import Flask, jsonify, app\nfrom flask import request\n\nfrom 형태소분석.app import morpAPI2, morpAPI\n\n\n@app.route(\"/cosmos/KStars/morp\", methods=['POST'])\ndef cosmos_morp():\n data = request.json\n print(data)\n hi = morpAPI2(data['text'])\n moreResult = hi.showMorp2()\n\n data['analysisResult'] = moreResult\n print(type(data['analysisResult']))\n print(data['analysisResult'])\n return jsonify(data)\n\n@app.route(\"/cosmos/KStars/morpList\", methods=['POST'])\ndef cosmos_morp_board():\n data = request.json\n for i in range(len(data)):\n analysis = morpAPI2(data[i]['text'])\n resultList = analysis.showMorp2()\n data[i]['analysisResult'] = resultList\n\n return jsonify(data)\n\n\n@app.route(\"/test\", methods=['POST'])\ndef test():\n data = request.json\n # print(data)\n hi = morpAPI(data['text'])\n moreResult = hi.showMorp()\n\n # print(moreResult)\n data['analysisResult'] = moreResult\n\n return jsonify(data)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"252172179","text":"\"\"\"\nProblem 62: Given an array arr[0 .. n-1] of distinct integers, the task is to find a local minima in it.\nWe say that an element arr[x] is a local minimum if it is less than or equal to both its neighbors.\n\nFor corner elements, we need to consider only one neighbor for comparison.\nThere can be more than one local minima in an array, we need to find any one of them.\n\"\"\"\n\n\ndef local_minima(A, start, end):\n mid = (start+end)//2\n\n if mid == 0 or A[mid] <= A[mid-1] and mid == len(A)-1 or A[mid] <= A[mid+1]:\n return mid\n elif A[mid] > A[mid-1]:\n return local_minima(A, start, mid-1)\n else:\n return local_minima(A, mid+1, end)\n\n\nA = [9, 6, 3, 14, 5, 7, 4]\nprint(local_minima(A, 0, len(A)-1))\n\n\n\n","sub_path":"karumanchi/Searching/local minima.py","file_name":"local minima.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"388937484","text":"from dataclasses import dataclass, field\nfrom typing import List\n\n\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n # 140 ms\t18 MB\n length = len(nums)\n if length == 0:\n return []\n\n num_count = {}\n for _, num in enumerate(nums):\n if num in num_count:\n num_count[num] += 1\n else:\n num_count[num] = 1\n\n count_num = {}\n for num, count in num_count.items():\n if count in count_num:\n count_num[count].append(num)\n else:\n count_num[count] = [num]\n\n result = []\n for count in range(length, 0, -1):\n if count not in count_num:\n continue\n\n candidates = count_num[count]\n for candidate in candidates:\n result.append(candidate)\n if len(result) == k:\n return result\n\n return result\n\n","sub_path":"python/347.py","file_name":"347.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"272630743","text":"def lis(list):\r\n cache=[0 for j in range(len(list))]\r\n if ( list[0] 2 or count == 9:\n win = check_win(board, player)\n if win == 1:\n print(\"Player 1 wins!!!\\n\") \n return\n elif count == 9 and win == 0:\n print(\"The game came to a draw\\n\")\n return\n player = 2\n \n\n \n elif player == 2:\n board[row][col] = 'O'\n p_2 += 1\n count += 1\n \n if p_2 > 2 or count == 9:\n win = check_win(board, player)\n if win == 2:\n print(\"Player 2 wins!!!\\n\")\n return\n elif count == 9 and win == 0:\n print(\"The game came to a draw\\n\")\n return\n player = 1\n print_board(board)\n \n \n \n \n \n \n \ndef print_board(board):\n for i in range(len(board)):\n for j in range(len(board[i])):\n print (board[i][j],end= ' ')\n print(\"\\n\")\n\ndef print_menu():\n #This function prints the menu\n print(\"============================\")\n print(\" Menu \")\n print(\"============================\")\n print(\"1. Choose Opponent\")\n print(\"2. New game\")\n print(\"3. Load game\")\n print(\"4. Quit game\")\n\n\n \n\ndef main():\n ch = True\n while ch:\n print_menu()\n print('\\n')\n user_in = int(input(\"Choose a menu option: \"))\n\n if user_in == 1:\n print(\"Coming soon!\")\n elif user_in == 2:\n board = create_board()\n print_board(board)\n play(board)\n elif user_in == 3:\n print(\"Coming soon!\")\n elif user_in == 4:\n print(\"Goodbye!\")\n ch = False\n else:\n print(\"Please choose a valid menu option\")\n \n \n \n \n\n\nif __name__ == '__main__':\n main()\n \n \n","sub_path":"Tictactoe_basic.py","file_name":"Tictactoe_basic.py","file_ext":"py","file_size_in_byte":6435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"642565541","text":"from math import sin, pi\n\n\nclass MyClass:\n \"\"\"A simple example class\"\"\"\n i = 12345\n\n @staticmethod\n def f():\n return 'hello world'\n\n\nm = MyClass()\nprint(m.f())\nprint(MyClass.f())\n\n\nclass Complex:\n __real_part = None\n __image_part = None\n\n def __init__(self, real_part, image_part):\n self.__real_part = real_part\n self.__image_part = image_part\n\n def __str__(self):\n return \"re: {}, img: {}\".format(self.__real_part, self.__image_part)\n\n\nx = Complex(3.0, -4.5)\nprint(x)\n\n\nclass Dog:\n tricks = []\n\n def __init__(self, name):\n self.name = name\n\n def add_trick(self, trick):\n self.tricks.append(trick)\n\n\ndog = Dog('bruno')\ndog.add_trick('1')\ndog.add_trick('2')\n\nprint(dog.tricks)\n\n\nclass B(Exception):\n pass\n\n\nclass C(B):\n pass\n\n\nclass D(C):\n pass\n\n\nfor cls in [B, C, D]:\n try:\n raise cls()\n except D:\n print(\"D\")\n except C:\n print(\"C\")\n except B:\n print(\"B\")\n\nfor element in [1, 2, 3]:\n print(element)\nfor element in (1, 2, 3):\n print(element)\nfor key in {'one': 1, 'two': 2}:\n print(key)\nfor char in \"123\":\n print(char)\nfor line in open(\"myfile.txt\"):\n print(line, end='')\n\nprint(\"\\n\")\n\n\nclass Reverse:\n\n def __init__(self, data):\n self.data = data\n self.index = len(data)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.index == 0:\n raise StopIteration\n self.index -= 1\n return self.data[self.index]\n\n\nprint(Reverse.__dict__)\n\nrev = Reverse('spam')\nfor char in rev:\n print(char)\n\nprint(\"\\n\")\n\n\ndef reverse(data):\n for index in range(len(data) - 1, -1, -1):\n yield data[index]\n\n\nfor char in reverse('golf'):\n print(char)\n\nsine_table = {x: sin(x * pi / 180) for x in range(0, 91)}\n\nprint(sine_table)\n","sub_path":"demo6.py","file_name":"demo6.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"334443340","text":"from .context import load_extended_raw_corpus, BM25Vectorizer, OnlinePipeline, load_raw_corpus, Text2Doc\n\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.pipeline import Pipeline\nfrom rich.progress import track\nfrom itertools import tee, islice\nfrom random import randint\n\nimport pytest\nfrom pytest import raises\n\nBATCH_SIZE = 10\n\n\ndef test_pipeline_training():\n pipeline = Pipeline([('t2d', Text2Doc()),\n ('sg_bm25', BM25Vectorizer()),\n ('lr', SGDClassifier())])\n\n X = load_raw_corpus(False)\n pipeline.fit(X, [randint(0, 1) for _ in range(len(X))])\n\n\n@pytest.mark.skip()\ndef test_online_pipeline_training():\n pipeline = OnlinePipeline([('t2d', Text2Doc()),\n ('sg_bm25', BM25Vectorizer()),\n ('lr', SGDClassifier())])\n\n X1, X2 = tee(islice(load_extended_raw_corpus(), 101), 2)\n\n total = sum(1 for _ in X1)\n\n batch = []\n for doc in track(X2, total=total):\n batch.append(doc)\n\n if len(batch) == BATCH_SIZE:\n pipeline.partial_fit(batch, [randint(0, 1) for _ in range(len(batch))], classes=[0, 1])\n\n batch.clear()\n\n pipeline.partial_fit(batch, [1 for _ in range(len(batch))])\n\n\n@pytest.mark.skip()\ndef test_online_pipeline_training_divisable_batch():\n pipeline = OnlinePipeline([('t2d', Text2Doc()),\n ('sg_bm25', BM25Vectorizer()),\n ('lr', SGDClassifier())])\n\n X1, X2 = tee(islice(load_extended_raw_corpus(), 100), 2)\n\n total = sum(1 for _ in X1)\n\n batch = []\n\n for doc in track(X2, total=total):\n batch.append(doc)\n\n if len(batch) == BATCH_SIZE:\n pipeline.partial_fit(batch, [randint(0, 1) for _ in range(len(batch))], classes=[0, 1])\n\n batch.clear()\n\n with raises(ValueError, match=r\"Ensure that X contains at least one valid document.*\"):\n pipeline.partial_fit(batch, [1 for _ in range(len(batch))])\n","sub_path":"tests/extension/test_bm25_pipeline.py","file_name":"test_bm25_pipeline.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"646723209","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated by sundazhong on 2019/4/13 17:34.\n\"\"\"\n\n\nclass TreeNode(object):\n\n\n\tdef __init__(self, x):\n\t\tself.val = x\n\t\tself.left = None\n\t\tself.right = None\n","sub_path":"tree/treeNode.py","file_name":"treeNode.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"576920516","text":"from contextlib import contextmanager\n\nfrom sqlalchemy import create_engine, Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n# super class base for all table models\nBase = declarative_base()\n\n# create a engine to execute sql queries\nengine = create_engine('sqlite:///:memory:')\n\n# session generator\nSession = sessionmaker(bind=engine)\n\n\nclass Cookie(Base):\n __tablename__ = 'cookies'\n\n id: int = Column(Integer, primary_key=True)\n type: str = Column(String(255), nullable=False)\n\n\ndef init_tables():\n # creates all tables for models, if they do not exist\n Base.metadata.create_all()\n\n\ninit_tables()\n\n\n@contextmanager\ndef transaction():\n s = Session()\n try:\n yield s\n s.commit()\n except:\n s.rollback()\n finally:\n s.close()\n\n\nwith transaction() as t:\n t.add(Cookie(type='test'))\n","sub_path":"sqlalchemy/quick_start_no_comments.py","file_name":"quick_start_no_comments.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"116760146","text":"import datetime\nfrom django.db import models\nfrom django.utils import timezone\n\n\nclass Question(models.Model):\n question_text = models.CharField(max_length=200)\n pub_date = models.DateTimeField('date published', default=timezone.now)\n\n def __str__(self):\n return self.question_text\n\n def was_published_recently(self):\n now = timezone.now()\n return now - datetime.timedelta(days=1) <= self.pub_date <= now\n\n def total_votes(self):\n \"\"\" Return the total number of votes for this poll question.\"\"\"\n count_votes = 0\n for choice in self.choice_set.all():\n count_votes += choice.total_votes\n return count_votes\n\n def reset_votes(self):\n \"\"\" Resets the vote count to zero for all Choice for the Question.\"\"\"\n for choice in self.choice_set.all():\n for vote in choice.vote_set.all():\n vote.delete()\n choice.save()\n\n was_published_recently.admin_order_field = 'pub_date'\n was_published_recently.boolean = True\n was_published_recently.short_description = 'Published recently?'\n","sub_path":"polls/models/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"376447346","text":"class Solution:\n def licenseKeyFormatting(self, S: str, K: int) -> str:\n s = \"\".join(S.split(\"-\"))\n a = len(s)\n l = list(s)\n \n if a % K ==0:\n ans = \"\".join(j + \"-\" * (i%K == (K-1)) for i,j in enumerate(l))\n else:\n f = a%K\n ans = \"\".join(l[0:f])+ \"-\" + \"\".join(j + \"-\" * (i%K == (K-1)) for i,j in enumerate(l[f:])) \n return ans.strip(\"-\").upper()\n","sub_path":"submission/python/python/0482.py","file_name":"0482.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"624237161","text":"\"\"\"\n Bisection-Method\n\n Formula:\n Given two guesses: [a,b]\n find the mid-point\n c = (b+a)/2\n evaluation f(a), f(b) and f(c)\n if:\n f(a) is +ve and f(b) is -ve and f(c) is +ve\n then replace a = c \n\"\"\"\nfrom Nu_Meth import *\nclass Bisection_Method(Nu_Meth):\n def __init__(self,fptr, max_iter = 500, tol = 0.0001): \n self._fptr = fptr\n self._max_iter = max_iter\n \n self._tol = tol\n\n def execute(self, a,b):\n \"\"\"\n Takes two numbers\n \"\"\" \n\n for i in range(self._max_iter):\n c = (a + b)/2\n f_a = self._fptr(a)\n \n f_b = self._fptr(b)\n f_c = self._fptr(c)\n\n if f_a * f_c <= 0:\n b = c\n if abs(f_a) < self._tol :\n return (a, i+1)\n if f_b * f_c <= 0:\n a = c\n if abs(f_b) < self._tol :\n return (b, i+1)\n return \"No solution was found after \" + str(self._max_iter) +\" iterations\"\n\n\n\"\"\"\n Test of Newton-Raphson\n f(x) = 12*x^2 + 13*x + 1\n\"\"\"\n\ndef f(x):\n return (12*x*x + 13*x + 1)\n\nBObj = Bisection_Method(f, 10000)\n\nimport timeit\nstart_time = timeit.default_timer()\n\na = -.5\nb = 0\n\nsoln = BObj.execute(a,b)\nprint(soln)\nelapsed = timeit.default_timer() - start_time\nprint(\"Time: \" + str(elapsed))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n","sub_path":"Python/Bisection_Method.py","file_name":"Bisection_Method.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"57921044","text":"from defaults import *\nfrom os import environ\nimport dj_database_url\n\nDEBUG = False\n\nADMINS = [\n ('Phil Gyford', 'phil@gyford.com'),\n]\n\nMANAGERS = ADMINS\n\nDATABASES = {'default': dj_database_url.config(\n default=environ.get('DATABASE_URL'))}\n\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST = 'smtp.sendgrid.net'\nEMAIL_HOST_USER = environ.get('SENDGRID_USERNAME')\nEMAIL_HOST_PASSWORD = environ.get('SENDGRID_PASSWORD')\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n\n# If you *don't* want to prepend www to the URL, remove the setting from\n# the environment entirely. Otherwise, set to 'True' (or anything tbh).\nPREPEND_WWW = True\n\n# See https://devcenter.heroku.com/articles/memcachier#django\nenviron['MEMCACHE_SERVERS'] = environ.get('MEMCACHIER_SERVERS', '').replace(',', ';')\nenviron['MEMCACHE_USERNAME'] = environ.get('MEMCACHIER_USERNAME', '')\nenviron['MEMCACHE_PASSWORD'] = environ.get('MEMCACHIER_PASSWORD', '')\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django_pylibmc.memcached.PyLibMCCache',\n\n # Use binary memcache protocol (needed for authentication)\n 'BINARY': True,\n\n # TIMEOUT is not the connection timeout! It's the default expiration\n # timeout that should be applied to keys! Setting it to `None`\n # disables expiration.\n 'TIMEOUT': None,\n\n 'OPTIONS': {\n # Enable faster IO\n 'tcp_nodelay': True,\n\n # Keep connection alive\n 'tcp_keepalive': True,\n\n # Timeout settings\n 'connect_timeout': 2000, # ms\n 'send_timeout': 750 * 1000, # us\n 'receive_timeout': 750 * 1000, # us\n '_poll_timeout': 2000, # ms\n\n # Better failover\n 'ketama': True,\n 'remove_failed': 1,\n 'retry_timeout': 2,\n 'dead_timeout': 30,\n }\n }\n}\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 'null': {\n 'class': 'logging.NullHandler',\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'django.security.DisallowedHost': {\n 'handlers': ['null'],\n 'propagate': False,\n },\n }\n}\n\n\n#############################################################################\n# PEPYSDIARY-SPECIFIC SETTINGS.\n\nGOOGLE_ANALYTICS_ID = 'UA-89135-2'\n\nGOOGLE_MAPS_API_KEY = environ.get('GOOGLE_MAPS_API_KEY')\n\n# From https://www.google.com/recaptcha/\nRECAPTCHA_PUBLIC_KEY = environ.get('RECAPTCHA_PUBLIC_KEY')\nRECAPTCHA_PRIVATE_KEY = environ.get('RECAPTCHA_PRIVATE_KEY')\nRECAPTCHA_USE_SSL = True\n\n# Do we use Akismet/TypePad spam checking?\n# True/False. If false, no posted comments are checked.\n# If True, AKISMET_API_KEY must also be set.\nUSE_SPAM_CHECK = environ.get('USE_SPAM_CHECK')\n\n# From http://akismet.com/\nAKISMET_API_KEY = environ.get('AKISMET_API_KEY')\n\n# From http://mapbox.com/\nMAPBOX_MAP_ID = environ.get('MAPBOX_MAP_ID')\nMAPBOX_ACCESS_TOKEN = environ.get('MAPBOX_ACCESS_TOKEN')\n","sub_path":"pepysdiary/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"459672027","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom pathlib import Path\n\n\ndef get_reldir(full_filename, dest_dir, level=None):\n if level and level >= len(Path(full_filename).resolve().parents):\n return dest_dir\n\n dir_path, filename = os.path.split(full_filename)\n if level:\n full = str(Path(full_filename).resolve().parents[0])\n path_level = str(Path(full_filename).resolve().parents[level])\n dir_path = full.replace(path_level, '')\n else:\n dir_path = os.path.relpath(filename)\n\n return '{}{}'.format(dest_dir, dir_path)\n\n\ndef makedir(path, parents=False, exist_ok=False):\n dirpath = Path(Path(path).parent)\n if dirpath.exists() and dirpath.is_file():\n raise FileExistsError('{} is exists.'.format(dirpath))\n dirpath.mkdir(parents=parents, exist_ok=exist_ok)\n","sub_path":"ext/pathutils.py","file_name":"pathutils.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629544599","text":"from collections import OrderedDict\nresult = []\ndict = OrderedDict()\n\n\ndef LRU_chache2(capacity, query_type, key, value):\n for i, num in enumerate(query_type):\n if num == 1:\n set(key[i], value[i], capacity)\n else:\n get(key[i])\n return result\n\n\ndef get(key):\n if key in dict:\n dict.move_to_end(key)\n result.append(dict.get(key))\n else:\n result.append(-1)\n\n\ndef set(key, value, capacity):\n dict[key] = value\n dict.move_to_end(key)\n print(dict)\n print(len(dict))\n if len(dict) > capacity:\n #print(len(dict))\n dict.popitem(last=False)\n print('after', dict)\n # dict[key] = value\n # dict.move_to_end(key)\n\n\nquery_type = [1, 1, 0, 1, 0, 1, 0]\nkey = [5, 10, 5, 15, 10, 5, 5]\nvalue = [11, 22, 1, 33, 1, 55, 1]\n\nans = LRU_chache2(2, query_type, key, value)\nprint(ans)\n","sub_path":"IK/LinkedLists/LRUcache2.py","file_name":"LRUcache2.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"139452047","text":"from pyspark import SparkConf, SparkContext\nfrom pyspark.sql import SparkSession, SQLContext\nfrom pyspark.sql.functions import col, asc, desc, lit, row_number\nfrom pyspark.sql.window import Window\nimport sys\nfrom graphframes import *\n\n\nconf = SparkConf().setAppName(\"project\").setMaster(\"local[*]\")\nsc = SparkContext(conf = conf)\nspark = SparkSession(sc)\nsqlContext = SQLContext(sc)\nsc.setLogLevel(\"ERROR\")\n\nINPUT_DATA_PATH = sys.argv[1]\nOUTPUT_DATA_PATH = sys.argv[2]\n\n####SUBTASK 1\n#Create a graph of posts and comments. Nodes are users, and there is an edge from\n#node 𝑖 to node 𝑗 if 𝑖 wrote a comment for 𝑗’s post. Each edge has a weight 𝑤𝑖𝑗 that is\n#the number of times 𝑖 has commented a post by j\n\ncomments = sc.textFile(INPUT_DATA_PATH + \"/comments.csv.gz\")\nposts = sc.textFile(INPUT_DATA_PATH + \"/posts.csv.gz\")\nheaderComments = comments.first()\nheaderPosts = posts.first()\n#x[0]: postid of which the comment is written for, x[4]: userid of the one commenting\ncomment = comments.filter(lambda x : x != headerComments) \\\n .map(lambda lines : lines.split(\"\\t\")) \\\n .map(lambda x : (x[0],x[4]))\n\n#x[0]: postID, x[6]: ownerUserid\npost = posts.filter(lambda x : x != headerPosts) \\\n .map(lambda lines : lines.split(\"\\t\")) \\\n .map(lambda x : (x[0], x[6]))\n\njoin = comment.join(post)\nnewRDD = join.map(lambda x : (x[1],1)) \\\n .reduceByKey(lambda a,b : a+b)\nedges = newRDD.map(lambda x : (x[0][0], x[0][1], x[1]))\nvertices = comment.filter(lambda x : x != headerComments) \\\n .map(lambda x : x[1])\n\n#######Could not get this to work.##########\n# e = sqlContext.createDataFrame(edges)\n# v = sqlContext.createDataFrame(vertices)\n#\n# g = GraphFrame(v, e)\n# print(g)\n\n####SUBTASK 2\n#Convert the result of the previous step into a Spark DataFrame (DF)\n#and answer the following subtasks using DataFrame API, namely using Spark SQL\n\ncolumns = [\"src\", \"dst\", \"w\"]\ndf = edges.toDF(columns)\ndf.printSchema()\ndf.show(truncate=False)\n\n\n####SUBTASK 3\n#Find the user ids of top 10 users who wrote the most comments\n\n#create a dummy row to generate row numbers\n\nprint(\"User ids of top 10 users who wrote the most comments: \")\nw = Window().partitionBy(lit('a')).orderBy(lit('a'))\n\nsortedDf = df.sort(col(\"w\").desc())\nselectRows = sortedDf.withColumn(\"row_num\", row_number().over(w))\nselectRows.filter(col(\"row_num\") \\\n .between(1,10)) \\\n .select(\"src\") \\\n .show(truncate=False)\n\n####SUBTASK 4\n#Find the display names of top 10 users who their posts received the greatest number\n#of comments. To do so, you can load users information (or table) into a DF and join the\n#DF from previous subtasks (that the DF containing the graph of posts and comments)\n#with it to produce the results\n\nprint(\"These are the display names of the top 10 users who received the greatest number of comments:\\n\")\n\nuserDf = spark.read.options(header ='True', inferSchema='True', delimiter='\\t') \\\n .csv(INPUT_DATA_PATH + \"/users.csv.gz\") \\\n .select(\"DisplayName\", \"Id\")\n\nleftJoin = selectRows.join(userDf, selectRows.dst == userDf.Id, 'inner') \\\n .filter(col(\"row_num\") \\\n .between(1,10)) \\\n .select(\"DisplayName\") \\\n .show(truncate=False)\n\n####SUBTASK 5\ndf.coalesce(1).write.format('com.databricks.spark.csv').option('header', 'true').save(OUTPUT_DATA_PATH + '/output.csv')\n","sub_path":"task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"609678048","text":"#!/usr/bin/env python\n\n# pylint: disable = bad-whitespace\n# pylint: disable = invalid-name\n# pylint: disable = missing-docstring\n\nimport unittest\nimport fuzz_thread\nfrom connect import set_target, scrape_links, parse_html\n\n\nclass TestUM(unittest.TestCase):\n\n def setUp(self):\n pass\n\n # Test connection success\n def test_connect(self):\n res = set_target('https://www.google.com/')[1]\n self.assertEquals(res, 'Success')\n\n # Test basic scraper functionality\n def test_scrape(self):\n res = scrape_links('https://www.google.com/', 3)\n self.assertTrue(res != None)\n\n # Test scraper parsing ability\n def test_scrape_2(self):\n data = open('test_html/wiki.dat').read()\n url = 'https://en.wikipedia.org/wiki/George_Frideric_Handel'\n link_cnt = 861\n length = len(parse_html(url, data, 10))\n self.assertEquals(link_cnt, length)\n\n # Test queue class, and see if discovering paramaterized urls\n def test_queue(self):\n data = open('test_html/wiki.dat').read()\n url = 'https://en.wikipedia.org/wiki/George_Frideric_Handel'\n links = parse_html(url, data, 10)\n queue = fuzz_thread.DictQueue({url: 5})\n queue.delay = 0\n queue.add_links(links)\n\n # 30 parameterized links in the html\n self.assertEquals(len(queue.param_links), 30)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"TestFuzzer.py","file_name":"TestFuzzer.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"513500440","text":"class Node(object):\n\tdef __init__(self,elem=-1,lchild=None,rchild=None):\n\t\tself.elem = elem\n\t\tself.lchild = lchild\n\t\tself.rchild = rchild\n\n\nclass Tree(object):\n\tdef __init__(self,root=None):\n\t\tself.root = None\n\n\tdef add(self,elem):\n\t\tnode = Node(elem)\n\t\tif self.root == None:\n\t\t\tself.root = node\n\t\telse:\n\t\t\tqueue = []\n\t\t\tqueue.append(self.root)\n\t\t\twhile queue:\n\t\t\t\tcur = queue.pop(0)\n\t\t\t\tif cur.lchild == None:\n\t\t\t\t\tcur.lchild = node\n\t\t\t\t\treturn\n\t\t\t\telif cur.rchild == None:\n\t\t\t\t\tcur.rchild = node\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\tqueue.append(cur.lchild)\n\t\t\t\t\tqueue.append(cur.rchild)\n\n\tdef preorder(self,root):\n\t\t'''先序'''\n\t\tif root == None:\n\t\t\treturn \n\t\tprint(root.elem,end=' ')\n\t\tself.preorder(root.lchild)\n\t\tself.preorder(root.rchild)\n\n\n\tdef inorder(self,root):\n\t\t'''中序'''\n\t\tif root == None:\n\t\t\treturn\n\t\tself.inorder(root.lchild)\n\t\tprint(root.elem,end=' ')\n\t\tself.inorder(root.rchild)\n\t\t\n\n\tdef postorder(self,root):\n\t\t'''后序'''\n\t\tif root == None:\n\t\t\treturn\n\t\tself.postorder(root.lchild)\n\t\tself.postorder(root.rchild)\n\t\tprint(root.elem,end=' ')\n\n\tdef breadth_travel(self,root):\n\t\t'''层次'''\n\t\tif root == None:\n\t\t\treturn\n\t\tqueue = []\n\t\tqueue.append(root)\n\t\twhile queue:\n\t\t\tnode = queue.pop(0)\n\t\t\tprint(node.elem,end=' ')\n\t\t\tif node.lchild != None:\n\t\t\t\tqueue.append(node.lchild)\n\t\t\tif node.rchild != None:\n\t\t\t\tqueue.append(node.rchild)\n\t\t \nif __name__ == \"__main__\":\n\ttree = Tree()\n\ttree.add(0)\n\ttree.add(1)\n\ttree.add(2)\n\ttree.add(3)\n\ttree.add(4)\n\ttree.add(5)\n\ttree.add(6)\n\ttree.add(7)\n\ttree.add(8)\n\ttree.add(9)\n\ttree.preorder(tree.root)\n\tprint()\n\ttree.inorder(tree.root)\n\tprint()\n\ttree.postorder(tree.root)\n\tprint()\n\ttree.breadth_travel(tree.root)\n\n\n","sub_path":"Traversing.py","file_name":"Traversing.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"189789735","text":"from .utils import *\n\n__all__ = ['page']\n\npage = Blueprint('page', __name__)\n\n@page.route('')\ndef index():\n\treturn render_template('page/index.html', **locals())\n\n@page.route('hah')\ndef hah():\n\t\"\"\"hah\"\"\"\n\treturn 'hah'\n\n@page.route('help')\ndef help():\n\tfunc_list = {}\n\tfor rule in current_app.url_map.iter_rules():\n\t\tif rule.endpoint != 'static':\n\t\t\tfunc_list[rule.rule] = rule.endpoint\n\treturn jsonify(func_list)\n\n","sub_path":"app/views/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"2658407","text":"import urllib\nimport urllib2\nimport json\nimport time\n\n### Cooops key\n# AIzaSyBQLYjFS54lmPrIl2P0mCZ2h21pSdXBivI\n\n### My key\n# AIzaSyBDMRlHkKNzsVMVUUcsajKgU6K3URJfu3k\n\n### Dotun Key\n# AIzaSyCSH3RvIURBhOBJJBrorm5Lc8AjsiNu2Q8\nparams = {\n 'q': 'GUNTER SCHLIERKAMP',\n 'num': 10, # range 1 to 8\n 'start': 1,\n 'key' : \"AIzaSyBDMRlHkKNzsVMVUUcsajKgU6K3URJfu3k\",\n 'cx' : '014326078567566203289:jbmph5cj2ue',\n 'searchType': 'image',\n \"imgColorType\": 'color'\n}\n\nBASE_URL = \"https://www.googleapis.com/customsearch/v1?\"\n\nseenUrls = set()\nwith open(\"urls.txt\",\"r\") as seenFile:\n seenUrls = set(seenFile.readlines())\nprint(\"# seen urls\",len(seenUrls))\n\nsearchTerms = [\"Arnold Schwarzenegger bodybuilding\",\"phil health bodybuilding\", \\\n\"franco columbo bodybuilding\",\"Murli Kumar bodybuilding\", \"Suhas Khamkar bodybuilding\",\"flex wheeler bodybuilding\" \\\n\"ronnie coleman bodybuilding\", \"kevin levrone bodybuilding\",\"jay cutler bodybuilding\", \"matt ogus bodybuilding\"]\nsearchDepth = 3\n\nfor term in searchTerms:\n params['q'] = term\n params['start'] = 1\n for i in range(searchDepth):\n \n SEARCH_URL = BASE_URL+ urllib.urlencode(params)\n print(\"starting iter:\",i)\n imgUrls = []\n\n def parse(response):\n response = json.load(response)\n # print(type(response))\n # print(response.keys())\n # print(\"\\n \\n got response keys \\n\",response.keys())\n for result in response['items']:\n # print(result)\n imgUrls.append((result[\"title\"],result[\"link\"]))\n\n\n response = urllib2.urlopen(SEARCH_URL)\n parse(response)\n\n print(\"got images: \",len(imgUrls))\n\n # Download Images\n count = params['start']\n for title,link in imgUrls:\n if link not in seenUrls:\n savePath = \"./buff/\"+params[\"q\"].replace(\" \",\"_\")+\"-\"+str(count)+\".jpg\"\n try:\n urllib.urlretrieve(link, savePath)\n except Exception as e:\n print(\"caught exception\",e,\"\\n \\n \")\n count+=1\n print(\"retrieved: \",count,link)\n seenUrls.add(link)\n params['start'] += params['num']\n time.sleep(.5)\n\nwith open(\"urls.txt\",\"w\") as updatedSeen:\n for url in seenUrls:\n updatedSeen.write(url+\"\\n\")\n\n","sub_path":"google_img_scrapy.py","file_name":"google_img_scrapy.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"399653182","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 12 10:35:00 2020\n\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport sklearn.linear_model as lm\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.metrics import r2_score\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.preprocessing import StandardScaler\n\ndf_train=pd.read_csv(\"../Data/House Price Prediction/train.csv\")\n#self created testing:\n#df_train = df_train.head(8000)\n\ndf_train['date']=pd.to_datetime(df_train['date'])\ndf_train['year']=df_train['date'].dt.year\ndf_train['month']=df_train['date'].dt.month\n\ntable_zip=pd.pivot_table(df_train,values='price',index='zipcode',aggfunc=np.mean)\ntable_zip=table_zip.sort_values('price')\ntable_zip['sorted_zipcode']=range(len(table_zip))\ntable_zip.sort_index(inplace=True)\nplt.scatter(table_zip['sorted_zipcode'],table_zip['price'])\nplt.show()\n\nfor i in range(len(df_train)):\n zc=df_train.loc[i,'zipcode']\n zp_new=table_zip.loc[zc,'sorted_zipcode']\n df_train.loc[i,'zipcode']=zp_new\n\n\n#df_train['sorted_zipcode']=[table_zip.loc[i,'sorted_zipcode'] for i in df_train['zipcode']]\n\n#linear\ny=df_train['price']\nX_train1=df_train.drop(['price','id','date'],axis=1)\n\nreg1=lm.LinearRegression()\ny_log=np.log(y)\nreg1.fit(X_train1,y_log)\n\nPred1=reg1.predict(X_train1)\nPred1=np.exp(Pred1)\nPred1[Pred1>df_train['price'].max()]=df_train['price'].max()\nPred1[Pred1df_train['price'].max()]=df_train['price'].max()\nPred2[Pred2df_train['price'].max()]=df_train['price'].max()\nPred3[Pred3df_train['price'].max()]=df_train['price'].max()\nPred4[Pred4\\n\"\n ret += self.vtk_add_DataArray( Data=connect , DataName=\"connectivity\", VectorData=True, nComponents=1 )\n ret += self.vtk_add_DataArray( Data=offsets , DataName=\"offsets\" )\n ret += self.vtk_add_DataArray( Data=types , DataName=\"types\" )\n ret += \"\\n\"\n return( ret )\n\n \n # ------------------------------------------------- #\n # --- vtk_add_DataArray --- #\n # ------------------------------------------------- #\n def vtk_add_DataArray( self, Data=None, DataName=None, DataFormat=None, DataType=None, nComponents=None, nData=None, VectorData=False ):\n if ( Data is None ): sys.exit( \"[vtk_add_DataArray -@makeUnstructuredGrid-] Data == ??? \" )\n if ( DataName is None ): sys.exit( \"[vtk_add_DataArray -@makeUnstructuredGrid-] DataName == ??? \" )\n if ( DataFormat is None ): DataFormat = self.DataFormat\n if ( DataType is None ): DataType = self.inquiryData( Data=Data, ret_DataType =True, VectorData=VectorData )\n if ( nComponents is None ): nComponents = self.inquiryData( Data=Data, ret_nComponents=True, VectorData=VectorData )\n if ( nData is None ): nData = self.inquiryData( Data=Data, ret_nData =True, VectorData=VectorData )\n ret = \"\"\n ret += '\\n'\\\n .format( DataName, DataType, nComponents, DataFormat )\n lines = \"\"\n if ( VectorData ):\n for line in Data:\n lines += ( \" \".join( [ str( val ) for val in line ] ) + \"\\n\" )\n else:\n for line in np.ravel( Data ):\n lines += \"{0} \".format( line )\n lines += \"\\n\"\n ret += lines\n ret += '\\n'\n return( ret )\n \n \n # ------------------------------------------------- #\n # --- vtk_writeFile --- #\n # ------------------------------------------------- #\n def vtk_writeFile( self, vtkFile=None ):\n if ( vtkFile is None ): vtkFile = self.vtkFile\n with open( vtkFile, \"w\" ) as f:\n f.write( self.vtkContents )\n f.write( self.vtkEndTags )\n subprocess.call( ( \"xmllint --format --encode utf-8 {0} -o {0}\"\\\n .format( vtkFile ) ).split() )\n print( \"[vtk_writeFile-@makeUnstructuredGrid-] VTK File output :: {0}\".format( vtkFile ) )\n\n\n # ------------------------------------------------- #\n # --- inquiryData --- #\n # ------------------------------------------------- #\n def inquiryData( self, Data=None, VectorData=False, ret_DataType=False, ret_nComponents=False, ret_nData=False ):\n if ( Data is None ): sys.exit( \"[inquiryData-@vtk_makeUnstructuredGrid-] Data == ??? \" )\n # ------------------------------------------------- #\n # --- [1] DataType Check --- #\n # ------------------------------------------------- #\n if ( type(Data) is not np.ndarray ):\n sys.exit( \"[inquiryData-@vtk_makeUnstructuredGrid-] Data should be np.ndarray [ERROR]\" )\n if ( Data.dtype == np.int32 ): DataType = \"Int32\"\n if ( Data.dtype == np.int64 ): DataType = \"Int64\"\n if ( Data.dtype == np.float32 ): DataType = \"Float32\"\n if ( Data.dtype == np.float64 ): DataType = \"Float64\"\n # ------------------------------------------------- #\n # --- [2] Data Shape Check --- #\n # ------------------------------------------------- #\n if ( VectorData is True ):\n nComponents = Data.shape[-1]\n nData = np.size( Data[-1][:] )\n else:\n nComponents = 1\n nData = np.size( Data[:] )\n # ------------------------------------------------- #\n # --- [3] Return --- #\n # ------------------------------------------------- #\n if ( ret_DataType ): return( DataType )\n if ( ret_nComponents ): return( nComponents )\n if ( ret_nData ): return( nData )\n return( { \"DataType\":DataType, \"nComponents\":nComponents, \"nData\":nData } )\n\n \n # ------------------------------------------------- #\n # --- prepareData --- #\n # ------------------------------------------------- #\n def prepareData( self, Data=None, VectorData=False ):\n # ------------------------------------------------- #\n # --- [1] Data Array Type/Shape Check --- #\n # ------------------------------------------------- #\n if ( Data is None ): return()\n if ( type(Data) is not np.ndarray ):\n sys.exit( \"[prepareData-@vtk_makeUnstructuredGrid-] Data should be np.ndarray [ERROR]\" )\n if ( Data.ndim >= 5 ):\n sys.exit( \"[prepareData-@vtk_makeUnstructuredGrid-] incorrect Data size ( ndim >= 5 ) [ERROR]\" )\n # ------------------------------------------------- #\n # --- [2] DataDims & LILJLK Check --- #\n # ------------------------------------------------- #\n if ( VectorData is True ):\n self.DataDims = Data.shape[-1]\n self.LILJLK = Data.shape[:-1]\n else:\n self.DataDims = 1\n self.LILJLK = Data.shape[:]\n # ------------------------------------------------- #\n # --- [3] for 2D Data --- #\n # ------------------------------------------------- #\n if ( len( self.LILJLK ) == 2 ):\n self.LILJLK = self.LILJLK + (1,)\n Data = Data.reshape( self.LILJLK )\n if ( len( self.LILJLK ) == 1 ):\n self.LILJLK = self.LILJLK + (1,1,)\n Data = Data.reshape( self.LILJLK )\n\n\n \n# ======================================== #\n# === 実行部 === #\n# ======================================== #\nif ( __name__==\"__main__\" ):\n elemFile = \"elems.dat\"\n nodeFile = \"nodes.dat\"\n with open( elemFile, \"r\" ) as f:\n rElem = np.loadtxt( f )\n Elem = np.array( rElem[:,1:], dtype=np.int64 )\n with open( nodeFile, \"r\" ) as f:\n Node = np.loadtxt( f )\n Data = np.zeros( (Elem.shape[0]) )\n for iE,el in enumerate( Elem ):\n Data[iE] = 0.25 * ( Node[el[0],2] + Node[el[1],2] + Node[el[2],2] + Node[el[3],2] )\n vtk = vtk_makeUnstructuredGrid( Data=Data, Elem=Elem, Node=Node )\n \n","sub_path":"makeUnstructuredGrid/makeUnstructuredGrid.py","file_name":"makeUnstructuredGrid.py","file_ext":"py","file_size_in_byte":12623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"207577092","text":"from random import randint\nimport pygame\n\nd = pygame.image.load(\"Assets/bd.png\")\nf = pygame.image.load(\"Assets/bf.png\")\nm = pygame.image.load(\"Assets/bm.png\")\np = dict()\np[0] = pygame.image.load(\"Assets/bp0.png\")\np[1] = pygame.image.load(\"Assets/bp1.png\")\np[2] = pygame.image.load(\"Assets/bp2.png\")\np[3] = pygame.image.load(\"Assets/bp3.png\")\np[4] = pygame.image.load(\"Assets/bp4.png\")\np[5] = pygame.image.load(\"Assets/bp5.png\")\np[6] = pygame.image.load(\"Assets/bp6.png\")\np[7] = pygame.image.load(\"Assets/bp7.png\")\np[8] = pygame.image.load(\"Assets/bp8.png\")\n\n\nclass Minesweeper:\n\n def __init__(self, dim, num_mines):\n # making sure mines will fit\n if num_mines > dim**2:\n raise ValueError(\"Number of Mines Too High!!\")\n\n self.__env = []\n self._dim = dim\n self._num_mines = num_mines\n self.__mines = []\n # creating minesweeper environment\n for row in range(dim):\n self.__env.append([])\n for col in range(dim):\n self.__env[row].append(Minecell())\n\n # setting mines in random places\n for i in range(num_mines):\n mine_set = False\n while not mine_set:\n row = randint(0, dim-1)\n col = randint(0, dim-1)\n if not self.__env[row][col].mine:\n self.__env[row][col].mine = True\n self.__mines.append(self.__env[row][col])\n mine_set = True\n\n # Setting clue for each cell\n for row in range(dim):\n for col in range(dim):\n mine_counter = 0\n\n # Setting clue if cell contain mine to -1\n if self.__env[row][col].mine:\n self.__env[row][col].value = -1\n continue\n\n # incrementing mine count for above and to the left cell\n if row - 1 >= 0 and col - 1 >= 0 and self.__env[row - 1][col - 1].mine:\n mine_counter += 1\n\n\n # incrementing mine count for above cell\n if row - 1 >= 0 and col < dim and self.__env[row - 1][col].mine:\n mine_counter += 1\n\n # incrementing mine count for above and to the right cell\n if row - 1 >= 0 and col + 1 < dim and self.__env[row - 1][col + 1].mine:\n mine_counter += 1\n\n # incrementing mine count for the left cell\n if row >= 0 and col - 1 >= 0 and self.__env[row][col - 1].mine:\n mine_counter += 1\n\n # incrementing mine count for the right cell\n if row >= 0 and col + 1 < dim and self.__env[row][col + 1].mine:\n mine_counter += 1\n\n\n # incrementing mine count for below and to the left cell\n if row + 1 < dim and col - 1 >= 0 and self.__env[row + 1][col - 1].mine:\n mine_counter += 1\n\n # incrementing mine count for below cell\n if row + 1 < dim and col >= 0 and self.__env[row + 1][col].mine:\n mine_counter += 1\n\n # incrementing mine count for below and to the right cell\n if row + 1 < dim and col + 1 < dim and self.__env[row + 1][col + 1].mine:\n mine_counter += 1\n\n # setting mine count to the value of the cell\n self.__env[row][col].value = mine_counter\n\n # function to query a cell that agent will use\n def query(self, row, col):\n return self.__env[row][col].query()\n\n # function to flag a cell that agent will use\n def flag(self, row, col):\n self.__env[row][col].flag()\n\n # function to calculate score\n def calculate_score(self):\n count = 0\n for cell in self.__mines:\n if cell.flagged and not cell.queried:\n count += 1\n if self._num_mines == 0:\n return 100\n return (count / self._num_mines) * 100\n\n # function to check if game is over\n def game_over(self):\n count = 0\n for row in self.__env:\n for cell in row:\n if cell.flagged or cell.queried:\n count += 1\n return self._dim**2 == count\n\n # Function for graphics to draw the minesweeper game\n def draw(self, screen_size):\n img_size = int(screen_size / self._dim)\n surface_dim = img_size * self._dim\n surface = pygame.Surface((surface_dim, surface_dim))\n\n for row in range(len(self.__env)):\n for col in range(len(self.__env)):\n cell = self.__env[row][col]\n if not cell.queried and not cell.flagged:\n surface.blit(pygame.transform.smoothscale(d, (img_size, img_size)), (col * img_size, row * img_size))\n elif cell.mine and cell.queried:\n surface.blit(pygame.transform.smoothscale(m, (img_size, img_size)), (col * img_size, row * img_size))\n elif cell.flagged:\n surface.blit(pygame.transform.smoothscale(f, (img_size, img_size)), (col * img_size, row * img_size))\n else:\n surface.blit(pygame.transform.smoothscale(p[cell.value], (img_size, img_size)), (col * img_size, row * img_size))\n return surface\n\n # Function for graphics to draw the minesweeper game (only updates portion specified)\n def draw_single(self, screen_size, row, col):\n img_size = int(screen_size / self._dim)\n surface_dim = img_size\n surface = pygame.Surface((surface_dim, surface_dim))\n\n cell = self.__env[row][col]\n\n if not cell.queried and not cell.flagged:\n surface.blit(pygame.transform.smoothscale(d, (img_size, img_size)), (0, 0))\n elif cell.mine and cell.queried:\n surface.blit(pygame.transform.smoothscale(m, (img_size, img_size)), (0, 0))\n elif cell.flagged:\n surface.blit(pygame.transform.smoothscale(f, (img_size, img_size)), (0, 0))\n else:\n surface.blit(pygame.transform.smoothscale(p[cell.value], (img_size, img_size)), (0, 0))\n\n return surface, img_size\n\n\nclass Minecell:\n\n mine = False\n value = -1\n flagged = False\n queried = False\n\n def __init__(self):\n pass\n\n def __str__(self):\n return self.value\n\n def query(self):\n self.queried = True\n return self.mine, self.value\n\n def flag(self):\n if not self.queried:\n self.flagged = True\n\n def unflag(self):\n self.flagged = False\n\n\n\n\n\n","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":6558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"382584011","text":"from django.core.exceptions import ImproperlyConfigured\nfrom django.template.response import TemplateResponse\n\nfrom ....checkout import app\nfrom ....order import forms, handler\n\nclass SingleStepCheckoutApp(app.CheckoutApp):\n billing_form_class = forms.BillingForm\n checkout_templates = [\n 'satchless/checkout/checkout.html'\n ]\n\n def checkout(self, request, order_token):\n \"\"\"\n Checkout step 1 of 1\n The order is split into delivery groups and the user gets to pick both the\n delivery and payment methods.\n \"\"\"\n order = self.get_order(request, order_token)\n if not order or order.status != 'checkout':\n return self.redirect_order(order)\n delivery_groups = order.groups.all()\n for group in delivery_groups:\n delivery_types = list(handler.delivery_queue.enum_types(group))\n if len(delivery_types) != 1:\n raise ImproperlyConfigured(\"The singlestep checkout requires \"\n \"exactly one delivery type per group.\")\n group.delivery_type = delivery_types[0][1].typ\n group.save()\n delivery_group_forms = forms.get_delivery_details_forms_for_groups(delivery_groups,\n request.POST)\n delivery_valid = True\n if request.method == 'POST':\n delivery_valid = True\n for group, typ, form in delivery_group_forms:\n if form:\n delivery_valid = delivery_valid and form.is_valid()\n payment_types = list(handler.payment_queue.enum_types(order))\n if len(payment_types) != 1:\n raise ImproperlyConfigured(\"The singlestep checkout requires \"\n \"exactly one payment methods.\")\n order.payment_type = payment_types[0][1].typ\n order.save()\n billing_form = self.billing_form_class(request.POST or None,\n instance=order)\n payment_form = forms.get_payment_details_form(order, request.POST)\n if request.method == 'POST':\n billing_valid = billing_form.is_valid()\n payment_valid = payment_form.is_valid() if payment_form else True\n if billing_valid and delivery_valid and payment_valid:\n order = billing_form.save()\n for group, typ, form in delivery_group_forms:\n handler.delivery_queue.create_variant(group, form)\n handler.payment_queue.create_variant(order, payment_form)\n order.set_status('payment-pending')\n return self.redirect('confirmation',\n order_token=order.token)\n return TemplateResponse(request, self.checkout_templates, {\n 'billing_form': billing_form,\n 'delivery_group_forms': delivery_group_forms,\n 'order': order,\n 'payment_form': payment_form,\n })\n\ncheckout_app = SingleStepCheckoutApp()","sub_path":"satchless/contrib/checkout/singlestep/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"7590105","text":"import io\nimport scipy.io as matio\nimport os\nimport os.path\nimport numpy as np\nfrom PIL import Image\nimport time\nimport re\n\nimport torch\nimport torch.utils.data\nimport torch.nn.parallel as para\nfrom torch import nn, optim\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\nimport torch.utils.model_zoo as model_zoo\nfrom torch.nn import Parameter\n\n# —Path settings———————————————————————————————————————————————————————————————————————————————————————————————————————\nroot_path = '/mnt/FoodRecog/' # /home/lily/Desktop/food/ /Users/lei/PycharmProjects/FoodRecog/ /mnt/FoodRecog/\nimage_folder = 'ready_chinese_food' # scaled_images ready_chinese_food\nimage_path = os.path.join(root_path, image_folder, '/')\n\nfile_path = os.path.join(root_path, 'SplitAndIngreLabel/')\ningredient_path = os.path.join(file_path, 'IngreLabel.txt')\nglove_path = os.path.join(root_path, 'SplitAndIngreLabel/', 'glove.6B.300d.txt')\n\ntrain_data_path = os.path.join(file_path, 'TR.txt')\nvalidation_data_path = os.path.join(file_path, 'VAL.txt')\ntest_data_path = os.path.join(file_path, 'TE.txt')\n\nresult_path = root_path + 'results2/'\nif not os.path.exists(result_path):\n os.makedirs(result_path)\n\ntest_path = root_path + 'test/'\nif not os.path.exists(test_path):\n os.makedirs(test_path)\n\ntrain_path = root_path + 'train/'\nif not os.path.exists(train_path):\n os.makedirs(train_path)\n\n\n# —Create dataset———————————————————————————————————————————————————————————————————————————————————————————————————————\ndef default_loader(path):\n img_path = root_path + image_folder + path\n\n jpgfile = Image.open(img_path).convert('RGB')\n\n return jpgfile\n\n\nclass FoodData(torch.utils.data.Dataset):\n def __init__(self, train_data=False, test_data=False, transform=None,\n loader=default_loader):\n\n # load image paths / label file\n if train_data:\n with io.open(train_data_path, encoding='utf-8') as file:\n path_to_images = file.read().split('\\n')\n labels = matio.loadmat(file_path + 'train_label.mat')['train_label']\n\n with io.open(validation_data_path, encoding='utf-8') as file:\n path_to_images1 = file.read().split('\\n')\n labels1 = matio.loadmat(file_path + 'validation_label.mat')['validation_label']\n\n path_to_images = path_to_images + path_to_images1\n labels = np.concatenate([labels, labels1], 1)[0, :]\n\n self.path_to_images = path_to_images\n self.labels = labels\n\n self.transform = transform\n self.loader = loader\n\n def __getitem__(self, index):\n # get image matrix and transform to tensor\n path = self.path_to_images[index]\n img = self.loader(path)\n if self.transform is not None:\n img = self.transform(img)\n # get label\n label = self.labels[index]\n\n return img, label\n\n def __len__(self):\n return len(self.path_to_images)\n\n\n# —Manual settings———————————————————————————————————————————————————————————————————————————————————————————————————————\n# Image Info\nno_of_channels = 3\nimage_size = [256, 256] # [64,64]\n\n# changed configuration to this instead of argparse for easier interaction\nCUDA = 1 # 1 for True; 0 for False\nSEED = 1\nBATCH_SIZE = 32\nLOG_INTERVAL = 10\nlearning_rate = 1e-4\nblk_len = 1536\n\ntorch.manual_seed(SEED)\nif CUDA:\n torch.cuda.manual_seed(SEED)\n\n# DataLoader instances will load tensors directly into GPU memory\nkwargs = {'num_workers': 4, 'pin_memory': True} if CUDA else {}\n\n# Download or load dataset\n# shuffle data at every epoch\ntrain_loader = torch.utils.data.DataLoader(\n FoodData(train_data=True, test_data=False,\n transform=transforms.ToTensor()),\n batch_size=BATCH_SIZE, shuffle=True, **kwargs)\n\n# —Model———————————————————————————————————————————————————————————————————————————————————————————————————————\n\n# Encoder network for image\n__all__ = [\n 'vgg16_bn',\n 'vgg19_bn',\n]\n\nmodel_urls = {\n 'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',\n 'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',\n}\n\n\nclass VGG(nn.Module):\n def __init__(self, features, init_weights=True):\n super(VGG, self).__init__()\n self.features = features\n\n if init_weights:\n self._initialize_weights()\n\n def forward(self, x):\n x = self.features(x)\n return x\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, 0, 0.01)\n nn.init.constant_(m.bias, 0)\n\n\ndef make_layers(cfg, batch_norm=False):\n layers = []\n in_channels = 3\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)]\n in_channels = v\n return nn.Sequential(*layers)\n\n\ncfg = {\n 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\n 'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\n}\n\n\ndef vgg16_bn(pretrained=False, **kwargs):\n \"\"\"VGG 16-layer model (configuration \"D\") with batch normalization\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n if pretrained:\n kwargs['init_weights'] = False\n\n model = VGG(make_layers(cfg['D'], batch_norm=True), **kwargs)\n\n if pretrained:\n pretrained_dict = model_zoo.load_url(model_urls['vgg16_bn'])\n model_dict = model.state_dict()\n\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict\n and not re.match(k, 'classifier.0.weight')\n and not re.match(k, 'classifier.6.weight')\n and not re.match(k, 'classifier.6.bias')\n }\n\n model_dict.update(pretrained_dict)\n model.load_state_dict(model_dict)\n\n return model\n\n\ndef vgg19_bn(pretrained=False, **kwargs):\n \"\"\"VGG 19-layer model (configuration 'E') with batch normalization\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n if pretrained:\n kwargs['init_weights'] = False\n\n model = VGG(make_layers(cfg['E'], batch_norm=True), **kwargs)\n\n if pretrained:\n pretrained_dict = model_zoo.load_url(model_urls['vgg19_bn'])\n model_dict = model.state_dict()\n\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict\n and not re.match(k, 'classifier.0.weight')\n and not re.match(k, 'classifier.6.weight')\n and not re.match(k, 'classifier.6.bias')\n }\n\n model_dict.update(pretrained_dict)\n model.load_state_dict(model_dict)\n\n return model\n\n\nset_gpu_encoder = 3\nset_gpu_others = 1\n\n\n# entire model\nclass MyModel(nn.Module):\n def __init__(self, num_key_ingre=5, max_seq=30):\n super(MyModel, self).__init__()\n # network for image channel\n self.encoder = vgg19_bn().cuda(set_gpu_encoder)\n self.vgg_map2vec = nn.Linear(512 * ((image_size[0] // (2 ** 5)) ** 2), 4096).cuda(set_gpu_others)\n self.vgg_linear = nn.Linear(4096, 4096).cuda(set_gpu_others)\n\n # classifier\n self.classifier_v = nn.Linear(blk_len, 172).cuda(set_gpu_others)\n\n # domain transfer\n self.trans_img2l = nn.Linear(blk_len, blk_len).cuda(set_gpu_others)\n\n self.softmax = nn.Softmax()\n self.log_softmax = nn.LogSoftmax()\n self.relu = nn.LeakyReLU()\n self.dropout = nn.Dropout()\n\n self._initialize_weights()\n\n def forward(self, x): # x:image, y:ingredient\n # compute image latent vectors & recons\n x_latent_maps = self.encoder(x)\n x_latent = self.get_latent(x_latent_maps.cuda(set_gpu_others))\n\n # compute v t predicts in domain adapted space\n predicts = self.get_predicts_with_align(x_latent[:, 0:blk_len])\n\n return predicts.cuda(set_gpu_others)\n\n def get_latent(self, x_latent_maps):\n x_latent = x_latent_maps.view(x_latent_maps.size(0), -1)\n x_latent = self.dropout(self.relu(self.vgg_map2vec(x_latent)))\n x_latent = self.dropout(self.relu(self.vgg_linear(x_latent)))\n return x_latent\n\n def get_predicts_with_align(self, x_latent):\n # compute features in the transferred latent domain\n x_latent2l = self.trans_img2l(x_latent)\n predicts = self.classifier_v(x_latent2l)\n return predicts\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, 0, 0.01)\n\n\n# —Model training & testing———————————————————————————————————————————————————————————————————————————————————————————————————————\ndef get_updateModel():\n model_dict = model.state_dict()\n\n # update image channel\n pretrained_dict = torch.load(file_path + 'model9-words.pt', map_location='cpu')\n extracted_dict_img = {k[7:]: v for k, v in pretrained_dict.items() if\n k.startswith('module.encoder.') and not k.startswith('module.encoder.classifier')}\n\n # # update lstm channel\n # pretrained_dict = torch.load(file_path + 'finalModel_vgg-lstm.pt', map_location='cpu')\n # extracted_dict_lstm = {k: v for k, v in pretrained_dict.items() if\n # k.startswith('encoder_t.')\n # or k.startswith('decoder_t.')\n # or k.startswith('classifier_')\n # or k.startswith('trans_')\n # }\n\n model_dict.update(extracted_dict_img)\n # model_dict.update(extracted_dict_lstm)\n model.load_state_dict(model_dict)\n\n return model\n\n\n# Model\nmodel = MyModel()\nmodel = get_updateModel()\n\n\n# pretrained_dict = torch.load(file_path + 'model9-words.pt')\n# model_dict = model.state_dict()\n# pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict and (n.startswith('encoder') or #n.startswith('decoder'))}\n\n# model_dict.update(pretrained_dict)\n# model.load_state_dict(model_dict)\n\ndef get_optim(lr):\n # Lower the learning rate on the VGG fully connected layers by 1/10th. It's a hack, but it helps\n # stabilize the models.\n fc_params = [p for n, p in model.named_parameters() if n.startswith('encoder.') and p.requires_grad]\n non_fc_params = [p for n, p in model.named_parameters() if not n.startswith('encoder.') and p.requires_grad]\n params = [{'params': fc_params, 'lr': 1e-10}, {'params': non_fc_params}]\n # params = [p for n,p in detector.named_parameters() if p.requires_grad]\n\n optimizer = optim.Adam(params, lr=lr) # weight_decay=1e-3, lr=lr)\n\n return optimizer\n\n\noptimizer = get_optim(learning_rate)\n\n# optim.Adam(model.parameters(), weight_decay=1e-3,\n# lr=learning_rate) # .module.parameters(), lr=learning_rate)\n\n# ------------------------------------------------------------------\n\n\n\n\n# Loss\ncriterion = nn.CrossEntropyLoss()\n\n\ndef loss_function(predicts_V, labels):\n # image channel loss\n CE_V = criterion(predicts_V, labels - 1) * 20\n\n return CE_V\n\n\n# ------------------------------------------------------------------\n\ndef top_match(predicts, labels):\n sorted_predicts = predicts.cpu().data.numpy().argsort()\n top1_labels = sorted_predicts[:, -1:][:, 0]\n match = float(sum(top1_labels == (labels - 1)))\n\n top5_labels = sorted_predicts[:, -5:]\n hit = 0\n for i in range(0, labels.size(0)):\n hit += (labels[i] - 1) in top5_labels[i, :]\n\n return match, hit\n\n\ndef train(epoch):\n # toggle model to train mode\n print('Training starts..')\n model.train()\n train_loss = 0\n top1_accuracy_total_V = 0\n top5_accuracy_total_V = 0\n total_time = time.time()\n\n for batch_idx, (data, labels) in enumerate(train_loader):\n # ---------------------------------------------------------------------------------------------------------------------------------\n # for effective code debugging\n # if batch_idx < len(train_loader)-20:\n # print('skip batch {}'.format(batch_idx))\n # continue\n # print('batch %',batch_idx)\n # ---------------------------------------------------------------------------------------------------------------------------------\n\n start_time = time.time()\n data = Variable(data)\n if CUDA:\n data = data.cuda(set_gpu_encoder)\n labels = labels.cuda(set_gpu_others)\n\n # obtain output from model\n predicts_V = model(data)\n\n # loss\n CE_V = loss_function(predicts_V, labels)\n\n # optim for myModel with generator\n optimizer.zero_grad()\n loss = CE_V\n loss.backward()\n train_loss += loss.data\n optimizer.step()\n\n # compute accuracy\n predicts_V = predicts_V.cpu()\n labels = labels.cpu()\n\n matches_V, hits_V = top_match(predicts_V, labels)\n # top 1 accuracy\n top1_accuracy_total_V += matches_V\n top1_accuracy_cur_V = matches_V / float(labels.size(0))\n\n # top 5 accuracy\n top5_accuracy_total_V += hits_V\n top5_accuracy_cur_V = hits_V / float(labels.size(0))\n\n if epoch == 1 and batch_idx == 0:\n print(\n 'Train Epoch: {} [{}/{} ({:.0f}%)] | Loss: {:.4f} | CE_V: {:.4f} | Top1_Accuracy_V:{} | Top5_Accuracy_V:{} | Time:{} | Total_Time:{}'.format(\n epoch, (batch_idx + 1) * len(data), len(train_loader.dataset),\n 100. * (batch_idx + 1) / len(train_loader), loss.data,\n CE_V.data,\n top1_accuracy_cur_V, top5_accuracy_cur_V,\n round((time.time() - start_time), 4),\n round((time.time() - total_time), 4)))\n\n with io.open(result_path + 'train_loss.txt', 'a', encoding='utf-8') as file:\n # print('write in-batch loss at epoch {} | batch {}'.format(epoch,batch_idx))\n file.write('%f\\n' % (train_loss))\n\n elif batch_idx % LOG_INTERVAL == 0:\n print(\n 'Train Epoch: {} [{}/{} ({:.0f}%)] | Loss: {:.4f} | CE_V: {:.4f} | Top1_Accuracy_V:{} | Top5_Accuracy_V:{} | Time:{} | Total_Time:{}'.format(\n epoch, (batch_idx + 1) * len(data), len(train_loader.dataset),\n 100. * (batch_idx + 1) / len(train_loader), loss.data,\n CE_V.data,\n top1_accuracy_cur_V, top5_accuracy_cur_V,\n round((time.time() - start_time), 4) * LOG_INTERVAL,\n round((time.time() - total_time), 4)))\n\n # records current progress for tracking purpose\n with io.open(result_path + 'model_batch_train_loss.txt', 'w', encoding='utf-8') as file:\n file.write(\n 'Train Epoch: {} [{}/{} ({:.0f}%)] | Loss: {:.4f} | CE_V: {:.4f} | Top1_Accuracy_V:{} | Top5_Accuracy_V:{} | Time:{} | Total_Time:{}'.format(\n epoch, (batch_idx + 1) * len(data), len(train_loader.dataset),\n 100. * (batch_idx + 1) / len(train_loader), loss.data,\n CE_V.data,\n top1_accuracy_cur_V, top5_accuracy_cur_V,\n round((time.time() - start_time), 4) * LOG_INTERVAL,\n round((time.time() - total_time), 4)))\n\n print(\n '====> Epoch: {} | Average loss: {:.4f} | Average Top1_Accuracy_V:{} | Average Top5_Accuracy_V:{} | Time:{}'.format(\n epoch, train_loss / len(train_loader), top1_accuracy_total_V / len(train_loader.dataset),\n top5_accuracy_total_V / len(train_loader.dataset), round((time.time() - total_time), 4)))\n\n with io.open(result_path + 'train_loss.txt', 'a', encoding='utf-8') as file:\n # print('write in-epoch loss at epoch {} | batch {}'.format(epoch,batch_idx))\n file.write('%f\\n' % (train_loss / len(train_loader)))\n\n # save current model\n torch.save(model.state_dict(), result_path + 'model' + str(epoch) + '.pt')\n\n\ndef lr_scheduler(optimizer, init_lr, epoch, lr_decay_iter):\n if epoch % lr_decay_iter:\n return init_lr\n\n # drop to 0.1*init_lr\n lr = init_lr * 0.1\n optimizer.param_groups[1]['lr'] = lr\n if lr > 0:\n optimizer.param_groups[0]['lr'] = lr\n\n return lr\n\n\ndecay = 4\nEPOCHS = decay * 3 + 1\n\nfor epoch in range(1, EPOCHS + 1):\n learning_rate = lr_scheduler(optimizer, learning_rate, epoch, decay)\n print(learning_rate)\n train(epoch)\n\n\n\n\n","sub_path":"VireoFood-172/Models/vgg/final_vgg-lstm.py","file_name":"final_vgg-lstm.py","file_ext":"py","file_size_in_byte":18614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"586747150","text":"\"\"\"\nCreated on Jan 5, 2017\n@author: lixi729\n@Project: Xanthos V1.0\n\n\nLicense: BSD 2-Clause, see LICENSE and DISCLAIMER files\n\nCopyright (c) 2017, Battelle Memorial Institute\n\n\nPerform diagnostics by comparing the estimates of average total annual runoff (km^3/yr) of this study to other models.\n\n# Estimates of average total annual runoff (km^3/yr)\n# The comparison data file needs to be preprocessed.\n# Dimension: (67420, 1)\n# Unit: km3/year\n#\n# Runoff\n# - VIC The major comparison\n# - WBM Ref comparison: WBM (Fekete et al., 2000) and WBMc (Fekete et al., 2000) are also used as additional comparisons (2 column csv files)\n# - UNH Ref comparison: UNH-GRDC 1986-1995\n\"\"\"\n\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\nfrom xanthos.data_reader.data_load import load_const_griddata as loadfile\n\n\ndef Diagnostics(settings, Q, Avg_ChFlow, ref):\n\n\n area = ref.area\n\n if settings.PerformDiagnostics:\n # Prepare the data\n ny = int(settings.EndYear - settings.StartYear + 1)\n # convert the original unit mm/month to new unit km3/year\n q = np.sum(Q[:, :], axis=1) / ny * area / 1e6\n # ac = np.sum(Avg_ChFlow[:,:], axis=1)/ny * area/1e6\n\n VIC = loadfile(settings.VICDataFile, 0, \"q\") # 67420*30\n VICyears = range(1971, 2001)\n try:\n si = VICyears.index(settings.StartYear)\n except:\n si = 0\n try:\n ei = VICyears.index(settings.EndYear) + 1\n except:\n ei = 30\n\n qq = np.sum(VIC[:, si:ei], axis=1) / (ei - si)\n plotname = 'VIC_' + str(VICyears[si]) + '-' + str(VICyears[ei - 1])\n\n UNH = loadfile(settings.UNHDataFile, 0, \"q\") # 67420*1\n\n temp1 = loadfile(settings.WBMDataFile, 0, \"q\")\n temp2 = loadfile(settings.WBMCDataFile, 0, \"q\")\n wbm = np.zeros((settings.ncell), dtype=float)\n wbmc = np.zeros((settings.ncell), dtype=float)\n for i in range(temp1.shape[0]):\n wbm[int(temp1[i, 0]) - 1] = temp1[i, 1]\n\n for i in range(temp2.shape[0]):\n wbmc[int(temp2[i, 0]) - 1] = temp2[i, 1]\n\n # Only basins/countries/regions for which all four models have values are used to estimate the RMSE values\n\n if settings.DiagnosticScale == 0 or settings.DiagnosticScale == 1:\n # Basin Based\n qb = np.zeros((max(ref.basin_ids), 5), dtype=float)\n qb[:, 0] = Aggregation_Diagnostics(settings, ref.basin_ids, q)\n qb[:, 1] = Aggregation_Diagnostics(settings, ref.basin_ids, qq)\n qb[:, 2] = Aggregation_Diagnostics(settings, ref.basin_ids, wbm)\n qb[:, 3] = Aggregation_Diagnostics(settings, ref.basin_ids, wbmc)\n qb[:, 4] = Aggregation_Diagnostics(settings, ref.basin_ids, UNH)\n qb = np.insert(qb, 0, np.sum(qb, axis=0), axis=0) # add global\n BasinNames = np.insert(ref.basin_names, 0, 'Global')\n\n writecsvDiagnostics(os.path.join(settings.OutputFolder, \"Diagnostics_Runoff_Basin_Scale\"), qb, plotname, BasinNames)\n\n outputname = os.path.join(settings.OutputFolder, \"Diagnostics_Runoff_Basin_Scale\")\n\n Plot_Diagnostics(qb[1:, :], outputname, 'Basin', plotname)\n\n for i in range(qb.shape[0]):\n if not (qb[i, 0] > 0 and qb[i, 1] > 0 and qb[i, 2] > 0 and qb[i, 3] > 0 and qb[i, 4] > 0):\n qb[i, :] = 0\n\n if settings.DiagnosticScale == 0 or settings.DiagnosticScale == 2:\n # Country Based\n qc = np.zeros((max(ref.country_ids), 5), dtype=float)\n qc[:, 0] = Aggregation_Diagnostics(settings, ref.country_ids, q)\n qc[:, 1] = Aggregation_Diagnostics(settings, ref.country_ids, qq)\n qc[:, 2] = Aggregation_Diagnostics(settings, ref.country_ids, wbm)\n qc[:, 3] = Aggregation_Diagnostics(settings, ref.country_ids, wbmc)\n qc[:, 4] = Aggregation_Diagnostics(settings, ref.country_ids, UNH)\n qc = np.insert(qc, 0, np.sum(qc, axis=0), axis=0) # add global\n CountryNames = np.insert(ref.country_names, 0, 'Global')\n\n writecsvDiagnostics(os.path.join(settings.OutputFolder, \"Diagnostics_Runoff_Country_Scale\"), qc, plotname, CountryNames)\n outputname = os.path.join(settings.OutputFolder, \"Diagnostics_Runoff_Country_Scale\")\n\n Plot_Diagnostics(qc[1:, :], outputname, 'Country', plotname)\n\n for i in range(qc.shape[0]):\n if not (qc[i, 0] > 0 and qc[i, 1] > 0 and qc[i, 2] > 0 and qc[i, 3] > 0 and qc[i, 4] > 0):\n qc[i, :] = 0\n\n # q1 = qc[np.nonzero(qc[:,0])[0][1:],0]\n # q2 = qc[np.nonzero(qc[:,1])[0][1:],1]\n # q3 = qc[np.nonzero(qc[:,2])[0][1:],2]\n # q4 = qc[np.nonzero(qc[:,3])[0][1:],3]\n # q5 = qc[np.nonzero(qc[:,4])[0][1:],4]\n\n # print \"RMSE at the country scale: \", np.sqrt(((q1 - q2) ** 2).mean()), np.sqrt(((q1 - q3) ** 2).mean()), np.sqrt(((q1 - q4) ** 2).mean()), np.sqrt(((q1 - q5) ** 2).mean())\n\n if settings.DiagnosticScale == 0 or settings.DiagnosticScale == 3:\n # Region Based\n qr = np.zeros((max(ref.region_ids), 5), dtype=float)\n qr[:, 0] = Aggregation_Diagnostics(settings, ref.region_ids, q)\n qr[:, 1] = Aggregation_Diagnostics(settings, ref.region_ids, qq)\n qr[:, 2] = Aggregation_Diagnostics(settings, ref.region_ids, wbm)\n qr[:, 3] = Aggregation_Diagnostics(settings, ref.region_ids, wbmc)\n qr[:, 4] = Aggregation_Diagnostics(settings, ref.region_ids, UNH)\n qr = np.insert(qr, 0, np.sum(qr, axis=0), axis=0) # add global\n RegionNames = np.insert(ref.region_names, 0, 'Global')\n\n writecsvDiagnostics(os.path.join(settings.OutputFolder, \"Diagnostics_Runoff_Region_Scale\"), qr, plotname, RegionNames)\n outputname = os.path.join(settings.OutputFolder, \"Diagnostics_Runoff_Region_Scale\")\n\n Plot_Diagnostics(qr[1:, :], outputname, 'Region', plotname)\n\n for i in range(qr.shape[0]):\n if not (qr[i, 0] > 0 and qr[i, 1] > 0 and qr[i, 2] > 0 and qr[i, 3] > 0 and qr[i, 4] > 0):\n qr[i, :] = 0\n\n else:\n return\n\n\ndef Aggregation_Diagnostics(settings, Map, runoff):\n NB = max(Map)\n Map_runoff = np.zeros((NB,), dtype=float)\n\n for index in range(0, settings.ncell):\n if not np.isnan(runoff[index]) and Map[index] > 0:\n Map_runoff[Map[index] - 1] += runoff[index]\n\n return Map_runoff\n\n\ndef writecsvDiagnostics(filename, data, ComparisonDataName, Names):\n headerline = \"Name,This Study,\" + ComparisonDataName + \",WBM,WBMc,UNH_1986-1995,Unit(km^3/year)\"\n newdata = np.insert(data.astype(str), 0, Names, axis=1)\n\n with open(filename + '.csv', 'w') as outfile:\n np.savetxt(outfile, newdata, delimiter=',', header=headerline, fmt='%s')\n\n\ndef Plot_Diagnostics(data, outputname, titlestr, ComparisonDataName):\n fig = plt.figure()\n ax = plt.gca()\n ax.loglog([0.01, 100000], [0.01, 100000], 'grey')\n ax.scatter(data[:, 0], data[:, 1], c='black', alpha=0.5, edgecolors='none', label=ComparisonDataName)\n ax.scatter(data[:, 0], data[:, 2], c='Red', alpha=0.5, edgecolors='none', label='WBM')\n ax.scatter(data[:, 0], data[:, 3], c='Blue', alpha=0.5, edgecolors='none', label='WBMc')\n ax.scatter(data[:, 0], data[:, 4], c='green', alpha=0.5, edgecolors='none', label='UNH/GRDC_1986-1995')\n ax.set_yscale('log')\n ax.set_xscale('log')\n ax.axis([0.01, 1e5, 0.01, 1e5])\n ax.legend(loc='lower right', bbox_to_anchor=(1, 0), fontsize=10)\n plt.title('Hydro Model Diagnostics at ' + titlestr + ' Scale', fontsize=12, fontweight='bold')\n plt.xlabel(r'This Study Estimated Averaged Annual Runoff ($km^3$/yr)', fontsize=12)\n plt.ylabel(r'Averaged Annual Runoff ($km^3$/yr)', fontsize=12)\n fig.savefig(outputname + '.png', dpi=300)\n plt.close(fig)","sub_path":"xanthos/diagnostics/diagnostics.py","file_name":"diagnostics.py","file_ext":"py","file_size_in_byte":8005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"24131835","text":"import unittest\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\nclass douyuSelenium(unittest.TestCase):\n # init\n def setUp(self):\n self.driver = webdriver.Chrome()\n\n # 具体测试用例方法,一定要以test开头\n def testDouyu(self):\n self.driver.get(\"http://www.douyu.com/directory/all\")\n while True:\n # 指定XML解析\n soup = BeautifulSoup(self.driver.page_source,'xml')\n # 返回当前页面所有房间标题列表合观众人数列表\n titles = soup.find_all(\"h3\",{\"class\":\"ellipsis\"})\n nums = soup.find_all(\"span\",{\"class\":\"dy-num fr\"})\n\n # 使用zip()函数把列表合并,并创建一个元祖对的列表[(1,2),(3,4)]\n for title, num in zip(nums,titles):\n print(\"观众人数:\" + num.get_text().strip(), \"\\t房间标题:\" + title.get_text.strip())\n # page_source.find()未找到内容则返回-1\n if self.driver.page_source.find(\"shark-pager-disable-next\") != -1:\n break\n #模拟下一页点击\n self.driver.find_element_by_class_name(\"shark-pager-next\").click()\n\n # 退出式的清理方法\n def tearDown(self):\n print(\"加载完成....\")\n self.driver.quit()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"spider_learn/spider_learn01/ocr_learn/demo02_click.py","file_name":"demo02_click.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"53996812","text":"'''sinex stations quick view'''\nimport argparse\nimport os as _os\n\n\nfrom gn_lib.gn_io.sp3 import merge_sp3, write_sp3\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description='Merge sinex SITE/ID block and create html map.')\n parser.add_argument('-s', '--sp3list',help='sp3 files paths',nargs=\"+\",default=[])\n parser.add_argument('-c', '--clklist',help='clk paths',nargs=\"+\",default=None)\n parser.add_argument('-o', '--outpath',help='path to output dir',default=_os.curdir + '/merge.sp3')\n return parser.parse_args()\n\ndef file_path(path):\n if _os.path.isfile(path):\n return path\n else:\n raise argparse.ArgumentTypeError(f\"{path} is not a valid path\")\n\n\n\nif __name__ == \"__main__\":\n parsed_args = parse_arguments()\n print(parsed_args.outpath)\n if parsed_args.sp3list:\n merged_df = merge_sp3(sp3_paths = parsed_args.sp3list, clk_paths = parsed_args.clklist)\n write_sp3(sp3_df = merged_df, path = parsed_args.outpath)\n else:\n print('sp3 list is empty')\n\n\n\n","sub_path":"scripts/merge_sp3.py","file_name":"merge_sp3.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"654177921","text":"from tkinter import *\nclass Okno(Frame):\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.pack()\n self.createWidgets()\n self.choice=0\n def createWidgets(self):\n #Guzik wyjscia\n self.QUIT = Button(self)\n self.QUIT[\"text\"] = \"Wyjdz\"\n self.QUIT[\"fg\"] = \"blue\"\n self.QUIT[\"command\"] = self.quit\n self.QUIT.pack({\"side\": \"right\"})\n #Guzik wpisywania z klawiatury\n self.keyboard = Button(self)\n self.keyboard[\"text\"] = \"Wczytaj dane z klawiatury\"\n self.keyboard[\"fg\"] = \"red\"\n self.keyboard[\"command\"] = self.quit\n self.keyboard.pack({\"side\": \"right\"})\n #Guzik wczytywania z pliku\n self.file = Button(self)\n self.file[\"text\"] = \"Wczytaj dane z pliku\"\n self.file[\"fg\"] = \"green\"\n self.file[\"command\"] = self.quit\n self.file.pack({\"side\": \"right\"})\n\n\n","sub_path":"Okno.py","file_name":"Okno.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"616954637","text":"\"\"\"\nAsteroids - the game itself.\n\"\"\"\n\nimport pygame as pg\n\nfrom . import widget_tools\nfrom .. import prepare, tools, state_machine\nfrom ..components import ship, asteroids, ufo\n\n\nBOTTOM_Y_SHIFT = 10\nSIDE_MARGIN = 20\nFONT_SIZE = 80\nSPACING = 10\nSHIP_SPACING = 50\n\nclass Game(state_machine._State):\n \"\"\"\n The core of the game.\n \"\"\"\n def __init__(self):\n state_machine._State.__init__(self)\n self.end = False\n\n self.asteroids = asteroids.AsteroidsGroup()\n self.asteroids.next_level()\n self.playerGroup = pg.sprite.GroupSingle()\n self.health = HealthBar(prepare.SHIP['lives'])\n\n self.score = Score()\n\n def spawn(self):\n \"\"\"\n Spawn ship and consume one life.\n \"\"\"\n self.ship = ship.Ship()\n self.health.lost()\n self.playerGroup.add(self.ship)\n\n def get_event(self, event):\n \"\"\"\n Proccess events, if player ship is destroyed.\n If not, ship handle movement on its own.\n \"\"\"\n if self.end:\n self.restart.get_event(event)\n elif event.type == pg.KEYDOWN and event.key == pg.K_SPACE:\n self.ship.space_pressed()\n\n def draw(self, surface, interpolate):\n surface.fill(prepare.BACKGROUND_COLOR)\n if not self.end:\n self.ship.draw(surface)\n self.asteroids.draw(surface)\n self.score.draw(surface)\n self.health.draw(surface)\n\n def update(self, keys, now):\n if self.playerGroup.__len__() == 0:\n print(self.health.healths)\n if self.health.healths > 0:\n self.spawn()\n else:\n self.end = True\n else:\n if self.asteroids.__len__() == 0:\n self.asteroids.next_level()\n self.ship.update(keys, now)\n self.asteroids.update()\n self.check_collide()\n\n def check_collide(self):\n \"\"\"\n Check for collisions.\n \"\"\"\n for asteroid in pg.sprite.groupcollide(\n self.asteroids,\n self.ship.ship_lasers,\n 1,\n 1):\n self.score.add_score(100)\n\n\n if not self.ship.immortal:\n for asteroid in pg.sprite.groupcollide(\n self.playerGroup,\n self.asteroids,\n 1,\n 0):\n pass\n\n\nclass PlayerGroup(pg.sprite.GroupSingle):\n def __init__(self):\n pg.sprite.GroupSingle.__init__()\n\n def update(self, keys, now):\n sprite.update(keys, now)\n\n def get_event(self, event):\n sprite.get_event(event)\n\n\nclass Restart(state_machine._State):\n \"\"\"\n Class that handle game over screen.\n \"\"\"\n pass\n\n\nclass HealthBar:\n \"\"\"\n Draw ship icons. Include self.healths property that show remaining ships.\n \"\"\"\n def __init__(self, healths):\n self.healths = healths\n self.image = prepare.GTX['ship_icon']\n\n y = prepare.SCREEN_SIZE[1] - BOTTOM_Y_SHIFT - FONT_SIZE - SPACING\n x = prepare.SCREEN_SIZE[0] - SIDE_MARGIN\n x_shift = - SHIP_SPACING - prepare.GTX['ship_icon'].get_size()[0]\n self.positions = [(x + i * x_shift, y) for i in range(self.healths)]\n self.positions = list(reversed(self.positions))\n\n def draw(self, surface):\n for position in self.positions:\n surface.blit(self.image, self.image.get_rect(bottomright=position))\n\n def lost(self):\n \"\"\"\n Deincrement healths and remove one ship icon.\n \"\"\"\n self.positions = self.positions[1:]\n self.healths -= 1\n\n\nclass Score(widget_tools.SimpleText):\n \"\"\"\n This class show score.\n \"\"\"\n def __init__(self):\n self.position = (prepare.SCREEN_RECT.right - SIDE_MARGIN,\n prepare.SCREEN_RECT.bottom - BOTTOM_Y_SHIFT)\n self.score = 0\n widget_tools.SimpleText.__init__(self, 'ARCADECLASSIC', FONT_SIZE, '0')\n self.update_text()\n\n def update_text(self):\n self.text = 'Score {score}'.format(score=self.score)\n widget_tools.SimpleText.update_text(self)\n self.rect = self.image.get_rect(bottomright=self.position)\n\n def add_score(self, value):\n \"\"\"\n Add to score value value and update text.\n \"\"\"\n self.score += value\n self.update_text()\n","sub_path":"data/states/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"233093734","text":"import logging\nimport os\nimport select\nimport sys\nimport threading\n\ntry:\n import thread\nexcept ImportError:\n import _thread as thread\nimport termios\nimport tty\n\nfrom . import responses\n\nlogger = logging.getLogger(__name__)\n\n\n# Initially taken from https://github.com/magmax/python-readchar\ndef readchar(wait_for_char=0.1):\n old_settings = termios.tcgetattr(sys.stdin)\n tty.setcbreak(sys.stdin.fileno())\n res = b''\n try:\n if select.select([sys.stdin, ], [], [], wait_for_char)[0]:\n res = os.read(sys.stdin.fileno(), 1)\n while select.select([sys.stdin, ], [], [], 0.0)[0]:\n res += os.read(sys.stdin.fileno(), 1)\n if res:\n return res\n finally:\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)\n return None\n\n\ndef single_char_with_timeout(timeout=5):\n timer = threading.Timer(timeout, thread.interrupt_main)\n response = None\n try:\n timer.start()\n while response is None:\n response = readchar()\n except KeyboardInterrupt:\n pass\n timer.cancel()\n return response\n\n\ndef format_track(track):\n return '%s by %s' % (\n track.name,\n ' & '.join(\n artist.name for artist in track.artists\n if artist.name\n )\n )\n\n\ndef format_album(album):\n return '%s by %s [%s]' % (\n album.album.name,\n album.artist.name,\n album.album.year\n )\n\n\ndef sorted_menu_items(items):\n global_items = []\n for key, value in sorted(items):\n if value.destination in responses.ALL:\n global_items.append((key, value))\n else:\n yield key, value\n for key, value in global_items:\n yield key, value\n\n\ndef get_duration_from_s(s):\n '''\n Formats seconds as \"%M:%S\"\n :param s: Seconds in int/float\n :returns: s formatted as \"%M:%S\"\n '''\n # Max length is 59 minutes, 59 seconds\n MAX_LENGTH = 59 * 60 + 59\n if not isinstance(s, (int, float)):\n raise TypeError('Seconds must be int/float')\n elif s < 0:\n raise TypeError('Seconds must be positive')\n elif s > MAX_LENGTH:\n s = MAX_LENGTH\n return '%s:%s' % (\n str(int(s / 60)).zfill(2),\n str(int(s % 60)).zfill(2)\n )\n\nif __name__ == '__main__':\n if sys.argv[-1] == 'wrapper':\n print(single_char_with_timeout())\n else:\n char = readchar(10)\n print(char)\n print(char.decode('utf-8'))\n","sub_path":"spoppy/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"453526414","text":"'''\nKnowledgebase admin settings\n'''\n\nfrom django.contrib import admin\nfrom .models import Question\n\nclass KnowledgebaseAdmin(admin.ModelAdmin):\n '''\n Settings for model view in django admin\n '''\n list_display = ('question', 'role', 'is_draft')\n list_editable = ['is_draft']\n list_filter = ('is_draft', 'role', 'publish_date')\n list_per_page = 20\n search_fields = ['question']\n\nadmin.site.register(Question, KnowledgebaseAdmin)\n","sub_path":"knowledgebase/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"126835551","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom ..items import FootballPlayerItem\n\nclass Fbplayer100Spider(scrapy.Spider):\n name = 'fbplayer100'\n allowed_domains = ['transfermarkt.com']\n start_urls = ['https://www.transfermarkt.com/spieler-statistik/wertvollstespieler/marktwertetop/']\n custom_settings = {\n 'COOKIES_ENABLED': False,\n 'ITEM_PIPELINES': {\n 'ArticleSpider.pipelines.FootballPlayerPipeline': 100\n }\n }\n\n def parse(self, response):\n tr_list = response.css('table.items>tbody>tr')\n item = FootballPlayerItem()\n for row in tr_list:\n item['rank'], item['position'], item['age'] = row.css('td::text').extract()\n item['country'] = row.css('td>img::attr(alt)').extract_first()\n item['name'], item['club'] = row.css('td>a>img::attr(alt)').extract()\n item['market_value'] = row.css('td>b::text').extract_first()\n yield item\n\n next = response.css('li.naechste-seite a')\n if next:\n yield response.follow(next[0], callback=self.parse)\n\n\n\n","sub_path":"ArticleSpider/ArticleSpider/spiders/fbplayer100.py","file_name":"fbplayer100.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"616200798","text":"\"\"\"\n12.0 topk问题\n\n·现在有n个数,设计算法得到前k大的数(k取列表前k个元素建立一个小根堆,堆顶就是目前第k大的数\n-->依次向后遍历列表,对于列表中的元素:\n 如果小于堆顶,则忽略该元素;\n 如果大于堆顶,则将堆顶更换为该元素,并且对堆进行一次调整\n-->遍历列表所有元素后,倒叙弹出堆顶\n\n===============================================================================\n===============================================================================\n\"\"\"\n\n\n# ========== example ==========\ndef sift(li, low, high):\n i = low\n j = 2*i + 1\n tmp = li[low]\n while j <= high:\n if j + 1 <= high and li[j+1] < li[j]: # 如果右子节点比较小\n j = j + 1\n if li[j] < tmp:\n li[i] = li[j]\n i = j\n j = 2 * i + 1\n else:\n break\n li[i] = tmp\n\n\ndef topk(li, k):\n heap = li[0:k]\n # 1.建堆\n for i in range((k - 2) // 2, -1, -1):\n sift(heap, i, k - 1)\n # 2.遍历\n for i in range(k, len(li)):\n if li[i] > heap[0]:\n heap[0] = li[i]\n sift(heap, 0, k - 1)\n # 3.出数\n for i in range(k - 1, -1, -1):\n heap[0], heap[i] = heap[i], heap[0]\n sift(heap, 0, i - 1)\n return heap\n\n\nimport random\nli = list(range(10))\nrandom.shuffle(li)\n\nprint(topk(li, 5))\n","sub_path":"12 TOPK Problem-topk问题.py","file_name":"12 TOPK Problem-topk问题.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"642796727","text":"#!/usr/bin/env python3\n# coding: utf-8\n\"\"\"\nTwinleaf Generic Multi Device Control\nCopyright 2019 Twinleaf LLC\nLicense: MIT\n\"\"\"\n\nimport tldevice\nimport threading\nimport time\n\nclass DeviceSync():\n def __init__(self, url=\"tcp://localhost\", verbose=False, rpcs=[], stateCache=True, connectingMessage = True, connectionTime = 1, timeout = False):\n self._routes = {}\n self._routes[\"/\"] = tldevice.Device(url=url, verbose=verbose, rpcs=rpcs, stateCache=stateCache, connectingMessage=connectingMessage, timeout = timeout)\n self._routes[\"/\"]._tio.recv_router = self._recvRouter\n self.__dict__[self._routes[\"/\"]._shortname] = self._routes[\"/\"]\n time.sleep(connectionTime)\n\n def _recvRouter(self, routing, packet):\n routingKey = '/'.join(map(str,routing))\n if routingKey in self._routes.keys():\n self._routes[routingKey]._tio.recv_queue.put(packet)\n else: # Create new route\n self._routes[routingKey] = tldevice.Device(url=\"router://interthread/\"+routingKey, send_router = self._routes[\"/\"]._tio.send, verbose=True, specialize=False)\n threading.Thread(target=self._specialize, args=(routingKey,)).start()\n\n def _specialize(self, routingKey):\n self._routes[routingKey]._specialize()\n self._routes[routingKey]._shortname += routingKey\n #self._routes[routingKey]._tio.shortname = self._routes[routingKey]._shortname\n self.__dict__[self._routes[routingKey]._shortname.replace(\"/\",\"\")] = self._routes[routingKey]\n\n def _interact(self):\n imported_objects = {}\n imported_objects['tio'] = self\n banner=\"\"\n exit_msg = f\"tio thanks you.\"\n try:\n from IPython import embed\n embed(\n user_ns=imported_objects, \n banner1=banner, \n banner2=f\"Use : tio.\",\n exit_msg=exit_msg)\n except ImportError:\n import code\n repl = code.InteractiveConsole(locals=imported_objects)\n repl.interact(\n banner=banner, \n exitmsg = exit_msg)\n\nclass SyncStream():\n def __init__(self, streams = []):\n self.streams = streams\n self.sync()\n\n def sync(self, flush=True):\n # Find the initial datum time\n times = []\n data = []\n for stream in self.streams:\n row = stream(samples=1, flush=flush, timeaxis=True)\n times += [row[0]]\n data += row[1:]\n\n # TODO: Check that the streams have compatible data rates\n\n # Ensure the times match up!\n # If not, catch up on the streams that are behind\n maxtime = max(times)\n mintime = min(times)\n if maxtime != mintime:\n for i,stream in enumerate(self.streams):\n max_deviation = 0\n while times[i] < maxtime:\n # print(f\"Drop a sample on stream {i}\")\n times[i] = stream(samples=1, flush=False, timeaxis=True)[0]\n max_deviation -= 1\n if max_deviation > 5:\n raise Exception(\"Can't sync stream!\")\n\n def __call__(self, samples = 1, duration=None, timeaxis=True, flush=True):\n return self.read(samples = samples, duration=duration, timeaxis=timeaxis, flush=flush)\n\n def read(self, samples = 1, duration=None, timeaxis=True, flush=True):\n if flush:\n self.sync()\n\n # Acquire data\n times = []\n data = [] \n for stream in self.streams:\n streamdata = stream(samples=samples, duration=duration, timeaxis=True, flush=False)\n times += [streamdata[0]]\n data += streamdata[1:]\n\n if len(data[0])==1:\n starttimes = times\n else:\n starttimes = [timecol[0] for timecol in times]\n\n if max(starttimes) != min(starttimes):\n delta = max(starttimes) - min(starttimes)\n raise Exception(f\"Streams out of sync by {delta}!\")\n \n if timeaxis:\n data = [times[0]] + data\n\n return data\n\n def readQueueSize(self):\n \"\"\"This reports the queue depth for the first stream\"\"\"\n return self.streams[0].queueSize()\n\n def readAvailable(self, timeaxis=True):\n samples = self.readQueueSize()\n if samples < 1:\n samples = 1\n return self.read(samples=samples, timeaxis=timeaxis, flush=False)\n\n def columnnames(self, timeaxis=True, withName=True):\n if timeaxis:\n names = [\"time\"]\n else:\n names = []\n for stream in self.streams:\n names += stream.columnnames(withName=withName)\n return names\n\n def rate(self):\n return self.streams[0].rate()\n\n def iter(self, samples=0, flush=True):\n if flush:\n yield self.read(samples = 1, flush=True)\n samples -= 1\n if samples<=0:\n while True:\n yield self.read(samples = 1, flush=False)\n else:\n for x in range(number):\n yield self.read(samples = 1, flush=False)\n \nif __name__ == \"__main__\":\n device = DeviceSync()\n device._interact()","sub_path":"tldevicesync/tldevicesync.py","file_name":"tldevicesync.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"515719223","text":"from torch.utils.data import Dataset, DataLoader\nimport os\nimport torch\nfrom torchvision import transforms\nfrom PIL import Image\n\n\nclass NORB(Dataset):\n processedDirectory = \"/data/smallNORB/processed/\"\n training_file = 'training.pt'\n testing_file = 'test.pt'\n trainingTransformations = transforms.Compose([\n transforms.Resize(48),\n transforms.RandomCrop(32),\n transforms.ColorJitter(\n brightness=32./255, contrast=0.5),\n transforms.ToTensor()\n ])\n testingTransformations = transforms.Compose([\n transforms.Resize(48),\n transforms.CenterCrop(32),\n transforms.ToTensor()\n ])\n\n def __init__(self, training):\n self.trainingFlag = training\n self.loadTrainingData()\n self.loadTestingData()\n\n def loadTrainingData(self):\n self.train_data, self.train_labels, self.train_info = self.loadFromTorchFile(\n self.training_file)\n self.train_data, self.train_labels, self.train_info = self.performAssertionChecksAndExpandLabelset(\n self.train_data, self.train_labels, self.train_info)\n\n def loadTestingData(self):\n self.test_data, self.test_labels, self.test_info = self.loadFromTorchFile(\n self.testing_file)\n self.test_data, self.test_labels, self.test_info = self.performAssertionChecksAndExpandLabelset(\n self.test_data, self.test_labels, self.test_info)\n\n def loadFromTorchFile(self, filename):\n return torch.load(os.path.join(os.getcwd()+self.processedDirectory+filename))\n\n def performAssertionChecksAndExpandLabelset(self, data, labels, info):\n size = len(labels)\n assert size == len(info)\n assert size*2 == len(data)\n labels = labels.view(\n size, 1).repeat(1, 2).view(2*size, 1)\n info = info.repeat(1, 2).view(2*size, 4)\n return data, labels, info\n\n def __getitem__(self, index):\n img, target = self.train_data[index], self.train_labels[index]\n if self.trainingFlag:\n img = self.performTrainingTransformations(img)\n else:\n img = self.performTestingTransformations(img)\n return img, target\n\n def performTrainingTransformations(self, img):\n img = Image.fromarray(img.numpy(), mode='L')\n img = self.trainingTransformations(img)\n return img\n\n def performTestingTransformations(self, img):\n img = Image.fromarray(img.numpy(), mode=\"L\")\n img = self.testingTransformations(img)\n return img\n\n def __len__(self):\n return len(self.train_data)\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"norb_loader.py","file_name":"norb_loader.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"87459015","text":"from pprint import pprint\n\nfrom climvc.clicontroller import CLIController\n\nfrom decisionmaker import Choice, ChoiceList\n\n\nclass Controller(CLIController):\n def b(self):\n \"\"\"Command. Select the best item from a list.\"\"\"\n print(self.model.lists[self.input(\"list\")].best())\n \n def nb(self):\n \"\"\"Comand. Get the best item in a list, excluding the last returned best item.\"\"\"\n print(self.model.lists[self.input(\"list\")].next_best())\n \n def i(self, exclude=False):\n \"\"\"Comand. Include items for consideration\"\"\"\n operation = 'exclude' if exclude else 'include'\n list_name = self.input(\"list name\")\n inclusions = self.input(operation + \" what? (optional)\").split(\", \")\n if not inclusions or not inclusions[0]:\n inclusions = self.model.lists[list_name].excluded()\n for choice_name in inclusions:\n if len(inclusions) > 1:\n answer = self.input(operation + \" \" + str(choice_name) + \"? (y/n)\")\n else:\n answer = 'y'\n \n if answer == 'y':\n choice = next(i for i in self.model.lists[list_name] if i.text == choice_name)\n if operation == 'include':\n self.model.lists[list_name].include(choice)\n else:\n self.model.lists[list_name].exclude(choice)\n \n \n def x(self):\n \"\"\"Command. Exclude items from consideration.\"\"\"\n self.i(exclude=True)\n \n def n(self):\n \"\"\"Command. Add something.\"\"\"\n type_ = self.input(\"list or choices?\")\n list_ = self.input(\"list name\")\n if type_ == \"list\":\n self.model.lists[list_] = ChoiceList()\n scale_values = self.input('scale values (optional)').split(', ')\n if scale_values:\n self.model.lists[list_].scale.values = scale_values\n for choice_text in self.input(\"choices\").split(\", \"):\n self.model.lists[list_].add(Choice(choice_text, self.model.lists[list_].scale))\n \n def s(self):\n \"\"\"Command. Sort a list.\"\"\"\n print(*sorted(self.model.lists[self.input('list name')]), sep=\"\\n\")\n \n def d(self):\n \"\"\"Command. Delete something.\"\"\"\n type_ = self.input(\"list or choices?\")\n if type_ == \"list\":\n del self.model.lists[self.input(\"name\")]\n elif type_ == \"choices\":\n choices = self.input(\"choices\").split(\", \")\n list_name = self.input(\"list\")\n for i in choices:\n self.model.lists[list_name].discard(i)\n else:\n raise RuntimeError(\"Unknown option.\")\n \n def p(self):\n \"\"\"Command. Show useful info\"\"\"\n for list_ in self.model.lists:\n pprint(vars(list_))\n \n def blargh(self):\n \"\"\"Command. For debug purposes only. Do not run!\"\"\"\n print(', '.join(str(i) for i in self.model.lists['activities']))\n \n def ss(self):\n \"\"\"Command. Set the rating scale for a list\"\"\"\n self.model.lists[self.input('list name')].scale.values = self.input('scale values').split(', ')\n \n def rn(self):\n \"\"\"Command. rename a choice.\"\"\"\n list_name = self.input('list name')\n choice_name = self.input('choice name')\n replacement_text = self.input('replacement text')\n for i in self.model.lists[list_name]:\n if i.text == choice_name:\n i.text = replacement_text\n","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"15693698","text":"# import cv2 as cv\nfrom inference import preprocessing, load_to_IE, sync_inference, async_inference, get_async_output, get_input_shape\nfrom imutils import face_utils\nimport dlib\nimport numpy as np\nfrom datetime import datetime, timedelta\nfrom time import sleep\nimport pygame\n\n\nmodel = \"face-detection-adas-0001/INT8/face-detection-adas-0001.xml\"\nimage_name = \"manish.jpg\"\n#image = cv.imread(image_name)\nheadpose_model = \"head-pose-estimation-adas-0001/head-pose-estimation-adas-0001.xml\"\ndlib_model = \"shape_predictor_68_face_landmarks.dat\"\n\t\n#shape of input\n\nn, c, h, w = get_input_shape(model)\nnn,cc,hh,ww = get_input_shape(headpose_model)\n\nexec_net = load_to_IE(model)\nexec_net_headpose = load_to_IE(headpose_model)\n\n#for dlib models\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(dlib_model)\n\n\t\n\ndef hisEqulColor(img):\n\thls=cv.cvtColor(img,cv.COLOR_BGR2HLS)\n\tchannels=cv.split(hls)\n\t# print(np.mean(channels[0]))\n\tif(np.mean(channels[1] ) < 127):\n\t\t# clahe = cv.createCLAHE(clipLimit=16.0,tileGridSize=(8,8))\n\t\t# channels[1] = clahe.apply(channels[1])\n\t\tcv.equalizeHist(channels[1],channels[1])\n\t\tcv.merge(channels,hls)\n\t\tcv.cvtColor(hls,cv.COLOR_HLS2BGR,img)\n\t\t# print(\"after equ \"+str(np.mean(cv.split(yuv)[0])))\n\t\n\treturn img\n\t\n\t\n\n\ndef main():\n\t\n\ttotal_count = 0\n\n\t#for sound\n\tpygame.mixer.init()\n\tpygame.mixer.set_num_channels(8)\n\tvoice = pygame.mixer.Channel(5)\n\n\tsound = pygame.mixer.Sound(\"warn.wav\")\n\n\t# if(cap.isOpened()==False):\n\t# \tprint(\"error while streaming\")\n\t#eye counters\n\ttime = datetime.now()\n\tone_min_start_time = time\n\teye_closed_counter = 0\n\teye_closed = False\n\teye_close_time = time\n\n\t#mouth counters\n\tmouth_open_time = time\n\tmouth_open = False\n\tyawn_count = 0\n\n\t#nod counter\n\tnod_time = time\n\tnodding = False\n\tnod_count = 0\n\n\tm_EAR_left, m_EAR_right = get_mEARS()\n\tcap = cv.VideoCapture(0)\n\twhile True:\n\t\t_, frame = cap.read()\n\t\t#for mirror image\n\t\tframe = cv.flip(frame, 1)\n\t\t#print(frame.shape)\n\n\t\tframe = hisEqulColor(frame)\n\t\t\n\t\t\n\t\t\n\t\t#cv.putText(frame,\"is doing\",(100,100),cv.FONT_HERSHEY_COMPLEX, 1, (255,255,255))\n\t\tpreprocessed_image = preprocessing(frame, h, w)\n\t\tresult = sync_inference(exec_net, image = preprocessed_image)\n\t\t#print(result.keys())\n\t\tresult = result['detection_out']\n\t\t#print(result)\n\t\t\n\t\t#setting bounding box color, image height and width\n\t\tcolor = (0,0,255)\n\t\theight = frame.shape[0]\n\t\twidth = frame.shape[1]\n\n\t\t#we get output blob as [1*1*N*7] that means result[0][0][i] will give result of i-th box.\n\t\t#Each box has 7 numbers (last digit(7) of the output blob). \n\t\t#3rd index numbered 2 gives the confidence\n\t\t#4th, 5th, 6th, 7th indices numbered 3,4,5,6 resp. give xmin, ymin, xmax, ymax\n\n\t\t#incase no face detected, crop will be unresolved variable\n\t\tcrop = frame[0:1, 0:1]\n\t\t#iterating over the detected boxes\n\t\tfor i in range(len(result[0][0])):\n\t\t\tbox = result[0][0][i]\t#result of i-th box\n\t\t\tconfidence = box[2]\n\t\t\tif confidence > 0.5:\n\t\t\t\txmin = int(box[3] * width)\n\t\t\t\tymin = int(box[4] * height)\n\t\t\t\txmax = int(box[5] * width)\n\t\t\t\tymax = int(box[6] * height)\n\t\t\t\t#print(str(xmin)+\", \"+str(ymin)+\", \"+str(xmax)+\", \"+str(ymax))\n\n\t\t\t\t#Drawing the box with image\n\t\t\t\tcv.rectangle(frame,(xmin,ymin),(xmax,ymax),color,1)\n\t\t\t\t#cv.putText(frame, str(i), (50,50),cv.FONT_HERSHEY_COMPLEX, 1, (255,255,255))\n\t\t\t\tif xmin<0:\n\t\t\t\t\txmin = 0\n\t\t\t\tif ymin<0:\n\t\t\t\t\tymin = 0\n\t\t\t\tcrop = frame[ymin-30: ymax+30, xmin-30:xmax+30]\n\n\t\t\n\n\t\tprocessed_crop = preprocessing(crop, hh, ww)\n\t\tnew_res = sync_inference(exec_net_headpose, image = processed_crop)\n\n\t\tyaw = new_res['angle_y_fc'][0]\n\t\tpitch = new_res['angle_p_fc'][0]\n\t\troll = new_res['angle_r_fc'][0]\n\n\t\t# cv.putText(frame,\"yaw: {}\".format(str(yaw)), (20,30),cv.FONT_HERSHEY_COMPLEX, 1, color,1)\n\t\t# cv.putText(frame,\"pitch: {}\".format(str(pitch)), (20,60),cv.FONT_HERSHEY_COMPLEX, 1, color,1)\n\t\t# cv.putText(frame,\"roll: {}\".format(str(roll)), (20,90),cv.FONT_HERSHEY_COMPLEX, 1, color,1)\n\n\t\tif pitch > -15 and pitch < 25:\n\t\t\tcv.putText(frame,\"straight face\", (20,60),cv.FONT_HERSHEY_COMPLEX, 1, color,1)\n\t\t\tnodding = False\n\n\n\t\telif pitch > 25:\n\t\t\tcv.putText(frame,\"facing downwards\", (20,60),cv.FONT_HERSHEY_COMPLEX, 1, color,1)\n\t\t\tif not nodding:\n\t\t\t\tnodding = True\n\t\t\t\tnod_time = time.now()\n\n\t\t\tif nodding:\n\t\t\t\tif datetime.now() - nod_time >= timedelta(seconds = 2):\n\t\t\t\t\tnod_count += 1\n\t\t\t\t\tprint(\"nod count= \"+ str(nod_count))\n\t\t\t\t\tnod_time = time.now()\n\t\t\t\t\tif voice.get_busy() == 0:\n\t\t\t\t\t\tvoice.play(sound)\n\n\n\t\telif pitch < -15:\n\t\t\tcv.putText(frame,\"facing upwards\", (20,60),cv.FONT_HERSHEY_COMPLEX, 1, color,1)\n\t\t\tnodding = False\n\t\t\n\n\t\t#feed frame face to dlib\n\t\t# print(crop.shape)\n\t\t\n\t\tcrop_dlib = cv.resize(crop, (300,300))\n\t\tgray = cv.cvtColor(crop_dlib, cv.COLOR_BGR2GRAY)\n\t\tclahe = cv.createCLAHE(clipLimit=2.0,tileGridSize=(8,8))\n\t\tgray = clahe.apply(gray)\n\t\t \n\t\trects = detector(gray,0)\n\t\tfor (i, rect) in enumerate(rects):\n\t\t\txmin = rect.left()\n\t\t\tymin = rect.top()\n\t\t\txmax = rect.right()\n\t\t\tymax = rect.bottom()\n\n\t\t\tcv.rectangle(gray,(xmin,ymin),(xmax,ymax),color,1)\n\t\t\tshape = predictor(gray, rect)\n\t\t\tshape = face_utils.shape_to_np(shape)\n\n\t\t\t#EAR\n\n\t\t\tear_l = ((shape[41][1]-shape[37][1]) + (shape[40][1]-shape[38][1]))/(2*(shape[39][0]-shape[36][0]))\n\t\t\n\n\t\t\tear_r = ((shape[47][1]-shape[43][1]) + (shape[46][1]-shape[44][1]))/(2*(shape[45][0]-shape[42][0]))\n\n\t\t\t\n\n\t\t\tif(ear_l < m_EAR_left and ear_r < m_EAR_right):\n\t\t\t\tcv.putText(frame, \"closed\", (100,80),cv.FONT_HERSHEY_COMPLEX, 1, (255,255,255))\n\n\t\t\t\t#if eye closed for first frame set the eye close time(eye was not closed in last frame)\n\t\t\t\tif not eye_closed:\n\t\t\t\t\teye_close_time = datetime.now()\n\n\t\t\t\t#if eye closed for more than 2 sec straight\n\t\t\t\tif eye_closed and (datetime.now() - eye_close_time >= timedelta(seconds = 2)):\n\t\t\t\t\tif voice.get_busy() == 0:\n\t\t\t\t\t\tvoice.play(sound) \n\t\t\t\t\t\n\t\t\t\teye_closed = True\n\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tcv.putText(frame, \"open\", (100,80),cv.FONT_HERSHEY_COMPLEX, 1, (255,255,255))\n\n\t\t\t\t#previous frame was eye closed and now eye opened, increase counter\n\t\t\t\tif eye_closed:\n\t\t\t\t\teye_closed_counter += 1\n\t\t\t\t\tprint(\"eye_closed_counter = \"+ str(eye_closed_counter))\n\t\t\t\teye_closed = False\n\n\n\t\t\t#mouth ratio\n\n\t\t\tmouth_ratio = ((shape[58][1] - shape[50][1]) + (shape[56][1] - shape[52][1])) / (2*(shape[54][0] - shape[48][0]))\n\n\t\t\tfor (x,y) in shape:\n\t\t\t\tcv.circle(gray, (x,y), 2, color, -1)\n\n\t\t\tif(mouth_ratio>0.35):\n\t\t\t\tcv.putText(frame,\"Mouth open\", (20,90),cv.FONT_HERSHEY_COMPLEX, 1, color, 1)\n\t\t\t\t#if previous frame was closed, then first frame to open mouth note time\n\t\t\t\tif not mouth_open:\n\t\t\t\t\tmouth_open_time = datetime.now()\n\t\t\t\t\tmouth_open = True\n\t\t\t\t\t#print(mouth_open_time)\n\t\t\t\t#check if more than 4.5 sec opened\n\t\t\t\tif mouth_open and (datetime.now() - mouth_open_time > timedelta(seconds = 4.5)):\n\t\t\t\t\tprint(datetime.now() - mouth_open_time)\n\t\t\t\t\tmouth_open_time = datetime.now()\n\t\t\t\t\tyawn_count += 1\n\t\t\t\t\tprint(\"yawn count= \"+ str(yawn_count))\n\t\t\t\t\tif voice.get_busy() == 0:\n\t\t\t\t\t\tvoice.play(sound)\n\n\t\t\telse:\n\t\t\t\tcv.putText(frame,\"Mouth close\", (20,90),cv.FONT_HERSHEY_COMPLEX, 1, color, 1)\n\t\t\t\tif mouth_open:\n\t\t\t\t\tmouth_open = False\n\n\t\t#check 1 min timer:\n\t\tif(datetime.now() - one_min_start_time >= timedelta(minutes = 1)):\n\t\t\t\n\t\t\tif eye_closed_counter > 25 or eye_closed_counter < 10:\n\t\t\t\ttotal_count += 1\n\t\t\t\tif(voice.get_busy() == 0):\n\t\t\t\t\tvoice.play(sound)\n\n\n\t\t\ttotal_count += yawn_count + nod_count\n\t\t\tprint(\"drowsy_count = \"+ str(total_count))\n\t\t\tprint(\"total eye_closed_counter= \"+ str(eye_closed_counter))\n\t\t\tprint(\"total yawn = \" + str(yawn_count))\n\t\t\tprint(\"total nod_count = \" + str(nod_count))\n\n\t\t\tif total_count >= 3:\n\t\t\t\tvoice.play(sound)\n\n\n\t\t\tone_min_start_time = datetime.now()\n\t\t\tprint(eye_closed_counter)\n\t\t\tyawn_count = 0\n\t\t\teye_closed_counter = 0\n\t\t\tnod_count = 0\n\n\t\tcv.imshow(\"Face detection\", frame)\n\t\tcv.imshow(\"Cropped face\", gray)\n\t\t\n\t\t#to stop\n\t\tinterrupt = cv.waitKey(10)\n\t\tif interrupt & 0xFF == 27:\n\t\t\tbreak\n\tcap.release()\n\tcv.destroyAllWindows()\n\n\n\ndef output_processing(result, image, threshold = 0.5):\n\t#setting bounding box color, image height and width\n\tcolor = (0,0,255)\n\theight = image.shape[0]\n\twidth = image.shape[1]\n\n\t#we get output blob as [1*1*N*7] that means result[0][0][i] will give result of i-th box.\n\t#Each box has 7 numbers (last digit(7) of the output blob). \n\t#3rd index numbered 2 gives the confidence\n\t#4th, 5th, 6th, 7th indices numbered 3,4,5,6 resp. give xmin, ymin, xmax, ymax\n\n\t#iterating over the detected boxes\n\tfor i in range(len(result[0][0])):\n\t\tbox = result[0][0][i]\t#result of i-th box\n\t\tconfidence = box[2]\n\t\tif confidence > threshold:\n\t\t\txmin = int(box[3] * width)\n\t\t\tymin = int(box[4] * height)\n\t\t\txmax = int(box[5] * width)\n\t\t\tymax = int(box[6] * height)\n\n\t\t\t#Drawing the box with image\n\t\t\tcv.rectangle(image,(xmin,ymin),(xmax,ymax),color,1)\n\n\treturn image\n\n\ndef get_mEARS():\n\tcap = cv.VideoCapture(0)\n\tstart_time = datetime.now()\n\n\tl_Amin = 100\n\tl_Amax = 0\n\tl_Bmin = 100\n\tl_Bmax = 0\n\tl_Cmin = 100\n\tl_Cmax = 0\n\tr_Amin = 100\n\tr_Amax = 0\n\tr_Bmin = 100\n\tr_Bmax = 0\n\tr_Cmin = 100\n\tr_Cmax = 0\n\n\twhile True:\n\t\t_, frame = cap.read()\n\t\t#for mirror image\n\t\tframe = cv.flip(frame, 1)\n\t\t\n\t\t\n\t\tpreprocessed_image = preprocessing(frame, h, w)\n\t\tresult = sync_inference(exec_net, image = preprocessed_image)\n\t\t\n\t\tresult = result['detection_out']\n\t\t\n\t\t\n\t\t#setting bounding box color, image height and width\n\t\tcolor = (0,0,255)\n\t\theight = frame.shape[0]\n\t\twidth = frame.shape[1]\n\n\t\tcrop = frame[0:1, 0:1]\n\t\t#iterating over the detected boxes\n\t\tfor i in range(len(result[0][0])):\n\t\t\tbox = result[0][0][i]\t#result of i-th box\n\t\t\tconfidence = box[2]\n\t\t\tif confidence > 0.5:\n\t\t\t\txmin = int(box[3] * width)\n\t\t\t\tymin = int(box[4] * height)\n\t\t\t\txmax = int(box[5] * width)\n\t\t\t\tymax = int(box[6] * height)\n\t\t\t\t#print(str(xmin)+\", \"+str(ymin)+\", \"+str(xmax)+\", \"+str(ymax))\n\n\t\t\t\t#Drawing the box with image\n\t\t\t\tcv.rectangle(frame,(xmin,ymin),(xmax,ymax),color,1)\n\t\t\t\t#cv.putText(frame, str(i), (50,50),cv.FONT_HERSHEY_COMPLEX, 1, (255,255,255))\n\t\t\t\tif xmin<0:\n\t\t\t\t\txmin = 0\n\t\t\t\tif ymin<0:\n\t\t\t\t\tymin = 0\n\t\t\t\tcrop = frame[ymin-0:ymax+30, xmin-30:xmax+30]\n\t\t\t\t\n\n\n\t\t\n\n\t\t#feed frame face to dlib\n\t\t# print(crop.shape)\n\t\tcrop_dlib = cv.resize(crop, (300,300))\n\t\tgray = cv.cvtColor(crop_dlib, cv.COLOR_BGR2GRAY)\n\t\tclahe = cv.createCLAHE(clipLimit=2.0,tileGridSize=(8,8))\n\t\tgray = clahe.apply(gray)\n\t\t \n\t\trects = detector(gray,0)\n\t\tfor (i, rect) in enumerate(rects):\n\t\t\txmin = rect.left()\n\t\t\tymin = rect.top()\n\t\t\txmax = rect.right()\n\t\t\tymax = rect.bottom()\n\n\t\t\tcv.rectangle(gray,(xmin,ymin),(xmax,ymax),color,1)\n\t\t\tshape = predictor(gray, rect)\n\t\t\tshape = face_utils.shape_to_np(shape)\n\n\t\t\t#EAR\n\n\t\t\tear_l = ((shape[41][1]-shape[37][1]) + (shape[40][1]-shape[38][1]))/(2*(shape[39][0]-shape[36][0]))\n\t\t\n\n\t\t\tear_r = ((shape[47][1]-shape[43][1]) + (shape[46][1]-shape[44][1]))/(2*(shape[45][0]-shape[42][0]))\n\n\t\t\t\n\t\t\tleft_A = shape[41][1]-shape[37][1]\n\t\t\n\t\t\tleft_B = shape[40][1]-shape[38][1]\n\t\t\t\n\t\t\tleft_C = shape[39][0]-shape[36][0]\n\t\t\t\n\t\t\tright_A = shape[47][1]-shape[43][1]\n\t\t\t\n\t\t\tright_B = shape[46][1]-shape[44][1]\n\t\t\t\n\t\t\tright_C = shape[45][0]-shape[42][0]\n\n\t\t\t#left\n\t\t\t# print(left_A)\n\t\t\t# print(l_Amin)\n\t\t\tif(left_A < l_Amin):\n\t\t\t\tl_Amin = left_A\n\n\n\t\t\tif(left_A > l_Amax):\n\t\t\t\tl_Amax = left_A\n\n\t\t\tif(left_B < l_Bmin):\n\t\t\t\tl_Bmin = left_B\n\n\t\t\tif(left_B > l_Bmax):\n\t\t\t\tl_Bmax = left_B\n\n\t\t\tif(left_C < l_Cmin):\n\t\t\t\tl_Cmin = left_C\n\n\t\t\tif(left_C > l_Cmax):\n\t\t\t\tl_Cmax = left_C\n\n\t\t\t#right\n\t\t\tif(right_A < r_Amin):\n\t\t\t\tr_Amin = right_A\n\n\t\t\tif(right_A > r_Amax):\n\t\t\t\tr_Amax = right_A\n\n\t\t\tif(right_B < r_Bmin):\n\t\t\t\tr_Bmin = right_B\n\n\t\t\tif(right_B > r_Bmax):\n\t\t\t\tr_Bmax = right_B\n\n\t\t\tif(right_C < r_Cmin):\n\t\t\t\tr_Cmin = right_C\n\n\t\t\tif(right_C > r_Cmax):\n\t\t\t\tr_Cmax = right_C\n\n\n\n\t\t\tcv.putText(frame, \"l_Amin\\tl_Amax\\tl_Bmin\\tl_Bmax\\tl_Cmin\\tl_Cmax\", (100,50),cv.FONT_HERSHEY_COMPLEX, 0.5, (255,255,255))\n\t\t\tcv.putText(frame, str(l_Amin)+\"\\t\"+str(l_Amax)+\"\\t\"+str(l_Bmin)+\"\\t\"+str(l_Bmax)+\"\\t\"\n\t\t\t\t+str(l_Cmin)+\"\\t\"+str(l_Cmax), (100,65),cv.FONT_HERSHEY_COMPLEX, 0.5, (255,255,255))\n\n\t\t\tear_close_left = (l_Amin + l_Bmin) / (2 * l_Cmax)\n\t\t\tear_open_left = (l_Amax + l_Bmax) / (2 * l_Cmin)\n\t\t\tm_EAR_left = (ear_open_left - ear_close_left) / 2\n\n\t\t\tear_close_right = (r_Amin + r_Bmin) / (2 * r_Cmax)\n\t\t\tear_open_right = (r_Amax + r_Bmax) / (2 * r_Cmin)\n\t\t\tm_EAR_right = (ear_open_right - ear_close_right) / 2\n\n\t\t\tif(ear_l < m_EAR_left and ear_r < m_EAR_right):\n\t\t\t\tcv.putText(frame, \"closed\", (100,80),cv.FONT_HERSHEY_COMPLEX, 1, (255,255,255))\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tcv.putText(frame, \"open\", (100,80),cv.FONT_HERSHEY_COMPLEX, 1, (255,255,255))\n\n\n\t\t\tfor (x,y) in shape:\n\t\t\t\tcv.circle(gray, (x,y), 2, color, -1)\n\n\n\t\t#cv.imshow(\"Face detection\", frame)\n\t\tcv.imshow(\"Cropped face\", gray)\n\n\t\t\n\t\t#to stop\n\t\tinterrupt = cv.waitKey(10)\n\t\tif interrupt & 0xFF == 27:\n\t\t\tbreak\n\t\tif(datetime.now() - start_time > timedelta(seconds=10)):\n\t\t\tbreak\n\tcap.release()\n\tcv.destroyAllWindows()\n\tprint(m_EAR_left)\n\tprint(m_EAR_right)\n\treturn m_EAR_left, m_EAR_right\n\n\nif __name__ == '__main__':\n\t\n\t\n\tmain()\n\t\n\t\n\t","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"263950491","text":"import urllib2\r\nimport json\r\n\r\nfrom pymongo import MongoClient\r\n\r\n# Create a MongoDB Connection\r\nclient = MongoClient('mongodb://localhost:27017/')\r\n\r\n# Connect to the Database and it's collection\r\ndb = client.project.stocks\r\n\r\nfileOpen = open('company.txt')\r\n## Read the first line\r\nline = fileOpen.readline()\r\n\r\n\r\nwhile line:\r\n print(line.rstrip())\r\n companyName = 'https://api.stocktwits.com/api/2/streams/symbol/'+line.rstrip()+'.json'\r\n print(companyName)\r\n response = urllib2.urlopen(companyName)\r\n data = json.load(response)\r\n db.insert(data)\r\n line = fileOpen.readline()\r\n\r\nfileOpen.close()\r\n\r\nresults = db.find()\r\n\r\nprint()\r\nprint('+-+-+-+-+-+-+-+-+-+-+-+-+-+-')\r\nfor record in results:\r\n print(record['symbol']['symbol'])\r\n\r\nprint()\r\n\r\nclient.close()\r\n\r\n","sub_path":"stock_sentiments.py","file_name":"stock_sentiments.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615535919","text":"import matplotlib.pyplot as plt\nimport networkx as nx\n# import matplotlib as mpl\n# print(mpl.matplotlib_fname())\n# import matplotlib.font_manager\n# print(matplotlib.font_manager.findSystemFonts(fontpaths=None,fontext=\"ttf\"))\n# print([f.name for f in matplotlib.font_manager.fontManager.ttflist])\n\nG = nx.DiGraph()\n#G = nx.Graph()\n# G.add_nodes_from([\"NO(g)\",\"NO*\",\"N*\",\"N2*\",\"O*\",\"CO(g)\",\"CO*\",\"CO2*\",\"CO2(g)\",\"N2O*\",\"N2O(g)\"],color=\"gray\")\n# G.add_nodes_from([\"N2(g)\",\"O*\",\"CO(g)\",\"CO*\",\"CO2*\",\"CO2(g)\",\"N2O*\",\"N2O(g)\"],color=\"gray\")\n\nc_siz=100; c_col=\"gray\"\nr_siz=10; r_col=\"black\"\n\nG.add_node(\"O2\", size=c_siz, color=c_col) ; G.add_node(\"O*\", size=c_siz, color=c_col)\nG.add_node(\"O2-dis-ads\",size=r_siz,color=r_col)\nG.add_edge(\"O2\",\"O2-dis-ads\") ; G.add_edge(\"O2-dis-ads\",\"O*\")\n\nG.add_node(\"CH4\",size=c_siz, color=c_col)\nG.add_node(\"CH4-CHdiss\", size=r_siz, color=r_col)\nG.add_edge(\"CH4\",\"CH4-CHdiss\") ; G.add_edge(\"CH4-CHdiss\",\"CH3\")\nG.add_edge(\"O2\", \"CH4-CHdiss\") ; G.add_edge(\"CH4-CHdiss\",\"O2H\") \nG.add_edge(\"O*\", \"CH4-CHdiss\") ; G.add_edge(\"CH4-CHdiss\",\"OH*\") \nG.add_node(\"O2\", size=c_siz, color=c_col)\nG.add_node(\"CH3\",size=c_siz, color=c_col)\nG.add_node(\"O2H\",size=c_siz, color=c_col)\nG.add_node(\"OH*\",size=c_siz, color=c_col)\n\nG.add_node(\"CH3-COform\", size=r_siz, color=r_col)\nG.add_edge(\"CH3\",\"CH3-COform\") ; G.add_edge(\"CH3-COform\",\"CH3O\") \nG.add_edge(\"O2\", \"CH3-COform\")\nG.add_edge(\"O*\", \"CH3-COform\") \nG.add_node(\"CH3O\",size=c_siz, color=c_col)\n\nG.add_node(\"CH3-CHdiss\", size=r_siz, color=r_col)\nG.add_edge(\"CH3O\",\"CH3-CHdiss\") ; G.add_edge(\"CH3-CHdiss\",\"CH2O\") \nG.add_edge(\"O2\", \"CH3-CHdiss\") ; G.add_edge(\"CH3-CHdiss\",\"O2H\") \nG.add_edge(\"O*\", \"CH3-CHdiss\") ; G.add_edge(\"CH3-CHdiss\",\"OH*\") \nG.add_node(\"CH2O\",size=c_siz, color=c_col)\n\nG.add_node(\"CH2-CHdiss\", size=r_siz, color=r_col)\nG.add_edge(\"CH2O\",\"CH2-CHdiss\") ; G.add_edge(\"CH2-CHdiss\",\"CHO\") \nG.add_edge(\"O2\", \"CH2-CHdiss\") ; G.add_edge(\"CH2-CHdiss\",\"O2H\") \nG.add_edge(\"O*\", \"CH2-CHdiss\") ; G.add_edge(\"CH2-CHdiss\",\"OH*\") \nG.add_node(\"CHO\",size=c_siz, color=c_col)\n\nG.add_node(\"CH-CHdiss\", size=r_siz, color=r_col)\nG.add_edge(\"CHO\",\"CH-CHdiss\") ; G.add_edge(\"CH-CHdiss\",\"CO\") \nG.add_edge(\"O2\", \"CH-CHdiss\") ; G.add_edge(\"CH-CHdiss\",\"O2H\") \nG.add_edge(\"O*\", \"CH-CHdiss\") ; G.add_edge(\"CH-CHdiss\",\"OH*\") \nG.add_node(\"CO\",size=c_siz, color=c_col)\n\nG.add_node(\"CO-COform\", size=r_siz, color=r_col)\nG.add_edge(\"CO\",\"CO-COform\") ; G.add_edge(\"CO-COform\",\"CO2\") \nG.add_edge(\"O2\",\"CO-COform\") ; G.add_edge(\"CO-COform\",\"O2H\") \nG.add_edge(\"O*\",\"CO-COform\") ; G.add_edge(\"CO-COform\",\"OH*\") \nG.add_node(\"CO2\",size=c_siz, color=c_col)\n\nedges = G.edges()\n# weights = [G[u][v]['weight'] for u,v in edges]\n\nplt.figure(num=None,figsize=(4,4),dpi=140)\n\n#pos = nx.spring_layout(G)\npos = nx.nx_pydot.graphviz_layout(G,prog=\"dot\")\n# nx.draw(G,pos,with_labels=False,arrows=False)\n# nx.draw(G,pos,edges=edges, width=weights)\n\n# print(G.nodes())\n# print(siz)\n# quit()\n\nsiz = nx.get_node_attributes(G,\"size\")\ncol = nx.get_node_attributes(G,\"color\")\nnx.draw_networkx_nodes(G, pos, nodelist=siz.keys(), node_size=siz.values(),node_color=col.values())\nnx.draw_networkx_edges(G, pos)\nnx.draw_networkx_labels(G,pos,font_size=10,font_family=\"Gill Sans MT\")\n\nplt.xticks([])\nplt.yticks([])\nplt.savefig(\"test.eps\",format=\"eps\")\nplt.show()\n","sub_path":"example_ch4.py","file_name":"example_ch4.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"491000090","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom flask import Flask, render_template\nfrom flask_bootstrap import Bootstrap\nfrom os import path\n\n\napp = Flask(__name__)\napp.jinja_env.auto_reload = True\napp.config.update(dict(\n SECRET_KEY='development_key',\n TEMPLATES_AUTO_RELOAD=True,\n SEND_FILE_MAX_AGE_DEFAULT=0,\n JSON_AS_ASCII=False\n))\nBootstrap(app)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html', message='Hello World!', content_id_name='js', js_file='js/index_bundle.js')\n","sub_path":"{{cookiecutter.package_name}}/backend/{{cookiecutter.package_name}}/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"648583420","text":"import sqlite3\nimport sys, os, re\nimport glob\nimport datetime\nfrom scripts.parse3 import ParseProto\nimport codecs\nimport json\nimport sqlite3\nimport io\nimport sys\nimport csv\nimport pathlib\nimport shutil\nimport textwrap\nimport base64\nfrom time import process_time\nfrom bs4 import BeautifulSoup\nimport xml.etree.ElementTree as ET \nimport scripts.usagestatsservice_pb2 as usagestatsservice_pb2\nfrom enum import IntEnum\n\n\nnl = '\\n' \nnow = datetime.datetime.now()\ncurrenttime = str(now.strftime('%Y-%m-%d_%A_%H%M%S'))\nreportfolderbase = './ALEAPP_Reports_'+currenttime+'/'\nbase = '/ALEAPP_Reports_'+currenttime+'/'\ntemp = reportfolderbase+'temp/'\n\ndef logfunc(message=\"\"):\n\tif pathlib.Path(reportfolderbase+'Script Logs/Screen Output.html').is_file():\n\t\twith open(reportfolderbase+'Script Logs/Screen Output.html', 'a', encoding='utf8') as a:\n\t\t\tprint(message)\n\t\t\ta.write(message+'
')\n\telse:\n\t\twith open(reportfolderbase+'Script Logs/Screen Output.html', 'a', encoding='utf8') as a:\n\t\t\tprint(message)\n\t\t\ta.write(message+'
')\n\ndef usagestats(filefound):\n\tlogfunc('UsageStats function executing')\n\t\n\tclass EventType(IntEnum):\n\t NONE = 0\n\t MOVE_TO_FOREGROUND = 1\n\t MOVE_TO_BACKGROUND = 2\n\t END_OF_DAY = 3\n\t CONTINUE_PREVIOUS_DAY = 4\n\t CONFIGURATION_CHANGE = 5\n\t SYSTEM_INTERACTION = 6\n\t USER_INTERACTION = 7\n\t SHORTCUT_INVOCATION = 8\n\t CHOOSER_ACTION = 9\n\t NOTIFICATION_SEEN = 10\n\t STANDBY_BUCKET_CHANGED = 11\n\t NOTIFICATION_INTERRUPTION = 12\n\t SLICE_PINNED_PRIV = 13\n\t SLICE_PINNED = 14\n\t SCREEN_INTERACTIVE = 15\n\t SCREEN_NON_INTERACTIVE = 16\n\t KEYGUARD_SHOWN = 17\n\t KEYGUARD_HIDDEN = 18\n\n\t def __str__(self):\n\t return self.name # This returns 'KNOWN' instead of 'EventType.KNOWN'\n\n\tclass EventFlag(IntEnum):\n\t FLAG_IS_PACKAGE_INSTANT_APP = 1\n\t \n\t def __str__(self):\n\t return self.name\n\n\tdef ReadUsageStatsPbFile(input_path):\n\t\t'''Opens file, reads usagestats protobuf and returns IntervalStatsProto object'''\n\t\tstats = usagestatsservice_pb2.IntervalStatsProto()\n\n\t\twith open (input_path, 'rb') as f:\n\t\t\tstats.ParseFromString(f.read())\n\t\t\t#print(stats)\n\t\t\treturn stats\n\n\tdef AddEntriesToDb(stats, db):\n\t\tcursor = db.cursor()\n\t\t# packages\n\t\tfor usagestat in stats.packages:\n\t\t\tfinalt = ''\n\t\t\tif usagestat.HasField('last_time_active_ms'):\n\t\t\t\tfinalt = usagestat.last_time_active_ms\n\t\t\t\tif finalt < 0:\n\t\t\t\t\tfinalt = abs(finalt)\n\t\t\t\telse:\n\t\t\t\t\tfinalt += file_name_int\n\t\t\ttac = ''\n\t\t\tif usagestat.HasField('total_time_active_ms'):\n\t\t\t\ttac = abs(usagestat.total_time_active_ms)\n\t\t\tpkg = stats.stringpool.strings[usagestat.package_index - 1]\n\t\t\talc = ''\n\t\t\tif usagestat.HasField('app_launch_count'):\n\t\t\t\talc = abs(usagestat.app_launch_count)\n\n\t\t\tdatainsert = ('packages', finalt, tac, '', '', '', alc, pkg, '' , '' , sourced, '')\n\t\t\t#print(datainsert)\n\t\t\tcursor.execute('INSERT INTO data (usage_type, lastime, timeactive, last_time_service_used, last_time_visible, total_time_visible, '\n\t\t\t\t\t\t\t'app_launch_count, package, types, classs, source, fullatt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)', datainsert)\n\t\t#configurations\n\t\tfor conf in stats.configurations:\n\t\t\tusagetype = 'configurations'\n\t\t\tfinalt = ''\n\t\t\tif usagestat.HasField('last_time_active_ms'):\n\t\t\t\tfinalt = usagestat.last_time_active_ms\n\t\t\t\tif finalt < 0:\n\t\t\t\t\tfinalt = abs(finalt)\n\t\t\t\telse:\n\t\t\t\t\tfinalt += file_name_int\n\t\t\ttac = ''\n\t\t\tif usagestat.HasField('total_time_active_ms'):\n\t\t\t\ttac = abs(usagestat.total_time_active_ms)\n\t\t\tfullatti_str = str(conf.config)\n\t\t\tdatainsert = (usagetype, finalt, tac, '', '', '', '', '', '', '', sourced, fullatti_str)\n\t\t\t#print(datainsert)\n\t\t\tcursor.execute('INSERT INTO data (usage_type, lastime, timeactive, last_time_service_used, last_time_visible, total_time_visible, '\n\t\t\t\t\t\t\t'app_launch_count, package, types, classs, source, fullatt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)', datainsert)\t\t\t\t\t\t\t\n\t\t#event-log\n\t\tusagetype = 'event-log'\n\t\tfor event in stats.event_log:\n\t\t\tpkg = ''\n\t\t\tclassy = ''\n\t\t\ttipes = ''\n\t\t\tfinalt = ''\n\t\t\tif event.HasField('time_ms'):\n\t\t\t\tfinalt = event.time_ms\n\t\t\t\tif finalt < 0:\n\t\t\t\t\tfinalt = abs(finalt)\n\t\t\t\telse:\n\t\t\t\t\tfinalt += file_name_int\n\t\t\tif event.HasField('package_index'):\n\t\t\t\tpkg = stats.stringpool.strings[event.package_index - 1]\n\t\t\tif event.HasField('class_index'):\n\t\t\t\tclassy = stats.stringpool.strings[event.class_index - 1]\n\t\t\tif event.HasField('type'):\n\t\t\t\ttipes = str(EventType(event.type)) if event.type <= 18 else str(event.type)\n\t\t\tdatainsert = (usagetype, finalt, '' , '' , '' , '' ,'' , pkg , tipes , classy , sourced, '')\n\t\t\tcursor.execute('INSERT INTO data (usage_type, lastime, timeactive, last_time_service_used, last_time_visible, total_time_visible, '\n\t\t\t\t\t\t'app_launch_count, package, types, classs, source, fullatt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)', datainsert)\n\n\t\tdb.commit()\n\n\t### MAIN PROGRAM ###\n\tprocessed = 0\n\n\ttry:\n\t\tif os.path.isdir(reportfolderbase+'UsageStats/'):\n\t\t\tpass\n\t\telse:\n\t\t\tos.makedirs(reportfolderbase+'UsageStats/')\n\texcept:\n\t\tlogfunc('Error creating UsageStats() report directory')\n\n\t#Create sqlite databases\n\tdb = sqlite3.connect(reportfolderbase+'UsageStats/usagestats.db')\n\tcursor = db.cursor()\n\n\t#Create table usagedata.\n\n\tcursor.execute('''\n\n\t CREATE TABLE data(usage_type TEXT, lastime INTEGER, timeactive INTEGER,\n\t\t\t\t\t\t last_time_service_used INTEGER, last_time_visible INTEGER, total_time_visible INTEGER,\n\t\t\t\t\t\t app_launch_count INTEGER,\n\t\t\t\t\t\t package TEXT, types TEXT, classs TEXT,\n\t\t\t\t\t\t source TEXT, fullatt TEXT)\n\n\t''')\n\n\tdb.commit()\n\n\terr=0\n\tstats = None\n\n\n\tlogfunc ('Android Usagestats XML & Potobuf Parser')\n\tlogfunc ('By: @AlexisBrignoni & @SwiftForensics')\n\tlogfunc ('Web: abrignoni.com & swiftforensics.com')\n\n\t#script_dir = os.path.dirname(__file__)\n\tsplitfilefound, tail = filefound[0].split('/usagestats/')\n\tfor filename in glob.iglob(str(splitfilefound)+'/usagestats/**', recursive=True):\n\t\tif os.path.isfile(filename): # filter dirs\n\t\t\tfile_name = os.path.basename(filename)\n\t\t\t#Test if xml is well formed\n\t\t\tif file_name == 'version':\n\t\t\t\tcontinue\t\n\t\t\telse:\n\t\t\t\tif 'daily' in filename:\n\t\t\t\t\tsourced = 'daily'\n\t\t\t\telif 'weekly' in filename:\n\t\t\t\t\tsourced = 'weekly'\n\t\t\t\telif 'monthly' in filename:\n\t\t\t\t\tsourced = 'monthly'\n\t\t\t\telif 'yearly' in filename:\n\t\t\t\t\tsourced = 'yearly'\n\t\t\t\t\n\t\t\t\ttry:\n\t\t\t\t\tfile_name_int = int(file_name)\n\t\t\t\texcept: \n\t\t\t\t\tlogfunc('Invalid filename: ')\n\t\t\t\t\tlogfunc(filename)\n\t\t\t\t\tlogfunc('')\n\t\t\t\t\terr = 1\n\t\t\t\t\n\t\t\t\ttry:\n\t\t\t\t\tET.parse(filename)\n\t\t\t\texcept ET.ParseError:\n\t\t\t\t\t# Perhaps an Android Q protobuf file\n\t\t\t\t\ttry:\n\t\t\t\t\t\tstats = ReadUsageStatsPbFile(filename)\n\t\t\t\t\t\terr = 0\n\t\t\t\t\texcept:\n\t\t\t\t\t\tlogfunc('Parse error - Non XML and Non Protobuf file? at: ')\n\t\t\t\t\t\tlogfunc(filename)\n\t\t\t\t\t\tlogfunc('')\n\t\t\t\t\t\terr = 1\n\t\t\t\t\t\t#print(filename)\n\t\t\t\t\tif stats:\n\t\t\t\t\t\t#print('Processing - '+filename)\n\t\t\t\t\t\t#print('')\n\t\t\t\t\t\tAddEntriesToDb(stats, db)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\tif err == 1:\n\t\t\t\t\terr = 0\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\ttree = ET.parse(filename)\n\t\t\t\t\troot = tree.getroot()\n\t\t\t\t\tprint('Processing: '+filename)\n\t\t\t\t\tprint('')\n\t\t\t\t\tfor elem in root:\n\t\t\t\t\t\t#print(elem.tag)\n\t\t\t\t\t\tusagetype = elem.tag\n\t\t\t\t\t\t#print(\"Usage type: \"+usagetype)\n\t\t\t\t\t\tif usagetype == 'packages':\n\t\t\t\t\t\t\tfor subelem in elem:\n\t\t\t\t\t\t\t\t#print(subelem.attrib)\n\t\t\t\t\t\t\t\tfullatti_str = json.dumps(subelem.attrib)\n\t\t\t\t\t\t\t\t#print(subelem.attrib['lastTimeActive'])\n\t\t\t\t\t\t\t\ttime1 = subelem.attrib['lastTimeActive']\n\t\t\t\t\t\t\t\ttime1 = int(time1)\n\t\t\t\t\t\t\t\tif time1 < 0:\n\t\t\t\t\t\t\t\t\tfinalt = abs(time1)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tfinalt = file_name_int + time1\n\t\t\t\t\t\t\t\t#print('final time: ')\n\t\t\t\t\t\t\t\t#print(finalt)\n\t\t\t\t\t\t\t\t#print(subelem.attrib['package'])\n\t\t\t\t\t\t\t\tpkg = (subelem.attrib['package'])\n\t\t\t\t\t\t\t\t#print(subelem.attrib['timeActive'])\n\t\t\t\t\t\t\t\ttac = (subelem.attrib['timeActive'])\n\t\t\t\t\t\t\t\t#print(subelem.attrib['lastEvent'])\n\t\t\t\t\t\t\t\talc = (subelem.attrib.get('appLaunchCount', ''))\n\t\t\t\t\t\t\t\t#insert in database\n\t\t\t\t\t\t\t\tcursor = db.cursor()\n\t\t\t\t\t\t\t\tdatainsert = (usagetype, finalt, tac, '', '', '', alc, pkg, '', '', sourced, fullatti_str,)\n\t\t\t\t\t\t\t\t#print(datainsert)\n\t\t\t\t\t\t\t\tcursor.execute('INSERT INTO data (usage_type, lastime, timeactive, last_time_service_used, last_time_visible, total_time_visible, '\n\t\t\t\t\t\t\t\t\t\t\t 'app_launch_count, package, types, classs, source, fullatt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)', datainsert)\n\t\t\t\t\t\t\t\tdb.commit()\n\t\t\t\t\t\t\n\t\t\t\t\t\telif usagetype == 'configurations':\n\t\t\t\t\t\t\tfor subelem in elem:\n\t\t\t\t\t\t\t\tfullatti_str = json.dumps(subelem.attrib)\n\t\t\t\t\t\t\t\t#print(subelem.attrib['lastTimeActive'])\n\t\t\t\t\t\t\t\ttime1 = subelem.attrib['lastTimeActive']\n\t\t\t\t\t\t\t\ttime1 = int(time1)\n\t\t\t\t\t\t\t\tif time1 < 0:\n\t\t\t\t\t\t\t\t\tfinalt = abs(time1)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tfinalt = file_name_int + time1\n\t\t\t\t\t\t\t\t#print('final time: ')\n\t\t\t\t\t\t\t\t#print(finalt)\n\t\t\t\t\t\t\t\t#print(subelem.attrib['timeActive'])\n\t\t\t\t\t\t\t\ttac = (subelem.attrib['timeActive'])\n\t\t\t\t\t\t\t\t#print(subelem.attrib)\n\t\t\t\t\t\t\t\t#insert in database\n\t\t\t\t\t\t\t\tcursor = db.cursor()\n\t\t\t\t\t\t\t\tdatainsert = (usagetype, finalt, tac, '', '', '', '', '', '', '', sourced, fullatti_str,)\n\t\t\t\t\t\t\t\t#print(datainsert)\n\t\t\t\t\t\t\t\tcursor.execute('INSERT INTO data (usage_type, lastime, timeactive, last_time_service_used, last_time_visible, total_time_visible, '\n\t\t\t\t\t\t\t\t\t\t\t 'app_launch_count, package, types, classs, source, fullatt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)', datainsert)\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t#datainsert = (usagetype, finalt, tac, '' , '' , '' , sourced, fullatti_str,)\n\t\t\t\t\t\t\t\t#cursor.execute('INSERT INTO data (usage_type, lastime, timeactive, package, types, classs, source, fullatt) VALUES(?,?,?,?,?,?,?,?)', datainsert)\n\t\t\t\t\t\t\t\tdb.commit()\n\t\t\t\t\n\t\t\t\t\t\telif usagetype == 'event-log':\n\t\t\t\t\t\t\tfor subelem in elem:\n\t\t\t\t\t\t\t\t#print(subelem.attrib['time'])\n\t\t\t\t\t\t\t\ttime1 = subelem.attrib['time']\n\t\t\t\t\t\t\t\ttime1 = int(time1)\n\t\t\t\t\t\t\t\tif time1 < 0:\n\t\t\t\t\t\t\t\t\tfinalt = abs(time1)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tfinalt = file_name_int + time1\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t#time1 = subelem.attrib['time']\n\t\t\t\t\t\t\t\t#finalt = file_name_int + int(time1)\n\t\t\t\t\t\t\t\t#print('final time: ')\n\t\t\t\t\t\t\t\t#print(finalt)\n\t\t\t\t\t\t\t\t#print(subelem.attrib['package'])\n\t\t\t\t\t\t\t\tpkg = (subelem.attrib['package'])\n\t\t\t\t\t\t\t\t#print(subelem.attrib['type'])\n\t\t\t\t\t\t\t\ttipes = (subelem.attrib['type'])\n\t\t\t\t\t\t\t\t#print(subelem.attrib)\n\t\t\t\t\t\t\t\tfullatti_str = json.dumps(subelem.attrib)\n\t\t\t\t\t\t\t\t#add variable for type conversion from number to text explanation\n\t\t\t\t\t\t\t\t#print(subelem.attrib['fs'])\n\t\t\t\t\t\t\t\t#classy = subelem.attrib['class']\n\t\t\t\t\t\t\t\tif 'class' in subelem.attrib:\n\t\t\t\t\t\t\t\t\tclassy = subelem.attrib['class']\n\t\t\t\t\t\t\t\t\tcursor = db.cursor()\n\t\t\t\t\t\t\t\t\tdatainsert = (usagetype, finalt, '' , '' , '' , '' ,'' , pkg , tipes , classy , sourced, fullatti_str,)\n\t\t\t\t\t\t\t\t\tcursor.execute('INSERT INTO data (usage_type, lastime, timeactive, last_time_service_used, last_time_visible, total_time_visible, '\n\t\t\t\t\t\t\t\t\t\t\t 'app_launch_count, package, types, classs, source, fullatt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)', datainsert)\n\t\t\t\t\t\t\t\t\tdb.commit()\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t#insert in database\n\t\t\t\t\t\t\t\t\tcursor = db.cursor()\n\t\t\t\t\t\t\t\t\tcursor.execute('INSERT INTO data (usage_type, lastime, timeactive, last_time_service_used, last_time_visible, total_time_visible, '\n\t\t\t\t\t\t\t\t\t\t\t 'app_launch_count, package, types, classs, source, fullatt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)', datainsert)\n\t\t\t\t\t\t\t\t\tdatainsert = (usagetype, finalt, '' , '' , '', '', '', pkg , tipes , '' , sourced, fullatti_str,)\n\t\t\t\t\t\t\t\t\t#cursor.execute('INSERT INTO data (usage_type, lastime, timeactive, package, types, classs, source, fullatt) VALUES(?,?,?,?,?,?,?,?)', datainsert)\n\t\t\t\t\t\t\t\t\tdb.commit()\n\t\t\t\t\t\t\t\t\t\n\t#query for reporting\n\tcursor.execute('''\n\tselect \n\tusage_type,\n\tdatetime(lastime/1000, 'UNIXEPOCH', 'localtime') as lasttimeactive,\n\ttimeactive as time_Active_in_msecs,\n\ttimeactive/1000 as timeactive_in_secs,\n\tcase last_time_service_used WHEN '' THEN ''\n\t ELSE datetime(last_time_service_used/1000, 'UNIXEPOCH', 'localtime')\n\tend last_time_service_used,\n\tcase last_time_visible WHEN '' THEN ''\n\t ELSE datetime(last_time_visible/1000, 'UNIXEPOCH', 'localtime') \n\tend last_time_visible,\n\ttotal_time_visible,\n\tapp_launch_count,\n\tpackage,\n\tCASE types\n\t WHEN '1' THEN 'MOVE_TO_FOREGROUND'\n\t WHEN '2' THEN 'MOVE_TO_BACKGROUND'\n\t WHEN '5' THEN 'CONFIGURATION_CHANGE'\n\t\t WHEN '7' THEN 'USER_INTERACTION'\n\t\t WHEN '8' THEN 'SHORTCUT_INVOCATION'\n\t ELSE types\n\tEND types,\n\tclasss,\n\tsource,\n\tfullatt\n\tfrom data\n\torder by lasttimeactive DESC\n\t''')\n\tall_rows = cursor.fetchall()\n\n\t#HTML report section\n\th = open(reportfolderbase+'UsageStats/UsageStats.html', 'w')\t\n\th.write('')\n\th.write('

Android Usagestats report (Dates are localtime!)

')\n\th.write('UsageStats located at '+str(splitfilefound)+'/usagestats/')\n\th.write('
')\n\th.write('')\n\th.write('
')\n\th.write('')\n\t\n\t\n\n\t#HTML headers\n\th.write(f'')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\th.write('')\n\n\tfor row in all_rows:\n\t\tusage_type = row[0]\n\t\tlasttimeactive = row[1]\n\t\ttime_Active_in_msecs = row[2]\n\t\ttimeactive_in_secs = row[3]\n\t\tlast_time_service_used = row[4]\n\t\tlast_time_visible = row[5]\n\t\ttotal_time_visible = row[6]\n\t\tapp_launch_count = row[7]\n\t\tpackage = row[8]\n\t\ttypes = row[9]\n\t\tclasss = row[10]\n\t\tsource = row[11]\n\t\t\n\t\tprocessed = processed+1\n\t\t#report data\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\t\th.write('')\n\n\t#HTML footer\t\n\th.write('
Usage TypeLast Time ActiveTime Active in MsecsTime Active in SecsLast Time Service UsedLast Time VisibleTotal Time VisibleApp Launch CountPackageTypesClassSource
'+str(usage_type)+''+str(lasttimeactive)+''+str(time_Active_in_msecs)+''+str(timeactive_in_secs)+''+str(last_time_service_used)+''+str(last_time_visible)+''+str(total_time_visible)+''+str(app_launch_count)+''+str(package)+''+str(types)+''+str(classs)+''+str(source)+'
')\n\th.write('
')\t\n\n\t\n\tlogfunc('Records processed: '+str(processed))\n\tlogfunc('UsageStats function completed')\n\t\t\n\n\n\n\ndef wellbeing(filefound):\n\tlogfunc(f'Wellbeing events function executing')\n\ttry:\n\t\tif os.path.isdir(reportfolderbase+'Wellbeing/'):\n\t\t\tpass\n\t\telse:\n\t\t\tos.makedirs(reportfolderbase+'Wellbeing/')\n\texcept:\n\t\tlogfunc('Error creating wellbeing() report directory')\n\n\ttry:\n\t\thead, tail = os.path.split(filefound[0])\n\t\tdb = sqlite3.connect(head+'/app_usage')\n\t\tcursor = db.cursor()\n\t\tcursor.execute('''\n\t\tSELECT \n\t\t\t\tevents._id, \n\t\t\t\tdatetime(events.timestamp /1000, 'UNIXEPOCH') as timestamps, \n\t\t\t\tpackages.package_name,\n\t\t\t\tevents.type,\n\t\t\t\tcase\n\t\t\t\t\twhen events.type = 1 THEN 'ACTIVITY_RESUMED'\n\t\t\t\t\twhen events.type = 2 THEN 'ACTIVITY_PAUSED'\n\t\t\t\t\twhen events.type = 12 THEN 'NOTIFICATION'\n\t\t\t\t\twhen events.type = 18 THEN 'KEYGUARD_HIDDEN & || Device Unlock'\n\t\t\t\t\twhen events.type = 19 THEN 'FOREGROUND_SERVICE_START'\n\t\t\t\t\twhen events.type = 20 THEN 'FOREGROUND_SERVICE_STOP' \n\t\t\t\t\twhen events.type = 23 THEN 'ACTIVITY_STOPPED'\n\t\t\t\t\twhen events.type = 26 THEN 'DEVICE_SHUTDOWN'\n\t\t\t\t\twhen events.type = 27 THEN 'DEVICE_STARTUP'\n\t\t\t\t\telse events.type\n\t\t\t\t\tEND as eventtype\n\t\t\t\tFROM\n\t\t\t\tevents INNER JOIN packages ON events.package_id=packages._id \n\t\t''')\n\n\t\tall_rows = cursor.fetchall()\n\t\tusageentries = len(all_rows)\n\t\tif usageentries > 0:\n\t\t\t#logfunc(f'Wellbeing events function executing')\n\t\t\twith open(reportfolderbase+'Wellbeing/Events.html', 'w', encoding='utf8') as f:\n\t\t\t\tf.write('')\n\t\t\t\tf.write('

Wellbeing events report

')\n\t\t\t\tf.write(f'Wellbeing event entries: {usageentries}
')\n\t\t\t\tf.write(f'Wellbeing events located at: {filefound[0]}
')\n\t\t\t\tf.write('')\n\t\t\t\tf.write('
')\n\t\t\t\tf.write('')\n\t\t\t\tf.write(f'
')\n\t\t\t\tf.write(f'')\n\t\t\t\tfor row in all_rows:\n\t\t\t\t\tf.write(f'')\n\t\t\t\tf.write(f'
TimestampPackage IDEvent Type
{row[1]}{row[2]}{row[4]}
')\n\t\telse:\n\t\t\t\tlogfunc('No Wellbeing event data available')\n\texcept:\n\t\tlogfunc('Error in Wellbeing event section')\n\tlogfunc('Wellbeing event function completed')\n\ndef wellbeingaccount(filefound):\t\n\tlogfunc(f'Wellbeing Account function executing')\n\ttry:\n\t\tif os.path.isdir(reportfolderbase+'Wellbeing/'):\n\t\t\tpass\n\t\telse:\n\t\t\tos.makedirs(reportfolderbase+'Wellbeing/')\n\texcept:\n\t\tlogfunc('Error creating wellbeing() report directory')\n\n\ttry:\n\t\tcontent = ParseProto(filefound[0])\n\t\t\n\t\tcontent_json_dump = json.dumps(content, indent=4, sort_keys=True, ensure_ascii=False)\n\t\tparsedContent = str(content_json_dump).encode(encoding='UTF-8',errors='ignore')\n\t\t\n\t\twith open(reportfolderbase+'Wellbeing/Account Data.html', 'w', encoding='utf8') as f:\n\t\t\tf.write('')\n\t\t\tf.write('

Wellbeing Account report

')\n\t\t\tf.write(f'Wellbeing Account located at: {filefound[0]}
')\n\t\t\tf.write('')\n\t\t\tf.write('
')\n\t\t\tf.write('')\n\t\t\tf.write(f'')\n\t\t\tf.write(f'')\n\t\t\tf.write('')\n\t\t\tf.write(f'
Protobuf Parsed DataProtobuf Data
'+str(parsedContent).replace(\"\\\\n\", \"
\")+'
'+str(content)+'
')\n\texcept:\n\t\tlogfunc('Error in Wellbeing Account section')\n\tlogfunc('Wellbeing Account function completed')\n\t\ndef deviceinfoin(ordes, kas, vas, sources):\n\tsources = str(sources)\n\tdb = sqlite3.connect(reportfolderbase+'Device Info/di.db')\n\tcursor = db.cursor()\n\tdatainsert = (ordes, kas, vas, sources,)\n\tcursor.execute('INSERT INTO devinf (ord, ka, va, source) VALUES(?,?,?,?)', datainsert)\n\tdb.commit()\n\t\ndef html2csv(reportfolderbase):\n\t#List of items that take too long to convert or that shouldn't be converted\n\titemstoignore = ['index.html',\n\t\t\t\t\t'Distribution Keys.html', \n\t\t\t\t\t'StrucMetadata.html',\n\t\t\t\t\t'StrucMetadataCombined.html']\n\t\t\t\t\t\n\tif os.path.isdir(reportfolderbase+'_CSV Exports/'):\n\t\tpass\n\telse:\n\t\tos.makedirs(reportfolderbase+'_CSV Exports/')\n\tfor root, dirs, files in sorted(os.walk(reportfolderbase)):\n\t\tfor file in files:\n\t\t\tif file.endswith(\".html\"):\n\t\t\t\tfullpath = (os.path.join(root, file))\n\t\t\t\thead, tail = os.path.split(fullpath)\n\t\t\t\tif file in itemstoignore:\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tdata = open(fullpath, 'r', encoding='utf8')\n\t\t\t\t\tsoup=BeautifulSoup(data,'html.parser')\n\t\t\t\t\ttables = soup.find_all(\"table\")\n\t\t\t\t\tdata.close()\n\t\t\t\t\toutput_final_rows=[]\n\n\t\t\t\t\tfor table in tables:\n\t\t\t\t\t\toutput_rows = []\n\t\t\t\t\t\tfor table_row in table.findAll('tr'):\n\n\t\t\t\t\t\t\tcolumns = table_row.findAll('td')\n\t\t\t\t\t\t\toutput_row = []\n\t\t\t\t\t\t\tfor column in columns:\n\t\t\t\t\t\t\t\t\toutput_row.append(column.text)\n\t\t\t\t\t\t\toutput_rows.append(output_row)\n\t\t\n\t\t\t\t\t\tfile = (os.path.splitext(file)[0])\n\t\t\t\t\t\twith codecs.open(reportfolderbase+'_CSV Exports/'+file+'.csv', 'a', 'utf-8-sig') as csvfile:\n\t\t\t\t\t\t\twriter = csv.writer(csvfile, quotechar='\"', quoting=csv.QUOTE_ALL)\n\t\t\t\t\t\t\twriter.writerows(output_rows)\n","sub_path":"scripts/ilapfuncs.py","file_name":"ilapfuncs.py","file_ext":"py","file_size_in_byte":19799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"138027554","text":"#!/usr/bin/python\n\nimport pdb, json, sys, os, pytest, datetime, random, calendar, time\n\ntry:\n zbathome = os.environ['ZBAT_HOME']\nexcept:\n #pdb.set_trace()\n print('Test cannot run. Please export ZBAT_HOME.')\n sys.exit()\n\nif zbathome+'lib' not in sys.path:\n sys.path.append(zbathome+'lib')\n \nfrom ui.mssp.zbUIMSSP import MSSP\nfrom common.zbConfig import defaultEnv, NUMBER_RETRIES, DELAY_SECONDS, SCREENSHOT_ON_FAIL\nfrom common.zbCommon import rerunIfFail\n\n\nenv = defaultEnv()\n\n# fixtures\n@pytest.fixture(scope=\"module\")\ndef browser(browser_factory):\n return browser_factory(MSSP)\n\n\n@pytest.fixture(scope=\"module\", params=[\"1D\"])\ndef timerange(request):\n return request.param\n\n\n@pytest.mark.skipif(os.environ['NODE_ENV'] in ['production'], reason='MSSP test should not be run on Production')\nclass Test_MSSP:\n \n @pytest.mark.bugs #AP-3992\n def test_SummaryCompareCustomers(self, browser, timerange):\n selenium = browser[\"selenium\"]\n assert rerunIfFail(function=selenium.verifyMSSPCustomers(timerange), selenium=selenium.selenium, screenshot=SCREENSHOT_ON_FAIL, testname=zbathome+'artifacts/test_MSSPSummaryCompareCustomers.png', number=NUMBER_RETRIES, delay=DELAY_SECONDS) == True\n\n @pytest.mark.bugs #AP-3460\n def test_Resellers(self, browser):\n selenium = browser[\"selenium\"]\n assert rerunIfFail(function=selenium.verifyMSSPResellers(), selenium=selenium.selenium, screenshot=SCREENSHOT_ON_FAIL, testname=zbathome+'artifacts/test_MSSPResellers.png', number=NUMBER_RETRIES, delay=DELAY_SECONDS) == True\n\n @pytest.mark.bugs #AP-3460\n def test_CustomerDetail(self, browser):\n selenium = browser[\"selenium\"]\n assert rerunIfFail(function=selenium.verifyCustomerDetail(), selenium=selenium.selenium, screenshot=SCREENSHOT_ON_FAIL, testname=zbathome+'artifacts/test_MSSPCustomerDetail.png', number=NUMBER_RETRIES, delay=DELAY_SECONDS) == True\n\n @pytest.mark.bugs #AP-3460\n def test_CustomerCompareDashboard(self, browser):\n selenium = browser[\"selenium\"]\n assert rerunIfFail(function=selenium.verifyMSSPDashboard(), selenium=selenium.selenium, screenshot=SCREENSHOT_ON_FAIL, testname=zbathome+'artifacts/test_MSSPCustomerCompareDashboard.png', number=NUMBER_RETRIES, delay=DELAY_SECONDS) == True\n","sub_path":"tests/ui_old/test_mssp.py","file_name":"test_mssp.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"471897184","text":"from flask import Flask, request, render_template # Lightweight web application framework\nfrom datetime import timedelta, datetime\nfrom services import *\n\n# *****application logic*****\n\n# Initialize hte web framework\napp = Flask(__name__, template_folder='./templates/', static_folder='./static/', static_url_path='/static')\n\n\n# The following @app.route decorator is used to register the web request handler\n\n@app.route('/', endpoint='index')\ndef index():\n return render_template('battery.html')\n\n\n@app.route('/battery/list/', endpoint='battery.list')\ndef list():\n parent_assetId = '0RmeXD6D'\n # parent_assetId = '6Pvbj63S' # Change this to your battery's parent assentId\n\n results = get_child_asset_list(parent_assetId)\n\n resp = {}\n battery_list = {}\n\n if results is not None:\n for item in results['data']:\n battery_list[item['name']['defaultValue']] = item['assetId']\n\n # Sort the asset list in ascending order by the aseet name\n sorted_list = [{'name': k, 'assetId': battery_list[k]} for k in sorted(battery_list.keys())]\n resp['batteries'] = sorted_list\n\n return resp\n\n\n@app.route('/battery/asset/', endpoint='battery.asset')\ndef asset(assetId):\n req = get_asset_info(assetId)\n return req\n\n\n@app.route('/battery/status/', endpoint='battery.status')\ndef status(assetId):\n req = get_asset_info(assetId)\n capacity = 10\n if req is not None:\n capacity = req['data']['attributes']['Capacity']\n\n health_level = 100\n accumulating_power = 0\n\n req = get_asset_latest_data(assetId, 'health_level,accumulating_power')\n if req is not None:\n for item in req['data']['items']:\n if 'health_level' in item.keys():\n health_level = int(item['health_level'])\n elif 'accumulating_power' in item.keys():\n accumulating_power = float(item['accumulating_power'])\n\n # Calculate the remaining power percentage of batteries\n remaining_power = \"%.0f%%\" % (100 * accumulating_power / capacity)\n\n resp = {'health_level': health_level, 'remaining_power': remaining_power}\n\n return resp\n\n\n@app.route('/battery/tsdb/', endpoint='battery.tsdb')\ndef tsdb(assetId):\n endTime = datetime.now()\n startTime = endTime + timedelta(hours=-1)\n startTime = startTime.strftime(format='%Y-%m-%d %H:%M:%S')\n endTime = endTime.strftime(format='%Y-%m-%d %H:%M:%S')\n req = get_asset_ai_raw_data(assetId, startTime, endTime)\n\n # Arrange the returned data in array format\n time = []\n current = []\n voltage = []\n temp = []\n\n if req is not None:\n for item in req['data']['items']:\n if 'current' in item.keys():\n time.append(item['localtime'])\n current.append(item['current'])\n elif 'voltage' in item.keys():\n voltage.append(item['voltage'])\n elif 'temp' in item.keys():\n temp.append(item['temp'])\n else:\n pass\n\n # Assemble the response structure\n resp = {'time': time, 'voltage': voltage, 'current': current, 'temp': temp}\n\n return resp\n\n\n@app.route('/battery/alerts/', endpoint='battery.alerts')\ndef alerts():\n req = get_active_alerts()\n\n # Add asset name for each alert record\n if req is not None:\n for item in req['data']:\n result = get_asset_info(item['assetId'])\n if 'data' in result.keys() and result['data'] is not None:\n name = result['data']['name']\n if 'defaultValue' in name.keys() and (name['defaultValue'] != ''):\n item['assetName'] = name['defaultValue']\n elif 'i18nValue' in name.keys():\n i18_name = name['i18nValue']\n if 'zh_CN' in i18_name.keys() and (i18_name['zh_CN'] != ''):\n item['assetName'] = i18_name['zh_CN']\n elif 'en_US' in i18_name.keys() and (i18_name['en_US'] != ''):\n item['assetName'] = i18_name['en_US']\n return req\n\n\n@app.route('/battery/service/', endpoint='battery.service', methods=['POST'])\ndef service(assetId):\n req = {}\n if request.method == 'POST':\n if request.form['command'] == 'set_frequency':\n freq = int(request.form['parameter'])\n req = set_battery_frequency(assetId, freq)\n\n res = {\n \"status\": \"success\",\n \"result\": req\n }\n return res\n\n\n# Main entrance\nif __name__ == '__main__':\n app.debug = True\n # app.run()\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"Developer_Bootcamp_EN/Full_Demo_App/battery-app-python/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"308980815","text":"\"\"\"\n/***********************************************\n* PetaPhaser Development\n* http://omniphaser.wc.lt\n* Copyright (C) 2015\n* ALL CODE LICENSES APPLY\n* See the license in license.txt in the home\n* \tdirectory of the program\n***********************************************/\n\"\"\"\nimport os, sys, inspect\n# realpath() will make your script run, even if you symlink it :)\ncmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))\nif cmd_folder not in sys.path:\n sys.path.insert(0, cmd_folder)\n\n# use this if you want to include modules from a subfolder\ncmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],\"subfolder\")))\nif cmd_subfolder not in sys.path:\n sys.path.insert(0, cmd_subfolder)\n\n# Info:\n# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!\n# __file__ fails if script is called in different ways on Windows\n# __file__ fails if someone does os.chdir() before\n# sys.argv[0] also fails because it doesn't not always contains the path\n\nimport pyaes\nimport random\nimport string\n\ndef newkey(bytes_length):\n key=''.join(random.SystemRandom().choice(string.ascii_lowercase+string.digits) for _ in range(bytes_length))\n return key\n\ndef encrypt(plain,key):\n key=key.encode('utf-8')\n aes = pyaes.AESModeOfOperationCTR(key) \n ciphertext = aes.encrypt(plain)\n return ciphertext\n\ndef decrypt(cipher,key):\n key=key.encode('utf-8')\n aes = pyaes.AESModeOfOperationCTR(key)\n # decrypted data is always binary, need to decode to plaintext\n decrypted = aes.decrypt(cipher).decode('utf-8')\n return decrypted\n","sub_path":"powercrypt/aes.py","file_name":"aes.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"522215211","text":"#! /usr/bin/env python3\n\nimport argparse\nimport collections\nimport datetime\nimport re\nimport string\nimport sys\nimport urllib\n\nimport github\n\n\nREPOS = [\n 'bazelbuild/bazel',\n 'bazelbuild/bazel-gazelle',\n 'bazelbuild/bazelisk',\n 'bazelbuild/bazel-skylib',\n 'bazelbuild/bazel-website',\n 'bazelbuild/buildtools',\n 'bazelbuild/rules_android',\n 'bazelbuild/rules_apple',\n 'bazelbuild/rules_cc',\n 'bazelbuild/rules_docker',\n 'bazelbuild/rules_foreign_cc',\n 'bazelbuild/rules_kotlin',\n 'bazelbuild/rules_python',\n 'bazelbuild/rules_rust',\n 'bazelbuild/skydoc',\n 'bazelbuild/starlark',\n]\n\nBins = collections.namedtuple(\n 'Bins',\n 'product version arch os packaging installer is_bin attributes leftover')\n\n_PRODUCT_VERSION_RE = re.compile(r'(\\w+[-\\w]*)[-_.](\\d+\\.\\d+\\.\\d+[a-z\\d]*)[^.\\D]?')\n_JDK_SPEC_RE = re.compile(r'[^a-z]?(jdk\\d*)')\n\n_LINUX_PACKAGE_EXTENSIONS = ['.sh', '.deb', '.rpm', '.zip', '.tar.gz', '.tgz']\n_MACOS_PACKAGE_EXTENSIONS = ['.dmg', '.mac', '.osx']\n_WINDOWS_PACKAGE_EXTENSIONS = ['.exe']\n\n\ndef FetchDownloadCounts(all_repos=False):\n repos = REPOS\n if all_repos:\n repos = github.fetch_repos('bazelbuild')\n print(repos)\n now = datetime.datetime.now()\n ymd = now.strftime('%Y-%m-%d')\n hm = now.strftime('%H%M')\n file_name = 'downloads.%s.%s.txt' % (ymd, hm)\n\n # FUTURE: save to cloud rather than local disk\n with open(file_name, 'w') as out:\n CollectDownloadCounts(out, repos, ymd, hm)\n\n\ndef CollectDownloadCounts(out, repos, ymd, hm):\n for repo in repos:\n try:\n releases = github.fetch_releases(repo)\n for release in releases:\n tag = release['tag_name']\n label = '%s/%s' % (repo, tag)\n print('Scanning:', label)\n name_to_counts = collections.defaultdict(dict)\n assets = release.get('assets')\n if not assets:\n err = 'WARNING: %s has no assets' % label\n if release.get('tarball_url') or release.get('zipball_url'):\n err += ', but it does have zip or tar downloads'\n print(err)\n continue\n for asset in release['assets']:\n file_name = asset['name']\n count = int(asset['download_count'])\n if file_name.endswith('.sig'):\n file_name = file_name[0:-4]\n name_to_counts[file_name]['sig'] = count\n elif file_name.endswith('.sha256'):\n file_name = file_name[0:-7]\n name_to_counts[file_name]['sha256'] = count\n else:\n name_to_counts[file_name]['bin'] = count\n\n for file_name, counts in name_to_counts.items():\n bins = Categorize(file_name, tag)\n if bins:\n out.write('%s|%s|%s|%d|%d|%d|%s|%s|%s|%s|%s|%s|%s|{%s}%s\\n' % (\n file_name, ymd, hm, counts.get('bin') or 0,\n counts.get('sha256') or 0, counts.get('sig') or 0,\n bins.product, bins.version, bins.arch, bins.os, bins.packaging,\n bins.installer, bins.is_bin, bins.attributes,\n bins.leftover))\n\n except urllib.error.HTTPError as e:\n print('Skipping %s: %s' % (repo, e))\n\n\ndef ExtractFeature(s, feature_list):\n \"\"\"Extract a feature from a file name.\n\n The feature and then redundant punction is removed from the input.\n\n Returns:\n feature, remainder\n \"\"\"\n for feature in feature_list:\n pos = s.find(feature)\n if pos < 0:\n pos = s.find(feature.upper())\n if pos >= 0:\n before = s[0:pos]\n after = s[pos+len(feature):]\n if (len(before) and len(after)\n and before[-1] in string.punctuation\n and after[0] in string.punctuation):\n before = before[0:-1]\n # If we are left with after just being the '-', drop it.\n if len(after) == 1:\n after = ''\n elif len(after) == 0 and before[-1] in string.punctuation:\n before = before[0:-1]\n return feature.lower(), before + after\n return None, s\n\n\ndef MapRawData(file_names):\n \"\"\"Recategorize the download files names into bucketable dimensions.\n\n This is used for regression testing changes to the categorizor.\n\n For each data files:\n Categorize each entry along the important dimensions\n - gather the oddball stuff into an attribute bag for now\n Re-emit that in a form easy to sort and reduce\n \"\"\"\n for f in file_names:\n print('Loading:', f, file=sys.stderr)\n with open(f, 'r') as df:\n for line in df:\n line = line.strip()\n (file_name, ymd, hm, bin_count, sha_count, sig_count, o_prod,\n o_version) = line.split('|')\n bins = Categorize(file_name, o_version or '@REPO_TAG@')\n if bins:\n print('%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|{%s}%s' % (\n file_name, ymd, hm, bin_count, sha_count, sig_count,\n bins.product, bins.version, bins.arch, bins.os, bins.packaging,\n bins.installer, bins.is_bin, bins.attributes,\n bins.leftover))\n\n\ndef Categorize(file_name, default_version=None):\n \"\"\"Break down file name into bins that matter.\"\"\"\n\n # eat away parts until todo us empty\n todo = file_name\n attributes = []\n\n # msvc was an odd tag added to early versions\n if todo.find('-msvc') > 0:\n attributes.append('msvc')\n todo = todo.replace('-msvc', '')\n\n arch, todo = ExtractFeature(todo, ['x86_64', 'amd64'])\n if arch == 'amd64':\n arch = 'x86_64'\n\n os, todo = ExtractFeature(\n todo, ['dist', 'linux', 'darwin', 'macos', 'osx', 'windows'])\n if os in ['darwin', 'osx']:\n os = 'macos'\n if os == 'dist':\n os = 'any'\n\n # extract sig before packaging, so .sh and .sha256 are not confused\n is_bin = True\n if todo.endswith('.sig'):\n todo = todo[0:-4]\n attributes.append('sig')\n is_bin = False\n elif todo.endswith('.sha256'):\n todo = todo[0:-7]\n attributes.append('sig')\n is_bin = False\n\n packaging, todo = ExtractFeature(todo, _LINUX_PACKAGE_EXTENSIONS +\n _MACOS_PACKAGE_EXTENSIONS +\n _WINDOWS_PACKAGE_EXTENSIONS)\n if packaging and packaging[0] == '.':\n packaging = packaging[1:]\n if packaging in ['tar.gz', 'tgz']:\n if not arch:\n arch = 'src'\n if not os:\n os = 'any'\n if not os:\n if packaging in _LINUX_PACKAGE_EXTENSIONS:\n os = 'linux'\n if packaging in _MACOS_PACKAGE_EXTENSIONS:\n os = 'macos'\n if packaging in _WINDOWS_PACKAGE_EXTENSIONS:\n os = 'windows'\n\n installer, todo = ExtractFeature(todo, ['installer'])\n installer = 'installer' if installer else 'standalone'\n\n # How we say things about JDK is a mess\n nojdk, todo = ExtractFeature(todo, ['without-jdk'])\n jdk = None\n if nojdk:\n jdk = 'nojdk'\n else:\n jdk_match = _JDK_SPEC_RE.search(todo)\n if jdk_match:\n jdk = jdk_match.group(1)\n todo = todo[0:jdk_match.start(1)] + todo[jdk_match.end(1):]\n if jdk:\n attributes.append(jdk)\n\n # At this point, only the product name and version should be left.\n\n m = _PRODUCT_VERSION_RE.match(todo)\n if m:\n product = todo[0:m.end(1)]\n version = m.group(2)\n todo = todo[m.end(2):]\n else:\n # some things are unversioned. e.g. bazelisk-os-arch.\n sep_pos = todo.find('-')\n if sep_pos <= 0:\n print('Can not find version on:', file_name, file=sys.stderr)\n product = todo\n todo = ''\n version = default_version\n else:\n version = 'head'\n product = todo[0:sep_pos]\n todo = todo[sep_pos:]\n\n left = re.sub(r'^[- _.]*', '', todo)\n if left:\n left = ' - LEAVES(%s)' % left\n\n return Bins(product, version, arch, os, packaging, installer, is_bin,\n '|'.join(attributes), left)\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Gather Bazel metrics')\n subparsers = parser.add_subparsers(dest='command', help='select a command')\n\n update_parser = subparsers.add_parser('update', help='update the datasets')\n update_parser.add_argument(\n '--all', action='store_true',\n help='Get all repositories rather than just the select ones')\n\n # Usage: download-stats map downloads.*\n map_parser = subparsers.add_parser('map', help='categorize the data')\n map_parser.add_argument(\n 'files', nargs=argparse.REMAINDER, help='raw data files')\n\n args = parser.parse_args()\n if args.command == 'update':\n FetchDownloadCounts(args.all)\n elif args.command == 'map':\n MapRawData(args.files)\n else:\n parser.print_usage()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"download-stats.py","file_name":"download-stats.py","file_ext":"py","file_size_in_byte":8421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"150762108","text":"import zmail\r\n\r\nclass G_email():\r\n\r\n def __init__(self):\r\n self.__send_account='1931784039@qq.com'\r\n self.__send_password='fumhridxjneocagb'\r\n self.__mail_content={}\r\n self.__receive_account=[]\r\n\r\n\r\n @property \r\n def mail_content(self):\r\n '''getter'''\r\n return self.__mail_content\r\n\r\n @mail_content.setter \r\n def mail_content(self,email_dict):\r\n '''setter'''\r\n self.__mail_content=email_dict \r\n\r\n @property\r\n def receive_account(self):\r\n '''getter'''\r\n return self.__receive_account\r\n\r\n @receive_account.setter\r\n def receive_account(self,account_list):\r\n '''setter'''\r\n self.__receive_account=account_list\r\n\r\n def send__email(self):\r\n server=zmail.server(self.__send_account,self.__send_password)\r\n server.send_mail(self.__receive_account,self.__mail_content)\r\n \r\n def clocking_send(self):\r\n while True:\r\n s=input('是否即时发送y/n:')\r\n if s == 'y':\r\n self.send__email()\r\n return\r\n elif s == 'n':\r\n clock_time=input('请设置发送的时间,时-分-秒:')\r\n c=clock_time.split('-') \r\n n=TIME.localtime()[3:5]\r\n TIME.sleep((int(c[3])-n[3])*3600+(int(c[4])-n[4])*60+(int(c[5])-n[5]))\r\n self.send__email()\r\n return\r\n else:\r\n continue\r\n\r\n def everyday_send(self):\r\n while True:\r\n s=input('是否每天发送y/n:')\r\n if s == 'y':\r\n TIME.sleep(86400)\r\n self.send__email()\r\n return\r\n elif s == 'n':\r\n return\r\n else:\r\n continue","sub_path":"email_class.py","file_name":"email_class.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"245582350","text":"from scipy import stats, linalg\r\nfrom geosoup.common import Handler, Opt, np\r\nimport warnings\r\n\r\n\r\n__all__ = ['Distance',\r\n 'Mahalanobis',\r\n 'Euclidean']\r\n\r\n\r\nclass Distance(object):\r\n \"\"\"\r\n Parent class for all the distance type methods\r\n \"\"\"\r\n\r\n def __init__(self,\r\n samples=None,\r\n names=None,\r\n csv_file=None,\r\n index=None):\r\n \"\"\"\r\n Class constructor\r\n :param samples: List of sample dictionaries\r\n :param names: Name of the columns or dimensions\r\n :param csv_file: path of the csv file with sample data in columns\r\n :param index: Name of index column\r\n :return: _Distance object\r\n \"\"\"\r\n self.samples = samples\r\n self.nsamp = len(samples)\r\n self.names = names\r\n self.csv_file = csv_file\r\n self.index = index\r\n\r\n if samples is not None:\r\n self.samples = samples\r\n self.nsamp = len(samples)\r\n\r\n elif csv_file is not None:\r\n self.samples = Handler(filename=csv_file).read_from_csv(return_dicts=True)\r\n self.nsamp = len(self.samples)\r\n else:\r\n warnings.warn('Empty Samples class initialized')\r\n self.samples = None\r\n self.nsamp = 0\r\n\r\n if self.nsamp > 0:\r\n self.index = list(range(self.nsamp))\r\n else:\r\n self.index = list()\r\n\r\n if names is not None:\r\n self.names = names\r\n elif self.samples is not None:\r\n self.names = list(self.samples[0])\r\n else:\r\n self.names = list()\r\n\r\n self.matrix = None\r\n self.center = None\r\n\r\n def __repr__(self):\r\n return \"\".format(hex(id(self)))\r\n\r\n def sample_matrix(self):\r\n \"\"\"\r\n Method to convert sample dictionaries to sample matrix\r\n :return: Numpy matrix with columns as dimensions and rows as individual samples\r\n \"\"\"\r\n # dimensions of the sample matrix\r\n nsamp = len(self.samples)\r\n nvar = len(self.names)\r\n\r\n if nsamp > 1:\r\n # copy data to matrix\r\n self.matrix = np.array([[Handler.string_to_type(self.samples[i][self.names[j]])\r\n for j in range(0, nvar)]\r\n for i in range(0, self.nsamp)])\r\n else:\r\n raise ValueError('Not enough samples to make a matrix object')\r\n\r\n def cluster_center(self,\r\n method='median'):\r\n \"\"\"\r\n Method to determine cluster center of the sample matrix\r\n :param method: Type of reducer to use. Options: 'mean', 'median', 'percentile_xx' where xx is 1-99\r\n :return: Cluster center (vector of column/dimension values)\r\n \"\"\"\r\n if self.matrix is not None:\r\n if method == 'median':\r\n self.center = np.array(np.median(self.matrix, axis=0))[0]\r\n elif method == 'mean':\r\n self.center = np.array(np.mean(self.matrix, axis=0))[0]\r\n elif 'percentile' in method:\r\n perc = int(method.replace('percentile', '')[1:])\r\n self.center = np.array(np.percentile(self.matrix, perc, axis=0))[0]\r\n else:\r\n raise ValueError(\"Invalid or no reducer\")\r\n else:\r\n raise ValueError(\"Sample matrix not found\")\r\n\r\n\r\nclass Mahalanobis(Distance):\r\n \"\"\"\r\n Class for calculating Mahalanobis distance from cluster center\r\n \"\"\"\r\n\r\n def __init__(self,\r\n samples=None,\r\n names=None,\r\n index=None):\r\n \"\"\"\r\n Class constructor\r\n Class constructor\r\n :param samples: List of sample dictionaries\r\n :param names: Name of the columns or dimensions\r\n :param index: Name of index column\r\n :return: Mahalanobis object\r\n \"\"\"\r\n\r\n super(Mahalanobis, self).__init__(samples,\r\n names,\r\n index)\r\n\r\n self.inverse = None\r\n self.distance = None\r\n\r\n def __repr__(self):\r\n return \"\".format(hex(id(self)))\r\n\r\n def covariance(self,\r\n inverse=False):\r\n \"\"\"\r\n Method to calculate a covariance matrix for a given sample matrix\r\n where rows are samples, columns are dimensions\r\n :param inverse: Should the inverse matrix be calculated\r\n :return: Covariance or inverse covariance matrix (numpy.matrix object)\r\n \"\"\"\r\n cov_mat = np.cov(self.matrix,\r\n rowvar=False)\r\n\r\n if inverse:\r\n # Inverse using SVD\r\n u, s, v = np.linalg.svd(cov_mat)\r\n\r\n try:\r\n return np.dot(np.dot(v.T, np.linalg.inv(np.diag(s))), u.T)\r\n\r\n except ValueError:\r\n return None\r\n else:\r\n return np.array(cov_mat)\r\n\r\n def difference(self,\r\n transpose=False):\r\n \"\"\"\r\n Method to calculate difference from scene center\r\n :return: matrix (numpy.ndarray)\r\n \"\"\"\r\n center = self.center\r\n\r\n diff_matrix = np.apply_along_axis(lambda row: np.array(row) - center,\r\n axis=1,\r\n arr=np.array(self.matrix))\r\n\r\n if transpose:\r\n return diff_matrix.T\r\n else:\r\n return diff_matrix\r\n\r\n def calc_distance(self):\r\n \"\"\"\r\n Method to calculate mahalanobis distance from scene center\r\n :return: scalar value\r\n \"\"\"\r\n inv_cov_matrix = self.covariance(True)\r\n\r\n diff = self.difference(False)\r\n transpose_diff = self.difference(True)\r\n\r\n mdist = np.zeros(self.nsamp)\r\n\r\n for i in range(0, self.nsamp):\r\n\r\n if inv_cov_matrix is None:\r\n mdist[i] = np.nan\r\n continue\r\n\r\n mdist_val = np.dot(np.dot(diff[i, :],\r\n inv_cov_matrix),\r\n transpose_diff[:, i])\r\n\r\n if type(mdist_val) not in (float, int):\r\n if type(mdist_val) in (list, tuple, np.ndarray):\r\n mdist_val = mdist_val[0]\r\n\r\n if mdist_val < 0:\r\n mdist[i] = np.nan\r\n else:\r\n mdist[i] = np.sqrt(mdist_val)\r\n\r\n return list(mdist)\r\n\r\n def partial_corr(self):\r\n \"\"\"\r\n Partial Correlation using the linear regression approach to compute partial\r\n correlation among variables\r\n :returns Sample linear partial correlation coefficients between pairs of variables in self.matrix\r\n [i, j] contains the partial correlation of self.matrix[:, i] and self.matrix[:, j]\r\n \"\"\"\r\n\r\n var_data = np.asarray(self.matrix)\r\n n_var = var_data.shape[1]\r\n part_corr = np.zeros((n_var, n_var), dtype=np.float)\r\n\r\n for var_indx in range(0, n_var):\r\n part_corr[var_indx, var_indx] = 1\r\n\r\n for comparison_var_indx in range(var_indx + 1, n_var):\r\n\r\n indices = np.ones(n_var, dtype=np.bool)\r\n indices[var_indx] = False\r\n indices[comparison_var_indx] = False\r\n\r\n beta_var = linalg.lstsq(var_data[:, indices], var_data[:, comparison_var_indx])[0]\r\n beta_comparison_var = linalg.lstsq(var_data[:, indices], var_data[:, var_indx])[0]\r\n\r\n result_var = var_data[:, comparison_var_indx] - var_data[:, indices].dot(beta_var)\r\n result_comparison_var = var_data[:, var_indx] - var_data[:, indices].dot(beta_comparison_var)\r\n\r\n correlation = stats.pearsonr(result_var, result_comparison_var)[0]\r\n part_corr[var_indx, comparison_var_indx] = part_corr[comparison_var_indx, var_indx] = correlation\r\n\r\n return part_corr\r\n\r\n\r\nclass Euclidean(Distance):\r\n \"\"\"\r\n Class for calculating Euclidean distance\r\n \"\"\"\r\n\r\n def __init__(self,\r\n samples=None,\r\n csv_file=None,\r\n names=None):\r\n \"\"\"\r\n :param csv_file: csv file that contains the samples\r\n :param samples: List of dictionaries\r\n \"\"\"\r\n\r\n self.csv_file = csv_file\r\n\r\n self.index = None\r\n self.nfeat = None\r\n\r\n super(Euclidean, self).__init__(samples,\r\n names,\r\n csv_file,\r\n self.index)\r\n\r\n if self.samples is not None:\r\n self.sample_matrix()\r\n else:\r\n self.matrix = None\r\n\r\n self.grid = None\r\n\r\n self.distance_matrix = None\r\n\r\n def __repr__(self):\r\n return \"\".format(hex(id(self)),\r\n str(len(self.samples)))\r\n\r\n @staticmethod\r\n def euc_dist(vec1,\r\n vec2):\r\n \"\"\"\r\n Method to calculate euclidean distance between two vectors\r\n :param vec1: first vector\r\n :param vec2: second vector\r\n :return: scalar\r\n \"\"\"\r\n\r\n return np.linalg.norm(np.array(vec1) - np.array(vec2))\r\n\r\n @staticmethod\r\n def mat_dist(vec1, mat1):\r\n \"\"\"\r\n Method to calculate euclidean distance between between a vector and all the vectors in a matrix\r\n :param vec1: vector\r\n :param mat1: matrix (numpy array of vectors)\r\n :return: numpy array of scalars\r\n \"\"\"\r\n return np.apply_along_axis(lambda x: Euclidean.euc_dist(x, np.array(vec1)),\r\n 1,\r\n mat1)\r\n\r\n def calc_dist_matrix(self,\r\n approach=2,\r\n verbose=False):\r\n \"\"\"\r\n Method to calculate euclidean distance from each sample\r\n and make a matrix\r\n :return: 2d matrix\r\n \"\"\"\r\n\r\n if verbose:\r\n Opt.cprint('Building distance matrix... ', newline='')\r\n\r\n if approach == 1:\r\n self.distance_matrix = np.apply_along_axis(lambda x: Euclidean.mat_dist(x, self.matrix),\r\n 1,\r\n self.matrix)\r\n\r\n elif approach == 2:\r\n ndims = self.matrix.shape[1]\r\n\r\n temp_mat = np.zeros([self.matrix.shape[0], self.matrix.shape[0]], np.float32)\r\n\r\n for dim in range(ndims):\r\n arr = np.repeat(self.matrix[:, dim][:, np.newaxis], self.nsamp, 1)\r\n arr_ = arr.T\r\n temp_mat += (arr - arr_) ** 2\r\n\r\n self.distance_matrix = np.sqrt(temp_mat)\r\n\r\n else:\r\n raise ValueError('Unrecognized approach')\r\n\r\n if verbose:\r\n Opt.cprint('Done!')\r\n\r\n def proximity_filter(self,\r\n thresh=None,\r\n verbose=False):\r\n \"\"\"\r\n method to remove points based on proximity threshold\r\n :param thresh: proximity threshold (default: 90th percentile) valid values: 1-99\r\n :param verbose: If steps should be displayed\r\n :return: None\r\n \"\"\"\r\n if verbose:\r\n Opt.cprint('Applying proximity filter...')\r\n\r\n if thresh is None:\r\n thresh = self.cluster_center('percentile_90')\r\n elif type(thresh) in (int, float):\r\n thresh = self.cluster_center('percentile_{}'.format(str(int(thresh))))\r\n elif type(thresh) == str and 'percentile_' in thresh:\r\n thresh = self.cluster_center(thresh)\r\n else:\r\n if verbose:\r\n warnings.warn('Invalid thresh value.\\n Using default: 90th percentile centroid vector.')\r\n thresh = self.cluster_center('percentile_90')\r\n\r\n # number of close proximities associated with each element\r\n n_proxim = np.apply_along_axis(lambda x: np.count_nonzero((x > 0.0) & (x < thresh)),\r\n 0,\r\n self.distance_matrix)\r\n\r\n if verbose:\r\n Opt.cprint('Max group size : {} '.format(str(n_proxim.max())), newline='')\r\n Opt.cprint('Min group size : {} '.format(str(n_proxim.min())))\r\n\r\n # sort the indices in increasing order of n_proxim\r\n idx = []\r\n idx += np.argsort(n_proxim).tolist()\r\n idx_out = list()\r\n\r\n # find indices of elements that should be removed\r\n for ii in idx:\r\n if ii not in idx_out:\r\n arr = self.distance_matrix[ii, 0:(ii + 1)]\r\n temp_list = (np.where((arr < thresh) & (arr > 0.0))[0]).tolist()\r\n idx_out += temp_list\r\n idx_out = list(set(idx_out))\r\n\r\n # sort the indices in decreasing order for pop()\r\n pop_idx = sorted(list(set(idx_out)),\r\n reverse=True)\r\n\r\n if verbose:\r\n Opt.cprint('Removing {} elements...'.format(str(len(pop_idx))))\r\n\r\n for pop_id in pop_idx:\r\n self.samples.pop(pop_id)\r\n\r\n self.nsamp = len(self.samples)\r\n self.index = list(range(self.nsamp))\r\n\r\n def apply_proximity_filter(self,\r\n **kwargs):\r\n \"\"\"\r\n Apply proximity filter at a given threshold\r\n :param kwargs:\r\n thresh: proximity threshold (default: 90th percentile) valid values: 1-99\r\n default: 90\r\n :return: list of dictionaries\r\n \"\"\"\r\n self.calc_dist_matrix()\r\n self.proximity_filter(**kwargs)\r\n\r\n return self.samples\r\n","sub_path":"geosoupML/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":13808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"377626525","text":"import datajoint as dj\nimport numpy as np\nfrom numpy.lib import emath\nfrom functools import reduce\n\nfrom .common_session import Session # noqa: F401\n\nschema = dj.schema('common_interval')\n\n# TODO: ADD export to NWB function to save relevant intervals in an NWB file\n\n@schema\nclass IntervalList(dj.Manual):\n definition = \"\"\"\n # Time intervals used for analysis\n -> Session\n interval_list_name: varchar(200) # descriptive name of this interval list\n ---\n valid_times: longblob # numpy array with start and end times for each interval\n \"\"\"\n\n @classmethod\n def insert_from_nwbfile(cls, nwbf, *, nwb_file_name):\n \"\"\"Add each entry in the NWB file epochs table to the IntervalList table.\n\n The interval list name for each epoch is set to the first tag for the epoch.\n If the epoch has no tags, then 'interval_x' will be used as the interval list name, where x is the index\n (0-indexed) of the epoch in the epochs table.\n The start time and stop time of the epoch are stored in the valid_times field as a numpy array of\n [start time, stop time] for each epoch.\n\n Parameters\n ----------\n nwbf : pynwb.NWBFile\n The source NWB file object.\n nwb_file_name : str\n The file name of the NWB file, used as a primary key to the Session table.\n \"\"\"\n if nwbf.epochs is None:\n print('No epochs found in NWB file.')\n return\n epochs = nwbf.epochs.to_dataframe()\n for epoch_index, epoch_data in epochs.iterrows():\n epoch_dict = dict()\n epoch_dict['nwb_file_name'] = nwb_file_name\n if epoch_data.tags[0]:\n epoch_dict['interval_list_name'] = epoch_data.tags[0]\n else:\n epoch_dict['interval_list_name'] = 'interval_' + str(epoch_index)\n epoch_dict['valid_times'] = np.asarray(\n [[epoch_data.start_time, epoch_data.stop_time]])\n cls.insert1(epoch_dict, skip_duplicates=True)\n\n@schema\nclass SortInterval(dj.Manual):\n definition = \"\"\"\n -> Session\n sort_interval_name: varchar(200) # name for this interval\n ---\n sort_interval: longblob # 1D numpy array with start and end time for a single interval to be used for spike sorting\n \"\"\"\n\n\n# TODO: make all of the functions below faster if possible\ndef intervals_by_length(interval_list, min_length=0.0, max_length=1e10):\n \"\"\"Returns an interval list with only the intervals whose length is > min_length and < max_length\n\n Args:\n interval_list ((N,2) np.array): input interval list.\n min_length (float, optional): [minimum interval length in seconds]. Defaults to 0.0.\n max_length ([type], optional): [maximum interval length in seconds]. Defaults to 1e10.\n \"\"\"\n # get the length of each interval\n lengths = np.ravel(np.diff(interval_list))\n # return only intervals of the appropriate lengths\n return interval_list[np.logical_and(lengths > min_length, lengths < max_length)]\n\ndef interval_list_contains_ind(valid_times, timestamps):\n \"\"\"Returns the indices for the timestamps that are contained within the valid_times intervals\n\n :param valid_times: Array of [start, end] times\n :type valid_times: numpy array\n :param timestamps: list of timestamps\n :type timestamps: numpy array or list\n :return: indices of timestamps that are in one of the valid_times intervals\n \"\"\"\n ind = []\n for valid_time in valid_times:\n ind += np.ravel(np.argwhere(np.logical_and(timestamps >= valid_time[0],\n timestamps <= valid_time[1]))).tolist()\n return np.asarray(ind)\n\n\ndef interval_list_contains(valid_times, timestamps):\n \"\"\"Returns the timestamps that are contained within the valid_times intervals\n\n :param valid_times: Array of [start, end] times\n :type valid_times: numpy array\n :param timestamps: list of timestamps\n :type timestamps: numpy array or list\n :return: numpy array of timestamps that are in one of the valid_times intervals\n \"\"\"\n ind = []\n for valid_time in valid_times:\n ind += np.ravel(np.argwhere(np.logical_and(timestamps >= valid_time[0],\n timestamps <= valid_time[1]))).tolist()\n return timestamps[ind]\n\n\ndef interval_list_excludes_ind(valid_times, timestamps):\n \"\"\"Returns the indices of the timestamps that are excluded from the valid_times intervals\n\n :param valid_times: Array of [start, end] times\n :type valid_times: numpy array\n :param timestamps: list of timestamps\n :type timestamps: numpy array or list\n :return: numpy array of timestamps that are in one of the valid_times intervals\n \"\"\"\n # add the first and last times to the list and creat a list of invalid intervals\n valid_times_list = np.ndarray.ravel(valid_times).tolist()\n valid_times_list.insert(0, timestamps[0] - 0.00001)\n valid_times_list.append(timestamps[-1] + 0.001)\n invalid_times = np.array(valid_times_list).reshape(-1, 2)\n # add the first and last timestamp indices\n ind = []\n for invalid_time in invalid_times:\n ind += np.ravel(np.argwhere(np.logical_and(timestamps > invalid_time[0],\n timestamps < invalid_time[1]))).tolist()\n return np.asarray(ind)\n\n\ndef interval_list_excludes(valid_times, timestamps):\n \"\"\"Returns the indices of the timestamps that are excluded from the valid_times intervals\n\n :param valid_times: Array of [start, end] times\n :type valid_times: numpy array\n :param timestamps: list of timestamps\n :type timestamps: numpy array or list\n :return: numpy array of timestamps that are in one of the valid_times intervals\n \"\"\"\n # add the first and last times to the list and creat a list of invalid intervals\n valid_times_list = np.ravel(valid_times).tolist()\n valid_times_list.insert(0, timestamps[0] - 0.00001)\n valid_times_list.append(timestamps[-1] + 0.00001)\n invalid_times = np.array(valid_times_list).reshape(-1, 2)\n # add the first and last timestamp indices\n ind = []\n for invalid_time in invalid_times:\n ind += np.ravel(np.argwhere(np.logical_and(timestamps > invalid_time[0],\n timestamps < invalid_time[1]))).tolist()\n return timestamps[ind]\n\ndef interval_list_intersect(interval_list1, interval_list2):\n \"\"\"Finds the intersections between two interval lists\n\n Parameters\n ----------\n interval_list1 : np.array, (N,2) where N = number of intervals\n interval_list2 : np.array, (N,2) where N = number of intervals\n\n Each interval is (start time, stop time)\n \n Returns\n -------\n interval_list: np.array, (N,2)\n \"\"\"\n \n if interval_list1.ndim==1:\n interval_list1 = np.expand_dims(interval_list1,0)\n else:\n interval_list1 = interval_list1[np.argsort(interval_list1[:,0])]\n interval_list1 = reduce(_union_concat, interval_list1)\n # the following check is needed in the case where the interval list is a single element (behavior of reduce)\n if interval_list1.ndim==1:\n interval_list1 = np.expand_dims(interval_list1,0)\n \n if interval_list2.ndim==1:\n interval_list2 = np.expand_dims(interval_list2,0)\n else:\n interval_list2 = interval_list2[np.argsort(interval_list2[:,0])]\n interval_list2 = reduce(_union_concat, interval_list2)\n # the following check is needed in the case where the interval list is a single element (behavior of reduce)\n if interval_list2.ndim==1:\n interval_list2 = np.expand_dims(interval_list2,0)\n\n intersecting_intervals = []\n for interval2 in interval_list2:\n for interval1 in interval_list1:\n if _intersection(interval2, interval1) is not None:\n intersecting_intervals.append(_intersection(interval1, interval2)) \n \n intersecting_intervals = np.asarray(intersecting_intervals)\n intersecting_intervals = intersecting_intervals[np.argsort(intersecting_intervals[:,0])]\n \n return intersecting_intervals\n\ndef _intersection(interval1, interval2):\n \"Takes the (set-theoretic) intersection of two intervals\"\n intersection = np.array([max([interval1[0],interval2[0]]),\n min([interval1[1],interval2[1]])])\n if intersection[1]>intersection[0]:\n return intersection\n else:\n return None\n \ndef _union(interval1, interval2):\n \"Takes the (set-theoretic) union of two intervals\"\n if _intersection(interval1, interval2) is None:\n return np.array([interval1, interval2])\n else:\n return np.array([min([interval1[0],interval2[0]]),\n max([interval1[1],interval2[1]])])\n\ndef _union_concat(interval_list, interval):\n \"\"\"Compares the last interval of the interval list to the given interval and\n * takes their union if overlapping\n * concatenates the interval to the interval list if not\n \n Recursively called with `reduce`.\n \"\"\"\n if interval_list.ndim==1:\n interval_list = np.expand_dims(interval_list, 0)\n if interval.ndim==1:\n interval = np.expand_dims(interval, 0)\n\n x = _union(interval_list[-1], interval[0])\n if x.ndim==1:\n x = np.expand_dims(x, 0)\n return np.concatenate((interval_list[:-1], x), axis=0)\n\ndef union_adjacent_index(interval1, interval2):\n \"\"\"unions two intervals that are adjacent in index\n e.g. [a,b] and [b+1, c] is converted to [a,c]\n if not adjacent, just concatenates interval2 at the end of interval1\n\n Parameters\n ----------\n interval1 : np.array\n [description]\n interval2 : np.array\n [description]\n \"\"\"\n if interval1.ndim==1:\n interval1 = np.expand_dims(interval1, 0)\n if interval2.ndim==1:\n interval2 = np.expand_dims(interval2, 0)\n\n if interval1[-1][1]+1 == interval2[0][0] or interval2[0][1]+1 == interval1[-1][0]:\n x = np.array([[np.min([interval1[-1][0],interval2[0][0]]), \n np.max([interval1[-1][1],interval2[0][1]])]])\n return np.concatenate((interval1[:-1], x), axis=0)\n else:\n return np.concatenate((interval1, interval2),axis=0)\n\n# TODO: test interval_list_union code\ndef interval_list_union(interval_list1, interval_list2, min_length=0.0, max_length=1e10):\n \"\"\"Finds the union (all times in one or both) for two interval lists\n\n :param interval_list1: The first interval list\n :type interval_list1: numpy array of intervals [start, stop]\n :param interval_list2: The second interval list\n :type interval_list2: numpy array of intervals [start, stop]\n :param min_length: optional minimum length of interval for inclusion in output, default 0.0\n :type min_length: float\n :param max_length: optional maximum length of interval for inclusion in output, default 1e10\n :type max_length: float\n :return: interval_list\n :rtype: numpy array of intervals [start, stop]\n \"\"\"\n # return np.array([min(interval_list1[0],interval_list2[0]),\n # max(interval_list1[1],interval_list2[1])])\n interval_list1 = np.ravel(interval_list1)\n # create a parallel list where 1 indicates the start and -1 the end of an interval\n interval_list1_start_end = np.ones(interval_list1.shape)\n interval_list1_start_end[1::2] = -1\n\n interval_list2 = np.ravel(interval_list2)\n # create a parallel list for the second interval where 1 indicates the start and -1 the end of an interval\n interval_list2_start_end = np.ones(interval_list2.shape)\n interval_list2_start_end[1::2] = -1\n\n # concatenate the two lists so we can resort the intervals and apply the same sorting to the start-end arrays\n combined_intervals = np.concatenate((interval_list1, interval_list2))\n ss = np.concatenate((interval_list1_start_end, interval_list2_start_end))\n sort_ind = np.argsort(combined_intervals)\n combined_intervals = combined_intervals[sort_ind]\n # a cumulative sum of 1 indicates the beginning of a joint interval; a cumulative sum of 0 indicates the end\n union_starts = np.ravel(np.array(np.where(np.cumsum(ss[sort_ind]) == 1)))\n union_stops = np.ravel(np.array(np.where(np.cumsum(ss[sort_ind]) == 0)))\n union = []\n for start, stop in zip(union_starts, union_stops):\n union.append([combined_intervals[start], combined_intervals[stop]])\n return np.asarray(union)\n\ndef interval_list_censor(interval_list, timestamps):\n \"\"\"returns a new interval list that starts and ends at the first and last timestamp\n\n Args:\n interval_list (numpy array of intervals [start, stop]): interval list from IntervalList valid times\n timestamps (numpy array or list): timestamp list\n\n Returns:\n interval_list (numpy array of intervals [start, stop])\n \"\"\"\n # check that all timestamps are in the interval list\n assert len(interval_list_contains_ind(interval_list, timestamps)) == len(timestamps), 'interval_list must contain all timestamps' \n \n timestamps_interval = np.asarray([[timestamps[0], timestamps[-1]]])\n return interval_list_intersect(interval_list, timestamps_interval) \n","sub_path":"src/nwb_datajoint/common/common_interval.py","file_name":"common_interval.py","file_ext":"py","file_size_in_byte":13252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"147485368","text":"# -*- coding: utf-8 -*-\nimport os\n\n\nclass Config(object):\n APP_ROOT = os.path.abspath(os.path.dirname(__file__))\n PROJECT_ROOT = os.path.abspath(os.path.join(APP_ROOT, os.pardir))\n WTF_CSRF_ENABLED = True\n SECRET_KEY = os.environ.get('SECRET_KEY')\n SECURITY_PASSWORD_SALT = SECRET_KEY\n SECURITY_PASSWORD_HASH = os.environ.get('SECURITY_PASSWORD_HASH', 'bcrypt')\n MONGODB_SETTINGS = {\n 'host': os.environ.get('MONGO_URI')\n }\n MAIL_SERVER = os.environ.get('MAILGUN_SMTP_SERVER')\n MAIL_PORT = os.environ.get('MAILGUN_SMTP_PORT')\n MAIL_USERNAME = os.environ.get('MAILGUN_SMTP_LOGIN')\n MAIL_PASSWORD = os.environ.get('MAILGUN_SMTP_PASSWORD')\n MAILGUN_API_KEY = os.environ.get('MAILGUN_API_KEY')\n HOST = os.environ.get('HOST', 'localhost')\n EMAIL_DOMAIN = os.environ.get('EMAIL_DOMAIN', 'mylog.civilservice.digital')\n\n OIDC = {\n # 'google': {\n # 'domain': 'accounts.google.com',\n # 'client': {\n # 'client_id': os.environ.get('GOOG_CLIENT_ID'),\n # 'client_secret': os.environ.get('GOOG_CLIENT_SECRET'),\n # 'redirect_uri': os.environ.get(\n # 'GOOG_OIDC_CALLBACK_URL',\n # 'http://localhost:8000/login/callback')\n # }\n # },\n 'auth0': {\n 'domain': 'xgs.eu.auth0.com',\n 'client': {\n 'client_id': os.environ.get('AUTH0_CLIENT_ID'),\n 'client_secret': os.environ.get('AUTH0_CLIENT_SECRET'),\n 'redirect_uri': os.environ.get(\n 'AUTH0_CALLBACK_URL',\n 'http://localhost:8000/login/callback')\n }\n }\n }\n\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n WTF_CSRF_ENABLED = False\n SECRET_KEY = os.environ.get('SECRET_KEY', 'local-dev-not-secret')\n\n\nclass DockerConfig(DevelopmentConfig):\n # is this guaranteed to be up yet cause it's linked?\n host = os.environ.get('DB_PORT_27017_TCP_ADDR')\n port = int(os.environ.get('DB_PORT_27017_TCP_PORT', 27017))\n MONGODB_SETTINGS = {\n 'host': host,\n 'db': 'xgs_performance_reviews',\n 'port': port\n }\n OIDC = {\n 'google': {\n 'domain': 'accounts.google.com',\n 'client': {\n 'client_id': os.environ.get('GOOG_CLIENT_ID'),\n 'client_secret': os.environ.get('GOOG_CLIENT_SECRET'),\n 'redirect_uri': 'http://192.168.99.100:8000/login/callback'\n }\n },\n 'auth0': {\n 'domain': 'xgs.eu.auth0.com',\n 'client': {\n 'client_id': os.environ.get('AUTH0_CLIENT_ID'),\n 'client_secret': os.environ.get('AUTH0_CLIENT_SECRET'),\n 'redirect_uri': 'http://192.168.99.100:8000/login/callback'\n }\n }\n }\n\n\nclass TestConfig(DevelopmentConfig):\n TESTING = True\n","sub_path":"application/config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"397316460","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom .models import Course\nfrom django.contrib import messages\nfrom django.contrib.messages import get_messages\n\n# Create your views here.\ndef index(request):\n\tcontext = {\n\t 'courses': Course.objects.all(),\n\t 'messages': get_messages(request)\n\t}\n\treturn render(request, 'courses/index.html', context)\n\ndef add(request):\n\tif request.method == \"POST\":\n\t\terrors = Course.objects.basic_validator(request.POST)\n\t\tif len(errors):\n\t\t\tfor tag,error in errors.iteritems():\n\t\t\t\tmessages.error(request, error, extra_tags=tag)\n\t\t\treturn redirect('/')\n\t\telse:\n\t\t\tCourse.objects.create(name=request.POST['name'], description=request.POST['desc'])\n\t\t\treturn redirect('/')\n\telse:\n\t\treturn redirect('/')\n\ndef destroy(request, id):\n\tcontext = {\n\t\t'course': Course.objects.get(id=id)\n\t}\n\treturn render(request, 'courses/destroy.html', context)\n\ndef remove(request, id):\n\tif request.method == \"POST\":\n\t\tcourse = Course.objects.get(id=id)\n\t\tcourse.delete()\n\t\treturn redirect('/')\n\telse:\n\t\treturn redirect('/')","sub_path":"apps/courses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"443973466","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 11 15:55:25 2016\n\n@author: Payden McBee\n\"\"\"\n\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\n\nfrom sklearn import svm \nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.lda import LDA\n\ndef main():\n \n for question in range(3,18):\n \n print(\"Question \", question, \" Percent Accuracy\")\n\n trainingSet_features, trainingSet_labels, testSet_features, testSet_labels = loadTrainingAndTestData(question)\n #print(len(trainingSet_features))\n #print(trainingSet_labels)\n #print(len(testSet_features))\n #print(len(testSet_labels))\n \n #print(trainingSet_labels)\n nnC = KNeighborsClassifier(n_neighbors=5)\n nnC.fit(trainingSet_features, trainingSet_labels) \n nnC_predictions = nnC.predict(testSet_features)\n print(\"Nearest Neighbor: %.2f\" % (100*accuracy_score(testSet_labels,nnC_predictions)),\"%\")\n\n svmC = svm.SVC()\n svmC.fit(trainingSet_features, trainingSet_labels) \n svmCpredictions = svmC.predict(testSet_features)\n print(\"Support Vector Machines: %.2f\" % (100*accuracy_score(testSet_labels,svmCpredictions)),\"%\")\n\n rfC = RandomForestClassifier(n_estimators=100)\n rfC.fit(trainingSet_features, trainingSet_labels) \n rfC_predictions = rfC.predict(testSet_features)\n print(\"Random Forrest: %.2f\" % (100*accuracy_score(testSet_labels,rfC_predictions)),\"%\")\n\n ldaC = LDA(solver='lsqr')\n ldaC.fit(trainingSet_features, trainingSet_labels) \n ldaC_predictions = ldaC.predict(testSet_features)\n print(\"Linear Discriminant Analysis Classifier: %.2f\" % (100*accuracy_score(testSet_labels,ldaC_predictions)),\"%\")\n\ndef loadTrainingAndTestData(question):\n \n trainingSet_features_str = 'trainingSet' + str(question) + 'features.npy'\n trainingSet_labels_str = 'trainingSet' + str(question) + 'labels.npy'\n testSet_features_str = 'testSet' + str(question) + 'features.npy'\n testSet_labels_str = 'testSet' + str(question) + 'labels.npy'\n trainingSet_features = np.load(trainingSet_features_str)\n trainingSet_labels = np.load(trainingSet_labels_str)\n testSet_features = np.load(testSet_features_str)\n testSet_labels = np.load(testSet_labels_str)\n return trainingSet_features, trainingSet_labels, testSet_features, testSet_labels\n \nif __name__ == '__main__':\n main()","sub_path":"classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"7751969","text":"# @Time : 2018/7/5 10:13\n# @Author : cap\n# @FileName: lenet_for_mnist2.py\n# @Software: PyCharm Community Edition\n# @introduction:\n# 添加learning-rate优化,添加regulation优化,添加滑动评价优化\n# 二次优化\n# 第一层:conv1--relu1-pool1\n# 第二层;conv2--reul2-pool2\n# 第三层:fc1-relu\n# 第四层(输出层):fc2\n# 运行5000次后,validation accuracy:0.98280;test accuracy:98190\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n# 输入输出参数\n# 输入图边长\ninput_size = 28\n# 黑白图\ninput_channel = 1\n# 输出节点数\noutput_nodes = 10\n\n# 第一层参数\n# 第一层卷积核大小\nconv_size = 5\n# 卷积核深度\nlayer1_output = 6\n\n# 第二层卷积核深度\nlayer2_output = 16\n\n# 第三层全连接节点数\nfc_nodes = 512\n\n# 卷积步长\nconv_stride = 1\n\n# 池化层核大小和步长\npool_size = 2\npool_stride = 2\n\n# 学习率\nlearning_rate = 0.01\n# 学习衰减率\nlearning_dency = 0.99\n\n# 正则化\nregulation_rate = 0.0001\n\n# 滑动平均\naverage_dency = 0.99\n\n# batch\nbatch_size = 128\n# 迭代次数\nsteps = 10000\n\n\n# 定义计算图\ndef inference(x, regularizer=None):\n # 第一层,一个[5, 5, 1, 6]的卷积层, 一个[1, 2, 2, 1]的池化层,一个relu\n # 输入为[batch, 28, 28 ,1]黑白图, 输出为[batch, 14, 14, 6]\n with tf.variable_scope('layer1'):\n weight = tf.get_variable('weight', [conv_size, conv_size, input_channel, layer1_output], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1))\n if regularizer is not None:\n tf.add_to_collection('losses', regularizer(weight))\n\n biases = tf.get_variable('biases', [layer1_output], dtype=tf.float32, initializer=tf.constant_initializer(0.1))\n\n conv1 = tf.nn.conv2d(x, weight, [1, conv_stride, conv_stride, 1], padding='SAME')\n conv1_out = tf.nn.relu(tf.nn.bias_add(conv1, biases))\n\n pool1 = tf.nn.max_pool(conv1_out, [1, pool_size, pool_size, 1], [1, pool_stride, pool_stride, 1], padding='SAME')\n # 第二层,一个[5, 5, 6, 16]的卷积层, 一个[1, 2, 2, 1]的池化层,一个relu\n # 输入为[batch, 14, 14 ,6]黑白图, 输出为[batch, 7, 7, 16]\n\n with tf.variable_scope('layer2'):\n weight2 = tf.get_variable('weight', [conv_size, conv_size, layer1_output, layer2_output], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1))\n if regularizer is not None:\n tf.add_to_collection('losses', regularizer(weight2))\n\n biases2 = tf.get_variable('biases', [layer2_output], dtype=tf.float32, initializer=tf.constant_initializer(0.1))\n\n conv2 = tf.nn.conv2d(pool1, weight2, [1, conv_stride, conv_stride, 1], padding='SAME')\n conv2_out = tf.nn.relu(tf.nn.bias_add(conv2, biases2))\n\n pool2 = tf.nn.max_pool(conv2_out, [1, pool_size, pool_size, 1], [1, pool_stride, pool_stride, 1], padding='SAME')\n # 第三层,由于还剩7层,直接开始两个全连接层\n # 全连接层1,一个relu\n # reshape输入数据为[batch, 7*7*16, 512],输出为[batch, 512]\n with tf.variable_scope('layer3'):\n # 将四维数据转成二维数据\n pool2_shape = pool2.shape\n layer3_input_nodes = pool2_shape[1] * pool2_shape[2] * pool2_shape[3]\n pool2 = tf.reshape(pool2, [-1, layer3_input_nodes])\n\n weight3 = tf.get_variable('weight', [layer3_input_nodes, fc_nodes], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1))\n if regularizer is not None:\n tf.add_to_collection('losses', regularizer(weight3))\n\n biases3 = tf.get_variable('biases', [fc_nodes], dtype=tf.float32, initializer=tf.constant_initializer(0.1))\n fc1 = tf.matmul(pool2, weight3)\n fc1_out = tf.nn.relu(tf.add(fc1, biases3))\n\n # 全连接层2\n # 输入为[batch, 512],输出为[512, 10]\n with tf.variable_scope('layer4'):\n weight4 = tf.get_variable('weight', [fc_nodes, output_nodes], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1))\n if regularizer is not None:\n tf.add_to_collection('losses', regularizer(weight4))\n\n biases4 = tf.get_variable('biases', [output_nodes], dtype=tf.float32, initializer=tf.constant_initializer(0.1))\n\n fc2 = tf.matmul(fc1_out, weight4) + biases4\n\n return fc2\n\n\n# train\ndef train(mnist):\n x = tf.placeholder(dtype=tf.float32, shape=[None, input_size, input_size, input_channel], name='x')\n y = tf.placeholder(dtype=tf.float32, shape=[None, output_nodes], name='y')\n\n # 添加正则项,只对weight操作\n regularizer = tf.contrib.layers.l2_regularizer(regulation_rate)\n logit = inference(x, regularizer)\n cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logit, labels=tf.argmax(y, 1)))\n loss = cost + tf.add_n(tf.get_collection('losses'))\n\n # 学习率优化,创建global\n global_step = tf.Variable(0, trainable=False)\n learning_rate_new = tf.train.exponential_decay(learning_rate,\n global_step,\n mnist.train.num_examples / batch_size,\n learning_dency)\n\n # 对参数滑动平均优化\n variable_average = tf.train.ExponentialMovingAverage(average_dency, global_step)\n average_op = variable_average.apply(tf.trainable_variables())\n\n step_op = tf.train.GradientDescentOptimizer(learning_rate_new).minimize(loss, global_step)\n\n with tf.control_dependencies([step_op, average_op]):\n train_op = tf.no_op('train')\n\n correct = tf.equal(tf.argmax(logit, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n # validation_x = mnist.validation.images\n validation_x = np.reshape(mnist.validation.images, [-1, input_size, input_size ,input_channel])\n validation_y = mnist.validation.labels\n\n # test_x = mnist.test.images\n test_x = np.reshape(mnist.test.images, [-1, input_size, input_size, input_channel])\n test_y = mnist.test.labels\n for i in range(steps):\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n batch_x = np.reshape(batch_x, [-1, input_size, input_size, input_channel])\n\n _, step = sess.run([train_op, global_step], feed_dict={x: batch_x, y: batch_y})\n if step % 1000 == 0:\n validation_accu = sess.run(accuracy, feed_dict={x: validation_x, y:validation_y})\n print('After {} steps, accuracy:{:.5f}'.format(step, validation_accu))\n\n print('train finished!')\n test_accu = sess.run(accuracy, feed_dict={x: test_x, y: test_y})\n print('Test accuracy:%.5f' % test_accu)\n\n\n# main\ndef main(args=None):\n mnist = input_data.read_data_sets('D:/softfiles/workspace/data/tensorflow/data/', one_hot=True)\n train(mnist)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"books/tensorflow_jishujiexiyushijian/lenet_for_mnist/lenet_for_mnist2.py","file_name":"lenet_for_mnist2.py","file_ext":"py","file_size_in_byte":7072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"367640376","text":"### -*- coding: utf-8 -*-\n###\n### Export data from TUFS\n###\n\n### Luis wants list of 12 tsv for wn linking\n### DICNAME pos sense lang|lemma,lang|lemma (8 empty)\n###\n\n\nfrom collections import defaultdict as dd\nimport nltk\nfrom nltk.corpus import wordnet as wn\nfrom iso639 import languages\nimport re\nimport sys\n\ndatadir = 'tufsdata' # where the tufs data is downloaded to \nlog = open('munge.log', 'w')\n\n\n\ndef read_bunrui_names(filename):\n \"\"\"\n read the names of the bunrui concepts \n we have them in four languages: en, ms, my, ja\n\n bunrui_name['4.50']['en'] = 'Animal calls'\n \n >>> bn = read_bunrui_names('tufsdata/bunrui_names.tsv')\n >>> dict(bn['4.50'])\n {'en': 'Animal calls', 'ms': 'Bunyi haiwan', 'my': 'တိရစ္တာန်များ၏အော်မြည်သံ', 'ja': '動物の鳴き声'}\n \"\"\"\n bunrui_name = dd(lambda: dd(str))\n fh = open(filename)\n for l in fh:\n #print(l)\n (code, en, ms, my, ja) = l.strip().split(\"\\t\")\n if code == 'Code':\n continue\n bunrui_name[code]['en'] = en\n bunrui_name[code]['ms'] = ms\n bunrui_name[code]['my'] = my\n bunrui_name[code]['ja'] = ja\n return bunrui_name\n\ndef scrub(cell):\n \"\"\"\n return a cleaned cell\n \"\"\"\n cell = None if cell == '\\\\N' else cell\n return cell\n\ndef read_tables(datadir, lang):\n \"\"\"Put all the data for language in a table\n the key is the table name, \n the first row contains the column names\n the following rows have the values\n \n If the data is '\\\\N', replace with None.\n Otherwise each element is a string.\n\n >>> data = read_tables('tufsdata', 'en') \n >>> data['t_bunrui'][:3]\n [['bunrui_no', 'chukoumoku'], ['1.10', '事柄'], ['1.11', '類']]\n >>> data['t_word'][:2]\n [['id', 'basic', 'selected', 'index_char', 'sort_order'], \n ['1208', 'word', '1', 'W', None]]\n\n \"\"\"\n data = dd(list)\n fh = datadir + \"/vmod_{}.sql\".format(lang)\n state = None\n for l in open(fh):\n if 'COPY' in l:\n row = l[5:-14].split(' (')\n #print(row)\n state = row[0]\n data[state].append(row[1].split(', '))\n elif l.startswith(r'\\.'):\n state = None\n elif state:\n data[state].append([scrub(c) for c in l.strip().split('\\t')])\n \n return data\n\ndef fetch_data(datadir,langs):\n \"\"\"\n Get the data for all the languages\n data = fetch_data('tufsdata', ['en', 'ja'])\n\n >>> data = fetch_data('tufsdata', ['en', 'ja'])\n >>> data['ja']['t_word'][:2]\n [['id', 'basic', 'selected', 'index_char', 'sort_order'], \n ['1781', '東', '1', 'ひ', None]]\n >>> data['en']['t_word'][:2]\n [['id', 'basic', 'selected', 'index_char', 'sort_order'], \n ['1208', 'word', '1', 'W', None]]\n\n \"\"\"\n alldata = dict()\n for l in langs:\n alldata[l] = read_tables('tufsdata', l) \n return alldata\n\ndef get_words(data):\n \"\"\"\n get information about words, senses and more from the tables.\n\n word[lang][wid] = form \n wid is language specific\n wid can be used to access the pronunciation\n url = 'http://www.coelang.tufs.ac.jp/mt/{}/vmod/sound/word/word_{}.mp3'.format(lang,wid)\n\n >>> data = fetch_data('tufsdata', ['en', 'ja'])\n >>> word = get_words(data)\n >>> word['en']['946'] \n 'post office'\n >>> word['ja']['946']\n '写真'\n\n \"\"\"\n word = dd(lambda: dd(str))\n for lang in data.keys():\n ### link words to their ids\n for (id, basic, selected, index_char, sort_order) in data[lang]['t_word'][1:]:\n # only keep selected words\n if selected != \"0\":\n word[lang][id] = basic.strip()\n return word\n\ndef get_usage(data):\n \"\"\"\n usage is like a gloss of the meaning\n\n usage[lang][uid] = (wid, usage)\n\n >>> data = fetch_data('tufsdata', ['en', 'ja'])\n >>> usage = get_usage(data)\n >>> usage['en']['215'] # usage ID\n ('946', '郵便局') \n >>> usage['ja']['297']\n ('946', '【よみ】; しゃしん;【意味】; photograph')\n\n Note: escaped backslashes '\\\\' to '\\\\\\\\'\n\n \"\"\"\n usage = dict()\n for lang in data.keys():\n usage[lang] = dict()\n for (usage_id, word_id, explanation,\n disp_priority, selected) in data[lang]['t_usage'][1:]:\n if selected != 0:\n ## check for duplicates (this never happened)\n if usage_id in usage[lang]:\n print('WARNING usage_id used twice', usage_id, explanation, usage[lang][usage_id][1],\n file=sys.stderr)\n explanation = re.sub(r'(\\\\n)+', ';', str(explanation)).strip(';').strip()\n usage[lang][usage_id] = (word_id, explanation)\n return usage\n\n\ndef get_concepts(data):\n \"\"\"\n this links concepts to usage and more\n\n ## map the language internal usage id to the shared ID\n u2t[uid] = tid \n\n >>> data = fetch_data('tufsdata', ['en', 'ja'])\n >>> u2t, bunrui_n, bunrui_c, bunrui_u = get_concepts(data)\n >>> u2t['ja']['297']\n '35159'\n >>> u2t['en']['297']\n '11443'\n\n ## bunrui word for this concept\n\n >>> bunrui_n['35159']\n '写真'\n >>> bunrui_n['23439']\n '郵便局'\n\n ## bunrui code for this concept\n\n >>> bunrui_c['35159']\n '1.3220'\n >>> bunrui_c['23439']\n '1.2720'\n\n ## bunrui usages for this concept\n\n >>> bunrui_u['35159']['en']\n ['454']\n >>> bunrui_u['23439']['ja']\n ['660']\n\n \"\"\"\n u2t = dd(dict)\n\n ###\n ### The key is the classified_id\n ###\n bunrui = dict()\n bunrui_n = dict() #\n bunrui_c = dict() #t[50788] = '1.431' \n bunrui_u = dd(lambda: dd(list)) # usage_id\n # from which we can get (word, wordid, explanation)\n #bunrui_we = dd(lambda: dd(list)) # explanation\n #bunrui_e = dd(lambda: dd(list)) # examples\n #super_w = dd(lambda: dd(list)) # super_w['1.40'][lang] = [w1, w2]\n\n for lang in data.keys():\n for (usage_id, classified_id, bunrui_no, chukoumoku_no, rui,\n bumon, chukoumoku, bunruikoumoku, midasi, hontai,\n yomirow) in data[lang]['t_usage_classified_rel'][1:]:\n # usage_id is the language internal thing\n # classified_id is the shared id (we call it the TUFS ID)\n #\n # links the usage_id to the supertype (and gives information about that)\n # bunrui[23439] = '郵便局' name of category\n # bunrui_t[23439] = 1.272 number of category (rounded poorly in the db)\n # bunrui_w[23439] = [('post office', 946, '郵便局'), ..\n # super_w[23439] = [] list of words used by this supertype\n u2t[lang][usage_id] = classified_id ## map the language internal usage id to the tufs ID\n bunrui_n[classified_id] = midasi ## name of category, not language dependant\n bunrui_c[classified_id] = str(round(float(bunrui_no), 4)).ljust(6,'0')\n bunrui_u[classified_id][lang].append(usage_id)\n #bunrui_w[classified_id][lang].append((word[lang][usage[usage_id][0]],\n # usage[usage_id][0],\n # usage[usage_id][1]))\n #super_w[bunrui_t[classified_id][:4]][lang].append(word[lang][usage[usage_id][0]]) \n return u2t, bunrui_n, bunrui_c, bunrui_u\n\n\ndef get_instances(data):\n \"\"\"\n this gets the example sentences\n many also have translations into Japanese\n # instances (for examples)\n # inst[lang][iid] = (form, trans)\n\n >>> data = fetch_data('tufsdata', ['en', 'ja'])\n >>> inst, usage_inst = get_instances(data)\n >>> usage_inst['en']['215']\n ['859']\n\n # iid (instance ID) also links to pronounciation\n # url = 'http://www.coelang.tufs.ac.jp/mt/{}/vmod/sound/inst/inst_{}.mp3'.format(lang,iid)\n # usage_inst[usage_id] = inst_id\n\n >>> inst['en']['859']\n ('I went to the post office to buy some stamps.',\n '私は郵便局に切手を買いに行った。')\n\n \"\"\"\n inst = dd(lambda: dd(tuple))\n usage_inst = dd(lambda: dd(list))\n for lang in data.keys():\n ## get the examples for each instance\n for (iid, targetlanguage, trans, function, pronun, explanation,\n module_id, xml_file_name, xpath, web_url, usage_id_rel,\n selected) in data[lang]['t_instance'][1:]:\n if selected == '1': #selected\n if targetlanguage.strip('\\\\n'): #only save if there is an example\n inst[lang][iid] = (targetlanguage.strip('\\\\n'),\n str(trans).strip('\\\\n'))\n ## get the examples for each usage\n for (uiid, usage_id, inst_id, disp_priority,\n token, token_index, ptoken, ptoken_indexrow) in data[lang]['t_usage_inst_rel']:\n #print(lang, uiid, usage_id, inst_id, token, token_index, ptoken, ptoken_indexrow, sep='\\t')\n if inst_id in inst[lang]: # only add if there is an example\n usage_inst[lang][usage_id].append(inst_id)\n \n return inst, usage_inst\n\ndef clean(word, lang):\n \"\"\"return a list of (word, thing:value)\n\n >>> clean('hot', 'en') \n [('hot', '')]\n >>> clean('辣 là', 'zh')\n [('辣', 'orth:pīnyīn là')]\n >>> clean('طيّب (ـين)‏', 'as') # note wierd ltr\n [('طيّب', 'morph:pl ـين')]\n \"\"\"\n \n ### delete trailing newline and left-to-right mark\n if word.endswith('\\\\n'):\n word = word[:-3]\n word=word.replace('\\u200f','')\n cleaned = []\n\n ### too hard to process\n if word in [\"(…이/가) 되다\",\n \"sala (de aula)\",\n \"-arak/-erek (yürü-yerek)\",\n \"poderia (fazer) …\"]:\n return [(word, '')]\n\n ### split and handle stuff in brackets\n \n for w in re.split(r'[/,]\\s*',word):\n ### split on '/' or ',', not perfect but ok\n m = re.match(r'(.+) \\((.+?)\\)', w)\n if m: # remember bracketed stuff\n if lang in ['ar', 'as']: # Arabic gives plural\n cleaned.append((m.group(1), 'morph:pl '+m.group(2)))\n elif lang in ['ja']: # it is a footnotemark\n cleaned.append((m.group(1), ''))\n elif lang in ['ms']: # Malay gives us roots\n if m.group(1)[0] == 'm':\n cleaned.append((m.group(2), 'morph:meN- '+m.group(1)))\n elif m.group(1)[0] == 'b':\n cleaned.append((m.group(2), 'morph:ber- '+m.group(1)))\n elif lang == 'zh': # split pinyin\n #print(w)\n #print('zh', w)\n zhs = w.split() # single or multi\n cleaned.append((zhs[0], 'orth:pīnyīn ' + zhs[1]))\n if len(zhs) > 2:\n print('ERROR in pinyin', file=log)\n else:\n cleaned.append((w, ''))\n # if cleaned != [(word, '')]:\n # print (\"CLEANED:\", lang, word, cleaned)\n return cleaned\n \n\n\n\ndef print_tsv(filename, data):\n \"\"\"\n print out the data as tsv\n # \"cid\", \"lang\", \"wid\", \"lemma\", \"meaning\", \"example\"\n \"\"\"\n word = get_words(data)\n usage = get_usage(data)\n u2t, bunrui_n, bunrui_c, bunrui_u = get_concepts(data)\n inst, usage_inst = get_instances(data) \n \n with open(filename,'w') as t:\n ## sense[tid][lang] = [(wid, explanation, iid), (wid, explanation, iid) ]\n for l in usage:\n for u in usage[l]:\n tufs_id = u2t[l][u] if u in u2t[l] else None\n # if u not in u2t[l]:\n # print ('WARNING unknown usage', l, u, usage[l][u][0],\n # usage[l][u][1], usage_inst[l][u], file=sys.stderr)\n w = word[l][usage[l][u][0]]\n if w == '':\n continue\n cleaned = []\n for (lem,typ) in clean(w,l):\n if not typ:\n cleaned.append(lem)\n else:\n cleaned.append(lem + ' (' + typ + ')')\n examples = []\n for iid in usage_inst[l][u]: \n examples.append('|'.join(inst[l][iid]))\n print(tufs_id, # tufs id\n l, # language\n usage[l][u][0], # wid\n \"; \".join(cleaned), #lemmas \n usage[l][u][1], # usage explanation\n \";\".join(usage_inst[l][u]), # iids \n \";;;\".join(examples) if examples else '', # examples \n sep='\\t', file=t)\n\ndef l2l3(l):\n \"\"\"convert the language name\n >>> l2l3('en')\n ('eng', 'English')\n >>> l2l3('as')\n ('apc', 'Arabic, Syrian')\n >>> l2l3('ar')\n ('arb', 'Arabic')\n \"\"\"\n try:\n if l == 'pb':\n language= 'Por., Brazil'\n l3 ='por'\n elif l == 'ms':\n language= 'Malay'\n l3='zsm'\n elif l == 'as':\n language= 'Arabic, Syrian'\n l3='apc'\n elif l == 'ar':\n language= 'Arabic'\n l3='arb'\n elif l == 'zh':\n language= 'Chinese, Mandarin'\n l3='cmn' \n else:\n language= languages.get(alpha2=l).name\n l3 = languages.get(alpha2=l).part3\n except:\n language=l\n l3='unk'\n return l3, language\n\n \n# def print_html(filename, data):\n# \"\"\"\n# print html\n# \"\"\"\n# with open(filename,'w') as t:\n \n# print(\"\"\"\n# \n# \n# \n# \"\"\", file=t)\n# print(\"\"\"\n#
\n#

Based on data from TUFS Open Language Resources\n#

This view created by Francis Bond\n# \n# \"\"\", file=t)\n\n # stats=dd(int)\n# for b in sorted(bunrui, key=lambda x: bunrui_t[x]):\n# ### messy html\n# tid = b\n# print(\"\"\"

{0} ({1}: {2}) id={3}, pos={4}

\n# \"\"\".format(bunrui[b], bunrui_t[b],\n# st[bunrui_t[b][:4]]['en'], b,\n# bunrui2pos[bunrui_t[b][0]]),\n# file=html)\n# print (\"{} ({}: {}) id={}\".format(bunrui[b], bunrui_t[b],\n# st[bunrui_t[b][:4]]['en'], b))\n# ws = [] # for dic matching\n# print(\"\"\" \\n\"\"\", file=html)\n \n# print (\"\"\" \n# \n# \n# \n# \n# \n# \"\"\", file=html)\n# #print (sense[tid].keys()\n# for l in sorted(sense[tid].keys()):\n# stats[l] += len(sense[tid][l])\n# (wid, explanation, iid) = sense[tid][l]\n# w = word[l][wid]\n# if w == '':\n# continue\n# cleaned = []\n# for (lem,typ) in clean(w,l):\n# if not typ:\n# cleaned.append(lem)\n# else:\n# cleaned.append(lem + ' (' + typ + ')')\n# ws.append(l2l3(l)[0] +'|' + lem)\n# ### print language\n# print(\"\"\" \\n\"\"\", file=html)\n# print(''.format(l2l3(l)[1],l),file=html)\n# # s= \n# # \n# #\t🔊\n# url='http://www.coelang.tufs.ac.jp/mt/{0}/vmod'.format(l)\n# print(\"\"\"\"\"\".format(url,\n# wid,\n# w),file=html)\n# print(\"\".format('; '.join(cleaned)),file=html)\n# print(''.format(explanation),file=html)\n# if inst[l][iid]:\n# print(\"\".format(url,\n# iid,\n# inst[l][iid][0],\n# inst[l][iid][1]),file=html)\n# else:\n# print('', file=html)\n# print(\"\"\" \\n\"\"\", file=html)\n# print(\"\"\"
LanguageLemmaCleanedMeaningExample
{}{2}\n# (🔊){}{}{2} (🔊)
{3}

\\n\"\"\", file=html)\n# ### output for LUIS\n# if ws:\n# sens=bunrui[b] + ':' + bunrui_t[b]\n# comment='tufs_id='+b\n# print('TUFS', bunrui2pos[bunrui_t[b][0]], sens,\n# ', '.join(ws),\n# comment, '', '', '', '', '', '', '', \n# sep='\\t',file=luis)\n# print(\"\"\"
\n#

Based on data from TUFS Open Language Resources\n#

This view created by Francis Bond\n# \n# \"\"\",\n# file=html)\n# html.close()\n \n\n \ndef main():\n langs = [\"ar\", \"as\", \"de\", \"en\", \"es\", \"fr\", \"id\",\n \"ja\", \n \"km\", \"ko\", \"lo\", \"mn\",\n \"ms\",\n \"my\",\n \"pb\", \"pt\", \"ru\", \"th\",\n \"tl\", \"tr\", \"ur\", \"vi\", \"zh\"]\n data = fetch_data(datadir, langs)\n print_tsv('tufs-vocab.tsv', data)\n #print_html('onew.html',data)\n return None\n\nif __name__ == \"__main__\":\n main()\n\n \n\n\n\n\n\n\n# # \n# bunrui2pos = dd(lambda: '?')\n# bunrui2pos['1'] = 'n'\n# bunrui2pos['2'] = 'v'\n# bunrui2pos['3'] = 'a'\n# bunrui2pos['4'] = 'r'\n\n\n\n\n# def main():\n# st =read_bunrui_names(datadir + \"/bunrui_names.tsv\")\n# luis =open ('luis-vocab.tsv','w')\n# html=open ('tufs-vocab.html','w')\n# print(\"\"\"\n# \n# \n# \"\"\",\n# file=html)\n \n# stats=dd(int)\n# for b in sorted(bunrui, key=lambda x: bunrui_t[x]):\n# ### messy html\n# tid = b\n# print(\"\"\"

{0} ({1}: {2}) id={3}, pos={4}

\n# \"\"\".format(bunrui[b], bunrui_t[b],\n# st[bunrui_t[b][:4]]['en'], b,\n# bunrui2pos[bunrui_t[b][0]]),\n# file=html)\n# print (\"{} ({}: {}) id={}\".format(bunrui[b], bunrui_t[b],\n# st[bunrui_t[b][:4]]['en'], b))\n# ws = [] # for dic matching\n# print(\"\"\"
\\n\"\"\", file=html)\n \n# print (\"\"\" \n# \n# \n# \n# \n# \n# \"\"\", file=html)\n# #print (sense[tid].keys()\n# for l in sorted(sense[tid].keys()):\n# stats[l] += len(sense[tid][l])\n# (wid, explanation, iid) = sense[tid][l]\n# w = word[l][wid]\n# if w == '':\n# continue\n# cleaned = []\n# for (lem,typ) in clean(w,l):\n# if not typ:\n# cleaned.append(lem)\n# else:\n# cleaned.append(lem + ' (' + typ + ')')\n# ws.append(l2l3(l)[0] +'|' + lem)\n# ### print language\n# print(\"\"\" \\n\"\"\", file=html)\n# print(''.format(l2l3(l)[1],l),file=html)\n# # s= \n# # \n# #\t🔊\n# url='http://www.coelang.tufs.ac.jp/mt/{0}/vmod'.format(l)\n# print(\"\"\"\"\"\".format(url,\n# wid,\n# w),file=html)\n# print(\"\".format('; '.join(cleaned)),file=html)\n# print(''.format(explanation),file=html)\n# if inst[l][iid]:\n# print(\"\".format(url,\n# iid,\n# inst[l][iid][0],\n# inst[l][iid][1]),file=html)\n# else:\n# print('', file=html)\n# print(\"\"\" \\n\"\"\", file=html)\n# print(\"\"\"
LanguageLemmaCleanedMeaningExample
{}{2}\n# (🔊){}{}{2} (🔊)
{3}

\\n\"\"\", file=html)\n# ### output for LUIS\n# if ws:\n# sens=bunrui[b] + ':' + bunrui_t[b]\n# comment='tufs_id='+b\n# print('TUFS', bunrui2pos[bunrui_t[b][0]], sens,\n# ', '.join(ws),\n# comment, '', '', '', '', '', '', '', \n# sep='\\t',file=luis)\n# print(\"\"\"
\n#

Based on data from TUFS Open Language Resources\n#

This view created by Francis Bond\n# \n# \"\"\",\n# file=html)\n# html.close()\n# luis.close()\n \n \n# fh =open('tufgoi.tex', 'w')\n# print(\"\\\\begin{tabular}{llrrrl} \", file=fh)\n# print(\"Language& & Concepts\\t& Words & \\% in WN & Comment \\\\\\\\\\n\\\\hline \", file=fh)\n# total = dd(int)\n# for l in sorted(stats.keys()):\n# l3, language=l2l3(l)\n# shared=set()\n# bad =0\n# for i in word[l]:\n# #w = clean(i, l)[0][0]\n# w = word[l][i]\n# if (not w) or w==\"\":\n# bad+=1\n# continue\n# w = clean(w,l)[0][0] \n# w_ = w.replace(' ','_')\n# try:\n# if wn.synsets(w, lang=l3) or wn.synsets(w_, lang=l3): \n# shared.add(w)\n# else:\n# print('\"{}\" not found in wn ({})'.format(w,l))\n# except:\n# True\n# print(\"{} & {}\\t&{:6,d}\\t&{:6,d} & {:d}\\\\\\\\\".format(language, l,\n# stats[l], len(word[l]),\n# round(100* len(shared)/(len(word[l])-bad))\n# ), file=fh)\n# total['words'] += len(word[l])\n# total['concepts'] += stats[l]\n# print(\"{}\\t&{:6,d}\\t&{:6,d} \\\\\\\\\".format('Total',\n# total['concepts'], total['words']), file=fh)\n# print(\"\\\\end{tabular}\", file=fh)\n# fh.close()\n \n# for sp in sorted(super_w.keys()):\n# lxn = dd(float)\n# for w in super_w[sp]['en']:\n# for l in wn.lemmas(w):\n# lxn[l.synset().lexname()] += l.count() + .5\n# print (sp, st[sp]['en'], \",\".join(super_w[sp]['en']), sep='\\t')\n# stp = (0, 'Unknown')\n# if len(lxn.items()) > 0:\n# stp=sorted([(f,w) for (w, f) in lxn.items()])[-1]\n \n# print ('', '', stp, sep='\\t')\n# #print ('', '', lxn, sep='\\t')\n \n# if __name__ == \"__main__\":\n# main()\n","sub_path":"munge.py","file_name":"munge.py","file_ext":"py","file_size_in_byte":23728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"500351120","text":"#\t-*-\tcoding:\tlatin-1\t-*-\nfrom django.shortcuts\timport\trender_to_response, redirect, get_object_or_404\nfrom django.core.urlresolvers\timport\treverse\nfrom django.template.context\timport\tRequestContext\nfrom sace.inventario.models import Producto, Inventario\nfrom sace.inventario.forms import ProductoForm, OperacionProductoForm\nfrom sace.centroeducativo.views import validar_usuario\n\ndef menu_principal_inventario(request):\n\treturn render_to_response('inventario_index.html', context_instance=RequestContext(request))\n\t\ndef registrar_producto(request):\n\tif request.method == 'GET':\n\t\tpf = ProductoForm()\n\t\treturn render_to_response('admin_producto.html',{'pf':pf,'admin_producto':'Registrar Producto','t_mod':False}, context_instance=RequestContext(request))\n\telse:\n\t\tcentro = validar_usuario(request.user)\n\t\tpf = ProductoForm(request.POST)\n\t\tif pf.is_valid():\n\t\t\tif Producto.objects.filter(centro=centro, codigo = pf.cleaned_data['codigo']).exists():\n\t\t\t\treturn render_to_response('admin_producto.html',{'pf':pf,'admin_producto':'Registrar Producto','errores_extra':u'Ya existe un producto con este código','t_mod':False}, context_instance=RequestContext(request))\n\t\t\t\n\t\t\ttmp_pf = pf.save(commit=False)\n\t\t\ttmp_pf.centro = centro\n\t\t\ttmp_pf.save()\n\t\t\tpf = ProductoForm()\n\t\t\t#print request.POST\n\t\t\tif request.POST.get('_ingresarotro','') == 'otro':\n\t\t\t\treturn render_to_response('admin_producto.html',{'exito':True,'pf':pf,'admin_producto':'Registrar Producto','t_mod':False}, context_instance=RequestContext(request))\n\t\t\telse:\n\t\t\t\treturn redirect(reverse('listar_producto'))\n\t\telse:\n\t\t\treturn render_to_response('admin_producto.html',{'pf':pf,'admin_producto':'Registrar Producto','t_mod':False}, context_instance=RequestContext(request))\n\t\t\t\ndef modificar_producto(request, mod_id):\n\tif request.method == 'GET':\n\t\tpf = ProductoForm(instance = get_object_or_404(Producto, pk=mod_id))\n\t\treturn render_to_response('admin_producto.html',{'p_pk':mod_id,'pf':pf,'admin_producto':'Modificar Producto','t_mod':True}, context_instance=RequestContext(request))\n\telse:\n\t\tcentro = validar_usuario(request.user)\n\t\tinstance = get_object_or_404(Producto, pk=mod_id)\n\t\tcod_act = instance.codigo\n\t\tpf = ProductoForm(request.POST, instance = instance)\n\t\tif pf.is_valid(): \n\t\t\tif Producto.objects.filter(centro=centro, codigo = pf.cleaned_data['codigo']).exists() and pf.cleaned_data['codigo'] != cod_act:\n\t\t\t\treturn render_to_response('admin_producto.html',{'p_pk':mod_id,'pf':pf,'admin_producto':'Modificar Producto','errores_extra':u'Ya existe un producto con este código','t_mod':True}, context_instance=RequestContext(request))\n\t\t\tpf.save()\n\t\t\treturn redirect(reverse('listar_producto'))\n\t\telse:\n\t\t\treturn render_to_response('admin_producto.html',{'p_pk':mod_id,'pf':pf,'admin_producto':'Modificar Producto','t_mod':True}, context_instance=RequestContext(request))\ndef listar_producto(request):\n\tcentro = validar_usuario(request.user)\n\tl_productos = Producto.objects.filter(centro=centro).order_by('codigo')\n\treturn render_to_response('listar_productos.html',{'l_productos':l_productos}, context_instance=RequestContext(request))\n\ndef inventario_productos(request):\n\tcentro = validar_usuario(request.user)\n\tinv_p = Producto.objects.filter(centro=centro)\n\treturn render_to_response('inventario_productos.html',{'inv_p':inv_p},context_instance=RequestContext(request))\n\t\ndef operacion_producto(request, tipo=None,id=None):\n\tadmin_operacion\t= ''\n\tif tipo == '1':\n\t\tadmin_operacion = 'Ingresar Producto'\n\telif tipo == '2':\n\t\tadmin_operacion = 'Egresar Producto'\n\n\tprod = get_object_or_404(Producto, pk=id)\n\n\tif request.method == 'GET':\n\t\topf = OperacionProductoForm()\n\t\treturn render_to_response('operacion_producto.html',{'admin_operacion':admin_operacion,'opf':opf,'prod':prod,'tipo':tipo},context_instance=RequestContext(request))\n\telse:\n\t\topf = OperacionProductoForm(request.POST)\n\t\tif opf.is_valid():\n\t\t\topf_tmp = opf.save(commit=False)\n\t\t\topf_tmp.producto = prod\n\t\t\topf_tmp.accion = tipo\n\t\t\topf_tmp.save()\n\t\t\tinv = Inventario.objects.filter(producto = prod)\n\t\t\tif inv.exists():\n\t\t\t\tif tipo == '1':\n\t\t\t\t\tcnt = inv[0].cantidad+opf_tmp.cantidad\n\t\t\t\t\tinv.update(cantidad=cnt)\n\t\t\t\telse:\n\t\t\t\t\tcnt = inv[0].cantidad-opf_tmp.cantidad\n\t\t\t\t\tinv.update(cantidad=cnt)\n\t\t\telse:\n\t\t\t\tInventario.objects.create(producto=prod,cantidad = opf_tmp.cantidad)\n\t\t\treturn redirect(reverse('listar_producto'))\n\t\telse:\n\t\t\treturn render_to_response('operacion_producto.html',{'admin_operacion':admin_operacion,'opf':opf,'prod':prod,'tipo':tipo},context_instance=RequestContext(request))\n\t\n\t\n\t","sub_path":"inventario/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"447769955","text":"import csv\nfrom weather_preprossessing import * #引用气象数据获取模块\nfrom tomorrow_transfer import *\nresult=[]\ntags=[]\n\ndef pollution_get(): #污染物监测数据获取\n flag = 0 # 是否需要该组数据的标签\n for day in range(20140513,20170610):\n pwd = \"/media/lordshi/Seagate Expansion Drive/全国空气质量/城市汇总/china_cities_\"+str(day)+\".csv\"\n try:\n file = open(pwd,\"r\")\n except:\n continue\n csv_reader = csv.reader(file)\n line_top = next(csv_reader)\n colune_index = line_top.index(\"杭州\")\n # print(line_top)\n data_get = [[line[colune_index]] for line in csv_reader]\n select_index = [0, 2, 4, 6, 8, 10, 12, 14]\n data_need = [day]\n for index in select_index:\n try:\n pollution_cate = data_get[index::15][12]\n except:\n print(day)\n flag=1\n continue\n #print(type(pollution_cate))\n if (len(pollution_cate[0]) == 0):\n flag = 1\n continue\n else:\n data_need += pollution_cate\n if(flag==0):\n result.append(data_need)\n file.close()\n flag = 0\n return result\n#days=[]\n\n\n\ndef tags_get(): #获取标签数据\n for pollution_situation in result:\n day_select = pollution_situation[0]\n day_tomorrow = tomorrow_trans(day_select)\n #days.append([day_select])\n #print(days)\n file_pwd = \"/media/lordshi/Seagate Expansion Drive/全国空气质量/城市汇总/china_cities_\" + str(day_tomorrow) + \".csv\"\n try:\n file_next_day = open(file_pwd,\"r\")\n except:\n print(\"Error-1!!!\")\n print(day_select)\n continue\n csv_reader_2 = csv.reader(file_next_day)\n line_top_2 = next(csv_reader_2)\n colune_index_2 = line_top_2.index(\"杭州\") #杭州所在list序号获取\n data_get_2 = [[line[colune_index_2]] for line in csv_reader_2]\n try:\n AQI_select=data_get_2[::15][12]\n except:\n print(\"Error-2!!!\")\n print(day_select)\n continue\n tags_line=[day_select]+[AQI_select]\n tags.append(tags_line)\n\ndef combine_pollution_and_weather(): #污染物监测数据与气象数据结合\n pollution_result = pollution_get()\n #print(pollution_result)\n weather_info = weather_info_get()\n #print(weather_info)\n for pollution_list in pollution_result:\n day_ = pollution_list[0]\n try:\n day_weather_info = weather_info[day_]\n except:\n print(\"Can't find day \"+str(day_))\n #pollution_result.remove(pollution_list) 这里的相关关系还要考虑一下,实在不行可以删掉一些数据\n continue\n pollution_list += day_weather_info\n return pollution_result\n\nif(__name__==\"__main__\"):\n input_info_get = combine_pollution_and_weather()\n #print(pollution_result)\n #print(tags)\n # print(result)\n file_out_without_tags = open(\"./data/pre_processing_result.csv\",\"w\")\n csv_writer = csv.writer(file_out_without_tags)\n for row in result:\n csv_writer.writerow(row)\n file_out_without_tags.close()\n","sub_path":"data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"541187218","text":"import math\n\nimport numpy as np\nfrom scipy.fftpack import fft, ifft\nimport matplotlib.pyplot as plt\nfrom matplotlib.pylab import mpl\nimport os\n\n\ndef to_bin(value, num): # 十进制数据,二进制位宽\n bin_chars = \"\"\n temp = value\n for i in range(num):\n bin_char = bin(temp % 2)[-1]\n temp = temp // 2\n bin_chars = bin_char + bin_chars\n return bin_chars.upper() # 输出指定位宽的二进制字符串\n\n\nmpl.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文\nmpl.rcParams['axes.unicode_minus'] = False # 显示负号\n\ntest_y = []\nsignal_freq = 64000 # 720KHz\nsampling_rate = 23040000 # 23.04MHz\n\n\nN = 1024\n# 是否写文件?1->写;0->不写\nflag = 0\n# 相位移动\nsignal_phase = 0\nprint(signal_phase)\n\n# 采样点选择1400个,因为设置的信号频率分量最高为600赫兹,根据采样定理知采样频率要大于信号频率2倍,所以这里设置采样频率为1400赫兹(即一秒内有1400个采样点,一样意思的)\n# x = np.linspace(0, 1, sampling_rate)\n# temp = 1/sampling_rate\nx = np.linspace(0, 1, sampling_rate)\n\n# 设置需要采样的信号,频率为signal_freq\n# y = 1 * np.cos(2 * np.pi * signal_freq * x)\ny = 1 * np.cos(2 * np.pi * signal_freq * (x + 1 / sampling_rate * (sampling_rate / signal_freq * signal_phase / 360)))\n# y = 1 * np.cos(2 * np.pi * signal_freq * x)\n# y = 0.5 * np.sin(2 * np.pi * signal_freq * x) + 0.5 * np.sin(2 * np.pi * int(1.05e6) * x)\n# y = np.around(y, decimals=2)\n# y = y * 100\n# y = y + 100\n# y = y * 10 + 10\n# y = np.rint(y)\n# N = 1024\n# print(len(y))\ny = y[:N]\n\n# y_temp = []\n# for i in range(len(y)):\n# y[i] = round(y[i], 1)\n# y[i] = y[i] * 10\n# y[i] = int(y[i])\n# y_temp.append(y[i])\n# # print(y[i])\n# y = y_temp\n\nfor i in range(len(y)):\n y[i] = np.around(y[i], decimals=3)\n y[i] = y[i]*1000\n y[i] = np.rint(y[i])\n # y[i] = int(y[i])\n y[i] = str(y[i])\n # y[i] = int(y[i])\nprint(y[:100])\n# y = y.astype(int)\n\nprint(type(y[1]))\n# y = y[2:514]\n# print(y[:10])\nfft_y = fft(y) # 快速傅里叶变换\nfft_y = fft_y[:N]\n# print(fft_y)\n# print(fft_y[16])\nabs_y = np.abs(fft_y) # 取复数的绝对值,即复数的模(双边频谱)\n# real_fft_y = np.real(fft_y)\nlist_real_fft_y = abs_y.tolist()\n\n# (np.abs(fft_y)).sort(reverse=True)\n# max_list_real_fft_y = list_real_fft_y.index(max(list_real_fft_y)) # 返回最大值的索引\n# list_real_fft_y.pop(max_list_real_fft_y)\nmax_list_real_fft_y = list_real_fft_y.index(max(list_real_fft_y)) # 返回最大值的索引\n# max_list_abs_fft_i = list_abs_fft_i.index(max(list_abs_fft_i)) # 返回最大值的索引\n\nprint(\"max_list_real_fft_y:{}\".format(max_list_real_fft_y))\n# max_list_real_fft_y = 43\n\nmax_fft_y_real = np.real(fft_y[max_list_real_fft_y])\nmax_fft_y_imag = np.imag(fft_y[max_list_real_fft_y])\nprint(max_fft_y_real)\nprint(max_fft_y_imag)\ncal_signal_phase_radian = np.arctan(max_fft_y_imag / max_fft_y_real)\ncal_signal_phase_angle = math.degrees(cal_signal_phase_radian)\nif cal_signal_phase_angle < 0:\n cal_signal_phase_angle = 180 + cal_signal_phase_angle\nprint(\"cal_signal_phase_angle:{:.2f}\".format(cal_signal_phase_angle))\n\n# while True:\n# pass\nx = np.arange(N) # 频率个数\nhalf_x = x[range(int(N / 2))] # 取一半区间\n\nabs_y = np.abs(fft_y) # 取复数的绝对值,即复数的模(双边频谱)\nangle_y = np.angle(fft_y) # 取复数的角度\nnormalization_y = abs_y / N # 归一化处理(双边频谱)\nnormalization_half_y = normalization_y[range(int(N / 2))] # 由于对称性,只取一半区间(单边频谱)\n\nplt.subplot(231)\nplt.plot(x, y)\nplt.title('原始波形')\n\nplt.subplot(232)\n# plt.plot(x, fft_y, 'black')\nplt.plot(x, np.real(fft_y), 'black')\n# plt.title('双边振幅谱(未求振幅绝对值)', fontsize=9, color='black')\nplt.title('FFT 实部', fontsize=9, color='black')\n\nplt.subplot(233)\n# plt.plot(x, abs_y, 'r')\nplt.plot(x, np.imag(fft_y), 'r')\n# plt.title('双边振幅谱(未归一化)', fontsize=9, color='red')\nplt.title('FFT 虚部', fontsize=9, color='red')\n\nplt.subplot(234)\nplt.plot(x, angle_y, 'violet')\nplt.title('双边相位谱(未归一化)', fontsize=9, color='violet')\n\nplt.subplot(235)\nplt.plot(x, normalization_y, 'g')\nplt.title('双边振幅谱(归一化)', fontsize=9, color='green')\n\nplt.subplot(236)\nplt.plot(half_x, normalization_half_y, 'blue')\nplt.title('单边振幅谱(归一化)', fontsize=9, color='blue')\n\nplt.show()\nall_zero = \"\"\nall_one = \"\"\nif flag == 1:\n count = 0\n file_name = \"{:.0e}Hzcos+10_signal_{:.0e}Hz_{}.bin\".format(\n signal_freq, sampling_rate, N)\n # file_name = \"test\"\n f = open(file_name, 'wb')\n # COE文件头\n f.write((\"MEMORY_INITIALIZATION_RADIX=16;\" + os.linesep).encode(\"utf-8\"))\n f.write((\"MEMORY_INITIALIZATION_VECTOR=\" + os.linesep).encode(\"utf-8\"))\n for i in range(0, N):\n\n # for i in range(0, 100):\n count += 1\n # int_yi = int(round(y[i], 1) * 10) + 10\n print(y[i])\n # 原码转补码\n # if int3_xi >= 0:\n # tem = to_bin(int3_xi, 7)\n # tem = tem.replace(\"0b\", \"\")\n # result = (\"0{}\".format(tem))\n # elif int3_xi < 0:\n # tem = to_bin(int3_xi, 7)\n # tem = tem.replace(\"-0b\", \"\")\n # result = (\"1{}\".format(tem))\n y[i] = int(y[i])\n y[i] = bin(y[i])\n y[i] = str(y[i]).replace(\"0b\", \"\")\n\n print(y[i])\n if y[i][0] == \"-\":\n y[i] = int(y[i])\n y[i] = (\"%05d\" % y[i])\n\n y[i] = y[i].replace(\"1\", \"x\")\n y[i] = y[i].replace(\"0\", \"1\")\n y[i] = y[i].replace(\"x\", \"0\")\n y[i] = y[i].replace(\"-\", \"\")\n print(y[i])\n # 十进制\n y[i] = int(y[i], 2)\n print(\"十进制\", y[i])\n y[i] = y[i] + 1\n # 二进制\n y[i] = bin(y[i])\n print(y[i])\n y[i] = str(y[i]).replace(\"0b\", \"\")\n y[i] = int(y[i])\n y[i] = (\"%04d\" % y[i])\n print(y[i])\n for n in range(8 - len(y[i])):\n all_one = \"1\" + all_one\n y[i] = all_one + y[i]\n elif y[i][0] != \"-\":\n y[i] = int(y[i])\n y[i] = (\"%04d\" % y[i])\n for n in range(8 - len(y[i])):\n all_zero = \"0\" + all_zero\n y[i] = all_zero + y[i]\n all_zero = \"\"\n all_one = \"\"\n print(y[i])\n\n # test_y.append(int_yi)\n # hex_yi = hex(y[i])\n # # 指定长度10进制转16进制\n # hex_yi = (\"{:#010X}\".format(y[i]))\n # y[i] = str(y[i])\n y[i] = int(y[i], 2)\n hex_yi = (\"{:#04X}\".format(y[i]))\n print(hex_yi)\n print()\n\n # 写文件\n if i == N - 1:\n # 最后一行\n f.write((hex_yi[2:] + \";\").encode(\"utf-8\"))\n else:\n f.write((hex_yi[2:] + \",\" + os.linesep).encode(\"utf-8\"))\n f.close()\n # 变换后波形\n # test_x = np.arange(N) # 频率个数\n # # test_x = np.arange(100) # 频率个数\n # plt.plot(test_x, test_y)\n # plt.title('原始波形')\n # plt.show()\nelif flag == 0:\n pass\nprint(\"Done!\")\n","sub_path":"signal_source/gen_1xsin_signal.py","file_name":"gen_1xsin_signal.py","file_ext":"py","file_size_in_byte":7153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"463283993","text":"import json\nimport logging\n\nimport requests\nfrom django.contrib import admin\nfrom django.forms import model_to_dict\nfrom rest_framework.reverse import reverse as rest_reverse\n\nfrom fulfillment.utils import CustomJsonEncoder\nfrom warehouse.models import Order\n\n\nclass OrderAdmin(admin.ModelAdmin):\n logger = logging.getLogger(__name__)\n\n # A handy constant for the name of the alternate database.\n using = 'warehouse_db'\n\n def has_add_permission(self, request):\n return False\n\n def save_model(self, request, obj, form, change):\n is_update = obj.created_at is not None\n\n obj.save(using=self.using)\n\n # Save the object to the store as well.\n headers = {'Content-Type': 'application/json'}\n data = model_to_dict(\n obj,\n fields=(\n 'id',\n 'company',\n 'address',\n 'status',\n 'deliver_by',\n ),\n )\n\n if is_update:\n url = request.build_absolute_uri(rest_reverse(\n 'store:order-detail',\n args=[obj.id],\n ))\n resp = requests.patch(\n url,\n data=json.dumps(data, cls=CustomJsonEncoder),\n headers=headers,\n )\n\n self.logger.debug(\n 'Warehouse order saved to store status: {}; reason: {}'.format(\n resp.status_code,\n resp.reason,\n ),\n )\n else:\n self.logger.warning(\n 'Orders should not be created in the warehouse!'\n )\n\n def delete_model(self, request, obj):\n # Tell Django to delete objects from the 'other' database\n obj.delete(using=self.using)\n\n def get_queryset(self, request):\n # Tell Django to look for objects on the 'other' database.\n return super().get_queryset(request).using(self.using)\n\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n # Tell Django to populate ForeignKey widgets using a query\n # on the 'other' database.\n return super().formfield_for_foreignkey(\n db_field,\n request,\n using=self.using,\n **kwargs,\n )\n\n def formfield_for_manytomany(self, db_field, request, **kwargs):\n # Tell Django to populate ManyToMany widgets using a query\n # on the 'other' database.\n return super().formfield_for_manytomany(\n db_field,\n request,\n using=self.using,\n **kwargs,\n )\n\n\nadmin.site.register(Order, OrderAdmin)\n","sub_path":"warehouse/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"592923110","text":"import copy\nimport time\nimport math\n\n\ndef test_sudoku(matrix):\n\n check_nums = [0 for i in range(0,10)]\n\n #Test each row\n for i in range(0, 9):\n zero_list(check_nums)\n for j in range(0, 9):\n check_nums[matrix[i][j]] += 1\n if check_vector(check_nums) == 0:\n #print('fail row')\n return 0\n\n #Test each column\n for i in range(0, 9):\n zero_list(check_nums)\n for j in range(0, 9):\n check_nums[matrix[j][i]] += 1\n if check_vector(check_nums) == 0:\n #print('fail col')\n return 0\n\n #Test each 3x3 cell\n for i in range(0, 3): #'row' of cell\n for j in range(0, 3): #'column' of cell\n zero_list(check_nums)\n for x in range(i*3, (i+1)*3): #row value\n for y in range(j*3, (j+1)*3): #column value\n check_nums[matrix[x][y]] += 1\n if check_vector(check_nums) == 0:\n #print('fail cell')\n return 0\n\n return 1 #passes all tests for now\n\ndef zero_list(list_in):\n\n for i in range(0,len(list_in)):\n list_in[i] = 0\n\ndef check_vector(list_in):\n\n sliced_list = list_in[1:]\n if max(sliced_list) > 1:\n return 0 #invalid combo\n else:\n return 1 #still a potential valid combo\n\ndef solve_sudoku(matrix_in):\n\n matrix = copy.deepcopy(matrix_in)\n next_zero = find_next_zero(matrix)\n\n #if find_next_zero is [-1,-1], then we are done...\n #depth first\n\n if next_zero[0] == -1: #found a solution!\n return True\n\n for i in range(1,10):\n copy_value(matrix_in, matrix)\n matrix_in[next_zero[0]][next_zero[1]] = i\n #print(matrix)\n if test_sudoku(matrix_in) == 1:\n if solve_sudoku(matrix_in):\n return True\n\n return False\n\ndef fill_sudoku(matrix, in_string):\n\n matr_len = int(math.sqrt(len(in_string)))\n counter = 0\n for i in range(0, matr_len):\n for j in range(0, matr_len):\n sudoku_matrix[i][j] = int(sudoku_string[counter])\n counter += 1\n\ndef copy_value(copyto, copyfrom):\n for i in range(0,len(copyto)):\n for j in range(0,len(copyto[i])):\n copyto[i][j] = copyfrom[i][j]\n\ndef find_next_zero(matrix):\n\n zero_loc = [-1,-1] #if no zeros\n\n for i in range(0,9):\n for j in range(0,9):\n if matrix[i][j] == 0:\n return [i,j]\n\n return zero_loc\n\n\n\n\n#Main part\n\n\n\nwith open(\"//Uds/9/wzheng1/Documents/p096_sudoku.txt\", \"r\") as f:\n contents = f.readlines()\n\ninput_string = ''\n\nfor line in contents:\n for char in line:\n temp_char = char\n if str.isdigit(temp_char):\n input_string = input_string + temp_char\n else:\n break\n\n\nstr_len = len(input_string)\nsudoku_len = 81\nnum_sudos = str_len // sudoku_len\nanswer = 0\n\nstart = time.clock()\n\nfor i in range(0, num_sudos):\n start1 = time.clock()\n sudoku_string = input_string[i*sudoku_len:(i+1)*sudoku_len]\n #sudoku_string = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'\n #sudoku_string = '000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n sudoku_matrix = [[0]* 9 for x in range(0,9)]\n\n fill_sudoku(sudoku_matrix, sudoku_string)\n\n\n\n\n print('')\n print('Sudoku number:', i+1)\n solve_sudoku(sudoku_matrix)\n for row in sudoku_matrix:\n print(row)\n\n answer += sudoku_matrix[0][0]*100 + sudoku_matrix[0][1]*10 + sudoku_matrix[0][2]\n\n end = time.clock()\n print(\"Time taken = {} seconds\".format((round(end-start1,3))))\n print(\"Cumulative time = {} seconds\".format((round(end - start, 3))))\n\nprint(\"Answer is:\", answer)","sub_path":"p96 sudoku.py","file_name":"p96 sudoku.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"541511651","text":"from django.core import exceptions\nfrom django.db import IntegrityError\nfrom django.template import loader, Context\n\nfrom fancypages import test\nfrom fancypages import models\nfrom fancypages.utils import get_container_names_from_template\n\n\nclass TestContainerNames(test.FancyPagesTestCase):\n\n def test_can_be_extracted_from_template(self):\n self.prepare_template_file(\"\"\"{% load fp_container_tags %}\n{% block main-content %}\n{% fp_object_container first-container %}\n{% templatetag opencomment %}\n{% endblock %}\n{% fp_object_container another-container %}\n\"\"\")\n self.assertSequenceEqual(\n get_container_names_from_template(self.template_name),\n [u'first-container', u'another-container']\n )\n\n def test_cannot_be_duplicated_in_template(self):\n self.prepare_template_file(\"\"\"{% load fp_container_tags %}\n{% block main-content %}\n{% fp_object_container first-container %}\n{% fp_object_container first-container %}\n{% templatetag opencomment %}\n{% endblock %}\n\"\"\")\n self.assertRaises(\n exceptions.ImproperlyConfigured,\n get_container_names_from_template,\n self.template_name\n )\n\nclass TestAPage(test.FancyPagesTestCase):\n\n def test_creates_containers_when_saved(self):\n self.prepare_template_file(\"\"\"{% load fp_container_tags %}\n{% block main-content %}\n{% fp_object_container first-container %}\n{% fp_object_container second-container %}\n{% templatetag opencomment %}\n{% endblock %}\n\"\"\")\n page_type = models.PageType.objects.create(\n name=\"Example Type\",\n template_name=self.template_name,\n )\n article_page = models.FancyPage.add_root(\n name='This is an article',\n page_type=page_type,\n )\n\n article_page = models.FancyPage.objects.get(id=article_page.id)\n self.assertEquals(article_page.containers.count(), 2)\n\n\nclass TestContainer(test.FancyPagesTestCase):\n\n def test_without_page_object_is_unique(self):\n var_name = 'test-container'\n models.Container.objects.create(name=var_name)\n self.assertRaises(\n exceptions.ValidationError,\n models.Container.objects.create,\n name=var_name\n )\n\n def test_with_page_object_is_unique(self):\n var_name = 'test-container'\n page = models.FancyPage.add_root(name=\"Test Page\")\n models.Container.objects.create(\n name=var_name,\n page_object=page\n )\n self.assertRaises(\n IntegrityError,\n models.Container.objects.create,\n name=var_name,\n page_object=page,\n )\n\n def test_containers_can_have_same_name_for_different_objects(self):\n var_name = 'test-container'\n page = models.FancyPage.add_root(name=\"Test Page\")\n models.Container.objects.create(\n name=var_name,\n page_object=page\n )\n other_page = models.FancyPage.add_root(name=\"Another Test Page\")\n try:\n models.Container.objects.create(\n name=var_name,\n page_object=other_page,\n )\n except IntegrityError:\n self.fail(\n 'containers with different pages do not have to be unique'\n )\n\n def test_containers_can_have_same_name_with_an_without_object(self):\n var_name = 'test-container'\n page = models.FancyPage.add_root(name=\"Test Page\")\n models.Container.objects.create(\n name=var_name,\n page_object=page\n )\n try:\n models.Container.objects.create(name=var_name)\n except exceptions.ValidationError:\n self.fail(\n 'containers with different pages do not have to be unique'\n )\n\n\nclass TestContainerWithObject(test.FancyPagesTestCase):\n\n def setUp(self):\n super(TestContainerWithObject, self).setUp()\n self.prepare_template_file(\n \"{% load fp_container_tags %}\"\n \"{% fp_object_container test-container %}\"\n )\n\n page_type = models.PageType.objects.create(\n name=\"Example Type\",\n template_name=self.template_name,\n )\n self.page = models.FancyPage.add_root(\n name=\"Some Title\",\n page_type=page_type\n )\n self.container_names = get_container_names_from_template(\n self.page.page_type.template_name\n )\n\n def test_can_be_assigned_to_a_page(self):\n self.assertEquals(self.container_names, [u'test-container'])\n self.assertEquals(self.page.containers.count(), 1)\n\n def test_cannot_assign_multiple_instance_to_page(self):\n self.assertEquals(self.container_names, [u'test-container'])\n\n self.page.create_container(self.container_names[0])\n self.assertEquals(self.page.containers.count(), 1)\n\n self.page.create_container(self.container_names[0])\n self.assertEquals(self.page.containers.count(), 1)\n\n def test_can_be_retrieved_from_page_and_container_name(self):\n container = models.Container.get_container_by_name(\n name='test-container',\n obj=self.page,\n )\n self.assertEquals(\n container.name,\n self.page.containers.all()[0].name\n )\n self.assertEquals(self.page.containers.count(), 1)\n\n\nclass TestContainerWithoutObject(test.FancyPagesTestCase):\n\n def setUp(self):\n super(TestContainerWithoutObject, self).setUp()\n self.prepare_template_file(\n \"{% load fp_container_tags %}\"\n \"{% fp_container test-container %}\"\n )\n\n def test_can_be_used_in_template(self):\n tmpl = loader.get_template(self.template_name)\n tmpl.render(Context({}))\n\n containers = models.Container.objects.all()\n self.assertEquals(len(containers), 1)\n self.assertEquals(containers[0].page_object, None)\n\n #def test_can_render_contained_blocks(self):\n # container = models.Container.objects.create(\n # name='test-container'\n # )\n # text = \"I am a fancy block with only text\"\n # text_block = models.TextBlock.objects.create(\n # container=container,\n # text=text,\n # )\n # print self.template_name\n # tmpl = loader.get_template(self.template_name)\n # content = tmpl.render(self.client.request().context[0])\n # self.assertIn(text, content)\n\n # container = models.Container.objects.get(id=container.id)\n # self.assertEquals(container.blocks.count(), 1)\n # self.assertEquals(container.blocks.all()[0].id, text_block.id)\n","sub_path":"fancypages/tests/unit/test_pages.py","file_name":"test_pages.py","file_ext":"py","file_size_in_byte":6656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"507133753","text":"# -*- coding: utf-8 -*-\nimport logging\n\nfrom cghq.exc import AnalysisNotCompleteError\nfrom cghq.extensions import glue\n\nlogger = logging.getLogger(__name__)\n\n\ndef post_genotypes(cust_id, case_id):\n \"\"\"Load genotypes for the most recent analysis of a case.\"\"\"\n analysis_res = glue.get('analyze', 'analyses', cust_id, case_id)\n\n if analysis_res.json['is_complete']:\n logger.debug('loading genotypes...')\n payload = {'type': 'vcf', 'file': analysis_res.json['ready_vcf']}\n addgt_res = glue.post('genotype', 'samples', data=payload)\n else:\n logger.error('analysis not complete')\n raise AnalysisNotCompleteError\n return addgt_res.json\n\n\ndef post_concordance(sample_id):\n \"\"\"Match genotypes across samples to confirm concordance.\"\"\"\n sample_res = glue.get('lims', 'samples', sample_id)\n cust_id = sample_res.json['customer']\n case_id = sample_res.json['family_id']\n\n analysis_res = glue.get('analyze', 'analyses', cust_id, case_id)\n started_at = analysis_res.json['analyzed_at']\n\n logger.debug('match sample genotypes')\n match_res = glue.get('genotype', 'samples', 'match', sample_id)\n top_hit = match_res.json['results'][0]\n\n logger.debug('persist the comparison result')\n add_payload = {'sample_id': sample_id, 'started_at': started_at,\n 'matches': top_hit['match'],\n 'mismatches': top_hit.get('mismatch', 0),\n 'unknowns': top_hit.get('unknown', 0),\n 'is_failed': match_res.json.get('is_failed')}\n add_res = glue.post('moneypenny', 'genotypings', data=add_payload)\n return add_res.json\n","sub_path":"cghq/routes/genotypes.py","file_name":"genotypes.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"557200705","text":"\n\nfrom xai.brain.wordbase.verbs._abscond import _ABSCOND\n\n#calss header\nclass _ABSCONDING(_ABSCOND, ):\n\tdef __init__(self,): \n\t\t_ABSCOND.__init__(self)\n\t\tself.name = \"ABSCONDING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"abscond\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_absconding.py","file_name":"_absconding.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"100876905","text":"from graphene import relay, Field, String, ID\r\n\r\nfrom danesh_boom.viewer_fields import ViewerFields\r\nfrom media.models import Media\r\nfrom users.forms import CertificateForm\r\nfrom users.models import Certificate\r\nfrom users.schemas.queries.certificate import CertificateNode\r\nfrom utils.relay_helpers import get_node\r\n\r\n\r\nclass CreateCertificateMutation(ViewerFields, relay.ClientIDMutation):\r\n class Input:\r\n title = String(required=True)\r\n picture_id = String()\r\n\r\n certificate = Field(CertificateNode)\r\n\r\n @classmethod\r\n def mutate_and_get_payload(cls, input, context, info):\r\n user = context.user\r\n\r\n picture_id = input.get('picture_id')\r\n picture = get_node(picture_id, context, info, Media)\r\n\r\n # create certificate\r\n form = CertificateForm(input, context.FILES)\r\n if form.is_valid():\r\n new_certificate = form.save(commit=False)\r\n new_certificate.user = user\r\n new_certificate.picture = picture\r\n new_certificate.save()\r\n else:\r\n raise Exception(str(form.errors))\r\n\r\n return CreateCertificateMutation(certificate=new_certificate)\r\n\r\n\r\nclass UpdateCertificateMutation(ViewerFields, relay.ClientIDMutation):\r\n class Input:\r\n id = String(required=True)\r\n picture_id = String()\r\n title = String(required=True)\r\n\r\n certificate = Field(CertificateNode)\r\n\r\n @classmethod\r\n def mutate_and_get_payload(cls, input, context, info):\r\n user = context.user\r\n certificate_id = input.get('id', None)\r\n certificate = get_node(certificate_id, context, info, Certificate)\r\n if not certificate:\r\n raise Exception(\"Invalid Certificate\")\r\n\r\n if certificate.user != user:\r\n raise Exception(\"Invalid Access to Certificate\")\r\n\r\n picture_id = input.get('picture_id')\r\n picture = get_node(picture_id, context, info, Media)\r\n\r\n # update certificate\r\n certificate.picture = picture\r\n form = CertificateForm(input, context.FILES, instance=certificate)\r\n if form.is_valid():\r\n form.save()\r\n else:\r\n raise Exception(str(form.errors))\r\n\r\n return UpdateCertificateMutation(certificate=certificate)\r\n\r\n\r\nclass DeleteCertificateMutation(ViewerFields, relay.ClientIDMutation):\r\n class Input:\r\n id = String(required=True)\r\n\r\n deleted_id = ID()\r\n\r\n @classmethod\r\n def mutate_and_get_payload(cls, input, context, info):\r\n user = context.user\r\n certificate_id = input.get('id', None)\r\n certificate = get_node(certificate_id, context, info, Certificate)\r\n if not certificate:\r\n raise Exception(\"Invalid Certificate\")\r\n if certificate.user != user:\r\n raise Exception(\"Invalid Access to Certificate\")\r\n\r\n # delete certificate\r\n certificate.delete()\r\n\r\n return DeleteCertificateMutation(deleted_id=id)\r\n","sub_path":"users/schemas/mutations/certificate.py","file_name":"certificate.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"446066622","text":"from file_control import File\nimport json\nimport logging\n\nf = File()\n'''\n1. Meletakkan file\n Request: upload\n Parameter: nama dari file [spasi] isi dari file\n Response:\n Berhasil -> OK\n Gagal -> ERROR\n2. Mengambil file\n Request: download\n Parameter: nama dari file\n Response: isi file dalam bentuk base64encode format\n Melihat list file\n3. Request: list\n Parameter: tidak ada\n Response: daftar nama file yang ada pada folder files dalam bentuk json format\nJika command tidak dikenali akan merespon dengan ERRCMD\n\n'''\nclass FileMachine:\n def proses(self,string_to_process):\n s = string_to_process\n cstring = s.split(\" \")\n try:\n command = cstring[0].strip()\n if (command=='upload'):\n logging.warning(\"upload\")\n namafile = cstring[1].strip()\n isifile = cstring[2].strip()\n print(namafile+\" \"+isifile)\n f.upload_file(namafile,isifile.encode())\n return \"OK\"\n elif (command=='download'):\n logging.warning(\"download\")\n namafile = cstring[1].strip()\n hasil = f.download_file(namafile)\n return hasil[0]\n elif (command=='list'):\n logging.warning(\"list\")\n namafile = f.list_files()\n hasil = {\"filename\":namafile}\n return json.dumps(hasil, indent=4)\n else:\n return \"ERRCMD\"\n except:\n return \"ERROR\"\n\n\nif __name__=='__main__':\n fm = FileMachine()\n hasil = fm.proses(\"upload text1.txt testing\")\n print(hasil)\n","sub_path":"tugas4/file_machine.py","file_name":"file_machine.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"132385266","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('reimbursements', '0004_auto_20150116_1050'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='reimbursement',\n old_name='trip_type',\n new_name='commute_type',\n ),\n ]\n","sub_path":"grh/reimbursements/migrations/0005_auto_20150122_2116.py","file_name":"0005_auto_20150122_2116.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"528029153","text":"# c11ex05.py\n# various list algorithms\n\n\ndef count(myList, x):\n ans = 0\n for item in myList:\n if item == x:\n ans = ans + 1\n return ans\n\ndef isin(myList, x):\n for item in myList:\n if item == x:\n return True\n return False\n\ndef index(myList, x):\n for i in range(len(myList)):\n if myList[i] == x:\n return i\n # If not found, raise a value error\n # an alternative would be to return -1\n raise ValueError(\"x not in list\")\n\ndef reverse(lst):\n for i in range(len(lst)/2):\n j = -(i+1)\n lst[i], lst[j] = lst[j], lst[i]\n\n\ndef sort(lst):\n # selection sort. See Chapter 13 for other examples.\n for i in range(len(lst)-1):\n # find min of remaining items\n minpos = i\n for j in range(i+1,len(lst)):\n if lst[j] < lst[minpos]:\n minpos = j\n # swap min to front of remaining\n lst[i], lst[minpos] = lst[minpos], lst[i]\n\n\n\n","sub_path":"code/chapter11/c11ex05.py","file_name":"c11ex05.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"261102937","text":"\"\"\"\nMain module for TTV code.\n\"\"\"\nfrom __future__ import (print_function, division, unicode_literals, absolute_import)\n\nimport datetime\nimport struct\n\nfrom eight import bytes, str, PY2, builtins\n\nfrom kkmip import enums\nfrom kkmip.ttv import json\nfrom kkmip.ttv import ttlv\nfrom kkmip.ttv import types\nfrom kkmip.ttv import xml\n\nif PY2:\n _integer_types = (builtins.int, builtins.long,)\nelse:\n _integer_types = (builtins.int,)\n\n_enums_types = (enums.Enum, types.UnknownEnumeration, types.UnknownEnumerationString)\n\n\ndef _enum_value(x):\n \"\"\" Convert a int/Enum value into a int\"\"\"\n if isinstance(x, _integer_types):\n return x\n return x.value\n\n\nclass TTV(object):\n \"\"\"\n TTV represents a KMIP tag, type, value node.\n\n If the type is a KMIP Structure, then value is a list of TTV nodes, making it a tree.\n\n Args:\n tag (kkmip.enums.Tag): the KMIP tag of the node.\n value: the value of the node.\n Its Python type depend on typ:\n Integer: Integer\n LongInteger: LongInteger\n BigInterger: BigInterger\n Enumeration: Enum or Enumeration\n Boolean: bool\n TextString: str\n ByteString: bytes\n DateTime: datetime.datetime\n Interval: datetime.timedelta\n typ (kkmip.enums.ItemType): the KMIP type of the node. If None, it is automatically\n determined from the Python type of the value.\n \"\"\"\n\n def __init__(self, tag, value, typ=None):\n self.tag = tag\n self.value = value\n if typ is None:\n if isinstance(value, types.LongInteger):\n self.typ = enums.ItemType.LongInteger\n elif isinstance(value, types.BigInteger):\n self.typ = enums.ItemType.BigInteger\n elif isinstance(value, _enums_types):\n self.typ = enums.ItemType.Enumeration\n elif isinstance(value, bool):\n self.typ = enums.ItemType.Boolean\n elif isinstance(value, str):\n self.typ = enums.ItemType.TextString\n elif isinstance(value, (bytes, bytearray)):\n self.typ = enums.ItemType.ByteString\n elif isinstance(value, datetime.datetime):\n self.typ = enums.ItemType.DateTime\n elif isinstance(value, datetime.timedelta):\n self.typ = enums.ItemType.Interval\n elif isinstance(value, list):\n self.typ = enums.ItemType.Structure\n elif isinstance(value, (types.Integer,) + _integer_types):\n self.typ = enums.ItemType.Integer\n self.value = types.Integer(self.value)\n else:\n raise RuntimeError(\n 'Value {} does not correspond to a TTLV type'.format(repr(value)))\n else:\n self.typ = typ\n if self.typ == enums.ItemType.Integer:\n if not isinstance(self.value, (types.Integer, types.UnknownIntegerMask)):\n self.value = types.Integer(self.value)\n elif self.typ == enums.ItemType.LongInteger:\n self.value = types.LongInteger(self.value)\n elif self.typ == enums.ItemType.BigInteger:\n self.value = types.BigInteger(self.value)\n elif self.typ == enums.ItemType.Enumeration:\n if isinstance(self.value, _integer_types):\n self.value = types.UnknownEnumeration(self.value)\n elif self.typ == enums.ItemType.Boolean:\n self.value = bool(self.value)\n elif self.typ == enums.ItemType.TextString:\n self.value = str(self.value)\n elif self.typ == enums.ItemType.ByteString:\n self.value = bytes(self.value)\n elif self.typ == enums.ItemType.DateTime:\n if not isinstance(self.value, datetime.datetime):\n raise RuntimeError('Value must be instance of datetime.datetime')\n elif self.typ == enums.ItemType.Interval:\n if not isinstance(self.value, datetime.timedelta):\n raise RuntimeError('Value must be instance of datetime.timedelta')\n\n if isinstance(self.value, types.Integer):\n if not -(1 << 31) <= self.value <= (1 << 31) - 1:\n raise RuntimeError('Integer out of range')\n elif isinstance(self.value, types.LongInteger):\n if not -(1 << 63) <= self.value <= (1 << 63) - 1:\n raise RuntimeError('LongInteger out of range')\n\n def __eq__(self, o):\n if o is None:\n return False\n if _enum_value(self.tag) != _enum_value(o.tag) or self.typ != o.typ:\n return False\n if self.typ == enums.ItemType.Structure:\n return all((a == b) for a, b in zip(self.value, o.value))\n return self.value == o.value\n\n def __ne__(self, o):\n return not self.__eq__(o)\n\n def __str__(self):\n s = 'TTV(tag={}, typ={}, value='.format(self.tag, self.typ)\n if self.typ == enums.ItemType.Structure:\n s += '[' + ', '.join(str(elem) for elem in self.value) + ']'\n else:\n if self.typ == enums.ItemType.ByteString:\n s += json.encode_bytestring(self.value)\n else:\n s += repr(self.value)\n s += ')'\n return s\n\n def __repr__(self):\n return self.__str__()\n\n def encode_json(self):\n return json.encode(self)\n\n def encode_xml(self):\n return xml.encode(self)\n\n def encode_ttlv(self):\n return ttlv.encode(self)\n\n def encodeTTLV(self):\n tt = struct.pack('>I', self.tag << 8 | self.typ.value)\n value = self.value.encode_ttlv()\n length = struct.pack('>I', len(value))\n ttlv = tt + length + value\n if len(value) % 8 != 0:\n pad_len = 8 - len(value) % 8\n pad = '\\0' * pad_len\n ttlv += pad\n return ttlv\n","sub_path":"reporter/kkmip/kkmip/ttv/ttv.py","file_name":"ttv.py","file_ext":"py","file_size_in_byte":5954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"408548698","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom booking import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.index, name='index'),\n path('carsearch', views.carsearch, name='carsearch'),\n path('info', views.info, name='info'),\n path('signup',views.signup, name='signup'),\n path('accounts/', include('django.contrib.auth.urls')),\n]\n","sub_path":"instacar/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"420250471","text":"from re import T\nimport gym\nimport math\nimport random\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple, deque\nfrom itertools import count\nfrom PIL import Image\nfrom torch.cuda import init\nfrom env import HangmanEnv\nfrom torch.autograd import Variable\nfrom config import Config\nimport yaml\nimport logging\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom memory import Transition, ReplayMemory\nfrom dqn import DQN\nfrom log import setup_custom_logger\nimport time\n# import torchvision.transforms as T\n\nBATCH_SIZE = 128\nGAMMA = 0.999\nEPS_START = 0.8\nEPS_END = 0.05\nEPS_DECAY = 200\nTARGET_UPDATE = 10\nobscured_string_len = 27\n\n# create logger\nlogger = setup_custom_logger('root', \"./latest.log\", \"INFO\")\nlogger.propagate = False\nlogger.setLevel(logging.INFO)\n\n# create console handler and set level to debug\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n\n# create formatter\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n# add formatter to ch\nch.setFormatter(formatter)\n\n# add ch to logger\nlogger.addHandler(ch)\n\n# set up matplotlib\nis_ipython = 'inline' in matplotlib.get_backend()\nif is_ipython:\n from IPython import display\n\nplt.ion()\n\n# if gpu is to be used\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nconfig = None\n \nclass HangmanPlayer():\n def __init__(self, env, config):\n self.memory = None\n self.steps_done = 0\n self.episode_durations = []\n self.last_episode = 0\n self.reward_in_episode = []\n self.env = env\n self.id = int(time.time())\n self.config = config\n self.n_actions = self.env.action_space.n\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.compile()\n \n def compile(self): \n self.policy_net = DQN().to(device)\n self.target_net = DQN().to(device)\n self.target_net.load_state_dict(self.policy_net.state_dict())\n # summary(self.target_net, (128, 25, 27))\n self.target_net.eval()\n self.optimizer = optim.RMSprop(self.policy_net.parameters())\n \n def _update_target(self):\n self.target_net.load_state_dict(self.policy_net.state_dict())\n \n def _adjust_learning_rate(self, episode):\n delta = self.config.training.learning_rate - self.config.optimizer.lr_min\n base = self.config.optimizer.lr_min\n rate = self.config.optimizer.lr_decay\n lr = base + delta * np.exp(-episode / rate)\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = lr\n \n def _get_action_for_state(self, state):\n sample = random.random()\n eps_threshold = EPS_END + (EPS_START - EPS_END) * \\\n math.exp(-1. * self.steps_done / EPS_DECAY)\n self.steps_done += 1\n if sample > eps_threshold:\n with torch.no_grad():\n # t.max(1) will return largest column value of each row.\n # second column on max result is index of where max element was\n # found, so we pick action with the larger expected reward.\n # print(\"This value is \", policy_net(state).max(1))\n selected_action = self.policy_net(torch.tensor(state[0]), torch.tensor([state[1]])).argmax()\n # print(\"ActionSelect: require grad = \", tens.requires_grad)\n value = selected_action.numpy()\n b = np.zeros((value.size, 26))\n # print(\"Value = \", value)\n b[np.arange(value.size), value] = 1\n selected_action = torch.from_numpy(b).long()\n # print(\"from net, got action = \", int(value))\n # final_action = torch.zeros(26).scatter(1, selected_action.unsqueeze (1), 1).long()\n # print(\"Final action2 = \", selected_action)\n return selected_action\n else:\n a = np.array(random.randrange(self.n_actions))\n b = np.zeros((1, 26))\n b[0, a] = 1\n print(b.shape)\n selected_action = torch.from_numpy(b).long()\n # print(\"ActionSelect: action selected = \", type(random.randrange(self.n_actions)))\n # final_action = torch.zeros(26).scatter(1, selected_action.unsqueeze (1), 1).long()\n # print(\"Final action = \", selected_action)\n return selected_action\n \n def save(self):\n torch.save({\n 'policy_state_dict': self.policy_net.state_dict(),\n 'target_state_dict': self.target_net.state_dict(),\n 'optimizer_state_dict': self.optimizer.state_dict(),\n \"reward_in_episode\": self.reward_in_episode,\n \"episode_durations\": self.episode_durations,\n \"config\": self.config\n }, f\"./models/pytorch_{self.id}.pt\")\n \n def _remember(self, state, action, next_state, reward, done):\n self.memory.push(torch.tensor([state], device=self.device),\n torch.tensor([action], device=self.device, dtype=torch.long),\n torch.tensor([next_state], device=self.device),\n torch.tensor([reward], device=self.device),\n torch.tensor([done], device=self.device, dtype=torch.bool))\n \n def fit(self):\n num_episodes = 5000000\n self.memory = ReplayMemory(10000)\n self.episode_durations = []\n self.reward_in_episode = []\n reward_in_episode = 0\n self.epsilon_vec = []\n for i_episode in range(num_episodes):\n # Initialize the environment and state\n state = self.env.reset()\n # self.check_grad()\n # last_screen = get_screen()\n # current_screen = get_screen()\n # print(\"Fit: state = \", state)\n state = (state[0].reshape(-1, 25, 27), state[1])\n # state = current_screen - last_screen\n for t in count():\n # Select and perform an action\n # self.check_grad()\n action = self._get_action_for_state(state)\n # self.check_grad()\n # print(\"Fit: action = \", action.shape)\n next_state, reward, done, info = self.env.step(action)\n \n # reward = torch.tensor([reward], device=device)\n next_state = (next_state[0].reshape(-1, 25, 27), next_state[1]) # Observe new state\n # action_vector = next_state[1]\n # print(\"Fit: next state actions = \", next_state[1])\n # last_state = state\n # state=next_state\n # current_screen = get_screen()\n # if not done:\n # next_state = current_screen - last_screen\n # else:\n # next_state = None\n\n # Store the transition in memory\n self._remember(state[0], next_state[1], next_state[0], reward, done)\n \n if i_episode >= self.config.training.warmup_episode:\n self._train_model()\n self._adjust_learning_rate(i_episode - self.config.training.warmup_episode + 1)\n done = (t == self.config.rl.max_steps_per_episode - 1) or done\n else:\n done = (t == 5 * self.config.rl.max_steps_per_episode - 1) or done\n \n # Move to the next state\n state = next_state\n reward_in_episode += reward\n\n if done:\n self.episode_durations.append(t + 1)\n self.reward_in_episode.append(reward_in_episode)\n # self.epsilon_vec.append(epsilon)\n reward_in_episode = 0\n break\n\n # Update the target network, copying all weights and biases in DQN\n if i_episode % 50 == 0:\n self._update_target()\n\n # if i_episode % self.config.training.save_freq == 0:\n # self.save()\n\n self.last_episode = i_episode\n # Move to the next state\n\n # Perform one step of the optimization (on the policy network)\n if done:\n self.episode_durations.append(t + 1)\n # plot_durations()\n break\n # Update the target network, copying all weights and biases in DQN\n if i_episode % self.config.rl.target_model_update_episodes == 0:\n self.target_net.load_state_dict(self.policy_net.state_dict())\n \n if i_episode % self.config.training.save_freq == 0:\n self.save()\n \n def _train_model(self): \n if len(self.memory) < BATCH_SIZE:\n return\n transitions = self.memory.sample(BATCH_SIZE)\n # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for\n # detailed explanation). This converts batch-array of Transitions\n # to Transition of batch-arrays.\n batch = Transition(*zip(*transitions))\n \n \n\n # Compute a mask of non-final states and concatenate the batch elements\n # (a final state would've been the one after which simulation ended)\n non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,\n batch.next_state)), device=device, dtype=torch.bool)\n non_final_next_states = torch.cat([s for s in batch.next_state\n if s is not None])\n state_batch = torch.cat(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n state_batch.resize_(BATCH_SIZE, 25, 27)\n non_final_next_states.resize_(BATCH_SIZE, 25, 27)\n # print(\"action batch = \", action_batch.numpy().sum())\n # action_batch.resize_(BATCH_SIZE)\n\n # Compute Q(s_t, a) - the model computes Q(s_t), then we select the\n # columns of actions taken. These are the actions which would've been taken\n # for each batch state according to policy_net\n # print(\"Here printing = \", self.policy_net(state_batch, action_batch))\n state_action_values = self.policy_net(state_batch, action_batch).gather(0, action_batch)\n # print(\"State batch = \", state_batch)\n # print(\"action batch = \", action_batch.shape)\n # print(\"reward batch = \", reward_batch.shape)\n # Compute V(s_{t+1}) for all next states.\n # Expected values of actions for non_final_next_states are computed based\n # on the \"older\" self.target_net; selecting their best reward with max(1)[0].\n # This is merged based on the mask, such that we'll have either the expected\n # state value or 0 in case the state was final.\n next_state_values = torch.zeros(BATCH_SIZE, device=device, dtype=torch.float)\n temp = self.target_net(non_final_next_states, action_batch).max(1)[0].detach()\n # print(\"TrainModel: temp = \", temp.numpy().tolist())\n # print(next_state_values)\n next_state_values[non_final_mask] = self.target_net(non_final_next_states, action_batch).max(1)[0].detach()\n # Compute the expected Q values\n \n expected_state_action_values = (next_state_values * GAMMA) + reward_batch\n # print(\"TrainModel: expected state action values = \", expected_state_action_values)\n # print(\"TrainModel: state action values = \", state_action_values.numpy().tolist())\n # Compute Huber loss\n criterion = nn.SmoothL1Loss()\n # clone = expected_state_action_values.clone()\n # with torch.enable_grad():\n # print(next_state_values.shape)\n # print(state_action_values.shape)\n loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1)).float()\n # print(expected_state_action_values.requires_grad)\n logger.info(\"trainmodel: loss = {0}\".format(loss))\n # loss.requires_grad = True\n self.optimizer.zero_grad()\n # loss = Variable(loss, requires_grad = True)\n # Optimize the model\n # loss.retain_grad()\n # print(loss.grad)\n loss.backward()\n\n # print(\"TrainModel: params = \", list(self.policy_net.parameters()))\n for name, param in self.policy_net.named_parameters():\n # print(\"Param = \", name, param.is_leaf)\n # try:\n # param.is_leaf\n param.grad.data.clamp_(-1, 1)\n # break\n # except:\n # print(\"Failed\")\n # # pass\n self.optimizer.step()\n \n def play(self, verbose:bool=False, sleep:float=0.2, max_steps:int=100):\n # Play an episode\n try:\n actions_str = [\"South\", \"North\", \"East\", \"West\", \"Pickup\", \"Dropoff\"]\n\n iteration = 0\n state = self.env.reset() # reset environment to a new, random state\n state = (state[0].reshape(-1, 25, 27), state[1])\n if verbose:\n print(f\"Iter: {iteration} - Action: *** - Reward ***\")\n time.sleep(sleep)\n done = False\n\n while not done:\n action = self._get_action_for_state(state)\n iteration += 1\n state, reward, done, info = self.env.step(action)\n display.clear_output(wait=True)\n self.env.render()\n if verbose:\n print(f\"Iter: {iteration} - Action: {action}({actions_str[action]}) - Reward {reward}\")\n time.sleep(sleep)\n if iteration == max_steps:\n print(\"cannot converge :(\")\n break\n except KeyboardInterrupt:\n pass\n \n def evaluate(self, max_steps:int=100):\n try:\n total_steps, total_penalties = 0, 0\n episodes = 100\n\n for episode in trange(episodes):\n state = self.env.reset() # reset environment to a new, random state\n state = (state[0].reshape(-1, 25, 27), state[1])\n nb_steps, penalties, reward = 0, 0, 0\n\n done = False\n\n while not done:\n action = self._get_action_for_state(state)\n state, reward, done, info = self.env.step(action)\n\n if reward == -10:\n penalties += 1\n\n nb_steps += 1\n if nb_steps == max_steps:\n done = True\n\n total_penalties += penalties\n total_steps += nb_steps\n\n print(f\"Results after {episodes} episodes:\")\n print(f\"Average timesteps per episode: {total_steps / episodes}\")\n print(f\"Average penalties per episode: {total_penalties / episodes}\") \n except KeyboardInterrupt:\n pass","sub_path":"hangman_agent.py","file_name":"hangman_agent.py","file_ext":"py","file_size_in_byte":15051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"421272285","text":"# -*- coding:utf-8 -*-\n\nclass Node(object):\n def __init__(self, value):\n # 元素域\n self.value = value\n # 链接域\n self.next = None\n\nclass UnorderedList(object): # 单向线性表\n \"reference:https://www.cnblogs.com/yifeixu/p/8954991.html\"\n\n def __init__(self, node=None):\n self.__head = node\n\n def __len__(self):\n # 游标 cursor ,用来遍历链表\n cur = self.__head\n # 记录遍历次数\n count = 0\n # 当前节点为None则说明已经遍历完毕\n while cur:\n count += 1\n cur = cur.next\n return count\n\n def isEmpty(self):\n # 头节点不为None则不为空\n return self.__head == None\n\n def add(self, value): # 链表头部添加元素\n \"\"\"\n 头插法\n 先让新节点的next指向头节点\n 再让头节点指向新节点\n 顺序不可错,要先保证原链表的链不断,否则头节点后面的链会丢失\n \"\"\"\n node = Node(value)\n node.next = self.__head\n self.__head = node # node是最新插入节点的地址\n\n def append(self, value): # 链表尾部添加元素\n \"\"\"尾插法\"\"\"\n node = Node(value)\n cur = self.__head\n if self.isEmpty():\n self.__head = node\n else:\n while cur.next:\n cur = cur.next\n cur.next = node\n\n def insert(self, pos, value): # 指定位置添加元素\n # 应对特殊情况:插入位置小于 0 就使用头插法,插入位置溢出长度就采用尾插法\n if pos <= 0:\n self.add(value)\n elif pos > len(self) - 1:\n self.append(value)\n else:\n node = Node(value)\n prior = self.__head\n count = 0\n # 在插入位置的前一个节点停下\n while count < (pos - 1):\n prior = prior.next\n count += 1\n # 先将插入节点与节点后的节点连接,防止链表断掉,先链接后面的,再链接前面的\n node.next = prior.next\n prior.next = node\n\n def remove(self, value): # 删除节点\n cur = self.__head\n prior = None\n while cur:\n if value == cur.value:\n # 判断此节点是否是头节点\n if cur == self.__head:\n self.__head = cur.next\n else:\n prior.next = cur.next\n break\n # 还没找到节点,有继续遍历\n else:\n prior = cur\n cur = cur.next\n\n def search(self, value): # 查找节点是否存在\n cur = self.__head\n while cur:\n if value == cur.value:\n return True\n cur = cur.next\n return False\n\n def traverse(self): # 遍历整个链表\n cur = self.__head\n while cur:\n print(cur.value)\n cur = cur.next\n\nif __name__ == \"__main__\":\n l = UnorderedList()\n print(l.isEmpty())","sub_path":"数据结构与算法/lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"98082251","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('system', '0004_auto_20150903_0416'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='plan',\n old_name='plan_premium',\n new_name='plan_adult_premium',\n ),\n migrations.AddField(\n model_name='plan',\n name='plan_minor_premium',\n field=models.DecimalField(decimal_places=2, max_digits=12, default=0),\n preserve_default=False,\n ),\n ]\n","sub_path":"system/migrations/0005_auto_20150903_0502.py","file_name":"0005_auto_20150903_0502.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"444315588","text":"import subprocess\n\n\nclass CardanoNodeError(Exception):\n pass\n\n\nclass CardanoNode():\n\n def __init__(self, binary, topology, database_path, socket_path, port,\n config, host_addr=None, kes_key=None, vrf_key=None, cert=None,\n ssh=None):\n \"\"\"Provides an interface for starting up a node locally or remote.\n \"\"\"\n self.binary = binary\n self.topology = topology\n self.db_path = database_path\n self.socket_path = socket_path\n self.port = port\n self.config = config\n self.host_addr = host_addr\n self.kes_key = kes_key\n self.vrf_key = vrf_key\n self.cert = cert\n self.ssh = ssh\n self.debug = False\n\n def __exec(self, args):\n cmd = f\"nohup {args} &> /dev/null &\"\n if self.debug:\n print(cmd)\n if self.ssh is not None:\n self.ssh.open()\n self.ssh.run(cmd, warn=True, hide=True)\n self.ssh.close()\n else:\n subprocess.run(cmd.split())\n\n def start(self, mode=\"relay\"):\n \"\"\"Start the cardano-node (default relay mode).\"\"\"\n cmd = (\n f\"{self.binary} run \"\n f\"--topology {self.topology} \"\n f\"--database-path {self.db_path} \"\n f\"--socket-path {self.socket_path} \"\n f\"--port {self.port} \"\n f\"--config {self.config} \"\n )\n if self.host_addr is not None:\n cmd += f\"--host-addr {self.host_addr} \"\n if mode.lower() == \"pool\":\n cmd += (\n f\"--shelley-kes-key {self.kes_key} \"\n f\"--shelley-vrf-key {self.vrf_key} \"\n f\"--shelley-operational-certificate {self.cert}\"\n )\n self.__exec(cmd)\n","sub_path":"cardano_tools/cardano_node.py","file_name":"cardano_node.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"530112826","text":"import numpy\nimport pytest\n\nimport cupy\nfrom cupy import testing\nimport cupyx\nimport cupyx.scipy.stats # NOQA\n\ntry:\n import scipy.stats\nexcept ImportError:\n pass\n\n\n@testing.with_requires('scipy')\nclass TestTrim:\n\n @testing.for_CF_orders()\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(\n scipy_name='scp', rtol=1e-6, contiguous_check=False)\n @pytest.mark.parametrize('shape', [(24,), (6, 4), (6, 4, 3), (4, 6)])\n def test_base(self, xp, scp, dtype, order, shape):\n a = testing.shaped_random(\n shape, xp=xp, dtype=dtype, order=order, scale=100)\n return scp.stats.trim_mean(a, 2 / 6.)\n\n @testing.for_all_dtypes()\n def test_zero_dim(self, dtype):\n for xp, scp in [(numpy, scipy), (cupy, cupyx.scipy)]:\n a = xp.array(0, dtype=dtype)\n with pytest.raises(IndexError):\n return scp.stats.trim_mean(a, 2 / 6.)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(scipy_name='scp')\n def test_zero_dim_axis_none(self, xp, scp, dtype):\n a = xp.array(0, dtype=dtype)\n return scp.stats.trim_mean(a, 2 / 6., axis=None)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(scipy_name='scp')\n @pytest.mark.parametrize('propotiontocut', [0.0, 0.6])\n def test_empty(self, xp, scp, dtype, propotiontocut):\n a = xp.array([])\n return scp.stats.trim_mean(a, 2 / 6., propotiontocut)\n\n @testing.for_CF_orders()\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(\n scipy_name='scp', rtol=1e-6, contiguous_check=False)\n @pytest.mark.parametrize('axis', [0, 1, 2, 3, -1, None])\n def test_axis(self, xp, scp, dtype, order, axis):\n a = testing.shaped_random(\n (5, 6, 4, 7), xp=xp, dtype=dtype, order=order, scale=100)\n return scp.stats.trim_mean(a, 2 / 6., axis=axis)\n\n def test_propotion_too_big(self):\n for xp, scp in [(numpy, scipy), (cupy, cupyx.scipy)]:\n a = xp.array([4, 8, 2, 0, 9, 5, 10, 1, 7, 3, 6])\n with pytest.raises(ValueError):\n scp.stats.trim_mean(a, 0.6)\n","sub_path":"tests/cupyx_tests/scipy_tests/stats_tests/test_stats.py","file_name":"test_stats.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"342822567","text":"#This script constructs an iTOL tree with information of loci counts and heritability using itol.py\n#It is based on the example.py script provided by A. Wang at https://github.com/albertyw/itolapi\n#To use mgwas_itol.py, you need a tree, a loci counts table and heritability data.\n\n#Import required modules\nimport os\nimport sys\nfrom itolapi import Itol, ItolExport\n\n#Define paths\npathname = os.path.dirname(sys.argv[0])\nfullpath = os.path.abspath(pathname)\nparent_path = fullpath + \"/../\"\nsys.path.append(parent_path)\n\nprint('Running itol and itolexport script')\nprint('')\nprint('Creating the upload params')\n\n# Set the tree file, loci counts and heritability data\ntreefile = sys.argv[1]\ntree = fullpath + '/' + treefile\nlocicountsfile = sys.argv[2]\nlocicounts = fullpath + '/' + locicountsfile\nheritabilityfile = sys.argv[3]\nheritability = fullpath + '/' + heritabilityfile\n\n# Create the Itol class\nmgwastree = Itol.Itol()\nmgwastree.add_variable('treeFile', tree)\n\n# Add parameters\nmgwastree.add_variable('treeName', 'mgwastree')\nmgwastree.add_variable('treeFormat', 'newick')\n# Add parameters for loci counts (dataset1)\nmgwastree.add_variable('dataset1File', locicounts)\nmgwastree.add_variable('dataset1Label', 'colors')\nmgwastree.add_variable('dataset1Separator', 'comma')\nmgwastree.add_variable('dataset1Type', 'multibar')\nmgwastree.add_variable('dataset1PieTransparent', 'multibar')\nmgwastree.add_variable('dataset1PieRadiusMax', '200')\n# Add parameters for heritability (dataset2)\nmgwastree.add_variable('dataset2File', heritability)\nmgwastree.add_variable('dataset2Label', 'colors')\nmgwastree.add_variable('dataset2Type', 'colorstrip')\nmgwastree.add_variable('dataset2Separator', 'space')\nmgwastree.add_variable('dataset2BranchColoringType', 'branch')\n\n# Check parameters\nmgwastree.print_variables()\n# Submit the tree\nprint('')\nprint('Uploading the tree. This may take some time depending on how large the tree is and how much load there is on the itol server')\ngood_upload = mgwastree.upload()\nif not good_upload:\n print('There was an error:' + mgwastree.comm.upload_output)\n sys.exit(1)\n\n# Read the tree ID\nprint('Tree ID: ' + str(mgwastree.comm.tree_id))\n# Read the iTOL API return statement\nprint('iTOL output: ' + str(mgwastree.comm.upload_output))\n# Website to be redirected to iTOL tree\nprint('Tree Web Page URL: ' + mgwastree.get_webpage())\n# Warnings associated with the upload\nprint('Warnings: ' + str(mgwastree.comm.warnings))\n\n# Export the tree above to svg\nprint('Exporting to svg')\nitol_exporter = mgwastree.get_itol_export()\nexport_location = 'mgwas_tree.svg'\nitol_exporter.set_export_param_value('format', 'svg')\n#itol_exporter.set_export_param_value('resolution', '300')\nitol_exporter.set_export_param_value('fontSize', '90')\nitol_exporter.set_export_param_value('lineWidth', '18')\nitol_exporter.set_export_param_value('colorBranches', '1')\nitol_exporter.set_export_param_value('datasetList', 'dataset1,dataset2')\nitol_exporter.export('mgwas_tree.svg')\nprint('exported tree to ', export_location)\n","sub_path":"scripts/mgwas_itol.py","file_name":"mgwas_itol.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"308459323","text":"import itertools\r\n\r\nx = 1\r\ny = 1\r\nz = 1\r\nn = 2\r\n\r\nprint([list(coords)\r\n for coords in itertools.product(range(x+1), range(y+1), range(z+1))\r\n if sum(coords) != n])\r\n","sub_path":"lexicorder.py","file_name":"lexicorder.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"197845397","text":"#!/usr/bin/env python\n\"\"\"word-similarity-scores.py\n\nTest word vectors and collect word similarity metrics from human\nevaluations, measuring how close we were in absolute distance\nbetween human word similarity and vector space word similarity\nfor a given model.\"\"\"\n\nimport argparse\nimport csv\nimport os\nimport sys\n\nimport numpy as np\n\nfrom collections import namedtuple\nfrom gensim.models import KeyedVectors\n\nfrom sklearn.metrics.pairwise import cosine_similarity\n\nfrom tqdm.auto import tqdm\n\nfrom util import make_vec, make_tokenizer\n\n\nDataset = namedtuple(\"Dataset\", \"first second similarity scale postproc\")\n\nDATASETS = {\n \"mc-30.csv\": Dataset(1, 2, 3 ,4, lambda x: x),\n \"men.csv\": Dataset(1, 2, 3, 50, lambda x: x[:-2]),\n \"mturk-287.csv\": Dataset(1, 2, 3, 5, lambda x: x),\n \"mturk-771.csv\": Dataset(1, 2, 3, 5, lambda x: x),\n \"rg-65.csv\": Dataset(1, 2, 3, 4, lambda x: x),\n \"rw.csv\": Dataset(1, 2, 3, 10, lambda x: x),\n \"semeval17.csv\": Dataset(1, 2, 3, 4, lambda x: x),\n \"simverb-3500.csv\": Dataset(2, 3, 1, 4, lambda x: x),\n \"verb-143.csv\": Dataset(1, 2, 3, 4, lambda x: x),\n \"wordsim353-rel.csv\": Dataset(1, 2, 3, 10, lambda x: x),\n \"wordsim353-sim.csv\": Dataset(1, 2, 3, 10, lambda x: x),\n \"yp-130.csv\": Dataset(1, 2, 3, 4, lambda x: x),\n}\n\n\ndef load_dataset(name, path):\n with open(path) as f:\n csv_data = csv.reader(f)\n\n _ = next(csv_data)\n metadata = DATASETS[name]\n\n for row in csv_data:\n first = metadata.postproc(row[metadata.first])\n second = metadata.postproc(row[metadata.second])\n similarity = float(row[metadata.similarity]) / metadata.scale\n\n yield first, second, similarity\n\n\ndef score_dataset(model, dataset, tokenizer):\n \"\"\"Get score for one dataset for a given KeyedVectors model.\"\"\"\n tfunc = tokenizer.tokenize if tokenizer is not None else lambda x: [x]\n similarities = [\n abs(\n cosine_similarity(np.array([make_vec(model, tfunc(first))]),\n np.array([make_vec(model, tfunc(second))]))[0] -\n similarity\n )\n for first, second, similarity in tqdm(dataset, \"Processing Dataset\")\n if tokenizer is not None or (first in model.vocab and second in model.vocab)\n ]\n return np.mean(similarities)\n\n\ndef score_model(model, datasets, tokenizer):\n \"\"\"Get scores for all datasets.\"\"\"\n\n for dataset_name in tqdm(sorted(datasets.keys()), desc=\"Processing Datasets\"):\n yield score_dataset(model, datasets[dataset_name], tokenizer)\n\n\ndef load_model(name):\n \"\"\"Load a model.\"\"\"\n return KeyedVectors.load(name).wv\n\n\ndef main():\n \"\"\"Entry point.\"\"\"\n parser = argparse.ArgumentParser(\"\"\"Word similarity score checker.\"\"\")\n parser.add_argument(\"models\", nargs=\"+\")\n parser.add_argument(\"--benchmarks\", nargs=\"+\", default=list(DATASETS.keys()))\n parser.add_argument(\"--data-dir\", type=str, help=\"Path to data\")\n parser.add_argument(\"--tokenizer\", type=str, help=\"Tokenizer to use\")\n args = parser.parse_args()\n\n datasets = {\n n: list(load_dataset(n, os.path.join(args.data_dir, n))) for n in args.benchmarks\n }\n models = {\n os.path.basename(n): load_model(n) for n in args.models\n }\n tokenizer = make_tokenizer(args.tokenizer)\n\n output = csv.writer(sys.stdout)\n output.writerow(['model'] + sorted(datasets.keys()))\n for model_name in sorted(models.keys()):\n output.writerow([model_name] + list(score_model(models[model_name], datasets, tokenizer)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tests/word-similarity-scores.py","file_name":"word-similarity-scores.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"177800163","text":"'''\nCreated on Nov 3, 2015\n\n@author: turbineyan\n'''\n#coding=utf-8\nimport logging\nimport sys\n\n\n'''\nutility for getting break point info,as line number, function name and so on.\\\nprint sys._getframe().f_code.co_name\nprint sys._getframe().f_back.f_code.co_name\n'''\ndef _get_breakpoint():\n funcName = sys._getframe(1).f_back.f_code.co_name\n lineNumber = sys._getframe(1).f_back.f_lineno\n return (funcName,lineNumber)\n\nclass Logger(object):\n '''\n classdocs\n '''\n def __init__(self,theModuleName):\n '''\n Constructor\n '''\n logging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s %(levelname)s %(message)s',\n filename='/tmp/spider.log',\n filemode='w'\n )\n\n self.theModuleName = theModuleName\n self.logger = logging.getLogger(theModuleName)\n self.logger.setLevel(logging.FATAL)\n\n \n def __log(self,level,text,func, line):\n print ('%s: [@fn=%s,ln=%s]%s'%(level,func,line,text))\n if level == 'warn':\n logging.warning('[@fn=%s,ln=%s]%s'%(func,line,text))\n elif level == 'Fatal':\n logging.fatal('[@fn=%s,ln=%s]%s'%(func,line,text))\n elif level == 'Error':\n logging.error('[@fn=%s,ln=%s]%s'%(func,line,text))\n elif level == 'Info':\n logging.info('[@fn=%s,ln=%s]%s'%(func,line,text))\n elif level == 'Debug':\n logging.debug('[@fn=%s,ln=%s]%s'%(func,line,text))\n \n \n def warn(self,text=''):\n func,line = _get_breakpoint()\n self.__log('warn', text,func,line)\n\n\n def fatal(self,text=''):\n func,line = _get_breakpoint()\n self.__log('Fatal', text,func,line)\n \n def error(self,text=''):\n func,line = _get_breakpoint()\n self.__log('Error', text, func,line)\n \n \n def info(self,text=''):\n func,line = _get_breakpoint()\n self.__log('Info', text, func,line)\n \n def debug(self,text=''):\n func,line = _get_breakpoint()\n self.__log('Debug', text, func,line)\n\n\n\n","sub_path":"Log.py","file_name":"Log.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"184883846","text":"################ main.py\nimport sys\nfrom PyQt5 import QtGui, QtWidgets,QtCore\nfrom gui import Ui_Dialog\n\n\nclass mywindow(QtWidgets.QMainWindow,Ui_Dialog):\n def __init__(self):\n super(mywindow, self).__init__()\n self.setupUi(self)\n \n def showImage(self,imgName):\n if imgName!='':\n i1=QtGui.QPixmap(imgName)\n i1=i1.scaled(self.lbl_img.width(),self.lbl_img.height(),QtCore.Qt.KeepAspectRatio) #圖片等比例塞到Dialog中\n self.lbl_img.setPixmap(i1) #lil_img: 圖片在這裡顯示\n self.lbl_img.setAlignment(QtCore.Qt.AlignCenter) #設置對齊方式 \n \n def on_slc_Img(self):\n imgName, _=QtWidgets.QFileDialog.getOpenFileName(None,'Select Image TITLE_HERE','','Images (*.jpg)') #選擇檔案\n self.showImage(imgName)\n \nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n Main = mywindow() \n Main.show()\n sys.exit(app.exec_())\n\n","sub_path":"main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"557968242","text":"# ----------------------------------------------------------------------\r\n# |\r\n# | StatementsParser.py\r\n# |\r\n# | David Brownell \r\n# | 2021-05-11 05:50:49\r\n# |\r\n# ----------------------------------------------------------------------\r\n# |\r\n# | Copyright David Brownell 2021\r\n# | Distributed under the Boost Software License, Version 1.0. See\r\n# | accompanying file LICENSE_1_0.txt or copy at\r\n# | http://www.boost.org/LICENSE_1_0.txt.\r\n# |\r\n# ----------------------------------------------------------------------\r\n\"\"\"Contains functionality that parses multiple statements\"\"\"\r\n\r\nimport os\r\nimport textwrap\r\n\r\nfrom collections import OrderedDict\r\nfrom concurrent.futures import Future\r\nfrom typing import Callable, Dict, List, Optional, Tuple, Union\r\nfrom dataclasses import dataclass, field, InitVar\r\n\r\nimport CommonEnvironment\r\nfrom CommonEnvironment import Interface\r\nfrom CommonEnvironment import StringHelpers\r\n\r\nfrom CommonEnvironmentEx.Package import InitRelativeImports\r\n\r\n# ----------------------------------------------------------------------\r\n_script_fullpath = CommonEnvironment.ThisFullpath()\r\n_script_dir, _script_name = os.path.split(_script_fullpath)\r\n# ----------------------------------------------------------------------\r\n\r\nwith InitRelativeImports():\r\n from .Error import Error\r\n from .NormalizedIterator import NormalizedIterator\r\n from .Statement import DynamicStatements, Statement\r\n\r\n\r\n# ----------------------------------------------------------------------\r\n@dataclass(frozen=True)\r\nclass DynamicStatementInfo(object):\r\n \"\"\"Contains statements that have dynamically been added to the active scope\"\"\"\r\n\r\n statements: List[Statement]\r\n expressions: List[Statement]\r\n allow_parent_traversal: bool = True # If False, prevent content from including values from higher-level scope\r\n name: Optional[str] = None\r\n\r\n # ----------------------------------------------------------------------\r\n def Clone(\r\n self,\r\n updated_statements=None,\r\n updated_expressions=None,\r\n updated_allow_parent_traversal=None,\r\n updated_name=None,\r\n ):\r\n return self.__class__(\r\n updated_statements if updated_statements is not None else list(self.statements),\r\n updated_expressions if updated_expressions is not None else list(self.expressions),\r\n updated_allow_parent_traversal if updated_allow_parent_traversal is not None else self.allow_parent_traversal,\r\n name=updated_name if updated_name is not None else self.name,\r\n )\r\n\r\n\r\n# ----------------------------------------------------------------------\r\n@dataclass(frozen=True)\r\nclass InvalidDynamicTraversalError(Error):\r\n \"\"\"Exception thrown when dynamic statements that prohibit parent traversal are applied over other dynamic statements\"\"\"\r\n\r\n ExistingDynamicStatements: List[NormalizedIterator]\r\n\r\n MessageTemplate = Interface.DerivedProperty(\"Dynamic statements that prohibit parent traversal should never be applied over other dynamic statements within the same lexical scope. You should make these dynamic statements the first ones applied in this lexical scope.\")\r\n\r\n\r\n# ----------------------------------------------------------------------\r\n@dataclass(frozen=True)\r\nclass SyntaxInvalidError(Error):\r\n \"\"\"Exception thrown when no matching statements were found\"\"\"\r\n\r\n PotentialStatements: Dict[Statement, Statement.ParseResultItemsType] = field(init=False)\r\n parse_result_items: InitVar[Statement.ParseResultItemsType]\r\n\r\n MessageTemplate = Interface.DerivedProperty(\"The syntax is not recognized\")\r\n\r\n # ----------------------------------------------------------------------\r\n def __post_init__(self, parse_result_items):\r\n potentials = OrderedDict()\r\n\r\n for parse_result_item in parse_result_items:\r\n key = parse_result_item.Statement\r\n\r\n if isinstance(key, Statement.NamedItem):\r\n key = key.Item\r\n\r\n if isinstance(key, list):\r\n key = tuple(key)\r\n\r\n potentials[key] = parse_result_item.Results\r\n\r\n object.__setattr__(self, \"PotentialStatements\", potentials)\r\n\r\n # ----------------------------------------------------------------------\r\n def DebugString(self):\r\n content = []\r\n\r\n for parse_results in self.PotentialStatements.values():\r\n for parse_result in parse_results:\r\n if not getattr(parse_result, \"Results\", True):\r\n continue\r\n\r\n # If here, we are looking at a token or something with results\r\n content.append(str(parse_result))\r\n\r\n return textwrap.dedent(\r\n \"\"\"\\\r\n {msg} [{line}, {column}]\r\n\r\n Partial Matches:\r\n {partial}\r\n\r\n \"\"\",\r\n ).format(\r\n msg=str(self),\r\n line=self.Line,\r\n column=self.Column,\r\n partial=\"\" if not content else StringHelpers.LeftJustify(\"\\n\".join(content).rstrip(), 4),\r\n )\r\n\r\n\r\n# ----------------------------------------------------------------------\r\nclass Observer(Interface.Interface):\r\n # ----------------------------------------------------------------------\r\n @staticmethod\r\n @Interface.abstractmethod\r\n def Enqueue(\r\n funcs: List[Callable[[], None]],\r\n ) -> List[Future]:\r\n \"\"\"Enqueues the funcs for execution\"\"\"\r\n raise Exception(\"Abstract method\") # pragma: no cover\r\n\r\n # ----------------------------------------------------------------------\r\n @staticmethod\r\n @Interface.abstractmethod\r\n def OnIndent(\r\n statement: Statement,\r\n results: Statement.ParseResultItemsType,\r\n ) -> Optional[DynamicStatementInfo]:\r\n raise Exception(\"Abstract method\") # pragma: no cover\r\n\r\n # ----------------------------------------------------------------------\r\n @staticmethod\r\n @Interface.abstractmethod\r\n def OnDedent(\r\n statement: Statement,\r\n results: Statement.ParseResultItemsType,\r\n ):\r\n raise Exception(\"Abstract method\") # pragma: no cover\r\n\r\n # ----------------------------------------------------------------------\r\n @staticmethod\r\n @Interface.abstractmethod\r\n def OnStatementComplete(\r\n result: Statement.StatementParseResultItem,\r\n iter_before: NormalizedIterator,\r\n iter_after: NormalizedIterator,\r\n ) -> Union[\r\n bool, # True to continue processing, False to terminate\r\n DynamicStatementInfo, # DynamicStatementInfo generated by the statement (if necessary)\r\n ]:\r\n \"\"\"Called on the completion of each statement\"\"\"\r\n raise Exception(\"Abstract method\") # pragma: no cover\r\n\r\n\r\n# ----------------------------------------------------------------------\r\ndef Parse(\r\n initial_statement_info: DynamicStatementInfo,\r\n normalized_iter: NormalizedIterator,\r\n observer: Observer,\r\n\r\n # True to execute all statements within a single thread\r\n single_threaded=False,\r\n) -> Optional[List[Statement.StatementParseResultItem]]:\r\n \"\"\"Repeatedly matches statements for all of the iterator\"\"\"\r\n\r\n assert normalized_iter.Offset == 0, normalized_iter.Offset\r\n\r\n statement_observer = _StatementObserver(initial_statement_info, observer)\r\n results = []\r\n\r\n while not normalized_iter.AtEnd():\r\n result = Statement.ParseMultiple(\r\n statement_observer.GetDynamicStatements(DynamicStatements.Statements),\r\n normalized_iter,\r\n statement_observer,\r\n single_threaded=single_threaded,\r\n )\r\n\r\n if result is None:\r\n return None\r\n\r\n if not result.Success:\r\n raise SyntaxInvalidError(\r\n result.Iter.Line,\r\n result.Iter.Column,\r\n result.Results,\r\n )\r\n\r\n normalized_iter = result.Iter\r\n\r\n assert len(result.Results) == 1, result.Results\r\n result = result.Results[0]\r\n\r\n results.append(result)\r\n\r\n assert normalized_iter.AtEnd()\r\n\r\n return results\r\n\r\n\r\n# ----------------------------------------------------------------------\r\n# ----------------------------------------------------------------------\r\n# ----------------------------------------------------------------------\r\nclass _StatementObserver(Statement.Observer):\r\n # ----------------------------------------------------------------------\r\n def __init__(\r\n self,\r\n init_statement_info: InitVar[DynamicStatementInfo],\r\n observer: Observer,\r\n ):\r\n all_statement_infos: List[\r\n List[\r\n Tuple[\r\n Optional[NormalizedIterator],\r\n DynamicStatementInfo,\r\n ]\r\n ]\r\n ] = [\r\n [ (None, init_statement_info.Clone()) ],\r\n ]\r\n\r\n self._observer = observer\r\n self._all_statement_infos = all_statement_infos\r\n\r\n self._cached_statements: Union[Statement.NamedItem, List[Statement]] = []\r\n self._cached_expressions: Union[Statement.NamedItem, List[Statement]] = []\r\n\r\n self._UpdateCache()\r\n\r\n # ----------------------------------------------------------------------\r\n @Interface.override\r\n def Enqueue(\r\n self,\r\n funcs: List[Callable[[], None]],\r\n ) -> List[Future]:\r\n return self._observer.Enqueue(funcs)\r\n\r\n # ----------------------------------------------------------------------\r\n @Interface.override\r\n def GetDynamicStatements(\r\n self,\r\n value: DynamicStatements,\r\n ) -> List[Statement]:\r\n if value == DynamicStatements.Statements:\r\n return self._cached_statements\r\n elif value == DynamicStatements.Expressions:\r\n return self._cached_expressions\r\n else:\r\n assert False, value # pragma: no cover\r\n\r\n # Make the linter happy\r\n return [] # pragma: no cover\r\n\r\n # ----------------------------------------------------------------------\r\n @Interface.override\r\n def OnIndent(self, statement, results):\r\n self._all_statement_infos.append([])\r\n\r\n this_result = self._observer.OnIndent(statement, results)\r\n if isinstance(this_result, DynamicStatementInfo):\r\n self.AddDynamicStatementInfo(results[-1].IterAfter, this_result)\r\n\r\n return None\r\n\r\n # ----------------------------------------------------------------------\r\n @Interface.override\r\n def OnDedent(self, statement, results):\r\n assert self._all_statement_infos\r\n self._all_statement_infos.pop()\r\n assert len(self._all_statement_infos) >= 1, self._all_statement_infos\r\n\r\n self._UpdateCache()\r\n\r\n self._observer.OnDedent(statement, results)\r\n\r\n # ----------------------------------------------------------------------\r\n @Interface.override\r\n def OnInternalStatement(\r\n self,\r\n result: Statement.StatementParseResultItem,\r\n iter_before: NormalizedIterator,\r\n iter_after: NormalizedIterator,\r\n ) -> bool:\r\n this_result = self._observer.OnStatementComplete(result, iter_before, iter_after)\r\n\r\n if isinstance(this_result, DynamicStatementInfo):\r\n self.AddDynamicStatementInfo(iter_before, this_result)\r\n return True\r\n\r\n return this_result\r\n\r\n # ----------------------------------------------------------------------\r\n def AddDynamicStatementInfo(\r\n self,\r\n normalized_iter: NormalizedIterator,\r\n info: DynamicStatementInfo,\r\n ):\r\n if not info.statements and not info.expressions:\r\n return\r\n\r\n if not info.allow_parent_traversal and self._all_statement_infos[-1]:\r\n raise InvalidDynamicTraversalError(\r\n normalized_iter.Line,\r\n normalized_iter.Column,\r\n [location for location, _ in self._all_statement_infos[-1] if location is not None],\r\n )\r\n\r\n self._all_statement_infos[-1].append((normalized_iter, info))\r\n\r\n self._UpdateCache()\r\n\r\n # ----------------------------------------------------------------------\r\n # ----------------------------------------------------------------------\r\n # ----------------------------------------------------------------------\r\n def _UpdateCache(self):\r\n statements = []\r\n statement_names = []\r\n\r\n expressions = []\r\n expression_names = []\r\n\r\n for statement_infos in reversed(self._all_statement_infos):\r\n for _, statement_info in reversed(statement_infos):\r\n if statement_info.statements:\r\n statements += statement_info.statements\r\n statement_names.append(\r\n statement_info.name or Statement.ItemTypeToString(statement_info.statements),\r\n )\r\n\r\n if statement_info.expressions:\r\n expressions += statement_info.expressions\r\n expression_names.append(\r\n statement_info.name or Statement.ItemTypeToString(statement_info.expressions),\r\n )\r\n\r\n if statement_infos and not statement_infos[0][1].allow_parent_traversal:\r\n break\r\n\r\n # In the code above, we reversed the list so that statements added later (or nearer)\r\n # to the code would be matched before statements defined further away. However when\r\n # displaying the content names, we want the names to be the order in which they were\r\n # defined.\r\n if statement_names:\r\n statement_names = \" / \".join(reversed(statement_names))\r\n statements = Statement.NamedItem(statement_names, statements)\r\n\r\n if expression_names:\r\n expression_names = \" / \".join(reversed(expression_names))\r\n expressions = Statement.NamedItem(expression_names, expressions)\r\n\r\n self._cached_statements = statements\r\n self._cached_expressions = expressions\r\n","sub_path":"src/TheLanguage/ParserImpl/StatementsParser.py","file_name":"StatementsParser.py","file_ext":"py","file_size_in_byte":14255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"309852885","text":"from scrapy.spider import Spider\nfrom Bookies.loaders import EventLoader\nfrom Bookies.items import EventItem2\nfrom scrapy.contrib.loader.processor import TakeFirst\nfrom scrapy import log\n# from Bookies.help_func import linkFilter\nfrom scrapy.http import Request\nimport json\nimport re\ntake_first = TakeFirst()\n\n# Another bpsgameserver like Dhoze and Betsson.\n\n\nclass DhozeSpider(Spider):\n name = \"Dhoze\"\n allowed_domains = [\"dhoze.com\", \"bpsgameserver.com\"]\n\n # Set session cookie\n start_urls = ['https://apostas.dhoze.com/en/']\n\n # First make the leagues request to bpsgameserver\n def parse(self, response):\n\n base_url = ('https://sbfacade.bpsgameserver.com/'\n 'PlayableMarketService/PlayableMarketServicesV2.svc/'\n 'jsonp/FetchLeftMenuJSONP?')\n GETstr = 'unique=15_39_&segmentId=501&languageCode=en&callback=_jqjsp'\n\n yield Request(url=base_url+GETstr, callback=self.parse_leagues)\n\n def parse_leagues(self, response):\n\n # Extract the needed params from the JSON response\n # JSON is between _jqjsp(....); so extract with regex\n matches = re.findall(r'_jqjsp\\((.+?)\\);', response.body)\n if matches:\n jsonResp = json.loads(matches[0])\n\n # Now we have the left sidebar in JSON format,\n # get needed football league ids\n idList = []\n for country in jsonResp['FetchLeftMenuJSONPResult']['c_c'][0]['sc_r']:\n for league in country['sc_c']:\n # print league['i_c'], league['mc'], league['n'], league['rid']\n idList.append(league['i_c'])\n base_url = ('https://sbfacade.bpsgameserver.com/PlayableMarketService/'\n 'PlayableMarketServicesV2.svc/jsonp/'\n 'FetchPrematchFullMarketsWithSortOrderJSONP?')\n for id in idList:\n # 'unique' param looks like it is set in the jquery script\n # (http://jsbeautifier.org/ is nice to search these scripts)\n # It seems to increase with each req, but for now I leave fixed,\n # seems fine. segmentid seems always fixed.\n # I increase noOfEventsPerPageMain to 200\n # (as is possible on the drop down).\n GETstr = \"unique=15_48_&subCategoryIds=\"+str(id)+\"&segmentid=201&languageCode=en&clientTimeZone=UTC%2B02.00&\"\n GETstr += \"noOfEventsPerPageProView=50&noOfEventsPerPageMain=200&noOfEventsPerPagePopular=50&\"\n GETstr += \"noOfEventsPerPage1stHalf=50&noOfEventsPerPageHandicap=50&noOfEventsPerPageGoals=50&\"\n GETstr += \"noOfEventsPerPageSpecials=50&noOfEventsPerPageOutrights=50&noOfhrsForStartingSoon=0&callback=_jqjsp\"\n # Arguably we should inc referer in the header here. Seems to work without\n # might have to work on this in future if becomes a prob\n yield Request(url=base_url+GETstr, callback=self.pre_parse_Data)\n\n def pre_parse_Data(self, response):\n\n # JSON is between _jqjsp(....); so extract with regex\n matches = re.findall(r'_jqjsp\\((.+?)\\);', response.body)\n if matches:\n jsonResp = json.loads(matches[0])\n\n try:\n jsonData = jsonResp['FetchPrematchFullMarketsWithSortOrderJSONPResult']['mmEv']['mListEvts']\n except KeyError as e:\n log.msg('KeyError: %s' % (self.name, e), level=log.ERROR)\n log.msg('Error response or 404?' % (self.name), level=log.ERROR)\n log.msg('response dump: %s ' % (self.name, jsonResp), level=log.ERROR)\n yield []\n\n base_url = ('https://sbfacade.bpsgameserver.com/PlayableMarketService/'\n 'PlayableMarketServicesV2.svc/jsonp/'\n 'FetchPrematchEventMarketsByEventIdJSONP')\n\n # After mListEvts the events are in a list ordered by date\n for eventBlock in jsonData:\n for event in eventBlock['PrmEvts']:\n\n eid = event['Id']\n sid = event['SubCategoryId']\n GETstr = ('?unique=0_0_&subcategoryId=%s&eventId=%s&'\n 'languageCode=en&segmentid=501&callback=_jqjsp' % (sid, eid))\n yield Request(url=base_url+GETstr, callback=self.parseData)\n\n def parseData(self, response):\n\n log.msg('Going to parse data for URL: %s' % response.url[20:],\n level=log.INFO)\n\n # JSON is between _jqjsp(....); so extract with regex\n matches = re.findall(r'_jqjsp\\((.+?)\\);', response.body)\n if matches:\n jsonResp = json.loads(matches[0])\n\n try:\n jsonData = jsonResp['FetchPrematchEventMarketsByEventIdJSONPResult']\n except KeyError as e:\n log.msg('KeyError: %s' % (self.name, e), level=log.ERROR)\n log.msg('Error response or 404?' % (self.name), level=log.ERROR)\n log.msg('response dump: %s ' % (self.name, jsonResp), level=log.ERROR)\n return []\n\n l = EventLoader(item=EventItem2(), response=response)\n l.add_value('sport', u'Football')\n l.add_value('bookie', self.name)\n\n dateTime = jsonData['DeadlineUTC']\n l.add_value('dateTime', dateTime)\n\n eventName = jsonData['Name']\n if eventName:\n teams = eventName.lower().split(' - ')\n l.add_value('teams', teams)\n\n # Markets\n mkts = jsonData['Markets']\n allmktdicts = []\n for mkt in mkts:\n marketName = mkt['Name']\n mdict = {'marketName': marketName, 'runners': []}\n runners = mkt['Selections']\n for runner in runners:\n runnername = runner['Name']\n price = runner['Odds']\n mdict['runners'].append({'runnerName': runnername, 'price': price})\n allmktdicts.append(mdict)\n\n # Do some Dhoze specific post processing and formating\n for mkt in allmktdicts:\n if mkt['marketName'] == 'Match Winner':\n mkt['marketName'] = 'Match Odds'\n for runner in mkt['runners']:\n if runner['runnerName'] == u'1':\n runner['runnerName'] = 'HOME'\n elif runner['runnerName'] == u'2':\n runner['runnerName'] = 'AWAY'\n elif runner['runnerName'] == u'X':\n runner['runnerName'] = 'DRAW'\n # Add markets\n l.add_value('markets', allmktdicts)\n\n # Load item\n return l.load_item()\n","sub_path":"Bookies/spiders/Dhoze_spider.py","file_name":"Dhoze_spider.py","file_ext":"py","file_size_in_byte":6486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"597799847","text":"from flask import Flask, flash, redirect, render_template, \\\n request, url_for\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport subprocess\nimport json\nimport os\n\nfrom datetime import datetime\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///reports.db'\napp.secret_key = 'ksafkjnsakjnfsnafknds'\n\ndb = SQLAlchemy(app)\n\n\nclass Report(db.Model):\n __tablename__ = 'reports'\n id = db.Column(db.Integer, primary_key=True)\n created = db.Column(db.DateTime)\n\n duration = db.Column(db.Float)\n scenarios = db.Column(db.Integer)\n successes = db.Column(db.Integer)\n failures = db.Column(db.Integer)\n steps = db.Column(db.Integer)\n\n def __init__(self, summary):\n\n self.created = datetime.utcnow()\n self.duration = summary['scenarios']\n self.scenarios = summary['scenarios']\n self.successes = summary['successes']\n self.failures = summary['failures']\n self.steps = summary['steps']\n\n def __repr__(self):\n return '' % self.id\n\n\ndef write_report(report_json, report_id):\n report_json_file = open('./static/reports/{}.json'.format(report_id), 'w')\n\n report_json_file.write(json.dumps(report_json))\n report_json_file.close()\n\n\ndef read_report(report_id):\n report_json_file = open('./static/reports/{}.json'.format(report_id), 'r')\n\n report_json = report_json_file.read()\n report_json_file.close()\n\n return json.loads(report_json)\n\n\ndef parse_tags(loaded_json):\n for report_json in loaded_json:\n if report_json['tags']:\n report_json['tags'] = \",\".join(map(lambda tag: tag.name, report_json.tags))\n else:\n report_json['tags'] = ''\n\n\ndef scenario_summary(loaded_json):\n scenarios = 0\n successes = 0\n failures = 0\n duration = float(0)\n steps = 0\n\n for report_json in loaded_json:\n\n scenarios += len(report_json[\"elements\"])\n\n for element in report_json[\"elements\"]:\n steps += len(element['steps'])\n failures += len([step for step in element[\"steps\"] if \"result\" in step and step[\"result\"][\"status\"] == \"failed\"])\n duration += sum([step[\"result\"][\"duration\"] for step in element[\"steps\"] if \"result\" in step])\n successes = steps - failures\n\n return {\n \"duration\": duration,\n \"scenarios\": scenarios,\n \"successes\": successes,\n \"failures\": failures,\n \"steps\": steps\n }\n\n\ndef run_report(args):\n try:\n subprocess.check_call(args)\n except:\n pass\n\n try:\n loaded_json = json.loads(open(\"behave.json\", 'r').read())\n\n parse_tags(loaded_json)\n summary = scenario_summary(loaded_json)\n\n app.logger.debug(summary)\n\n new_report = Report(summary)\n\n db.session.add(new_report)\n db.session.commit()\n\n write_report(loaded_json, new_report.id)\n\n flash(u\"Published report # {report_id}: \".format(report_id=new_report.id), 'success')\n except:\n flash(u\"Error on publishing report\", 'danger')\n\n\n@app.route('/publish/')\ndef publish_single(feature_file):\n feature_file = \"features/{}\".format(feature_file)\n\n if not os.path.exists(feature_file):\n flash(u\"Feature file not found\", 'danger')\n else:\n publish_args = [\"behave\", feature_file, \"-f\", \"json.pretty\", \"-o\", \"behave.json\"]\n\n run_report(publish_args)\n\n return redirect(url_for('reports'))\n\n\n@app.route('/publish')\ndef publish():\n publish_args = [\"behave\", \"-f\", \"json.pretty\", \"-o\", \"behave.json\"]\n\n run_report(publish_args)\n\n return redirect(url_for('reports'))\n\n\n@app.route('/reports/')\ndef report(report_id):\n return render_template('report.html', reports=read_report(report_id))\n\n\n@app.route('/')\ndef reports():\n return render_template('index.html', reports=Report.query.order_by('id DESC'))\n\nif __name__ == '__main__':\n db.create_all()\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"build_server.py","file_name":"build_server.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"520176745","text":"from unittest import TestCase\nfrom icon_storage.util.cache_help import CacheHelp\nfrom icon_storage.actions.store import Store\n\n\nclass TestStoreAction(TestCase):\n def test_store(self):\n store = Store()\n params = {\n \"variable_name\": \"foobar\",\n \"variable_value\": \"barfoo\"\n }\n store.run(params)\n cache_help = CacheHelp()\n\n # This is cheaty, but it's a test\n actual = cache_help._get_dict_from_store()\n expected = {'foobar': 'barfoo'}\n\n self.assertEqual(expected, actual)\n cache_help._delete_dict_file()\n","sub_path":"storage/unit_test/test_store.py","file_name":"test_store.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"535587477","text":"import requests\nfrom lxml import html\nimport json\nimport datetime as dt\nimport global_settings as gs\n\nif not gs.local:\n import boto3 \n from dynamodb_json import json_util as dyjson\n\n\ndef daterange(start_date, end_date):\n \"\"\"\n Works the same as python's 'range' but for datetime in days.\n As in 'range', the 'end_date' is omitted.\n \"\"\"\n for n in range(int ((end_date - start_date).days)):\n yield start_date + dt.timedelta(n)\n\n\ndef get_artigos_do(data, secao):\n \"\"\"\n For a date (datetime) 'data' and a DOU section 'secao', \n retuns a list of jsons with all links to that day and section's\n articles, along with some metadata.\n \n If no articles exist for a certain date and/or section, \n if returns an empty list.\n \"\"\"\n\n # Hard-coded:\n do_date_format = '%d-%m-%Y'\n url_prefix = 'http://www.in.gov.br/leiturajornal?data='\n url_sec_sel = '&secao=do'\n \n # Transforms date to DOU format:\n data_string = data.strftime(do_date_format)\n \n # Example of URL: 'http://www.in.gov.br/leiturajornal?data=13-05-2019&secao=do1'\n url = url_prefix + data_string + url_sec_sel + str(secao)\n\n # Specifies number of retries for GET:\n session = requests.Session()\n session.mount('http://www.in.gov.br', requests.adapters.HTTPAdapter(max_retries=3))\n \n # Captura a lista de artigos daquele dia e seção:\n res = session.get(url, timeout=10)\n if res.status_code != 200:\n raise Exception('http GET request failed with code '+str(res.status_code)+'!')\n tree = html.fromstring(res.content)\n xpath = '//*[@id=\"params\"]/text()'\n return json.loads(tree.xpath(xpath)[0])['jsonArray']\n\n\ndef fix_filename(urlTitle):\n \"\"\"\n Change the url 'urlTitle' substring used to acess the DOU article to something \n that can be used as part of a filename. \n \"\"\"\n fixed = urlTitle.replace('//', '/')\n return fixed\n\n\ndef brasilia_day():\n \"\"\"\n No matter where the code is ran, return UTC-3 day\n (Brasilia local day, no daylight savings)\n \"\"\"\n return (dt.datetime.utcnow() + dt.timedelta(hours=-3)).replace(hour=0, minute=0, second=0, microsecond=0)\n\n\ndef update_config(config, Narticles_in_section):\n \"\"\"\n Given a config file for capturing DOU articles' URLs and a dict \n that states how many articles were found in each requested section\n 'Narticles_in_section', return an updated config for the next request \n try. \n \n Required config keys:\n * end_date > The articles' date to request the URLs;\n * date_format > The format of the date above (e.g. %Y-%m-%d);\n * secao > Current list of sections to request URLs;\n * secao_all > All sections one may want to request (does not update);\n * timedelta > Current implementation requires this to be 0.\n` * last_extra > The extra edition number of the last capture.\n \"\"\"\n \n if config['timedelta'] != 0:\n raise Exception('current implementation only allows timedelta=0.')\n \n # Copy config:\n config2 = dict(config)\n end_date = dt.datetime.strptime(config['end_date'], config['date_format'])\n \n # If end_date is in the future, keep the same config:\n if end_date > brasilia_day():\n return config2\n \n # If end_date is in the past, return next day and all sections:\n if end_date < brasilia_day():\n config2['secao'] = config['secao_all']\n config2['end_date'] = (end_date + dt.timedelta(days=1)).strftime(config['date_format'])\n config2['last_extra'] = 0\n return config2\n \n # PRESENT DAY: find out missing sections and set config to that:\n # PS: always keep Extra ('e') because it can appear at any time \n section_keys = list(filter(lambda k: Narticles_in_section[k] == 0 or k == 'e', Narticles_in_section.keys()))\n config2['secao'] = section_keys\n\n # If there are no missing sections, reset sections list and get next day:\n if len(section_keys)==0:\n config2['end_date'] = (end_date + dt.timedelta(days=1)).strftime(config['date_format'])\n config2['secao'] = config['secao_all']\n \n return config2\n\n\ndef get_articles_url(config):\n \"\"\"\n Get as input a dict 'config' with keys:\n \n * 'date_format': format of 'end_date' below, e.g. '%Y-%m-%d';\n * 'end_date': last date to search for URLs (one can set to 'now' to get the current day); \n * 'secao': list of DOU sections to scan (1, 2, 3, e and/or 1a, or set to 'all' for '[1,2,3,e]';\n * 'timedelta': number of days from end_date to start URL search (is a negative number);\n \n and creates a list of DOU articles' URLs to download. \n \"\"\"\n \n # Hard-coded stuff:\n url_prefix = 'http://www.in.gov.br/web/dou/-/'\n \n # Debug message:\n if True or gs.debug == True:\n print(\"Starting get_articles_url with config:\")\n print(config)\n \n # Translate string representing date to datetime:\n if gs.debug == True:\n print('Reading date range...')\n if config['end_date'] == 'now':\n end_date = brasilia_day()\n elif config['end_date'] == 'yesterday':\n end_date = brasilia_day() + dt.timedelta(days=-1)\n else:\n end_date = dt.datetime.strptime(config['end_date'], config['date_format'])\n # Save it back to config dict:\n config['end_date'] = end_date.strftime(config['date_format'])\n \n timedelta = dt.timedelta(days=config['timedelta'])\n \n # If end_date is in the future, return empty list and same config\n # (wait for the next day):\n # PS: this will skip request URLs even for negative timedelta.\n if end_date > brasilia_day():\n return [], config\n \n # Translate secao config to a list of strings:\n if gs.debug == True:\n print('Reading selected sections...') \n secoes = config['secao']\n secoes = [1, 2, 3, 'e', '1a'] if secoes == 'all' else secoes\n secoes = secoes if type(secoes) == list else [secoes]\n secoes = [str(s) for s in secoes]\n \n # LOOP over dates:\n url_file_list = []\n Narticles_in_section = dict(zip(secoes, [0]*len(secoes)))\n start_date = end_date + timedelta\n if gs.debug == True:\n print('Will enter loop over config date and section range:') \n for date in daterange(start_date, end_date + dt.timedelta(days=1)):\n if gs.debug == True:\n print('-- '+date.strftime('%Y-%m-%d'))\n # LOOP over DOU sections:\n for s in secoes:\n if gs.debug == True:\n print(' -- s'+str(s))\n jsons = get_artigos_do(date, s)\n Narticles_in_section[s] = len(jsons)\n # LOOP over downloaded URL list:\n if gs.debug == True:\n print(' Looping over URLs...') \n for j in jsons:\n url = url_prefix + j['urlTitle']\n filename = date.strftime('%Y-%m-%d') + '_s' + str(s) + '_' + fix_filename(j['urlTitle']) + '.json'\n url_file_list.append({'url':url, 'filename':filename})\n \n return url_file_list, update_config(config, Narticles_in_section)\n\n\ndef load_remote_config():\n \"\"\"\n Given a hard-coded table reference in dynamoDB (AWS) (see event), \n loads the configuration for the DOU articles' capture.\n \"\"\"\n \n # Event for old lambda_handler, tells which data in dynamoDB to load:\n event = {\n \"table_name\": \"capture_urls\",\n \"key\": {\n \"name\": {\n \"S\": \"executivo-federal-dou\"\n },\n \"capture_type\": {\n \"S\": \"historical\"\n }\n }\n }\n\n # Read json from dynamoDB: \n client = boto3.client('dynamodb')\n response = client.get_item(TableName=event['table_name'], Key=event['key'])\n response = dyjson.loads(response)\n # Get configurations:\n config = response['Item']['parameters'][0]['params']\n config['bucket'] = response['Item']['bucket']\n config['key'] = response['Item']['key']\n \n return config\n\n\ndef load_local_config(config_file):\n \"\"\"\n Given a filename 'config_file' for the configuration file for the\n 'get_articles_url' function, loads the configuration.\n \"\"\"\n # Load the configuration:\n with open(config_file, 'r') as f:\n config = json.load(f)\n \n return config\n","sub_path":"src/get_articles_url.py","file_name":"get_articles_url.py","file_ext":"py","file_size_in_byte":8284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"508613946","text":"# !/usr/bin/env pyhton\n# -*- coding: utf-8 -*-\nimport collections\n\n' LeetCode 387. First Unique Character in a String '\n\n__author__ = 'LNN'\n\n# Runtime: 144 ms\nclass Solution:\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if len(s) == 0:\n return -1\n else:\n count = collections.Counter(c for c in s)\n\n index = 0\n for c in s:\n if count[c] == 1:\n return index\n index += 1\n return -1\n\n\n# 想用count,但超时\nclass Solution:\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if len(s) == 0:\n return -1\n else:\n index = 0\n for c in s:\n if s.count(c) == 1:\n return index\n index += 1\n return -1\n\n\n\ns = \"loveleetcode\"\nprint(Solution.firstUniqChar(Solution, s))\n\n# Solution samples\n# Runtime: 96 ms\ndef firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n\n letters = 'abcdefghijklmnopqrstuvwxyz'\n index = [s.index(l) for l in letters if s.count(l) == 1]\n return min(index) if len(index) > 0 else -1\n\n'''\n对比两种利用count的方法可知\nSample可以通过是因为它只对26个字母每个字母统计一遍即可,而自己想的方法做了很多重复\n更简便的遍历一遍进行字典统计\n'''\n\n\nclass Solution:\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n ret_idx = len(s)\n alpha = 'abcdefghijklmnopqrstuvwxyz'\n for char in alpha:\n idx_s = s.find(char)\n if idx_s != -1:\n idx_r = s.rfind(char, idx_s)\n if idx_s == idx_r:\n ret_idx = min(ret_idx, idx_s)\n\n if ret_idx != len(s):\n return ret_idx\n\n return -1","sub_path":"First Unique Character in a String.py","file_name":"First Unique Character in a String.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"453567211","text":"import os\nimport csv\nimport re\n\nfilepath = os.path.join(\"paragraph_1.txt\" )\nwith open(filepath, 'r') as filehandle:\n# ------------------------------------------------------------------------------------------------------------------------------------------------\n# Finding Number of Words:\n#------------------------------------------------------------------------------------------------------------------------------------------------\n#reorganized file content into a string with no newlines.(if needed)\n paragraph = filehandle.readlines()\n new_paragraph = []\n newer_paragraph = []\n for i in paragraph:\n#remove extra newline indicators not attached to setence strings\n if i != '\\n':\n new_paragraph.append(i)\n#remove newline indicators attached to sentence strings \n for x in new_paragraph:\n newstr = x.replace(\"\\n\", \" \")\n newer_paragraph.append(newstr)\n paragraph_string = \"\".join(newer_paragraph)\n#-------------------------------------------------------------------------------------------------------------------------------------------------------\n#seperate string by space (which is logically the equivalent to a new word indicator).\n words = paragraph_string.split(\" \")\n#Total word count is equal to the length of our word list\n Total_wordcount = len(words)\n#-------------------------------------------------------------------------------------------------------------------------------------------------------\n#Finding Number of Sentences:\n# Note: \n# There are inconsistences with the interpretation of the end of a sentence. \n# Some periods appear within quatations thus, are not followed by a space. while other periods are used to abbreviate names.\n# Hence a consistent interpretation of the end of a sentence is diffcult\n# Consquently we are left with only an approximation of number of sentences rather than an exact. \n\n#create a list that will hold the individual sentences\n Sentences = []\n#create a new paragraph which replaces all instances of sensible (but different) end-of-sentence indicators with \"*\"\n#Doing this will provide us with a reasonable way to seperate the sentences in the paragraph using regular expressions split. \n#This will produce a more accurate count of sentences\n paragraph_edit = re.sub(r\"\\.\\'|\\.\\\"|\\. \", \"*\", paragraph_string)\n\n#split the paragraph string by the \"*\" character which is now logical equivalent to the end of a sentence\n Sentences = paragraph_edit.split(\"*\")\n#the number of sentences will equal to the number of elements within our sentence list\n num_of_sentences = len(Sentences)\n#-------------------------------------------------------------------------------------------------------------------------------------------------\n#Finding average letters per word:\n Alpha_character_list = re.findall(\"[a-zA-Z]\", paragraph_string)\n#Total letter count will be equal to the length of the Alpha_character_list\n Total_letter_count = len(Alpha_character_list)\n Average_letter_count = Total_letter_count / Total_wordcount\n#--------------------------------------------------------------------------------------------------------------------------------------------------\n#Finding Average Sentence Length:\n average_setence_len = Total_wordcount/ num_of_sentences\n\nprint(\"Paragraph Analysis\")\n\nprint(\"-----------------------\")\n\nprint(\"Approximate Word Count: \" + str(Total_wordcount))\n\nprint(\"Approximate Sentence Count: \" + str(num_of_sentences))\n\nprint(f'Average Letter Count: {\"{:.2f}\".format(Average_letter_count)}')\n\nprint(f'Average Sentence Length: {\"{:.2f}\".format(average_setence_len)}')","sub_path":"PyParagraph/paragraph1/pypara1main.py","file_name":"pypara1main.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"522447623","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n#從 keras 的 datasets 匯入 mnist 資料集\nfrom keras.datasets import mnist \n(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n\n\n# In[2]:\n\n\n#神經網路架構\nfrom keras import models\nfrom keras import layers\n\nnetwork = models.Sequential()\nnetwork.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))\nnetwork.add(layers.Dense(10, activation='softmax'))\n\n\n# In[3]:\n\n\n#編譯步驟\nnetwork.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n\n\n# In[4]:\n\n\n#準備圖片資料\ntrain_images = train_images.reshape((60000, 28 * 28))\ntrain_images = train_images.astype('float32') / 255\n\ntest_images = test_images.reshape((10000, 28 * 28))\ntest_images = test_images.astype('float32') / 255\n\n\n# In[5]:\n\n\n#準備標籤\nfrom keras.utils import to_categorical\n\ntrain_labels = to_categorical(train_labels)\ntest_labels = to_categorical(test_labels)\n\n\n# In[6]:\n\n\n#檢驗神經網路模型\n#加入驗證集validation_data\nhistory = network.fit(train_images,\n train_labels,\n epochs=20,\n batch_size=128,\n validation_data=(test_images, test_labels))\n\n\n# In[7]:\n\n\n#評估測試資料的表現\ntest_loss, test_acc = network.evaluate(test_images, test_labels)\nprint('test_acc:', test_acc)\n\n\n# In[8]:\n\n\n#繪製訓練與驗證的損失函數\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nhistory_dict = history.history\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\n\n\nepochs = range(1, len(loss_values)+ 1)\n\nplt.plot(epochs, loss_values, 'g', label='Training loss', linewidth=3)\nplt.plot(epochs, val_loss_values, 'b', label='Validation loss', linewidth=3)\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.grid(True)\nplt.legend()\n\n\n# In[9]:\n\n\n#繪製訓練和驗證的準確度\nplt.clf()\nacc = history_dict['acc']\nval_acc = history_dict['val_acc']\n\nplt.plot(epochs, acc, 'g', label='Training acc', linewidth=3)\nplt.plot(epochs, val_acc, 'b', label='Validation acc', linewidth=3)\nplt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.grid(True)\n\n","sub_path":"20191017HW/20191017_1_MNIST+validtion data+plot/20191017_1_MNIST+validtion data+plot.py","file_name":"20191017_1_MNIST+validtion data+plot.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"611623830","text":"# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM Corp. 2017 and later.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\nfrom qiskit.aqua import Pluggable\nfrom abc import abstractmethod\nimport copy\nfrom qiskit.aqua import AquaError\n\n\nclass AlgorithmInput(Pluggable):\n\n _PROBLEM_SET = ['energy', 'excited_states', 'eoh', 'classification', 'ising', 'linear_system']\n\n @abstractmethod\n def __init__(self):\n super().__init__()\n if 'problems' not in self.configuration or len(self.configuration['problems']) <= 0:\n raise AquaError('Algorithm Input missing or empty configuration problems')\n\n for problem in self.configuration['problems']:\n if problem not in AlgorithmInput._PROBLEM_SET:\n raise AquaError('Problem {} not in known problem set {}'.format(problem, AlgorithmInput._PROBLEM_SET))\n\n @property\n def all_problems(self):\n return copy.deepcopy(self._PROBLEM_SET)\n\n @property\n def problems(self):\n \"\"\"\n Gets the set of problems that this input form supports\n \"\"\"\n return self.configuration.problems\n\n @abstractmethod\n def to_params(self):\n \"\"\"\n Convert the derived algorithminput class fields to a dictionary where the values are in a\n form that can be saved to json\n Returns:\n Dictionary of input fields\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def from_params(self, params):\n \"\"\"\n Load the dictionary into the algorithminput class fields. This dictionary being that as\n created by to_params()\n Args:\n params: A dictionary as originally created by to_params()\n \"\"\"\n raise NotImplementedError()\n","sub_path":"qiskit/aqua/input/algorithm_input.py","file_name":"algorithm_input.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"101322245","text":"#!/usr/bin/env python3\nimport serial\n\nser = serial.Serial('/dev/ttyUSB0',115200)\ns = [0]\nwhile True:\n\tread_serial=ser.readline()\n\ts[0] = str(int (ser.readline(),16))\n\tprint (s[0])\n\tprint (read_serial)\n","sub_path":"sensor_scripts/read_arduino.py","file_name":"read_arduino.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"371255354","text":"import titanic_data as data\nimport matplotlib.pyplot as plot\nimport pandas as pd\n\n#data.engineered().CleanedFare.plot.kde(title=\"Fare density\")\n# plot.savefig(\"fare_density.png\")\n# data.original.Sex.value_counts().plot.bar(title=\"Sex distribution\")\n# plot.savefig(\"sex_dist.png\")\n# data.original.Embarked.value_counts().plot.bar(title=\"Embarked distribution\")\n# plot.savefig(\"embarked_dist.png\")\n# data.original.Age.plot.kde(title = \"Age distribution\")\n# plot.savefig(\"age_dist.png\")\n#data.engineered().Title.value_counts().plot.bar(title=\"titles\")\nd = data.engineered()\nmale_famsize = d[d['Sex'] == \"male\"].FamilySize\nfemale_famsize = d[d['Sex'] == \"female\"].FamilySize\n\nqueenstown_famsize = d[d.Embarked == 'Q'].FamilySize\ncherbourg_famsize = d[d.Embarked == 'C'].FamilySize\nsouthhampton_famsize = d[d.Embarked == 'S'].FamilySize\n\nfirst_class_famsize = d[d.Pclass == 1].FamilySize\nsecond_class_famsize = d[d.Pclass == 2].FamilySize\nthird_class_famsize = d[d.Pclass == 3].FamilySize\n\nsex_con = pd.concat([male_famsize, female_famsize], join_axes=None, axis=1, keys=[\"Male\", \"Female\"])\nembarked_con = pd.concat([queenstown_famsize, cherbourg_famsize, southhampton_famsize],\n join_axes=None, axis=1, keys=[\"Queenstown\", \"Cherbourg\", \"Southhampton\"])\nclass_con = pd.concat([first_class_famsize, second_class_famsize, third_class_famsize],\n join_axes=None, axis=1, keys=[\"First\", \"Second\", \"Third\"])\n#class_con.plot.box()\n\nqueenstown_fare = d[d.Embarked == 'Q'].CleanedFare\ncherbourg_fare = d[d.Embarked == 'C'].CleanedFare\nsouthhampton_fare = d[d.Embarked == 'S'].CleanedFare\n\nfirst_class_fare = d[d.Pclass == 1].CleanedFare\nsecond_class_fare = d[d.Pclass == 2].CleanedFare\nthird_class_fare = d[d.Pclass == 3].CleanedFare\n\n\nf, (ax_one, ax_two) = plot.subplots(1, 2)\nuncleaned = d.Fare.astype('float64').values\ncleaned = d.CleanedFare.values\nax_one.boxplot(uncleaned, labels=[\"Fare\"])\nax_one.set_title(\"Original Values\")\nax_two.boxplot(cleaned, labels=[\"CleanedFare\"])\nax_two.set_title(\"Cleaned Values\")\n# pd.DataFrame(fare_data).plot.box(showmeans=True, showbox=True) \nplot.show()\n#data.engineered().plot.bar(y='Sex', x='Parch')\n\n","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"628570501","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nfrom maro.rl import ActionShaper\nfrom maro.simulator.scenarios.cim.common import Action\n\n\nclass CIMActionShaper(ActionShaper):\n def __init__(self, action_space):\n super().__init__()\n self._action_space = action_space\n self._zero_action_index = action_space.index(0)\n\n def __call__(self, model_action, decision_event, snapshot_list):\n scope = decision_event.action_scope\n tick = decision_event.tick\n port_idx = decision_event.port_idx\n vessel_idx = decision_event.vessel_idx\n\n port_empty = snapshot_list[\"ports\"][tick: port_idx: [\"empty\", \"full\", \"on_shipper\", \"on_consignee\"]][0]\n vessel_remaining_space = snapshot_list[\"vessels\"][tick: vessel_idx: [\"empty\", \"full\", \"remaining_space\"]][2]\n early_discharge = snapshot_list[\"vessels\"][tick:vessel_idx: \"early_discharge\"][0]\n assert 0 <= model_action < len(self._action_space)\n\n if model_action < self._zero_action_index:\n actual_action = max(round(self._action_space[model_action] * port_empty), -vessel_remaining_space)\n elif model_action > self._zero_action_index:\n plan_action = self._action_space[model_action] * (scope.discharge + early_discharge) - early_discharge\n actual_action = (\n round(plan_action) if plan_action > 0\n else round(self._action_space[model_action] * scope.discharge)\n )\n else:\n actual_action = 0\n\n return Action(vessel_idx, port_idx, actual_action)\n","sub_path":"examples/cim/dqn/components/action_shaper.py","file_name":"action_shaper.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"103522561","text":"import pandas as pd\r\nimport numpy as np\r\nimport os\r\nimport sys\r\n\r\nif os.getenv('MY_PYTHON_PKG') not in sys.path:\r\n sys.path.append(os.getenv('MY_PYTHON_PKG'))\r\n\r\nimport syspath\r\nimport sqlCommand as sqlc\r\nfrom common.connection import conn_local_lite\r\n\r\nconn_lite = conn_local_lite('summary.sqlite3')\r\ncur_lite = conn_lite.cursor()\r\nsql = \"SELECT * FROM `%s` \" % ('ifrs前後-綜合損益表-一般業')\r\ninc = pd.read_sql_query(sql, conn_lite).replace('--', np.nan).replace('', np.nan)\r\n# inc['年'] = [x.split('/')[0] for x in inc['年季']]\r\n# inc['季'] = [x.split('/')[1] for x in inc['年季']]\r\n# inc['公司代號'] = inc['公司代號'].astype(str).replace('\\.0', '', regex=True)\r\n# col = ['年', '季', '公司代號', '公司名稱', '營業收入', '營業成本', '營業毛利(毛損)', '未實現銷貨(損)益', '已實現銷貨(損)益', '營業毛利(毛損)淨額', '營業費用',\r\n# '其他收益及費損淨額', '營業利益(損失)', '營業外收入及支出', '稅前淨利(淨損)', '所得稅費用(利益)', '繼續營業單位本期淨利(淨損)', '停業單位損益', '合併前非屬共同控制股權損益',\r\n# '本期淨利(淨損)', '其他綜合損益(淨額)', '合併前非屬共同控制股權綜合損益淨額', '本期綜合損益總額', '淨利(淨損)歸屬於母公司業主', '淨利(淨損)歸屬於共同控制下前手權益',\r\n# '淨利(淨損)歸屬於非控制權益', '綜合損益總額歸屬於母公司業主', '綜合損益總額歸屬於共同控制下前手權益', '綜合損益總額歸屬於非控制權益', '基本每股盈餘(元)', '利息淨收益', '利息以外淨收益',\r\n# '呆帳費用及保證責任準備提存(各項提存)', '淨收益', '保險負債準備淨變動', '支出及費用', '收入', '支出', '會計原則變動累積影響數', '呆帳費用', '會計原則變動之累積影響數', '稀釋每股盈餘',\r\n# '利息收入', '減:利息費用', '收回(提存)各項保險責任準備淨額', '費用', '列計非常損益及會計原則變動累積影響數前損益', '營業支出']\r\n# col1 = ['營業收入', '營業成本', '營業毛利(毛損)', '未實現銷貨(損)益', '已實現銷貨(損)益', '營業毛利(毛損)淨額', '營業費用', '其他收益及費損淨額', '營業利益(損失)', '營業外收入及支出',\r\n# '稅前淨利(淨損)', '所得稅費用(利益)', '繼續營業單位本期淨利(淨損)', '停業單位損益', '合併前非屬共同控制股權損益', '本期淨利(淨損)', '其他綜合損益(淨額)',\r\n# '合併前非屬共同控制股權綜合損益淨額', '本期綜合損益總額', '淨利(淨損��歸屬於母公司業主', '淨利(淨損)歸屬於共同控制下前手權益', '淨利(淨損)歸屬於非控制權益', '綜合損益總額歸屬於母公司業主',\r\n# '綜合損益總額歸屬於共同控制下前手權益', '綜合損益總額歸屬於非控制權益', '基本每股盈餘(元)', '利息淨收益', '利息以外淨收益', '呆帳費用及保證責任準備提存(各項提存)', '淨收益',\r\n# '保險負債準備淨變動', '支出及費用', '收入', '支出', '會計原則變動累積影響數', '呆帳費用', '會計原則變動之累積影響數', '稀釋每股盈餘', '利息收入', '減:利息費用',\r\n# '收回(提存)各項保險責任準備淨額', '費用', '列計非常損益及會計原則變動累積影響數前損益', '營業支出']\r\n# inc = inc[col]\r\n# inc.dtypes\r\ninc.ix[:,4:]=inc.ix[:,4:].astype(float)\r\n# def change(s):\r\n# a = np.array(s)\r\n# return Series(append(a[0], a[1:] - a[0:len(s) - 1]),name=s.name)\r\n\r\n\r\ninc.年, inc.季, inc.公司代號 = inc.年.astype(str), inc.季.astype(str), inc.公司代號.astype(str)\r\n\r\n# def change0(s):\r\n# if s.dtypes == 'object':\r\n# return s\r\n# else:\r\n# return s-s\r\n# inc.apply(change0)\r\n# inc.groupby(['公司代號', '年']).apply(change0) # apply applies function to each series of one dataframe(dataframe object)\r\n#\r\n# def change1(df):\r\n# df1 = df[[x for x in list(df) if df[x].dtype != 'object']]\r\n# a1 = np.array(df1)\r\n# v = np.vstack((a1[0], a1[1:] - a1[0:len(df) - 1]))\r\n# return pd.DataFrame(v, columns=list(df1))\r\n# inc0 = inc.groupby(['公司代號', '年']).apply(change1).reset_index(drop=True);inc0\r\n# list(inc0)\r\n\r\ndef change1(df):\r\n df0 = df[[x for x in list(df) if df[x].dtype == 'object']]\r\n df1 = df[[x for x in list(df) if df[x].dtype != 'object']]\r\n a0 = np.array(df0)\r\n a1 = np.array(df1)\r\n v = np.vstack((a1[0], a1[1:] - a1[0:len(df) - 1]))\r\n h = np.hstack((a0, v))\r\n return pd.DataFrame(h, columns=list(df0) + list(df1))\r\ninc = inc.groupby(['公司代號', '年']).apply(change1).sort_values(['年', '季', '公司代號']).reset_index(drop=True);inc # apply applies function to each datafrme(group) of one dataframe(groupby object)\r\n\r\ntable='ifrs前後-綜合損益表(季)-一般業'\r\n# df = pd.read_sql_query(\"SELECT * from `{}`\".format(table), conn_lite)\r\ndf=inc\r\ndf['年'], df['季'], df['公司代號']= df['年'].astype(int), df['季'].astype(int), df['公司代號'].astype(str)\r\ndf=df.drop_duplicates(subset=['年','季', '公司代號']).sort_values(['年', '季', '公司代號'])\r\nsql='ALTER TABLE `{}` RENAME TO `{}0`'.format(table, table)\r\ncur_lite.execute(sql)\r\nsql='create table `{}` (`{}`, PRIMARY KEY ({}))'.format(table, '`,`'.join(list(df)), '`年`, `季`, `公司代號`')\r\ncur_lite.execute(sql)\r\nsql='insert into `{}`(`{}`) values({})'.format(table, '`,`'.join(list(df)), ','.join('?'*len(list(df))))\r\ncur_lite.executemany(sql, df.values.tolist())\r\nconn_lite.commit()\r\nsql=\"drop table `{}0`\".format(table)\r\ncur_lite.execute(sql)\r\nprint('finish')\r\n","sub_path":"彙總報表/ifrs前後-綜合損益表(季)-一般業.py","file_name":"ifrs前後-綜合損益表(季)-一般業.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"151209616","text":"import settings\nimport pytz\nimport datetime\nfrom django.utils import timezone\n\n\nINVALID_UTCOFFSET = 99\n\ndef get_utcoffset(mytzinfo):\n if not isinstance(mytzinfo, datetime.tzinfo):\n return INVALID_UTCOFFSET\n\n #bug: if don't specify float here, python implicit conver to integer value for IST timezone(GMT+5.5)\n #in fact, it should get value 5.5\n utcoffset = float(mytzinfo.utcoffset(datetime.datetime.now()).seconds)/3600\n\n return utcoffset\n\ndef get_user_utcoffset(request):\n # calculate the user's utcoffset from user timezone\n user_tzinfo = request.session.get('user_tzinfo', None)\n if user_tzinfo is None:\n return INVALID_UTCOFFSET\n\n return get_utcoffset(user_tzinfo)\n\ndef get_sys_utcoffset():\n try:\n sys_tzinfo = pytz.timezone(settings.TIME_ZONE)\n except:\n return INVALID_UTCOFFSET\n\n return get_utcoffset(sys_tzinfo)\n \ndef convert_naivetime_to(src_time, src_timezone, target_timezone):\n if not isinstance(src_time, datetime.datetime):\n raise\n \n if not timezone.is_naive(src_time):\n raise\n\n try:\n aware_src_time = src_time.replace(tzinfo=pytz.timezone(src_timezone))\n target_time = convert_awaretime_to(aware_src_time, target_timezone)\n except:\n raise\n\n return target_time\n\ndef convert_awaretime_to(src_time, target_timezone):\n if not isinstance(src_time, datetime.datetime):\n raise\n \n if not timezone.is_aware(src_time):\n raise\n\n try:\n target_tzinfo = pytz.timezone(target_timezone)\n target_time = target_tzinfo.normalize(src_time.astimezone(target_tzinfo))\n except:\n raise\n \n return target_time","sub_path":"srportal/spweb/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"335240037","text":"#!/usr/bin/env python\n#\n# Copyright 2019 the original author or authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#\n\"\"\"Quantum version of the classic Pong game\"\"\"\n\nimport random\n\nimport pygame as pg\nfrom pygame import DOUBLEBUF, FULLSCREEN, HWSURFACE\n\nfrom components.ball import Ball\nfrom components.scene import Scene\nfrom components.player import Player\n\nfrom prepare import (\n CLASSICAL_COMPUTER,\n QUANTUM_COMPUTER_1P,\n QUANTUM_COMPUTER_2P,\n WIDTH_UNIT,\n WINDOW_HEIGHT,\n WINDOW_SIZE,\n COLORS,\n MODES,\n POSITIONS,\n BALL_ACTIONS,\n WIN_SCORE,\n QUBIT_NUM,\n FONTS,\n)\nfrom utils.input import Input\n\nif not pg.font:\n print(\"Warning, fonts disabled\")\nif not pg.mixer:\n print(\"Warning, sound disabled\")\n\n\ndef main():\n # hardware acceleration to reduce flickering. Works only in full screen\n flags = DOUBLEBUF | HWSURFACE | FULLSCREEN\n screen = pg.display.set_mode(WINDOW_SIZE, flags)\n\n # Display until loading finishes.\n screen.fill(COLORS[\"BLACK\"])\n _render = FONTS[\"GAMEOVER\"].render(\"LOADING...\", 0, pg.Color(\"white\"))\n SCREEN_RECT = pg.Rect((0, 0), WINDOW_SIZE)\n screen.blit(_render, _render.get_rect(center=SCREEN_RECT.center))\n\n pg.display.set_caption(\"QPong\")\n\n # clock for timing\n clock = pg.time.Clock()\n old_clock = pg.time.get_ticks()\n\n # initialize scene, level and input Classes\n scene = Scene(QUBIT_NUM)\n\n # players\n players = []\n\n input = Input()\n\n # define ball\n ball = Ball()\n balls = (\n pg.sprite.Group()\n ) # sprite group type is needed for sprite collide function in pg\n\n balls.add(ball)\n\n # Show start screen to select difficulty\n input.running = scene.mode(screen) # start screen returns running flag\n if not input.running:\n pg.quit()\n return\n\n input.running = scene.difficulty(screen, ball) # start mode selections returns flag\n if not input.running:\n pg.quit()\n return\n\n if scene.game_mode == MODES[\"ONE_PLAYER\"]:\n players += [\n Player(QUBIT_NUM, POSITIONS[\"RIGHT\"], QUANTUM_COMPUTER_1P, scene.game_mode)\n ]\n players += [\n Player(QUBIT_NUM, POSITIONS[\"LEFT\"], CLASSICAL_COMPUTER, scene.game_mode)\n ]\n elif scene.game_mode == MODES[\"TWO_PLAYER\"]:\n players += [\n Player(QUBIT_NUM, POSITIONS[\"RIGHT\"], QUANTUM_COMPUTER_1P, scene.game_mode)\n ]\n players += [\n Player(QUBIT_NUM, POSITIONS[\"LEFT\"], QUANTUM_COMPUTER_2P, scene.game_mode)\n ]\n\n # Put all moving sprites a group so that they can be drawn together\n moving_sprites = pg.sprite.Group()\n moving_sprites.add(ball)\n for player in players:\n moving_sprites.add(player.paddle)\n\n # update the screen\n pg.display.flip()\n\n # reset the ball\n ball.reset()\n\n # a valuable to record the time when the paddle is measured\n measure_time = 100000\n\n # Main Loop\n while input.running:\n # set maximum frame rate\n clock.tick(60)\n\n # refill whole screen with black color at each frame\n screen.fill(COLORS[\"BLACK\"])\n\n ball.update() # update ball position\n scene.dashed_line(screen) # draw dashed line in the middle of the screen\n scene.score(players, screen) # print score\n\n for _, player in enumerate(players):\n if player.player_type in (QUANTUM_COMPUTER_1P, QUANTUM_COMPUTER_2P):\n player.statevector.draw(\n screen\n ) # draw right paddle together with statevector grid\n player.circuit_grid.draw(screen) # draw circuit grid\n moving_sprites.draw(screen) # draw moving sprites\n\n # Show game over screen if the score reaches WIN_SCORE, reset everything if replay == TRUE\n if player.score >= WIN_SCORE:\n input.running = scene.gameover(screen, player.player_type)\n scene.replay(screen, players)\n\n player.update_paddle(screen)\n\n if player.score >= WIN_SCORE:\n input.running = scene.gameover(screen, player.player_type)\n scene.replay(screen, players)\n\n player.update_paddle(screen)\n\n # computer paddle movement\n if scene.game_mode == MODES[\"ONE_PLAYER\"]:\n cpu_player = next(\n filter(lambda p: p.player_type == CLASSICAL_COMPUTER, players)\n )\n qcpu_player = next(\n filter(\n lambda p: p.player_type\n in (QUANTUM_COMPUTER_1P, QUANTUM_COMPUTER_2P),\n players,\n )\n )\n\n if cpu_player:\n if pg.time.get_ticks() - old_clock > 300:\n cpu_player.paddle.rect.y = (\n ball.y\n - qcpu_player.statevector_grid.block_size / 2\n + random.randint(-WIDTH_UNIT * 4, WIDTH_UNIT * 4)\n )\n old_clock = pg.time.get_ticks()\n\n # handle input events\n input.handle_input(players, screen)\n\n # check ball location and decide what to do\n ball.action(players)\n\n if ball.ball_action == BALL_ACTIONS[\"MEASURE_RIGHT\"]:\n circuit = qcpu_player.circuit_grid_model.compute_circuit()\n pos = qcpu_player.statevector_grid.paddle_after_measurement(\n qcpu_player.position, circuit, QUBIT_NUM, 1\n )\n qcpu_player.statevector.arrange()\n\n # paddle after measurement\n qcpu_player.paddle.rect.y = (\n pos * round(WINDOW_HEIGHT * 0.7) / (2**QUBIT_NUM)\n )\n measure_time = pg.time.get_ticks()\n\n if pg.sprite.spritecollide(qcpu_player.paddle, balls, False):\n ball.bounce_edge()\n\n if pg.sprite.spritecollide(cpu_player.paddle, balls, False):\n ball.bounce_edge()\n\n if pg.time.get_ticks() - measure_time > 400:\n # refresh the screen a moment after measurement to update visual\n qcpu_player.update_paddle(screen)\n # add a buffer time before measure again\n measure_time = pg.time.get_ticks() + 100000\n\n elif scene.game_mode == MODES[\"TWO_PLAYER\"]:\n # handle input events\n input.handle_input(players, screen)\n\n # check ball location and decide what to do\n ball.action(players)\n\n if ball.ball_action == BALL_ACTIONS[\"MEASURE_RIGHT\"]:\n circuit = players[0].circuit_grid_model.compute_circuit()\n pos = players[0].statevector_grid.paddle_after_measurement(\n players[0].position, circuit, QUBIT_NUM, 1\n )\n players[0].statevector.arrange()\n\n # paddle after measurement\n players[0].paddle.rect.y = (\n pos * round(WINDOW_HEIGHT * 0.7) / (2**QUBIT_NUM)\n )\n measure_time = pg.time.get_ticks()\n\n if ball.ball_action == BALL_ACTIONS[\"MEASURE_LEFT\"]:\n circuit = players[1].circuit_grid_model.compute_circuit()\n pos = players[1].statevector_grid.paddle_after_measurement(\n players[1].position, circuit, QUBIT_NUM, 1\n )\n players[1].statevector.arrange()\n\n # paddle after measurement\n players[1].paddle.rect.y = (\n pos * round(WINDOW_HEIGHT * 0.7) / (2**QUBIT_NUM)\n )\n measure_time = pg.time.get_ticks()\n\n if pg.sprite.spritecollide(players[0].paddle, balls, False):\n ball.bounce_edge()\n\n if pg.sprite.spritecollide(players[1].paddle, balls, False):\n ball.bounce_edge()\n\n if pg.time.get_ticks() - measure_time > 400:\n # refresh the screen a moment after measurement to update visual\n players[0].update_paddle(screen)\n players[1].update_paddle(screen)\n # add a buffer time before measure again\n measure_time = pg.time.get_ticks() + 100000\n\n # Update the screen\n if input.running:\n pg.display.flip()\n\n pg.quit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"623938679","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n\nfrom random import shuffle\nimport sys\n\nclass ArvoreB:\n \n class Node:\n def __init__(self):\n self.filhos = []\n self.chaves = []\n \n def __repr__(self):\n return 'Node' + str(self.chaves) + str(self.filhos)\n\n def _limite_inferior(self, chave):\n b = 0\n e = len(self.filhos) - 1\n while b < e:\n meio = (b + e + 1) // 2\n if self.chaves[meio - 1] <= chave:\n b = meio\n else:\n e = meio - 1\n return b\n \n def __init__(self, m):\n self.raiz = self.Node()\n self.m = m\n \n def _split(self, node, parnode, pos):\n # caso base\n if parnode is None:\n self.raiz = self.Node()\n left = self.Node()\n right = self.Node()\n left.chaves = node.chaves[:self.m - 1]\n right.chaves = node.chaves[self.m:]\n left.filhos = node.filhos[:self.m]\n right.filhos = node.filhos[self.m:]\n self.raiz.chaves = [node.chaves[self.m - 1]]\n self.raiz.filhos = [left, right]\n return self.raiz\n else:\n left = self.Node()\n right = self.Node()\n left.chaves = node.chaves[:self.m - 1]\n right.chaves = node.chaves[self.m:]\n left.filhos = node.filhos[:self.m]\n right.filhos = node.filhos[self.m:]\n parnode.chaves = parnode.chaves[:pos] + [node.chaves[self.m - 1]] + parnode.chaves[pos:]\n parnode.filhos = parnode.filhos[:pos] + [left, right] + parnode.filhos[pos + 1:]\n\n def _inserir(self, chave, node, parnode):\n if node is None: return None\n\n # node esta cheio e deve ser a raiz\n if len(node.chaves) == 2 * self.m - 1:\n assert node == self.raiz\n node = self._split(node, parnode, -1)\n assert len(node.chaves) == 1\n \n # para a direita\n if node.chaves[0] <= chave:\n self._inserir(chave, node.filhos[1], node)\n else:\n self._inserir(chave, node.filhos[0], node)\n \n return\n \n # somente possivel para a raiz no começo\n if len(node.filhos) == 0:\n assert node == self.raiz\n node.filhos.append(None)\n node.chaves.append(chave)\n node.filhos.append(None)\n \n return\n \n \n pos = node._limite_inferior(chave)\n\n \n # em uma folha\n if node.filhos[pos] is None:\n node.chaves = node.chaves[:pos] + [chave] + node.chaves[pos:]\n node.filhos.append(None)\n else:\n \n # filho esta cheio, fazendo split\n if node.filhos[pos] is not None and len(node.filhos[pos].chaves) == 2 * self.m - 1:\n self._split(node.filhos[pos], node, pos)\n # go to right\n if node.chaves[pos] <= chave:\n self._inserir(chave, node.filhos[pos + 1], node)\n else:\n self._inserir(chave, node.filhos[pos], node)\n else:\n self._inserir(chave, node.filhos[pos], node)\n\n def inserir(self, chave):\n self._inserir(chave, self.raiz, None)\n\n def _busca(self, chave, node):\n if node is None or len(node.filhos) == 0:\n return None\n \n pos = node._limite_inferior(chave)\n\n if pos >= 1 and node.chaves[pos - 1] == chave:\n return node.chaves[pos - 1]\n else:\n return self._busca(chave, node.filhos[pos])\n \n def busca(self, chave):\n return self._busca(chave, self.raiz)\n\n# testes\ndef teste0():\n T = ArvoreB(6)\n rng = list(range(9000))\n shuffle(rng)\n for i in rng:\n T.inserir(i)\n \n for i in range(9):\n print(T.busca(i), '\\n')\n\nif __name__ == '__main__':\n if sys.argv[1] == 'test':\n teste0()\n","sub_path":"btree.py","file_name":"btree.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"198535991","text":"# this is the most basic A* search - no heap, no tiebreaking, no optimization\n\ndef search(self, unit, exceptions=None):\n\tself.clear()\n\tself.open.append(unit.current_node)\n\tself.grid.reset_for_search()\n\t\n\tif exceptions:\n\t\tfor e in exceptions:\n\t\t\tself.grid[e].open=False\n\t\n\tfor p in unit.path:\n\t\tp.solutions.remove(unit)\n\t\n\tfor x in xrange(X_LENGTH):\n\t\tfor y in xrange(Y_LENGTH):\n\t\t\tself.grid[x,y].dist_remain=self.distance_estimate((x ,y), unit.goal)\n\t\n\tunit.current_node.calc_score()\n\t\n\twhile True:\n\t\tif len(self.open)==0:\n\t\t\tbreak\n\t\t\n\t\tbest_move=self.open[0]\n\t\t\n\t\tif best_move==self.grid[unit.goal]:\n\t\t\tbreak\n\t\t\n\t\tself.open=self.open[1:]\n\t\tself.closed.append(best_move)\n\t\tbest_move.open=False\n\t\t\n\t\tfor n in self.grid.neighbors_of(best_move):\n\t\t\tif n.open==None:\n\t\t\t\tn.parent=best_move\n\t\t\t\tn.open=True\n\t\t\t\tn.dist_traveled=best_move.dist_traveled+self.movement_cost(n, best_move)\n\t\t\t\tn.calc_score()\n\t\t\t\tself.open.append(n)\n\t\t\telif best_move.dist_traveled+self.movement_cost(n, best_move)2:\n\t\t# \tunit.path.append(solution[0])\n\t\t# \tfor i in xrange(1,len(solution)-1):\n\t\t# \t\tif xy_difference(solution[i-1], solution[i])!=xy_difference(solution[i], solution[i+1]):\n\t\t# \t\t\tunit.path.append(solution[i])\n\t\t# else:\n\t\t# \t\tunit.path=solution\n\t\n\tfor p in unit.path:\n\t\tp.solutions.add(unit)","sub_path":"Old Projects/Pygame Projects/a-star/base astar.py","file_name":"base astar.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"387456339","text":"# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"Utilities for measuring memory utilization for a process.\"\"\"\nimport time\nfrom queue import Queue\nfrom threading import Lock, Thread\n\nfrom framework import utils\n\n\nclass MemoryUsageExceededException(Exception):\n \"\"\"A custom exception containing details on excessive memory usage.\"\"\"\n\n def __init__(self, usage, threshold, out):\n \"\"\"Compose the error message containing the memory consumption.\"\"\"\n super().__init__(\n f\"Memory usage ({usage} KiB) exceeded maximum threshold \"\n f\"({threshold} KiB).\\n {out} \\n\"\n )\n\n\nclass MemoryMonitor(Thread):\n \"\"\"Class to represent an RSS memory monitor for a Firecracker process.\n\n The guest's memory region is skipped, as the main interest is the\n VMM memory usage.\n \"\"\"\n\n MEMORY_THRESHOLD = 5 * 1024\n MEMORY_SAMPLE_TIMEOUT_S = 0.05\n X86_MEMORY_GAP_START = 3407872\n\n def __init__(self):\n \"\"\"Initialize monitor attributes.\"\"\"\n Thread.__init__(self)\n self._pid = None\n self._guest_mem_mib = None\n self._guest_mem_start_1 = None\n self._guest_mem_end_1 = None\n self._guest_mem_start_2 = None\n self._guest_mem_end_2 = None\n self._exceeded_queue = Queue()\n self._pmap_out = None\n self._threshold = self.MEMORY_THRESHOLD\n self._should_stop = False\n self._current_rss = 0\n self._lock = Lock()\n self.daemon = True\n\n @property\n def pid(self):\n \"\"\"Get the pid.\"\"\"\n return self._pid\n\n @property\n def guest_mem_mib(self):\n \"\"\"Get the guest memory in MiB.\"\"\"\n return self._guest_mem_mib\n\n @property\n def threshold(self):\n \"\"\"Get the memory threshold.\"\"\"\n return self._threshold\n\n @property\n def exceeded_queue(self):\n \"\"\"Get the exceeded queue.\"\"\"\n return self._exceeded_queue\n\n @guest_mem_mib.setter\n def guest_mem_mib(self, guest_mem_mib):\n \"\"\"Set the guest memory MiB.\"\"\"\n self._guest_mem_mib = guest_mem_mib\n\n @pid.setter\n def pid(self, pid):\n \"\"\"Set the pid.\"\"\"\n self._pid = pid\n\n @threshold.setter\n def threshold(self, threshold):\n \"\"\"Set the threshold.\"\"\"\n self._threshold = threshold\n\n def signal_stop(self):\n \"\"\"Signal that the thread should stop.\"\"\"\n self._should_stop = True\n\n def run(self):\n \"\"\"Thread for monitoring the RSS memory usage of a Firecracker process.\n\n `pmap` is used to compute the memory overhead. If it exceeds\n the maximum value, it is pushed in a thread safe queue and memory\n monitoring ceases. It is up to the caller to check the queue.\n \"\"\"\n pmap_cmd = \"pmap -xq {}\".format(self.pid)\n\n while not self._should_stop:\n mem_total = 0\n try:\n _, stdout, _ = utils.run_cmd(pmap_cmd)\n pmap_out = stdout.split(\"\\n\")\n\n except ChildProcessError:\n return\n for line in pmap_out:\n tokens = line.split()\n if not tokens:\n break\n try:\n address = int(tokens[0].lstrip(\"0\"), 16)\n total_size = int(tokens[1])\n rss = int(tokens[2])\n except ValueError:\n # This line doesn't contain memory related information.\n continue\n if self.update_guest_mem_regions(address, total_size):\n continue\n if self.is_in_guest_mem_regions(address):\n continue\n mem_total += rss\n with self._lock:\n self._current_rss = mem_total\n if mem_total > self.threshold:\n self.exceeded_queue.put(mem_total)\n self._pmap_out = stdout\n return\n\n time.sleep(self.MEMORY_SAMPLE_TIMEOUT_S)\n\n def update_guest_mem_regions(self, address, size_kib):\n \"\"\"\n If the address is recognised as a guest memory region,\n cache it and return True, otherwise return False.\n \"\"\"\n\n # If x86_64 guest memory exceeds 3328M, it will be split\n # in 2 regions: 3328M and the rest. We have 3 cases here\n # to recognise a guest memory region:\n # - its size matches the guest memory exactly\n # - its size is 3328M\n # - its size is guest memory minus 3328M.\n if size_kib in (\n self.guest_mem_mib * 1024,\n self.X86_MEMORY_GAP_START,\n self.guest_mem_mib * 1024 - self.X86_MEMORY_GAP_START,\n ):\n if not self._guest_mem_start_1:\n self._guest_mem_start_1 = address\n self._guest_mem_end_1 = address + size_kib * 1024\n return True\n if not self._guest_mem_start_2:\n self._guest_mem_start_2 = address\n self._guest_mem_end_2 = address + size_kib * 1024\n return True\n return False\n\n def is_in_guest_mem_regions(self, address):\n \"\"\"Check if the address is inside a guest memory region.\"\"\"\n for guest_mem_start, guest_mem_end in [\n (self._guest_mem_start_1, self._guest_mem_end_1),\n (self._guest_mem_start_2, self._guest_mem_end_2),\n ]:\n if (\n guest_mem_start is not None\n and guest_mem_start <= address < guest_mem_end\n ):\n return True\n return False\n\n def check_samples(self):\n \"\"\"Check that there are no samples over the threshold.\"\"\"\n if not self.exceeded_queue.empty():\n raise MemoryUsageExceededException(\n self.exceeded_queue.get(), self.threshold, self._pmap_out\n )\n\n @property\n def current_rss(self):\n \"\"\"Obtain current RSS for Firecracker's overhead.\"\"\"\n # This is to ensure that the monitor has updated itself.\n time.sleep(self.MEMORY_SAMPLE_TIMEOUT_S + 0.5)\n with self._lock:\n return self._current_rss\n","sub_path":"tests/host_tools/memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":6168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"393482693","text":"import streamlit as st\nimport plotly.express as px\n#from src.image_export import show_export_format\n\n\ndef graph_controls(chart_type, df, dropdown_options, template):\n \"\"\"\n Function which determines the widgets that would be shown for the different chart types\n :param chart_type: str, name of chart\n :param df: uploaded dataframe\n :param dropdown_options: list of column names\n :param template: str, representation of the selected theme\n :return:\n \"\"\"\n length_of_options = len(dropdown_options)\n length_of_options -= 1\n\n plot = px.scatter()\n\n if chart_type == 'Scatter plots':\n st.sidebar.subheader(\"Scatterplot Settings\")\n\n try:\n x_values = st.sidebar.selectbox('X axis', index=length_of_options,options=dropdown_options)\n y_values = st.sidebar.selectbox('Y axis',index=length_of_options, options=dropdown_options)\n color_value = st.sidebar.selectbox(\"Color\", index=length_of_options,options=dropdown_options)\n symbol_value = st.sidebar.selectbox(\"Symbol\",index=length_of_options, options=dropdown_options)\n #size_value = st.sidebar.selectbox(\"Size\", index=length_of_options,options=dropdown_options)\n\n marginalx = st.sidebar.selectbox(\"Marginal X\", index=2,options=['rug', 'box', None,\n 'violin', 'histogram'])\n marginaly = st.sidebar.selectbox(\"Marginal Y\", index=2,options=['rug', 'box', None,\n 'violin', 'histogram'])\n log_x = st.sidebar.selectbox('Log axis on x', options=[False, True])\n log_y = st.sidebar.selectbox('Log axis on y', options=[False, True])\n title = st.sidebar.text_input(label='Title of chart')\n plot = px.scatter(data_frame=df,\n x=x_values,\n y=y_values,\n color=color_value,\n symbol=symbol_value, \n log_x=log_x, log_y=log_y,marginal_y=marginaly, marginal_x=marginalx,\n template=template, title=title)\n\n except Exception as e:\n print(e)\n\n\n if chart_type == 'Box plots':\n\n try:\n x_values = st.sidebar.selectbox('X axis', index=length_of_options,options=dropdown_options)\n y_values = st.sidebar.selectbox('Y axis',index=length_of_options, options=dropdown_options)\n color_value = st.sidebar.selectbox(\"Color\", index=length_of_options,options=dropdown_options)\n \n plot = px.box(data_frame=df, x=x_values,\n y=y_values, color=color_value,template=template)\n \n xstart=(df[y_values].mean()+df[y_values].std())\n xstart1=(df[y_values].mean()+2*df[y_values].std())\n xstart2=(df[y_values].mean()+3*df[y_values].std())\n x_value=df[x_values].nunique()+df[color_value].nunique()+1\n \n xend=(df[y_values].mean()-df[y_values].std())\n xend1=(df[y_values].mean()-2*df[y_values].std())\n xend2=(df[y_values].mean()-3*df[y_values].std())\n \n plot.add_shape(dict(type=\"rect\", x0=-1,x1=x_value, y0=xstart2, y1=xend2, fillcolor='red',\n opacity=0.2), row=\"all\", col=\"all\",)\n plot.add_shape(dict(type=\"rect\", x0=-1,x1=x_value, y0=xstart1, y1=xend1, fillcolor='yellow',\n opacity=0.2), row=\"all\", col=\"all\",)\n plot.add_shape(dict(type=\"rect\", x0=-1,x1=x_value, y0=xstart, y1=xend, fillcolor='turquoise',\n opacity=0.2), row=\"all\", col=\"all\",)\n\n\n except Exception as e:\n print(e)\n\n\n if chart_type == 'Violin plots':\n st.sidebar.subheader('Violin plot Settings')\n\n try:\n x_values = st.sidebar.selectbox('X axis', index=length_of_options,options=dropdown_options)\n y_values = st.sidebar.selectbox('Y axis',index=length_of_options, options=dropdown_options)\n color_value = st.sidebar.selectbox(label='Color(Selected Column should be categorical)', options=dropdown_options)\n #violinmode = st.sidebar.selectbox('Violin mode', options=['group', 'overlay'])\n #box = st.sidebar.selectbox(\"Show box\", options=[False, True])\n outliers = st.sidebar.selectbox('Show points', options=[False, 'all', 'outliers', 'suspectedoutliers'])\n #hover_name_value = st.sidebar.selectbox(\"Hover name\", index=length_of_options,options=dropdown_options)\n #facet_row_value = st.sidebar.selectbox(\"Facet row\",index=length_of_options, options=dropdown_options,)\n facet_column_value = st.sidebar.selectbox(\"Facet column\", index=length_of_options,\n options=dropdown_options)\n log_x = st.sidebar.selectbox('Log axis on x', options=[False,True])\n log_y = st.sidebar.selectbox('Log axis on y', options=[False,True])\n title = st.sidebar.text_input(label='Title of chart')\n plot = px.violin(data_frame=df,x=x_values,\n y=y_values,color=color_value,\n #hover_name=hover_name_value,\n #facet_row=facet_row_value,\n facet_col=facet_column_value,\n #box=box,\n log_x=log_x, log_y=log_y,\n #violinmode=violinmode,\n points=outliers,\n template=template, title=title)\n\n except Exception as e:\n print(e)\n \n if chart_type == 'custom':\n try:\n plot = px.box(data_frame=df, x='Site', y='ALT',color='Site',template=template)\n xstart=(df['ALT'].mean()+df['ALT'].std())\n xstart2=(df['ALT'].mean()+2*df['ALT'].std())\n xend=(df['ALT'].mean()-df['ALT'].std())\n xend2=(df['ALT'].mean()-2*df['ALT'].std())\n plot.add_shape(dict(type=\"rect\", x0=-1,x1=6, y0=xstart2, y1=xend2, fillcolor='yellow',\n opacity=0.1), row=\"all\", col=\"all\",)\n plot.add_shape(dict(type=\"rect\", x0=-1,x1=6, y0=xstart, y1=xend, fillcolor='turquoise',\n opacity=0.1), row=\"all\", col=\"all\",)\n\n except Exception as e:\n print(e)\n\n\n\n\n if chart_type == 'Pie Charts':\n st.sidebar.subheader('Pie Chart Settings')\n\n try:\n name_value = st.sidebar.selectbox(label='Name (Selected Column should be categorical)', options=dropdown_options)\n color_value = st.sidebar.selectbox(label='Color(Selected Column should be categorical)', options=dropdown_options)\n value = st.sidebar.selectbox(\"Value\", index=length_of_options, options=dropdown_options)\n hole = st.sidebar.selectbox('Log axis on y', options=[True, False])\n title = st.sidebar.text_input(label='Title of chart')\n\n plot = px.pie(data_frame=df,names=name_value,hole=hole,\n values=value,color=color_value, title=title)\n\n except Exception as e:\n print(e)\n\n\n\n\n\n st.subheader(\"Chart\")\n st.plotly_chart(plot)\n #show_export_format(plot)\n","sub_path":"src/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"494057166","text":"from torch.nn import Module, LSTM, Dropout, Embedding, AvgPool1d, Linear, MaxPool1d\nfrom torch import sigmoid, softmax\nfrom fat_language_model_dataset import FstLanguageModuleDataset\nfrom language_model_params import LanguageModelParams\n\n\nclass LanguageModuleLSTM(Module):\n def __init__(self, embed_dim, vocab_dim, lstm_hidden_dim, lstm_layers, lstm_dropout):\n super(LanguageModuleLSTM, self).__init__()\n # word embed layer\n self._embeddings = Embedding(vocab_dim, embed_dim)\n # Bi-LSTM layers\n self._lstm = LSTM(embed_dim, lstm_hidden_dim, lstm_layers, batch_first=True, bidirectional=False)\n self._dropout = Dropout(p=lstm_dropout)\n\n @property\n def lstm(self):\n return self._lstm\n\n def forward(self, words_embed, hidden):\n x = self._embeddings(words_embed)\n output_seq, hidden_seq = self._lstm(self._dropout(x), hidden)\n return output_seq, hidden_seq\n\n\nclass LanguageModuleMLP(Module):\n def __init__(self, in_dim, hidden_dim, out_dim, activation):\n super(LanguageModuleMLP, self).__init__()\n # useful info in forward function\n self._layer0 = Linear(in_dim, hidden_dim)\n self._layer1 = Linear(hidden_dim, out_dim)\n self._activation = activation\n\n def forward(self, x):\n x = self._layer0(x)\n x = self._activation(x)\n x = self._layer1(x)\n x = softmax(x, dim=1)\n return x\n\n\nclass LanguageModule(Module):\n def __init__(self, params: LanguageModelParams):\n super(LanguageModule, self).__init__()\n # useful info in forward function\n self._dim_hidden_lstm = params.RNN_LSTM_hidden_dim\n self._num_layers_lstm = params.RNN_LSTM_layers\n self._sequence_lstm = LanguageModuleLSTM(params.RNN_EMBED_dim, params.RNN_EMBED_vocab_dim,\n params.RNN_LSTM_hidden_dim, params.RNN_LSTM_layers,\n params.RNN_LSTM_dropout)\n self._mlp = LanguageModuleMLP(params.MLP_LINEAR_in_dim, params.MLP_LINEAR_hidden_dim, params.MLP_LINEAR_out_dim,\n params.MLP_Activation)\n self.optimizer = self.set_optimizer(params.LEARNING_RATE, params.OPTIMIZER)\n\n @property\n def lstm_module(self):\n return self._sequence_lstm.lstm\n\n @property\n def dim_hidden_lstm(self):\n return self._dim_hidden_lstm\n\n @property\n def lstm_layers(self):\n return self._num_layers_lstm\n\n def set_optimizer(self, lr, opt):\n return opt(self.parameters(), lr=lr)\n\n def forward(self, x, hidden):\n x, hidden = self._sequence_lstm(x, hidden)\n x = self._mlp(x)\n return x, hidden\n\n\nif __name__ == \"__main__\":\n from torch.utils.data import DataLoader\n from dataset_params import FSTParams\n from fst_dataset import FstDataset\n import torch\n _ds_params = FSTParams()\n _ds = FstLanguageModuleDataset(_ds_params)\n _dl = DataLoader(\n dataset=_ds,\n batch_size=2,\n collate_fn=_ds.collate_fn\n )\n\n _lm = LanguageModule(LanguageModelParams(alphabet_size=_ds_params.FST_ALPHABET_SIZE))\n for _i, (_sequence, _label) in enumerate(_dl):\n # ( lstm_layers, batch_size, x_input_dim )\n _hidden = (torch.zeros((_lm.lstm_layers, _sequence.shape[0], _lm.dim_hidden_lstm)), # dim = (bach, len_seq=1, hidden_dim)\n torch.zeros((_lm.lstm_layers, _sequence.shape[0], _lm.dim_hidden_lstm)))\n\n for _sym_idx in range(_sequence.shape[1]):\n word_col = _sequence[:, _sym_idx].unsqueeze(dim=1)\n _out, _hidden = _lm(word_col, _hidden)\n print(_out)\n e = 0\n","sub_path":"python_code/rnn_models/language_model/language_model.py","file_name":"language_model.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543926941","text":"# 可以自己import我们平台支持的第三方python模块,比如pandas、numpy等\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport math\nimport talib\nfrom collections import OrderedDict\n\n\n\n# 在这个方法中编写任何的初始化逻辑, context对象将会在你的算法策略的任何方法之间做传递\ndef init(context):\n\n # 每月第22个交易日筛选公司\n scheduler.run_monthly(filter_stocks, 22)\n\n # 每周一根据最新一季财报筛选的公司,观望交易机会并进行调仓\n scheduler.run_weekly(rebalance, 1)\n \n # 最新一季财报符合筛选条件的股票列表\n context.stocks = []\n \n # 设置投资组合股票数量上限,等权重分配资金\n context.totalstocks = 30\n \n # 投资组合中还有的空余位置\n context.availableslots = context.totalstocks\n\n # 设置每支股票的资金上限\n context.fundForEachStock = context.stock_account.cash / context.totalstocks\n logger.info(\"Fund for each stock is \" + str(context.fundForEachStock))\n \n # 参数\n \n # 买入条件的周换手率为 <= X%\n context.turnoverrate_buy = 4\n \n # 卖出条件的周换手率为 >= X%\n context.turnoverrate_sell = 7\n \n # 强制清仓时的收益率\n context.selloutgrowth = 0.2\n \n # 买卖1/3的条件 - 连续涨跌的星期数\n context.onethirdtransaction = 5\n \n # 买卖2/3的条件 - 连续涨跌的星期数\n context.halftransaction = 7\n \n # 全买卖的条件 - 连续涨跌的星期数\n context.fulltransaction = 9\n\n\n\n# 每周一触发,该函数用于判断该股票是否连续若干周周收盘价上涨或下跌(周收盘价=周五收盘价)\ndef check_condition(stock, weeks, rise):\n\n #logger.info(stock + \" check \" + str(weeks) + \" rise?:\" + str(rise))\n\n result = True\n historyprice = history_bars(stock, 150, '1d', ['datetime', 'close'])\n lastIndex = np.count_nonzero(historyprice) - 1\n\n # Dictionary - key is 日历中的第几周(相邻的数周该数值不同),value is 这周周五收盘价(如果周五停牌,就找周四、周三、周二、周一)在 historyprice 中的下标,每一周只有一天的数据\n indexesOfWeek = OrderedDict()\n \n # 往前回溯150个交易日,找出若干周的数据,今天的数据为 historyprice[149],150个交易日前当天的数据为 historyprice[0]\n for day in range(0, lastIndex):\n \n i = lastIndex - day\n \n for j in range(0, 4):\n \n thisWeekDataIndex = i - j\n thisDayStr = str(historyprice[thisWeekDataIndex][0])\n thisDay = datetime.datetime.strptime(thisDayStr, '%Y%m%d%H%M%S')\n currentWeek = thisDay.isocalendar()[1]\n\n if currentWeek not in indexesOfWeek.keys():\n # 周一为0,周五为4\n if (thisDay.weekday() == 4):\n if currentWeek not in indexesOfWeek.keys():\n #logger.info(stock + \":Add Fri \" + str(thisDay) + \" \" + str(thisWeekDataIndex) + \" price: \" + str(historyprice[thisWeekDataIndex][1]))\n indexesOfWeek[currentWeek] = thisWeekDataIndex\n break\n elif (thisDay.weekday() == 3):\n if currentWeek not in indexesOfWeek.keys():\n #logger.info(stock + \":Add Thurs \" + str(thisDay) + \" \" + str(thisWeekDataIndex) + \" price: \" + str(historyprice[thisWeekDataIndex][1]))\n indexesOfWeek[currentWeek] = thisWeekDataIndex\n break\n elif (thisDay.weekday() == 2):\n if currentWeek not in indexesOfWeek.keys():\n #logger.info(stock + \":Add Wed \" + str(thisDay) + \" \" + str(thisWeekDataIndex) + \" price: \" + str(historyprice[thisWeekDataIndex][1]))\n indexesOfWeek[currentWeek] = thisWeekDataIndex\n break\n elif (thisDay.weekday() == 1):\n if currentWeek not in indexesOfWeek.keys():\n #logger.info(stock + \":Add Tues \" + str(thisDay) + \" \" + str(thisWeekDataIndex) + \" price: \" + str(historyprice[thisWeekDataIndex][1]))\n indexesOfWeek[currentWeek] = thisWeekDataIndex\n break\n elif (thisDay.weekday() == 0):\n if currentWeek not in indexesOfWeek.keys():\n #logger.info(stock + \":Add Mon \" + str(thisDay) + \" \" + str(thisWeekDataIndex) + \" price: \" + str(historyprice[thisWeekDataIndex][1]))\n indexesOfWeek[currentWeek] = thisWeekDataIndex\n break\n \n if (len(indexesOfWeek) == weeks):\n break\n\n # 处理成正序周收盘价\n weeklyPriceReverseOrder = []\n \n for i in indexesOfWeek.keys():\n #logger.info(stock + \" append \" + str(historyprice[indexesOfWeek[i]][0]) + \":\" + str(historyprice[indexesOfWeek[i]][1]))\n weeklyPriceReverseOrder.append(historyprice[indexesOfWeek[i]][1])\n \n weeklyPrice = weeklyPriceReverseOrder[::-1]\n\n # 周数据为正序,依次比较\n for nextWeekIndex in range(1, len(weeklyPrice)):\n \n thisWeekIndex = nextWeekIndex - 1\n\n thisWeekData = weeklyPrice[thisWeekIndex]\n nextWeekData = weeklyPrice[nextWeekIndex]\n #logger.info(stock + \" compare \" + str(thisWeekData) + \" with \" + str(nextWeekData))\n\n # 判断上涨\n if rise:\n # 上涨则本周股价低于下周\n result &= thisWeekData < nextWeekData\n \n if not result:\n #logger.info(stock + \" \" + str(weeks) + \" rise:\" + str(rise) + \" fail because \" + str(thisWeekData) + \" >= \" + str(nextWeekData))\n break\n \n else:\n # 下跌则反之\n result &= thisWeekData >= nextWeekData\n \n if not result:\n #logger.info(stock + \" \" + str(weeks) + \" rise:\" + str(rise) + \" fail because \" + str(thisWeekData) + \" < \" + str(nextWeekData))\n break\n \n return result\n\n\n\n# 筛选股票函数\ndef filter_stocks(context, bar_dict):\n\n #基于最新一季的财务数据,筛选符合条件的股票\n context.fundamental_df = get_fundamentals(\n query(\n #ROE\n fundamentals.financial_indicator.return_on_equity,\n #营业收入同比增长率\n fundamentals.financial_indicator.inc_operating_revenue,\n #扣除非经常损益净利润\n fundamentals.financial_indicator.adjusted_net_profit,\n #扣除非经常损益净利润同比增长率\n fundamentals.financial_indicator.inc_adjusted_net_profit,\n #经营性现金流同比增长率\n fundamentals.financial_indicator.inc_cash_from_operations,\n #经营性现金流净额\n fundamentals.cash_flow_statement.cash_flow_from_operating_activities\n )\n .filter(\n #ROE >= 15\n fundamentals.financial_indicator.return_on_equity >= 15\n )\n .filter(\n #营业收入同比增长30%\n fundamentals.financial_indicator.inc_operating_revenue >= 0.3\n )\n .filter(\n #扣非净利润率同比增长30%\n fundamentals.financial_indicator.inc_adjusted_net_profit >= 0.3\n )\n .filter(\n #经营性现金流同比增长\n fundamentals.financial_indicator.inc_operating_revenue > 0\n )\n .filter(\n #经营性现金流为正\n fundamentals.financial_indicator.inc_adjusted_net_profit > 0\n )\n .order_by(\n fundamentals.financial_indicator.inc_adjusted_net_profit.desc()\n ),\n entry_date = None,\n interval = '1y',\n report_quarter = 'Q1'\n )\n \n context.stocks = []\n \n for stock in context.fundamental_df.columns.values:\n if instruments(stock).days_from_listed() > 180:\n context.stocks.append(stock)\n \n logger.info(\"Filtered \" + str(len(context.stocks)) + \" stocks\")\n\n\n\n# 调仓函数\ndef rebalance(context, bar_dict):\n\n # 买入股票列表\n stocks_tobuy = {}\n\n # 如果投资组合中的股票已经不在新一季的符合筛选条件的公司中,清空\n for holdstock in context.portfolio.positions:\n \n if holdstock not in context.stocks:\n logger.info(str(holdstock) + \" is not in filtered stock list, selling all shares\")\n sell_stock(context, holdstock, 1, True)\n\n # 对每支股票进行买入或卖出条件检查\n for stock in context.stocks:\n\n # 如果该股票满足平仓条件,清空\n if check_condition(stock, context.fulltransaction, True):\n logger.info(str(stock) + \" keeps rising for \" + str(context.fulltransaction) + \" weeks\")\n sell_stock(context, stock, 1)\n\n # 如果该股票满足卖出目前其份额的2/3的条件\n elif check_condition(stock, context.halftransaction, True):\n logger.info(str(stock) + \" keeps rising for \" + str(context.halftransaction) + \" weeks\")\n sell_stock(context, stock, 0.66)\n\n # 如果该股票满足买入2/3的条件,如果在筛选结果中,购买其分配资金池的2/3\n elif check_condition(stock, context.halftransaction, False) and (not check_condition(stock, context.halftransaction + 1, False)):\n logger.info(str(stock) + \" keeps falling for \" + str(context.halftransaction) + \" weeks\")\n stocks_tobuy[str(stock)] = 0.66\n\n # 如果该股票满足满仓的条件,如果在筛选结果中,购买其分配资金池的全部\n elif check_condition(stock, context.fulltransaction, False) and (not check_condition(stock, context.fulltransaction + 1, False)):\n logger.info(str(stock) + \" keeps falling for \" + str(context.fulltransaction) + \" weeks\")\n stocks_tobuy[str(stock)] = 1\n\n # 买入操作\n logger.info(\"Stocks to watch: \" + str(len(stocks_tobuy)))\n buy_stock(context, stocks_tobuy)\n\n\n\n# 调整投资组合权重平仓\ndef sell_stock(context, stock, percentage, force = False):\n\n context.availableslots = context.totalstocks - len(context.portfolio.positions)\n\n # 如果该股票在投资组合中\n if stock in context.portfolio.positions:\n \n # force为True时,因为该股票以及不在最新一季的筛选股票名单中,所以忽略周转率强制清空\n if force:\n # 如果满足收益条件,盈利 >= 建仓成本 * 收益比率\n if context.portfolio.positions[stock].pnl >= context.portfolio.positions[stock].avg_price * context.portfolio.positions[stock].quantity * context.selloutgrowth:\n order_target_percent(stock, 0)\n context.availableslots = context.totalstocks - len(context.portfolio.positions)\n \n # force为False时,为根据涨跌买卖的情况,只交易当周换手率为特定条件的股票\n else:\n \n weekTurnoverRates = get_turnover_rate(stock).week\n currWeekRate = weekTurnoverRates[len(weekTurnoverRates) - 1]\n logger.info(stock + \" weekly turnover rate is \" + str(currWeekRate))\n \n if (currWeekRate >= context.turnoverrate_sell):\n logger.info(\"Sell stock \" + stock + \" with percentage \" + str(percentage * 100) + \"%\")\n \n # 获取当前该股票在投资组合中的权重\n curweight = context.portfolio.positions[stock].value_percent\n logger.info(\"Stock \" + stock + \"'s current weight is \" + str(curweight * 100) + \"%\")\n \n # 设置新权重,percentage为卖掉目前其份额的多少\n newweight = curweight * (1 - percentage)\n \n # 根据新权重,卖出股票份额\n logger.info(\"Update \" + stock + \"'s new weight to \" + str(newweight * 100) + \"%\")\n order_target_percent(stock, newweight)\n \n # 如果交易操作为清空该股票,腾出投资组合中一支股票的空间\n if percentage == 1:\n context.availableslots = context.totalstocks - len(context.portfolio.positions)\n logger.info(\"Sold out \" + stock + \", available slots are \" + str(context.availableslots))\n\n\n\n# 调整投资组合权重以调仓\ndef buy_stock(context, stocks_tobuy):\n\n context.availableslots = context.totalstocks - len(context.portfolio.positions)\n\n if len(stocks_tobuy) > 0:\n\n # 购买2/3的股票组合\n stocks_halfbuy = []\n \n # 满仓的股票组合\n stocks_allbuy = []\n \n # 按照筛选出来的买入股票列表的优先级,调整仓位\n for stock in stocks_tobuy:\n \n # 只交易当周换手率为特定条件的股票\n weekTurnoverRates = get_turnover_rate(stock).week\n currWeekRate = weekTurnoverRates[len(weekTurnoverRates) - 1]\n logger.info(stock + \" weekly turnover rate is \" + str(currWeekRate))\n \n if currWeekRate <= context.turnoverrate_buy:\n if stocks_tobuy[stock] == 0.33:\n stocks_onethirdbuy.append(stock)\n \n elif stocks_tobuy[stock] == 0.66:\n stocks_halfbuy.append(stock)\n \n elif stocks_tobuy[stock] == 1:\n stocks_allbuy.append(stock)\n\n if context.availableslots > 0:\n # 如果还有剩余空位,购买2/3的股票\n for stock in stocks_halfbuy:\n \n halfbuy_cash_eachstock = context.fundForEachStock * 2 / 3\n \n if stock not in context.portfolio.positions:\n # 如果该股票目前不在投资组合中,加入并买2/3\n logger.info(\"Buy 2/3 = \" + str(halfbuy_cash_eachstock) + \" of \" + stock)\n order_value(stock, halfbuy_cash_eachstock)\n context.availableslots = context.totalstocks - len(context.portfolio.positions)\n logger.info(\"Add \" + stock + \" to portfolio, available slots are \" + str(context.availableslots))\n \n if context.availableslots == 0:\n break\n\n if context.availableslots > 0:\n # 如果还有剩余空位,购入满仓的股票\n for stock in stocks_allbuy:\n \n allbuy_cash_eachstock = context.fundForEachStock\n \n if stock in context.portfolio.positions:\n # 如果该股票目前在投资组合中,满仓\n logger.info(stock + \" is already in portfolio, adjust to 100% = \" + str(allbuy_cash_eachstock))\n order_target_value(stock, allbuy_cash_eachstock)\n \n else:\n # 如果该股票目前不在投资组合中,加入并满仓\n logger.info(\"Buy 100% = \" + str(allbuy_cash_eachstock) + \" of \" + stock)\n order_value(stock, allbuy_cash_eachstock)\n context.availableslots = context.totalstocks - len(context.portfolio.positions)\n logger.info(\"Add \" + stock + \" to portfolio, available slots are \" + str(context.availableslots))\n \n if context.availableslots == 0:\n break\n\n\n","sub_path":"value_macd_7_11.py","file_name":"value_macd_7_11.py","file_ext":"py","file_size_in_byte":15573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"530342856","text":"#!/usr/bin/env python\n# coding=utf8\n\nimport numpy as np\nimport cv2\nfrom skimage.feature import hog\n\n\n# Define a function to return HOG features and visualization\ndef get_hog_features(img, orient, pix_per_cell, cells_per_block,\n vis=False, feature_vec=True):\n # Call with two outputs if vis==True\n if vis:\n features, hog_image = hog(img, orientations=orient,\n pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cells_per_block, cells_per_block),\n transform_sqrt=True, block_norm=\"L2-Hys\",\n visualise=vis, feature_vector=feature_vec)\n return features, hog_image\n # Otherwise call with one output\n else:\n features = hog(img, orientations=orient,\n pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cells_per_block, cells_per_block),\n transform_sqrt=True, block_norm=\"L2-Hys\",\n visualise=vis, feature_vector=feature_vec)\n return features\n\n\n# Define a function to compute binned color features\ndef color_digest(img, target_size, channels):\n resized_img = cv2.resize(img, target_size)\n # Return the feature vector\n return resized_img[:, :, channels].ravel()\n\n\n# Define a function to compute color histogram features\n# NEED TO CHANGE bins_range if reading .png files with mpimg!\ndef color_hist(img, nbins, channels, bins_range=(0, 256)):\n # Compute the histogram of the color channels separately\n features = []\n for c in channels:\n hist = np.histogram(img[:, :, c], bins=nbins, range=bins_range)\n features.append(hist[0])\n # Concatenate the histograms into a single feature vector\n hist_features = np.concatenate(features)\n # Return the individual histograms, bin_centers and feature vector\n return hist_features\n\n\ndef convert_color(bgr_img, color_space='BGR'):\n if color_space != 'BGR':\n if color_space == 'HSV':\n converted_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2HSV)\n elif color_space == 'LUV':\n converted_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2LUV)\n elif color_space == 'HLS':\n converted_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2HLS)\n elif color_space == 'YUV':\n converted_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2YUV)\n elif color_space == 'YCrCb':\n converted_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2YCrCb)\n elif color_space == \"Gray\":\n converted_img = cv2.cvtColor(bgr_img, cv2.COLOR_RGB2GRAY)\n converted_img = np.expand_dims(converted_img, 2)\n else:\n converted_img = np.copy(bgr_img)\n else:\n converted_img = np.copy(bgr_img)\n\n return converted_img\n\n\n# Define a function to extract features from a single image window\ndef single_window_features(img_window, feature_cfg):\n # 1) Define an empty list to receive features\n\n hog_feature_cfg = feature_cfg.hog_feature_cfg\n color_feature_cfg = feature_cfg.color_feature_cfg\n hist_feature_cfg = feature_cfg.hist_feature_cfg\n\n # 2) Apply color conversion if other than 'BGR'\n hog_color_space = hog_feature_cfg[\"color_space\"]\n img_for_hog = convert_color(img_window, hog_color_space)\n\n img_features = []\n # 3) Compute spatial features if flag is set\n if feature_cfg.use_color_feature is True:\n if color_feature_cfg[\"color_space\"] == hog_color_space:\n img_for_color = img_for_hog\n else:\n img_for_color = convert_color(img_window, color_feature_cfg[\"color_space\"])\n color_features = color_digest(img_for_color, color_feature_cfg[\"target_size\"], color_feature_cfg[\"channels\"])\n # 4) Append features to list\n img_features.append(color_features)\n\n # 5) Compute histogram features if flag is set\n if feature_cfg.use_hist_feature is True:\n if hist_feature_cfg[\"color_space\"] == hog_color_space:\n img_for_hist = img_for_hog\n else:\n img_for_hist = convert_color(img_window, hist_feature_cfg[\"color_space\"])\n hist_features = color_hist(img_for_hist, hist_feature_cfg[\"nbins\"], hist_feature_cfg[\"channels\"])\n # 6) Append features to list\n img_features.append(hist_features)\n # 7) Compute HOG features if flag is set\n if feature_cfg.use_hog_feature is True:\n hog_features = []\n for channel in hog_feature_cfg[\"channels\"]:\n hog_features.extend(get_hog_features(img_for_hog[:, :, channel],\n hog_feature_cfg[\"orient\"], hog_feature_cfg[\"pix_per_cell\"],\n hog_feature_cfg[\"cells_per_block\"],\n vis=False, feature_vec=True))\n # 8) Append features to list\n img_features.append(hog_features)\n\n # 9) Return concatenated array of features\n return np.concatenate(img_features)\n\n\n# Define a function to extract features from a list of training images, all traing images have the same size.\n# Have this function call bin_spatial() and color_digest()\ndef extract_train_features(train_image_list, feature_cfg):\n # Create a list to append feature vectors to\n features = []\n # Iterate through the list of images\n for path in train_image_list:\n # Read in each one by one\n image = cv2.imread(path)\n file_features = single_window_features(image, feature_cfg)\n # assert file_features.shape[0] == 9636, \"%s feature error\" % path\n features.append(file_features)\n # Return list of feature vectors\n return features\n\n\n# Define a function to draw bounding boxes\ndef draw_boxes(img, bboxes, color=(0, 0, 255), thick=6):\n # Make a copy of the image\n #imcopy = np.copy(img)\n # Iterate through the bounding boxes\n for bbox in bboxes:\n # Draw a rectangle given bbox coordinates\n cv2.rectangle(img, bbox[0], bbox[1], color, thick)\n # Return the image copy with boxes drawn\n #return imcopy\n","sub_path":"feature_utils.py","file_name":"feature_utils.py","file_ext":"py","file_size_in_byte":6122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"206753590","text":"# DS18B20 Sensor\n# Roberto Roman\n\n#Remember to add w1-gpio and w1-therm to /etc/modules\n\nimport glob\nimport time\n\nclass DS18B20Sensor:\n id = None\n name = None\n deviceFile = None\n maxAttempts = None\n\n def __init__(self, pId, pName, pMaxAttempts):\n self.id = pId\n self.name = pName\n self.maxAttempts = pMaxAttempts\n\n def getDeviceFile(self):\n try:\n baseDir = '/sys/bus/w1/devices/'\n deviceFolder = glob.glob(baseDir + '28*')[0]\n self.deviceFile = deviceFolder + '/w1_slave'\n except Exception as e:\n self.deviceFile = False\n\n def readRawTemp(self):\n self.getDeviceFile()\n if self.deviceFile:\n try:\n f = open(self.deviceFile, 'r')\n lines = f.readlines()\n f.close()\n return lines\n except Exception as e:\n return False\n else:\n return False\n\n def read(self):\n attempts = 0\n while attempts < self.maxAttempts:\n lines = self.readRawTemp()\n if lines:\n if lines[0].strip()[-3:] == 'YES':\n break;\n else:\n continue;\n attempts += 1\n time.sleep(2)\n if attempts >= self.maxAttempts:\n return \"read_error\"\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos+2:]\n temp = float(temp_string) / 1000.0\n return round(temp, 2)\n else:\n return \"read_error\"\n","sub_path":"modules/sensors/ds18b20.py","file_name":"ds18b20.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"483725900","text":"\"\"\"\n the reminder provides a function of keeping a lists of (title, body, time(to remind), set_time)\n if also have the abilities of editing, removing and listing the messages already set down\n the 1st edition use the shelve for persisting data, later it will support sqlite3\n\n add function of switching\n\"\"\"\nimport argparse, datetime, shelve, pickle\n\n\ndef init_db(filename='reminder'):\n db = None\n try:\n db = shelve.open(filename, protocol=pickle.HIGHEST_PROTOCOL)\n finally:\n return db\n\n\ndef add_rd(db, title, body, time_from_remind=None, set_time=datetime.datetime.now()):\n if title in db:\n return title, body, time_from_remind, set_time\n db[title] = (body, time_from_remind, set_time)\n db.sync()\n\n\ndef list_rd(db):\n fmt = \"{title} {set_time} {time_from_remind} {body}\"\n print(\"title set_time time_from_remind body\")\n for title in sorted(db, key=str.lower):\n body, time_from_remind, set_time = db[title]\n print(fmt.format(**locals()))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('title', help='the title')\n parser.add_argument('-b', '--body', help='add the content')\n parser.add_argument()\n db = init_db()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"reminder.py","file_name":"reminder.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"315744557","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\nC2017-39\r\n\r\n\r\n\"\"\"\r\nimport scrapy\r\nfrom carbuisness.items import w58officeitem\r\nimport time\r\nfrom scrapy.conf import settings\r\nfrom scrapy.mail import MailSender\r\nimport logging\r\nimport json\r\nimport re\r\nimport random\r\nimport hashlib\r\nfrom hashlib import md5\r\nfrom carbuisness.getip import getProxy\r\nfrom selenium import webdriver\r\nfrom scrapy.xlib.pydispatch import dispatcher\r\nfrom scrapy import signals\r\nfrom scrapy.conf import settings\r\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\r\nfrom carbuisness.items import ZupukItem\r\n\r\nwebsite='zupuk_new'\r\n\r\nclass CarSpider(scrapy.Spider):\r\n\r\n name=website\r\n start_urls = [\r\n \"http://www.zupuk.com/\"\r\n ]\r\n\r\n\r\n def __init__(self,**kwargs):\r\n super(CarSpider,self).__init__(**kwargs)\r\n self.mailer=MailSender.from_settings(settings)\r\n self.counts=0\r\n self.carnum=800000\r\n\r\n settings.set('CrawlCar_Num',self.carnum,priority='cmdline')\r\n settings.set('MONGODB_DB','carbusiness',priority='cmdline')\r\n settings.set('MONGODB_COLLECTION',website,priority='cmdline')\r\n\r\n # def spider_closed(self):\r\n # self.browser.quit()\r\n\r\n def parse(self, response):\r\n # hrefs = response.xpath(\"//*[@class='part_div3']/a\")\r\n # print(hrefs)\r\n # for href in hrefs:\r\n # city_url = href.xpath(\"@href\").extract_first()\r\n # print(city_url)\r\n # city_name = re.findall(\"^http://(.*?).zupuk.com/$\", city_url)[0]\r\n # yield scrapy.Request(url=\"http://%s.zupuk.com/shangpu/m-121n-100000/\" % city_name, callback=self.parse_list)\r\n yield scrapy.Request(url=\"http://%s.zupuk.com/shangpu/m-121n-100000/\" % \"beijing\", callback=self.parse_list)\r\n\r\n def parse_list(self, response):\r\n\r\n lis = response.xpath(\"//*[@id='ul_list']/li\")\r\n for li in lis:\r\n shangpu_url = li.xpath(\"./p[2]/a/@href\").extract_first()\r\n # address = re.findall(\"地址:(.*?)<\", response.body)\r\n # if address:\r\n # print(address[0])\r\n yield scrapy.Request(url=response.urljoin(shangpu_url), callback=self.parse_detail)\r\n\r\n nexts = response.xpath(\"//*[@class='next']/a\")\r\n for next in nexts:\r\n if next.xpath(\"text()\").extract_first() == u\"下一页\":\r\n detail_url = next.xpath(\"@href\").extract_first()\r\n print(response.urljoin(detail_url))\r\n yield scrapy.Request(url=response.urljoin(detail_url), callback=self.parse_list)\r\n\r\n def parse_detail(self, response):\r\n item = ZupukItem()\r\n item[\"grabtime\"] = time.strftime('%Y-%m-%d %X', time.localtime())\r\n item[\"url\"] = response.url\r\n item[\"price\"] = response.xpath(\"//div[@class='zhaozushow_left_content1']/div[2]/ul/li[1]/p[2]/span/text()\").extract_first()\r\n item[\"area\"] = response.xpath(\"//div[@class='zhaozushow_left_content1']/div[2]/ul/li[2]/p[2]/span/text()\").extract_first()\r\n item[\"address\"] = re.findall(\"

(.*?)<\", response.body)\r\n if item[\"address\"]:\r\n item[\"address\"] = item[\"address\"][0]\r\n item[\"type\"] = response.xpath(\"//div[@class='zhaozushow_left_content1']/div[2]/ul/li[5]/p[2]/a/text()\").extract_first()\r\n item[\"title\"] = response.xpath(\"//div[@class='zhaozushow_left_content1']/div[2]/h1/text()\").extract_first()\r\n item[\"store_id\"] = response.xpath(\"//div[@class='zhaozushow_left_content1']/div[1]/p/span/text()\").extract_first()\r\n item[\"status\"] = response.url\r\n item[\"city\"] = response.xpath(\"//span[@class='currentcity']/text()\").extract_first()\r\n item['posttime'] = response.xpath(\"//div[@class='zhaozushow_left_content1_top']/p[3]/span/text()\").extract_first()\r\n if not item['posttime']:\r\n item['posttime'] = response.xpath(\r\n \"//div[@class='zhaozushow_left_content1_top']/p[2]/span/text()\").extract_first()\r\n yield item\r\n","sub_path":"cagey/carbuisness/carbuisness/spiders/zupuk_new.py","file_name":"zupuk_new.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"441065040","text":"from django.db import models\nfrom phonenumber_field.modelfields import PhoneNumberField\n# Create your models here.\n\nclass Messages(models.Model):\n Name = models.CharField(max_length=128)\n Email = models.EmailField()\n Phone = PhoneNumberField()\n Message = models.TextField(max_length=5000)\n\n def __str__(self):\n return self.Name\n\n class Meta:\n verbose_name = \"1 - Customer Query\"\n verbose_name_plural = \"1 - Customer Queries\"","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"545739239","text":"# MIT License\n#\n# Copyright (c) 2020-2021 Tskit Developers\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nPython implementation of the IBD-finding algorithms.\n\"\"\"\nimport argparse\nimport collections\n\nimport numpy as np\n\nimport tskit\n\n\nclass Segment:\n \"\"\"\n A class representing a single segment. Each segment has a left and right,\n denoting the loci over which it spans, a node and a next, giving the next\n in the chain.\n\n The node it records is the *output* node ID.\n \"\"\"\n\n def __init__(self, left=None, right=None, node=None, next_seg=None):\n self.left = left\n self.right = right\n self.node = node\n self.next = next_seg\n\n def __str__(self):\n s = \"({}-{}->{}:next={})\".format(\n self.left, self.right, self.node, repr(self.next)\n )\n return s\n\n def __repr__(self):\n return repr((self.left, self.right, self.node))\n\n def __eq__(self, other):\n # NOTE: to simplify tests, we DON'T check for equality of 'next'.\n return (\n self.left == other.left\n and self.right == other.right\n and self.node == other.node\n )\n\n def __lt__(self, other):\n return (self.node, self.left, self.right) < (\n other.node,\n other.left,\n other.right,\n )\n\n\nclass SegmentList:\n \"\"\"\n A class representing a list of segments that are descended from a given ancestral\n node via a particular child of the ancestor.\n Each SegmentList keeps track of the first and last segment in the list, head and\n tail. The next attribute points to another SegmentList, allowing SegmentList\n objects to be 'chained' to one another.\n \"\"\"\n\n def __init__(self, head=None, tail=None, next_list=None):\n self.head = head\n self.tail = tail\n self.next = next_list\n\n def __str__(self):\n s = \"head={},tail={},next={}\".format(self.head, self.tail, repr(self.next))\n return s\n\n def __repr__(self):\n if self.head is None:\n s = \"[{}]\".format(repr(None))\n elif self.head == self.tail:\n s = \"[{}]\".format(repr(self.head))\n elif self.head.next == self.tail:\n s = \"[{}, {}]\".format(repr(self.head), repr(self.tail))\n else:\n s = \"[{}, ..., {}]\".format(repr(self.head), repr(self.tail))\n return s\n\n def add(self, other):\n \"\"\"\n Use to append another SegmentList, or a single segment.\n SegmentList1.add(SegmentList2) will modify SegmentList1 so that\n SegmentList1.tail.next = SegmentList2.head\n SegmentList1.add(Segment1) will add Segment1 to the tail of SegmentList1\n \"\"\"\n assert isinstance(other, SegmentList) or isinstance(other, Segment)\n\n if isinstance(other, SegmentList):\n if self.head is None:\n self.head = other.head\n self.tail = other.tail\n else:\n self.tail.next = other.head\n self.tail = other.tail\n elif isinstance(other, Segment):\n if self.head is None:\n self.head = other\n self.tail = other\n else:\n self.tail.next = other\n self.tail = other\n\n\nclass IbdResult:\n \"\"\"\n Class representing the IBD segments in a tree sequence for a given\n set of sample pairs.\n \"\"\"\n\n def __init__(self):\n self.segments = collections.defaultdict(list)\n\n def add_segment(self, a, b, seg):\n key = (a, b) if a < b else (b, a)\n self.segments[key].append(tskit.IbdSegment(seg.left, seg.right, seg.node))\n\n\nclass IbdFinder:\n \"\"\"\n Finds all IBD relationships between specified sample pairs in a tree sequence.\n \"\"\"\n\n def __init__(self, ts, *, within=None, between=None, min_length=0, max_time=None):\n self.ts = ts\n self.result = IbdResult()\n if within is not None and between is not None:\n raise ValueError(\"within and between are mutually exclusive\")\n\n self.sample_set_id = np.zeros(ts.num_nodes, dtype=int) - 1\n self.finding_between = False\n if between is not None:\n self.finding_between = True\n for set_id, samples in enumerate(between):\n self.sample_set_id[samples] = set_id\n else:\n if within is None:\n within = ts.samples()\n self.sample_set_id[within] = 0\n self.min_length = min_length\n self.max_time = np.inf if max_time is None else max_time\n self.A = [None for _ in range(ts.num_nodes)] # Descendant segments\n self.tables = self.ts.tables\n\n def print_state(self):\n print(\"IBD Finder\")\n print(\"min_length = \", self.min_length)\n print(\"max_time = \", self.max_time)\n print(\"finding_between = \", self.finding_between)\n print(\"u\\tset_id\\tA = \")\n for u, a in enumerate(self.A):\n print(u, self.sample_set_id[u], a, sep=\"\\t\")\n\n def run(self):\n \"\"\"\n The wrapper for the procedure that calculates IBD segments.\n \"\"\"\n\n # Set up an iterator over the edges in the tree sequence.\n edges_iter = iter(self.ts.edges())\n e = next(edges_iter)\n parent_should_be_added = True\n node_times = self.tables.nodes.time\n\n # Iterate over the edges.\n while e is not None:\n\n current_parent = e.parent\n current_time = node_times[current_parent]\n if current_time > self.max_time:\n # Stop looking for IBD segments once the\n # processed nodes are older than the max time.\n break\n\n seg = Segment(e.left, e.right, e.child)\n\n # Create a SegmentList() holding all segments that descend from seg.\n list_to_add = SegmentList()\n u = seg.node\n if self.sample_set_id[u] != tskit.NULL:\n list_to_add.add(seg)\n else:\n if self.A[u] is not None:\n s = self.A[u].head\n while s is not None:\n intvl = (\n max(seg.left, s.left),\n min(seg.right, s.right),\n )\n if intvl[1] - intvl[0] > self.min_length:\n list_to_add.add(Segment(intvl[0], intvl[1], s.node))\n s = s.next\n\n if list_to_add.head is not None:\n self.calculate_ibd_segs(current_parent, list_to_add)\n\n # For parents that are also samples\n if (\n self.sample_set_id[current_parent] != tskit.NULL\n ) and parent_should_be_added:\n singleton_seg = SegmentList()\n singleton_seg.add(Segment(0, self.ts.sequence_length, current_parent))\n # if self.A[u] is not None:\n # list_to_add.add(self.A[u])\n self.calculate_ibd_segs(current_parent, singleton_seg)\n parent_should_be_added = False\n\n # Move to next edge.\n e = next(edges_iter, None)\n\n # Remove any processed nodes that are no longer needed.\n # Update parent_should_be_added.\n if e is not None and e.parent != current_parent:\n parent_should_be_added = True\n\n return self.result.segments\n\n def passes_filters(self, a, b, left, right):\n if a == b:\n return False\n if right - left <= self.min_length:\n return False\n if self.finding_between:\n return self.sample_set_id[a] != self.sample_set_id[b]\n else:\n return True\n\n def calculate_ibd_segs(self, current_parent, list_to_add):\n \"\"\"\n TODO describe what this does\n \"\"\"\n if self.A[current_parent] is None:\n self.A[current_parent] = list_to_add\n else:\n seg0 = self.A[current_parent].head\n while seg0 is not None:\n seg1 = list_to_add.head\n while seg1 is not None:\n left = max(seg0.left, seg1.left)\n right = min(seg0.right, seg1.right)\n # If there are any overlapping segments, record as a new\n # IBD relationship.\n if self.passes_filters(seg0.node, seg1.node, left, right):\n self.result.add_segment(\n seg0.node, seg1.node, Segment(left, right, current_parent)\n )\n seg1 = seg1.next\n seg0 = seg0.next\n # Add list_to_add to A[u].\n self.A[current_parent].add(list_to_add)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n A simple CLI for running IBDFinder on a command line from the `python`\n subdirectory. Basic usage:\n > python3 ./tests/ibd.py --infile test.trees\n \"\"\"\n\n parser = argparse.ArgumentParser(\n description=\"Command line interface for the IBDFinder.\"\n )\n\n parser.add_argument(\n \"--infile\",\n type=str,\n dest=\"infile\",\n nargs=1,\n metavar=\"IN_FILE\",\n help=\"The tree sequence to be analysed.\",\n )\n\n parser.add_argument(\n \"--min-length\",\n type=float,\n dest=\"min_length\",\n nargs=1,\n metavar=\"MIN_LENGTH\",\n help=\"Only segments longer than this cutoff will be returned.\",\n )\n\n parser.add_argument(\n \"--max-time\",\n type=float,\n dest=\"max_time\",\n nargs=1,\n metavar=\"MAX_TIME\",\n help=\"Only segments younger this time will be returned.\",\n )\n\n parser.add_argument(\n \"--samples\",\n type=int,\n dest=\"samples\",\n nargs=2,\n metavar=\"SAMPLES\",\n help=\"If provided, only this pair's IBD info is returned.\",\n )\n\n args = parser.parse_args()\n ts = tskit.load(args.infile[0])\n if args.min_length is None:\n min_length = 0\n else:\n min_length = args.min_length[0]\n if args.max_time is None:\n max_time = None\n else:\n max_time = args.max_time[0]\n\n s = IbdFinder(ts, samples=ts.samples(), min_length=min_length, max_time=max_time)\n all_segs = s.find_ibd_segments()\n\n if args.samples is None:\n print(all_segs)\n else:\n samples = args.samples\n print(all_segs[(samples[0], samples[1])])\n","sub_path":"python/tests/ibd.py","file_name":"ibd.py","file_ext":"py","file_size_in_byte":11407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"304514506","text":"import os\nimport sys\nimport pickle\nimport joblib\nimport math\nimport functools\nfrom scipy import spatial\nimport numpy as np\nimport scipy.sparse as ss\nfrom tqdm.notebook import tqdm\n\nsys.path.append('..')\nimport config\nfrom cluster import cluster, spectrum\n\n#msclustering_tolerance = 0.05\n#hdvectors_min_mz, hdvectors_max_mz = 101, 1500\n#hdvectors_fragment_mz_tolerance = 0.05\n\n\n# The function to process the spectra (same as for falcon)\nprocess_spectrum = functools.partial(\n spectrum.process_spectrum,\n min_peaks=config.min_peaks,\n min_mz_range=config.min_mz_range,\n mz_min=config.min_mz,\n mz_max=config.max_mz,\n remove_precursor_tolerance=config.remove_precursor_tolerance,\n min_intensity=config.min_intensity,\n max_peaks_used=config.max_peaks_used,\n scaling=config.scaling)\n\n\"\"\"\n IO functions\n\"\"\"\n\ndef extract_mz_split(filename):\n ch, mz, extension = filename.replace('.', '_').split('_')\n return int(mz)\n\n\n# Return True if this is a pkl file and it contains spectra of the indicated charge (based on the filename)\ndef is_valid(filename, charge):\n ch_mz, extension = filename.split('.')\n if extension != \"pkl\":\n return False\n\n ch, mz = map(int, ch_mz.split('_'))\n if ch != charge:\n return False\n\n return True\n\n\n# Assume that all the .pkl in \"path\" contain spectra. Adapted from the falcon source code.\ndef read_spectra(charge, path, limit=None):\n filenames = os.listdir(path)\n pkl_filenames = [fn for fn in filenames if is_valid(fn, charge)]\n mz_splits = [extract_mz_split(fn) for fn in pkl_filenames]\n mz_splits.sort()\n cnt = 0\n\n for mz_split in mz_splits:\n with open(os.path.join(path, f'{charge}_{mz_split}.pkl'), 'rb') as f_in:\n for spec in pickle.load(f_in):\n cnt = cnt + 1\n if limit is not None and cnt > limit:\n return\n yield spec\n\ndef read_spectra_from_bucket(charge, path, mz_split, limit=None):\n cnt = 0\n\n with open(os.path.join(path, f'{charge}_{mz_split}.pkl'), 'rb') as f_in:\n for spec in pickle.load(f_in):\n cnt = cnt + 1\n if limit is not None and cnt > limit:\n return\n yield spec\n\n\"\"\"\n Functions related to the precursor mz tolerance\n\"\"\"\n\n# It seems that the precursor_tol_mass is applied on the precursor_mz, not the mass\n# sp1 is the \"current spectrum\", sp2 is a potential neighbor\ndef respect_constraint(sp1, sp2, precursor_tol_mass):\n prec_mz1, prec_mz2 = (sp1.precursor_mz, sp2.precursor_mz)\n return math.abs(prec_mz1-prec_mz2)/prec_mz2 * 10**6 < precursor_tol_mass\n\n\n# The formula used in falcon is abs(curr_mz - other_mz)/other_mz * 10^6 < tol\ndef window_precursor_mz(mz, tol):\n # For the begin of the window, abs(curr_mz - other_mz) = curr_mz - other_mz\n start_w = mz*10**6 / (tol+10**6)\n\n # For the end of the window, abs(curr_mz - other_mz) = other_mz - cyrr_mz\n end_w = mz*10**6 / (10**6-tol)\n\n return start_w, end_w\n\n# Use a sliding window to extract all the potential neighbors\ndef update_window(queue_sp, currw_sp, curr_mz, mass_tol, iter, curr_id, pbar = None):\n startw, endw = window_precursor_mz(curr_mz, mass_tol)\n currw_sp = [sp for sp in currw_sp if sp is not None and sp[1].precursor_mz >= startw]\n\n while (len(currw_sp) == 0) or (currw_sp[-1][1].precursor_mz < endw):\n spec = next(iter, None)\n if spec is None:\n # All the spectra have been read.\n if currw_sp[-1][1].precursor_mz < endw:\n currw_sp.append(None)\n\n break\n else:\n if pbar is not None:\n pbar.update()\n\n # Process the spectrum\n spec = process_spectrum(spec)\n\n if spec is not None:\n queue_sp.append( (curr_id, spec) )\n currw_sp.append( (curr_id, spec) )\n curr_id = curr_id + 1\n\n return queue_sp, currw_sp, curr_id\n\n\ndef exact_sparse_matrix(sp_path, charge, precursor_tol_mass, dist_func):\n charge_count = joblib.load(os.path.join(sp_path, 'info.joblib'))\n pbar = tqdm(total=charge_count[charge])\n\n # Use the sliding window\n iter_sp = read_spectra(charge, sp_path)\n curr_id = 0\n queue_sp, currw_sp, curr_id = \\\n update_window([], [], -1, precursor_tol_mass, iter_sp, curr_id, pbar)\n\n n_spectra, n_neighbors, n_sp_diff_bucket = 0, 0, 0\n data, indices, indptr = [], [], [0]\n\n while len(queue_sp) > 0:\n # Pull the next element from the queue of spectra\n i, curr_sp = queue_sp[0]\n if curr_sp is None: # All the spectra have been processed\n break\n n_spectra = n_spectra + 1\n\n queue_sp = queue_sp[1:] # Remove the pulled spectra from the queue (decrease memory requirements)\n curr_mz = curr_sp.precursor_mz\n queue_sp, currw_sp, curr_id = \\\n update_window(queue_sp, currw_sp, curr_mz, precursor_tol_mass, iter_sp, curr_id, pbar)\n\n indptr.append(indptr[-1])\n # Compare the spectrum with all the spectra in the same precursor mz window\n for j, pot_neighbor in currw_sp[:-1]:\n n_neighbors = n_neighbors + 1\n if math.floor(curr_sp.precursor_mz) != math.floor(pot_neighbor.precursor_mz):\n n_sp_diff_bucket = n_sp_diff_bucket + 1\n d = dist_func( (curr_sp, pot_neighbor) )\n data.append(d)\n indices.append(j)\n indptr[-1] = indptr[-1] + 1\n\n sparse_mat = ss.csr_matrix( (data, indices, indptr), shape=(n_spectra, n_spectra) )\n return sparse_mat, n_sp_diff_bucket\n\n\"\"\"\n Helpers for sparse matrices\n\"\"\"\ndef ind_in_sparse(mat, ind):\n i, j = ind\n ind_ptr = mat.indptr[i:i+2]\n indices = mat.indices[ind_ptr[0]:ind_ptr[1]]\n if j not in indices:\n return False\n return True\n\ndef ss_generator(mat):\n i = 0\n for i in range(0, mat.shape[0]):\n ind_ptr = mat.indptr[i:i + 2]\n indices = mat.indices[ind_ptr[0]:ind_ptr[1]]\n for j in indices:\n yield (i, j)\n\n return\n\n# Check how many entries are in mat1 but not in mat2\ndef indices_lost(matrices):\n mat1, mat2 = matrices\n assert mat1.shape == mat2.shape\n n_spectra = mat1.shape[0]\n ind_lost = []\n\n for i in range(0, n_spectra): # For each row\n indptr = [mat.indptr[i:i+2] for mat in matrices]\n indices = [mat.indices[ind_ptr[0]:ind_ptr[1]] for mat, ind_ptr in zip(matrices, indptr)]\n\n for j in indices[0]:\n if j not in indices[1]:\n ind_lost.append( (i, j) )\n\n return ind_lost\n\n# Count the number of entries larger than thr in each row (= number of potential neighbors)\ndef extract_n_neighbors(mat, thresholds):\n n_spectra = mat.shape[0]\n n_neighbors = np.zeros( (n_spectra, len(thresholds)) )\n\n for i in tqdm(range(0, n_spectra)):\n indptr = mat.indptr[i:i+2]\n indices = mat.indices[indptr[0]:indptr[1]]\n indices = indices[np.where(indices != i)]\n\n for l in range(0, len(thresholds)):\n if len(indices) != 0:\n mask = np.where(mat.data[indices] < thresholds[l])\n n_neighbors[i,l] = len(mask[0])\n\n return n_neighbors\n\n# Mat is a sparse matrix\ndef extract_nondiag_values(mat):\n n_spectra = mat.shape[0]\n data = []\n for i in tqdm(range(0, n_spectra)):\n indptr = mat.indptr[i:i+2]\n indices = mat.indices[indptr[0]:indptr[1]]\n indices = indices[np.where(indices != i)]\n data = data + mat.data[indices].tolist()\n return data\n\n\n\"\"\"\n Distance functions\n\"\"\"\ndef hdvectors_distance(sps, hdvectors_min_mz, hdvectors_max_mz, hdvectors_fragment_mz_tolerance):\n min_mz = hdvectors_min_mz\n max_mz = hdvectors_max_mz\n fragment_mz_tolerance = hdvectors_fragment_mz_tolerance\n vecs = []\n for sp in sps:\n l = math.ceil((max_mz - min_mz) / fragment_mz_tolerance)\n vec = np.zeros(l)\n for mz, intensity in zip(sp.mz, sp.intensity):\n ind = int(np.floor((mz - min_mz) / fragment_mz_tolerance))\n vec[ind] = vec[ind] + intensity\n vecs.append(vec)\n return spatial.distance.cosine( vecs[0], vecs[1] )\n\ndef msclustering_distance(sps):\n n_peaks = round((sps[0].precursor_charge * sps[0].precursor_mz)/1000 * 15)\n mz_int1_int2 = []\n for i, sp in zip( [0,1], sps):\n mz = sp.mz.tolist()\n intensity = sp.intensity.tolist()\n mz_intensity = [(i, m) for m, i in zip(mz, intensity)]\n mz_intensity.sort(reverse=True)\n mz_intensity = mz_intensity[:n_peaks]\n\n for int, mz in mz_intensity:\n if i == 0:\n mz_int1_int2.append( (mz, int, 0) )\n else:\n mz_int1_int2.append( (mz, 0, int) )\n\n mz_int1_int2.sort()\n mz_int1_int2_merged = []\n i = 0\n while i < ( len(mz_int1_int2) - 1):\n (mz1, int11, int12) = mz_int1_int2[i]\n (mz2, int21, int22) = mz_int1_int2[i+1]\n if(abs(mz1 - mz2) < msclustering_tolerance):\n mz_int1_int2_merged.append( (mz1+mz2/2, int11+int21, int12+int22) )\n i = i + 2\n else:\n mz_int1_int2_merged.append(mz_int1_int2[i])\n i = i+1\n\n if i == len(mz_int1_int2) - 2:\n mz_int1_int2_merged.append(mz_int1_int2[i+1])\n\n v1 = [int for _, int, _ in mz_int1_int2_merged]\n v2 = [int for _, _, int in mz_int1_int2_merged]\n\n return spatial.distance.cosine(v1, v2)","sub_path":"notebooks/nb_utils.py","file_name":"nb_utils.py","file_ext":"py","file_size_in_byte":9461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"312911170","text":"from pyramid.config import Configurator\nfrom sqlalchemy import engine_from_config\n\nfrom .models import (\n DBSession,\n Base,\n DataStoreSession\n )\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n #engine = engine_from_config(settings, 'sqlalchemy.')\n #DBSession.configure(bind=engine)\n #Base.metadata.bind = engine\n DataStoreSession.configure(\n host=settings['irods.host'],\n port=int(settings['irods.port']),\n zone=settings['irods.zone'],\n user=settings['irods.user'],\n password=settings['irods.password']\n )\n config = Configurator(settings=settings)\n config.include('pyramid_chameleon')\n config.add_static_view('static', 'static', cache_max_age=3600)\n config.add_route('home', '/')\n config.add_route('browse', '/browse/*path')\n config.add_route('download_file', '/download/*path')\n config.add_route('serve_file', '/serve/*path')\n config.add_route('markdown', '/markdown/*path')\n config.add_route('file', '/api/file')\n config.add_route('children', '/api/collection')\n config.add_route('legacy', '/{path:.*}')\n config.scan()\n return config.make_wsgi_app()\n","sub_path":"sra/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"398243888","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n'''\ndate: 2019/7/3\nmail: cally.maxiong@gmail.com\nblog: http://www.cnblogs.com/callyblog/\n'''\n\nimport numpy as np\nimport tensorflow as tf\n\n__all__ = ['get_token_embeddings', 'atrous_conv1d', 'attention_encoder', 'noam_scheme', 'positional_encoding']\n\ndef get_token_embeddings(vocab_size, num_units, zero_pad=True):\n '''Constructs token embedding matrix.\n Note that the column of index 0's are set to zeros.\n vocab_size: scalar. V.\n num_units: embedding dimensionalty. E.\n zero_pad: Boolean. If True, all the values of the first row (id = 0) should be constant zero\n To apply query/key masks easily, zero pad is turned on.\n\n Returns\n weight variable: (V, E)\n '''\n with tf.variable_scope(\"shared_weight_matrix\", reuse=tf.AUTO_REUSE):\n embeddings = tf.get_variable('weight_mat',\n dtype=tf.float32,\n shape=(vocab_size, num_units),\n initializer=tf.contrib.layers.xavier_initializer())\n if zero_pad:\n embeddings = tf.concat((tf.zeros(shape=[1, num_units]),\n embeddings[1:, :]), 0)\n return embeddings\n\ndef atrous_conv1d(X, window=3, dilation=1, padding='SAME', scope='atrous_conv1d'):\n \"\"\"\n expansion of convolution\n :param X: embedding\n :param dilation: the size of expansion\n :param window: the size of kernel length\n \"\"\"\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n filters = X.shape.as_list()[-1]\n\n conv1 = tf.layers.conv1d(X, filters, window, dilation_rate=dilation, padding=padding)\n conv1 = tf.subtract(conv1, X)\n\n conv2 = tf.layers.conv1d(X, filters, window, dilation_rate=dilation, activation=tf.sigmoid, padding=padding)\n\n conv = X + tf.multiply(conv1, conv2)\n\n # mask\n conv = tf.where(tf.equal(X, 0), X, conv)\n\n return conv\n\ndef attention_encoder(X, dropout_rate=0.1, scope='attention_encoder'):\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n time_step = X.shape.as_list()[-2]\n num_units = X.shape.as_list()[-1]\n\n # fully connection\n # X = tf.layers.dropout(X, rate=dropout_rate)\n attention = tf.layers.dense(X, num_units, use_bias=False, activation=tf.tanh, name='tanh_fully')\n attention = tf.layers.dense(attention, time_step, use_bias=False, name='softmax_fully')\n\n # mask\n padding_num = -2 ** 32 + 1 # multiply max number, let 0 index of timestep equal softmax 0\n masks = tf.sign(tf.reduce_sum(tf.abs(X), axis=-1)) # [N, T]\n masks = tf.tile(tf.expand_dims(masks, axis=1), [1, time_step, 1]) # [N, T, T]\n paddings = tf.ones_like(masks) * padding_num\n attention = tf.where(tf.equal(masks, 0), paddings, attention)\n\n attention = tf.nn.softmax(attention)\n\n outputs = tf.matmul(attention, X) # [N, T, H]\n outputs = tf.reduce_sum(outputs, axis=1) # [N, H]\n\n return outputs\n\ndef positional_encoding(inputs, maxlen, masking=True, scope='positional_encoding'):\n '''Sinusoidal Positional_Encoding. See https://www.cnblogs.com/callyblog/p/11111493.html\n inputs: 3d tensor. (N, T, E)\n maxlen: scalar. Must be >= T\n masking: Boolean. If True, padding positions are set to zeros.\n scope: Optional scope for `variable_scope`.\n\n returns\n 3d tensor that has the same shape as inputs.\n '''\n E = inputs.shape.as_list()[-1]\n N, T = tf.shape(inputs)[0], tf.shape(inputs)[1]\n\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n # position indices\n position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), [N, 1])\n\n # First part of the PE function: sin and cos argument\n position_enc = np.array([\n [pos / np.power(10000, (i-i % 2)/E) for i in range(E)]\n for pos in range(maxlen)])\n\n # Second part, apply the cosine to even columns and sin to odds.\n position_enc[:, 0::2] = np.sin(position_enc[:, 0::2])\n position_enc[:, 1::2] = np.cos(position_enc[:, 1::2])\n position_enc = tf.convert_to_tensor(position_enc, tf.float32)\n\n # lookup\n outputs = tf.nn.embedding_lookup(position_enc, position_ind)\n\n if masking:\n outputs = tf.where(tf.equal(inputs, 0), inputs, outputs)\n\n return outputs\n\ndef noam_scheme(d_model, global_step, warmup_steps=4000.):\n '''Noam scheme learning rate decay\n d_model: encoder and decoder embedding\n global_step: scalar.\n warmup_steps: scalar. During warmup_steps, learning rate increases\n until it reaches init_lr.\n '''\n step = tf.cast(global_step + 1, dtype=tf.float32)\n return d_model ** -0.5 * tf.minimum(step * warmup_steps ** -1.5, step ** -0.5)","sub_path":"modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":4785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629729236","text":"import asyncio\nimport types\n\n\ndef name_that_thing(thing):\n \"\"\"\n Returns either the function/class path or just the object's repr\n \"\"\"\n # Instance method\n if hasattr(thing, \"im_class\"):\n # Mocks will recurse im_class forever\n if hasattr(thing, \"mock_calls\"):\n return \"\"\n return name_that_thing(thing.im_class) + \".\" + thing.im_func.func_name\n # Other named thing\n if hasattr(thing, \"__name__\"):\n if hasattr(thing, \"__class__\") and not isinstance(\n thing, (types.FunctionType, types.MethodType)\n ):\n if thing.__class__ is not type and not issubclass(thing.__class__, type):\n return name_that_thing(thing.__class__)\n if hasattr(thing, \"__self__\"):\n return \"%s.%s\" % (thing.__self__.__module__, thing.__self__.__name__)\n if hasattr(thing, \"__module__\"):\n return \"%s.%s\" % (thing.__module__, thing.__name__)\n # Generic instance of a class\n if hasattr(thing, \"__class__\"):\n return name_that_thing(thing.__class__)\n return repr(thing)\n\n\nasync def await_many_dispatch(consumer_callables, dispatch):\n \"\"\"\n Given a set of consumer callables, awaits on them all and passes results\n from them to the dispatch awaitable as they come in.\n If a dispatch awaitable raises an exception,\n this coroutine will fail with that exception.\n \"\"\"\n # Call all callables, and ensure all return types are Futures\n tasks = [\n asyncio.ensure_future(consumer_callable())\n for consumer_callable in consumer_callables\n ]\n\n dispatch_tasks = []\n fut = asyncio.Future() # For child task to report an exception\n tasks.append(fut)\n\n def on_dispatch_task_complete(task):\n dispatch_tasks.remove(task)\n exc = task.exception()\n if exc and not isinstance(exc, asyncio.CancelledError) and not fut.done():\n fut.set_exception(exc)\n\n try:\n while True:\n # Wait for any of them to complete\n await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)\n # Find the completed one(s), yield results, and replace them\n for i, task in enumerate(tasks):\n if task.done():\n if task == fut:\n exc = fut.exception() # Child task has reported an exception\n if exc:\n raise exc\n else:\n result = task.result()\n task = asyncio.create_task(dispatch(result))\n dispatch_tasks.append(task)\n task.add_done_callback(on_dispatch_task_complete)\n tasks[i] = asyncio.ensure_future(consumer_callables[i]())\n finally:\n # Make sure we clean up tasks on exit\n for task in tasks:\n task.cancel()\n try:\n await task\n except asyncio.CancelledError:\n pass\n if dispatch_tasks:\n \"\"\"\n This may be needed if the consumer task running this coroutine\n is cancelled and one of the subtasks raises an exception after cancellation.\n \"\"\"\n done, pending = await asyncio.wait(dispatch_tasks)\n for task in done:\n exc = task.exception()\n if exc and not isinstance(exc, asyncio.CancelledError):\n raise exc\n if not fut.done():\n fut.set_result(None)\n","sub_path":"channels/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"96842874","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('establecimientos', '0011_auto_20170210_0938'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='establecimiento',\n name='modulo_parto',\n field=models.BooleanField(default=False, verbose_name='Parto'),\n preserve_default=True,\n ),\n ]\n","sub_path":"apps/establecimientos/migrations/0012_establecimiento_modulo_parto.py","file_name":"0012_establecimiento_modulo_parto.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"79453018","text":"import pandas as pd\n\nfileName='request_m_1'\na=pd.read_csv(fileName,sep=',')\nb=pd.DataFrame(columns=a.columns)\nfor i in range(0,len(a),2):\n b=b.append(a.iloc[i,:])\n\nb.to_csv('half'+fileName,sep=',',header=True,index=None)\n\n\n","sub_path":"halfDemand.py","file_name":"halfDemand.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"154451813","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 2 21:37:41 2017\n\n@author: mehdiregina\n\"\"\"\n\nimport requests\nimport json\nfrom bs4 import BeautifulSoup\nimport functools\nimport time\nfrom multiprocessing import Pool\n\ndef get_soup_from_url(url):\n \n page=requests.get(url);\n if (page.status_code == 200):\n return BeautifulSoup(page.content,'html.parser')\n else:\n return None\n\ndef get_top(url, nb):\n soup=get_soup_from_url(url)\n \n #je sélection tous les tags tr contenus dans un tag tbody\n #attention d'autres combinaisons tbody -> tr existe après le top : considérer les 256 premiers tags\n liste_row=soup.select(\"tbody tr\")[0:nb]\n \n \n liste_rank = [row.find(\"th\").get_text() for row in liste_row]\n liste_name = [row.select(\"td:nth-of-type(1)\")[0].find(\"a\").get_text() for row in liste_row]\n liste_contribs = [int(row.select(\"td:nth-of-type(2)\")[0].get_text()) for row in liste_row]\n liste_location = [row.select(\"td:nth-of-type(3)\")[0].get_text() for row in liste_row]\n \n return liste_rank,liste_name,liste_contribs,liste_location\n\n\ndef get_star_mean(user):\n #commande get & user/repos renvoie la liste des repos associés au user\n url = \"https://api.github.com/users/\"+user+\"/repos\"\n \n #header pour l'autentification, (le mdp n'estpas entré)\n header = {\"Authorization\" : \"Basic mdp_encrypt\" }\n page = requests.get(url,headers = header)\n \n #j'instancie mon json object sur la base de page.content\n json_obj = json.loads(page.content)\n \n #je recupère dans chaque dico repo l'info nb étoiles contenu dans 'stargazers_count'\n liste_star=[dico_repo['stargazers_count'] for dico_repo in json_obj]\n \n #je retourne la moyenne d'étoiles\n if (len(liste_star) !=0):\n return functools.reduce(lambda x,y : x+y, liste_star)/double(len(liste_star))\n else :\n return 0\n\n\n#Main sequenciel\ndebut = time.time()\nliste_rank,liste_name,liste_contribs,liste_location = get_top(\"https://gist.github.com/paulmillr/2657075\",256)\nliste_star_mean=[get_star_mean(name) for name in liste_name]\nprint(liste_star_mean)\n\n\nfin = time.time()\nprint(\"-------\")\nprint(fin-debut) \n\n#main multi processing\np = Pool(4)\ndebut = time.time()\n#multiprocessing fonctionne avec la fonction map\n#en param la fonction à appliquer sur chaque élément, et le conteneur des éléments\nliste_star_mean=p.map(get_star_mean,liste_name)\n\nfin = time.time()\nprint(\"-------\")\nprint(fin-debut) \n\n\n\n\n","sub_path":"test_api_github.py","file_name":"test_api_github.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"340861629","text":"\"\"\"\nValidate repository information from a spreadsheet.\n\"\"\"\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom xlsimport import validators\n\nclass Command(BaseCommand):\n \"\"\"Import collections to ICA Atom.\"\"\"\n args = \"\"\n def handle(self, *args, **options):\n \"\"\"Perform import.\"\"\"\n if not args:\n raise CommandError(\"No XLS file given.\")\n\n validator = validators.Collection()\n validator.validate(args[0])\n if validator.errors:\n for err in validator.errors:\n self.stderr.write(\"Line %-6d : %s\\n\" % err[0:2])\n\n\n","sub_path":"ehriimporter/xlsimport/management/commands/validate_collection_xls.py","file_name":"validate_collection_xls.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"40433325","text":"import re\n\"\"\"\n1 将给定字符串的PHP替换为Python\nbest_language = \"PHP is the best programming language in the world! \"\n\"\"\"\nbest_language = \"PHP is the best programming language in the world! \"\nprint(best_language.replace('PHP','Python'))\n\n\n\"\"\"\n2 编写代码,提示用户输入1-7七个数字,分别代表周一到周日,打印输出“今天是周几”\n\"\"\"\nnumber=input('输入1-7七个数字,分别代表周一到周日:')\n#print(type(number))\nif number=='1':\n print('今天是周一')\nelif number=='2':\n print('今天是周二')\nelif number == '3':\n print('今天是周三')\nelif number == '4':\n print('今天是周5')\nelif number=='5':\n print('今天是周五')\nelif number=='6':\n print('今天是周六')\nelse:\n print('今天是周日')\n\n\"\"\"\n3 给定一个字符串: Python is the BEST programming Language!\n编写一个正则表达式用来判断该字符串是否全部为小写。\n\"\"\"\n\nstr=\" Python is the BEST programming Language!\"\ns=re.match('[a-z]+$',str)\nif s:\n print('全部是小写')\nelse:\n print('不全是小写')\n\n\n\"\"\"\"\n4 读取一个字符串,要求使用正则表达式来读取其中的电话号码,电话号码的格式假定为:\n(xxx) xxx-xxxx或xxx-xxx-xxxx。\n\"\"\"\ntels=input(\"enter your tel like this way (xxx-xxxx or xxx-xxx-xxxx):\")\ntell=re.search(r\"(\\d{3}-\\d{4}-\\d{4})\",tels)\nif tell=='\\n':\n tell=re.search(r\"(\\d{3}-\\d{4})\",tels)\nprint(tell)\n\n\"\"\"\n5 利用正则表达式从下列不同的字符串中获取指定格式的日期。日期的格式为yyyy-mm-dd。\n'今天是2022/9/24', '今天是2017/09/25', '今天是2012-07-25', '今天是2020年04月25',\n\"\"\"\n\nstr = '今天是2022/9/24,今天是2017/09/25,今天是2012-07-25,今天是2020年04月25'\nymd = re.compile(r'\\d{4}-\\d{2}-\\d{2}')\nymd = ymd.findall(str)\nprint(\"\".join(ymd))","sub_path":"homework6/Group5/hw6_1720379.py","file_name":"hw6_1720379.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"420972180","text":"import os\nimport json\nfrom jsonschema import RefResolver\nfrom importlib import import_module\n\nSCHEMA_RELATIVE_DIRECTORY = \"schema\"\nSIMPLE_SCHEMA_FILENAME = \"charge-simple.json\"\nINHERITED_SCHEMA_FILENAME = \"charge-inherited.json\"\nSCHEMA_VERSIONS = [\"v1_0\"]\n\n\nclass SchemaExtension(object):\n\n def __init__(self, app=None):\n self.simple_resolver = {}\n self.inherited_resolver = {}\n self.simple_schema = {}\n self.inherited_schema = {}\n self.semantic_validators = {}\n\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n path = os.path.split(os.path.realpath(__file__))\n app_dir = os.path.split(path[0])[0]\n for version in SCHEMA_VERSIONS:\n schema_path = os.path.join(app_dir, SCHEMA_RELATIVE_DIRECTORY, version)\n with open(os.path.join(schema_path, SIMPLE_SCHEMA_FILENAME)) as simple:\n self.simple_schema[version] = json.load(simple)\n\n with open(os.path.join(schema_path, INHERITED_SCHEMA_FILENAME)) as inherited:\n self.inherited_schema[version] = json.load(inherited)\n\n self.simple_resolver[version] = RefResolver('file://' + schema_path + '/', self.simple_schema[version])\n self.inherited_resolver[version] = RefResolver(\n 'file://' + schema_path + '/', self.inherited_schema[version])\n\n sem_mod = import_module('local_land_charges_api_stub.schema.' + version + '.semantics')\n self.semantic_validators[version] = sem_mod.validation_rules\n","sub_path":"local_land_charges_api_stub/validation/schema_extension.py","file_name":"schema_extension.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"517586487","text":"import subprocess as sh\n\nclass Dict:\n \n def __init__(self, dict_name, dict_csv_name, dict_index_path, dict_space_path):\n self.dict_name = dict_name\n self.dict_csv = dict_csv_name\n self.dict_index_path = dict_index_path\n self.dict_space_path = dict_space_path\n\n # csvデータを辞書に変換\n def dict_from_csv(self, csvfile):\n return sh.call([self.dict_index_path, \"-d\", self.dict_space_path, \"-u\", self.dict_name, \"-f\", \"utf8\", \"-t\", \"utf8\", csvfile])\n\n # 名詞の辞書形式に変換\n def makeline(self, word, word_tag):\n word = str(word)\n cost = int(max(-36000, -400 * len(word)**1.5))\n return \"%s,0,0,1,名詞,一般,*,*,*,*,%s,*,%s\\n\" % (word, word, word_tag)\n\n # 辞書に追加できるかチェック\n def add_check(self, word):\n f = open(\"addtest.csv\", \"w\")\n f.write(self.makeline(word, \"test\"))\n f.close()\n if len(word) > 1:\n if self.dict_from_csv(\"addtest.csv\") == 0:\n return True\n else:\n return False\n else:\n return False\n \n # 単語リストをcsvデータに変換\n def words_to_csv(self, words, word_tag):\n f = open(self.dict_csv, \"w\")\n logg = open(\"logg.txt\", \"w\")\n cnt = 0\n for word in [str(x) for x in words]:\n cnt += 1\n print(\"processing: %d / %d\" % (cnt, len(words)))\n if self.add_check(word):\n line = self.makeline(word, word_tag)\n f.write(line)\n logg.write(\"%s: ok\\n\" % word)\n else:\n logg.write(\"%s: error!!\\n\" % word)\n f.close()\n logg.close()\n\n # 辞書を反映させる\n def mvdict(self):\n sh.call([\"cp\", \"-f\", self.dict_name, self.dict_space_path]) \n","sub_path":"mecab/dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"56467771","text":"import pandas as pd\r\nteste = pd.read_csv('teste.csv', encoding='utf-8', engine='python')\r\n\r\nteste_sem_resposta = teste[['id', 'tweet_id', 'retweet_count', 'tweet_created', 'tweet_location', 'text', 'airline']]\r\nteste_sem_resposta.to_csv('teste-sem-resposta.csv', index=False, header=True, encoding='utf-8')\r\n\r\nresposta = teste[['id', 'airline_sentiment']]\r\nresposta_exemplo = pd.DataFrame({'id': resposta['id'], 'airline_sentiment': [1] * len(resposta.index)})\r\n \r\n\r\nresposta.to_csv('teste_kaggle.csv', index=False, header=True)\r\nresposta_exemplo.to_csv('exemplo_kaggle.csv', index=False, header=True, encoding='utf-8')\r\n\r\nprint('fim')","sub_path":"IME/tweets/cria_solucao.py","file_name":"cria_solucao.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476511049","text":"\"\"\"yaca URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom yaca import views\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url('^', include('django.contrib.auth.urls')),\n url(r'^$', views.home, name='home'),\n url(r'^accounts/login/$', 'django.contrib.auth.views.login',\n {'template_name': 'yacalogin.html'}),\n url(r'^show/bytag/$', views.renderInstancesByTag, name='render_by_tag' ),\n url(r'^show/byregion/$', views.renderInstancesByRegion, name=\"render_by_region\"),\n url(r'^show/byregion/(?P[\\-a-z]+-[0-9]/)?$', views.renderInstancesByRegion, name=\"render_by_named_region\"),\n url(r'^detail/(?P[\\-a-z]+-[0-9])/(?Pi-[0-9a-f]+)/(page?P[0-9]{1,10})?(statFunction?P[a-zA-Z]{1,20})?$', views.detail, name=\"detail\"),\n url(r'^accounts/logout/$', 'django.contrib.auth.views.logout')\n]\n","sub_path":"yaca/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"424930431","text":"#!/usr/bin/python3\n\nimport sys,os\nsys.path.append(os.path.join(os.getcwd(),'lib'))\nimport parse\nimport xml.etree.ElementTree as ET\n\nif not os.path.isdir('stories'):\n\tos.mkdir('stories')\n\nstories=[]\n\nindex=ET.Element('html')\nbody=ET.SubElement(index,'body')\nul=ET.SubElement(body,'ul')\n\nfor fn in os.listdir('source'):\n\tif not fn.endswith('.yxml'): continue\n\tbn=os.path.basename(os.path.splitext(fn)[0])\n\tfn=os.path.join('source',fn)\n\tofn=os.path.join('stories',bn+'.html')\n\ttry:\n\t\thtml=parse.parse(fn)\n\t\twith open(ofn,'w') as fh:\n\t\t\tfh.write(html)\n\t\tli=ET.SubElement(ul,'li')\n\t\ta=ET.SubElement(li,'a',href=ofn)\n\t\ta.text=bn\n\t\tprint('{} -> {}'.format(fn,ofn))\n\texcept Exception as e:\n\t\tprint('failed to parse {}'.format(fn))\n\t\tprint(e)\n\nwith open('index.html','w') as fh:\n\tfh.write(parse.fancify(index))\n","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"604640846","text":"from PIL import Image\n\nimport time\nimport pygame\n\nimport logging\n\ndef loadSprite(imagename, frames, startIndex = 0, label=None, offset=1, animation_time=.1):\n images = []\n for frameno in range(frames):\n image_frame_name=imagename+str('{0:02d}'.format(frameno+1))+'.png'\n images.append(pygame.image.load(image_frame_name).convert_alpha())\n\n return AnimatedSprite(images, startIndex=startIndex, label=label, offset=offset, animation_time=animation_time)\n\nclass AnimatedSprite():\n def __init__(self, images, startIndex=0, label=None, offset=1, animation_time=.1):\n logging.debug(\"AnimatedSprite init: \")\n self.images = images[:]\n self.index = self.startIndex = startIndex\n self.image = self.images[self.startIndex] # 'image' is the current image of the animation.\n self.animation_time = animation_time\n self.startTime = time.time()\n self.offset = offset\n\n self.active = True\n\n def pause(self):\n self.active = False\n \n def run(self):\n self.active = True\n self.startIndex = self.index\n self.startTime = time.time()\n\n def update(self, screen, x=None,y=None):\n if self.active:\n dt = round((time.time() - self.startTime) / self.animation_time)\n\n self.index = (dt + self.startIndex) % len(self.images)\n\n self.image = self.images[self.index]\n screen.blit(self.image, [x,y])\n","sub_path":"AnimatedSprite.py","file_name":"AnimatedSprite.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"565770096","text":"import warnings\n\nimport dask\nimport numpy as np\nimport xarray as xr\n\nfrom climpred.constants import CLIMPRED_DIMS, CONCAT_KWARGS, PM_CALENDAR_STR\n\nfrom .checks import (\n has_dims,\n has_valid_lead_units,\n warn_if_chunking_would_increase_performance,\n)\nfrom .comparisons import (\n ALL_COMPARISONS,\n COMPARISON_ALIASES,\n HINDCAST_COMPARISONS,\n __m2o,\n)\nfrom .exceptions import KeywordError\nfrom .metrics import ALL_METRICS, METRIC_ALIASES\nfrom .prediction import compute_hindcast, compute_perfect_model\nfrom .reference import compute_climatology, compute_persistence\nfrom .stats import dpp\n\ntry:\n from .stats import varweighted_mean_period\nexcept ImportError:\n varweighted_mean_period = None\nfrom .utils import (\n _transpose_and_rechunk_to,\n assign_attrs,\n convert_time_index,\n find_start_dates_for_given_init,\n get_comparison_class,\n get_lead_cftime_shift_args,\n get_metric_class,\n lead_units_equal_control_time_stride,\n rechunk_to_single_chunk_if_more_than_one_chunk_along_dim,\n shift_cftime_singular,\n)\n\n\ndef _resample(hind, resample_dim):\n \"\"\"Resample with replacement in dimension ``resample_dim``.\n\n Args:\n hind (xr.object): input xr.object to be resampled.\n resample_dim (str): dimension to resample along.\n\n Returns:\n xr.object: resampled along ``resample_dim``.\n\n \"\"\"\n to_be_resampled = hind[resample_dim].values\n smp = np.random.choice(to_be_resampled, len(to_be_resampled))\n smp_hind = hind.sel({resample_dim: smp})\n # ignore because then inits should keep their labels\n if resample_dim != \"init\":\n smp_hind[resample_dim] = hind[resample_dim].values\n return smp_hind\n\n\ndef _resample_iterations(init, iterations, dim=\"member\", dim_max=None, replace=True):\n \"\"\"Resample over ``dim`` by index ``iterations`` times.\n\n .. note::\n This gives the same result as `_resample_iterations_idx`. When using dask, the\n number of tasks in `_resample_iterations` will scale with iterations but\n constant chunksize, whereas the tasks in `_resample_iterations_idx` will stay\n constant with increasing chunksize.\n\n Args:\n init (xr.DataArray, xr.Dataset): Initialized prediction ensemble.\n iterations (int): Number of bootstrapping iterations.\n dim (str): Dimension name to bootstrap over. Defaults to ``'member'``.\n dim_max (int): Number of items to select in `dim`.\n replace (bool): Bootstrapping with or without replacement. Defaults to ``True``.\n\n Returns:\n xr.DataArray, xr.Dataset: Bootstrapped data with additional dim ```iteration```\n\n \"\"\"\n if dim_max is not None and dim_max <= init[dim].size:\n # select only dim_max items\n select_dim_items = dim_max\n new_dim = init[dim].isel({dim: slice(None, dim_max)})\n else:\n select_dim_items = init[dim].size\n new_dim = init[dim]\n\n if replace:\n idx = np.random.randint(0, init[dim].size, (iterations, select_dim_items))\n elif not replace:\n # create 2d np.arange()\n idx = np.linspace(\n (np.arange(select_dim_items)),\n (np.arange(select_dim_items)),\n iterations,\n dtype=\"int\",\n )\n # shuffle each line\n for ndx in np.arange(iterations):\n np.random.shuffle(idx[ndx])\n idx_da = xr.DataArray(\n idx,\n dims=(\"iteration\", dim),\n coords=({\"iteration\": range(iterations), dim: new_dim}),\n )\n init_smp = []\n for i in np.arange(iterations):\n idx = idx_da.sel(iteration=i).data\n init_smp2 = init.isel({dim: idx}).assign_coords({dim: new_dim})\n init_smp.append(init_smp2)\n init_smp = xr.concat(init_smp, dim=\"iteration\", **CONCAT_KWARGS)\n init_smp[\"iteration\"] = np.arange(1, 1 + iterations)\n return init_smp\n\n\ndef _resample_iterations_idx(\n init, iterations, dim=\"member\", replace=True, chunk=True, dim_max=None\n):\n \"\"\"Resample over ``dim`` by index ``iterations`` times.\n\n .. note::\n This is a much faster way to bootstrap than resampling each iteration\n individually and applying the function to it. However, this will create a\n DataArray with dimension ``iteration`` of size ``iterations``. It is probably\n best to do this out-of-memory with ``dask`` if you are doing a large number\n of iterations or using spatial output (i.e., not time series data).\n\n Args:\n init (xr.DataArray, xr.Dataset): Initialized prediction ensemble.\n iterations (int): Number of bootstrapping iterations.\n dim (str): Dimension name to bootstrap over. Defaults to ``'member'``.\n replace (bool): Bootstrapping with or without replacement. Defaults to ``True``.\n chunk: (bool): Auto-chunk along chunking_dims to get optimal blocksize\n dim_max (int): Number of indices from `dim` to return. Not implemented.\n\n Returns:\n xr.DataArray, xr.Dataset: Bootstrapped data with additional dim ```iteration```\n\n \"\"\"\n if dask.is_dask_collection(init):\n init = init.chunk({\"lead\": -1, \"member\": -1})\n init = init.copy(deep=True)\n\n def select_bootstrap_indices_ufunc(x, idx):\n \"\"\"Selects multi-level indices ``idx`` from xarray object ``x`` for all\n iterations.\"\"\"\n # `apply_ufunc` sometimes adds a singleton dimension on the end, so we squeeze\n # it out here. This leverages multi-level indexing from numpy, so we can\n # select a different set of, e.g., ensemble members for each iteration and\n # construct one large DataArray with ``iterations`` as a dimension.\n return np.moveaxis(x.squeeze()[idx.squeeze().transpose()], 0, -1)\n\n if dask.is_dask_collection(init):\n if chunk:\n chunking_dims = [d for d in init.dims if d not in CLIMPRED_DIMS]\n init = _chunk_before_resample_iterations_idx(\n init, iterations, chunking_dims\n )\n\n # resample with or without replacement\n if replace:\n idx = np.random.randint(0, init[dim].size, (iterations, init[dim].size))\n elif not replace:\n # create 2d np.arange()\n idx = np.linspace(\n (np.arange(init[dim].size)),\n (np.arange(init[dim].size)),\n iterations,\n dtype=\"int\",\n )\n # shuffle each line\n for ndx in np.arange(iterations):\n np.random.shuffle(idx[ndx])\n idx_da = xr.DataArray(\n idx,\n dims=(\"iteration\", dim),\n coords=({\"iteration\": range(iterations), dim: init[dim]}),\n )\n transpose_kwargs = (\n {\"transpose_coords\": False} if isinstance(init, xr.DataArray) else {}\n )\n return xr.apply_ufunc(\n select_bootstrap_indices_ufunc,\n init.transpose(dim, ..., **transpose_kwargs),\n idx_da,\n dask=\"parallelized\",\n output_dtypes=[float],\n )\n\n\ndef _distribution_to_ci(ds, ci_low, ci_high, dim=\"iteration\"):\n \"\"\"Get confidence intervals from bootstrapped distribution.\n\n Needed for bootstrapping confidence intervals and p_values of a metric.\n\n Args:\n ds (xarray object): distribution.\n ci_low (float): low confidence interval.\n ci_high (float): high confidence interval.\n dim (str): dimension to apply xr.quantile to. Default: 'iteration'\n\n Returns:\n uninit_hind (xarray object): uninitialize hindcast with hind.coords.\n \"\"\"\n ds = rechunk_to_single_chunk_if_more_than_one_chunk_along_dim(ds, dim)\n if isinstance(ds, xr.Dataset):\n for v in ds.data_vars:\n if np.issubdtype(ds[v].dtype, np.bool_):\n ds[v] = ds[v].astype(np.float_) # fails on py>36 if boolean dtype\n else:\n if np.issubdtype(ds.dtype, np.bool_):\n ds = ds.astype(np.float_) # fails on py>36 if boolean dtype\n return ds.quantile(q=[ci_low, ci_high], dim=dim, skipna=False)\n\n\ndef _pvalue_from_distributions(ref_skill, init_skill, metric=None):\n \"\"\"Get probability that skill of a reference forecast (e.g., persistence or\n uninitialized skill) is larger than initialized skill.\n\n Needed for bootstrapping confidence intervals and p_values of a metric in\n the hindcast framework. Checks whether a simple forecast like persistence, climatology\n or uninitialized performs better than initialized forecast. Need to keep in\n mind the orientation of metric (whether larger values are better or worse\n than smaller ones.)\n\n Args:\n ref_skill (xarray object): persistence or uninitialized skill.\n init_skill (xarray object): initialized skill.\n metric (Metric): metric class Metric\n\n Returns:\n pv (xarray object): probability that simple forecast performs better\n than initialized forecast.\n \"\"\"\n pv = ((ref_skill - init_skill) > 0).mean(\"iteration\")\n if not metric.positive:\n pv = 1 - pv\n return pv\n\n\ndef bootstrap_uninitialized_ensemble(hind, hist):\n \"\"\"Resample uninitialized hindcast from historical members.\n\n Note:\n Needed for bootstrapping confidence intervals and p_values of a metric in\n the hindcast framework. Takes hind.lead.size timesteps from historical at\n same forcing and rearranges them into ensemble and member dimensions.\n\n Args:\n hind (xarray object): hindcast.\n hist (xarray object): historical uninitialized.\n\n Returns:\n uninit_hind (xarray object): uninitialize hindcast with hind.coords.\n \"\"\"\n has_dims(hist, \"member\", \"historical ensemble\")\n has_dims(hind, \"member\", \"initialized hindcast ensemble\")\n # Put this after `convert_time_index` since it assigns 'years' attribute if the\n # `init` dimension is a `float` or `int`.\n has_valid_lead_units(hind)\n\n # find range for bootstrapping\n first_init = max(hist.time.min(), hind[\"init\"].min())\n\n n, freq = get_lead_cftime_shift_args(hind.lead.attrs[\"units\"], hind.lead.size)\n hist_last = shift_cftime_singular(hist.time.max(), -1 * n, freq)\n last_init = min(hist_last, hind[\"init\"].max())\n\n hind = hind.sel(init=slice(first_init, last_init))\n\n uninit_hind = []\n for init in hind.init.values:\n # take uninitialized members from hist at init forcing\n # (Goddard et al. allows 5 year forcing range here)\n uninit_at_one_init_year = hist.sel(\n time=slice(\n shift_cftime_singular(init, 1, freq),\n shift_cftime_singular(init, n, freq),\n ),\n ).rename({\"time\": \"lead\"})\n uninit_at_one_init_year[\"lead\"] = np.arange(\n 1, 1 + uninit_at_one_init_year[\"lead\"].size\n )\n uninit_hind.append(uninit_at_one_init_year)\n uninit_hind = xr.concat(uninit_hind, \"init\")\n uninit_hind[\"init\"] = hind[\"init\"].values\n uninit_hind.lead.attrs[\"units\"] = hind.lead.attrs[\"units\"]\n uninit_hind[\"member\"] = hist[\"member\"].values\n return (\n _transpose_and_rechunk_to(\n uninit_hind, hind.isel(member=[0] * uninit_hind.member.size)\n )\n if dask.is_dask_collection(uninit_hind)\n else uninit_hind\n )\n\n\ndef bootstrap_uninit_pm_ensemble_from_control_cftime(init_pm, control):\n \"\"\"Create a pseudo-ensemble from control run.\n\n Bootstrap random numbers for years to construct an uninitialized ensemble from.\n This assumes a continous control simulation without gaps.\n\n Note:\n Needed for block bootstrapping a metric in perfect-model framework. Takes\n random segments of length ``block_length`` from control based on ``dayofyear``\n (and therefore assumes a constant climate control simulation) and rearranges\n them into ensemble and member dimensions.\n\n Args:\n init_pm (xarray object): initialized ensemble simulation.\n control (xarray object): control simulation.\n\n Returns:\n uninit_pm (xarray object): uninitialized ensemble generated from control run.\n \"\"\"\n lead_units_equal_control_time_stride(init_pm, control)\n # short cut if annual leads\n if init_pm.lead.attrs[\"units\"] == \"years\":\n return _bootstrap_by_stacking(init_pm, control)\n\n block_length = init_pm.lead.size\n freq = get_lead_cftime_shift_args(init_pm.lead.attrs[\"units\"], block_length)[1]\n nmember = init_pm.member.size\n # start and end years possible to resample the actual uninitialized ensembles from\n c_start_year = control.time.min().dt.year.astype(\"int\")\n # dont resample from years that control wont have timesteps for all leads\n c_end_year = (\n shift_cftime_singular(control.time.max(), -block_length, freq).dt.year.astype(\n \"int\"\n )\n - 1\n )\n\n def sel_time(start_year_int, suitable_start_dates):\n \"\"\"Select time segments from control from ``suitable_start_dates`` based on\n year ``start_year_int``.\"\"\"\n start_time = suitable_start_dates.time.sel(time=str(start_year_int))\n end_time = shift_cftime_singular(start_time, block_length - 1, freq)\n new = control.sel(time=slice(*start_time, *end_time))\n new[\"time\"] = init_pm.lead.values\n return new\n\n def create_pseudo_members(init):\n \"\"\"For every initialization take a different set of start years.\"\"\"\n startlist = np.random.randint(c_start_year, c_end_year, nmember)\n suitable_start_dates = find_start_dates_for_given_init(control, init)\n return xr.concat(\n (sel_time(start, suitable_start_dates) for start in startlist),\n dim=\"member\",\n **CONCAT_KWARGS,\n )\n\n uninit = xr.concat(\n (create_pseudo_members(init) for init in init_pm.init),\n dim=\"init\",\n **CONCAT_KWARGS,\n ).rename({\"time\": \"lead\"})\n uninit[\"member\"] = init_pm.member.values\n uninit[\"lead\"] = init_pm.lead\n # chunk to same dims\n transpose_kwargs = (\n {\"transpose_coords\": False} if isinstance(init_pm, xr.DataArray) else {}\n )\n uninit = uninit.transpose(*init_pm.dims, **transpose_kwargs)\n return (\n _transpose_and_rechunk_to(uninit, init_pm)\n if dask.is_dask_collection(uninit)\n else uninit\n )\n\n\ndef _bootstrap_by_stacking(init_pm, control):\n \"\"\"Bootstrap member, lead, init from control by reshaping. Fast track of function\n `bootstrap_uninit_pm_ensemble_from_control_cftime` when lead units is 'years'.\"\"\"\n assert type(init_pm) == type(control)\n lead_unit = init_pm.lead.attrs[\"units\"]\n if isinstance(init_pm, xr.Dataset):\n init_pm = init_pm.to_array()\n init_was_dataset = True\n else:\n init_was_dataset = False\n if isinstance(control, xr.Dataset):\n control = control.to_array()\n\n init_size = init_pm.init.size * init_pm.member.size * init_pm.lead.size\n # select random start points\n new_time = np.random.randint(\n 0, control.time.size - init_pm.lead.size, init_size // (init_pm.lead.size)\n )\n new_time = np.array(\n [np.arange(s, s + init_pm.lead.size) for s in new_time]\n ).flatten()[:init_size]\n larger = control.isel(time=new_time)\n fake_init = init_pm.stack(time=tuple(d for d in init_pm.dims if d in CLIMPRED_DIMS))\n # exchange values\n transpose_kwargs = (\n {\"transpose_coords\": False} if isinstance(init_pm, xr.DataArray) else {}\n )\n larger = larger.transpose(*fake_init.dims, **transpose_kwargs)\n fake_init.data = larger.data\n fake_uninit = fake_init.unstack()\n if init_was_dataset:\n fake_uninit = fake_uninit.to_dataset(dim=\"variable\")\n fake_uninit[\"lead\"] = init_pm[\"lead\"]\n fake_uninit.lead.attrs[\"units\"] = lead_unit\n return fake_uninit\n\n\ndef _bootstrap_hindcast_over_init_dim(\n hind,\n hist,\n verif,\n dim,\n reference,\n resample_dim,\n iterations,\n metric,\n comparison,\n compute,\n resample_uninit,\n **metric_kwargs,\n):\n \"\"\"Bootstrap hindcast skill over the ``init`` dimension.\n\n When bootstrapping over the ``member`` dimension, an additional dimension\n ``iteration`` can be added and skill can be computing over that entire\n dimension in parallel, since all members are being aligned the same way.\n However, to our knowledge, when bootstrapping over the ``init`` dimension,\n one must evaluate each iteration independently. I.e., in a looped fashion,\n since alignment of initializations and target dates is unique to each\n iteration.\n\n See ``bootstrap_compute`` for explanation of inputs.\n \"\"\"\n pers_skill = []\n bootstrapped_init_skill = []\n bootstrapped_uninit_skill = []\n for i in range(iterations):\n # resample with replacement\n smp_hind = _resample(hind, resample_dim)\n # compute init skill\n init_skill = compute(\n smp_hind,\n verif,\n metric=metric,\n comparison=comparison,\n add_attrs=False,\n dim=dim,\n **metric_kwargs,\n )\n # reset inits when probabilistic, otherwise tests fail\n if (\n resample_dim == \"init\"\n and metric.probabilistic\n and \"init\" in init_skill.coords\n ):\n init_skill[\"init\"] = hind.init.values\n bootstrapped_init_skill.append(init_skill)\n if \"uninitialized\" in reference:\n # generate uninitialized ensemble from hist\n uninit_hind = resample_uninit(hind, hist)\n # compute uninit skill\n bootstrapped_uninit_skill.append(\n compute(\n uninit_hind,\n verif,\n metric=metric,\n comparison=comparison,\n dim=dim,\n add_attrs=False,\n **metric_kwargs,\n )\n )\n if \"persistence\" in reference:\n pers_skill.append(\n compute_persistence(\n smp_hind,\n verif,\n metric=metric,\n dim=dim,\n add_attrs=False,\n **metric_kwargs,\n )\n )\n bootstrapped_init_skill = xr.concat(\n bootstrapped_init_skill, dim=\"iteration\", **CONCAT_KWARGS\n )\n if \"uninitialized\" in reference:\n bootstrapped_uninit_skill = xr.concat(\n bootstrapped_uninit_skill, dim=\"iteration\", **CONCAT_KWARGS\n )\n else:\n bootstrapped_uninit_skill = None\n if \"persistence\" in reference:\n bootstrapped_pers_skill = xr.concat(\n pers_skill, dim=\"iteration\", **CONCAT_KWARGS\n )\n else:\n bootstrapped_pers_skill = None\n return (bootstrapped_init_skill, bootstrapped_uninit_skill, bootstrapped_pers_skill)\n\n\ndef _get_resample_func(ds):\n \"\"\"Decide for resample function based on input `ds`.\n\n Returns:\n callable: `_resample_iterations`: if big and chunked `ds`\n `_resample_iterations_idx`: else (if small and eager `ds`)\n \"\"\"\n resample_func = (\n _resample_iterations\n if (\n dask.is_dask_collection(ds)\n and len(ds.dims) > 3\n # > 2MB\n and ds.nbytes > 2000000\n )\n else _resample_iterations_idx\n )\n return resample_func\n\n\ndef _maybe_auto_chunk(ds, dims):\n \"\"\"Auto-chunk on dimension `dims`.\n\n Args:\n ds (xr.object): input data.\n dims (list of str or str): Dimensions to auto-chunk in.\n\n Returns:\n xr.object: auto-chunked along `dims`\n\n \"\"\"\n if dask.is_dask_collection(ds) and dims is not []:\n if isinstance(dims, str):\n dims = [dims]\n chunks = [d for d in dims if d in ds.dims]\n chunks = {key: \"auto\" for key in chunks}\n ds = ds.chunk(chunks)\n return ds\n\n\ndef _chunk_before_resample_iterations_idx(\n ds, iterations, chunking_dims, optimal_blocksize=100000000\n):\n \"\"\"Chunk ds so small that after _resample_iteration_idx chunks have optimal size\n `optimal_blocksize`.\n\n Args:\n ds (xr.obejct): input data`.\n iterations (int): number of bootstrap iterations in `_resample_iterations_idx`.\n chunking_dims (list of str or str): Dimension(s) to chunking in.\n optimal_blocksize (int): dask blocksize to aim at in bytes.\n Defaults to 100000000.\n\n Returns:\n xr.object: chunked to have blocksize: optimal_blocksize/iterations.\n\n \"\"\"\n if isinstance(chunking_dims, str):\n chunking_dims = [chunking_dims]\n # size of CLIMPRED_DIMS\n climpred_dim_chunksize = 8 * np.product(\n np.array([ds[d].size for d in CLIMPRED_DIMS if d in ds.dims])\n )\n # remaining blocksize for remaining dims considering iteration\n spatial_dim_blocksize = optimal_blocksize / (climpred_dim_chunksize * iterations)\n # size of remaining dims\n chunking_dims_size = np.product(\n np.array([ds[d].size for d in ds.dims if d not in CLIMPRED_DIMS])\n ) # ds.lat.size*ds.lon.size\n # chunks needed to get to optimal blocksize\n chunks_needed = chunking_dims_size / spatial_dim_blocksize\n # get size clon, clat for spatial chunks\n cdim = [1 for i in chunking_dims]\n nchunks = np.product(cdim)\n stepsize = 1\n counter = 0\n while nchunks < chunks_needed:\n for i, d in enumerate(chunking_dims):\n c = cdim[i]\n if c <= ds[d].size:\n c = c + stepsize\n cdim[i] = c\n nchunks = np.product(cdim)\n counter += 1\n if counter == 100:\n break\n # convert number of chunks to chunksize\n chunks = dict()\n for i, d in enumerate(chunking_dims):\n chunksize = ds[d].size // cdim[i]\n if chunksize < 1:\n chunksize = 1\n chunks[d] = chunksize\n ds = ds.chunk(chunks)\n return ds\n\n\ndef bootstrap_compute(\n hind,\n verif,\n hist=None,\n alignment=\"same_verifs\",\n metric=\"pearson_r\",\n comparison=\"m2e\",\n dim=\"init\",\n reference=None,\n resample_dim=\"member\",\n sig=95,\n iterations=500,\n pers_sig=None,\n compute=compute_hindcast,\n resample_uninit=bootstrap_uninitialized_ensemble,\n **metric_kwargs,\n):\n \"\"\"Bootstrap compute with replacement.\n\n Args:\n hind (xr.Dataset): prediction ensemble.\n verif (xr.Dataset): Verification data.\n hist (xr.Dataset): historical/uninitialized simulation.\n metric (str): `metric`. Defaults to 'pearson_r'.\n comparison (str): `comparison`. Defaults to 'm2e'.\n dim (str or list): dimension(s) to apply metric over. default: 'init'.\n reference (str, list of str): Type of reference forecasts with which to\n verify. One or more of ['persistence', 'uninitialized'].\n If None or empty, returns no p value.\n resample_dim (str): dimension to resample from. default: 'member'::\n\n - 'member': select a different set of members from hind\n - 'init': select a different set of initializations from hind\n\n sig (int): Significance level for uninitialized and\n initialized skill. Defaults to 95.\n pers_sig (int): Significance level for persistence skill confidence levels.\n Defaults to sig.\n iterations (int): number of resampling iterations (bootstrap\n with replacement). Defaults to 500.\n compute (func): function to compute skill.\n Choose from\n [:py:func:`climpred.prediction.compute_perfect_model`,\n :py:func:`climpred.prediction.compute_hindcast`].\n resample_uninit (func): function to create an uninitialized ensemble\n from a control simulation or uninitialized large\n ensemble. Choose from:\n [:py:func:`bootstrap_uninitialized_ensemble`,\n :py:func:`bootstrap_uninit_pm_ensemble_from_control`].\n ** metric_kwargs (dict): additional keywords to be passed to metric\n (see the arguments required for a given metric in :ref:`Metrics`).\n\n Returns:\n results: (xr.Dataset): bootstrapped results for the three different skills:\n\n - `initialized` for the initialized hindcast `hind` and describes skill due\n to initialization and external forcing\n - `uninitialized` for the uninitialized/historical and approximates skill\n from external forcing\n - `persistence` for the persistence forecast computed by\n `compute_persistence`\n\n the different results:\n - `verify skill`: skill values\n - `p`: p value\n - `low_ci` and `high_ci`: high and low ends of confidence intervals based\n on significance threshold `sig`\n\n\n Reference:\n * Goddard, L., A. Kumar, A. Solomon, D. Smith, G. Boer, P.\n Gonzalez, V. Kharin, et al. “A Verification Framework for\n Interannual-to-Decadal Predictions Experiments.” Climate\n Dynamics 40, no. 1–2 (January 1, 2013): 245–72.\n https://doi.org/10/f4jjvf.\n\n See also:\n * climpred.bootstrap.bootstrap_hindcast\n * climpred.bootstrap.bootstrap_perfect_model\n \"\"\"\n warn_if_chunking_would_increase_performance(hind, crit_size_in_MB=5)\n if pers_sig is None:\n pers_sig = sig\n if isinstance(dim, str):\n dim = [dim]\n if isinstance(reference, str):\n reference = [reference]\n if reference is None:\n reference = []\n\n p = (100 - sig) / 100\n ci_low = p / 2\n ci_high = 1 - p / 2\n p_pers = (100 - pers_sig) / 100\n ci_low_pers = p_pers / 2\n ci_high_pers = 1 - p_pers / 2\n\n # get metric/comparison function name, not the alias\n metric = METRIC_ALIASES.get(metric, metric)\n comparison = COMPARISON_ALIASES.get(comparison, comparison)\n\n # get class Metric(metric)\n metric = get_metric_class(metric, ALL_METRICS)\n # get comparison function\n comparison = get_comparison_class(comparison, ALL_COMPARISONS)\n\n # Perfect Model requires `same_inits` setup\n isHindcast = True if comparison.name in HINDCAST_COMPARISONS else False\n reference_alignment = alignment if isHindcast else \"same_inits\"\n chunking_dims = [d for d in hind.dims if d not in CLIMPRED_DIMS]\n\n # carry alignment for compute_reference separately\n metric_kwargs_reference = metric_kwargs.copy()\n metric_kwargs_reference[\"alignment\"] = reference_alignment\n # carry alignment in metric_kwargs\n if isHindcast:\n metric_kwargs[\"alignment\"] = alignment\n\n if hist is None: # PM path, use verif = control\n hist = verif\n\n # slower path for hindcast and resample_dim init\n if resample_dim == \"init\" and isHindcast:\n warnings.warn(\"resample_dim=`init` will be slower than resample_dim=`member`.\")\n (\n bootstrapped_init_skill,\n bootstrapped_uninit_skill,\n bootstrapped_pers_skill,\n ) = _bootstrap_hindcast_over_init_dim(\n hind,\n hist,\n verif,\n dim,\n reference,\n resample_dim,\n iterations,\n metric,\n comparison,\n compute,\n resample_uninit,\n **metric_kwargs,\n )\n else: # faster: first _resample_iterations_idx, then compute skill\n resample_func = _get_resample_func(hind)\n if not isHindcast:\n if \"uninitialized\" in reference:\n # create more members than needed in PM to make the uninitialized\n # distribution more robust\n members_to_sample_from = 50\n repeat = members_to_sample_from // hind.member.size + 1\n uninit_hind = xr.concat(\n [resample_uninit(hind, hist) for i in range(repeat)],\n dim=\"member\",\n **CONCAT_KWARGS,\n )\n uninit_hind[\"member\"] = np.arange(1, 1 + uninit_hind.member.size)\n if dask.is_dask_collection(uninit_hind):\n # too minimize tasks: ensure uninit_hind get pre-computed\n # alternativly .chunk({'member':-1})\n uninit_hind = uninit_hind.compute().chunk()\n # resample uninit always over member and select only hind.member.size\n bootstrapped_uninit = resample_func(\n uninit_hind,\n iterations,\n \"member\",\n replace=False,\n dim_max=hind[\"member\"].size,\n )\n bootstrapped_uninit[\"lead\"] = hind[\"lead\"]\n # effectively only when _resample_iteration_idx which doesnt use dim_max\n bootstrapped_uninit = bootstrapped_uninit.isel(\n member=slice(None, hind.member.size)\n )\n bootstrapped_uninit[\"member\"] = np.arange(\n 1, 1 + bootstrapped_uninit.member.size\n )\n if dask.is_dask_collection(bootstrapped_uninit):\n bootstrapped_uninit = bootstrapped_uninit.chunk({\"member\": -1})\n bootstrapped_uninit = _maybe_auto_chunk(\n bootstrapped_uninit, [\"iteration\"] + chunking_dims\n )\n else: # hindcast\n if \"uninitialized\" in reference:\n uninit_hind = resample_uninit(hind, hist)\n if dask.is_dask_collection(uninit_hind):\n # too minimize tasks: ensure uninit_hind get pre-computed\n # maybe not needed\n uninit_hind = uninit_hind.compute().chunk()\n bootstrapped_uninit = resample_func(\n uninit_hind, iterations, resample_dim\n )\n bootstrapped_uninit = bootstrapped_uninit.isel(\n member=slice(None, hind.member.size)\n )\n bootstrapped_uninit[\"lead\"] = hind[\"lead\"]\n if dask.is_dask_collection(bootstrapped_uninit):\n bootstrapped_uninit = _maybe_auto_chunk(\n bootstrapped_uninit.chunk({\"lead\": 1}),\n [\"iteration\"] + chunking_dims,\n )\n\n if \"uninitialized\" in reference:\n bootstrapped_uninit_skill = compute(\n bootstrapped_uninit,\n verif,\n metric=metric,\n comparison=\"m2o\" if isHindcast else comparison,\n dim=dim,\n add_attrs=False,\n **metric_kwargs,\n )\n # take mean if 'm2o' comparison forced before\n if isHindcast and comparison != __m2o:\n bootstrapped_uninit_skill = bootstrapped_uninit_skill.mean(\"member\")\n\n with xr.set_options(keep_attrs=True):\n bootstrapped_hind = resample_func(hind, iterations, resample_dim)\n if dask.is_dask_collection(bootstrapped_hind):\n bootstrapped_hind = bootstrapped_hind.chunk({\"member\": -1})\n\n bootstrapped_init_skill = compute(\n bootstrapped_hind,\n verif,\n metric=metric,\n comparison=comparison,\n add_attrs=False,\n dim=dim,\n **metric_kwargs,\n )\n if \"persistence\" in reference:\n pers_skill = compute_persistence(\n hind,\n verif,\n metric=metric,\n dim=dim,\n **metric_kwargs_reference,\n )\n # bootstrap pers\n if resample_dim == \"init\":\n bootstrapped_pers_skill = compute_persistence(\n bootstrapped_hind,\n verif,\n metric=metric,\n **metric_kwargs_reference,\n )\n else: # member no need to calculate all again\n bootstrapped_pers_skill, _ = xr.broadcast(\n pers_skill, bootstrapped_init_skill\n )\n\n # calc mean skill without any resampling\n init_skill = compute(\n hind,\n verif,\n metric=metric,\n comparison=comparison,\n dim=dim,\n **metric_kwargs,\n )\n\n if \"uninitialized\" in reference:\n # uninit skill as mean resampled uninit skill\n unin_skill = bootstrapped_uninit_skill.mean(\"iteration\") # noqa: F841\n if \"persistence\" in reference:\n pers_skill = compute_persistence(\n hind, verif, metric=metric, dim=dim, **metric_kwargs_reference\n )\n if \"climatology\" in reference:\n clim_skill = compute_climatology(\n hind, verif, metric=metric, dim=dim, comparison=comparison, **metric_kwargs\n )\n # get clim_skill into init,lead dimensions\n if \"time\" in clim_skill.dims and \"valid_time\" in init_skill.coords:\n # for idea see https://github.com/pydata/xarray/discussions/4593\n valid_time_overlap = init_skill.coords[\"valid_time\"].where(\n init_skill.coords[\"valid_time\"].isin(clim_skill.time)\n )\n clim_skill = clim_skill.rename({\"time\": \"valid_time\"})\n clim_skill = clim_skill.sel(\n valid_time=init_skill.coords[\"valid_time\"], method=\"nearest\"\n )\n # mask wrongly taken method nearest values\n clim_skill = clim_skill.where(valid_time_overlap.notnull())\n # print('after special sel', clim_skill.coords, clim_skill.sizes)\n bootstrapped_clim_skill, _ = xr.broadcast(clim_skill, bootstrapped_init_skill)\n\n # get confidence intervals CI\n init_ci = _distribution_to_ci(bootstrapped_init_skill, ci_low, ci_high)\n if \"uninitialized\" in reference:\n unin_ci = _distribution_to_ci( # noqa: F841\n bootstrapped_uninit_skill, ci_low, ci_high\n )\n if \"climatology\" in reference:\n clim_ci = _distribution_to_ci( # noqa: F841\n bootstrapped_clim_skill, ci_low, ci_high\n )\n if \"persistence\" in reference:\n pers_ci = _distribution_to_ci( # noqa: F841\n bootstrapped_pers_skill, ci_low_pers, ci_high_pers\n )\n\n # pvalue whether uninit or pers better than init forecast\n if \"uninitialized\" in reference:\n p_unin_over_init = _pvalue_from_distributions( # noqa: F841\n bootstrapped_uninit_skill, bootstrapped_init_skill, metric=metric\n )\n if \"climatology\" in reference:\n p_clim_over_init = _pvalue_from_distributions( # noqa: F841\n bootstrapped_clim_skill, bootstrapped_init_skill, metric=metric\n )\n if \"persistence\" in reference:\n p_pers_over_init = _pvalue_from_distributions( # noqa: F841\n bootstrapped_pers_skill, bootstrapped_init_skill, metric=metric\n )\n\n # gather return\n # p defined as probability that reference better than\n # initialized, therefore not defined for initialized skill\n # itself\n results = xr.concat(\n [\n init_skill,\n init_skill.where(init_skill == -999),\n init_ci.isel(quantile=0, drop=True),\n init_ci.isel(quantile=1, drop=True),\n ],\n dim=\"results\",\n coords=\"minimal\",\n ).assign_coords(\n results=(\"results\", [\"verify skill\", \"p\", \"low_ci\", \"high_ci\"]),\n skill=\"initialized\",\n )\n\n if reference != []:\n for r in reference:\n ref_skill = eval(f\"{r[:4]}_skill\")\n ref_p = eval(f\"p_{r[:4]}_over_init\")\n ref_ci_low = eval(f\"{r[:4]}_ci\").isel(quantile=0, drop=True)\n ref_ci_high = eval(f\"{r[:4]}_ci\").isel(quantile=1, drop=True)\n ref_results = xr.concat(\n [ref_skill, ref_p, ref_ci_low, ref_ci_high],\n dim=\"results\",\n **CONCAT_KWARGS,\n ).assign_coords(\n skill=r, results=(\"results\", [\"verify skill\", \"p\", \"low_ci\", \"high_ci\"])\n )\n if \"member\" in ref_results.dims:\n if not ref_results[\"member\"].identical(results[\"member\"]):\n ref_results[\"member\"] = results[\n \"member\"\n ] # fixes m2c different member names in reference forecasts\n results = xr.concat([results, ref_results], dim=\"skill\", **CONCAT_KWARGS)\n results = results.assign_coords(skill=[\"initialized\"] + reference).squeeze()\n else:\n results = results.drop_sel(results=\"p\")\n results = results.squeeze()\n\n # Attach climpred compute information to skill\n # results.results\n metadata_dict = {\n \"confidence_interval_levels\": f\"{ci_high}-{ci_low}\",\n \"bootstrap_iterations\": iterations,\n }\n if reference is not None:\n metadata_dict[\n \"p\"\n ] = \"probability that reference performs better than initialized\"\n metadata_dict.update(metric_kwargs)\n results = assign_attrs(\n results,\n hind,\n alignment=alignment,\n metric=metric,\n comparison=comparison,\n dim=dim,\n metadata_dict=metadata_dict,\n )\n # Ensure that the lead units get carried along for the calculation. The attribute\n # tends to get dropped along the way due to ``xarray`` functionality.\n results[\"lead\"] = hind[\"lead\"]\n if \"units\" in hind[\"lead\"].attrs and \"units\" not in results[\"lead\"].attrs:\n results[\"lead\"].attrs[\"units\"] = hind[\"lead\"].attrs[\"units\"]\n return results\n\n\ndef bootstrap_hindcast(\n hind,\n hist,\n verif,\n alignment=\"same_verifs\",\n metric=\"pearson_r\",\n comparison=\"e2o\",\n dim=\"init\",\n reference=None,\n resample_dim=\"member\",\n sig=95,\n iterations=500,\n pers_sig=None,\n **metric_kwargs,\n):\n \"\"\"Bootstrap compute with replacement. Wrapper of\n py:func:`bootstrap_compute` for hindcasts.\n\n Args:\n hind (xr.Dataset): prediction ensemble.\n verif (xr.Dataset): Verification data.\n hist (xr.Dataset): historical/uninitialized simulation.\n metric (str): `metric`. Defaults to 'pearson_r'.\n comparison (str): `comparison`. Defaults to 'e2o'.\n dim (str): dimension to apply metric over. default: 'init'.\n reference (str, list of str): Type of reference forecasts with which to\n verify. One or more of ['persistence', 'uninitialized'].\n If None or empty, returns no p value.\n resample_dim (str or list): dimension to resample from. default: 'member'.\n\n - 'member': select a different set of members from hind\n - 'init': select a different set of initializations from hind\n\n sig (int): Significance level for uninitialized and\n initialized skill. Defaults to 95.\n pers_sig (int): Significance level for persistence skill confidence levels.\n Defaults to sig.\n iterations (int): number of resampling iterations (bootstrap\n with replacement). Defaults to 500.\n ** metric_kwargs (dict): additional keywords to be passed to metric\n (see the arguments required for a given metric in :ref:`Metrics`).\n\n Returns:\n results: (xr.Dataset): bootstrapped results for the three different kinds of\n predictions:\n\n - `initialized` for the initialized hindcast `hind` and describes skill due\n to initialization and external forcing\n - `uninitialized` for the uninitialized/historical and approximates skill\n from external forcing\n - `persistence` for the persistence forecast computed by\n `compute_persistence`\n\n the different results:\n - `verify skill`: skill values\n - `p`: p value\n - `low_ci` and `high_ci`: high and low ends of confidence intervals based\n on significance threshold `sig`\n\n Reference:\n * Goddard, L., A. Kumar, A. Solomon, D. Smith, G. Boer, P.\n Gonzalez, V. Kharin, et al. “A Verification Framework for\n Interannual-to-Decadal Predictions Experiments.” Climate\n Dynamics 40, no. 1–2 (January 1, 2013): 245–72.\n https://doi.org/10/f4jjvf.\n\n See also:\n * climpred.bootstrap.bootstrap_compute\n * climpred.prediction.compute_hindcast\n\n \"\"\"\n # Check that init is int, cftime, or datetime; convert ints or datetime to cftime.\n hind = convert_time_index(hind, \"init\", \"hind[init]\")\n if isinstance(hist, xr.Dataset):\n hist = convert_time_index(hist, \"time\", \"uninitialized[time]\")\n else:\n hist = False\n verif = convert_time_index(verif, \"time\", \"verif[time]\")\n # Put this after `convert_time_index` since it assigns 'years' attribute if the\n # `init` dimension is a `float` or `int`.\n has_valid_lead_units(hind)\n\n if (\"same_verif\" in alignment) & (resample_dim == \"init\"):\n raise KeywordError(\n \"Cannot have both alignment='same_verifs' and \"\n \"resample_dim='init'. Change `resample_dim` to 'member' to keep \"\n \"common verification alignment or `alignment` to 'same_inits' to \"\n \"resample over initializations.\"\n )\n\n # Kludge for now. Since we're computing persistence here we need to ensure that\n # all products have a union in their time axis.\n if hist not in [None, False]:\n times = np.sort(\n list(set(hind.init.data) & set(hist.time.data) & set(verif.time.data))\n )\n else:\n times = np.sort(list(set(hind.init.data) & set(verif.time.data)))\n hind = hind.sel(init=times)\n if isinstance(hist, xr.Dataset):\n hist = hist.sel(time=times)\n verif = verif.sel(time=times)\n\n return bootstrap_compute(\n hind,\n verif,\n hist=hist,\n alignment=alignment,\n metric=metric,\n comparison=comparison,\n dim=dim,\n reference=reference,\n resample_dim=resample_dim,\n sig=sig,\n iterations=iterations,\n pers_sig=pers_sig,\n compute=compute_hindcast,\n resample_uninit=bootstrap_uninitialized_ensemble,\n **metric_kwargs,\n )\n\n\ndef bootstrap_perfect_model(\n init_pm,\n control,\n metric=\"pearson_r\",\n comparison=\"m2e\",\n dim=None,\n reference=None,\n resample_dim=\"member\",\n sig=95,\n iterations=500,\n pers_sig=None,\n **metric_kwargs,\n):\n \"\"\"Bootstrap compute with replacement. Wrapper of\n py:func:`bootstrap_compute` for perfect-model framework.\n\n Args:\n hind (xr.Dataset): prediction ensemble.\n verif (xr.Dataset): Verification data.\n hist (xr.Dataset): historical/uninitialized simulation.\n metric (str): `metric`. Defaults to 'pearson_r'.\n comparison (str): `comparison`. Defaults to 'm2e'.\n dim (str): dimension to apply metric over. default: ['init', 'member'].\n reference (str, list of str): Type of reference forecasts with which to\n verify. One or more of ['persistence', 'uninitialized'].\n If None or empty, returns no p value.\n resample_dim (str or list): dimension to resample from. default: 'member'.\n\n - 'member': select a different set of members from hind\n - 'init': select a different set of initializations from hind\n\n sig (int): Significance level for uninitialized and\n initialized skill. Defaults to 95.\n pers_sig (int): Significance level for persistence skill confidence levels.\n Defaults to sig.\n iterations (int): number of resampling iterations (bootstrap\n with replacement). Defaults to 500.\n ** metric_kwargs (dict): additional keywords to be passed to metric\n (see the arguments required for a given metric in :ref:`Metrics`).\n\n Returns:\n results: (xr.Dataset): bootstrapped results for the three different kinds of\n predictions:\n\n - `initialized` for the initialized hindcast `hind` and describes skill due\n to initialization and external forcing\n - `uninitialized` for the uninitialized/historical and approximates skill\n from external forcing\n - `persistence` for the persistence forecast\n - `climatology`\n\n the different results:\n - `skill`: skill values\n - `p`: p value\n - `low_ci` and `high_ci`: high and low ends of confidence intervals based\n on significance threshold `sig`\n\n Reference:\n * Goddard, L., A. Kumar, A. Solomon, D. Smith, G. Boer, P.\n Gonzalez, V. Kharin, et al. “A Verification Framework for\n Interannual-to-Decadal Predictions Experiments.” Climate\n Dynamics 40, no. 1–2 (January 1, 2013): 245–72.\n https://doi.org/10/f4jjvf.\n\n See also:\n * climpred.bootstrap.bootstrap_compute\n * climpred.prediction.compute_perfect_model\n \"\"\"\n if dim is None:\n dim = [\"init\", \"member\"]\n # Check init & time is int, cftime, or datetime; convert ints or datetime to cftime.\n init_pm = convert_time_index(\n init_pm, \"init\", \"init_pm[init]\", calendar=PM_CALENDAR_STR\n )\n control = convert_time_index(\n control, \"time\", \"control[time]\", calendar=PM_CALENDAR_STR\n )\n lead_units_equal_control_time_stride(init_pm, control)\n return bootstrap_compute(\n init_pm,\n control,\n hist=None,\n metric=metric,\n comparison=comparison,\n dim=dim,\n reference=reference,\n resample_dim=resample_dim,\n sig=sig,\n iterations=iterations,\n pers_sig=pers_sig,\n compute=compute_perfect_model,\n resample_uninit=bootstrap_uninit_pm_ensemble_from_control_cftime,\n **metric_kwargs,\n )\n\n\ndef _bootstrap_func(\n func,\n ds,\n resample_dim,\n sig=95,\n iterations=500,\n *func_args,\n **func_kwargs,\n):\n \"\"\"Sig % threshold of function based on iterations resampling with replacement.\n\n Reference:\n * Mason, S. J., and G. M. Mimmack. “The Use of Bootstrap Confidence\n Intervals for the Correlation Coefficient in Climatology.” Theoretical and\n Applied Climatology 45, no. 4 (December 1, 1992): 229–33.\n https://doi.org/10/b6fnsv.\n\n Args:\n func (function): function to be bootstrapped.\n ds (xr.object): first input argument of func. `chunk` ds on `dim` other\n than `resample_dim` for potential performance increase when multiple\n CPUs available.\n resample_dim (str): dimension to resample from.\n sig (int,float,list): significance levels to return. Defaults to 95.\n iterations (int): number of resample iterations. Defaults to 500.\n *func_args (type): `*func_args`.\n **func_kwargs (type): `**func_kwargs`.\n\n Returns:\n sig_level: bootstrapped significance levels with\n dimensions of init_pm and len(sig) if sig is list\n \"\"\"\n if not callable(func):\n raise ValueError(f\"Please provide func as a function, found {type(func)}\")\n warn_if_chunking_would_increase_performance(ds)\n if isinstance(sig, list):\n psig = [i / 100 for i in sig]\n else:\n psig = sig / 100\n\n resample_func = _get_resample_func(ds)\n bootstraped_ds = resample_func(ds, iterations, dim=resample_dim, replace=False)\n bootstraped_results = func(bootstraped_ds, *func_args, **func_kwargs)\n bootstraped_results = rechunk_to_single_chunk_if_more_than_one_chunk_along_dim(\n bootstraped_results, dim=\"iteration\"\n )\n sig_level = bootstraped_results.quantile(dim=\"iteration\", q=psig, skipna=False)\n return sig_level\n\n\ndef dpp_threshold(control, sig=95, iterations=500, dim=\"time\", **dpp_kwargs):\n \"\"\"Calc DPP significance levels from re-sampled dataset.\n\n Reference:\n * Feng, X., T. DelSole, and P. Houser. “Bootstrap Estimated Seasonal\n Potential Predictability of Global Temperature and Precipitation.”\n Geophysical Research Letters 38, no. 7 (2011).\n https://doi.org/10/ft272w.\n\n See also:\n * climpred.bootstrap._bootstrap_func\n * climpred.stats.dpp\n \"\"\"\n return _bootstrap_func(\n dpp, control, dim, sig=sig, iterations=iterations, **dpp_kwargs\n )\n\n\ndef varweighted_mean_period_threshold(control, sig=95, iterations=500, time_dim=\"time\"):\n \"\"\"Calc the variance-weighted mean period significance levels from re-sampled\n dataset.\n\n See also:\n * climpred.bootstrap._bootstrap_func\n * climpred.stats.varweighted_mean_period\n \"\"\"\n if varweighted_mean_period is None:\n raise ImportError(\n \"xrft is not installed; see\"\n \"https://xrft.readthedocs.io/en/latest/installation.html\"\n )\n return _bootstrap_func(\n varweighted_mean_period,\n control,\n time_dim,\n sig=sig,\n iterations=iterations,\n )\n","sub_path":"climpred/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":48906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"360037747","text":"from flask_restful import Resource, reqparse\nfrom models.rentals import RentalsModel\nfrom datetime import datetime, timedelta\nfrom models.motos import MotosModel\nfrom models.users import auth\nfrom flask import g\n\n\nparser = reqparse.RequestParser()\nparser.add_argument('moto_id', type=int, required=False, help='Moto id of rented moto.')\nparser.add_argument('user_id', type=int, required=False, help='User id of rented moto.')\nparser.add_argument('end_rental', type=str, required=False, help='end_rental=True to end rental,'\n 'end_rental=False to start counting time of rental')\nparser.add_argument('latitude', type=float, required=False, help='Moto latitude of rented moto.')\nparser.add_argument('longitude', type=float, required=False, help='Moto longitude of rented moto.')\n\n\nclass Rentals(Resource):\n \"\"\"\n API Restful methods for Rentals\n \"\"\"\n\n def get(self, id):\n \"\"\"\n GET method\n Gets a rental by id\n Param: int id\n Return: dict (account ok / message)\n \"\"\"\n\n rental = RentalsModel.find_by_id(id=id)\n\n if rental:\n return {'rental': rental.json()}, 200\n else:\n return {'message': 'Rental with id [{}] not found'.format(id)}, 404\n\n def post(self):\n \"\"\"\n POST method\n Adds a new rental. This method is used for initialize a rental.\n Return: dict (rental created / message)\n \"\"\"\n data = parser.parse_args()\n if not data['moto_id']:\n return {'message': {\n \"moto_id\": \"Moto_id cant be empty\"\n }}, 400\n if not data['user_id']:\n return {'message': {\n \"user_id\": \"User_id cant be empty\"\n }}, 400\n\n activerental = RentalsModel.find_active_rental_by_user_id(user_id=data['user_id'])\n if activerental:\n return {'message': \"User with id [{}] already has an ongoing rental\".format(data['user_id'])}, 409\n\n rental = RentalsModel(moto_id=data['moto_id'],\n user_id=data['user_id'],\n book_hour=datetime.now().isoformat())\n moto = MotosModel.find_by_id(data['moto_id'])\n try:\n rental.save_to_db()\n moto.set_available(False)\n return {'rental': RentalsModel.find_by_id(rental.id).json()}, 201\n\n except:\n return {'message': 'Internal server error'}, 500\n\n def put(self, id):\n \"\"\"\n PUT method\n Updates a rental. This method is used for finish a rental.\n :param id:\n :return: dict (rental updated / message)\n \"\"\"\n data = parser.parse_args()\n rental = RentalsModel.find_by_id(id)\n moto = MotosModel.find_by_id(rental.moto_id)\n if rental is None:\n return {'message': 'This rental doesn t exist'}, 404\n if data['end_rental'] is not None:\n if str_to_bool(data['end_rental']):\n if rental.finish_rental_hour is not None:\n return {'message': 'The rental is already finsished.'}, 409\n if not data['latitude'] or not data['longitude']:\n return {'message': 'latitude and longitude parameters needed for updating moto coordinates'}, 409\n try:\n rental.update_finish_rent_hour(datetime.now().isoformat())\n moto.set_available(True)\n moto.update_coords(data['latitude'], data['longitude'])\n new_rental = RentalsModel.find_by_id(rental.id)\n return {'rental': new_rental.json()}, 200\n except:\n return {'message': 'Internal server error'}, 500\n else:\n if rental.finish_book_hour is not None:\n return {'message': 'The book is already finsished.'}, 409\n try:\n max_finish_book_hour = datetime.strptime(rental.book_hour, '%Y-%m-%dT%H:%M:%S.%f') + timedelta(minutes=15)\n if max_finish_book_hour > datetime.now():\n rental.update_finish_book_hour(datetime.now().isoformat())\n new_rental = RentalsModel.find_by_id(rental.id)\n return {'rental': new_rental.json()}, 200\n else:\n rental.update_finish_book_hour(max_finish_book_hour.isoformat())\n new_rental = RentalsModel.find_by_id(rental.id)\n return {'rental': new_rental.json()}, 200\n except:\n return {'message': 'Internal server error'}, 500\n else:\n return {'message': 'Bad request, you must pass end_rental param'}, 400\n\n @auth.login_required(role='admin')\n def delete(self, id):\n \"\"\"\n DELETE method\n Removes a rental\n Param: int id\n Return: dict (message ok / message)\n \"\"\"\n rental = RentalsModel.find_by_id(id=id)\n if rental:\n try:\n rental.delete_from_db()\n return {'message': \"Rental with id [{}] and all associated info deleted\".format(id)}, 200\n except:\n return {'message': \"Internal server error\"}, 500\n else:\n return {'message': \"Rental with id [{}] Not found\".format(id)}, 404\n\nclass ActiveRentals(Resource):\n \"\"\"\n API Restful methods for ActiveRentals\n \"\"\"\n\n def get(self, user_id):\n \"\"\"\n GET method\n Gets active rental by user id\n Param: int user id\n Return: dict (account ok / message)\n \"\"\"\n\n rental = RentalsModel.find_active_rental_by_user_id(user_id=user_id)\n\n if rental:\n return {'rental': rental.json()}, 200\n else:\n return {'message': 'User with id [{}] has no active rentals'.format(user_id)}, 404\n\nclass RentalsList(Resource):\n \"\"\"\n API Restful methods for RentalsList\n \"\"\"\n\n def get(self):\n \"\"\"\n GET method\n Return: dict (rentals)\n \"\"\"\n try:\n rentals = RentalsModel.all_rentals()\n return {'rentals': [rental.json() for rental in rentals]}, 200\n except Exception as e:\n return {'message': 'Internal server error.\\n' + str(e)}, 500\n\n\ndef str_to_bool(s):\n if s.lower() == 'true':\n return True\n elif s.lower() == 'false':\n return False\n else:\n raise ValueError","sub_path":"Backend/resources/rentals.py","file_name":"rentals.py","file_ext":"py","file_size_in_byte":6516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"107913427","text":"from tkinter import *\n\nclass ChangeLabel:\n\tdef __init__(self):\n\t\twindow = Tk()\n\t\twindow.title(\"Change Label Demo\")\n\n\t\tframe1 = Frame(window)\n\t\tframe1.pack()\n\t\tself.label1 = Label(frame1, text = \"Your Text Is Shown Here\")\n\t\tself.label1.pack()\n\n\t\tframe2 = Frame(window)\n\t\tframe2.pack()\n\t\tlabel2 = Label(frame2, text = \"Enter name: \")\n\t\tlabel2.pack()\n\t\tself.v1 = StringVar()\n\t\tentry = Entry(frame2, textvariable = self.v1)\n\t\tbutton = Button(frame2, text = \"Change\", command = self.processChangeBtn)\t\n\t\tself.v2 = StringVar()\n\t\tradioBtn1 = Radiobutton(frame2, text = \"Red\", variable = self.v2, value = 'R', command = self.processRBtn)\n\t\tradioBtn2 = Radiobutton(frame2, text = \"Yellow\", variable = self.v2, value = 'Y', command = self.processRBtn)\n\n\t\tlabel2.grid(row = 1, column = 1)\n\t\tentry.grid(row = 1, column = 2)\n\t\tbutton.grid(row = 1, column = 3)\n\t\tradioBtn1.grid(row = 1, column = 4)\n\t\tradioBtn2.grid(row = 1, column = 5)\n\n\t\twindow.mainloop()\n\n\tdef processChangeBtn(self):\n\t\tif self.v1.get() == '':\n\t\t\tself.label1[\"text\"] = \"Enter Valid String\"\n\t\telse:\n\t\t\tself.label1[\"text\"] = self.v1.get()\n\n\tdef processRBtn(self):\n\t\tif self.v2.get() == 'R':\n\t\t\tself.label1['bg'] = \"red\"\n\t\telif self.v2.get() == 'Y':\n\t\t\tself.label1['bg'] = \"yellow\"\n\n\nChangeLabel()\n","sub_path":"python_GUI/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"147489408","text":"import datetime\nfrom datetime import date\nfrom datetime import timedelta\nimport shutil\nimport openpyxl\nfrom files.calweek import calweek\nfrom files.planning import planning\nimport os\nfrom files.read_data import read_eBas\nfrom files.copyx import copyx\n\nJahr = '2020'\n\n\ndef __init__(Prüffeld = 'UPZ'):\n\n\t'''Wochenplanung für EA-8 AKF Beladungen.'''\n\t\n\tP = input('Prüffeld auswählen E für EETZ, U für UPZ: ')\n\tif P in ['e', 'E', 'EETZ', 'eetz']:\n\t\tPrüffeld = 'EETZ'\n\t\n\twhile True:\n\t\tfilen = input('Dateiname eingeben: ')\n\t\t#if len(filen) < 1: filen = 'ebas_export.xlsx'\n\t\tfile = 'AKF-Wochenplanung\\{}'.format(filen)\n\t\tif os.path.isfile(file):\n\t\t\tbreak\n\t\telif filen in ['x', 'X']:\n\t\t\tprint('Programm beendet')\t\n\t\t\texit()\n\t\telse:\n\t\t\tprint('Datei nicht gefunden. Erneut eingeben.\\n Hinweis: Auf Endung \".xlsx\" achten!\\n \"x\" zum Beenden eingeben\\n\\n')\n\n\t# Get current Calendar Week or desirede CW\n\tyear = input('\\nJahr eingeben oder Enter für 2020: ')\n\tif len(year)<1:\n\t\tyear = Jahr\n\tKW = calweek()\n\n\tprint('\\n\\nArbeite...')\n\n\t#Copy Excel Template and create new File\n\tfname = copyx(Prüffeld,KW)\n\t\n\t# Get Monday for current CW\n\tmonday = date.fromisocalendar(int(year), KW, 1)\n\n\t# Open workbook\n\tworkbook = openpyxl.load_workbook(fname)\n\tsheet = workbook.active\n\n\n\t# NEW in V1.2: For Loop for creating list for weekdays and writing in Excel\n\tweek = list()\n\tfor i in range(-1, 6):\n\t\tweek.append(monday+timedelta(days=i))\n\n\tif Prüffeld == 'EETZ':\n\t\tsheet['A1'] = 'KW{}'.format(str(KW))\n\t\tsheet['A2'] = '{}'.format(year)\n\tif Prüffeld == 'UPZ':\n\t\tsheet['D1'] = 'KW{}'.format(str(KW))\n\t\tsheet['A1'] = '{}'.format(year)\n\tfor i, j in zip(['A4','A6','A19','A32','A45','A58','A71'], week):\n\t\tsheet[i] = j.strftime(\"%d.%m\")\n\n\t# Read the AKF data from eBas Export\n\takfs = read_eBas(file, Prüffeld)\n\n\t#Call planning function\n\tplanning(workbook, sheet, monday, akfs, Prüffeld)\n\n\n\tworkbook.save(fname)\n\tworkbook.close()\n\tshutil.move(fname, \"AKF-Wochenplanung\\{}\".format(fname))\n\tinput('\\nExcel-Datei mit dem Namen ' + fname + ' erstellt. Enter zum Beenden drücken')\n\t\n\nif __name__ == '__main__':\n __init__()\n\n\n","sub_path":"app/files/Archive/Wochenplanung_V1.2.py","file_name":"Wochenplanung_V1.2.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"284509926","text":"from ..RssPost import *\nfrom ..Tags import *\nfrom ..Site import *\nimport requests\nimport time\nfrom .. import DOMparser\nfrom lxml import etree\nfrom lxml import html as lxmlhtml\nfrom ..systemHelper import parseTime, specialize_path\nfrom ..MyFunction import randomString\nimport logging\n\nclass basicrsshand(object):\n def __init__(self):\n self.rsspost = RssPost()\n\n def handle(self, d, Acc, domain, imgdir):\n self.imgdir = imgdir\n last_update = Acc['last_update']\n self.site = Site.GetOrCreate(domain)\n for rsselem in d.entries:\n t = rsselem.published\n t = parseTime(t)\n if t < last_update: continue\n self.rsspost['account_id'] = Acc['id']\n self.rsspost['site_id'] = self.site['id']\n try: self.rsspost['title'] = rsselem.title.encode('ascii','ignore')\n except: self.rsspost['title'] = ''\n try: self.rsspost['description'] = rsselem.summary.encode('ascii','ignore')\n except: self.rsspost['description'] = ''\n self.rsspost['content'] = ''\n self.rsspost['tags'] = ''\n self.rsspost['image_file'] = None\n if ('media_content' in rsselem) and (len(rsselem.media_content)>0) and ('url' in rsselem.media_content[0]): self.rsspost['image_link'] = rsselem.media_content[0]['url']\n else: self.rsspost['image_link'] = None\n self.rsspost['link'] = rsselem.link\n self.rsspost['social_score'] = 0\n self.rsspost['created_at'] = parseTime(rsselem.published)\n if self.rsspost['link']!=None and len(self.rsspost['link'])>0: self.getcontent(Acc['tag_limit'])\n if self.rsspost['image_link']!=None and len(self.rsspost['image_link'])>0: self.withimglink()\n logging.info('Puller: @%s | new feed %s'%(Acc['name'], (self.rsspost['title'])[:16]))\n self.rsspost.Put()\n return\n\n def withimglink(self):\n try: r = requests.get(self.rsspost['image_link'])\n except: return\n if r.status_code!=200: return\n self.rsspost['image_file'] = str(time.time())+'_'+randomString(16)+'.'+self.rsspost['image_link'].split('?')[0].split('.')[-1].strip()\n with open(specialize_path(self.imgdir+self.rsspost['image_file']), 'wb') as f:\n for chunk in r.iter_content():\n f.write(chunk)\n return\n\n def getcontent(self, tag_limit):\n if tag_limit: tag_limit = int(tag_limit)\n else: tag_limit = 0\n try: r = requests.get(self.rsspost['link'])\n except: return\n if r.status_code!=200: return\n htmltree = etree.HTML(r.text)\n mostptagelem = DOMparser.findelemwithmostptag(htmltree)\n if mostptagelem is None: return\n self.rsspost['content'] = '\\n'.join([lxmlhtml.tostring(child) for child in mostptagelem if (child.tag=='p') and (child.text is not None) and ('Like Us on' not in child.text)])\n try: self.rsspost['content'] = self.rsspost['content'].encode('ascii','ignore')\n except: self.rsspost['content'] = ''\n tag_list = Tags.ParseTags(self.rsspost['content'], self.rsspost['site_id'])\n tag_list.extend(Tags.ParseTags(self.rsspost['title'], self.rsspost['site_id']))\n if tag_list is not None and len(tag_list)>0 and tag_limit>0:\n self.rsspost['tags'] = ','.join(tag_list[:tag_limit])\n self.withhtmltree(htmltree)\n return\n \n def withhtmltree(self, htmltree):\n pass\n return\n\nclass myrsshand(basicrsshand):\n \"\"\"docstring for myrsshand\"\"\"\n def __init__(self):\n super(myrsshand, self).__init__()\n\n","sub_path":"SocialManager/Lib/RssHandler/basic_rsshandler.py","file_name":"basic_rsshandler.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"507195483","text":"#-*- coding:utf-8 -*-\r\nimport tensorflow as tf\r\n\r\n# MobilenetV2 와 Resnetxt 를 결합해보자!\r\nclass GroupConv(tf.keras.layers.Layer):\r\n def __init__(self, filters, kernel_size, strides, padding, use_bias, weight_decay, n_groups, name):\r\n super(GroupConv, self).__init__()\r\n self.filters = filters\r\n self.kernel_size = kernel_size\r\n self.strides = strides\r\n self.padding = padding\r\n self.use_bias = use_bias\r\n self.weight_decay = weight_decay\r\n self.n_groups = n_groups\r\n self.name_ = name\r\n\r\n def build(self, inputs):\r\n #input_channels = tf.shape(inputs)\r\n _,_,_,input_channels = tf.TensorShape(inputs)\r\n #input_channels = inputs.shape[-1]\r\n kernel_shape = (self.kernel_size, self.kernel_size) + (input_channels // self.n_groups, self.filters)\r\n\r\n self.kernel = self.add_weight(name=\"kernel\",\r\n shape=kernel_shape,\r\n initializer=tf.keras.initializers.glorot_uniform,\r\n regularizer=tf.keras.regularizers.l2(self.weight_decay),\r\n constraint=None,\r\n trainable=True,\r\n dtype=self.dtype)\r\n if self.use_bias:\r\n self.bias = self.add_weight(name='bias',\r\n shape=(self.filters,),\r\n initializer=tf.keras.initializers.Zeros,\r\n regularizer=None,\r\n constraint=None,\r\n trainable=True,\r\n dtype=self.dtype)\r\n\r\n else:\r\n self.bias = None\r\n\r\n self.groupConv = lambda i, k: tf.nn.conv2d(i, k, strides=self.strides,\r\n padding=self.padding, name=self.name_)\r\n\r\n @tf.function\r\n def call(self, inputs):\r\n if self.n_groups == 1:\r\n outputs = self.groupConv(inputs, self.kernel)\r\n else:\r\n inputGroups = tf.split(axis=3, num_or_size_splits=self.n_groups, value=inputs)\r\n weightGroups = tf.split(axis=3, num_or_size_splits=self.n_groups, value=self.kernel)\r\n convGroup = [self.groupConv(i, k) for i,k in zip(inputGroups, weightGroups)]\r\n outputs = tf.concat(convGroup, 3)\r\n if self.use_bias:\r\n outputs = tf.nn.bias_add(outputs, self.bias)\r\n return outputs\r\n\r\n####################################################################################\r\ndef make_divisible(v, divisor, min_value=None):\r\n if min_value is None:\r\n min_value = divisor\r\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\r\n # Make sure that round down does not go down by more than 10%.\r\n if new_v < 0.9 * v:\r\n new_v += divisor\r\n return new_v\r\n\r\ndef res_block(inputs, expansion, strides, alpha, filters, weight_decay, block_id, blocks=\"depth\"):\r\n\r\n input_channels = tf.keras.backend.int_shape(inputs)[3]\r\n pointwise_conv_filters = int(filters * alpha)\r\n pointwise_filters = make_divisible(pointwise_conv_filters, 8)\r\n \r\n h = inputs\r\n prefix = \"block_{}_\".format(block_id)\r\n\r\n if block_id:\r\n h = tf.keras.layers.Conv2D(filters=expansion * input_channels,\r\n kernel_size=1,\r\n strides=1,\r\n padding=\"same\",\r\n use_bias=False,\r\n kernel_regularizer=tf.keras.regularizers.l2(weight_decay),\r\n name=prefix + \"expand\")(h)\r\n h = tf.keras.layers.BatchNormalization(name=prefix + \"expand_BN\")(h)\r\n h = tf.keras.layers.ReLU(6., name=prefix + \"expand_relu\")(h)\r\n else:\r\n prefix = \"expanded_conv_\"\r\n\r\n if blocks == \"depth\":\r\n if strides == 2:\r\n h = tf.keras.layers.ZeroPadding2D(padding=(1,1), name=prefix + \"pad\")(h)\r\n h = tf.keras.layers.DepthwiseConv2D(kernel_size=3,\r\n strides=strides,\r\n use_bias=False,\r\n padding=\"same\" if strides == 1 else \"valid\",\r\n depthwise_regularizer=tf.keras.regularizers.l2(weight_decay),\r\n name=prefix + \"depthwise\")(h)\r\n h = tf.keras.layers.BatchNormalization(name=prefix + \"depthwise_BN\")(h)\r\n h = tf.keras.layers.ReLU(6., name=prefix + \"depthwise_relu\")(h)\r\n \r\n else:\r\n h = GroupConv(filters=expansion * input_channels,\r\n kernel_size=3,\r\n strides=strides,\r\n padding=\"SAME\" if strides == 1 else \"VALID\",\r\n use_bias=False,\r\n weight_decay=weight_decay,\r\n n_groups=32,\r\n name=prefix + \"groupconv\")(h)\r\n h = tf.keras.layers.BatchNormalization(name=prefix + \"groupconv_BN\")(h)\r\n h = tf.keras.layers.ReLU(6., name=prefix + \"groupconv_relu\")(h)\r\n\r\n h = tf.keras.layers.Conv2D(filters=pointwise_filters,\r\n kernel_size=1,\r\n strides=1,\r\n padding=\"same\",\r\n use_bias=False,\r\n kernel_regularizer=tf.keras.regularizers.l2(weight_decay),\r\n name=prefix + \"project\")(h)\r\n h = tf.keras.layers.BatchNormalization(name=prefix + \"project_BN\")(h)\r\n\r\n if input_channels == pointwise_filters and strides == 1:\r\n return tf.keras.layers.Add(name=prefix + \"add\")([inputs, h])\r\n return h\r\n\r\ndef fix_model(input_shape=(224, 224, 3), num_classes=100, weight_decay=1e-4, alpha=1.0, depth='depth'):\r\n \r\n h = inputs = tf.keras.Input(input_shape)\r\n\r\n first_block_filters = make_divisible(32 * alpha, 8)\r\n h = tf.keras.layers.ZeroPadding2D(padding=(1,1), name=\"Conv1_pad\")(h)\r\n h = tf.keras.layers.Conv2D(filters=first_block_filters,\r\n kernel_size=3,\r\n strides=2,\r\n padding='valid',\r\n use_bias=False,\r\n kernel_regularizer=tf.keras.regularizers.l2(weight_decay),\r\n name=\"Conv1\")(h)\r\n h = tf.keras.layers.BatchNormalization(name=\"bn_Conv1\")(h)\r\n h = tf.keras.layers.ReLU(6., name=\"Conv1_relu\")(h)\r\n\r\n h = res_block(inputs=h, expansion=1, strides=1, alpha=alpha, filters=16, weight_decay=weight_decay, block_id=0, blocks='depth')\r\n\r\n h = res_block(inputs=h, expansion=6, strides=2, alpha=alpha, filters=24, weight_decay=weight_decay, block_id=1, blocks='depth')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=24, weight_decay=weight_decay, block_id=2, blocks='depth')\r\n\r\n h = res_block(inputs=h, expansion=6, strides=2, alpha=alpha, filters=32, weight_decay=weight_decay, block_id=3, blocks='depth') \r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=32, weight_decay=weight_decay, block_id=4, blocks='depth')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=32, weight_decay=weight_decay, block_id=5, blocks='depth')\r\n\r\n h = res_block(inputs=h, expansion=6, strides=2, alpha=alpha, filters=64, weight_decay=weight_decay, block_id=6, blocks='depth')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=64, weight_decay=weight_decay, block_id=7, blocks='depth')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=64, weight_decay=weight_decay, block_id=8, blocks='depth')\r\n\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=96, weight_decay=weight_decay, block_id=9, blocks='depth')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=96, weight_decay=weight_decay, block_id=10, blocks='depth')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=96, weight_decay=weight_decay, block_id=11, blocks='depth')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=96, weight_decay=weight_decay, block_id=12, blocks='depth')\r\n\r\n h = res_block(inputs=h, expansion=6, strides=2, alpha=alpha, filters=160, weight_decay=weight_decay, block_id=13, blocks='depth')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=160, weight_decay=weight_decay, block_id=14, blocks='groupconv')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=160, weight_decay=weight_decay, block_id=15, blocks='groupconv')\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=160, weight_decay=weight_decay, block_id=16, blocks='groupconv')\r\n\r\n h = res_block(inputs=h, expansion=6, strides=1, alpha=alpha, filters=320, weight_decay=weight_decay, block_id=17, blocks='depth')\r\n\r\n if alpha > 1.0:\r\n last_block_filters = make_divisible(1280 * alpha, 8)\r\n else:\r\n last_block_filters = 1280\r\n\r\n h = tf.keras.layers.Conv2D(filters=last_block_filters,\r\n kernel_size=1,\r\n strides=1,\r\n padding='same',\r\n use_bias=False,\r\n kernel_regularizer=tf.keras.regularizers.l2(weight_decay),\r\n name=\"Conv_1\")(h)\r\n h = tf.keras.layers.BatchNormalization(name=\"Conv_1_bn\")(h)\r\n h = tf.keras.layers.ReLU(6., name=\"out_relu\")(h)\r\n\r\n h = tf.keras.layers.GlobalAveragePooling2D()(h)\r\n h = tf.keras.layers.Dense(num_classes)(h)\r\n\r\n return tf.keras.Model(inputs=inputs, outputs=h)","sub_path":"Age_model_8.py","file_name":"Age_model_8.py","file_ext":"py","file_size_in_byte":9907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"32099964","text":"import os\n\nfrom flask import Flask\nfrom flask import render_template\n\nfrom mitmproxy.options import CONF_BASENAME\nfrom mitmproxy.options import CONF_DIR\nfrom mitmproxy.utils.magisk import write_magisk_module\n\napp = Flask(__name__)\n# will be overridden in the addon, setting this here so that the Flask app can be run standalone.\napp.config[\"CONFDIR\"] = CONF_DIR\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/cert/pem\")\ndef pem():\n return read_cert(\"pem\", \"application/x-x509-ca-cert\")\n\n\n@app.route(\"/cert/p12\")\ndef p12():\n return read_cert(\"p12\", \"application/x-pkcs12\")\n\n\n@app.route(\"/cert/cer\")\ndef cer():\n return read_cert(\"cer\", \"application/x-x509-ca-cert\")\n\n\n@app.route(\"/cert/magisk\")\ndef magisk():\n filename = CONF_BASENAME + f\"-magisk-module.zip\"\n p = os.path.join(app.config[\"CONFDIR\"], filename)\n p = os.path.expanduser(p)\n\n if not os.path.exists(p):\n write_magisk_module(p)\n\n with open(p, \"rb\") as f:\n cert = f.read()\n\n return cert, {\n \"Content-Type\": \"application/zip\",\n \"Content-Disposition\": f\"attachment; filename={filename}\",\n }\n\n\ndef read_cert(ext, content_type):\n filename = CONF_BASENAME + f\"-ca-cert.{ext}\"\n p = os.path.join(app.config[\"CONFDIR\"], filename)\n p = os.path.expanduser(p)\n with open(p, \"rb\") as f:\n cert = f.read()\n\n return cert, {\n \"Content-Type\": content_type,\n \"Content-Disposition\": f\"attachment; filename={filename}\",\n }\n","sub_path":"mitmproxy/addons/onboardingapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"587094666","text":"# -*- coding: utf-8 -*-\nfrom fabric.api import run, sudo, task, cd, env, settings\nfrom fabric.contrib.files import exists\nfrom fabtools import require\n\n\n_emr_support_bucket = 'support.elasticmapreduce'\n_lzo_lib_path = 'bootstrap-actions/presto/hadoop-lzo-0.4.19.jar'\n_openjdk = 'java-1.8.0-openjdk-headless.x86_64'\n\n\n@task\ndef install_libs():\n sudo(\"yum install {} -y\".format(_openjdk))\n run(\"/home/hadoop/bin/hdfs dfs -get s3://{bucket}/{path} presto_home/plugin/hive-hadoop2/\")\n","sub_path":"presto/fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249007691","text":"\nimport numpy as np\n\nclass ASCReader:\n\n def __init__ (self, fileName):\n self.FileName = fileName\n self.Options = self.parse_config ( )\n self.Time, self.Amplitude = self.parse_data();\n\n def getParameterByName (self, Name ):\n return self.Options[Name]\n\n def getTime ( self, us=False ):\n if us:\n return self.Time*1e6\n else:\n return self.Time\n\n def getData ( self ):\n return self.Amplitude\n\n def getGain ( self, Linear=False ):\n if Linear:\n return 10 ** ( float( self.Options['Gain'] ) / -20)\n else:\n return float( self.Options['Gain'] )\n\n def parse_data ( self ):\n data = np.loadtxt( self.FileName, skiprows=72, encoding='ISO-8859-1' )\n dt = float ( self.Options ['TimeBase'] ) * 1e-6\n dtO = float ( self.Options ['TriggerDelay'] ) *1e-6\n amp = 100 * data / 2048\n t = np.arange ( 0, (data.shape[0]*dt), dt) + dtO\n return t, amp\n\n def parse_config(self):\n COMMENT_CHAR = '#'\n OPTION_CHAR = ':'\n\n options = {}\n f = open(self.FileName, encoding='latin9')\n for line in f:\n # First, remove comments:\n if COMMENT_CHAR in line:\n # split on comment char, keep only the part before\n line, comment = line.split(COMMENT_CHAR, 1)\n # Second, find lines with an option=value:\n if OPTION_CHAR in line:\n # split on option char:\n option, value = line.split(OPTION_CHAR, 1)\n # strip spaces:\n strOption = \"\".join(option)\n if '[' in strOption:\n option, ba = strOption.split ( '[', 1 )\n\n option = option.strip()\n # print ( option )\n if option == 'Bemerkungen':\n param_list = value.split(',')\n for opt in param_list:\n #print ( opt.strip() )\n if '=' in opt:\n param, val = \"\".join(opt).split('=', 1)\n options[param.strip() ] = val.strip()\n #print ('%s = %s' % (param, val ) )\n\n value = value.strip()\n # store in dictionary:\n options[option] = value\n f.close()\n return options\n","sub_path":"Helper/HelpersIO.py","file_name":"HelpersIO.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"400897493","text":"# Item 28: Inherit from collections.abc for Custom Container Types\n\n# Python's built-in container types (lists, tuples, sets, dictionaries) can be subclassed to be extended with additional\n# functionality, e.g:\nclass FrequencyList(list):\n def __init__(self, members):\n super().__init__(members)\n\n def frequency(self):\n counts = {}\n for item in self:\n counts.setdefault(item, 0)\n counts[item] += 1\n return counts\n\nfoo = FrequencyList(['a', 'b', 'a', 'c', 'b', 'a', 'd'])\nprint('Length is', len(foo))\nfoo.pop()\nprint('After pop:', repr(foo))\nprint('Frequency:', foo.frequency())\n\n# Length is 7\n# After pop: ['a', 'b', 'a', 'c', 'b', 'a']\n# Frequency: {'b': 2, 'a': 3, 'c': 1}\n\n# Suppose now you want to write a class whose objects feel like a list, but is not a subclass of list. Consider you\n# want sequence semantics for a binary tree:\nclass BinaryNode(object):\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n# This class lacks the necessary __getitem__ method that Python executes when a call like bar[0] is executed:\nclass IndexableNode(BinaryNode):\n def _search(self, count, index):\n found = None\n if self.left:\n found, count = self.left._search(count, index)\n if not found and count == index:\n found = self\n else:\n count += 1\n if not found and self.right:\n found, count = self.right._search(count, index)\n return found, count\n\n def __getitem__(self, index):\n found, _ = self._search(0, index)\n if not found:\n raise IndexError('Index out of range')\n return found.value\n\ntree = IndexableNode(10,\n left=IndexableNode(5,\n left=IndexableNode(2),\n right=IndexableNode(6, right=IndexableNode(7))),\n right=IndexableNode(15, left=IndexableNode(11)))\n\n# Nodes can now be accessed in different ways:\nprint('LRR = ', tree.left.right.right.value)\nprint('Index 0 = ', tree[0])\nprint('Index 1 = ', tree[1])\nprint('11 in the tree?', 11 in tree)\nprint('17 in the tree?', 17 in tree)\nprint('Tree is', list(tree))\n\n# LRR = 7\n# Index 0 = 2\n# Index 1 = 5\n# 11 in the tree? True\n# 17 in the tree? False\n# Tree is [2, 5, 6, 7, 10, 11, 15]\n\n# However, this class does not fully resemble a built-in container class, e.g. len(tree) will fail, because it is not\n# implemented. This can be fixed easily:\nclass SequenceNode(IndexableNode):\n def __len__(self):\n _, count = self._search(0, None)\n return count\n\ntree = SequenceNode(10,\n left=SequenceNode(5,\n left=SequenceNode(2),\n right=SequenceNode(6, right=SequenceNode(7))),\n right=SequenceNode(15, left=SequenceNode(11)))\n\nprint('Length is:', len(tree))\n\n# Length is: 7\n\n# Yet other methods like count and index are still missing, so defining your own container type this way is harder\n# than appears at first.\n# The solution to this problem is to use the abstract base classes defined in the collections.abc module. When all\n# abstract methods are implemented, other ones like index and count come for free:\nfrom collections.abc import Sequence\n\nclass BetterNode(SequenceNode, Sequence):\n pass\n\ntree = BetterNode(10,\n left=BetterNode(5,\n left=BetterNode(2),\n right=BetterNode(6, right=BetterNode(7))),\n right=BetterNode(15, left=BetterNode(11)))\n\nprint('Index of 7 is', tree.index(7))\nprint('Count of 10 is', tree.count(10))\n\n# Index of 7 is 3\n# Count of 10 is 1\n\n# The benefit of this approach is even larger for classes that need more methods to match Python conventions, like\n# Set and MutableMapping.\n\n","sub_path":"item28.py","file_name":"item28.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"518297541","text":"import ipywidgets as widgets\nimport inputparams\n\n\n########\n# making species data\n########\nnumspecies = inputparams.input['num_species']\n\nspeciestab = widgets.Tab()\nspeciestab.children = inputparams.create_species(1)\nfor i in range(len(speciestab.children)):\n speciestab.set_title(i, 'species '+str(i+1))\n\ndef handle_species_change(change):\n speciestab.children = inputparams.create_species(change.new)\n for i in range(len(speciestab.children)):\n speciestab.set_title(i, 'species '+str(i+1))\n\nnumspecies.observe(handle_species_change, names='value')\n########\n# end of making species data\n########\n\n\n########\n# making laser_array\n########\n# numlaser = inputparams.input['n_laser']\n#\n# lasertab = widgets.Tab()\n# lasertab.children = inputparams.create_lasers(0)\n# for i in range(len(lasertab.children)):\n# lasertab.set_title(i, 'laser '+str(i+1))\n#\n# def handle_laser_change(change):\n# lasertab.children = inputparams.create_lasers(change.new)\n# for i in range(len(lasertab.children)):\n# lasertab.set_title(i, 'laser '+str(i+1))\n#\n# numlaser.observe(handle_laser_change, names='value')\n########\n# end of making laser_array\n########\n\n\n########\n# making antenna_array\n########\nnumant = inputparams.input['n_antenna']\n\nanttab = widgets.Tab()\nanttab.children = inputparams.create_antennas(1)\nfor i in range(len(anttab.children)):\n anttab.set_title(i, 'antenna '+str(i+1))\n\ndef handle_antenna_change(change):\n anttab.children = inputparams.create_antennas(change.new)\n for i in range(len(anttab.children)):\n anttab.set_title(i, 'antenna '+str(i+1))\n\nnumant.observe(handle_antenna_change, names='value')\n########\n# end of making antenna_array\n########\n\n\ndef benform():\n # tab_titles = ['General', 'EM Fields', 'Particles', 'Laser Pulses', 'Electrical Current', 'Antennas']\n tab_titles = ['General', 'EM Fields', 'Particles', 'Antennas']\n tab_contents = []\n\n children = [\n # For General Simulation Parameters\n widgets.VBox(children=[\n inputparams.input['node_number'],\n inputparams.input['if_periodic'],\n inputparams.input['coordinates'],\n widgets.HBox(children=[\n inputparams.input['xmin'],\n inputparams.input['xmax'],\n ]),\n inputparams.input['nx_p'],\n widgets.HBox(children=[\n inputparams.input['tmin'],\n inputparams.input['tmax'],\n ]),\n inputparams.input['dt']\n\n ]),\n\n # For EM Field Parameters\n widgets.VBox(children=[\n inputparams.input['type_emf_bound_1_1'],\n inputparams.input['type_emf_bound_2_1']\n ]),\n\n # For Particle Parameters\n widgets.VBox(children=[\n numspecies,\n inputparams.input['interpolation'],\n speciestab\n ]),\n\n # # For Laser Pulses\n # widgets.VBox(children=[\n # numlaser,\n # lasertab\n # ]),\n #\n # # For Current\n # widgets.VBox(children=[\n # widgets.Dropdown(\n # options=['linear', 'quadratic', 'cubic', 'quartic'],\n # value='cubic',\n # description='interpolation order:',\n # disabled=False,\n # style={'description_width': 'initial'}\n # ),\n # ]),\n\n # For Antennas\n widgets.VBox(children=[\n numant,\n anttab\n ])\n\n ]\n\n for keys in inputparams.input:\n inputparams.input[keys].style.description_width = '60%'\n\n tab = widgets.Tab()\n tab.children = children\n for i in range(len(children)):\n tab.set_title(i, tab_titles[i])\n return tab\n\n\ndef benreadform(bentab,inputfilename):\n\n f = inputbeginfile(inputfilename)\n\n inputbeginsection(f,\"simulation\")\n inputendsection(f)\n\n inputbeginsection(f,\"node_conf\")\n f.write(\"node_number(1:1) = \" + str(bentab.children[0].children[0].value) + \",\\n\")\n f.write(\"if_periodic(1:1) = .\" + bentab.children[0].children[1].value + \".,\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"grid\")\n f.write(\"nx_p(1:1) = \" + str(bentab.children[0].children[4].value) + \",\\n\")\n f.write(\"coordinates = '\" + bentab.children[0].children[2].value + \"',\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"time_step\")\n f.write(\"dt = \" + str(bentab.children[0].children[6].value) + \"e0,\\n\")\n f.write(\"ndump = 1,\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"restart\")\n f.write(\"ndump_fac = 0,\\n\")\n f.write(\"if_restart=.false.,\\n\")\n f.write(\"if_remold=.true.,\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"space\")\n f.write(\"xmin(1:1) = \" + str(bentab.children[0].children[3].children[0].value) + \"e0,\\n\")\n f.write(\"xmax(1:1) = \" + str(bentab.children[0].children[3].children[1].value) + \"e0,\\n\")\n f.write(\"if_move(1:1) = .false.,\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"time\")\n f.write(\"tmin = \" + str(bentab.children[0].children[5].children[0].value) + \"e0,\\n\")\n f.write(\"tmax = \" + str(bentab.children[0].children[5].children[1].value) + \"e0,\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"el_mag_fld\")\n f.write(\"ext_fld = 'static',\\n\")\n f.write(\"type_ext_b(1:3) = 'uniform', 'uniform', 'uniform',\\n\")\n f.write(\"ext_b0(1:3) = 0.0, 0.0, 0.0,\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"emf_bound\")\n f.write(\"type(1:2,1) = '\" + bentab.children[1].children[0].value + \"','\" + bentab.children[1].children[1].value + \"',\\n\")\n f.write(\"vpml_bnd_size = 30,\\n\")\n f.write(\"vpml_diffuse(1:2,1) = .true., .true.,\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"diag_emf\")\n f.write(\"ndump_fac = 25,\\n\")\n f.write(\"reports = 'e1','e2','e3','b1','b2','b3',\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"particles\")\n f.write(\"num_species = \" + str(bentab.children[2].children[0].value) + \",\\n\")\n f.write(\"interpolation = '\" + str(bentab.children[2].children[1].value) + \"',\\n\")\n inputendsection(f)\n\n for i in range(bentab.children[2].children[0].value):\n inputbeginsection(f,\"species\")\n f.write(\"name = '\" + bentab.children[2].children[2].children[i].children[0].value + \"',\\n\")\n f.write(\"num_par_max = 250000,\\n\")\n f.write(\"rqm = \" + str(bentab.children[2].children[2].children[i].children[1].value) + \"d0,\\n\")\n f.write(\"q_real = -1.0d0,\\n\")\n f.write(\"num_par_x(1:1) = \" + str(bentab.children[2].children[2].children[i].children[2].value) + \",\\n\")\n inputendsection(f)\n inputbeginsection(f,\"udist\")\n f.write(\"uth(1:3) = \" + str(bentab.children[2].children[2].children[i].children[3].children[0].value) + \"d0,\" + str(bentab.children[2].children[2].children[i].children[3].children[1].value) + \"d0,\" + str(bentab.children[2].children[2].children[i].children[3].children[2].value) + \"d0,\\n\")\n f.write(\"ufl(1:3) = 0.0d0 , 0.0d0 , 0.0d0 ,\\n\")\n inputendsection(f)\n inputbeginsection(f,\"profile\")\n f.write(\"num_x = 6,\\n\")\n f.write(\"fx(1:6,1) = 1, 1, 1, 1, 1, 1,\\n\")\n f.write(\"x(1:6,1) = 0.000, 10.0, 800, 900, 1000, 1500,\\n\")\n inputendsection(f)\n inputbeginsection(f,\"spe_bound\")\n f.write(\"type(1:2,1) = 'thermal', 'thermal',\\n\")\n f.write(\"uth_bnd(1:3,1,1) = 0.2d0 , 0.2d0 , 0.2d0 ,\\n\")\n f.write(\"uth_bnd(1:3,2,1) = 0.2d0 , 0.2d0 , 0.2d0 ,\\n\")\n inputendsection(f)\n inputbeginsection(f,\"diag_species\")\n f.write(\"ndump_fac_ene = 0,\\n\")\n f.write(\"ndump_fac_pha = 25,\\n\")\n f.write(\"!ndump_fac_raw = 0,\\n\")\n f.write(\"ps_xmin(1:1) = \" + str(bentab.children[0].children[3].children[0].value) + \",\\n\")\n f.write(\"ps_xmax(1:1) = \" + str(bentab.children[0].children[3].children[1].value) + \",\\n\")\n f.write(\"ps_nx(1:1) = \" + str(bentab.children[0].children[4].value) + \",\\n\")\n f.write(\"ps_pmin(1:3) = -1.0, -1.0, -1.0,\\n\")\n f.write(\"ps_pmax(1:3) = 1.0, 1.0, 1.0,\\n\")\n f.write(\"ps_np(1:3) = 100, 100, 100,\\n\")\n f.write(\"if_ps_p_auto(1:3) = .true., .true., .false.,\\n\")\n f.write(\"phasespaces = 'x1', 'p1x1',\\n\")\n f.write(\"'x1_q1', 'x1_ene',\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"collisions\")\n inputendsection(f)\n\n inputbeginsection(f,\"smooth\")\n f.write(\"type = '5pass',\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"diag_current\")\n f.write(\"ndump_fac = 0,\\n\")\n f.write(\"reports = 'j1', 'j2', 'j3',\\n\")\n inputendsection(f)\n\n inputbeginsection(f,\"antenna_array\")\n f.write(\"n_antenna = \" + str(bentab.children[3].children[0].value) +\",\\n\")\n inputendsection(f)\n\n for i in range(bentab.children[3].children[0].value):\n inputbeginsection(f,\"antenna\")\n f.write(\"a0 = \" +\n str(bentab.children[3].children[1].children[i].children[0].value) + \"d0,\\n\")\n f.write(\"t_rise = \" +\n str(bentab.children[3].children[1].children[i].children[1].children[0].value) + \"d0,\\n\")\n f.write(\"t_flat = \" +\n str(bentab.children[3].children[1].children[i].children[1].children[1].value) + \"d0,\\n\")\n f.write(\"t_fall = \" +\n str(bentab.children[3].children[1].children[i].children[1].children[2].value) + \"d0,\\n\")\n f.write(\"omega0 = \" +\n str(bentab.children[3].children[1].children[i].children[2].value) + \"d0,\\n\")\n f.write(\"pol = \" +\n str(bentab.children[3].children[1].children[i].children[3].value) + \"d0,\\n\")\n inputendsection(f)\n\n inputendfile(f)\n\n\ndef inputbeginfile(inputfilename):\n f = open(inputfilename,\"w+\")\n return f\n\ndef inputendfile(f):\n f.close()\n\ndef inputbeginsection(f,sectionname):\n f.write(sectionname+\"\\n\")\n f.write(\"{\\n\")\n\ndef inputendsection(f):\n f.write(\"}\\n\\n\")\n","sub_path":"main/tajima-notebook/benform.py","file_name":"benform.py","file_ext":"py","file_size_in_byte":9801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"625883505","text":"#Python OCR Maths Core 1 Question Generator\n#By Brandon Harris\n\n#Mass function dump so other files are neat ^-^\n\n#IMPORT EVERTHING\nimport random, time, os, sys, codecs\n\n#SEED ME\nrandom.seed(time.time())\n\n#Get line, if random > skew then x^2 the P(x^2) increases\ndef getRandomLine(skew):\n\t#Get shared coefficients\n\ta = random.randint(1, 5)\n\tb = random.randint(-5, 5)\n\tc = random.randint(-2, 4)\n\td = random.randint(-5, 20)\n\tcoeffs = [a, b, c, -d]\n\t\n\t#Create line list\n\tline = []\n\t\n\t#Get powers\n\tif (random.random() > skew):\n\t\tr = random.choice([0, -1])\n\t\tpowers = [2, 1, r, 0]\n\telse:\n\t\tr = random.choice([1, -1, -2])\n\t\tpowers = [3, 2, r, 0]\n\t\t\n\tfor i in range(0, 4):\n\t\tif coeffs[i] == 0:\n\t\t\tcontinue\n\t\t\n\t\tsegment = [coeffs[i], powers[i]]\n\t\tline.append(segment)\n\t\t\n\treturn line\n\n#Get gradient function\ndef getGradientFunction(line):\n\t#Variables\n\tgrad_func = []\n\tvalues = []\n\tcoeffs = []\n\t\n\tnew_values = []\n\tnew_coeffs = []\n\t\n\t#New lists\n\tfor i in range(0, len(line)):\n\t\tvalues.append(line[i][0])\n\tfor i in range(0, len(line)):\n\t\tcoeffs.append(line[i][1])\n\t\n\t#Remove doubles\n\tfor coeff in range(0, len(coeffs)):\n\t\t#If at end break or error\n\t\tif (coeff == len(coeffs)-1):\n\t\t\tif (coeffs[coeff] not in new_coeffs):\n\t\t\t\tnew_values.append(values[coeff])\n\t\t\t\tnew_coeffs.append(coeffs[coeff])\n\t\t\tbreak\n\t\t\t\n\t\t#Remove doubles\n\t\tif (coeffs[coeff] == coeffs[coeff+1]):\n\t\t\tnew_values.append(values[coeff] + values[coeff+1])\n\t\t\tnew_coeffs.append(coeffs[coeff])\n\t\t\tcontinue\n\t\tif (coeffs[coeff] in new_coeffs):\n\t\t\tcontinue\n\t\t\n\t\t#Add new non doubles\n\t\tnew_values.append(values[coeff])\n\t\tnew_coeffs.append(coeffs[coeff])\n\t\t\n\t#Construct gradient function\n\tfor i in range(0, len(new_values)):\n\t\t#Skips 0s\n\t\tif (new_values[i]*new_coeffs[i] == 0):\n\t\t\tcontinue\n\t\tsegment = [new_values[i]*new_coeffs[i], int(new_coeffs[i])-1]\n\t\tgrad_func.append(segment)\n\t\n\treturn grad_func\n\t\n#Get point\ndef getRandomPoint(x_range, y_range):\n\t#Randomise coordinates\n\tx = random.randint(x_range[0],x_range[1])\n\ty = random.randint(y_range[0],y_range[1])\n\t\n\treturn (x, y)\n\n#Get maximum\ndef max(a, b):\n\tif a > b:\n\t\treturn a\n\treturn b\n\n#Get maximum\ndef min(a, b):\n\tif a > b:\n\t\treturn b\n\treturn a\n\t\n#Simplify sqrt(x)\ndef surdForm(x):\n\t#Attempt division by each square number until root x\n\tsurd = ''\n\thighest_square_factor = 0\n\t\n\t#If a square number return root\n\tif (x**0.5 % 1 == 0):\n\t\treturn str(int(x**0.5))\n\t\n\t#Find highest square factor\n\tfor number in range(2, int(x**0.5)):\n\t\tif (x % number**2 == 0):\n\t\t\thighest_square_factor = number\n\t\n\t#If no square factors -> :(\n\tif (highest_square_factor == 0):\n\t\tsurd = 'root(' + str(x) + ')'\n\telse:\n\t\tin_root = x/(highest_square_factor**2)\n\t\tsurd = str(highest_square_factor) + ' root(' + str(int(in_root)) + ')'\n\t\n\t#Return surd form\n\treturn surd\n\n#Get string representing given line\t\ndef lineAsString(line, base = 0):\n\tanswer_string = ''\n\t\n\tif (line[0][0] == 1):\n\t\tif (line[0][1] == 1):\n\t\t\tanswer_string += 'x'\n\t\telse:\n\t\t\tanswer_string += 'x^' + str(line[0][1])\n\telse:\n\t\tif (line[0][1] == 1):\n\t\t\tanswer_string += str(line[0][0]) + 'x'\n\t\telse:\n\t\t\tanswer_string += str(line[0][0]) + 'x^' + str(line[0][1])\n\t\n\tfor term in range(1, len(line)):\n\t\tif (term == len(line)-1):\n\t\t\tif (base == 1):\n\t\t\t\tanswer_string += ' = ' + str(line[term][0]*-1)\n\t\t\t\tcontinue\n\t\t\tif (line[term][1] == 0):\n\t\t\t\tif (line[term][0] > 0):\n\t\t\t\t\tanswer_string += '+' + str(line[term][0])\n\t\t\t\telse:\n\t\t\t\t\tanswer_string += str(line[term][0])\n\t\t\telif (line[term][1] == 1):\n\t\t\t\tif (line[term][0] > 0):\n\t\t\t\t\tanswer_string += '+' + str(line[term][0]) + 'x'\n\t\t\t\telse:\n\t\t\t\t\tanswer_string += str(line[term][0]) + 'x'\n\t\t\telse:\n\t\t\t\tif (line[term][0] > 0):\n\t\t\t\t\tanswer_string += '+' + str(line[term][0]) + 'x^' + str(line[term][1])\n\t\t\t\telse:\n\t\t\t\t\tanswer_string += str(line[term][0]) + 'x^' + str(line[term][1])\n\t\t\tcontinue\n\t\t\n\t\tif (line[term][1] == 1):\n\t\t\tif (line[term][0] == 1):\n\t\t\t\tanswer_string += '+x'\n\t\t\telif (line[term][0] > 0):\n\t\t\t\tanswer_string += '+' + str(line[term][0]) + 'x'\n\t\t\telse:\n\t\t\t\tanswer_string += str(line[term][0]) + 'x'\n\t\t\tcontinue\n\t\t\n\t\tif (line[term][1] == 0):\n\t\t\tif (line[term][0] > 0):\n\t\t\t\tanswer_string += '+' + str(line[term][0])\n\t\t\telse:\n\t\t\t\tanswer_string += str(line[term][0])\n\t\t\tcontinue\n\t\t\n\t\tif (line[term][0] > 0):\n\t\t\tanswer_string += '+' + str(line[term][0]) + 'x^' + str(line[term][1])\n\t\telse:\n\t\t\tanswer_string += str(line[term][0]) + 'x^' + str(line[term][1])\n\t\n\treturn answer_string\n\n","sub_path":"genericFunctions.py","file_name":"genericFunctions.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"589858190","text":"#O mesmo professor do desafio anterior quer sortear a ordem de apresentação de trabalhos\n#dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada\nimport random\nnome1 = input('Digite o nome do primeiro aluno: ')\nnome2 = input('Digite o nome do segundo aluno: ')\nnome3 = input('Digite o nome do terceiro aluno: ')\nnome4 = input('Digite o nome quarto aluno: ')\nlista = [nome1, nome2, nome3, nome4]\nescolha = random.choice(lista[nome1, nome2, nome3, nome4])\nprint('Os nomes escolhidos, foram nesta ordem {}'.format(escolha))\n","sub_path":"aula_08/aula_08_XII.py","file_name":"aula_08_XII.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"423702676","text":"def eDivisibile(num1, num2):\r\n ciao = False\r\n if(num1 % num2 == 0):\r\n ciao = True\r\n return ciao\r\n\r\n\r\ndef mcm(num1,num2):\r\n return num1*num2/MCD(num1,num2)\r\n\r\ndef MCD(num1,num2):\r\n \r\n vettore = []\r\n if(num2>num1):\r\n #inverte in modo tale che num1 sia maggiore di num2\r\n num1,num2 = num2,num1 \r\n while(1):\r\n n = num1 % num2 \r\n if(n==0):\r\n break\r\n vettore.append(n)\r\n num1 = n\r\n return vettore[-1]\r\n\r\n\r\nn1 = int(input(\"inserire un numero: \"))\r\nn2 = int(input(\"inserire un altro numero: \"))\r\nprint(f\"il minimo comune multiplo è {mcm(n1,n2)}\")\r\nprint(f\"il minimo comune multiplo è {MCD(n1,n2)}\")","sub_path":"crittografia/aritmetica/mcm_MCD.py","file_name":"mcm_MCD.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"130859186","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nHelper functions for 3D grid operations.\r\n\r\nCreated on Thu Jan 23 20:55:40 2020\r\n\r\n@author: Bing-Jyun Tsao (btsao2@illinois.edu)\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom matplotlib import cm\r\nprint(\"mhf3d called\")\r\n\r\n#adding to denominator to avoid 0/0 error\r\nsingular_null = 1.0e-30\r\n\r\n###############################################\r\n\r\n\r\n#### spherical coordinates transformation ####\r\n# x = r sin(Theta) cos(Phi)\r\n# y = r sin(Theta) sin(Phi)\r\n# z = r cos(Theta)\r\n\r\n# return r(x,y)\r\ndef XYZtoR(x,y,z):\r\n return np.sqrt(x**2+y**2+z**2)\r\n\r\n# return theta(x,y)\r\ndef XYZtoTheta(x,y,z):\r\n return np.arctan2(np.sqrt(x**2 + y**2),z)\r\n\r\n# return (x,y)\r\ndef XYZtoPhi(x,y,z):\r\n return np.arctan2(y,x)\r\n\r\n# return normalized mesh\r\ndef norm_mesh(x,y,z):\r\n ret_l = np.sqrt(x**2 + y**2 + z**2)\r\n ret_x = x / (ret_l + singular_null)\r\n ret_y = y / (ret_l + singular_null)\r\n ret_z = z / (ret_l + singular_null)\r\n return ret_x, ret_y, ret_z\r\n\r\n#### Level set functions ####\r\n# Delta function (phi > 0)\r\ndef D(phi_):\r\n return np.heaviside(phi_,1)\r\n\r\n# Delta function (phi > 0)\r\ndef not_D(phi_):\r\n return np.heaviside(-phi_,1)\r\n\r\n# return the interior of the level set (phi > 0)\r\ndef get_frame(phi_):\r\n isOut = D(-phi_)\r\n return 1 - isOut\r\n\r\n#### vector calculus helper functions ####\r\n \r\n# gradient function\r\ndef grad(f,dx,dy,dz):\r\n ret_y, ret_x, ret_z = np.gradient(f,dx,dy,dz)\r\n return ret_x, ret_y, ret_z\r\n\r\n# normalized gradient function\r\ndef grad_norm(f,dx,dy,dz):\r\n ret_y, ret_x, ret_z = np.gradient(f,dx,dy,dz)\r\n ret_x_n, ret_y_n, ret_z_n = norm_mesh(ret_x, ret_y, ret_z)\r\n return ret_x_n, ret_y_n, ret_z_n\r\n \r\n\r\n# absolute gradient\r\ndef abs_grad(f,dx,dy,dz):\r\n grad_y, grad_x, grad_z = np.gradient(f,dx,dy,dz)\r\n return np.sqrt(grad_x**2 + grad_y**2 + grad_z**2)\r\n\r\n# Laplacian\r\ndef laplace(f,dx,dy,dz):\r\n ret = np.zeros_like(f)\r\n ret[1:-1,1:-1,1:-1] = (f[1:-1,2: ,1:-1] + f[1:-1,0:-2,1:-1] +\\\r\n f[2: ,1:-1,1:-1] + f[0:-2,1:-1,1:-1] +\\\r\n f[1:-1,1:-1,2: ] + f[1:-1,1:-1,0:-2] - 6*f[1:-1,1:-1,1:-1])/dx**2\r\n return ret\r\n\r\n# Normalized normal gradient\r\ndef grad_n(u_, phi_, dx_, dy_, dz_):\r\n phi_x, phi_y, phi_z = grad_norm(phi_,dx_,dy_,dz_)\r\n u_nx, u_ny, u_nz = grad(u_, dx_, dy_,dz_)\r\n u_n = u_nx * phi_x + u_ny * phi_y + u_nz * phi_z\r\n return u_n\r\n\r\n# Normalized normal gradient\r\ndef grad_n_n(u_, phi_, dx_, dy_, dz_):\r\n phi_x, phi_y, phi_z = grad_norm(phi_,dx_,dy_,dz_)\r\n u_nx, u_ny, u_nz = grad(u_, dx_, dy_,dz_)\r\n u_n = -(u_nx * phi_x + u_ny * phi_y + u_nz * phi_z)\r\n return u_n\r\n\r\n# grad(a) dot grad(b)\r\ndef grad_dot_grad(a_mat, b_mat, dx,dy,dz):\r\n ax,ay,az = grad(a_mat,dx,dy,dz)\r\n bx,by,bz = grad(b_mat,dx,dy,dz)\r\n return ax*bx + ay*by + az*bz\r\n\r\ndef grad_dot(scalar, vec, dx,dy,dz):\r\n ax, ay, az = grad(scalar,dx,dy,dz)\r\n return vec[0] * ax + vec[1] * ay + vec[2] * az\r\n\r\n# divergence(fx,fy,fz)\r\ndef div(fx,fy,fz,dx,dy,dz):\r\n ret_x = np.zeros_like(fx)\r\n ret_y = np.zeros_like(fy)\r\n ret_z = np.zeros_like(fz)\r\n# ret_x[1:-1, : , : ] = (fx[:-2,: ,: ] - fx[2:, :, :])/(2*dx)\r\n# ret_y[ : ,1:-1, : ] = (fy[: ,:-2,: ] - fy[: ,2:, :])/(2*dy)\r\n# ret_z[ : , : ,1:-1] = (fz[: ,: ,:-2] - fz[: , :,2:])/(2*dz)\r\n# ret_x[0 , :, :] = (0 - fx[ 1, :, :])/dx\r\n# ret_x[-1, :, :] = (fx[-1, :, :] - 0)/dx\r\n# ret_y[: , 0, :] = (0 - fy[ :, 1, :])/dy\r\n# ret_y[: ,-1, :] = (fy[ :,-1, :] - 0)/dy\r\n# ret_z[: , :, 0] = (0 - fz[ :, :, 1])/dz\r\n# ret_z[: , :,-1] = (fz[ :, :,-1] - 0)/dz\r\n ret_y[1:-1, : , : ] = (fy[2:,: ,: ] - fy[:-2, :, :])/(2*dy)\r\n ret_x[ : ,1:-1, : ] = (fx[: ,2:,: ] - fx[: ,:-2, :])/(2*dx)\r\n ret_z[ : , : ,1:-1] = (fz[: ,: ,2:] - fz[: , :,:-2])/(2*dz)\r\n ret_y[0 , :, :] = (fy[ 1, :, :] - 0)/dy\r\n ret_y[-1, :, :] = (0 - fy[-1, :, :])/dy\r\n ret_x[: , 0, :] = (fx[ :, 1, :] - 0)/dx\r\n ret_x[: ,-1, :] = (0 - fx[ :,-1, :])/dx\r\n ret_z[: , :, 0] = (fz[ :, :, 1] - 0)/dz\r\n ret_z[: , :,-1] = (0 - fz[ :, :,-1])/dz\r\n \r\n \r\n return ret_x + ret_y + ret_z\r\n\r\n\r\n\r\n# gradient in the frame, boundary with ghost points\r\ndef grad_frame(u_, mesh_, phi_):\r\n xmesh, ymesh, zmesh = mesh_\r\n isOut = np.array(D(phi_) , dtype = int)\r\n isOutx1 = np.array(D(phi_[1 :, :, :]), dtype = int)\r\n isOutx2 = np.array(D(phi_[:-1, :, :]), dtype = int)\r\n isOuty1 = np.array(D(phi_[ :, 1:, :]), dtype = int)\r\n isOuty2 = np.array(D(phi_[ :,:-1, :]), dtype = int)\r\n isOutz1 = np.array(D(phi_[ :, :, 1:]), dtype = int)\r\n isOutz2 = np.array(D(phi_[ :, :,:-1]), dtype = int)\r\n \r\n # phi_x, phi_y\r\n dx = xmesh[0,1,0]-xmesh[0,0,0]\r\n dy = ymesh[1,0,0]-ymesh[0,0,0]\r\n dz = zmesh[0,0,1]-zmesh[0,0,0]\r\n phi_x, phi_y, phi_z = grad_norm(phi_,dx,dy,dz)\r\n \r\n# step is 1 if k+1 is out and k is in\r\n# step is -1 if k is out and k+1 is in\r\n# step is 0 if both out or in\r\n xstep = isOutx1 - isOutx2\r\n ystep = isOuty1 - isOuty2\r\n zstep = isOutz1 - isOutz2\r\n xstep_p = np.array(D( xstep),dtype = int)\r\n xstep_m = np.array(D(-xstep),dtype = int)\r\n ystep_p = np.array(D( ystep),dtype = int)\r\n ystep_m = np.array(D(-ystep),dtype = int)\r\n zstep_p = np.array(D( zstep),dtype = int)\r\n zstep_m = np.array(D(-zstep),dtype = int)\r\n \r\n # ghost points for the boundary\r\n u_ghost_x = np.copy(u_) * (1-isOut)\r\n u_ghost_y = np.copy(u_) * (1-isOut)\r\n u_ghost_z = np.copy(u_) * (1-isOut)\r\n \r\n u_ghost_x[:-2,:,:] += -u_[ 2:,:,:]*xstep_m[:-1,:,:] + 2*u_[ 1:-1,:,:]*xstep_m[:-1,:,:]\r\n u_ghost_x[ 2:,:,:] += -u_[:-2,:,:]*xstep_p[ 1:,:,:] + 2*u_[ 1:-1,:,:]*xstep_p[ 1:,:,:]\r\n u_ghost_y[:,:-2,:] += -u_[:, 2:,:]*ystep_m[:,:-1,:] + 2*u_[:, 1:-1,:]*ystep_m[:,:-1,:]\r\n u_ghost_y[:, 2:,:] += -u_[:,:-2,:]*ystep_p[:, 1:,:] + 2*u_[:, 1:-1,:]*ystep_p[:, 1:,:]\r\n u_ghost_z[:,:,:-2] += -u_[:,:, 2:]*zstep_m[:,:,:-1] + 2*u_[:,:, 1:-1]*zstep_m[:,:,:-1]\r\n u_ghost_z[:,:, 2:] += -u_[:,:,:-2]*zstep_p[:,:, 1:] + 2*u_[:,:, 1:-1]*zstep_p[:,:, 1:]\r\n \r\n u_nx,temp,temp = grad(u_ghost_y,dx,dy,dz)\r\n temp,u_ny,temp = grad(u_ghost_x,dx,dy,dz)\r\n temp,temp,u_nz = grad(u_ghost_z,dx,dy,dz)\r\n \r\n u_n = u_nx * phi_x + u_ny * phi_y + u_nz * phi_z\r\n \r\n return (u_nx* (1-isOut),u_ny* (1-isOut),u_nz* (1-isOut)) \r\n\r\n#### Error Analysis ####\r\n \r\n# return Ln normal\r\ndef L_n_norm(error, n=2):\r\n error_n = np.power(error, n)\r\n average_n = np.sum(error_n) / len(error_n.flatten())\r\n average = np.power(average_n, 1./n)\r\n return average\r\n\r\n# return Ln error in the frame \r\ndef L_n_norm_frame(error,frame, n=2):\r\n num = np.sum(frame)\r\n error_n = np.power(error, n) * frame\r\n average_n = np.sum(error_n) / num\r\n average = np.power(average_n, 1./n)\r\n return average\r\n\r\n#\r\ndef map_01_11(arr):\r\n return np.array(2*(arr - 0.5),dtype = int)\r\n\r\ndef map_11_01(arr):\r\n return arr/2.0 + 0.5\r\n\r\n# find absolute error, return maximum error, L2 error \r\ndef get_error(u_result_, frame_, sol_, print_option = True):\r\n dif = np.abs(u_result_ - sol_)\r\n L2Dif = L_n_norm_frame(dif,frame_,2)\r\n maxDif = np.max(dif*frame_)\r\n if(print_option):\r\n print(\"Max error : \", maxDif)\r\n print(\"L^2 error : \", L2Dif)\r\n print(\"\")\r\n return maxDif, L2Dif\r\n\r\n# find absolute relative error, return maximum relative error, L2 relative error \r\ndef get_error_N(u_result_, u_theory_, frame_, option = (True,True)):\r\n# plt.matshow(frame_[:,:,1])\r\n w1,w2,w3 = u_result_.shape\r\n u_result_0 = u_result_ - u_result_[int(w1/2),int(w2/2)]\r\n u_theory_0 = u_theory_ - u_theory_[int(w1/2),int(w2/2)]\r\n dif = np.abs(u_result_0 - u_theory_0)\r\n L2Dif = L_n_norm_frame(dif,frame_,2)\r\n maxDif = np.max(dif*frame_)\r\n if(option[0]):\r\n print(\"Max error : \", maxDif)\r\n print(\"L^2 error : \", L2Dif)\r\n print(\"\")\r\n# if(option[1]):\r\n# plt.matshow(dif*frame_)\r\n return maxDif, L2Dif\r\n\r\n# show the position of the maximum absolute in the grid\r\ndef show_max(u_):\r\n ret = np.zeros_like(u_)\r\n maxNum = np.max(np.abs(u_))\r\n ret = np.heaviside(np.abs(u_) - maxNum,1)\r\n plt.matshow(ret)\r\n return ret\r\n \r\n# plot the 3d error\r\ndef plot3d_all(u_result_, mesh_, sol_, fig_label_, toPlot_ = [True, True, True, True]):\r\n xmesh, ymesh = mesh_\r\n \r\n # 2D color plot of the max difference\r\n if(toPlot_[0]):\r\n test_mat = (sol_ - u_result_)/(sol_ + singular_null)\r\n plt.matshow(test_mat)\r\n plt.colorbar()\r\n \r\n #3D plot of the analytic solution\r\n if(toPlot_[1]):\r\n fig_an = plt.figure(\"poisson analytic solution %d\" % fig_label_)\r\n ax_an = fig_an.gca(projection='3d')\r\n surf_an = ax_an.plot_surface(xmesh, ymesh, sol_, cmap=cm.coolwarm)\r\n fig_an.colorbar(surf_an)\r\n \r\n #3D plot of the numerical result\r\n if(toPlot_[2]):\r\n fig = plt.figure(\"poisson result %d\" % fig_label_)\r\n ax = fig.gca(projection='3d')\r\n surf = ax.plot_surface(xmesh, ymesh, u_result_, cmap=cm.coolwarm)\r\n fig.colorbar(surf)\r\n \r\n #3D plot of the error\r\n if(toPlot_[3]):\r\n fig_dif = plt.figure(\"poisson difference %d\" % fig_label_)\r\n ax_dif = fig_dif.gca(projection='3d')\r\n surf_dif = ax_dif.plot_surface(xmesh, ymesh, u_result_ - sol_, cmap=cm.coolwarm)\r\n fig_dif.colorbar(surf_dif)\r\n \r\n plt.show()\r\n\r\n\r\ndef setup_grid_3d(N_grid_val = 100):\r\n # grid dimension\r\n grid_min = -1.\r\n grid_max = 1.\r\n \r\n global N_grid\r\n N_grid = N_grid_val\r\n # grid spacing\r\n global h\r\n h = (grid_max - grid_min) / (N_grid) \r\n \r\n # define arrays to hold the x and y coordinates\r\n xyz = np.linspace(grid_min,grid_max,N_grid + 1)\r\n global x, y, z\r\n x,y,z = xyz,xyz,xyz\r\n global xmesh, ymesh, zmesh\r\n xmesh, ymesh, zmesh = np.meshgrid(xyz,xyz,xyz)\r\n \r\n # solution\r\n global u_init\r\n u_init = np.zeros_like(xmesh)\r\n return u_init, (xmesh,ymesh), h\r\n\r\ndef log_frame(mat_, frame_):\r\n return np.log(mat_* frame_ + 1.0*(1-frame_))\r\n\r\ndef plot2d(mat_, title_=\"\", *arg):\r\n frame = np.ones_like(mat_)\r\n if(arg):\r\n frame = arg[0]\r\n plt.matshow(mat_*frame)\r\n plt.colorbar()\r\n plt.title(title_)\r\n\r\n \r\ndef plot2d_compare(mat1, mat2, *arg):\r\n \r\n fig, ax = plt.subplots(2,2,figsize=(8,8))\r\n frame = np.ones_like(mat1)\r\n this_cmap = cm.coolwarm\r\n if(arg):\r\n frame = arg[0]\r\n \r\n from matplotlib import ticker\r\n from matplotlib.ticker import FormatStrFormatter\r\n formatter = ticker.ScalarFormatter(useMathText=True)\r\n formatter.format = '%.2f'\r\n formatter.set_scientific(True) \r\n formatter.set_powerlimits((-1,1)) \r\n \r\n \r\n pt1 = ax[0,0].matshow(mat1*frame,cmap = this_cmap)\r\n ax[0,0].set_title(\"result\")\r\n fig.colorbar(pt1,ax = ax[0,0], format=formatter)\r\n \r\n pt2 = ax[0,1].matshow(mat2*frame,cmap = this_cmap)\r\n ax[0,1].set_title(\"theory\")\r\n fig.colorbar(pt2,ax = ax[0,1], format=formatter)\r\n \r\n pt3 = ax[1,0].matshow(np.abs(mat1 - mat2)*frame,cmap=this_cmap)\r\n ax[1,0].set_title(\"absolute error\")\r\n fig.colorbar(pt3,ax = ax[1,0], format=formatter)\r\n \r\n frame_small = get_frame_n(np.abs(frame*mat2) - 1e-15*np.max(np.abs(frame*mat2)))\r\n rel_err = np.abs(mat1 - mat2)/ (np.abs(mat2) + singular_null)\r\n frame_min = np.min(frame_small * rel_err)\r\n frame_max = np.max(frame_small * rel_err)\r\n pt4 = ax[1,1].matshow(rel_err * frame,cmap=this_cmap, vmin = frame_min, vmax = frame_max)\r\n ax[1,1].set_title(\"relative error\")\r\n fig.colorbar(pt4,ax = ax[1,1], format=formatter)\r\n \r\n if(len(arg) > 1):\r\n fig.suptitle(arg[1])\r\n \r\n for i in range(2):\r\n for j in range(2):\r\n ax[i,j].xaxis.set_ticks_position('bottom')\r\n ax[i,j].yaxis.set_ticks_position('left')\r\n if(len(arg) > 2):\r\n ax[i,j].set_xlabel(arg[2][0])\r\n ax[i,j].set_ylabel(arg[2][1])\r\n# plt.matshow(frame_small)\r\n \r\ndef plot2d_compare_zero(mat1, mat2, *arg):\r\n frame = np.ones_like(mat1)\r\n if(arg):\r\n frame = arg[0]\r\n \r\n mat1_zero = mat1 - frame * np.sum(mat1*frame) / np.sum(frame)\r\n mat2_zero = mat2 - frame * np.sum(mat2*frame) / np.sum(frame)\r\n plot2d_compare(mat1_zero, mat2_zero, frame)\r\n \r\n \r\nif(__name__ == \"__main__\"):\r\n plt.close(\"all\")\r\n print(\"Poisson solver mesh helper function 3d file\")\r\n# grid_size = 100\r\n# setup_grid_3d(grid_size)\r\n# x0,y0,z0 = 0.5,0.2,0.3\r\n# f = (xmesh-x0)**2 + (ymesh-y0)**2 + (zmesh - z0)**2\r\n# gx, gy, gz = grad(f,h,h,h)\r\n# z_slice = int(grid_size / 2)\r\n# plt.matshow(gx[:,:,z_slice])\r\n# plt.colorbar()\r\n# plt.matshow(gy[:,:,z_slice])\r\n# plt.colorbar()\r\n# plt.matshow(gz[:,:,z_slice])\r\n# plt.colorbar()\r\n# plt.matshow(xmesh[:,:,z_slice])\r\n# plt.colorbar()\r\n# print(xmesh[0,:,0])\r\n# print(ymesh[:,0,0])\r\n# print(zmesh[0,0,:])\r\n \r\n","sub_path":"mesh_helper_functions_3D.py","file_name":"mesh_helper_functions_3D.py","file_ext":"py","file_size_in_byte":13084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"204346258","text":"from pymatgen.io.vasp import Structure, Vasprun, Dos, Spin, OrbitalType\nfrom pymatgen.core import PeriodicSite\nimport numpy as np\nfrom typing import Tuple\nfrom pymatgen.electronic_structure.plotter import DosPlotter\n\n\ndef find_ind(structure: Structure, start, end):\n arr = []\n sites: Tuple[PeriodicSite] = structure.sites\n for j in sites:\n if end > j.c > start:\n arr.append(j)\n\n return arr\n\n\ndef sum_spin(dos: Dos):\n dos.densities[Spin.up] -= dos.densities.pop(Spin.down)\n\n\ndef integrate(dos):\n den = {}\n de = dos.energies[1] - dos.energies[0]\n for k, d in dos.densities.items():\n densities = []\n for i in range(len(d)):\n if dos.energies[i] - dos.efermi > 0:\n densities.append(0)\n else:\n densities.append(sum(d[0:i]) * de)\n den[k] = np.array(densities)\n dos.__setattr__('densities', den)\n return dos\n\n\ndef write_dos(name, dos: Dos):\n with open(name, 'w') as f:\n for i, j in zip(dos.energies - dos.efermi, dos.get_densities(Spin.up)):\n f.write(f'{i:.6}\\t{j:6.6}\\n')\n\n if vrun.is_spin:\n f.write('#Spin down\\n')\n for i, j in zip(reversed(dos.energies - dos.efermi), reversed(dos.get_densities(Spin.down))):\n f.write(f'{i:6}\\t{-j:6.6}\\n')\n\n\ndef sum_orbital(dos: Dos, dos2: Dos):\n dos.densities[Spin.up] += dos2.densities[Spin.up]\n if dos.densities.keys().__contains__(Spin.down):\n dos.densities[Spin.down] += dos2.densities[Spin.down]\n\n\nif __name__ == \"__main__\":\n vrun = Vasprun('vasprun.xml')\n cdos = vrun.complete_dos\n dp = DosPlotter()\n en = {'first': (0.4, 0.5),\n 'second': (0.5, 0.6),\n }\n for key, val in en.items():\n s: PeriodicSite = None\n dosN = Dos(cdos.efermi, cdos.energies, {k: np.zeros(d.shape) for k, d in cdos.densities.items()})\n dosMetal = Dos(cdos.efermi, cdos.energies, {k: np.zeros(d.shape) for k, d in cdos.densities.items()})\n for s in find_ind(cdos.structure, *val):\n if s.specie.__str__() == 'N':\n sum_orbital(dosN, cdos.get_site_spd_dos(s)[OrbitalType.p])\n elif s.specie.__str__() == 'Ni':\n sum_orbital(dosMetal, cdos.get_site_spd_dos(s)[OrbitalType.d])\n\n dosN.densities = dosN.get_smeared_densities(0.03)\n dosMetal.densities = dosMetal.get_smeared_densities(0.03)\n\n sum_spin(dosN)\n sum_spin(dosMetal)\n\n dosN = integrate(dosN)\n dosMetal = integrate(dosMetal)\n\n dp.add_dos_dict({key+\"dosN\": dosN, key + \"dosM\": dosMetal})\n dp.show()\n # write_dos(key + '_N_mag.dat', integrate(dosN))\n # write_dos(key + '_Cu_mag.dat', integrate(dosMetal))\n","sub_path":"vasprun_related/oep_dos.py","file_name":"oep_dos.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"489558363","text":"#LATAM Scraper\n# %%\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\n# %%\nURL = 'https://www.latam.com/es_co/apps/personas/booking?fecha1_dia=01&fecha1_anomes=2021-06&fecha2_dia=15&fecha2_anomes=2021-06&from_city2=LON&to_city2=BOG&auAvailability=1&ida_vuelta=ida_vuelta&vuelos_origen=Bogot%C3%A1&from_city1=BOG&vuelos_destino=Londres&to_city1=LON&flex=1&vuelos_fecha_salida_ddmmaaaa=01/06/2021&vuelos_fecha_regreso_ddmmaaaa=15/06/2021&cabina=Y&nadults=1&nchildren=0&ninfants=0&cod_promo=&stopover_outbound_days=0&stopover_inbound_days=0#/'\n# %%\ndef get_prices(vuelo):\n \"\"\"\n Funcion que retorna una lista de diccionarios con las distintas tarifas\n \"\"\"\n tarifas = vuelo.find_elements_by_xpath('//div[@class=\"fares-table-container\"]//tfoot//td[contains(@class,\"fare-\")]')\n precio_tarifa=[]\n for tarifa in tarifas:\n nombre= tarifa.find_element_by_xpath('.//label').get_attribute('for')\n sym = tarifa.find_element_by_xpath('.//span[@class=\"price\"]/span[@class=\"currency-symbol\"]').text\n valor = tarifa.find_element_by_xpath('.//span[@class=\"price\"]/span[@class=\"value\"]').text\n dict_tarifa={nombre:{'moneda':sym,'valor':valor}}\n precio_tarifa.append(dict_tarifa)\n return precio_tarifa\n# %%\ndef get_datos_escalas(vuelo):\n \"\"\"\n Funcion que retorna una lista de diccionarios con la informacion de las escalas de cada vuelo\n \"\"\"\n \n segmentos = vuelo.find_elements_by_xpath('//div[@class=\"sc-hZSUBg gfeULV\"]/div[@class=\"sc-cLQEGU hyoued\"]')\n info_escalas = []\n for segmento in segmentos:\n #Origen - Destino\n origen,destino = segmento.find_elements_by_xpath('.//div[@class=\"sc-iujRgT jEtESl\"]//abbr[@class=\"sc-hrWEMg hlCkST\"]')\n #Salida - llegada\n hora_salida, hora_llegada = segmento.find_elements_by_xpath('.//div[@class=\"sc-iujRgT jEtESl\"]//time')\n #Duracion\n duracion_vuelo=segmento.find_element_by_xpath('.//span[@class=\"sc-esjQYD dMquDU\"]/time').get_attribute('datetime')\n #Num vuelo\n num_vuelo=segmento.find_element_by_xpath('.//div[@class=\"airline-flight-details\"]/b').text\n #Modelo\n modelo = segmento.find_element_by_xpath('.//div[@class=\"airline-flight-details\"]/span[@class=\"sc-gzOgki uTyOl\"]').text\n if segmento != segmentos[-1]:\n #Duracion Escala\n escala = segmento.find_element_by_xpath('//div[@class=\"sc-hMFtBS cfwWiO\"]//span[@class=\"sc-esjQYD dMquDU\"]/time').get_attribute('datetime')\n else:\n escala =''\n escalas_dict={\n 'origen': origen.text,\n 'hora_salida': hora_salida.get_attribute('datetime'),\n 'destino': destino.text,\n 'hora_llegada' : hora_llegada.get_attribute('datetime'),\n 'duracion_vuelo' : duracion_vuelo,\n 'num_vuelo' : num_vuelo,\n 'modelo' : modelo,\n 'duracion_escala' : escala}\n info_escalas.append(escalas_dict)\n \n return info_escalas\n# %%\ndef get_times(vuelo):\n \"\"\"\n Funcion que retorna un diccionario con los horarios de salida y llegada de cada vuelo, incluyendo duración.\n Nota:la duración del vuelo no es hora de llegada - hora de salida, puede haber diferencia de horarios entre el origen y el destino\n \"\"\"\n hora_salida = vuelo.find_element_by_xpath('.//div[@class=\"departure\"]/time').get_attribute('datetime')\n hora_llegada = vuelo.find_element_by_xpath('.//div[@class=\"arrival\"]/time').get_attribute('datetime')\n duracion_vuelo = vuelo.find_element_by_xpath('.//span[@class=\"duration\"]/time').get_attribute('datetime').replace('PT','')\n dict_times = {\n 'hora_salida':hora_salida,\n 'hora_llegada':hora_llegada,\n 'duracion_vuelo':duracion_vuelo\n }\n return dict_times\n# %%\ndef get_flights_info(driver):\n vuelos = driver.find_elements_by_xpath('//li[@class=\"flight\"]')\n print(f'Se encontraron {len(vuelos)} vuelos')\n print('Iniciando Scraping...')\n info =[]\n for vuelo in vuelos:\n #Get general times for flight\n times = get_times(vuelo)\n #CLick sobre boton Escalas\n boton_escalas = vuelo.find_element_by_xpath('.//div[@class=\"flight-summary-stops-description\"]/button')\n boton_escalas.click()\n escalas = get_datos_escalas(vuelo)\n driver.find_element_by_xpath('//div[@class=\"modal-content sc-iwsKbI eHVGAN\"]//button[@class=\"close\"]').click()\n #click sobr el vuelo para ver precios\n vuelo.click()\n precios = get_prices(vuelo)\n vuelo.click()\n info.append({'precios':precios,'tiempos':times,'escalas':escalas})\n return info\n# %%\noptions = webdriver.ChromeOptions()\noptions.add_argument('--incognito')\ndriver = webdriver.Chrome(executable_path = 'D:\\_Me\\Selenium\\Chromedriver', options=options)\ndriver.get(URL)\n# delay\ndelay = 10\ntry:\n #Dinamic delay\n vuelo = WebDriverWait(driver,delay).until(EC.presence_of_all_elements_located((By.XPATH, '//li[@class=\"flight\"]')))\n print('La página terminó de Cargar')\n info_vuelos = get_flights_info(driver)\nexcept TimeoutException:\n print('La página tardó demasiado en cargar')\n info_vuelos=[]\ndriver.close()\n# %%\nprint(info_vuelos)\n# %%\nimport json\n\nwith open('data.json', 'w') as fp:\n json.dump(info_vuelos , fp, indent=4)","sub_path":"Clases/Webscraper/Selenium/LatamScraper.py","file_name":"LatamScraper.py","file_ext":"py","file_size_in_byte":5469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"549436062","text":"# coding: utf-8\n\nfrom django.test import TestCase\nfrom django.db import IntegrityError\nfrom datetime import datetime\nfrom eventex.subscriptions.models import Subscription\n\n\nclass SubscriptionTest(TestCase):\n def setUp(self):\n self.obj = Subscription(\n name=u'Márcio Ramos Corrêa', #'u' do unicode!\n cpf='12345678901',\n email='marcio.ramos.correa@gmail.com',\n phone='14-96274121'\n )\n\n def test_create(self):\n 'Subscription must have name, cpf, email, phone'\n self.obj.save()\n self.assertEqual(1, self.obj.id)\n\n def test_has_created_at(self):\n 'Subscription must have automatic created_at'\n self.obj.save()\n self.assertIsInstance(self.obj.created_at, datetime)\n\n def test_unicode(self):\n self.assertEqual(u'Márcio Ramos Corrêa', unicode(self.obj))\n\n def test_paid_default_value_is_False(self):\n 'By default paid must be False.'\n self.assertEqual(False, self.obj.paid)\n\n\nclass SubscriptionUniqueTest(TestCase):\n def setUp(self):\n 'Create a fist entry to force the colision'\n Subscription.objects.create(name='Márcio Ramos Corrêa', cpf='12345678901',\n email='marcio.ramos.correa@gmail.com', phone='14-96274121')\n\n def test_cpf_unique(self):\n 'CPF must be unique.'\n s = Subscription(name='Márcio Ramos Corrêa', cpf='12345678901',\n email='marcio557@yahoo.com.br', phone='14-96274121')\n self.assertRaises(IntegrityError, s.save)\n\n def test_email_can_repeat(self):\n 'Email is not unique anymore.'\n s = Subscription.objects.create(name='Márcio Ramos Corrêa', cpf='00000000011',\n email='marcio.ramos.correa@gmail.com', phone='14-96274121')\n self.assertEqual(2, s.pk)","sub_path":"eventex/subscriptions/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"273610865","text":"# python - problem 15\n\nimport math\nimport time\nt = time.time()\n\ndef fact(n):\n if n is 1:\n return 1\n return fact(n-1)*n\n\nsol = fact(40)/fact(20)/fact(20)\n\nprint(sol)\n\nt = time.time()-t\nprint( \"Spend time :\", t , \"sec\")\n","sub_path":"problem 015.py","file_name":"problem 015.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"375196619","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Python 2 and 3 compatible from start\nfrom __future__ import print_function\nimport shutil\nimport subprocess\nimport sys\nfrom os import path as osp\n\n\nBASE_DIR = osp.dirname(osp.abspath(__file__))\nVENV_DIR = osp.join(BASE_DIR, 'venv')\nPIP_VERSION = '9.0.1'\nSETUPTOOLS_VERSION = '32.3.1'\nREQUIREMENTS_FILE = 'requirements.txt'\nDEBUG = False\nCONFIG_MODULE = 'bootconf'\n\n\ndef info(message=None, **kwargs):\n _output(sys.stdout, message, **kwargs)\n\ndef error(message, **kwargs):\n _output(sys.stderr, message, **kwargs)\n\ndef fatal(message=None, **kwargs):\n if message:\n error(message, **kwargs)\n\n raise SystemExit(1)\n\ndef debug(message, **kwargs):\n if DEBUG:\n info(message, **kwargs)\n\ndef _output(out, message, end='\\n', flush=True):\n if message:\n out.write(str(message))\n\n if end:\n out.write(end)\n\n if flush:\n out.flush() # python 2 print() got no flush arg\n\ndef execute_and_exit(cmd):\n raise SystemExit(execute(cmd, raise_error=False))\n\ndef venv_execute(cmd, **kwargs):\n cmd[0] = osp.join(VENV_DIR, 'bin', cmd[0])\n return execute(cmd, **kwargs)\n\ndef execute(cmd, raise_error=True):\n debug('+ {}'.format(subprocess.list2cmdline(cmd)))\n try:\n subprocess.check_call(cmd)\n except subprocess.CalledProcessError as e:\n if raise_error:\n raise\n\n return e.returncode\n\n return 0\n\n\nif __name__ == '__main__':\n if sys.version_info[0] != 3:\n execute_and_exit(['/usr/bin/env', 'python3', __file__] + sys.argv[1:])\n\n # Python 3 from here onwards\n\n\n def satisfy_requirements():\n\n def read(filename):\n try:\n with open(filename) as f:\n return f.read()\n except FileNotFoundError:\n return None\n\n name = REQUIREMENTS_FILE\n actual_file = osp.join(BASE_DIR, name)\n actual = read(actual_file)\n\n if actual is None:\n return True\n\n cached_file = osp.join(VENV_DIR, name)\n cached = read(cached_file)\n\n if actual != cached:\n venv_execute(['pip', 'install', '-r', actual_file])\n\n with open(cached_file, 'w') as f:\n f.write(actual)\n\n import venv\n\n venv_python = osp.join(VENV_DIR, 'bin/python')\n venv_exists = osp.exists(venv_python)\n\n if not venv_exists:\n debug('Creating virtual environment in {!r}'.format(VENV_DIR))\n try:\n venv.main([VENV_DIR]) # TODO: handle ensurepip error when python3-venv is not installed\n venv_execute(['pip', 'install', 'pip=={}'.format(PIP_VERSION)])\n venv_execute(['pip', 'install', 'setuptools=={}'.format(SETUPTOOLS_VERSION)])\n except:\n shutil.rmtree(VENV_DIR) # rollback\n raise\n\n satisfy_requirements()\n\n if sys.executable != venv_python: # osp.samefile() always true\n execute_and_exit([venv_python, __file__] + sys.argv[1:])\n\n\nimport functools\nimport importlib\nimport inspect\nimport json\nimport os\nimport pprint\nimport re\nimport runpy\nimport textwrap\nfrom argparse import ArgumentParser\nfrom contextlib import contextmanager\n\n\nclass Configuration(object):\n command_spec_pattern = re.compile(r'^(?P(\\w+)(\\.\\w+)*)(:(?P(\\w+)(\\.\\w+)*))?$')\n\n def __init__(self):\n # TODO: generate example\n self.module = importlib.import_module(CONFIG_MODULE)\n self.commands = getattr(self.module, 'COMMANDS', {})\n\n if not isinstance(self.commands, dict):\n self.invalid_config('commands must be a dict, got {!r} instead'.format(commands))\n\n for name, spec in self.commands.items():\n try:\n self.commands[name] = self.load_command(spec)\n except (ValueError, ImportError) as e:\n self.invalid_config('COMMANDS[{!r}]: {}'.format(name, e))\n\n # Default commands\n self.commands['venv'] = VenvCommand()\n\n # TODO: unit test\n def load_command(self, spec):\n m = self.command_spec_pattern.match(spec)\n\n if not m:\n self.invalid_command_spec(spec, 'Must match {}'.format(self.command_spec_pattern.pattern))\n\n mod_name = m.group('module')\n module = importlib.import_module(mod_name)\n attr = m.group('attr')\n\n if attr:\n try:\n obj = self.get_attr(module, attr)\n except AttributeError as e:\n self.invalid_command_spec(spec, e)\n\n if inspect.isfunction(obj):\n return FunctionCommand(obj)\n\n # Cannot use isinstance(obj, click.core.Command)\n if type(obj).__module__ == 'click.core':\n return ClickCommand(obj)\n\n error = 'Module attribute {!r} is neither function nor Click command'.format(attr)\n self.invalid_command_spec(spec, error)\n\n return ModuleCommand(mod_name)\n\n def get_attr(self, obj, attr):\n path = attr.split('.')\n progress = []\n\n for name in path:\n progress.append(name)\n try:\n obj = getattr(obj, name)\n except AttributeError as e:\n raise AttributeError('{}: {}'.format('.'.join(progress), e))\n\n return obj\n\n def invalid_config(self, message):\\\n fatal('Invalid {!r}: {}'.format(self.module.__file__, message))\n\n def invalid_command_spec(self, spec, message):\n self.invalid_config('Invalid command spec {!r}: {}'.format(spec, message))\n\n\nclass Command(object):\n default_desc = ''\n\n @property\n def desc(self):\n if hasattr(self, '_desc'):\n return self._desc\n\n return self.default_desc\n\n @desc.setter\n def desc(self, value):\n self._desc = value\n\n\nclass VenvCommand(Command):\n default_desc = 'Run a venv command, for example: venv pip freeze'\n\n def __call__(self):\n\n def usage():\n error('Usage: {} []'.format(program))\n error('Same as: {} '.format(osp.join(bin_dir, '')))\n fatal()\n\n program, args = sys.argv[0], sys.argv[1:]\n bin_dir = osp.join(VENV_DIR, 'bin')\n\n if not args:\n usage()\n\n executable = osp.join(bin_dir, args[0])\n\n if not osp.exists(executable):\n usage()\n\n execute_and_exit([executable] + args[1:])\n\n\nclass FunctionCommand(Command):\n\n def __init__(self, func):\n self.func = func\n\n def __call__(self):\n self.func()\n\n @property\n def default_desc(self):\n return 'Function {}'.format(self.func.__qualname__)\n\n\nclass ClickCommand(Command):\n\n def __init__(self, command):\n self.command = command\n\n def __call__(self):\n self.command()\n\n @property\n def default_desc(self):\n return self.command.help or ''\n\n\nclass ModuleCommand(Command):\n\n def __init__(self, mod_name, desc=None):\n self.mod_name = mod_name\n self._desc = desc\n\n def __call__(self):\n runpy.run_module(self.mod_name, run_name='__main__')\n\n @property\n def default_desc(self):\n return 'Module {}'.format(self.mod_name)\n\n\nCONFIG = Configuration()\n\n\ndef main(args=None):\n if args is None:\n program, args = sys.argv[0], sys.argv[1:]\n else:\n program = main.__qualname__\n\n commands = CONFIG.commands\n\n # TODO: standardize command help, e.g. upper case variable\n if not args or args[0] in ['-h', '--help']:\n error('Usage: {} [-h|--help] []'.format(program))\n error('\\nAvailable commands:')\n\n for cmd in sorted(commands.keys()):\n error(' {:10} {}'.format(cmd, commands[cmd].desc))\n\n error(\"\\nRun '{} [-h|--help]' to see command specific help.\".format(program))\n fatal()\n\n target = args[0]\n command = commands.get(target)\n\n if not command:\n fatal(\"Invalid command {!r}, run '{} -h' for more info\".format(target, program))\n\n orig_sys_argv = sys.argv\n try:\n sys.argv = ['{} {}'.format(program, args[0])] + args[1:]\n command()\n finally:\n sys.argv = orig_sys_argv\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"boot.py","file_name":"boot.py","file_ext":"py","file_size_in_byte":8163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"390752861","text":"from typing import List\n\nfrom common.Tree import TreeNode\n\n\ndef root_to_leaf_sum(root: TreeNode, sum, result: List[int]):\n if not root:\n return False\n\n if not root.left and not root.right: # leaf node\n if root.value == sum:\n result.append(root.value)\n return True\n else:\n return False\n\n if root_to_leaf_sum(root.left, sum - root.value, result):\n result.append(root.value)\n return True\n\n if root_to_leaf_sum(root.right, sum - root.value, result):\n result.append(root.value)\n return True\n\n return False\n","sub_path":"tusher_roy/tree/l_root_to_leaf_sum_binary_tree.py","file_name":"l_root_to_leaf_sum_binary_tree.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"380037816","text":"# -*- coding: utf-8 -*-\nimport time\nimport scrapy\nfrom selenium import webdriver\nfrom scrapy.signalmanager import dispatcher\nfrom scrapy import signals\nfrom selenium.webdriver.common.by import By\n# WebDriverWait 库,负责循环等待\nfrom selenium.webdriver.support.ui import WebDriverWait\n# expected_conditions 类,负责条件出发\nfrom selenium.webdriver.support import expected_conditions as EC\n\nfrom job_message.items import JobItemLoader, LaGouItem\nfrom job_message.settings import CHROME_PATH\nfrom job_message.utils.item_parser import time_now\n\nclass LagouSpider(scrapy.Spider):\n name = 'lagou'\n allowed_domains = ['lagou.com']\n start_urls = ['https://www.lagou.com/jobs/list_python%E5%AE%89%E5%85%A8?px=new&yx=15k-25k&gx=%E5%85%A8%E8%81%8C&city=%E5%85%A8%E5%9B%BD#order']\n NEEDJS = 'brower'\n\n headers = {\n \"HOST\" : \"www.lagou.com\",\n \"Refere\" : \"https://www.lagou.com\",\n }\n\n def __init__(self):\n self.logger.info('Lagou webdrive start')\n super(LagouSpider, self).__init__()\n chrome_opt = webdriver.ChromeOptions()\n pref = {\"profile.managed_default_content_settings.images\":2}\n chrome_opt.add_experimental_option(\"prefs\", pref)\n self.browser = webdriver.Chrome(executable_path=CHROME_PATH, chrome_options=chrome_opt)\n dispatcher.connect(self.spider_close, signals.spider_closed)\n\n def spider_close(self, spider):\n self.logger.info('Lagou webdrive closed')\n self.browser.quit()\n\n def start_requests(self):\n self.logger.info(\"Lagou crawl start\")\n yield scrapy.Request(self.start_urls[0], callback=self.next_page)\n\n\n def next_page(self, response):\n page_list = response.xpath('//span[@class=\"span totalNum\"]/text()').extract()\n if page_list:\n page = int(page_list[0])\n else:\n return\n for i in range(page):\n self.page_parse(response)\n self.browser.find_element_by_xpath(\"//div[@id='s_position_list']//span[@action='next']\").click()\n try:\n WebDriverWait(self.browser, 10).until(EC.presence_of_element_located((By.XPATH, '//span[@class=\"format-time\"]')))\n except:\n self.logger.error('Lagou can not find next page')\n\n\n # self.headers['Content-Type'] = 'application/json;charset=UTF-8'\n # page_list = response.xpath('//span[@class=\"span totalNum\"]/text()[]').extract()\n # if page_list:\n # page = int(page_list[0])\n # else:\n # self.logger.error(\"Can't find total num\")\n # return\n # page_data = {\"first\": False, \"pn\": 1, \"kd\": \"python爬虫\"}\n # # debug start\n # page_data = 'first=true&pn=1&kd=python%E7%88%AC%E8%99%AB$sid=b317970d39ed45cea3d29a1f339d170a'\n # yield scrapy.Request(self.page_url, method=\"POST\", headers=self.headers, body=page_data, callback=self.page_parse)\n # #debug end\n\n # for i in range(1, page+1):\n # if i == 1:\n # page_data['first'] = True\n # else:\n # page_data['pn'] = i\n # yield scrapy.Request(self.page_url, method=\"POST\", headers=self.headers, body=page_data, callback=self.parse)\n\n def page_parse(self, response):\n ul = response.xpath('//*[@id=\"s_position_list\"]/ul/li[1]')[0]\n lis = ul.xpath('//li[@data-index]')\n for i,li in enumerate(lis):\n self.logger.debug('Lagou crawl li num:{}'.format(i))\n item_loader = JobItemLoader(item=LaGouItem(), response=li)\n item_loader.add_xpath('postion', 'div//h3/text()')\n postion_url = li.xpath('div//a[@class=\"position_link\"]/@href').extract()[0]\n item_loader.add_xpath('postion_url','div//a[@class=\"position_link\"]/@href')\n item_loader.add_xpath('company_location', 'div//em/text()')\n item_loader.add_xpath('money', 'div//span[@class=\"money\"]')\n item_loader.add_xpath('experience', 'div//div[@class=\"p_bot\"]/div/text()').re('经验([0-9-]{3})年')\n item_loader.add_xpath('education', 'div//div[@class=\"p_bot\"]/div/text()').re('/ (\\w+?)\\n')\n tag = '-'.join(li.xpath('div[@class=\"list_item_bot\"]/div[@class=\"li_b_l\"]/span/text()').extract())\n item_loader.add_xpath('tag', tag)\n item_loader.add_xpath('company', 'div//div[@class=\"company_name\"]/a/text()')\n business, scale, financing = li.xpath('div//div[@class=\"industry\"]/text()').extract()[0].split('/')\n item_loader.add_xpath('scale', scale)\n item_loader.add_xpath('business', business)\n item_loader.add_xpath('financing', financing)\n item_loader.add_xpath('advantage', 'div[@class=\"list_item_bot\"]/div[@class=\"li_b_r\"]/text()')\n item_loader.add_xpath('public_time', 'div//span[@class=\"format-time\"]/text()')\n item_loader.add_xpath('crawl_time', time_now())\n item_loader.add_xpath('update_num', 0)\n item_loader.add_xpath('company_url', 'div//div[@class=\"company_name\"]/a/@href')\n yield scrapy.Request(postion_url, headers=self.headers, meta={\"lagou_item\": item_loader}, callback=self.parse)\n\n def parse(self, response):\n print(response.text)\n pass\n","sub_path":"job_message/job_message/spiders/lagou.py","file_name":"lagou.py","file_ext":"py","file_size_in_byte":5266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"161671208","text":"def div_1_n(n):\n res = 1\n\n divisors = []\n\n for d in range(2, n):\n tmp = d\n\n if res % d == 0:\n continue\n\n for div in divisors:\n if tmp % div == 0:\n tmp = int(tmp / div)\n\n divisors.append(tmp)\n res *= tmp\n\n return res\n\n\nprint(div_1_n(20))\n","sub_path":"pe/_1-100/_1-9/task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"607212857","text":"import socket\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect(('localhost', 9090))\n\nprint(\"Please, input only 'a', 'b' and 'c' from your quadratic equation sepparating them by space: \")\nclient.send(input().encode('utf-8'))\n\ndata = client.recv(1024)\nprint(data.decode('utf-8'))\n\nclient.close()","sub_path":"students/K33422/Khusnutdinov_Sergei/Lab_01/task2_client.py","file_name":"task2_client.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"78418237","text":"class Solution:\n\n # @param board, a 9x9 2D array\n # @return a boolean\n def isValidSudoku(self, board):\n rows, cols = [set() for i in range(9)], [set() for i in range(9)]\n blocks = [set() for i in range(9)]\n for i, p in enumerate(board):\n for j, q in enumerate(p):\n if q != '.':\n block = i - (i % 3) + (j // 3)\n if q in rows[i] or q in cols[j] or q in blocks[block]:\n return False\n rows[i].add(q)\n cols[j].add(q)\n blocks[block].add(q)\n return True\n","sub_path":"leetcode/python/isValidSudoku.py","file_name":"isValidSudoku.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"603969726","text":"\"\"\"\nLoosely based on https://github.com/ikostrikov/pytorch-a2c-ppo-acktr/blob/master/a2c_ppo_acktr/storage.py\n\"\"\"\nimport torch\nfrom torch.utils.data.sampler import BatchSampler, SubsetRandomSampler\n\nclass RolloutStorage(object):\n def __init__(self, num_steps, num_processes, device='cpu', other_keys=[], recurrent_state_keys=[]):\n self.num_steps = num_steps\n self.num_processes = num_processes\n self.recurrent_state_keys = recurrent_state_keys\n self.keys = ['ob', 'ac', 'r', 'mask', 'vpred'] + list(other_keys) + list(recurrent_state_keys)\n self.data = None\n self.device = device\n self.step = 0\n\n def init_data(self, step_data):\n self.data = {}\n assert step_data['r'].shape == step_data['vpred'].shape\n assert step_data['r'].shape == step_data['mask'].shape\n for k in self.keys:\n if k in self.recurrent_state_keys:\n shape = [1] + list(step_data[k].shape)\n else:\n shape = [self.num_steps] + list(step_data[k].shape)\n self.data[k] = torch.zeros(size=shape, dtype=step_data[k].dtype, device=self.device)\n shape = [self.num_steps] + list(step_data['vpred'].shape)\n self.data['vtarg'] = torch.zeros(size=shape, dtype=step_data['vpred'].dtype, device=self.device)\n self.data['atarg'] = torch.zeros_like(self.data['vtarg'])\n\n def insert(self, step_data):\n \"\"\"\n Insert new data into storage, transferring to the correct device if needed.\n \"\"\"\n if self.data is None:\n self.init_data(step_data)\n for k in self.keys:\n assert step_data[k].shape[0] == self.num_processes, \\\n f\"inserted data is expected to have its first dimension equal to the numper of processes: {self.num_processes}\"\n if k in self.recurrent_state_keys and self.step > 0:\n continue\n if step_data[k].device != self.device:\n self.data[k][self.step].copy_(step_data[k].to(self.device))\n else:\n self.data[k][self.step].copy_(step_data[k])\n\n self.step = (self.step + 1) % self.num_steps\n\n def compute_targets(self, next_value, next_mask, gamma, use_gae=True, lambda_=1.0, norm_advantages=False):\n if use_gae:\n gae = self.data['r'][-1] + gamma * next_mask * next_value - self.data['vpred'][-1]\n self.data['vtarg'][-1] = gae + self.data['vpred'][-1]\n for step in reversed(range(self.num_steps - 1)):\n delta = self.data['r'][step] + gamma * self.data['mask'][step + 1] * self.data['vpred'][step + 1] - self.data['vpred'][step]\n gae = delta + gamma * lambda_ * self.data['mask'][step + 1] * gae\n self.data['vtarg'][step] = gae + self.data['vpred'][step]\n else:\n self.data['vtarg'][-1] = self.data['r'][-1] + gamma * next_mask * next_value\n for step in reversed(range(self.num_steps - 1)):\n self.data['vtarg'][step] = self.data['r'][step] + \\\n gamma * self.data['mask'][step + 1] * self.data['vtarg'][step + 1]\n self.data['atarg'] = self.data['vtarg'] - self.data['vpred']\n if norm_advantages:\n self.data['atarg'] = (self.data['atarg'] - self.data['atarg'].mean()) / (self.data['atarg'].std() + 1e-5)\n\n\n def feed_forward_generator(self, batch_size):\n assert self.step == 0, f\"Insert exactly {self.num_steps} transitions before calling a generator. Only {self.step} insertions were made.\"\n assert len(self.recurrent_state_keys) == 0, \"Call self.recurrent_generator when using a recurrent model.\"\n N = self.num_processes * self.num_steps\n assert batch_size <= N\n sampler = BatchSampler(SubsetRandomSampler(range(N)), batch_size, drop_last=False)\n for indices in sampler:\n batch = {}\n for k,v in self.data.items():\n batch[k] = v.view(-1, *v.shape[2:])[indices]\n yield batch\n\n def recurrent_generator(self, batch_size):\n assert self.step == 0, f\"Insert exactly {self.num_steps} transitions before calling a generator. Only {self.step} insertions were made.\"\n N = self.num_processes\n assert batch_size <= N\n sampler = BatchSampler(SubsetRandomSampler(range(N)), batch_size, drop_last=False)\n for indices in sampler:\n batch = {}\n for k,v in self.data.items():\n batch[k] = v[:,indices].view(-1, *v.shape[2:])\n yield batch\n\n def compute_ob_stats(self):\n batch_mean = self.data['ob'].mean((0,1))\n batch_var = self.data['ob'].view(-1, *self.data['ob'].shape[2:]).var(0, unbiased=False) # can't reduce over multiple dims...\n batch_count = self.num_steps\n return batch_mean, batch_var, batch_count\n\nimport unittest\nimport numpy as np\n\nclass TestRollout(unittest.TestCase):\n def test_feed_forward(self):\n def _gen_data(np, x):\n data = {}\n data['ob'] = x*torch.ones(size=(np,1,84,84))\n data['ac'] = torch.zeros(size=(np,1))\n data['r'] = torch.zeros(size=(np,1))\n data['mask'] = torch.ones(size=(np,1))\n data['vpred'] = x*torch.ones(size=(np,1))\n data['logp'] = torch.zeros(size=(np,1))\n return data\n r = RolloutStorage(10, 2, other_keys=['logp'])\n for i in range(10):\n r.insert(_gen_data(2,i))\n if i < 9:\n try:\n r.feed_forward_generator(6)\n assert False\n except:\n pass\n r.compute_targets(torch.ones(size=(2,1)), torch.ones(size=(2,1)), gamma=0.99, use_gae=True, lambda_=1.0, norm_advantages=True)\n assert np.allclose(r.data['atarg'].mean(), 0., atol=1e-6) and np.allclose(r.data['atarg'].std(), 1., atol=1e-6)\n for batch in r.feed_forward_generator(6):\n assert batch['ob'].shape == (6,1,84,84) or batch['ob'].shape == (2,1,84,84)\n try:\n r.recurrent_generator(1)\n assert False\n except:\n pass\n\n bm, bv, bc = r.compute_ob_stats()\n assert bc == r.num_steps\n assert bm.shape == r.data['ob'].shape[2:]\n assert bv.shape == r.data['ob'].shape[2:]\n\n def test_recurrent(self):\n def _gen_data(np, x):\n data = {}\n data['ob'] = x*torch.ones(size=(np,1,84,84))\n data['ac'] = torch.zeros(size=(np,1))\n data['r'] = torch.zeros(size=(np,1))\n data['mask'] = torch.ones(size=(np,1))\n data['vpred'] = x*torch.ones(size=(np,1))\n data['logp'] = torch.zeros(size=(np,1))\n data['state'] = torch.zeros(size=(np,5))\n return data\n r = RolloutStorage(10, 4, other_keys=['logp'], recurrent_state_keys=['state'])\n for i in range(10):\n r.insert(_gen_data(4,i))\n if i < 9:\n try:\n r.recurrent_generator(2)\n assert False\n except:\n pass\n r.compute_targets(torch.ones(size=(4,1)), torch.ones(size=(4,1)), gamma=0.99, use_gae=True, lambda_=1.0)\n for batch in r.recurrent_generator(2):\n assert batch['ob'].shape == (20,1,84,84)\n assert batch['atarg'].shape == (20,1)\n assert batch['vtarg'].shape == (20,1)\n assert batch['mask'].shape == (20,1)\n assert batch['r'].shape == (20,1)\n assert batch['state'].shape == (2,5)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"dl/util/rollout.py","file_name":"rollout.py","file_ext":"py","file_size_in_byte":7614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"22310792","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 28 08:20:05 2017\n\n@author: mbh\n\"\"\"\n\n#from j123, problem 193\n#updated, more compact\n#requires a prime generator and a memoize decorator.\ndef do(N=1<<50):\n PP = [p * p for p in odd_primes(isqrt(N))] #int(N**0.5) works\n @memoize\n def f(n, stop):\n ans = n - (n >> 2)\n for pp in PP:\n if pp >= stop: break\n n_pp = n // pp\n ans -= f(n_pp, pp if pp <= n_pp else n_pp + 1)\n return ans\n return f(N - 1, N)\n\nprint(do())","sub_path":"PE_0193/j123.py","file_name":"j123.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"369409588","text":"#Policy Gradients with CartPole-v1\n#Alps \n#12/13\n\nimport gym\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tensorflow.keras import models, layers, optimizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout\n\n\n\nmax_episodes = 2048 #max trained episodes for the model\ndropout_rate = 0.05\naction_d = 2\nstate_d = 4\nscore_list = [] \nmodel = Sequential()\nmodel.add(Dense(64, input_dim=state_d, activation='relu'))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(dropout_rate))\nmodel.add(Dense(64))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(dropout_rate))\nmodel.add(Dense(action_d))\nmodel.add(Activation('softmax'))\nmodel.compile(loss = 'mse', optimizer=optimizers.Adam(0.001))\n\n\n\n\ndef cal_score(score):\n if(score > 400): return 1 + 1\n elif (score > 200): return 1 + 0.3 \n else: return 1\n\ndef act(s):\n prob = model.predict(np.array([s]))[0]\n return np.random.choice(len(prob), p=prob)\n\ndef discount_rewards(rewards, gamma=0.975):\n prior = 0\n out = np.zeros_like(rewards)\n for i in reversed(range(len(rewards))):\n prior = prior * gamma + rewards[i]\n out[i] = prior\n return out / np.std(out - np.mean(out))\n\ndef train(records):\n s_batch = np.array([record[0] for record in records])\n a_batch = np.array([[1 if record[1] == i else 0 for i in range(ACTION_DIM)]\n for record in records])\n prob_batch = model.predict(s_batch) * a_batch\n r_batch = discount_rewards([record[2] for record in records])\n model.fit(s_batch, prob_batch, sample_weight=r_batch, verbose=0)\n\n\nenv = gym.make('CartPole-v1')\nfor i in range(max_episodes):\n s = env.reset()\n score = 0\n replay_records = []\n while True:\n a = act(s)\n next_s, r, done, _ = env.step(a)\n r = cal_score(score)\n replay_records.append((s, a, r))\n score += r\n s = next_s\n if done:\n train(replay_records)\n score_list.append(score)\n break\n \n if np.mean(score_list[-20:]) >= 500:\n model.save('CartPole-v0-pg.h5')\n break\nenv.close()\n\n\n","sub_path":"2017201980/src/scrips_B/Policy _gradient_agaent.py","file_name":"Policy _gradient_agaent.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"396999189","text":"import EncoderFactory\nfrom DatasetManager import DatasetManager\nfrom calibration_wrappers import LGBMCalibrationWrapper\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.pipeline import FeatureUnion\nfrom sklearn.calibration import CalibratedClassifierCV\n#from sklearn.imblearn.over_sampling import RandomOverSampler\n\nfrom sklearn.metrics import brier_score_loss\n\nimport time\nimport os\nimport sys\nfrom sys import argv\nimport pickle\n\nimport lightgbm as lgb\n\n\ndef create_model(param, n_lgbm_iter=100, calibrate=False):\n \n param['metric'] = ['auc', 'binary_logloss']\n param['objective'] = 'binary'\n param['verbosity'] = -1\n \n if oversample:\n# train_data = lgb.Dataset(X_train_ros, label=y_train_ros)\n print(\"that should not happen\")\n else:\n train_data = lgb.Dataset(X_train, label=y_train)\n lgbm = lgb.train(param, train_data, n_lgbm_iter)\n \n if calibrate:\n wrapper = LGBMCalibrationWrapper(lgbm)\n cls = CalibratedClassifierCV(wrapper, cv=\"prefit\", method=calibration_method)\n cls.fit(X_val, y_val)\n return (cls, lgbm)\n else:\n return lgbm\n\n\ndataset_name = argv[1]\noptimal_params_filename = argv[2]\nresults_dir = argv[3]\n\ncalibrate = False\nsplit_type = \"temporal\"\noversample = False\ncalibration_method = \"beta\"\n\ntrain_ratio = 0.8\nval_ratio = 0.2\n\n# create results directory\nif not os.path.exists(os.path.join(results_dir)):\n os.makedirs(os.path.join(results_dir))\n \nprint('Preparing data...')\nstart = time.time()\n\n# read the data\ndataset_manager = DatasetManager(dataset_name)\ndata = dataset_manager.read_dataset()\n\nmin_prefix_length = 1\nmax_prefix_length = int(np.ceil(data.groupby(dataset_manager.case_id_col).size().quantile(0.9)))\n\n \ncls_encoder_args = {'case_id_col': dataset_manager.case_id_col, \n 'static_cat_cols': dataset_manager.static_cat_cols,\n 'static_num_cols': dataset_manager.static_num_cols, \n 'dynamic_cat_cols': dataset_manager.dynamic_cat_cols,\n 'dynamic_num_cols': dataset_manager.dynamic_num_cols, \n 'fillna': True}\n \n# split into training and test\nif split_type == \"temporal\":\n train, test = dataset_manager.split_data_strict(data, train_ratio, split=split_type)\nelse:\n train, test = dataset_manager.split_data(data, train_ratio, split=split_type)\n\ntrain, val = dataset_manager.split_val(train, val_ratio)\n \n# generate data where each prefix is a separate instance\ndt_train_prefixes = dataset_manager.generate_prefix_data(train, min_prefix_length, max_prefix_length)\ndt_val_prefixes = dataset_manager.generate_prefix_data(val, min_prefix_length, max_prefix_length)\ndt_test_prefixes = dataset_manager.generate_prefix_data(test, min_prefix_length, max_prefix_length)\n\n# encode all prefixes\nfeature_combiner = FeatureUnion([(method, EncoderFactory.get_encoder(method, **cls_encoder_args)) for method in [\"static\", \"agg\"]])\nX_train = feature_combiner.fit_transform(dt_train_prefixes)\nX_test = feature_combiner.fit_transform(dt_test_prefixes)\ny_train = dataset_manager.get_label_numeric(dt_train_prefixes)\ny_test = dataset_manager.get_label_numeric(dt_test_prefixes)\nX_val = feature_combiner.fit_transform(dt_val_prefixes)\ny_val = dataset_manager.get_label_numeric(dt_val_prefixes)\n\n#if oversample:\n# ros = RandomOverSampler(random_state=42)\n# X_train_ros, y_train_ros = ros.fit_sample(X_train, y_train)\n\n\n# train the model with pre-tuned parameters\nwith open(optimal_params_filename, \"rb\") as fin:\n best_params = pickle.load(fin)\n\n# get predictions for test set\nif calibrate:\n gbm, gbm_uncalibrated = create_model(best_params, calibrate=calibrate)\n\n preds_train = gbm.predict_proba(X_train)[:,1]\n preds_val = gbm.predict_proba(X_val)[:,1]\n preds = gbm.predict_proba(X_test)[:,1]\n \n preds_train_not_cal = gbm_uncalibrated.predict(X_train)\n preds_val_not_cal = gbm_uncalibrated.predict(X_val)\n preds_not_cal = gbm_uncalibrated.predict(X_test)\n \n print(\"Brier scores:\")\n print(\"train calibrated: %s, train not calibrated: %s\" % (brier_score_loss(y_train, preds_train), brier_score_loss(y_train, preds_train_not_cal)))\n print(\"val calibrated: %s, val not calibrated: %s\" % (brier_score_loss(y_val, preds_val), brier_score_loss(y_val, preds_val_not_cal)))\n print(\"test calibrated: %s, test not calibrated: %s\" % (brier_score_loss(y_test, preds), brier_score_loss(y_test, preds_not_cal)))\n\nelse:\n lgbm = create_model(best_params, calibrate=calibrate)\n preds_train = lgbm.predict(X_train)\n preds_val = lgbm.predict(X_val)\n preds = lgbm.predict(X_test)\n\n \n# write train-val set predictions\ndt_preds = pd.DataFrame({\"predicted_proba\": preds_train, \"actual\": y_train,\n \"prefix_nr\": dt_train_prefixes.groupby(dataset_manager.case_id_col).first()[\"prefix_nr\"],\n \"case_id\": dt_train_prefixes.groupby(dataset_manager.case_id_col).first()[\"orig_case_id\"]})\ndt_preds_val = pd.DataFrame({\"predicted_proba\": preds_val, \"actual\": y_val,\n \"prefix_nr\": dt_val_prefixes.groupby(dataset_manager.case_id_col).first()[\"prefix_nr\"],\n \"case_id\": dt_val_prefixes.groupby(dataset_manager.case_id_col).first()[\"orig_case_id\"]})\n#dt_preds = pd.concat([dt_preds, dt_preds_val], axis=0)\ndt_preds.to_csv(os.path.join(results_dir, \"preds_train_%s.csv\" % dataset_name), sep=\";\", index=False)\ndt_preds_val.to_csv(os.path.join(results_dir, \"preds_val_%s.csv\" % dataset_name), sep=\";\", index=False)\n\n\n# write test set predictions\ndt_preds = pd.DataFrame({\"predicted_proba\": preds, \"actual\": y_test,\n \"prefix_nr\": dt_test_prefixes.groupby(dataset_manager.case_id_col).first()[\"prefix_nr\"],\n \"case_id\": dt_test_prefixes.groupby(dataset_manager.case_id_col).first()[\"orig_case_id\"]})\n\ndt_preds.to_csv(os.path.join(results_dir, \"preds_%s.csv\" % dataset_name), sep=\";\", index=False)\n\n\n# write AUC for every prefix length\nwith open(os.path.join(results_dir, \"results_%s.csv\" % dataset_name), 'w') as fout:\n fout.write(\"dataset;nr_events;auc\\n\")\n\n for i in range(min_prefix_length, max_prefix_length+1):\n tmp = dt_preds[dt_preds.prefix_nr==i]\n if len(tmp.actual.unique()) > 1:\n auc = roc_auc_score(tmp.actual, tmp.predicted_proba)\n fout.write(\"%s;%s;%s\\n\" % (dataset_name, i, auc))\n \n\n# write errors for every prefix length\nwith open(os.path.join(results_dir, \"errors_%s.csv\" % dataset_name), 'w') as fout:\n fout.write(\"dataset;prefix_nr;mean_error;std_error\\n\")\n\n for i in range(min_prefix_length, max_prefix_length+1):\n tmp = dt_preds_val[dt_preds_val.prefix_nr==i]\n mean = np.mean(tmp.actual - tmp.predicted_proba)\n std = np.std(tmp.actual - tmp.predicted_proba)\n fout.write(\"%s;%s;%s;%s\\n\" % (dataset_name, i, mean, std))\n \n \n# write deltas for every prefix length\nwith open(os.path.join(results_dir, \"deltas_%s.csv\" % dataset_name), 'w') as fout:\n mean_cols = [\"mean_delta_%s\" % i for i in range(min_prefix_length, max_prefix_length)]\n std_cols = [\"std_delta_%s\" % i for i in range(min_prefix_length, max_prefix_length)]\n fout.write(\"dataset;prefix_nr;%s;%s\\n\" % (\";\".join(mean_cols), \";\".join(std_cols)))\n\n for k in range(min_prefix_length, max_prefix_length):\n tmp_k = dt_preds_val[dt_preds_val.prefix_nr==k]\n means = []\n stds = []\n for i in range(k+1, max_prefix_length+1):\n tmp_i = dt_preds_val[dt_preds_val.prefix_nr==i]\n tmp_merged = tmp_k.merge(tmp_i, on=\"case_id\", suffixes=[\"_k\", \"_i\"])\n mean = np.mean(tmp_merged.predicted_proba_i - tmp_merged.predicted_proba_k)\n std = np.std(tmp_merged.predicted_proba_i - tmp_merged.predicted_proba_k)\n means.append(mean)\n stds.append(std)\n for i in range(k-1):\n means.append(mean)\n stds.append(std)\n fout.write(\"%s;%s;%s;%s\\n\" % (dataset_name, k, \";\".join([str(val) for val in means]), \";\".join([str(val) for val in stds])))","sub_path":"write_lgbm_predictions.py","file_name":"write_lgbm_predictions.py","file_ext":"py","file_size_in_byte":8153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"501920689","text":"# [253. 会议室 II](https://leetcode-cn.com/problems/meeting-rooms-ii/)\n\n\"\"\"\n给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],...] (si < ei),为避免会议冲突,同时要考虑充分利用会议室资源,请你计算至少需要多少间会议室,才能满足这些会议安排。\n\n示例 1:\n\n输入: [[0, 30],[5, 10],[15, 20]]\n输出: 2\n示例 2:\n\n输入: [[7,10],[2,4]]\n输出: 1\n\n\"\"\"\nfrom typing import List\nclass Solution:\n def minMeetingRooms(self, intervals: List[List[int]]) -> int:\n n = len(intervals)\n if n < 2:\n return n\n intervals.sort()\n res = 1\n for row in range(1, n):\n left = intervals[row - 1][0]\n right = intervals[row - 1][1]\n if intervals[row][0] < right:\n res += 1\n return res\n\nif __name__ == \"__main__\":\n sol = Solution()\n param = [[0, 30],[5, 10],[15, 20]]\n val = sol.minMeetingRooms(param) # 2\n assert val == 2\n param = [[7,10],[2,4]]\n val = sol.minMeetingRooms(param) # 1\n assert val == 1\n","sub_path":"leetcode刷题笔记/253.会议室II.py","file_name":"253.会议室II.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"50884012","text":"import os\nimport sys\nimport time\nimport shutil\nimport random\nimport subprocess\nfrom itertools import starmap\nfrom tempfile import mkdtemp, NamedTemporaryFile\n\nfrom .. import current, FlowSpec\nfrom ..metaflow_config import DATATOOLS_S3ROOT\nfrom ..util import is_stringish,\\\n to_bytes,\\\n to_unicode,\\\n to_fileobj,\\\n url_quote,\\\n url_unquote\nfrom ..exception import MetaflowException\nfrom ..debug import debug\nfrom . import s3op\n\ntry:\n # python2\n from urlparse import urlparse\nexcept:\n # python3\n from urllib.parse import urlparse\n\nfrom ..metaflow_config import get_authenticated_boto3_client\nfrom botocore.exceptions import ClientError\n\nNUM_S3OP_RETRIES = 8\n\nclass MetaflowS3InvalidObject(MetaflowException):\n headline = 'Not a string-like object'\n\nclass MetaflowS3URLException(MetaflowException):\n headline = 'Invalid address'\n\nclass MetaflowS3Exception(MetaflowException):\n headline = 'S3 access failed'\n\nclass MetaflowS3NotFound(MetaflowException):\n headline = 'S3 object not found'\n\nclass MetaflowS3AccessDenied(MetaflowException):\n headline = 'S3 access denied'\n\nclass S3Object(object):\n \"\"\"\n This object represents a path or an object in S3,\n with an optional local copy.\n\n Get or list calls return one or more of S3Objects.\n \"\"\"\n\n def __init__(self, prefix, url, path, size=None):\n\n # all fields of S3Object should return a unicode object\n def ensure_unicode(x):\n return None if x is None else to_unicode(x)\n prefix, url, path = map(ensure_unicode, (prefix, url, path))\n\n self._size = size\n self._url = url\n self._path = path\n self._key = None\n\n if path:\n self._size = os.stat(self._path).st_size\n\n if prefix is None or prefix == url:\n self._key = url\n self._prefix = None\n else:\n self._key = url[len(prefix.rstrip('/')) + 1:].rstrip('/')\n self._prefix = prefix\n\n @property\n def exists(self):\n \"\"\"\n Does this key correspond to an object in S3?\n \"\"\"\n return self._size is not None\n\n @property\n def downloaded(self):\n \"\"\"\n Has this object been downloaded?\n \"\"\"\n return bool(self._path)\n\n @property\n def url(self):\n \"\"\"\n S3 location of the object\n \"\"\"\n return self._url\n\n @property\n def prefix(self):\n \"\"\"\n Prefix requested that matches the object.\n \"\"\"\n return self._prefix\n\n @property\n def key(self):\n \"\"\"\n Key corresponds to the key given to the get call that produced\n this object. This may be a full S3 URL or a suffix based on what\n was requested.\n \"\"\"\n return self._key\n\n @property\n def path(self):\n \"\"\"\n Path to the local file corresponding to the object downloaded.\n This file gets deleted automatically when a S3 scope exits.\n\n Returns None if this S3Object has not been downloaded.\n \"\"\"\n return self._path\n\n @property\n def blob(self):\n \"\"\"\n Contents of the object as a byte string.\n\n Returns None if this S3Object has not been downloaded.\n \"\"\"\n if self._path:\n with open(self._path, 'rb') as f:\n return f.read()\n\n @property\n def text(self):\n \"\"\"\n Contents of the object as a Unicode string.\n\n Returns None if this S3Object has not been downloaded.\n \"\"\"\n if self._path:\n return self.blob.decode('utf-8', errors='replace')\n\n @property\n def size(self):\n \"\"\"\n Size of the object in bytes.\n\n Returns None if the key does not correspond to an object in S3.\n \"\"\"\n return self._size\n\n def __str__(self):\n if self._path:\n return '' % (self._url, self._size)\n elif self._size:\n return '' % (self._url, self._size)\n else:\n return '' % self._url\n\n def __repr__(self):\n return str(self)\n\nclass S3(object):\n\n def __init__(self,\n tmproot='.',\n bucket=None,\n prefix=None,\n run=None,\n s3root=None):\n \"\"\"\n Initialize a new context for S3 operations. This object is based used as\n a context manager for a with statement.\n\n There are two ways to initialize this object depending whether you want\n to bind paths to a Metaflow run or not.\n\n 1. With a run object:\n\n run: (required) Either a FlowSpec object (typically 'self') or a\n Run object corresponding to an existing Metaflow run. These\n are used to add a version suffix in the S3 path.\n bucket: (optional) S3 bucket.\n prefix: (optional) S3 prefix.\n\n 2. Without a run object:\n\n s3root: (optional) An S3 root URL for all operations. If this is\n not specified, all operations require a full S3 URL.\n\n These options are supported in both the modes:\n\n tmproot: (optional) Root path for temporary files (default: '.')\n \"\"\"\n\n if run:\n # 1. use a (current) run ID with optional customizations\n parsed = urlparse(DATATOOLS_S3ROOT)\n if not bucket:\n bucket = parsed.netloc\n if not prefix:\n prefix = parsed.path\n if isinstance(run, FlowSpec):\n if current.is_running_flow:\n prefix = os.path.join(prefix,\n current.flow_name,\n current.run_id)\n else:\n raise MetaflowS3URLException(\\\n \"Initializing S3 with a FlowSpec outside of a running \"\n \"flow is not supported.\")\n else:\n prefix = os.path.join(prefix, run.parent.id, run.id)\n\n self._s3root = u's3://%s' % os.path.join(bucket, prefix.strip('/'))\n elif s3root:\n # 2. use an explicit S3 prefix\n parsed = urlparse(to_unicode(s3root))\n if parsed.scheme != 's3':\n raise MetaflowS3URLException(\\\n \"s3root needs to be an S3 URL prefxied with s3://.\")\n self._s3root = s3root.rstrip('/')\n else:\n # 3. use the client only with full URLs\n self._s3root = None\n\n self._tmpdir = mkdtemp(dir=tmproot, prefix='metaflow.s3.')\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.close()\n\n def close(self):\n \"\"\"\n Delete all temporary files downloaded in this context.\n \"\"\"\n try:\n if not debug.s3client:\n shutil.rmtree(self._tmpdir)\n except:\n pass\n\n def _url(self, key):\n # NOTE: All URLs are handled as Unicode objects (unicde in py2,\n # string in py3) internally. We expect that all URLs passed to this\n # class as either Unicode or UTF-8 encoded byte strings. All URLs\n # returned are Unicode.\n if self._s3root is None:\n parsed = urlparse(to_unicode(key))\n if parsed.scheme == 's3' and parsed.path:\n return key\n else:\n if current.is_running_flow:\n raise MetaflowS3URLException(\\\n \"Specify S3(run=self) when you use S3 inside a running \"\n \"flow. Otherwise you have to use S3 with full \"\n \"s3:// urls.\")\n else:\n raise MetaflowS3URLException(\\\n \"Initialize S3 with an 's3root' or 'run' if you don't \"\n \"want to specify full s3:// urls.\")\n elif key:\n if key.startswith('s3://'):\n raise MetaflowS3URLException(\\\n \"Don't use absolute S3 URLs when the S3 client is \"\n \"initialized with a prefix. URL: %s\" % key)\n return os.path.join(self._s3root, key)\n else:\n return self._s3root\n\n def list_paths(self, keys=None):\n \"\"\"\n List the next level of paths in S3. If multiple keys are\n specified, listings are done in parallel. The returned\n S3Objects have .exists == False if the url refers to a\n prefix, not an existing S3 object.\n\n Args:\n keys: (required) a list of suffixes for paths to list.\n\n Returns:\n a list of S3Objects (not downloaded)\n\n Example:\n\n Consider the following paths in S3:\n\n A/B/C\n D/E\n\n In this case, list_paths(['A', 'D']), returns ['A/B', 'D/E']. The\n first S3Object has .exists == False, since it does not refer to an\n object in S3. It is just a prefix.\n \"\"\"\n def _list(keys):\n if keys is None:\n keys = [None]\n urls = (self._url(key).rstrip('/') + '/' for key in keys)\n res = self._read_many_files('list', urls)\n for s3prefix, s3url, size in res:\n if size:\n yield s3prefix, s3url, None, int(size)\n else:\n yield s3prefix, s3url, None, None\n\n return list(starmap(S3Object, _list(keys)))\n\n def list_recursive(self, keys=None):\n \"\"\"\n List objects in S3 recursively. If multiple keys are\n specified, listings are done in parallel. The returned\n S3Objects have always .exists == True, since they refer\n to existing objects in S3.\n\n Args:\n keys: (required) a list of suffixes for paths to list.\n\n Returns:\n a list of S3Objects (not downloaded)\n\n Example:\n\n Consider the following paths in S3:\n\n A/B/C\n D/E\n\n In this case, list_recursive(['A', 'D']), returns ['A/B/C', 'D/E'].\n \"\"\"\n def _list(keys):\n if keys is None:\n keys = [None]\n res = self._read_many_files('list',\n map(self._url, keys),\n recursive=True)\n for s3prefix, s3url, size in res:\n yield s3prefix, s3url, None, int(size)\n return list(starmap(S3Object, _list(keys)))\n\n def get(self, key=None, return_missing=False):\n \"\"\"\n Get a single object from S3.\n\n Args:\n key: (optional) a suffix identifying the object.\n return_missing: (optional, default False) if set to True, do\n not raise an exception for a missing key but\n return it as an S3Object with .exists == False.\n\n Returns:\n an S3Object corresponding to the object requested.\n \"\"\"\n url = self._url(key)\n src = urlparse(url)\n\n def _download(s3, tmp):\n s3.download_file(src.netloc, src.path.lstrip('/'), tmp)\n return url\n\n try:\n path = self._one_boto_op(_download, url)\n except MetaflowS3NotFound:\n if return_missing:\n path = None\n else:\n raise\n\n return S3Object(self._s3root, url, path)\n\n def get_many(self, keys, return_missing=False):\n \"\"\"\n Get many objects from S3 in parallel.\n\n Args:\n keys: (required) a list of suffixes identifying the objects.\n return_missing: (optional, default False) if set to True, do\n not raise an exception for a missing key but\n return it as an S3Object with .exists == False.\n\n Returns:\n a list of S3Objects corresponding to the objects requested.\n \"\"\"\n def _get():\n res = self._read_many_files('get',\n map(self._url, keys),\n allow_missing=return_missing,\n verify=True,\n verbose=False,\n listing=True)\n\n for s3prefix, s3url, fname in res:\n if fname:\n yield self._s3root, s3url, os.path.join(self._tmpdir, fname)\n else:\n # missing entries per return_missing=True\n yield self._s3root, s3prefix, None, None\n return list(starmap(S3Object, _get()))\n\n def get_recursive(self, keys):\n \"\"\"\n Get many objects from S3 recursively in parallel.\n\n Args:\n keys: (required) a list of suffixes for paths to download\n recursively.\n\n Returns:\n a list of S3Objects corresponding to the objects requested.\n \"\"\"\n def _get():\n res = self._read_many_files('get',\n map(self._url, keys),\n recursive=True,\n verify=True,\n verbose=False,\n listing=True)\n\n for s3prefix, s3url, fname in res:\n yield s3prefix, s3url, os.path.join(self._tmpdir, fname)\n return list(starmap(S3Object, _get()))\n\n def get_all(self):\n \"\"\"\n Get all objects from S3 recursively (in parallel). This request\n only works if S3 is initialized with a run or a s3root prefix.\n\n Returns:\n a list of S3Objects corresponding to the objects requested.\n \"\"\"\n if self._s3root is None:\n raise MetaflowS3URLException(\\\n \"Can't get_all() when S3 is initialized without a prefix\")\n else:\n return self.get_recursive([None])\n\n def put(self, key, obj, overwrite=True):\n \"\"\"\n Put an object to S3.\n\n Args:\n key: (required) suffix for the object.\n obj: (required) a bytes, string, or a unicode object to \n be stored in S3.\n overwrite: (optional) overwrites the key with obj, if it exists\n\n Returns:\n an S3 URL corresponding to the object stored.\n \"\"\"\n\n if not is_stringish(obj):\n raise MetaflowS3InvalidObject(\\\n \"Object corresponding to the key '%s' is not a string \"\n \"or a bytes object.\" % key)\n\n url = self._url(key)\n src = urlparse(url)\n\n def _upload(s3, tmp):\n # we need to recreate the StringIO object for retries since\n # apparently upload_fileobj will/may close() it\n blob = to_fileobj(obj)\n s3.upload_fileobj(blob, src.netloc, src.path.lstrip('/'))\n\n if overwrite:\n self._one_boto_op(_upload, url)\n return url\n else:\n def _head(s3, tmp):\n s3.head_object(Bucket=src.netloc, Key=src.path.lstrip('/'))\n\n try:\n self._one_boto_op(_head, url)\n except MetaflowS3NotFound as err:\n self._one_boto_op(_upload, url) \n return url\n\n def put_many(self, key_objs, overwrite=True):\n \"\"\"\n Put objects to S3 in parallel.\n\n Args:\n key_objs: (required) an iterator of (key, value) tuples. Value must\n be a string, bytes, or a unicode object.\n overwrite: (optional) overwrites the key with obj, if it exists\n\n Returns:\n a list of (key, S3 URL) tuples corresponding to the files sent.\n \"\"\"\n def _store():\n for key, obj in key_objs:\n if is_stringish(obj):\n with NamedTemporaryFile(dir=self._tmpdir,\n delete=False,\n mode='wb',\n prefix='metaflow.s3.put_many.') as tmp:\n tmp.write(to_bytes(obj))\n tmp.close()\n yield tmp.name, self._url(key), key\n else:\n raise MetaflowS3InvalidObject(\n \"Object corresponding to the key '%s' is not a string \"\n \"or a bytes object.\" % key)\n\n return self._put_many_files(_store(), overwrite)\n\n\n def put_files(self, key_paths, overwrite=True):\n \"\"\"\n Put files to S3 in parallel.\n\n Args:\n key_paths: (required) an iterator of (key, path) tuples.\n overwrite: (optional) overwrites the key with obj, if it exists\n\n Returns:\n a list of (key, S3 URL) tuples corresponding to the files sent.\n \"\"\"\n def _check():\n for key, path in key_paths:\n if not os.path.exists(path):\n raise MetaflowS3NotFound(\"Local file not found: %s\" % path)\n yield path, self._url(key), key\n\n return self._put_many_files(_check(), overwrite)\n\n def _one_boto_op(self, op, url):\n error = ''\n for i in range(NUM_S3OP_RETRIES):\n tmp = NamedTemporaryFile(dir=self._tmpdir,\n prefix='metaflow.s3.one_file.',\n delete=False)\n try:\n s3 = get_authenticated_boto3_client('s3')\n op(s3, tmp.name)\n return tmp.name\n except ClientError as err:\n error_code = s3op.normalize_client_error(err)\n if error_code == 404:\n raise MetaflowS3NotFound(url)\n elif error_code == 403:\n raise MetaflowS3AccessDenied(url)\n error = str(err)\n except Exception as ex:\n # TODO specific error message for out of disk space\n error = str(ex)\n os.unlink(tmp.name)\n # add some jitter to make sure retries are not synchronized\n time.sleep(2**i + random.randint(0, 10))\n raise MetaflowS3Exception(\"S3 operation failed.\\n\"\\\n \"Key requested: %s\\n\"\\\n \"Error: %s\" % (url, error))\n\n # NOTE: re: _read_many_files and _put_many_files\n # All file IO is through binary files - we write bytes, we read\n # bytes. All inputs and outputs from these functions are Unicode.\n # Conversion between bytes and unicode is done through url_quote\n # and url_unquote.\n def _read_many_files(self, op, prefixes, **options):\n with NamedTemporaryFile(dir=self._tmpdir,\n mode='wb',\n delete=not debug.s3client,\n prefix='metaflow.s3.inputs.') as inputfile:\n inputfile.write(b'\\n'.join(map(url_quote, prefixes)))\n inputfile.flush()\n stdout, stderr = self._s3op_with_retries(op,\n inputs=inputfile.name,\n **options)\n if stderr:\n raise MetaflowS3Exception(\"Getting S3 files failed.\\n\"\\\n \"First prefix requested: %s\\n\"\\\n \"Error: %s\" % (prefixes[0], stderr))\n else:\n for line in stdout.splitlines():\n yield tuple(map(url_unquote, line.strip(b'\\n').split(b' ')))\n\n def _put_many_files(self, url_files, overwrite):\n url_files = list(url_files)\n with NamedTemporaryFile(dir=self._tmpdir,\n mode='wb',\n delete=not debug.s3client,\n prefix='metaflow.s3.put_inputs.') as inputfile:\n lines = (b' '.join(map(url_quote, (os.path.realpath(local), url)))\n for local, url, _ in url_files)\n inputfile.write(b'\\n'.join(lines))\n inputfile.flush()\n stdout, stderr = self._s3op_with_retries('put',\n filelist=inputfile.name,\n verbose=False,\n overwrite=overwrite,\n listing=True)\n if stderr:\n raise MetaflowS3Exception(\"Uploading S3 files failed.\\n\"\\\n \"First key: %s\\n\"\\\n \"Error: %s\" % (url_files[0][2],\n stderr))\n else:\n urls = set()\n for line in stdout.splitlines():\n url, _, _ = map(url_unquote, line.strip(b'\\n').split(b' '))\n urls.add(url)\n return [(key, url) for _, url, key in url_files if url in urls]\n\n def _s3op_with_retries(self, mode, **options):\n\n cmdline = [sys.executable, os.path.abspath(s3op.__file__), mode]\n for key, value in options.items():\n key = key.replace('_', '-')\n if isinstance(value, bool):\n if value:\n cmdline.append('--%s' % key)\n else:\n cmdline.append('--no-%s' % key)\n else:\n cmdline.extend(('--%s' % key, value))\n\n for i in range(NUM_S3OP_RETRIES):\n with NamedTemporaryFile(dir=self._tmpdir,\n mode='wb+',\n delete=not debug.s3client,\n prefix='metaflow.s3op.stderr') as stderr:\n try:\n debug.s3client_exec(cmdline)\n stdout = subprocess.check_output(cmdline,\n cwd=self._tmpdir,\n stderr=stderr.file)\n return stdout, None\n except subprocess.CalledProcessError as ex:\n stderr.seek(0)\n err_out = stderr.read().decode('utf-8', errors='replace')\n stderr.seek(0)\n if ex.returncode == s3op.ERROR_URL_NOT_FOUND:\n raise MetaflowS3NotFound(err_out)\n elif ex.returncode == s3op.ERROR_URL_ACCESS_DENIED:\n raise MetaflowS3AccessDenied(err_out)\n time.sleep(2**i + random.randint(0, 10))\n\n return None, err_out","sub_path":"metaflow/metaflow/datatools/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":22798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"397830713","text":"from django.db import models\n\n# Create your models here.\nclass Grades(models.Model):\n class Meta:\n db_table = \"grades\"\n ordering = [\"gname\"]\n # 类里面的 属性对应表里面的字段\n gname = models.AutoField(primary_key=True)\n gdate = models.DateTimeField()\n ggirlnum = models.IntegerField()\n gboynum = models.IntegerField()\n isDelete = models.BooleanField(default=False)\n # def __str__(self):\n # return self.gname\n\nclass StudentsManger(models.Manager):\n def get_queryset(self):\n # 调用父类的方法\n return super(StudentsManger, self).get_queryset().filter(isDelete=False)\n # return super().__init__().get_queryset().filter(isDelete=False)\n def creatStudent(self, name, age, gender, contend, lastT, createT, gradeT, isD=False):\n stu = self.model()\n # print(type(grade))\n stu.sname = name\n stu.sage = age\n stu.sgender = gender\n stu.scontend = contend\n stu.sgrade = gradeT\n stu.lastTime = lastT\n stu.createTime = createT\n return stu\n\n\nclass Students(models.Model):# 定义一个类方法创建对象(用@classmethod就表明是类方法)\n # cls就代表students类\n # 调用此方法就可以直接创建一个对象\n @classmethod\n def createStudent(cls, name, age, gender, contend, lastT, createT, gradeT, isD=False):\n stu = cls(sname=name, sage=age, sgender=gender,\n scontend=contend, lastTime=lastT, createTime=createT, isDelete=isD, sgrade=gradeT)\n return stu\n # 自定义模型管理器\n # 当自定义模型管理器,objects就不存在了\n stuObj = models.Manager()\n stuObj2 = StudentsManger()\n\n sname = models.CharField(max_length=20)\n sgender = models.BooleanField(default=True)\n sage = models.IntegerField(db_column=\"age\")\n scontend = models.CharField(max_length=20)\n isDelete = models.BooleanField(default=False)\n # 关联外键\n \"\"\"\n 在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,\n 此参数为了避免两个表里的数据不一致问题,不然会报错:\n TypeError: __init__() missing 1 required positional argument: 'on_delete'\n\n\n 即在外键值的后面加上 on_delete=models.CASCADE 一般为此值就好\"\"\"\n sgrade = models.ForeignKey(\"Grades\", on_delete=models.CASCADE)\n def __str__(self):\n \"\"\"\n 管理站点时,创建学生时,显示的不是object,而是班级的名称\n :return:\n \"\"\"\n return self.sname\n\n \"\"\"最后一次修改的时间\"\"\"\n lastTime = models.DateTimeField(auto_now=True)\n \"\"\"创建的时间\"\"\"\n createTime = models.DateTimeField(auto_now_add=True)\n class Meta:\n db_table = \"students\"\n ordering = [\"id\"]\n\n\n","sub_path":"WebProject/Django/Django模型/project/myApp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"626928064","text":"from keras.datasets import mnist\r\n\r\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\r\n\r\nx_train = x_train.reshape(-1, 28 * 28) / 255.0\r\nx_test = x_test.reshape(-1, 28 * 28) / 255.0\r\n\r\nfrom keras.models import load_model\r\n\r\nnew_model = load_model('./my_model/my_model.h5')\r\nnew_model.summary()\r\n\r\nloss, acc = new_model.evaluate(x_test, y_test, verbose=2)\r\nprint(\"복원된 모델의 정확도: {:5.2f}%\".format(100*acc))\r\n\r\nprint(new_model.predict(x_test).shape)","sub_path":"keras34_load_all.py","file_name":"keras34_load_all.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"213082908","text":"from . import halconfig_types as types\nfrom . import halconfig_dependency as dep\n\nname = \"CSEN\"\ncompatibility = dep.Dependency(dep.Platform.SERIES1) # all\nperipheral = 'CSEN'\nmodes = {\n 'define': 'hal_csen_mode',\n 'description': 'Mode',\n 'hide_properties': False,\n 'values': [\n types.EnumValue('single', 'Single Channel Mode'),\n types.EnumValue('scan', 'Scan Mode'),\n types.EnumValue('bonded', 'Bonded Mode'),\n ]\n}\noptions = {\n \"BSP_CSEN_SINGLE_INPUT\": {\n \"type\": types.AportSingleChannel(\n \"BSP_CSEN_SINGLE_INPUT\",\n signal='CEXT',\n define_name_prefix='BSP_CSEN_SINGLE',\n define_value_prefix='_CSEN_SINGLECTRL_SINGLESEL_',\n ),\n \"description\": \"Single input selection\",\n \"subcategory\":\"Single Channel Input\",\n \"mode\": \"single\",\n },\n \"BSP_CSEN_SCAN_MASK0\": {\n \"type\": types.AportScanMode(\n define_value_prefix=\"_CSEN_SCANINPUTSEL0_INPUT%nSEL_\",\n ),\n \"description\": \"Scan input mask (0-31)\",\n \"category\": \"Scan Mode\",\n \"allowedconflicts\": [\"BSP_CSEN_BONDED_INPUT\", \"BSP_CSEN_SCAN_INPUT\"],\n \"mode\": \"scan\",\n },\n \"BSP_CSEN_SCAN_MASK1\": {\n \"type\": types.AportScanMode(\n define_value_prefix=\"_CSEN_SCANINPUTSEL1_INPUT%nSEL_\",\n channel_start=32\n ),\n \"description\": \"Scan input mask (32-63)\",\n \"category\": \"Scan Mode\",\n \"allowedconflicts\": [\"BSP_CSEN_BONDED_INPUT\", \"BSP_CSEN_SCAN_INPUT\"],\n \"mode\": \"scan\",\n },\n \"BSP_CSEN_BONDED_MASK0\": {\n \"type\": types.AportBondedMode(\n channel_start=0,\n aport=\"1\"\n ),\n \"description\": \"Bonded input mask (0-31)\",\n \"category\": \"Bonded Mode\",\n \"subcategory\": \"Input 0-31 (APORT1)\",\n \"allowedconflicts\": [\"BSP_CSEN_BONDED_INPUT\", \"BSP_CSEN_SCAN_INPUT\"],\n \"mode\": \"bonded\",\n },\n \"BSP_CSEN_BONDED_MASK1\": {\n \"type\": types.AportBondedMode(\n channel_start=32,\n aport=\"3\"\n ),\n \"description\": \"Bonded input mask (32-63)\",\n \"category\": \"Bonded Mode\",\n \"subcategory\": \"Input 32-63 (APORT3)\",\n \"allowedconflicts\": [\"BSP_CSEN_BONDED_INPUT\", \"BSP_CSEN_SCAN_INPUT\"],\n \"mode\": \"bonded\",\n }\n}","sub_path":"platform/hwconf_data/efm32gg11b/modules/CSEN/CSEN_model.py","file_name":"CSEN_model.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"125285976","text":"AST=0\nCIRC=1\nTIMES=2\n\nfigNb=0\npatchNb=0\n\ndef whereIsFirst(e,L):\n if not e in L:\n return None\n for i in range(len(L)):\n if L[i]==e:\n return i\ndef whereIsLast(e,L):\n if not e in L:\n return None\n for i in reversed(range(len(L))):\n if L[i]==e:\n return i\ndef disjoint(L1,L2):\n for e in L1:\n if e in L2:\n return False\n return True\n\ndef areCompatible(L1,L2,v1,v2):\n #L1 and L2 are lists of lists\n #returns True iff L1 and L2 contain each a list that are disjoint from each other\n #and none of those contain v1 nor v2\n if L1==[]:\n return False\n if L2==[]:\n return False\n if [] in L1:\n return True\n if [] in L2:\n return True\n for l1 in L1:\n for l2 in L2:\n if v1 not in l1 and v2 not in l1:\n if v1 not in l2 and v2 not in l2:\n if disjoint(l1,l2):\n return True\n return False\n\nclass Face:\n def __init__(self,faceNb,faceSize,neigh=[],w=[],a=[],sn=[],sw=[],dist=None,label=None):\n self.nb=faceNb\n self.s =faceSize \n self.n =neigh #list of neighbors\n self.w =w #where the actual face is in the list of neighbors of its neighbors\n self.a =a #list of incident vertices\n self.sn=sn #list of subadjacent faces\n self.sw=sw #where is face in subadjacency list of subneighbor\n self.d=dist #distance from the outer outer face\n self.label=label #ast (black), circ (white resonant) or times (white Q)\n def show(self):\n print(self.nb,self.s,self.d,self.n,self.a,self.sn,self.sw)\n\nclass Vertex:\n def __init__(self,vertexNb,neigh=[],a=[],w=[],dist=None):\n self.nb=vertexNb\n self.n = neigh #list of neighbors\n self.a = a #list of incident faces\n self.w=w #where the vertex is in the list of neighbors of its neighbors\n self.d=dist #distance from the outer outer face\n def show(self):\n print(self.nb,self.d,self.n,self.a)\n\nclass qpath:\n def __init__(self,timesFaces,astFaces,forVer):\n self.timesFaces=timesFaces #TIMES faces of a Q-path\n self.astFaces=astFaces #AST faces o a Q-path\n self.forVer=forVer #vertices of the Q-edges of the Q-path\n \nclass Patch:\n def __init__(self,f4,f5,f6,f=[],v=[],nb=0,boundary=[],nbOuterFaces=0,t=None,meta=\"\",success=[False,False],initialAstFaces=[],Qpaths=[],nbp=False):\n self.f4=f4 #nb of 4-faces\n self.f5=f5 #nb of 5-faces\n self.f6=f6 #nb of 6-faces\n self.c=2*f4+f5 #curvature\n self.f=f #the list of faces\n self.v=v #the list of vertices\n self.nb=nb #patch number\n self.boundary=boundary #boundary description\n self.nbOuterFaces=nbOuterFaces #nb of incomplete faces\n self.type=t #ODD, ID_EVEN or CY_EVEN\n self.meta=meta #metapost declaration of vertices and faces\n self.success=success #found a solution for even and odd Q-paths\n self.initialAstFaces=initialAstFaces #initial AST faces\n self.Qpaths=Qpaths #Q-paths\n self.needBothParities=nbp #whether both parities are needed or just one\n\n def calculateType(self):\n if self.c!=6:\n self.nanoType=None\n else:\n vector=[]\n for face in self.f[-1].n:\n vector.append(self.f[face].s-3)\n length=self.f[-1].s\n reducedVector=[]\n for i in range(length):\n if vector[i]!=2:\n reducedVector.append(i)\n nanoType=[0,0]\n if reducedVector==[]:\n nanoType=[length,0]\n else:\n for i in range(len(reducedVector)):\n nanoType[i%2]+=(reducedVector[i]-reducedVector[i-1])%length\n if nanoType[0]1:\n realFace=boundary[0][0]\n self.f.append(Face(newOuter,len(boundary[0])+3,[]))\n for j in range(len(boundary[0])):\n realFace=boundary[0][j]\n whereIs=whereIsFirst(None,self.f[realFace].n)\n self.f[realFace].n[whereIs]=newOuter\n self.f[newOuter].n.insert(0,realFace)\n self.f[newOuter].n.append(newOuter-1)\n self.f[newOuter].n.append(self.outer)\n self.f[newOuter].n.insert(0,newOuter+1)\n del(boundary[0])\n newOuter=newOuter+1\n realFace=boundary[0][0]\n self.f.append(Face(newOuter,len(boundary[0])+3,[]))\n for j in range(len(boundary[0])):\n realFace=boundary[0][j]\n whereIs=whereIsFirst(None,self.f[realFace].n)\n self.f[realFace].n[whereIs]=newOuter\n self.f[newOuter].n.insert(0,realFace)\n self.f[newOuter].n.append(newOuter-1)\n self.f[newOuter].n.append(self.outer)\n self.f[newOuter].n.insert(0,firstOuter)\n del(boundary[0])\n self.f.append(Face(self.outer,nbOuterFaces,[]))\n for i in range(firstOuter,self.outer):\n self.f[self.outer].n.insert(0,i)\n \n def calculateVertices(self):\n for face in self.f:\n face.w = [whereIsFirst(face.nb,self.f[face.n[i]].n)\n for i in range(face.s)]\n cv=0 \n AllDone=False\n maxFaceNb=len(self.f)-1\n for face in self.f:\n face.a=[None for i in range(face.s)]\n for whichFace in range(len(self.f)):\n for where in range(self.f[whichFace].s):\n if self.f[whichFace].a[where]==None:\n self.v.append(Vertex(cv,[],[],[None,None,None]))\n vr=self.v[cv]\n secondFace=self.f[whichFace].n[where]\n thirdFace=self.f[whichFace].n[(where+1)%self.f[whichFace].s]\n vr.a=[whichFace,secondFace,thirdFace]\n self.f[whichFace].a[where]=cv\n self.f[secondFace].a[whereIsFirst(thirdFace,self.f[secondFace].n)]=cv\n self.f[thirdFace].a[whereIsFirst(whichFace,self.f[thirdFace].n)]=cv\n cv+=1\n for vr in self.f[-1].a:\n while self.v[vr].a[1]!=maxFaceNb:\n self.v[vr].a.append(self.v[vr].a.pop(0))\n for vr in self.v:\n for i in range(3):\n whichFace=vr.a[i]\n where=whereIsFirst(vr.nb,self.f[whichFace].a)\n vr.n.append(self.f[whichFace].a[(where+1)%self.f[whichFace].s])\n\n for vr in self.v:\n vr.w=[whereIsFirst(vr.nb,self.v[vr.n[i]].n) for i in range(3)]\n\n for face in self.f:\n face.sn=[self.f[face.n[i]].n[face.w[i]-2]\n for i in range(face.s)]\n for face in self.f:\n face.sw=[whereIsFirst(face.n[(i+1)%face.s],self.f[face.sn[i]].n) for i in range(face.s)]\n \n L=[maxFaceNb]\n self.f[maxFaceNb].d=0\n while L!=[]:\n currentFace=self.f[L.pop(0)]\n for i in currentFace.n:\n if self.f[i].d==None:\n L.append(i)\n self.f[i].d=currentFace.d+1\n L=[]\n for i in self.f[maxFaceNb].a:\n self.v[i].d=0\n L.append(i)\n while L!=[]:\n currentVertex=self.v[L.pop(0)]\n for i in currentVertex.n:\n if self.v[i].d==None:\n L.append(i)\n self.v[i].d=currentVertex.d+1\n\n def startingEdges(self):\n maxFaceNb=len(self.f)-1\n startingEdges=[]\n astFaces=[]\n astFace=self.f[maxFaceNb-1]\n di = 0\n while astFace!=None:\n left=astFace.n[di]\n right=astFace.n[di+1]\n stE=[(astFace,di)]\n astF=[astFace.nb]\n while len(stE)<=1 or (astFace,di)!=stE[0]:\n if astFace.d==0:\n while self.f[astFace.n[(di+1)%astFace.s]].s==6:\n di+=1\n di=di%astFace.s\n stE.append((astFace,di))\n (astFace,di)=(self.f[astFace.sn[di]],astFace.sw[di])\n astF.append(astFace.nb)\n if astFace.d==1:\n di+=1\n while self.f[astFace.n[(di+1)%astFace.s]].d>0 and self.f[astFace.n[(di+1)%astFace.s]].s>4:\n stE.append((astFace,di))\n di+=1\n di-=1\n (astFace,di)=(self.f[astFace.sn[di]],astFace.sw[di])\n astF.append(astFace.nb)\n elif astFace.d<=3:\n while self.f[astFace.sn[di-1]].d<2:\n di-=1\n stE.append((self.f[astFace.sn[di]],astFace.sw[di]))\n (astFace,di)=(self.f[astFace.sn[di]],astFace.sw[di])\n astF.append(astFace.nb)\n del(stE[-1])\n del(astF[-1])\n startingEdges.append(stE)\n astFaces.append(astF)\n\n astFace=None\n maybeAstFace=self.f[maxFaceNb-1]\n while astFace==None and maybeAstFace.d==1:\n for dire in range(maybeAstFace.s):\n if astFace==None:\n if self.f[maybeAstFace.sn[dire]].d>1:\n found=False\n for stE in startingEdges:\n if (maybeAstFace,dire) in stE:\n found=True\n if not found:\n astFace=maybeAstFace\n di=dire\n maybeAstFace=self.f[maybeAstFace.nb-1]\n return startingEdges,astFaces\n\n def calculateTimesEdges(self,Qpaths):\n timesEdges=[]\n for Qpath in Qpaths:\n qpath=Qpath.timesFaces\n for i in range(1,len(qpath)):\n first=self.f[qpath[i-1]]\n second=self.f[qpath[i]]\n v1=Qpath.forVer[2*i-2]\n v2=Qpath.forVer[2*i-1]\n di=whereIsFirst(second.nb,first.sn)\n di2=whereIsLast(second.nb,first.sn)\n timesEdges.append((first.nb,v1,v2,second.nb))\n\n return timesEdges\n\n def calculateCircEdges(self):\n foundEdge=[[None for i in face.n] for face in self.f]\n maxFaceNb=len(self.f)-1\n circEdges=[]\n for face in self.f:\n if face.nb1) or (\n self.f[circEdge[0]].label!=CIRC and self.f[circEdge[0]].d>1)):\n hasEvolved=True\n if self.f[circEdge[1]].label!=CIRC: \n erasedCirc=circEdge[0]\n elif self.f[circEdge[0]].label!=CIRC:\n erasedCirc=circEdge[1]\n if self.f[erasedCirc].label!=CIRC:\n return []\n else:\n self.f[erasedCirc].label=TIMES\n containErasedCirc=[]\n for otherCircEdge in circEdges:\n if erasedCirc in otherCircEdge and otherCircEdge!=circEdge:\n containErasedCirc.append(otherCircEdge)\n foundFirst=False\n if len(containErasedCirc)==2:\n newCircEdge=[]\n for otherCircEdge in containErasedCirc:\n if not foundFirst: \n if otherCircEdge[0]==erasedCirc:\n foundFirst=True\n newCircEdge.append(otherCircEdge[1])\n newCircEdge+=list(reversed(otherCircEdge[2:]))\n firstToRemove=otherCircEdge\n elif otherCircEdge[1]==erasedCirc:\n foundFirst=True\n newCircEdge.append(otherCircEdge[0])\n newCircEdge+=list(otherCircEdge[2:])\n firstToRemove=otherCircEdge\n else:\n if otherCircEdge[0]==erasedCirc:\n foundSecond=True\n newCircEdge.insert(1,otherCircEdge[1])\n newCircEdge+=list(otherCircEdge[2:])\n secondToRemove=otherCircEdge\n elif otherCircEdge[1]==erasedCirc:\n foundSecond=True\n newCircEdge.insert(1,otherCircEdge[0])\n newCircEdge+=list(reversed(otherCircEdge[2:]))\n secondToRemove=otherCircEdge\n circEdges.remove(circEdge)\n circEdges.remove(firstToRemove)\n circEdges.remove(secondToRemove)\n circEdges.append(tuple(newCircEdge))\n elif len(containErasedCirc)==1:\n circEdges.remove(circEdge)\n return circEdges\n\n def isTriangle(self,circEdges):\n adj={}\n for face in self.f:\n if face.label==CIRC:\n adj[face.nb]=[]\n for edge in circEdges:\n if self.f[edge[0]].label==CIRC and self.f[edge[1]].label==CIRC:\n if edge[0]==edge[1]:\n return -1\n else:\n adj[edge[0]].append(edge[1])\n adj[edge[1]].append(edge[0])\n for f in adj:\n for n1 in adj[f]:\n if adj[f].count(n1)>1:\n return 2\n for n2 in adj[f]:\n if n1!=n2:\n if n1 in adj[n2]:\n if n1 in self.f[f].n and n2 in self.f[f].n and n1 in self.f[n2].n:\n return -3\n for f in adj:\n for n1 in adj[f]:\n if adj[f].count(n1)>1:\n return 2\n for n2 in adj[f]:\n if n1!=n2:\n if n1 in adj[n2]:\n if n1 in self.f[f].n and n2 in self.f[f].n and n1 in self.f[n2].n:\n return -3\n else:\n return 3\n return 4\n \n def completeLabels(self,astFaces,timesFaces,Qpaths):\n maxFaceNb=len(self.f)-1\n NbOuterFaces=self.f[maxFaceNb].s\n for face in self.f:\n face.label=None\n circFaces=[]\n for nb in self.f[maxFaceNb].n:\n if True not in [nb in x for x in astFaces] and True not in [nb in x for x in timesFaces]:\n circFaces.append(nb)\n astFaces.append([])\n for nb in range(maxFaceNb-NbOuterFaces,-1,-1):\n if True not in [nb in x for x in astFaces] and True not in [nb in x for x in timesFaces]:\n if [i for i in self.f[nb].n if True in [i in x for x in astFaces]]==[\n ] and [i for i in self.f[nb].sn if True in [i in x for x in astFaces]]!=[]:\n astFaces[-1].append(nb)\n elif [i for i in self.f[nb].n if True in [i in x for x in astFaces]]!=[]:\n circFaces.append(nb)\n else:\n if self.f[nb].s==4:\n circFaces.append(nb)\n else:\n return False\n for x in astFaces:\n for faceNb in x:\n self.f[faceNb].label=AST\n for qpath in timesFaces:\n for faceNb in qpath:\n self.f[faceNb].label=TIMES\n for faceNb in circFaces:\n self.f[faceNb].label=CIRC\n k=0\n for faceNb in range(len(self.f)-1):\n if self.f[faceNb].label==AST:\n for nei in self.f[faceNb].n:\n if nei4:\n cc=2\n c0=(f0.s-6+f2.s-6)/cc\n c1=(f1.s-6+f0.s-6)/cc\n c2=(f2.s-6+f1.s-6)/cc\n corr=1.5*(-2+max(2,vr.d))\n meta+=str(2*(n0.d+n1.d+n2.d)-3*corr+c0+c1+c2)+\"v\"+str(vr.nb)+\"=\"\n meta+=str(n1.d+n2.d-corr+c0)+\"v\"+str(n0.nb)+\"+\"\n meta+=str(n0.d+n2.d-corr+c1)+\"v\"+str(n1.nb)+\"+\"\n meta+=str(n0.d+n1.d-corr+c2)+\"v\"+str(n2.nb)+\";\\n\"\n meta+=\"pair f[];\\n\"\n for face in self.f:\n meta+=str(face.s)+\"f\"+str(face.nb)+\"=v\"+str(face.a[0])\n for i in range(1,face.s):\n meta+=\"+v\"+str(face.a[i])\n meta+=\";\\n\"\n meta+=\"pickup pencircle scaled .3mm;\\n\"\n for i in range(len(self.v)-1,-1,-1):\n if i not in self.f[maxFaceNb].a:\n vr=self.v[i]\n for ii in range(3):\n ni=self.v[vr.n[ii]]\n if ni.nb>vr.nb:\n meta+=\"draw v\"+str(vr.nb)+\"--v\"+str(ni.nb)+\";\\n\"\n meta+=\"pickup pencircle scaled 2pt;\\n\"\n realVertices=[vr.nb for vr in self.v if vr.nb not in self.f[maxFaceNb].a]\n meta+=\"for i:=\"+str(realVertices[0])\n for nb in realVertices[1:]:\n meta+=\",\"+str(nb)\n meta+=\": draw v[i]; endfor \\n\"\n meta+=\"picture underlyingGraph;\\n\"\n meta+=\"underlyingGraph:=currentpicture;\\n\"\n self.meta=meta\n\n def setInitialAstFacesOneActiveSegment(self,face,di,aroundFaces):\n astFaces=[]\n leftNb=face.n[di]\n rightNb=face.n[(di+1)%face.s]\n leftIndex=aroundFaces.index(leftNb)\n rightIndex=aroundFaces.index(rightNb)\n if rightIndex2 or (self.f[newface.sn[incoming-i]].d>1 and (self.c<=5 or self.f6<28+2*self.c)) or newface.sn[incoming-i] in targets:\n L.append((nbTimesEdges+1,mode,Qpaths,newface,incoming-i,forVer+[v1,v2],xFaces+[newface.nb],astFaces+[f1,f2],targets))\n elif newface.s==4:\n for i in [3,1]:\n if self.f[newface.sn[incoming-i]].d>1 or newface.sn[incoming-i] in targets:\n L.append((nbTimesEdges+1,mode,Qpaths,newface,incoming-i,forVer+[v1,v2],xFaces+[newface.nb],astFaces+[f1,f2],targets))\n elif newface.d==1:\n for i in [1,-1]:\n if newface.n[(incoming+i)%newface.s]!=maxFaceNb:\n if newface.n[(incoming+i+1)%newface.s]!=maxFaceNb:\n L.append((nbTimesEdges+1,mode,Qpaths,newface,(incoming+i)%newface.s,forVer+[v1,v2],xFaces+[newface.nb],astFaces+[f1,f2],targets))\n elif True in [newface.nb in qpath.timesFaces for qpath in Qpaths] and newface.d>=2:\n existingTimesEdges=self.existingTimesEdges(newface,Qpaths)\n if len(existingTimesEdges)==newface.s-4:\n if newface.s==5:\n existing=existingTimesEdges[0]\n new=[]\n if (incoming-existing)%5==2:\n new.append((incoming-1)%5)\n elif (incoming-existing)%5==3:\n new.append((incoming+1)%5)\n elif (incoming-existing)%5==1:\n new.append((incoming+1)%5)\n new.append((incoming+3)%5)\n elif (incoming-existing)%5==4:\n new.append((incoming-1)%5)\n new.append((incoming-3)%5)\n for i in new:\n if self.f[newface.sn[i]].d>1 or newface.sn[incoming-i] in targets:\n L.append((nbTimesEdges+1,mode,Qpaths,newface,i,forVer+[v1,v2],xFaces+[newface.nb],astFaces+[f1,f2],targets))\n elif newface.s==6:\n new=[]\n if (existingTimesEdges[0]-existingTimesEdges[1])%6==3:\n for i in [-1,1]:\n if (incoming-i)%6 not in existingTimesEdges:\n new.append((incoming-i)%6)\n else:\n for i in [1,3,5]:\n if self.f[newface.sn[incoming-i]].d>1 or newface.sn[incoming-i] in targets:\n if (incoming-i)%6 not in existingTimesEdges:\n new.append((incoming-i)%6)\n for i in new:\n if self.f[newface.sn[i]].d>1 or newface.sn[incoming-i] in targets:\n L.append((nbTimesEdges+1,mode,Qpaths,newface,i,forVer+[v1,v2],xFaces+[newface.nb],astFaces+[f1,f2],targets))\n \n def findFreePentagons(self,Qpaths):\n freePentagons=[]\n for p in self.pentagons:\n isFree=True\n for path in Qpaths:\n if p in path.astFaces:\n isFree=False\n if p in path.timesFaces:\n isFree=False\n if isFree:\n freePentagons.append(p)\n return freePentagons\n \n def existingTimesEdges(self,face,Qpaths):\n timesEdges=[]\n for qpath in Qpaths:\n for i in range(len(qpath.timesFaces)):\n if qpath.timesFaces[i]==face.nb:\n if i>0:\n timesEdges.append(whereIsFirst(qpath.timesFaces[i-1],face.sn))\n if i1 and face.label==CIRC:\n #find the two incident circEdges and join them\n erasedCirc=face.nb\n face.label=TIMES\n containErasedCirc=[]\n for edge in circEdges:\n if erasedCirc in edge:\n containErasedCirc.append(edge)\n foundFirst=False\n if len(containErasedCirc)==2:\n newCircEdge=[]\n for otherCircEdge in containErasedCirc:\n if not foundFirst: \n if otherCircEdge[0]==erasedCirc:\n foundFirst=True\n newCircEdge.append(otherCircEdge[1])\n newCircEdge+=list(reversed(otherCircEdge[2:]))\n firstToRemove=otherCircEdge\n elif otherCircEdge[1]==erasedCirc:\n foundFirst=True\n newCircEdge.append(otherCircEdge[0])\n newCircEdge+=list(otherCircEdge[2:])\n firstToRemove=otherCircEdge\n else:\n if otherCircEdge[0]==erasedCirc:\n foundSecond=True\n newCircEdge.insert(1,otherCircEdge[1])\n newCircEdge+=list(otherCircEdge[2:])\n secondToRemove=otherCircEdge\n elif otherCircEdge[1]==erasedCirc:\n foundSecond=True\n newCircEdge.insert(1,otherCircEdge[0])\n newCircEdge+=list(reversed(otherCircEdge[2:]))\n secondToRemove=otherCircEdge\n circEdges.remove(firstToRemove)\n circEdges.remove(secondToRemove)\n circEdges.append(tuple(newCircEdge))\n return circEdges\n def dfs(self,face,resFaceNb):\n for nei in face.n:\n if self.f[nei].label==AST:\n if self.f[nei].resFace==-1:\n self.f[nei].resFace=resFaceNb\n self.f[nei].father=face.nb\n self.dfs(self.f[nei],resFaceNb)\n elif self.f[nei].resFace!=resFaceNb:\n self.isWrong=True\n return\n elif self.f[nei].resFace==resFaceNb:\n if nei!=face.father:\n self.isWrong=True\n return \n \n def calculateResidualFaces(self):\n self.isWrong=False\n for face in self.f:\n face.resFace=-1\n resFaceNb=0\n for face in self.f:\n if face.label==AST:\n if face.resFace==-1:\n if not self.isWrong:\n face.resFace=resFaceNb\n face.father=None\n self.dfs(face,resFaceNb)\n resFaceNb+=1\n if not self.isWrong:\n for ver in self.v:\n ver.resFace=-1\n for face in self.f:\n if face.label==AST:\n for ver in face.a:\n self.v[ver].resFace=face.resFace\n newResFaceNb=-2\n peri=self.f[-1].s\n for i in range(peri):\n ver=self.f[-1].a[i]\n if self.v[ver].resFace==-1:\n prec=self.f[-1].a[i-1]\n succ=self.f[-1].a[(i+1)%peri]\n precFace=self.f[self.v[ver].a[2]]\n succFace=self.f[self.v[ver].a[0]]\n if self.v[prec].resFace!=-1 and (precFace.s==6 or (precFace.s==5 and ((self.inSegment[0]==precFace or self.outSegment[0]==precFace) and not (self.inSegment[0]==precFace and self.outSegment[0]==precFace)))):\n self.v[ver].resFace=self.v[prec].resFace\n elif self.v[succ].resFace!=-1 and (succFace.s==6 or (succFace.s==5 and ((self.inSegment[0]==succFace or self.outSegment[0]==succFace) and not (self.inSegment[0]==succFace and self.outSegment[0]==succFace)))):\n self.v[ver].resFace=self.v[succ].resFace\n else:\n self.v[ver].resFace=newResFaceNb\n newResFaceNb-=1\n first = self.f[-1].a[0]\n last = self.f[-1].a[-1]\n precFace=self.f[self.f[-1].n[0]]\n firstResFace = self.v[first].resFace\n lastResFace = self.v[last].resFace\n if precFace.s==6 or (precFace.s==5 and ((self.inSegment[0]==precFace or self.outSegment[0]==precFace) and not (self.inSegment[0]==precFace and self.outSegment[0]==precFace))):\n if firstResFace <-1:\n if lastResFace <-1:\n if firstResFace != lastResFace:\n for ver in self.v:\n if ver.resFace==lastResFace:\n ver.resFace=firstResFace\n\n def calculateResidualAdjacencies(self):\n direction=None\n length=self.f[-1].s\n self.resGraphFaces={}\n for ver in self.v:\n if ver.resFace>-1:\n if ver.resFace not in self.resGraphFaces:\n self.resGraphFaces[ver.resFace]=[]\n first=ver.nb\n whereTo=0\n #find the edge that is boundary of a residual face\n while not (self.f[ver.a[whereTo]].label==AST and self.f[ver.a[whereTo-1]].label!=AST):\n whereTo+=1\n loop=True\n while ver.nb!=first or loop:\n loop=False\n #if there is a outgoing edge, look at the resFAce\n if self.f[ver.a[whereTo-2]].label!=AST:\n other=self.v[ver.n[whereTo-1]].resFace\n if other!=ver.resFace:\n if self.resGraphFaces[ver.resFace]==[]:\n self.resGraphFaces[ver.resFace].append(other)\n elif other!=self.resGraphFaces[ver.resFace][-1]:\n self.resGraphFaces[ver.resFace].append(other)\n elif ver.d==0 and self.v[ver.n[whereTo-1]].d==0:\n whereIs = whereIsFirst(ver.nb,self.f[-1].a)\n whereIsOther = whereIsFirst(ver.n[whereTo-1],self.f[-1].a)\n\n if (whereIsOther-whereIs)%length == 1:\n direction = 1\n else:\n direction = -1\n if direction==1: \n whereIs+=direction\n whereIs=whereIs%length\n newOther = self.v[self.v[self.f[-1].a[whereIs]].n[0]].resFace\n while self.v[self.f[-1].a[whereIs]].resFace==ver.resFace and newOther!=ver.resFace:\n if self.resGraphFaces[ver.resFace]==[]:\n self.resGraphFaces[ver.resFace].append(newOther)\n elif newOther!=self.resGraphFaces[ver.resFace][-1]:\n self.resGraphFaces[ver.resFace].append(newOther)\n whereIs+=direction\n whereIs=whereIs%length\n newOther = self.v[self.v[self.f[-1].a[whereIs]].n[0]].resFace\n newOther = self.v[self.f[-1].a[whereIs]].resFace\n if newOther!=ver.resFace:\n if self.resGraphFaces[ver.resFace]==[]:\n self.resGraphFaces[ver.resFace].append(newOther)\n elif newOther!=self.resGraphFaces[ver.resFace][-1]:\n self.resGraphFaces[ver.resFace].append(newOther)\n else:\n oldWhereIs=whereIs\n whereIs+=direction\n whereIs=whereIs%length\n newOther = self.v[self.v[self.f[-1].a[whereIs]].n[0]].resFace\n while self.v[self.f[-1].a[whereIs]].resFace==ver.resFace and newOther!=ver.resFace:\n whereIs+=direction\n whereIs=whereIs%length\n newOther = self.v[self.v[self.f[-1].a[whereIs]].n[0]].resFace\n newOther = self.v[self.f[-1].a[whereIs]].resFace\n if newOther!=ver.resFace:\n if self.resGraphFaces[ver.resFace]==[]:\n self.resGraphFaces[ver.resFace].append(newOther)\n elif newOther!=self.resGraphFaces[ver.resFace][-1]:\n self.resGraphFaces[ver.resFace].append(newOther)\n whereIs-=direction\n whereIs=whereIs%length\n while whereIs!=oldWhereIs:\n newOther = self.v[self.v[self.f[-1].a[whereIs]].n[0]].resFace\n if self.resGraphFaces[ver.resFace]==[]:\n self.resGraphFaces[ver.resFace].append(newOther)\n elif newOther!=self.resGraphFaces[ver.resFace][-1]:\n self.resGraphFaces[ver.resFace].append(newOther)\n whereIs-=direction\n whereIs=whereIs%length\n \n if ver.d==0 and self.v[ver.n[whereTo]].d==0:\n if self.resGraphFaces[ver.resFace]==[] or self.resGraphFaces[ver.resFace][-1]!=-1:\n self.resGraphFaces[ver.resFace].append(-1)\n ver=self.v[ver.n[whereTo]]\n whereTo=0\n while not (self.f[ver.a[whereTo]].label==AST and self.f[ver.a[whereTo-1]].label!=AST):\n whereTo+=1\n elif ver.resFace<-1:\n if ver.resFace not in self.resGraphFaces:\n self.resGraphFaces[ver.resFace]=[]\n whereIs = whereIsFirst(ver.nb,self.f[-1].a)\n while self.v[self.f[-1].a[whereIs-1]].resFace == ver.resFace:\n whereIs-=1\n newOther = self.v[self.f[-1].a[whereIs-1]].resFace\n if newOther!=ver.resFace:\n if self.resGraphFaces[ver.resFace]==[]:\n self.resGraphFaces[ver.resFace].append(newOther)\n elif newOther!=self.resGraphFaces[ver.resFace][-1]:\n self.resGraphFaces[ver.resFace].append(newOther)\n newOther = self.v[self.v[self.f[-1].a[whereIs]].n[0]].resFace\n while self.v[self.f[-1].a[whereIs]].resFace==ver.resFace and newOther!=ver.resFace:\n if self.resGraphFaces[ver.resFace]==[]:\n self.resGraphFaces[ver.resFace].append(newOther)\n elif newOther!=self.resGraphFaces[ver.resFace][-1]:\n self.resGraphFaces[ver.resFace].append(newOther)\n whereIs+=1\n whereIs=whereIs%length\n newOther = self.v[self.v[self.f[-1].a[whereIs]].n[0]].resFace\n newOther = self.v[self.f[-1].a[whereIs]].resFace\n if newOther!=ver.resFace:\n if self.resGraphFaces[ver.resFace]==[]:\n self.resGraphFaces[ver.resFace].append(newOther)\n elif newOther!=self.resGraphFaces[ver.resFace][-1]:\n self.resGraphFaces[ver.resFace].append(newOther)\n self.resGraphFaces[ver.resFace].append(-1) \n self.resGraphFaces[-1]=[]\n for ver in self.f[-1].a:\n if self.resGraphFaces[-1]==[]:\n self.resGraphFaces[-1].append(self.v[ver].resFace)\n elif self.v[ver].resFace!=self.resGraphFaces[-1][-1]:\n self.resGraphFaces[-1].append(self.v[ver].resFace)\n for rf in self.resGraphFaces:\n if len(self.resGraphFaces[rf])==1:\n self.isWrong=True\n elif self.resGraphFaces[rf][0]==self.resGraphFaces[rf][-1]:\n del(self.resGraphFaces[rf][-1])\n## for i in self.resGraphFaces:\n## for j in self.resGraphFaces[i]:\n## if i not in self.resGraphFaces[j]:\n## print('problematic resGraphFaces',i,j,self.resGraphFaces,[self.v[ver].resFace for ver in self.f[-1].a])\n def isNontrivial3cut(self):\n checked={}\n changed=True\n checked[-1]=True\n for resFaceNb in self.resGraphFaces:\n checked[resFaceNb]=True\n resFace=self.resGraphFaces[resFaceNb]\n deg=len(resFace)\n for i in range(deg):\n ii=resFace[i]\n if ii not in checked:\n for j in range(i+2-deg,i-1):\n jj=resFace[j]\n if jj not in checked:\n if ii in self.resGraphFaces[jj]:\n degi=len(self.resGraphFaces[ii])\n whereji=self.resGraphFaces[ii].index(jj)\n wheredi=self.resGraphFaces[ii].index(resFaceNb)\n difi=whereji-wheredi\n if difi<0:\n difi*=-1\n if 2<=difi and difi <= degi - 2:\n degj=len(self.resGraphFaces[jj])\n whereij=self.resGraphFaces[jj].index(ii)\n wheredj=self.resGraphFaces[jj].index(resFaceNb)\n difj=whereij-wheredj\n if difj<0:\n difj*=-1\n if 2<=difj and difj<=degj-2:\n if not ((2==difi or difi==degi-2) and (2==difj or difj==degj-2) and -1 in [resFaceNb,ii,jj]):\n return True\n \n return False\n def completeSolution(self,Qpaths):\n if self.completeLabels([self.initialAstFaces]+[qpath.astFaces for qpath in Qpaths],[qpath.timesFaces for qpath in Qpaths],Qpaths):\n self.completeTheRest(Qpaths)\n\n def completeTheRest(self,Qpaths):\n qua=[face.nb for face in self.f if (face.s==4 and face.d>1)]\n parity = (\n len([q for q in qua if self.f[q].label!=AST])\n + len(Qpaths)\n - len([\n 1 for qpath in Qpaths if\n ( qpath.timesFaces[0]==qpath.timesFaces[-1] and not (self.inSegment[0]!=None and self.outSegment[0]!=None and qpath.timesFaces[0]==self.inSegment[0].nb ))\n ])\n )%2\n if self.isTooComplicated(Qpaths):\n return\n self.calculateResidualFaces()\n if self.isWrong: \n return\n self.calculateResidualAdjacencies()\n for rf in self.resGraphFaces:\n if len(self.resGraphFaces[rf])==1:\n return\n digons = [rf for rf in self.resGraphFaces if len(self.resGraphFaces[rf])==2]\n trigons = [rf for rf in self.resGraphFaces if (len(self.resGraphFaces[rf])==3 and -1 not in self.resGraphFaces[rf])]\n isUgly=False\n if len(digons)+len(trigons)>1:\n isUgly=True\n if len(digons)==1:\n digon=digons[0]\n nei1=self.resGraphFaces[digon][0]\n nei2=self.resGraphFaces[digon][1]\n done=False\n for face in self.f:\n if face.label!=AST and face.s==6 and not done:\n whatISee=[self.v[ver].resFace for ver in face.a]\n if digon in whatISee and nei1 in whatISee and nei2 in whatISee:\n done=True\n face.label=AST\n for fn in face.n:\n if self.f[fn].label==CIRC:\n self.f[fn].label=TIMES\n for ff in self.f:\n if ff.resFace==nei1 or ff.resFace==nei2:\n ff.resFace=digon\n for vv in self.v:\n if vv.resFace==nei1 or vv.resFace==nei2:\n vv.resFace=digon\n if not done:\n isUgly=True\n elif len(trigons)==1:\n trigon=trigons[0]\n neis=[self.resGraphFaces[trigon][i] for i in range(3)]\n isAvailable=[None,None,None]\n for i in range(3):\n previous = self.resGraphFaces[trigon][i-1]\n nextt = self.resGraphFaces[trigon][i-2]\n whereIs = whereIsFirst(nextt,self.resGraphFaces[previous])\n if whereIs==None:\n print(self.resGraphFaces)\n print(trigon)\n print([path.timesFaces for path in Qpaths])\n opposite = self.resGraphFaces[previous][(whereIs+1)%len(self.resGraphFaces[previous])]\n if len(self.resGraphFaces[opposite])>=5 or opposite<-1:\n isAvailable[i]=True\n else:\n isAvailable[i]=False\n lengths=[len(self.resGraphFaces[neis[i]]) for i in range(3)]\n longest=max(lengths)\n if lengths.count(4)>=2:\n isUgly=True\n if longest<6:\n isUgly=True\n if lengths.count(longest)==1:\n other=lengths.index(longest)\n elif lengths.count(longest)==2:\n other=None\n for i in range(3):\n if isAvailable[i]:\n if lengths[i]==longest:\n other=i\n if other==None:\n other=lengths.index(longest)\n elif lengths.count(longest)==3:\n other=None\n for i in range(3):\n if isAvailable[i]:\n if lengths[i]==longest:\n other=i\n if other==None:\n other=lengths.index(longest)\n others=[0,1,2]\n del(others[other])\n second=neis[others[0]]\n third=neis[others[1]]\n for face in self.f:\n if face.label!=AST and face.s==6:\n whatISee=[self.v[ver].resFace for ver in face.a]\n if trigon in whatISee and second in whatISee and third in whatISee:\n auxList=[nei for nei in face.n if self.f[nei].label==TIMES and self.f[nei].d==1]\n \n if False and auxList!=[]:\n isUgly=True\n \n else:\n if not isUgly:\n face.label=AST\n for fn in face.n:\n if self.f[fn].label==CIRC:\n self.f[fn].label=TIMES\n for ff in self.f:\n if ff.resFace==second or ff.resFace==third:\n ff.resFace=trigon\n for vv in self.v:\n if vv.resFace==second or vv.resFace==third:\n vv.resFace=trigon\n self.calculateResidualFaces()\n if self.isWrong: \n return\n \n self.calculateResidualAdjacencies()\n if self.isNontrivial3cut():\n isUgly=True\n timesEdges=self.calculateTimesEdges(Qpaths)\n circEdges=self.calculateCircEdges()\n if circEdges==[]:\n return\n circEdges=self.eliminate2vertices(circEdges)\n isTri=self.isTriangle(circEdges)\n if self.success[parity]==False:\n if not isUgly: \n if isTri>=2:\n self.success[parity]=True\n if self.needBothParities==False:\n self.success[1-parity]=True\n self.drawFigure(timesEdges,circEdges,parity,Qpaths)\n \n \n def callForNewInitialDirections(self,Qpaths):\n astPentagons=[]\n timesPentagons=[]\n d={}\n for p in self.pentagons:\n if True in [p in qpath.astFaces for qpath in Qpaths]:\n astPentagons.append(p) \n elif True in [p in qpath.timesFaces for qpath in Qpaths]:\n timesPentagons.append(p)\n else:\n foundAst=False\n L=[p]\n dist={}\n dist[p]=0\n while not foundAst:\n nf=L.pop(0)\n for i in self.f[nf].n:\n if i not in dist:\n dist[i]=dist[nf]+1\n L.append(i)\n if True in [i in qpath.astFaces for qpath in Qpaths] or i in self.initialAstFaces:\n foundAst=True\n d[p]=dist[i]\n self.completeSolution(Qpaths)\n if d=={}:\n if self.success!=[True,True]: \n initialDirections=[]\n quad = [face.nb for face in self.f if face.s==4 and face.d>1] \n for where in quad:\n face=self.f[where]\n if where not in timesPentagons:\n if where not in astPentagons: \n for i in range(face.s):\n if face.n[i] not in astPentagons:\n if face.n[i-2] not in astPentagons:\n if face.n[i-1] not in timesPentagons:\n whereFrom=face.n[i]\n newDi=face.w[i]\n initialDirections+=[(0,self.f[whereFrom],newDi,[whereFrom])]\n return initialDirections\n if self.success!=[True,True]:\n initialDirections=[]\n for where in d:\n face=self.f[where]\n initialDirections+=[(0,face,di,[p for p in d if p>where]) for di in range(face.s)]\n for where in d:\n face=self.f[where]\n for i in range(face.s):\n if face.n[i] not in astPentagons:\n if face.n[i-2] not in astPentagons:\n if face.n[i-1] not in timesPentagons:\n whereFrom=face.n[i]\n newDi=face.w[i]\n initialDirections+=[(0,self.f[whereFrom],newDi,[whereFrom])]\n quad = [face.nb for face in self.f if face.s==4 and face.d>1] \n for where in quad:\n face=self.f[where]\n if where not in timesPentagons:\n if where not in astPentagons: \n for i in range(face.s):\n if face.n[i] not in astPentagons:\n if face.n[i-2] not in astPentagons:\n if face.n[i-1] not in timesPentagons:\n whereFrom=face.n[i]\n newDi=face.w[i]\n initialDirections+=[(0,self.f[whereFrom],newDi,[whereFrom])]\n return initialDirections\n else:\n return []\n\n\n\n def regularizeAstFaces(self):\n toRemove=[]\n for astFace in self.initialAstFaces:\n if self.f[astFace].d>2:\n toRemove.append(astFace)\n for face in toRemove:\n while face in self.initialAstFaces:\n self.initialAstFaces.remove(face)\n def checkInactiveEverywhere(self):\n if self.completeLabels([self.initialAstFaces],[],[]):\n self.completeTheRest([])\n\n def isDanger(self,face,di):\n mayContinue = []\n size=face.s\n for i in [-1,1,-3]:\n newDi=(di+i)%size\n nextFace = self.f[face.sn[newDi]]\n if nextFace.d>=2:\n mayContinue.append((newDi,nextFace))\n if len(mayContinue)>=2:\n return (False,None)\n elif len(mayContinue)==0:\n print('Error, cannot continue at all!')\n return (True,None)\n else:\n return (True,mayContinue[0])\n\n def check(self,pNb):\n global patchNb\n patchNb=pNb\n global figNb\n figNb=0\n self.setMetapostDefinitions()\n output=str(self.f4)+'.'+str(self.f5)+'.'+str(self.f6)+'.'+str(patchNb)\n metapostFile=open(\"./output/\"+output+'.mp','w')\n print(output)\n metapostFile.write(self.meta)\n metapostFile.close()\n texFile=open(\"./output/\"+output+'.tex','w')\n texFile.write(\"\\\\documentclass{article}\\n\")\n texFile.write(\"\\\\usepackage{graphicx}\\n\")\n texFile.write(\"\\\\begin{document}\\n\")\n texFile.close()\n pentagons = [face.nb for face in self.f if face.s==5 and face.d>1]\n self.pentagons=[face.nb for face in self.f if face.s==5 and face.d>1]\n maxFaceNb=len(self.f)-1\n\n\n (startingEdges,aroundFaces)=self.startingEdges()\n if self.c%2==1:\n if len(aroundFaces[0])>len(aroundFaces[1]):\n (aroundFaces[0],aroundFaces[1])=(aroundFaces[1],aroundFaces[0])\n (startingEdges[0],startingEdges[1])=(startingEdges[1],startingEdges[0])\n \n aroundFacesThird=aroundFaces[0]\n tobeRemoved=[]\n for astFace in aroundFacesThird:\n if self.f[astFace].d==3:\n tobeRemoved.append(astFace)\n for astFace in tobeRemoved:\n aroundFacesThird.remove(astFace)\n incomplete=0\n \n self.outSegment=(None,None)\n self.needBothParities=True\n texFile=open(\"./output/\"+output+'.tex','a')\n texFile.write(\"\\n\")\n texFile.close()\n \n self.success=[False,False]\n self.initialAstFaces=aroundFaces[0]\n #print(self.initialAstFaces)\n self.Qpaths=[]\n self.inSegment=(None,None)\n self.outSegment=(None,None)\n self.checkInactiveEverywhere()\n newInitialDirections=self.callForNewInitialDirections([])\n self.searchFrom(newInitialDirections)\n if self.success==[False,False]:\n print('Cannot find any solution for 0 active segments !!!')\n self.drawBadCase()\n elif self.success==[True,True]:\n self.needBothParities=False\n else:\n if self.c>=7:\n print('Cannot change parity!')\n ## else:\n ## print('Success')\n # print([(face.nb,face.sn[di]) for (face,di) in twoActiveSegmentsStartingEdges])\n if self.c<=5:\n texFile=open(\"./output/\"+output+'.tex','a')\n texFile.write(\"\\n\")\n texFile.close()\n if self.needBothParities:\n for face in self.f:\n face.bothParities=False\n\n oneActiveSegmentStartingEdges = startingEdges[0]\n twoActiveSegmentsStartingEdges = startingEdges[1]\n self.outSegment=(None,None)\n oneActiveSegmentStartingPoints=[(face,di%2,di) for (face,di) in (oneActiveSegmentStartingEdges[::2]+oneActiveSegmentStartingEdges[1::2])]\n #self.show()\n for (face,pa,di) in oneActiveSegmentStartingPoints:\n #print(oneActiveSegmentStartingPoints.index((face,pa,di))*2+1)\n # if oneActiveSegmentStartingPoints.index((face,pa,di))*2+1==9:\n## texFile=open(\"./output/\"+output+'.tex','a')\n## texFile.write(\"\\n\")\n## texFile.close()\n \n self.success=[False,False]\n self.setOddInitialAstFacesOneActiveSegment(face,di,aroundFaces[1])\n # print(self.initialAstFaces)\n self.Qpaths=[]\n self.inSegment=(face,di)\n self.outSegment=(None,None)\n initialDirections=[(1,face,di,pentagons)]\n self.searchFrom(initialDirections)\n if self.success==[False,False]:\n print('Cannot find any solution for',oneActiveSegmentStartingPoints.index((face,pa,di))*2+1,'!!!')\n self.drawBadCase()\n else:\n if self.needBothParities:\n if self.success==[True,True]:\n newface=self.f[face.sn[di]]\n incoming=face.sw[di]\n f1=face.n[di]\n f2=newface.n[incoming]\n face.bothParities=True\n self.f[f1].bothParities=True\n self.f[f2].bothParities=True\n newface.bothParities=True\n if self.needBothParities:\n AllBothParities=True\n for faceDist1 in self.f[maxFaceNb].n:\n if self.f[faceDist1].bothParities==False:\n nbNotBothParities=0\n for nei in self.f[faceDist1].n:\n if nei1:\n AllBothParities=False\n #print('face',faceDist1,'does not have both parities')\n if not AllBothParities:\n print('cannot guarantee both parities for one active segment...')\n else:\n self.needBothParities=False\n redStartingEdges = startingEdges[1][::2]\n blueStartingEdges = startingEdges[1][1::2]\n for (inFace,inDi) in redStartingEdges:\n texFile=open(\"./output/\"+output+'.tex','a')\n texFile.write(\"\\n\")\n texFile.close()\n incoming=inFace.sw[inDi]\n inNewFace=self.f[inFace.sn[inDi]]\n v1=inFace.a[inDi]\n v2=inNewFace.a[incoming]\n f1=inFace.n[inDi]\n f2=inNewFace.n[incoming]\n inDanger = self.isDanger(inNewFace,incoming) \n for (outFace,outDi) in blueStartingEdges:\n outcoming=outFace.sw[outDi]\n outNewFace=self.f[outFace.sn[outDi]]\n v3=outFace.a[outDi]\n v4=outNewFace.a[outcoming]\n f3=outFace.n[outDi]\n f4=outNewFace.n[outcoming]\n outDanger = self.isDanger(outNewFace,outcoming)\n danger=False\n if inDanger[0] and outDanger[0]:\n (inNewDi,inNextFace) = inDanger[1]\n (outNewDi,outNextFace) = outDanger[1]\n w1=inNewFace.a[inNewDi]\n w2=inNextFace.a[inNewFace.sw[inNewDi]]\n w3=outNewFace.a[outNewDi]\n w4=outNextFace.a[outNewFace.sw[outNewDi]]\n if not disjoint([w1,w2],[w3,w4]):\n danger=True\n if not danger:\n self.success=[False,False]\n self.setOddInitialAstFacesTwoActiveSegments(inFace,inDi,outFace,outDi,aroundFaces)\n while maxFaceNb in self.initialAstFaces:\n self.initialAstFaces.remove(maxFaceNb)\n self.regularizeAstFaces()\n countPairs=0\n pairs=[]\n for faceNb in self.initialAstFaces:\n for i in range(self.f[faceNb].s):\n if self.f[faceNb].n[i] in self.initialAstFaces:\n countPairs+=1\n pairs.append((faceNb,self.f[faceNb].n[i]))\n \n astAdj={}\n for (i,j) in pairs:\n if i not in astAdj:\n astAdj[i]=[j]\n else:\n astAdj[i]+=[j]\n possible=True\n for i in astAdj:\n if len(astAdj[i])==2:\n if astAdj[i][0] in astAdj[astAdj[i][1]]:\n possible=False\n if possible:\n if countPairs==4:\n self.Qpaths=[]\n initialDirections=[(2,inFace,inDi,pentagons+[outFace.sn[outDi]]),(2,outFace,outDi,pentagons+[inFace.sn[inDi]])]\n self.inSegment=(inFace,inDi)\n self.outSegment=(outFace,outDi)\n self.searchFrom(initialDirections)\n if self.success==[False,False]:\n print('Cannot find any solution for',inFace.nb,outFace.nb,'!!!')\n self.drawBadCase()\n \n if self.c%2==0 and len(aroundFaces)==1:\n for aroundFacesThird in aroundFaces:\n tobeRemoved=[]\n for astFace in aroundFacesThird:\n if self.f[astFace].d==3:\n tobeRemoved.append(astFace)\n for astFace in tobeRemoved:\n aroundFacesThird.remove(astFace)\n\n for face in self.f:\n face.bothParities=False\n startingEdges=startingEdges[0]\n aroundFaces=aroundFaces[0] \n firstLeftNb=startingEdges[0][0].n[startingEdges[0][1]]\n firstRightNb=startingEdges[0][0].n[startingEdges[0][1]+1]\n if aroundFaces.index(firstLeftNb)>aroundFaces.index(firstRightNb):\n oneActiveSegmentStartingEdges = startingEdges[::2]\n twoActiveSegmentsStartingEdges = startingEdges[1::2]\n else:\n oneActiveSegmentStartingEdges = startingEdges[1::2]\n twoActiveSegmentsStartingEdges = startingEdges[::2]\n self.outSegment=(None,None)\n oneActiveSegmentStartingPoints=[(face,di%2,di) for (face,di) in oneActiveSegmentStartingEdges]\n self.needBothParities=True\n for (face,pa,di) in oneActiveSegmentStartingPoints:\n texFile=open(\"./output/\"+output+'.tex','a')\n texFile.write(\"\\n\")\n texFile.close()\n \n self.success=[False,False]\n self.setInitialAstFacesOneActiveSegment(face,di,aroundFaces)\n self.Qpaths=[]\n self.inSegment=(face,di)\n self.outSegment=(None,None)\n initialDirections=[(1,face,di,pentagons)]\n self.searchFrom(initialDirections)\n if self.success==[False,False]:\n print('Cannot find any solution for',oneActiveSegmentStartingPoints.index((face,pa,di))*2+1,'!!!')\n self.drawBadCase()\n elif self.success!=[True,True]:\n True\n else:\n newface=self.f[face.sn[di]]\n incoming=face.sw[di]\n f1=face.n[di]\n f2=newface.n[incoming]\n if face.d in [1,2]:\n face.bothParities=True\n if self.f[f1].d in [1,2]:\n self.f[f1].bothParities=True\n if self.f[f2].d in [1,2]:\n self.f[f2].bothParities=True\n if newface.d in [1,2]:\n newface.bothParities=True\n AllBothParities=True\n for faceDist1 in self.f[-1].n:\n if self.f[faceDist1].s==4:\n if not self.f[faceDist1].bothParities: \n nb=0\n for faceNb in self.f[faceDist1].n:\n if self.f[faceNb].bothParities:\n nb+=1\n if nb>=3:\n self.f[faceDist1].bothParities=True\n \n for faceDist1 in self.f[maxFaceNb].n:\n if self.f[faceDist1].bothParities==False:\n AllBothParities=False\n print('face',faceDist1,'does not have both parities')\n\n if not AllBothParities:\n print('cannot guarantee both parities for one active segment')\n self.needBothParities=True\n else:\n self.needBothParities=False\n \n if self.c<6 or (self.c==6 and self.nanoType in [[8,0],[6,2]]) :\n for inSegmentNb in range(len(twoActiveSegmentsStartingEdges)):\n (inFace,inDi)=twoActiveSegmentsStartingEdges[inSegmentNb]\n incoming=inFace.sw[inDi]\n inNewFace=self.f[inFace.sn[inDi]]\n v1=inFace.a[inDi]\n v2=inNewFace.a[incoming]\n f1=inFace.n[inDi]\n f2=inNewFace.n[incoming]\n inDanger = self.isDanger(inNewFace,incoming) \n\n outSegmentNb=inSegmentNb-(len(twoActiveSegmentsStartingEdges)//2)\n texFile=open(\"./output/\"+output+'.tex','a')\n texFile.write(\"\\n\")\n texFile.close()\n continues=True\n while continues:\n (outFace,outDi)=twoActiveSegmentsStartingEdges[outSegmentNb]\n outcoming=outFace.sw[outDi]\n outNewFace=self.f[outFace.sn[outDi]]\n v3=outFace.a[outDi]\n v4=outNewFace.a[outcoming]\n f3=outFace.n[outDi]\n f4=outNewFace.n[outcoming]\n outDanger = self.isDanger(outNewFace,outcoming)\n danger=False\n if inDanger[0] and outDanger[0]:\n (inNewDi,inNextFace) = inDanger[1]\n (outNewDi,outNextFace) = outDanger[1]\n w1=inNewFace.a[inNewDi]\n w2=inNextFace.a[inNewFace.sw[inNewDi]]\n w3=outNewFace.a[outNewDi]\n w4=outNextFace.a[outNewFace.sw[outNewDi]]\n if not disjoint([w1,w2],[w3,w4]):\n danger=True\n if not danger:\n self.success=[False,False]\n self.success=[False,False]\n self.setInitialAstFacesTwoActiveSegments(inFace,inDi,outFace,outDi,aroundFaces)\n self.Qpaths=[]\n initialDirections=[(2,inFace,inDi,pentagons+[outFace.sn[outDi]]),(2,outFace,outDi,pentagons+[inFace.sn[inDi]])]\n self.inSegment=(inFace,inDi)\n self.outSegment=(outFace,outDi)\n self.searchFrom(initialDirections)\n if self.success==[False,False]:\n print('Cannot find any solution for',inFace.nb,outFace.nb,'!!!')\n self.drawBadCase()\n outSegmentNb+=1\n (outFace,outDi)=twoActiveSegmentsStartingEdges[outSegmentNb]\n outcoming=outFace.sw[outDi]\n v3=outFace.a[outDi]\n v4=self.f[outFace.sn[outDi]].a[outcoming]\n f3=outFace.n[outDi]\n f4=self.f[outFace.sn[outDi]].n[outcoming]\n\n\n if (not disjoint([v1,v2],[v3,v4])) or inFace.sn[inDi] in [f3,f4] or outFace.sn[outDi] in [f1,f2]:\n continues=False\n\n elif self.c%2==0 and len(aroundFaces)>1:\n if len(aroundFaces)==2:\n aroundFaces.append(self.f[-1].sn)\n for aroundFacesThird in aroundFaces:\n tobeRemoved=[]\n for astFace in aroundFacesThird:\n if self.f[astFace].d==3:\n tobeRemoved.append(astFace)\n for astFace in tobeRemoved:\n aroundFacesThird.remove(astFace)\n incomplete=0\n for i in range(3):\n \n self.inSegment=(None,None)\n self.outSegment=(None,None)\n self.needBothParities=True\n texFile=open(\"./output/\"+output+'.tex','a')\n texFile.write(\"\\n\")\n texFile.close()\n \n self.success=[False,False]\n self.initialAstFaces=aroundFaces[i]\n self.Qpaths=[]\n\n newInitialDirections=self.callForNewInitialDirections([])\n self.searchFrom(newInitialDirections)\n\n if self.success==[False,False]:\n print('Cannot find any solution for',i,'!!!')\n self.drawBadCase()\n elif self.success!=[True,True]:\n incomplete+=1\n if incomplete==3:\n print('Cannot change parity for any choice!')\n if self.c<6:\n self.needBothParities=False\n for i in range(3):\n redStartingEdges = startingEdges[i][::2]\n blueStartingEdges = startingEdges[i][1::2]\n for (inFace,inDi) in redStartingEdges:\n texFile=open(\"./output/\"+output+'.tex','a')\n texFile.write(\"\\n\")\n texFile.close()\n for (outFace,outDi) in blueStartingEdges:\n self.success=[False,False]\n self.setInitialAstFacesTwoActiveAccordedSegments(inFace,inDi,outFace,outDi,aroundFaces)\n self.Qpaths=[]\n initialDirections=[(2,inFace,inDi,pentagons+[outFace.sn[outDi]]),(2,outFace,outDi,pentagons+[inFace.sn[inDi]])]\n self.outSegment=(outFace,outDi)\n self.inSegment=(inFace,inDi)\n self.searchFrom(initialDirections)\n if self.success==[False,False]:\n print('Cannot find any solution for',inFace.nb,outFace.nb,'!!!')\n self.drawBadCase()\n \n\n metapostFile=open(\"./output/\"+output+'.mp','a')\n metapostFile.write(\"end.\\n\")\n metapostFile.close()\n texFile=open(\"./output/\"+output+'.tex','a')\n texFile.write(\"\\\\end{document}\\n\")\n texFile.close()\n \n\n \n","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":86472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"126587579","text":"import function_def as fd\r\n\r\ndef play_game():\r\n ## Sets a var, game_board, to a Game_Board class\r\n game_board = fd.game_start()\r\n \r\n ## Sets a var, play_1, to a Player class \r\n play_1 = fd.play_1\r\n \r\n ## Calls the main_loop function to start game\r\n fd.main_loop(game_board,play_1)\r\n return\r\n## Starts the game so the user doesn't have to call\r\n## the function themself\r\nplay_game()\r\n","sub_path":"main_game.py","file_name":"main_game.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"361901004","text":"# _*_ coding:utf-8 _*_\n# Speaker information coming from the transcript\n#\n# Example:\n# DONALD TRUMP: Thank you very much\n#\nSPEAKERS = {\n 'BRUCE RAUNER': 'speaker rep',\n}\n\n# Fact checker information for each annotation\n#\n# Example:\n# NPR: dm-content-slug TKTKTKTK\n#\nFACT_CHECKERS = {\n # \"dm\": {\n # \"initials\": \"dm\",\n # \"name\": \"Domenico Montanaro\",\n # \"role\": \"NPR Political Editor & Digital Audience\",\n # \"page\": \"http://www.npr.org/people/392602474/domenico-montanaro\",\n # \"img\": \"http://media.npr.org/assets/img/2015/03/24/domenico_montanaro_npr_007_sq-8689edad716cacac58fb1afc56bc1bcd0d3647e8-s400-c85.jpg\"\n # },\n \"ch\": {\n \"initials\": \"ch\",\n \"name\": \"Chris Hagan\",\n \"role\": \"WBEZ Data Reporter\",\n \"page\": \"https://www.wbez.org/staff/Chris+Hagan/\",\n \"img\": \"http://v2.chicagopublicmedia.org/sites/default/files/chagan.jpg\"\n },\n\n}\n","sub_path":"doc_config.py","file_name":"doc_config.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"551402159","text":"# Copyright 2023 Google LLC. All Rights Reserved.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom connector import channel\nfrom google3.cloud.graphite.mmv2.services.google.cloud_build import worker_pool_pb2\nfrom google3.cloud.graphite.mmv2.services.google.cloud_build import worker_pool_pb2_grpc\n\nfrom typing import List\n\n\nclass WorkerPool(object):\n def __init__(\n self,\n name: str = None,\n display_name: str = None,\n uid: str = None,\n annotations: dict = None,\n create_time: str = None,\n update_time: str = None,\n delete_time: str = None,\n state: str = None,\n private_pool_v1_config: dict = None,\n etag: str = None,\n worker_config: dict = None,\n network_config: dict = None,\n project: str = None,\n location: str = None,\n service_account_file: str = \"\",\n ):\n channel.initialize()\n self.name = name\n self.display_name = display_name\n self.annotations = annotations\n self.private_pool_v1_config = private_pool_v1_config\n self.worker_config = worker_config\n self.network_config = network_config\n self.project = project\n self.location = location\n self.service_account_file = service_account_file\n\n def apply(self):\n stub = worker_pool_pb2_grpc.CloudbuildAlphaWorkerPoolServiceStub(\n channel.Channel()\n )\n request = worker_pool_pb2.ApplyCloudbuildAlphaWorkerPoolRequest()\n if Primitive.to_proto(self.name):\n request.resource.name = Primitive.to_proto(self.name)\n\n if Primitive.to_proto(self.display_name):\n request.resource.display_name = Primitive.to_proto(self.display_name)\n\n if Primitive.to_proto(self.annotations):\n request.resource.annotations = Primitive.to_proto(self.annotations)\n\n if WorkerPoolPrivatePoolV1Config.to_proto(self.private_pool_v1_config):\n request.resource.private_pool_v1_config.CopyFrom(\n WorkerPoolPrivatePoolV1Config.to_proto(self.private_pool_v1_config)\n )\n else:\n request.resource.ClearField(\"private_pool_v1_config\")\n if WorkerPoolWorkerConfig.to_proto(self.worker_config):\n request.resource.worker_config.CopyFrom(\n WorkerPoolWorkerConfig.to_proto(self.worker_config)\n )\n else:\n request.resource.ClearField(\"worker_config\")\n if WorkerPoolNetworkConfig.to_proto(self.network_config):\n request.resource.network_config.CopyFrom(\n WorkerPoolNetworkConfig.to_proto(self.network_config)\n )\n else:\n request.resource.ClearField(\"network_config\")\n if Primitive.to_proto(self.project):\n request.resource.project = Primitive.to_proto(self.project)\n\n if Primitive.to_proto(self.location):\n request.resource.location = Primitive.to_proto(self.location)\n\n request.service_account_file = self.service_account_file\n\n response = stub.ApplyCloudbuildAlphaWorkerPool(request)\n self.name = Primitive.from_proto(response.name)\n self.display_name = Primitive.from_proto(response.display_name)\n self.uid = Primitive.from_proto(response.uid)\n self.annotations = Primitive.from_proto(response.annotations)\n self.create_time = Primitive.from_proto(response.create_time)\n self.update_time = Primitive.from_proto(response.update_time)\n self.delete_time = Primitive.from_proto(response.delete_time)\n self.state = WorkerPoolStateEnum.from_proto(response.state)\n self.private_pool_v1_config = WorkerPoolPrivatePoolV1Config.from_proto(\n response.private_pool_v1_config\n )\n self.etag = Primitive.from_proto(response.etag)\n self.worker_config = WorkerPoolWorkerConfig.from_proto(response.worker_config)\n self.network_config = WorkerPoolNetworkConfig.from_proto(\n response.network_config\n )\n self.project = Primitive.from_proto(response.project)\n self.location = Primitive.from_proto(response.location)\n\n def delete(self):\n stub = worker_pool_pb2_grpc.CloudbuildAlphaWorkerPoolServiceStub(\n channel.Channel()\n )\n request = worker_pool_pb2.DeleteCloudbuildAlphaWorkerPoolRequest()\n request.service_account_file = self.service_account_file\n if Primitive.to_proto(self.name):\n request.resource.name = Primitive.to_proto(self.name)\n\n if Primitive.to_proto(self.display_name):\n request.resource.display_name = Primitive.to_proto(self.display_name)\n\n if Primitive.to_proto(self.annotations):\n request.resource.annotations = Primitive.to_proto(self.annotations)\n\n if WorkerPoolPrivatePoolV1Config.to_proto(self.private_pool_v1_config):\n request.resource.private_pool_v1_config.CopyFrom(\n WorkerPoolPrivatePoolV1Config.to_proto(self.private_pool_v1_config)\n )\n else:\n request.resource.ClearField(\"private_pool_v1_config\")\n if WorkerPoolWorkerConfig.to_proto(self.worker_config):\n request.resource.worker_config.CopyFrom(\n WorkerPoolWorkerConfig.to_proto(self.worker_config)\n )\n else:\n request.resource.ClearField(\"worker_config\")\n if WorkerPoolNetworkConfig.to_proto(self.network_config):\n request.resource.network_config.CopyFrom(\n WorkerPoolNetworkConfig.to_proto(self.network_config)\n )\n else:\n request.resource.ClearField(\"network_config\")\n if Primitive.to_proto(self.project):\n request.resource.project = Primitive.to_proto(self.project)\n\n if Primitive.to_proto(self.location):\n request.resource.location = Primitive.to_proto(self.location)\n\n response = stub.DeleteCloudbuildAlphaWorkerPool(request)\n\n @classmethod\n def list(self, project, location, service_account_file=\"\"):\n stub = worker_pool_pb2_grpc.CloudbuildAlphaWorkerPoolServiceStub(\n channel.Channel()\n )\n request = worker_pool_pb2.ListCloudbuildAlphaWorkerPoolRequest()\n request.service_account_file = service_account_file\n request.Project = project\n\n request.Location = location\n\n return stub.ListCloudbuildAlphaWorkerPool(request).items\n\n def to_proto(self):\n resource = worker_pool_pb2.CloudbuildAlphaWorkerPool()\n if Primitive.to_proto(self.name):\n resource.name = Primitive.to_proto(self.name)\n if Primitive.to_proto(self.display_name):\n resource.display_name = Primitive.to_proto(self.display_name)\n if Primitive.to_proto(self.annotations):\n resource.annotations = Primitive.to_proto(self.annotations)\n if WorkerPoolPrivatePoolV1Config.to_proto(self.private_pool_v1_config):\n resource.private_pool_v1_config.CopyFrom(\n WorkerPoolPrivatePoolV1Config.to_proto(self.private_pool_v1_config)\n )\n else:\n resource.ClearField(\"private_pool_v1_config\")\n if WorkerPoolWorkerConfig.to_proto(self.worker_config):\n resource.worker_config.CopyFrom(\n WorkerPoolWorkerConfig.to_proto(self.worker_config)\n )\n else:\n resource.ClearField(\"worker_config\")\n if WorkerPoolNetworkConfig.to_proto(self.network_config):\n resource.network_config.CopyFrom(\n WorkerPoolNetworkConfig.to_proto(self.network_config)\n )\n else:\n resource.ClearField(\"network_config\")\n if Primitive.to_proto(self.project):\n resource.project = Primitive.to_proto(self.project)\n if Primitive.to_proto(self.location):\n resource.location = Primitive.to_proto(self.location)\n return resource\n\n\nclass WorkerPoolPrivatePoolV1Config(object):\n def __init__(self, worker_config: dict = None, network_config: dict = None):\n self.worker_config = worker_config\n self.network_config = network_config\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = worker_pool_pb2.CloudbuildAlphaWorkerPoolPrivatePoolV1Config()\n if WorkerPoolPrivatePoolV1ConfigWorkerConfig.to_proto(resource.worker_config):\n res.worker_config.CopyFrom(\n WorkerPoolPrivatePoolV1ConfigWorkerConfig.to_proto(\n resource.worker_config\n )\n )\n else:\n res.ClearField(\"worker_config\")\n if WorkerPoolPrivatePoolV1ConfigNetworkConfig.to_proto(resource.network_config):\n res.network_config.CopyFrom(\n WorkerPoolPrivatePoolV1ConfigNetworkConfig.to_proto(\n resource.network_config\n )\n )\n else:\n res.ClearField(\"network_config\")\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return WorkerPoolPrivatePoolV1Config(\n worker_config=WorkerPoolPrivatePoolV1ConfigWorkerConfig.from_proto(\n resource.worker_config\n ),\n network_config=WorkerPoolPrivatePoolV1ConfigNetworkConfig.from_proto(\n resource.network_config\n ),\n )\n\n\nclass WorkerPoolPrivatePoolV1ConfigArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [WorkerPoolPrivatePoolV1Config.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [WorkerPoolPrivatePoolV1Config.from_proto(i) for i in resources]\n\n\nclass WorkerPoolPrivatePoolV1ConfigWorkerConfig(object):\n def __init__(self, machine_type: str = None, disk_size_gb: int = None):\n self.machine_type = machine_type\n self.disk_size_gb = disk_size_gb\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = worker_pool_pb2.CloudbuildAlphaWorkerPoolPrivatePoolV1ConfigWorkerConfig()\n if Primitive.to_proto(resource.machine_type):\n res.machine_type = Primitive.to_proto(resource.machine_type)\n if Primitive.to_proto(resource.disk_size_gb):\n res.disk_size_gb = Primitive.to_proto(resource.disk_size_gb)\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return WorkerPoolPrivatePoolV1ConfigWorkerConfig(\n machine_type=Primitive.from_proto(resource.machine_type),\n disk_size_gb=Primitive.from_proto(resource.disk_size_gb),\n )\n\n\nclass WorkerPoolPrivatePoolV1ConfigWorkerConfigArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [\n WorkerPoolPrivatePoolV1ConfigWorkerConfig.to_proto(i) for i in resources\n ]\n\n @classmethod\n def from_proto(self, resources):\n return [\n WorkerPoolPrivatePoolV1ConfigWorkerConfig.from_proto(i) for i in resources\n ]\n\n\nclass WorkerPoolPrivatePoolV1ConfigNetworkConfig(object):\n def __init__(\n self,\n peered_network: str = None,\n peered_network_ip_range: str = None,\n egress_option: str = None,\n ):\n self.peered_network = peered_network\n self.peered_network_ip_range = peered_network_ip_range\n self.egress_option = egress_option\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = (\n worker_pool_pb2.CloudbuildAlphaWorkerPoolPrivatePoolV1ConfigNetworkConfig()\n )\n if Primitive.to_proto(resource.peered_network):\n res.peered_network = Primitive.to_proto(resource.peered_network)\n if Primitive.to_proto(resource.peered_network_ip_range):\n res.peered_network_ip_range = Primitive.to_proto(\n resource.peered_network_ip_range\n )\n if WorkerPoolPrivatePoolV1ConfigNetworkConfigEgressOptionEnum.to_proto(\n resource.egress_option\n ):\n res.egress_option = (\n WorkerPoolPrivatePoolV1ConfigNetworkConfigEgressOptionEnum.to_proto(\n resource.egress_option\n )\n )\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return WorkerPoolPrivatePoolV1ConfigNetworkConfig(\n peered_network=Primitive.from_proto(resource.peered_network),\n peered_network_ip_range=Primitive.from_proto(\n resource.peered_network_ip_range\n ),\n egress_option=WorkerPoolPrivatePoolV1ConfigNetworkConfigEgressOptionEnum.from_proto(\n resource.egress_option\n ),\n )\n\n\nclass WorkerPoolPrivatePoolV1ConfigNetworkConfigArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [\n WorkerPoolPrivatePoolV1ConfigNetworkConfig.to_proto(i) for i in resources\n ]\n\n @classmethod\n def from_proto(self, resources):\n return [\n WorkerPoolPrivatePoolV1ConfigNetworkConfig.from_proto(i) for i in resources\n ]\n\n\nclass WorkerPoolWorkerConfig(object):\n def __init__(\n self,\n machine_type: str = None,\n disk_size_gb: int = None,\n no_external_ip: bool = None,\n ):\n self.machine_type = machine_type\n self.disk_size_gb = disk_size_gb\n self.no_external_ip = no_external_ip\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = worker_pool_pb2.CloudbuildAlphaWorkerPoolWorkerConfig()\n if Primitive.to_proto(resource.machine_type):\n res.machine_type = Primitive.to_proto(resource.machine_type)\n if Primitive.to_proto(resource.disk_size_gb):\n res.disk_size_gb = Primitive.to_proto(resource.disk_size_gb)\n if Primitive.to_proto(resource.no_external_ip):\n res.no_external_ip = Primitive.to_proto(resource.no_external_ip)\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return WorkerPoolWorkerConfig(\n machine_type=Primitive.from_proto(resource.machine_type),\n disk_size_gb=Primitive.from_proto(resource.disk_size_gb),\n no_external_ip=Primitive.from_proto(resource.no_external_ip),\n )\n\n\nclass WorkerPoolWorkerConfigArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [WorkerPoolWorkerConfig.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [WorkerPoolWorkerConfig.from_proto(i) for i in resources]\n\n\nclass WorkerPoolNetworkConfig(object):\n def __init__(self, peered_network: str = None, peered_network_ip_range: str = None):\n self.peered_network = peered_network\n self.peered_network_ip_range = peered_network_ip_range\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = worker_pool_pb2.CloudbuildAlphaWorkerPoolNetworkConfig()\n if Primitive.to_proto(resource.peered_network):\n res.peered_network = Primitive.to_proto(resource.peered_network)\n if Primitive.to_proto(resource.peered_network_ip_range):\n res.peered_network_ip_range = Primitive.to_proto(\n resource.peered_network_ip_range\n )\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return WorkerPoolNetworkConfig(\n peered_network=Primitive.from_proto(resource.peered_network),\n peered_network_ip_range=Primitive.from_proto(\n resource.peered_network_ip_range\n ),\n )\n\n\nclass WorkerPoolNetworkConfigArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [WorkerPoolNetworkConfig.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [WorkerPoolNetworkConfig.from_proto(i) for i in resources]\n\n\nclass WorkerPoolStateEnum(object):\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return resource\n return worker_pool_pb2.CloudbuildAlphaWorkerPoolStateEnum.Value(\n \"CloudbuildAlphaWorkerPoolStateEnum%s\" % resource\n )\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return resource\n return worker_pool_pb2.CloudbuildAlphaWorkerPoolStateEnum.Name(resource)[\n len(\"CloudbuildAlphaWorkerPoolStateEnum\") :\n ]\n\n\nclass WorkerPoolPrivatePoolV1ConfigNetworkConfigEgressOptionEnum(object):\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return resource\n return worker_pool_pb2.CloudbuildAlphaWorkerPoolPrivatePoolV1ConfigNetworkConfigEgressOptionEnum.Value(\n \"CloudbuildAlphaWorkerPoolPrivatePoolV1ConfigNetworkConfigEgressOptionEnum%s\"\n % resource\n )\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return resource\n return worker_pool_pb2.CloudbuildAlphaWorkerPoolPrivatePoolV1ConfigNetworkConfigEgressOptionEnum.Name(\n resource\n )[\n len(\n \"CloudbuildAlphaWorkerPoolPrivatePoolV1ConfigNetworkConfigEgressOptionEnum\"\n ) :\n ]\n\n\nclass Primitive(object):\n @classmethod\n def to_proto(self, s):\n if not s:\n return \"\"\n return s\n\n @classmethod\n def from_proto(self, s):\n return s\n","sub_path":"python/services/cloudbuild/alpha/worker_pool.py","file_name":"worker_pool.py","file_ext":"py","file_size_in_byte":18569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"393447631","text":"import unittest\nimport json\nimport os \n\nfrom fwf2csv import FWF2CSV\n\nclass TestFWF2CSV(unittest.TestCase):\n # tc stands for test_case\n @classmethod\n def setUpClass(cls):\n print('setupClass')\n\n @classmethod\n def tearDownClass(cls):\n print('teardownClass')\n\n \n def setUp(self):\n self.base_test_case = {\n 'f1': ['ab','AB','AAABBB_B'],\n 'f2': ['cd','CD','CCC_DDD_D'],\n 'f3': ['ef','EF','EFFF_FFF'],\n 'f4': ['gh','GH','GHGHGHGH'],\n 'f5': ['ij','IJ','IJIJIJIJ'],\n 'f6': ['kl','KL','KL___KL'],\n 'f7': ['mn','MN','MN123456MN'],\n 'f8': ['op','OP','OPOP'],\n 'f9': ['qr','QR','QRqrQRqr'],\n 'f10': ['st','ST','STSTstST']\n }\n\n with open ('spec.json','r') as jf:\n specs_dict = json.load(jf)\n self.base_config_dict = {col_name:{'length': int(length_val), 'type': str,'default_value' : ''} \n for (col_name,length_val) in zip(specs_dict['ColumnNames'], specs_dict['Offsets'])}\n\n self.base_tc_isntance = FWF2CSV(self.base_test_case,self.base_config_dict)\n\n \n def tearDown(self):\n print('tearDown\\n')\n \n def test_fix_dict(self):\n tc_1 = {\n 'f1': ['ab','AB',12345678],\n 'f2': [1],\n 'f3': ['ef','EF'],\n }\n\n config_1 = {\n 'f1': {'length': 5, 'type': str, 'default_value' : ''},\n 'f2': {'length': 12, 'type': int, 'default_value' : -1},\n 'f3': {'length': 3, 'type': str, 'default_value' : ''}\n }\n\n EA_1 = {\n 'f1': ['ab','AB',12345678],\n 'f2': [1,-1,-1],\n 'f3': ['ef','EF',''],\n }\n \n self.assertEqual(FWF2CSV.fix_dict(self,tc_1,config_1,3),EA_1)\n \n def test_fix_data_type(self):\n # type f1 from int to str, type f2 from str to int, type f3 from bool to str, \n # length f1 should be cut to 5\n tc_2 = {\n 'f1': 12345678,\n 'f2': '1',\n 'f3': True,\n }\n\n config_2 = {\n 'f1': {'length': 5, 'type': str, 'default_value' : ''},\n 'f2': {'length': 12, 'type': int, 'default_value' : -1},\n 'f3': {'length': 6, 'type': str, 'default_value' : ''}\n }\n\n EA_2 = {\n 'f1': '12345',\n 'f2': 1,\n 'f3': 'True',\n } \n\n self.assertEqual(FWF2CSV.fix_data_type(FWF2CSV(tc_2,config_2),tc_2,config_2),EA_2)\n\n def test_fix_cols_type(self):\n # f1 is a string and can't be converted to int\n tc_3 = {\n 'f1': 'ab',\n 'f2': '1',\n }\n\n config_3_1 = {\n 'f1': {'length': 5, 'type': int, 'default_value' : ''},\n 'f2': {'length': 12, 'type': int, 'default_value' : -1},\n }\n\n self.assertRaises( (TypeError,ValueError),FWF2CSV.fix_cols_type(self,tc_3,config_3_1))\n\n config_3_2 = {\n 'f1': {'length': 5, 'type': float, 'default_value' : ''},\n 'f2': {'length': 12, 'type': int, 'default_value' : -1},\n }\n self.assertRaises( (TypeError,ValueError),FWF2CSV.fix_cols_type(self,tc_3,config_3_2))\n\n def test_fix_cols_length(self):\n # f1 should be cut to 5 letters. f2 with config_4_1 should be fine\n # but when change the length to 2, 123 can't fit into 2 spaces field, should raise error\n # same with config_4_3 in which f2 column type is float\n tc_4 = {\n 'f1': 'abcdef',\n 'f2': 123,\n }\n\n config_4_1 = {\n 'f1': {'length': 5, 'type': str, 'default_value' : ''},\n 'f2': {'length': 3, 'type': int, 'default_value' : -1},\n }\n\n EA_4 = {\n 'f1': 'abcde',\n 'f2': 123,\n }\n\n self.assertEqual( FWF2CSV.fix_cols_length(self,tc_4,config_4_1),EA_4)\n\n config_4_2 = {\n 'f1': {'length': 5, 'type': str, 'default_value' : ''},\n 'f2': {'length': 2, 'type': int, 'default_value' : -1},\n }\n self.assertRaises( (TypeError,ValueError),FWF2CSV.fix_cols_type(self,tc_4,config_4_2))\n\n config_4_3 = {\n 'f1': {'length': 5, 'type': str, 'default_value' : ''},\n 'f2': {'length': 2, 'type': float, 'default_value' : -1},\n }\n self.assertRaises( (TypeError,ValueError),FWF2CSV.fix_cols_type(self,tc_4,config_4_3))\n\n\n def test_make_new_line(self):\n # should return line in binary format\n tc_5 = {\n 'f1': 'abcde',\n 'f2': 123,\n }\n \n config_5= {\n 'f1': {'length': 7, 'type': str, 'default_value' : ''},\n 'f2': {'length': 3, 'type': int, 'default_value' : -1}\n }\n\n EA_5 = b'abcde 123\\n'\n self.assertEqual(FWF2CSV.make_new_line(self,tc_5,config_5),EA_5)\n\n \n\n def test_break_dict(self):\n tc_6 = {\n 'f1': ['ab','AB','12345'],\n 'f2': [1,0,2],\n 'f3': ['ef','EF','EFG'],\n }\n\n config_6 = {\n 'f1': {'length': 5, 'type': str, 'default_value' : ''},\n 'f2': {'length': 12, 'type': int, 'default_value' : -1},\n 'f3': {'length': 3, 'type': str, 'default_value' : ''}\n }\n\n EA_6 = {'0':{'f1': 'ab', 'f2': 1, 'f3': 'ef'},\n '1':{'f1': 'AB', 'f2': 0, 'f3': 'EF'},\n '2':{'f1': '12345', 'f2': 2, 'f3': 'EFG'}\n }\n\n self.assertEqual(FWF2CSV.break_dict(FWF2CSV(tc_6, config_6), tc_6, config_6), EA_6)\n\n def test_write_file(self):\n # should write file to local directory \n file_name = 'test_new_file.txt'\n FWF2CSV.write_file(self.base_tc_isntance,\n self.base_test_case, self.base_config_dict, file_name=file_name)\n self.assertTrue(os.path.exists(file_name))\n\n def test_chopper(self):\n tc_7 = ' fo 12 bar'\n\n config_7 = {\n 'f1': {'length': 4, 'type': str, 'default_value' : ''},\n 'f2': {'length': 5, 'type': int, 'default_value' : -1},\n 'f3': {'length': 6, 'type': str, 'default_value' : ''}\n }\n EA_7 =[' fo',' 12',' bar']\n self.assertEqual(FWF2CSV.chopper(self,tc_7,config_7),EA_7)\n\n def test_joiner(self):\n tc_8 = [' fo',' 12',' bar']\n\n EA_8 =' fo, 12, bar\\n'\n self.assertEqual(FWF2CSV.joiner(self,tc_8),EA_8) \n\n def test_fwf_2_csv_line(self):\n tc_9 = ' fo 12 bar'\n config_9 = {\n 'f1': {'length': 4, 'type': str, 'default_value' : ''},\n 'f2': {'length': 5, 'type': int, 'default_value' : -1},\n 'f3': {'length': 6, 'type': str, 'default_value' : ''}\n }\n\n EA_9 =' fo, 12, bar\\n'\n self.assertEqual(FWF2CSV.fwf_2_csv_line(FWF2CSV(tc_9,config_9),tc_9,config_9),EA_9) \n\n def test_E2E(self):\n # test case with all kind of problems\n # the file should show correctly in excel while with problem in other utf-8 based apps\n tc_10 = {\n 'f1': ['ab','‘’','AAABBB_B'],# big cell\n 'f2': [12.3,123,True], # incompatible cell type\n 'f3': ['ef','EF','EFFF_FFF'],# big cell\n 'f4': ['gh','','GHGHGHGH'], # empty cell\n 'f5': ['Jânis','El Niño','résumé'],\n 'f6': ['kl','KL'], # missing cell\n 'f7': [10,12,20], # int to float\n 'f8': [12.3,1.23,2.8], # foat to int\n 'f9': ['qr','QR','QRqrQRqr'],\n 'f10': ['st','ST','STSTstST']\n }\n config_10 = {\n 'f1': {'length': 5, 'type': str, 'default_value': ''},\n 'f2': {'length': 12, 'type': str, 'default_value': ''},\n 'f3': {'length': 3, 'type': str, 'default_value': ''},\n 'f4': {'length': 2, 'type': str, 'default_value': ''},\n 'f5': {'length': 13, 'type': str, 'default_value': ''},\n 'f6': {'length': 7, 'type': str, 'default_value': ''},\n 'f7': {'length': 10, 'type': float, 'default_value': ''},\n 'f8': {'length': 13, 'type': int, 'default_value': ''},\n 'f9': {'length': 20, 'type': str, 'default_value': ''},\n 'f10': {'length': 13, 'type': str, 'default_value': ''}\n }\n\n file_name = 'E2E_test_new_file.txt'\n tc_10_insctance = FWF2CSV(tc_10,config_10)\n\n FWF2CSV.write_file(tc_10_insctance,\n tc_10, config_10, file_name=file_name)\n self.assertTrue(os.path.exists(file_name))\n\n \n def test_E2E_csv(self):\n tc_11 = {\n 'f1': ['ab','‘’','AAABBB_B'],# big cell\n 'f2': [12.3,123,True], # incompatible cell type\n 'f3': ['ef','EF','EFFF_FFF'],# big cell\n 'f4': ['gh','','GHGHGHGH'], # empty cell\n 'f5': ['Jânis','El Niño','résumé'],\n 'f6': ['kl','KL'], # missing cell\n 'f7': [10,12,20], # int to float\n 'f8': [12.3,1.23,2.8], # foat to int\n 'f9': ['qr','QR','QRqrQRqr'],\n 'f10': ['st','ST','STSTstST']\n }\n config_11 = {\n 'f1': {'length': 5, 'type': str, 'default_value': ''},\n 'f2': {'length': 12, 'type': str, 'default_value': ''},\n 'f3': {'length': 3, 'type': str, 'default_value': ''},\n 'f4': {'length': 2, 'type': str, 'default_value': ''},\n 'f5': {'length': 13, 'type': str, 'default_value': ''},\n 'f6': {'length': 7, 'type': str, 'default_value': ''},\n 'f7': {'length': 10, 'type': float, 'default_value': ''},\n 'f8': {'length': 13, 'type': int, 'default_value': ''},\n 'f9': {'length': 20, 'type': str, 'default_value': ''},\n 'f10': {'length': 13, 'type': str, 'default_value': ''}\n }\n\n tc_11_instance = FWF2CSV(tc_11,config_11)\n FWF2CSV.fwf_2_csv(tc_11_instance, config_11, \n input_file = 'E2E_test_new_file.txt', output_file = 'E2E_test_new_utf8_file.csv', \n input_encoding = 'cp1252', output_encoding = 'utf-8')\n self.assertTrue(os.path.exists('E2E_test_new_utf8_file.csv')) \n\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_fwf2csv.py","file_name":"test_fwf2csv.py","file_ext":"py","file_size_in_byte":10205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"621020182","text":"# 1. Write each test case in in1, in2, in3, ...\n# 2. Write each output in out1, out2, out3, ...\n# 3. run this file\n\n# Note:\n# This program detects type of program (java, c++, haskell) you have in the current directory.\n# In order to avoid confusion, do NOT put multiple programs in the current directory.\n\nfrom commands import *\nimport time\nimport os\nimport sys\n\n# checking what kind of file the current directly has\ndirectoryContents = getstatusoutput(\"ls\")[1].split()\n\nexecCommand = \"\" \nfor name in directoryContents:\n if \".java\" in name:\n status = getstatusoutput(\"javac \" + name)\n if len(status[1]) > 0:\n print('compilatin error')\n print(status[1])\n sys.exit()\n execCommand = \"java \" + os.path.splitext(name)[0]\n break\n elif \".cpp\" in name:\n status = getstatusoutput(\"g++ \" + name)\n if len(status[1]) > 0:\n print('compilatin error')\n print(status[1])\n sys.exit()\n execCommand = \"./a.out\"\n break\n elif \".hs\" in name:\n execCommand = \"runghc \" + name\n break\n\nAC = True \nnumTests = 0\n\nfor i in range(1, 100):\n try: \n correct = True # whether this program works with this particular testcase\n \n # check the input file exists\n if not os.path.exists(\"in\" + str(i)):\n break\n\n print('test ' + str(i))\n\n # conducting the test\n start = time.clock()\n\n outputInExecution = getstatusoutput(execCommand + \" < in\" + str(i) + \" > ans\" + str(i))\n if len(outputInExecution[1]) > 0:\n print('Error Message')\n print(outputInExecution[1])\n correct = False\n\n\n end = time.clock()\n\n # checking the answer\n\n correctFile = open(\"out\" + str(i), 'r')\n correctOutput = correctFile.readlines()\n\n myanswerFile = open(\"ans\" + str(i), 'r')\n myanswer = myanswerFile.readlines()\n\n\n if len(myanswer) != len(correctOutput):\n print('The number of lines is different.')\n correct = False\n for j in range(min(len(correctOutput), len(myanswer))):\n if myanswer[j] != correctOutput[j]:\n correct = False\n print('correct -> ' + correctOutput[j])\n print('my ans -> ' + myanswer[j])\n AC = AC and correct\n numTests += 1\n\n if correct:\n print('Correct Answer')\n\n # checking the execution time.\n if end - start < 3: # No additional test if it takes too long\n start = time.clock()\n for test in range(5):\n getstatusoutput(execCommand + \" < in\" + str(i))\n end = time.clock()\n print('execution time: ' + str((end - start) / 5) + ' sec')\n\n print('') # print a blank line\n except: \n break\n\nprint(str(numTests) + ' test(s) conducted')\nif AC:\n print('========Passed========')\n\n\n\n","sub_path":"212-2/B-2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"308330400","text":"#!/usr/local/bin/python3\n\nmy_dict = {}\nmy_list = []\n\n###try:\n### my_list[0]\n### my_dict['ip_addr']\n###except (KeyError, IndexError):\n### print(\"Handled multiple potention exceptions\")\n\ntry:\n my_list[0]\n my_dict['ip_addr']\nexcept KeyError:\n print(\"handled KeyError\")\nexcept IndexError:\n print(\"handled IndexError\")\nfinally:\n print(\"finally always executes\")\n\n\n#try:\n#except Exception:\n","sub_path":"lesson4/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"284729768","text":"# Licensed to the StackStorm, Inc ('StackStorm') under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport mock\n\nfrom st2common.models.db.trigger import TriggerDB\nfrom st2common.transport.publishers import PoolPublisher\nimport st2reactor.container.utils as container_utils\nfrom st2tests.base import CleanDbTestCase\n\nMOCK_TRIGGER_TYPE = {}\nMOCK_TRIGGER_TYPE['id'] = 'trigger-type-test.id'\nMOCK_TRIGGER_TYPE['name'] = 'trigger-type-test.name'\nMOCK_TRIGGER_TYPE['pack'] = 'dummy_pack_1'\nMOCK_TRIGGER_TYPE['parameters_schema'] = {}\nMOCK_TRIGGER_TYPE['payload_schema'] = {}\n\nMOCK_TRIGGER = TriggerDB()\nMOCK_TRIGGER.id = 'trigger-test.id'\nMOCK_TRIGGER.name = 'trigger-test.name'\nMOCK_TRIGGER.pack = 'dummy_pack_1'\nMOCK_TRIGGER.parameters = {}\nMOCK_TRIGGER.type = 'dummy_pack_1.trigger-type-test.name'\n\n\n@mock.patch.object(PoolPublisher, 'publish', mock.MagicMock())\nclass ContainerUtilsTest(CleanDbTestCase):\n\n def test_create_trigger_instance_invalid_trigger(self):\n trigger_instance = 'dummy_pack.footrigger'\n instance = container_utils.create_trigger_instance(trigger_instance, {}, None)\n self.assertTrue(instance is None)\n","sub_path":"st2reactor/tests/unit/test_container_utils.py","file_name":"test_container_utils.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"415726839","text":"# 336. Palindrome Pairs\n\n\n# 2021/03/04\n# Runtime: 864 ms, faster than 29.66% of Python3 online submissions for Palindrome Pairs.\n# Memory Usage: 20.7 MB, less than 21.14% of Python3 online submissions for Palindrome Pairs.\n\n# 字典树高难度题,看了官方解答研究了很久才写出来\n# 回文串主要有两种pattern = word1 + word2\n# pattern 1 = ABC + LOLCBA\n# pattern 2 = ABCLOL + CBA\n# 假设我们遍历数组中的word1, 对于每个word1我们用字典树来找满足回文条件的word2。\n# 那么对应这两种情况,word2分别是1、回文串 + word1 逆序字符串;2、word1前缀的逆序字符串\n# 由于我们要找逆序字符串,再创建字典树时我们将每个单词的逆序词存入字典树\n# case 1: 找更长的字符串 = word1 + 回文串 (注意单词在字典树中是逆序放置的)\n# case 2: 找更短的字符串 = word1的某个前缀,即要找到某个word2, 使得 word1 = word2 + 回访串\n# 注1:在字典树结点中,ending word代表这个单词在原单词数组中的位置,如果是-1, 表示这不是一个单词\n# 注2:在字典树结点中,palindrome_suffixes存放的是逆序词在这个结点后面回文串的情况,下面举例说明\n# 假设字典树中有如下单词 eff, egg\n# 在结点e中,后面有两个回文子串ff和gg,于是palindrome_suffixes = [0,1],其中0, 1分别代表的是eff, egg在词表中的位置\n# 也就是说如果某个单词在某个结点处后面子串是回文串的话,那么就将这个单词在词表中的位置存到palindrome_suffixes中\n# 注3:由于空字符串无法保存在字典树中,导致在对待空字符串时要分开处理。这是个比较简单的edge case.根据我们set up,如果空字符串存在的话,\n# 那么整棵字典树树根的ending word 就是这个空串在词组中的位置。\n\n\n\nclass Solution:\n def palindromePairs(self, words: List[str]) -> List[List[int]]:\n # case 1: ABC + LOLCBA\n # case 2: ABCLOL + CBA, where LOL could be empty\n # case 3: ABBA + \"\"\n trie = Trie()\n\n for i, word in enumerate(words):\n trie.insert(word[::-1], i) # insert word and palindrome_suffixes\n empty_index = trie.root.ending_word # postion of empty string\n ans = []\n for i, word in enumerate(words):\n # case 1: pattern = reverse + palindrome_suffixes\n palindrome_suffixes = trie.search_longer(word)\n for j in palindrome_suffixes:\n if i == j: continue\n ans.append([i, j])\n # case 2: pattern = word1 - palindrome\n prefixes = trie.search_shorter(word)\n for j in prefixes:\n if i == j: continue\n ans.append([i, j])\n # case 3: pattern = palindrome + \"\"\n if empty_index > -1 and i != empty_index and word == word[::-1]:\n ans.append([i, empty_index])\n return ans\n\n\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.ending_word = -1 # index of the word in words array, default: not word\n self.palindrome_suffixes = []\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, word, i):\n node = self.root\n for j, w in enumerate(word):\n # if word itself is palindrome, save it to palindrome_suffixes of the root\n if word[j:] == word[j:][::-1]:\n node.palindrome_suffixes.append(i)\n if w not in node.children:\n node.children[w] = TrieNode()\n node = node.children[w]\n\n node.ending_word = i\n\n def search_longer(self, word):\n node = self.root\n for w in word:\n if w not in node.children:\n return []\n node = node.children[w]\n return node.palindrome_suffixes\n\n def search_shorter(self, word):\n # pattern = ABC + CBA is covered in this case\n ans = []\n node = self.root\n for j, w in enumerate(word):\n if w not in node.children:\n return ans\n node = node.children[w]\n if node.ending_word == -1: continue\n if word[j+1:] == word[j+1:][::-1]:\n ans.append(node.ending_word)\n return ans","sub_path":"0336. Palindrome Pairs.py","file_name":"0336. Palindrome Pairs.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"551899085","text":"from os import listdir\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider\nimport numpy as np\n\nimport config\n\n\nplt.ion()\n\n\n# create a figure with two subplots\nfig, (ax1, ax2) = plt.subplots(2, 1)\n\n# ECG y axis\necg_y_min = 0\necg_y_max = 100\n\n# ACC y axis\nacc_y_min = 0\nacc_y_max = 100\n\n# intialize two line objects (one in each axes)\nline1 = None\nline2 = None\n\n# Slider\necg_spos = None\nacc_spos = None\n\n# Slider pos\naxcolor = 'lightgoldenrodyellow'\n\n\ndef update_ecg(ecg):\n global line1, ecg_spos, ecg_y_min, ecg_y_max\n if line1 is None:\n line1, = ax1.plot(ecg, lw=2, color=\"green\")\n ecg = np.array(ecg)\n line1.set_ydata(ecg)\n line1.set_xdata(range(len(ecg)))\n ecg_y_min = ecg.min()\n ecg_y_max = ecg.max()\n ax1.set_ylim(ecg_y_min - 100, ecg_y_max + 100)\n axpos = plt.axes([0.2, 0.47, 0.65, 0.01])\n ecg_spos = Slider(axpos, 'ECG', 0, len(ecg), valstep=1, valfmt=\"%d\")\n\ndef update_acc(acc):\n global line2, acc_spos, acc_y_min, acc_y_max\n if line2 is None:\n line2, = ax2.plot(acc, lw=2, color=\"red\")\n acc = np.array(acc)\n line2.set_ydata(acc)\n line2.set_xdata(range(len(acc)))\n acc_y_min = acc.min()\n acc_y_max = acc.max()\n ax2.set_ylim(acc_y_min - 100, acc_y_max + 100)\n axpos = plt.axes([0.2, 0.05, 0.65, 0.01])\n acc_spos = Slider(axpos, 'ACC', 0, len(acc), valstep=1, valfmt=\"%d\")\n\ndef update():\n global ecg_spos, ax1, ecg_y_min, ecg_y_max, acc_spos, ax2, acc_y_min, acc_y_max\n\n ecg_pos = ecg_spos.val\n ax1.axis([ecg_pos, ecg_pos + 1200, ecg_y_min - 100, ecg_y_max + 100])\n\n acc_pos = acc_spos.val\n ax2.axis([acc_pos, acc_pos + 900, acc_y_min - 100, acc_y_max + 100])\n\n fig.canvas.draw_idle()\n fig.canvas.flush_events()\n\n\n\n\nif __name__ == \"__main__\":\n from s3_handler import S3Handler\n from file_handler import FileHandler\n\n fh = FileHandler(config.data['location'])\n handler = S3Handler()\n handler.download_all_data()\n\n ecg_signal = []\n acc_signal = []\n for filename in listdir(config.data['location']):\n _, data_type = filename.split(\"-\")\n signal = fh.load_signal(filename)\n if data_type == \"ECG\":\n ecg_signal.extend(signal)\n elif data_type == \"ACC\":\n acc_signal.extend(signal)\n\n update_ecg(ecg_signal)\n update_acc(acc_signal)\n\n\n while True:\n update()\n","sub_path":"graph_visualizer.py","file_name":"graph_visualizer.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"637196402","text":"# Copyright (c) 2016 The University of Manchester\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom spinn_utilities.progress_bar import ProgressBar\nfrom spinn_machine import MulticastRoutingEntry\nfrom pacman.data import PacmanDataView\nfrom pacman.model.routing_tables import (\n UnCompressedMulticastRoutingTable, MulticastRoutingTables)\n\n\ndef basic_routing_table_generator():\n \"\"\"\n An basic algorithm that can produce routing tables.\n\n :rtype: MulticastRoutingTables\n \"\"\"\n routing_infos = PacmanDataView.get_routing_infos()\n routing_table_by_partitions = (\n PacmanDataView.get_routing_table_by_partition())\n progress = ProgressBar(\n routing_table_by_partitions.n_routers, \"Generating routing tables\")\n routing_tables = MulticastRoutingTables()\n for x, y in progress.over(routing_table_by_partitions.get_routers()):\n parts = routing_table_by_partitions.get_entries_for_router(x, y)\n routing_tables.add_routing_table(__create_routing_table(\n x, y, parts, routing_infos))\n\n return routing_tables\n\n\ndef __create_routing_table(x, y, partitions_in_table, routing_infos):\n \"\"\"\n :param int x:\n :param int y:\n :param partitions_in_table:\n :type partitions_in_table:\n dict(((ApplicationVertex or MachineVertex), str),\n MulticastRoutingTableByPartitionEntry)\n :param RoutingInfo routing_infos:\n :rtype: MulticastRoutingTable\n \"\"\"\n table = UnCompressedMulticastRoutingTable(x, y)\n for source_vertex, partition_id in partitions_in_table:\n r_info = routing_infos.get_routing_info_from_pre_vertex(\n source_vertex, partition_id)\n entry = partitions_in_table[source_vertex, partition_id]\n table.add_multicast_routing_entry(\n __create_entry(r_info.key_and_mask, entry))\n\n return table\n\n\ndef __create_entry(key_and_mask, entry):\n \"\"\"\n :param BaseKeyAndMask key_and_mask:\n :param MulticastRoutingTableByPartitionEntry entry:\n :rtype: MulticastRoutingEntry\n \"\"\"\n return MulticastRoutingEntry(\n routing_entry_key=key_and_mask.key_combo,\n defaultable=entry.defaultable, mask=key_and_mask.mask,\n link_ids=entry.link_ids, processor_ids=entry.processor_ids)\n","sub_path":"pacman/operations/routing_table_generators/basic_routing_table_generator.py","file_name":"basic_routing_table_generator.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"581257496","text":"import cv2\nimport numpy as np\nimport time\n\n# Create a VideoCapture object\ncap = cv2.VideoCapture(0)\n\n# Check if camera opened successfully\nif (cap.isOpened() == False): \n print(\"Unable to read camera feed\")\n\ncapture_duration =5\nwaittime = 4\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\n# ช่วงรอเวลา 3 วินาที\n# รอเวลา 3 วินาที\nstart_time = time.time()\n\nwhile(int(time.time() - start_time) < waittime):\n ret, frame = cap.read()\n if ret == True:\n\n text = str('{} {}'.format('Ready to record in ',int(np.subtract(time.time(),start_time))))\n cv2.putText(frame, text, (0,int((frame.shape[0]/2)+((frame.shape[0]/2)*(-0.8)))), font, 2, (255, 255, 255), 10)\n\n cv2.imshow('wait',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# ช่วงบันทึกวิดิโอ\nframe_width = int(cap.get(3))\nframe_height = int(cap.get(4))\nout = cv2.VideoWriter('outpy.mp4',cv2.VideoWriter_fourcc('M','J','P','G'), 30, (frame_width,frame_height))\nstart_time = time.time()\n\nwhile(int(time.time() - start_time) < capture_duration):\n # print(int(time.time() - start_time))\n ret, frame = cap.read()\n frame_copy = frame.copy()\n if ret == True: \n\n text = str('{} {}'.format('Recording.. ',int(np.subtract(time.time(),start_time))))\n cv2.putText(frame_copy, text, (0,int((frame_copy.shape[0]/2)+((frame_copy.shape[0]/2)*(-0.8)))), font, 2, (255, 255, 255), 10)\n \n out.write(frame)\n # Display the resulting frame \n cv2.imshow('record',frame_copy)\n\n # Press Q on keyboard to stop recording\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break \n\n# When everything done, release the video capture and video write objects\ncap.release()\nout.release()\n\n# Closes all the frames\ncv2.destroyAllWindows() \n","sub_path":"IoT/scr/research/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"418804712","text":"import glob\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib \r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport numpy as np\r\nimport math\r\nimport json\r\nimport datetime\r\nimport matplotlib.dates as mdates\r\nimport os.path\r\nimport pickle\r\nimport time\r\nimport matplotlib.dates as mdates\r\nfrom matplotlib.font_manager import FontProperties\r\n\r\nsns.set(context='paper', style={'axes.axisbelow': True,\r\n 'axes.edgecolor': '.8',\r\n 'axes.facecolor': 'white',\r\n 'axes.grid': True,\r\n 'axes.labelcolor': '.15',\r\n 'axes.linewidth': 0.5,\r\n 'figure.facecolor': 'white',\r\n 'font.family': [u'sans-serif'],\r\n 'font.sans-serif': [u'Abel'],\r\n 'font.weight' : u'light',\r\n 'grid.color': '.8',\r\n 'grid.linestyle': u'-',\r\n 'image.cmap': u'Greys',\r\n 'legend.frameon': True,\r\n 'legend.numpoints': 1,\r\n 'legend.scatterpoints': 1,\r\n 'lines.solid_capstyle': u'butt',\r\n 'text.color': '.15',\r\n 'xtick.color': '.8',\r\n 'xtick.direction': u'out',\r\n 'xtick.major.size': 0.0,\r\n 'xtick.minor.size': 0.0,\r\n 'ytick.color': '.8',\r\n 'ytick.direction': u'out',\r\n 'ytick.major.size': 0.0,\r\n 'ytick.minor.size': 0.0}, font_scale = 1.2)\r\n\r\nflatui = ['#28aad5', '#b24d94', '#38ae97' ,'#ec7545']\r\n\r\ndatasetname = { 'T-Test' : {1000 : 'rand_1k', 5000: 'rand_5k', 10000: 'rand_10k', 4177: 'Abalone'},\r\n 'Pearson' : {1000 : 'rand_1k', 5000: 'rand_5k', 10000: 'rand_10k', 4177: 'Abalone'}, \r\n 'Chi-Squared' : {1000 : 'cat_1k', 5000: 'cat_5k', 10000: 'cat_10k', 108: 'Pittsburgh'}}\r\n\r\nsortorder = { 'T-Test' : {1000 : '1', 5000: '2', 10000: '3', 4177: '0'},\r\n 'Pearson' : {1000 : '1', 5000: '2', 10000: '3', 4177: '0'}, \r\n 'Chi-Squared' : {1000 : '1', 5000: '2', 10000: '3', 108: '0'}}\r\n\r\n\r\ndef runtime_bar(type, data, showCategoriesLabel, show, size, fn = None):\r\n comptime = {}\r\n divtime = {}\r\n \r\n numParties = []\r\n NumRowss = []\r\n categories = {}\r\n \r\n #prefill\r\n for d in data:\r\n if d['Test'] == type:\r\n if d['NumRows'] not in NumRowss:\r\n NumRowss.append(d['NumRows'])\r\n comptime[d['NumRows']] = {}\r\n divtime[d['NumRows']] = {}\r\n categories[d['NumRows']] = []\r\n \r\n if d['NumParties'] not in numParties:\r\n numParties.append(d['NumParties'])\r\n \r\n if d['NumCols'] not in categories[d['NumRows']]:\r\n categories[d['NumRows']].append(d['NumCols'])\r\n \r\n if d['NumParties'] not in comptime[d['NumRows']]:\r\n comptime[d['NumRows']][d['NumParties']] = {}\r\n divtime[d['NumRows']][d['NumParties']] = {} \r\n\r\n if d['NumCols'] not in comptime[d['NumRows']][d['NumParties']]:\r\n comptime[d['NumRows']][d['NumParties']][d['NumCols']] = []\r\n divtime[d['NumRows']][d['NumParties']][d['NumCols']] = [] \r\n \r\n for d in data:\r\n if d['Test'] == type:\r\n comptime[d['NumRows']][d['NumParties']][d['NumCols']].append(d['ComputeRuntime'])\r\n divtime[d['NumRows']][d['NumParties']][d['NumCols']].append(d['DivRuntime'])\r\n \r\n print(categories) \r\n width = 0.24 \r\n gap = 0.02\r\n f, (ax1) = plt.subplots(1, 1, sharey=False, figsize=size)\r\n numParties = sorted(numParties)\r\n NumRowss = sorted(NumRowss)\r\n NumRowss = sorted(NumRowss, key=lambda k: sortorder[type][k]) \r\n print(NumRowss)\r\n \r\n xLabels = {}\r\n p1 = None\r\n p2 = None\r\n ccc = 0\r\n for ds, NumRows in enumerate(NumRowss): \r\n xLabels[NumRows] = {} \r\n for c, category in enumerate(sorted(categories[NumRows])): \r\n xLabels[NumRows][category] = []\r\n idx = ccc #ds * len(categories[NumRows]) + c \r\n ccc = ccc + 1\r\n \r\n for p, numParty in enumerate(numParties): \r\n mean_comp = np.array(comptime[NumRows][numParty][category]).mean() \r\n std_comp = np.array(comptime[NumRows][numParty][category]).std()\r\n mean_div = np.array(divtime[NumRows][numParty][category]).mean()\r\n std_div = np.array(divtime[NumRows][numParty][category]).std()\r\n #current_in\r\n total_width = width * len(numParties) + gap * (len(numParties) - 1)\r\n pos = (idx - total_width / 2 + width / 2) + width * p + gap * p\r\n \r\n xLabels[NumRows][category].append((pos, numParty))\r\n \r\n p1 = ax1.bar(pos, mean_comp, width, yerr=std_comp, color=flatui[1], hatch='//') \r\n p2 = ax1.bar(pos, mean_div, width, bottom=mean_comp, yerr=std_div, color=flatui[0])\r\n \r\n # label\r\n axis_to_data = ax1.transAxes + ax1.transData.inverted()\r\n data_to_axis = axis_to_data.inverted()\r\n width_trans = data_to_axis.transform([width / 2, 0])[0]\r\n cat_yoff = -.20\r\n ds_yoff = -.30\r\n leftmost = 1000\r\n if not showCategoriesLabel:\r\n ds_yoff = cat_yoff\r\n pa_yoff = -.1\r\n \r\n for ds in xLabels: \r\n all_xpos = []\r\n min_xpos = []\r\n max_xpos = []\r\n for cat in xLabels[ds]: \r\n cat_all_xpos = []\r\n cat_min_xpos = []\r\n cat_max_xpos = []\r\n for p in xLabels[ds][cat]:\r\n xpos = data_to_axis.transform([p[0], 0])[0]\r\n \r\n all_xpos.append(xpos)\r\n min_xpos.append(data_to_axis.transform([p[0] - width / 2, 0])[0])\r\n max_xpos.append(data_to_axis.transform([p[0] + width / 2, 0])[0])\r\n \r\n cat_all_xpos.append(xpos)\r\n cat_min_xpos.append(data_to_axis.transform([p[0] - width / 2, 0])[0])\r\n cat_max_xpos.append(data_to_axis.transform([p[0] + width / 2, 0])[0])\r\n \r\n ax1.text(xpos, pa_yoff, str(p[1]), ha='center', fontsize=11, transform=ax1.transAxes) \r\n if showCategoriesLabel:\r\n xpos = np.array(cat_all_xpos).mean()\r\n ax1.text(xpos, cat_yoff, str(cat), ha='center', fontsize=11, transform=ax1.transAxes)\r\n xpos = np.array(cat_min_xpos).min() \r\n plt.plot([xpos, xpos], [0, cat_yoff], 'k-', lw=1.0, color='.8', clip_on=False, transform=ax1.transAxes)\r\n xpos = np.array(cat_max_xpos).max()\r\n plt.plot([xpos, xpos], [0, cat_yoff], 'k-', lw=1.0, color='.8', clip_on=False, transform=ax1.transAxes)\r\n \r\n \r\n xpos = np.array(all_xpos).mean()\r\n dsName = datasetname[type][ds]\r\n ax1.text(xpos, ds_yoff, dsName, ha='center', fontsize=11, transform=ax1.transAxes)\r\n xpos = np.array(min_xpos).min() \r\n leftmost = min(leftmost, xpos)\r\n plt.plot([xpos, xpos], [0, ds_yoff], 'k-', lw=2.5, color='.8', clip_on=False, transform=ax1.transAxes)\r\n xpos = np.array(max_xpos).max()\r\n plt.plot([xpos, xpos], [0, ds_yoff], 'k-', lw=2.5, color='.8', clip_on=False, transform=ax1.transAxes)\r\n\r\n ax1.text(leftmost-0.005, pa_yoff, '# parties:', ha='right', fontsize=11, transform=ax1.transAxes)\r\n ax1.text(leftmost-0.005, ds_yoff, 'dataset:', ha='right', fontsize=11, transform=ax1.transAxes)\r\n if showCategoriesLabel:\r\n ax1.text(leftmost-0.005, cat_yoff, '# categories:', ha='right', fontsize=11, transform=ax1.transAxes)\r\n \r\n f.subplots_adjust(bottom=0.3)\r\n plt.xticks([])\r\n ax1.xaxis.grid(False)\r\n ymin, ymax = ax1.get_ylim()\r\n ax1.set_ylim([ymin, ymax * 1.3])\r\n ax1.set_ylabel('time in seconds')\r\n #formatter = matplotlib.ticker.FuncFormatter(lambda ms, x: time.strftime('%M:%S', time.gmtime(ms)))\r\n #ax1.yaxis.set_major_formatter(formatter)\r\n \r\n plt.legend((p1[0], p2[0]), ('local + interactive computations', 'division computation'))\r\n plt.setp(ax1.get_xticklabels(), color=\".15\")\r\n plt.setp(ax1.get_yticklabels(), color=\".15\")\r\n \r\n mode = 'shares'\r\n #if shares:\r\n # mode = 'shares'\r\n if fn is None:\r\n f.savefig('fig/runtime_' + type.lower() + '_' + mode + '.pdf', bbox_inches='tight')\r\n else:\r\n f.savefig('fig/runtime_' + fn + '.pdf', bbox_inches='tight')\r\n \r\n \r\n if show:\r\n plt.show() \r\n \r\n \r\n \r\n\r\nif __name__== \"__main__\":\r\n show = True\r\n \r\n all_runs = []\r\n for filename in glob.glob(\"../results/*.json\"):\r\n with open(filename) as f:\r\n data = json.load(f)\r\n all_runs.append(data)\r\n \r\n for d in all_runs:\r\n if d['Test'] == 'T-Test' and d['NumParties'] == 16 and d['NumRows'] == 10000:\r\n print (d['DivRuntime'])\r\n \r\n runtime_bar('Chi-Squared', all_runs, True, show, (14, 4)) \r\n runtime_bar('T-Test', all_runs, False, show, (6, 4))\r\n runtime_bar('Pearson', all_runs, False, show, (6, 4))\r\n\r\n runtime_bar('Chi-Squared', [x for x in all_runs if x['NumCols'] == 5 or x['NumCols'] == 4], True, show, (6, 4), 'chi_5') \r\n runtime_bar('Chi-Squared', [x for x in all_runs if x['NumCols'] == 10], True, show, (6, 4), 'chi_10') \r\n runtime_bar('Chi-Squared', [x for x in all_runs if x['NumCols'] == 20], True, show, (6, 4), 'chi_20') \r\n \r\n ","sub_path":"cmd/scripts/analysis_mult_bar.py","file_name":"analysis_mult_bar.py","file_ext":"py","file_size_in_byte":9368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"381978828","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 8 20:11:31 2019\n\n@author: truejefs\nCopyright (c) 2019 truejefs\n\"\"\"\n\nfrom xlrd import open_workbook, xldate_as_tuple\nfrom os.path import splitext\n\nSTART_ROW=1\nEmployee_column=0\n\n\nfile_path=\"C:/Python_Scripts/ExcellRead/ExcellRead.xlsx\"\n\nwith open_workbook(file_path) as rb: #Using a with clause to ensure the workbook is closed in case the code crashes.\n r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file\n \n employee=\"Jack\"\n \n for row_index in range(START_ROW, r_sheet.nrows): #searching for the employee\n if r_sheet.cell_value(row_index,Employee_column) == employee:\n for col_index in range(Employee_column+1, r_sheet.ncols): #printing data\n day=xldate_as_tuple(r_sheet.cell_value(0,col_index), rb.datemode)\n day=str(day[2]) + '/' + str(day[1]) + '/' + str(day[0])\n print(day + \": \" + r_sheet.cell_value(row_index,col_index))\n continue\n elif row_index == r_sheet.nrows:\n print('Employee not found')\n","sub_path":"Excelread.py","file_name":"Excelread.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"173005609","text":"\"\"\"\nAd-hoc utility functions\n\"\"\"\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport importlib\nimport pkgutil\nimport datetime as datetime\nfrom xlrd.xldate import xldate_as_tuple\nfrom dateutil.relativedelta import relativedelta\nimport calendar\nimport requests\nimport log\nimport os\nimport pyodbc\n\nimport time\n\nfrom IPython.core.display import display\n\n#==============================================================================\n# Default data directory\n#==============================================================================\n\n_pkg_dir = os.path.dirname(os.path.abspath(__file__))\n_root_dir = os.path.split(_pkg_dir )[0]\n\ndata_dir = os.path.join(_root_dir, 'data')\nraw_dir = os.path.join(_root_dir, 'raw')\ntemp_dir = os.path.join(_root_dir, 'temp')\n\ndef datapath(*p):\n return os.path.join(data_dir, *p)\n\ndef rawpath(*p):\n return os.path.join(raw_dir, *p)\n\ndef tmppath(*p):\n return os.path.join(temp_dir, *p)\n\ndef filepath(f=None):\n\n if f is None:\n return os.getcwd()\n\n try:\n foo = os.path.dirname(os.path.realpath(f))\n except NameError:\n foo = os.getcwd()\n return foo\n\n#==============================================================================\n# Parameter wrapping utilities\n#==============================================================================\ndef tolist(obj):\n \"\"\"\n wraps to a list if not already a list\n \"\"\"\n if obj is None:\n return []\n\n if not isinstance(obj, list):\n return [obj]\n else:\n return obj\n\n\ndef list2csvstr(a, sep=','):\n if isinstance(a, str) or isinstance(a, unicode):\n results = a\n else: #assumes a list is passed\n results = sep.join(a)\n\n return results\n\n#==============================================================================\n# Date utilities\n#==============================================================================\n\ndef _dateconv(d):\n # just use the pandas one...\n\n return pd.datetools.to_datetime(d, infer_datetime_format=True).date()\n\ndef date2iso(d):\n \"\"\"\n :param d: date representation in some format (see _dateconv)\n :return: isoformat of date\n \"\"\"\n return _dateconv(d).isoformat()\n\ndef date2date(d):\n \"\"\"\n :param d: date representation in some format (see _dateconv)\n :return: date object\n \"\"\"\n\n return _dateconv(d)\n\ndef datestr(d):\n if isinstance(d, datetime.date):\n return d.strftime('%Y-%m-%d')\n\n # Assume str now\n if d.find('-')<0: #insert dashes\n return d[:4] + '-' + d[4:6] + '-' + d[6:]\n\n return d\n\ndef datedt(d):\n return pd.Timestamp(d).to_datetime()\n\ndef eomonth(d, n=0):\n # returns the last day of the month from d, with offset n (in months)\n # basically same as excel function\n\n d = date2date(d) + relativedelta(months=n)\n\n # figure out the last day\n mr = calendar.monthrange(d.year, d.month)\n\n return datetime.date(d.year, d.month, mr[1])\n\ndtdecade = lambda x: np.floor(x.year/10)*10\ndtsemidecade = lambda x: np.floor(x.year/5)*5\n\n#==============================================================================\n# Numeric utilities\n#==============================================================================\n\ndef sones(index):\n \"\"\"\n Generates a series of ones with given index\n :param index:\n :return:\n \"\"\"\n\n return pd.Series(1, index=index)\n\n\ndef dfones(index, columns):\n \"\"\"\n Generates a dataframe of ones with a given index/columns\n :param index:\n :param columns:\n :return:\n \"\"\"\n return pd.DataFrame(1, index=index, columns=columns)\n\n\n\n#==============================================================================\n# Plotting utilities\n#==============================================================================\ndef pltstr(obj, ax, fz=9, x=0.5, y=0, ha='center', va='bottom'):\n \"\"\"\n Plots a table on figure (requires latex)\n TODO: Remove this with 0.19 pandas\n \"\"\"\n if isinstance(obj, pd.DataFrame):\n fmt = lambda x: '%.2f' % x\n textstr = obj.to_latex(float_format=fmt).replace('\\n', ' ')\n else:\n textstr = obj.replace('_', '\\_')\n\n ax.set_frame_on(False)\n ax.axes.get_xaxis().set_visible(False)\n ax.axes.get_yaxis().set_visible(False)\n plt.text(x, y, textstr, size=fz, ha=ha, va=va)\n\ndef figc():\n plt.close(\"all\")\n\ndef fig():\n plt.rcParams['font.size'] = 9\n plt.figure(figsize=(6, 4), facecolor='w', edgecolor='w')\n return plt.gca()\n\ndef figpage():\n plt.rcParams['font.size'] = 9\n plt.figure(figsize=(8.5, 11), facecolor='w', edgecolor='w')\n return plt.gca()\n\ndef figl():\n plt.rcParams['font.size'] = 9\n plt.figure(figsize=(8.5, 4.5), facecolor='w', edgecolor='w')\n return plt.gca()\n\ndef figs():\n plt.rcParams['font.size'] = 9\n plt.figure(figsize=(4.25, 3), facecolor='w', edgecolor='w')\n return plt.gca()\n\ndef plot_table(df,ax=None,loc='center',round=2,**kwargs):\n if ax is None: ax = figl()\n\n if round > 0:\n try:\n df = np.round(df.astype(np.double),round)\n except:\n for i in range(df.shape[0]):\n for j in range(df.shape[1]):\n try:\n df.iloc[i,j] = np.round(df.iloc[i,j],round)\n except:\n pass\n\n pd.tools.plotting.table(ax, df, loc=loc, **kwargs)\n plt.axis('off')\n\n return ax\n\ndef colorpreview(map='jet', n=5, start=0, end=1):\n # shows a preview of a colormap\n\n x=np.linspace(0,10)\n phase = np.linspace(0, np.pi, n)\n\n ax = figl()\n\n color_idx = np.linspace(start, end, n)\n for i, shift in zip(color_idx, phase):\n ax.plot(x, np.sin(x-shift), color=getattr(plt.cm, map)(i), lw=2)\n\n return None\n\ndef colormap(map='jet', n=5, start=0, end=1):\n\n ii = np.linspace(start, end, n)\n\n cmap = [getattr(plt.cm, map)(i) for i in ii]\n\n return cmap\n\n\ndef simpleaxis(ax, hide='right'):\n ax.grid(False)\n ax.spines['top'].set_visible(False)\n ax.spines[hide].set_visible(False)\n ax.get_xaxis().tick_bottom()\n if hide=='right':\n ax.get_yaxis().tick_left()\n elif hide=='left':\n ax.get_yaxis().tick_right()\n\n#==============================================================================\n# Date utilities\n#==============================================================================\ndef pafactor(R):\n \"\"\"\n Returns per annum factor for a given series/table\n \"\"\"\n if R.index.freq=='B':\n return 260.0\n if R.index.freq=='W':\n return 52.0\n if R.index.freq=='BM':\n return 12.0\n if R.index.freq=='M':\n return 12.0\n if R.index.freq=='A':\n return 1.0\n\n return float(len(pd.date_range('2000', '2010', freq=R.index.freq))/10) \n\n#==============================================================================\n# Return Utilities\n#==============================================================================\n\nlogdiff = lambda x: np.log(x).diff()\nddiff = lambda x: x.div(x.shift(1))-1.0\n\nlogint = lambda x: x.apply(np.exp).cumprod()\ndint = lambda x: (1.0+x).cumprod()\n\ncompret = lambda x: reduce(lambda r1, r2: (1+r1)*(1+r2)-1, x)\n\n#==============================================================================\n# Australian Utilities\n#==============================================================================\ndef ozfutmv(screenpx, yrs):\n i = (100-screenpx) / 200\n v = 1 / (1+i)\n n = yrs * 2\n c = 6 / 2\n P = 1000 * ( c * (1.0-v ** n) / i + 100 * v ** n )\n return P\n\n\n#==============================================================================\n# Excel Utilities\n#==============================================================================\n\ndef xldate(list):\n \"\"\"\n Returns excel dates\n \"\"\"\n return [datetime.datetime(*xldate_as_tuple(x, 0)) for x in list]\n\n\ndef read_range(io, rangename, indexcol=None):\n \"\"\"\n Note: Since Excel spreadsheets don't really have data types, the Excel driver uses the first 8 rows\n to determine what data type to assign to each. The majority type in the first 8 rows determines the type.\n If the majority of the first 8 rows are floats, all strings in this column will be returned as NAN\n\n :param io: filepath\n :param rangename: named range to return\n :param indexcol: optional - set a column as the index\n :rtype: pd.DataFrame\n \"\"\"\n assert os.path.exists(io)\n\n # query parameters\n CNXNSTRING = 'Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;READONLY=TRUE' % io\n QUERY = 'SELECT * FROM {}'.format(rangename)\n\n # establish connection, query results\n cnxn = pyodbc.connect(CNXNSTRING, autocommit=True)\n df = pd.read_sql(QUERY, cnxn)\n df.dropna(how='all', inplace=True)\n\n # format results\n if isinstance(indexcol, int):\n colname = df.iloc[:,indexcol].name\n df.set_index(colname, drop=True, inplace=True)\n elif isinstance(indexcol, str):\n df.set_index(indexcol, drop=True, inplace=True)\n\n return df\n\n\n#==============================================================================\n# Risk utilities\n#==============================================================================\ndef cov2corr(cov):\n \"\"\"\n Return correlation matrix and volatility vector of given covariance matrix\n \"\"\"\n vol = np.sqrt(np.diag(cov))\n if isinstance(cov, pd.DataFrame):\n corr = cov.div(vol, axis=0).div(vol, axis=1)\n vol = pd.Series(vol, index=cov.index)\n else: # numpy arrays\n corr = cov / vol / vol[:, np.newaxis]\n\n return corr, vol\n\ndef corr2cov(corr, vol):\n \"\"\"\n Returns covariance matrix for given correlation matrix, vol vector\n \"\"\"\n cov = np.diag(vol).dot(corr).dot(np.diag(vol))\n if isinstance(corr, pd.DataFrame):\n cov = pd.DataFrame(cov, index=corr.index, columns=corr.columns)\n return cov\n\n\n#==============================================================================\n# Web utilities\n#==============================================================================\ndef saveurl(url, file_name, **kwargs):\n \"\"\"\n Downloads and save url to file_name\n \"\"\"\n r = requests.get(url, **kwargs)\n if r.status_code != 200:\n raise Exception('Error downloading from %s: code %d' %\n (url,r.status_code))\n\n with open(file_name, 'wb') as f:\n f.write(r.content)\n\n log.info('Downloaded %s to %s' %(url, file_name))\n\n\n#==============================================================================\n# Database utilities\n#==============================================================================\ndef regenmulti(DF, axis = 1):\n \"\"\"\n Regenerates a MultiIndex that is returned by the database utility.\n axis = 1: regenerate the multiIndex in the DFs column\n axis = 0: regenerate the multiIndex in the DFs index\n \"\"\"\n newlevel = []\n if axis == 1:\n for level in range(len(DF.columns[0].split(\"_\"))):\n newlevel.append([i.split(\"_\")[level] for i in DF.columns])\n else:\n for level in range(len(DF.index[0].split(\"_\"))):\n newlevel.append([i.split(\"_\")[level] for i in DF.index])\n\n newmulti = pd.MultiIndex.from_arrays(newlevel)\n\n return newmulti\n\n#==============================================================================\n# Other utilities\n#==============================================================================\ndef showall(df):\n \"\"\"\n Shows the full dataframe\n \"\"\"\n cur_maxrows = pd.options.display.max_rows\n pd.options.display.max_rows = len(df)\n print(df)\n pd.options.display.max_rows = cur_maxrows\n\ndef wide(df):\n # shows a wide slice of the dataframe\n cur_maxcols = pd.options.display.max_columns\n pd.options.display.max_columns = df.shape[1]\n display(df)\n pd.options.display.max_columns = cur_maxcols\n\ndef flipdict(d):\n # reverses a dictionary\n return {v: k for k, v in d.items()}\n\n#==============================================================================\n# Backtest utilities\n#==============================================================================\ndef ffillna(df, value=None, method=None):\n \"\"\"\n Performs adjusted fillna / ffill\n Only fills after the first valid value, leading nas are untouched\n \"\"\"\n df = df.copy()\n\n def _stitch(s, value, method):\n\n if len(s.dropna()) > 0:\n first = s.dropna().index[0] # first index of valid value\n ss = s[first:].fillna(value, method) # filled values\n else: # no values at all\n ss = s.copy()\n\n return ss.reindex(index=s.index)\n\n if isinstance(df, pd.Series):\n df = _stitch(df, value, method) # stitch each column\n else:\n for c in df:\n df[c] = _stitch(df[c], value, method) # stitch each column\n\n return df\n\n\ndef dropleadingna(df):\n \"\"\"\n Drop leading na's only\n \"\"\"\n if isinstance(df, pd.Series):\n first = df.dropna().index[0]\n else:\n first = df.index[-1]\n for c in df:\n first = min(first, df[c].dropna().index[0])\n\n return df[first:].copy()\n\ndef trimna(df):\n \"\"\"\n Drop leading and ENDING na's only\n \"\"\"\n if isinstance(df, pd.Series):\n dfn = df.dropna()\n first = dfn.index[0]\n last = dfn.index[-1]\n else:\n first = df.index[-1]\n last = df.index[0]\n for c in df:\n dfn = df[c].dropna()\n first = min(first, dfn.index[0])\n last = max(last, dfn.index[-1])\n\n return df[first:last].copy()\n\n\ndef drawdown(prices):\n \"\"\"\n Returns start and end index of maximum drawdown of given series\n \"\"\"\n prevmaxi = 0\n prevmini = 0\n maxi = 0\n\n for i in range(len(prices))[1:]:\n if prices[i] >= prices[maxi]:\n maxi = i\n else:\n if (prices[maxi] - prices[i]) > (prices[prevmaxi] - prices[prevmini]):\n prevmaxi = maxi\n prevmini = i\n\n return prices.index[prevmaxi], prices.index[prevmini]\n\n\ndef objname(obj, namemaps=None):\n \"\"\"\n returns use friendly string of module\n \"\"\"\n try:\n s = obj.__name__\n except:\n s = obj\n\n ss = s.split('_')\n if ss[0].lower().endswith('signal') or ss[0].lower().endswith('factor'):\n s = '_'.join(ss[1:])\n\n try:\n s = namemaps[s]\n except:\n pass\n\n return s\n\ndef get_model_config(config):\n if isinstance(config,str):\n config = importlib.import_module(config)\n\n prefix = config.pkg.__name__ + \".\"\n importlib.import_module(prefix + 'returns')\n importlib.import_module(prefix + 'glb')\n config.signals = \\\n {k: [importlib.import_module(prefix + 'signal_' + x) for x in v]\n for k, v in config.signal_list.iteritems() }\n\n # Conver to tables\n config.signal_weights = pd.Series(config.signal_weights, name='Weights')\n\n return config\n\ndef signals_availabe(pkg):\n if isinstance(pkg, str):\n pkg = importlib.import_module(pkg)\n\n prefix = pkg.__name__ + \".\"\n return {x: importlib.import_module(prefix + x)\n for _,x,_ in pkgutil.iter_modules(pkg.__path__)\n if x.startswith('signal_')}\n\n\n\ndef pkg_modules(pkg, config=None):\n prefix = pkg.__name__ + \".\"\n returns = importlib.import_module(prefix + 'returns')\n glb = importlib.import_module(prefix + 'glb')\n if config is None:\n config = glb\n factors = { k:[importlib.import_module(prefix + x) for x in v]\n for k, v in config.factors.iteritems() }\n return returns, glb, factors\n\n\ndef copynote(objdest, objsource):\n if isinstance(objsource, str):\n objdest.notes = objsource\n else:\n try:\n objdest.notes = objsource.notes\n except:\n pass\n\n return objdest\n\n\ndef splice(old, new, method=None):\n \"\"\"\n Supplements data series with adjustments. Requires overlap of at least one period.\n :param old: old series / df\n :param new: new series / df\n :param method: backwards ratio, backwards level shift, or None\n :return:\n \"\"\"\n assert new.index[0] in old.index\n\n truncated = old.ix[:new.index[0]].iloc[:-1]\n\n if method is None:\n return pd.concat([truncated, new])\n elif method.lower() == 'ratio':\n if isinstance(old, pd.Series):\n scalar = new.iloc[0] / old.loc[new.index[0]]\n else:\n scalar = new.iloc[0].divide(old.loc[new.index[0]])\n return pd.concat([truncated.multiply(scalar), new])\n elif method.lower() == 'shift':\n if isinstance(old, pd.Series):\n diff = new.iloc[0] - old.loc[new.index[0]]\n else:\n diff = new.iloc[0].subtract(old.loc[new.index[0]])\n return pd.concat([truncated.add(diff), new])\n","sub_path":"research/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"122617104","text":"# -*- coding: utf-8 -*-\n# Copyright 2017 GIG Technology NV\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# @@license_version:1.3@@\nimport datetime\nimport json\nimport logging\n\nfrom google.appengine.ext.deferred import deferred\n\nfrom mcfw.consts import DEBUG\nfrom mcfw.properties import object_factory\nfrom mcfw.rpc import arguments, returns\nfrom onfido import Applicant, Address\nfrom onfido.rest import ApiException\nfrom plugins.its_you_online_auth.bizz.profile import index_profile\nfrom plugins.its_you_online_auth.models import Profile\nfrom plugins.rogerthat_api.exceptions import BusinessException\nfrom plugins.rogerthat_api.to import UserDetailsTO\nfrom plugins.rogerthat_api.to.messaging.flow import FLOW_STEP_MAPPING, FormFlowStepTO\nfrom plugins.rogerthat_api.to.messaging.forms import FormResultTO, UnicodeWidgetResultTO, LongWidgetResultTO\nfrom plugins.rogerthat_api.to.messaging.service_callback_results import FlowMemberResultCallbackResultTO, \\\n TYPE_FLOW, FlowCallbackResultTypeTO\nfrom plugins.tff_backend.api.rogerthat.referrals import api_set_referral\nfrom plugins.tff_backend.bizz.global_stats import ApiCallException\nfrom plugins.tff_backend.bizz.iyo.utils import get_iyo_username\nfrom plugins.tff_backend.bizz.kyc.onfido_bizz import update_applicant, create_applicant, upload_document\nfrom plugins.tff_backend.bizz.rogerthat import create_error_message\nfrom plugins.tff_backend.bizz.user import get_tff_profile, generate_kyc_flow\nfrom plugins.tff_backend.models.user import KYCStatus\nfrom plugins.tff_backend.plugin_consts import KYC_FLOW_PART_2_TAG\nfrom plugins.tff_backend.utils import get_step\n\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\n\nclass InvalidKYCStatusException(Exception):\n def __init__(self, status):\n self.status = status\n msg = 'Invalid KYC status %s' % status\n super(InvalidKYCStatusException, self).__init__(msg)\n\n\n@returns(FlowMemberResultCallbackResultTO)\n@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory('step_type', FLOW_STEP_MAPPING)],\n end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,\n flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=[UserDetailsTO],\n flow_params=unicode)\ndef kyc_part_1(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,\n result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params):\n iyo_username = get_iyo_username(user_details[0])\n if not iyo_username:\n logging.error('No username found for user %s', user_details[0])\n return create_error_message(FlowMemberResultCallbackResultTO())\n result = _validate_kyc_status(iyo_username)\n if isinstance(result, FlowMemberResultCallbackResultTO):\n return result\n step = get_step(steps, 'message_nationality') or get_step(steps, 'message_nationality_with_vibration')\n assert isinstance(step, FormFlowStepTO)\n assert isinstance(step.form_result, FormResultTO)\n assert isinstance(step.form_result.result, UnicodeWidgetResultTO)\n country_code = step.form_result.result.value\n ref_step = get_step(steps, 'message_referrer')\n if ref_step and not result.referrer_user:\n try:\n api_set_referral({'code': ref_step.get_value()}, user_details[0])\n except ApiCallException as e:\n return create_error_message(FlowMemberResultCallbackResultTO(), e.message)\n xml, flow_params = generate_kyc_flow(country_code, iyo_username)\n result = FlowCallbackResultTypeTO(flow=xml, tag=KYC_FLOW_PART_2_TAG, force_language=None,\n flow_params=json.dumps(flow_params))\n return FlowMemberResultCallbackResultTO(type=TYPE_FLOW, value=result)\n\n\n@returns(FlowMemberResultCallbackResultTO)\n@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory('step_type', FLOW_STEP_MAPPING)],\n end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,\n flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=[UserDetailsTO],\n flow_params=unicode)\ndef kyc_part_2(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,\n result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params):\n deferred.defer(_kyc_part_2, message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key,\n tag, result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params)\n\n\n@returns(FlowMemberResultCallbackResultTO)\n@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory('step_type', FLOW_STEP_MAPPING)],\n end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,\n flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=[UserDetailsTO],\n flow_params=unicode)\ndef _kyc_part_2(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,\n result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params):\n parsed_flow_params = json.loads(flow_params)\n applicant = Applicant(nationality=parsed_flow_params['nationality'], addresses=[Address()])\n documents = []\n\n def _set_attr(prop, value):\n if hasattr(applicant, prop):\n setattr(applicant, prop, value)\n elif prop.startswith('address_'):\n prop = prop.replace('address_', '')\n if prop == 'country':\n applicant.country = value\n setattr(applicant.addresses[0], prop, value)\n else:\n logging.warn('Ignoring unknown property %s with value %s', prop, value)\n for step in steps:\n assert isinstance(step, FormFlowStepTO)\n step_id_split = step.step_id.split('_', 1)\n if step_id_split[0] == 'message':\n prop = step_id_split[1] # 'type' from one of plugins.tff_backend.consts.kyc.kyc_steps\n step_value = step.form_result.result.get_value()\n if prop.startswith('national_identity_card'):\n side = None\n if prop.endswith('front'):\n side = 'front'\n elif prop.endswith('back'):\n side = 'back'\n documents.append(\n {'type': 'national_identity_card', 'side': side, 'value': step_value})\n elif prop.startswith('passport'):\n documents.append({'type': 'passport', 'value': step_value})\n elif isinstance(step.form_result.result, UnicodeWidgetResultTO):\n _set_attr(prop, step.form_result.result.value.strip())\n elif isinstance(step.form_result.result, LongWidgetResultTO):\n # date step\n date = datetime.datetime.utcfromtimestamp(step_value).strftime('%Y-%m-%d')\n _set_attr(prop, date)\n else:\n logging.info('Ignoring step %s', step)\n username = get_iyo_username(user_details[0])\n if not username:\n logging.error('Could not find username for user %s!' % user_details[0])\n return create_error_message(FlowMemberResultCallbackResultTO())\n result = _validate_kyc_status(username)\n if isinstance(result, FlowMemberResultCallbackResultTO):\n return result\n profile = get_tff_profile(username)\n try:\n if profile.kyc.applicant_id:\n applicant = update_applicant(profile.kyc.applicant_id, applicant)\n else:\n applicant = create_applicant(applicant)\n profile.kyc.applicant_id = applicant.id\n except ApiException as e:\n if e.status in xrange(400, 499):\n raise BusinessException('Invalid status code from onfido: %s %s' % (e.status, e.body))\n raise\n for document in documents:\n deferred.defer(upload_document, applicant.id, document['type'], document['value'], document.get('side'))\n profile.kyc.set_status(KYCStatus.SUBMITTED.value, username)\n profile.put()\n deferred.defer(index_profile, Profile.create_key(username))\n\n\ndef _validate_kyc_status(username):\n profile = get_tff_profile(username)\n if profile.kyc:\n status = profile.kyc.status\n if status not in (KYCStatus.UNVERIFIED, KYCStatus.PENDING_SUBMIT):\n message = None\n if status == KYCStatus.DENIED:\n message = 'Sorry, we are regrettably not able to accept you as a customer.'\n elif status == KYCStatus.PENDING_APPROVAL or status == KYCStatus.SUBMITTED:\n message = 'We already have the information we currently need to pass on to our KYC provider.' \\\n ' We will contact you if we need more info.' \\\n ' Please contact us if you want to update your information.'\n elif status == KYCStatus.VERIFIED:\n message = 'You have already been verified, so you do not need to enter this process again. Thank you!'\n if not DEBUG:\n return create_error_message(FlowMemberResultCallbackResultTO(), message)\n return profile\n","sub_path":"plugins/tff_backend/bizz/kyc/rogerthat_callbacks.py","file_name":"rogerthat_callbacks.py","file_ext":"py","file_size_in_byte":9861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"143374019","text":"import jieba\nfrom tqdm import tqdm\nimport random\nimport logging\njieba.setLogLevel(logging.INFO)\n\nfrom multiprocessing import Pool\n\ndef cut_list(data, batch_size):\n return [data[x:x+batch_size] for x in range(0, len(data), batch_size)]\n\ndef parallel(func: callable, data:list, num_worker:int=3, debug=False) -> callable:\n if num_worker == 1:\n return func(data)\n\n batch_size = len(data)//num_worker + 1\n with Pool(num_worker) as p:\n if debug: print('parallel debug M:', cut_list(data, batch_size))\n res = p.map(func, cut_list(data, batch_size))\n if debug: print('parallel debug R:', res)\n result = []\n for e in res: result.extend(e)\n return result\n\n\nif __name__ == '__main__':\n path_en = '/data/lbh/translate/all_1kw_tagged/all.en'\n path_zh = '/data/lbh/translate/all_1kw_tagged/all.zh'\n path_out = \"data/\"\n \n data_pair = [(en.strip(), zh.strip()) for en, zh in \\\n tqdm(zip(open(path_en, 'r').read().split('\\n'),\n open(path_zh, 'r').read().split('\\n')), 'strip')]\n print(f'total len: {len(data_pair)}')\n data_pair = set(data_pair)\n print(f'remove duplicate: {len(data_pair)}')\n\n data_en, data_zh = zip(*data_pair)\n del data_pair\n \n def cut_sent(data):\n return [[e.strip() for e in jieba.lcut(line) if e.strip()] for line in tqdm(data)]\n \n data_en = parallel(cut_sent, data_en, num_worker=30)\n data_zh = parallel(cut_sent, data_zh, num_worker=30)\n \n # filter sents\n max_seq_len = 200\n max_ratio = 1.3\n data = [(' '.join(en), ' '.join(zh)) for en, zh in zip(data_en, data_zh) \\\n if len(en) * len(zh) and 1/max_ratio < len(en)/ len(zh) < max_ratio \\\n and len(zh) <= max_seq_len and len(en) <= max_seq_len]\n random.shuffle(data)\n print(f'remove ratio {max_ratio} length {max_seq_len}: {len(data)}')\n\n start_point = [int(e*len(data)) for e in [0, 0.05, 0.10]] + [None]\n datasets = [[], [], []]\n for i, dataset in enumerate(datasets):\n dataset.extend(data[start_point[i]:start_point[i+1]])\n\n print(f'dataset len: {[len(e) for e in datasets]}')\n \n outf = {}\n for k in ['dev', 'val', 'train']:\n for type in ['en', 'zh']:\n name = f'{type}-{k}.txt'\n outf[name] = open(f'{path_out}/{name}', 'w')\n\n for k, v in zip(['dev', 'val', 'train'], datasets):\n for en, zh in tqdm(v, f'save {k}'):\n print(en, file=outf[f'en-{k}.txt'])\n print(zh, file=outf[f'zh-{k}.txt'])\n \n\n","sub_path":"scrpit/prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"621057271","text":"import time\n#from Adafruit_AMG88xx import Adafruit_AMG88xx\nfrom time import sleep\nimport Adafruit_BBIO.GPIO as GPIO\nimport Adafruit_BBIO.ADC as ADC\nfrom Adafruit_BBIO.Encoder import RotaryEncoder, eQEP2\nfrom Adafruit_AMG88xx import Adafruit_AMG88xx\n\nmyEncoder = RotaryEncoder(eQEP2)\nmyEncoder.enable()\nsensor = Adafruit_AMG88xx(address=0x69, busnum=2)\n\nADC.setup()\nanalogPin=\"P9_39\"\nAct = 'P8_7'\nActt = 'P8_9'\nFan = 'P8_11'\nFann = 'P8_15'\nGPIO.setup(Act, GPIO.OUT)\nGPIO.setup(Actt, GPIO.OUT)\nGPIO.setup(Fan, GPIO.OUT)\nGPIO.setup(Fann, GPIO.OUT)\nGPIO.output(Act, GPIO.HIGH)\n\n\n\nf = raw_input('file name : ')\nfilename = f + '.txt'\ntdata = open(filename, 'a+')\n\ntdata.write(\"Cal_Disp(mm),Temperature('c),Time(s) \\n\")\na=0\n\nwhile a!=4:\n a= int(input('act=1, cool=2, cycle=3, stop=4 '))\n\n if a==1:\n c = int(input('heating time(s) : '))\n b = c*10+1\n GPIO.output(Act, GPIO.LOW)\n tdata.write(\"Cal_Disp(mm),Temperature('c),Resistance(ohm),Time(s) \\n\")\n for count in range(1,b):\n distance = myEncoder.position * 0.01\n temp = max(sensor.readPixels())\n Vr=ADC.read(analogPin)\n R=10000*Vr/(1.8-Vr)\n print(\"%.2f,%d,%d,%.1f\" % (distance, temp, R, count*0.1))\n tdata.write(\"%.2f,%d,%d,%.1f\" % (distance, temp, R, count*0.1))\n time.sleep(0.1)\n GPIO.output(Act, GPIO.HIGH)\n for count in range(b,b+11):\n distance = myEncoder.position * 0.01\n temp = max(sensor.readPixels())\n Vr=ADC.read(analogPin)\n R=10000*Vr/(1.8-Vr)\n print(\"%.2f,%d,%d,%.1f\" % (distance, temp, R, count*0.1))\n tdata.write(\"%.2f,%d,%d,%.1f\" % (distance, temp, R, count*0.1))\n time.sleep(0.1)\n\n elif a==2:\n c = int(input('cooling time(s) : '))\n b = c*5+1\n GPIO.output(Fan, GPIO.LOW)\n tdata.write(\"Cal_Disp, mm, Sen_Disp, mm, Temperature, 'c, Time, s \\n\")\n for count in range(1,b):\n distance = myEncoder.position * 0.01\n temp = max(sensor.readPixels())\n Vr=ADC.read(analogPin)\n R=10000*Vr/(1.8-Vr)\n print(\"%.2f,%d,%d,%.1f\" % (distance, temp, R, count*0.1))\n tdata.write(\"%.2f,%d,%d,%.1f\" % (distance, temp, R, count*0.1))\n time.sleep(0.1)\n GPIO.output(Fan, GPIO.HIGH)\n\n elif a==3:\n ht = int(input('heating time(s) : '))\n ct = int(input('cooling time(s) : '))\n cy = int(input('cycle number : '))\n h = ht*10+1\n c = ct*10+1\n tdata.write(\"Cal_Disp(mm),Temperature('c),Time(s) \\n\")\n for cycle in range(1, cy):\n for count in range(1, h):\n GPIO.output(Act, GPIO.LOW)\n distance = myEncoder.position * 0.01\n temp = max(sensor.readPixels())\n Vr = ADC.read(analogPin)\n R = 10000 * Vr / (1.8 - Vr)\n print(\"%.2f,%d,%d,%.1f\\n\" % (distance, temp, R, count * 0.1))\n tdata.write(\"%.2f,%d,%d,%.1f\\n\" % (distance, temp, R, count * 0.1))\n time.sleep(0.1)\n GPIO.output(Act, GPIO.HIGH)\n for count in range(1, c):\n GPIO.output(Fan, GPIO.LOW)\n distance = myEncoder.position * 0.01\n temp = max(sensor.readPixels())\n Vr = ADC.read(analogPin)\n R = 10000 * Vr / (1.8 - Vr)\n print(\"%.2f,%d,%d,%.1f\\n\" % (distance, temp, R, count * 0.1))\n tdata.write(\"%.2f,%d,%d,%.1f\\n\" % (distance, temp, R, count * 0.1))\n time.sleep(0.1)\n GPIO.output(Fan, GPIO.HIGH)\n GPIO.output(Act, GPIO.HIGH)\n GPIO.output(Fan, GPIO.HIGH)\n elif a==5:\n myEncoder.zero()\n\n\n\ntdata.close()\n","sub_path":"Act_test/1_test.py","file_name":"1_test.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"448156387","text":"'''\r\nRequrements\r\nPrepare a GUI that enables generation and visualization of data samples from two classes. \r\nSamples should be two-dimensional, so that they can be plotted in x-y space. \r\nEach class should consist of one or more gaussian modes1 with their means \r\nand variances chosen randomly from some given inteval (e.g. μx, μy ∈ [−1..1]).\r\nThe interface should allow for setting a desired number of modes per class and a desired number of samples per mode, \r\nas well as visualization of the generated samples on a two-dimensional plot. \r\nClass labels, which are either 0 or 1, should be indicated by colors.\r\n'''\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom matplotlib.widgets import TextBox,Button\r\nimport itertools\r\nimport copy\r\nfrom neuron import *\r\n\r\nfig, ax = [],[]\r\nRED = 0\r\nBLUE = 1\r\ncolor_type = ('ro','bo')\r\nmean = [[[-5,-5],[5,5]],[[10,10],[-10,-10]]]\r\ncov = [[[[1, 2], [0.5, 2]],[[1, 2], [0.5, 2]]],[[[1, 0.3], [2, 0.5]],[[1, 2], [5, 6]]]]\r\nsamples = [100,100]\r\nmeshDensity = 200\r\ndataClass = []\r\nclassesNo = [1,1]\r\nmeanRange = [-5,5]\r\ncovRange = (-2,2)\r\nneuron = None\r\ncolorbar = None\r\ngrid = None\r\nfunction = \"tanh_func\"\r\nx = [[],[]]\r\ny = [[],[]]\r\n\r\ndef train():\r\n global function,neuron\r\n neuron.act_func = function\r\n print(\"training iter: \",neuron.train([x[RED],y[RED]],[x[BLUE],y[BLUE]],0.5))\r\n\r\ndef predict(inputTable, ID):\r\n neuron.setInput(inputTable)\r\n return neuron.calculateOutput(True)\r\n \r\n\r\ndef drawPlot(ID):\r\n global mean\r\n global cov\r\n global samples\r\n global dataClass\r\n global classesNo\r\n global x,y\r\n\r\n for i in range(classesNo[ID]):\r\n _x,_y = np.random.multivariate_normal(mean[ID][i], cov[ID][i], samples[ID]).T\r\n x[ID].extend(_x)\r\n y[ID].extend(_y)\r\n return ax.plot(x[ID], y[ID], color_type[ID])\r\n\r\ndef redraw(ID):\r\n return ax.plot(x[ID], y[ID], color_type[ID])\r\n\r\ndef initsRegenerate(ID):\r\n global mean\r\n global cov\r\n mean.pop(ID)\r\n mean.insert(ID,[])\r\n cov.pop(ID)\r\n cov.insert(ID,[])\r\n for i in range(classesNo[ID]):\r\n mean[ID].insert(i,randomMultivariateMean(meanRange[0],meanRange[1]))\r\n cov[ID].insert(i,randomCov(covRange[0],covRange[1]))\r\n \r\n\r\ndef randomMultivariateMean(_min,_max):\r\n newmean = np.random.uniform(_min,_max,2)\r\n return [newmean[0],newmean[1]]\r\n\r\ndef randomCov(_min,_max):\r\n _x,_y = [],[]\r\n _x = np.random.uniform(_min,_max,2)\r\n _y = np.random.uniform(_min,_max,2)\r\n covariance = [[_x[0],_x[1]],[_y[0],_y[1]]]\r\n return covariance\r\n\r\ndef mapCurrentView():\r\n xLim = ax.get_xlim()\r\n yLim = ax.get_ylim()\r\n _x = np.linspace(xLim[0], xLim[1], meshDensity) \r\n _y = np.linspace(yLim[0], yLim[1], meshDensity) \r\n x_1,y_1 = np.meshgrid(_x, _y)\r\n return [x_1,y_1]\r\n\r\ndef neuralValorisation(_map):\r\n values = copy.deepcopy(_map[0])\r\n for i in range(meshDensity):\r\n for j in range(meshDensity):\r\n table = [_map[0][i,j],_map[1][i,j]]\r\n neuron.setInput(table)\r\n values[i,j] = (neuron.calculateOutput(False))\r\n return values\r\n\r\ndef drawFieldDiv():\r\n global grid,colorbar\r\n if(grid != None):\r\n del grid\r\n _map = mapCurrentView()\r\n grid = ax.pcolormesh(_map[0],_map[1],neuralValorisation(_map),cmap='jet',alpha = 0.1)\r\n\r\ndef plotDataUpdate(ID):\r\n global classesNo,plotFill,mean,cov,samples,dataClass, neurPlot,neuron,x,y\r\n try:\r\n x.pop(ID)\r\n x.insert(ID,[])\r\n y.pop(ID)\r\n y.insert(ID,[])\r\n for i in range(classesNo[ID]):\r\n _x,_y = np.random.multivariate_normal(mean[ID][i], cov[ID][i], samples[ID]).T\r\n x[ID].extend(_x)\r\n y[ID].extend(_y)\r\n except:\r\n print(\"Incorrect data input!\")\r\n dataClass[ID][0].set_xdata(x[ID])\r\n dataClass[ID][0].set_ydata(y[ID])\r\n \r\n\r\ndef plotUpdate():\r\n ax.cla()\r\n redraw(RED)\r\n redraw(BLUE)\r\n drawFieldDiv()\r\n ax.relim()\r\n ax.autoscale_view()\r\n plt.draw()\r\n \r\n\r\ndef initPlots():\r\n global fig,ax\r\n global cov\r\n fig, ax = plt.subplots()\r\n plt.subplots_adjust(bottom=0.29)\r\n plt.autoscale(enable=True, axis='both', tight=True)\r\n fig.colorbar(plt.cm.ScalarMappable( cmap='jet'), ax=ax)\r\n initsRegenerate(RED)\r\n initsRegenerate(BLUE)\r\n return fig,ax\r\n\r\nclass Index(object):\r\n ind = 0\r\n \r\n def regenerate(self,event):\r\n self.ind +=1\r\n neuron.setWeight([1,1,1])\r\n initsRegenerate(RED)\r\n initsRegenerate(BLUE)\r\n plotDataUpdate(RED)\r\n plotDataUpdate(BLUE)\r\n plotUpdate()\r\n def training(self,event):\r\n self.ind -=1\r\n train()\r\n def refresh(self,event):\r\n plotUpdate()\r\n self.ind -=10\r\n \r\ndef initGUI():\r\n #TextBox position variables (matplotlib.axes.Axes)\r\n RED_boxAxis = plt.axes([0.15, 0.05, 0.32, 0.05])\r\n RED_sampleBoxAxis = plt.axes([0.15, 0.11, 0.32, 0.05])\r\n BLUE_boxAxis = plt.axes([0.61, 0.05, 0.32, 0.05])\r\n BLUE_sampleBoxAxis = plt.axes([0.61, 0.11, 0.32, 0.05])\r\n meanBoxAxis = plt.axes([0.63, 0.17, 0.12, 0.05])\r\n Train_boxAxis = plt.axes([0.15, 0.17, 0.15, 0.05])\r\n #Button position variables (matplotlib.axes.Axes)\r\n Train_axButton = plt.axes([0.31, 0.17, 0.1, 0.05])\r\n Reg_axButton = plt.axes([0.78, 0.17, 0.15, 0.05])\r\n Refresh_axButton = plt.axes([0.43, 0.17, 0.1, 0.05])\r\n #buttons\r\n Train_button = Button(Train_axButton, 'Train',color = 'green')\r\n Reg_button = Button(Reg_axButton, 'Regenerate')\r\n Refresh_button = Button(Refresh_axButton, 'Refresh')\r\n #TextBox text boxes\r\n \r\n RED_textBox = TextBox(RED_boxAxis, 'Modes\\nRED', initial=str(classesNo[RED]))\r\n RED_textBox.label.set_wrap(True)\r\n meantextBox = TextBox(meanBoxAxis, 'Mean\\nRange', initial=str(meanRange))\r\n meantextBox.label.set_wrap(True)\r\n RED_sampletextBox = TextBox(RED_sampleBoxAxis, 'Samples\\nRED', initial=str(samples[RED]))\r\n RED_sampletextBox.label.set_wrap(True)\r\n BLUE_textBox = TextBox(BLUE_boxAxis, 'Modes\\nBLUE', initial=str(classesNo[BLUE]))\r\n BLUE_textBox.label.set_wrap(True)\r\n BLUE_sampletextBox = TextBox(BLUE_sampleBoxAxis, 'Samples\\nBLUE', initial=str(samples[BLUE]))\r\n BLUE_sampletextBox.label.set_wrap(True)\r\n Train_TextBox = TextBox(Train_boxAxis, 'Func',initial=str(function))\r\n\r\n #on_submit event handlers\r\n RED_textBox.on_submit(lambda value: submitNo(RED,RED_textBox.text))\r\n BLUE_textBox.on_submit(lambda value: submitNo(BLUE,BLUE_textBox.text))\r\n meantextBox.on_submit(lambda value: submitMean(meantextBox.text))\r\n RED_sampletextBox.on_submit(lambda value: submitSamples(RED,RED_sampletextBox.text))\r\n BLUE_sampletextBox.on_submit(lambda value: submitSamples(BLUE,BLUE_sampletextBox.text))\r\n Train_TextBox.on_submit(setFunction)\r\n callback = Index()\r\n Train_button.on_clicked(callback.training)\r\n Refresh_button.on_clicked(callback.refresh)\r\n Reg_button.on_clicked(callback.regenerate)\r\n\r\n plt.show()\r\n return callback\r\n\r\ndef setFunction(input_string):\r\n global function\r\n function = input_string\r\n\r\ndef submitNo(ID, input_string):\r\n newNo = 0\r\n global classesNo\r\n try:\r\n newNo = int(input_string)\r\n classesNo[ID] = newNo\r\n except:\r\n print(\"Parsing Error!\")\r\n initsRegenerate(ID)\r\n #plotDataUpdate(ID)\r\n \r\ndef submitMean(input_string):\r\n newMeanRange = [0,0]\r\n global meanRange \r\n try:\r\n newMeanRange = eval(input_string)\r\n meanRange = newMeanRange\r\n except:\r\n print(\"Parsing Error!\")\r\n initsRegenerate(BLUE)\r\n initsRegenerate(RED)\r\n \r\n \r\ndef submitSamples(ID, input_string):\r\n newSamples = 1\r\n global samples\r\n try:\r\n newSamples = int(input_string)\r\n samples[ID] = newSamples\r\n except:\r\n print(\"Parsing Error!\")\r\n \r\n\r\n \r\nif __name__ == '__main__':\r\n initPlots()\r\n dataClass = [drawPlot(RED),drawPlot(BLUE)]\r\n neuron = Neuron([1,1,1],function,[1,1,1],0.1)\r\n drawFieldDiv()\r\n initGUI()\r\n plt.show()\r\n\r\n","sub_path":"EX2/Generator_gui.py","file_name":"Generator_gui.py","file_ext":"py","file_size_in_byte":8020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"9797979","text":"#----------------------------------------------------------THE HANGMAN GAME-----------------------------------------------------------------\r\nimport random\r\n#------------------------------------------------------------First Screen-------------------------------------------------------------------\r\nprint(\"HEY THERE! WELCOME to Hangman Gaming console\") #Welcome user\r\nusername = input(\"Enter Your Username Here --> \") #Input Username of user\r\nprint(f\"WOW {username.title()}! Let the Game Begin :) \") #Excite the user to play the game\r\nprint(\"Please Choose The Topic Of Your Interest Below. Type \")\r\nprint(\"A --> Cities \\nB --> Bollywood \\nH --> Hollywood \\nC --> Company \\nP --> Personality\")\r\nchoice = input(\"Input Your Choice --> \")\r\n#-----------------------------------------------------------Second Screen-------------------------------------------------------------------\r\nif choice == 'A':\r\n data = ['NEWYORK','LASVEGAS','MUMBAI','SYDNEY','AUKLAND','SANFRANCISCO','PRETORIA','ROME','BERLIN','BUDAPEST','CHICAGO',\r\n 'LONDON','PARIS','TORONTO','MOSCOW','TOKYO','KOLKATA','SHANGHAI','BEIJING','AMSTERDAM','ABUDHABI','DUBAI',\r\n 'DUBLIN','HONGKONG','NEWDELHI','AHMEDABAD','BANGALORE','HYDERABAD','PATNA','BHUBANESWAR','INDORE','RAJKOT','VARANASI',\r\n 'VISAKHAPATNAM','CHENNAI','JAIPUR','WASHINGTONDC','SANDIEGO'] #Data\r\nelif choice == 'B':\r\n data = ['SANAMRE','CHHICHHORE','BHARAT','DABANGG','DANGAL','BAAGHI','PK','WAR','CHENNAIEXPRESS','GOLMAAL','BARFI','LAGAAN','RANGDEBASANTI',\r\n 'WANTED','RACE','HATESTORY','RAID','SANJU','EKTHATIGER','ZINDAGINAMILEGIDOBARA']\r\nelif choice == 'H':\r\n data = ['JOKER','AVENGERSENDGAME','TOYSTORY','THEINCRIDIBLEHULK','IRONMAN','FASTANDFURIOUS','DEADPOOL','CAPTAINAMERICA',\r\n 'INCEPTION','STARWARS','TITANIC','THEMATRIX','DOCTORSTRANGE','PACIFICRIM','DIEHARD','WALLE','AVATAR','THELIONKING','THEHANGOVER']\r\nelif choice == 'C':\r\n data = ['FORD','COCACOLA','MERCEDES','BMW','SPICEJET','EMIRATES','FERRARI','LAMBORGHINI','TATA','APPLE','XIAOMI','SAMSUNG','SUZUKI',\r\n 'VISA','FACEBOOK','INSTAGRAM','WHATSAPP','LENOVO','MICROSOFT','WALMART','RELIANCE','BOEING','NIKE','ADIDAS','DOMINOS','ADOBE',\r\n 'YOUTUBE','PAYPAL','GOOGLE','ALPHABET','INTEL','MASTERCARD','NETFLIX','TOYOTA','UNILEVER','NOKIA','AMERICANTOURISTER']\r\nelif choice == 'P':\r\n data = ['SACHINTENDULKAR','SUNDARPICHAI','ELONMUSK','BILLGATES','VIRATKOHLI','BARACKOBAMA','MAHATMAGANDHI','NEILARMSTRONG','ADOLFHITLER',\r\n 'ALBERTEINSTEIN','HILARYCLINTON','NARENDRAMODI','RATANTATA','MUKESHAMBANI','JKROWLING','LIONELMESSI','CRISTIANORONALDO',\r\n 'ISACNEWTON','NIKOLATESLA','BRADPITT','ROHITSHARMA','SALMANKHAN','SHAHRUKHKHAN','ANGELINAJOLIE','DONALDTRUMP','VIRENDRASEHWAG',\r\n 'MARKZUKERBERG','STEVEJOBS','WARRENBUFFETT','MICHEALJACKSON','HRITIKROSHAN','STEPHENHAWKINGS','SHAKIRA','TOMCRUISE','USAINBOLT'\r\n 'CHARLIECHAPLIN','ABRAHAMLINCOLN','NELSONMANDELA','WILLIAMSHAKESPEARE','ELIZABETHTAYLOR','TIGERWOODS','WALTDISNEY','LADYGAGA']\r\nrandom.shuffle(data) #Shuffled the data\r\nmdata = data[0] #Got the main data(mdata)\r\n# print(mdata)\r\nwgcounter = 0 #Wrong Guess Counter\r\nrgcounter = 0 #Right Guess Counter\r\nfinallist = [] #The list of all the correct input by the user. finallist = mdata when user wins.\r\nwglist = []\r\nlist1 = [\" \" for i in range(0,len(mdata))]\r\nfor i in range(0,45):\r\n if i == 0: #The First Guess\r\n print(\"You Will Be Given Total 7 Chances\")\r\n print(list1)\r\n letter = input(f\"Lets Start! Enter Your First Guess {username.title()} \") #Input the first guess \r\n for j in range(0,len(mdata)): #Loop for Comparing mdata and first guess Indexwise\r\n if letter == mdata[j] : #statement if right guess\r\n rgcounter = rgcounter + 1\r\n list1[j] = letter\r\n if rgcounter == 0 : #statement If wrong guess\r\n wgcounter = wgcounter + 1\r\n print(list1)\r\n print()\r\n elif i > 0: #The next guess\r\n frgcounter = 0 #First Right Guess Counter (right guess counter for only a particular loop)\r\n print(f\"You Have {7-wgcounter} Chances Left\") #Update about the chances left\r\n letter = input(f\"Its Time For Your Next Guess {username.title()} \") #Input the next guess\r\n for j in range(0,len(mdata)): #Loop for comparing mdata and next guess Indexwise\r\n if letter == mdata[j]: #statement if right guess\r\n frgcounter = frgcounter + 1 #frgcounter used specially for this loop(if i>0)\r\n rgcounter = rgcounter + 1 #update rgcounter\r\n list1[j] = letter\r\n print(list1) #Update about right guessed letters in list\r\n print()\r\n if frgcounter == 0 : #statement if wrong guess\r\n wgcounter = wgcounter + 1\r\n if 7-wgcounter == 0: #If no chances left\r\n print(f\"YOU LOOSE!!. BAD LUCK. Better Luck Next Time {username.title()} \")\r\n print(f\"The Word Was {mdata} \") #Telling user what was the word\r\n break\r\n elif list1 == list(mdata): #If user win\r\n print(f\"HURRAY!! YOU WIN. Well Played {username.title()} \")\r\n break\r\n# print(rgcounter) #print rgcounter\r\n# print(wgcounter) #print wgcounter\r\n# print(list1)\r\n# print(list(mdata))\r\n#--------------------------------------------------------------CODE END HERE------------------------------------------------------------------","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"28888658","text":"import cv2\nimport numpy as np\n\n\nclass LaneIsolator(object):\n\n def __init__(self,\n ksize=3,\n gradx_thresh=(20, 100),\n grady_thresh=(20, 100),\n mag_thresh=(20, 100),\n dir_thresh = (0, np.pi / 8),\n trace_intermediate_image=(lambda label,img : None)):\n \"\"\"\n\n :param ksize:\n :param gradx_thresh:\n :param grady_thresh:\n :param mag_thresh:\n :param dir_thresh:\n :param trace_intermediate_image: For receiving intermediary images in lane isolation.\n Expects function(label:str, image). The image given to this function by LaneIsolater\n could be change after the call (passed by reference). Copy it if e.g. you want to plot it later.\n \"\"\"\n self.ksize = ksize\n self.gradx_thresh = gradx_thresh\n self.grady_thresh = grady_thresh\n self.mag_thresh = mag_thresh\n self.dir_thresh = dir_thresh\n self._sobelx = None\n self._sobely = None\n self._gray = None\n self.trace_intermediate_image = trace_intermediate_image\n\n def _abs_sobel_thresh(self, sobel, thresh_min=0, thresh_max=255):\n abs_sobel = np.absolute(sobel)\n # Rescale back to 8 bit integer\n scaled_sobel = np.uint8(255 * abs_sobel / np.max(abs_sobel))\n sobel_mask = np.zeros_like(scaled_sobel) # TODO do not create copy\n sobel_mask[(scaled_sobel >= thresh_min) & (scaled_sobel <= thresh_max)] = 1\n\n return sobel_mask\n\n # Define a function to return the magnitude of the gradient\n # for a given sobel kernel size and threshold values\n def _mag_thresh(self, sobelx, sobely, mag_thresh=(0, 255)):\n # Calculate the gradient magnitude\n gradmag = np.sqrt(sobelx ** 2 + sobely ** 2)\n # Rescale to 8 bit\n scale_factor = np.max(gradmag) / 255\n gradmag = (gradmag / scale_factor).astype(np.uint8)\n # Create a binary image of ones where threshold is met, zeros otherwise\n sobel_mag_mask = np.zeros_like(gradmag)\n sobel_mag_mask[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1\n\n return sobel_mag_mask\n\n # Define a function to threshold an image for a given range and Sobel kernel\n def _dir_threshold(self, sobelx, sobely, thresh=(-np.pi / 2, np.pi / 2)):\n # Take the absolute value of the gradient direction,\n # apply a threshold, and create a binary image result\n absgraddir = np.arctan2(np.absolute(sobely), np.absolute(sobelx))\n sobel_dir_mask = np.zeros_like(absgraddir) # TODO .astype(np.uint8\n sobel_dir_mask[(absgraddir >= thresh[0]) & (absgraddir <= thresh[1])] = 1\n\n return sobel_dir_mask\n\n def _color_threshold(self, img):\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n\n yellow_hls_low = np.array([0, 100, 100])\n yellow_hls_high = np.array([255, 255, 255])\n\n white_rgb_low = np.array([200, 200, 200])\n white_rgb_high = np.array([255, 255, 255])\n\n yellow_mask = cv2.inRange(hls, yellow_hls_low, yellow_hls_high)\n self.trace_intermediate_image('yellow color mask', yellow_mask)\n\n white_mask = cv2.inRange(img, white_rgb_low, white_rgb_high)\n self.trace_intermediate_image('white color mask', white_mask)\n\n color_mask = cv2.bitwise_or(yellow_mask, white_mask)\n return color_mask\n\n def isolate_lanes(self, img):\n #self._gray = cv2.cvtColor(src=img, code=cv2.COLOR_RGB2GRAY, dst=self._gray)\n #self.trace_intermediate_image('converted to gray scale', self._gray)\n\n #self._sobelx = cv2.Sobel(src=self._gray, ddepth=cv2.CV_64F, dx=1, dy=0, dst=self._sobelx, ksize=self.ksize)\n #self.trace_intermediate_image('sobel x', self._sobelx)\n\n #self._sobely = cv2.Sobel(src=self._gray, ddepth=cv2.CV_64F, dx=0, dy=1, dst=self._sobely, ksize=self.ksize)\n #self.trace_intermediate_image('sobel y', self._sobely)\n\n #gradx = self._abs_sobel_thresh(\n # sobel=self._sobelx, thresh_min=self.gradx_thresh[0], thresh_max=self.gradx_thresh[1])\n #self.trace_intermediate_image('gradx', gradx)\n\n #grady = self._abs_sobel_thresh(\n # sobel=self._sobely, thresh_min=self.grady_thresh[0], thresh_max=self.grady_thresh[1])\n #self.trace_intermediate_image('grady', grady)\n\n #mag_binary = self._mag_thresh(sobelx=self._sobelx, sobely=self._sobely, mag_thresh=self.mag_thresh)\n #self.trace_intermediate_image('magnitude', mag_binary)\n\n #dir_binary = self._dir_threshold(sobelx=self._sobelx, sobely=self._sobely, thresh=self.dir_thresh)\n #self.trace_intermediate_image('direction', dir_binary)\n\n color_binary = self._color_threshold(img)\n self.trace_intermediate_image('color mask', color_binary)\n\n #lanes = np.zeros_like(dir_binary)\n #lanes[((dir_binary == 1) & (mag_binary == 1) & (gradx == 1) & (grady == 1)) | (color_binary == 1)] = 1\n #lanes[(color_binary == 1)] = 1\n #self.trace_intermediate_image('lanes', lanes)\n\n return color_binary\n","sub_path":"lane_isolator.py","file_name":"lane_isolator.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"220670245","text":"#!/usr/bin/python\nimport sys\n\ndef get_offsets():\n with open('input.txt', 'r') as f:\n for line in f:\n l = line.strip()\n if l:\n yield l\n\ndef get_instr():\n return [ int(x) for x in get_offsets() ]\n\ndef main(instr):\n steps = 0\n i = 0\n num_instr = len(instr)\n while True:\n offset = instr[i]\n j = offset + i\n instr[i] = instr[i] + (1 if offset < 3 else -1)\n steps = steps + 1\n if j < 0 or j >= num_instr:\n break\n i = j\n\n print('Num steps: {}'.format(steps))\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n main([int(x) for x in sys.argv[1::]])\n else:\n main(get_instr())\n","sub_path":"day5/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"413588475","text":"#!/bin/python3\nimport subprocess\nimport sys\n\nfile_in = open(sys.argv[1],'r')\nfile_out = open(sys.argv[2],'w+')\n\ntext_in = file_in.read()\ntext_out = ''\nflag = 0\n\nprint('Please Wait')\nfor x in text_in:\n if x == ' ':\n if flag == 0:\n text_out+=', '\n flag = 1\n else:\n pass\n else:\n text_out+=x\n flag=0\n\nfile_out.write(text_out)\n\nprint('Done!')\n","sub_path":"File Manipulation/seperate by commas.py","file_name":"seperate by commas.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"533854396","text":"from tkinter import *\nfrom tkinter import ttk\nimport wikipedia\nwindow=Tk()\ndef get_result():\n entry_value=entry.get()\n try:\n answer_value=wikipedia.summary(entry_value)\n answer.delete(1.0,END)\n answer.insert(INSERT,answer_value)\n except:\n answer.delete(1.0,END)\n answer.insert(INSERT,\"No search result for \"+entry_value)\n\ntopframe=Frame(window,highlightcolor=\"green\",highlightthickness=2,width=250,height=100)\nentry=Entry(topframe,width=30)\nentry.pack()\nbutton=ttk.Button(topframe,text=\"search\",command=get_result).pack()\ntopframe.pack(side=TOP)\n\nbottomframe=Frame(window,highlightcolor=\"red\",highlightthickness=2,width=250,height=150)\nscroll=Scrollbar(bottomframe,)\nscroll.pack(side=RIGHT,fill=Y)\nanswer=Text(bottomframe,width=40,height=10,wrap=WORD,yscrollcommand=scroll.set)\nscroll.config(command=answer.yview)\nanswer.pack()\nbottomframe.pack()\nwindow.geometry(\"300x300\")\nwindow.mainloop()\n","sub_path":"importing wikipedia module for search app.py","file_name":"importing wikipedia module for search app.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"49498165","text":"# code for local testing of genomearray code on laublab server\nimport sys, os\nimport numpy as np\nsys.path.append(os.path.relpath(\"/home/laublab/notebooks/dropbox_link/culviner/repositories/genomearray/\"))\nimport genomearray as ga\nfrom numpy import nan\n\n# test 5' and 3' slope function : rollingslope(input_array, slope_distance, slope_position)\nslope_test = np.arange(0,20,2)\nslope_test[0:5] = np.arange(0,10)[0:5]\nslope_test = np.asarray([slope_test,slope_test])\n# known answers for 5' and 3' functionality\nexpected_5 = np.array([[ 1. , 2. , 2.7, 3. , 2.8, 2. , nan, nan, nan, nan],\n [ nan, nan, nan, nan, -1. , -2. , -2.7, -3. , -2.8, -2. ]])\nexpected_3 = np.array([[ nan, nan, nan, nan, 1. , 2. , 2.7, 3. , 2.8, 2. ],\n [-1. , -2. , -2.7, -3. , -2.8, -2. , nan, nan, nan, nan]])\n\ndef test_rolling_slope_5prime_shape():\n assert ga.ntmath.rollingslope(slope_test, 5, '5_prime').shape == expected_5.shape\n\ndef test_rolling_slope_5prime_value():\n np.testing.assert_equal(ga.ntmath.rollingslope(slope_test, 5, '5_prime'), expected_5)\n\ndef test_rolling_slope_3prime_shape():\n assert ga.ntmath.rollingslope(slope_test, 5, '3_prime').shape == expected_3.shape\n\ndef test_rolling_slope_3prime_value():\n np.testing.assert_equal(ga.ntmath.rollingslope(slope_test, 5, '3_prime'), expected_3)","sub_path":"test/ntmath_test.py","file_name":"ntmath_test.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"442531750","text":"\"\"\"\n Function module\n\"\"\"\nimport logging\nfrom itertools import groupby\n\nfrom securewei.core.children.child_contract import ChildContract\nfrom securewei.core.declarations.solidity_variables import (SolidityFunction,\n SolidityVariable,\n SolidityVariableComposed)\nfrom securewei.core.expressions.identifier import Identifier\nfrom securewei.core.expressions.index_access import IndexAccess\nfrom securewei.core.expressions.member_access import MemberAccess\nfrom securewei.core.expressions.unary_operation import UnaryOperation\nfrom securewei.core.source_mapping.source_mapping import SourceMapping\nfrom securewei.core.variables.state_variable import StateVariable\n\nlogger = logging.getLogger(\"Function\")\n\nclass Function(ChildContract, SourceMapping):\n \"\"\"\n Function class\n \"\"\"\n\n def __init__(self):\n super(Function, self).__init__()\n self._name = None\n self._view = None\n self._pure = None\n self._payable = None\n self._visibility = None\n self._is_constructor = None\n self._is_implemented = None\n self._is_empty = None\n self._entry_point = None\n self._nodes = []\n self._variables = {}\n self._parameters = []\n self._returns = []\n self._vars_read = []\n self._vars_written = []\n self._state_vars_read = []\n self._vars_read_or_written = []\n self._solidity_vars_read = []\n self._state_vars_written = []\n self._internal_calls = []\n self._external_calls = []\n self._expression_vars_read = []\n self._expression_vars_written = []\n self._expression_calls = []\n self._expression_modifiers = []\n self._modifiers = []\n self._payable = False\n\n\n @property\n def return_type(self):\n \"\"\"\n Return the list of return type \n If no return, return None\n \"\"\"\n returns = self.returns\n if returns:\n return [r.type for r in returns]\n return None\n\n @property\n def name(self):\n \"\"\"\n str: function name\n \"\"\"\n if self._name == '':\n if self.is_constructor:\n return 'constructor'\n else:\n return 'fallback'\n return self._name\n\n @property\n def nodes(self):\n \"\"\"\n list(Node): List of the nodes\n \"\"\"\n return list(self._nodes)\n\n @property\n def entry_point(self):\n \"\"\"\n Node: Entry point of the function\n \"\"\"\n return self._entry_point\n\n @property\n def visibility(self):\n \"\"\"\n str: Function visibility\n \"\"\"\n return self._visibility\n\n @property\n def payable(self):\n \"\"\"\n bool: True if the function is payable\n \"\"\"\n return self._payable\n\n @property\n def is_constructor(self):\n \"\"\"\n bool: True if the function is the constructor\n \"\"\"\n return self._is_constructor or self._name == self.contract.name\n\n @property\n def view(self):\n \"\"\"\n bool: True if the function is declared as view\n \"\"\"\n return self._view\n\n @property\n def pure(self):\n \"\"\"\n bool: True if the function is declared as pure\n \"\"\"\n return self._pure\n\n @property\n def is_implemented(self):\n \"\"\"\n bool: True if the function is implemented\n \"\"\"\n return self._is_implemented\n\n @property\n def is_empty(self):\n \"\"\"\n bool: True if the function is empty\n \"\"\"\n return self._is_empty\n\n @property\n def parameters(self):\n \"\"\"\n list(LocalVariable): List of the parameters\n \"\"\"\n return list(self._parameters)\n\n @property\n def returns(self):\n \"\"\"\n list(LocalVariable): List of the return variables\n \"\"\"\n return list(self._returns)\n\n @property\n def modifiers(self):\n \"\"\"\n list(Modifier): List of the modifiers\n \"\"\"\n return list(self._modifiers)\n\n def __str__(self):\n return self._name\n\n @property\n def variables(self):\n \"\"\"\n Return all local variables\n Include paramters and return values\n \"\"\"\n return list(self._variables.values())\n\n @property\n def local_variables(self):\n \"\"\"\n Return all local variables (dont include paramters and return values)\n \"\"\"\n return list(set(self.variables) - set(self.returns) - set(self.parameters))\n\n def variables_as_dict(self):\n return self._variables\n\n @property\n def variables_read(self):\n \"\"\"\n list(Variable): Variables read (local/state/solidity)\n \"\"\"\n return list(self._vars_read)\n\n @property\n def variables_written(self):\n \"\"\"\n list(Variable): Variables written (local/state/solidity)\n \"\"\"\n return list(self._vars_written)\n\n @property\n def state_variables_read(self):\n \"\"\"\n list(StateVariable): State variables read\n \"\"\"\n return list(self._state_vars_read)\n\n @property\n def solidity_variables_read(self):\n \"\"\"\n list(SolidityVariable): Solidity variables read\n \"\"\"\n return list(self._solidity_vars_read)\n\n @property\n def state_variables_written(self):\n \"\"\"\n list(StateVariable): State variables written\n \"\"\"\n return list(self._state_vars_written)\n\n @property\n def variables_read_or_written(self):\n \"\"\"\n list(Variable): Variables read or written (local/state/solidity)\n \"\"\"\n return list(self._vars_read_or_written)\n\n @property\n def variables_read_as_expression(self):\n return self._expression_vars_read\n\n @property\n def variables_written_as_expression(self):\n return self._expression_vars_written\n\n @property\n def internal_calls(self):\n \"\"\"\n list(Function or SolidityFunction): List of function calls (that does not create a transaction)\n \"\"\"\n return list(self._internal_calls)\n\n @property\n def external_calls(self):\n \"\"\"\n list(ExpressionCall): List of message calls (that creates a transaction)\n \"\"\"\n return list(self._external_calls)\n\n @property\n def calls_as_expression(self):\n return self._expression_calls\n\n @property\n def expressions(self):\n \"\"\"\n list(Expression): List of the expressions\n \"\"\"\n expressions = [n.expression for n in self.nodes]\n expressions = [e for e in expressions if e]\n return expressions\n\n @property\n def signature(self):\n \"\"\"\n (str, list(str), list(str)): Function signature as\n (name, list parameters type, list return values type)\n \"\"\"\n return self.name, [str(x.type) for x in self.parameters], [str(x.type) for x in self.returns]\n\n @property\n def signature_str(self):\n \"\"\"\n str: func_name(type1,type2) returns (type3)\n Return the function signature as a str (contains the return values)\n \"\"\"\n name, parameters, returnVars = self.signature\n return name+'('+','.join(parameters)+') returns('+','.join(returnVars)+')'\n\n @property\n def full_name(self):\n \"\"\"\n str: func_name(type1,type2)\n Return the function signature without the return values\n \"\"\"\n name, parameters, _ = self.signature\n return name+'('+','.join(parameters)+')'\n\n\n @property\n def securewei(self):\n return self.contract.securewei\n\n def _filter_state_variables_written(self, expressions):\n ret = []\n for expression in expressions:\n if isinstance(expression, Identifier):\n ret.append(expression)\n if isinstance(expression, UnaryOperation):\n ret.append(expression.expression)\n if isinstance(expression, MemberAccess):\n ret.append(expression.expression)\n if isinstance(expression, IndexAccess):\n ret.append(expression.expression_left)\n return ret\n\n def _analyze_read_write(self):\n \"\"\" Compute variables read/written/...\n\n \"\"\"\n write_var = [x.variables_written_as_expression for x in self.nodes]\n write_var = [x for x in write_var if x]\n write_var = [item for sublist in write_var for item in sublist]\n write_var = list(set(write_var))\n # Remove dupplicate if they share the same string representation\n write_var = [next(obj) for i, obj in groupby(sorted(write_var, key=lambda x: str(x)), lambda x: str(x))]\n self._expression_vars_written = write_var\n\n write_var = [x.variables_written for x in self.nodes]\n write_var = [x for x in write_var if x]\n write_var = [item for sublist in write_var for item in sublist]\n write_var = list(set(write_var))\n # Remove dupplicate if they share the same string representation\n write_var = [next(obj) for i, obj in\\\n groupby(sorted(write_var, key=lambda x: str(x)), lambda x: str(x))]\n self._vars_written = write_var\n\n read_var = [x.variables_read_as_expression for x in self.nodes]\n read_var = [x for x in read_var if x]\n read_var = [item for sublist in read_var for item in sublist]\n # Remove dupplicate if they share the same string representation\n read_var = [next(obj) for i, obj in\\\n groupby(sorted(read_var, key=lambda x: str(x)), lambda x: str(x))]\n self._expression_vars_read = read_var\n\n read_var = [x.variables_read for x in self.nodes]\n read_var = [x for x in read_var if x]\n read_var = [item for sublist in read_var for item in sublist]\n # Remove dupplicate if they share the same string representation\n read_var = [next(obj) for i, obj in\\\n groupby(sorted(read_var, key=lambda x: str(x)), lambda x: str(x))]\n self._vars_read = read_var\n\n self._state_vars_written = [x for x in self.variables_written if\\\n isinstance(x, StateVariable)]\n self._state_vars_read = [x for x in self.variables_read if\\\n isinstance(x, (StateVariable))]\n self._solidity_vars_read = [x for x in self.variables_read if\\\n isinstance(x, (SolidityVariable))]\n\n self._vars_read_or_written = self._vars_written + self._vars_read\n\n def _analyze_calls(self):\n calls = [x.calls_as_expression for x in self.nodes]\n calls = [x for x in calls if x]\n calls = [item for sublist in calls for item in sublist]\n # Remove dupplicate if they share the same string representation\n calls = [next(obj) for i, obj in\\\n groupby(sorted(calls, key=lambda x: str(x)), lambda x: str(x))]\n self._expression_calls = calls\n\n internal_calls = [x.internal_calls for x in self.nodes]\n internal_calls = [x for x in internal_calls if x]\n internal_calls = [item for sublist in internal_calls for item in sublist]\n internal_calls = [next(obj) for i, obj in\n groupby(sorted(internal_calls, key=lambda x: str(x)), lambda x: str(x))]\n self._internal_calls = internal_calls\n\n external_calls = [x.external_calls for x in self.nodes]\n external_calls = [x for x in external_calls if x]\n external_calls = [item for sublist in external_calls for item in sublist]\n external_calls = [next(obj) for i, obj in\n groupby(sorted(external_calls, key=lambda x: str(x)), lambda x: str(x))]\n self._external_calls = external_calls\n\n\n def _explore_functions(self, f_new_values):\n values = f_new_values(self)\n explored = [self]\n to_explore = [c for c in self.internal_calls if\n isinstance(c, Function) and c not in explored]\n to_explore += [m for m in self.modifiers if m not in explored]\n\n while to_explore:\n f = to_explore[0]\n to_explore = to_explore[1:]\n if f in explored:\n continue\n explored.append(f)\n\n values += f_new_values(f)\n\n to_explore += [c for c in f.internal_calls if\\\n isinstance(c, Function) and c not in explored and c not in to_explore]\n to_explore += [m for m in f.modifiers if m not in explored and m not in to_explore]\n\n return list(set(values))\n\n def all_state_variables_read(self):\n \"\"\" recursive version of variables_read\n \"\"\"\n return self._explore_functions(lambda x: x.state_variables_read)\n\n def all_solidity_variables_read(self):\n \"\"\" recursive version of solidity_read\n \"\"\"\n return self._explore_functions(lambda x: x.solidity_variables_read)\n\n def all_expressions(self):\n \"\"\" recursive version of variables_read\n \"\"\"\n return self._explore_functions(lambda x: x.expressions)\n\n def all_state_variables_written(self):\n \"\"\" recursive version of variables_written\n \"\"\"\n return self._explore_functions(lambda x: x.state_variables_written)\n\n def all_internal_calls(self):\n \"\"\" recursive version of internal_calls\n \"\"\"\n return self._explore_functions(lambda x: x.internal_calls)\n\n def all_conditional_state_variables_read(self):\n \"\"\"\n Return the state variable used in a condition\n\n Over approximate and also return index access\n It won't work if the variable is assigned to a temp variable\n \"\"\"\n def _explore_func(func):\n ret = [n.state_variables_read for n in func.nodes if n.is_conditional()]\n return [item for sublist in ret for item in sublist]\n return self._explore_functions(lambda x: _explore_func(x))\n\n def all_conditional_solidity_variables_read(self):\n \"\"\"\n Return the Soldiity variables directly used in a condtion\n\n Use of the IR to filter index access\n Assumption: the solidity vars are used directly in the conditional node\n It won't work if the variable is assigned to a temp variable\n \"\"\"\n from securewei.slithir.operations.binary import Binary\n def _solidity_variable_in_node(node):\n ret = []\n for ir in node.irs:\n if isinstance(ir, Binary):\n ret += ir.read\n return [var for var in ret if isinstance(var, SolidityVariable)]\n def _explore_func(func, f):\n ret = [f(n) for n in func.nodes if n.is_conditional()]\n return [item for sublist in ret for item in sublist]\n return self._explore_functions(lambda x: _explore_func(x, _solidity_variable_in_node))\n\n def all_solidity_variables_used_as_args(self):\n \"\"\"\n Return the Soldiity variables directly used in a call\n\n Use of the IR to filter index access\n Used to catch check(msg.sender)\n \"\"\"\n from securewei.slithir.operations.internal_call import InternalCall\n def _solidity_variable_in_node(node):\n ret = []\n for ir in node.irs:\n if isinstance(ir, InternalCall):\n ret += ir.read\n return [var for var in ret if isinstance(var, SolidityVariable)]\n def _explore_func(func, f):\n ret = [f(n) for n in func.nodes]\n return [item for sublist in ret for item in sublist]\n return self._explore_functions(lambda x: _explore_func(x, _solidity_variable_in_node))\n\n def is_reading(self, variable):\n \"\"\"\n Check if the function reads the variable\n Args:\n variable (Variable):\n Returns:\n bool: True if the variable is read\n \"\"\"\n return variable in self.variables_read\n\n def is_reading_in_conditional_node(self, variable):\n \"\"\"\n Check if the function reads the variable in a IF node\n Args:\n variable (Variable):\n Returns:\n bool: True if the variable is read\n \"\"\"\n variables_read = [n.variables_read for n in self.nodes if n.contains_if()]\n variables_read = [item for sublist in variables_read for item in sublist]\n return variable in variables_read\n\n def is_reading_in_require_or_assert(self, variable):\n \"\"\"\n Check if the function reads the variable in an require or assert\n Args:\n variable (Variable):\n Returns:\n bool: True if the variable is read\n \"\"\"\n variables_read = [n.variables_read for n in self.nodes if n.contains_require_or_assert()]\n variables_read = [item for sublist in variables_read for item in sublist]\n return variable in variables_read\n\n def is_writing(self, variable):\n \"\"\"\n Check if the function writes the variable\n Args:\n variable (Variable):\n Returns:\n bool: True if the variable is written\n \"\"\"\n return variable in self.variables_written\n\n def apply_visitor(self, Visitor):\n \"\"\"\n Apply a visitor to all the function expressions\n Args:\n Visitor: securewei.visitors\n Returns\n list(): results of the visit\n \"\"\"\n expressions = self.expressions\n v = [Visitor(e).result() for e in expressions]\n return [item for sublist in v for item in sublist]\n\n\n def cfg_to_dot(self, filename):\n \"\"\"\n Export the function to a dot file\n Args:\n filename (str)\n \"\"\"\n with open(filename, 'w') as f:\n f.write('digraph{\\n')\n for node in self.nodes:\n f.write('{}[label=\"{}\"];\\n'.format(node.node_id, str(node)))\n for son in node.sons:\n f.write('{}->{};\\n'.format(node.node_id, son.node_id))\n\n f.write(\"}\\n\")\n\n def slithir_cfg_to_dot(self, filename):\n \"\"\"\n Export the function to a dot file\n Args:\n filename (str)\n \"\"\"\n from securewei.core.cfg.node import NodeType\n with open(filename, 'w') as f:\n f.write('digraph{\\n')\n for node in self.nodes:\n label = 'Node Type: {}\\n'.format(NodeType.str(node.type))\n if node.expression:\n label += '\\nEXPRESSION:\\n{}\\n'.format(node.expression)\n label += '\\nIRs:\\n' + '\\n'.join([str(ir) for ir in node.irs])\n f.write('{}[label=\"{}\"];\\n'.format(node.node_id, label))\n for son in node.sons:\n f.write('{}->{};\\n'.format(node.node_id, son.node_id))\n\n f.write(\"}\\n\")\n\n def get_summary(self):\n \"\"\"\n Return the function summary\n Returns:\n (str, str, list(str), list(str), listr(str), list(str), list(str);\n name, visibility, modifiers, vars read, vars written, internal_calls, external_calls\n \"\"\"\n return (self.name, self.visibility,\n [str(x) for x in self.modifiers],\n [str(x) for x in self.state_variables_read + self.solidity_variables_read],\n [str(x) for x in self.state_variables_written],\n [str(x) for x in self.internal_calls],\n [str(x) for x in self.external_calls])\n\n def is_protected(self):\n \"\"\"\n Determine if the function is protected using a check on msg.sender\n\n Only detects if msg.sender is directly used in a condition\n For example, it wont work for:\n address a = msg.sender\n require(a == owner)\n Returns\n (bool)\n \"\"\"\n\n if self.is_constructor:\n return True\n conditional_vars = self.all_conditional_solidity_variables_read()\n args_vars = self.all_solidity_variables_used_as_args()\n return SolidityVariableComposed('msg.sender') in conditional_vars + args_vars\n","sub_path":"CORE/core/declarations/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":20339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"305690126","text":"import sys\nimport requests\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nimport PyQt5.QtCore as QtCore\nfrom Connection import Connection\nimport json\nimport ctypes\nmyappid = 'SleepyGuy.unofficial.devrant.1' # arbitrary string\nctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)\nURI = \"https://www.devrant.io/api/devrant/rants?app=3&token_id=3\"\ndef algo():\n data = requests.get(URI + '')\n return json.loads(data.text)\n\n\nclass w (QMainWindow):\n def __init__(self):\n super().__init__()\n self.startUi()\n\n def startUi(self):\n\n self.setGeometry(100,100,600,600)\n self.maximumSize()\n self.setWindowTitle('Devrant')\n self.setWindowIcon(QIcon('web.png'))\n self.setStyleSheet(\"QMainWindow{background-color: #011e4c;}\")\n\n\n self.text = QTextEdit()\n self.text.setReadOnly(True)\n\n self.text.setStyleSheet(\"QTextEdit{\"\n \" background-color:#3d4859;\"\n \" color: white;\"\n \"border-radius: 5px;\"\n \" font-weight: bold;\"\n \" padding: 1em;\"\n \"font-size: 12px;\"\n \"text-align:center;\"\n \"}\")\n\n self.text.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.text.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n Connection.get_algo(self)\n\n exitA = QAction('Exit',self)\n exitA.setShortcut('Ctrl+Q')\n exitA.setToolTip('Close app')\n exitA.triggered.connect(self.close)\n\n widget = QWidget()\n widget.move(0,0)\n btn = QPushButton('Show rants',self)\n btn.setToolTip('This shows rants')\n btn.clicked.connect(self.algo)\n btn.setStyleSheet(\"QPushButton{background: white;\"\n \"border:none;\"\n \"margin:1%;\"\n \"color: black;\"\n \"font-size:10px;\"\n \"}\")\n btn.setFixedHeight(20)\n btn2 = QPushButton('Recent', self)\n btn2.setToolTip('This shows recent rants')\n btn2.clicked.connect(self.recent)\n btn2.setStyleSheet(\"QPushButton{border:none; border-radius:5px;\"\n \" background-color:#edeff2;\"\n \"color:black; font-size:10px;}\")\n btn2.setFixedHeight(20)\n\n search_btn = QPushButton('Search',self)\n search_btn.clicked.connect(self.search)\n search_btn.setStyleSheet(\"QPushButton{border:none; border-radius:5px; \"\n \"background-color:#edeff2;\"\n \"color:black; font-size:10px;}\")\n search_btn.setFixedHeight(20)\n\n self.search_bar = QPlainTextEdit()\n self.search_bar.setFixedSize(75,20)\n self.search_bar.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n\n\n grid = QGridLayout()\n grid.setSpacing(10)\n cWidget = QWidget()\n self.setWindowIcon(QIcon('penguin-icon.png'))\n cWidget.setFont(QFont('Roboto'))\n cWidget.setLayout(grid)\n\n\n grid.addWidget(btn, 1,0)\n grid.addWidget(btn2,2,0)\n grid.addWidget(self.text,1,5,5,1)\n grid.addWidget(self.search_bar,3,0)\n grid.addWidget(search_btn,4,0)\n self.setCentralWidget(cWidget)\n\n self.show()\n def algo(self):\n Connection.get_algo(object=self)\n def recent(self):\n self.text.clear()\n self.text.append(\"Loading recent rants...\")\n Connection.recent_rants(object=self)\n def search(self):\n term = self.search_bar.toPlainText()\n print('Term is '+term)\n Connection.search(term,self)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n example = w()\n sys.exit(app.exec_())\n\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"137866338","text":"# coding=utf-8\n\"\"\"\n\nPROBLEM 020 - Factorial Digit Sum\n\nWritten by: Yuanjie Li\nDate: Oct 23, 2017\n\nn! means n × (n − 1) × ... × 3 × 2 × 1\n\nFor example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,\nand the sum of the digits in the number 10! is\n 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.\n\nFind the sum of the digits in the number 100!\n\n\"\"\"\ndef main():\n # Python is cheating.\n fact = 100\n for x in xrange(2,100):\n fact *= x\n\n print(sum([int(x) for x in str(fact)]))\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"p020/fact_sum.py","file_name":"fact_sum.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"270367359","text":"import socket\n\nip = \"10.0.0.69\"\nport = 50149\n\n# Connect to the server\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((ip, port))\n\n# Send the data\nmessage = 'Hello, world'\nprint('Sending : \"%s\"' % message)\nlen_sent = s.send(message.encode('ascii'))\n\n# Receive a response\nresponse = s.recv(len_sent).decode('ascii')\nprint('Received: \"%s\"' % response)\n\n# Clean up\ns.close()","sub_path":"echo_client2.py","file_name":"echo_client2.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"633155426","text":"from django.urls import path\nfrom beautyapp import views\nfrom django.contrib import admin\n\nfrom django.conf import settings\nadmin.site.header = 'Elixir Beauty Spa'\n\nurlpatterns = [\n path('about/',views.about,name='about'),\n path('service/',views.services,name='service'),\n # path('gallery/',views.spa_treatment,name='spa_treatment'),\n # path('blog/',views.blog,name='blog'),\n # path('contact/',views.contact,name='contact'),\n path('register/',views.register,name='register'),\n path('login/',views.login,name='login'),\n path('logout/',views.logout,name='logout'),\n path('appointment/',views.appointment,name='appointment'),\n path('contact/',views.contact,name='contact'),\n path('gift/',views.buygift,name='buygift'),\n path('gallery/',views.gallery,name='gallery'),\n path('espackage/',views.espackage,name='espackage'),\n path('careers/',views.careers,name='careers'),\n path('mens/',views.mens,name='mens'),\n path('footrefl/',views.footrefl,name='footrefl'),\n path('memberplan',views.memberplan,name='memberplan'),\n path('eservice',views.eservice,name='eservice'),\n\n\n\n\n\n\n\n]\n","sub_path":"Documents/djangoenv/beautyapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"594358718","text":"from flask import Flask, request\nfrom flask_restful import Resource, Api\nimport mysql.connector\n\n\n\napp = Flask(__name__)\napi = Api(app)\n\nclass Student(Resource):\n def get(self, name):\n return { 'student':name}\n\napi.add_resource(Student, '/student/')\napp.run(debug=True, port=5000)\n\n\n# mongodb://SreeAnanthaKannan:qwe$7500@ds163354.mlab.com:63354/testt","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"143090256","text":"__author__ = 'nsifniotis'\n\n\nimport itertools\n\n\ndistance_map = dict()\n\ndef add_distance_to_map(origin, destination, distance):\n if origin not in distance_map:\n distance_map[origin] = dict()\n\n if destination in distance_map[origin]:\n distance_map[origin][destination] += distance\n else:\n distance_map[origin][destination] = distance\n\n\ndef compute_distance(list):\n distance = 0\n for i in range(0, len(list) - 1):\n distance += distance_map[list[i]][list[i + 1]]\n\n distance += distance_map[list[0]][list[len(list) - 1]]\n return distance\n\n\nwith open(\"input_13.txt\") as input_file:\n for line in input_file.readlines():\n parts = line.split(\" \")\n distance = int(parts[3])\n if parts[2] == 'lose':\n distance = -distance\n\n add_distance_to_map(parts[0], parts[10][:-2], distance)\n add_distance_to_map(parts[10][:-2], parts[0], distance)\n add_distance_to_map(\"Nick\", parts[0], 0)\n add_distance_to_map(parts[0], \"Nick\", 0)\n\n\nplaces_list = distance_map.keys()\ncombo_generator = itertools.permutations(places_list)\ninitial_distance = 0\n\nfor permutation in combo_generator:\n holding_distance = compute_distance(permutation)\n if holding_distance > initial_distance:\n initial_distance = holding_distance\n print(str(permutation) + \" -> \" + str(initial_distance))\n\nprint(\"Done!\")","sub_path":"day_thirteen.py","file_name":"day_thirteen.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"341281854","text":"import os, re, sys\nimport csv\nimport json\nimport xlrd, xlwt\nimport numpy as np\n\n\nN_FEATURES = 16\n\nfeatures = ['head_body_dist', 'body_speed_x', 'body_speed_y',\n 'head_speed_x', 'head_speed_y', 'head_body_dist_change',\n 'head_rotation', 'body_speed', 'head_speed',\n 'body_acceleration', 'head_acceleration',\n 'body_coord_x', 'body_coord_y',\n 'head_coord_x', 'head_coord_y',\n 'temp', 'img', 'date'#, 'frames',\n ]\n\n\nos.chdir('/root/Novosad/mouses/')\n\n\ndef create_avg(dirname, mouse):\n if not os.path.isdir(os.path.join('check', dirname, 'xlses', 'avg')):\n os.mkdir(os.path.join('check', dirname, 'xlses', 'avg'))\n\n data_path = os.path.join('check', dirname, 'xlses', 'data')\n avg_path = os.path.join('check', dirname, 'xlses', 'avg')\n \n xlses = [f for f in os.listdir(data_path) if f.split('_')[0] == mouse]\n xlses.sort(key=lambda x: (int(re.split('[._]', x)[3]), re.split('[._]', x)[1],\n int(re.split('[._]', x)[2]), re.split('[._]', x)[6],\n int(re.split('[._]', x)[4]) % 12, int(re.split('[._]', x)[5])))\n\n data = [[] for i in range(N_FEATURES)]\n dates = [[] for i in range(2)]\n\n for _, xls in enumerate(xlses):\n print(xls)\n\n with open(os.path.join(data_path, xls), newline='') as csvfile:\n cur_data = list(csv.reader(csvfile))\n if len(cur_data) > 20:\n cur_data = np.array(cur_data).T.tolist()\n\n for i in range(N_FEATURES):\n data[i] += np.array(cur_data[i]).astype(float).tolist()\n\n dates[0] += cur_data[-2]\n dates[1] += cur_data[-1]\n\n # sheet = xlrd.open_workbook(os.path.join(data_path, xls))\n # sheet = sheet.sheet_by_index(0)\n #\n # for i in range(N_FEATURES):\n # feature = np.array(sheet.col_values(i)).astype(float)\n # data[i] += feature.tolist()\n #\n # for i in [17, 18]:\n # feature = sheet.col_values(i)\n # dates[i - 17] += feature\n\n data = np.array(data).T.tolist()\n bad = np.where(np.isnan(data[:]))[0].tolist()\n for i in bad:\n data[i][2] = 0\n data[i][4] = 0\n\n times = dates[1]\n\n dates = np.array(dates).T.tolist()\n\n day_indexes = [i for i in range(1, len(times)) if '12:00:00 AM' in times[i] and '12:00:00 AM' not in times[i - 1]]\n print(day_indexes)\n day_indexes = [0] + day_indexes + [len(times) - 1]\n\n data_split_by_days = [data[day_indexes[i]: day_indexes[i + 1]] for i in range(len(day_indexes) - 1)]\n dates_split_by_days = [dates[day_indexes[i]: day_indexes[i + 1]] for i in range(len(day_indexes) - 1)]\n\n data_split_by_days = data_split_by_days[1:-1]\n data_split_by_days = data_split_by_days[-3:]\n\n dates_split_by_days = dates_split_by_days[1:-1]\n dates_split_by_days = dates_split_by_days[-3:]\n\n tt = 24 * 6\n if not os.path.isdir(os.path.join('check', dirname, 'xlses', 'avg', str(tt))):\n os.mkdir(os.path.join('check', dirname, 'xlses', 'avg', str(tt)))\n\n mouse = 'left_' if mouse == '0' else 'right_'\n sheet1 = xlwt.Workbook()\n table = sheet1.add_sheet('data from mouse')\n\n for kk in range(len(features)):\n table.write(0, kk, mouse + features[kk])\n\n xls_ind = 1\n\n avg_day = [[0 for i in range(len(data_split_by_days))] for j in range(tt)]\n avg_dates = [0 for i in range(tt)]\n\n for day in range(len(data_split_by_days)):\n frames = len(data_split_by_days[day]) // tt\n\n splitted_data = [data_split_by_days[day][i * frames: (i + 1) * frames] for i in range(tt)]\n splitted_dates = [dates_split_by_days[day][i * frames: (i + 1) * frames] for i in range(tt)]\n\n for _ in range(tt):\n mean_values = np.mean(splitted_data[_], axis=0)\n avg_day[_][day] = mean_values.tolist()\n date = splitted_dates[_][0]\n if day == 0:\n avg_dates[_] = date\n\n # TABLE\n\n for t in range(tt):\n # print(np.array([avg_day[t][day] for day in range(len(data_split_by_days))]))\n avg_day[t] = np.mean(np.array([avg_day[t][day] for day in range(len(data_split_by_days))]), axis=0).tolist()\n\n for t in range(tt):\n for s in range(len(avg_day[t])):\n table.write(xls_ind, s, avg_day[t][s])\n\n table.write(xls_ind, s + 1, avg_dates[t][0])\n table.write(xls_ind, s + 2, avg_dates[t][1])\n\n xls_ind += 1\n\n sheet1.save(os.path.join('check', dirname, 'xlses', 'avg', str(tt), '{}avg_day.xls'.format(mouse)))\n\n\nif __name__ == '__main__':\n create_avg(sys.argv[1], sys.argv[2])","sub_path":"important_files/create_avg_day.py","file_name":"create_avg_day.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"255368745","text":"import os\nimport pandas as pd\nfrom pptx import Presentation\nfrom pd2ppt import df_to_table\nfrom pptx.chart.data import CategoryChartData\nfrom pptx.enum.chart import XL_CHART_TYPE, XL_LEGEND_POSITION, XL_DATA_LABEL_POSITION\nfrom pptx.enum.dml import MSO_THEME_COLOR_INDEX\nfrom pptx.enum.text import MSO_VERTICAL_ANCHOR, PP_PARAGRAPH_ALIGNMENT\nfrom pptx.util import Inches, Pt, Cm\nfrom pptx.dml.color import RGBColor\nfrom datetime import datetime\n\nimport HAR_Analysis as har\nimport utils\nimport objects\n\n# Some Technical Functions for PPTX\n\n\ndef format_slide_table(slide, new_table, title_font, row_font, col_idx=None, col_wid=None):\n # Setting font size for header\n for cell in new_table.rows[0].cells:\n for par in cell.text_frame.paragraphs:\n par.font.size = Pt(title_font)\n # Setting font size for lines\n for r in range(1, len(new_table.rows)):\n for cell in new_table.rows[r].cells:\n for par in cell.text_frame.paragraphs:\n par.font.size = Pt(row_font)\n # Setting vertical alignment for all\n for cell in new_table.iter_cells():\n cell.vertical_anchor = MSO_VERTICAL_ANCHOR.MIDDLE\n # Setting column width\n total_table_width = 0.0\n for cc in new_table.columns:\n width_cm = round(float(cc.width / 360000), 3)\n total_table_width += width_cm\n if col_idx and col_wid:\n subset_width = 0.0\n for ci in col_idx:\n new_table.columns[ci].width = Cm(col_wid[col_idx.index(ci)])\n subset_width += Cm(col_wid[col_idx.index(ci)])\n rest_width = Cm(total_table_width) - subset_width\n col_num = len(new_table.columns)\n for i in range(0, col_num):\n if i in col_idx:\n continue\n else:\n new_table.columns[i].width = round(rest_width / (col_num - len(col_idx)))\n\n\ndef create_slide(layout=3, title_text=None, subtitle_text=None, presentation=None):\n presa = presentation\n slide = presa.slides.add_slide(presa.slide_layouts[layout])\n if slide.shapes.title:\n title_placeholder = slide.shapes.title\n title_placeholder.text = title_text\n for shape in slide.placeholders:\n if 'Subtitle' in shape.name:\n shape.text = subtitle_text\n #print('\\nNew slide with following placeholders created:')\n #for shape in slide.placeholders:\n #print(f'{shape.placeholder_format.idx}, {shape.name}')\n return slide\n\n\ndef create_presentation(path_to_har_file, path_to_pptx):\n\n ########## 1.1 Get Objects\n\n analysis = har.StoryAnalyzer(path_to_har_file)\n analysis.read_har_file()\n\n # 1.1.1 Product and Story\n\n products = analysis.get_product_info()\n story = analysis.get_story_info_2()\n\n # 1.1.2. All widgets existing in Story (from ContentLib) + Calculation Entities\n\n widgets_content_lib = analysis.get_widgets_contentlib_info()[0]\n calc_entities = analysis.get_widgets_contentlib_info()[1]\n\n # 1.1.3 Get Calls Info\n\n calls = analysis.get_calls_info(calc_entities)\n\n # 1.1.4 Get all widgets that have been loaded (Events)\n\n events_widgets = analysis.get_widgets_info()\n\n # 1.1.5 Get all widgets with MDS Requests\n\n # test_calls + test_widgets\n\n # 1.1.6 Action Summary\n\n # events_widgets\n\n # 1.1.7 Widgets + MDS Execution Timeline\n\n # calls + events_widgets\n\n # 1.1.8 All Widgets Timeline\n\n # events_widgets\n\n # 1.1.9 MDS Request for Widget Info\n\n presentation = Presentation(os.getcwd() + '/SAP_Template_Presentation.pptx')\n\n # 1 Slide - Title\n\n if story:\n\n story_frame = utils.get_story_frame(story)\n title_text = story_frame.T['Story Name'][0]\n story_title = f'Story Analysis ({title_text})'\n slide1 = create_slide(layout=0, title_text=story_title, subtitle_text=f'by {os.getlogin()}', presentation=presentation)\n image = slide1.placeholders[12]\n image.insert_picture(os.getcwd() + '/banner.png')\n\n # 2 Slide - Total Story Info And Widgets Total Count - Two Tables\n\n if products:\n\n product_frame = utils.get_product_frame(products)\n story_product_frame = pd.concat((product_frame, story_frame))\n title = 'General Story Info And Widgets Total Count'\n slide2 = create_slide(layout=1, title_text=title, presentation=presentation)\n table1 = slide2.placeholders[10]\n df = story_product_frame.reset_index()\n df = df.rename(columns=df.iloc[0])\n df_to_table(slide2, df, left=table1.left, top=table1.top, width=table1.width, height=table1.height)\n\n if widgets_content_lib:\n\n widgets_content_lib_frame = utils.get_widgets_from_contentlib_frame(widgets_content_lib)\n table2 = slide2.placeholders[11]\n widgets_frame = widgets_content_lib_frame[['Story Name', 'Page Title', 'Widget ID', 'Widget Class']]\n widgets_frame_columns = ['Story Name', 'Page Title', 'Number of Widgets', 'Widget Class']\n widgets_frame.columns = widgets_frame_columns\n widgets_frame = widgets_frame.groupby(['Story Name', 'Page Title', 'Widget Class']).count()\n df_to_table(slide2, widgets_frame.reset_index(), left=table2.left, top=table2.top,\n width=table2.width, height=table2.height)\n\n # 3 Slide - Time Graphs - Pie Charts\n\n if calls:\n\n story_summary = utils.get_story_summary(calls)\n slide3 = create_slide(layout=4, title_text='Time Graphs in Seconds', presentation=presentation)\n slide3.placeholders[17].text = 'Total and average time graphs are made with wait time excluded'\n #slide3.placeholders[17].text.font.size = Pt(18)\n total_time_chart_shape = slide3.placeholders[22]\n average_time_chart_shape = slide3.placeholders[23]\n biggest_time_chart_shape = slide3.placeholders[24]\n\n pie_charts_df = story_summary\n wait_index = pie_charts_df.index.isin(['wait'])\n # Prepare Data\n total_time_chart_data = CategoryChartData()\n # Labels\n total_time_chart_data.categories = pie_charts_df[~wait_index].index\n # Data\n total_time_chart_data.add_series('Series 1', pie_charts_df['total_runtime'][~wait_index].map('{:,.2f}'.format))\n total_time_chart_shape = total_time_chart_shape.insert_chart(XL_CHART_TYPE.PIE, total_time_chart_data)\n total_time_chart = total_time_chart_shape.chart\n # Format Chart\n total_time_chart.has_legend = True\n total_time_chart.legend.position = XL_LEGEND_POSITION.CORNER\n total_time_chart.legend.font.size = Pt(9)\n total_time_chart.legend.include_in_layout = False\n total_time_chart.plots[0].has_data_labels = True\n total_time_chart_data_labels = total_time_chart.plots[0].data_labels\n total_time_chart_data_labels.font.size = Pt(9)\n total_time_chart_data_labels.position = XL_DATA_LABEL_POSITION.OUTSIDE_END\n slide3.placeholders[15].text = 'Total Trace Time with Wait Time Excluded in Seconds'\n #slide3.placeholders[15].text.font.size = Pt(16)\n\n average_time_chart_data = CategoryChartData()\n average_time_chart_data.categories = pie_charts_df[~wait_index].index\n average_time_chart_data.add_series('Series 1', pie_charts_df['average_runtime'][~wait_index].map('{:,.2f}'.format))\n average_time_chart_shape = average_time_chart_shape.insert_chart(XL_CHART_TYPE.PIE, average_time_chart_data)\n average_time_chart = average_time_chart_shape.chart\n average_time_chart.has_legend = True\n average_time_chart.legend.position = XL_LEGEND_POSITION.CORNER\n average_time_chart.legend.font.size = Pt(9)\n average_time_chart.legend.include_in_layout = False\n average_time_chart.plots[0].has_data_labels = True\n average_time_chart_data_labels = average_time_chart.plots[0].data_labels\n average_time_chart_data_labels.font.size = Pt(9)\n average_time_chart_data_labels.position = XL_DATA_LABEL_POSITION.OUTSIDE_END\n slide3.placeholders[20].text = 'Average Times with Wait Time Excluded'\n #slide3.placeholders[20].text.font.size = Pt(16)\n\n biggest_time_chart_data = CategoryChartData()\n biggest_time_chart_data.categories = pie_charts_df.index\n biggest_time_chart_data.add_series('Series 1', pie_charts_df['maximum_runtime'].map('{:,.2f}'.format))\n biggest_time_chart_shape = biggest_time_chart_shape.insert_chart(XL_CHART_TYPE.PIE, biggest_time_chart_data)\n biggest_time_chart = biggest_time_chart_shape.chart\n biggest_time_chart.has_legend = True\n biggest_time_chart.legend.position = XL_LEGEND_POSITION.CORNER\n biggest_time_chart.legend.font.size = Pt(9)\n biggest_time_chart.legend.include_in_layout = False\n biggest_time_chart.plots[0].has_data_labels = True\n biggest_time_chart_data_labels = biggest_time_chart.plots[0].data_labels\n biggest_time_chart_data_labels.font.size = Pt(9)\n biggest_time_chart_data_labels.position = XL_DATA_LABEL_POSITION.OUTSIDE_END\n slide3.placeholders[21].text = 'The biggest times'\n #slide3.placeholders[21].text.font.size = Pt(16)\n\n # 4 Slide - Widgets executed when opening page(s)\n\n if events_widgets:\n\n df = utils.get_widgets_from_events_frame(events_widgets)[0]\n actions = df['User Action'].unique().tolist()\n for action in actions:\n #events_widgets_df = df.query(\"'User Action' == @action\")\n events_widgets_df = df[df['User Action'] == action].drop(columns=['User Action Start Time'])\n max_lines_on_slide = 15\n slide_number = 0\n\n while len(events_widgets_df.index) > 0:\n if len(events_widgets_df.index) > max_lines_on_slide:\n slide_number += 1\n slide4 = create_slide(layout=2, title_text='Widgets executed during user action: \"' + action + '\" (' + str(slide_number) + ') ',\n presentation=presentation)\n table = slide4.placeholders[10]\n slide4_df = df_to_table(slide4, events_widgets_df[0:(max_lines_on_slide - 1)], left=table.left, top=table.top,\n width=table.width, height=table.height)\n events_widgets_df = events_widgets_df[max_lines_on_slide:len(events_widgets_df.index)]\n format_slide_table(slide4, slide4_df.table, title_font=12, row_font=10, col_idx=[0,1,2,3,4,5],\n col_wid=[6.8, 3.4, 6.2, 2.3, 4.6, 4.6, 3.2])\n row_height = slide4_df.table.rows[0].height\n else:\n slide_number += 1\n slide4 = create_slide(layout=2, title_text='Widgets executed during user action: \"' + action + '\" (' + str(slide_number) + ') ',\n presentation=presentation)\n table = slide4.placeholders[10]\n slide4_df = df_to_table(slide4, events_widgets_df, left=table.left, top=table.top,\n width=table.width, height=table.height)\n format_slide_table(slide4, slide4_df.table, title_font=12, row_font=10, col_idx=[0,1,2,3,4,5],\n col_wid=[6.8, 3.4, 6.2, 2.3, 4.6, 4.6, 3.2])\n events_widgets_df = events_widgets_df.iloc[0:0]\n row_height = slide4_df.table.rows[0].height\n for row in slide4_df.table.rows:\n row.height = Cm(0.8)\n\n # 5 Slide - Widgets with MDS Requests\n\n if calls and events_widgets:\n\n df = utils.get_widgets_from_mds_frame(calls, events_widgets)[0]\n actions = df['User Action'].unique().tolist()\n for action in actions:\n mds_widgets_df = df[df['User Action'] == action].drop(columns=['User Action'])\n max_lines_on_slide = 15\n slide_number = 0\n\n while len(mds_widgets_df.index) > 0:\n if len(mds_widgets_df.index) > max_lines_on_slide:\n slide_number += 1\n slide5 = create_slide(layout=2, title_text='Widgets with MDS requests for action \"' + action + '\" (' + str(slide_number) + ') ',\n presentation=presentation)\n table = slide5.placeholders[10]\n slide5_df = df_to_table(slide5, mds_widgets_df[0:(max_lines_on_slide - 1)], left=table.left,\n top=table.top,\n width=table.width, height=table.height)\n mds_widgets_df = mds_widgets_df[max_lines_on_slide:len(mds_widgets_df.index)]\n format_slide_table(slide5, slide5_df.table, title_font=12, row_font=10, col_idx=[0, 1, 3, 4],\n col_wid=[2.8, 6.2, 4.6, 4.6])\n else:\n slide_number += 1\n slide5 = create_slide(layout=2, title_text='Widgets with MDS requests for action \"' + action + '\" (' + str(slide_number) + ') ',\n presentation=presentation)\n table = slide5.placeholders[10]\n slide5_df = df_to_table(slide5, mds_widgets_df, left=table.left, top=table.top,\n width=table.width, height=table.height)\n format_slide_table(slide5, slide5_df.table, title_font=12, row_font=10, col_idx=[0, 1, 3, 4],\n col_wid=[2.8, 6.2, 4.6, 4.6])\n mds_widgets_df = mds_widgets_df.iloc[0:0]\n\n # 6 Slide - Action Summary\n\n if events_widgets:\n\n df = utils.get_widgets_from_events_frame(events_widgets)[1]\n table_summary = df.groupby('User Action', as_index=False) \\\n .agg({'User Action Start': lambda x: x.iloc[0], 'Widget Start':'min', 'Widget Finish':'max'}) \\\n .sort_values('User Action Start') \\\n .rename(columns={'Widget Start':'First Widget Start', 'Widget Finish':'Last Widget End'})\n table_summary['Widget Start to End (sec)'] = table_summary['Last Widget End'] - table_summary['First Widget Start']\n table_summary['Widget Start to End (sec)'] = round(table_summary['Widget Start to End (sec)'].dt.total_seconds(), 3)\n table_summary['Action Start to Widget End (sec)'] = table_summary['Last Widget End'] - table_summary['User Action Start']\n table_summary['Action Start to Widget End (sec)'] = round(table_summary['Action Start to Widget End (sec)'].dt.total_seconds(), 3)\n table_summary['User Action Start'] = table_summary['User Action Start'].dt.strftime(\"%H:%M:%S.%f\")\n table_summary['First Widget Start'] = table_summary['First Widget Start'].dt.strftime(\"%H:%M:%S.%f\")\n table_summary['Last Widget End'] = table_summary['Last Widget End'].dt.strftime(\"%H:%M:%S.%f\")\n\n slide6 = create_slide(layout=2, title_text='Summary of User Actions', presentation=presentation)\n table = slide6.placeholders[10]\n slide6_df = df_to_table(slide6, table_summary, left=table.left,\n top=table.top,\n width=table.width)\n format_slide_table(slide6, slide6_df.table, title_font=12, row_font=12, col_idx=[1, 2, 3, 4, 5],\n col_wid=[5.8, 5.8, 5.8, 3.5, 3.5])\n for row in slide6_df.table.rows:\n row.height = Cm(0.8)\n\n # 7 Slide - Widget & MDS Execution timeline\n\n if calls and events_widgets:\n\n df = utils.get_widgets_from_mds_frame(calls, events_widgets)[1]\n actions = df['User Action'].unique().tolist()\n for action in actions:\n gantt_df = df[df['User Action'] == action]\n slide7 = create_slide(layout=5, title_text='Widget & MDS Execution timeline for action: \"' + action + '\" ', presentation=presentation)\n gantt_chart_shape = slide7.placeholders[22]\n gantt_chart_data = CategoryChartData()\n gantt_chart_data.categories = gantt_df['MDS Number'].values\n gantt_chart_data.add_series('', gantt_df['Start Mark'], number_format=\"hh:mm:ss.000\")\n gantt_chart_data.add_series('Widget ->', gantt_df['Before MDS Duration'], number_format=\"hh:mm:ss.000\")\n gantt_chart_data.add_series('MDS Request', gantt_df['MDS Duration'], number_format=\"hh:mm:ss.000\")\n gantt_chart_data.add_series('<- Widget', gantt_df['After MDS Duration'], number_format=\"hh:mm:ss.000\")\n gantt_chart_shape = gantt_chart_shape.insert_chart(XL_CHART_TYPE.BAR_STACKED, gantt_chart_data)\n gantt_chart = gantt_chart_shape.chart\n gantt_chart.has_legend = True\n gantt_chart.legend.position = XL_LEGEND_POSITION.BOTTOM\n gantt_chart.legend.include_in_layout = False\n\n category_axis = gantt_chart.category_axis\n category_axis.tick_labels.font.size = Pt(12)\n\n value_axis = gantt_chart.value_axis\n value_axis.tick_labels.font.size = Pt(12)\n\n plot = gantt_chart.plots[0]\n plot.gap_width = 50\n plot.series[0].format.fill.background()\n plot.series[1].format.fill.solid()\n plot.series[2].format.fill.solid()\n plot.series[3].format.fill.solid()\n plot.series[0].format.line.fill.background()\n plot.series[1].format.fill.fore_color.theme_color = MSO_THEME_COLOR_INDEX.ACCENT_4\n plot.series[3].format.fill.fore_color.theme_color = MSO_THEME_COLOR_INDEX.ACCENT_4\n plot.series[2].format.fill.fore_color.theme_color = MSO_THEME_COLOR_INDEX.ACCENT_5\n plot.has_data_labels = True\n plot.data_labels.font.size = Pt(10)\n plot.data_labels.number_format = \"mm:ss.000\"\n plot.series[0].data_labels.font.fill.background()\n plot.series[1].data_labels.font.color.rgb = RGBColor(0x01, 0x01, 0x01)\n plot.series[3].data_labels.font.color.rgb = RGBColor(0x01, 0x01, 0x01)\n\n # 8 Slide - Gantt Common Widgets timelines (by Action)\n\n if events_widgets:\n\n df = utils.get_widgets_from_events_frame(events_widgets)[1]\n actions = df['User Action'].unique().tolist()\n for action in actions:\n gantt_df = df[df['User Action'] == action]\n slide8 = create_slide(layout=5, title_text='All Widgets Timeline for User Action: \"' + action + '\" ', presentation=presentation)\n gantt_chart_shape = slide8.placeholders[22]\n gantt_chart_data = CategoryChartData()\n\n gantt_chart_data.categories = gantt_df['Label'].values\n gantt_chart_data.add_series('', gantt_df['Widget Start'], number_format=\"hh:mm:ss.000\")\n gantt_chart_data.add_series('Widget runtime', gantt_df['Widget Duration'], number_format=\"hh:mm:ss.000\")\n\n gantt_chart_shape = gantt_chart_shape.insert_chart(XL_CHART_TYPE.BAR_STACKED, gantt_chart_data)\n gantt_chart = gantt_chart_shape.chart\n gantt_chart.has_legend = True\n gantt_chart.legend.position = XL_LEGEND_POSITION.BOTTOM\n gantt_chart.legend.include_in_layout = False\n\n category_axis = gantt_chart.category_axis\n category_axis.tick_labels.font.size = Pt(10)\n value_axis = gantt_chart.value_axis\n value_axis.tick_labels.font.size = Pt(9)\n plot = gantt_chart.plots[0]\n plot.gap_width = 50\n plot.series[0].format.fill.background()\n plot.series[0].format.line.fill.background()\n plot.series[0].data_labels.font.fill.background()\n plot.series[1].format.fill.solid()\n #plot.series[1].format.fill.fore_color.rgb = RGBColor(0x9A, 0xC8, 0xFC)\n plot.series[1].format.fill.fore_color.rgb = RGBColor(0, 188, 242)\n plot.has_data_labels = True\n plot.data_labels.font.size = Pt(9)\n plot.data_labels.number_format = \"mm:ss.000\"\n\n # 9 Slides with MDS Info and MDS Definition\n\n if calls:\n\n index = 1\n for call in calls:\n if isinstance(call, objects.Call_2) and call.get_response_type == 'Batch':\n # First Slide: tables with MDS Details and Views Info + graph\n mds_timings_frame = utils.get_mds_timings_frame(call, index)\n mds_timings_frame = mds_timings_frame.reset_index()\n mds_timings_frame = mds_timings_frame.rename(columns=mds_timings_frame.iloc[0]).drop(index=0)\n mds_views_frame = utils.get_view_info_table(call)\n slide9 = create_slide(layout=6, title_text='MDS Request for widget', presentation=presentation)\n if call.widgets:\n slide9.placeholders[25].text = f'Widget ID: {call.widgets[0]}'\n timings_table = slide9.placeholders[23]\n views_table = slide9.placeholders[24]\n slide9_timings_df = df_to_table(slide9, mds_timings_frame, left=timings_table.left, top=timings_table.top,\n width=timings_table.width, height=timings_table.height)\n slide9_views_df = df_to_table(slide9, mds_views_frame, left=views_table.left, top=views_table.top,\n width=views_table.width, height=views_table.height)\n format_slide_table(slide9, slide9_timings_df.table, title_font=14, row_font=12, col_idx=[0], col_wid=[4.5])\n format_slide_table(slide9, slide9_views_df.table, title_font=14, row_font=10, col_idx=[0,2,3,4],\n col_wid=[8.6, 4.5, 9, 2.5])\n for row in slide9_views_df.table.rows:\n row.height = Cm(0.8)\n index += 1\n\n chart_shape = slide9.placeholders[22]\n chart_data = CategoryChartData()\n\n chart_data.categories = [ds.ds_name for ds in call.datasources]\n chart_data.add_series('Runtime (s)', [ds.ds_runtime for ds in call.datasources])\n\n chart_shape = chart_shape.insert_chart(XL_CHART_TYPE.BAR_STACKED, chart_data)\n chart = chart_shape.chart\n\n category_axis = chart.category_axis\n category_axis.tick_labels.font.size = Pt(14)\n\n value_axis = chart.value_axis\n value_axis.tick_labels.font.size = Pt(10)\n value_axis.axis_title.text_frame.paragraphs[0].text = 'Runtime (s)'\n value_axis.axis_title.text_frame.paragraphs[0].font.size = Pt(12)\n\n plot = chart.plots[0]\n plot.gap_width = 30\n plot.vary_by_categories = False\n plot.series[0].format.fill.solid()\n plot.series[0].format.fill.fore_color.theme_color = MSO_THEME_COLOR_INDEX.ACCENT_4\n\n plot.has_data_labels = True\n plot.data_labels.show_category_name = False\n plot.data_labels.show_value = False\n plot.data_labels.font.size = Pt(12)\n\n dpl_ind = 0\n for p in plot.series[0].points:\n p.data_label.text_frame.auto_size = True\n p.data_label.text_frame.word_wrap = False\n p.data_label.text_frame.paragraphs[0].add_run()\n p.data_label.text_frame.paragraphs[0].runs[0].text = [ds.ds_name for ds in call.datasources][dpl_ind]\n p.data_label.text_frame.paragraphs[0].runs[0].font.size = Pt(10)\n p.data_label.position = XL_DATA_LABEL_POSITION.INSIDE_BASE\n p.data_label.text_frame.paragraphs[0].alignment = PP_PARAGRAPH_ALIGNMENT.LEFT\n dpl_ind += 1\n\n # Second Slide(s): MDS Details: Dimensions, Calc Entities\n for ds in call.datasources:\n slide10 = create_slide(layout=7, title_text=f'Definition for MDS \"{ds.ds_name}\"', presentation=presentation)\n slide10.placeholders[12].text = f'View: {ds.view}'\n\n text_shape = slide10.placeholders[11]\n text_frame = text_shape.text_frame\n text_frame.fit_text(max_size=18)\n\n p1 = text_frame.paragraphs[0]\n p1.text = f'MDS Runtime: {ds.ds_runtime} (s)'\n font = p1.runs[0].font\n font.name = 'Calibri'\n\n p2 = text_frame.add_paragraph()\n p2.text = f'MDS Dimensions:'\n font = p2.runs[0].font\n font.name = 'Calibri'\n font.underline = True\n\n for k in ds.dimensions.keys():\n p = text_frame.add_paragraph()\n p.level = 1\n p.space_after = Pt(1)\n p.space_before = Pt(1)\n p.text = f'{k}'\n p.runs[0].font.size = Pt(12)\n if ds.dimensions[k]:\n pt = text_frame.add_paragraph()\n pt.text = f'Formula Members in {k}:'\n font = pt.runs[0].font\n font.name = 'Calibri'\n font.underline = True\n for item in ds.dimensions[k]:\n pi = text_frame.add_paragraph()\n pi.level = 1\n pi.space_after = Pt(1)\n pi.space_before = Pt(1)\n pi.text = f'{item}'\n pi.runs[0].font.size = Pt(12)\n\n # 10 Appendix 1 - All Widgets Existing in Story\n\n if widgets_content_lib:\n\n df = widgets_content_lib_frame\n pages = df['Page Title'].unique().tolist()\n for page in pages:\n contlib_widgets_df = df[df['Page Title'] == page].drop(columns=['Story Name'])\n max_lines_on_slide = 15\n slide_number = 0\n while len(contlib_widgets_df.index) > 0:\n if len(contlib_widgets_df.index) > max_lines_on_slide:\n slide_number += 1\n slide11 = create_slide(layout=2,\n title_text='Appendix 1: All widgets used on page: \"' + page + '\" (' + str(\n slide_number) + ') ',\n presentation=presentation)\n table = slide11.placeholders[10]\n slide11_df = df_to_table(slide11, contlib_widgets_df[0:(max_lines_on_slide - 1)], left=table.left,\n top=table.top,\n width=table.width, height=table.height)\n contlib_widgets_df = contlib_widgets_df[max_lines_on_slide:len(contlib_widgets_df.index)]\n format_slide_table(slide11, slide11_df.table, title_font=12, row_font=10, col_idx=[2, 3],\n col_wid=[9.0, 10.0])\n row_height = slide11_df.table.rows[0].height\n else:\n slide_number += 1\n slide11 = create_slide(layout=2,\n title_text='Appendix 1: All widgets used on page: \"' + page + '\" (' + str(\n slide_number) + ') ',\n presentation=presentation)\n table = slide11.placeholders[10]\n slide11_df = df_to_table(slide11, contlib_widgets_df, left=table.left, top=table.top,\n width=table.width, height=table.height)\n format_slide_table(slide11, slide11_df.table, title_font=12, row_font=10, col_idx=[2, 3],\n col_wid=[9.0, 10.0])\n contlib_widgets_df = contlib_widgets_df.iloc[0:0]\n row_height = slide11_df.table.rows[0].height\n for row in slide11_df.table.rows:\n row.height = Cm(0.8)\n\n # 11 Appendix 2 - All Calculation Entities in Story\n\n if calc_entities:\n\n df = utils.get_calc_entities_frame(calc_entities)\n max_lines_on_slide = 15\n slide_number = 0\n while len(df.index) > 0:\n if len(df.index) > max_lines_on_slide:\n slide_number += 1\n slide12 = create_slide(layout=2,\n title_text='Appendix 2: All calculation entities used in story (' + str(\n slide_number) + ') ',\n presentation=presentation)\n table = slide12.placeholders[10]\n slide12_df = df_to_table(slide12, df[0:(max_lines_on_slide - 1)], left=table.left,\n top=table.top,\n width=table.width, height=table.height)\n df = df[max_lines_on_slide:len(df.index)]\n format_slide_table(slide12, slide12_df.table, title_font=12, row_font=10, col_idx=[0],\n col_wid=[10.0])\n row_height = slide12_df.table.rows[0].height\n else:\n slide_number += 1\n slide12 = create_slide(layout=2,\n title_text='Appendix 2: All calculation entities used in story (' + str(\n slide_number) + ') ',\n presentation=presentation)\n table = slide12.placeholders[10]\n slide12_df = df_to_table(slide12, df, left=table.left, top=table.top,\n width=table.width, height=table.height)\n format_slide_table(slide12, slide12_df.table, title_font=12, row_font=10, col_idx=[0],\n col_wid=[10.0])\n df = df.iloc[0:0]\n row_height = slide12_df.table.rows[0].height\n for row in slide12_df.table.rows:\n row.height = Cm(0.8)\n filename = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n presentation.save(path_to_pptx + '/' + story_title + '_' + filename + '.pptx')\n\n # # Default slide = 3 - empty slide with header\n #\n #\n # def analyze_ppt(input, output):\n # \"\"\" Take the input file and analyze the structure.\n # The output file contains marked up information to make it easier\n # for generating future powerpoint templates.\n # \"\"\"\n # prs = Presentation(input)\n # # Each powerpoint file has multiple layouts\n # # Loop through them all and see where the various elements are\n # for index, _ in enumerate(prs.slide_layouts):\n # slide = prs.slides.add_slide(prs.slide_layouts[index])\n # # Not every slide has to have a title\n # try:\n # title = slide.shapes.title\n # title.text = 'Title for Layout {}'.format(index)\n # except AttributeError:\n # print(\"No Title for Layout {}\".format(index))\n # # Go through all the placeholders and identify them by index and type\n # for shape in slide.placeholders:\n # if shape.is_placeholder:\n # phf = shape.placeholder_format\n # # Do not overwrite the title which is just a special placeholder\n # try:\n # if 'Title' not in shape.text:\n # shape.text = 'Placeholder index:{} type:{}'.format(phf.idx, shape.name)\n # except AttributeError:\n # print(\"{} has no text attribute\".format(phf.type))\n # print('{} {}'.format(phf.idx, shape.name))\n # prs.save(output)\n #\n # prs_path = '/Users/annademidova/PycharmProjects/HAR_Parser/'\n # analyze_ppt(settings.TEMPLATE_PATH, prs_path + 'Analysis.pptx')","sub_path":"Code/presentation.py","file_name":"presentation.py","file_ext":"py","file_size_in_byte":32219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"159021906","text":"import random\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx, y = [], []\nx_test1, x_test2, x_test3 = [], [], []\n\n# 随机生成3种不同分类的点,分别打上标签存在y中\nfor i in range(0, 20):\n x1 = random.random()\n x2 = random.random()\n if x1 + x2 < 1:\n x.append([x1, x2, 1])\n x_test1.append([x1, x2])\n y.append([1, 0, 0])\n\n x.append([x1 * 2, x2 + 1, 1])\n x_test2.append([x1 * 2, x2 + 1])\n y.append([0, 1, 0])\n\n if x1 > x2:\n x.append([x1 + 1, x2, 1])\n x_test3.append([x1 + 1, x2])\n y.append([0, 0, 1])\n\n# 将list转换为numpy array\nx = np.array(x)\ny = np.array(y)\n\n# 学习率\nlr = 0.5\n\nw = np.ones((3, 3))\nm = len(x)\nfor i in range(0, 1000):\n w_gard = 0\n for j in range(0, m):\n # sigmoid函数分类,这里用到了矩阵乘法\n w_gard += -x[j] * np.atleast_2d(1 / (1 + np.exp(-np.matmul(w, x[j]))) - y[j]).T\n w += lr * w_gard / m\n\n# 画点\nplt.plot(np.array(x_test1)[:, 0], np.array(x_test1)[:, 1], 'ro')\nplt.plot(np.array(x_test2)[:, 0], np.array(x_test2)[:, 1], 'gx')\nplt.plot(np.array(x_test3)[:, 0], np.array(x_test3)[:, 1], 'b.')\n# 画分类直线\nplt.plot([0, 2], [-w[0][2] / w[0][1], -(w[0][2] + 2 * w[0][0]) / w[0][1]], 'r')\nplt.plot([0, 2], [-w[1][2] / w[1][1], -(w[1][2] + 2 * w[1][0]) / w[1][1]], 'g')\nplt.plot([0, 2], [-w[2][2] / w[2][1], -(w[2][2] + 2 * w[2][0]) / w[2][1]], 'b')\n\nplt.show()","sub_path":"logistics.py","file_name":"logistics.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"289019610","text":"def parse_time_v2(pd, np, df, data):\r\n import time \r\n import calendar\r\n \r\n DT = []\r\n ET = []\r\n DoY = []\r\n \r\n ds = df.loc[:, 'Date':'Date':1].values #extract date from data frame\r\n \r\n for i in range(0, len(ds)):\r\n tt = time.strptime(str(ds[i]), \"['%d/%m/%Y %H:%M']\")\r\n #DoY\r\n DoY.append(float(tt[7]) + ((((float(tt[5])/60) + float(tt[4]))/60) + float(tt[3]))/24) \r\n #ET\r\n ET.append(int(calendar.timegm(tt)))\r\n #DT\r\n DT.append(tt[0:6])\r\n\t\t \r\n data.DT = np.array(DT)\r\n data.DoY = np.array(DoY)\r\n data.ET = np.array(ET)\r\n \r\n return data\r\n \r\ndef parse_data_v2(pd, np, df, data):\r\n #remove any nans from data\r\n df[\"NO_ppb\"].fillna(-1.00e+20, inplace = True)\r\n df[\"NO2_ppb\"].fillna(-1.00e+20, inplace = True)\r\n df[\"NOx_ppb\"].fillna(-1.00e+20, inplace = True)\r\n \r\n no = df.loc[:, 'NO_ppb':'NO_ppb':1].values\r\n flag_no = df.loc[:, 'NO_Flag':'NO_Flag':1].values\r\n no2 = df.loc[:, 'NO2_ppb':'NO2_ppb':1].values\r\n flag_no2 = df.loc[:, 'NO2_Flag':'NO2_Flag':1].values\r\n nox = df.loc[:, 'NOx_ppb':'NOx_ppb':1].values\r\n flag_nox = df.loc[:, 'NOx_Flag':'NOx_Flag':1].values\r\n \r\n data.no = np.array(no)\r\n data.flag_no = np.array(flag_no)\r\n data.no2 = np.array(no2)\r\n data.flag_no2 = np.array(flag_no2)\r\n data.nox = np.array(nox)\r\n data.flag_nox = np.array(flag_nox)\r\n\r\n ii = np.where(data.no <= 0)\r\n data.flag_no[ii] = 2 \r\n ii = np.where(data.no > 9000)\r\n data.flag_no[ii] = 2\r\n ii = np.where(data.no2 <= 0)\r\n data.flag_no2[ii] = 2 \r\n ii = np.where(data.no2 > 9000)\r\n data.flag_no2[ii] = 2\r\n ii = np.where(data.nox <= 0)\r\n data.flag_nox[ii] = 2 \r\n ii = np.where(data.nox > 9000)\r\n data.flag_nox[ii] = 2\r\n \r\n return data","sub_path":"nox/V2/nox_parser_v2.py","file_name":"nox_parser_v2.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"423174862","text":"#coding: UTF-8\nimport gensim\nimport torch\nfrom tensorboardX import SummaryWriter\nfrom gensim import models\n\nvec_path = \"doc2vec.model\"\n\nwriter = SummaryWriter()\n#model = gensim.models.KeyedVectors.load_word2vec_format(vec_path, binary=False)\nmodel = models.Doc2Vec.load(vec_path)\nweights =[]\nlabels =[]\nfor i in range(0,len(model.docvecs)):\n weights.append(model.docvecs[i].tolist())\n labels.append(model.docvecs.index_to_doctag(i))\n \n# DEBUG: visualize vectors up to 1000\nweights = weights[:1000]\nlabels = labels[:1000]\n\nwriter.add_embedding(torch.FloatTensor(weights), metadata=labels)\n","sub_path":"yamada/tbx.py","file_name":"tbx.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"645418735","text":"import cPickle as pickle\n\ndef dataIO(fileName, IO, obj=0):\n\tif IO == 'i':\n\t\treturn pickle.load(open(fileName, 'rb'))\n\telse:\n\t\tpickle.dump(obj, open(fileName, 'wb'), True)\n\t\treturn 0\n\n\n# 2017.02.09 - KNN\ndef knn_sampleImport(folderName, labels):\n\t# Import text file.\n\timport os\n\tfLst = os.listdir(folderName + '/')\n\tcount = 0\n\tsamples = []\n\tfLst.sort()\n\tfor fileName in fLst:\n\t\t# print('Reading %s' % fileName)\n\t\twith open(folderName+'/'+fileName, 'r') as o:\n\t\t\tstrTmp = o.read().replace('\\n', '')\n\t\tlstTmp = []\n\t\tfor i in strTmp:\n\t\t\tif i == '0' or i == '1':\n\t\t\t\t# Without this judgement, error would occur in Linux/Unix.\n\t\t\t\tlstTmp.append(int(i))\n\t\tlstTmp.append(labels[count])\n\t\tsamples.append(lstTmp)\n\t\tcount += 1\n\tdataIO('samples.dat', 'o', samples)\n\treturn samples\n\ndef knn(samples, data, n, method='eu'):\n\t# samples = [[x,x,...,x,label]...]\n\t# data = [x,x,...,x]\n\tif len(samples[0]) != len(data)+1:\n\t\treturn -1\n\tnumSample = len(samples)\n\tnumData = len(data)\n\tdistance = []\n\n\tif method == 'eu':\n\t\tfor i in range(numSample):\n\t\t\ttmp = 0\n\t\t\tfor j in range(numData):\n\t\t\t\ttmp += (samples[i][j] - data[j]) ** 2\n\t\t\tdistance.append([tmp**0.5, samples[i][-1]])\n\t\t\n\telif method == 'ha':\n\t\tfor i in range(numSample):\n\t\t\tOnes = 0\n\t\t\tfor j in range(numData):\n\t\t\t\tif samples[i][j] != data[j]:\n\t\t\t\t\tOnes += 1\n\t\t\tdistance.append([float(Ones)/len(samples[i]), samples[i][-1]])\n\n\n\tsortedList = sorted(distance)\n\treturn sortedList[:n]\n","sub_path":"OCR/ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"530524533","text":"# Copyright 2015 Leon Sixt\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 numpy as np\nfrom beras.util import collect_layers, sequential, concat\n\nfrom keras.layers.core import Dense\nfrom keras.engine.topology import Input, merge\nfrom keras.engine.training import collect_trainable_weights\nfrom keras.models import Model\nimport pytest\n\n\ndef test_collect_layers():\n input = Input(shape=(5,))\n layer_a = Dense(20)\n layer_b = Dense(20)\n layer_c = Dense(20)\n layer_d = Dense(20)\n a = layer_a(input)\n b = layer_b(a)\n c = layer_c(b)\n d = layer_d(c)\n\n layers = collect_layers([b], [d])\n assert layer_c in layers\n assert layer_d in layers\n assert len(layers) == 2\n\n layers = collect_layers([input], [c])\n assert layer_a in layers\n assert layer_b in layers\n assert layer_c in layers\n assert len(layers) == 3\n\n\ndef test_collect_layers_mimo():\n x = Input(shape=(5,))\n y = Input(shape=(5,))\n layer_a = Dense(20)\n layer_b = Dense(20)\n layer_c = Dense(20)\n layer_d = Dense(20)\n layer_e = Dense(20)\n a = layer_a(x)\n b = layer_b(y)\n m = merge([a, b])\n c = layer_c(m)\n d = layer_d(m)\n e = layer_e(d)\n\n layers = collect_layers([x, y], [c, e])\n # pytest.set_trace()\n assert layer_a in layers\n assert layer_b in layers\n assert m._keras_history[0] in layers\n assert layer_c in layers\n assert layer_d in layers\n assert layer_e in layers\n\n layers = collect_layers([x, y], [e])\n assert layer_c not in layers\n\n # missing inputs are detected\n with pytest.raises(Exception):\n layers = collect_layers([x], [c, e])\n\n\ndef test_concat():\n x = Input(shape=(20,))\n y = Input(shape=(20,))\n model = Model([x, y], concat([x, y]))\n in_x = np.random.sample((32, 20))\n in_y = np.random.sample((32, 20))\n model.compile('adam', 'mse')\n assert model.predict_on_batch([in_x, in_y]).shape == (32, 40)\n\n\ndef test_sequential():\n x = Input(shape=(20,))\n seq = sequential([\n Dense(20),\n Dense(10),\n Dense(1),\n ])\n\n out = seq(x)\n model = Model([x], [out])\n model.compile('adam', 'mse')\n model.predict_on_batch(np.random.sample((64, 20)))\n\n\ndef test_sequential_flatten():\n x = Input(shape=(20,))\n seq = sequential([\n Dense(20),\n [\n Dense(10)\n ],\n [\n [\n Dense(1)\n ],\n Dense(1)\n ]\n ])\n out = seq(x)\n model = Model([x], [out])\n model.compile('adam', 'mse')\n model.predict_on_batch(np.random.sample((64, 20)))\n\n\ndef test_sequential_trainable():\n x = Input(shape=(20,))\n dense1 = Dense(20)\n dense2 = Dense(10)\n dense3 = Dense(1)\n seq = sequential([\n dense1,\n dense2,\n dense3,\n ], trainable=False)\n seq(x)\n assert collect_trainable_weights(dense1) == []\n assert collect_trainable_weights(dense2) == []\n assert collect_trainable_weights(dense3) == []\n\n\ndef test_sequential_namespace():\n x = Input(shape=(20,))\n dense1 = Dense(20)\n dense2 = Dense(10)\n dense3 = Dense(1)\n seq = sequential([\n dense1,\n dense2,\n dense3,\n ], ns='hello')\n seq(x)\n assert dense1.name.startswith('hello.')\n assert dense2.name.startswith('hello.')\n assert dense3.name.startswith('hello.')\n\n\ndef test_sequential_enumerate():\n x = Input(shape=(20,))\n dense1 = Dense(20)\n dense2 = Dense(10)\n dense3 = Dense(1)\n seq = sequential([\n dense1,\n dense2,\n dense3,\n ], ns='hello')\n seq(x)\n assert dense1.name.endswith('hello.00_dense')\n assert dense2.name.endswith('hello.01_dense')\n assert dense3.name.endswith('hello.02_dense')\n","sub_path":"tests/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"556397692","text":"#!/usr/bin/env python\n\nimport mebo\n\nfrom setuptools import (\n setup,\n find_packages\n)\n\n\ndef find_requirements(filename='requirements.txt'):\n with open(filename, 'r') as f:\n return f.readlines()\n\n\ndef readme(filename='README.rst'):\n with open(filename, 'r') as f:\n return f.read()\n\n\nsetup(\n name='mebo',\n version=mebo.__version__,\n description='Simple python interface to control the mebo toy robot',\n long_description=readme(),\n author='Cameron Lane',\n author_email='crlane@adamanteus.com',\n url='https://github.com/crlane/python-mebo',\n packages=find_packages(exclude=['contrib', 'docs', 'test*']),\n install_requires=find_requirements(),\n license='MIT',\n extras_require={\n 'testing': find_requirements('test_requirements.txt'),\n 'development': ['ipython', 'ipdb']\n },\n classifiers=[\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 3 - Alpha',\n\n # Indicate who your project is intended for\n 'Intended Audience :: Education',\n 'Topic :: Scientific/Engineering :: Human Machine Interfaces',\n # Pick your license as you wish (should match \"license\" above)\n 'License :: OSI Approved :: MIT License',\n\n # Specify the Python versions you support here. In particular, ensure\n # that you indicate whether you support Python 2, Python 3 or both.\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"43425557","text":"from requests import auth\nfrom app import db \nfrom app.models.task import Task\nfrom flask import Blueprint, json, jsonify, make_response, request, abort\nimport datetime, requests\nimport os\n\n\n\ntask_bp = Blueprint(\"task\", __name__, url_prefix=\"/tasks\")\n\n#Helper Functions \ndef valid_int(number, parameter_type):\n try:\n int(number)\n except:\n abort(make_response({\"error\": f\"{parameter_type} must be an int\"}, 400))\n\n\ndef get_task_from_id(task_id):\n valid_int(task_id, \"task_id\")\n return Task.query.get_or_404(task_id, description=\"{task not found}\")\n\n#ROUTES\n@task_bp.route(\"\", methods=[\"GET\"])\ndef read_all_tasks():\n\n title_query = request.args.get(\"title\")\n sort_query = request.args.get(\"sort\")\n sort_id_query = request.args.get(\"sort_id\")\n \n \n if sort_query == \"asc\":\n tasks = Task.query.order_by(Task.title.asc())\n elif sort_query == \"desc\":\n tasks = Task.query.order_by(Task.title.desc())\n elif sort_id_query == \"asc\":\n tasks = Task.query.order_by(Task.task_id.asc())\n elif sort_id_query == \"desc\":\n tasks = Task.query.order_by(Task.task_id.desc())\n elif title_query:\n tasks = Task.query.filter_by(title=title_query)\n else:\n tasks = Task.query.all()\n\n tasks_response = []\n for task in tasks:\n tasks_response.append(\n task.to_dict()\n )\n return jsonify(tasks_response)\n\n\n# Create one task \n@task_bp.route(\"\", methods=[\"POST\"])\ndef create_tasks():\n request_body = request.get_json()\n if \"title\" not in request_body or \"description\" not in request_body or \"completed_at\" not in request_body:\n return {\"details\": \"Invalid data\"}, 400\n\n new_task = Task(\n title=request_body[\"title\"],\n description=request_body[\"description\"],\n completed_at=request_body[\"completed_at\"]\n )\n\n db.session.add(new_task)\n db.session.commit()\n\n return make_response({\"task\":new_task.to_dict()}, 201)\n\n\n\n#Get one task with id \n@task_bp.route(\"/\", methods=[\"GET\"])\ndef read_task(task_id):\n task = get_task_from_id(task_id)\n return {\"task\": task.to_dict()}\n\n\n#Mark complete on incomplete task\n@task_bp.route(\"//mark_complete\", methods=[\"PATCH\"])\ndef mark_complete_on_incomplete_task(task_id):\n\n task = get_task_from_id(task_id)\n\n task.completed_at = datetime.date.today()\n db.session.commit()\n\n URL = os.environ.get('URL')\n API_KEY = os.environ.get('KEY')\n params = {\"channel\":\"task-notifications\", \"text\":f\"Someone just completed the task {task.title}\"}\n header = {'Authorization' : API_KEY}\n \n try: \n response = requests.post(URL, params=params, headers=header)\n response.raise_for_status()\n except requests.exceptions.HTTPError as e:\n return f\"Slack API returned error {e}\"\n \n return {\"task\": task.to_dict()}\n\n\n@task_bp.route(\"//mark_incomplete\", methods=[\"PATCH\"])\ndef mark_incomplete_on_complete_task(task_id):\n task = get_task_from_id(task_id)\n\n task.completed_at = None\n db.session.commit()\n\n return {\"task\": task.to_dict()}\n\n\n\n#UPDATE A TASK\n@task_bp.route(\"/\", methods=[\"PUT\"])\ndef update_task(task_id):\n task = get_task_from_id(task_id)\n request_body = request.get_json()\n\n if \"title\" in request_body:\n task.title = request_body[\"title\"]\n if \"description\" in request_body:\n task.description = request_body[\"description\"]\n if \"completed_at\" in request_body:\n task.completed_at = request_body[\"completed_at\"]\n \n db.session.commit()\n return make_response({\"task\": task.to_dict()},200)\n\n#DELETE A TASK\n@task_bp.route(\"/\", methods=[\"DELETE\"])\ndef delete_task(task_id):\n task = get_task_from_id(task_id)\n\n db.session.delete(task)\n db.session.commit()\n return ({\"details\": f'Task {task_id} \"{task.title}\" successfully deleted'})\n\n\n#OPTIONAL ROUTES\n\n# @task_bp.route(\"/\", methods=[\"GET\"])\n# def read_task(task_id):\n# task = get_task_from_id(task_id)\n# return {\"task\": task.to_dict()}\n\n\n\n","sub_path":"app/task_routes.py","file_name":"task_routes.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"498728537","text":"import time\nimport zmq\nimport paho.mqtt.client as mqtt\n\nbroker_addr = \"10.0.0.2\" # address of air broker\nbroker_port = 1883 # port of broker\n\n\ndef on_connect(client, obj, flags, rc):\n print(\"rc: \" + str(rc))\n\n\ndef on_message(client, obj, msg): # on_message(client, userdata, message)\n # print(\"Sending task to workers \" + msg.topic + \" \" + str(msg.payload))\n msg = str(msg.topic + \"/\" + msg.payload.decode())\n sender.send_string(msg)\n\n\ndef on_subscribe(client, obj, mid, granted_qos):\n print(\"Subscribed on broker: \" + str(mid) + \" \" + str(granted_qos))\n\n\n# Socket to send messages to workers\ncontext = zmq.Context()\nsender = context.socket(zmq.PUSH)\nsender.bind(\"tcp://*:5558\")\n\n# Connect and subs. to broker\nclient = mqtt.Client(\"v_sub_air\")\nclient.on_message = on_message\nclient.on_connect = on_connect\nclient.on_subscribe = on_subscribe\nclient.connect(broker_addr, broker_port, 60)\nclient.subscribe(\"drivers/virtual_air\", 0)\nclient.loop_forever()\n","sub_path":"mid/v_sub_air.py","file_name":"v_sub_air.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"231504970","text":"from testfixtures import log_capture\nfrom testsuite.base_test import BaseTest\nfrom testsuite import config\nfrom core.sessions import SessionURL\nfrom core import modules\nfrom core import utilities\nfrom core import messages\nimport core.utilities\nimport subprocess\nimport os\n\nclass FindName(BaseTest):\n\n def _recursive_folders(self, recursion = 4):\n\n folders_abs = [ config.script_folder ]\n\n for folder in [ utilities.randstr() for f in range(0, recursion) ]:\n folders_abs.append(os.path.join(*[ folders_abs[-1], folder ] ))\n\n folders_rel = [ f.replace(config.script_folder, '') for f in folders_abs[1:] ]\n\n return folders_abs[1:], folders_rel\n\n def setUp(self):\n self.session = SessionURL(\n self.url,\n self.password,\n volatile = True\n )\n\n modules.load_modules(self.session)\n\n # Create the folder tree\n self.folders_abs, self.folders_rel = self._recursive_folders()\n\n for folder_abs in self.folders_abs:\n subprocess.check_call(\n config.cmd_env_mkdir_s % (folder_abs),\n shell=True)\n\n files_names = [ 'test1', 'TEST1', 'TEST2', 'TEST3' ]\n\n # Add a file in every folder and save paths\n self.files_abs = []\n self.files_rel = []\n for folder_abs in self.folders_abs:\n self.files_abs.append(os.path.join(folder_abs, files_names.pop(0)))\n self.files_rel.append(self.files_abs[-1].replace(config.script_folder, ''))\n subprocess.check_call(\n config.cmd_env_content_s_to_s % ('1', self.files_abs[-1]),\n shell=True)\n\n self.run_argv = modules.loaded['find_name'].run_argv\n\n def tearDown(self):\n\n for folder in reversed(self.folders_abs):\n\n subprocess.check_call(\n config.cmd_env_remove_s % (self.files_abs.pop()),\n shell=True)\n\n subprocess.check_call(\n config.cmd_env_rmdir_s % (folder),\n shell=True)\n\n\n @log_capture()\n def test_find_name(self, log_captured):\n\n # find file[0] (case insensitive, recursive, not contains) -> file[0], file[1]\n filep, filen = os.path.split(self.files_rel[0])\n self.assertEqual(self.run_argv([ filen ]), './%s\\n./%s' % (self.files_rel[0], self.files_rel[1]))\n\n # find file[0] (case sensitive, recursive, not contains) -> file[0]\n filep, filen = os.path.split(self.files_rel[0])\n self.assertEqual(self.run_argv([ '--case=True', filen ]), './%s' % (self.files_rel[0]))\n\n # find the end of file[0] (case insensitive, recursive, contains) -> file[0], file[1]\n filep, filen = os.path.split(self.files_rel[0])\n self.assertEqual(\n self.run_argv(\n [ '--contains=True',\n filen[-3:] ]\n ),\n './%s\\n./%s' % (self.files_rel[0], self.files_rel[1])\n )\n\n # find file[0] not recursive -> none\n filep, filen = os.path.split(self.files_rel[0])\n self.assertEqual(self.run_argv([ '--recursive=False', filen ]), '')\n\n # find file[3] (case insensitive, recursive, not contains) -> file[0], file[1]\n filep, filen = os.path.split(self.files_rel[3])\n self.assertEqual(self.run_argv([ filen ]), './%s' % (self.files_rel[3]))\n\n # find file[1] with wrong rpath (case insensitive, recursive, not contains) -> none\n filep, filen = os.path.split(self.files_rel[1])\n self.assertEqual(self.run_argv([ '--rpath=%s' % (self.folders_rel[-1]), filen ]), '')\n\n # find file[1] with right path and no recursive. Set all the params.\n filep, filen = os.path.split(self.files_rel[1])\n self.assertEqual(\n self.run_argv(\n [\n '--rpath=%s' % (self.folders_rel[1]),\n '--recursive=False',\n '--contains=True',\n '--case=True',\n filen[-3:]\n ]\n ),\n '%s' % (self.files_rel[1]))\n\n # find file[0] with sh vector (case insensitive, recursive, not contains) -> file[0], file[1]\n filep, filen = os.path.split(self.files_rel[0])\n self.assertEqual(self.run_argv([ '--vector=sh_find', filen ]), './%s\\n./%s' % (self.files_rel[0], self.files_rel[1]))\n","sub_path":"testsuite/test_find_name.py","file_name":"test_find_name.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"593748123","text":"\"\"\"We prebuild payout reports to decrease loading times for users.\"\"\"\n\n\nfrom django_cron import CronJobBase, Schedule\nimport console.models\nimport ark_delegate_manager.custom_functions as fnc\nimport ark_analytics.analytic_functions as anal\nimport ark_analytics.models\nimport json\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass CreateVoteReports(CronJobBase):\n RUN_EVERY_MINS = 1\n schedule = Schedule(run_every_mins=RUN_EVERY_MINS)\n code = 'ark_delegate_manager.create_vote_reports'\n\n def do(self):\n fnc.set_lock(name='CreateVoteReports')\n for user in console.models.UserProfile.objects.all():\n try:\n payout_report = json.dumps(anal.gen_payout_report(wallet=user.address))\n balance_report = json.dumps(anal.gen_balance_report(wallet=user.address))\n\n ark_analytics.models.PayoutReports.objects.update_or_create(\n address=user.address,\n payout_report=payout_report,\n balance_report=balance_report\n )\n except Exception:\n logger.exception('generating reports failed')\n\n fnc.release_lock(name='CreateVoteReports')","sub_path":"ark_analytics/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"93881209","text":"# -*- coding: utf-8 -*-\nimport numpy as np\n\ndef numerical_gradient(func, X):\n h = 1e-4\n grad = np.zeros_like(X)\n\n for index in range(X.size):\n val = X[index]\n X[index] = val + h\n fxh1 = func(X)\n\n X[index] = val - h\n fxh2 = func(X)\n\n grad[index] = (fxh1 - fxh2) / (2 * h)\n X[index] = val\n\n return grad\n\ndef gradient_descent(func, init_x, lr = 0.01, step_num = 100):\n X = init_x\n\n for i in range(step_num):\n grad = numerical_gradient(func, X)\n X -= grad\n\n return X\n","sub_path":"python/deep-learning/src/util/grad.py","file_name":"grad.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"191716616","text":"from django.urls import path\nfrom . import views\napp_name='App_Article'\n\n\nurlpatterns = [\n path('',views.mainhome,name='home'),\n path('article_home/',views.home.as_view(),name='article_home'),\n path('post_article/',views.Createarticle.as_view(),name='post_article'),\n path('view_article//',views.detail,name='view_article'),\n]\n","sub_path":"App_Article/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"188638073","text":"import sys\nimport os\nsys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '../..')) # To access files in other directorys\n\nimport tkinter as tk\nfrom tkinter import tix\nfrom tkinter.constants import *\n\nimport Styling as font\nimport inspect\n\n# define all settings files to be displayed on Options Page\n# (\"FolderName\", \"FileName\")\nsettingFiles = [(\"Control\", \"ControlSettings\"), (\"LaneKeeping\", \"LaneSettings\"), (\"Lidar\", \"LidarSettings\"), \n (\"OutputManager\", \"OutputSettings\")]\n\n\nmw = tix.Tk()\n\nmw.title(\"Debug Console\")\nmw.configure(background='white')\nmw.minsize(600, 500)\nmw.state(\"zoomed\")\n\nscreenWidth = mw.winfo_screenwidth()\nscreenHeight = mw.winfo_screenheight()\n\n# Heading\nheading = tk.Label(mw, text=\"Debugging Console\".upper(), background=\"white\", font=font.h2())\nheading.pack()\n\n# Sub Heading\nsubHeading = tk.Label(mw, text=\"Access to the cars current stats and values\",\n background=\"white\", font=font.h3())\nsubHeading.pack()\n\n\n# Title of Settings\nvar = tk.StringVar()\ntitel = tk.Label(mw, textvariable=var, font=font.h1(), bg=\"white\")\ntitel.place(relx=0.55, rely=0.15, anchor=\"nw\")\n\n# Settings Label\nsettingsheight = 10\nlabels = []\nentrys = []\npaths = []\nclasses = None\n\n# Submitt Button\ndef submitt():\n for i in range(len(entrys)):\n fileimport = __import__(paths[i], fromlist=[classes])\n fileimport = entrys[i].get()\n print (labels[i].cget(\"text\"), entrys[i].get())\n\n# Create Button\nsubbtn = tk.Button(mw, text= \"Submitt Changes\", command=submitt)\nsubbtn.place(relx=0.9, rely=0.9, anchor=\"se\")\n\n\n# Display settings of currently selected class\ndef select(event):\n widget = event.widget\n selection = widget.info_selection()\n selectedText = widget.info_data(selection)\n children = widget.info_children(selection)\n\n # remove old settings\n for label in labels:\n label.destroy()\n\n for entry in entrys:\n entry.destroy()\n\n #create new settings\n i = 0\n for child in children:\n v = tk.StringVar()\n data = str(widget.info_data(child))\n text, value, path = data.split(\"=\")\n\n settinglb = tk.Label(mw, text=(text), bg=\"white\")\n settinglb.place(relx=0.55, y = screenHeight*0.2 + i)\n settingent = tk.Entry(mw, textvariable= v)\n settingent.place(relx=0.90, y = screenHeight*0.2 + i, anchor=\"ne\")\n v.set(value)\n\n labels.append(settinglb)\n entrys.append(settingent)\n paths.append(path)\n i = i + 20\n # Set Titel to current Selection\n var.set(str(selectedText))\n classes = str(selectedText)\n \n\ndef createListBox():\n options = tix.HList(mw, width=50, indent=20)\n options.bind(\"\", select)\n\n for folder, file in settingFiles:\n # add Filename\n settingsImport = __import__(\"SelfDrivingCar.\" + folder + \".\" + file, fromlist=[\"*\"])\n options.add(file, text=file)\n countClass = 0\n for name, obj in inspect.getmembers(settingsImport):\n # add Class\n countSetting = 0\n if inspect.isclass(obj):\n options.add_child(file, text=name, data=name)\n for atribute in dir(obj):\n # add Setting\n if not atribute.startswith('__'):\n # value = atribute + \"=\" + str(getattr(obj, atribute) + \"=\")\n path = \"SelfDrivingCar.{}.{}\".format(folder, file)\n value = \"{}={}={}\".format(atribute, getattr(obj, atribute), path)\n #value.format(atribute, getattr(obj, atribute), )\n options.add_child(file + \".\" + str(countClass), text=atribute, data=value)\n options.hide_entry(file + \".\" + str(countClass) + \".\" + str(countSetting))\n countSetting = countSetting + 1\n countClass = countClass + 1\n options.place(relx=0.45, rely=0.15, anchor=\"ne\")\n\ncreateListBox()\n\nmw.mainloop()","sub_path":"DebugConsole/DebugWindow.py","file_name":"DebugWindow.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"309520317","text":"# MAP GENERATOR FOR VWORLD\r\n# By H.S.Jeong 2021/08/12\r\n\r\nimport requests\r\nimport os\r\n\r\nimport configparser\r\n\r\n# READ CONFIG\r\nconfig = configparser.ConfigParser()\r\nconfig.read('Config.ini')\r\n\r\nlateral_begin = int(config['AXIS']['TOP']) #위 404\r\nlateral_end = int(config['AXIS']['BOTTOM']) #아래 405\r\nlongitudinal_begin = int(config['AXIS']['LEFT']) #왼쪽 874\r\nlongitudinal_end = int(config['AXIS']['RIGHT']) #오른쪽 875\r\n\r\nmin_level = int(config['LEVEL']['MIN']) # 11\r\nmax_level = int(config['LEVEL']['MAX']) # 18\r\n\r\n# Prepare\r\n# base = 'https://map4.daumcdn.net/map_2d/2106wof/' #map0~4\r\nbase = 'https://xdworld.vworld.kr/2d/Base/service/'#7/110/48.png\r\n# level = 10\r\n# lateral_begin = 6 # 범위 찾기 #아래\r\n# lateral_end = 7 #위\r\n# longitudinal_begin = 7 # 범위 찾기 #왼쪽\r\n# longitudinal_end = 8 #오른쪽\r\n# 브이월드 지도 특징은 폴더가 가로축 파일이 세로축이다.\r\n# 이미지가 옆으로 이동.\r\next = '.png'\r\n\r\nos.mkdir('Base')\r\n\r\n# Download\r\nprint(\"Download Start...\")\r\nfor level in range(min_level,max_level + 1): # 11~ 18\r\n if level >= 10:\r\n print(\"CURRENT LEVEL = {}\".format(level),end = '\\r')\r\n else:\r\n print(\"CURRENT LEVEL = {}\".format(level),end = '\\r')\r\n folder_base = 'Base' + \"\\\\\" +str(level)\r\n os.mkdir(folder_base)\r\n # print(folder_base)\r\n # Download\r\n for longitudinal in range(longitudinal_begin,longitudinal_end+1):\r\n folder = folder_base + \"\\\\\" + str(longitudinal)\r\n os.mkdir(folder)\r\n # print(folder)\r\n folder = folder_base + \"\\\\\" + str(longitudinal) + \"\\\\\"\r\n for lateral in range(lateral_begin,lateral_end+1):\r\n # print(folder + str(longitudinal) + ext)\r\n f = open(folder + str(lateral) + ext ,'wb')\r\n url = base + str(level) + '/' + str(longitudinal) + '/' + str(lateral) + ext\r\n response = requests.get(url)\r\n f.write(response.content)\r\n f.close()\r\n\r\n # 다음 레벨로 이동\r\n longitudinal_begin = longitudinal_begin * 2\r\n longitudinal_end = longitudinal_end * 2 + 1\r\n lateral_begin = lateral_begin * 2\r\n lateral_end = lateral_end * 2 + 1\r\n\r\n# Finish\r\nprint(\"Download End...\")\r\n\r\n# f = open(str(longitudinal) + '_4' + ext ,'wb')\r\n# url = base + 'L' + str(level) + '/' + str(lateral) + '/' + str(longitudinal) + ext\r\n# response = requests.get(url)\r\n# print(response.status_code)\r\n# f.write(response.content)\r\n# f.close()\r\n# #https://map0.daumcdn.net/map_2d/2106wof/L4/494/824.png\r\n# print(\"download successful\")\r\n","sub_path":"Company/2021/Map/Vworld/MapDownloader.py","file_name":"MapDownloader.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"267201492","text":"# -*- coding: utf-8 -*-\n\n\nclass Solution(object):\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n d = {}\n for n in nums:\n if n in d:\n return True\n d[n] = True\n return False\n\nnums = [1,2,3,1]\nprint(Solution().containsDuplicate(nums))","sub_path":"array/0217_contains_duplicate/0217_contains_duplicate.py","file_name":"0217_contains_duplicate.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"584634240","text":"# Complete the alternatingCharacters function below.\n# Returns the number of deletions required to change string of only A and B into strings of alternating A's and B's\ndef alternatingCharacters(s):\n last_char = \"\"\n removals = 0\n for char in s:\n if char == last_char:\n removals += 1\n last_char = char\n return removals\n\n\n# Returns true if s can be re-arranged into a palindrome.\ndef canBeRearrangedIntoPalindrome(s):\n character_dictionary = {}\n unique_character_found = False\n\n for char in s:\n if char in character_dictionary.keys():\n character_dictionary[char] += 1\n else:\n character_dictionary[char] = 1\n \n for char in character_dictionary.keys():\n if character_dictionary[char] % 2 == 1 and unique_character_found:\n return False\n elif character_dictionary[char] % 2 == 1 and not unique_character_found:\n unique_character_found = True\n\n return True\n\n# returns the number of occurances of a character char in the characters of string s repeated n times\ndef repeatedCharacter(s, n, char):\n repeated = 0\n times_divided = n / len(s)\n remainder = n % len(s)\n for i in range(len(s)):\n if s[i] == char:\n repeated += 1\n\n repeated *= times_divided\n\n for i in range(remainder):\n if s[i] == char:\n repeated += 1\n\n return repeated","sub_path":"Python/string_exercises.py","file_name":"string_exercises.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"405357540","text":"import time\n\nfrom optimization.cpu.operators import MRIOperator\nfrom optimization.cpu.dwt import dwt2, idwt2\nfrom optimization.cpu.algorithms import LASSOGradient, FISTA, PrimalDual\nfrom optimization.cpu.proximal import BPDNFStar, BPDNG\n\ndef run_pd(im, samp_patt, wav, levels, n_iter, eta, sigma=0.5, tau=0.5, theta=1):\n \"\"\"Perform experiment\"\"\"\n op = MRIOperator(samp_patt, wav, levels)\n measurements = op.sample(im)\n initial_x = op(measurements, True)\n\n prox_f_star = BPDNFStar(sigma, eta, measurements)\n prox_g = BPDNG(tau)\n alg = PrimalDual(op, prox_f_star, prox_g, theta, tau, sigma, eta)\n\n start = time.time()\n result = alg.run(n_iter, initial_x)\n total_time = time.time() - start\n\n return result, total_time\n\n\ndef run_fista(im, samp_patt, wav, levels, n_iter, lam, L=2):\n \"\"\"Perform experiment\"\"\"\n op = MRIOperator(samp_patt, wav, levels)\n measurements = op.sample(im)\n initial_x = op(measurements, True)\n\n gradient = LASSOGradient(op, measurements)\n alg = FISTA(gradient, L, lam)\n\n\n start = time.time()\n result = alg.run(n_iter, initial_x)\n total_time = time.time() - start\n\n return result, total_time\n","sub_path":"optimization/cpu/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"234080395","text":"import time\nimport json\nfrom datetime import datetime\nfrom MeteorClient import MeteorClient\n\ndef connected():\n print('Connected to server.')\n\ndef failed():\n print('Failed.')\n\ndef insert_callback(error, data):\n if error:\n print(error)\n return\n print(data)\n\ndef callback_function(error, result):\n print('callback')\n if error:\n print(error)\n return\n print(result)\n\nclient = MeteorClient('ws://127.0.0.1:3000/websocket')\n\nclient.on('connected', connected)\nclient.on('failed', failed)\n\nclient.connect()\n\ntimestamp = str(datetime.now())\nlat = 1.2956\nlng = 103.7767\nspeed = 50\nbearing = 50\naltitude = 50\n\nclient.insert('Telemetry', {\"timestamp\": timestamp, \"lat\": lat, \"lng\": lng, \"speed\": speed, \"bearing\": bearing, \"altitude\": altitude}, callback=insert_callback)","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"648075261","text":"# Print the average of all the numbers from 0 to the given limit that are divisible by the given number (HINT: User range())\n\nlimit = int(input('Enter limit: '))\nnum = int(input('Enter number: '))\nsum = 0\ncnt = 0\n\nfor i in range(limit+1):\n if i % num == 0:\n sum = sum + i\n cnt = cnt + 1\n\nprint(sum/cnt)","sub_path":"submissions/sm_009_chinmay/week_13/day_4/part_1/average_divisible.py","file_name":"average_divisible.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"296154878","text":"#!/usr/bin/env python \nimport roslib\nimport rospy\nimport tf\nimport geometry_msgs.msg\nfrom geometry_msgs.msg import Pose\n\ndef handle_aruco_pose(msg, markerID):\n br = tf.TransformBroadcaster()\n # Coordinates of the assembly parts from the center of the aruco marker\n br.sendTransform((0.2, 0, 0.05),\n (0,0,0,1),\n rospy.Time.now(),\n \"assembly_part_ID_%s\" % markerID,\n \"world_aruco_ID_%s\" % markerID)\n\n\nif __name__ == '__main__':\n rospy.init_node('world_aruco_tf_broadcaster')\n markerID = [0, 1, 2, 3, 4]\n rospy.Subscriber('world_to_aruco_ID_0/target_pose', geometry_msgs.msg.Pose, handle_aruco_pose, markerID[0])\n rospy.Subscriber('world_to_aruco_ID_1/target_pose', geometry_msgs.msg.Pose, handle_aruco_pose, markerID[1])\n #rospy.Subscriber('world_to_aruco_ID_2/target_pose', geometry_msgs.msg.Pose, handle_aruco_pose, markerID[2])\n #rospy.Subscriber('world_to_aruco_ID_3/target_pose', geometry_msgs.msg.Pose, handle_aruco_pose, markerID[3])\n #rospy.Subscriber('world_to_aruco_ID_4/target_pose', geometry_msgs.msg.Pose, handle_aruco_pose, markerID[4])-->\n rospy.spin()","sub_path":"fanuc_planning/src/scripts/aruco_transforms/assembly_part_tf_broadcaster.py","file_name":"assembly_part_tf_broadcaster.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"446541695","text":"def GCM(a, b):\n if a < b:\n a, b = b, a\n if a % b:\n return GCM(b, a % b)\n return b\n\ndef yakusuu(r):\n if r == 1:\n return []\n ret = [r]\n for i in range(2, int(r**0.5)+1):\n if r % i == 0:\n ret.append(i)\n ret.append(r//i)\n return sorted(ret)\n\na, b = map(int, input().split())\nyakusu = yakusuu(GCM(a, b))\n\nans = []\nfor i in yakusu:\n tmp = True\n for j in ans:\n if i % j == 0:\n tmp = False\n break\n if tmp:\n ans.append(i)\n\nprint(len(ans)+1)\n","sub_path":"contest/abc142/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"441518914","text":"# -*- coding: utf-8 -*-\n#Interpreta o arquivo como utf-8 (aceita acentos)\nimport enlayce\nimport sys\n\n\nif(len(sys.argv) < 2):\n\tprint('É necessário informar a porta serial, a ID da sessão e o tempo de timeout')\n\tprint('Ex.: inicia_enlayce10.0.0.2.py /dev/pts/38 123 5')\n\texit()\n\np_serial = sys.argv[1]\nidSessao = int(sys.argv[2])\ntimeout = float(sys.argv[3])\n\nenl = enlayce.Enlayce(p_serial, idSessao, timeout, \"10.0.0.2\", \"10.0.0.1\")\n","sub_path":"projeto1-parte2-integração-com-o-subsistema-de-rede-do-Linux/inicia_enlayce10.0.0.2.py","file_name":"inicia_enlayce10.0.0.2.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"395535366","text":"import os\nimport sys\nimport ps3hiratranslator\n\n# This is a script to translate an arbitrary file from ps3 japanese character encoding to normal encoding.\n# It is not used in the other merge scripts.\n\n# ONLY THESE INSTRUCTIONS will be substituted.\n# When scanning the script, I found that only these instructions were ever modifeid, EXCEPT\n# for the first < ? 1.0 xml > header at the top of the file, because it had a question mark\n# {'HIDDEN_DIALOGUE', '1.0', 'REGISTER_CONDITION', 'DIALOGUE'}\n# when you run this script it will print the above set\n\n# gets the instruction type of an xml instruction\ndef get_instruction_type(line):\n return line.split('\"', maxsplit=2)[1]\n\n#parse input args, determine if file is xml\nif len(sys.argv) < 2:\n print('You need to specify the file to be translated as only argument')\n exit(-1)\n\ninput_file_path = sys.argv[1]\noutput_file_path = 'sui_translated.xml'\n\nis_xml = False\nname, ext = os.path.splitext(input_file_path)\nif ext == '.xml':\n is_xml = True\n\n#do translation\nall_instructions_which_were_changed = set()\nwith open(input_file_path, encoding='utf-8') as infile:\n with open(output_file_path, 'w', encoding='utf-8') as outfile:\n for line in infile:\n # do translation\n newline = ps3hiratranslator.translate(line)\n outfile.write(newline)\n\n # record which instructions were modified\n if is_xml and newline != line:\n all_instructions_which_were_changed.add(get_instruction_type(line))\n\n# print instructions which were modified\nif is_xml:\n print(all_instructions_which_were_changed)\n","sub_path":"tools/translate_script.py","file_name":"translate_script.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"145525552","text":"# -*- coding: utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\n\nfile = open(\"capitalData.json\", \"a\")\n\nurl = \"http://www.csgnetwork.com/llinfotable.html\"\npage = requests.get(url)\nsoup = BeautifulSoup(page.content)\n\nrows = soup.find_all('tr')\ncount = 0\n\nfor row in rows:\n\tcount += 1\n\tif (count > 8 and count < 209):\n\t\tinfo = row.find_all('td')\n\t\tcountry = info[0].getText()\n\t\tcity = info[1].getText()\n\n\t\tlat = info[2].getText().encode('utf8').replace(\"°\", \".\")\n\t\tif (lat[len(lat) - 1]) == 'S':\n\t\t\tlat = \"-\" + lat\n\t\tlat = lat[:-2]\n\n\n\t\tlon = info[3].getText().encode('utf8').replace(\"°\", \".\")\n\t\tif (lon[len(lon) - 1]) == 'W':\n\t\t\tlon = \"-\" + lon\n\t\t\tlon = lon[:-2]\n\t\tif (country != \"Heard Island and McDonald Islands\"):\n\t\t\tfile.write(\"{\")\n\t\t\tdata = (\"\\n\\t\\\"country\\\": \\\"{0}\\\",\\n\\t\\\"city\\\": \\\"{1}\\\",\\n\\t\\\"latitude\\\": {2},\\n\\t\\\"longitude\\\": {3}\").format(country, city, lat, lon)\n\t\t\tfile.write(data + \"\\n}\\n\")\n","sub_path":"capitals/data/LatLongScrape.py","file_name":"LatLongScrape.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"196241853","text":"#poster\n# encoding=utf-8\nimport os\nfrom io import BytesIO\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nfrom PIL import Image\nimport re\nimport csv\nimport pandas as pd\n\nindex = 0\nptitle = ''\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}\n\ndef get_images(name, no, type):\n\tglobal index\n\tglobal ptitle\n\n\tif not os.path.exists(\"./images/\" + name + '/' + type):\n\t\tos.makedirs(\"./images/\" + name + '/' + type)\n\n\tutpye = 'still_frame' if type == 'still' else 'poster'\n\tprint(utpye)\n\turl = 'https://www.imdb.com/name/'+no+'/mediaindex?refine='+utpye\n\thtml = BeautifulSoup(requests.get(url, headers=headers).text, features=\"html.parser\")\n\timgs = html.find('div', {'class', 'media_index_thumb_list'}).find_all('a')\n\tfor link in imgs:\n\t\timg = re.sub(r'V1(\\S*).jpg','V1.jpg', link.find('img').get('src'))\n\t\ttxt = link.find('img').get('alt')\n\t\tprint(txt)\n\t\ttime.sleep(0.1)\n\t\ttry:\n\t\t\tr = requests.get(img, timeout=5, stream=True)\n\t\t\ttmpIm = BytesIO(r.content)\n\t\t\tim = Image.open(tmpIm)\n\t\t\tprint(im.size[0])\n\t\t\tif(im.size[0]<500 or im.size[0]>1200):\n\t\t\t\tprint('inappropriate')\n\t\t\t\tcontinue\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tcontinue\n\t\t\n\t\twith open('./images/' + name + '/' + type + '/' + str(index) + \".jpg\", 'wb') as jpg:\n\t\t\tprint(\"正在抓取第%s条数据\" % index)\n\t\t\tjpg.write(r.content)\n\t\t\tptitle += txt+'|'\n\t\t\tindex += 1\n\n\tdata = pd.read_csv('star.csv', encoding='utf-8')\n\tdata.tail(1)[type] = str(index)\n\tdata.tail(1)[type+'t'] = ptitle\n\tprint(data.tail(1)[type])\n\tdata.to_csv('star.csv', header=True, index=False, encoding='utf-8')\n\n#get_images('Leonardo DiCaprio', 'nm0000138', 'poster')\n#get_images('Leonardo DiCaprio', 'nm0000138', 'still')\n#get_images('Evangeline Lilly', 'nm1431940', 'poster')\nget_images('Catherine Zeta Jones', 'nm0001876', 'still')","sub_path":"ps.py","file_name":"ps.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"61796026","text":"\"\"\"Custom-made Packages installation.\n\"\"\"\nimport logging\nimport sys\nimport os\nimport stat\nimport zipfile\nfrom lib import *\nimport diomreader\nfrom time import strftime\nimport shutil\n\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt=\"\")\nlogger = logging.getLogger(\"cmpack.cmpack\")\n\nclass Package():\n \"\"\"Install/rollback/uninstall Packages\n \"\"\"\n __repoOnline = 'Online_Repo'\n __repoLocal = 'Local_Repo'\n\n def __init__(self, vendorname, profile, configFile, version=None):\n self.profile = profile\n self.configFile = configFile\n self.version = version\n self.setConfig(vendorname)\n\n def setConfig(self, vendorname):\n self.config = {}\n self.config['vendorname'] = vendorname\n (self.sysName, nodeName, release, version, self.machine) = os.uname()\n logger.debug(\"System Information: %s(OS), %s(HOST), %s(Release), %s(ARCH)\", self.sysName, nodeName, release, self.machine)\n self.config.update(propsparser.ini(self.configFile, scope=['Root'])['Root'])\n ## load Root data if file found\n if self.config.has_key('root_config_file'):\n self.config['root_config_file'] = os.path.join(os.path.dirname(self.configFile),\n self.config['root_config_file'])\n self.config.update(propsparser.ini(self.config['root_config_file'],\n scope=['Root'])['Root'])\n self.config.update(propsparser.ini(self.configFile, scope=['Root'])['Root'])\n self.config['root_config_file'] = os.path.join(os.path.dirname(self.configFile),\n self.config['root_config_file'])\n self.config.update(propsparser.ini(self.configFile, scope=[self.profile])[self.profile])\n self.config['profile'] = self.profile\n if self.config.has_key('root_config_file'):\n self.config.update(propsparser.ini(self.config['root_config_file'],\n scope=[self.config['repo_option']])[self.config['repo_option']])\n else:\n self.config.update(propsparser.ini(self.configFile,\n scope=[self.config['repo_option']])[self.config['repo_option']])\n\n ## Load local repo. Online repo is disabled.\n \"\"\"\n self.config.update(propsparser.ini(self.configFile,\n scope=[Package.__repoLocal])[Package.__repoLocal])\n \"\"\"\n\n def install(self):\n # Read online and download software\n xml = diomreader.XMLReader(url=self.config['url'], file=self.config['dm_file'],\n sysName=self.sysName,sysBit=self.machine,vendorName=self.config['vendorname'],\n packageName=self.config['pkg_name'], version=self.version,\n realm=self.config['url_realm'],user=self.config['url_user'],\n passwd=self.config['url_passwd'])\n\n self.config.update(xml.getSWDownloadDetails())\n if self.config['repo_option'] == Package.__repoLocal:\n download.Download(self.config['url'], self.config['fileName'], self.config['target_loc'],\n realm=self.config['url_realm'], user=self.config['url_user'],\n passwd=self.config['url_passwd'])\n\n if self.config['install_type'] == 'copy':\n Package.cmpack_copy(os.path.join(self.config['target_loc'],\n self.config['fileName'].rstrip('.zip')),\n self.config['install_root'],\n )\n elif self.config['install_type'] == 'overwrite':\n Package.cmpack_overwrite(os.path.join(self.config['target_loc'],\n self.config['fileName'].rstrip('.zip')),\n self.config['install_root'],\n )\n elif self.config['install_type'] == 'symlink':\n Package.cmpack_symlink(os.path.join(self.config['target_loc'],\n self.config['fileName'].rstrip('.zip')),\n self.config['install_root'],\n )\n\n\n @staticmethod\n def cmpack_copy(src, dst):\n if os.path.isdir(dst):\n timestamp = strftime(\"%Y%m%d_%H%M%S\")\n logger.info(\"Existing package found. Taking backup as %s\", dst + \".\" + timestamp)\n os.rename(dst, dst + \".\" + timestamp)\n logger.info(\"Copying from %s to %s\", src, dst)\n shutil.copytree(src, dst, symlinks=False, ignore=None)\n\n @staticmethod\n def cmpack_overwrite(src, dst):\n if os.path.isdir(dst):\n timestamp = strftime(\"%Y%m%d_%H%M%S\")\n logger.info(\"Existing package found. Taking backup as %s\", dst + \".\" + timestamp)\n shutil.copytree(dst, dst + \".\" + timestamp, symlinks=False, ignore=None)\n cmd = ( \"cp -R \" + src + '/* ' + dst)\n else:\n cmd = ( \"cp -R \" + src + ' ' + dst)\n logger.info(\"Copying from %s to %s\", src, dst)\n (ret_code, output) = shell.Shell.runCmd(cmd)\n\n @staticmethod\n def cmpack_symlink(src, dst):\n logger.info(\"Copying from %s to %s\", src, dst)\n cmd = ( \"cp -R \" + src + ' ' + os.path.join(os.path.dirname(dst), os.path.basename(src)))\n (ret_code, output) = shell.Shell.runCmd(cmd)\n if os.path.islink(dst):\n logger.info(\"Symlink found for %s. Removing it.\", dst)\n cmd = ( \"unlink \" + dst)\n (ret_code, output) = shell.Shell.runCmd(cmd)\n cmd = ( \"ln -s \" + os.path.join(os.path.dirname(dst), os.path.basename(src)) + \\\n \" \" + dst)\n logger.info(\"Creating symlink for %s -> %s\", dst,\n os.path.join(os.path.dirname(dst), os.path.basename(src)))\n (ret_code, output) = shell.Shell.runCmd(cmd)\n","sub_path":"plugins/cmpack/lib/cmpack.py","file_name":"cmpack.py","file_ext":"py","file_size_in_byte":6051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"374711013","text":"from os.path import expanduser, join, exists\nfrom os import mkdir\nimport requests\nfrom mutagen.id3 import ID3, APIC, TIT2, MutagenError, TPE1, TCON, Encoding, TALB, TIT3\nfrom mutagen.mp3 import MP3\n\nHOME_DIR = expanduser('~')\nMEDIA_DIR = join(HOME_DIR, \"mediasync\")\nif not exists(MEDIA_DIR):\n mkdir(MEDIA_DIR)\n\nCLIENT_ID = \"0f2c0a484c1aaf5a86b68200cf308b45\"\nCHUNK_SIZE = 5000\n\n\ndef set_image(id3, url, cover_type, description):\n if url:\n artwork_url = url.replace(\"-large.\", \"-t500x500.\")\n response = requests.get(artwork_url)\n if response.ok:\n id3.tags.add(APIC(\n encoding=Encoding.UTF8,\n mime='image/png' if artwork_url.endswith(\".png\") else \"image/jpeg\",\n type=cover_type,\n desc=description,\n data=response.content))\n\n\ndef main():\n response = requests.get(\n \"http://api.soundcloud.com/users/kapouille/favorites\",\n params={\"client_id\": CLIENT_ID, \"limit\": 50000})\n if response.ok:\n favourites = response.json()\n for favourite in favourites:\n if favourite[\"streamable\"]:\n filename = join(MEDIA_DIR, str(favourite[\"id\"]) + \".mp3\")\n if not exists(filename):\n response = requests.get(\n favourite[\"stream_url\"],\n params={\"client_id\": CLIENT_ID},\n stream=True)\n if response.ok:\n with open(filename, 'wb') as fd:\n for chunk in response.iter_content(CHUNK_SIZE):\n fd.write(chunk)\n print(\"downloading \" + favourite[\"title\"])\n else:\n continue\n else:\n print(favourite[\"title\"] + \" already downloaded\")\n\n id3 = MP3(filename, ID3=ID3)\n # add ID3 tag if it doesn't exist\n try:\n id3.add_tags()\n except MutagenError:\n pass\n\n id3.tags.clear()\n id3.tags.add(TIT2(\n encoding=Encoding.UTF8, text=[favourite[\"title\"]]))\n id3.tags.add(TIT3(\n encoding=Encoding.UTF8, text=[favourite[\"description\"]]))\n id3.tags.add(TPE1(\n encoding=Encoding.UTF8,\n text=[favourite[\"user\"][\"username\"]]))\n id3.tags.add(TCON(\n encoding=Encoding.UTF8, text=[favourite[\"genre\"]]))\n id3.tags.add(TALB(encoding=Encoding.UTF8, text=[\"SoundCloud\"]))\n\n set_image(id3, favourite[\"artwork_url\"], 4, \"Back Cover\")\n set_image(id3, favourite[\"user\"][\"avatar_url\"], 8, \"Artist\")\n id3.tags.add(APIC(\n encoding=Encoding.UTF8,\n mime=\"image/png\",\n type=3, # 3 front cover image\n desc='Cover',\n data=open('soundcloud.png', \"rb\").read()))\n id3.save()\n\nmain()\n\n\n\n\n\n\n\n\n","sub_path":"mediasync/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"16686269","text":"import winreg\nimport ctypes\nimport sys\n\ndef is_admin():\n try:\n return ctypes.windll.shell32.IsUserAnAdmin()\n except:\n return False\n\nif is_admin():\n network_list_path = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\NetworkList'\n\n nla_cache_path = network_list_path + '\\\\Nla\\\\Cache'\n try:\n nla_cache_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, nla_cache_path, 0, winreg.KEY_ALL_ACCESS)\n nla_cache_intranet_subkey = winreg.OpenKey(nla_cache_key, 'Intranet', 0, winreg.KEY_ALL_ACCESS)\n winreg.DeleteKey(nla_cache_intranet_subkey, 'lan')\n nla_cache_intranet_subkey.Close()\n winreg.DeleteKey(nla_cache_key, 'Intranet')\n nla_cache_key.Close()\n except:\n print(nla_cache_path + ' not found.')\n \n nla_wireless_path = network_list_path + '\\\\Nla\\\\Wireless'\n try:\n nla_wireless_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, nla_wireless_path, 0, winreg.KEY_ALL_ACCESS)\n count_of_keys_in_nla_wireless = winreg.QueryInfoKey(nla_wireless_key)[0]\n for i in range(count_of_keys_in_nla_wireless):\n winreg.DeleteKey(nla_wireless_key, winreg.EnumKey(nla_wireless_key, 0))\n nla_wireless_key.Close()\n except:\n print(nla_wireless_path + ' not found.')\n \n profiles_path = network_list_path + '\\\\Profiles'\n try:\n profiles_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, profiles_path, 0, winreg.KEY_ALL_ACCESS)\n count_of_keys_in_profiles = winreg.QueryInfoKey(profiles_key)[0]\n for i in range(count_of_keys_in_profiles):\n winreg.DeleteKey(profiles_key, winreg.EnumKey(profiles_key, 0))\n profiles_key.Close()\n except:\n print(profiles_path + ' not found.')\n \n signatures_unmanaged_path = network_list_path + '\\\\Signatures\\\\Unmanaged'\n try:\n signatures_unmanaged_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, signatures_unmanaged_path, 0, winreg.KEY_ALL_ACCESS)\n count_of_keys_in_signatures_unmanaged = winreg.QueryInfoKey(signatures_unmanaged_key)[0]\n for i in range(count_of_keys_in_signatures_unmanaged):\n winreg.DeleteKey(signatures_unmanaged_key, winreg.EnumKey(signatures_unmanaged_key, 0))\n signatures_unmanaged_key.Close()\n except:\n print(signatures_unmanaged_path + ' not found.')\n\nelse:\n ctypes.windll.shell32.ShellExecuteW(None, 'runas', sys.executable, __file__, None, 1)\n","sub_path":"network_list_cleaner.py","file_name":"network_list_cleaner.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"557534365","text":"#!/bin/python3\n\nimport numpy\nimport time\n#from f_toolbox import atom\n\nfrom g import g\nfrom ds import ds\n\n\n\nclass std:\n\n\n\n @staticmethod\n def read(file_path):\n\n # Read file\n ###############################################################\n\n block = ''\n fh = open(file_path, 'r')\n for line in fh:\n block = block + line\n fh.close()\n\n no_comments = ''\n in_comment = 0\n n = 0\n while(n 5.0:\n f = self.DEAD\n else:\n f = self.LIVE\n self.canvas.itemconfig(self.get_rect(x, y), fill=f)\n\n def reset_to_pulsator(self, x, yoffset):\n for x_offset in [x, x + 5]:\n #\n self.canvas.itemconfig(self.get_rect(x_offset - 2, yoffset + 0), fill=self.LIVE)\n self.canvas.itemconfig(self.get_rect(x_offset - 1, yoffset + 0), fill=self.LIVE)\n #\n self.canvas.itemconfig(self.get_rect(x_offset + 0, yoffset - 1), fill=self.LIVE)\n self.canvas.itemconfig(self.get_rect(x_offset + 0, yoffset + 1), fill=self.LIVE)\n #\n self.canvas.itemconfig(self.get_rect(x_offset + 1, yoffset + 0), fill=self.LIVE)\n self.canvas.itemconfig(self.get_rect(x_offset + 2, yoffset + 0), fill=self.LIVE)\n\n def reset_to_blinker(self, x, y):\n self.canvas.itemconfig(self.get_rect(x + 0, y), fill=self.LIVE)\n self.canvas.itemconfig(self.get_rect(x + 1, y), fill=self.LIVE)\n self.canvas.itemconfig(self.get_rect(x + 2, y), fill=self.LIVE)\n\n def get_rect(self, x, y):\n return self.rects[y * self.COLS + x]\n\n def is_alive(self, x, y):\n r = self.get_rect(x, y)\n return self.canvas.itemcget(r, \"fill\") == self.LIVE\n\n def num_living_neighbors(self, xxx, yyy):\n num = 0\n for x in range(xxx - 1, xxx + 2):\n for y in range(yyy - 1, yyy + 2):\n if x != xxx or y != yyy:\n if self.is_alive(x, y):\n num += 1\n return num\n\n def num_alive(self):\n num = 0\n for r in self.rects:\n if self.canvas.itemcget(r, \"fill\") == self.LIVE:\n num += 1\n return num\n\n def on_update(self):\n idle_secs = self.timeout_idle()\n if (time.time() - self.last_exec) < self.UPDATE_IN_SECS:\n return\n self.last_exec = time.time()\n\n # return True\n self.canvas.itemconfig(self.info, text=str(self.TIMEOUT - idle_secs))\n\n next_state = []\n # top row\n for x in range(self.COLS):\n next_state.append(self.DEAD)\n\n for y in range(1, self.ROWS - 1):\n # left col\n next_state.append(self.DEAD)\n for x in range(1, self.COLS - 1):\n nn = self.num_living_neighbors(x, y)\n is_dead = not self.is_alive(x, y)\n if is_dead and nn == 3:\n next_state.append(self.LIVE)\n elif not is_dead and nn < 2:\n next_state.append(self.DEAD)\n elif not is_dead and (nn == 2 or nn == 3):\n next_state.append(self.LIVE)\n elif not is_dead and nn > 3:\n next_state.append(self.DEAD)\n else:\n if is_dead:\n next_state.append(self.DEAD)\n else:\n next_state.append(self.LIVE)\n # right col\n next_state.append(self.DEAD)\n\n # bottom row\n for x in range(self.COLS):\n next_state.append(self.DEAD)\n\n # apply\n for i, r in enumerate(self.rects):\n r = self.rects[i]\n self.canvas.itemconfig(r, fill=next_state[i])\n\n def on_click(self, event):\n self.reset_timeout()\n\n x = int(event.x / self.TILE_SIZE)\n y = int(event.y / self.TILE_SIZE)\n\n # top left\n if x == 0 and y == 0:\n self.close_cnt += 1\n if self.close_cnt > 1:\n return self.close()\n\n if self.num_alive() == 0:\n self.on_reset(None)\n","sub_path":"User/rpi.py/src/apps/Conway.py","file_name":"Conway.py","file_ext":"py","file_size_in_byte":5588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"27686514","text":"s = input().lower().split()\ns = \"\".join(s)\n\ndef PangramChecker(s):\n subsequence = \"abcdefghijklmnopqrstuvwxyz\"\n j = 0\n for i in subsequence:\n if s.find(i)!=-1:\n j += 1\n if j==len(subsequence):\n return \"Pangram\"\n else:\n return \"not Pangram\"\n\nprint(PangramChecker(s))\n","sub_path":"Python/PangramChecker.py","file_name":"PangramChecker.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"563826029","text":"\ndef InitFM(startPoint, map):\n # Initialize FM propagation with T = 0\n map[startPoint[0],startPoint[1]] = 0 \n return map\n\ndef Eikonal(startPoint, currentCell, cellMap):\n\n ## Calculate arrival time from the propagation point\n time = 0\n\n # Calculate dx and dy \n dx = currentCell.x - startPoint[0]\n dy = currentCell.y - startPoint[1]\n\n # Get Tx and Ty\n\n # If dx or dy are negatives then select the cell on the right (-1) of the map\n # else select the cell on the left (+1)\n if(dx < 0):\n xCell = cellMap[currentCell.x - 1][currentCell.y]\n else:\n xCell = cellMap[currentCell.x + 1][currentCell.y]\n \n if(dy < 0):\n yCell = cellMap[currentCell.x][currentCell.y - 1]\n else:\n yCell = cellMap[currentCell.x][currentCell.y + 1]\n \n\n if( not yCell and not xCell):\n return False\n\n # If the cell is occupied the corresponding time is set to 0\n if(yCell == False):\n # dx/F = dx ; F=1\n return (xCell.cost + dx)\n else:\n Ty = yCell.cost\n\n if(xCell == False):\n # dx/F = dx ; F=1\n Tx = (yCell.cost + dy)\n else:\n Tx = xCell.cost\n\n # Calculate\n\n return time\n","sub_path":"Fast Marching/FastMarchingMethod.py","file_name":"FastMarchingMethod.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"474165923","text":"from pathlib import Path\nimport argparse\nimport pandas as pd\nimport os\n\nHERE = os.path.abspath(os.path.dirname(__file__))\nDEFAULT_CONFIG_FILE = os.path.join(HERE, \"config_templates\",\n \"default_configs.txt\")\nDATASET_STATS = os.path.join(HERE, \"dataset_stats\", \"dataset_stats.tsv\")\n\n\ndef output_config(config_dict, output_dir):\n device = config_dict.get(\"device\")\n if config_dict.get(\"dataset\") is None:\n ds_name = \"custom\"\n else:\n ds_name = config_dict.get(\"dataset\")\n\n file = Path(output_dir) / Path(str(ds_name) + \"_\" +\n device.lower() + \".ini\")\n sections = [\"model\", \"storage\", \"training\", \"training_pipeline\",\n \"evaluation\", \"evaluation_pipeline\", \"path\", \"reporting\"]\n opts = list(config_dict.keys())\n\n with open(file, \"w+\") as f:\n f.write(\"[general]\\n\")\n f.write(\"device=\" + config_dict.get(\"general.device\") + \"\\n\")\n if config_dict.get(\"general.gpu_ids\") is not None:\n f.write(\"gpu_ids=\" + config_dict.get(\"general.gpu_ids\") + \"\\n\")\n if config_dict.get(\"general.random_seed\") is not None:\n f.write(\"random_seed=\" + config_dict.get(\"general.random_seed\")\n + \"\\n\")\n f.write(\"num_train=\" + str(config_dict.get(\"num_train\")) + \"\\n\")\n f.write(\"num_nodes=\" + str(config_dict.get(\"num_nodes\")) + \"\\n\")\n f.write(\"num_relations=\" + str(config_dict.get(\"num_relations\"))\n + \"\\n\")\n f.write(\"num_valid=\" + str(config_dict.get(\"num_valid\")) + \"\\n\")\n f.write(\"num_test=\" + str(config_dict.get(\"num_test\")) + \"\\n\")\n f.write(\"experiment_name=\" +\n config_dict.get(\"general.experiment_name\") + \"\\n\")\n\n for sec in sections:\n f.write(\"\\n[\" + sec + \"]\\n\")\n for key in opts:\n if key.split(\".\")[0] == sec:\n f.write(key.split(\".\")[1] +\n \"=\" + config_dict.get(key) + \"\\n\")\n\n\ndef read_template(file):\n with open(file, \"r\") as f:\n lines = f.readlines()\n\n keys = []\n values = []\n valid_dict = {}\n for line in lines:\n line = line.split(\"=\")\n line[1] = line[1].rstrip()\n keys.append(line[0])\n sub_line = line[1].split(\"*\")\n values.append(sub_line[0])\n if len(sub_line) > 1:\n valid_dict.update({line[0]: [sub_line[1:]]})\n config_dict = dict(zip(keys, values))\n\n return config_dict, valid_dict\n\n\ndef set_up_files(output_directory):\n try:\n if not Path(output_directory).exists():\n Path(output_directory).mkdir(parents=False, exist_ok=False)\n except FileExistsError:\n print(\"Directory already exists.\")\n except FileNotFoundError:\n print(\"Incorrect parent path given for output directory.\")\n\n\ndef update_dataset_stats(dataset, config_dict):\n datasets_stats = pd.read_csv(DATASET_STATS, sep='\\t')\n stats_row = datasets_stats[datasets_stats['dataset'] == dataset]\n if not stats_row.empty:\n stats_list = stats_row.iloc[0][['num_nodes', 'num_relations',\n 'num_train', 'num_valid',\n 'num_test']].tolist()\n config_dict = update_stats(stats_list, config_dict)\n else:\n raise RuntimeError(\"Unrecognized dataset\")\n\n return config_dict\n\n\ndef update_stats(stats, config_dict):\n config_dict.update({\"num_train\": str(int(stats[2]))})\n config_dict.update({\"num_nodes\": str(int(stats[0]))})\n config_dict.update({\"num_relations\": str(int(stats[1]))})\n config_dict.update({\"num_valid\": str(int(stats[3]))})\n config_dict.update({\"num_test\": str(int(stats[4]))})\n\n return config_dict\n\n\ndef update_data_path(dir, config_dict):\n config_dict.update({\"path.train_edges\": str(dir.strip(\"/\") +\n \"/train_edges.pt\")})\n config_dict.update({\"path.train_edges_partitions\": str(dir.strip(\"/\") +\n \"/train_edges_partitions.txt\")})\n config_dict.update({\"path.validation_edges\": str(dir.strip(\"/\") +\n \"/valid_edges.pt\")})\n config_dict.update({\"path.test_edges\": str(dir.strip(\"/\") +\n \"/test_edges.pt\")})\n config_dict.update({\"path.node_labels\": str(dir.strip(\"/\") +\n \"/node_mapping.txt\")})\n config_dict.update({\"path.relation_labels\": str(dir.strip(\"/\") +\n \"/rel_mapping.txt\")})\n config_dict.update({\"path.node_ids\": str(dir.strip(\"/\") +\n \"/node_mapping.bin\")})\n config_dict.update({\"path.relations_ids\": str(dir.strip(\"/\") +\n \"/rel_mapping.bin\")})\n\n return config_dict\n\n\ndef set_args():\n parser = argparse.ArgumentParser(\n description='Generate configs', prog='config_generator',\n formatter_class=argparse.RawTextHelpFormatter,\n epilog=('Specify certain config (optional): ' +\n '[--

.=]'))\n mode = parser.add_mutually_exclusive_group()\n parser.add_argument('output_directory', metavar='output_directory',\n type=str, help='Directory to put configs \\nAlso ' +\n 'assumed to be the default directory of preprocessed' +\n ' data if --data_directory is not specified')\n parser.add_argument('--data_directory', metavar='data_directory',\n type=str, help='Directory of the preprocessed data')\n mode.add_argument('--dataset', '-d', metavar='dataset', type=str,\n help='Dataset to preprocess')\n mode.add_argument('--stats', '-s',\n metavar=('num_nodes', 'num_relations', 'num_train',\n 'num_valid', 'num_test'),\n nargs=5, help='Dataset statistics\\n' +\n 'Enter in order of num_nodes, num_relations, num_train' +\n ' num_valid, num_test')\n parser.add_argument('--device', '-dev', metavar='generate_config',\n choices=[\"GPU\", \"CPU\", \"multi-GPU\"],\n nargs='?', default='GPU',\n help=('Generates configs for a single-GPU/multi-CPU' +\n '/multi-GPU training configuration file by ' +\n 'default. \\nValid options (default to GPU): ' +\n '[GPU, CPU, multi-GPU]'))\n\n config_dict, valid_dict = read_template(DEFAULT_CONFIG_FILE)\n\n for key in list(config_dict.keys())[1:]:\n if valid_dict.get(key) is not None:\n parser.add_argument(str(\"--\" + key), metavar=key, type=str,\n choices=valid_dict.get(key),\n default=config_dict.get(key),\n help=argparse.SUPPRESS)\n else:\n parser.add_argument(str(\"--\" + key), metavar=key, type=str,\n default=config_dict.get(key),\n help=argparse.SUPPRESS)\n\n return parser, config_dict\n\n\ndef parse_args(args):\n arg_dict = vars(args)\n set_up_files(args.output_directory)\n\n arg_dict.update({\"general.device\": arg_dict.get(\"device\")})\n if arg_dict.get(\"device\") == \"multi-GPU\":\n arg_dict.update({\"device\": \"multi_GPU\"})\n arg_dict.update({\"general.device\": \"GPU\"})\n arg_dict.update({\"general.gpu_ids\": \"0 1\"})\n else:\n arg_dict.update({\"device\": arg_dict.get(\"device\")})\n\n if arg_dict.get(\"general.random_seed\") == \"#\":\n arg_dict.pop(\"general.random_seed\")\n\n if arg_dict.get(\"dataset\") is not None:\n arg_dict.update({\"dataset\": arg_dict.get(\"dataset\")})\n arg_dict = update_dataset_stats(arg_dict.get(\"dataset\"), arg_dict)\n elif arg_dict.get(\"stats\") is not None:\n arg_dict = update_stats(arg_dict.get(\"stats\"), arg_dict)\n else:\n raise RuntimeError(\"Must specify either dataset or dataset stats.\")\n\n return arg_dict\n\n\ndef main():\n parser, config_dict = set_args()\n args = parser.parse_args()\n config_dict = parse_args(args)\n\n dir = args.output_directory\n if args.data_directory is None:\n config_dict = update_data_path(dir, config_dict)\n else:\n config_dict = update_data_path(args.data_directory, config_dict)\n\n output_config(config_dict, dir)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/python/tools/config_generator.py","file_name":"config_generator.py","file_ext":"py","file_size_in_byte":8439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"550203580","text":"\"\"\"Extract .gmas to folders.\"\"\"\nfrom os.path import exists as path_exists\nfrom os.path import dirname as path_get_directory\nfrom os.path import join as path_join\nfrom os.path import splitext as path_ext\nfrom os import makedirs as path_make_directories\nfrom binascii import crc32\nfrom shutil import rmtree\nfrom json import loads as json_decode\nimport chardet\n\nif __name__ == \"__main__\":\n import utils\nelse:\n import gmad.utils as utils\n\ndef get_header(in_path):\n \"\"\"Extracts the gma header from the input file.\"\"\"\n if not path_exists(in_path):\n raise IOError(\"in_path \" + in_path + \" does not exist.\")\n\n file = open(in_path, 'rb')\n data = {}\n\n data['identifier'] = utils.read_length_string(file, 4)\n if data['identifier'] != \"GMAD\":\n raise IOError(\"in_path `\" + in_path + \"` does not contain .gma file.\")\n\n data['gmadversion'] = utils.read_int(file, 1)\n data['steamid'] = utils.read_int(file, 8)\n data['timestamp'] = utils.read_int(file, 8)\n data['required'] = utils.read_int(file, 1)\n data['title'] = utils.read_null_string(file)\n data['info'] = utils.read_null_string(file)\n data['author'] = utils.read_null_string(file)\n data['version'] = utils.read_int(file)\n\n return data, file\n\ndef extract_header(in_path):\n \"\"\"Extracts the gma header, closing the file and returning the information.\"\"\"\n header, file = get_header(in_path)\n file.close()\n\n header['in_json'] = json_decode(header['info'])\n return header\n\ndef extract_gma(in_path, out_path):\n if path_exists(out_path):\n rmtree(out_path)\n if not path_exists(out_path):\n path_make_directories(out_path)\n\n \"\"\"Takes an input path, and output path, and creates a directory from the gma input.\"\"\"\n data, file = get_header(in_path) # Call the function. Might as well, keep it dry.\n\n file_num = 0\n files = []\n\n while utils.read_int(file) != 0:\n file_data = {}\n file_num += 1\n file_data['name'] = utils.read_null_string(file)\n file_data['size'] = utils.read_int(file, 8)\n file_data['crc'] = utils.read_int(file)\n files.append(file_data)\n\n for key in range(file_num):\n content = file.read(files[key][\"size\"])\n\n if crc32(content) != files[key]['crc']:\n raise IOError(\"CRC of data from \" + files[key]['name'] + \" failed to pass CRC.\")\n\n tmp_out_path = path_join(out_path, files[key]['name'])\n if not path_exists(path_get_directory(tmp_out_path)):\n path_make_directories(path_get_directory(tmp_out_path))\n with open(tmp_out_path, 'wb') as new_file:\n new_file.write(content)\n _, ext = path_ext(tmp_out_path)\n if ext == \".lua\":\n with open(tmp_out_path, 'rb') as new_file:\n cnt = new_file.read()\n cset = chardet.detect(cnt)['encoding']\n if cset is None:\n cset = \"ascii\"\n # print(tmp_out_path, cset)\n cnt = cnt.decode(cset, errors = \"ignore\")\n cnt = cnt.replace(\"//\", \"--\")\n cnt = cnt.replace(\"/*\", \"--[[\")\n cnt = cnt.replace(\"*/\", \"--]]\")\n with open(tmp_out_path, 'w', encoding=\"utf8\") as new_file:\n new_file.write(cnt)\n\n with open(path_join(out_path, \"addon.json\"), 'w', encoding=\"utf8\") as new_file:\n new_file.write(data['info'])\n\n file.close()\n return data\n\nif __name__ == \"__main__\":\n import sys\n try:\n PATH = sys.argv[1]\n if len(sys.argv) > 2:\n OUT = sys.argv[2]\n else:\n OUT = \"\"\n extract_gma(PATH, OUT)\n except IndexError:\n print(\"Usage: fromgma.py []\")\n print(\"Created and populate the output directory.\")\n print(\"Data is sourced from the gma passed as input path.\")\n","sub_path":"worker/gmad/fromgma.py","file_name":"fromgma.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"84945085","text":"# Copyright (c) 2011 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom lxml import etree\nimport numbers\n\nfrom troveclient.compat import exceptions\nfrom troveclient.compat import client\n\nXML_NS = {None: \"http://docs.openstack.org/database/api/v1.0\"}\n\n# If XML element is listed here then this searches through the ancestors.\nLISTIFY = {\n \"accounts\": [[]],\n \"databases\": [[]],\n \"flavors\": [[]],\n \"instances\": [[]],\n \"links\": [[]],\n \"hosts\": [[]],\n \"devices\": [[]],\n \"users\": [[]],\n \"versions\": [[]],\n \"attachments\": [[]],\n \"limits\": [[]],\n \"security_groups\": [[]],\n \"backups\": [[]],\n \"datastores\": [[]],\n \"datastore_versions\": [[]],\n \"configuration_parameters\": [[]],\n}\n\n\nclass IntDict(object):\n pass\n\n\nTYPE_MAP = {\n \"instance\": {\n \"volume\": {\n \"used\": float,\n \"size\": int,\n \"total\": float,\n },\n \"deleted\": bool,\n \"server\": {\n \"local_id\": int,\n \"deleted\": bool,\n },\n },\n \"instances\": {\n \"deleted\": bool,\n },\n \"deleted\": bool,\n \"flavor\": {\n \"ram\": int,\n },\n \"diagnostics\": {\n \"vmHwm\": int,\n \"vmPeak\": int,\n \"vmSize\": int,\n \"threads\": int,\n \"vmRss\": int,\n \"fdSize\": int,\n },\n \"security_group_rule\": {\n \"from_port\": int,\n \"to_port\": int,\n },\n \"quotas\": IntDict,\n \"configuration_parameter\": {\n \"max\": int,\n \"min\": int,\n },\n}\nTYPE_MAP[\"flavors\"] = TYPE_MAP[\"flavor\"]\n\nREQUEST_AS_LIST = set(['databases', 'users'])\n\n\ndef element_ancestors_match_list(element, list):\n \"\"\"\n For element root at matches against\n list [\"blah\", \"foo\"].\n \"\"\"\n itr_elem = element.getparent()\n for name in list:\n if itr_elem is None:\n break\n if name != normalize_tag(itr_elem):\n return False\n itr_elem = itr_elem.getparent()\n return True\n\n\ndef element_must_be_list(parent_element, name):\n \"\"\"Determines if an element to be created should be a dict or list.\"\"\"\n if name in LISTIFY:\n list_of_lists = LISTIFY[name]\n for tag_list in list_of_lists:\n if element_ancestors_match_list(parent_element, tag_list):\n return True\n return False\n\n\ndef element_to_json(name, element):\n if element_must_be_list(element, name):\n return element_to_list(element)\n else:\n return element_to_dict(element)\n\n\ndef root_element_to_json(name, element):\n \"\"\"Returns a tuple of the root JSON value, plus the links if found.\"\"\"\n if name == \"rootEnabled\": # Why oh why were we inconsistent here? :'(\n if element.text.strip() == \"False\":\n return False, None\n elif element.text.strip() == \"True\":\n return True, None\n if element_must_be_list(element, name):\n return element_to_list(element, True)\n else:\n return element_to_dict(element), None\n\n\ndef element_to_list(element, check_for_links=False):\n \"\"\"\n For element \"foo\" in \n Returns [{}, {}]\n \"\"\"\n links = None\n result = []\n for child_element in element:\n # The \"links\" element gets jammed into the root element.\n if check_for_links and normalize_tag(child_element) == \"links\":\n links = element_to_list(child_element)\n else:\n result.append(element_to_dict(child_element))\n if check_for_links:\n return result, links\n else:\n return result\n\n\ndef element_to_dict(element):\n result = {}\n for name, value in element.items():\n result[name] = value\n for child_element in element:\n name = normalize_tag(child_element)\n result[name] = element_to_json(name, child_element)\n if len(result) == 0 and element.text:\n string_value = element.text.strip()\n if len(string_value):\n if string_value == 'None':\n return None\n return string_value\n return result\n\n\ndef standardize_json_lists(json_dict):\n \"\"\"\n In XML, we might see something like {'instances':{'instances':[...]}},\n which we must change to just {'instances':[...]} to be compatible with\n the true JSON format.\n\n If any items are dictionaries with only one item which is a list,\n simply remove the dictionary and insert its list directly.\n \"\"\"\n found_items = []\n for key, value in json_dict.items():\n value = json_dict[key]\n if isinstance(value, dict):\n if len(value) == 1 and isinstance(value.values()[0], list):\n found_items.append(key)\n else:\n standardize_json_lists(value)\n for key in found_items:\n json_dict[key] = json_dict[key].values()[0]\n\n\ndef normalize_tag(elem):\n \"\"\"Given an element, returns the tag minus the XMLNS junk.\n\n IOW, .tag may sometimes return the XML namespace at the start of the\n string. This gets rids of that.\n \"\"\"\n try:\n prefix = \"{\" + elem.nsmap[None] + \"}\"\n if elem.tag.startswith(prefix):\n return elem.tag[len(prefix):]\n except KeyError:\n pass\n return elem.tag\n\n\ndef create_root_xml_element(name, value):\n \"\"\"Create the first element using a name and a dictionary.\"\"\"\n element = etree.Element(name, nsmap=XML_NS)\n if name in REQUEST_AS_LIST:\n add_subelements_from_list(element, name, value)\n else:\n populate_element_from_dict(element, value)\n return element\n\n\ndef create_subelement(parent_element, name, value):\n \"\"\"Attaches a new element onto the parent element.\"\"\"\n if isinstance(value, dict):\n create_subelement_from_dict(parent_element, name, value)\n elif isinstance(value, list):\n create_subelement_from_list(parent_element, name, value)\n else:\n raise TypeError(\"Can't handle type %s.\" % type(value))\n\n\ndef create_subelement_from_dict(parent_element, name, dict):\n element = etree.SubElement(parent_element, name)\n populate_element_from_dict(element, dict)\n\n\ndef create_subelement_from_list(parent_element, name, list):\n element = etree.SubElement(parent_element, name)\n add_subelements_from_list(element, name, list)\n\n\ndef add_subelements_from_list(element, name, list):\n if name.endswith(\"s\"):\n item_name = name[:len(name) - 1]\n else:\n item_name = name\n for item in list:\n create_subelement(element, item_name, item)\n\n\ndef populate_element_from_dict(element, dict):\n for key, value in dict.items():\n if isinstance(value, basestring):\n element.set(key, value)\n elif isinstance(value, numbers.Number):\n element.set(key, str(value))\n elif isinstance(value, None.__class__):\n element.set(key, '')\n else:\n create_subelement(element, key, value)\n\n\ndef modify_response_types(value, type_translator):\n \"\"\"\n This will convert some string in response dictionary to ints or bool\n so that our response is compatible with code expecting JSON style responses\n \"\"\"\n if isinstance(value, str):\n if value == 'True':\n return True\n elif value == 'False':\n return False\n else:\n return type_translator(value)\n elif isinstance(value, dict):\n for k, v in value.iteritems():\n if type_translator is not IntDict:\n if v.__class__ is dict and v.__len__() == 0:\n value[k] = None\n elif k in type_translator:\n value[k] = modify_response_types(value[k],\n type_translator[k])\n else:\n value[k] = int(value[k])\n return value\n elif isinstance(value, list):\n return [modify_response_types(element, type_translator)\n for element in value]\n\n\nclass TroveXmlClient(client.TroveHTTPClient):\n\n @classmethod\n def morph_request(self, kwargs):\n kwargs['headers']['Accept'] = 'application/xml'\n kwargs['headers']['Content-Type'] = 'application/xml'\n if 'body' in kwargs:\n body = kwargs['body']\n root_name = body.keys()[0]\n xml = create_root_xml_element(root_name, body[root_name])\n xml_string = etree.tostring(xml, pretty_print=True)\n kwargs['body'] = xml_string\n\n @classmethod\n def morph_response_body(self, body_string):\n # The root XML element always becomes a dictionary with a single\n # field, which has the same key as the elements name.\n result = {}\n try:\n root_element = etree.XML(body_string)\n except etree.XMLSyntaxError:\n raise exceptions.ResponseFormatError()\n root_name = normalize_tag(root_element)\n root_value, links = root_element_to_json(root_name, root_element)\n result = {root_name: root_value}\n if links:\n result['links'] = links\n modify_response_types(result, TYPE_MAP)\n return result\n","sub_path":"troveclient/compat/xml.py","file_name":"xml.py","file_ext":"py","file_size_in_byte":9588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"324277259","text":"######################\n# Positional Arguments\n######################\n\nparam_args = [1, 2, 3]\nparam_kwargs = {'x': 1, 'y': 2}\n\ndef func(a, b=1):\n print(a, b)\n\ndef positional_unlimited(a, b=1, *args):\n print(a, b, *args)\n\nfunc(1)\nfunc(1, 42)\nfunc(1, 2, 3) # Noncompliant. Too many positional arguments\nfunc() # Noncompliant. Missing positional argument for \"a\"\n\npositional_unlimited(1, 2, 3, 4, 5)\n\ndef positional_limited(a, *, b=2):\n print(a, b)\n\npositional_limited(1, 2) # Noncompliant. Too many positional arguments\n\n\n#############################\n# Unexpected Keyword argument\n#############################\n\ndef keywords(a=1, b=2, *, c=3):\n print(a, b, c)\n\nkeywords(1)\nkeywords(1, z=42) # Noncompliant. Unexpected keyword argument \"z\"\n\ndef keywords_unlimited(a=1, b=2, *, c=3, **kwargs):\n print(a, b, kwargs)\n\nkeywords_unlimited(a=1, b=2, z=42)\n\n#################################\n# Mandatory Keyword argument only\n#################################\n\ndef mandatory_keyword(a, *, b):\n print(a, b)\n\nmandatory_keyword(1, b=2)\nmandatory_keyword(1) # Noncompliant. Missing keyword argument \"b\"\n\n\n\n####################################################\nfrom Cryptodome.Cipher import DES, DES3, ARC2, ARC4, Blowfish, AES\nfrom Cryptodome.Random import get_random_bytes\n\nkey = b'-8B key-'\nDES.new(key, DES.MODE_OFB) # Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search\n\nkey = DES3.adjust_key_parity(get_random_bytes(24))\ncipher = DES3.new(key, DES3.MODE_CFB) # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack\n\nkey = b'Sixteen byte key'\ncipher = ARC2.new(key, ARC2.MODE_CFB) # Noncompliant: RC2 is vulnerable to a related-key attack\n\nkey = b'Very long and confidential key'\ncipher = ARC4.new(key) # Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security)\n\nkey = b'An arbitrarily long key'\ncipher = Blowfish.new(key, Blowfish.MODE_CBC) # Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks\n\n######################################################\ndef foo(a): # NonCompliant\n b = 12\n if a == 1:\n return b\n return b\n\n#######################################################\nusername = 'admin'\npassword = 'admin' # Sensitive\nusernamePassword = 'user=admin&password=admin' # Sensitive\n","sub_path":"src/noncompliant.py","file_name":"noncompliant.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"441766272","text":"import numpy as np\n\n\ndef calc_logits(matrix):\n \"\"\"\n Self-attention Logits\n :param matrix: numpy matrix\n \"\"\"\n return np.dot(matrix, np.transpose(matrix))\n\n\ndef rows_softmax(matrix):\n \"\"\"\n Softmax by rows\n :param matrix: numpy matrix\n \"\"\"\n att_scores = np.zeros((matrix.shape))\n for i, row in enumerate(matrix):\n for j, value in enumerate(row):\n att_scores[i][j] = np.exp(value)/sum(np.exp(row))\n\n return att_scores\n\n\nif __name__ == '__main__':\n Input = np.array([[1, 0], [0, 1], [1, 1], [0, 0]])\n Logits = calc_logits(Input)\n AttScores = rows_softmax(Logits)\n Result = np.dot(AttScores, Input)\n print(Result)\n","sub_path":"self_attention/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"39503958","text":"import json\nimport pandas as pd\nfrom functools import reduce\n\ndef read_json(file = 'conf_RNA_Seq.json'):\n with open(file) as json_file:\n conf = json.load(json_file)\n return conf\n\n# Load in params\ndict_conf = read_json(snakemake.params[0])\nsample_list = snakemake.params[1]\n\n# get counts\ndf_anno = pd.read_csv(dict_conf['config']['annotation_file'],index_col = 0) \ncount_tables = [pd.read_csv(f'2.Internal_files/bam_aligned/{sample}/{sample}_ReadsPerGene.out.tab',sep = '\\t',skiprows = 4,header = None).set_index(0)[[1]] for sample in sorted(sample_list)]\ndf_counts = reduce(lambda left,right: pd.merge(left,right,left_index = True, right_index = True), count_tables)\ndf_counts.columns = sorted(sample_list)\nfilter_gene_list = df_anno[df_anno[\"gene_type\"].str.contains('tRNA|rRNA')==False].index\ndf_counts_filter = df_counts.loc[filter_gene_list]\ncounts = df_counts_filter.values/df_anno['Length'].loc[df_counts_filter.index].values[:,None]\ndf_TPM = pd.DataFrame((1e6*counts)/(counts.sum(axis = 0)), index = filter_gene_list, columns=df_counts.columns)\ndf_TPM.to_csv('4.Output/counts/TPM_counts.csv')\ndf_counts.to_csv('4.Output/counts/raw_counts_unfiltered.csv')\ndf_counts_filter.to_csv('4.Output/counts/raw_counts.csv')","sub_path":"pipeline/scripts/merge_counts.py","file_name":"merge_counts.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"434102980","text":"from pwn import *\nimport sys\nfrom string import *\n\nIP = \"35.198.90.23\"\nport = 30789\n\np = remote(IP, port)\n\np.recvuntil(\"What is the value of <<\")\nnumber = p.recvuntil(\">>\")\nprint(number[:-2])\nhex_value = hex(int(number[:-2]))\nprint(f\"hex number: {hex_value}\\n\")\np.recvuntil(\"Input: \")\np.sendline(str(hex_value))\n\n\n\np.recvuntil(\"What is the value of <<\")\nstring = p.recvuntil(\">>\")[:-2]\nprint(string)\nstring_value = \"\"\nfor i in range(0, len(string), 2):\n ascii_aux = string[i:i+2]\n number = int(ascii_aux, base=16)\n char = chr(number)\n string_value = string_value + char\nprint(string_value)\np.recvuntil(\"\\n\")\np.recvuntil(\"Input:\")\np.sendline(string_value)\n\n\np.recvuntil(\"What is the value of <<\")\nanother_string = p.recvuntil(\">>\")[:-2]\nprint(another_string)\nanother_string_value = \"\"\nfor i in range(0, len(another_string), 5):\n ascii_aux = another_string[i:i+4]\n number = int(ascii_aux, base=8)\n char = chr(number)\n another_string_value = another_string_value + char\nprint(another_string_value)\np.recvuntil(\"\\n\")\np.recvuntil(\"Input:\")\np.sendline(another_string_value)\n\n\nflag = str(p.recv())\nprint(flag)\np.interactive()\n \n","sub_path":"Unbreakable_2021/base/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"434469197","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('library_app', '0009_remove_componentissue_quantity'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='component',\n name='lend_by',\n field=models.ManyToManyField(default=None, to='library_app.UserProfile'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='componentissue',\n name='quantity',\n field=models.IntegerField(default=1, max_length=100),\n preserve_default=False,\n ),\n ]\n","sub_path":"library_app/migrations/0010_auto_20160303_0524.py","file_name":"0010_auto_20160303_0524.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"277520556","text":"import shutil\nimport os\nfrom threading import Thread\nimport time\nimport datetime\nimport subprocess\n\nclass Uploader:\n def __init__(self, config):\n self.upload_thread = Thread(target=self.upload_models)\n self.upload_now = config.upload_now\n\n self.cwd = f'{os.getcwd()}/'\n self.drive_dir = self.cwd + config.drive_dir\n self.models_dir = self.cwd + 'models/'\n self.iteration_path = self.models_dir + config.iteration_path\n self.best_path = self.models_dir + config.best_path\n self.games_path = self.models_dir + config.games_path\n self.contest_games_path = self.models_dir + 'contest_games.txt'\n\n self.files_to_save = [self.iteration_path, self.best_path, self.games_path, self.contest_games_path]\n\n self.start_iter = 1\n self.num_eps = config.num_eps\n \n def wait_for_upload_complete(self):\n if self.upload_thread.is_alive():\n self.upload_thread.join()\n \n def request_upload(self, i = 0):\n if self.upload_thread.is_alive():\n print('Still uploading... Aborting this upload request...\\n')\n elif self.should_upload(i):\n print(f'Uploading model to Drive... {self.get_time()}\\n')\n self.start_upload_thread()\n\n def should_upload(self, i):\n return self.upload_now or i > self.start_iter\n\n def start_upload_thread(self):\n self.upload_thread = Thread(target=self.upload_models)\n self.upload_thread.start()\n \n def get_time_log(self):\n return f'At {self.get_time()} | Taken {self.get_time_elapsed()}s'\n \n def upload_models(self):\n self.start_time = time.time()\n\n if not os.path.exists(self.drive_dir):\n os.makedirs(self.drive_dir)\n\n for file in self.files_to_save:\n if os.path.exists(file):\n shutil.copy2(file, self.drive_dir)\n\n shutil.make_archive('models', 'zip', 'models/')\n \n print(f'Archive created!', self.get_time_log(), '\\n')\n self.start_time = time.time()\n\n shutil.copy2('models.zip', self.drive_dir)\n\n print(f'Model uploaded to Drive!', self.get_time_log(), '\\n')\n \n def get_time_elapsed(self):\n now = time.time()\n elapsed = round(now - self.start_time)\n delta = datetime.timedelta(seconds = elapsed)\n delta = str(delta).split(':', 1)[1].replace(':', 'm')\n return delta\n\n def save_iteration(self, i):\n with open(self.iteration_path, 'w+') as file:\n file.write(str(i))\n \n def add_best_log(self, text):\n with open(self.best_path, 'a+') as file:\n file.write(text)\n \n def read_iteration(self):\n if os.path.exists(self.iteration_path):\n with open(self.iteration_path, 'r') as file:\n self.start_iter = int(file.read())\n return self.start_iter\n \n def upload_best_model(self, i):\n checkpoints_folder = self.drive_dir + 'checkpoints/'\n if not os.path.exists(checkpoints_folder):\n os.makedirs(checkpoints_folder)\n shutil.copyfile('models/best_checkpoint.pt', f'{checkpoints_folder}{i}.pt')\n \n def reset_game_history(self):\n history_on_drive = self.drive_dir + 'games.txt'\n if os.path.exists(history_on_drive):\n shutil.copy2(history_on_drive, self.models_dir)\n\n def save_game(self, i, eps, moves, contest=False):\n file_path = self.contest_games_path if contest else self.games_path\n with open(file_path, 'a+') as file:\n if eps == 1:\n file.write(f'ITER :: {i}\\n')\n \n game = ' '.join([self.number_to_alphanum(m) for m in moves])\n file.write(f'EPS {eps} - {game}\\n')\n \n if eps == self.num_eps:\n file.write('\\n')\n \n def read_game(self, i, eps, contest=False):\n filepath = self.contest_games_path if contest else self.games_path\n return Uploader.read_game_from_file(filepath, i, eps, contest)\n\n @staticmethod\n def read_game_from_file(filepath, i, eps, contest=False):\n with open(filepath, 'r') as file:\n text = file.read()\n\n iter_text = f'ITER :: {i}'\n eps_text = f'EPS {eps} - '\n \n iter_pos = text.index(iter_text)\n start_pos = text.index(eps_text, iter_pos)\n end_pos = text.index('\\n', start_pos)\n\n text = text[start_pos:end_pos]\n if '-' in text:\n text = text.split('-')[1]\n \n return text","sub_path":"src/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":4521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"281067049","text":"# Copyright 2019 ZTE corporation. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nTrain a VGG_M_16 model on cifar10 dataset\n\"\"\"\nimport os\n# If you did not execute the setup.py, uncomment the following four lines\n# import sys\n# from os.path import abspath, join, dirname\n# sys.path.insert(0, join(abspath(dirname(__file__)), '../src'))\n# print(sys.path)\n\nfrom model_optimizer import prune_model # noqa: E402\n\n\ndef _main():\n base_dir = os.path.dirname(__file__)\n request = {\n \"dataset\": \"cifar10\",\n \"model_name\": \"vgg_m_16\",\n \"data_dir\": os.path.join(base_dir, \"./data/cifar10\"),\n \"batch_size\": 128,\n \"batch_size_val\": 100,\n \"learning_rate\": 0.1,\n \"epochs\": 160,\n \"checkpoint_path\": os.path.join(base_dir, \"./models_ckpt/vgg_m_16_cifar10\"),\n \"checkpoint_save_period\": 20, # save a checkpoint every epoch\n \"checkpoint_eval_path\": os.path.join(base_dir, \"./models_eval_ckpt/vgg_m_16_cifar10\"),\n \"scheduler\": \"train\"\n }\n prune_model(request)\n\n\nif __name__ == \"__main__\":\n _main()\n","sub_path":"examples/vgg_m_16_cifar10_train.py","file_name":"vgg_m_16_cifar10_train.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"406926528","text":"# coding: utf-8\r\n\r\n# In[1]:\r\n\r\n#this is simply an optimization for naive bayes\r\n#the default sklearn package is so damnnnn slow for large scale of text data\r\n#for small dataset (refer to vocabulary size less than 10000)\r\n#you can consider using the following part instead\r\n\r\n\"\"\"\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.naive_bayes import MultinomialNB\r\n\r\ndef nlp(ds_train,ds_test):\r\n \r\n ds_train['clean']=[' '.join(text2list(i,stopword,lower=True)) for i in ds_train['title']]\r\n train=CountVectorizer()\r\n train_matrix=train.fit_transform(ds_train['clean'])\r\n clf=MultinomialNB().fit(train_matrix,ds_train['spam'])\r\n \r\n ds_test['clean']=[' '.join(text2list(i,stopword,lower=True)) for i in ds_test['title']]\r\n test_matrix=CountVectorizer(vocabulary=train.vocabulary_).fit_transform(ds_test['clean'])\r\n ds_test['spam']=clf.predict(test_matrix)\r\n \r\n return ds_test[ds_test['spam']==0]\r\n\"\"\"\r\n\r\n#for large dataset, we can apply a memoization technique to improve its time complexity\r\n#for details of naive bayes, plz refer to the following link\r\n# https://github.com/je-suis-tm/machine-learning/blob/master/naive%20bayes.ipynb\r\n\r\nimport pandas as pd\r\nimport re\r\nimport os\r\nfrom nltk.tokenize import RegexpTokenizer\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import PorterStemmer\r\nfrom nltk.stem.wordnet import WordNetLemmatizer\r\nos.chdir('h:/')\r\n\r\n\r\n# In[2]:\r\n\r\n#convert text into a list of words\r\n#we use stemming and lemmatization to save space and improve efficiency\r\n#for instance, we have words walked,walking,walks\r\n#with nltk package, we can revert all of them to walk\r\ndef text2list(text,stopword,lower=True):\r\n\r\n temp=text if lower==False else text.lower()\r\n tokenizer=RegexpTokenizer(r'\\w+')\r\n temp2=[WordNetLemmatizer().lemmatize(i) for i in tokenizer.tokenize(temp)]\r\n output=[PorterStemmer().stem(i) for i in temp2 if i not in stopword]\r\n \r\n #remove numbers as they are stopword as well\r\n for i in output:\r\n try:\r\n float(i)\r\n output.remove(i)\r\n except:\r\n pass\r\n \r\n return output\r\n\r\n\r\n# In[3]:\r\n\r\n#build up vocabulary for all words in our training data\r\ndef get_vocabulary(output,stopword):\r\n \r\n vocabulary=sorted(list(set(output)))\r\n \r\n for i in vocabulary:\r\n if i in stopword:\r\n vocabulary.remove(i)\r\n \r\n return vocabulary\r\n\r\n\r\n# In[4]:\r\n\r\n#calculate conditional probability with laplace smoothing\r\ndef multivariate_calc_prob(word,x_train,y_train,classification):\r\n \r\n\r\n num=list(y_train).count(classification)\r\n \r\n temp=[i.count(word) for i in x_train[y_train==classification]]\r\n freq=len(temp)-temp.count(0)\r\n \r\n if freq!=0:\r\n p=freq/num\r\n \r\n else:\r\n p=(freq+1)/(num+2)\r\n\r\n return p\r\n\r\n\r\n#memoization\r\n#calculate every conditional probability in our training dataset\r\n#and store these probabilities in a local folder\r\n#so everytime we wanna make forecast\r\n#we do not need to caculate these probabilities again\r\ndef multivariate_store_prob(sample,stopword):\r\n \r\n temp=[]\r\n for i in sample['title']:\r\n temp.append(text2list(i,lower=True))\r\n\r\n sample['word']=temp\r\n \r\n phi_y0=list(sample['key']).count(0)/len(sample)\r\n phi_y1=1-phi_y0\r\n \r\n df=pd.DataFrame()\r\n \r\n df['entire training sample']=[phi_y0,phi_y1]\r\n \r\n for i in sample['word']:\r\n for j in i:\r\n if j not in stopword:\r\n px_y0=multivariate_calc_prob(j, \r\n sample['word'], \r\n sample['key'],0)\r\n px_y1=multivariate_calc_prob(j, \r\n sample['word'], \r\n sample['key'],1)\r\n \r\n df[j]=[px_y0,px_y1]\r\n else:\r\n pass\r\n\r\n return df\r\n\r\n\r\n#when we make forecast on several words\r\n#we intend to find the conditional probability in our local file first\r\n#if it doesnt exist, we would get a keyerror\r\n#we just ignore it and take 1/2 as the laplace smoothed probability\r\n#we create a new column in dataframe to store the forecast\r\ndef multivariate_forecast(df,dic,stopword):\r\n \r\n temp=[]\r\n for i in df['title']:\r\n temp.append(text2list(i,lower=True))\r\n\r\n df['word']=temp\r\n forecast=[]\r\n \r\n phi_y0=dic['entire training sample'][0]\r\n phi_y1=dic['entire training sample'][1]\r\n\r\n \r\n for j in df['word']:\r\n px_y0,px_y1=1,1\r\n\r\n for k in j:\r\n if k not in stopword:\r\n try:\r\n px_y0*=dic[k][0]\r\n px_y1*=dic[k][1]\r\n except KeyError:\r\n px_y0*=1/2\r\n px_y1*=1/2\r\n else:\r\n pass\r\n \r\n \r\n py0_x=px_y0*phi_y0\r\n py1_x=px_y1*phi_y1\r\n\r\n p=0 if py0_x>py1_x else 1\r\n forecast.append(p)\r\n \r\n df['forecast']=forecast\r\n \r\n return df\r\n\r\n\r\n# In[5]:\r\n\r\n#this is the stopword i have thought of\r\n#anything i am missing?\r\nstopword=stopwords.words('english')+['u',\r\n 'beyond',\r\n 'within',\r\n 'around',\r\n 'would',\r\n 'b',\r\n 'c',\r\n 'e',\r\n 'f',\r\n 'g',\r\n 'h',\r\n 'j',\r\n 'k',\r\n 'l',\r\n 'n',\r\n 'p',\r\n 'q',\r\n 'r',\r\n 'u',\r\n 'v',\r\n 'w',\r\n 'x',\r\n 'z',\r\n 'first']\r\n\r\n\r\n#when this file is run as a main\r\n#we could add some new training datasets into our csv file first\r\n#it would automatically update our vocabulary and conditional probabilities\r\n#next time we import this file\r\n#we would get more accurate forecast\r\ndef main():\r\n \r\n #i use latin-1 cuz utf_8_sig cannot encode some characters\r\n #some punctuations could turn out to be a mess\r\n #as we only care about words and we have regex to fix it\r\n #we do not need to worry too much about it\r\n #and dic is shorter form for dictionary:P\r\n df=pd.read_csv('training dataset.csv',encoding='latin-1')\r\n dic=multivariate_store_prob(df,stopword)\r\n dic.to_csv('local data.csv',index=False)\r\n \r\n \r\n #this is how we use this file to forecast\r\n \r\n \"\"\"\r\n df=pd.read_csv('testing data.csv',encoding='latin-1')\r\n new=name_of_this_script.multivariate_forecast(df,dic,name_of_this_script.stopword)\r\n new.to_csv('testing data.csv',encoding='utf_8_sig')\r\n \"\"\"\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n","sub_path":"optimized naive bayes with memoization.py","file_name":"optimized naive bayes with memoization.py","file_ext":"py","file_size_in_byte":6598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"125969995","text":"from googletrans import Translator\nfrom pyperclip import paste\nfrom threading import Thread\nfrom time import sleep\nfrom tkinter import Tk, Frame, Text, Scrollbar, END, INSERT, RIGHT, VERTICAL, Y, PhotoImage\n\ndef display(content):\n text.config(state='normal')\n text.delete(1.0, END)\n text.insert(INSERT, content)\n text.config(state='disabled')\n\ndef translate():\n translator = Translator(service_urls=['translate.google.cn'])\n data_old = paste()\n while True:\n data = paste()\n if data != data_old:\n try:\n result = translator.translate(data, src='en', dest='zh-CN').text\n display(result)\n data_old = data\n except Exception as error:\n display(error)\n sleep(0.5)\n\nif __name__ == '__main__':\n\n root = Tk()\n root.title('cliptrans')\n root.geometry('300x100')\n root.resizable(0, 0)\n root.iconbitmap('.\\\\icon.ico')\n root.attributes('-topmost', True)\n frame = Frame(root)\n scrollbar = Scrollbar(frame, orient=VERTICAL)\n text = Text(\n frame,\n state='disable',\n font=('宋体', 12,),\n yscrollcommand=scrollbar.set\n )\n scrollbar.pack(side=RIGHT, fill=Y)\n scrollbar.config(command=text.yview)\n text.pack()\n frame.pack(expand=True, fill='both')\n\n thread = Thread(target=translate)\n thread.daemon = True\n thread.start()\n\n root.mainloop()\n","sub_path":"old_version/cliptrans_v0.0.1.py","file_name":"cliptrans_v0.0.1.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"101717747","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.14-x86_64/egg/a3cosmos_gas_evolution/Common_Python_Code/calc_galaxy_gas_mass_function.py\n# Compiled at: 2019-07-18 22:30:15\n# Size of source mod 2**32: 3687 bytes\nfrom __future__ import print_function\nimport os, sys, re, json, time, astropy, numpy as np\nfrom astropy.table import Table, Column, hstack\nfrom copy import copy\nfrom numpy import log, log10, power, sum, sqrt, pi, exp\npow = power\nlg = log10\nln = log\nfrom scipy.interpolate import InterpolatedUnivariateSpline, interp1d\nif os.path.dirname(os.path.abspath(__file__)) not in sys.path:\n sys.path.append(os.path.dirname(os.path.abspath(__file__)))\nimport apply_cosmology\ncosmo = apply_cosmology.cosmo\nif sys.version_info.major >= 3:\n long = int\nelse:\n\n def Schechter_Function(lgM, phi, lg_M0, alpha):\n lgx = lgM - lg_M0\n Phi_Schechter = phi * 10 ** (lgx * (alpha + 1)) * np.exp(-10 ** lgx) * ln(10)\n return Phi_Schechter\n\n\n def calc_CO10_LF_Saintonge2017(lgMgas=None, input_type=1):\n if lgMgas is None:\n lgMgas_grid = np.linspace(6.0, 13.0, num=1000, endpoint=True)\n else:\n lgMgas_grid = lgMgas\n tb = Table.read((os.path.dirname(os.path.dirname(__file__)) + os.sep + 'Data_Tables/datatables_GMF/datatable_Saintonge2017_CO10_LF_%s.txt' % input_type), format='ascii')\n GMF_zmin = np.min(tb['zLo'])\n GMF_zmax = np.max(tb['zHi'])\n GMF_lgMchar = tb['lgLchar'][0]\n GMF_phi_1 = tb['Phi_1'][0]\n GMF_alpha_1 = tb['alpha_1'][0]\n GMF_Phi_L_Prime_CO10 = Schechter_Function(lgMgas_grid, GMF_phi_1, GMF_lgMchar, GMF_alpha_1)\n lgPhiMgas_grid = np.log10(GMF_Phi_L_Prime_CO10)\n lgPhiMgas_grid[np.isnan(lgPhiMgas_grid)] = -100\n lgPhiMgas_grid[lgPhiMgas_grid < -100] = -100\n if lgMgas is None:\n return (\n lgMgas_grid, lgPhiMgas_grid)\n return lgPhiMgas_grid\n\n\n def calc_CO10_LF_Saintonge2017_updated(lgMgas=None, input_type=1):\n if lgMgas is None:\n lgMgas_grid = np.linspace(6.0, 13.0, num=1000, endpoint=True)\n else:\n lgMgas_grid = lgMgas\n tb = Table.read((os.path.dirname(os.path.dirname(__file__)) + os.sep + 'Data_Tables/datatables_GMF/datatable_Saintonge2017_CO10_LF_%s_updated.txt' % input_type), format='ascii')\n GMF_zmin = np.min(tb['zLo'])\n GMF_zmax = np.max(tb['zHi'])\n GMF_lgMchar = tb['lgLchar'][0]\n GMF_phi_1 = tb['Phi_1'][0]\n GMF_alpha_1 = tb['alpha_1'][0]\n GMF_Phi_L_Prime_CO10 = Schechter_Function(lgMgas_grid, GMF_phi_1, GMF_lgMchar, GMF_alpha_1)\n lgPhiMgas_grid = np.log10(GMF_Phi_L_Prime_CO10)\n lgPhiMgas_grid[np.isnan(lgPhiMgas_grid)] = -100\n lgPhiMgas_grid[lgPhiMgas_grid < -100] = -100\n if lgMgas is None:\n return (\n lgMgas_grid, lgPhiMgas_grid)\n return lgPhiMgas_grid","sub_path":"pycfiles/a3cosmos_gas_evolution-1.0.0-py3.7/calc_galaxy_gas_mass_function.cpython-37.py","file_name":"calc_galaxy_gas_mass_function.cpython-37.py","file_ext":"py","file_size_in_byte":3029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"265093730","text":"\"\"\"Lab 3\"\"\"\n\nfrom mrjob.job import MRJob\nimport re\nimport time\nimport datetime\nimport statistics\n\nclass Lab3(MRJob):\n\n# this class will define two additional methods: the mapper method goes here\n def mapper(self, _, line):\n fields = line.split(\";\")\n try:\n if (len(fields)==4):\n #tweetLength = len(fields[2])\n tweetHash = fields[2].count('#')\n yield(\"Hash\",tweetHash)\n except:\n pass\n #no need to do anything\n\n def combiner(self,lengthString,tweetLength,):\n tweetLengthCount = sum(tweetLength)\n yield (lengthString,tweetLengthCount)\n\n\n#and the reducer method goes after this line\n def reducer(self,lengthString,tweetLength):\n lenghtSum = sum(tweetLength)\n average = lenghtSum/25568614.0\n yield(\"Length\",average)\n\nif __name__ == '__main__':\n #Lab3.JOBCONF= { 'mapreduce.job.reduces': '5' }\n Lab3.run()\n","sub_path":"BigDataProcessing/lab3/tweetlenght.py","file_name":"tweetlenght.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"7023108","text":"\"\"\"\nThis is the tutorial from Mesa: a simple agent-based economic model with the\nfollowing rules:\n\n 1. There are some number of agents.\n 2. All agents begin with 1 unit of money\n 3. At every step of the model, an agent gives 1 unit of money (if they have\n it) to some other agent.\n\n\"\"\"\n\nfrom mesa import Agent, Model\nfrom mesa.time import RandomActivation\nimport random\nfrom mesa.datacollection import DataCollector\nfrom mesa.batchrunner import BatchRunner\nfrom mesa.space import MultiGrid\nimport matplotlib.pyplot as plt\n\n\ndef compute_gini(model):\n \"\"\"\n Collects Gini Coefficient, a measure of wealth inequality, to be measured\n at every step of the model\n\n \"\"\"\n agent_wealths = [agent.wealth for agent in model.schedule.agents]\n x = sorted(agent_wealths)\n N = model.num_agents\n B = sum(xi * (N-i) for i, xi in enumerate(x)) / (N*sum(x))\n return 1 + (1/N) - 2*B\n\n\nclass MoneyAgent(Agent):\n \"\"\"\n Creates the agents - individuals with fixed initial wealth,\n includes unique identifier\n\n \"\"\"\n def __init__(self, unique_id, model):\n super().__init__(unique_id, model)\n self.wealth = 1 # Starting wealth of the agent is 1\n\n def move(self):\n \"\"\"\n Defines the space that the agents inhabit, in this case a grid, and the\n movement of agents to a neighboring cell\n\n \"\"\"\n possible_steps = self.model.grid.get_neighborhood(\n self.pos,\n moore=True,\n # Moore cell neighborhood means agents can move to diagonal cells\n # vs. Von-Neumann\n include_center=False) # Center cell is not considered a neighboring cell\n new_position = random.choice(possible_steps)\n self.model.grid.move_agent(self, new_position)\n\n def give_money(self):\n \"\"\" Finds all the agents present in a cell and gives one some money \"\"\"\n cellmates = self.model.grid.get_cell_list_contents([self.pos])\n if len(cellmates) > 1: # if there is more than one cellmate\n other = random.choice(cellmates)\n # defines the 'other' random agent that will receive money\n other.wealth += 1 # other agent gets +1 money\n self.wealth -= 1 # original agent -1 money\n\n def step(self):\n \"\"\"\n The step(s) the agent takes, if the agent has money (>0), calls the\n give_money method\n\n \"\"\"\n self.move()\n if self.wealth > 0:\n self.give_money()\n\n\nclass MoneyModel(Model):\n \"\"\" A model with some number of agents. \"\"\"\n def __init__(self, N, width, height):\n self.num_agents = N # Number of agents\n self.grid = MultiGrid(width, height, True)\n # Multiple agents allowed per grid, set dimensions\n self.schedule = RandomActivation(self)\n # Activates all agents once per step, in random order\n self.running = True\n\n for i in range(self.num_agents): # Create agents\n a = MoneyAgent(i, self)\n self.schedule.add(a) # Add the agent to a random grid cell\n x = random.randrange(self.grid.width)\n y = random.randrange(self.grid.height)\n self.grid.place_agent(a, (x, y))\n # Places agent at a given set of coordinates (x, y)\n\n self.datacollector = DataCollector(\n model_reporters={\"Gini\": compute_gini},\n agent_reporters={\"Wealth\": lambda a: a.wealth})\n\n def step(self):\n self.datacollector.collect(self) # Collect data at each step\n self.schedule.step()\n\n\n\"\"\"\nSet up and run the BatchRunner, which runs the model multiple times with fixed\nparameters to determine the overall distributions of the model - automated by Mesa\n\n\"\"\"\nparameters = {\"width\": 10, # Width of the cell\n \"height\": 10, # Height of the cell\n \"N\": range(10, 500, 10)} # Vary # of agents from 10 to 500 in units of 10\n\nbatch_run = BatchRunner(MoneyModel,\n parameters,\n iterations=5,\n # 5 instantiations of the model with each number of agents\n max_steps=100, # Run each for 100 steps\n model_reporters={\"Gini\": compute_gini}) # Collect Gini value\n\nbatch_run.run_all()\n\n\n# Data collection methods\n# Extract data as a DataFrame\nrun_data = batch_run.get_model_vars_dataframe()\nrun_data.head()\nplt.scatter(run_data.N, run_data.Gini)\n","sub_path":"MoneyModel.py","file_name":"MoneyModel.py","file_ext":"py","file_size_in_byte":4426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"72895889","text":"def foo_1(n):\n n += 1\n return n\n\ndef foo_2(n):\n if n>=5: return True\n else: return False\n\nlist_1 = range(10)\n\n\ndef my_map(my_list, foo):\n ''' allows you to apply a given function to all elements of the list '''\n new_list = []\n for i in range(len(my_list)):\n try:\n new_list.append(foo(my_list[i]))\n except: return None\n return new_list\n#TEST\n#print(my_map(list_1, foo_1))\n\ndef my_filter(my_list, foo):\n ''' Allows you to filter values ​​from a list using specified function \"foo\".\n Returns a list which contains only those values ​​\n for which the function \"foo\" returned \"True\"\n '''\n new_list = []\n for i in range(len(my_list)):\n try:\n if foo(my_list[i]):\n new_list.append(my_list[i])\n else: continue\n except: return None\n return new_list\n#TEST\n#print(my_filter(list_1, foo_2))\n \n","sub_path":"3rd_week/3_5_map&filter.py","file_name":"3_5_map&filter.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"628151589","text":"import unittest\nfrom DiGraph import DiGraph\n\n\n# graph creator of 10 nodes 12 edges.\ndef graph_creator():\n g = DiGraph()\n for i in range(10):\n g.add_node(i)\n g.add_edge(0, 1, 1)\n g.add_edge(0, 8, 2)\n g.add_edge(9, 0, 1)\n g.add_edge(1, 5, 2.5)\n g.add_edge(1, 4, 3)\n g.add_edge(4, 3, 1)\n g.add_edge(2, 4, 1.5)\n g.add_edge(3, 2, 0.5)\n g.add_edge(7, 6, 1)\n g.add_edge(6, 7, 1)\n g.add_edge(5, 7, 4)\n g.add_edge(8, 5, 3)\n return g\n\n\nclass TestDiGraph(unittest.TestCase):\n\n def test_v_size(self):\n g = graph_creator()\n v = g.v_size()\n self.assertEqual(10, v)\n\n def test_e_size(self):\n g = graph_creator()\n self.assertEqual(12, g.e_size())\n\n def test_get_all_v(self):\n g = graph_creator()\n v = g.get_all_v()\n self.assertEqual(10, v.__len__())\n\n def test_all_in_edges_of_node(self):\n g = graph_creator()\n v = g.all_in_edges_of_node(4)\n self.assertEqual(2, v.__len__())\n\n def test_all_out_edges_of_node(self):\n g = graph_creator()\n v = g.all_out_edges_of_node(4)\n self.assertEqual(1, v.__len__())\n\n def test_add_edge(self):\n g = graph_creator()\n g.add_edge(1, 2, 3.2) # add new edge\n g.add_edge(5, 5, 1) # edge to itself SHOULD NOT add\n g.add_edge(8, 5, 1) # exist edge\n self.assertEqual(13, g.e_size())\n\n def test_add_node(self):\n g = graph_creator()\n g.add_node(5) # exist node\n g.add_node(10)\n g.add_node(12) # add twice the same node\n g.add_node(12)\n self.assertEqual(12, g.v_size())\n\n def test_remove_node(self):\n g = graph_creator()\n g.remove_node(7)\n g.remove_node(7)\n g.remove_node(20)\n self.assertEqual(9, g.v_size())\n self.assertEqual(9, g.e_size())\n\n def test_remove_edge(self):\n g = graph_creator()\n g.remove_edge(0, 1)\n g.remove_edge(0, 1)\n g.remove_edge(0, 0)\n g.remove_edge(0, 8)\n g.remove_edge(7, 6)\n self.assertEqual(9, g.e_size())\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/TestDiGraph.py","file_name":"TestDiGraph.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"391779039","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 31 19:27:25 2019\r\n\r\n@author: Mateusz\r\n\"\"\"\r\n\r\nfrom flask import Flask, request, jsonify\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom flask_marshmallow import Marshmallow\r\nimport os\r\n\r\n#init app\r\napp = Flask(__name__)\r\nbasedir = os.path.abspath(os.path.dirname(__file__))\r\n\r\n#Database\r\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite') \r\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\r\n\r\n#Initialize DB\r\ndb = SQLAlchemy(app)\r\n\r\nma = Marshmallow(app)\r\n\r\nclass APIData(db.Model):\r\n idx = db.Column(db.Integer, primary_key=True)\r\n name = db.Column(db.String)\r\n value = db.Column(db.Float)\r\n \r\n def __init__(self, name, value):\r\n self.name = name\r\n self.value = value\r\n\r\nclass DataShow(ma.Schema):\r\n class Meta:\r\n fields = ('idx', 'name', 'value')\r\n \r\ndata_show = DataShow()\r\ndata_show_all = DataShow(many = True)\r\n\r\n@app.route('/', methods = ['GET'])\r\ndef home():\r\n return jsonify({'msg': 'Hello World!'})\r\n \r\n@app.route('/data', methods = ['POST'])\r\ndef add_value():\r\n name = request.json['name']\r\n value = request.json['value']\r\n \r\n new_data = APIData(name, value)\r\n db.session.add(new_data)\r\n db.session.commit()\r\n return data_show.jsonify(new_data)\r\n\r\n@app.route('/data', methods = ['GET'])\r\ndef get_all_data():\r\n data = APIData.query.all()\r\n result = data_show_all.dump(data)\r\n return jsonify(result)\r\n\r\n@app.route('/data/', methods = ['GET'])\r\ndef get_data(idx):\r\n data = APIData.query.get(idx)\r\n return data_show.jsonify(data)\r\n\r\n@app.route('/data/', methods = ['PUT'])\r\ndef update_value(idx):\r\n data = APIData.query.get(idx)\r\n name = request.json['name']\r\n value = request.json['value']\r\n \r\n data.name = name\r\n data.value = value\r\n \r\n db.session.commit()\r\n return data_show.jsonify(data)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n \r\n ","sub_path":"AGH_API.py","file_name":"AGH_API.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543017369","text":"import pandas as pd\nimport numpy as np\nfrom dtwpy.distance_measure import distancefunc\nfrom dtwpy import dtwpy\nimport matplotlib.pyplot as plt\n\n\n\ndata1 = pd.read_csv('Output1.txt', sep = \" \", names=[\"Time\", \"Intensity\"])\nd11 = data1.iloc[6994:12433]\n\nx,y = d11.astype(float).values[:,0]*60,d11.astype(float).values[:,1]\n\nxvals = np.arange(0,max(x),1)\nyinterp = np.interp(xvals,x,y)\n\nd1 = yinterp\n\n\n\n\ndata2 = np.load('Output2.npy')\nd21 = data2[2]\nd2 = d21.mean(1)\n\n\n\nplt.figure(1)\nplt.plot(d1)\n\nplt.figure(2)\nplt.plot(d2)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"CFEL/Unshifted_UV_and_X-Ray_plots.py","file_name":"Unshifted_UV_and_X-Ray_plots.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"564144012","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Job specialization\n# Natalia Vélez, July 2021\n\nimport pymongo\nimport numpy as np\nimport pandas as pd\nfrom scipy.spatial import distance\nfrom tqdm import notebook\n\n\nimport sys\nsys.path.append('..')\nfrom utils import str_extract\n\n# Load avatar_embeddings:\ninput_df = pd.read_json('outputs/original_input_data_merged.json', orient='records')\ninput_df = input_df[['avatar', 'family', 'vec']]\ninput_df = input_df.set_index('avatar')\n\nprint('Input data:')\nprint(input_df.shape)\nprint(input_df.head())\n\n\n# Load contemporaries:\nprint('Contemporaries:')\ncontemporaries = pd.read_json('outputs/original_contemporaries.json', orient='records')\ncontemporaries = contemporaries[['family', 'epoch', 'contemporaries', 'pop_size']]\nprint(contemporaries.shape)\nprint(contemporaries.head())\n\n\n# ## Measuring specialization\n# \n# We measured specialization using the Herfindahl–Hirschman Index (HHI), a widely-used measure of absolute diversity (Hannah & Kay, 1977; Palan, 2010). HHI is typically calculated by squaring the market share of each competing firm in an industry ($s_i$) and summing the squares; higher HHI indicate more concentrated industries.\n# \n# $$\n# H = \\sum_{i=1}^{N} s_i^2\n# $$\n# \n# Where N is the total number of firms.\n# \n# In order to adapt this index to our dataset, start with an M x N matrix X, which contains the jobspace embeddings of $M$ agents across $N$ abstract \"jobs\" in jobspace. We then summed within each column to obtain a 1 x N vector of the community's total jobspace embeddings, $x_{tot}$ The magnitude of the embeddings $|x_{tot}|$ measures of how well the algorithm can assign each community to the latent dimensions. We normalized this embedding vector by dividing each element by the sum of the vector:\n# \n# $$\n# S = X/\\sum_{i=1}^{N} x_i\n# $$\n# \n# We used these normalized embedding vectors to compute $H$. $H$ is bounded between $1/N$ (indicating total equality) and 1 (indicating total concentration). We then computed a normalized HHI, $H^*$, which bounded between 0 and 1:\n# \n# $$\n# H^* = \\frac{(H - 1/N)}{1 - 1/N}\n# $$\n# \n# Intuitively, a community with H = 0 distributes its activity across all jobs, and a community with H = 1 concentrates all of its activity onto a single job.\n\n# In[54]:\n\n\nspec_list = []\nfor _, row in contemporaries.iterrows():\n\n # load all contempories' jobspace embedddings\n embeddings = input_df.loc[row.contemporaries]\n embed_list = embeddings.vec.values.tolist() # hacky workaround to put everything in a matrix\n embed_mtx = np.array(embed_list)\n\n # aggregate activity across all avatars\n tot_embed = embed_mtx.sum(axis=0) \n tot_share = tot_embed/tot_embed.sum() # convert total activity to a share of total\n\n # compute HHI\n n_jobs = len(tot_share)\n hhi = np.sum(np.square(tot_share))\n hhi_norm = (hhi - 1/n_jobs)/(1 - 1/n_jobs)\n\n spec_list.append((row.family, row.epoch, hhi_norm))\n\n\n# Save to dataframe:\nprint('Specialization:')\nspec_df = pd.DataFrame(spec_list, columns=['family', 'epoch', 'hhi'])\nprint(spec_df.shape)\nprint(spec_df.head())\n\n# Merge with demographic info\ndiversity_df = contemporaries.merge(spec_df)\n\n# ## Control: Diversity with random job embeddings\n\n# Load randomized job matrix from database:\n#Connection string\ncreds = open('../0_database/credentials.key', 'r').read().splitlines()\nmyclient = pymongo.MongoClient('134.76.24.75', username=creds[0], password=creds[1], authSource='ohol') \nohol = myclient.ohol\nohol.list_collection_names()\n\n\n# Add demographic information:\nfamilies = input_df.copy().reset_index().drop(columns=['vec']) # Family labels\n\n# Pull embeddings from database\nrandom_embed_list = list(ohol.random_avatar_embeddings.find({}, {'_id': None}))\nrandom_embed = pd.DataFrame(random_embed_list)\nrandom_embed = families.merge(random_embed)\nrandom_embed = random_embed.set_index('avatar')\n\n# Compute specialization metrics\nprint(random_embed.shape)\nrandom_embed.head()\n\n\n# Compute family-wide measures of specialization:\nrandom_diversity = []\n\nrandom_list = []\nfor _, row in contemporaries.iterrows():\n\n # load all contempories' jobspace embedddings\n embeddings = random_embed.loc[row.contemporaries]\n embed_list = random_embed.vec.values.tolist() # hacky workaround to put everything in a matrix\n embed_mtx = np.array(embed_list)\n\n # aggregate activity across all avatars\n tot_embed = embed_mtx.sum(axis=0) \n tot_share = tot_embed/tot_embed.sum() # convert total activity to a share of total\n\n # compute HHI\n n_jobs = len(tot_share)\n hhi = np.sum(np.square(tot_share))\n hhi_norm = (hhi - 1/n_jobs)/(1 - 1/n_jobs)\n\n random_list.append((row.family, row.epoch, hhi_norm))\n\n\n# Merge with real diversity measures:\nrandom_df = pd.DataFrame(random_list, columns=['family', 'epoch', 'hhi_random'])\n\nout_df = diversity_df.merge(random_df)\nprint(diversity_df.shape)\nprint(random_df.shape)\nprint(out_df.shape)\nout_df.head()\n\n# Save locally:\nout_df.to_json('outputs/original_specialization.json', orient='records')\nout_df.head()\n\n\n# Save to database:\nmerged_records = out_df.to_dict('records')\nmerged_col = ohol.specialization\nmerged_col.drop()\nmerged_col.insert_many(merged_records)\n\n\n","sub_path":"6_regression/6_2_specialization.py","file_name":"6_2_specialization.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"46736475","text":"#pdb is for debugging dont need it right now.\nimport pdb\n\n\n\n# using readlines() reads in text as a list line by line and read() reads in full text as text.\nreadMe = open('file.txt','r').readlines()\n\npdb.set_trace()\n\n#open a file to write to\nsaveFile =open('test.txt','w')\n\n\n\n\n# this loops thru you text readme by lines\n# you can set a default value to be inputted with (=)\n\ndef findWord(value=\"words\"):\n # this is your counter variable starting at 0\n counter = 0\n for string in readMe:\n #this splits up lines by words\n string = string.split()\n\n # this loops thru each word in the line\n for word in string:\n\n # this checks for matching line word and user input\n if word == value:\n \n #count adds if word matches\n counter += 1\n \n # prints the results and used find as the looked for word. must concatenate the intiger counter to add\n # to the string because its a number by using str(counter).\n print(\"this is how many times \"+value+\" and appear in this text \"+ str(counter))\n\n return \"this is how many times \"+value+\" and appear in this text \"+ str(counter)\n readMe.close()\n\n\n#a function that doesnt have input\ndef greetings():\n print('hi there')\n\n\n\n\n \n\nfirst = 'what'\nsecond = 'story'\n\n# this is calling our functions and passing in what to be looked for.\nx = findWord(first)\ny = findWord(second)\nz = findWord()\n\n#using the file variable and .write lets you write to the file\n# \\n is use to start a newline\nsaveFile.write(x+\" \\n \")\nsaveFile.write(y+\"\\n \")\nsaveFile.write(z+'\\n')\n\na = \"dog\"\nb = \"cat\"\n\n\n# use %s for string formatting.\n# like then following.\nsaveFile.write(\"I hate %s but really like %s's\" % (a,b))\n\n#calling our function\ngreetings()\n\n\n\n#close your door\nsaveFile.close()\n\n\n\n\n\n\n\n\n","sub_path":"pythonTools/python/6_12_18/csvTest.py","file_name":"csvTest.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"240521175","text":"import os\nimport time\nfrom selenium import webdriver\nfrom apscheduler.schedulers.blocking import BlockingScheduler\n\nsched = BlockingScheduler()\n\nop = webdriver.ChromeOptions()\nop.binary_location = os.environ.get(\"GOOGLE_CHROME_BIN\")\nop.add_argument(\"--headless\")\nop.add_argument(\"--no-sandbox\")\nop.add_argument(\"--disable-dev-sh-usage\")\n\ndriver = webdriver.Chrome(executable_path=os.environ.get(\"CHROMEDRIVER_PATH\"), chrome_options=op)\n\n# driver = webdriver.Chrome(executable_path='C:/chromedriver', chrome_options=op) local\ncounter = 0\n\n\n@sched.scheduled_job('interval', minutes=5)\ndef timed_job():\n global counter\n driver.get(\"https://www.tiktok.com/@mano.five/video/7021547372081663238?is_from_webapp=v1&is_copy_url=0&sender_device=pc&sender_web_id=7010683830760146437\")\n print(\"mano\")\n counter = counter + 1\n print(counter)\n\n\nsched.start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"246235067","text":"\n# imports\nimport tensorflow as tf\n\n###### MODEL DEVELOPMENT BELOW THIS LINE\n\nNUM_CLASSES = 2 # binary classification problem\nNUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 12800\nNUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 3200\n\nf.app.flags.DEFINE_integer('batch_size', 128,\n \"\"\"Number of examples to process in a batch.\"\"\")\n\n# Constants describing the training process.\nMOVING_AVERAGE_DECAY = 0.9999 # The decay to use for the moving average.\nNUM_EPOCHS_PER_DECAY = 350.0 # Epochs after which learning rate decays.\nLEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.\nINITIAL_LEARNING_RATE = 0.1 # Initial learning rate.\n\n\ndef _variable_on_gpu(name, shape, initializer):\n \"\"\" Helper function to create a GPU-stored Variable\n \n Args:\n name: name of variable\n shape: list of ints\n initializer: initializer for Variable\n\n Returns:\n Variable Tensor\n \"\"\"\n with tf.device('/gpu:0'):\n dtype = tf.float32\n var = tf.get_variable(name, shape, initializer=initializer,\n dtype=dtype)\n return var\n\n\ndef _variable_with_weight_decay(name, shape, stddev, wd):\n \"\"\"\n Helper function to create an initialized Variable, with \n weight decay during training.\n \n Initialization is with truncated normal distribution as in\n He et al, 2015. \n \n Args:\n name: name of variable\n shape: list of ints\n stddev: standard deviation of a truncated Gaussian\n wd: add L2Loss weight decay multiplied by this float. \n if wd is None, then no weight decay is added.\n \"\"\"\n \n dtype = tf.float32\n var = _variable_on_gpu(name, shape, \n tf.truncated_normal_initializer(stddev=stddev,\n dtype=dtype))\n if wd:\n weight_decay = tf.mul(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n\ndef build_model(data):\n \"\"\"\n Build a CNN using TF\n \"\"\"\n \n keep_prob = tf.placeholder(tf.float32)\n num_filters_1 = 45\n num_filters_2 = 50\n num_filters_3 = 50\n \n with tf.variable_scope('first_conv') as scope:\n kernel = _variable_with_weight_decay('weights',\n shape=[4, 8, 1, num_filters_1],\n stddev=5e-2,\n wd=0.0)\n conv = tf.nn.conv2d(data, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_gpu('biases', [num_filters_1], tf.constant_initializer(0.0))\n bias = tf.nn.bias_add(conv, biases)\n conv1 = tf.nn.relu(bias)\n conv1_drop = tf.nn.dropout(conv1, keep_prob, name=scope.name)\n \n with tf.variable_scope('second_conv') as scope:\n kernel = _variable_with_weight_decay('weights', \n shape=[1, 8, 1, num_filters_2],\n stddev=5e-2,\n wd=0.0)\n conv = tf.nn.conv2d(data, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_gpu('biases', [num_filters_2], tf.constant_initializer(0.0))\n bias = tf.nn.bias_add(conv, biases)\n conv2 = tf.nn.relu(bias)\n conv2_drop = tf.nn.dropout(conv2, keep_prob, name=scope.name)\n \n with tf.variable_scope('third_conv') as scope:\n kernel = _variable_with_weight_decay('weights', \n shape=[1, 8, 1, num_filters_3],\n stddev=5e-2,\n wd=0.0)\n conv = tf.nn.confv2d(data, kernel, [1,1,1,1], padding='SAME')\n biases = _variable_on_gpu('biases', [num_filters_3], tf.constant_initializer(0.0))\n bias = tf.nn.bias_add(conv, biases)\n conv3 = tf.nn.relu(bias)\n conv3_drop = tf.nn.dropout(conv3, keep_prob, name=scope.name)\n \n with tf.variable_scope('max_pool') as scope:\n maxpool = tf.nn.max_pool(conv3_drop, ksize=[1, 25, 1, 1],\n strides=[1, 2, 2, 1], padding='SAME', name=scope.name)\n \n with tf.variable_scope('fc_layer') as scope:\n flattened = tf.flatten(maxplool, [-1])\n print('FC LAYER SHAPE', flattened.get_shape().value)\n dim = flattened.get_shape()[0].value\n weights = _variable_with_weight_decay('weights', shape=[dim, NUM_CLASSES],\n stddev=0.04, wd=0.004)\n biases = _variable_on_gpu('biases', [NUM_CLASSES], tf.constant_initializer(0.0))\n sigmoid_result = tf.nn.sigmoid(tf.matmul(maxpool, weights) + biases, name=scope.name)\n \n return sigmoid_result\n\ndef loss(model, targets):\n \"\"\"\n Compute L2 Loss and add to variables\n \"\"\"\n\n targets = tf.cast(targets, tf.float64)\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n model, targets, name='cross_entropy_per_example')\n cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')\n tf.add_to_collection('losses', cross_entropy_mean)\n return tf.add_n(tf.get_collection('losses'), name='total_loss')\n\ndef _add_loss_summaries(total_loss):\n \"\"\"Add summaries for losses in CIFAR-10 model.\n Generates moving average for all losses and associated summaries for\n visualizing the performance of the network.\n Args:\n total_loss: Total loss from loss().\n Returns:\n loss_averages_op: op for generating moving averages of losses.\n \"\"\"\n # Compute the moving average of all individual losses and the total loss.\n loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')\n losses = tf.get_collection('losses')\n loss_averages_op = loss_averages.apply(losses + [total_loss])\n\n # Attach a scalar summary to all individual losses and the total loss; do the\n # same for the averaged version of the losses.\n for l in losses + [total_loss]:\n # Name each loss as '(raw)' and name the moving average version of the loss\n # as the original loss name.\n tf.scalar_summary(l.op.name +' (raw)', l)\n tf.scalar_summary(l.op.name, loss_averages.average(l))\n\n return loss_averages_op\n\ndef train(total_loss, global_step):\n \"\"\"\n Train model\n \"\"\"\n\n num_batches = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / FLAGS.batch_size\n decay_steps = int(num_batches_per_epoch * NUM_EPOCHS_PER_DECAY)\n \n # Decay the learning rate exponentially based on the number of steps.\n lr = tf.train.exponential_decay(INITIAL_LEARNING_RATE,\n global_step,\n decay_steps,\n LEARNING_RATE_DECAY_FACTOR,\n staircase=True)\n tf.scalar_summary('learning_rate', lr)\n\n loss_averages_op = _add_loss_summaries(total_loss)\n with tf.control_dependencies([loss_averages_op]):\n opt = tf.train.AdamOptimizer(learning_rate=lr)\n grads = opt.compute_gradients(total_loss)\n\n apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)\n for var in tf.trainable_variables():\n tf.histogram_summary(var.op.name, var)\n \n for grad, var in grads:\n if grad is not None:\n tf.histogram_summary(var.op.name + '/gradients', grad)\n \n # Track the moving averages of all trainable variables.\n variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)\n variables_averages_op = variable_averages.apply(tf.trainable_variables())\n\n with tf.control_dependencies([apply_gradient_op, variables_averages_op]):\n train_op = tf.no_op(name='train')\n\n return train_op\n","sub_path":"src/old_model.py","file_name":"old_model.py","file_ext":"py","file_size_in_byte":7682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"397955832","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\nn=int(input())\nfor i in range(n):\n x=input()\n\n\n# In[13]:\n\n\nimport re\nxx=\"gu ru99,educatio0n is fun\"\nr1=re.findall(r\"^\\w+\",xx)\nprint(r1)\n\n\n# In[15]:\n\n\nimport re\nxx = \"guru99,education is fun\"\nr1 =re.findall(r\"^\\w+\", xx)\nprint((re.split(r'\\s','we are splitting the words')))\nprint((re.split(r's',' split the words')))\n\n\n# In[20]:\n\n\nimport re\ntxt = \"The rain in Spain\"\nx = re.match(\"^The.*Spain$\", txt) \nprint(x)\n\n\n# In[25]:\n\n\nimport re\ntxt = \"The rain in Spaina\"\nx = re.findall(\"a\", txt)\nprint(x)\n\n\n# In[26]:\n\n\nimport re\ntxt = \"The rain in Spain\"\nx = re.findall(\"Portugal\", txt)\nprint(x) \n\n\n# In[36]:\n\n\nimport re\n\ntxt = \"Thenaga rain in Spain\"\nx = re.search(\"\\s\", txt)\nprint( x.end()) \n\n\n# In[40]:\n\n\nimport re\ntxt = \"Thie rain in Spain\"\nx = re.search(\"\\n\", txt)\nprint(x) \n\n\n# In[48]:\n\n\nimport re\n\ntxt = \"The rain in Spain\"\nx = re.split(\"\\s\", txt,5)\nprint(x) \n\n\n# In[51]:\n\n\nimport re\n\ntxt = \"The rain in Spain\"\nx = re.sub(\"\\ZSpain\", \"909\", txt)\nprint(x) \n\n\n# In[52]:\n\n\nimport re\n\ntxt = \"The rain in Spain\"\nx = re.sub(\"\\s\", \"9\", txt, 2)\nprint(x) \n\n\n# In[68]:\n\n\nimport re\n\ntxt = \"The rain in Spain\"\nx = re.search(\"Spain\\Z\", txt)#end to end match in teh sentence\nprint(x)#ending and starting index of the searching charector\n\n\n# In[59]:\n\n\nimport re\ntxt = \"The rain in Spain\"\nx = re.search(r\"i\", txt)\nprint(x.string)\n\n\n# In[65]:\n\n\nimport re\ntxt = \"The rain in Spain\"\nx = re.search(r\"\\bS\\w+\", txt)\nprint(x.group()) \n\n\n# In[73]:\n\n\nimport json#java script object notation\n\n# some JSON:\nx ='{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}'\n\n# parse x:\ny = json.loads(x)\n\n# the result is a Python dictionary:\nprint(y[\"age\"]) \n\n\n# In[70]:\n\n\nprint(y)\n\n\n# In[74]:\n\n\n# a Python object (dict):\nimport json#loads and jumps\nx = {\n \"name\": \"John\",\n \"age\": 30,\n \"city\": \"New York\"\n}\n\n# convert into JSON:\ny = json.dumps(x)\n\n# the result is a JSON string:\nprint(y) \n\n\n# In[75]:\n\n\nimport json\n\nprint(json.dumps({\"name\": \"John\", \"age\": 30}))\nprint(json.dumps([\"apple\", \"bananas\"]))\nprint(json.dumps((\"apple\", \"bananas\")))\nprint(json.dumps(\"hello\"))\nprint(json.dumps(42))\nprint(json.dumps(31.76))\nprint(json.dumps(True))\nprint(json.dumps(False))\nprint(json.dumps(None)) \n\n\n# In[76]:\n\n\nimport json\n\nx = {\n \"name\": \"John\",\n \"age\": 30,\n \"married\": True,\n \"divorced\": False,\n \"children\": (\"Ann\",\"Billy\"),\n \"pets\": None,\n \"cars\": [\n {\"model\": \"BMW 230\", \"mpg\": 27.5},\n {\"model\": \"Ford Edge\", \"mpg\": 24.1}\n ]\n}\n\nprint(json.dumps(x))\n\n\n# In[83]:\n\n\ntry:\n print(l)\nexcept ValueError:\n print(\"Something went wrong\",ValueError)\nfinally:\n print(\"The 'try except' is finished\") \n\n\n# In[85]:\n\n\ntry:\n print(s)\nexcept NameError:\n print(\"Something went wrong\")\nfinally:\n print(\"The 'try except' is finished\") \n\n\n# In[90]:\n\n\ntry:\n f=open(\"demofile.txt\")\n f.write(\"Lorum Ipsum\")\nexcept:\n print(\"Something went wrong when writing to the file\")\n\n\n# In[100]:\n\n\nx = \"hello\"\nif not type(x) is int:\n raise TypeError(\"Only integers are allowed\") \n\n\n# In[102]:\n\n\nclass Person:\n def __init__(self, fname, lname):\n self.firstname = fname\n self.lastname = lname\n\n def printname(self):\n print(self.firstname, self.lastname)\n\n#Use the Person class to create an object, and then execute the printname method:\n\nx = Person(\"John\", \"Doe\")\nx.printname() \nclass Student(Person):\n pass\np=Student(\"naga\",\"laxmi\")\np.printname()\n\n\n# In[103]:\n\n\nclass Student(Person):\n def __init__(self, fname, lname):\n Person.__init__(self, fname, lname) \n\n\n# In[104]:\n\n\nclass Student(Person):\n def __init__(self, fname, lname):\n super().__init__(fname, lname)\n self.graduationyear = 2019\n\n\n# In[118]:\n\n\nclass Person:\n def __init__(self,fname,lname):\n self.fname=fname\n self.lname=lname\n def naga(self):\n print(self.fname,self.lname)\nclass Student(Person):\n def __init__(self, fname, lname, year):\n super().__init__(fname, lname)\n self.graduationyear = year\nx = Student(\"Mike\", \"Olsen\", 2019) \nx.graduationyear\n\n\n# In[122]:\n\n\nmystr = \"banana\"\nfor x in mystr:\n print(x) \n\n\n# In[125]:\n\n\nclass MyNumbers:\n def __iter__(self):\n self.a = 2\n return self\n def __next__(self):\n self.a += 1\n return self.a\nmyclass = MyNumbers()\nmyiter = iter(myclass)\nprint(next(myiter))\nprint(next(myiter))\nprint(next(myiter))\nprint(next(myiter))\nprint(next(myiter)) \n\n","sub_path":"python_Hacker/itet_next_class.py","file_name":"itet_next_class.py","file_ext":"py","file_size_in_byte":4303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"597318092","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\nfrom baseball.items import VbItem;\n\nclass BatterSpider(scrapy.Spider):\n name = 'DeNA'\n allowed_domains = ['npb.jp']\n start_urls = ['http://npb.jp/bis/teams/rst_db.html']\n\n def parse(self, response):\n\n #//=ノードの省略 @=クラス要素の指定\n for tr in response.xpath('//*[@id=\"tedivmaintbl\"]/div[4]/table').xpath('tr'):\n \n item = VbItem()\n \n item['number'] = tr.xpath('td[1]/text()').extract_first()\n #if文で値がnullかを判断する\n if not isinstance(tr.xpath('td[2]/a/text()').re_first(r'\\w+\\s*\\w+'),type(None)):\n name_str = tr.xpath('td[2]/a/text()').re_first(r'\\w+\\s*\\w+')\n #全角空白の削除\n item['name'] = name_str.replace(' ', ' ')\n \n item['day'] = tr.xpath('td[3]/text()').extract_first()\n item['height'] = tr.xpath('td[4]/text()').extract_first()\n item['weight'] = tr.xpath('td[5]/text()').extract_first()\n item['pit'] = tr.xpath('td[6]/text()').extract_first()\n item['bat'] = tr.xpath('td[7]/text()').extract_first()\n \n yield item\n ","sub_path":"baseball/spiders/vb.py","file_name":"vb.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"586687290","text":"# pylint: disable=E1101, C0116, C0114\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom fos import Workout, AMPWorkout\nfrom fos.callbacks import LRScheduler\n\n\ndef get_model():\n return nn.Sequential(\n nn.Linear(10, 32),\n nn.ReLU(),\n nn.Linear(32, 1))\n\n\ndef get_data(steps):\n return [(torch.randn(16, 10), torch.rand(16, 1)) for i in range(steps)]\n\n\ndef test_workout():\n model = get_model()\n loss = F.mse_loss\n optim = torch.optim.Adam(model.parameters())\n workout = Workout(model, loss, optim)\n\n data = get_data(100)\n workout.fit(data)\n assert workout.epoch == 1\n\n workout.fit(data, epochs=10)\n assert workout.epoch == 11\n\n valid_data = get_data(100)\n for minibatch in valid_data:\n workout.validate(*minibatch)\n assert workout.epoch == 11\n\n workout.fit(data, valid_data, epochs=5)\n assert workout.epoch == 16\n\n\n\ndef test_workout_metrics():\n model = get_model()\n loss = F.mse_loss\n optim = torch.optim.Adam(model.parameters())\n\n def my_metric(*_):\n return 1.0\n\n workout = Workout(model, loss, optim, my_metric=my_metric)\n data = get_data(100)\n workout.fit(data, epochs=10)\n\n assert workout.has_metric('my_metric')\n assert not workout.has_metric('my_metric2')\n assert len(workout.get_metrics()) == 3\n assert workout.get_metric(\"my_metric\") == 1.0\n\n\n\ndef test_ampworkout():\n if not torch.cuda.is_available():\n return\n\n model = get_model().to(\"cuda\")\n loss = F.mse_loss\n optim = torch.optim.Adam(model.parameters())\n workout = AMPWorkout(model, loss, optim)\n\n data = get_data(100)\n workout.fit(data)\n assert workout.epoch == 1\n\n workout.fit(data, epochs=10)\n assert workout.epoch == 11\n\n valid_data = get_data(100)\n for minibatch in valid_data:\n workout.validate(*minibatch)\n assert workout.epoch == 11\n\n workout.fit(data, valid_data, epochs=5)\n assert workout.epoch == 16\n\n\ndef test_lr_scheduler():\n model = get_model()\n loss = F.mse_loss\n optim = torch.optim.Adam(model.parameters(), lr=1e-02)\n workout = Workout(model, loss, optim)\n\n scheduler = torch.optim.lr_scheduler.StepLR(optim, step_size=10, gamma=0.1)\n callback = LRScheduler(scheduler)\n\n data = get_data(100)\n workout.fit(data, epochs=30, callbacks=[callback])\n assert workout.optim.param_groups[0]['lr'] == 1e-05\n\n model = get_model()\n val_data = get_data(25)\n optim = torch.optim.Adam(model.parameters(), lr=1e-02)\n workout = Workout(model, loss, optim)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optim)\n callback = LRScheduler(scheduler, \"val_loss\")\n workout.fit(data, val_data, epochs=100, callbacks=[callback])\n assert workout.optim.param_groups[0]['lr'] < 1e-02\n\ndef test_predict():\n model = get_model()\n loss = F.mse_loss\n optim = torch.optim.Adam(model.parameters())\n workout = Workout(model, loss, optim)\n\n data = torch.randn(16, 10)\n result = workout.predict(data)\n assert len(result) == 16\n\n\ndef test_workout_state():\n model = get_model()\n loss = F.mse_loss\n workout = Workout(model, loss)\n\n state = workout.state_dict()\n workout = Workout(model, loss)\n workout.load_state_dict(state)\n\n filename = \"./tmp_file.dat\"\n result = workout.save(filename)\n assert result == filename\n\n result = workout.load(filename)\n assert result == filename\n os.remove(filename)\n\n filename1 = workout.save()\n filename2 = workout.load()\n os.remove(filename1)\n assert filename1 == filename2\n dir1 = os.path.dirname(filename1)\n os.rmdir(dir1)\n dir1 = os.path.dirname(dir1)\n os.rmdir(dir1)\n\ndef test_workout_basic():\n model = get_model()\n loss = F.mse_loss\n optim = torch.optim.Adam(model.parameters())\n workout = Workout(model, loss, optim)\n\n data = get_data(100)\n workout.fit(data, data)\n assert workout.epoch == 1\n","sub_path":"test/test_workout.py","file_name":"test_workout.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"372002190","text":"# AtCoder Beginner Contest 140\n# C - Maximal Value\n\nN = int(input())\nB = list(map(int, input().split()))\nans = B[0]\n\nfor i, j in zip(B[:-1], B[1:]):\n if i <= j:\n ans += i\nelse:\n ans += j\n\nprint(ans)\n","sub_path":"abc/abc14x/abc140/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"298294742","text":"#!/usr/local/bin/python3\n# -*- coding:utf-8 -*-\nimport os, sys\nprint(os.getcwd())\n#sys.path.append(os.getcwd())\nsys.path.append(\"..\")\nimport scrapy\nimport time\nimport requests\nimport json\nimport base64\n#from scrapy.conf import settings\nfrom scrapy.utils.project import get_project_settings\nfrom scrapy.linkextractors import LinkExtractor\nfrom newscrawler.items import NewscrawlerItem\n#from items import NewscrawlerItem\nfrom scrapy.selector import Selector\nfrom datetime import date, datetime, timezone, timedelta\nfrom googletrans import Translator\nfrom scrapy.xlib.pydispatch import dispatcher\nfrom scrapy.crawler import CrawlerProcess\nfrom multiprocessing import Process, Queue\n\nfrom twisted.internet import reactor,defer\nfrom scrapy.crawler import CrawlerRunner\nfrom scrapy.utils.log import configure_logging\n\nimport scrapy.crawler as crawler\n\nsettings = get_project_settings()\n\nJST = timezone(timedelta(hours=+9), 'JST')\nCST = timezone(timedelta(hours=+8), 'CST')\n#loc = datetime.fromtimestamp(now, CST)\n#utc = datetime.fromtimestamp(now, timezone.utc)\n#time.time()\n\n###############################\n#author:ChenRukun #\n#created:20180622 #\n#scrapy crawl newscrawler #\n###############################\n#金色财经爬虫\nclass NewsSpider1(scrapy.Spider):\n #爬虫启动参数初始化\n name = \"newscrawler\"\n allowed_domains= settings['ALLOWED_DOMAINS_1']\n start_urls= settings['START_URLS_1']\n\n #wp api 参数初始化\n wp_api_id = settings['WP_API_ID']\n wp_api_pw = settings['WP_API_PW']\n end_point_url = settings['END_POINT_URL']\n\n def parse(self, response):\n #对爬虫对象json解析\n body = response.body.decode('utf-8')\n #jdict = json.loads(response.body)\n jdict = json.loads(body)\n jlists = jdict[\"list\"]\n if jlists:\n #实例化googletrans\n translaor = Translator()\n for list in jlists:\n for live in list[\"lives\"]:\n item = NewscrawlerItem()\n #创建日期\n item[\"date\"] = list[\"date\"]\n #爬虫源文章ID\n item[\"cid\"] = live[\"id\"]\n #中文标题&中文内容\n str_title_content = live[\"content\"].split('】',1)\n str_title = str_title_content[0].lstrip('【')\n str_content = str_title_content[1]\n item[\"title\"] = str_title\n item[\"content\"] = str_content\n #日文标题&日文内容\n item[\"title_jp\"] = translaor.translate(str_title, dest='ja').text\n item[\"content_jp\"] = translaor.translate(str_content, dest='ja').text\n #重要度\n item[\"grade\"] = live[\"grade\"]\n #类别\n item[\"sort\"] = live[\"sort\"]\n #创建时间\n loc = datetime.fromtimestamp(live[\"created_at\"], JST)\n item[\"created_at\"] = loc\n #好评数\n item[\"up_counts\"] = live[\"up_counts\"]\n #差评数\n item[\"down_counts\"] = live[\"down_counts\"]\n #赞数\n item[\"zan_status\"] = live[\"zan_status\"]\n\n #WP API投稿\n wp_api_id = self.wp_api_id\n wp_api_pw = self.wp_api_pw\n end_point_url = self.end_point_url\n\n p_grade = item[\"grade\"]\n p_title = str_title\n p_content = str_content\n p_title_jp = item[\"title_jp\"]\n p_content_jp = item[\"content_jp\"]\n p_category_jp = item[\"sort\"]\n p_create_at = item[\"created_at\"]\n p_up_count = item[\"up_counts\"]\n p_down_count = item[\"down_counts\"]\n payload = {\n 'title' : p_title,\n 'content' : p_content,\n 'status' : \"draft\",\n 'fields' : {\n 'importance': p_grade,\n 'title_JP' : p_title_jp,\n 'content_JP' : p_content_jp,\n 'category_JP' : p_category_jp,\n 'tag' : \"ビッグニュース_\",\n 'newsFrom' : \"金色财经\",\n 'created_at' : p_create_at.isoformat(),\n 'up_count' : p_up_count,\n 'down_count' : p_down_count\n }\n }\n headers = {'content-type': \"Application/json\"}\n r = requests.post(end_point_url, data=json.dumps(payload), headers=headers, auth=(wp_api_id, wp_api_pw))\n # print(r)\n print(item)\n #yield item\n else:\n print(\"The news is empty!!!\")\n\n#火球财经爬虫\nclass NewsSpider2(scrapy.Spider):\n #爬虫启动参数初始化\n name = \"newscrawler\"\n allowed_domains= settings['ALLOWED_DOMAINS_2']\n start_urls= settings['START_URLS_2']\n\n #wp api 参数初始化\n wp_api_id = settings['WP_API_ID']\n wp_api_pw = settings['WP_API_PW']\n end_point_url = settings['END_POINT_URL']\n\n def parse(self, response):\n #对爬虫对象解析\n news = Selector(response).xpath(\"//div[@class='hq_newslist_container']\")\n\n translaor = Translator()\n\n i = 0\n if news:\n for new in news:\n item = NewscrawlerItem()\n item[\"created_at\"] = new.xpath(\"//div[@class='hq_newslist_time']/p/text()\").extract()[i]\n #中文标题&中文内容\n contents= new.xpath(\"//div[@class='hq_newslist_content']/p[1]/text()\").extract()[i].strip()\n if contents.count('】')>1 or contents.count('】')<1:\n print(\"币世界数据标题标签异常,处理下一条数据\")\n continue\n str_title_content = new.xpath(\"//div[@class='hq_newslist_content']/p[1]/text()\").extract()[i].strip().split('】',1)\n str_title = str_title_content[0].lstrip('【')\n str_content = str_title_content[1]\n item[\"title\"] = str_title\n item[\"content\"] = str_content\n #日文标题&日文内容\n item[\"title_jp\"] = translaor.translate(str_title, dest='ja').text\n item[\"content_jp\"] = translaor.translate(str_content, dest='ja').text\n #快讯下标\n i += 1\n\n #WP API投稿\n wp_api_id = self.wp_api_id\n wp_api_pw = self.wp_api_pw\n end_point_url = self.end_point_url\n\n p_title = item[\"title\"]\n p_content = item[\"content\"]\n p_title_jp = item[\"title_jp\"]\n p_content_jp = item[\"content_jp\"]\n p_create_at = item[\"created_at\"]\n payload = {\n 'title' : p_title,\n 'content' : p_content,\n 'status' : \"draft\",\n 'fields' : {\n 'importance': \"\",\n 'title_JP' : p_title_jp,\n 'content_JP' : p_content_jp,\n 'tag' : \"ビッグニュース_\",\n 'newsFrom' : \"火球财经\",\n 'created_at' : p_create_at\n }\n }\n headers = {'content-type': \"Application/json\"}\n r = requests.post(end_point_url, data=json.dumps(payload), headers=headers, auth=(wp_api_id, wp_api_pw))\n #print(r)\n print(item)\n #yield item\n if i==3:\n break\n else:\n print(\"The news is empty!!!\")\n\n#币世界爬虫\nclass NewsSpider3(scrapy.Spider):\n #爬虫启动参数初始化\n name = \"newscrawler\"\n allowed_domains= settings['ALLOWED_DOMAINS_3']\n start_urls= settings['START_URLS_3']\n\n #wp api 参数初始化\n wp_api_id = settings['WP_API_ID']\n wp_api_pw = settings['WP_API_PW']\n end_point_url = settings['END_POINT_URL']\n\n def parse(self, response):\n #google翻译对象实例化\n translaor = Translator()\n\n #币世界日期标签\n now = datetime.now()\n nowstr = now.strftime('%Y-%m-%d')\n divtag = \"live livetop \"+nowstr\n divtag = \"//div[@class='kuaixun_list']/div[@class='\"+divtag+\"']/ul\"\n #对爬虫对象解析\n news = Selector(response).xpath(divtag)\n\n datasCheck = Selector(response).xpath(divtag+\"/span[1]/text()\").extract()\n for dataCheck in datasCheck:\n if dataCheck:\n print(dataCheck)\n print(\"币世界在[%s]有数据!\"%(nowstr))\n break\n else:\n print(\"币世界在[%s]还没有数据!\"%(nowstr))\n return 0\n i = 0\n for new in news:\n item = NewscrawlerItem()\n item[\"created_at\"] = nowstr+\" \"+new.xpath(\"span[1]/text()\").extract()[0]\n item[\"title\"] = new.xpath(\"//h2/a/text()\").extract()[i]\n item[\"content\"] = new.xpath(\"li[1]/div/a/text()\").extract()[0].strip()\n # #中文标题&中文内容\n str_title = item[\"title\"]\n str_content = item[\"content\"]\n #日文标题&日文内容\n item[\"title_jp\"] = translaor.translate(str_title, dest='ja').text\n item[\"content_jp\"] = translaor.translate(str_content, dest='ja').text\n #好评数\n item[\"up_counts\"] = new.xpath(\"li[2]/div[1]/b/text()\").extract()[0]\n #差评数\n item[\"down_counts\"] = new.xpath(\"li[2]/div[2]/b/text()\").extract()[0]\n #快讯下标\n i += 1\n\n #WP API投稿\n wp_api_id = self.wp_api_id\n wp_api_pw = self.wp_api_pw\n end_point_url = self.end_point_url\n\n p_title = item[\"title\"]\n p_content = item[\"content\"]\n p_title_jp = item[\"title_jp\"]\n p_content_jp = item[\"content_jp\"]\n p_create_at = item[\"created_at\"]\n p_up_count = item[\"up_counts\"]\n p_down_count = item[\"down_counts\"]\n\n payload = {\n 'title' : p_title,\n 'content' : p_content,\n 'status' : \"draft\",\n 'fields' : {\n 'importance': \"\",\n 'title_JP' : p_title_jp,\n 'content_JP' : p_content_jp,\n 'tag' : \"ビッグニュース_\",\n 'newsFrom' : \"币世界\",\n 'created_at' : p_create_at,\n 'up_count' : p_up_count,\n 'down_count' : p_down_count\n }\n }\n headers = {'content-type': \"Application/json\"}\n r = requests.post(end_point_url, data=json.dumps(payload), headers=headers, auth=(wp_api_id, wp_api_pw))\n # print(r)\n print(item)\n #yield item\n if i==3:\n break\n\n# the wrapper to make it run more times\ndef run_spider(spider):\n def f(q):\n try:\n runner = crawler.CrawlerRunner()\n deferred = runner.crawl(spider)\n deferred.addBoth(lambda _: reactor.stop())\n reactor.run()\n q.put(None)\n except Exception as e:\n q.put(e)\n\n q = Queue()\n p = Process(target=f, args=(q,))\n p.start()\n result = q.get()\n p.join()\n\n if result is not None:\n raise result\n\n\nprint(\"START---------金色财经数据抓取\")\nrun_spider(NewsSpider1)\nprint(\"END---------金色财经数据抓取\")\nprint(\"START---------火球财经数据抓取\")\nrun_spider(NewsSpider2)\nprint(\"END---------火球财经数据抓取\")\nprint(\"START---------币世界数据抓取\")\nrun_spider(NewsSpider3)\nprint(\"END---------币世界数据抓取\")\n\n# Usage\n# if __name__ == \"__main__\":\n# #log.start()\n#\n# process = CrawlerProcess()\n# crawler = NewsSpider()\n# try:\n# process.crawl(crawler)\n# process.start()\n# print(\"Completed\")\n# except Exception as e:\n# print(\"错误》》\", e)\n","sub_path":"newscrawler/newscrawler/spiders/NewsSpider.py","file_name":"NewsSpider.py","file_ext":"py","file_size_in_byte":13034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"261100918","text":"#\n# gemini_python\n#\n# primtives_gmos_longslit.py\n# ------------------------------------------------------------------------------\nimport numpy as np\nfrom gempy.gemini import gemini_tools as gt\nfrom gempy.library import astrotools as at\nfrom gempy.library import astromodels\n\nfrom geminidr.gemini.lookups import DQ_definitions as DQ\n\nfrom .primitives_gmos_spect import GMOSSpect\nfrom .primitives_gmos_nodandshuffle import GMOSNodAndShuffle\nfrom . import parameters_gmos_longslit\n\nfrom astropy.modeling import models, fitting\nfrom astropy.stats import sigma_clip\n\nfrom recipe_system.utils.decorators import parameter_override\n# ------------------------------------------------------------------------------\n@parameter_override\nclass GMOSLongslit(GMOSSpect, GMOSNodAndShuffle):\n \"\"\"\n This is the class containing all of the preprocessing primitives\n for the GMOSLongslit level of the type hierarchy tree. It inherits all\n the primitives from the level above\n \"\"\"\n tagset = set([\"GEMINI\", \"GMOS\", \"SPECT\", \"LS\"])\n\n def __init__(self, adinputs, **kwargs):\n super(GMOSLongslit, self).__init__(adinputs, **kwargs)\n self._param_update(parameters_gmos_longslit)\n\n def addIllumMaskToDQ(self, adinputs=None, suffix=None, illum_mask=None):\n \"\"\"\n Adds an illumination mask to each AD object\n\n Parameters\n ----------\n suffix: str\n suffix to be added to output files\n illum_mask: str/None\n name of illumination mask mask (None -> use default)\n \"\"\"\n log = self.log\n log.debug(gt.log_message(\"primitive\", self.myself(), \"starting\"))\n timestamp_key = self.timestamp_keys[self.myself()]\n\n for ad, illum in zip(*gt.make_lists(adinputs, illum_mask, force_ad=True)):\n if ad.phu.get(timestamp_key):\n log.warning('No changes will be made to {}, since it has '\n 'already been processed by addIllumMaskToDQ'.\n format(ad.filename))\n continue\n\n if illum is None:\n # Default operation for GMOS LS\n # The 95% cut should ensure that we're sampling something\n # bright (even for an arc)\n # The 75% cut is intended to handle R150 data, where many of\n # the extensions are unilluminated\n row_medians = np.percentile(np.array([np.percentile(ext.data, 95, axis=1)\n for ext in ad]), 75, axis=0)\n rows = np.arange(len(row_medians))\n m_init = models.Polynomial1D(degree=2)\n fit_it = fitting.FittingWithOutlierRemoval(fitting.LinearLSQFitter(),\n outlier_func=sigma_clip)\n m_final, mask = fit_it(m_init, rows, row_medians)\n mask &= (row_medians < m_final(rows))\n # The default selection tends to mask the edges of the good\n # regions, so rein it in a bit\n mask = at.boxcar(mask, operation=np.logical_and, size=1)\n for ext in ad:\n ext.mask |= (mask * DQ.unilluminated).astype(DQ.datatype)[:, np.newaxis]\n\n else:\n log.fullinfo(\"Using {} as illumination mask\".format(illum.filename))\n final_illum = gt.clip_auxiliary_data(ad, aux=illum, aux_type='bpm',\n return_dtype=DQ.datatype)\n\n for ext, illum_ext in zip(ad, final_illum):\n if illum_ext is not None:\n # Ensure we're only adding the unilluminated bit\n iext = np.where(illum_ext.data > 0, DQ.unilluminated,\n 0).astype(DQ.datatype)\n ext.mask = iext if ext.mask is None else ext.mask | iext\n\n # Timestamp and update filename\n gt.mark_history(ad, primname=self.myself(), keyword=timestamp_key)\n ad.update_filename(suffix=suffix, strip=True)\n\n return adinputs\n\n def normalizeFlat(self, adinputs=None, **params):\n \"\"\"\n This primitive normalizes a GMOS Longslit spectroscopic flatfield\n in a manner similar to that performed by gsflat in Gemini-IRAF.\n A cubic spline is fitted along the dispersion direction of each\n row, separately for each CCD.\n\n As this primitive is GMOS-specific, we know the dispersion direction\n will be along the rows, and there will be 3 CCDs.\n\n For Hamamatsu CCDs, the 21 unbinned columns at each CCD edge are\n masked out, following the procedure in gsflat.\n TODO: Should we add these in the BPM?\n\n Parameters\n ----------\n suffix: str\n suffix to be added to output files\n spectral_order: int/str\n order of fit in spectral direction\n \"\"\"\n log = self.log\n log.debug(gt.log_message(\"primitive\", self.myself(), \"starting\"))\n timestamp_key = self.timestamp_keys[self.myself()]\n suffix = params[\"suffix\"]\n spectral_order = params[\"spectral_order\"]\n\n # Parameter validation should ensure we get an int or a list of 3 ints\n try:\n orders = [int(x) for x in spectral_order]\n except TypeError:\n orders = [spectral_order] * 3\n\n for ad in adinputs:\n xbin, ybin = ad.detector_x_bin(), ad.detector_y_bin()\n array_info = gt.array_information(ad)\n is_hamamatsu = 'Hamamatsu' in ad.detector_name(pretty=True)\n ad_tiled = self.tileArrays([ad], tile_all=False)[0]\n for ext, order, indices in zip(ad_tiled, orders, array_info.extensions):\n # If the entire row is unilluminated, we want to fit\n # the pixels but still keep the edges masked\n try:\n ext.mask ^= (np.bitwise_and.reduce(ext.mask, axis=1) & DQ.unilluminated)[:, None]\n except TypeError: # ext.mask is None\n pass\n else:\n if is_hamamatsu:\n ext.mask[:, :21 // xbin] = 1\n ext.mask[:, -21 // xbin:] = 1\n fitted_data = np.empty_like(ext.data)\n pixels = np.arange(ext.shape[1])\n\n for i, row in enumerate(ext.nddata):\n masked_data = np.ma.masked_array(row.data, mask=row.mask)\n weights = np.sqrt(np.where(row.variance > 0, 1. / row.variance, 0.))\n spline = astromodels.UnivariateSplineWithOutlierRemoval(pixels, masked_data,\n order=order, w=weights)\n fitted_data[i] = spline(pixels)\n ext.divide(fitted_data)\n\n # Split the normalized flat back into the separate extensions\n tiled_detsec = ext.detector_section()\n for i in indices:\n detsec = ad[i].detector_section()\n slice_ = (slice((detsec.y1 - tiled_detsec.y1) // ybin, (detsec.y2 - tiled_detsec.y1) // ybin),\n slice((detsec.x1 - tiled_detsec.x1) // xbin, (detsec.x2 - tiled_detsec.x1) // xbin))\n ad[i].data = np.nan_to_num(ext.data[slice_])\n ad[i].variance = np.nan_to_num(ext.variance[slice_])\n\n # Timestamp and update filename\n gt.mark_history(ad, primname=self.myself(), keyword=timestamp_key)\n ad.update_filename(suffix=suffix, strip=True)\n\n return adinputs","sub_path":"geminidr/gmos/primitives_gmos_longslit.py","file_name":"primitives_gmos_longslit.py","file_ext":"py","file_size_in_byte":7768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"303209532","text":"import numpy as np\nclass KMeans:\n def __init__(self, k, max_iter=1000, tolerance=1e-2, random_state=None):\n \"\"\"\n @k: number of clusters -> int\n @max_iter: maximum iterations -> int\n @tolerance: tolerance of error of centers between iterations -> float\n \"\"\"\n self.k = k\n self.max_iter = max_iter\n self.tolerance = tolerance\n np.random.seed(random_state)\n\n def get_distances(self, centroid, points):\n \"\"\"\n Returns the distance the centroid is from each data point in points.\n \"\"\"\n return np.linalg.norm(points - centroid, axis=1)\n\n def init_centers(self, points, k):\n \"\"\"\n Initializes clusters as k randomly selected points from points.\n \"\"\"\n return points[np.random.choice(points.shape[0], size=k, replace=False)]\n\n def fit(self, points):\n \"\"\"\n Fit the KMeans model: perform the assignment step and the update step\n \"\"\"\n k = self.k\n centers = self.init_centers(points, k)\n new_centers = centers\n\n classes = np.zeros(points.shape[0])\n distances = np.zeros([points.shape[0], k])\n\n for i in range(self.max_iter):\n # Assign all points to the nearest centroid\n for c in range(k):\n distances[:,c] = self.get_distances(centers[c], points)\n # Determine class membership of each point by picking the closest centroid\n classes = distances.argmin(axis=1)\n # Update centroid location using the newly\n # assigned data point classes\n for c in range(k):\n new_centers[c] = np.mean(points[classes==c], axis=0)\n if np.sum(abs(new_centers-centers)) < self.tolerance:\n break\n centers = new_centers\n return centers, classes\n\npoints = np.array([[1,3], [2,4], [3,6]], dtype=np.float64)\nkm = KMeans(2, random_state=1)\n\nkm.fit(points)\n","sub_path":"src/clustering/KMeans.py","file_name":"KMeans.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"463665931","text":"#coding: utf-8\nimport codecs\nimport time\nimport random\nfrom selenium import webdriver\ndriver = webdriver.Chrome()\ndriver.get('https://weibo.com/')\ntime.sleep(6)\nusername = '15716302402'\npwd = 'appijyw231870t..'\ndriver.find_element_by_xpath('//*[@id=\"loginname\"]').send_keys(username)\ndriver.find_element_by_xpath('//*[@id=\"pl_login_form\"]/div/div[3]/div[2]/div/input').send_keys(pwd)\ndriver.find_element_by_xpath('//*[@id=\"pl_login_form\"]/div/div[3]/div[6]/a/span').click()\nwhile True:\n time.sleep(2)\n text = '最新会员电影免费看^_^,请亲们及时保存到百度网盘即可观看哦。\\r\\n'\n f = codecs.open(\"E:\\\\wechat\\\\movie.txt\", 'r', encoding='utf-8').readlines()\n for i in f:\n text += i\n try:\n driver.get('https://weibo.com/u/5710928238/home?leftnav=1#1513515573373')\n driver.find_element_by_xpath('//*[@id=\"v6_pl_content_publishertop\"]/div/div[2]/textarea').send_keys(text)\n time.sleep(random.randrange(1,5))\n driver.find_element_by_xpath('//*[@id=\"v6_pl_content_publishertop\"]/div/div[3]/div[1]/a').click()\n except:\n pr\n pass\n time.sleep(random.randrange(100,200))\n file = codecs.open(\"E:\\\\wechat\\\\movie.txt\", 'r', encoding='utf-8').readlines()\n if file ==f:\n print(\"电影未更新,无需发微博\")\n time.sleep(random.randrange(300,400))\n else:\n print(\"即将发微博\")\n continue\n\n\n","sub_path":"wxpy_test/weibo_spider.py","file_name":"weibo_spider.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"135489232","text":"import tensorflow as tf\nimport numpy as np\nimport h5py\nimport math\nfrom homepage.src.tf_utils import SessionHandler\n\nVALID_METHOD = \"VALID\"\nSAME_METHOD = \"SAME\"\n\nLAYER_TYPE = [\"convpool\", \"conv\", \"pool\", \"fc\", \"shortcut\"]\n\nIS_GPU = False\n\nINIT_VAL = 0.1\n\n\"\"\"the basic layer class\"\"\"\nclass CommonLayer(object):\n def get_filter(self):\n return self.filter_shape\n\n ## padding method is either VALID or SAME\n def get_padding_method(self):\n return self.padding\n\n def get_output(self, input):\n pass\n\n def set_weights(self, weights):\n self.init_weights = weights\n\n def init_net(self):\n if IS_GPU:\n self._init_net()\n else:\n with tf.device(\"/cpu:0\"):\n self._init_net()\n\n\nclass ConvLayer(CommonLayer):\n def __init__(self, filter_shape, padding=\"SAME\", weights=None):\n self.layer_type = \"conv\"\n\n self.filter_shape = filter_shape\n self.padding = padding\n\n self.init_weights = weights\n\n self.update_weights_op = None\n\n def set_init_values(self, weights=None):\n self.init_weights = weights\n\n def _init_net(self):\n if self.init_weights is None:\n self.init_weights = tf.random_uniform(self.filter_shape,\n minval = -INIT_VAL,\n maxval = INIT_VAL\n )\n self.conv_weights = tf.Variable(self.init_weights)\n\n def get_output(self, input):\n self.input = input\n conv = tf.nn.conv2d(input=self.input,\n filter=self.conv_weights,\n strides=[1, 1, 1, 1],\n padding=self.padding)\n\n # relu = tf.nn.relu(conv)\n return conv\n\n ## padding method is either VALID or SAME\n def get_padding_method(self):\n return self.padding\n\n def get_filter(self):\n return self.filter_shape\n\n def get_weights(self):\n return self.conv_weights\n\n def set_weights(self, weights):\n return self.conv_weights.assign(weights)\n\n def set_placeholder_weights(self, weights):\n if self.update_weights_op is None:\n self.update_placeholder_weights = tf.placeholder(self.init_weights.dtype,\n shape=self.conv_weights.get_shape())\n self.update_weights_op = self.conv_weights.assign(self.update_placeholder_weights)\n SessionHandler().get_session().run(self.update_weights_op,\n {self.update_placeholder_weights:weights})\n\n def save_weights(self, h5File, init_num):\n weight_num = init_num\n name = \"weight_%s\" % str(weight_num)\n h5File.create_dataset(name, data=self.conv_weights.eval())\n weight_num += 1\n return weight_num\n\n\n\nclass PoolLayer(CommonLayer):\n def __init__(self, padding=\"SAME\"):\n self.layer_type = \"pool\"\n self.padding = padding\n\n\n def init_net(self):\n pass\n\n def get_output(self, input):\n self.input = input\n pool = tf.nn.max_pool(self.input,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=self.padding)\n return pool\n\n ## padding method is either VALID or SAME\n def get_padding_method(self):\n return self.padding\n\n\nclass ConvPoolLayer(ConvLayer):\n def __init__(self,filter_shape, weights=None, is_add_bias=False):\n self.filter_shape = filter_shape\n self.layer_type = \"convpool\"\n self.padding = \"SAME\"\n self.init_weights = weights\n\n\n def _init_net(self):\n if self.init_weights is None:\n self.init_weights = tf.random_uniform(self.filter_shape,\n minval = -INIT_VAL,\n maxval = INIT_VAL\n )\n self.conv_weights = tf.Variable(self.init_weights)\n\n def get_output(self, input):\n self.input = input\n conv = tf.nn.conv2d(input=self.input,\n filter=self.conv_weights,\n strides=[1, 1, 1, 1],\n padding='SAME')\n\n relu = tf.nn.relu(conv)\n pool = tf.nn.max_pool(relu,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding='SAME')\n\n return pool\n\n\nclass FullForwardLayer(CommonLayer):\n def __init__(self, input_size, output_size, weights=None, biases=None):\n self.layer_type = \"fc\"\n self.input_size = input_size\n self.output_size = output_size\n\n self.init_fc_weights = weights\n self.init_fc_biases = biases\n\n self.update_fc_weights_op = None\n self.update_fc_biases_op = None\n\n def set_init_values(self, weights=None, biases=None):\n self.init_fc_weights = weights\n self.init_fc_biases = biases\n\n def init_net(self):\n if self.init_fc_weights is None:\n # fully connected, depth 512\n self.init_fc_weights = tf.random_uniform([self.input_size, self.output_size],\n minval = -INIT_VAL,\n maxval = INIT_VAL)\n\n if self.init_fc_biases is None:\n self.init_fc_biases = tf.constant(0.0, shape=[self.output_size])\n\n self.fc_weights = tf.Variable(self.init_fc_weights)\n self.fc_biases = tf.Variable(self.init_fc_biases)\n\n def get_output(self, input):\n self.input = input\n return tf.matmul(self.input, self.fc_weights) + self.fc_biases\n\n def get_weights(self):\n return self.fc_weights\n\n def get_biases(self):\n return self.fc_biases\n\n def set_weights(self, weights):\n return self.fc_weights.assign(weights)\n\n def set_biases(self, biases):\n return self.fc_biases.assign(biases)\n\n def set_placeholder_weights(self, weights):\n if self.update_fc_weights_op is None:\n self.update_placeholder_weights = tf.placeholder(self.init_fc_weights.dtype,\n shape=self.fc_weights.get_shape())\n self.update_fc_weights_op = self.fc_weights.assign(self.update_placeholder_weights)\n SessionHandler().get_session().run(self.update_fc_weights_op,\n {self.update_placeholder_weights:weights})\n\n def set_placeholder_biases(self, biases):\n if self.update_fc_biases_op is None:\n self.update_placeholder_biases = tf.placeholder(self.init_fc_biases.dtype,\n shape=self.fc_biases.get_shape())\n self.update_fc_biases_op = self.fc_biases.assign(self.update_placeholder_biases)\n SessionHandler().get_session().run(self.update_fc_biases_op,\n {self.update_placeholder_biases:biases})\n\n\nclass ShortcutLayer(CommonLayer):\n \"\"\"\n Shortcut connection layer.\n \"\"\"\n def __init__(self, weights=None, padding=\"SAME\"):\n self.layer_type = \"shortcut\"\n self.con_layers_map = {}\n self.layer_num = 0\n self.init_weights = weights\n self.padding = padding\n\n self.update_weights_op = None\n\n def add(self, conv_layer):\n self.con_layers_map[self.layer_num] = conv_layer\n self.layer_num += 1\n\n def _init_net(self):\n self.filter_shape = [3,3,self.con_layers_map[0].get_filter()[2],self.con_layers_map[self.layer_num-1].get_filter()[3]]\n\n if self.init_weights is None:\n self.init_weights = tf.random_uniform(self.filter_shape,\n minval = -INIT_VAL,\n maxval = INIT_VAL\n )\n\n for i in range(self.layer_num):\n self.con_layers_map[i].init_net()\n\n def get_output(self, input):\n output = input\n\n if input.get_shape()[3] == self.con_layers_map[self.layer_num-1].get_filter()[3]:\n self.is_need_weights = False\n else:\n self.is_need_weights = True\n\n for i in range(self.layer_num):\n if i < (self.layer_num-1):\n output = tf.nn.relu(self.con_layers_map[i].get_output(output))\n elif self.is_need_weights and i == (self.layer_num-1):\n self.conv_weights = self.conv_weights = tf.Variable(self.init_weights)\n conv = tf.nn.conv2d(input=input,\n filter=self.conv_weights,\n strides=[1, 1, 1, 1],\n padding=self.padding)\n\n output = self.con_layers_map[i].get_output(output) + conv\n\n elif not self.is_need_weights and i == (self.layer_num-1):\n output = self.con_layers_map[i].get_output(output) + input\n\n return output\n\n def set_placeholder_weights(self, weights):\n if self.update_weights_op is None:\n self.update_placeholder_weights = tf.placeholder(self.init_weights.dtype,\n shape=self.conv_weights.get_shape())\n self.update_weights_op = self.conv_weights.assign(self.update_placeholder_weights)\n SessionHandler().get_session().run(self.update_weights_op,\n {self.update_placeholder_weights:weights})\n\n\n def save_weights(self, h5File, init_num):\n weight_num = init_num\n for i in range(self.layer_num):\n self.con_layers_map[i].save_weights(h5File, weight_num)\n weight_num += 1\n if self.is_need_weights:\n weight = self.conv_weights.eval()\n name = \"weight_%s\" % str(weight_num)\n h5File.create_dataset(name, data=weight)\n weight_num += 1\n return weight_num\n\n def set_conv_placeholder_weights(self, h5File, init_num):\n weight_num = init_num\n for i in range(self.layer_num):\n self.con_layers_map[i].set_init_values(h5File['weight_%s'%(weight_num)][:])\n weight_num += 1\n if self.is_need_weights:\n self.set_placeholder_weights(h5File['weight_%s'%(weight_num)][:])\n weight_num += 1\n return weight_num\n\n\nclass CNN(object):\n \"\"\"a Convolution neural network model\n Args:\n # IMAGE_SIZE\n # NUM_CHANNELS\n # NUM_LABELS\n # BATCH_SIZE=None\n # a parameters above are used for defining the image input node\n # in the first time, i want to make a model like keras, however,\n # i found it a lit of bit difficult. so, i just make a cnn model instead.\n # in the near future, i would like to make a residual cnn\n \"\"\"\n def __init__(self, IMAGE_SIZE, NUM_CHANNELS, NUM_LABELS, BATCH_SIZE=None):\n self.image_size = IMAGE_SIZE\n self.label_size = NUM_LABELS\n self.batch_size = BATCH_SIZE\n\n self.last_layer_size = IMAGE_SIZE\n self.last_core_size = NUM_CHANNELS\n\n self.num_layer = 0\n self.layer_map = {}\n\n self.weight_list = []\n self.bias_list = []\n\n self.input_node = tf.placeholder(tf.float32,\n shape=(BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))\n\n self.label_node = tf.placeholder(tf.float32,\n shape=(BATCH_SIZE, NUM_LABELS))\n\n # initial learning rate\n self.lr_value = 0.01\n self.placeholder_mode = False\n\n # self.fc1_weights = None\n # self.fc1_biases = None\n # self.fc2_weights = None\n # self.fc2_biases = None\n\n self.batch_size = tf.placeholder(dtype=tf.int32)\n self.gobal_step = tf.Variable(0, trainable=False)\n self.decay_size = tf.placeholder(dtype=tf.int32)\n self.momentum = tf.Variable(0.8)\n self.learning_rate = tf.placeholder(dtype=tf.float32)\n\n ## add convpool layer\n def add(self, layer):\n self.layer_map[self.num_layer] = layer\n # self.compute_last_layer_size(layer)\n self.num_layer += 1\n\n\n ## actually init session\n def make_net(self, mode=\"softmax\"):\n if IS_GPU:\n self.create_net(mode)\n else:\n with tf.device(\"/cpu:0\"):\n self.create_net(mode)\n\n def load_init_weights(self, hdf5_dset):\n weight_num = 0\n bias_num = 0\n for i in range(0,self.num_layer):\n if self.layer_map[i].layer_type != LAYER_TYPE[2] and self.layer_map[i].layer_type != LAYER_TYPE[3]:\n self.layer_map[i].set_init_values(hdf5_dset['weight_%s'%(weight_num)][:])\n weight_num += 1\n elif self.layer_map[i].layer_type == LAYER_TYPE[3]:\n self.layer_map[i].set_init_values(hdf5_dset['weight_%s'%(weight_num)][:],\n hdf5_dset['bias_%s'%(bias_num)][:])\n weight_num += 1\n bias_num += 1\n\n def load_weights(self, hdf5_dset):\n weight_num = 0\n bias_num = 0\n for i in range(0,self.num_layer):\n if self.layer_map[i].layer_type == LAYER_TYPE[0] and self.layer_map[i].layer_type == LAYER_TYPE[1]:\n self.layer_map[i].set_placeholder_weights(hdf5_dset['weight_%s'%(weight_num)][:])\n weight_num += 1\n elif self.layer_map[i].layer_type == LAYER_TYPE[3]:\n self.layer_map[i].set_placeholder_weights(hdf5_dset['weight_%s'%(weight_num)][:])\n self.layer_map[i].set_placeholder_biases(hdf5_dset['bias_%s'%(bias_num)][:])\n weight_num += 1\n bias_num += 1\n elif self.layer_map[i].layer_type == LAYER_TYPE[4]:\n weight_num = self.layer_map[i].set_conv_placeholder_weights(hdf5_dset, weight_num)\n\n def save_weights(self, file_name):\n with h5py.File(file_name, 'w') as f:\n weight_num = 0\n bias_num = 0\n for i in range(0,self.num_layer):\n if self.layer_map[i].layer_type == LAYER_TYPE[0] and self.layer_map[i].layer_type == LAYER_TYPE[1]:\n # weight = self.layer_map[i].conv_weights.eval()\n # name = \"weight_%s\" % str(weight_num)\n # f.create_dataset(name, data=weight)\n weight_num = self.layer_map[i].save_weights(f, weight_num)\n\n elif self.layer_map[i].layer_type == LAYER_TYPE[3]:\n weight = self.layer_map[i].fc_weights.eval()\n bias = self.layer_map[i].fc_biases.eval()\n f.create_dataset(\"weight_%s\" % str(weight_num), data=weight)\n f.create_dataset(\"bias_%s\"%str(bias_num), data=bias)\n weight_num += 1\n bias_num += 1\n\n elif self.layer_map[i].layer_type == LAYER_TYPE[4]:\n weight_num = self.layer_map[i].save_weights(f, weight_num)\n\n def set_learning_rate(self, lr):\n self.lr_value = lr\n\n # initialize every layer\n def compile_net(self):\n for i in range(self.num_layer):\n self.layer_map[i].init_net()\n\n # in order to use GPU or CPU selectively\n def create_net(self, mode=\"Softmax\"):\n self.compile_net()\n\n last_layer_type = \"\"\n for i in range(self.num_layer):\n if i == 0 and self.layer_map[i].layer_type != LAYER_TYPE[2]:\n next_input = tf.nn.relu(self.layer_map[i].get_output(self.input_node))\n last_layer_type = self.layer_map[i].layer_type\n elif i == (self.num_layer-1):\n next_input = self.layer_map[i].get_output(next_input)\n elif i < (self.num_layer-1) and (last_layer_type == LAYER_TYPE[1] or last_layer_type == LAYER_TYPE[0]\n or last_layer_type == LAYER_TYPE[2]) \\\n and self.layer_map[i].layer_type == LAYER_TYPE[3]:\n shape = next_input.get_shape().as_list()\n reshape = tf.reshape(\n next_input,\n [-1, shape[1] * shape[2] * shape[3]])\n next_input = tf.nn.relu(self.layer_map[i].get_output(reshape))\n elif self.layer_map[i].layer_type == LAYER_TYPE[2]:\n next_input = self.layer_map[i].get_output(next_input)\n else:\n next_input = tf.nn.relu(self.layer_map[i].get_output(next_input))\n last_layer_type = self.layer_map[i].layer_type\n\n self.logits = next_input\n\n if mode == \"softmax\":\n self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n self.logits, self.label_node))\n self.pred = tf.nn.softmax(self.logits)\n elif mode == \"regression\":\n self.loss = tf.reduce_mean((self.label_node - self.logits)**2)\n self.pred = self.logits\n\n self.optimizer = tf.train.MomentumOptimizer(self.learning_rate, self.momentum\n ).minimize(self.loss,\n aggregation_method=tf.AggregationMethod.EXPERIMENTAL_TREE,\n global_step=None)\n\n\n\n def fit(self, inputX, inputY, epoch, batch_size, lr=0.01, decay_size=20, verbose=False):\n lost = 0\n for i in range(epoch):\n feed_dict = {self.input_node: inputX,\n self.label_node: inputY,\n self.batch_size: batch_size,\n self.decay_size: decay_size,\n self.learning_rate: lr}\n\n [ _, l ] = SessionHandler().get_session().run([self.optimizer, self.loss],\n feed_dict=feed_dict)\n lost += l\n if verbose:\n print(\"loss is \"+str(l))\n return lost\n\n\n def get_predict(self, input):\n return self.pred.eval(session=SessionHandler().get_session(),\n feed_dict = {self.input_node:input})\n\n\n\n def release(self):\n self.session.close()\n\n def init_vars(self):\n SessionHandler().initialize_variables()\n\n#\ndef get_predict_by_batch(model, test_x, batch_size):\n iter = math.ceil(test_x.shape[0] / batch_size)\n pred_list = []\n\n for i in range(iter-1):\n batch_ind = i * batch_size\n batch_ind_plus1 = (i+1) * batch_size\n batch_x = test_x[batch_ind:batch_ind_plus1,:,:,:]\n batch_pred = model.get_predict(batch_x)\n pred_list.append(batch_pred)\n batch_pred = model.get_predict(test_x[batch_ind_plus1:,:,:,:])\n pred_list.append(batch_pred)\n\n pred = np.concatenate(pred_list)\n return pred\n\ndef error_rate(predictions, labels):\n \"\"\"Return the error rate based on dense predictions and 1-hot labels.\"\"\"\n return 100.0 - (\n 100.0 *\n np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) /\n predictions.shape[0])\n\n\ndef get_cnn_model():\n \"\"\"\n get the policy model. i would like to make it like keras, just need input json.\n this function is totally handmake, it was so ugly\n Returns:\n\n \"\"\"\n try:\n if not SessionHandler().is_session_init:\n SessionHandler().set_default()\n except:\n SessionHandler().set_default()\n\n state_size = 19\n cnn = CNN(state_size, 3 ,state_size**2)\n\n next_core_size = 4\n cnn.add(ConvLayer([2,2,3,next_core_size],\"VALID\"))\n for i in range(5):\n cnn.add(ConvLayer([3,3,next_core_size,next_core_size*2],\"SAME\"))\n next_core_size *=2\n cnn.add(ConvLayer([1,1,next_core_size,next_core_size],\"SAME\"))\n cnn.add(FullForwardLayer(128*18*18,512))\n cnn.add(FullForwardLayer(512,361))\n\n cnn.make_net()\n cnn.init_vars()\n return cnn\n\n# like above\ndef get_cnn_value_model(weight_dir=None):\n try:\n if not SessionHandler().is_session_init:\n SessionHandler().set_default()\n except:\n SessionHandler().set_default()\n\n weights_dict = {}\n\n if weight_dir is None:\n for i in range(8):\n weights_dict[\"weight_%s\"%i] = None\n for i in range(2):\n weights_dict[\"bias_%s\"%i] = None\n else:\n dset = h5py.File(weight_dir, 'r')\n for name in dset:\n weights_dict[name] = dset[name][:]\n dset.close()\n\n state_size = 19\n cnn = CNN(state_size, 3 ,1)\n\n next_core_size = 4\n cnn.add(ConvLayer([2,2,3,next_core_size],\"VALID\", weights=weights_dict['weight_0']))\n for i in range(5):\n cnn.add(ConvLayer([3,3,next_core_size,next_core_size*2],\"SAME\", weights=weights_dict['weight_%s'%(i+1)]))\n next_core_size *=2\n cnn.add(ConvLayer([1,1,next_core_size,next_core_size],\"SAME\" ,weights=weights_dict['weight_%s'%(i+2)]))\n cnn.add(FullForwardLayer(128*18*18,512, weights=weights_dict['weight_%s'%(i+3)], biases=weights_dict['bias_0']))\n cnn.add(FullForwardLayer(512,1))\n\n cnn.make_net(\"regression\")\n cnn.init_vars()\n return cnn\n\n# for testing the class made by tensorflow\n\ndef test_data():\n digit = np.loadtxt(\"../static/digitInputOutput.txt\",dtype=np.float32)\n np.random.shuffle(digit)\n train_size = 4000\n train_X = digit[:train_size,0:400].reshape((train_size,20,20,1))\n train_Y = digit[:train_size,400:]\n\n test_X = digit[train_size:,0:400].reshape((5000-train_size,20,20,1))\n test_Y = digit[train_size:,400:]\n return (train_X, train_Y, test_X, test_Y)\n\ndef test_cnn():\n\n X, Y, test_X, test_Y = test_data()\n\n NUM_CHANNELS = 1\n BATCH_SIZE = 200\n\n dset = h5py.File('../weights/test_w.hdf5','r')\n weights_0 = dset['weight_0'][:]\n\n\n cnn = CNN(20,NUM_CHANNELS,10)\n next_cores_size = 8\n cnn.add(ConvLayer(filter_shape=[3,3,NUM_CHANNELS,8]))\n cnn.add(ConvLayer(filter_shape=[3,3,8,16]))\n cnn.add(ConvLayer(filter_shape=[3,3,16,32]))\n cnn.add(PoolLayer())\n cnn.add(FullForwardLayer(32*10*10,512))\n cnn.add(FullForwardLayer(512,10))\n\n cnn.make_net()\n cnn.init_vars()\n # fc1_pre = cnn.fc1_weights.eval()\n\n\n for epoch in range(1):\n print(\"epoch %d\" % epoch)\n for i in range(20):\n tmpX = X[i*200:(i+1)*200,:,:,:].reshape((200,20,20,1))\n tmpY = Y[i*200:(i+1)*200,:]\n\n cnn.fit(tmpX,tmpY,1,BATCH_SIZE, decay_size=20)\n pred = get_predict_by_batch(cnn, test_X, BATCH_SIZE)\n er = error_rate(pred, test_Y)\n print(\"test error: %s\" % str(er))\n\n\n cnn.load_weights(dset)\n # fc1_pre = cnn.fc1_weights.eval()\n tf.get_default_graph().finalize()\n\n for epoch in range(10):\n print(\"epoch %d\" % epoch)\n for i in range(20):\n tmpX = X[i*200:(i+1)*200,:,:,:].reshape((200,20,20,1))\n tmpY = Y[i*200:(i+1)*200,:]\n\n cnn.fit(tmpX,tmpY,1,BATCH_SIZE, decay_size=20, lr=0.005)\n # print(tf.get_default_graph().)\n pred = get_predict_by_batch(cnn, test_X, BATCH_SIZE)\n er = error_rate(pred, test_Y)\n print(\"test error: %s\" % str(er))\n\n\ndef test_resnet():\n NUM_CHANNELS = 1\n BATCH_SIZE = 200\n\n X, Y, test_X, test_Y = test_data()\n resnet = CNN(20,NUM_CHANNELS,10)\n next_cores_size = 8\n\n\n shortcut1 = ShortcutLayer()\n shortcut1.add(ConvLayer(filter_shape=[3,3,8,16]))\n shortcut1.add(ConvLayer(filter_shape=[3,3,16,16]))\n shortcut2 = ShortcutLayer()\n shortcut2.add(ConvLayer(filter_shape=[3,3,16,16]))\n shortcut2.add(ConvLayer(filter_shape=[3,3,16,16]))\n\n shortcut3 = ShortcutLayer()\n shortcut3.add(ConvLayer(filter_shape=[3,3,16,32]))\n shortcut3.add(ConvLayer(filter_shape=[3,3,32,32]))\n shortcut4 = ShortcutLayer()\n shortcut4.add(ConvLayer(filter_shape=[3,3,32,32]))\n shortcut4.add(ConvLayer(filter_shape=[3,3,32,32]))\n\n resnet.add(ConvLayer(filter_shape=[3,3,NUM_CHANNELS,8]))\n resnet.add(PoolLayer())\n resnet.add(shortcut1)\n resnet.add(shortcut2)\n resnet.add(shortcut3)\n resnet.add(shortcut4)\n resnet.add(PoolLayer())\n resnet.add(FullForwardLayer(32*5*5,512))\n resnet.add(FullForwardLayer(512,10))\n resnet.make_net()\n resnet.init_vars()\n\n dset = h5py.File(\"/home/kyoka/python_ws/gyygo/homepage/weights/test_resnet_w.hdf5\",'r')\n resnet.load_weights(dset)\n\n for epoch in range(10):\n print(\"epoch %d\" % epoch)\n for i in range(20):\n tmpX = X[i*200:(i+1)*200,:,:,:].reshape((200,20,20,1))\n tmpY = Y[i*200:(i+1)*200,:]\n\n resnet.fit(tmpX,tmpY,1,BATCH_SIZE, decay_size=20)\n pred = get_predict_by_batch(resnet, test_X, BATCH_SIZE)\n er = error_rate(pred, test_Y)\n print(\"test error: %s\" % str(er))\n\n dset.close()\n resnet.save_weights(\"/home/kyoka/python_ws/gyygo/homepage/weights/test_resnet_w.hdf5\")\n\nif __name__ == '__main__':\n SessionHandler().set_default()\n\n test_resnet()\n\n","sub_path":"homepage/src/nn_utils.py","file_name":"nn_utils.py","file_ext":"py","file_size_in_byte":25044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629744503","text":"\n\nfrom conans import ConanFile, CMake, tools\nimport shutil\nimport os\n\nclass FmtConan(ConanFile):\n name = \"fmt\"\n version = \"3.0.1\"\n license = \"BSD\"\n url = \"https://github.com/barcharcraz/conan-packages\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"shared\": [True, False],\n \"tests\": [True, False],\n \"docs\": [True, False]}\n default_options = \"shared=False\", \"tests=False\", \"docs=False\"\n generators = \"cmake\"\n \n def source(self):\n zip_name = f\"{self.name}-{self.version}.zip\"\n tools.download(f\"https://github.com/fmtlib/fmt/archive/{self.version}.zip\", zip_name)\n tools.unzip(zip_name)\n shutil.move(f\"{self.name}-{self.version}\", f\"{self.name}\")\n os.unlink(zip_name)\n\n def build(self):\n cmake = CMake(self.settings)\n cmake_options = [\n f\"-DCMAKE_INSTALL_PREFIX={self.package_folder}\",\n f\"-DBUILD_SHARED_LIBS={self.options.shared}\",\n f\"-DFMT_INSTALL=ON\",\n f\"-DFMT_TEST={self.options.tests}\",\n f\"-DFMT_DOCS={self.options.docs}\"\n ]\n self.run(f\"cmake {self.name} {cmake.command_line} {' '.join(cmake_options)}\")\n self.run(f\"cmake --build . --target install {cmake.build_config}\")\n \n def package(self):\n cmake = CMake(self.settings)\n self.run(f\"cmake --build . --target install {cmake.build_config}\")","sub_path":"fmt/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"358908517","text":"from telethon import events\n\n\"\"\"Command: .bigspam DO NOT TRY THIS WITH YOUR ACCOUNT\n\ntelethon.errors.rpcerrorlist.FloodWaitError: A wait of 280 seconds is required\"\"\"\n\n\n@borg.on(events.NewMessage(pattern=r\"\\.bigspam (.*)\", outgoing=True))\nasync def _(event):\n if event.fwd_from:\n return\n input_str = event.pattern_match.group(1)\n for _ in range(int(input_str)):\n m = await event.respond(\"https://github.com/prono69/PepeBot\")\n await m.delete()\n \"\"\"if \"|\" in input_str:\n counter, spam_text = input_str.split(\"|\")\n shiiinabot = \"\\u2060\"\n for i in range(4000):\n shiiinabot += \"\\u2060\"\n message_text = shiiinabot + spam_text\n await event.edit(message_text)\n for i in range(int(counter)):\n time.sleep(0.3)\n await event.respond(message_text)\n await event.delete()\n else:\n await event.edit(\"send me a message in the format `.bigspam count | spam message` and admins won't see it in recent actions\" +\n \" \\n Courtesy: @shiiinabot\")\"\"\"\n","sub_path":"stdplugins/bigspam.py","file_name":"bigspam.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"363646103","text":"from typing import *\nimport os\nimport csv\nimport logging\nimport pickle\nimport loompy\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport cytograph as cg\nimport luigi\nimport numpy_groupies.aggregate_numpy as npg\nimport scipy.stats\nimport adolescent_mouse as am\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\n\n\nclass OligosL6(luigi.Task):\n\t\"\"\"\n\tExtract and plot oligos cell types\n\t\"\"\"\n\n\tdef requires(self) -> luigi.Task:\n\t\treturn am.PoolL5()\n\n\tdef output(self) -> luigi.Target:\n\t\treturn luigi.LocalTarget(os.path.join(am.paths().build, f\"F_Oligos\"))\n\t\t\n\tdef run(self) -> None:\n\t\tlogging = cg.logging(self, True)\n\t\twith self.output().temporary_path() as out_dir:\n\t\t\tlogging.info(\"Exporting oligo cell types\")\n\t\t\tif not os.path.exists(out_dir):\n\t\t\t\tos.mkdir(out_dir)\n\t\t\twith loompy.connect(self.input().fn) as ds:\n\t\t\t\tcelltypes = [\n\t\t\t\t\t\"COP1\",\n\t\t\t\t\t\"COP2\",\n\t\t\t\t\t\"NFOL2\",\n\t\t\t\t\t\"NFOL1\",\n\t\t\t\t\t\"OPC\"\n\t\t\t\t]\n\t\t\t\tselected = np.array([], dtype='int')\n\t\t\t\tfor ct in celltypes:\n\t\t\t\t\tprint(ct)\n\t\t\t\t\tcells = np.where(ds.ca.ClusterName == ct)[0]\n\t\t\t\t\tif cells.shape[0] > 820:\n\t\t\t\t\t\tcells = np.random.choice(cells, size=820, replace=False)\n\t\t\t\t\tselected = np.union1d(selected, cells)\n\n\t\t\t\tngfile = os.path.join(out_dir, \"F_Oligos.loom\")\n\t\t\t\tfor (_, _, view) in ds.scan(items=selected, axis=1):\n\t\t\t\t\tloompy.create_append(ngfile, view.layers, view.ra, view.ca)\n\t\t\t\n\t\t\twith loompy.connect(ngfile) as ds:\n\t\t\t\tlogging.info(\"Learning the manifold\")\n\t\t\t\tml = cg.ManifoldLearning2(gtsne=False, alpha=1)\n\t\t\t\t(knn, mknn, tsne) = ml.fit(ds)\n\t\t\t\tds.col_graphs.KNN = knn\n\t\t\t\tds.col_graphs.MKNN = mknn\n\t\t\t\tds.ca._X = tsne[:, 0]\n\t\t\t\tds.ca._Y = tsne[:, 1]\n\n\t\t\t\tfig = plt.figure(figsize=(3, 3))\n\t\t\t\tax = fig.add_axes([0, 0, 1, 1])\n\t\t\t\tlc = LineCollection(zip(tsne[mknn.row], tsne[mknn.col]), linewidths=0.25, zorder=0, color='grey', alpha=0.1)\n\t\t\t\tax.add_collection(lc)\n\t\t\t\tax.axis('off')\n\t\t\t\tcolors = cg.colorize(np.unique(ds.ca.ClusterName))\n\t\t\t\tix = 0\n\t\t\t\tfor ct in np.unique(ds.ca.ClusterName):\n\t\t\t\t\tcells = (ds.ca.ClusterName == ct)\n\t\t\t\t\tplt.scatter(x=ds.ca._X[cells], y=ds.ca._Y[cells], s=40, c=colors[ix, :], marker='.', label=ct, alpha=0.5, lw=0)\n\t\t\t\t\tix += 1\n\t\t\t\t\tlgnd = ax.legend(fontsize=10, labelspacing=0.2, loc=\"upper left\", bbox_to_anchor=(1, 1), frameon=False)\n\t\t\t\t\tfor handle in lgnd.legendHandles:\n\t\t\t\t\t\thandle.set_sizes([250])\n\t\t\t\t\t\thandle.set_alpha(1)\n\t\t\t\tplt.savefig(os.path.join(out_dir, \"Fig_Oligos_Types.png\"), dpi=600, transparent=True, bbox_extra_artists=(lgnd,), bbox_inches='tight')\n\t\t\t\tplt.close()\n\n\t\t\t\tfig = plt.figure(figsize=(3, 3))\n\t\t\t\tax = fig.add_axes([0, 0, 1, 1])\n\t\t\t\tax.axis('off')\n\t\t\t\tplt.scatter(x=ds.ca._X, y=ds.ca._Y, s=40, c=cg.colors75[(ds[ds.ra.Gene == \"Cdk1\", :][0] != 0).astype('int')], marker='.', label=ct, alpha=0.5, lw=0)\n\t\t\t\tplt.savefig(os.path.join(out_dir, \"Fig_Oligos_Cdk1.png\"), dpi=600, transparent=True, bbox_inches='tight')\n","sub_path":"adolescent_mouse/adolescent_L6/oligos_L6.py","file_name":"oligos_L6.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"25649783","text":"# ====| OUT/LOUD - Flask Server |====\n\n# TODO: HOW TO OSC IF IP ISN'T LOCALHHOST??????\n\nfrom flask import Flask, render_template, request, url_for, jsonify, redirect\nimport random\nimport time\n#import pyttsx\nimport sys\nimport socket\n\nfrom pythonosc import osc_message_builder, udp_client, osc_bundle_builder\n\napp = Flask(__name__)\n\nip = \"127.0.0.1\"\nip2 = \"10.226.10.21\"\nip3 = 'localhost'\nport = 2046\n\n#sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nclient = udp_client.UDPClient(ip3, port)\n\ndef sendSimple(msg):\n client.send_message(\"/test\", msg.encode())\n print(\"send\")\n\ndef sendMult(add, *msg):\n global client\n message = osc_message_builder.OscMessageBuilder(address=add)\n\n for elem in msg:\n print('Element:', elem)\n message.add_arg(elem)\n\n message = message.build()\n client.send(message)\n\nstate = 'a'\n\ncontent = {\n 'a': {\n 'robot': [],\n 'calls': [],\n 'poll': {\n 'b': {\n 'options': ['yay', 'keep it up!', 'you are great', 'keep going', 'stick with it', 'you are so good'],\n 'count' : 0,\n 'list' : []\n },\n 'c': {\n 'options':['no no no', 'stop', \"don't waste your life\", 'this is pointless', 'why are you doing this?', 'stupid robot'],\n 'count' : 0,\n 'list' : []\n }\n },\n 'period': 90\n },\n 'b': {\n 'robot': [],\n 'calls': [],\n 'poll': {\n 'd': {\n 'options':['you can do this', 'outgrow your shell!', 'no risk no gain', 'time to shine', 'do it!', 'believe yourself'],\n 'count' : 0,\n 'list' : []\n },\n 'e': {\n 'options':['stay in your comfort zone', 'what if you fail?', 'you could never...', \"don't even think about it\", 'are you mad?', 'you must be joking'],\n 'count' : 0,\n 'list' : []\n }\n },\n 'period': 90\n },\n 'c': {\n 'robot': [],\n 'calls': [],\n 'poll': {\n 'e': {\n 'options':['stay in your comfort zone', 'what if you fail?', 'you could never...', \"don't even think about it\", 'are you mad?', 'you must be joking'],\n 'count' : 0,\n 'list' : []\n },\n 'f': {\n 'options':['screw this!', \"you'll find something better!\", 'stop wasting your time and go!', 'this job is killing you', 'choose happiness!', 'you are built for greater things'],\n 'count' : 0,\n 'list' : []\n }\n },\n 'period': 90\n },\n 'd': {\n 'robot': [],\n 'calls': []\n },\n 'e': {\n 'robot': [],\n 'calls': []\n },\n 'f': {\n 'robot': [],\n 'calls': []\n }\n }\n\ntimestamp = 0\nperiod = 90;\n\n@app.route('/')\ndef root():\n return render_template(\"index.html\")\n\n@app.route('/api/poll/', methods=['GET', 'POST'])\ndef poll():\n global timestamp\n global period\n global state\n\n try:\n if request.method == 'POST':\n form = request.form\n choice = form['choice']\n word = form['word']\n print(word, choice)\n\n content[state]['poll'][choice]['count'] += 1\n lst = content[state]['poll'][choice]['list']\n lst.append(word)\n\n keys = []\n p = content[state]['poll']\n for key in p:\n keys.append(key)\n\n index = -1;\n if keys[0] == choice:\n index = 0\n elif keys[1] == choice:\n index = 1\n\n sendMult('/text', index, word)\n\n if time.clock() >= timestamp + period:\n reset()\n p = content[state]['poll']\n\n for key in p:\n keys.append(key)\n\n if p[keys[0]]['count'] > p[keys[1]]['count']:\n state = keys[0]\n else:\n state = keys[1]\n timestamp = time.clock()\n \n keys = []\n p = content[state]['poll']\n for key in p:\n keys.append(key)\n \n n1 = p[keys[0]]['count']\n n2 = p[keys[1]]['count']\n print(n1, ':', n2)\n\n\n res = []\n \n pollObj = content[state]['poll']\n for item in pollObj:\n text = pollObj[item]['options']\n vol = (time.clock()-timestamp)/period\n if vol > 1:\n vol = 1.0\n res.append({\n 'key': item,\n 'text': random.choice(text),\n 'volume': vol\n })\n\n return jsonify(res)\n except KeyError:\n res = [{\n 'key': '0',\n 'text': 'Thank You',\n 'volume': 0\n },{\n 'key': '0',\n 'text': 'Robot Has Decided',\n 'volume': 0\n }]\n return jsonify(res)\n\n@app.route('/api/override/', methods=['GET', 'POST'])\ndef override():\n global timestamp\n global period\n global state\n\n if request.method == 'POST':\n reset()\n ovr = int(request.form['override'])\n print(ovr)\n\n states = ['a', 'b', 'c', 'd', 'e', 'f']\n if ovr < 6:\n state = states[ovr]\n else:\n print('RING RING')\n\n jsUrl = url_for('static', filename='override.js')\n cssUrl = url_for('static', filename='style.css')\n oCssUrl = url_for('static', filename = 'override.css')\n saUrl = url_for('static', filename = 'superagent.js')\n\n return render_template(\"override.html\", js=jsUrl, css = cssUrl, sa = saUrl, oCss = oCssUrl)\n\n@app.route('/api/reset')\ndef resetRoute():\n reset()\n return redirect('/')\n\n@app.errorhandler(404)\ndef four_oh_four(err):\n return redirect('/')\n\ndef reset():\n timestamp = time.clock()\n sendMult('/reset', 1)\n \n for key in content:\n try:\n pollThing = content[key]['poll']\n for option in pollThing:\n thing = pollThing[option]\n thing['count'] = 0\n thing['list'] = []\n except KeyError:\n continue","sub_path":"individuals/mateo/out_loud/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"447655924","text":"import scipy as sp\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport scipy.interpolate as spi # 插值专用函数\r\nimport scipy.integrate as sci # 积分专用函数\r\nimport scipy.optimize as spo # 优化专用函数\r\n\r\nx = np.linspace(-2 * np.pi, 2 * np.pi, 11)\r\nf = lambda x: np.sin(x) + 0.5 * x\r\ntck = spi.splrep(x, f(x), k=1)\r\niy = spi.splev(x, tck)\r\n# 利用matplotlib进行可视化\r\nplt.figure(figsize=(8, 4), dpi=80)\r\nx_ = np.linspace(-2 * np.pi, 2 * np.pi, 1000)\r\nplt.plot(x_, f(x_), color='blue', linewidth=2.5, label='true value')\r\nplt.scatter(x, iy, 30, color='red', label='interpolated value')\r\nplt.legend(loc=0)\r\nplt.grid(True)\r\nplt.xlabel('x')\r\nplt.ylabel('f(x)')\r\nplt.show()\r\n\r\nxd = np.linspace(1, 3, 50)\r\niyd = spi.splev(xd, tck)\r\ntck = spi.splrep(x, f(x), k=3)\r\niyd = spi.splev (xd, tck)\r\nprint(xd, '\\n\\n,iyd')\r\nplt.figure(figsize=(8, 4), dpi=80)\r\nplt.plot(xd, f(xd), color='blue', linewidth=2.5, label='true value')\r\nplt.scatter(xd, iyd, 30, color='red', label='interpolated value')\r\nplt.legend(loc=0)\r\nplt.grid(True)\r\nplt.xlabel('x')\r\nplt.ylabel('f(x)')\r\nplt.show()\r\n","sub_path":"编程学习/code/scipy_test.py","file_name":"scipy_test.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"116019209","text":"#-----------------------------------------------------------------------------\n# consumer_missingkillmails.py\n# https://github.com/brentnowak/spotmarket\n#-----------------------------------------------------------------------------\n# Version: 0.1\n# - Initial release\n#-----------------------------------------------------------------------------\n\nfrom _utility import *\nfrom requests.exceptions import ConnectionError, ChunkedEncodingError\nimport requests.packages.urllib3\nfrom _consumer_kills import *\n\nrequests.packages.urllib3.disable_warnings()\n# Suppress InsecurePlatformWarning messages\n\nservice = \"consumer_missingkillmails.py\"\n\ntotal = gettotalkmemptyvalues()\n\nwhile getkmemptyvalue() != None:\n try:\n results = getkmemptyvalue()\n\n url = 'https://zkillboard.com/api/killID/' + str(results['killID']) + \"/\"\n headers = {'user-agent': 'github.com/brentnowak/spotmarket'}\n\n try:\n r = requests.get(url, headers=headers)\n except (ConnectionError, ChunkedEncodingError) as e:\n print(e)\n else:\n for kill in json.loads(r.text):\n if kill['killID'] == results['killID']: # Check to confirm we have the correct Killmail\n setkmtotalvalue(results['killID'], kill['zkb']['totalValue'])\n print(\"[total:\" + str(total) + \"][killID:\" + str(results['killID']) + \"][totalValue:\" + str(kill['zkb']['totalValue']) + \"]\")\n total -= 1\n except Exception as e:\n print(e)\n\nprint(\"[km][all killmail values populated]\")\n\n","sub_path":"consumer_missingkillmails.py","file_name":"consumer_missingkillmails.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"463774641","text":"\ndef data_type(a):\n if type(a) == str:\n return len(a)\n \n elif a == None:\n return (\"no value\")\n \n elif type(a) == bool:\n return bool(a)\n \n elif type(a) == int:\n if a > 100:\n return (\"more than 100\")\n elif a<100:\n return(\"less than 100\")\n elif a==100:\n return(\"equal to 100\")\n \n elif type(a) == type([]):\n if len(a)==3:\n return a[2]\n else:\n return None ","sub_path":"DAY 2/data_types.py","file_name":"data_types.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8208746","text":"# This file is part of Code Cropper\n# The tool has been designed and developed by Eng. Gervasio Calderon\n#\n# Copyright (c) 2022, Core Security Technologies\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials\n# provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nimport os\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nwith open(os.path.join(os.path.dirname(__file__), \"code_cropper/VERSION\"), 'r') as vf:\n the_version = vf.read().strip()\n\nsetup(\n name = \"code_cropper\",\n version = the_version,\n packages=[\"code_cropper\"],\n author='Gervasio Calderon',\n author_email='gervicalder@gmail.com',\n tests_require = 'nose',\n test_suite = 'tests',\n package_data={\n # Export VERSION, for use in the client code.\n '': ['VERSION']\n },\n zip_safe=False\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"308900350","text":"\n\n#calss header\nclass _INTERFERENCE():\n\tdef __init__(self,): \n\t\tself.name = \"INTERFERENCE\"\n\t\tself.definitions = [u'an occasion when someone tries to interfere in a situation: ', u'noise or other electronic signals that stop you from getting good pictures or sound on a television or radio']\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/_interference.py","file_name":"_interference.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"146114839","text":"import pygame\nfrom objects.player import Player\n\n\nclass Game:\n def __init__(self):\n self._running = True\n self._screen = None\n self._display = None\n self._player = None\n self._sprite_group = None\n self._clock = None\n\n def on_render(self):\n self._display.fill((123, 13, 3))\n self._sprite_group.update()\n self._sprite_group.draw(self._display)\n self._screen.blit(pygame.transform.scale(self._display, (800, 600)), (0, 0))\n pygame.display.update()\n\n def on_loop(self):\n self._player.on_update()\n self._clock.tick(60)\n\n def on_init(self):\n pygame.init()\n self._screen = pygame.display.set_mode((800, 600))\n self._display = pygame.Surface((400, 300))\n self._clock = pygame.time.Clock()\n self._sprite_group = pygame.sprite.Group()\n self._player = Player()\n\n self._sprite_group.add(self._player)\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n\n def on_execute(self):\n self.on_init()\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.on_loop()\n self.on_render()\n\n\nif __name__ == '__main__':\n game = Game()\n game.on_execute()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"52987770","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport logging\n\ntry:\n from . import utility\nexcept ImportError:\n import utility\n\nGraceDict = utility.GraceDict\nis_array = utility.is_array\n\n\nclass BaseDB(object):\n \"\"\"\n Implement database chain operation.\n\n After initialization with table name,use config_db to set connected database.\n\n In JOIN,use ### as table name prefix placeholder.\n\n If use SQL Server, param primary_key is necessary,used in the LIMIT implement tec.\n\n \"\"\"\n\n def __init__(self, table_name_prefix=\"\", debug=False, strict=True,\n cache_fields_name=True, grace_result=True):\n self.db = None\n self.table_name_prefix = table_name_prefix\n self.debug = debug\n self.strict = strict\n self.last_query = \"\" # latest executed sql\n self.cache_fields_name = cache_fields_name # when call get_fields_name\n self._cached_fields_name = {} # cached fields name\n self.grace_result = grace_result\n self.param_place_holder = \"%s\" # SQLite will use ?\n\n self._table = \"\"\n self._where = \"\"\n self._order_by = \"\"\n self._group_by = \"\"\n self._limit = \"\"\n self._inner_join = \"\"\n self._left_join = \"\"\n self._right_join = \"\"\n self._on = \"\"\n\n def _reset(self):\n \"\"\"reset param when call again\"\"\"\n # self._table = \"\" # keep table name\n self._where = \"\"\n self._order_by = \"\"\n self._group_by = \"\"\n self._limit = \"\"\n self._inner_join = \"\"\n self._left_join = \"\"\n self._right_join = \"\"\n self._on = \"\"\n self.last_query = \"\" # latest executed sql\n\n def connect(self, config_dict=None):\n \"\"\"\n set a connected torndb.Connection\n\n :param config_dict: dict,config to connect database\n \"\"\"\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def execute(self, *args, **kwargs):\n \"\"\"execute SQL\"\"\"\n res = self.db.execute_return_detail(*args, **kwargs)\n self._reset() # reset param\n return res\n\n def executemany(self, *args, **kwargs):\n \"\"\"execute SQL with many lines\"\"\"\n res = self.db.executemany_return_detail(*args, **kwargs)\n self._reset() # reset param\n return res\n\n def query(self, *args, **kwargs):\n \"\"\"query SQL\"\"\"\n res = self.db.query_return_detail(*args, **kwargs)\n self._reset() # reset param\n return res\n\n def table(self, table_name=\"\", *args):\n \"\"\"\n If table_name is empty,use DB().select(\"now()\") will run SELECT now()\n \"\"\"\n # check table name prefix\n if self.table_name_prefix and not table_name.startswith(self.table_name_prefix):\n table_name += self.table_name_prefix\n\n self._table = table_name\n return self\n\n def where(self, condition):\n self._where = condition\n return self\n\n def order_by(self, condition):\n self._order_by = condition\n return self\n\n def limit(self, condition):\n self._limit = condition\n return self\n\n def group_by(self, condition):\n self._group_by = condition\n return self\n\n def join(self, condition):\n if self.table_name_prefix and \"###\" in condition:\n condition = condition.replace(\"###\", self.table_name_prefix)\n\n self._inner_join = condition\n return self\n\n def inner_join(self, condition):\n if self.table_name_prefix and \"###\" in condition:\n condition = condition.replace(\"###\", self.table_name_prefix)\n self._inner_join = condition\n return self\n\n def left_join(self, condition):\n if self.table_name_prefix and \"###\" in condition:\n condition = condition.replace(\"###\", self.table_name_prefix)\n self._left_join = condition\n return self\n\n def right_join(self, condition):\n if self.table_name_prefix and \"###\" in condition:\n condition = condition.replace(\"###\", self.table_name_prefix)\n self._right_join = condition\n return self\n\n def select(self, fields=\"*\"):\n \"\"\"\n fields is fields or native sql function,\n ,use DB().select(\"=now()\") will run SELECT now()\n \"\"\"\n condition_values = []\n if fields.startswith(\"`\"): # native function\n sql = self.gen_select_without_fields(fields[1:]) # 用于直接执行 mysql 函数\n else:\n condition_sql, condition_values = self.parse_condition()\n sql = self.gen_select_with_fields(fields, condition_sql)\n\n res = self.query(sql, *condition_values)\n self.last_query = res[\"query\"]\n if self.grace_result:\n res[\"data\"] = [GraceDict(i) for i in res[\"data\"]]\n\n return res[\"data\"]\n\n def gen_select_with_fields(self, fields, condition):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def gen_select_without_fields(self, fields):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def get(self, fields=\"*\"):\n \"\"\"will replace self._limit to 1\"\"\"\n self._limit = 1\n res = self.select(fields)\n return res[0] if res else {} # return dit type\n\n def update(self, dict_data=None):\n if not dict_data:\n return False\n fields, values = self.split_update_fields_value(dict_data)\n condition_sql, condition_values = self.parse_condition()\n sql = self.gen_update(fields, condition_sql)\n values += condition_values\n values = tuple(values)\n res = self.execute(sql, *values)\n self.last_query = res[\"query\"]\n return res\n\n def gen_update(self, fields, condition):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def split_update_fields_value(self, dict_data):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def insert(self, dict_data=None):\n \"\"\"\n insert one line,support rwo kinds data::\n\n 1. dict with key fields and values,the values of keys are list or tuple\n respectively all field name and value\n\n 2. dict, field name and value\n\n \"\"\"\n if not dict_data:\n return False\n\n keys = dict_data.keys()\n if \"fields\" in keys and \"values\" in keys: # split dict\n fields = \",\".join(dict_data[\"fields\"])\n values = [v for v in dict_data[\"values\"]]\n elif \"values\" in keys and len(keys) == 1: # split dict without fields\n fields = None\n values = [v for v in dict_data[\"values\"]]\n else: # natural dict\n fields = \",\".join(keys)\n values = dict_data.values()\n\n values_sign = \",\".join([self.param_place_holder for i in values])\n if fields:\n sql = self.gen_insert_with_fields(fields, values_sign)\n else:\n sql = self.gen_insert_without_fields(values_sign)\n\n res = self.execute(sql, *values)\n self.last_query = res[\"query\"]\n return res\n\n def gen_insert_with_fields(self, fields, condition):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def gen_insert_without_fields(self, fields):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def insert_many(self, dict_data=None):\n \"\"\"\n insert one line,,support rwo kinds data,such as insert,\n but the values should be wraped with list or tuple\n\n \"\"\"\n if not dict_data:\n return False\n\n fields = \"\" # all fields\n\n if is_array(dict_data):\n dict_data_item_1 = dict_data[0] # should be dict\n keys = dict_data_item_1.keys()\n fields = \",\".join(keys)\n values = [tuple(i.values()) for i in dict_data]\n values_sign = \",\".join([self.param_place_holder for f in keys])\n elif isinstance(dict_data, dict): # split dict\n keys = dict_data.get(\"fields\")\n if keys:\n if \"values\" in keys and len(keys) == 1: # split dict without fields\n fields = None\n else:\n fields = \",\".join(dict_data[\"fields\"])\n values = list([v for v in dict_data[\"values\"]])\n values_sign = \",\".join([self.param_place_holder for f in keys])\n else:\n logging.error(\"Param should be list or tuple or dict\")\n return False\n\n if fields:\n sql = self.gen_insert_with_fields(fields, values_sign)\n else:\n sql = self.gen_insert_without_fields(values_sign)\n\n values = tuple([tuple(i) for i in values]) # SQL Server support tuple only\n\n res = self.executemany(sql, values)\n self.last_query = res[\"query\"]\n return res\n\n def gen_insert_many_with_fields(self, fields, condition):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def gen_insert_many_without_fields(self, fields):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def delete(self):\n if self.strict and not self._where:\n logging.warning(\"without where condition,can not delete\")\n return False\n\n condition_sql, condition_values = self.parse_condition()\n sql = self.gen_delete(condition_sql)\n res = self.execute(sql, *condition_values)\n self.last_query = res[\"query\"]\n return res\n\n def gen_delete(self, condition):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def increase(self, field, step=1):\n \"\"\"number field Increase \"\"\"\n sql = self.gen_increase(field, str(step))\n res = self.execute(sql)\n self.last_query = res[\"query\"]\n return res\n\n def gen_increase(self, field, step):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def decrease(self, field, step=1):\n \"\"\"number field decrease \"\"\"\n sql = self.gen_decrease(field, str(step))\n res = self.execute(sql)\n self.last_query = res[\"query\"]\n return res\n\n def gen_decrease(self, field, step):\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def get_fields_name(self):\n \"\"\"return all fields of table\"\"\"\n if not self._table:\n return []\n\n if self.cache_fields_name and self._cached_fields_name.get(self._table):\n return self._cached_fields_name.get(self._table)\n else:\n res = self.db.query_return_detail(self.gen_get_fields_name())\n fields_name = res[\"column_names\"]\n self._cached_fields_name[self._table] = fields_name\n\n return fields_name\n\n def gen_get_fields_name(self):\n \"\"\"get one line from table\"\"\"\n raise NotImplementedError(\"You must implement it in subclass\")\n\n # shorthand\n t = table\n w = where\n ob = order_by\n l = limit\n gb = group_by\n j = join\n ij = inner_join\n lj = left_join\n rj = right_join\n s = select\n i = insert\n im = insert_many\n u = update\n d = delete\n inc = increase\n dec = decrease\n\n def parse_where_condition(self):\n \"\"\"\n parse where condition\n\n where condition is the most complex condition,let it alone\n \"\"\"\n raise NotImplementedError(\"You must implement it in subclass\")\n\n def parse_condition(self):\n \"\"\"\n parse all condition\n\n Calling parse_where_condition first is a good idea.\n \"\"\"\n raise NotImplementedError(\"You must implement it in subclass\")\n\n\nclass ChainDB(BaseDB):\n \"\"\"\n Common SQL class,Most basic SQL statements are same as each other.\n\n Implement the different only.\n \"\"\"\n\n def gen_select_with_fields(self, fields, condition):\n return \"SELECT {} FROM {} {};\".format(fields, self._table, condition)\n\n def gen_select_without_fields(self, fields):\n return \"SELECT {};\".format(fields)\n\n def split_update_fields_value(self, dict_data):\n \"\"\"\n generate str ike filed_name = %s and values,use for update\n :return: tuple\n \"\"\"\n fields = \"\"\n values = []\n for k in dict_data.keys():\n v = dict_data[k]\n\n if isinstance(v, str):\n if v.startswith(\"`\"): # native function without param\n v = v[1:]\n fields += \"{}={},\".format(k, v)\n else:\n fields += k + \"=\" + self.param_place_holder + \",\"\n values.append(v)\n elif is_array(v): # native function with param\n v0 = v[0]\n if v0.startswith(\"`\"):\n v0 = v0[1:]\n v0 = v0.replace(\"?\", self.param_place_holder)\n fields += \"{}={},\".format(k, v0)\n values.append(v[1])\n\n if fields:\n fields = fields[:-1]\n\n return fields, values\n\n def gen_update(self, fields, condition):\n return \"UPDATE {} SET {} {};\".format(self._table, fields, condition)\n\n def gen_insert_with_fields(self, fields, values_sign):\n return \"INSERT INTO {} ({}) VALUES ({});\".format(self._table, fields, values_sign)\n\n def gen_insert_without_fields(self, values_sign):\n return \"INSERT INTO {} VALUES ({});\".format(self._table, values_sign)\n\n def gen_insert_many_with_fields(self, fields, values_sign):\n return \"INSERT INTO {} ({}) VALUES ({});\".format(self._table, fields, values_sign)\n\n def gen_insert_many_without_fields(self, values_sign):\n return \"INSERT INTO {} VALUES ({});\".format(self._table, values_sign)\n\n def gen_delete(self, condition):\n return \"DELETE FROM {} {};\".format(self._table, condition)\n\n def gen_increase(self, field, step):\n \"\"\"number field Increase \"\"\"\n return \"UPDATE {} SET {}={}+{};\".format(self._table, field, field, step)\n\n def gen_decrease(self, field, step=1):\n \"\"\"number field decrease \"\"\"\n return \"UPDATE {} SET {}={}-{};\".format(self._table, field, field, str(step))\n\n def gen_get_fields_name(self):\n \"\"\"get one line from table\"\"\"\n return \"SELECT * FROM {} LIMIT 1;\".format(self._table)\n\n def parse_where_condition(self):\n \"\"\"parse where condition\"\"\"\n sql = \"\"\n sql_values = []\n if self._where:\n if isinstance(self._where, str):\n sql += \"WHERE\" + self._where\n elif isinstance(self._where, dict):\n where = \"\"\n and_or_length = 3 # length of AND or OR\n for k in self._where.keys():\n v = self._where[k]\n if is_array(v):\n and_or = \"AND\" # Parallel relationship\n v0 = v[0]\n if isinstance(v0, str) and v0.lower() == \"or\":\n and_or = \"OR\"\n and_or_length = 2\n v = v[1:]\n if len(v) == 1:\n v = v[0]\n v0 = None\n else:\n v0 = v[0]\n\n sign = v0.strip() if isinstance(v0, str) else \"\"\n\n if sign and sign[0] in (\"<\", \">\", \"!\"): # < <= > >= !=\n v1 = v[1]\n if isinstance(v1, str) and v1.startswith(\"`\"):\n # native mysql function starts with `\n # JOIN STRING DIRECT\n v1 = v1.replace(\"`\", \"\")\n if \"?\" in v1:\n v0 = v0.replace(\"?\", \"{}\")\n v = v0.format(*v[1:])\n where += \" {}{}{} {}\".format(k, sign, v, and_or)\n else:\n where += \" {}{}{} {}\".format(k, sign, self.param_place_holder, and_or)\n sql_values.append(v[1])\n elif sign.lower() in (\"in\", \"not in\", \"is not\"):\n # IN / NOT IN / IS NOT etc.\n # JOIN STRING DIRECT\n v1 = v[1]\n\n if is_array(v1):\n v1 = \",\".join(v1)\n where += \" {} {} ({}) {}\".format(k, sign, v1, and_or)\n else:\n where += \" {} {} {} {}\".format(k, sign, str(v1), and_or)\n\n elif sign.lower() == \"between\": # BETWEEN\n where += \" {} BETWEEN {} AND {} {}\".format(k,\n self.param_place_holder,\n self.param_place_holder,\n and_or)\n sql_values += [v[1], v[2]]\n elif sign.startswith(\"`\"): # native mysql function\n # JOIN STRING DIRECT\n v0 = v0.replace(\"`\", \"\")\n if \"?\" in v0:\n v0 = v0.replace(\"?\", \"{}\")\n v0 = v0.format(*v[1:])\n where += \" {}={} {}\".format(k, v0, and_or)\n\n else:\n if isinstance(v, str) and v.startswith(\"`\"): # native mysql function\n where += \" {}={} {}\".format(k, v[1:], and_or)\n else:\n where += \" {}={} {}\".format(k, self.param_place_holder, and_or)\n sql_values.append(v)\n else:\n and_or_length = 3\n if isinstance(v, str) and v.startswith(\"`\"): # native mysql function\n where += \" {}={} AND\".format(k, v[1:])\n else:\n where += \" {}={} AND\".format(k, self.param_place_holder)\n sql_values.append(v)\n if where:\n sql += \"WHERE\" + where[:0 - and_or_length] # trim the last AND / OR character\n\n return sql, sql_values\n\n def parse_condition(self):\n \"\"\"\n generate query condition\n \"\"\"\n sql, sql_values = self.parse_where_condition()\n\n if self._inner_join:\n sql += \" INNER JOIN {} ON {}\".format(self._inner_join, self._on)\n elif self._left_join:\n sql += \" LEFT JOIN {} ON {}\".format(self._left_join, self._on)\n elif self._right_join:\n sql += \" RIGHT JOIN {} ON {}\".format(self._right_join, self._on)\n\n if self._order_by:\n sql += \" ORDER BY \" + self._order_by\n\n if self._limit:\n sql += \" LIMIT \" + str(self._limit)\n\n if self._group_by:\n sql += \" GROUP BY \" + self._group_by\n\n return sql, sql_values\n","sub_path":"saiorm/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":19154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"404497379","text":"import random\n\ndef generar_contrasena():\n mayusculas = [\"A\", \"B\", \"C\"]\n minusculas = [\"a\", \"b\", \"c\"]\n simbolos = [\"!\", \"@\", \"#\"]\n numeros = [1,2,3,4,5,6,7,8,9,0]\n\n caracteres = mayusculas + minusculas + simbolos + numeros\n\n contrasena2 = []\n\n for i in range(15):\n caracter_random = str(random.choice(caracteres))\n contrasena2.append(caracter_random)\n \n contrasena2 = \"\".join(contrasena2)\n return contrasena2\n\ndef run():\n contrasena = generar_contrasena()\n print(\"Tu nueva contraseña es: \" + contrasena)\n\nif __name__ == '__main__':\n run()","sub_path":"generador_contrasena.py","file_name":"generador_contrasena.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"306865601","text":"# Use the file name mbox-short.txt as the file name\r\nfname = input(\"Enter file name: \")\r\nfhand = open(fname)\r\ncount = 0\r\ntval = 0\r\nfor line in fhand:\r\n if not line.startswith(\"X-DSPAM-Confidence:\"):\r\n continue\r\n count = count + 1\r\n iline = line.find('X-DSPAM-Confidence:')\r\n sval = line[iline+19:]\r\n stripped_sval = sval.strip()\r\n fval = float(stripped_sval)\r\n tval = tval + fval\r\n\r\naval = (tval / count)\r\nprint('Average spam confidence:', aval)\r\n","sub_path":"files03.py","file_name":"files03.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"173661916","text":"import os\n\nimport pandas as pd\nfrom pandas.util.testing import assert_equal\n\nfrom nlp_profiler.constants \\\n import HIGH_LEVEL_OPTION, GRANULAR_OPTION, GRAMMAR_CHECK_OPTION, SPELLING_CHECK_OPTION\nfrom nlp_profiler.core import apply_text_profiling\n\nCURRENT_SOURCE_FILEPATH = os.path.abspath(__file__)\nEXPECTED_DATA_PATH = f'{os.path.dirname(CURRENT_SOURCE_FILEPATH)}/data'\n\n\ndef test_given_a_text_column_when_profiler_is_applied_grammar_check_analysis_then_profiled_dataset_is_returned():\n # given\n source_dataframe = create_source_dataframe()\n csv_filename = f'{EXPECTED_DATA_PATH}/expected_profiled_dataframe_grammar_check.csv'\n expected_dataframe = pd.read_csv(csv_filename)\n\n # when: in the interest of time, only perform grammar check\n # other tests are covering for high_level and granular functionality\n actual_dataframe = apply_text_profiling(\n source_dataframe, \"text\", {HIGH_LEVEL_OPTION: False,\n SPELLING_CHECK_OPTION: False,\n GRANULAR_OPTION: False,\n GRAMMAR_CHECK_OPTION: True}\n )\n\n # then\n assert_equal(expected_dataframe, actual_dataframe)\n\n\ndef create_source_dataframe():\n text_with_emojis = \"I love ⚽ very much 😁.\"\n text_with_a_number = '2833047 people live in this area. It is not a good area.'\n text_with_two_numbers = '2833047 and 1111 people live in this area.'\n text_with_punctuations = \"This sentence doesn't seem to too many commas, periods or semi-colons (;).\"\n text_with_a_date = \"Todays date is 04/28/2020 for format mm/dd/yyyy, not 28/04/2020.\"\n text_with_dates = \"Todays date is 28/04/2020 and tomorrow's date is 29/04/2020.\"\n text_with_duplicates = 'Everyone here is so hardworking. Hardworking people. ' \\\n 'I think hardworking people are a good trait in our company.'\n data = [text_with_emojis, text_with_a_number, text_with_two_numbers,\n text_with_punctuations, text_with_a_date, text_with_dates, text_with_duplicates]\n return pd.DataFrame(data, columns=['text'])\n","sub_path":"slow-tests/acceptance_tests/test_apply_text_profiling.py","file_name":"test_apply_text_profiling.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"214258162","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\nimport wx\nimport Database as db\n\n\nclass LabelCtrlDbLinker(wx.StaticText):\n\tdef __init__(self):\n\t\tpre = wx.PreStaticText()\n\t\tself.PostCreate(pre)\n\t\tself.Bind(wx.EVT_WINDOW_CREATE, self.on_create)\n\t\tself.Bind(wx.EVT_LEFT_DOWN, self.on_left_down)\n\n\n\tdef on_create(self, event):\n\t\tself.Unbind(wx.EVT_WINDOW_CREATE)\n\t\t#further initialization goes here\n\t\t\n\t\tself.SetCursor(wx.StockCursor(wx.CURSOR_HAND))\n\n\n\tdef on_left_down(self, event):\n\t\tLabelEditFrame(self)\n\n\n\nclass LabelEditFrame(wx.Frame):\n\tdef __init__(self, parent):\n\t\twx.Frame.__init__(self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size(-1,-1), style = wx.FRAME_FLOAT_ON_PARENT|wx.FRAME_NO_TASKBAR|wx.NO_BORDER)\n\n\t\tself.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)\n\t\tself.SetFont(wx.Font(10, 70, 90, 90, False, wx.EmptyString))\n\t\t\n\t\tsizer1 = wx.BoxSizer(wx.HORIZONTAL)\n\t\t\n\t\tself.panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)\n\t\tsizer2 = wx.BoxSizer(wx.HORIZONTAL)\n\t\t\n\t\tself.text = wx.TextCtrl(self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200,-1), wx.TE_PROCESS_ENTER)\n\t\tsizer2.Add(self.text, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 0)\n\t\t\n\t\tself.panel.SetSizer(sizer2)\n\t\tself.panel.Layout()\n\t\tsizer2.Fit(self.panel)\n\t\tsizer1.Add(self.panel, 1, wx.EXPAND, 0)\n\t\t\n\t\tself.SetSizer(sizer1)\n\t\tself.Layout()\n\n\t\tself.SetSize(self.GetBestSize())\n\t\t\n\t\tself.parent = parent\n\t\t\n\t\tcurrent_value = '{}'.format(parent.GetLabel())\n\t\t\n\t\tif current_value == '...':\n\t\t\tcurrent_value = ''\n\t\t\n\t\tself.text.SetValue(current_value)\n\t\t\n\t\tself.Bind(wx.EVT_TEXT_ENTER, self.on_text_enter)\n\t\tself.text.Bind(wx.EVT_KILL_FOCUS, self.on_focus_lost)\n\t\tself.Bind(wx.EVT_CLOSE, self.on_close_frame)\n\n\t\tself.Move((parent.GetScreenPosition()))\n\t\tself.Show()\n\n\n\tdef on_text_enter(self, event):\n\t\tself.parent.SetFocus()\n\t\t#this will trigger the frame to close\n\n\n\tdef on_focus_lost(self, event):\n\t\tself.Close()\n\t\tevent.Skip()\n\n\n\tdef on_close_frame(self, event):\n\t\t#parse our the table name and field from the control name\n\t\ttable = '.'.join(self.parent.GetName().split(':')[1].split('.')[0:2])\n\t\ttable_id = wx.GetTopLevelParent(self.parent).id\n\t\t\n\t\tfield = self.parent.GetName().split(':')[1].split('.')[2]\n\t\tnew_value = self.text.GetValue()\n\t\t\n\t\tdb.update_order(table, table_id, field, new_value)\n\n\t\tparent_frame = wx.GetTopLevelParent(self.parent)\n\t\tparent_frame.Freeze()\n\t\tparent_frame.reset_all()\n\t\tparent_frame.populate_all()\n\t\tparent_frame.Thaw()\n\t\t\n\t\tself.Destroy()\n\n\n","sub_path":"LabelCtrlDbLinker.py","file_name":"LabelCtrlDbLinker.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"224183715","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2021/2/19 22:06\n__author__ = \"hanruobing\"\n\nclass Solution(object):\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n for i in range(1,len(nums)):\n if nums[i-1]>0:\n nums[i] = nums[i]+nums[i-1]\n return max(nums)","sub_path":"maxSubArray.py","file_name":"maxSubArray.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"620382304","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 29 16:47:10 2019\n\n@author: spikezz\n\"\"\"\nimport rospy\nimport airsim\n\nimport numpy as np\nimport Functions\nfrom geometry_msgs.msg import Vector3, Quaternion, PoseArray,Pose\nfrom nav_msgs.msg import Odometry\nfrom std_msgs.msg import Float32MultiArray,Float64\nfrom sensor_msgs.msg import Image, PointCloud2\nfrom airsim import ImageRequest\n\nclass ROS_Interface(object):\n \n def __init__(self,client,car_controls,remote_control):\n \n rospy.init_node('ros_msg_publisher', anonymous=True)\n self.ros_publisher=self.define_ros_publisher()\n \n if remote_control:\n print('remote_control:',remote_control)\n self.ros_subscriber=self.define_ros_subscriber(client,car_controls)\n \n def set_throttle(self,data):\n \n self.car_controls.throttle=data.data\n self.client.setCarControls(self.car_controls)\n print(\"throttle:\",data.data)\n \n def set_brake(self,data):\n \n self.car_controls.brake=data.data\n self.client.setCarControls(self.car_controls)\n print(\"brake:\",data.data)\n \n def set_steering(self,data):\n \n self.car_controls.steering=data.data\n self.client.setCarControls(self.car_controls)\n print(\"steering:\",data.data)\n \n def define_ros_publisher(self):\n \n ros_publisher={'pub_Image':rospy.Publisher('UnrealImage', Image, queue_size=15),\\\n 'pub_euler':rospy.Publisher('EulerAngle', Vector3, queue_size=1),\\\n 'pub_velocity':rospy.Publisher('Velocity', Vector3, queue_size=1),\\\n 'pub_acceleration':rospy.Publisher('Acceleration', Vector3, queue_size=1),\\\n 'pub_angular_acceleration':rospy.Publisher('AngularAcceleration', Quaternion, queue_size=1),\\\n 'pub_angular_velocity':rospy.Publisher('AngularVelocity', Quaternion, queue_size=1),\\\n 'pub_odometry_auto':rospy.Publisher('Odometry', Odometry, queue_size=1),\\\n 'pub_action':rospy.Publisher('Action', Float32MultiArray, queue_size=1),\\\n 'pub_blue_cone':rospy.Publisher('rightCones', PoseArray, queue_size=1),\\\n 'pub_yellow_cone':rospy.Publisher('leftCones', PoseArray, queue_size=1),\\\n 'pub_lidar_data':rospy.Publisher('LidarData', PointCloud2, queue_size=1)\\\n }\n \n return ros_publisher\n \n def define_ros_subscriber(self,client,car_controls):\n \n self.car_controls=car_controls\n self.client=client\n ros_subscriber={'sub_throttle':rospy.Subscriber(\"throttle\",Float64,self.set_throttle),\\\n 'sub_brake':rospy.Subscriber(\"brake\",Float64,self.set_brake),\\\n 'sub_steering':rospy.Subscriber(\"steeringAngle\",Float64, self.set_steering) \n }\n \n return ros_subscriber\n def extracte_cone_coordinate(self,cone,cone_message):\n \n new_pose=Pose()\n new_pose.position.x=cone.position.x_val\n new_pose.position.y=cone.position.y_val\n new_pose.position.z=cone.position.z_val\n cone_message.poses.append(new_pose)\n\n def create_blue_cone_message(self,list_blue_cone):\n\n bcn_msg=PoseArray()\n \n bcn_msg.header.seq = 0\n bcn_msg.header.stamp = rospy.get_rostime()\n bcn_msg.header.frame_id = \"\"\n \n for cone in list_blue_cone:\n \n self.extracte_cone_coordinate(cone,bcn_msg)\n \n return bcn_msg\n \n def create_yellow_cone_message(self,list_yellow_cone):\n\n ycn_msg=PoseArray()\n \n ycn_msg.header.seq = 0\n ycn_msg.header.stamp = rospy.get_rostime()\n ycn_msg.header.frame_id = \"\"\n \n for cone in list_yellow_cone:\n \n self.extracte_cone_coordinate(cone,ycn_msg)\n\n return ycn_msg\n \n def create_state_message(self,client,initializer,episode_counter,create_image_message=False):\n \n car_state = client.getCarState()\n state_message=[]\n msg_time=rospy.get_rostime()\n acc_msg=Vector3()\n vel_msg=Vector3()\n a_a_msg=Quaternion()\n a_v_msg=Quaternion()\n odo_msg=Odometry()\n eul_msg=Vector3()\n euv_msg=Vector3()\n \n if create_image_message:\n \n responses = client.simGetImages([ImageRequest(\"0\", airsim.ImageType.Scene, False, False)])\n response = responses[0]\n \n img1d = np.fromstring(response.image_data_uint8, dtype=np.uint8)\n \n try:\n \n print(\"episode_counter:\",episode_counter%200)\n img_rgba = img1d.reshape(response.height, response.width, 3)\n \n # if box_painter!=None:\n # \n # box_painter.img_memory[seq%200]=img_rgba\n # airsim.write_png(os.path.normpath('greener.png'), img_rgba) \n # np.save('/home/spikezz/RL project copy/img_data/%d'%(seq%150), img_rgba)\n image_msg = Image()\n image_msg.header.frame_id = str(episode_counter%200)\n image_msg.height = img_rgba.shape[0];\n image_msg.width = img_rgba.shape[1];\n image_msg.encoding = 'rgb8';\n image_msg.step = img_rgba.shape[0]*img_rgba.shape[1]*3\n image_msg.data = img_rgba.tobytes();\n \n except:\n \n print(\"Image acquisition failed\") \n #0:linear_velocity,1:angular_velocity_q,2:angular_velocity_e,3:linear_acceleration,\n #4:angular_acceleration,5:odometry,6:euler_orientation,7:image\n vel_msg.x=car_state.kinematics_estimated.linear_velocity.x_val-initializer.initial_velocoty_noise[0]\n vel_msg.y=car_state.kinematics_estimated.linear_velocity.y_val-initializer.initial_velocoty_noise[1]\n vel_msg.z=car_state.kinematics_estimated.linear_velocity.z_val-initializer.initial_velocoty_noise[2]\n state_message.append(vel_msg)\n \n a_v_msg.w=car_state.kinematics_estimated.angular_velocity.to_Quaternionr().w_val\n a_v_msg.x=car_state.kinematics_estimated.angular_velocity.to_Quaternionr().x_val\n a_v_msg.y=car_state.kinematics_estimated.angular_velocity.to_Quaternionr().y_val\n a_v_msg.z=car_state.kinematics_estimated.angular_velocity.to_Quaternionr().z_val\n state_message.append(a_v_msg)\n \n euv_msg.x=car_state.kinematics_estimated.angular_velocity.x_val\n euv_msg.y=car_state.kinematics_estimated.angular_velocity.y_val\n euv_msg.z=car_state.kinematics_estimated.angular_velocity.z_val\n state_message.append(euv_msg)\n \n acc_msg.x=car_state.kinematics_estimated.linear_acceleration.x_val\n acc_msg.y=car_state.kinematics_estimated.linear_acceleration.y_val\n acc_msg.z=car_state.kinematics_estimated.linear_acceleration.z_val\n state_message.append(acc_msg)\n\n a_a_msg.w=car_state.kinematics_estimated.angular_acceleration.to_Quaternionr().w_val\n a_a_msg.x=car_state.kinematics_estimated.angular_acceleration.to_Quaternionr().x_val\n a_a_msg.y=car_state.kinematics_estimated.angular_acceleration.to_Quaternionr().y_val\n a_a_msg.z=car_state.kinematics_estimated.angular_acceleration.to_Quaternionr().z_val\n state_message.append(a_a_msg)\n \n odo_msg.header.seq = 0\n odo_msg.header.stamp = msg_time\n odo_msg.header.frame_id = \"\"\n odo_msg.pose.pose.position.x=car_state.kinematics_estimated.position.x_val\n odo_msg.pose.pose.position.y=car_state.kinematics_estimated.position.y_val\n odo_msg.pose.pose.position.z=car_state.kinematics_estimated.position.z_val\n odo_msg.pose.pose.orientation.w=car_state.kinematics_estimated.orientation.w_val\n odo_msg.pose.pose.orientation.x=car_state.kinematics_estimated.orientation.x_val\n odo_msg.pose.pose.orientation.y=car_state.kinematics_estimated.orientation.y_val\n odo_msg.pose.pose.orientation.z=car_state.kinematics_estimated.orientation.z_val\n odo_msg.twist.twist.linear.x=vel_msg.x\n odo_msg.twist.twist.linear.y=vel_msg.y\n odo_msg.twist.twist.linear.z=vel_msg.z\n odo_msg.twist.twist.angular.x=euv_msg.x\n odo_msg.twist.twist.angular.y=euv_msg.y\n odo_msg.twist.twist.angular.z=euv_msg.z\n state_message.append(odo_msg)\n \n (eul_msg.x, eul_msg.y, eul_msg.z) = Functions.euler_from_quaternion([odo_msg.pose.pose.orientation.x, \\\n odo_msg.pose.pose.orientation.y, odo_msg.pose.pose.orientation.z, odo_msg.pose.pose.orientation.w])\n state_message.append(eul_msg)\n \n if create_image_message:\n \n try:\n \n state_message.append(image_msg)\n \n except:\n \n pass\n \n return state_message\n \n def create_action_message(self,car_controls):\n \n act_msg=Float32MultiArray()\n now=rospy.get_rostime()\n act_msg.data.append(now.secs)\n act_msg.data.append(now.nsecs)\n act_msg.data.append(car_controls.throttle)\n act_msg.data.append(car_controls.brake)\n act_msg.data.append(car_controls.steering)\n \n return act_msg\n \n","sub_path":"src/ROS_Interface.py","file_name":"ROS_Interface.py","file_ext":"py","file_size_in_byte":9557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"219728605","text":"from django.test import TestCase\n\nfrom lists.forms import (\n ItemForm, ExistingListItemForm,\n EMPTY_LIST_ERROR, DUPLICATE_ITEM_ERROR\n )\nfrom lists.models import Item, List\n\n\nclass TestItemForm(TestCase):\n\n def test_form_renders_item_text_input(self):\n form = ItemForm()\n assert 'placeholder=\"Enter a to-do item\"' in form.as_p()\n assert 'class=\"form-control input-lg\"' in form.as_p()\n\n def test_form_validation_for_blank_items(self):\n form = ItemForm(data={'text': ''})\n assert form.is_valid() is False\n assert form.errors['text'] == [EMPTY_LIST_ERROR]\n\n def test_form_save_handles_saving_to_a_list(self):\n list_ = List.objects.create()\n form = ItemForm({'text': 'do me'})\n new_item = form.save(for_list=list_)\n assert new_item == Item.objects.first()\n assert new_item.text == 'do me'\n assert new_item.list == list_\n\n\nclass ExistingListItemFormTest(TestCase):\n\n def test_form_renders_item_text_input(self):\n list_ = List.objects.create()\n form = ExistingListItemForm(for_list=list_)\n assert 'placeholder=\"Enter a to-do item\"' in form.as_p()\n\n def test_form_validation_for_blank_items(self):\n list_ = List.objects.create()\n form = ExistingListItemForm(for_list=list_, data={'text': ''})\n assert form.is_valid() is False\n assert form.errors['text'] == [EMPTY_LIST_ERROR]\n\n def test_form_validation_for_duplicate_items(self):\n list_ = List.objects.create()\n Item.objects.create(list=list_, text='no twins!')\n form = ExistingListItemForm(for_list=list_, data={'text': 'no twins!'})\n assert form.is_valid() is False\n assert form.errors['text'] == [DUPLICATE_ITEM_ERROR]\n\n def test_form_save(self):\n list_ = List.objects.create()\n form = ExistingListItemForm(for_list=list_, data={'text': 'hi'})\n new_item = form.save()\n assert new_item == Item.objects.all()[0]\n","sub_path":"lists/test/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"431586787","text":"import os\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom amipy import AmiWrapper\n\n# for debugging\nprint(\"PID: \", os.getpid(), \"; continue? [y]\")\nanswer = input()\nif answer != 'y':\n exit(0)\n\n# defaults\nmf6_dll = r\"d:\\checkouts\\modflow6-mjr\\bin\\libmf6d.dll\"\nmf6_config_file = r\"d:\\Data\\Models\\mf6\\small_models\\ex_10x10_ani\\mfsim.nam\"\n\n# load the wrapper and cd to model dir\nold_dir = os.getcwd()\nmodel_dir = os.path.dirname(mf6_config_file)\nprint(\"\\n\", \"Change to model directory: \", model_dir, \"\\n\")\nos.chdir(model_dir)\n\nmf6 = AmiWrapper(mf6_dll)\n\n# run the model\nmf6.initialize(mf6_config_file)\n\n# get some 'pointers' to MF6 internal data\nhead = mf6.get_value_ptr(\"SLN_1/X\")\nspdis = mf6.get_value_ptr(\"TESTJE NPF/SPDIS\")\ninit_head = mf6.get_value_ptr(\"TESTJE IC/STRT\")\nrndm_head = 1.0 + np.random.rand(10,10)\ninit_head = rndm_head\n\n\nxorig = np.linspace(0.5, 9.5, 10) - 0.5\nyorig = np.linspace(0.5, 9.5, 10) - 0.5\norigin = np.meshgrid(xorig, yorig)\n\nhead_r = np.reshape(head, (10,10))\n\nmf6.update()\n\n# plot stuff here:\nspdis_r = 0.2*np.reshape(spdis, (10,10,3))\nplt.quiver(*origin, spdis_r[:,:,0], spdis_r[:,:,1])\nplt.imshow(head_r, cmap='Blues', interpolation='nearest')\nplt.show()\n\nmf6.finalize()\n\nos.chdir(old_dir)\n","sub_path":"examples/run_anisotropy.py","file_name":"run_anisotropy.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"616577900","text":"\"\"\"OpenAQ Air Quality Dashboard with Flask.\"\"\"\nfrom flask import Flask\nfrom openaq_py import API, OpenAQ\nimport openaq\nfrom flask_sqlalchemy import SQLAlchemy\n\nAPP = Flask(__name__)\nAPP.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'\nAPP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\nDB = SQLAlchemy(APP)\n\n@APP.route('/')\ndef root():\n return Record.query.filter(Record.value >=10).all()\n\n\n@APP.route('/refresh')\ndef refresh():\n \"\"\"Pull fresh data from Open AQ and replace existing data.\"\"\"\n DB.drop_all()\n DB.create_all()\n for i in date_val():\n db_record = Record(datetime=i[0], value=i[1])\n DB.session.add(db_record)\n DB.session.commit()\n return 'Data refreshed!'\n\n\ndef date_val():\n status, body = api.measurements(city='Los Angeles', parameter='pm 25')\n values = []\n for i in body['results']:\n date = i['date']['utc']\n val = i['value']\n values.append((date, val))\n return values\n\n\nclass Record(DB.Model):\n id = DB.Column(DB.Integer, primary_key=True)\n datetime = DB.Column(DB.String(25))\n value = DB.Column(DB.Float, nullable=False)\n\n def __repr__(self):\n return '< Time {} ~ Value {} >'.format(self.datetime, self.value)","sub_path":"aq_dashboard.py","file_name":"aq_dashboard.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"137923758","text":"import uuid\nfrom django.core.validators import MinValueValidator, MaxValueValidator\nfrom django.db import models\nfrom profiles.models import YEARS\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom PIL import Image\nfrom random import choice\nfrom os.path import join as path_join, isfile\nimport os\nUser = settings.AUTH_USER_MODEL\n\n\ndef random_img():\n dir_path = 'media/default'\n return_path = 'default'\n files = [content for content in os.listdir(dir_path) if isfile(path_join(dir_path, content))]\n return path_join(return_path, choice(files))\n\n\ndef get_file_path(instance, filename):\n ext = filename.split('.')[-1]\n filename = \"%s.%s\" % (instance.sender, ext)\n return os.path.join(Course.objects.get(pk=instance.course).name, filename)\n\n\nclass Project(models.Model):\n name = models.CharField(max_length=150)\n summary = models.TextField(null=True, blank=True)\n teacher = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n picture = models.ImageField(default=random_img, upload_to='project_pics')\n\n def __str__(self):\n return self.name\n\n def save(self, **kwargs):\n super().save()\n\n img = Image.open(self.picture.path)\n\n if img.height > 270 or img.width > 480:\n output_size = (480, 270)\n img.thumbnail(output_size)\n img.save(self.picture.path)\n\n\nclass Course(models.Model):\n name = models.CharField(max_length=200)\n summary = models.TextField(max_length=600, null=True, blank=True)\n project = models.ForeignKey(Project, on_delete=models.CASCADE)\n start_date = models.DateField(auto_now_add=True)\n end_date = models.DateField()\n points = models.IntegerField(null=True, default=0)\n year = models.IntegerField(choices=YEARS, default=1)\n teacher = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n\n def __str__(self):\n return self.name\n\n\nclass File(models.Model):\n file = models.FileField(upload_to=get_file_path)\n uploaded_at = models.DateTimeField(auto_now_add=True)\n course = models.IntegerField(default=\"\")\n sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n\n\nclass Mark(models.Model):\n student = models.ForeignKey(User, on_delete=models.CASCADE)\n course = models.ForeignKey(Course, on_delete=models.CASCADE)\n mark = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(50)])\n date = models.DateTimeField(default=timezone.now, blank=True)\n\n def __str__(self):\n return 'Student' + ' ' + str(self.student) + ' ' + str(self.mark) +'/'+str(self.course.points)","sub_path":"projects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"95230728","text":"from datetime import datetime\nimport json\nimport os\nfrom pathlib import Path\nimport random\n\nfrom jsonschema import Draft6Validator\nfrom pydantic import ValidationError\nimport pytest\nimport requests\n\nfrom ..models import (\n AccessType,\n AssetMeta,\n DandisetMeta,\n DigestType,\n IdentifierType,\n LicenseType,\n ParticipantRelationType,\n PublishedDandisetMeta,\n RelationType,\n RoleType,\n to_datacite,\n)\n\n\ndef test_dandiset():\n assert DandisetMeta.unvalidated()\n\n\ndef test_asset():\n assert AssetMeta.unvalidated()\n\n\n@pytest.mark.parametrize(\n \"enumtype,values\",\n [\n (\n AccessType,\n {\n \"Open\": \"dandi:Open\",\n # \"Embargoed\": \"dandi:Embargoed\",\n # \"Restricted\": \"dandi:Restricted\",\n },\n ),\n (\n RoleType,\n {\n \"Author\": \"dandi:Author\",\n \"Conceptualization\": \"dandi:Conceptualization\",\n \"ContactPerson\": \"dandi:ContactPerson\",\n \"DataCollector\": \"dandi:DataCollector\",\n \"DataCurator\": \"dandi:DataCurator\",\n \"DataManager\": \"dandi:DataManager\",\n \"FormalAnalysis\": \"dandi:FormalAnalysis\",\n \"FundingAcquisition\": \"dandi:FundingAcquisition\",\n \"Investigation\": \"dandi:Investigation\",\n \"Maintainer\": \"dandi:Maintainer\",\n \"Methodology\": \"dandi:Methodology\",\n \"Producer\": \"dandi:Producer\",\n \"ProjectLeader\": \"dandi:ProjectLeader\",\n \"ProjectManager\": \"dandi:ProjectManager\",\n \"ProjectMember\": \"dandi:ProjectMember\",\n \"ProjectAdministration\": \"dandi:ProjectAdministration\",\n \"Researcher\": \"dandi:Researcher\",\n \"Resources\": \"dandi:Resources\",\n \"Software\": \"dandi:Software\",\n \"Supervision\": \"dandi:Supervision\",\n \"Validation\": \"dandi:Validation\",\n \"Visualization\": \"dandi:Visualization\",\n \"Funder\": \"dandi:Funder\",\n \"Sponsor\": \"dandi:Sponsor\",\n \"StudyParticipant\": \"dandi:StudyParticipant\",\n \"Affiliation\": \"dandi:Affiliation\",\n \"EthicsApproval\": \"dandi:EthicsApproval\",\n \"Other\": \"dandi:Other\",\n },\n ),\n (\n RelationType,\n {\n \"IsCitedBy\": \"dandi:IsCitedBy\",\n \"Cites\": \"dandi:Cites\",\n \"IsSupplementTo\": \"dandi:IsSupplementTo\",\n \"IsSupplementedBy\": \"dandi:IsSupplementedBy\",\n \"IsContinuedBy\": \"dandi:IsContinuedBy\",\n \"Continues\": \"dandi:Continues\",\n \"Describes\": \"dandi:Describes\",\n \"IsDescribedBy\": \"dandi:IsDescribedBy\",\n \"HasMetadata\": \"dandi:HasMetadata\",\n \"IsMetadataFor\": \"dandi:IsMetadataFor\",\n \"HasVersion\": \"dandi:HasVersion\",\n \"IsVersionOf\": \"dandi:IsVersionOf\",\n \"IsNewVersionOf\": \"dandi:IsNewVersionOf\",\n \"IsPreviousVersionOf\": \"dandi:IsPreviousVersionOf\",\n \"IsPartOf\": \"dandi:IsPartOf\",\n \"HasPart\": \"dandi:HasPart\",\n \"IsReferencedBy\": \"dandi:IsReferencedBy\",\n \"References\": \"dandi:References\",\n \"IsDocumentedBy\": \"dandi:IsDocumentedBy\",\n \"Documents\": \"dandi:Documents\",\n \"IsCompiledBy\": \"dandi:IsCompiledBy\",\n \"Compiles\": \"dandi:Compiles\",\n \"IsVariantFormOf\": \"dandi:IsVariantFormOf\",\n \"IsOriginalFormOf\": \"dandi:IsOriginalFormOf\",\n \"IsIdenticalTo\": \"dandi:IsIdenticalTo\",\n \"IsReviewedBy\": \"dandi:IsReviewedBy\",\n \"Reviews\": \"dandi:Reviews\",\n \"IsDerivedFrom\": \"dandi:IsDerivedFrom\",\n \"IsSourceOf\": \"dandi:IsSourceOf\",\n \"IsRequiredBy\": \"dandi:IsRequiredBy\",\n \"Requires\": \"dandi:Requires\",\n \"Obsoletes\": \"dandi:Obsoletes\",\n \"IsObsoletedBy\": \"dandi:IsObsoletedBy\",\n },\n ),\n (\n ParticipantRelationType,\n {\n \"IsChildOf\": \"dandi:IsChildOf\",\n \"IsDizygoticTwinOf\": \"dandi:IsDizygoticTwinOf\",\n \"IsMonozygoticTwinOf\": \"dandi:IsMonozygoticTwinOf\",\n \"IsSiblingOf\": \"dandi:IsSiblingOf\",\n \"isParentOf\": \"dandi:isParentOf\",\n },\n ),\n (\n LicenseType,\n {\n \"CC0_10\": \"spdx:CC0-1.0\",\n \"CC_BY_40\": \"spdx:CC-BY-4.0\",\n \"CC_BY_NC_40\": \"spdx:CC-BY-NC-4.0\",\n },\n ),\n (\n IdentifierType,\n {\n \"doi\": \"dandi:doi\",\n \"orcid\": \"dandi:orcid\",\n \"ror\": \"dandi:ror\",\n \"dandi\": \"dandi:dandi\",\n \"rrid\": \"dandi:rrid\",\n },\n ),\n (\n DigestType,\n {\n \"md5\": \"dandi:md5\",\n \"sha1\": \"dandi:sha1\",\n \"sha2_256\": \"dandi:sha2-256\",\n \"sha3_256\": \"dandi:sha3-256\",\n \"blake2b_256\": \"dandi:blake2b-256\",\n \"blake3\": \"dandi:blake3\",\n \"dandi_etag\": \"dandi:dandi-etag\",\n },\n ),\n ],\n)\ndef test_types(enumtype, values):\n assert {v.name: v.value for v in enumtype} == values\n\n\ndef test_autogenerated_titles():\n schema = AssetMeta.schema()\n assert schema[\"title\"] == \"Asset Meta\"\n assert schema[\"properties\"][\"schemaVersion\"][\"title\"] == \"Schema Version\"\n assert schema[\"definitions\"][\"PropertyValue\"][\"title\"] == \"Property Value\"\n\n\ndef datacite_post(datacite, doi):\n \"\"\" posting the datacite object and checking the status of the requests\"\"\"\n\n # removing doi in case it exists\n _clean_doi(doi)\n\n # checking f I'm able to create doi\n rp = requests.post(\n \"https://api.test.datacite.org/dois\",\n json=datacite,\n headers={\"Content-Type\": \"application/vnd.api+json\"},\n auth=(\"DARTLIB.DANDI\", os.environ[\"DATACITE_DEV_PASSWORD\"]),\n )\n rp.raise_for_status()\n\n # checking if i'm able to get the url\n rg = requests.get(url=f\"https://api.test.datacite.org/dois/{doi}/activities\")\n rg.raise_for_status()\n\n # cleaning url\n _clean_doi(doi)\n\n\ndef _clean_doi(doi):\n \"\"\"removing doi, ignoring the status code\"\"\"\n requests.delete(\n f\"https://api.test.datacite.org/dois/{doi}\",\n auth=(\"DARTLIB.DANDI\", os.environ[\"DATACITE_DEV_PASSWORD\"]),\n )\n\n\n@pytest.fixture(scope=\"module\")\ndef schema():\n sr = requests.get(\n \"https://raw.githubusercontent.com/datacite/schema/master/source/\"\n \"json/kernel-4.3/datacite_4.3_schema.json\"\n )\n sr.raise_for_status()\n schema = sr.json()\n return schema\n\n\ndef _basic_publishmeta(dandi_id, version=\"v.0\", prefix=\"10.80507\"):\n \"\"\"\n adding basic info required by PublishedDandisetMeta in addition to\n fields required by DandisetMeta\n \"\"\"\n publish_meta = {\n \"datePublished\": str(datetime.now().year),\n \"publishedBy\": \"https://doi.test.datacite.org/dois\",\n \"version\": version,\n \"doi\": f\"{prefix}/dandi.{dandi_id}.{version}\",\n \"assetsSummary\": {\n \"numberOfBytes\": 10,\n \"numberOfFiles\": 1,\n \"dataStandard\": [{\"key\": \"value\"}],\n \"approach\": [{\"key\": \"value\"}],\n \"measurementTechnique\": [{\"key\": \"value\"}],\n \"species\": [{\"key\": \"value\"}],\n },\n }\n return publish_meta\n\n\n@pytest.mark.skipif(\n not os.getenv(\"DATACITE_DEV_PASSWORD\"), reason=\"no datacite password available\"\n)\n@pytest.mark.parametrize(\"dandi_id\", [\"000004\", \"000008\"])\ndef test_datacite(dandi_id, schema):\n \"\"\" checking to_datacite for a specific datasets\"\"\"\n\n # reading metadata taken from exemplary dandisets and saved in json files\n with (\n Path(__file__).with_name(\"data\") / \"metadata\" / f\"meta_{dandi_id}.json\"\n ).open() as f:\n meta_js = json.load(f)\n\n # updating with basic fields required for PublishDandisetMeta\n meta_js.update(\n _basic_publishmeta(dandi_id.replace(\"000\", str(random.randrange(100, 999))))\n )\n meta = PublishedDandisetMeta(**meta_js)\n\n datacite = to_datacite(meta=meta)\n\n Draft6Validator.check_schema(schema)\n validator = Draft6Validator(schema)\n validator.validate(datacite[\"data\"][\"attributes\"])\n\n # trying to post datacite\n datacite_post(datacite, meta.doi)\n\n\ndef test_dantimeta_1():\n \"\"\" checking basic metadata for publishing\"\"\"\n # meta data without doi, datePublished and publishedBy\n meta_dict = {\n \"identifier\": \"DANDI:999999\",\n \"id\": \"DANDI:999999/draft\",\n \"version\": \"v.1\",\n \"name\": \"testing dataset\",\n \"description\": \"testing\",\n \"contributor\": [\n {\n \"name\": \"last name, first name\",\n \"roleName\": [RoleType(\"dandi:ContactPerson\")],\n }\n ],\n \"license\": [LicenseType(\"spdx:CC-BY-4.0\")],\n }\n\n # should work for DandisetMeta but PublishedDandisetMeta should raise an error\n DandisetMeta(**meta_dict)\n with pytest.raises(ValidationError) as exc:\n PublishedDandisetMeta(**meta_dict)\n\n assert all([el[\"msg\"] == \"field required\" for el in exc.value.errors()])\n assert set([el[\"loc\"][0] for el in exc.value.errors()]) == {\n \"datePublished\",\n \"publishedBy\",\n \"doi\",\n \"assetsSummary\",\n }\n\n # after adding basic meta required to publish: doi, datePublished, publishedBy, assetsSummary,\n # so PublishedDandisetMeta should work\n meta_dict.update(_basic_publishmeta(dandi_id=\"DANDI:999999\"))\n PublishedDandisetMeta(**meta_dict)\n\n\n@pytest.mark.parametrize(\n \"additional_meta, datacite_checks\",\n [\n # no additional meta\n (\n {},\n {\n \"creators\": (1, {\"name\": \"A_last, A_first\"}),\n \"titles\": (1, {\"title\": \"testing dataset\"}),\n \"descriptions\": (\n 1,\n {\"description\": \"testing\", \"descriptionType\": \"Abstract\"},\n ),\n \"publisher\": (None, \"DANDI Archive\"),\n \"rightsList\": (\n 1,\n {\"rightsIdentifierScheme\": \"SPDX\", \"rightsIdentifier\": \"CC_BY_40\"},\n ),\n \"types\": (\n None,\n {\"resourceType\": \"NWB\", \"resourceTypeGeneral\": \"Dataset\"},\n ),\n },\n ),\n # additional contributor with dandi:Author\n (\n {\n \"contributor\": [\n {\n \"name\": \"A_last, A_first\",\n \"roleName\": [RoleType(\"dandi:ContactPerson\")],\n },\n {\"name\": \"B_last, B_first\", \"roleName\": [RoleType(\"dandi:Author\")]},\n ],\n },\n {\n \"creators\": (1, {\"name\": \"B_last, B_first\"}),\n \"contributors\": (\n 1,\n {\"name\": \"A_last, A_first\", \"contributorType\": \"ContactPerson\"},\n ),\n },\n ),\n # additional contributor with dandi:Sponsor, fundingReferences should be created\n (\n {\n \"contributor\": [\n {\n \"name\": \"A_last, A_first\",\n \"roleName\": [RoleType(\"dandi:ContactPerson\")],\n },\n {\n \"name\": \"B_last, B_first\",\n \"roleName\": [RoleType(\"dandi:Sponsor\")],\n },\n ],\n },\n {\n \"creators\": (1, {\"name\": \"A_last, A_first\"}),\n \"fundingReferences\": (1, {\"funderName\": \"B_last, B_first\"}),\n },\n ),\n # additional contributor with 2 roles: Author and Software (doesn't exist in datacite)\n # the person should be in creators and contributors (with contributorType Other)\n (\n {\n \"contributor\": [\n {\n \"name\": \"A_last, A_first\",\n \"roleName\": [\n RoleType(\"dandi:Author\"),\n RoleType(\"dandi:Software\"),\n ],\n },\n {\n \"name\": \"B_last, B_first\",\n \"roleName\": [RoleType(\"dandi:ContactPerson\")],\n },\n ],\n },\n {\n \"creators\": (1, {\"name\": \"A_last, A_first\"}),\n \"contributors\": (\n 2,\n {\"name\": \"A_last, A_first\", \"contributorType\": \"Other\"},\n ),\n },\n ),\n ],\n)\n@pytest.mark.skipif(\n not os.getenv(\"DATACITE_DEV_PASSWORD\"), reason=\"no datacite password available\"\n)\ndef test_dantimeta_datacite(schema, additional_meta, datacite_checks):\n \"\"\"\n checking datacite objects for specific metadata dictionaries,\n posting datacite object and checking the status code\n \"\"\"\n\n dandi_id = f\"DANDI:000{random.randrange(100, 999)}\"\n\n # meta data without doi, datePublished and publishedBy\n meta_dict = {\n \"identifier\": dandi_id,\n \"id\": f\"{dandi_id}/draft\",\n \"name\": \"testing dataset\",\n \"description\": \"testing\",\n \"contributor\": [\n {\n \"name\": \"A_last, A_first\",\n \"roleName\": [RoleType(\"dandi:ContactPerson\")],\n }\n ],\n \"license\": [LicenseType(\"spdx:CC-BY-4.0\")],\n }\n meta_dict.update(_basic_publishmeta(dandi_id=dandi_id))\n meta_dict.update(additional_meta)\n\n # creating PublishedDandisetMeta from the dictionary\n meta = PublishedDandisetMeta(**meta_dict)\n # creating and validating datacite objects\n datacite = to_datacite(meta)\n Draft6Validator.check_schema(schema)\n validator = Draft6Validator(schema)\n validator.validate(datacite[\"data\"][\"attributes\"])\n\n # checking some datacite fields\n attr = datacite[\"data\"][\"attributes\"]\n for key, el in datacite_checks.items():\n el_len, el_flds = el\n if el_len:\n # checking length and some fields from the first element\n assert len(attr[key]) == el_len\n for k, v in el_flds.items():\n assert attr[key][0][k] == v\n else:\n if isinstance(el_flds, dict):\n for k, v in el_flds.items():\n assert attr[key][k] == v\n else:\n assert attr[key] == el_flds\n\n # trying to poste datacite\n datacite_post(datacite, meta.doi)\n","sub_path":"dandischema/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":14902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"279164494","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n\n\ndef quick_sort(seq):\n \"\"\"\n 10000 random number seq :\n select_sort use time 3.0919713973999023\n quick sort use time 0.024930477142333984\n\n \"\"\"\n if not isinstance(seq, list):\n raise Exception(\"seq should be a list.\")\n\n if len(seq) < 2:\n return seq\n else:\n pivot = seq[0]\n\n less_part = [i for i in seq[1:] if i <= pivot]\n\n greater_part = [i for i in seq[1:] if i > pivot]\n\n return quick_sort(less_part) + [pivot] + quick_sort(greater_part)\n","sub_path":"my_python_module/algorithm/sort/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"238912180","text":"from django.contrib import admin\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\n\nfrom ..models import Education, Career, License, ApplicantLink, ApplicantSkill\n\nUser = get_user_model()\n\n__all__ = (\n 'ApplicantUserAdmin',\n)\n\n\nclass ApplicantLinkInline(admin.TabularInline):\n model = ApplicantLink\n extra = 1\n\n\nclass ApplicantSkillInline(admin.TabularInline):\n model = ApplicantSkill\n extra = 1\n\n\nclass EducationInline(admin.TabularInline):\n model = Education\n extra = 1\n\n\nclass CareerInline(admin.TabularInline):\n model = Career\n extra = 1\n\n\nclass LicenseInline(admin.TabularInline):\n model = License\n extra = 1\n\n\nclass ApplicantUserAdmin(BaseUserAdmin):\n list_display = ('name', 'is_active', 'email', 'phone_number', 'birth_date',)\n list_filter = ('is_active',)\n search_fields = ('name',)\n ordering = ('pk',)\n readonly_fields = ('is_active',)\n actions = ['activate']\n\n inlines = [\n EducationInline,\n CareerInline,\n LicenseInline,\n ApplicantLinkInline,\n ApplicantSkillInline,\n ]\n fieldsets = (\n (None, {'fields': (\n 'is_active',\n 'type',\n 'email',\n 'password',\n )}),\n ('개인정보', {'fields': (\n 'last_name',\n 'first_name',\n 'phone_number',\n 'birth_date',\n 'img_profile',\n )}),\n ('지원자 정보', {'fields': (\n 'is_published',\n 'is_looking',\n 'short_intro',\n 'introduce',\n 'job_groups',\n 'pdf1',\n 'pdf2',\n )}),\n )\n add_fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': (\n 'type',\n 'email',\n 'password1',\n 'password2',\n )\n }),\n ('개인정보', {'fields': (\n 'last_name',\n 'first_name',\n 'phone_number',\n 'birth_date',\n )}),\n )\n\n def activate(self, request, queryset):\n for user in queryset:\n user.send_signup_approve()\n user.is_active = True\n user.save()\n\n activate.short_description = '활성화 처리'\n\n def get_form(self, request, obj=None, **kwargs):\n form = super().get_form(request, obj, **kwargs)\n form.base_fields['type'].choices = [User.CHOICES_TYPE[0]]\n if obj:\n form.base_fields['type'].disabled = True\n return form\n","sub_path":"app/members/admin/applicant.py","file_name":"applicant.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"19293867","text":"'''\nimport platform\nif platform.system() is \"Darwin\":\n import matplotlib\n matplotlib.use('TkAgg')\n import matplotlib.pyplot as plt\nelse:\n import matplotlib.pyplot as plt\n'''\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets\nfrom tensorflow.contrib.layers import flatten\nfrom tensorflow.python.framework import ops\n\n# START A GRAPH SESSION\nsess = tf.Session()\n\n# DOWNLOAD DATA\ndata_dir = '../Data/HandWritten_Data/'\nmnist = read_data_sets(data_dir)\n\n# Convert images into 28x28 (they are downloaded as 1x784)\ntrain_xdata = np.array([np.reshape(x, (28, 28)) for x in mnist.train.images])\n#train_xdata = np.expand_dims(train_xdata, axis=3)\n\ntest_xdata = np.array([np.reshape(x, (28, 28)) for x in mnist.test.images])\n#test_xdata = np.expand_dims(test_xdata, axis=3)\n\n# CONVERT LABELS INTO ONE-HOT ENCODED VECTORS\ntrain_labels = mnist.train.labels\ntest_labels = mnist.test.labels\n\n#train_labels = tf.one_hot(train_labels, 10)\n#test_labels = tf.one_hot(test_labels, 10)\n#print(train_labels[0])\n\n# SET MODEL PARAMETERS\nbatch_size = 100\nlearning_rate = 0.005\nevaluation_size = 500\nimage_width = train_xdata[0].shape[0]\nimage_height = train_xdata[0].shape[1]\ntarget_size = max(train_labels) + 1\nnum_channels = 1 # greyscale = 1 channel\ngenerations = 500\neval_every = 5\nconv1_features = 25\nconv2_features = 50\nmax_pool_size1 = 2\nmax_pool_size2 = 2\nfully_connected_size1 = 100\n\n# MODEL PLACEHOLDER\nx_input_shape = (None, image_width, image_height, num_channels)\nx_input = tf.placeholder(tf.float32, shape=x_input_shape)\ny_target = tf.placeholder(tf.int32, shape=(None))\n\neval_input_shape = (None, image_width, image_height, num_channels)\neval_input = tf.placeholder(tf.float32, shape=eval_input_shape)\neval_target = tf.placeholder(tf.float32, shape=(None))\n\n# CONVOLUTIONAL LAYER VARIABLES\n#conv1_W = tf.Variable(tf.truncated_normal([4, 4, num_channels, conv1_features],\nconv1_W = tf.Variable(tf.random_normal([4, 4, num_channels, conv1_features],\n stddev=0.1, dtype=tf.float32)) # 4x4 filter shape\nconv1_b = tf.Variable(tf.zeros([conv1_features], dtype=tf.float32))\n\n#conv2_W = tf.Variable(tf.truncated_normal([4, 4, conv1_features, conv2_features],\nconv2_W = tf.Variable(tf.random_normal([4, 4, conv1_features, conv2_features],\n stddev=0.1, dtype=tf.float32)) # 4x4 filter shape\nconv2_b = tf.Variable(tf.zeros([conv2_features], dtype=tf.float32))\n\n#fully1_W = tf.Variable(tf.truncated_normal([4*4*50, fully_connected_size1], stddev=0.1, dtype=tf.float32))\nfully1_W = tf.Variable(tf.random_normal([4*4*50, fully_connected_size1], stddev=0.1, dtype=tf.float32))\nfully1_b = tf.Variable(tf.random_normal([fully_connected_size1], stddev=0.1, dtype=tf.float32))\n#fully1_b = tf.Variable(tf.truncated_normal([fully_connected_size1], stddev=0.1, dtype=tf.float32))\n\n#fully2_W = tf.Variable(tf.truncated_normal([fully_connected_size1, target_size], stddev=0.1, dtype=tf.float32))\nfully2_W = tf.Variable(tf.random_normal([fully_connected_size1, target_size], stddev=0.1, dtype=tf.float32))\n#fully2_b = tf.Variable(tf.truncated_normal([target_size], stddev=0.1, dtype=tf.float32))\nfully2_b = tf.Variable(tf.random_normal([target_size], stddev=0.1, dtype=tf.float32))\n\ndef my_conv_net(input_data):\n # FIRST CONV -> RELU -> MAXPOOL\n conv1 = tf.nn.conv2d(input_data, conv1_W, strides=[1,1,1,1], padding='VALID')\n relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_b))\n max_pool1 = tf.nn.max_pool(relu1, ksize=[1, max_pool_size1, max_pool_size1, 1],\n strides=[1, max_pool_size1, max_pool_size1, 1], padding='VALID')\n\n # FIRST CONV -> RELU -> MAXPOOL\n conv2 = tf.nn.conv2d(max_pool1, conv2_W, strides=[1,1,1,1], padding='VALID')\n relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_b))\n max_pool2 = tf.nn.max_pool(relu2, ksize=[1, max_pool_size2, max_pool_size2, 1],\n strides = [1, max_pool_size2, max_pool_size2, 1], padding='VALID')\n\n # FLATTEN\n flatten_node = flatten(max_pool2)\n\n\n # FIRST FULLY\n fully_connected_1 = tf.nn.relu(tf.add(tf.matmul(flatten_node, fully1_W), fully1_b))\n\n # SECOND FULLY\n final_model_output = tf.add(tf.matmul(fully_connected_1, fully2_W), fully2_b)\n\n return(final_model_output)\n \nmodel_output = my_conv_net(x_input)\ntest_model_output = my_conv_net(eval_input)\n\n# LOSS FUNCTION (softmax cross entropy)\nloss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model_output, labels=y_target))\n\n# PREDICTION FUNCTION\nprediction = tf.nn.softmax(model_output)\ntest_prediction = tf.nn.softmax(test_model_output)\n\n# ACCURACY FUNCTION\ndef get_accuracy(logits, targets):\n batch_predictions = np.argmax(logits, axis=1)\n num_correct = np.sum(np.equal(batch_predictions, targets))\n return(100. * num_correct/batch_predictions.shape[0])\n\n# OPTIMIZER\nmy_optimizer = tf.train.MomentumOptimizer(learning_rate, 0.9)\ntrain_step = my_optimizer.minimize(loss)\n\n# INITIALIZE\n#init = tf.global_variables_initializer()\ninit = tf.initialize_all_variables()\nsess.run(init)\n\n# TRAIN START\ntrain_loss = []\ntrain_acc = []\ntest_acc = []\n\n'''\ntrain_xdata = np.expand_dims(train_xdata, axis=3)\na = sess.run(loss, feed_dict={x_input: train_xdata, y_target: train_labels})\nprint(a)\n'''\n\nfor i in range(generations):\n rand_index = np.random.choice(len(train_xdata), size=batch_size)\n rand_x = train_xdata[rand_index]\n rand_x = np.expand_dims(rand_x, axis=3)\n rand_y = train_labels[rand_index]\n train_dict = {x_input: rand_x, y_target: rand_y}\n\n sess.run(train_step, feed_dict=train_dict)\n temp_train_loss, temp_train_preds = sess.run([loss, prediction], feed_dict=train_dict)\n temp_train_acc = get_accuracy(temp_train_preds, rand_y)\n\n if (i+1) % eval_every == 0:\n eval_index = np.random.choice(len(test_xdata), size=evaluation_size)\n eval_x = test_xdata[eval_index]\n eval_x = np.expand_dims(eval_x, 3)\n eval_y = test_labels[eval_index]\n test_dict = {eval_input: eval_x, eval_target: eval_y}\n test_preds = sess.run(test_prediction, feed_dict=test_dict)\n temp_test_acc = get_accuracy(test_preds, eval_y)\n \n # Record and print results\n train_loss.append(temp_train_loss)\n train_acc.append(temp_train_acc)\n test_acc.append(temp_test_acc)\n acc_and_loss = [(i+1), temp_train_loss, temp_train_acc, temp_test_acc]\n acc_and_loss = [np.round(x,2) for x in acc_and_loss]\n print('Generation # {}. Train Loss: {:.2f}. Train Acc (Test Acc): {:.2f} ({:.2f})'.format(*acc_and_loss))\n\n# Matlotlib code to plot the loss and accuracies\neval_indices = range(0, generations, eval_every)\n# Plot loss over time\nplt.plot(eval_indices, train_loss, 'k-')\nplt.title('Softmax Loss per Generation')\nplt.xlabel('Generation')\nplt.ylabel('Softmax Loss')\nplt.show()\n\n# Plot train and test accuracy\nplt.plot(eval_indices, train_acc, 'k-', label='Train Set Accuracy')\nplt.plot(eval_indices, test_acc, 'r--', label='Test Set Accuracy')\nplt.title('Train and Test Accuracy')\nplt.xlabel('Generation')\nplt.ylabel('Accuracy')\nplt.legend(loc='lower right')\nplt.show()\n\n'''\n#a = sess.run(model_output, feed_dict={x_input:train_xdata, y_target:train_labels})\n#a = sess.run(prediction, feed_dict={x_input:train_xdata, y_target:train_labels})\na = sess.run(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model_output, labels=y_target),\n feed_dict={x_input:train_xdata, y_target:train_labels})\nprint(a[0], a[100], train_labels[0], train_labels[100])\n\nprint(train_labels.shape)\n'''\n","sub_path":"TensorFlow/Book-Tutorials/Practice_SIMPLE_CNN.py","file_name":"Practice_SIMPLE_CNN.py","file_ext":"py","file_size_in_byte":7740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"344986737","text":"#!/usr/bin/env python\r\n#encoding: utf-8\r\nfrom django.conf.urls import include, url\r\nfrom django.contrib import admin\r\nfrom cmdb import views,tests\r\n\r\nurlpatterns = [\r\n url(r'^login/', views.login2),\r\n url(r'^logout/', views.logout),\r\n url(r'^index/', views.index),\r\n url(r'^lists/', views.lists),\r\n url(r'^baolei/', views.baolei),\r\n url(r'^add/', views.add),\r\n url(r'^cmd/', views.cmd),\r\n url(r'^uuzu/', views.uuzu),\r\n url(r'^36ji/', views.ss6j),\r\n url(r'^36ji_ajax/', views.ss6j_ajax),\r\n url(r'^36ji_down/', views.ss6j_down),\r\n url(r'^ajax_data/', views.ajax_data),\r\n url(r'^36ji_hero/', views.ss6j_hero),\r\n url(r'^36ji_hero_ajax/', views.ss6j_hero_ajax),\r\n url(r'^36ji_life/', views.ss6j_life),\r\n url(r'^36ji_life_ajax/', views.ss6j_life_ajax),\r\n #url(r'^api/', tests.api),\r\n url(r'^ujobs/', views.ujobs),\r\n url(r'^ujobs_log/', views.ujobs_log),\r\n url(r'^ujobs_ajax/', views.ujobs_ajax),\r\n url(r'^u_down/', views.u_down),\r\n url(r'^u_down_ajax/', views.u_down_ajax),\r\n url(r'^u_down_get/', views.u_down_get),\r\n url(r'^u_down_log/', views.u_down_log),\r\n url(r'^access_log/', views.access_log),\r\n]\r\n","sub_path":"cmdb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"181650459","text":"#====For in loop====\n# students = ['Jane','Andria','luke']\n# for x in students:\n# print('hi', x)\n\n#============\n# print(range(10))\n# print(list(range(10)))\n\n# print(list(range(3,7)))\n\n# print(list(range(2,14,3)))\n\n# for i in range(2,8):\n# for j in range(i):\n# print('*', end ='')\n# print()\n\n #====While loop===\n # i = 1\n # while i < 11:\n # print (i)\n # i += 1\n\n #===Break statements===\n# i = 1\n# while i < 11:\n# print (i)\n# if i == 3:\n# break\n# i += 1\n\n#=================continue======\n# i = 1\n# while i < 3:\n# i += 1\n# if i == 4:\n# continue\n# print(i)\n\nfor x in range(1,10):\n if x == 9:\n break\n print(x)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"78333501","text":"from os import sys\r\n\r\nimport pygame as pg\r\n\r\nfrom projections import point_projection\r\nfrom projections import combined_transformations\r\nfrom prisms3 import prisms\r\n\r\nclass Scene:\r\n # https://stackoverflow.com/a/14727074\r\n \"\"\"Base class of scene objects.\"\"\"\r\n def __init__(self, screen):\r\n self.screen = screen\r\n self.next = self\r\n self.previous = self\r\n self.t0 = 0\r\n self.font = pg.font.Font('freesansbold.ttf', 24)\r\n self.name_surface = self.get_scene_name_surface()\r\n self.init()\r\n\r\n def __repr__(self):\r\n return f'{self.__class__.__name__}'\r\n\r\n def get_scene_name_surface(self):\r\n \"\"\"\r\n Get the class name as a pygame surface to blit onto the screen.\r\n @return name of the class as a text surface\r\n \"\"\"\r\n name = self.__repr__()\r\n name_surface = self.render_text(self.font, name)\r\n return name_surface\r\n\r\n def init(self):\r\n \"\"\"Group initialize functions.\"\"\"\r\n pass\r\n\r\n def render(self):\r\n \"\"\"Group draw functions.\"\"\"\r\n raise NotImplementedError\r\n\r\n def update(self):\r\n \"\"\"Group update functions.\"\"\"\r\n raise NotImplementedError\r\n\r\n def handle_events(self):\r\n \"\"\"Pass pygame events to do specific things for each child class.\"\"\"\r\n raise NotImplementedError\r\n\r\n def get_change_of_time(self):\r\n if self.t0 is not 0:\r\n # correct change in time, since non active scenes are not updated\r\n dt = time.clock() - self.t0\r\n self.t0 = 0\r\n return dt\r\n else:\r\n return 0\r\n\r\n def switch_to_scene(self, next_scene):\r\n # switch current scene to new scene\r\n self.next = next_scene\r\n # set new scene to itself\r\n next_scene.next = next_scene\r\n # set previous scene of the new scene, if the scene does not have a previous scene yet\r\n if next_scene.previous is next_scene:\r\n next_scene.previous = self\r\n self.t0 = time.clock()\r\n\r\n def switch_to_previous(self):\r\n self.switch_to_scene(self.previous)\r\n\r\n # TEXT FUNCTIONS ----------------------------------\r\n\r\n @staticmethod\r\n def render_text(font, text_list):\r\n \"\"\"\r\n Renders text lines as font.render can only render 1 line of text.\r\n @param pygame font instance\r\n @param list of strings or 1 string\r\n @return list of pygame text surfaces or 1 pygame text surface\r\n \"\"\"\r\n text_surfaces = []\r\n if isinstance(text_list, str):\r\n text_list = [text_list]\r\n for text in text_list:\r\n text_surfaces.append(font.render(text, True, (255, 255, 255)))\r\n return text_surfaces\r\n\r\n @staticmethod\r\n def blit_text(target_surface, text_surfaces, pos, descending=True):\r\n \"\"\"\r\n Draw text surface onto target surface using surface.blit()\r\n @param target surface to blit onto\r\n @param text surface to blit\r\n @param position of text surface on target surface\r\n @param whether to blit list of surfaces ascending or descending\r\n \"\"\"\r\n # direction = True = descending, direction = False = Ascending\r\n for i, text_surface in enumerate(text_surfaces):\r\n h, w = text_surface.get_rect().h, text_surface.get_rect().w\r\n if descending:\r\n offset = (pos[0], pos[1]+(i*h))\r\n else:\r\n offset = (pos[0], pos[1]-(i*h))\r\n target_surface.blit(text_surface, offset)\r\n\r\n\r\nclass IsometricScene(Scene):\r\n def __init__(self, screen):\r\n super().__init__(screen)\r\n\r\n def init(self):\r\n point = (500, 50, -150)\r\n cube_size = 200\r\n center = tuple(element+(cube_size/2) for element in point)\r\n self.cube = prisms.Cube(point, cube_size)\r\n # transparency\r\n self.cube.apply_alpha(100)\r\n self.iso_transform = point_projection.Isometric()\r\n # angle values\r\n self.alpha = 0\r\n self.beta = 0\r\n self.gamma = 0\r\n self.rot_transform = combined_transformations.RotateAboutPoint(center, self.alpha, self.beta, self.gamma)\r\n\r\n def handle_events(self):\r\n events = pg.event.get()\r\n for event in events:\r\n if event.type == pg.QUIT:\r\n pg.quit()\r\n sys.exit()\r\n if event.type == pg.KEYDOWN:\r\n if event.key == pg.K_ESCAPE:\r\n pg.quit()\r\n sys.exit()\r\n if event.key == pg.K_UP:\r\n self.alpha += 10\r\n if event.key == pg.K_DOWN:\r\n self.beta += 10\r\n if event.key == pg.K_LEFT:\r\n self.gamma += 10\r\n if event.key == pg.K_RIGHT:\r\n pass\r\n\r\n def update(self):\r\n self.rot_transform.update(alpha=self.alpha, beta=self.beta, gamma=self.gamma)\r\n\r\n def render(self):\r\n self.screen.fill((155, 155, 155))\r\n self.blit_text(self.screen, self.name_surface, (0, 0))\r\n self.cube.render(self.screen, self.iso_transform, self.rot_transform)","sub_path":"scenes.py","file_name":"scenes.py","file_ext":"py","file_size_in_byte":5169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"577146961","text":"import discord\nfrom discord.ext import commands\nfrom discord.ext.commands import has_permissions\nimport pymongo\nimport requests\nfrom os import getenv\nfrom PIL import Image\nfrom module.welcome_image import welcome_image\nfrom module.goodbye_image import goodbye_image\nfrom io import BytesIO\n\nmyclient = pymongo.MongoClient('mongodb://127.0.0.1:52120/',\n username=getenv(\"MONGO_USER\"),\n password=getenv(\"MONGO_PASSWORD\"),\n authSource=\"bot\",\n authMechanism='SCRAM-SHA-256')\nmydb = myclient[\"bot\"]\nmysd = mydb[\"server_data\"]\n\n\ndef get_prefix(bot, message):\n for prefix in mysd.find({\"_id\": message.guild.id}, {\"_id\": 0, \"prefix\": 1}):\n return prefix[\"prefix\"]\n\n\ndef get_welcome_channel(bot, member):\n for id in mysd.find({\"_id\": member.guild.id}, {\"_id\": 0, \"welcome\": 1}):\n return id[\"welcome\"]\n\n\nBot = commands.Bot(command_prefix=get_prefix, case_insensitive=True)\nBot.remove_command(\"help\")\nowner = 286976165069979659\n\n\n@Bot.command()\nasync def changeprefix(ctx, prefix):\n mysd.update_one({\"_id\": ctx.guild.id}, {\"$set\": {\"prefix\": prefix}})\n\n\n@Bot.command()\nasync def setwelcomechannel(ctx):\n mysd.update_one({\"_id\": ctx.guild.id}, {\"$set\": {\"welcome\": ctx.channel.id}})\n await ctx.channel.send(\"Welcome channel set to {}\".format(ctx.channel))\n\n\n@Bot.command()\nasync def help(ctx):\n embed = discord.Embed(title=\"Commandes\",\n color=0x0080ff)\n embed.set_author(name=\"Aide pour le bot Sakura-chan\")\n embed.set_thumbnail(url=Bot.user.avatar_url)\n embed.add_field(name=\"changeprefix\", value=\"Changer le préfixe d'utilisation du bot\",\n inline=True)\n embed.add_field(name=\"setwelcomechannel\", value=\"Paramétrer le salon de bienvenue et d'au revoir\",\n inline=True)\n return await ctx.channel.send(embed=embed)\n\n\n@Bot.event\nasync def on_ready():\n print(\"Bot is ready\")\n\n\n@Bot.event\nasync def on_guild_join(guild):\n if mysd.find({\"_id\": guild.id}):\n mysd.delete_one({\"_id\": guild.id})\n mysd.insert_one({\"_id\": guild.id, \"prefix\": \".\"})\n\n\n@Bot.event\nasync def on_guild_remove(guild):\n mysd.delete_one({\"_id\": guild.id})\n\n\n@Bot.event\nasync def on_member_join(member):\n if member.bot:\n return await member.ban()\n channel = Bot.get_channel(get_welcome_channel(Bot, member))\n response = requests.get(\"https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.png?size=256\".format(member))\n img = Image.open(BytesIO(response.content))\n img = Image.open(BytesIO(welcome_image(img, member.name, member.discriminator,\n member.guild.member_count,\n member.guild.name).getvalue()))\n with BytesIO() as image_binary:\n img.save(image_binary, \"PNG\")\n image_binary.seek(0)\n await channel.send(\"Bienvenue dans le royaume de :cherry_blossom:Sakura:cherry_blossom: mon petit panda !\",\n file=discord.File(fp=image_binary, filename=\"image.png\"))\n\n\n@Bot.event\nasync def on_member_remove(member):\n if member.bot:\n return\n channel = Bot.get_channel(get_welcome_channel(Bot, member))\n response = requests.get(\"https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.png?size=256\".format(member))\n img = Image.open(BytesIO(response.content))\n img = Image.open(BytesIO(goodbye_image(img, member.name, member.discriminator).getvalue()))\n with BytesIO() as image_binary:\n img.save(image_binary, \"PNG\")\n image_binary.seek(0)\n await channel.send(\"{0.mention} vient de nous quitter :c A plus dans le bus mon petit panda... On t'aimera toujours :panda_face::cherry_blossom:\".format(member),\n file=discord.File(fp=image_binary, filename=\"image.png\"))\n\n\nBot.run(getenv(\"TOKEN2\"))\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"11171039","text":"# %%writefile /content/LearningToPaint/rllib/canvas_env.py\nimport os, subprocess, time, signal\n\nimport numpy as np\nfrom PIL import Image, ImageDraw\n\nimport gym\nfrom gym import error, spaces\nimport ray\nfrom ray import tune\nfrom ray.rllib.utils import try_import_tf\nfrom ray.tune import grid_search\nfrom ray.rllib.models import ModelCatalog\nfrom ray.rllib.models.tf.tf_modelv2 import TFModelV2\nfrom ray.rllib.agents.trainer_template import build_trainer\nfrom ray.rllib.evaluation.postprocessing import discount\nfrom ray.rllib.policy.tf_policy_template import build_tf_policy\n\ntf = try_import_tf()\n\nCANVAS_WIDTH = 64\nOBJ_WIDTH = 10\nN_ITEMS = 2\n\n\nclass CanvasEnv(gym.Env):\n def __init__(self, config):\n self.max_step = 10\n self.cur_step = 0\n self.width = CANVAS_WIDTH\n self.obj_wh = np.array([OBJ_WIDTH, OBJ_WIDTH], dtype=np.float32) / self.width\n self.n_items = N_ITEMS\n\n self.observation_space = spaces.Dict(\n {\n \"target_im\": spaces.Box(\n low=0, high=1, shape=(self.width, self.width, 1)\n ), # (H, W, C)\n \"cur_im\": spaces.Box(\n low=0, high=1, shape=(self.width, self.width, 1)\n ), # (H, W, C)\n \"cur_coord\": spaces.Box(low=-10, high=10, shape=(self.n_items, 4)),\n }\n )\n self.action_space = spaces.Tuple(\n [\n spaces.Discrete(self.n_items), # choosed item\n spaces.Discrete(5), # dx\n spaces.Discrete(5), # dy\n # spaces.Box(low=0, high=self.width, shape=(2,))\n ]\n )\n self.action_map = np.array([-8, 8, -1, 1, 0], dtype=np.float32) / self.width\n\n self.target_im = None\n self.target_coord = None # (n_obj, 4=(x0, y0, x1, y1))\n self.cur_im = None\n self.cur_coord = None # (n_obj, 4=(x0, y0, x1, y1))\n self.viewer = None\n\n def reset(self):\n self.cur_step = 0\n xy0 = np.random.rand(self.n_items, 2)\n self.target_coord = np.concatenate(\n [xy0, xy0 + np.tile(self.obj_wh, (self.n_items, 1))], axis=1\n )\n self.cur_coord = np.tile(\n np.array([0, 0, *tuple(self.obj_wh)], dtype=np.float32), (self.n_items, 1)\n )\n self.target_im = self._render(self.target_coord)\n self.cur_im = self._render(self.cur_coord)\n return self._obs()\n\n def step(self, action):\n \"\"\"\n Args:\n action: [int, int]\n Return:\n obs: target_im (H, W, C), cur_im (H, W, C), field_info (x0, y0)\n \"\"\"\n # print(self.action_map[action[0]], self.action_map[action[1]])\n idx = action[0]\n dmove = np.array(\n [self.action_map[action[1]], self.action_map[action[2]]], dtype=np.float32\n )\n xy0 = self.cur_coord[idx, :2] + dmove\n self.cur_coord[idx] = np.concatenate([xy0, xy0 + self.obj_wh], axis=0)\n self.cur_im = self._render(self.cur_coord)\n\n reward = self._reward(self.cur_coord, self.target_coord)\n\n self.cur_step += 1\n done = self.cur_step >= self.max_step\n\n return self._obs(), reward, done, {}\n\n def _render(self, coord: np.array):\n \"\"\"\n Args: coord: (n_items, 4)\n \"\"\"\n coord = (coord * self.width).astype(np.int16)\n im = Image.new(\"L\", (self.width, self.width))\n draw = ImageDraw.Draw(im)\n for i, c in enumerate(coord):\n if i == 0:\n draw.rectangle(tuple(c), fill=255)\n else:\n draw.ellipse(tuple(c), fill=255)\n x = np.array(im, dtype=np.float32) / 255.0 # normalize\n x = np.expand_dims(x, axis=-1) # (H, W, C=1)\n return x\n\n def _obs(self):\n return {\n \"target_im\": self.target_im,\n \"cur_im\": self.cur_im,\n \"cur_coord\": self.cur_coord,\n }\n\n def _reward(self, xy_a: np.array, xy_b: np.array):\n dist = np.linalg.norm(xy_a - xy_b, axis=1)\n r = -1 * dist / 2 + 1\n r = np.clip(r, -1, None)\n r = np.sum(r)\n # elif r > 0:\n # r *= 0.05 ** self.cur_step # 衰退因子\n return r\n\n def _denorm(self, a: np.array):\n return (a * self.width).astype(np.int16)\n\n def _regression_step(self, action):\n \"\"\"@Deprecated\n Args:\n action: list[obj_id: int, coord: np.array]\n Return:\n obs: target_im (H, W, C), cur_im (H, W, C), field_info (x0, y0)\n \"\"\"\n obj_id, coord = action\n coord *= self.width\n x0, y0 = coord\n self.obj_status = (\n np.array([[x0, y0, (x0 + self.obj_w), (y0 + self.obj_w)]], dtype=np.float32)\n / self.width\n )\n self.cur_im = self._render(x0, y0)\n reward = -(\n ((x0 - self.target_coords[0, 0]) ** 2)\n + ((y0 - self.target_coords[0, 1]) ** 2)\n )\n self.cur_step += 1\n done = self.cur_step >= self.max_step\n return self._obs(), reward, done, {\"episode\": {\"r\": reward}}\n\n def render(self, mode=\"human\", close=False):\n pass\n\n def close(self):\n pass\n\n\nclass MyModel(TFModelV2):\n def __init__(self, obs_space, action_space, num_outputs, model_config, name):\n super(MyModel, self).__init__(\n obs_space, action_space, num_outputs, model_config, name\n )\n input_img = tf.keras.Input(shape=(CANVAS_WIDTH, CANVAS_WIDTH, 1)) # (H, W, C)\n x = tf.keras.layers.Conv2D(8, 3, activation=\"relu\", padding=\"same\")(input_img)\n x = tf.keras.layers.Conv2D(32, 3, activation=\"relu\", padding=\"same\")(x)\n x = tf.keras.layers.Conv2D(64, 3, activation=\"relu\", padding=\"same\")(x)\n x = tf.keras.layers.Conv2D(64, 3, padding=\"same\")(x)\n x = tf.keras.layers.Conv2D(1, 3, padding=\"same\")(x)\n out = tf.keras.layers.Flatten()(x)\n\n cnn_model = tf.keras.Model(input_img, out)\n\n cur_im = tf.keras.Input(shape=(CANVAS_WIDTH, CANVAS_WIDTH, 1))\n target_im = tf.keras.Input(shape=(CANVAS_WIDTH, CANVAS_WIDTH, 1))\n\n # The vision model will be shared, weights and all\n out_cur = cnn_model(cur_im)\n out_target = cnn_model(target_im)\n cur_coord = tf.keras.Input(shape=(N_ITEMS, 4)) # (n_items, 4=(x0, y0, x1, y1))\n\n x = tf.keras.layers.Flatten()(cur_coord)\n x = tf.keras.layers.concatenate([out_cur, out_target, x])\n x = tf.keras.layers.Dense(128, activation=\"relu\")(x)\n x = tf.keras.layers.Dense(128, activation=\"relu\")(x)\n\n layer_out = tf.keras.layers.Dense(num_outputs, activation=None)(x)\n value_out = tf.keras.layers.Dense(1, activation=None)(x)\n\n self.model = tf.keras.Model(\n [cur_im, target_im, cur_coord], [layer_out, value_out]\n )\n self.register_variables(self.model.variables)\n\n def forward(self, input_dict, state, seq_lens):\n model_out, self._value_out = self.model(\n [\n input_dict[\"obs\"][\"cur_im\"],\n input_dict[\"obs\"][\"target_im\"],\n input_dict[\"obs\"][\"cur_coord\"],\n ]\n )\n return model_out, state\n\n def value_function(self):\n return tf.reshape(self._value_out, [-1])\n\n\ndef policy_gradient_loss(policy, model, dist_class, train_batch):\n # print(train_batch)\n logits, _ = model.from_batch(train_batch)\n action_dist = dist_class(logits, model)\n return -tf.reduce_mean(\n action_dist.logp(train_batch[\"actions\"]) * train_batch[\"returns\"]\n )\n\n\ndef calculate_advantages(policy, sample_batch, other_agent_batches=None, episode=None):\n # print(sample_batch)\n sample_batch[\"returns\"] = discount(sample_batch[\"rewards\"], 0.99)\n return sample_batch\n\n\nMyTFPolicy = build_tf_policy(\n name=\"MyTFPolicy\", loss_fn=policy_gradient_loss, postprocess_fn=calculate_advantages\n)\n\nMyTrainer = build_trainer(name=\"MyCustomTrainer\", default_policy=MyTFPolicy)\n\n\nif __name__ == \"__main__\":\n ray.init()\n\n ModelCatalog.register_custom_model(\"my_model\", MyModel)\n ray.tune.registry.register_env(\"canvas\", lambda config: CanvasEnv(config))\n\n tune.run(\n \"PPO\",\n # MyTrainer,\n checkpoint_at_end=True,\n stop={\"timesteps_total\": 1000000},\n config={\n # \"log_level\": \"INFO\",\n \"log_sys_usage\": False,\n \"num_workers\": 7, # parallelism\n \"num_gpus\": 1,\n \"env\": CanvasEnv, # or \"corridor\" if registered above\n # \"env_config\": {\"corridor_length\": 5},\n \"model\": {\"custom_model\": \"my_model\"},\n # \"model_config\": {},\n # \"lr\": grid_search([1e-2, 1e-4, 1e-6]), # try different lrs\n # \"vf_share_layers\": True,\n # \"train_batch_size\": 2000,\n },\n )\n\n # import pickle\n # from ray.rllib.agents import ppo\n\n # with open(\"/root/ray_results/PPO/PPO_CanvasEnv_0_2019-10-03_15-47-36_3odsslh/params.pkl\", \"rb\") as f:\n # config = pickle.load(f)\n # print(config)\n\n # agent = ppo.PPOTrainer(env=\"canvas\", config=config)\n # agent.restore(\"/root/ray_results/PPO/PPO_CanvasEnv_0_2019-10-03_15-47-36_3odsslh/checkpoint_5/checkpoint-5\")\n\n # print(agent.workers)\n\n # from ray.rllib import rollout\n # parser = rollout.create_parser()\n # args = parser.parse_args()\n # args.env = \"canvas\"\n # args.checkpoint = \"\"\n # rollout.run(args, parser)\n","sub_path":"my-rllib/canvas_env.py","file_name":"canvas_env.py","file_ext":"py","file_size_in_byte":9450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"582516724","text":"import io\nimport sys\nf = io.StringIO(\"\"\"4 3\n1 1 1 1\n1 0 1 1\n0 0 0 1\n0 1 1 1\n0 1 1 0\n\"\"\")\nsys.stdin = f\n\n\nf = io.StringIO(\"\"\"10 6\n1 1 1 0 1 1\n1 0 1 1 0 1\n0 0 0 1 1 1\n0 1 1 0 0 0\n1 1 1 1 1 0\n1 0 0 0 0 1\n1 1 0 1 0 1\n0 1 0 0 0 0\n1 1 0 0 1 1\n1 0 1 1 1 0\n\"\"\")\nsys.stdin = f\n\n# -----------------------------------------\n# 逐次最適をとりにいく → AC\n# -----------------------------------------\nfrom copy import deepcopy\n\ndef rm_col(x, drop_j):\n x = deepcopy(x)\n for i in range(n):\n del x[i][drop_j]\n return x\n\n\ndef identifiable_items(x):\n return set(map(\"\".join, map(str, x)))\n\n\nn, l = map(int, input().split())\nx = [list(map(int, input().split())) for _ in range(n)]\n\n\nj = 0\nans = l\nwhile j < len(x[0]):\n # print(f\"j={j}\")\n # 順番にcolをみていって、消せそうだったら消してまた1から順番にcolを見ていく貪欲法\n x_ = rm_col(x, j)\n if len(identifiable_items(x_)) < len(x_):\n j += 1\n else:\n # update\n x = x_\n j = 0 # reset j and restart loop\n if len(x_[0]) < ans:\n ans = len(x_[0])\n\nprint(ans)\n\n\n\n\n\n\n\n\n\n\n\n\n# -----------------------------------------\n# 縦方向に重複する値が多い列を順に消す -> WA\n# -----------------------------------------\n\n\ndef get_diffs(x):\n n_rows = len(x)\n n_cols = len(x[0])\n med = n_rows / 2\n diffs = []\n totals = []\n for j in range(n_cols):\n total = sum([x[i][j] for i in range(n_rows)])\n totals.append(total)\n abs_diff = abs(total - med)\n diffs.append(abs_diff)\n return diffs\n\n\ndef rm_col(x, diffs):\n max_diff = max(diffs)\n drop_j = diffs.index(max_diff)\n for i in range(n):\n del x[i][drop_j]\n return x\n\n\ndef identifiable_items(x):\n return set(map(\"\".join, map(str, x)))\n\n\nn, l = map(int, input().split())\nx = [list(map(int, input().split())) for _ in range(n)]\n\n\nfor _ in range(n*2):\n diffs = get_diffs(x)\n x = rm_col(x, diffs)\n if len(identifiable_items(x)) < len(x):\n ans = n_cols\n break\n n_cols = len(x[0])\n\n\nprint(ans)\n","sub_path":"paiza/A062.py","file_name":"A062.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"458725127","text":"from html.parser import HTMLParser\nimport csv\nfrom os import walk\nfrom os.path import join\nimport sys\n\n# create a subclass and override the handler methods\nclass HTMLProcessor(HTMLParser):\n def __init__(self, type):\n self.html_dict = {}\n self.word_dict = {}\n self.doc = 0\n self.docs = [{'':type}]\n self.type = type\n super().__init__()\n\n def handle_starttag(self, tag, attrs):\n if tag in self.html_dict:\n self.html_dict[tag] += 1\n else:\n self.html_dict[tag] = 1\n\n def handle_endtag(self, tag):\n pass\n\n def handle_data(self, data):\n word_dict = self.docs[self.doc]\n word_data = data.split()\n for x in word_data:\n if x in word_dict:\n word_dict[x] += 1\n else:\n word_dict[x] = 1\n \n def new_doc(self):\n self.docs += [{'':self.type}]\n if self.doc > 0:\n d = self.docs[self.doc]\n for key in d:\n for pd in self.docs[0:self.doc-1]:\n if key not in pd:\n pd[key] = 0\n self.docs[self.doc+1][key] = 0\n self.doc += 1\n\n def get_data_list(self):\n return self.word_data\n\ndef getHeaders(data):\n i = data.index('<')\n head = data[0:i]\n l = filter(lambda x: x != '', head.split('\\n'))\n t = [i.split(':') for i in l]\n d = dict((i[0], i[1].strip()) for i in t)\n return d\n\ndef getHTML(data):\n i = data.index('<')\n return data[i:-1]\n\ndef to_csv(data):\n keys = data[0].keys()\n with open('output.csv', 'w') as f:\n out = csv.DictWriter(f,fieldnames=keys)\n out.writeheader()\n out.writerows(data)\n\nif len(sys.argv) < 3:\n print(\"Usage python gen.py directory class_label\")\n exit()\n\np = HTMLProcessor(sys.argv[2])\n#\"webkb/course/cornell\"\n\ndef digest(processor, c):\n with open(join(sys.argv[1], c)) as f:\n try:\n data = f.read()\n except:\n return\n headers = getHeaders(data)\n html = getHTML(data)\n p.feed(html)\n p.new_doc()\n \n\nfor (dirpath, dirnames, filenames) in walk(sys.argv[1]):\n for c in filenames:\n digest(p, c)\n\nto_csv(p.docs)\n","sub_path":"gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"312281423","text":"# Pipe a console session into this, and it outputs a GitHub markdown version\n# with the commands' output in collapsible
tags.\n#\n# clipv | python twisty_console.py \"❯ \" 2 | gist -p -f console.md\n#\n# The arguments are:\n# prompt marker: the string at the end of your prompt. This must be distinctive\n# lines before (optional): the number of extra lines in your prompt\n\nimport html\nimport sys\n\ndef main(prompt, nbefore=0):\n text = sys.stdin.read()\n print(make_twisty(text, prompt, int(nbefore)))\n\ndef make_twisty(text, prompt, nbefore):\n lines = text.splitlines()\n twisty = []\n twprint = twisty.append\n prompt_line_nums = [n for n, line in enumerate(lines) if prompt.rstrip() in line]\n\n for pnum, npnum in zip(prompt_line_nums, prompt_line_nums[1:] + [-1]):\n prompt_line = lines[pnum].partition(prompt)[2]\n if not prompt_line.strip():\n continue\n twprint(f\"
\\n{html.escape(prompt_line)}\\n\")\n twprint(\"```\")\n output = \"\\n\".join(lines[pnum+1:npnum-nbefore])\n twprint(output)\n twprint(\"```\\n\\n
\\n\")\n return \"\\n\".join(twisty) + \"\\n\"\n\nmain(*sys.argv[1:])\n","sub_path":"twisty_console.py","file_name":"twisty_console.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"391128435","text":"import json \r\nimport re\r\nfrom nltk.tokenize import word_tokenize\r\nfrom nltk.corpus import stopwords\r\n\r\ndata = [json.loads(line) for line in open(\"E:\\MS SEM2\\CIS 593\\Project\\Dataset\\yelp_academic_dataset_review.json\", \"r\", encoding=\"utf8\", errors=\"ignore\")] \r\n\r\ntrue = 0\r\nfalse = 0\r\ntotal = 0\r\n\r\nfull_negative = 0\r\nfull_neutral = 0\r\nfull_positive = 0\r\n\r\npositive = []\r\nwith open(\"E:\\\\MS SEM2\\\\CIS 593\\\\Project\\\\Dataset\\\\positive_words.txt\",'r') as f:\r\n q = f.read().split()\r\n for i in q:\r\n positive.append(i)\r\n commmon_positive = set(q)\r\n\r\n\r\nnegative = []\r\nwith open(\"E:\\\\MS SEM2\\\\CIS 593\\\\Project\\\\Dataset\\\\negative_words.txt\",'r') as f:\r\n q_one = f.read().split()\r\n for i in q_one:\r\n negative.append(i)\r\n commmon_negative = set(q_one)\r\n\r\nfor i in range(1,10000):\r\n abcd = []\r\n abcd = data[i]['text']\r\n abcd_stars = data[i]['stars']\r\n abcd = abcd.lower()\r\n abce = re.sub(r'\\d+', '',abcd) # remove numeric value\r\n abcd = abcd.strip() # removed whitespace\r\n abcd = re.sub(r'[^\\w\\s]','',abcd) #removed punctuations\r\n \r\n\r\n stop_words = set(stopwords.words('english')) # to remove english stop words\r\n tokens = word_tokenize(abcd) #tokenizing whole file\r\n result = [i for i in tokens if not i in stop_words] # for stop words removal\r\n check_one = set(result)\r\n\r\n positive_test = commmon_positive & check_one\r\n negative_test = commmon_negative & check_one \r\n \r\n a = 0\r\n for w1 in positive_test:\r\n word1 = result.count(w1)\r\n a = a + word1 \r\n\r\n b = 0 \r\n for w2 in negative_test:\r\n word2 = result.count(w2)\r\n b = b + word2\r\n \r\n if b > a:\r\n #print(\"Review is Negative\")\r\n #print(\"Real Rating\",abcd_stars)\r\n full_negative = full_negative + 1 \r\n if(abcd_stars == 1 or abcd_stars == 2):\r\n true = true + 1\r\n total = total + 1\r\n else:\r\n false =false + 1\r\n total = total + 1\r\n elif a == b:\r\n #print(\"Review is Neutral\")\r\n #print(\"Real Rating\",abcd_stars)\r\n full_neutral = full_neutral + 1 \r\n if(abcd_stars == 3):\r\n true = true + 1\r\n total = total + 1\r\n else:\r\n false =false + 1\r\n total = total + 1\r\n else:\r\n #print(\"Review is Positive\")\r\n #print(\"Real Rating\",abcd_stars)\r\n full_positive = full_positive + 1 \r\n if(abcd_stars == 4 or abcd_stars == 5):\r\n true = true + 1\r\n total = total + 1\r\n else:\r\n false =false + 1\r\n total = total + 1 \r\n\r\nprint(\"True Positives- \",true)\r\nprint(\"False Positives- \",false)\r\nprint(\"Total Test Cases- \",total)\r\nprint(\"Accuracy- \",true/total)\r\n","sub_path":"Lexicon Sentiment Analysis.py","file_name":"Lexicon Sentiment Analysis.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"282466320","text":"\nfrom string import Template\n\n\"\"\"\nTemplate substitution examples \n\nThe string module provides a Template class. Template strings provide simpler string substitutions.\n\nhttps://docs.python.org/3/library/string.html#string.Template\n\n\"\"\"\ndef main():\n\n ## 1. Using list data for Template substitution\n #\n print(\"1. Using list data for Template substitution \\n\")\n cities = [ \"Singapore Changi\", \"Seoul Incheon\", \"Tokyo Haneda\", \"Hong Kong\" ]\n\n # create a template with placeholders\n template = Template(\"Welcome to ${city} Airport\\n\")\n \n for city in cities :\n # use the substitute method with keyword arguments\n announcement1 = template.substitute(city=city)\n print(announcement1)\n \n\n ## 2. Using dictionary for Template substitution\n #\n print(\"\\n\\n2. Using dictionary for Template substitution\\n\")\n\n # store flight data in dictionary\n records = [ \n { \n \"flight\": \"Singapore Airlines 608\",\n \"to\" : \"Seoul\",\n \"name\": \"John Graham\"\n },\n { \n \"flight\": \"Air France flight 56\",\n \"to\" : \"Boise\",\n \"name\" : \"Peter Francis\"\n },\n { \n \"flight\": \"Norwegian Air UK245\",\n \"to\" : \"New York City\",\n \"name\" : \"Lucy\"\n }\n ]\n \n # create a template with placeholders\n template = Template(\"Welcome to ${flight} to ${to}. My name is ${name} and I'm Your In-flight Service Director.\\n\")\n\n for record in records :\n announcement2 = template.substitute(record) \n print(announcement2)\n\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"basics/template-substitution/template_substitution_examples.py","file_name":"template_substitution_examples.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"111181850","text":"#!/usr/bin/python\n\nfrom types import NoneType\n\ndef IDandOccupancy(cursor, Occupancy):\n IDs = []\n query = \"Select HouseID from hes_database.home_information where Occupancy = %s\" % (Occupancy)\n cursor.execute(query)\n Houses = cursor.fetchall()\n for House in Houses:\n House = House[0]\n IDs.append(House)\n\n return IDs\n\ndef GetInfoId1(cursor):\n IDs = []\n #query = \"Show Tables FROM %s LIKE %s\" % (From_Database, \"'%Id1'\")\n cursor.execute(\"Show Tables FROM House_Sets LIKE '%Id1'\")\n #cursor.execute(query)\n tables = cursor.fetchall()\n for tab in tables:\n IDs.append(tab)\n return IDs\n\ndef GetInfoId2(cursor):\n IDs = []\n cursor.execute(\"Show Tables FROM House_Sets LIKE '%Id2'\")\n tables = cursor.fetchall()\n for tab in tables:\n IDs.append(tab)\n return IDs\n\ndef GetInfoId3(cursor):\n IDs = []\n cursor.execute(\"Show Tables FROM House_Sets LIKE '%Id3'\")\n tables = cursor.fetchall()\n for tab in tables:\n IDs.append(tab)\n return IDs\n\ndef SumTriHourly(cursor,TableNumber):\n #PartOfDay partitioning day up into 8 sections, Section 1 contains hours 0,1,2 \\\n # So on with the other sections\n temp1 = \"Create table temp1 (Data int, Date Date, PartOfDay int)\"\n cursor.execute(temp1)\n Section1 = \"Insert into temp1 (Data,Date,PartOfDay) \\\n SELECT Data, Date, '1' \\\n From %s \\\n Where Hour = 0 or Hour = 1 or Hour = 2\" % (TableNumber)\n\n Section2 = \"Insert into temp1 (Data,Date,PartOfDay) \\\n SELECT Data, Date, '2' \\\n From %s \\\n Where Hour = 3 or Hour = 4 or Hour = 5\" % (TableNumber)\n\n Section3 = \"Insert into temp1 (Data,Date,PartOfDay) \\\n SELECT Data, Date, '3' \\\n From %s \\\n Where Hour = 6 or Hour = 7 or Hour = 8\" % (TableNumber)\n\n Section4 = \"Insert into temp1 (Data,Date,PartOfDay) \\\n SELECT Data, Date, '4' \\\n From %s \\\n Where Hour = 9 or Hour = 10 or Hour = 11\" % (TableNumber)\n\n Section5 = \"Insert into temp1 (Data,Date,PartOfDay) \\\n SELECT Data, Date, '5' \\\n From %s \\\n Where Hour = 12 or Hour = 13 or Hour = 14\" % (TableNumber)\n\n Section6 = \"Insert into temp1 (Data,Date,PartOfDay) \\\n SELECT Data, Date, '6' \\\n From %s \\\n Where Hour = 15 or Hour = 16 or Hour = 17\" % (TableNumber)\n\n Section7 = \"Insert into temp1 (Data,Date,PartOfDay) \\\n SELECT Data, Date, '7' \\\n From %s \\\n Where Hour = 18 or Hour = 19 or Hour = 20\" % (TableNumber)\n\n Section8 = \"Insert into temp1 (Data,Date,PartOfDay) \\\n SELECT Data, Date, '8' \\\n From %s \\\n Where Hour = 21 or Hour = 22 or Hour = 23\" % (TableNumber)\n\n cursor.execute(Section1)\n cursor.execute(Section2)\n cursor.execute(Section3)\n cursor.execute(Section4)\n cursor.execute(Section5)\n cursor.execute(Section6)\n cursor.execute(Section7)\n cursor.execute(Section8)\n\n temp = \"Create table temp(Data int, Date Date, SectionOfDay int)\"\n cursor.execute(temp)\n query = \"INSERT INTO temp (Data,Date,SectionOfDay) \\\n SELECT sum(Data), Date, PartOfDay \\\n FROM temp1 \\\n group by Date, PartOfDay\"\n cursor.execute(query)\n\n cursor.execute(\"drop table temp1\")\n\n\ndef SumHourly(cursor,TableNumber):\n temp = \"Create table temp (Data int, Date Date, Hour int)\"\n cursor.execute(temp)\n query = \"INSERT INTO temp (Data, Date, Hour) \\\n Select sum(Data), Date, Hour \\\n from %s \\\n group by Date, Hour\" % (TableNumber)\n cursor.execute(query)\n\ndef SumDaily(cursor,TableNumber):\n temp = \"Create table temp (Data int,Date Date)\"\n cursor.execute(temp)\n query = \"INSERT INTO temp (Data,Date) \\\n SELECT sum(Data), Date \\\n FROM %s \\\n GROUP BY Date\" % (TableNumber)\n\ndef SumHalfHourly(cursor,TableNumber):\n temp = \"Create table temp (Data int, Date Date, Hour int, Minute int)\"\n cursor.execute(temp)\n query = \"INSERT INTO temp (Data,Date,Hour, Minute) \\\n SELECT SUM(Data), Date, Hour, MIN(Minute) \\\n FROM %s \\\n GROUP BY Date, Hour, FLOOR(Minute/30) \" % (TableNumber)\n cursor.execute(query)\n\n\n\ndef GetHouseIDs(cursor):\n HouseIds = []\n cursor.execute(\"Select Distinct Household from hes_database.appliance_group_data\")\n HouseNumbers = cursor.fetchall()\n for row in HouseNumbers:\n HouseNumber1 = row[\"Household\"]\n HouseIds.append(HouseNumber1)\n return HouseIds\n\n\n\n\n\ndef GetHouseDbsIDs(cursor):\n HouseNumbersDbs = []\n cursor.execute(\"Select Distinct Household from hes_database.appliance_group_data limit 1\")\n HouseNumbers = cursor.fetchall()\n for row in HouseNumbers:\n HouseNumber1 = row[\"Household\"]\n HouseNumber3 = 'n' + HouseNumber1\n HouseNumbersDbs.append(HouseNumber3)\n return HouseNumbersDbs\n\n\ndef AvgPerHour(cursor,Table,HouseNumber):\n AvgHourly = []\n HouseNumber = HouseNumber[0].split('_')[0]\n AvgHourly.append(HouseNumber)\n Hours = range(0,24)\n for hour in Hours:\n\n\n query = \"SELECT avg(Data) as Average \\\n from %s where Hour = %s\" % (Table, hour)\n cursor.execute(query)\n av = cursor.fetchone()\n av = av[0]\n av = float(av)\n AvgHourly.append([hour,av])\n return AvgHourly\n\ndef StdPerHour(cursor,Table,HouseNumber):\n StdHourly = []\n HouseNumber = HouseNumber[0].split('_')[0]\n StdHourly.append(HouseNumber)\n Hours = range(0,24)\n for hour in Hours:\n\n \"\"\"query = \"select sum(Data)/count(distinct Date) as Average \\\n from %s where Hour = %s\" % (Table,hour)\"\"\"\n query = \"SELECT STD(Data) as Average \\\n from %s where Hour = %s\" % (Table, hour)\n cursor.execute(query)\n av = cursor.fetchone()\n av = av[0]\n av = float(av)\n StdHourly.append([hour,av])\n return StdHourly\n\ndef StdAvgPerHour(cursor,Table,HouseNumber):\n StdvAvgHourly = []\n HouseNumber = HouseNumber[0].split('_')[0]\n StdvAvgHourly.append(HouseNumber)\n Hours = range(0,24)\n for hour in Hours:\n\n\n query = \"SELECT avg(Data) as Average, std(Data) as Stdv \\\n from %s where Hour = %s\" % (Table, hour)\n cursor.execute(query)\n av,stdv = cursor.fetchone()\n av = float(av)\n stdv = float(stdv)\n\n\n StdvAvgHourly.append([hour,av,stdv])\n return StdvAvgHourly\n\ndef AvgPerDay(cursor,Table,HouseNumber):\n AvgDaily = []\n HouseNumber = HouseNumber[0].split('_')[0]\n AvgDaily.append(HouseNumber)\n\n Day_of_the_week = \"date_format(Date, '%W')\"\n Days = [\"'Monday'\", \"'Tuesday'\", \"'Wednesday'\", \"'Thursday'\", \\\n \"'Friday'\", \"'Saturday'\", \"'Sunday'\"]\n for day in Days:\n query = \"select AVG(Data) as AvgDay \\\n from %s where %s = %s\" % (Table,Day_of_the_week, day)\n cursor.execute(query)\n apd = cursor.fetchone()\n apd = apd[0]\n if apd is None:\n apd = 0\n else:\n apd = float(apd)\n AvgDaily.append([day,apd])\n return AvgDaily\n\ndef StdPerDay(cursor,Table,HouseNumber):\n StdDaily = []\n HouseNumber = HouseNumber[0].split('_')[0]\n StdDaily.append(HouseNumber)\n\n Day_of_the_week = \"date_format(Date, '%W')\"\n Days = [\"'Monday'\", \"'Tuesday'\", \"'Wednesday'\", \"'Thursday'\", \\\n \"'Friday'\", \"'Saturday'\", \"'Sunday'\"]\n for day in Days:\n query = \"select Std(Data) as AvgDay \\\n from %s where %s = %s\" % (Table,Day_of_the_week, day)\n cursor.execute(query)\n apd = cursor.fetchone()\n apd = apd[0]\n if apd is None:\n apd = 0\n else:\n apd = float(apd)\n StdDaily.append([day,apd])\n return StdDaily\n\ndef StdAvgPerDay(cursor,Table,HouseNumber):\n AvgDaily = []\n HouseNumber = HouseNumber[0].split('_')[0]\n AvgDaily.append(HouseNumber)\n\n Day_of_the_week = \"date_format(Date, '%W')\"\n Days = [\"'Monday'\", \"'Tuesday'\", \"'Wednesday'\", \"'Thursday'\", \\\n \"'Friday'\", \"'Saturday'\", \"'Sunday'\"]\n for day in Days:\n query = \"select AVG(Data) as AvgDay, STD(Data) as Stdv \\\n from %s where %s = %s\" % (Table,Day_of_the_week, day)\n cursor.execute(query)\n apd, std = cursor.fetchone()\n if apd is None:\n apd = 0\n else:\n apd = float(apd)\n\n if std is None:\n std = 0\n else:\n std = float(std)\n AvgDaily.append([day,apd,std])\n return AvgDaily\n\n\ndef AvgPerHourDay(cursor,Table,HouseNumber):\n AvgHourDaily = []\n HouseNumber = HouseNumber[0].split('_')[0]\n AvgHourDaily.append(HouseNumber)\n Hours = range(0,24)\n Day_of_the_week = \"date_format(Date, '%W')\"\n Days = [\"'Monday'\", \"'Tuesday'\", \"'Wednesday'\", \"'Thursday'\", \\\n \"'Friday'\", \"'Saturday'\", \"'Sunday'\"]\n for day in Days:\n for hour in Hours:\n query = \"select AVG(Data) as AvgHourDay \\\n from %s where Hour = %s and %s = %s GROUP BY HOUR\" % (Table,hour, Day_of_the_week, day)\n cursor.execute(query)\n avd = cursor.fetchone()\n if avd is None:\n avd = 0\n else:\n avd = float(avd[0])\n AvgHourDaily.append([day,hour,avd])\n return AvgHourDaily\n\ndef StdAvgPerHourDay(cursor,Table,HouseNumber):\n StdAvgHourDaily = []\n HouseNumber = HouseNumber[0].split('_')[0]\n StdAvgHourDaily.append(HouseNumber)\n Hours = range(0,24)\n Day_of_the_week = \"date_format(Date, '%W')\"\n Days = [\"'Monday'\", \"'Tuesday'\", \"'Wednesday'\", \"'Thursday'\", \\\n \"'Friday'\", \"'Saturday'\", \"'Sunday'\"]\n for day in Days:\n for hour in Hours:\n query = \"select AVG(Data) as AvgHourDay, STD(Data) as StdHourDay \\\n from %s where Hour = %s and %s = %s GROUP BY HOUR\" % (Table,hour, Day_of_the_week, day)\n cursor.execute(query)\n\n thing = cursor.fetchone()\n if thing is None:\n avd = 0\n std = 0\n else:\n avd = float(thing[0])\n std = float(thing[1])\n\n StdAvgHourDaily.append([day,hour,avd,std])\n return StdAvgHourDaily\n\n\n","sub_path":"Sarah's Stuff/PROJECT_SUBMISSION_FOLDER/PYTHON/Total_Profile_Monthly/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":9979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"622413663","text":"import pandas as pd\npd.core.common.is_list_like = pd.api.types.is_list_like\nfrom numpy import NaN\nfrom pandas_datareader import data as pdr\nfrom time import sleep\nfrom requests import get\nfrom bs4 import BeautifulSoup\nfrom json import load,dump\nfrom datetime import datetime\nimport fix_yahoo_finance as yf\nyf.pdr_override() # <== that's all it takes :-)\n\ndef load_business_days():\n with open('hk_business_days.json') as f:\n data = load(f)\n return data\n\ndef clean_yahoo_data(stockDF):\n stockDF = stockDF.replace('null', NaN)\n stockDF = stockDF.astype(float).reset_index()\n businessDays = load_business_days()\n\n stockDF = stockDF[stockDF['Date'].isin(businessDays)]\n\n businessDaysDF = pd.DataFrame(businessDays,columns=['Date'])\n businessDaysDF['Dates'] = pd.to_datetime(businessDays,format='%Y-%m-%d')\n businessDaysDF = businessDaysDF.set_index('Date')\n\n stockDF['Date'] = pd.to_datetime(stockDF[\"Date\"])\n stockDF['CorrectDates'] = businessDaysDF\n\n for column in stockDF.columns:\n if column != 'Date':\n stockDF[column] = stockDF[column].replace(to_replace=0, method='ffill')\n stockDF = stockDF.fillna(method='ffill')\n stockDF = stockDF[['Date','Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']]\n stockDF = stockDF.dropna()\n stockDF.set_index(\"Date\",inplace=True)\n\n stockDF = stockDF[~stockDF.index.duplicated(keep='first')]\n return stockDF\n\ndef getStock(stock, start, end):\n success = False\n fail = False\n check = 0\n while not success:\n try:\n stockDF = pdr.get_data_yahoo(stock, start=start, end=end)\n success = True\n except Exception as e:\n print(stock, \" Retry Attempt:\", check+1)\n print(e)\n check += 1\n if check == 11:\n success = True\n fail = True\n sleep(3)\n if fail:\n return 'Fail'\n stockDF = clean_yahoo_data(stockDF)\n return stockDF\n\ndef aastock_data():\n url = 'http://chartdata1.internet.aastocks.com/servlet/iDataServlet/getdaily?id=110000.HK&type=24&market=1&level=1&period=56&encoding=utf8'\n r = get(url)\n soup = BeautifulSoup(r.content, 'lxml')\n df = []\n headers = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Turnover']\n split1 = str(soup).split('|')[1:-1]\n for i in split1:\n if '!' in i: #after ! are strange data\n break\n i = i.split(';')\n if len(i) == 7:\n df.append(i)\n df = pd.DataFrame(df, columns=headers)\n df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%Y')\n return df\n\n\ndef hk_business_days_update():\n business_days = load_business_days()\n df = aastock_data()\n date_list = df['Date'].astype(str).tolist()\n for element in date_list:\n if element not in business_days:\n business_days.append(element)\n print('Updated to: ', business_days[-1])\n with open('hk_business_days.json', 'w') as outfile:\n dump(business_days, outfile)\n\n\nif __name__ == '__main__':\n getStock('0700.HK',start='2000-01-01',end='2100-01-01')\n # df = load_business_days()\n # df = pd.DataFrame(df,columns=['Date'])\n # df['Dates'] = load_business_days()\n # df = df.set_index('Date')\n # print(df)\n pass\n\n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"404301401","text":"import pandas as pd\r\nimport csv\r\nfrom datetime import datetime\r\nimport numpy as np\r\nimport ctypes\r\nimport os\r\n\r\n\r\ndef select_file():\r\n \"\"\"Get filepath of folder with html doc from user.\"\"\"\r\n import tkinter as tk\r\n from tkinter import filedialog\r\n root = tk.Tk()\r\n root.withdraw()\r\n file_path = filedialog.askopenfilename(\r\n title=\"Select downloaded HTML file of the printable survey with scores\")\r\n return(file_path)\r\n\r\n\r\nfile = select_file()\r\nall_data = pd.read_html(file)[0]\r\nfolder_path = '/'.join(file.split('/')[0:-1])\r\n\r\n# pick and assign title to the CSV output\r\ncsv_title = str((datetime.now().strftime(\r\n \"%Y.%m.%d_%H.%M%p\") + \" Green Globes Export.csv\"))\r\n\r\n\r\ndef is_number(s):\r\n try:\r\n float(s)\r\n if float(s) > -100:\r\n return True\r\n else:\r\n return False\r\n except ValueError:\r\n return False\r\n\r\n\r\nall_data2 = pd.DataFrame()\r\n# format dataframe for export\r\nfor index, row in all_data.iterrows():\r\n if is_number(row[1]) and is_number(row[2]) and row[1] != np.NaN and float(row[1]) >= 0:\r\n #print(index, \"yay it's a number:\", row[1], type(row[1]))\r\n all_data2 = all_data2.append(row)\r\n elif not is_number(row[1]) and not is_number(row[2]) and not is_number(row[3]):\r\n #print(index, \"------its not a number. REMOVE ROW-------------\")\r\n pass\r\n else:\r\n #print(index, \"------its not a number but there are numbers. Remove value and shift left-------------\")\r\n row[1] = row[2]\r\n row[2] = row[3]\r\n row[3] = np.NaN\r\n all_data2 = all_data2.append(row)\r\n\r\n\r\ncsv_file_path = os.path.join(folder_path, csv_title)\r\n# write dataframe to csv\r\nall_data2.to_csv(csv_file_path, encoding='utf-8')\r\nctypes.windll.user32.MessageBoxW(\r\n 0, \"CSV output file has been saved to: \" + csv_file_path, \"Complete\", 1)\r\n","sub_path":"green_globes_public.py","file_name":"green_globes_public.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"536360360","text":"\n\"\"\"\nScript to run an instance of the VoltageScanner class.\nScript will:\n 1) Define the locations to scan\n 2) Read voltage at all of the defined locations\n 3) Save a csv of the collected data\n 4) Display and save a heatmap of the collected data\n\"\"\"\n\n### Imports ###\nfrom time import time\nfrom lab.scanning.voltage_scan import VoltageScanner\n\n### Program variables ###\nscanner_kwargs = {\n # Name for output csv and image\n 'file_name' : 'output', \n # Center of scanning region (mm)\n 'x_center' : 425, \n # Center of scanning region (mm) \n 'y_center' : 425,\n # Size of scanning step (mm) \n 'step_size' : 25.4, \n # Number of scanning steps in x\n 'x_steps' : 5, \n # Number of scanning steps in y\n 'y_steps' : 5, \n # Scanning speed (mm/s)\n 'velocity' : 40 \n }\n\n### Main ###\nscanner = VoltageScanner(**scanner_kwargs)\nscan_locations = scanner.get_scan_locations()\npath_locations = scanner.get_movement_path()\nstart = time()\ndata = scanner.scan_region(scan_locations, path_locations)\nif data is not None:\n end = time()\n runtime = round((end-start)/60, 2)\n print(\"Total scan time: {} min.\".format(runtime))\n scanner.write_output(data)\n scanner.plot_potential(data)\n","sub_path":"jetson/update_machine/examples/scanning/run_volt_scan.py","file_name":"run_volt_scan.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"320479080","text":"'''\nTemperature.py\n\nA cog file to hold functions for the Temperature events of the Colby Gaming Server\n'''\nfrom discord.ext import commands\n\n\nclass Events(commands.Cog):\n def __init__(self, client):\n self.client = client\n\n @commands.Cog.listener()\n async def on_ready(self):\n print(\"\\t- Temperature have loaded\")\n\n @commands.command()\n async def ftoc(self, ctx, temp):\n try:\n temperature = (5 / 9) * (int(temp) - 32)\n string = \"The temperature {}° Fahrenheit is {:.0f}° in Celsius\".format(temp, temperature)\n await ctx.send(string)\n except Exception:\n await ctx.send(\n f\"@{ctx.message.author}, a problem has been encountered with the input {ctx}\\nPlease try again\")\n\n @commands.command()\n async def ctof(self, ctx, temp):\n try:\n temperature = (int(temp) * (9 / 5)) + 32\n string = \"The temperature {}° Celsius is {:.0f}° in Fahrenheit\".format(temp, temperature)\n await ctx.send(string)\n except Exception:\n await ctx.send(\n f\"@{ctx.message.author}, a problem has been encountered with the input {temp}\\nPlease try again\")\n\n\ndef setup(client):\n client.add_cog(Events(client))","sub_path":"cogs/Temperature.py","file_name":"Temperature.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"251041827","text":"'''\nLet's get started!\n\nThis is the main entry point for the project. This will create the databases,\nthen allow for some user input to perform some basic CRUD operations on the\ndata we stored. Give it a try!\n\nCommand Line Arguments:\noptional [-n] - if present, creates a new instance of the MongoDB\n\nCreated: April 22, 2018\nBy: Alexander Gimmi\n'''\n\nimport sys, getopt\nfrom api import etl\nfrom api import crud\nfrom api import models\nfrom pymongo import MongoClient\nfrom pprint import pprint\n\ndef main(argv):\n # Check command line flags to see if we need a new instance of the database\n new_db = False\n try:\n opts, args = getopt.getopt(argv, 'hn')\n except getopt.GetoptError:\n print('main.py [-n]')\n sys.exit(2)\n for opt, arg in opts:\n if opt in ('-h', '--help'):\n print('main.py [-n]')\n sys.exit()\n elif opt in ('-n'):\n new_db = True\n\n if new_db:\n etl.create_database()\n\n # Main Loop\n while True:\n # Take valid user input\n opt = input(\"1. Create\" +\n \"\\n2. Find One\" +\n \"\\n3. Find All\" +\n \"\\n4. Update\" +\n \"\\n5. Delete One\" +\n \"\\n6. Exit\" +\n \"\\nPlease choose one of the above: \")\n\n if not (opt.isdigit() and 1 <= eval(opt) <= 6):\n continue\n elif opt == \"6\":\n break\n\n # Parse user input\n print(\"What collection would you like to perform this action on?\")\n if opt == \"1\":\n create()\n elif opt == \"2\":\n find_one()\n elif opt == \"3\":\n find()\n elif opt == \"4\":\n update_by_id()\n elif opt == \"5\":\n delete_by_id()\n\n# Workflow for creating a new data entry\ndef create():\n collection = get_collection()\n json_data = create_helper(collection.name)\n crud.create(collection, json_data)\n\n# Creates a new json object with user entered data\ndef create_helper(collection_name):\n json_data = {}\n\n if collection_name == \"marvel_heroes\":\n json_data = models.Hero.new().to_json()\n elif collection_name == \"marvel_villains\":\n json_data = models.Villain.new().to_json()\n elif collection_name == \"marvel_stats\":\n json_data = models.Stats.new().to_json()\n\n return json_data\n\n# Workflow for finding a single matching element\ndef find_one():\n collection = get_collection()\n selector = find_helper(collection.name)\n result = crud.find_one(collection, selector)\n\n if result == None:\n print(\"No matching data entry found.\")\n else:\n pprint(result)\n\n# Workflow for finding multiple matching elements\ndef find():\n collection = get_collection()\n selector = find_helper(collection.name)\n result = crud.find(collection, selector)\n\n if result.count() == 0:\n print(\"No matching data entries found.\")\n else:\n for r in result:\n pprint(r)\n\n# Creates a new selector object with user entered data\n# Note: Selectors can contain 1 or many targets - leave unused properties blank\ndef find_helper(collection_name):\n selector = {}\n\n if collection_name == \"marvel_heroes\":\n selector = models.Hero.new().to_selector()\n elif collection_name == \"marvel_villains\":\n selector = models.Villain.new().to_selector()\n elif collection_name == \"marvel_stats\":\n selector = models.Stats.new().to_selector()\n\n return selector\n\n# Workflow for updating a single matching element\ndef update_by_id():\n collection = get_collection()\n selector = {'id' : input(\"ID: \")}\n json_data = create_helper(collection.name)\n if crud.update_one(collection, selector, {'$set' : json_data}) == None:\n print(\"Did not find any entries with the ID \" + selector['id'] + \".\")\n else:\n print(\"Entry with ID \" + selector['id'] + \" successfully updated.\")\n\n# Workflow for deleting a single matching element\ndef delete_by_id():\n collection = get_collection()\n selector = {'id' : input(\"ID: \")}\n if crud.delete_one(collection, selector).deleted_count > 0:\n print(\"Entry with ID \" + selector['id'] + \" successfully deleted.\")\n else:\n print(\"Did not find any entries with ID \" + selector['id'] + \".\")\n\n# Helper function used to determine which collection to act upon\ndef get_collection():\n # Establish a connection to the default local database\n client = MongoClient('localhost', 27017)\n db = client['gimmi']\n\n # Take valid user input\n opt = input(\"1. Hero\" +\n \"\\n2. Villain\" +\n \"\\n3. Stats\" +\n \"\\nPlease choose one of the above: \")\n\n # Parse user input\n if opt == \"1\":\n return db['marvel_heroes']\n elif opt == \"2\":\n return db['marvel_villains']\n elif opt == \"3\":\n return db['marvel_stats']\n else:\n return get_collection()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])","sub_path":"project/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"250148884","text":"def main():\n\n isFirst = False\n previous = \" \"\n isCurrentTupleProcessed = True\n\n buffer = []\n maxBufferLength = 0\n\n r = open(\"R_sorted.tsv\",\"r\")\n s = open(\"S_sorted.tsv\",\"r\")\n output = open(\"RjoinS.tsv\", \"w\")\n\n \n s_line = s.readline()\n s_tuple = (s_line).split('\\t')\n while True:\n \n if isCurrentTupleProcessed: \n r_line = r.readline().rstrip()\n r_tuple = (r_line).split('\\t')\n\n if r_line == '':\n break\n \n if r_tuple[0] == s_tuple[0]:\n buffer.clear()\n\n while r_tuple[0] == s_tuple[0]:\n isFirst = True\n output.write(r_tuple[0] + \"\\t\" + r_tuple[1] + \"\\t\" + s_tuple[1])\n buffer.append(s_tuple[1])\n s_line = s.readline()\n s_tuple = (s_line).split('\\t')\n \n isCurrentTupleProcessed = True\n if len(buffer) > maxBufferLength:\n maxBufferLength = len(buffer)\n \n if isFirst:\n previous = r_tuple[0]\n isFirst = False \n elif r_tuple[0] == previous :\n\n for i in range (0, len(buffer)):\n \n output.write(r_tuple[0] + \"\\t\" + r_tuple[1] + \"\\t\" + buffer[i])\n \n isCurrentTupleProcessed = True \n elif r_tuple[0] != previous:\n \n buffer.clear()\n isCurrentTupleProcessed = True\n\n if r_tuple[0] > s_tuple[0] and s_line != '':\n isCurrentTupleProcessed = False\n s_line = s.readline()\n s_tuple = (s_line).split('\\t') \n \n output.close()\n print(\"The maximum buffer length is \"+str(maxBufferLength))\n \nif __name__ == '__main__':\n \n main()\nelse:\n \n pass\n","sub_path":"merge-join.py","file_name":"merge-join.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"218343874","text":"__author__ = 'anna'\n\nclass Node(object):\n\n def __init__(self, data=None, next_node=None):\n self.data = data\n self.next = next_node\n def __str__(self):\n return str(self.data)\n\ndef CompareLists(headA, headB):\n while headA and headB is not None:\n if headA.data != headB.data and headA.next != headB.next: return 0\n else:\n headA = headA.next\n headB = headB.next\n return 1\n\ndef main():\n node1, node2, node3, node4 = Node(1), Node(2), Node(3), Node(4)\n node1.next = node2\n node2.next = node3\n node3.next = node4\n\n node_1, node_2, node_3, node_4 = Node(1), Node(2), Node(3), Node(4)\n node_1.next = node_2\n node_2.next = node_3\n node_3.next = node_4\n\n\n print(CompareLists(node1, node_1))\n\nmain()\n\n","sub_path":"Hackerrank/Data_structures/Linked_lists/compaire_two_linked_lists.py","file_name":"compaire_two_linked_lists.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"226191361","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nMathematical models\n\"\"\"\nfrom __future__ import division\nimport collections\nimport numpy as np\nfrom . import parameters\nfrom .core import ParametricModel, Parametric1DModel, Model, _convert_input, _convert_output\nfrom .utils import InputParameterError, ModelDefinitionError\n\n__all__ = ['Gaussian1DModel', 'Gaussian2DModel', 'ScaleModel', 'ShiftModel',\n 'Custom1DModel', 'Sine1DModel', 'Linear1DModel', 'PowerLaw1DModel',\n 'Const1DModel', 'Lorentz1DModel', 'Box1DModel']\n\n\nclass Gaussian1DModel(Parametric1DModel):\n\n \"\"\"\n\n Implements 1D Gaussian model.\n\n Parameters\n ----------\n amplitude : float\n Amplitude of the gaussian\n mean : float\n Mean of the gaussian\n stddev : float\n Standard deviation of the gaussian\n \"\"\"\n\n param_names = ['amplitude', 'mean', 'stddev']\n\n def __init__(self, amplitude, mean, stddev, **cons):\n super(Gaussian1DModel, self).__init__(locals(), **cons)\n\n def eval(self, x, amplitude, mean, stddev):\n \"\"\"\n Model function Gauss1D\n \"\"\"\n return amplitude * np.exp(- 0.5 * (x - mean) ** 2 / stddev ** 2)\n\n def deriv(self, x, amplitude, mean, stddev):\n \"\"\"\n Model function derivatives Gauss1D\n \"\"\"\n d_amplitude = np.exp(-0.5 / stddev ** 2 * (x - mean) ** 2)\n d_mean = (amplitude * np.exp(-0.5 / stddev ** 2 * (x - mean) ** 2)\n * (x - mean) / stddev ** 2)\n d_stddev = (amplitude * np.exp(-0.5 / stddev ** 2 * (x - mean) ** 2)\n * (x - mean) ** 2 / stddev ** 3)\n return [d_amplitude, d_mean, d_stddev]\n\n\nclass Gaussian2DModel(ParametricModel):\n\n \"\"\"\n\n 2D Gaussian.\n\n Parameters\n ----------\n amplitude : float\n Amplitude of the gaussian\n x_mean : float\n Mean of the gaussian in x\n y_mean : float\n Mean of the gaussian in y\n x_stddev : float\n Standard deviation of the gaussian in x\n Either x_fwhm or x_stddev must be specified\n y_stddev : float\n Standard deviation of the gaussian in y\n Either y_fwhm or y_stddev must be specified\n theta : float\n Rotation angle in radians. Note: increases clockwise.\n x_fwhm : float\n Full width at half maximum in x\n Either x_fwhm or x_stddev must be specified\n y_fwhm : float\n Full width at half maximum in y\n Either y_fwhm or y_stddev must be specified\n jacobian_func : callable or None\n if callable - a function to compute the Jacobian of\n func with derivatives across the rows.\n if None - the Jacobian will be estimated\n cov_matrix : ndarray\n A 2x2 covariance matrix. If specified, overrides stddev, fwhm, and\n theta specification.\n \"\"\"\n\n param_names = ['amplitude', 'x_mean', 'y_mean',\n 'x_stddev', 'y_stddev', 'theta']\n\n def __init__(self, amplitude, x_mean, y_mean, x_stddev=None, y_stddev=None,\n theta=0.0, x_fwhm=None, y_fwhm=None, cov_matrix=None,\n jacobian_func=None, **cons):\n\n try:\n param_dim = len(amplitude)\n except TypeError:\n param_dim = 1\n\n if y_stddev is None and y_fwhm is None and cov_matrix is None:\n raise InputParameterError(\n \"Either y_fwhm or y_stddev must be specified, or a \"\n \"covariance matrix.\")\n elif x_stddev is None and x_fwhm is None and cov_matrix is None:\n raise InputParameterError(\n \"Either x_fwhm or x_stddev must be specified, or a \"\n \"covariance matrix.\")\n elif x_stddev is not None and x_fwhm is not None:\n raise InputParameterError(\"Cannot specify both x_fwhm and x_stddev\")\n elif y_stddev is not None and y_fwhm is not None:\n raise InputParameterError(\"Cannot specify both y_fwhm and y_stddev\")\n elif cov_matrix is not None and (x_stddev is not None or\n y_stddev is not None or\n x_fwhm is not None or\n y_fwhm is not None):\n raise InputParameterError(\"Cannot specify both cov_matrix and x/y_stddev or x/y_fwhm\")\n\n self._amplitude = parameters.Parameter('amplitude', amplitude,\n self, param_dim)\n if cov_matrix is None:\n if x_stddev is None:\n x_stddev = 0.42466 * x_fwhm\n if y_stddev is None:\n y_stddev = 0.42466 * y_fwhm\n else:\n cov_matrix = np.array(cov_matrix)\n assert cov_matrix.shape == (2, 2), \"Covariance matrix must be 2D\"\n eig_vals, eig_vecs = np.linalg.eig(cov_matrix)\n x_stddev, y_stddev = np.sqrt(eig_vals)\n y_vec = eig_vecs[:, 0]\n theta = np.arctan2(y_vec[1], y_vec[0])\n\n self._x_stddev = parameters.Parameter('x_stddev', x_stddev,\n self, param_dim)\n self._y_stddev = parameters.Parameter('y_stddev', y_stddev,\n self, param_dim)\n self._x_mean = parameters.Parameter('x_mean', x_mean, self, param_dim)\n self._y_mean = parameters.Parameter('y_mean', y_mean, self, param_dim)\n self._theta = parameters.Parameter('theta', theta, self, param_dim)\n\n super(Gaussian2DModel, self).__init__(self.param_names, n_inputs=2, n_outputs=1,\n param_dim=param_dim, **cons)\n self.linear = False\n if jacobian_func:\n self.deriv = jacobian_func\n else:\n self.deriv = None\n\n def eval(self, x, y, params):\n \"\"\"\n Evaluate the model.\n\n Parameters\n ----------\n x : array like or a number\n input\n y : dummy variable - array like or a number\n input\n params : array\n parameter sets\n \"\"\"\n a = 0.5 * ((np.cos(params[5]) / params[3]) ** 2 +\n (np.sin(params[5]) / params[4]) ** 2)\n b = 0.5 * (np.cos(params[5]) * np.sin(params[5]) *\n (1. / params[3] ** 2 - 1. / params[4] ** 2))\n c = 0.5 * ((np.sin(params[5]) / params[3]) ** 2 +\n (np.cos(params[5]) / params[4]) ** 2)\n\n return params[0] * np.exp(-(a * (x - params[1]) ** 2 +\n b * (x - params[1]) * (y - params[2]) +\n c * (y - params[2]) ** 2))\n\n def __call__(self, x, y):\n \"\"\"\n Transforms data using this model.\n\n Parameters\n ----------\n x : array like or a number\n input\n y : array like or a number\n input\n\n \"\"\"\n x, _ = _convert_input(x, self.param_dim)\n y, fmt = _convert_input(y, self.param_dim)\n result = self.eval(x, y, self.param_sets)\n return _convert_output(result, fmt)\n\n\nclass ShiftModel(Model):\n\n \"\"\"\n Shift a coordinate.\n\n Parameters\n ----------\n offsets : float or a list of floats\n offsets to be applied to a coordinate\n if a list - each value in the list is an offset to be applied to a\n column in the input coordinate array\n\n \"\"\"\n param_names = ['offsets']\n\n def __init__(self, offsets):\n if not isinstance(offsets, collections.Sequence):\n param_dim = 1\n else:\n param_dim = len(offsets)\n self._offsets = parameters.Parameter('offsets', offsets, self, param_dim)\n super(ShiftModel, self).__init__(self.param_names, n_inputs=1, n_outputs=1,\n param_dim=param_dim)\n\n def inverse(self):\n if self.param_dim == 1:\n return ShiftModel(offsets=(-1) * self.offsets[0])\n else:\n return ShiftModel(offsets=[off * (-1) for off in self._offsets])\n\n def __call__(self, x):\n \"\"\"\n Transforms data using this model.\n\n Parameters\n ----------\n x : array like or a number\n input\n \"\"\"\n x, fmt = _convert_input(x, self.param_dim)\n result = x + self.offsets\n return _convert_output(result, fmt)\n\n\nclass ScaleModel(Model):\n\n \"\"\"\n\n Multiply a model by a factor.\n\n Parameters\n ----------\n factors : float or a list of floats\n scale for a coordinate\n\n \"\"\"\n param_names = ['factors']\n\n def __init__(self, factors):\n if not isinstance(factors, collections.Sequence):\n param_dim = 1\n else:\n param_dim = len(factors)\n self._factors = parameters.Parameter('factors', factors, self, param_dim)\n super(ScaleModel, self).__init__(self.param_names, n_inputs=1, n_outputs=1,\n param_dim=param_dim)\n\n def inverse(self):\n if self.param_dim == 1:\n return ScaleModel(factors=1. / self.factors[0])\n else:\n return ScaleModel(factors=[1 / factor for factor in self._factors])\n\n def __call__(self, x):\n \"\"\"\n Transforms data using this model.\n\n Parameters\n ----------\n x : array like or a number\n input\n \"\"\"\n x, fmt = _convert_input(x, self.param_dim)\n result = x * self.factors\n return _convert_output(result, fmt)\n\n\nclass PowerLaw1DModel(Parametric1DModel):\n\n \"\"\"\n A power law model.\n\n The model is of the form :math:`A x^\\\\alpha`, where :math:`A` is\n the `scale` parameter, and :math:`\\\\alpha` is `alpha`.\n\n Parameters\n ----------\n scale : float\n Model scale\n alpha : float\n power\n\n Notes\n -----\n Model formula:\n f(x) = scale * x ** (-alpha)\n \"\"\"\n param_names = ['scale', 'alpha']\n\n def __init__(self, scale, alpha):\n super(PowerLaw1DModel, self).__init__(locals())\n\n def eval(self, x, scale, alpha):\n \"\"\"\n Model function PowerLaw1D\n \"\"\"\n return scale * x ** (-alpha)\n\n def deriv(self, x, scale, alpha):\n \"\"\"\n Model derivative PowerLaw1D\n \"\"\"\n d_scale = x ** (-alpha)\n d_alpha = scale * ((x) ** (-alpha)) * np.log(x)\n return [d_scale, d_alpha]\n\n\nclass Sine1DModel(Parametric1DModel):\n\n \"\"\"\n One dimensional sine model.\n\n Parameters\n ----------\n amplitude : float\n Oscillation amplitude\n frequency : float\n Oscillation frequency\n\n Notes\n -----\n Model formula:\n f(x) = amplitude * np.sin(2 * np.pi * frequency * x)\n \"\"\"\n param_names = ['amplitude', 'frequency']\n\n def __init__(self, amplitude, frequency):\n super(Sine1DModel, self).__init__(locals())\n\n def eval(self, x, amplitude, frequency):\n \"\"\"\n Model function Sine1D\n \"\"\"\n return amplitude * np.sin(2 * np.pi * frequency * x)\n\n def deriv(self, x, amplitude, frequency):\n \"\"\"\n Model function Sine1D\n \"\"\"\n d_amplitude = np.sin(2 * np.pi * frequency * x)\n d_frequency = (2 * np.pi * x * amplitude\n * np.cos(2 * np.pi * frequency * x))\n return [d_amplitude, d_frequency]\n\n\nclass Linear1DModel(Parametric1DModel):\n\n \"\"\"\n Simple one dimensional straight line model.\n\n Parameters\n ----------\n slope : float\n Slope of the straight line\n\n intercept : float\n Intercept of the straight line\n\n Notes\n -----\n Model formula:\n f(x) = slope * x + intercept\n \"\"\"\n param_names = ['slope', 'intercept']\n\n def __init__(self, slope, intercept):\n super(Linear1DModel, self).__init__(locals())\n self.linear = True\n\n def eval(self, x, slope, intercept):\n \"\"\"\n Model function Linear1D\n \"\"\"\n return slope * x + intercept\n\n def deriv(self, x, slope, intercept):\n \"\"\"\n Model function derivatives Linear1D\n \"\"\"\n d_slope = x\n d_intercept = np.ones_like(x)\n return [d_slope, d_intercept]\n\n\nclass Lorentz1DModel(Parametric1DModel):\n\n \"\"\"\n One dimensional Lorentzian function.\n\n Parameters\n ----------\n amplitude : float\n Peak value\n x_0 : float\n Position of the peak\n fwhm : float\n Full width at half maximum\n\n Notes\n -----\n Model formula:\n f(x) = amplitude * ((fwhm / 2.) ** 2) / ((x - x_0) ** 2 + (fwhm / 2.) ** 2)\n \"\"\"\n param_names = ['amplitude', 'x_0', 'fwhm']\n\n def __init__(self, amplitude, x_0, fwhm):\n super(Lorentz1DModel, self).__init__(locals())\n\n def eval(self, x, amplitude, x_0, fwhm):\n \"\"\"\n Model function Lorentz1D\n \"\"\"\n return amplitude * ((fwhm / 2.) ** 2) / ((x - x_0) ** 2 + (fwhm / 2.) ** 2)\n\n\nclass Const1DModel(Parametric1DModel):\n\n \"\"\"\n One dimensional constant function.\n\n Parameters\n ----------\n amplitude : float\n Value of the constant function\n\n Notes\n -----\n Model formula:\n f(x) = amplitude\n \"\"\"\n param_names = ['amplitude']\n\n def __init__(self, amplitude):\n super(Const1DModel, self).__init__(locals())\n\n def eval(self, x, amplitude):\n \"\"\"\n Model function Const1D\n \"\"\"\n return amplitude\n\n def deriv(self, x, amplitude):\n \"\"\"\n Model function derivatives Const1D\n \"\"\"\n d_amplitude = np.ones_like(x)\n return [d_amplitude]\n\n\nclass Const2DModel(ParametricModel):\n\n \"\"\"\n Two dimensional constant function.\n \"\"\"\n def __init__(self):\n raise ModelDefinitionError(\"Not implemented\")\n\n\nclass Disk2DModel(ParametricModel):\n\n \"\"\"\n Two dimensional radial symmetric box function.\n \"\"\"\n def __init__(self):\n raise ModelDefinitionError(\"Not implemented\")\n\n\nclass Delta1DModel(Parametric1DModel):\n\n \"\"\"\n One dimensional Dirac delta function\n \"\"\"\n def __init__(self):\n raise ModelDefinitionError(\"Not implemented\")\n\n\nclass Box1DModel(Parametric1DModel):\n\n \"\"\"\n One dimensional box function.\n\n Parameters\n ----------\n amplitude : float\n Amplitude A\n x_0 : float\n Position of the center of the box function\n width : float\n Width of the box\n\n Notes\n -----\n Model function:\n f(x) = np.select([x >= x_0 - width / 2., x <= x_0 + width / 2.],\n [amplitude, amplitude])\n\n Note that at f(x_0 - width / 2.) = f(x_0 + width / 2.) = amplitude.\n \"\"\"\n param_names = ['amplitude', 'x_0', 'width']\n\n def __init__(self, amplitude, x_0, width):\n super(Box1DModel, self).__init__(locals())\n\n def eval(self, x, amplitude, x_0, width):\n \"\"\"\n Model function Box1D\n \"\"\"\n return np.select([np.logical_and(x >= x_0 - width / 2., x <= x_0 + width / 2.)],\n [amplitude])\n\n def deriv(self, x, amplitude, x_0, width):\n \"\"\"\n Model function derivatives Box1D\n \"\"\"\n d_amplitude = self.eval(x, 1, x_0, width)\n d_x_0 = np.zeros_like(x)\n d_width = np.zeros_like(x)\n return [d_amplitude, d_x_0, d_width]\n\n\nclass Box2DModel(ParametricModel):\n\n \"\"\"\n Two dimensional box function.\n \"\"\"\n def __init__(self):\n raise ModelDefinitionError(\"Not implemented\")\n\n\nclass MexicanHat1DModel(ParametricModel):\n\n \"\"\"\n One dimensional mexican hat function.\n \"\"\"\n def __init__(self):\n raise ModelDefinitionError(\"Not implemented\")\n\n\nclass MexicanHat2DModel(ParametricModel):\n\n \"\"\"\n Two dimensional mexican hat function.\n \"\"\"\n def __init__(self):\n raise ModelDefinitionError(\"Not implemented\")\n\n\nclass Custom1DModel(Parametric1DModel):\n\n \"\"\"\n Create one dimensional model from a user defined function.\n\n IMPORTANT: All model parameters have to be defined as KEYWORD ARGUMENTS\n with default values in the model function.\n\n If you want to work with parameter sets, the parameters have to be defined\n as lists.\n\n Parameters\n ----------\n func : function\n Function which defines the model\n func_deriv : function\n Function which defines the model derivatives default = None\n\n Examples\n --------\n Define a sinusoidal model function:\n\n >>> from astropy.modeling.models import Custom1DModel\n >>> import numpy as np\n >>> def f(x, amplitude=1., frequency=1.):\n ... return amplitude * np.sin(2 * np.pi * frequency * x)\n\n And create a custom one dimensional model from it:\n\n >>> sin_model = Custom1DModel(f)\n >>> sin_model(0.25)\n 1.0\n\n This model instance can now be used like a usual astropy model.\n \"\"\"\n\n def __init__(self, func, func_deriv=None):\n if callable(func):\n self._func = func\n else:\n raise ModelDefinitionError(\"Not callable. Must be function\")\n\n param_values = func.func_defaults\n\n # Check if all parameters are keyword arguments\n if func.func_code.co_argcount == len(param_values) + 1:\n self.param_names = func.func_code.co_varnames[1:1 + len(param_values)]\n else:\n raise ModelDefinitionError(\"All parameters must be keyword arguments\")\n param_dict = dict(zip(self.param_names, param_values))\n super(Custom1DModel, self).__init__(param_dict)\n\n def eval(self, x, *params):\n \"\"\"\n Model function Custom1D\n \"\"\"\n return self._func(x, *params)\n","sub_path":"astropy/modeling/functional_models.py","file_name":"functional_models.py","file_ext":"py","file_size_in_byte":17520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"341407052","text":"#!/usr/bin/env python3\n\n\"\"\"Problem 46: Goldbach's other conjecture\"\"\"\n\nfrom utils import is_prime\n\n\ndef main():\n primes = {2}\n n = 3\n\n while True:\n if is_prime(n):\n primes.add(n)\n else:\n i = 1\n while 2*i*i < n:\n if n - 2*i*i in primes:\n break\n i += 1\n else:\n return n\n n += 2\n\nif __name__ == \"__main__\":\n print(main())\n","sub_path":"python/p046.py","file_name":"p046.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"272010442","text":"import os\nimport telebot\nfrom telebot import types,util\n\ntoken = os.getenv('API_KEY')\nbot = telebot.TeleBot('token', parse_mode=None)\n\n@bot.message_handler(commands=['Greet'])\ndef greet(message):\n bot.send_message(message, \"Hey, how's it going?\")\n\n@bot.message_handler(commands=['Hello'])\ndef hello(message):\n bot.send_message(message.chat.id, \"Welcome to Polkadot India Official\")\n\n@bot.chat_member_handler()\ndef chat_m(message: types.ChatMemberUpdated):\n old = message.old_chat_member\n new = message.new_chat_member\n if new.status == \"member\":\n bot.send_message(message.chat.id,\"Hello {name}! Welcome to Polkadot India. Checked pinned messages for more information\".format(name=new.user.first_name)) # Welcome message\n# To keep checking for the messages\n#bot.polling()\nbot.polling(allowed_updates=util.update_types)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"642004839","text":"from __future__ import print_function\nimport time\nimport thread\n\nclass Task:\n def __init__(self, function_to_run, interval):\n self.function_to_run = function_to_run\n self.interval = interval\n\nclass Worker:\n def __init__(self):\n self.queue = {}\n\n def add(self, item, exec_time, repetition_time):\n new_task = Task(item, repetition_time)\n if exec_time in self.queue:\n self.queue[exec_time].append(new_task)\n else:\n self.queue[exec_time] = [new_task]\n\n def run(self):\n current_time = 0\n while True:\n if current_time in self.queue:\n for task in self.queue[current_time]:\n thread.start_new_thread(task.function_to_run, ())\n self.add(task.function_to_run,\n current_time + task.interval, task.interval)\n time.sleep(1)\n current_time += 1\n\nworker = Worker()\n\nworker.add(lambda : print(\"One second\"), 1, 1)\nworker.add(lambda : print(\"Two seconds\"), 1, 2)\n#worker.add(lambda : print(\"One seconds again\"), 1)\n\nworker.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"304396770","text":"\"\"\"People Counter.\"\"\"\n\"\"\"\n Copyright (c) 2018 Intel Corporation.\n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n \"Software\"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and/or sell copies of the Software, and to\n permit person to whom the Software is furnished to do so, subject to\n the following conditions:\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n\nimport os\nimport sys\nimport time\nimport socket\nimport json\nimport cv2\n\nimport numpy as np\n\nimport logging as log\nimport paho.mqtt.client as mqtt\n\nfrom argparse import ArgumentParser\nfrom inference import Network\n\nimport utils\nimport metrics\nfrom transitions import Machine\nfrom frameAnalysisStateMachine import frmAnalyisSM\n\nfrom utils import release , drawBBoxes\n\n\n# MQTT server environment variables\nHOSTNAME = socket.gethostname()\nIPADDRESS = socket.gethostbyname(HOSTNAME)\nMQTT_HOST = IPADDRESS\nMQTT_PORT = 3001\nMQTT_KEEPALIVE_INTERVAL = 60\n\nframeProcessor = frmAnalyisSM()\nmachine = Machine(frameProcessor, ['PersonIn', 'PersonOut'], initial='PersonOut')\nmachine.add_transition('newPersonEntered', 'PersonOut', 'PersonIn', before='durationStats')\n\n\ndef build_argparser():\n \"\"\"\n Parse command line arguments.\n\n :return: command line arguments\n \"\"\"\n parser = ArgumentParser()\n parser.add_argument(\"-m\", \"--model\", required=True, type=str,\n help=\"Path to an xml file with a trained model.\")\n parser.add_argument(\"-i\", \"--input\", required=True, type=str,\n help=\"Path to image or video file\")\n parser.add_argument(\"-l\", \"--cpu_extension\", required=False, type=str,\n default=None,\n help=\"MKLDNN (CPU)-targeted custom layers.\"\n \"Absolute path to a shared library with the\"\n \"kernels impl.\")\n parser.add_argument(\"-d\", \"--device\", type=str, default=\"CPU\",\n help=\"Specify the target device to infer on: \"\n \"CPU, GPU, FPGA or MYRIAD is acceptable. Sample \"\n \"will look for a suitable plugin for device \"\n \"specified (CPU by default)\")\n parser.add_argument(\"-pt\", \"--prob_threshold\", type=float, default=0.5,\n help=\"Probability threshold for detections filtering\"\n \"(0.5 by default)\")\n return parser\n\n\ndef connect_mqtt():\n # Connect to the MQTT client\n\n client = mqtt.Client()\n client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)\n\n return client\n\ndef infer_on_stream(args, client):\n\n isImage = False\n\n # Handle the input stream \n if args.input != 'CAM':\n assert os.path.isfile(args.input)\n \n\n if args.input == 'CAM':\n args.input = 0\n elif args.input.endswith(('.jpg', '.bmp', '.png')):\n isImage = True\n\n\n last_count = 0\n total_count = 0\n durationList = []\n inferenceList = []\n f_n = 0 #False Negatives for analysis purpose...\n\n # Initialise the class\n infer_network = Network()\n\n # Set Probability threshold for detections\n prob_threshold = args.prob_threshold\n\n # Load the model through `infer_network`\n mdl_start = cv2.getTickCount() \n \n infer_network.load_model(args.model, args.device, args.cpu_extension)\n load_time = utils.timeLapse(mdl_start)\n \n cap = cv2.VideoCapture(args.input)\n cap.open(args.input)\n\n if not cap.isOpened():\n log.error(\"ERROR! Unable to open video source\")\n exit(1)\n\n w,h = utils.getSrcDim(cap) #dimensions from the captured source\n\n if not isImage:\n out = cv2.VideoWriter('out.mp4',utils.getCODEC(), cap.get(cv2.CAP_PROP_FPS), (w,h))\n else:\n out = None\n\n\n\n #Loop until stream is over\n while cap.isOpened():\n # Read from the video capture \n flag, frame = cap.read()\n if not flag:\n break\n key_pressed = cv2.waitKey(60)\n\n # Pre-process the image as needed \n p_frame = utils.preprocessed_input(infer_network,frame)\n\n # Start asynchronous inference for specified request \n inf_start = time.time()\n infer_network.exec_net(p_frame,request_id=0)\n\n # Wait for the result \n if infer_network.wait(request_id=0) == 0:\n det_time = time.time() - inf_start\n inferenceList.append(det_time * 1000)\n\n # Get the results of the inference request \n result = infer_network.get_output(request_id=0)\n \n # Extract any desired stats from the results \n frame, count , f_n = drawBBoxes(frame, result, prob_threshold, w, h,last_count,f_n)\n \n\n # Calculate and send relevant information on \n inf_time_message = \"Inference time: {:.3f}ms\".format(det_time * 1000)\n cv2.putText(frame, inf_time_message, (15, 15),cv2.FONT_HERSHEY_COMPLEX, 0.5, (200, 10, 10), 1)\n\n # When new person enters the video\n if count > last_count:\n\n frameProcessor.to_PersonOut() # re-assuring by Setting Previous person to have moved out.\n frameProcessor.newPersonEntered() #Set the state as new person entered and initialize timer.\n total_count = total_count + count - last_count\n client.publish(\"person\", json.dumps({\"total\": total_count}))\n\n ''' \n log.info('Entered Scene at MS {}'.format(cap.get(cv2.CAP_PROP_POS_MSEC)))\n log.info('Entered Scene at FRM {}'.format(cap.get(cv2.CAP_PROP_POS_FRAMES)))\n log.info('Entered Scene at AVI {}'.format(cap.get(cv2.CAP_PROP_POS_AVI_RATIO)))\n log.info('Frame Rate {}'.format(cap.get(cv2.CAP_PROP_FPS)))\n \n ## The logic of calculating duration with above CV2 attribs worked fine.\n ## But realised it may not work in CAM mode.. so need to build a generic logic.\n '''\n\n # current_count, total_count and duration to the MQTT server \n # Person duration in the video is calculated\n\n # Topic \"person\": keys of \"count\" and \"total\" \n # Topic \"person/duration\": key of \"duration\" \n if count < last_count:\n duration = float(time.time() - frameProcessor.getPersonEntrytime())\n frameProcessor.to_PersonOut()\n durationList.append(duration)\n\n # Publish average duration spent by people to the MQTT server\n client.publish(\"person/duration\", json.dumps({\"duration\": round(np.mean(durationList)) }))\n\n client.publish(\"person\", json.dumps({\"count\": count}))\n last_count = count\n\n \n if key_pressed == 27:\n break\n\n # Send the frame to the FFMPEG server \n sys.stdout.buffer.write(frame) \n sys.stdout.flush()\n\n # Write an output image if `single_image_mode` \n if isImage:\n cv2.imwrite('output/output_image.jpg', frame)\n else:\n out.write(frame)\n\n\n\n \n log.info('######################################################')\n log.info('# Average Inference Time :: {:.3f} ms'.format(np.mean(inferenceList)))\n log.info('# (IR) Model Size (XML) :: {}'.format(metrics.getSize(utils.getMOFiles(args.model)['model'])))\n log.info('# (IR) Model Weight (BIN) :: {}'.format(metrics.getSize(utils.getMOFiles(args.model)['weights'])))\n log.info('# Total Model Load Time :: {:.3f} ms'.format(load_time))\n log.info('# Set Probability Threshold :: {}'.format(prob_threshold))\n log.info('# No. of False Negatives @ 0.75 & 0.5 times of the set threhold :: {}'.format(f_n))\n log.info('# Error_percent in detecting Total ppl :: {}'.format(metrics.getErrorPercent(total_count,\"people\")))\n log.info('# Error_percent in average duration :: {}'.format(metrics.getErrorPercent(round(np.mean(durationList)),\"duration\")))\n log.info('######################################################')\n \n\n\n release(out,cap,client)\n\n\n\ndef main():\n \"\"\"\n Load the network and parse the output.\n\n :return: None\n \"\"\"\n # Grab command line args\n args = build_argparser().parse_args()\n # Connect to the MQTT server\n client = connect_mqtt()\n # Perform inference on the input stream\n infer_on_stream(args, client)\n\n \n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"470694121","text":"\"\"\"\n================\n99. Make reports\n================\n\nBuilds an HTML report for each subject containing all the relevant analysis\nplots.\n\"\"\"\n\nimport os.path as op\nimport itertools\nimport logging\n\nimport mne\nfrom mne.parallel import parallel_func\nfrom mne_bids import make_bids_basename\n\nimport config\nfrom config import gen_log_message, on_error, failsafe_run\n\nlogger = logging.getLogger('mne-study-template')\n\n\ndef plot_events(subject, session, deriv_path):\n raws_filt = []\n for run in config.get_runs():\n bids_basename = make_bids_basename(subject=subject,\n session=session,\n task=config.get_task(),\n acquisition=config.acq,\n run=run,\n processing=config.proc,\n recording=config.rec,\n space=config.space)\n fname = op.join(deriv_path, bids_basename + '_filt_raw.fif')\n raw_filt = mne.io.read_raw_fif(fname)\n raws_filt.append(raw_filt)\n del fname\n\n # Concatenate the filtered raws and extract the events.\n raw_filt_concat = mne.concatenate_raws(raws_filt)\n events, event_id = mne.events_from_annotations(raw=raw_filt_concat)\n fig = mne.viz.plot_events(events=events, event_id=event_id,\n first_samp=raw_filt_concat.first_samp,\n sfreq=raw_filt_concat.info['sfreq'],\n show=False)\n return fig\n\n\ndef plot_er_psd(subject, session):\n deriv_path = config.get_subject_deriv_path(subject=subject,\n session=session,\n kind=config.get_kind())\n\n bids_basename = make_bids_basename(subject=subject,\n session=session,\n task=config.get_task(),\n acquisition=config.acq,\n run=None,\n processing=config.proc,\n recording=config.rec,\n space=config.space)\n\n raw_er_filtered_fname = op.join(deriv_path,\n f'{bids_basename}_emptyroom_filt_raw.fif')\n\n extra_params = dict()\n if not config.use_maxwell_filter and config.allow_maxshield:\n extra_params['allow_maxshield'] = config.allow_maxshield\n\n raw_er_filtered = mne.io.read_raw_fif(raw_er_filtered_fname, preload=True,\n **extra_params)\n fig = raw_er_filtered.plot_psd(show=False)\n return fig\n\n\ndef run_report(subject, session=None):\n deriv_path = config.get_subject_deriv_path(subject=subject,\n session=session,\n kind=config.get_kind())\n\n bids_basename = make_bids_basename(subject=subject,\n session=session,\n task=config.get_task(),\n acquisition=config.acq,\n run=None,\n processing=config.proc,\n recording=config.rec,\n space=config.space\n )\n\n fname_ave = op.join(deriv_path, bids_basename + '-ave.fif')\n fname_trans = op.join(deriv_path, 'sub-{}'.format(subject) + '-trans.fif')\n subjects_dir = config.get_fs_subjects_dir()\n if op.exists(fname_trans):\n rep = mne.Report(info_fname=fname_ave, subject=subject,\n subjects_dir=subjects_dir)\n else:\n rep = mne.Report(info_fname=fname_ave)\n\n rep.parse_folder(deriv_path, verbose=True)\n\n # Visualize events.\n events_fig = plot_events(subject=subject, session=session,\n deriv_path=deriv_path)\n rep.add_figs_to_section(figs=events_fig,\n captions='Events in filtered continuous data',\n section='Events')\n\n conditions = config.conditions.copy()\n conditions.extend(config.contrasts)\n evokeds = mne.read_evokeds(fname_ave)\n\n ###########################################################################\n #\n # Visualize evoked responses.\n #\n for condition, evoked in zip(conditions, evokeds):\n if condition in config.conditions:\n caption = f'Condition: {condition}'\n section = 'Evoked'\n else: # It's a contrast of two conditions.\n caption = f'Contrast: {condition[0]} – {condition[1]}'\n section = 'Contrast'\n\n fig = evoked.plot(show=False, gfp=True, spatial_colors=True)\n rep.add_figs_to_section(figs=fig, captions=caption,\n comments=evoked.comment, section=section)\n\n ###########################################################################\n #\n # Visualize the coregistration & inverse solutions.\n #\n if op.exists(fname_trans):\n # We can only plot the coregistration if we have a valid 3d backend.\n if mne.viz.get_3d_backend() is not None:\n fig = mne.viz.plot_alignment(evoked.info, fname_trans,\n subject=subject,\n subjects_dir=subjects_dir,\n meg=True, dig=True, eeg=True)\n rep.add_figs_to_section(figs=fig, captions='Coregistration',\n section='Coregistration')\n else:\n msg = ('Cannot render sensor alignment (coregistration) because '\n 'no usable 3d backend was found.')\n logger.warn(gen_log_message(message=msg, step=99,\n subject=subject, session=session))\n\n for evoked in evokeds:\n msg = 'Rendering inverse solution for {evoked.comment} …'\n logger.info(gen_log_message(message=msg, step=99,\n subject=subject, session=session))\n\n if condition in config.conditions:\n caption = f'Condition: {condition}'\n else: # It's a contrast of two conditions.\n # XXX Will change once we process contrasts here too\n continue\n\n method = config.inverse_method\n cond_str = 'cond-%s' % evoked.comment.replace(op.sep, '')\n inverse_str = 'inverse-%s' % method\n hemi_str = 'hemi' # MNE will auto-append '-lh' and '-rh'.\n fname_stc = op.join(deriv_path, '_'.join([bids_basename, cond_str,\n inverse_str, hemi_str]))\n\n if op.exists(fname_stc + \"-lh.stc\"):\n stc = mne.read_source_estimate(fname_stc, subject)\n _, peak_time = stc.get_peak()\n\n # Plot using 3d backend if available, and use Matplotlib\n # otherwise.\n if mne.viz.get_3d_backend() is not None:\n brain = stc.plot(views=['lat'], hemi='both',\n initial_time=peak_time, backend='mayavi')\n figs = brain._figures[0]\n comments = evoked.comment\n captions = caption\n else:\n import matplotlib.pyplot as plt\n fig_lh = plt.figure()\n fig_rh = plt.figure()\n\n brain_lh = stc.plot(views='lat', hemi='lh',\n initial_time=peak_time,\n backend='matplotlib',\n subjects_dir=subjects_dir,\n figure=fig_lh)\n brain_rh = stc.plot(views='lat', hemi='rh',\n initial_time=peak_time,\n subjects_dir=subjects_dir,\n backend='matplotlib',\n figure=fig_rh)\n figs = [brain_lh, brain_rh]\n comments = [f'{evoked.comment} - left hemisphere',\n f'{evoked.comment} - right hemisphere']\n captions = [f'{caption} - left',\n f'{caption} - right']\n\n rep.add_figs_to_section(figs=figs,\n captions=captions,\n comments=comments,\n section='Sources')\n del peak_time\n\n if config.noise_cov == 'emptyroom':\n fig_er_psd = plot_er_psd(subject=subject, session=session)\n rep.add_figs_to_section(figs=fig_er_psd,\n captions='Empty-Room Power Spectral Density '\n '(after filtering)',\n section='Empty-Room')\n\n if config.get_task():\n task_str = '_task-%s' % config.get_task()\n else:\n task_str = ''\n\n fname_report = op.join(deriv_path, 'report%s.html' % task_str)\n rep.save(fname=fname_report, open_browser=False, overwrite=True)\n\n\n@failsafe_run(on_error=on_error)\ndef main():\n \"\"\"Make reports.\"\"\"\n msg = 'Running Step 99: Create reports'\n logger.info(gen_log_message(step=99, message=msg))\n\n parallel, run_func, _ = parallel_func(run_report, n_jobs=config.N_JOBS)\n parallel(run_func(subject, session) for subject, session in\n itertools.product(config.get_subjects(), config.get_sessions()))\n\n # Group report\n evoked_fname = op.join(config.bids_root, 'derivatives',\n config.PIPELINE_NAME,\n '%s_grand_average-ave.fif' % config.study_name)\n rep = mne.Report(info_fname=evoked_fname, subject='fsaverage',\n subjects_dir=config.get_fs_subjects_dir())\n evokeds = mne.read_evokeds(evoked_fname)\n deriv_path = config.deriv_root\n subjects_dir = config.get_fs_subjects_dir()\n bids_basename = make_bids_basename(task=config.get_task(),\n acquisition=config.acq,\n run=None,\n processing=config.proc,\n recording=config.rec,\n space=config.space)\n\n method = config.inverse_method\n inverse_str = 'inverse-%s' % method\n hemi_str = 'hemi' # MNE will auto-append '-lh' and '-rh'.\n morph_str = 'morph-fsaverage'\n\n conditions = config.conditions.copy()\n conditions.extend(config.contrasts)\n\n ###########################################################################\n #\n # Visualize evoked responses.\n #\n for condition, evoked in zip(conditions, evokeds):\n if condition in config.conditions:\n caption = f'Average: {condition}'\n section = 'Evoked'\n else: # It's a contrast of two conditions.\n caption = f'Average Contrast: {condition[0]} – {condition[1]}'\n section = 'Contrast'\n\n fig = evoked.plot(show=False, gfp=True, spatial_colors=True)\n fig = evoked.plot(spatial_colors=True, gfp=True, show=False)\n rep.add_figs_to_section(figs=fig, captions=caption,\n comments=evoked.comment, section=section)\n\n ###########################################################################\n #\n # Visualize inverse solutions.\n #\n\n for condition, evoked in zip(conditions, evokeds):\n if condition in config.conditions:\n caption = f'Average: {condition}'\n cond_str = 'cond-%s' % condition.replace(op.sep, '')\n else: # It's a contrast of two conditions.\n # XXX Will change once we process contrasts here too\n continue\n\n section = 'Source'\n fname_stc_avg = op.join(deriv_path, '_'.join(['average',\n bids_basename, cond_str,\n inverse_str, morph_str,\n hemi_str]))\n\n if op.exists(fname_stc_avg + \"-lh.stc\"):\n stc = mne.read_source_estimate(fname_stc_avg, subject='fsaverage')\n _, peak_time = stc.get_peak()\n\n # Plot using 3d backend if available, and use Matplotlib\n # otherwise.\n if mne.viz.get_3d_backend() is not None:\n brain = stc.plot(views=['lat'], hemi='both',\n initial_time=peak_time, backend='mayavi',\n subjects_dir=subjects_dir)\n figs = brain._figures[0]\n captions = caption\n else:\n import matplotlib.pyplot as plt\n fig_lh = plt.figure()\n fig_rh = plt.figure()\n\n brain_lh = stc.plot(views='lat', hemi='lh',\n initial_time=peak_time,\n backend='matplotlib', figure=fig_lh,\n subjects_dir=subjects_dir)\n brain_rh = stc.plot(views='lat', hemi='rh',\n initial_time=peak_time,\n backend='matplotlib', figure=fig_rh,\n subjects_dir=subjects_dir)\n figs = [brain_lh, brain_rh]\n captions = [f'{caption} - left',\n f'{caption} - right']\n\n rep.add_figs_to_section(figs=figs, captions=captions,\n section='Sources')\n\n del peak_time\n\n if config.get_task():\n task_str = '_task-%s' % config.get_task()\n else:\n task_str = ''\n\n fname_report = op.join(deriv_path, 'report_average%s.html' % task_str)\n rep.save(fname=fname_report, open_browser=False, overwrite=True)\n\n msg = 'Completed Step 99: Create reports'\n logger.info(gen_log_message(step=99, message=msg))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"99-make_reports.py","file_name":"99-make_reports.py","file_ext":"py","file_size_in_byte":14442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"556449108","text":"#!/usr/bin/env python3\n\nimport fileinput\nfrom pandas_plink import read_plink\nimport pandas as pd\nfrom pyplink import PyPlink\nimport sys\n\n\ninfile = sys.argv[1]\noutfile = sys.argv[2]\n\n(bim, fam, bed) = read_plink(\n\tinfile, \n\tverbose = True\n\t)\n\nbim['snp'] = range(1, 1+len(bim))\nbim['pos'] = 0\n\nbim.drop(\n\t\"i\", \n\taxis=1, \n\tinplace=True\n\t)\n\nfiledata = bim.to_string(\n\theader=False, \n\tindex=False\n\t)\nprint(\"SNP IDs IN PLACE\")\n\nfiledata = filedata.replace(\"0.0\",\"0\")\n\n\nwith open(outfile,\"w\") as file:\n\tfile.write(filedata)\n\n\nexit()","sub_path":"Dependencies/bim_fix.py","file_name":"bim_fix.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"555491069","text":"import sys\n\ntry:\n import click\nexcept ImportError:\n click = None\n\n\ndef main():\n\n if click is None:\n msg = (\n \"The dask command requires click to be installed.\\n\\n\"\n \"Install with conda or pip:\\n\\n\"\n \" conda install click\\n\"\n \" pip install click\\n\"\n )\n print(msg, file=sys.stderr)\n return 1\n\n from dask.cli import run_cli\n\n run_cli()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"dask/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"483405346","text":"import numpy\nimport pandas as pd\nimport os #用到的一个新库\nimport re\n\n\n'''\nio : string, path object ; excel 路径。 \nsheetname : string, int, mixed list of strings/ints, or None, default 0 返回多表使用sheetname=[0,1],若sheetname=None是返回全表 注意:int/string 返回的是dataframe,而none和list返回的是dict of dataframe \nheader : int, list of ints, default 0 指定列名行,默认0,即取第一行,数据为列名行以下的数据 若数据不含列名,则设定 header = None \nskiprows : list-like,Rows to skip at the beginning,省略指定行数的数据 \nskip_footer : int,default 0, 省略从尾部数的int行数据 \nindex_col : int, list of ints, default None指定列为索引列,也可以使用u”strings”\nnames : array-like, default None, 指定列的名字。\n\n\n'''\n\n \nurl=''\n\n \n\n\n\n\ndef urlfmt(url):\n url=re.sub(\"\\\"\",'',url)\n return url\n \n\ndef oneEtoMe(url=\"./data.xlsx\",group='村居',n=0):\n '''将一个文件拆分成多个XLSX文件;\n url:excel的路径;n:excel文件中列名的行号,第一行:0,第二行:1,默认为第一行;group:依据分组的列名,默认为村居,\n 请将要拆分的表放在首页!'''\n #url=urlfmt(url)\n data=pd.read_excel(url,header = n)\n #data['日期']=pd.to_datetime(data['时间']).dt.date\n data_excel=[]\n sheetname=[]\n for x in data.groupby(group):\n data_excel.append(x[1])\n sheetname.append(x[0])\n for i in range(len(sheetname)): #区别在于循环创建多个路径,路径中加入变量工作表名称\n data_excel[i].iloc[:,0:9].to_excel(url[:url.find('\\\\')+1] + str(sheetname[i]) + \".xlsx\")\n #桌面新建了一个data文件夹,将拆分的工作簿输出到这里\n\n\n\ndef Metoone(url='./files/' ):\n '''将多个xlsx文件合并成一个 2 \n op:文件夹路径,拖入窗体即可'''\n #op=urlfmt(op) \n name_list=os.listdir(op) #用os库获取该文件夹下的文件名称\n data=[] \n for x in range(len(name_list)):\n df=pd.read_excel(url+name_list[x])#循环导入多个excel文件\n data.append(df)#将每个excel写入到data变量中\n data=pd.concat(data)#合并data变量,转化成Dataframe\n data.to_excel(url+'sum.xlsx',index=False)#输出合并后的excel\n \n\n\ndef Ms_to_ones(url):\n '''将多个工作表合并成一个工作表'''\n #url=urlfmt(url)\n zx=pd.ExcelFile(url)#获取工作簿里面的属性\n data=zx.parse(zx.sheet_names) #调用属性中的所有sheet名称并将数传入变量data\n data=pd.concat(data)#合并变量中的所有表组成新的DataFrame\n data.to_excel(url[:url.find('\\\\')+1]+'new.xlsx',index=False)#输出excel文件到桌面,不展示索引\n\n\ndef oneE_to_Ms(url,group='村居',n=0):\n '''一个xlsx拆分成多个工作表'''\n #url=urlfmt(url)\n data=pd.read_excel(url,header = n)#导入数据\n \n data_excel=[] #建一个用于存储多个sheet的空集\n sheetname=[] #建议一个用于存储多个sheet名称的空集\n for x in data.groupby(group): #根据日期字段进行分组\n data_excel.append(x[1]) #将拆分的sheet存储到data_excle里面\n sheetname.append(x[0]) #将拆分的sheet名称存储到sheetname里面\n writer=pd.ExcelWriter(url[:url.find('\\\\')+1]+'new.xlsx')#定义一个最终文件存储的对象,防止覆盖\n for i in range(len(sheetname)):#创建一个循环将多个sheet输出\n data_excel[i].iloc[:,0:9].to_excel(writer,sheet_name=str(sheetname[i]),index=False)\n #循环将多个sheet表中的数据及对应的sheet表名称输出至桌面,并且不展示索引\n\nb=True\n\nwhile b:\n innum = input('''\n 1.将1个excel拆分成多个excel;\n 2.将一个文件夹中的多个excel合成一个excel;\n 3.将1个excel下的多个工作表合并为一个工作表,并准存到一个新的excel文件;\n 4.将1个excel中的一个工作表,拆分成多个工作表,并转存到一个新的excel文件。\n 5.输入q退出。\n 请输入(1/2/3/4/q):\n ''')\n if innum == \"1\":\n #geturl()\n group=input(\"请输入分组依据(列名)\")\n n = int(input(\"请输入列名的行号,在第一行为0,第二行为1,以此类推\"))\n oneEtoMe(url,group,n)\n print(\"转换完成\")\n elif innum == \"2\":\n #geturl-() \n Metoone(url,group,n)\n print(\"转换完成\")\n elif innum == \"3\":\n #geturl() \n Ms_to_ones(url)\n print(\"转换完成\")\n elif innum == '4':\n #geturl()\n group=input(\"请输入分组依据(列名)\")\n n = int(input(\"请输入列名的行号,在第一行为0,第二行为1,以此类推\"))\n oneE_to_Ms(url,group,n)\n print(\"转换完成\")\n elif innum == 'q':\n break\n else :\n print(\"输入错误,请重新输入\")\n\n\n\n\n\n\n\n\n\n\n","sub_path":"one_to_many/one_to_many.py","file_name":"one_to_many.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"89970701","text":"#Escribe la longitud de la base mayor: 2\r\n#Escribe la longitud de la base menor: 1\r\n#Escribe la altura: 1\r\n#Área: 1.50\r\n#Perímetro: 5.24\r\n\r\ndef calcularArea(baseM, basem, altura):\r\n area = ((baseM+basem)/2)*altura\r\n return area\r\n\r\ndef calcularHipotenusa(basem, baseM, altura):\r\n n = baseM-basem\r\n h = ((altura**2)+(n**2))**0.5\r\n return h\r\n\r\ndef calcularPerimetro(h, basem, baseM):\r\n P = h + h + basem + baseM\r\n return P\r\n\r\ndef main():\r\n baseM = int(input(\"Introduce la longitud de la base mayor:\"))\r\n basem = int(input(\"Introduce la longitud de la base menor:\"))\r\n altura = int(input(\"Introduce la altura:\"))\r\n area = calcularArea(baseM, basem, altura)\r\n h = calcularHipotenusa(basem, baseM, altura)\r\n perimetro = calcularPerimetro(h, basem, baseM)\r\n print(\"Área igual a:\", area)\r\n print(\"Perímetro igual a:\", perimetro)\r\n\r\nmain()","sub_path":"Trapecio.py","file_name":"Trapecio.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"601314460","text":"nome = input('Digite seu nome: ')\nnomeMa = nome.upper()\nnomeMi = nome.lower()\nnomeNoSpace = nome.replace(' ', '')\nnomeSplit = nome.split()\nprint('Nome Maiusculo: {}'.format(nomeMa))\nprint('Nome Minusculo: {}'.format(nomeMi))\nprint('Nome sem espaco: {}, quantidade de letras: {}'.format(nomeNoSpace, len(nomeNoSpace)))\nprint('Nome splitado: {}, primero nome: {}, letras primeiro nome {}'\n .format(nomeSplit, nomeSplit[0], len(nomeSplit[0])))\n","sub_path":"CursoEmVideoPython/Mundo001/ex022.py","file_name":"ex022.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"159563351","text":"\"\"\"Contains the SequenceProcessor class, which exposes most of Sabers functionality.\n\"\"\"\nfrom itertools import chain\nimport logging\nimport os\nimport pickle\nfrom pprint import pprint\nimport time\n\nfrom gensim.models import KeyedVectors\nimport numpy as np\nfrom spacy import displacy\n\nfrom . import constants\nfrom .config import Config\nfrom .dataset import Dataset\nfrom .preprocessor import Preprocessor\nfrom .trainer import Trainer\nfrom .utils import generic_utils\nfrom .utils import model_utils\n\nclass SequenceProcessor(object):\n \"\"\"A class for handeling the loading, saving and training of sequence models.\n\n Args:\n config (Config): A Config object which contains a set of harmonzied arguments provided in\n a .ini file and, optionally, from the command line. If not provided, a new instance of\n Config is used.\n \"\"\"\n def __init__(self, config=None):\n self.log = logging.getLogger(__name__)\n\n # hyperparameters and model details\n self.config = config if config is not None else Config()\n\n # dataset(s) tied to this instance\n self.ds = []\n # token embeddings tied to this instance\n self.token_embedding_matrix = None\n\n # model object tied to this instance\n self.model = None\n\n # preprocessor\n self.preprocessor = Preprocessor()\n\n if self.config.verbose:\n print('Hyperparameters and model details:')\n pprint({arg: getattr(self.config, arg) for arg in constants.CONFIG_ARGS})\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'\n\n def annotate(self, text, title=None, model_idx=0, jupyter=False):\n \"\"\"Uses a trained model to annotate `text`, returns the results in a dictionary.\n\n For the model at self.model.model[model_idx], coordinates a prediction step on `text`.\n Returns a dictionary containing the cleaned text (`text`), and any annotations made by the\n model (`ents`). This dictionary can easily be converted to a json. Optionally,\n renders a HTMl visilization of the annotations made by the model, for use in a jupyter\n notebook.\n\n text (str): raw text to annotate\n model_idx (int): index of model to use for prediction, defaults to 0\n jupyter (bool): if True, annotations made by the model are rendered in HTML, which can be\n visualized in a jupter notebook.\n\n Returns:\n dictionary containing the processed input text (`text`) and any annotations made by the\n model (`ents`).\n\n Raises:\n ValueError if `text` is invalid (not a string, or empty/falsey).\n \"\"\"\n if not isinstance(text, str) or not text:\n err_msg = \"Argument 'text' must be a valid, non-empty string.\"\n self.log.error(\"ValueError: %s\", err_msg)\n raise ValueError(err_msg)\n\n # model and its corresponding dataset\n ds = self.ds[model_idx]\n model = self.model.model[model_idx]\n\n # process raw input text, collect input to ML model\n transformed_text = self._transform(text, model_idx)\n model_input = [transformed_text['word2idx'], transformed_text['char2idx']]\n\n # perform prediction, convert from one-hot to predicted indices, flatten results\n y_pred = model.predict(model_input, batch_size=constants.PRED_BATCH_SIZE)\n y_pred = np.asarray(y_pred.argmax(-1)).ravel()\n # convert predictions to tags and chunk\n pred_tag_seq = [ds.idx_to_tag[idx] for idx in y_pred if ds.idx_to_tag[idx] != constants.PAD]\n pred_chunk_seq = self.preprocessor.chunk_entities(pred_tag_seq)\n # flatten the token offsets\n offsets = list(chain.from_iterable(transformed_text['offsets']))\n\n # accumulate predicted entities\n ents = []\n for chunk in pred_chunk_seq:\n # create the entity\n # chunks are tuples (label, start, end), offsets is a lists of lists of tuples\n start, end = offsets[chunk[1]][0], offsets[chunk[-1] - 1][-1]\n ents.append({'start': start,\n 'end': end,\n 'text': transformed_text['text'][start:end],\n 'label': chunk[0]})\n\n annotation = {\n 'text': transformed_text['text'],\n 'ents': ents,\n 'title': title\n }\n\n if jupyter:\n displacy.render(annotation, jupyter=jupyter, style='ent', manual=True,\n options=constants.OPTIONS)\n\n return annotation\n\n def save(self, directory=None, compress=True, model_idx=0):\n \"\"\"Coordinates the saving of Saber models.\n\n Saves the necessary files for model persistance to directory. `directory` defaults to\n \"self.config.output_folder/constants.PRETRAINED_MODEL_DIR/\"\n\n Args:\n directory (str): directory path to save model folder, if not provided, defaults to\n \"self.config.output_folder/constants.PRETRAINED_MODEL_DIR/\"\n compress (bool): True if model should be saved as tarball, defaults to True\n model_idx (int): which model in self.model.model to save, defaults to 0\n \"\"\"\n # if no filepath is provided, get a 'default' one from dataset names\n if directory is None:\n directory = generic_utils.get_pretrained_model_dir(self.config)\n directory = os.path.abspath(os.path.normpath(directory))\n generic_utils.make_dir(directory)\n\n # create filepaths to objects to be saved\n weights_filepath = os.path.join(directory, constants.WEIGHTS_FILEPATH)\n model_filepath = os.path.join(directory, constants.MODEL_FILEPATH)\n attributes_filepath = os.path.join(directory, constants.ATTRIBUTES_FILEPATH)\n\n # create a dictionary containg anything else we need to save the model\n model_attributes = {'type_to_idx': self.ds[model_idx].type_to_idx,\n 'idx_to_tag': self.ds[model_idx].idx_to_tag,\n }\n # save weights, model architecture, dataset it was trained on, and configuration file\n self.model.save(weights_filepath, model_filepath, model_idx)\n pickle.dump(model_attributes, open(attributes_filepath, 'wb'))\n self.config.save(directory)\n\n if compress:\n generic_utils.compress_model(directory)\n\n print('Model saved to {}'.format(directory))\n self.log.info('Model was saved to %s', directory)\n\n def load(self, directory):\n \"\"\"Coordinates the loading of Saber models.\n\n Loads a Saber model saved to `filepath`. Creates and compiles a new model with identical\n architecture and weights.\n\n Args:\n directory (str): directory path to saved pre-trained model folder\n \"\"\"\n if directory.upper() in constants.PRETRAINED_MODELS:\n directory = os.path.join(constants.PRETRAINED_MODEL_DIR, directory.upper())\n\n directory = generic_utils.clean_path(directory)\n generic_utils.decompress_model(directory)\n\n # load attributes, these attributes must be carried over from saved model\n weights_filepath = os.path.join(directory, constants.WEIGHTS_FILEPATH)\n model_filepath = os.path.join(directory, constants.MODEL_FILEPATH)\n attributes_filepath = os.path.join(directory, constants.ATTRIBUTES_FILEPATH)\n\n # load any attributes carried over from saved model\n model_attributes = pickle.load(open(attributes_filepath, \"rb\"))\n # create a new dataset instance, load the required attributes for model prediction\n # TEMP: this is an ugly hack, need way around having to provide a filepath\n dummy_ds = 'tests/resources/dummy_dataset_1'\n dummy_ds = os.path.join(os.path.dirname(os.path.abspath(__file__)), dummy_ds)\n self.ds = [Dataset(dummy_ds)]\n self.ds[0].type_to_idx = model_attributes['type_to_idx']\n self.ds[0].idx_to_tag = model_attributes['idx_to_tag']\n\n if self.config.model_name == 'mt-lstm-crf':\n from .models.multi_task_lstm_crf import MultiTaskLSTMCRF\n self.model = MultiTaskLSTMCRF(self.config, self.ds)\n\n self.model.load(weights_filepath, model_filepath)\n self.model.compile_()\n\n def load_dataset(self, directory=None):\n \"\"\"Coordinates the loading of a dataset.\n\n Args:\n directory (str): path to a dataset folder, if not None, overwrites\n `self.config.dataset_folder`\n \"\"\"\n start = time.time()\n\n if directory is not None:\n directory = directory if isinstance(directory, list) else [directory]\n directory = [generic_utils.clean_path(dir) for dir in directory]\n self.config.dataset_folder = directory\n\n if not self.config.dataset_folder:\n err_msg = \"Must provide at least one dataset via the 'dataset_folder' parameter\"\n self.log.error('AssertionError %s', err_msg)\n raise AssertionError(err_msg)\n\n # if not None, assume pre-trained model has been loaded, use its type mapping\n type_to_idx = None if not self.ds else self.ds[0].type_to_idx\n # datasets may be 'single' or 'compound' (more than one)\n if len(self.config.dataset_folder) == 1:\n print('Loading (single) dataset... ', end='', flush=True)\n self.ds = self._load_single_dataset(type_to_idx)\n self.log.info('Loaded single dataset at: %s', self.config.dataset_folder)\n else:\n print('Loading (compound) dataset... ', end='', flush=True)\n self.ds = self._load_compound_dataset(type_to_idx)\n self.log.info('Loaded multiple datasets at: %s', self.config.dataset_folder)\n\n end = time.time() - start\n print('Done ({0:.2f} seconds).'.format(end))\n\n def load_embeddings(self, filepath=None, binary=True):\n \"\"\"Coordinates the loading of pre-trained token embeddings.\n\n Args:\n filepath (str): path to pre-trained embeddings file, if not None, overwrites\n `self.config.pretrained_embeddings`\n binary (bool): True if pre-trained embeddings are in C binary format, False if they are\n in C text format.\n\n Raises:\n MissingStepException: if no dataset has been loaded.\n ValueError: If 'self.config.pretrained_embeddings' is None and filepath is None.\n \"\"\"\n if filepath is not None:\n filepath = generic_utils.clean_path(filepath)\n self.config.pretrained_embeddings = filepath\n\n if not self.ds:\n err_msg = \"You need to call 'load_dataset()' before calling 'load_embeddings()'\"\n self.log.error('MissingStepException: %s', err_msg)\n raise MissingStepException(err_msg)\n if not self.config.pretrained_embeddings:\n err_msg = \"'pretrained_embeddings' argument was empty'\"\n self.log.error('ValueError: %s', err_msg)\n raise ValueError(err_msg)\n\n self._load_token_embeddings(binary)\n\n def create_model(self, model_name=None, compile_model=True):\n \"\"\"Specifies and compiles chosen model (self.config.model_name).\n\n For a chosen model (provided at the command line or in the configuration file and saved as\n `self.config.model_name`), load this models class class. Then 'specify' and 'compile'\n the Keras model(s) it contains.\n\n Raises:\n ValueError if model name at `self.config.model_name` is not valid\n \"\"\"\n if model_name is not None:\n self.config.model_name = model_name.lower().strip()\n\n if self.config.model_name not in ['mt-lstm-crf']:\n err_msg = (\"'model_name' must be one of: {}, \"\n \"got {}\").format(constants.MODELS, self.config.model_name)\n self.log.error('ValueError: %s ', err_msg)\n raise ValueError(err_msg)\n\n start_time = time.time()\n # setup the chosen model\n if self.config.model_name == 'mt-lstm-crf':\n print('Building the multi-task BiLSTM-CRF model... ', end='', flush=True)\n from .models.multi_task_lstm_crf import MultiTaskLSTMCRF\n model = MultiTaskLSTMCRF(config=self.config, ds=self.ds,\n token_embedding_matrix=self.token_embedding_matrix)\n\n # specify and compile the chosen model\n model.specify_()\n if compile_model:\n model.compile_()\n\n # update this objects model attribute with instance of model class\n self.model = model\n\n elapsed_time = time.time() - start_time\n print('Done ({0:.2f} seconds).'.format(elapsed_time))\n self.log.info('%s model was built successfully', self.config.model_name.upper())\n\n if self.config.verbose:\n for i, model in enumerate(self.model.model):\n ds_name = os.path.basename(self.config.dataset_folder[i])\n print('Model architecture for dataset {}:'.format(ds_name))\n model.summary()\n\n def fit(self):\n \"\"\"Fit the specified model.\n\n For the given model(s) (self.model), sets up per epoch checkpointing and fits the model.\n\n Returns:\n a list, containing one or more model instances (subclass of\n BaseModel) with trained Keras models.\n \"\"\"\n # setup callbacks\n callbacks = {'checkpoint': None, 'tensorboard': None}\n train_session_dir = model_utils.prepare_output_directory(self.config.dataset_folder,\n self.config.output_folder,\n self.config)\n # model checkpointing\n callbacks['checkpoint'] = model_utils.setup_checkpoint_callback(train_session_dir)\n # tensorboard\n if self.config.tensorboard:\n callbacks['tensorboard'] = model_utils.setup_tensorboard_callback(train_session_dir)\n\n trainer = Trainer(self.config, self.ds, self.model)\n trainer.train(callbacks, train_session_dir)\n\n def _load_single_dataset(self, type_to_idx=None):\n \"\"\"Loads a single dataset.\n\n Creates and loads a single dataset object for a dataset at self.config.dataset_folder[0].\n\n Args:\n type_to_idx (dict): a mapping of types ('word', 'char') to unique integer ids, when\n provided, these are used in the loading of the dataset at\n `self.config.dataset_folder[0]`\n\n Returns:\n a list containing a single dataset object.\n \"\"\"\n ds = Dataset(self.config.dataset_folder[0],\n replace_rare_tokens=self.config.replace_rare_tokens)\n if type_to_idx is not None:\n ds.load_data_and_labels()\n ds.get_types()\n\n ds.load_dataset(type_to_idx)\n\n return [ds]\n\n def _load_compound_dataset(self, type_to_idx):\n \"\"\"Loads a compound dataset.\n\n Creates and loads a 'compound' dataset. Compound datasets are specified by multiple\n individual datasets, and share multiple attributes (such as 'word' and 'char' type to index\n mappings). Loads such a dataset for each dataset at self.dataset_folder.\n\n Args:\n type_to_idx (dict): a mapping of types ('word', 'char') to unique integer ids, when\n provided, these are used in the loading of the datasets at\n `self.config.dataset_folder`\n\n Returns:\n A list containing multiple compound dataset objects.\n \"\"\"\n # accumulate datasets\n compound_ds = [Dataset(ds, replace_rare_tokens=self.config.replace_rare_tokens) for ds in\n self.config.dataset_folder]\n\n for ds in compound_ds:\n ds.load_data_and_labels()\n ds.get_types()\n\n if type_to_idx is None:\n # get combined set of word and char types from all datasets\n combined_types = {'word': [ds.types['word'] for ds in compound_ds],\n 'char': [ds.types['char'] for ds in compound_ds]}\n combined_types['word'] = list(set(chain.from_iterable(combined_types['word'])))\n combined_types['char'] = list(set(chain.from_iterable(combined_types['char'])))\n\n # compute word to index mappings that will be shared across datasets\n type_to_idx = {'word': Preprocessor.type_to_idx(combined_types['word'],\n constants.INITIAL_MAPPING['word']),\n 'char': Preprocessor.type_to_idx(combined_types['char'],\n constants.INITIAL_MAPPING['word'])}\n # finally, load all the datasets, providing pre-populated type_to_idx mappings\n for ds in compound_ds:\n ds.load_dataset(type_to_idx)\n\n return compound_ds\n\n def _load_token_embeddings(self, binary=True):\n \"\"\"Coordinates the loading of pre-trained token embeddings.\n\n Coordinates the loading of pre-trained token embeddings by reading in the file containing\n the token embeddings and creating a embedding matrix whos ith row corresponds to the token\n embedding for the ith word in the models word to idx mapping.\n\n Args:\n binary (bool): True if pre-trained embeddings are in C binary format, False if they are\n in C text format.\n \"\"\"\n start = time.time()\n print('Loading embeddings... ', end='', flush=True)\n\n # prepare the embedding indicies\n embedding_idx = self._prepare_token_embedding_layer(binary)\n embedding_dim = len(list(embedding_idx.values())[0])\n # create the embedding matrix, update attribute\n embedding_matrix = self._prepare_token_embedding_matrix(embedding_idx, embedding_dim)\n self.token_embedding_matrix = embedding_matrix\n\n end = time.time() - start\n print('Done ({0:.2f} seconds)'.format(end))\n print('Found {} word vectors of dimension {}'.format(len(embedding_idx), embedding_dim))\n self.log.info('Loaded %i word vectors of dimension %i', len(embedding_idx), embedding_dim)\n\n def _prepare_token_embedding_layer(self, binary=True):\n \"\"\"Creates an embedding index using pretrained token embeddings.\n\n For the pretrained word embeddings given at `self.config.pretrained_embeddings`, creates\n and returns a dictionary mapping words to embeddings, or word vectors. Note that if\n `self.config.debug` is True, only the first 10K vectors are loaded.\n\n Args:\n binary (bool): True if pre-trained embeddings are in C binary format, False if they are\n in C text format.\n\n Returns:\n embed_idx (dict): mapping of words to pre-trained word embeddings\n \"\"\"\n limit = 10000 if self.config.debug else None\n vectors = KeyedVectors.load_word2vec_format(self.config.pretrained_embeddings,\n binary=binary,\n limit=limit)\n embed_idx = {word: vectors[word] for word in vectors.vocab}\n return embed_idx\n\n def _prepare_token_embedding_matrix(self, embedding_idx, embedding_dim):\n \"\"\"Creates an embedding matrix using pretrained token embeddings.\n\n For the models word to index mappings, and word to pre-trained token embeddings, creates a\n matrix which maps all words in the models dataset to a pre-trained token embedding. If the\n token embedding does not exist in the pre-trained token embeddings file, the word will be\n mapped to an embedding of all zeros.\n\n Args:\n embedding_idx (dict): dictionary mapping words to their dense embeddings\n embedding_size (int): dimension of dense embeddings\n\n Returns:\n matrix whos ith row corresponds to the word embedding for the ith word in the models\n word to idx mapping.\n \"\"\"\n # initialize the embeddings matrix\n word_types = len(self.ds[0].type_to_idx['word'])\n token_embedding_matrix = np.zeros((word_types, embedding_dim))\n\n # lookup embeddings for every word in the dataset\n for word, i in self.ds[0].type_to_idx['word'].items():\n token_embedding = embedding_idx.get(word)\n if token_embedding is not None:\n # words not found in embedding index will be all-zeros.\n token_embedding_matrix[i] = token_embedding\n\n return token_embedding_matrix\n\n def _transform(self, text, model_idx=0):\n \"\"\"Processes raw text, returns a dictionary of useful values.\n\n For the given raw text, returns a dictionary containing the following:\n - 'text': raw text, with minimal processing\n - 'sentences': a list of lists, contains the tokens in each sentence\n - 'offsets': A list of list of tuples containing the start and end\n indices of every token in 'text'\n - 'word2idx': 2-D numpy array containing the token index of every\n token in 'text'. Index is chosen based on the mapping of\n self.ds[model_idx]\n - 'char2idx': 3-D numpy array containing the character index of\n every character in 'text'. Index is chosen based on the mapping\n of self.ds[model_idx]\n\n Args:\n text (str): raw text to process\n model_idx (int): index of dataset in `self.ds` to use for mapping of word/character\n indices.\n \"\"\"\n ds = self.ds[model_idx]\n return self.preprocessor.transform(text, ds.type_to_idx['word'], ds.type_to_idx['char'])\n\n# https://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python\nclass MissingStepException(Exception):\n \"\"\"Execption subclass for signalling to user that some required previous step was missed.\"\"\"\n pass\n","sub_path":"saber/sequence_processor.py","file_name":"sequence_processor.py","file_ext":"py","file_size_in_byte":22107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"533471219","text":"import sys\n\nfrom datetime import date,timedelta\nimport calendar\nimport datetime\ndef counter(dates):\n# datelen=input(\"Enter the date:\\n\")\n l=dates.split()\n d1=int(l[0])\n m1=int(l[1])\n y1=int(l[2])\n d2=int(l[3])\n m2=int(l[4])\n y2=int(l[5])\n count=0\n def daterange(start_date, end_date):\n for n in range(int ((end_date - start_date).days)):\n yield start_date + timedelta(n)\n\n start_date = date(y1, m1, d1)\n end_date = date(y2, m2, d2)\n end_date = end_date+ datetime.timedelta(days=1)\n for single_date in daterange(start_date, end_date):\n #print(single_date.strftime(\"%Y-%m-%d\"))\n if (calendar.day_name[single_date.weekday()])==\"Friday\" and single_date.day==13:\n #print(single_date.strftime(\"%Y-%m-%d\"),calendar.day_name[single_date.weekday()])\n count=count+1\n return count\n\ntc=int(input())#input(\"Enter number of testcases:\\n\"))\narr=[]\nfor i in range(0,tc):\n arr.append(input())\nfor i in range(0,tc):\n print(counter(arr[i]))\n","sub_path":"dates.py","file_name":"dates.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"10081776","text":"import copy\nimport scipy\nfrom scipy import array, exp, zeros, arange, dot, eye\n\nfrom librl.util import encodeTriuAs1DArray,decode1DArrayAsSymMat\nfrom pybrain.structure.modules.module import Module\nfrom pybrain.structure.parametercontainer import ParameterContainer\nfrom pybrain.utilities import abstractMethod\n\nclass PolicyInterface(object):\n \"\"\"Interface for policy\n Policy is one type of controller that maps the observation\n to action probability\n PolicyController has two functions:\n 1. Generate Actions Based on Observations and Weights\n 2. Calculate basis function value. which is nabla_theta psi_theta(x,u)\n\n \"\"\"\n def calBasisFuncVal(self, feaList):\n abstractMethod()\n\n def calSecondBasisFuncVal(self, feaList):\n abstractMethod()\n\nclass BoltzmanPolicy(Module, ParameterContainer, PolicyInterface):\n \"\"\"\n for bolzman distribution\n mu(u_i | x) = a_i(theta) / sum(a_i(theta))\n a_i(theta) = F_i(x) exp(\n theta_1 * E{safety( f(x,u_i) )} +\n theta_2 * E{progress( f(x,u_i) )} )\n \"\"\"\n\n def __init__(self, actionnum, T, theta, **args):\n self.feadim = len(theta)\n Module.__init__(self, self.feadim * actionnum, 1, **args)\n ParameterContainer.__init__(self, self.feadim)\n self.T = T\n self.g = None\n self.bf = None\n\n # feadimx1 vector.\n self.theta = theta\n self.actionnum = actionnum\n\n self.cachedActionProb = None\n\n def get_theta(self): return self._params\n def set_theta(self, val): self._setParameters(val)\n theta = property(fget = get_theta, fset = set_theta)\n params = theta\n\n def _forwardImplementation(self, inbuf, outbuf):\n \"\"\" take observation as input, the output is the action\n \"\"\"\n action_prob = self._getActionProb(self.obs2fea(inbuf), self.theta)\n assert self.actionnum == len(action_prob), ('wrong number of ',\n 'action in policy')\n action = scipy.random.choice(range(self.actionnum), p=action_prob)\n outbuf[0] = action\n\n @staticmethod\n def getActionScore(score, theta, T):\n \"\"\"Calculate the total score for a control. It is the exp of the\n weighted sum of different features.\n \"\"\"\n perfer = sum( s * t for s, t in zip(score, theta) )\n return float(exp(perfer/T))\n\n def _getActionProb(self, feaList, theta):\n \"\"\"Calculate the Action Probability for each control.\n *feaList* is a list container different feature\n *theta* is the weight for each feature\n \"\"\"\n scores = scipy.zeros(len(feaList))\n for i, feature in enumerate(feaList):\n scores[i] = self.getActionScore(feature, theta, self.T)\n\n return scores / scipy.sum(scores)\n\n def getActionValues(self, obs):\n \"\"\"extract features from observation and call _getActionProb\"\"\"\n return array(self._getActionProb(self.obs2fea(obs), self.theta))\n\n def obs2fea(self, obs):\n \"\"\"observation to feature list\"\"\"\n return obs.reshape(self.actionnum, self.feadim)\n\n def fea2obs(self, fea):\n \"\"\"feature list to observation\"\"\"\n obs = fea.reshape(-1)\n assert len(obs) == self.actionnum * self.feadim, 'invalid feature!'\n return obs\n\n def calBasisFuncVal(self, feaList):\n \"\"\"for an observation, calculate value of basis function\n for all possible actions\n feaList is a list of tuple. each tuple represent the value of feature\n take the robot motion control as an example, a possible value may be:\n [\n ( safety_1 , progress_1),\n ( safety_2 , progress_2),\n ( safety_3 , progress_3),\n ( safety_4 , progress_4),\n ]\n 1, 2, 3, 4 coressponds to each action ['E', 'N', 'W', 'S']\n ]\n\n Basis Function Value: is the first order derivative of the log of the policy.\n \"\"\"\n feaMat = scipy.array(feaList)\n action_prob = self._getActionProb(feaList, self.theta)\n self.cachedActionProb = action_prob\n self.g = scipy.dot(action_prob, feaMat)\n self.bf = feaMat - self.g\n return self.bf\n\n def calSecondBasisFuncVal(self, feaList):\n \"\"\" calculate \\nab^2 log(\\mu)\n Please see https://goo.gl/PRnu58 for mathematical deduction.\n \"\"\"\n feaMat = scipy.array(feaList)\n # We assume second order basis calculation followe first order basis\n # calculation, so we just use the cachedActionProb.\n if self.cachedActionProb is not None:\n action_prob = self.cachedActionProb\n self.cachedActionProb = None\n else:\n action_prob = self._getActionProb(feaList, self.theta)\n mat1 = scipy.dot(feaMat.T * action_prob, feaMat)\n tmp = scipy.dot(feaMat.T, action_prob)\n log_likelihood_hessian = -1 * mat1 + scipy.outer(tmp, tmp.T)\n return log_likelihood_hessian\n\n\nclass PolicyFeatureModule(Module):\n \"\"\"Module to calculate features for state-action value function approximiation.\n Input: a vector whose the last element is the action, and the rest elements are\n observation.\n Output: a vector of features which is used for approximate state-action\n value function.\n \"\"\"\n def __init__(self, policy, name=None):\n self.policy = policy\n self.paramdim = policy.feadim\n self.actionnum = policy.actionnum\n\n self.feadesc, outdim = self._transformFeatureDescriptor(\n self.getFeatureDescriptor())\n\n super(PolicyFeatureModule, self).__init__(\n indim = self.paramdim * self.actionnum + 1,\n outdim = outdim,\n name = name\n )\n\n def _transformFeatureDescriptor(self, feadesc):\n # parse feature descriptor.\n bd = [0] # boundary\n feanames = []\n outdim = 0\n for feature in feadesc:\n outdim += feature['dimension']\n feanames.append(feature['name'])\n bd.append(outdim)\n\n newfeadesc = dict()\n for i, name in enumerate(feanames):\n desc = copy.deepcopy(feadesc[i])\n desc['fea_range'] = (bd[i], bd[i+1])\n desc['fea_index'] = i\n newfeadesc[name] = desc\n return newfeadesc, outdim\n\n def decodeFeature(self, feature, name):\n decoder = self.feadesc[name].get('decoder', self._identityDecoder)\n r = self.feadesc[name]['fea_range']\n feature = feature[r[0]:r[1]]\n return decoder(feature)\n\n # the default decoder.\n @staticmethod\n def _identityDecoder(feature):\n return feature\n\n def getFeatureDescriptor(self):\n # first order feature\n def _firstOrderFeature(policy, feature, action):\n return self.getFeatureSlice(policy.calBasisFuncVal(feature).reshape(-1),\n action)\n\n # second order feature\n n = self.paramdim\n sofl = (n * n - n) / 2 + n # second order feature length\n\n def _secondOrderFeature(policy, feature, action):\n hessian = policy.calSecondBasisFuncVal(feature)\n return encodeTriuAs1DArray(hessian)\n\n def _secondOrderFeatureDecoder(feature):\n assert sofl == len(feature), ('invalid feature'\n 'to decode')\n return decode1DArrayAsSymMat(feature, self.paramdim)\n\n return [\n {\n 'name': 'first_order',\n 'dimension': self.paramdim,\n 'constructor': _firstOrderFeature,\n 'decoder': self._identityDecoder,\n },\n {\n 'name': 'second_order',\n 'dimension': sofl,\n 'constructor': _secondOrderFeature,\n 'decoder': _secondOrderFeatureDecoder,\n },\n ]\n\n def getFeatureSlice(self, feature, action):\n featureslice = self.policy.obs2fea(feature[0:(self.paramdim *\n self.actionnum)])\n return featureslice[int(action), :]\n\n def _forwardImplementation(self, inbuf, outbuf):\n fea = self.policy.obs2fea(inbuf[:-1])\n action = inbuf[-1]\n offset = 0\n for name, desc in self.feadesc.iteritems():\n fearange = desc ['fea_range']\n outbuf[fearange[0]:fearange[1]] = desc['constructor'](self.policy,\n fea, action)\n\n def get_theta(self): return self.policy.theta.reshape(-1)\n def set_theta(self, val): self.policy._setParameters(val.reshape(-1))\n theta = property(fget = get_theta, fset = set_theta)\n\n\nclass PolicyValueFeatureModule(PolicyFeatureModule):\n \"\"\"Module to generate feature for approximating state value function\n\n The first part of the output is the _firstOrderFeature as in\n PolicyFeatureModule. The second part is value function is appended.\n\n ATTENTION! Please use this module only if the state-action feature is\n created by padding state feature with zeros. See pg. 29 of\n https://webdocs.cs.ualberta.ca/~sutton/papers/BSGL-TR.pdf\n \"\"\"\n def getFeatureDescriptor(self):\n assert self.paramdim % self.actionnum == 0, 'wrong module is used!'\n self.statefeadim = int(self.paramdim / self.actionnum)\n\n def _firstOrderFeature(policy, feature, action):\n return self.getFeatureSlice(policy.calBasisFuncVal(feature).reshape(-1),\n action)\n\n def _stateFeature(policy, feature, action):\n return feature[0][:self.statefeadim]\n\n return [\n {\n 'name': 'first_order',\n 'dimension': self.paramdim,\n 'constructor': _firstOrderFeature,\n },\n {\n 'name': 'state_feature',\n 'dimension': self.statefeadim,\n 'constructor': _stateFeature,\n },\n ]\n\n\n\nclass GLFWSBoltzmanPolicy(BoltzmanPolicy):\n def __init__(self, *args, **kwargs):\n super(GLFWSBoltzmanPolicy, self).__init__(*args, **kwargs)\n Module.__init__(self, self.feadim * (self.actionnum + 1), 1, *args,\n **kwargs)\n\n def _forwardImplementation(self, inbuf, outbuf):\n \"\"\" take observation as input, the output is the action\n \"\"\"\n obs = inbuf[:(self.feadim * self.actionnum)]\n super(GLFWSBoltzmanPolicy, self)._forwardImplementation(obs, outbuf)\n\n\nclass GLFWSPolicyFeatureModule(PolicyFeatureModule):\n \"\"\"Feature module for GarnetLookForwardWithStateObsTask\n \"\"\"\n def __init__(self, policy, name=None):\n self.policy = policy\n self.paramdim = policy.feadim\n self.actionnum = policy.actionnum\n self.statefeadim = self.paramdim\n self.feadesc, outdim = self._transformFeatureDescriptor(\n self.getFeatureDescriptor())\n\n self.expectedFeaDim = (self.actionnum + 1) * self.paramdim\n\n Module.__init__(self,\n indim = self.expectedFeaDim + 1,\n outdim = outdim,\n name = name\n )\n\n def getFeatureDescriptor(self):\n\n def _firstOrderFeature(policy, feature, action):\n oneStepAdvantage = feature.reshape(self.actionnum+1,\n self.paramdim)[:self.actionnum, :]\n return self.getFeatureSlice(policy.calBasisFuncVal(oneStepAdvantage).reshape(-1),\n action)\n\n def _stateFeature(policy, feature, action):\n assert self.expectedFeaDim == len(feature), ('Wrong feature'\n 'length!')\n return feature.reshape(self.actionnum+1,\n self.paramdim)[self.actionnum, :]\n\n\n return [\n {\n 'name': 'first_order',\n 'dimension': self.paramdim,\n 'constructor': _firstOrderFeature,\n },\n {\n 'name': 'state_feature',\n 'dimension': self.statefeadim,\n 'constructor': _stateFeature,\n },\n ]\n\n def _forwardImplementation(self, inbuf, outbuf):\n fea = inbuf[:-1]\n assert self.expectedFeaDim == len(fea), ('Wrong feature'\n 'length!')\n action = inbuf[-1]\n offset = 0\n for name, desc in self.feadesc.iteritems():\n fearange = desc ['fea_range']\n outbuf[fearange[0]:fearange[1]] = desc['constructor'](self.policy,\n fea, action)\n","sub_path":"librl/policies/boltzmann.py","file_name":"boltzmann.py","file_ext":"py","file_size_in_byte":12828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"446827422","text":"\"\"\"GTKWave save file generator.\n\nThis module provides tools for generating GTKWave save files.\n\n`GTKWave`__ is an application for viewing VCD data. When opening a VCD file\nwith GTKWave, by default, no VCD variables (signals) are displayed. It is thus\nuseful to have an accompanying \"save\" file which configures various aspects of\nhow GTKWave shows the VCD data, including which variables are displayed,\nvariable aliases, color information, and more.\n\n__ http://gtkwave.sourceforge.net\n\n\"\"\"\nfrom __future__ import print_function, division\nfrom contextlib import contextmanager\nimport datetime\nimport math\nimport operator\nimport os\nimport time\n\nimport six\nfrom six.moves import reduce\n\n\nclass GTKWSave(object):\n \"\"\"Write GTKWave save files.\n\n This class provides methods for writing the various pieces of a GTKWave\n save file. A GTKWave save file compliments a VCD dump file with dump file\n specific configuration GTKWave uses to display the dump file.\n\n A GTKWave save file is line-oriented ASCII text. Each line consists of a\n single configuration directive. All directives are optional.\n\n Some directives, such as :meth:`dumpfile()`, are for general GTKWave\n configuration. These general directives may be added anywhere in the save\n file and in any order relative to other directives. Directives may also be\n duplicated--the last one added will be used by GTKWave.\n\n The :meth:`trace()`, :meth:`trace_bits()`, :meth:`group()`, and\n :meth:`blank` directives add signals to the \"Signals\" list which are traced\n in the \"Waves\" frame. The order in which these signal traces are added\n determines the order in GTKWave.\n\n \"\"\"\n def __init__(self, savefile):\n self.file = savefile\n self.path = getattr(savefile, 'name', None)\n self._flags = 0\n self._color_stack = [0]\n self._filter_files = []\n self._filter_procs = []\n\n def _p(self, *args, **kwargs):\n print(*args, file=self.file, **kwargs)\n\n def _set_flags(self, flags):\n if flags != self._flags:\n self._p('@{:x}'.format(flags))\n self._flags = flags\n\n def _set_color(self, color):\n if color is not None:\n if isinstance(color, six.string_types):\n color = color_map[color]\n if color == -1:\n self._color_stack[-1] = (self._color_stack[-1] + 1) % 8\n else:\n self._color_stack[-1] = color\n self._p('[color] {}'.format(self._color_stack[-1]))\n\n def _set_translate_filter_file(self, filter_path):\n if filter_path:\n try:\n filter_id = 1 + self._filter_files.index(filter_path)\n except ValueError:\n self._filter_files.append(filter_path)\n filter_id = len(self._filter_files)\n self._p('^{} {}'.format(filter_id, filter_path))\n\n def _set_translate_filter_proc(self, proc_path):\n if proc_path:\n try:\n filter_id = 1 + self._filter_procs.index(proc_path)\n except ValueError:\n self._filter_procs.append(proc_path)\n filter_id = len(self._filter_procs)\n self._p('^>{} {}'.format(filter_id, proc_path))\n\n def comment(self, *comments):\n \"\"\"Add comment line(s) to save file.\"\"\"\n for comment in comments:\n self._p('[*]', comment)\n\n def dumpfile(self, dump_path, abspath=True):\n \"\"\"Add VCD dump file path to save file.\n\n The `[dumpfile]` must be in the save file in order to only have to\n specify the save file on the `gtkwave` command line. I.e.:\n\n $ gtkwave my.gtkw\n\n If the `[dumpfile]` is not present in the save file, both the dump and\n save files must be specified to `gtkwave`:\n\n $ gtkwave my.vcd my.gtkw\n\n :param dump_path: path to VCD dump file or None to produce special\n \"(null)\" value in the save file.\n :param bool abspath: convert *dump_path* to an absolute path.\n\n \"\"\"\n if dump_path is None:\n self._p('[dumpfile] (null)')\n else:\n if abspath:\n dump_path = os.path.abspath(dump_path)\n self._p('[dumpfile] \"{}\"'.format(dump_path))\n\n def dumpfile_mtime(self, mtime=None, dump_path=None):\n \"\"\"Add dump file modification time to save file.\n\n Configuring the dump file's modification time is optional.\n\n \"\"\"\n time_format = '%a %b %d %H:%M:%S %Y'\n if mtime is None:\n mtime = os.stat(dump_path).st_mtime\n if isinstance(mtime, float):\n mtime = time.gmtime(mtime)\n if isinstance(mtime, time.struct_time):\n mtime_str = time.strftime(time_format, mtime)\n elif isinstance(mtime, datetime.datetime):\n mtime_str = mtime.strftime(time_format)\n else:\n raise TypeError('Invalid mtime type ({})'.format(type(mtime)))\n self._p('[dumpfile_mtime] \"{}\"'.format(mtime_str))\n\n def dumpfile_size(self, size=None, dump_path=None):\n \"\"\"Add dump file size annotation to save file.\n\n Configuring the dump file's size is optional.\n\n \"\"\"\n if size is None:\n size = os.stat(dump_path).st_size\n self._p('[dumpfile_size] {}'.format(size))\n\n def savefile(self, save_path=None, abspath=True):\n \"\"\"Add the path of the save file to the save file.\n\n With no parameters, the output file's name will be used.\n\n Configuring the `[savefile]` is optional.\n\n :param save_path: path to this save file. None will use the output\n file's path.\n :param bool abspath: determines whether to make the path absolute.\n\n \"\"\"\n if save_path is None and self.path is None:\n self._p('[savefile] (null)')\n else:\n if save_path is None:\n save_path = self.path\n if abspath and save_path is not None:\n save_path = os.path.abspath(save_path)\n self._p('[savefile] \"{}\"'.format(save_path))\n\n def timestart(self, timestamp=0):\n \"\"\"Add simulation start time to the save file.\"\"\"\n self._p('[timestart] {}'.format(timestamp))\n\n def zoom_markers(self, zoom=0.0, marker=-1, **kwargs):\n \"\"\"Set zoom, primary marker, and markers 'a' - 'z'.\"\"\"\n self._p('*{:.6f} {}'.format(zoom, marker),\n *[kwargs.get(k, -1) for k in 'abcdefghijklmnopqrstuvwxyz'])\n\n def size(self, width, height):\n \"\"\"Set GTKWave window size.\"\"\"\n self._p('[size] {} {}'.format(width, height))\n\n def pos(self, x=-1, y=-1):\n \"\"\"Set GTKWave window position.\"\"\"\n self._p('[pos] {} {}'.format(x, y))\n\n def treeopen(self, tree):\n \"\"\"Start with *tree* open in Signal Search Tree (SST).\n\n GTKWave specifies tree paths with a trailing '.'. The trailing '.' will\n automatically be added if it is omitted in the *tree* parameter.\n\n :param str tree: scope/path/tree to be opened in GTKWave's SST frame.\n\n \"\"\"\n if tree[-1] == '.':\n self._p('[treeopen] {}'.format(tree))\n else:\n self._p('[treeopen] {}.'.format(tree))\n\n def signals_width(self, width):\n \"\"\"Set width of Signals frame.\"\"\"\n self._p('[signals_width] {}'.format(width))\n\n def sst_expanded(self, is_expanded):\n \"\"\"Set whether Signal Search Tree (SST) frame is expanded.\"\"\"\n self._p('[sst_expanded] {}'.format(int(bool(is_expanded))))\n\n def pattern_trace(self, is_enabled):\n \"\"\"Enable/disable pattern trace.\"\"\"\n self._p('[pattern_trace] {}'.format(int(bool(is_enabled))))\n\n @contextmanager\n def group(self, name, closed=False, highlight=False):\n \"\"\"Contextmanager helper for :meth:`begin_group` and :meth:`end_group`.\n\n This context manager starts a new group of signal traces and ends the\n group when leaving the `with` block. E.g.:\n\n >>> with gtkw.group('mygroup'):\n ... gtkw.trace('a.b.x')\n ... gtkw.trace('a.b.y')\n ... gtkw.trace('a.b.z')\n\n :param str name: the name/label of the trace group.\n :param bool closed: group should be closed at GTKWave startup.\n :param bool highlight: group should be highlighted at GTKWave startup.\n\n \"\"\"\n self.begin_group(name, closed, highlight)\n try:\n yield None\n finally:\n self.end_group(name, closed, highlight)\n\n def begin_group(self, name, closed=False, highlight=False):\n \"\"\"Begin a new signal trace group.\n\n Consider using :meth:`group()` instead of :meth:`begin_group()` and\n :meth:`end_group()`.\n\n :param str name: the name/label of the trace group.\n :param bool closed: group should be closed at GTKWave startup.\n :param bool highlight: group should be highlighted at GTKWave startup.\n\n \"\"\"\n flags = ['grp_begin', 'blank']\n if closed:\n flags.append('closed')\n if highlight:\n flags.append('highlight')\n self._set_flags(encode_flags(flags))\n self._p('-{}'.format(name))\n self._color_stack.append(0)\n\n def end_group(self, name, closed=False, highlight=False):\n \"\"\"End a signal trace group.\n\n This call must match with a prior call to :meth:`begin_group().\n Consider using :meth:`group()` instead of :meth:`begin_group()` and\n :meth:`end_group()`.\n\n :param str name: the name/label of the trace group.\n :param bool closed: group should be closed at GTKWave startup.\n :param bool highlight: group should be highlighted at GTKWave startup.\n\n \"\"\"\n flags = ['grp_end', 'blank']\n if closed:\n flags.extend(['closed', 'collapsed'])\n if highlight:\n flags.append('highlight')\n self._set_flags(encode_flags(flags))\n self._p('-{}'.format(name))\n self._color_stack.pop(-1)\n\n def blank(self, label='', analog_extend=False, highlight=False):\n \"\"\"Add blank or label to trace signals list.\n\n :param str label: Optional label for the blank.\n :param bool analog_extend: extend the height of an immediately\n preceding analog trace signal.\n :param bool highlight: blank should be highlighted at GTKWave startup.\n\n \"\"\"\n flags = ['blank']\n if analog_extend:\n flags.append('analog_blank_stretch')\n if highlight:\n flags.append('highlight')\n self._set_flags(encode_flags(flags))\n self._p('-' + label)\n\n def trace(self, name, alias=None, color=None, datafmt='hex',\n highlight=False, rjustify=True, extraflags=None,\n translate_filter_file=None,\n translate_filter_proc=None):\n \"\"\"Add signal trace to save file.\n\n :param str name: fully-qualified name of signal to trace.\n :param str alias: optional alias to display instead of the *name*.\n :param color: optional color to use for the signal's trace.\n :param str datafmt: the format used for data display. Must be one of\n 'hex', 'dec', 'bin', 'oct', 'ascii', 'real', or\n 'signed'.\n :param bool highlight: trace should be highlighted at GTKWave startup.\n :param bool rjustify: trace name/alias should be right-justified.\n :param list extraflags: extra flags to apply to the trace.\n :param str translate_filter_file: path to translate filter file.\n :param str translate_filter_proc: path to translate filter executable.\n\n .. Note::\n\n GTKWave versions <= 3.3.64 require vector signal names to have a\n bit range suffix. For example, an 8-bit vector variable\n \"module.myint\" would be known by GTKWave as \"module.myint[7:0]\".\n\n GTKWave versions after 3.3.64 do not use bit-range suffixes.\n\n \"\"\"\n if datafmt not in ['hex', 'dec', 'bin', 'oct', 'ascii', 'real',\n 'signed']:\n raise ValueError('Invalid datafmt ({})'.format(datafmt))\n flags = [datafmt]\n if extraflags:\n flags.extend(extraflags)\n if highlight:\n flags.append('highlight')\n if rjustify:\n flags.append('rjustify')\n if translate_filter_file:\n flags.append('ftranslated')\n if translate_filter_proc:\n flags.append('ptranslated')\n self._set_flags(encode_flags(flags))\n self._set_color(color)\n self._set_translate_filter_file(translate_filter_file)\n self._set_translate_filter_proc(translate_filter_proc)\n if alias:\n self._p('+{{{}}} '.format(alias), end='')\n self._p(name)\n\n @contextmanager\n def vector(self, name, alias=None, color=None, datafmt='hex',\n highlight=False, rjustify=True, extraflags=None,\n translate_filter_file=None,\n translate_filter_proc=None, traces=[]):\n\n if datafmt not in ['hex', 'dec', 'bin', 'oct', 'ascii', 'real',\n 'signed']:\n raise ValueError('Invalid datafmt ({})'.format(datafmt))\n flags = [datafmt]\n if extraflags:\n flags.extend(extraflags)\n if highlight:\n flags.append('highlight')\n if rjustify:\n flags.append('rjustify')\n if translate_filter_file:\n flags.append('ftranslated')\n if translate_filter_proc:\n flags.append('ptranslated')\n flags.append('grp_begin')\n self._set_flags(encode_flags(flags))\n self._set_color(color)\n self._set_translate_filter_file(translate_filter_file)\n self._set_translate_filter_proc(translate_filter_proc)\n\n self._p('#{{{}}} {}'.format(name, ' '.join(traces)))\n\n try:\n yield None\n finally:\n flags = ['blank', 'grp_end', 'collapsed']\n if highlight:\n flags.append('highlight')\n self._set_flags(encode_flags(flags))\n self._p('-group_end')\n\n @contextmanager\n def trace_bits(self, name, alias=None, color=None, datafmt='hex',\n highlight=False, rjustify=True, extraflags=None,\n translate_filter_file=None,\n translate_filter_proc=None):\n \"\"\"Contextmanager for tracing bits of a vector signal.\n\n This allows each individual bit of a vector signal to have its own\n trace (and trace configuration).\n\n >>> name = 'mod.myint'\n >>> with gtkw.trace_bits(name):\n ... gtkw.trace_bit(0, name)\n ... gtkw.trace_bit(1, name)\n ... gtkw.trace_bit(2, name)\n ... gtkw.trace_bit(3, name, 'special', color=3)\n\n :param str name: fully-qualified name of the vector variable to trace.\n :param str alias: optional alias to display instead of *name*.\n :param int color: optional trace color.\n :param str datafmt: format for data display.\n :param bool highlight: trace should be highlighted at GTKWave startup.\n :param bool rjustify: trace name/alias should be right-justified.\n :param list extraflags: extra flags to apply to the trace.\n :param str translate_filter_file: path to translate filter file.\n :param str translate_filter_proc: path to translate filter executable.\n\n \"\"\"\n self.trace(name, alias, color, datafmt, highlight, rjustify,\n extraflags, translate_filter_file, translate_filter_proc)\n flags = ['bin']\n if extraflags:\n flags.extend(extraflags)\n if highlight:\n flags.append('highlight')\n if rjustify:\n flags.append('rjustify')\n self._set_flags(encode_flags(flags))\n try:\n yield None\n finally:\n flags = ['blank', 'grp_end', 'collapsed']\n if highlight:\n flags.append('highlight')\n self._set_flags(encode_flags(flags))\n self._p('-group_end')\n\n def trace_bit(self, index, name, alias=None, color=None):\n \"\"\"Trace individual bit of vector signal.\n\n This is meant for use in conjunction with :meth:`trace_bits()`.\n\n :param int index: index of bit\n :param str name: name of parent vector signal.\n :param str alias: optional alias to display for bit.\n :param int color: optional color for bit's trace.\n\n \"\"\"\n self._set_color(color)\n if alias:\n self._p('+{{{}}} '.format(alias), end='')\n self._p('({}){}'.format(index, name))\n\n\ndef make_translation_filter(translations, datafmt='hex', size=None):\n \"\"\"Create translation filter.\n\n The returned translation filter string that can be written to a translation\n filter file usable by GTKWave.\n\n :param translations:\n\n Sequence of 2-tuples `(value, alias)` or 3-tuples `(value, alias,\n color)`.\n\n :param str datafmt:\n\n Format to apply to the translation values. This *datafmt* must match\n the *datafmt* used with :meth:`GTKWSave.trace()`, otherwise these\n translations will not be matched by GTKWave.\n\n :returns: Translation filter string suitable for writing to a translation\n filter file.\n\n \"\"\"\n if datafmt == 'hex':\n value_format = '0{}x'.format(int(math.ceil(size / 4)))\n elif datafmt == 'oct':\n value_format = '0{}o'.format(int(math.ceil(size / 3)))\n elif datafmt in ['dec', 'signed']:\n value_format = 'd'\n elif datafmt == 'bin':\n value_format = '0{}b'.format(size)\n elif datafmt == 'real':\n value_format = '.16g'\n elif datafmt == 'ascii':\n value_format = ''\n ascii_translations = []\n for translation in translations:\n value = translation[0]\n rest = list(translation[1:])\n if isinstance(value, six.integer_types):\n value = str(six.int2byte(value).decode('ascii'))\n elif not isinstance(value, six.string_types):\n raise TypeError(\"Invalid type ({}) for ascii translation\"\n .format(type(value)))\n elif len(value) != 1:\n raise ValueError(\"Invalid ascii string '{}'\".format(value))\n ascii_translations.append(tuple([value] + rest))\n translations = ascii_translations\n else:\n raise ValueError('invalid datafmt ({})'.format(datafmt))\n\n lines = []\n\n for translation in translations:\n if len(translation) == 2:\n value, label = translation\n color = None\n else:\n value, label, color = translation\n\n if datafmt in ['hex', 'oct', 'bin']:\n max_val = 1 << size\n if -value > (max_val >> 1) or value >= max_val:\n raise ValueError('Value ({}) not representable in {} bits'\n .format(value, size))\n if value < 0:\n # Two's compliment treatment\n value += 1 << size\n\n value_str = format(value, value_format)\n\n if color is None:\n lines.append('{} {}'.format(value_str, label))\n else:\n lines.append('{} ?{}?{}'.format(value_str, color, label))\n\n return '\\n'.join(lines)\n\n\n#: Map of color names to integer values.\ncolor_map = {\n 'cycle': -1,\n 'normal': 0,\n 'red': 1,\n 'orange': 2,\n 'yellow': 3,\n 'green': 4,\n 'blue': 5,\n 'indigo': 6,\n 'violet': 7\n}\n\n#: These are the valid GTKWave trace flag names.\nflag_names = [\n 'highlight', # Highlight the trace item\n 'hex', # Hexadecimal data value representation\n 'dec', # Decimal data value representation\n 'bin', # Binary data value representation\n 'oct', # Octal data value representation\n 'rjustify', # Right-justify signal name/alias\n 'invert',\n 'reverse',\n 'exclude',\n 'blank', # Used for blank, label, and/or analog height\n 'signed', # Signed (2's compliment) data representation\n 'ascii', # ASCII character representation\n 'collapsed', # Used for closed groups\n 'ftranslated', # Trace translated with filter file\n 'ptranslated', # Trace translated with filter process\n 'analog_step', # Show trace as discrete analog steps\n 'analog_interpolated', # Show trace as analog with interpolation\n 'analog_blank_stretch', # Used to extend height of analog data\n 'real', # Read (floating point) data value representation\n 'analog_fullscale', # Analog data scaled using full simulation time\n 'zerofill',\n 'onefill',\n 'closed',\n 'grp_begin', # Begin a group of signals\n 'grp_end', # End a group of signals\n 'bingray',\n 'graybin',\n 'real2bits',\n 'ttranslated',\n 'popcnt',\n 'fpdecshift',\n]\n\n#: Map flag names to their integer mask values.\nflag_masks = {name: (1 << i) for i, name in enumerate(flag_names)}\n\n\ndef decode_flags(flags):\n \"\"\"Decode hexadecimal flags from GTKWave save file into flag names.\n\n This is useful for understanding what, for example \"@802022\" means when\n inspecting a GTKWave save file.\n\n :param flags: Hexadecimal flags from GTKWave save file; either as an\n integer or string with hexadecimal characters.\n :returns: List of flag names\n\n \"\"\"\n if isinstance(flags, six.string_types):\n flags = int(flags.lstrip('@'), 16)\n return [name for i, name in enumerate(flag_names) if (1 << i) & flags]\n\n\ndef encode_flags(names):\n \"\"\"Encode flag names into integer representation.\n\n The this is the bitwise-or of each of the flag's mask values.\n\n :param names: Sequence of flag names, i.e. from :const:`flag_names`.\n :returns: Integer value of flags.\n\n \"\"\"\n return reduce(operator.ior, (flag_masks[name] for name in names), 0)\n\n\ndef spawn_gtkwave_interactive(dump_path, save_path,\n quiet=False): # pragma: no cover\n \"\"\"Spawn gtkwave process in interactive mode.\n\n A process pipeline is constructed such that the contents of the VCD dump\n file at *dump_path* are displayed interactively as the dump file is being\n written (i.e. with :class:`~vcd.writer.VCDWriter`.\n\n The process pipeline built is approximately equivalent to::\n\n $ tail -f dump_path | shmidcat | gtkwave -vI save_path\n\n The ``tail``, ``shmidcat``, and ``gtkwave`` executables must be found in\n ``$PATH``.\n\n .. Warning::\n\n This function does not work on Windows.\n\n .. Note::\n\n A child python process of the caller will remain running until the\n GTKWave window is closed. This process ensures that the various other\n child processes are properly reaped.\n\n :param str dump_path: path to VCD dump file. The dump file must exist, but\n be empty.\n :param str save_path: path to GTKWave save file. The save file will be read\n immediately by GTKWave and thus must be completely\n written.\n :param bool quiet: quiet GTKWave's output by closing its `stdout` and\n `stderr` file descriptors.\n\n \"\"\"\n import signal\n\n stdin_fd, stdout_fd, stderr_fd = 0, 1, 2\n\n if not os.fork():\n shmidcat_rd_fd, tail_wr_fd = os.pipe()\n\n tail_pid = os.fork()\n if not tail_pid:\n os.close(shmidcat_rd_fd)\n os.dup2(tail_wr_fd, stdout_fd)\n os.execlp('tail', 'tail', '-n', '+0', '-f', dump_path)\n\n os.close(tail_wr_fd)\n gtkwave_rd_fd, shmidcat_wr_fd = os.pipe()\n\n shmidcat_pid = os.fork()\n if not shmidcat_pid:\n os.close(gtkwave_rd_fd)\n os.dup2(shmidcat_rd_fd, stdin_fd)\n os.dup2(shmidcat_wr_fd, stdout_fd)\n os.execlp('shmidcat', 'shmidcat')\n\n os.close(shmidcat_rd_fd)\n os.close(shmidcat_wr_fd)\n\n gtkwave_pid = os.fork()\n if not gtkwave_pid:\n os.dup2(gtkwave_rd_fd, stdin_fd)\n if quiet:\n devnull = open(os.devnull, 'w')\n os.dup2(devnull.fileno(), stdout_fd)\n os.dup2(devnull.fileno(), stderr_fd)\n os.execlp('gtkwave',\n 'gtkwave', '--vcd', '--interactive', save_path)\n\n # The first forked process exists to do this cleanup...\n os.waitpid(gtkwave_pid, 0)\n os.kill(tail_pid, signal.SIGTERM)\n os.kill(shmidcat_pid, signal.SIGTERM)\n os._exit(0)\n","sub_path":"utils/gap_configs/python/gtkw_new.py","file_name":"gtkw_new.py","file_ext":"py","file_size_in_byte":24785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"541605181","text":"import logging\nimport os\n\nimport torch\nimport torch.multiprocessing as mp\n\nimport optimizer as my_optim\nfrom config import Params\nfrom envs import create_expansionai_env\nfrom model import ActorCritic\nfrom test import test\nfrom train import train\n\nLOGGING_FORMAT = '%(asctime)s - %(name)s - %(thread)d|%(process)d - %(levelname)s - %(message)s'\nlogging.basicConfig(format=LOGGING_FORMAT)\n\n# logging.getLogger('Model').setLevel(logging.INFO)\n# logging.getLogger('ExpansionAiEnv').setLevel(logging.DEBUG)\nlogging.getLogger('Train').setLevel(logging.INFO)\nlogging.getLogger('Test').setLevel(logging.INFO)\n\n# Main run\nos.environ['OMP_NUM_THREADS'] = '1' # 1 thread per core\nparams = Params() # creating the params object from the Params class, that sets all the model parameters\nparams.max_episode_length = 1_000_000\nparams.num_processes = 3\n\ntorch.manual_seed(params.seed) # setting the seed (not essential)\nenv = create_expansionai_env(params.env_name, params) # we create an optimized environment thanks to universe\n\n# shared_model is the model shared by the different agents (different threads in different cores)\nshared_model = ActorCritic(env.observation_space.shape[0], env.action_space)\n# storing the model in the shared memory of the computer, which allows the threads to have access to this shared memory even if they are in different cores\nshared_model.share_memory()\n\n# the optimizer is also shared because it acts on the shared model\noptimizer = my_optim.SharedAdam(shared_model.parameters(), lr=params.lr)\noptimizer.share_memory() # same, we store the optimizer in the shared memory so that all the agents can have access to this shared memory to optimize the model\n\nprocesses = [] # initializing the processes with an empty list\n\n# making a loop to run all the other processes that will be trained by updating the shared model\nfor rank in range(0, params.num_processes):\n p = mp.Process(target=train, args=(rank, params, shared_model, optimizer))\n p.start()\n processes.append(p)\n\n# allowing to create the 'test' process with some arguments 'args' passed to the 'test' target function - the 'test' process doesn't update the shared model but uses it on a part of it - torch.multiprocessing.Process runs a function in an independent thread\np = mp.Process(target=test, args=(params.num_processes, params, shared_model))\np.start() # starting the created process p\nprocesses.append(p) # adding the created process p to the list of processes\n\n# creating a pointer that will allow to kill all the threads when at least one of the threads, or main.py will be killed, allowing to stop the program safely\nfor p in processes:\n p.join()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"188854870","text":"# -*-coding:utf-8-*-\n\nimport unittest\nimport time\nfrom app.driver import Driver\n'''\n===========说明============\n功能:封装unittest\n\n==========================\n'''\n\n\nclass Myunittest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.dr = Driver()\n # cls.dr.implicitly_wait(30)\n return cls.dr\n\n\n @classmethod\n def tearDownClass(cls):\n time.sleep(2)\n cls.dr.quit()\n\n # # 每执行一个测试用例,就重启开启一次 appium Session(现象-重启app)\n # def setUp(self):\n # self.dr = Driver()\n # self.dr.implicitly_wait(30)\n # return self.dr\n #\n # def tearDown(self):\n # self.dr.quit()\n\n\nif __name__ == '__main__':\n Myunittest()","sub_path":"app/mytest.py","file_name":"mytest.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"39089975","text":"\"\"\"\nStores options and default values for \n\"\"\"\nimport yaml\nimport argparse\nfrom collections import OrderedDict\n\n\nclass Option:\n def __init__(self, name, type=str, default_value=None, required=None, force_flag=False, help=None):\n \"\"\"\n Defines a configuration option\n :param name: Name of the option\n :param type: Expected type. Should be a base type.\n :param default_value: Default option value. If this is set to anything other than none, and the option is not\n explicitly marked as required, it will be considered optional.\n :param required: Whether the option is required.\n :param force_flag: Force making this argument a flag (starting with '--') even though it is required\n \"\"\"\n self.name = name\n self.type = type\n self.default_value = default_value\n self.required = required == True or required is None and default_value is None\n self.force_flag = force_flag\n self.help = help\n\n\nclass Args: pass\n\n\nclass OptionParser:\n def __init__(self):\n self.tasks = {}\n \"\"\"Options, sorted by task\"\"\"\n\n def add_task(self, task_name, task_options):\n self.tasks[task_name] = OrderedDict([(opt.name, opt) for opt in task_options])\n\n def check_and_convert(self, task_name, option_name, value):\n if option_name not in self.tasks[task_name]:\n raise RuntimeError(\"Unknown option {} for task {}\".format(option_name, task_name))\n\n option = self.tasks[task_name][option_name]\n value = option.type(value)\n\n return value\n\n def args_from_config_file(self, file):\n \"\"\"\n Returns a dictionary of experiments => {task => {arguments object}}\n \"\"\"\n try:\n with open(file) as stream:\n config = yaml.load(stream)\n except IOError as e:\n raise RuntimeError(\"Could not read configuration file {}: {}\".format(file, e))\n\n # Default values as specified in option definitions\n defaults = {\n task_name: {name: opt.default_value for name, opt in task_options.items() if\n opt.default_value is not None or not opt.required}\n for task_name, task_options in self.tasks.items()}\n\n # defaults section in the config file\n if \"defaults\" in config:\n for task_name, task_options in config[\"defaults\"].items():\n defaults[task_name].update(\n {name: self.check_and_convert(task_name, name, value) for name, value in task_options.items()})\n del config[\"defaults\"]\n\n experiments = {}\n for exp, exp_tasks in config.items():\n experiments[exp] = {}\n for task_name in self.tasks:\n task_values = defaults[task_name].copy()\n exp_task_values = exp_tasks.get(task_name, dict())\n task_values.update(\n {name: self.check_and_convert(task_name, name, value) for name, value in exp_task_values.items()})\n\n # Check that no required option is missing\n for _, option in self.tasks[task_name].items():\n if option.required and option.name not in task_values:\n raise RuntimeError(\n \"Required option not found for experiment {}, task {}: {}\".format(exp, task_name, option.name))\n\n # Replace the special token \"\" with the experiment name if necessary\n for k in task_values.keys():\n if type(task_values[k]) == str:\n task_values[k] = task_values[k].replace(\"\", exp)\n\n experiments[exp][task_name] = Args()\n for name, val in task_values.items():\n setattr(experiments[exp][task_name], name, val)\n\n return experiments\n\n def args_from_command_line(self, task, argv):\n parser = argparse.ArgumentParser()\n for option in self.tasks[task].values():\n if option.required and not option.force_flag:\n parser.add_argument(option.name, type=option.type, help=option.help)\n else:\n parser.add_argument(\"--\" + option.name, default=option.default_value, required=option.required,\n type=option.type, help=option.help)\n\n return parser.parse_args(argv)\n\n def remove_option(self, task, option_name):\n if option_name not in self.tasks[task]:\n raise RuntimeError(\"Tried to remove nonexistent option {} for task {}\".format(option_name, task))\n del self.tasks[task][option_name]\n\n def generate_options_table(self):\n \"\"\"\n Generates markdown documentation for the options\n \"\"\"\n lines = []\n for task, task_options in self.tasks.items():\n lines.append(\"## {}\".format(task))\n lines.append(\"\")\n lines.append(\"| Name | Description | Type | Default value |\")\n lines.append(\"|------|-------------|------|---------------|\")\n for option in task_options.values():\n if option.required:\n template = \"| **{}** | {} | {} | {} |\"\n else:\n template = \"| {} | {} | {} | {} |\"\n lines.append(template.format(option.name, option.help if option.help else \"\", option.type.__name__,\n option.default_value if option.default_value is not None else \"\"))\n lines.append(\"\")\n\n return \"\\n\".join(lines)\n\n\n# Predefined options for dynet\ngeneral_options = [\n Option(\"dynet_mem\", int, required=False),\n Option(\"dynet_seed\", int, required=False),\n]\n","sub_path":"xnmt/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249269325","text":"import os\r\nfrom sqlalchemy import create_engine\r\nfrom sqlalchemy.engine import url\r\nfrom yaml import load, Loader\r\nfrom flask import Flask\r\n\r\ndef init_connect_engine():\r\n if os.environ.get(\"GAE_ENV\") != 'standard':\r\n variables = load(open(\"app.yaml\"), Loader=Loader)\r\n env_variables = variables['env_variables']\r\n for var in env_variables:\r\n os.environ[var] = env_variables[var]\r\n\r\n pool = create_engine(\r\n url.URL(\r\n drivername=\"mysql+pymysql\",\r\n username=os.environ.get('DB_USER'),\r\n password=os.environ.get('DB_PASS'),\r\n database=os.environ.get('DB_NAME'),\r\n host=os.environ.get('DB_HOST')\r\n )\r\n )\r\n \r\n return pool\r\n\r\ndb = init_connect_engine()\r\n\r\napp = Flask(__name__)\r\n# CORS(app)\r\n\r\nfrom goodreads_app import routes\r\n","sub_path":"cs411-final-project-main 3/flask_backend/goodreads_app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"294103643","text":"import requests\nimport re\n\nclass GoogleDirections():\n __fromAddress = None\n __toAddress = None\n __url = None\n __directions = None\n \n def __init__(self):\n self.__fromAddress = \"\"\n self.__toAddress = \"\"\n self.__url = \"http://maps.googleapis.com/maps/api/directions/json?origin=\"\n self.__directions = []\n\n def __cleanHTML(self, text):\n regex = re.compile('<.*?>')\n strippedText = re.sub(regex, ' ', text)\n return strippedText\n \n def getDirections(self, fromAddress, toAddress, instructionsLanguage=\"en\"):\n if len(self.__directions) > 0:\n del self.__directions[:]\n \n self.__fromAddress = fromAddress\n self.__toAddress = toAddress\n self.__url = self.__url + self.__fromAddress + \"&destination=\" + self.__toAddress + \"&language=\" + instructionsLanguage + \"&sensor=false\"\n jsonData = requests.get(self.__url)\n steps = None\n\n try:\n steps = jsonData.json()[\"routes\"][0][\"legs\"][0][\"steps\"]\n except Exception as e:\n return None\n \n if steps == None:\n return None\n\n for step in steps:\n direction = self.__cleanHTML(step[\"html_instructions\"])\n self.__directions.append(direction.replace(\" \", \" \"))\n\n return self.__directions\n","sub_path":"googledirections.py","file_name":"googledirections.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"348169705","text":"\"\"\"\r\n@ Recommendation using Nearest Neighbor\r\nThe Class for Collaborative Filtering: Correlation, Matrix Factorization and Association Rule\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\n# correlation and other packages for N-neighbors\r\nfrom scipy.spatial.distance import correlation\r\n\r\n# create the class which takes data and pivot matrix: userId, itemID, values=rating, K =10 default\r\nclass NearestNeighbors:\r\n def __init__(self, data_r,data_m, K=10):\r\n self.activeUser = None\r\n self.userId = None\r\n self.N = None\r\n self.data_r = data_r\r\n self.data_m=data_m\r\n self.K=K\r\n self.data = pd.merge(self.data_r,self.data_m,left_on='itemId',right_on=\"itemId\")\r\n self.userItemRatingMatrix= pd.pivot_table(self.data,\r\n values='rating',index=['userId'], columns=['itemId'])\r\n\r\n # Find the top N favorite movies of a user\r\n def favoriteMovies(self, activeUser, N):\r\n\r\n topMovies = pd.DataFrame.sort_values(\r\n self.data[self.data.userId == activeUser], ['rating'], ascending=[0])[:N]\r\n return list(topMovies.title)\r\n\r\n\r\n # Find the similarity between 2 users: a and b\r\n def similarity(self, user1, user2):\r\n \"\"\"\r\n takes users a and b => normalize\r\n get the common movie\r\n get the correlation between user a and b using rating values\r\n \"\"\"\r\n user1 = np.array(user1) - np.nanmean(user1)\r\n user2 = np.array(user2) - np.nanmean(user2)\r\n # common movies for user1 and user2\r\n commonItemIds = [i for i in range(len(user1)) if user1[i] > 0 and user2[i] > 0]\r\n # if they have no common movie: exit otherwise compute the correlation between two vectors of users a and b\r\n if len(commonItemIds) == 0:\r\n # If there are no movies in common\r\n return 0\r\n else:\r\n user1 = np.array([user1[i] for i in commonItemIds])\r\n user2 = np.array([user2[i] for i in commonItemIds])\r\n return correlation(user1, user2)\r\n\r\n # Compute the Nearest Neighbor for a user: using the correlation from usr_similarity function above\r\n def nearestNeighbourRatings(self, activeUser, K):\r\n # create the empty matrix with index = userID and column Similarity_score\r\n similarityMatrix = pd.DataFrame(index=self.userItemRatingMatrix.index,\r\n columns=['Similarity'])\r\n # find the similarity between active and each user from userItem rating matrix and add value to sim matrix\r\n for i in self.userItemRatingMatrix.index:\r\n similarityMatrix.loc[i] = self.similarity(self.userItemRatingMatrix.loc[activeUser],\r\n self.userItemRatingMatrix.loc[i])\r\n # Sort the similarity matrix in descending order based on similarity_score\r\n similarityMatrix = pd.DataFrame.sort_values(similarityMatrix,\r\n ['Similarity'], ascending=[0])\r\n # Chose the top K nearest neighbors\r\n nearestNeighbours = similarityMatrix[:K]\r\n # take the neighbor's rating for those movies where fixed_user have not rated (to predict the rating)\r\n neighbourItemRatings = self.userItemRatingMatrix.loc[nearestNeighbours.index]\r\n # Now predict the rating for based on other similar users rating for those movies which fix_users have not rated\r\n predictItemRating = pd.DataFrame(index=self.userItemRatingMatrix.columns, columns=['Rating'])\r\n # for each movie in userItem matrix: start with average rating of users\r\n for i in self.userItemRatingMatrix.columns:\r\n # for each item\r\n predictedRating = np.nanmean(self.userItemRatingMatrix.loc[activeUser])\r\n # for each neighbor in the neighbor list\r\n for j in neighbourItemRatings.index:\r\n # if nbr has rated movie add that rating adjusted with avg rating of nbr weighted by similarity\r\n # of the neighbor to the fix_user\r\n if self.userItemRatingMatrix.loc[j, i] > 0:\r\n predictedRating += (self.userItemRatingMatrix.loc[j, i]\r\n - np.nanmean(self.userItemRatingMatrix.loc[j])) * nearestNeighbours.loc[\r\n j, 'Similarity']\r\n # get out of loop and uses nbrs rating to predicted rating matrix\r\n predictItemRating.loc[i, 'Rating'] = predictedRating\r\n return predictItemRating\r\n\r\n # define function to find the top N recommendation based on what we predicted the rating\r\n def topNRecommendations(self, activeUser, N):\r\n # use 10 nearest nbrs to predict the rating:default value\r\n predictItemRating = self.nearestNeighbourRatings(activeUser, self.K)\r\n # To find the already watched movie = have some rating for that movie\r\n # find all the not NaN movies (scored by user already)\r\n moviesAlreadyWatched = list(self.userItemRatingMatrix.loc[activeUser]\r\n .loc[self.userItemRatingMatrix.loc[activeUser] > 0].index)\r\n # drop already seen movies\r\n predictItemRating = predictItemRating.drop(moviesAlreadyWatched)\r\n # Get the top recommended movie name\r\n topRecommendations = pd.DataFrame.sort_values(predictItemRating,\r\n ['Rating'], ascending=[0])[:N]\r\n # get the corresponding movie title\r\n topRecommendationTitles = (self.data_m.loc[self.data_m.itemId.isin(topRecommendations.index)])\r\n return list(topRecommendationTitles.title)","sub_path":"NearestNbr_CF_MatrixFacto_movieLenData/NearestNeighbor_CF.py","file_name":"NearestNeighbor_CF.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"410009279","text":"from sys import argv,exit\nfrom cs50 import SQL\nimport csv\n\ndef partition_name(full_name):\n names = full_name.split()\n return names if len(names) >= 3 else [names[0], None, names[1]]\n \nif len(argv) != 2:\n print(\"Incorrect number of arguments\")\n exit(1)\n \ndb = SQL(\"sqlite:///students.db\")\n\n\ncsv_path = argv[1]\n\nwith open (csv_path) as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n names = partition_name(row[\"name\"])\n db.execute(\"INSERT INTO students(first,middle,last,house,birth) VALUES(?, ? ,? ,? ,?)\",names[0],names[1],names[2],row[\"house\"],row[\"birth\"])\n \n\n\n\n","sub_path":"pset7/houses/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"60932255","text":"import pandas as pd\nfrom graphviz import Digraph\nfrom graphviz import *\n\nedge_df = pd.read_csv(\"edge_test.csv\")\n\n\nu = Digraph('unix', filename='test/test-unix2.gv',\n node_attr={'color': 'lightblue2', 'style': 'filled'}, graph_attr={'newrank': \"False\", 'fixedsize': \"False\"})\nu.attr(size='6,6')\n\n# u.edge(f'{row[\"source\"]}', f'{row[\"target\"]}')\n\nedge_df = edge_df.astype({\"source\": str, \"target\": str})\nu.node(\"0\")\n\nfor gen in edge_df.gen.unique():\n\n with u.subgraph() as s:\n s.attr(rank='same')\n counter = 0\n for i, row in edge_df[edge_df['gen'] == gen].iterrows():\n s.node(row['target'])\n counter += 1\n\nfor i, row in edge_df.iterrows():\n u.edge(row['source'], row['target'])\n# edge_df[edge_df['gen'] == gen].target.values\n# u.add_subgraph([edge_df[edge_df['gen'] == gen].target.values],name=f's-gen-{gen}').graph_attr['rank']='same'\n\n# for i, row in edge_df[edge_df['gen'] == gen].iterrows():\n# s.edge(f'{row[\"source\"]}', f'{row[\"target\"]}')\n\nu.view()","sub_path":"notebooks/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"209336395","text":"# example from https://github.com/chainer/chainerrl/blob/master/examples/quickstart/quickstart.ipynb modified for doom\nfrom __future__ import print_function\nfrom vizdoom import *\n\nfrom random import choice\nfrom time import sleep\n\nimport datetime\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nimport chainerrl\nfrom chainerrl import env\nfrom chainerrl import spaces\nimport gym\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom skimage.color import rgb2gray\nfrom skimage.transform import resize\n\nn_episodes = 220\nsave_every = 5\nsteps_per_epoch = 2000\n\nclass DOOM_ENV(env.Env):\n \"\"\"Arcade Learning Environment.\"\"\"\n\n def __init__(self, scenario=\"./config/basic.wad\", dmap = \"map01\", episode_len=200, window=True):\n self.game = DoomGame()\n self.game.set_doom_scenario_path(scenario)\n self.game.set_doom_map(dmap)\n self.game.set_screen_resolution(ScreenResolution.RES_640X480)\n self.game.set_screen_format(ScreenFormat.RGB24)\n self.game.set_depth_buffer_enabled(True)\n self.game.set_labels_buffer_enabled(True)\n self.game.set_automap_buffer_enabled(True)\n self.game.set_render_hud(False)\n self.game.set_render_minimal_hud(False) # If hud is enabled\n self.game.set_render_crosshair(False)\n self.game.set_render_weapon(True)\n self.game.set_render_decals(False) # Bullet holes and blood on the walls\n self.game.set_render_particles(False)\n self.game.set_render_effects_sprites(False) # Smoke and blood\n self.game.set_render_messages(False) # In-game messages\n self.game.set_render_corpses(False)\n self.game.set_render_screen_flashes(True) # Effect upon taking damage or picking up items\n self.game.add_available_button(Button.MOVE_LEFT)\n self.game.add_available_button(Button.MOVE_RIGHT)\n self.game.add_available_button(Button.ATTACK)\n self.game.add_available_game_variable(GameVariable.AMMO2)\n self.game.set_episode_timeout(episode_len)\n self.game.set_episode_start_time(10)\n self.game.set_window_visible(window)\n self.game.set_sound_enabled(True)\n self.game.set_living_reward(-1)\n self.game.set_mode(Mode.PLAYER)\n self.game.init()\n self.game.new_episode()\n self._reward=0\n self.frame = 0\n self.legal_actions = [[True, False, False], [False, True, False], [False, False, True]]\n self.episode_len = episode_len\n obs = resize(rgb2gray(self.game.get_state().screen_buffer), (80, 80))\n obs = obs[np.newaxis, :, :]\n self.current_screen = obs\n\n @property\n def state(self):\n if self.game.is_episode_finished():\n return self.current_screen\n rr = self.game.get_state()\n obs = resize(rgb2gray(rr.screen_buffer), (80, 80))\n obs = obs[np.newaxis, :, :]\n self.current_screen = obs\n return obs\n \n def random_action_doom(self,nothing=0) :\n result = choice(range(0,len(self.legal_actions)))\n return result\n\n @property\n def is_terminal(self):\n if self.game.is_episode_finished():\n return True\n return self.frame == self.episode_len-1\n\n @property\n def reward(self):\n return self._reward\n\n @property\n def number_of_actions(self):\n return len(self.legal_actions)\n\n def receive_action(self, action):\n self._reward = self.game.make_action(self.legal_actions[action])\n return self._reward\n\n def initialize(self):\n self.game.new_episode()\n self._reward = 0\n self.frame = 0\n\n def reset(self):\n self.initialize()\n return self.state\n\n def step(self, action):\n self.frame = self.frame + 1\n self.receive_action(action)\n return self.state, self.reward, self.is_terminal, {}\n\n def set_visible(self, visible):\n self.game.set_window_visible(visible)\n\n def close(self):\n pass\n\n\n#---------------------------------------------------------------------------\nenv = DOOM_ENV()\nobs = env.reset()\n\nclass QFunction(chainer.Chain):\n def __init__(self, n_history=1, n_action=6):\n super().__init__(\n l1=L.Convolution2D(n_history, 32, ksize=8, stride=4, nobias=False),\n l2=L.Convolution2D(32, 64, ksize=3, stride=2, nobias=False),\n l3=L.Convolution2D(64, 64, ksize=3, stride=1, nobias=False),\n l4=L.Linear(3136, 512),\n out=L.Linear(512, n_action, initialW=np.zeros((n_action, 512), dtype=np.float32))\n )\n\n def __call__(self, x, test=False):\n s = chainer.Variable(x)\n h1 = F.relu(self.l1(s))\n h2 = F.relu(self.l2(h1))\n h3 = F.relu(self.l3(h2))\n h4 = F.relu(self.l4(h3))\n h5 = self.out(h4)\n return chainerrl.action_value.DiscreteActionValue(h5)\n\nn_action = env.number_of_actions\nprint(\"n action size obs\")\nprint(n_action)\nn_history=1\nq_func = QFunction(n_history, n_action)\n\noptimizer = chainer.optimizers.Adam(eps=1e-2)\noptimizer.setup(q_func)\n\ngamma = 0.95\n\nexplorer = chainerrl.explorers.ConstantEpsilonGreedy(\n epsilon=0.3, random_action_func=env.random_action_doom)\n\nreplay_buffer = chainerrl.replay_buffer.ReplayBuffer(capacity=10 ** 4)\n\nphi = lambda x: x.astype(np.float32, copy=False)\n\nagent = chainerrl.agents.DoubleDQN(\n q_func, optimizer, replay_buffer, gamma, explorer,\n minibatch_size=4, replay_start_size=500,\n phi=phi)\n\nlast_time = datetime.datetime.now()\n\nfilename = \"toreplace\"\n\nenv = DOOM_ENV()\nobs = env.reset()\n\nclass QFunction(chainer.Chain):\n def __init__(self, n_history=1, n_action=6):\n super().__init__(\n l1=L.Convolution2D(n_history, 32, ksize=8, stride=4, nobias=False),\n l2=L.Convolution2D(32, 64, ksize=3, stride=2, nobias=False),\n l3=L.Convolution2D(64, 64, ksize=3, stride=1, nobias=False),\n l4=L.Linear(3136, 512),\n out=L.Linear(512, n_action, initialW=np.zeros((n_action, 512), dtype=np.float32))\n )\n\n def __call__(self, x, test=False):\n s = chainer.Variable(x)\n h1 = F.relu(self.l1(s))\n h2 = F.relu(self.l2(h1))\n h3 = F.relu(self.l3(h2))\n h4 = F.relu(self.l4(h3))\n h5 = self.out(h4)\n return chainerrl.action_value.DiscreteActionValue(h5)\n\nn_action = env.number_of_actions\nprint(\"n action size obs\")\nprint(n_action)\nn_history=1\nq_func = QFunction(n_history, n_action)\n\noptimizer = chainer.optimizers.Adam(eps=1e-2)\noptimizer.setup(q_func)\n\ngamma = 0.95\n\nexplorer = chainerrl.explorers.ConstantEpsilonGreedy(\n epsilon=0.3, random_action_func=env.random_action_doom)\n\nreplay_buffer = chainerrl.replay_buffer.ReplayBuffer(capacity=10 ** 4)\n\nphi = lambda x: x.astype(np.float32, copy=False)\n\nagent = chainerrl.agents.DoubleDQN(\n q_func, optimizer, replay_buffer, gamma, explorer,\n minibatch_size=4, replay_start_size=500,\n phi=phi)\n\nlast_time = datetime.datetime.now()\n\nenv.set_visible(False)\n\nfilename = \"toreplace\"\nfor i in range(1, n_episodes + 1):\n\n print(\"Epoch%d\\n________\"%(i))\n obs = resize(rgb2gray(env.reset()),(80,80))\n obs = obs[np.newaxis, :, :]\n\n reward = 0\n done = False\n R = 0\n\n trained_episode = 1\n total_reward = []\n\n last_time = datetime.datetime.now()\n for step in tqdm(range(steps_per_epoch)):\n action = agent.act_and_train(obs,reward)\n obs, reward, done, _ = env.step(action)\n obs = resize(rgb2gray(obs), (80, 80))\n obs = obs[np.newaxis, :, :]\n\n if reward != 0:\n R += reward\n\n if done == True:\n agent.stop_episode_and_train(obs, reward, done)\n obs = resize(rgb2gray(env.reset()),(80,80))\n obs = obs[np.newaxis, :, :]\n trained_episode += 1\n total_reward.append(R)\n\n reward = 0\n done = False\n R=0\n\n elapsed_time = datetime.datetime.now() - last_time\n print(\"%d episodes is trained\")\n print('minutes:', elapsed_time.seconds/60)\n total_reward = np.array(total_reward)\n print(\"reward_mean:%d, reward_max:%d, reward_min:%d\" % (np.mean(total_reward), np.max(total_reward), np.min(total_reward)))\n\n agent.stop_episode_and_train(obs, reward, done)\n if i % save_every == 0:\n filename = 'agent_Breakout' + str(i)\n agent.save(filename)\nprint('Finished. Now testing')\n\nprint(\"demo starts\")\n#agent.load(filename)\n\nenv.set_visible(True)\nfor i in range(1):\n obs = resize(rgb2gray(env.reset()),(80,80))\n obs = obs[np.newaxis, :, :]\n\n reward = 0\n done = False\n R = 0\n\n while not done:\n action = agent.act(obs)\n #action = agent.act_and_train(obs, reward)\n #action = agent.act(obs)\n obs, reward, done, _ = env.step(action)\n obs = resize(rgb2gray(obs), (80, 80))\n obs = obs[np.newaxis, :, :]\n\n\n agent.stop_episode()\nprint(\"demo ended\")\n","sub_path":"source/chainer_test/yutaro_chaintest4.py","file_name":"yutaro_chaintest4.py","file_ext":"py","file_size_in_byte":8881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"52499891","text":"from flask import Flask, render_template, url_for, flash, redirect\nfrom flask_sqlalchemy import SQLAlchemy\nimport odoorpc\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://quocanh:123@localhost/flask-blog'\ndb = SQLAlchemy(app)\n\n# Prepare the connection to the server\nodoo = odoorpc.ODOO('localhost', port=8069)\n\n# Check available databases\nprint(odoo.db.list())\n\n# Login\nodoo.login('flask-blog', 'admin', 'admin')\n\n\n@app.route(\"/\")\n@app.route(\"/home\")\ndef home():\n posts = odoo.env['post'].search([])\n posts.sort(reverse=True)\n post = odoo.execute('post', 'read', posts)\n return render_template('home.html', post=post)\n\n\n@app.route(\"/detail/\")\ndef post_detail(id):\n post = odoo.env['post'].browse(id)\n return render_template('detail.html', post=post)\n\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html')\n\n\n@app.route(\"/contact\")\ndef contact():\n return render_template('contact.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"my-blog/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"263596014","text":"from model import *\nfrom dense import *\nfrom activation import *\nfrom loss import *\nfrom optimizer import *\nimport numpy as np\n\n# 线性拟合\n\nsample = 10\nnum_input = 5\n\n#加入训练数据\nnormalRand = np.random.normal(0,0.1,sample)\nweight = [7,99,-1,-333,0.06]\nx_train = np.random.random((sample, num_input))\ny_train = np.zeros((sample,1))\nfor i in range (0,len(x_train)):\n\ttotal = 0\n\tfor j in range(0,len(x_train[i])):\n\t\ttotal += weight[j]*x_train[i,j]\n\ty_train[i] = total+normalRand[i]\n\n# 训练\nmodel = Model()\nmodel.add(Dense(1,input_shape=(1,5)))\n\noptimizer = Optimizer(rate=0.05,momentum=0.9)\nloss = Loss(\"mse\")\nmodel.compile(optimizer=optimizer,loss=loss)\n\nmodel.fit(x_train,y_train,epochs=1000)\n\nprint(model.get_weight())","sub_path":"deep_net/bp/linear_test.py","file_name":"linear_test.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"350208409","text":"try:\n import ujson as json\nexcept:\n import json\nimport pickle\nimport sys\nimport lzma as compressor\nCOMPRESSOR_EXTENSION = 'xz'\n\n# line = \"INSERT INTO TOXIC VALUES \"\n\ndef pickle2sql(file):\n with compressor.open(file, 'rb') as test_file:\n with open(\"dump.sql\", 'w') as result_file:\n result_file.write('START TRANSACTION;\\n\\n')\n test_pickle = pickle.load(test_file)\n counter = 0\n index = 0\n result_file.write(\"INSERT INTO twitchtoxicity.messages (`message_data`) VALUES \\n\");\n\n for line in test_pickle:\n if index == len(test_pickle)-1: \n line = json.dumps(line)\n line = line.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")\n result_file.write(\"('\")\n result_file.write(line)\n result_file.write(\"');\\n\")\n index += 1\n sys.stdout.write(\"Done. Processed {} from {} ({:.1%}) \\r\".format(index,len(test_pickle),index/len(test_pickle)))\n\n elif counter == 999:\n line = json.dumps(line)\n line = line.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")\n result_file.write(\"('\")\n result_file.write(line)\n result_file.write(\"');\\n\")\n counter = 0\n result_file.write(\"\\nINSERT INTO twitchtoxicity.messages (`message_data`) VALUES \\n\");\n index += 1\n sys.stdout.write(\"Processed {} from {} ({:.1%}) \\r\".format(index,len(test_pickle),index/len(test_pickle)))\n #sql_line = \"INSERT INTO twitchtoxicity.messages ('message_data') VALUES \\n\"\n\n else:\n line = json.dumps(line)\n line = line.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")\n result_file.write(\"('\")\n result_file.write(line)\n result_file.write(\"'),\\n\")\n\n counter += 1\n index += 1\n result_file.write('\\nCOMMIT;\\n')\n\n print(\"\\nDone.\")\n\nif __name__ == \"__main__\":\n test_pickle = \"./data/videos/MLG/Luminosity Gaming vs Virtus Pro - Quarter Finals - MLG CSGO Major-v58219102.rechat-filtered.pickle.xz\"\n pickle2sql(test_pickle)\n","sub_path":"src/Sentiment/pickle2sql.py","file_name":"pickle2sql.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"605258369","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 datetime import datetime\nfrom datetime import timedelta\nfrom distutils.util import strtobool\n\nfrom dlrn.api import app\nfrom dlrn.api.utils import auth\nfrom dlrn.api.utils import InvalidUsage\n\nfrom dlrn.db import CIVote\nfrom dlrn.db import Commit\nfrom dlrn.db import getSession\n\nfrom dlrn.remote import import_commit\n\nfrom flask import jsonify\nfrom flask import request\n\nimport os\nfrom sqlalchemy import desc\nimport time\n\n\n@app.errorhandler(InvalidUsage)\ndef handle_invalid_usage(error):\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n\ndef getVote(session, timestamp, success=None, job_id=None, fallback=True):\n votes = session.query(CIVote)\n votes = votes.filter(CIVote.timestamp > timestamp)\n # Initially we want to get any tested repo, excluding consistent repos\n votes = votes.filter(CIVote.ci_name != 'consistent')\n if success is not None:\n votes = votes.filter(CIVote.ci_vote == int(success))\n if job_id is not None:\n votes = votes.filter(CIVote.ci_name == job_id)\n vote = votes.order_by(desc(CIVote.timestamp)).first()\n\n if vote is None and not fallback:\n # This is the sequential use case. We do not want to find any vote\n # for a different CI\n raise InvalidUsage('No vote found', status_code=404)\n\n if vote is None and job_id is not None:\n # Second chance: no votes found for job_id. Let's find any real CI\n # vote, other than 'consistent'\n votes = session.query(CIVote).filter(CIVote.timestamp >\n timestamp)\n if success is not None:\n votes = votes.filter(CIVote.ci_vote == success)\n votes.filter(CIVote.ci_name != 'consistent')\n vote = votes.order_by(desc(CIVote.timestamp)).first()\n\n if vote is None:\n # No votes found, let's try to find one for consistent\n votes = session.query(CIVote).filter(CIVote.timestamp >\n timestamp)\n if success is not None:\n votes = votes.filter(CIVote.ci_vote == success)\n votes.filter(CIVote.ci_name == 'consistent')\n vote = votes.order_by(desc(CIVote.timestamp)).first()\n\n if vote is None:\n # No Votes found at all\n raise InvalidUsage('No vote found', status_code=404)\n\n return vote\n\n\n@app.route('/api/repo_status', methods=['GET'])\ndef repo_status():\n # commit_hash: commit hash\n # distro_hash: distro hash\n # success(optional): only report successful/unsuccessful votes\n if request.headers['Content-Type'] != 'application/json':\n raise InvalidUsage('Unsupported Media Type, use JSON', status_code=415)\n\n commit_hash = request.json.get('commit_hash', None)\n distro_hash = request.json.get('distro_hash', None)\n success = request.json.get('success', None)\n if (commit_hash is None or distro_hash is None):\n raise InvalidUsage('Missing parameters', status_code=400)\n\n if success is not None:\n success = bool(strtobool(success))\n\n # Find the commit id for commit_hash/distro_hash\n session = getSession(app.config['DB_PATH'])\n commit = session.query(Commit).filter(\n Commit.status == 'SUCCESS',\n Commit.commit_hash == commit_hash,\n Commit.distro_hash == distro_hash).first()\n if commit is None:\n raise InvalidUsage('commit_hash+distro_hash combination not found',\n status_code=404)\n commit_id = commit.id\n\n # Now find every vote for this commit_hash/distro_hash combination\n votes = session.query(CIVote).filter(CIVote.commit_id == commit_id)\n if success is not None:\n votes = votes.filter(CIVote.ci_vote == int(success))\n\n # And format the output\n data = []\n for vote in votes:\n d = {'timestamp': vote.timestamp,\n 'commit_hash': commit_hash,\n 'distro_hash': distro_hash,\n 'job_id': vote.ci_name,\n 'success': bool(vote.ci_vote),\n 'in_progress': vote.ci_in_progress,\n 'url': vote.ci_url,\n 'notes': vote.notes}\n data.append(d)\n return jsonify(data)\n\n\n@app.route('/api/last_tested_repo', methods=['GET'])\ndef last_tested_repo_GET():\n # max_age: Maximum age in hours, used as base for the search\n # success(optional): find repos with a successful/unsuccessful vote\n # job_id(optional); name of the CI that sent the vote\n # sequential_mode(optional): if set to true, change the search algorithm\n # to only use previous_job_id as CI name to\n # search for. Defaults to false\n # previous_job_id(optional): CI name to search for, if sequential_mode is\n # True\n if request.headers['Content-Type'] != 'application/json':\n raise InvalidUsage('Unsupported Media Type, use JSON', status_code=415)\n\n max_age = request.json.get('max_age', None)\n job_id = request.json.get('job_id', None)\n success = request.json.get('success', None)\n sequential_mode = request.json.get('sequential_mode', None)\n previous_job_id = request.json.get('previous_job_id', None)\n\n if success is not None:\n success = bool(strtobool(success))\n\n if sequential_mode is not None:\n sequential_mode = bool(strtobool(sequential_mode))\n\n if sequential_mode and previous_job_id is None:\n raise InvalidUsage('Missing parameter previous_job_id',\n status_code=400)\n\n if max_age is None:\n raise InvalidUsage('Missing parameters', status_code=400)\n\n # Calculate timestamp as now - max_age\n if int(max_age) == 0:\n timestamp = 0\n else:\n oldest_time = datetime.now() - timedelta(hours=int(max_age))\n timestamp = time.mktime(oldest_time.timetuple())\n\n session = getSession(app.config['DB_PATH'])\n try:\n if sequential_mode:\n # CI pipeline case\n vote = getVote(session, timestamp, success, previous_job_id,\n fallback=False)\n else:\n # Normal case\n vote = getVote(session, timestamp, success, job_id)\n except Exception as e:\n raise e\n\n commit = session.query(Commit).filter(\n Commit.status == 'SUCCESS',\n Commit.id == vote.commit_id).first()\n\n result = {'commit_hash': commit.commit_hash,\n 'distro_hash': commit.distro_hash,\n 'timestamp': vote.timestamp,\n 'job_id': vote.ci_name,\n 'success': vote.ci_vote,\n 'in_progress': vote.ci_in_progress}\n return jsonify(result), 200\n\n\n@app.route('/api/last_tested_repo', methods=['POST'])\n@auth.login_required\ndef last_tested_repo_POST():\n # max_age: Maximum age in hours, used as base for the search\n # success(optional): find repos with a successful/unsuccessful vote\n # job_id(optional); name of the CI that sent the vote\n # reporting_job_id: name of the CI that will test this repo\n # sequential_mode(optional): if set to true, change the search algorithm\n # to only use previous_job_id as CI name to\n # search for. Defaults to false\n # previous_job_id(optional): CI name to search for, if sequential_mode is\n # True\n if request.headers['Content-Type'] != 'application/json':\n raise InvalidUsage('Unsupported Media Type, use JSON', status_code=415)\n\n max_age = request.json.get('max_age', None)\n my_job_id = request.json.get('reporting_job_id', None)\n job_id = request.json.get('job_id', None)\n success = request.json.get('success', None)\n sequential_mode = request.json.get('sequential_mode', None)\n previous_job_id = request.json.get('previous_job_id', None)\n\n if success is not None:\n success = bool(strtobool(success))\n\n if sequential_mode is not None:\n sequential_mode = bool(strtobool(sequential_mode))\n\n if sequential_mode and previous_job_id is None:\n raise InvalidUsage('Missing parameter previous_job_id',\n status_code=400)\n\n if (max_age is None or my_job_id is None):\n raise InvalidUsage('Missing parameters', status_code=400)\n\n # Calculate timestamp as now - max_age\n if int(max_age) == 0:\n timestamp = 0\n else:\n oldest_time = datetime.now() - timedelta(hours=int(max_age))\n timestamp = time.mktime(oldest_time.timetuple())\n\n session = getSession(app.config['DB_PATH'])\n\n try:\n if sequential_mode:\n # CI pipeline case\n vote = getVote(session, timestamp, success, previous_job_id,\n fallback=False)\n else:\n # Normal case\n vote = getVote(session, timestamp, success, job_id)\n except Exception as e:\n raise e\n\n newvote = CIVote(commit_id=vote.commit_id, ci_name=my_job_id,\n ci_url='', ci_vote=False, ci_in_progress=True,\n timestamp=int(time.time()), notes='')\n session.add(newvote)\n session.commit()\n\n commit = session.query(Commit).filter(\n Commit.status == 'SUCCESS',\n Commit.id == vote.commit_id).first()\n\n result = {'commit_hash': commit.commit_hash,\n 'distro_hash': commit.distro_hash,\n 'timestamp': newvote.timestamp,\n 'job_id': newvote.ci_name,\n 'success': newvote.ci_vote,\n 'in_progress': newvote.ci_in_progress}\n return jsonify(result), 201\n\n\n@app.route('/api/report_result', methods=['POST'])\n@auth.login_required\ndef report_result():\n # job_id: name of CI\n # commit_hash: commit hash\n # distro_hash: distro hash\n # url: URL where more information can be found\n # timestamp: CI execution timestamp\n # success: boolean\n # notes(optional): notes\n\n if request.headers['Content-Type'] != 'application/json':\n raise InvalidUsage('Unsupported Media Type, use JSON', status_code=415)\n\n try:\n commit_hash = request.json['commit_hash']\n distro_hash = request.json['distro_hash']\n timestamp = request.json['timestamp']\n job_id = request.json['job_id']\n success = request.json['success']\n url = request.json['url']\n except KeyError:\n raise InvalidUsage('Missing parameters', status_code=400)\n\n notes = request.json.get('notes', '')\n\n session = getSession(app.config['DB_PATH'])\n commit = session.query(Commit).filter(\n Commit.status == 'SUCCESS',\n Commit.commit_hash == commit_hash,\n Commit.distro_hash == distro_hash).first()\n if commit is None:\n raise InvalidUsage('commit_hash+distro_hash combination not found',\n status_code=404)\n\n commit_id = commit.id\n\n vote = CIVote(commit_id=commit_id, ci_name=job_id, ci_url=url,\n ci_vote=bool(strtobool(success)), ci_in_progress=False,\n timestamp=int(timestamp), notes=notes)\n session.add(vote)\n session.commit()\n\n result = {'commit_hash': commit_hash,\n 'distro_hash': distro_hash,\n 'timestamp': timestamp,\n 'job_id': job_id,\n 'success': bool(success),\n 'in_progress': False,\n 'url': url,\n 'notes': notes}\n return jsonify(result), 201\n\n\n@app.route('/api/promote', methods=['POST'])\n@auth.login_required\ndef promote():\n # commit_hash: commit hash\n # distro_hash: distro hash\n # promote_name: symlink name\n\n if request.headers['Content-Type'] != 'application/json':\n raise InvalidUsage('Unsupported Media Type, use JSON', status_code=415)\n\n try:\n commit_hash = request.json['commit_hash']\n distro_hash = request.json['distro_hash']\n promote_name = request.json['promote_name']\n except KeyError:\n raise InvalidUsage('Missing parameters', status_code=400)\n\n if (promote_name == 'consistent' or promote_name == 'current'):\n raise InvalidUsage('Invalid promote_name %s' % promote_name,\n status_code=403)\n\n session = getSession(app.config['DB_PATH'])\n commit = session.query(Commit).filter(\n Commit.status == 'SUCCESS',\n Commit.commit_hash == commit_hash,\n Commit.distro_hash == distro_hash).first()\n if commit is None:\n raise InvalidUsage('commit_hash+distro_hash combination not found',\n status_code=404)\n\n target_link = os.path.join(app.config['REPO_PATH'], promote_name)\n # We should create a relative symlink\n yumrepodir = commit.getshardedcommitdir()\n\n # Remove symlink if it exists, so we can create it again\n if os.path.lexists(os.path.abspath(target_link)):\n os.remove(target_link)\n try:\n os.symlink(yumrepodir, target_link)\n except Exception as e:\n raise InvalidUsage(\"Symlink creation failed with error: %s\" %\n e, status_code=500)\n\n result = {'commit_hash': commit_hash,\n 'distro_hash': distro_hash,\n 'promote_name': promote_name}\n return jsonify(result), 201\n\n\n@app.route('/api/remote/import', methods=['POST'])\n@auth.login_required\ndef remote_import():\n # repo_url: repository URL to import from\n if request.headers['Content-Type'] != 'application/json':\n raise InvalidUsage('Unsupported Media Type, use JSON', status_code=415)\n\n try:\n repo_url = request.json['repo_url']\n except KeyError:\n raise InvalidUsage('Missing parameters', status_code=400)\n\n try:\n import_commit(repo_url, app.config['CONFIG_FILE'],\n db_connection=app.config['DB_PATH'])\n except Exception as e:\n raise InvalidUsage(\"Remote import failed with error: %s\" %\n e, status_code=500)\n\n result = {'repo_url': repo_url}\n return jsonify(result), 201\n","sub_path":"dlrn/api/dlrn_api.py","file_name":"dlrn_api.py","file_ext":"py","file_size_in_byte":14449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"366441661","text":"#!/usr/bin/nev python\n#-*-coding:utf-8 -*-\n#Author :show530\n\n\n# from car import Car\n#\n# my_new_car = Car('audi','a6',2018)\n# print(my_new_car.get_descriptive_name())\n# my_new_car.odometer_reading = 23\n# my_new_car.read_odometer()\n\n\n\n# my_tesla = ElectricCar('tesla','model S',2018)\n# print(my_tesla.get_descriptive_name())\n# my_tesla.battery.discrib_battery()\n# my_tesla.battery.upgrade_battery()\n# my_tesla.battery.discrib_battery()\n#\n# my_new_car = Car('audi','a6',2018)\n# print(my_new_car.get_descriptive_name())\n# my_new_car.odometer_reading = 23\n# my_new_car.read_odometer()\n\n\n# import car\n# my_beetle = car.Car('volkswagen','bettle',2018)\n# print(my_beetle.get_descriptive_name())\n#\n# my_tesla = car.ElectricCar('tesla','roadster',2018)\n# print(my_tesla.get_descriptive_name())\n\n\nfrom random import randint\n# x = randint(1,6)\n# print(x)\nclass Die():\n def roll_die(self):\n count = 0\n while count <= 5:\n roll_number = randint(1, 6)\n print('The number is : '+ str(roll_number))\n count += 1\n\n\n\nmy_die = Die()\nmy_die.roll_die()\n\n\n","sub_path":"4.6_2.py","file_name":"4.6_2.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"118406468","text":"import json\n\ncenarios = {\n \"inicio\": {\n \"titulo\": \"Saguao do perigo\",\n \"descricao\": \"Voce esta no saguao de entrada do insper\",\n \"opcoes\": {\n \"andar professor\": \"Tomar o elevador para o andar do professor\",\n \"biblioteca\": \"Ir para a biblioteca\",\n \"quarto andar\": \"Ir para o quarto andar\"\n }\n },\n \"andar professor\": {\n \"titulo\": \"Andar do desespero\",\n \"descricao\": \"Voce chegou ao andar da sala do seu professor\",\n \"opcoes\": {\n \"inicio\": \"Tomar o elevador para o saguao de entrada\",\n \"professor\": \"Falar com o professor\",\n \"quarto andar\": \"Ir para o quarto andar\"\n }\n },\n \"professor\": {\n \"titulo\": \"O monstro do Python\",\n \"descricao\": \"Voce foi pedir para o professor adiar o EP. \"\n \"O professor revelou que é um monstro disfarçado \"\n \"e devorou sua alma.\",\n \"opcoes\": {}\n },\n \"biblioteca\": {\n \"titulo\": \"Caverna da tranquilidade\",\n \"descricao\": \"Voce esta na biblioteca\",\n \"opcoes\": {\n \"inicio\": \"Voltar para o saguao de entrada\"\n }\n }\n}\n\n\ncenarios[\"quarto andar\"] = {}\ncenarios[\"quarto andar\"][\"titulo\"] = \"Casa 2.0\"\ncenarios[\"quarto andar\"][\"descricao\"] = \"Você esta na sua nova casa\"\ncenarios[\"quarto andar\"][\"opcoes\"] = {}\ncenarios[\"quarto andar\"][\"opcoes\"][\"inicio\"] = \"Voltar para o saguao de entrada\"\ncenarios[\"quarto andar\"][\"opcoes\"][\"maquina\"] = \"Ir comprar algo na maquina\"\ncenarios[\"quarto andar\"][\"opcoes\"][\"andar professor\"] = \"Tomar o elevador para o andar do professor\"\n\ncenarios[\"maquina\"] = {}\ncenarios[\"maquina\"][\"titulo\"] = \"Maquina de Comida/Bebida\"\ncenarios[\"maquina\"][\"descricao\"] = \"Não sei por que você decidiu ir comprar algo, sendo q seu ep ta uma merda ainda, mas já que estamos aqui...\"\ncenarios[\"maquina\"][\"opcoes\"] = {}\ncenarios[\"maquina\"][\"opcoes\"][\"sair\"] = \"Você para de olhar a maquina\"\n\n\n\n\n\n\n\nstring_cenarios = json.dumps(cenarios, sort_keys=False, indent=4)\nwith open('cenarios.json', 'w') as arquivo:\n arquivo.write(string_cenarios)\n\n\nplayer = {}\nplayer[\"vida\"] = 90\nplayer[\"arma\"] = \"punhos\"\nplayer[\"velocidade\"] = 10\nplayer[\"Dinheiro\"] = 100\nplayer[\"inventario\"] = {}\nplayer[\"inventario\"][\"poção de vida\"] = [2]\nplayer[\"inventario\"][\"RedBull\"] = [2]\nplayer[\"inventario\"][\"Armas\"] = {}\nplayer[\"inventario\"][\"Armas\"][\"punho\"] = 10\nplayer[\"inventario\"][\"Armas\"][\"notebook\"] = 20\n\nstring_player = json.dumps(player, sort_keys=False, indent=4)\nwith open('player.json', 'w') as arquivo:\n arquivo.write(string_player)\n\n\nenemys = {}\n\nenemys[\"professores\"] = {}\nenemys[\"professores\"][\"Raul\"] = {}\nenemys[\"professores\"][\"Raul\"]['vida'] = 70\nenemys[\"professores\"][\"Raul\"]['dano'] = 15\nenemys[\"professores\"][\"Raul\"]['velocidade'] = 8\n\nenemys['alunos'] = {}\nenemys['alunos'][\"Duarte\"] = {}\nenemys[\"alunos\"][\"Duarte\"]['vida'] = 40\nenemys[\"alunos\"][\"Duarte\"]['dano'] = 10\nenemys[\"alunos\"][\"Duarte\"]['velocidade'] = 20\n\nstring_enemys = json.dumps(enemys, sort_keys=False, indent=4)\nwith open('enemys.json', 'w') as arquivo:\n arquivo.write(string_enemys)\n\n\ntreasures_items = [\"poção de vida\", \"RedBull\"]\n\nstring_treasures_items = json.dumps(treasures_items, sort_keys=False, indent=4)\nwith open('treasures_items.json', 'w') as arquivo:\n arquivo.write(string_treasures_items)\n\ntreasures_weapons = {}\ntreasures_weapons[\"espada de papelão\"] = 17\ntreasures_weapons[\"estilete do FabLab\"] = 30\n\nstring_treasures_weapons = json.dumps(treasures_weapons, sort_keys=False, indent=4)\nwith open('treasures_weapons.json', 'w') as arquivo:\n arquivo.write(string_treasures_weapons)\n\n\nstore = {}\nstore[\"RedBull\"] = {}\nstore[\"RedBull\"][\"preco\"] = 10\nstore[\"RedBull\"][\"quantidade\"] = 5\n\nstore[\"poção de vida\"] = {}\nstore[\"poção de vida\"][\"preco\"] = 20\nstore[\"poção de vida\"][\"quantidade\"] = 5\n\nstore[\"??????\"] = {}\nstore[\"??????\"][\"preco\"] = 500\nstore[\"??????\"][\"quantidade\"] = 5\nstore[\"??????\"][\"dano\"] = 120\n\nstring_store = json.dumps(store, sort_keys=False, indent=4)\nwith open('store.json', 'w') as arquivo:\n arquivo.write(string_store)\n","sub_path":"create_json.py","file_name":"create_json.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"170524220","text":"\"\"\"\n代价函数,或称为优化目标(optimization objective),失真代价函数(distortion cost function)。\n\"\"\"\nimport numpy as np\n\n\ndef mse(X, Y):\n \"\"\"\n :param X: 既可以是数值也可以是列表\n :param Y: 既可以是数值也可以是列表\n :return:\n \"\"\"\n square = np.power(X - Y, 2)\n shape = X.shape\n m = shape[0]\n # mse 公式:1/m * sum((a - b)^2)\n if len(shape) == 2 and shape[1] != 1:\n return np.sum(square, axis=1) / m\n elif (len(shape) == 1) or (len(shape) == 2 and shape[1] == 1):\n return np.sum(square) / m\n\n\ndef binary_crossentropy(Y, H):\n m = len(Y)\n cost = -np.sum(Y * np.log(H) + (1 - Y) * np.log(1 - H)) / m\n return cost\n\n\ncost_fun = {\n 'binary_crossentropy': binary_crossentropy,\n}","sub_path":"cost_function.py","file_name":"cost_function.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"116657998","text":"from bpy.types import Panel\nfrom . import (\n\tvar,\n\tlocalization,\n)\nfrom .modules import report\nfrom .modules.icons import preview_collections\n\n\n\ndef icon_tria(prop):\n\tif prop:\n\t\treturn 'TRIA_DOWN'\n\telse:\n\t\treturn 'TRIA_RIGHT'\n\n\n\nclass ImportPanel(Panel):\n\n\tbl_label = \"Gems\"\n\tbl_idname = \"JEWELCRAFT_IMPORT\"\n\tbl_space_type = \"VIEW_3D\"\n\tbl_region_type = \"TOOLS\"\n\tbl_category = \"JewelCraft\"\n\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn context.mode == 'OBJECT'\n\n\tdef draw(self, context):\n\t\tlayout = self.layout\n\t\tprefs = context.user_preferences.addons[var.addon_id].preferences\n\t\tprops = context.scene.jewelcraft\n\t\tl = localization.locale[prefs.lang]\n\t\ticons = preview_collections['icons']\n\n\t\tcol = layout.column(align=True)\n\n\t\tcol.template_icon_view(props, \"import_gem_cut\", show_labels=True)\n\n\t\tcol.separator()\n\t\trow = col.row(align=True)\n\t\trow.prop(props, \"import_gem_type\", text=\"\")\n\t\trow.operator(\"jewelcraft.search_type\", text=\"\", icon=\"VIEWZOOM\")\n\t\tcol.prop(props, \"import_gem_size\", text=l['size'])\n\t\tcol.operator(\"jewelcraft.import_gem\", text=l['make_gem'])\n\n\t\tcol.separator()\n\t\trow = col.row(align=True)\n\t\trow.label(l['gem'])\n\t\trow.operator(\"jewelcraft.import_type\", text=\"\", icon=\"COLOR\")\n\t\trow.operator(\"jewelcraft.import_cut\", text=\"\", icon_value=icons['TOOL-CUT'].icon_id)\n\n\t\tcol.separator()\n\t\trow = col.row(align=True)\n\t\trow.label(l['prongs'])\n\t\trow.operator(\"jewelcraft.import_single_prong\", text=\"\", icon_value=icons['TOOL-SINGLE_PRONG'].icon_id)\n\t\trow.operator(\"jewelcraft.import_prongs\", text=\"\", icon=\"SURFACE_NCIRCLE\")\n\t\trow = col.row(align=True)\n\t\trow.label(l['cutter'])\n\t\trow.operator(\"jewelcraft.import_cutter_seat\", text=\"\", icon_value=icons['TOOL-CUTTER_SEAT'].icon_id)\n\t\trow.operator(\"jewelcraft.import_cutter\", text=\"\", icon_value=icons['TOOL-CUTTER'].icon_id)\n\t\trow = col.row(align=True)\n\t\trow.label(l['imitation'])\n\t\trow.operator(\"jewelcraft.import_imitation_3_prong\", text=\"\", icon_value=icons['TOOL-IMITATION_3_PRONG'].icon_id)\n\n\t\tcol.separator()\n\t\tcol.operator(\"jewelcraft.make_dupliface\", text=l['make_dupliface'])\n\t\tcol.operator(\"jewelcraft.select_dupli\", text=l['select_dupli'])\n\n\n\nclass WeightingPanel(Panel):\n\n\tbl_label = \"Weighting\"\n\tbl_idname = \"JEWELCRAFT_WEIGHTING\"\n\tbl_space_type = \"VIEW_3D\"\n\tbl_region_type = \"TOOLS\"\n\tbl_category = \"JewelCraft\"\n\tbl_options = {'DEFAULT_CLOSED'}\n\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn context.mode == 'OBJECT'\n\n\tdef draw(self, context):\n\t\tlayout = self.layout\n\t\tprefs = context.user_preferences.addons[var.addon_id].preferences\n\t\tprops = context.scene.jewelcraft\n\t\tl = localization.locale[prefs.lang]\n\t\tm = props.weighting_metals\n\t\tweight = report.data\n\n\t\tcol = layout.column(align=True)\n\n\t\tcol.prop(props, \"weighting_metals\", text=\"\")\n\n\t\tif m == 'CUSTOM':\n\t\t\tcol.separator()\n\t\t\tcol.prop(props, \"weighting_custom\", text=l['g/cm'])\n\n\t\tcol.separator()\n\t\tcol.operator(\"jewelcraft.weight_display\", text=l['wt_calc'])\n\n\t\tif weight:\n\t\t\tcol.separator()\n\t\t\tbox = col.box()\n\t\t\tbox.label(weight)\n\n\n\nclass ExportPanel(Panel):\n\t\n\tbl_label = \"Export\"\n\tbl_idname = \"JEWELCRAFT_EXPORT\"\n\tbl_space_type = \"VIEW_3D\"\n\tbl_region_type = \"TOOLS\"\n\tbl_category = \"JewelCraft\"\n\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn context.mode == 'OBJECT'\n\n\tdef draw(self, context):\n\t\tlayout = self.layout\n\t\tsce = context.scene\n\t\tprefs = context.user_preferences.addons[var.addon_id].preferences\n\t\tprops = sce.jewelcraft\n\t\tl = localization.locale[prefs.lang]\n\n\n\t\tbox = layout.box()\n\n\n\t\trow = box.row(align=True)\n\t\trow.prop(props, \"export_options\", icon=icon_tria(props.export_options), icon_only=True)\n\t\trow.label(l['export_options'])\n\t\tif props.export_options:\n\t\t\tcol = box.column()\n\t\t\trow = col.row(align=True)\n\t\t\trow.prop_search(props, \"export_size\", sce, \"objects\", text=l['size'])\n\t\t\trow.operator(\"jewelcraft.export_pick_size\", text=\"\", icon=\"EYEDROPPER\")\n\t\t\trow = col.row(align=True)\n\t\t\trow.prop_search(props, \"export_shank\", sce, \"objects\", text=l['shank'])\n\t\t\trow.operator(\"jewelcraft.export_pick_shank\", text=\"\", icon=\"EYEDROPPER\")\n\t\t\trow = col.row(align=True)\n\t\t\trow.prop_search(props, \"export_dim\", sce, \"objects\", text=l['dim'])\n\t\t\trow.operator(\"jewelcraft.export_pick_dim\", text=\"\", icon=\"EYEDROPPER\")\n\t\t\trow = col.row(align=True)\n\t\t\trow.prop_search(props, \"export_weight\", sce, \"objects\", text=l['weight'])\n\t\t\trow.operator(\"jewelcraft.export_pick_weight\", text=\"\", icon=\"EYEDROPPER\")\n\n\n\t\t\trow = box.row(align=True)\n\t\t\trow.prop(props, \"export_metals\", icon=icon_tria(props.export_metals), icon_only=True)\n\t\t\trow.label(l['metals'])\n\t\t\tif props.export_metals:\n\t\t\t\tcol = box.column(align=True)\n\t\t\t\tcol.prop(props, \"export_m_24g\", text=l['24g'])\n\t\t\t\tcol.prop(props, \"export_m_22g\", text=l['22g'])\n\t\t\t\tcol.prop(props, \"export_m_18wg\", text=l['18wg'])\n\t\t\t\tcol.prop(props, \"export_m_18yg\", text=l['18yg'])\n\t\t\t\tcol.prop(props, \"export_m_14wg\", text=l['14wg'])\n\t\t\t\tcol.prop(props, \"export_m_14yg\", text=l['14yg'])\n\t\t\t\tcol.prop(props, \"export_m_ster\", text=l['ster'])\n\t\t\t\tcol.prop(props, \"export_m_pd\", text=l['pd'])\n\t\t\t\tcol.prop(props, \"export_m_pl\", text=l['pl'])\n\t\t\t\tcol.prop(props, \"export_m_custom\", text=l['custom'])\n\n\t\t\t\tcol = col.column(align=True)\n\t\t\t\tcol.enabled = props.export_m_custom\n\t\t\t\trow = col.row()\n\t\t\t\trow.label(l['custom_name'])\n\t\t\t\trow.label(l['g/cm']+\":\")\n\t\t\t\trow = col.row()\n\t\t\t\trow.prop(props, \"export_m_custom_name\", text=\"\")\n\t\t\t\trow.prop(props, \"export_m_custom_dens\", text=\"\")\n\n\n\t\t\trow = box.row(align=True)\n\t\t\trow.label(l['lang']+\":\")\n\t\t\trow.prop(props, \"export_lang\", text=\"\")\n\n\n\t\tcol = layout.column(align=True)\n\t\tcol.operator(\"jewelcraft.export_stats\", text=l['export_stats'])\n","sub_path":"scripts/addons_extern/blender-addon-jewelcraft-master/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":5594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"514931990","text":"'''\nzstack security group and vm mediator class\n\nIt will record all sg and vm relationship and do the real check.\n\n\n@author: Youyk\n'''\n\nimport zstackwoodpecker.test_lib as test_lib\nimport zstackwoodpecker.test_util as test_util\nimport zstackwoodpecker.header.vm as vm_header\nimport zstackwoodpecker.header.security_group as sg_header\n\nTCP_INGRESS = 'tcp_ingress'\nTCP_EGRESS = 'tcp_egress'\nUDP_INGRESS = 'udp_ingress'\nUDP_EGRESS = 'udp_egress'\nICMP_INGRESS = 'icmp_ingress'\nICMP_EGRESS = 'icmp_egress'\n\n\nclass ZstackTestSgVm(sg_header.TestSecurityGroupVm):\n def __init__(self):\n #{test_sg_obj:[nic_obj]}\n self.sg_nic_dict = {}\n #{nic_uuid:[test_sg_obj]}\n self.nic_sg_dict = {}\n #each l3 will have one test vm. {l3_uuid: test_stub_vm_obj}\n self.stub_vm_dict = {}\n #{test_vm_obj: [nic_uuid]}\n self.vm_nic_dict = {}\n #{nic_uuid:{'tcp_ingress':{allowedCidr1:[rule1, rule2], allowedCidr2:[]}, 'tcp_egress':{}, } nic_uuid2:{}}\n self.nic_rule_dict = {}\n #[test_vm_obj]\n self.detached_vm_list = []\n\n def __repr__(self):\n return self.__class__.__name__\n\n def get_all_nics(self):\n return self.nic_sg_dict.keys()\n\n def get_detached_vm(self):\n return self.detached_vm_list\n\n def get_all_sgs(self):\n return self.sg_nic_dict.keys()\n\n def get_nic_list_by_sg(self, test_sg):\n if self.sg_nic_dict.has_key(test_sg):\n return self.sg_nic_dict[test_sg]\n\n def get_sg_list_by_nic(self, nic_uuid):\n if self.nic_sg_dict.has_key(nic_uuid):\n return self.nic_sg_dict[nic_uuid]\n\n def get_vm_by_nic(self, nic_uuid):\n for key, values in self.vm_nic_dict.items():\n if nic_uuid in values:\n return key\n\n def get_nic_list_by_vm(self, vm):\n if self.vm_nic_dict.has_key(vm):\n return self.vm_nic_dict[vm]\n\n def _add_sg_nic_dict(self, sg, target_nic):\n if self.sg_nic_dict.has_key(sg):\n nic_uuids = []\n for nic in self.get_nic_list_by_sg(sg):\n nic_uuids.append(nic.uuid)\n if not target_nic.uuid in nic_uuids:\n self.sg_nic_dict[sg].append(target_nic)\n else:\n self.sg_nic_dict[sg] = [target_nic]\n\n def _add_nic_sg_dict(self, nic_uuid, sg):\n if self.nic_sg_dict.has_key(nic_uuid):\n if not sg in self.get_sg_list_by_nic(nic_uuid):\n self.nic_sg_dict[nic_uuid].append(sg)\n else:\n self.nic_sg_dict[nic_uuid] = [sg]\n\n #when calling remove nic function, the nic might be not existed in db. So can't get full nic obj from nic_uuid\n def _remove_nic_from_sg_nic_dict(self, sg, nic_uuid):\n if self.sg_nic_dict.has_key(sg):\n nic_list = self.get_nic_list_by_sg(sg)\n for nic in nic_list:\n if nic.uuid == nic_uuid:\n self.sg_nic_dict[sg].remove(nic)\n\n #detach nic from sg.\n def _detach(self, test_sg, nic_uuid):\n self._remove_nic_from_sg_nic_dict(test_sg, nic_uuid)\n\n if self.nic_sg_dict.has_key(nic_uuid):\n if test_sg in self.get_sg_list_by_nic(nic_uuid):\n self.nic_sg_dict[nic_uuid].remove(test_sg)\n if not self.get_sg_list_by_nic(nic_uuid):\n self.nic_sg_dict.pop(nic_uuid)\n self._rm_nic_vm_map(nic_uuid)\n\n #detach sg from l3. It means all nic on the l3 will be detached from sg.\n def _detach_l3(self, test_sg, l3_uuid):\n for nic_uuid in test_sg.get_attached_nics_by_l3(l3_uuid):\n self._detach(test_sg, nic_uuid)\n\n #delete sg.\n def _remove_sg(self, test_sg):\n if self.sg_nic_dict.has_key(test_sg):\n nic_list = self.sg_nic_dict.pop(test_sg)\n for nic in nic_list:\n self.nic_sg_dict[nic.uuid].remove(test_sg)\n if not self.nic_sg_dict[nic.uuid]:\n self.nic_sg_dict.pop(nic.uuid)\n self._rm_nic_vm_map(nic.uuid)\n\n #delete nic, e.g. VM destroy\n def _remove_nic_from_sg(self, nic_uuid):\n if self.nic_sg_dict.has_key(nic_uuid):\n sg_list = self.nic_sg_dict.pop(nic_uuid)\n for sg in sg_list:\n self._remove_nic_from_sg_nic_dict(sg, nic_uuid)\n\n #add vm and nic mapping, when VM's NIC is attached to SG.\n def _map_nic_vm(self, nic_uuid, test_vm):\n if not self.vm_nic_dict.has_key(test_vm):\n self.vm_nic_dict[test_vm] = [nic_uuid]\n else:\n if not nic_uuid in self.vm_nic_dict[test_vm]:\n self.vm_nic_dict[test_vm].append(nic_uuid)\n\n if test_vm in self.detached_vm_list:\n self.detached_vm_list.remove(test_vm)\n\n #Remove VM and NIC mapping, when detach VM's nic or VM's NICs lost all attached SG. \n def _rm_nic_vm_map(self, nic_uuid):\n test_vm = self.get_vm_by_nic(nic_uuid)\n if not test_vm:\n return\n self.vm_nic_dict[test_vm].remove(nic_uuid)\n\n #no other attached NICs for this VM.\n if not self.vm_nic_dict[test_vm]:\n #still keep test_vm object in dict, until test_vm is destroyed.\n #self.vm_nic_dict.pop(test_vm)\n self.detached_vm_list.append(test_vm)\n\n def attach(self, test_sg, nic_vm_list):\n '''\n nic_vm_list = [(nic_uuid, test_vm), (nic_uuid2, test_vm2)] record the test_vm's nic_uuid for attaching to SG.\n test_vm is ZstackTestVm()\n\n SG test case should call this API to attach nic to SG. \n '''\n nic_list = []\n for nic_vm in nic_vm_list:\n nic_uuid = nic_vm[0]\n test_vm = nic_vm[1]\n nic_list.append(nic_uuid)\n nic = test_lib.lib_get_nic_by_uuid(nic_uuid)\n self._add_nic_sg_dict(nic_uuid, test_sg)\n self._add_sg_nic_dict(test_sg, nic)\n self._map_nic_vm(nic_uuid, test_vm)\n\n test_sg.attach(nic_list)\n\n #SG test case should call this API to detach nic from SG. \n def detach(self, test_sg, nic_uuid):\n self._detach(test_sg, nic_uuid)\n test_sg.detach(nic_uuid)\n\n #SG detach sg from l3.\n def detach_l3(self, test_sg, l3_uuid):\n self._detach_l3(test_sg, l3_uuid)\n test_sg.detach_l3(l3_uuid)\n\n def create_sg(self, sg_creation_option):\n import zstackwoodpecker.zstack_test.zstack_test_security_group as zstack_sg_header\n sg = zstack_sg_header.ZstackTestSecurityGroup()\n sg.set_creation_option(sg_creation_option)\n sg.create()\n self.sg_nic_dict[sg] = []\n return sg\n \n #SG test case should call this API to delete SG. \n def delete_sg(self, test_sg):\n self._remove_sg(test_sg)\n test_sg.delete()\n\n def delete_vm(self, test_vm):\n #test_vm was not attached to any SG.\n if test_vm in self.detached_vm_list:\n self.detached_vm_list.remove(test_vm)\n return\n\n #test_vm has some attached SG.\n for nic_uuid in self.vm_nic_dict[test_vm]:\n self._remove_nic_from_sg(nic_uuid)\n\n self.vm_nic_dict.pop(test_vm)\n\n def add_stub_vm(self, l3_uuid, stub_vm):\n self.stub_vm_dict[l3_uuid] = stub_vm\n\n def delete_stub_vm(self, l3_uuid):\n if self.stub_vm_dict.has_key(l3_uuid):\n del self.stub_vm_dict[l3_uuid]\n\n def get_stub_vm(self, l3_uuid):\n if self.stub_vm_dict.has_key(l3_uuid):\n return self.stub_vm_dict[l3_uuid]\n\n def get_all_stub_vm(self):\n stub_vm_list = []\n for value in self.stub_vm_dict.values():\n if not value in stub_vm_list:\n stub_vm_list.append(value)\n\n return stub_vm_list\n\n def _check_vm_destroyed(self):\n for vm in self.vm_nic_dict.keys():\n if vm.state == vm_header.DESTROYED \\\n or vm.state == vm_header.EXPUNGED:\n nic_list = self.get_nic_list_by_vm(vm)\n for nic in nic_list:\n sg_list = self.get_sg_list_by_nic(nic)\n for sg in sg_list:\n sg.delete_vm(vm)\n\n self.delete_vm(vm)\n\n def _check_sg_destroyed(self):\n for sg in self.sg_nic_dict.keys():\n if sg.state == sg_header.DELETED:\n self._remove_sg(sg)\n test_util.test_warn(\"Catch undeleted SG. It might be because SG deletion is not called by delete_sg() API.\")\n\n def get_nic_tcp_ingress_all_addr(self, nic_uuid):\n if self.nic_rule_dict.has_key(nic_uuid):\n return self.nic_rule_dict[nic_uuid][TCP_INGRESS].keys()\n else:\n return []\n\n def get_nic_tcp_ingress_rule_by_addr(self, nic_uuid, allowedCidr):\n if self.nic_rule_dict.has_key(nic_uuid) and self.nic_rule_dict[nic_uuid][TCP_INGRESS].has_key(allowedCidr):\n return self.nic_rule_dict[nic_uuid][TCP_INGRESS][allowedCidr]\n else:\n return []\n\n def get_nic_tcp_ingress_rules(self, nic_uuid):\n tcp_ingress_rules = []\n if self.nic_rule_dict.has_key(nic_uuid):\n for rules in self.nic_rule_dict[nic_uuid][TCP_INGRESS].values():\n tcp_ingress_rules.extend(rules)\n return tcp_ingress_rules\n\n def get_nic_tcp_egress_all_addr(self, nic_uuid):\n if self.nic_rule_dict.has_key(nic_uuid):\n return self.nic_rule_dict[nic_uuid][TCP_EGRESS].keys()\n else:\n return []\n\n def get_nic_tcp_egress_rule_by_addr(self, nic_uuid, allowedCidr):\n if self.nic_rule_dict.has_key(nic_uuid) and self.nic_rule_dict[nic_uuid][TCP_EGRESS].has_key(allowedCidr):\n return self.nic_rule_dict[nic_uuid][TCP_EGRESS][allowedCidr]\n else:\n return []\n\n def get_nic_tcp_egress_rules(self, nic_uuid):\n tcp_egress_rules = []\n if self.nic_rule_dict.has_key(nic_uuid):\n for rules in self.nic_rule_dict[nic_uuid][TCP_EGRESS].values():\n tcp_egress_rules.extend(rules)\n return tcp_egress_rules\n\n def get_nic_udp_ingress_all_addr(self, nic_uuid):\n if self.nic_rule_dict.has_key(nic_uuid):\n return self.nic_rule_dict[nic_uuid][UDP_INGRESS].keys()\n else:\n return []\n\n def get_nic_udp_ingress_rule_by_addr(self, nic_uuid, allowedCidr):\n if self.nic_rule_dict.has_key(nic_uuid) and self.nic_rule_dict[nic_uuid][UDP_INGRESS].has_key(allowedCidr):\n return self.nic_rule_dict[nic_uuid][UDP_INGRESS][allowedCidr]\n else:\n return []\n\n def get_nic_udp_ingress_rules(self, nic_uuid):\n udp_ingress_rules = []\n if self.nic_rule_dict.has_key(nic_uuid):\n for rules in self.nic_rule_dict[nic_uuid][UDP_INGRESS].values():\n udp_ingress_rules.extend(rules)\n return udp_ingress_rules\n\n def get_nic_udp_egress_all_addr(self, nic_uuid):\n if self.nic_rule_dict.has_key(nic_uuid):\n return self.nic_rule_dict[nic_uuid][UDP_EGRESS].keys()\n else:\n return []\n\n def get_nic_udp_egress_rule_by_addr(self, nic_uuid, allowedCidr):\n if self.nic_rule_dict.has_key(nic_uuid) and self.nic_rule_dict[nic_uuid][UDP_EGRESS].has_key(allowedCidr):\n return self.nic_rule_dict[nic_uuid][UDP_EGRESS][allowedCidr]\n else:\n return []\n\n def get_nic_udp_egress_rules(self, nic_uuid):\n udp_egress_rules = []\n if self.nic_rule_dict.has_key(nic_uuid):\n for rules in self.nic_rule_dict[nic_uuid][UDP_EGRESS].values():\n udp_egress_rules.extend(rules)\n return udp_egress_rules\n\n def get_nic_icmp_ingress_all_addr(self, nic_uuid):\n if self.nic_rule_dict.has_key(nic_uuid):\n return self.nic_rule_dict[nic_uuid][ICMP_INGRESS].keys()\n else:\n return []\n\n def get_nic_icmp_ingress_rule_by_addr(self, nic_uuid, allowedCidr):\n if self.nic_rule_dict.has_key(nic_uuid) and self.nic_rule_dict[nic_uuid][ICMP_INGRESS].has_key(allowedCidr):\n return self.nic_rule_dict[nic_uuid][ICMP_INGRESS][allowedCidr]\n else:\n return []\n\n def get_nic_icmp_ingress_rules(self, nic_uuid):\n icmp_ingress_rules = []\n if self.nic_rule_dict.has_key(nic_uuid):\n for rules in self.nic_rule_dict[nic_uuid][ICMP_INGRESS].values():\n icmp_ingress_rules.extend(rules)\n return icmp_ingress_rules\n\n def get_nic_icmp_egress_all_addr(self, nic_uuid):\n if self.nic_rule_dict.has_key(nic_uuid):\n return self.nic_rule_dict[nic_uuid][ICMP_EGRESS].keys()\n else:\n return []\n\n def get_nic_icmp_egress_rule_by_addr(self, nic_uuid, allowedCidr):\n if self.nic_rule_dict.has_key(nic_uuid) and self.nic_rule_dict[nic_uuid][ICMP_EGRESS].has_key(allowedCidr):\n return self.nic_rule_dict[nic_uuid][ICMP_EGRESS][allowedCidr]\n else:\n return []\n\n def get_nic_icmp_egress_rules(self, nic_uuid):\n icmp_egress_rules = []\n if self.nic_rule_dict.has_key(nic_uuid):\n for rules in self.nic_rule_dict[nic_uuid][ICMP_EGRESS].values():\n icmp_egress_rules.extend(rules)\n return icmp_egress_rules\n\n def _consolidate_nic_rules(self):\n for nic, sg_list in self.nic_sg_dict.items():\n self.nic_rule_dict[nic] = {TCP_INGRESS:{}, TCP_EGRESS:{}, UDP_INGRESS:{}, UDP_EGRESS:{}, ICMP_INGRESS:{}, ICMP_EGRESS:{}}\n for sg in sg_list:\n for allowedCidr in sg.get_tcp_ingress_all_addr():\n if not self.nic_rule_dict[nic][TCP_INGRESS].has_key(allowedCidr):\n self.nic_rule_dict[nic][TCP_INGRESS][allowedCidr] = list(sg.get_tcp_ingress_rule_by_addr(allowedCidr))\n else:\n self.nic_rule_dict[nic][TCP_INGRESS][allowedCidr].extend(sg.get_tcp_ingress_rule_by_addr(allowedCidr))\n for allowedCidr in sg.get_tcp_egress_all_addr():\n if not self.nic_rule_dict[nic][TCP_EGRESS].has_key(allowedCidr):\n self.nic_rule_dict[nic][TCP_EGRESS][allowedCidr] = list(sg.get_tcp_egress_rule_by_addr(allowedCidr))\n else:\n self.nic_rule_dict[nic][TCP_EGRESS][allowedCidr].extend(sg.get_tcp_egress_rule_by_addr(allowedCidr))\n\n for allowedCidr in sg.get_udp_ingress_all_addr():\n if not self.nic_rule_dict[nic][UDP_INGRESS].has_key(allowedCidr):\n self.nic_rule_dict[nic][UDP_INGRESS][allowedCidr] = list(sg.get_udp_ingress_rule_by_addr(allowedCidr))\n else:\n self.nic_rule_dict[nic][UDP_INGRESS][allowedCidr].extend(sg.get_udp_ingress_rule_by_addr(allowedCidr))\n for allowedCidr in sg.get_udp_egress_all_addr():\n if not self.nic_rule_dict[nic][UDP_EGRESS].has_key(allowedCidr):\n self.nic_rule_dict[nic][UDP_EGRESS][allowedCidr] = list(sg.get_udp_egress_rule_by_addr(allowedCidr))\n else:\n self.nic_rule_dict[nic][UDP_EGRESS][allowedCidr].extend(sg.get_udp_egress_rule_by_addr(allowedCidr))\n\n for allowedCidr in sg.get_icmp_ingress_all_addr():\n if not self.nic_rule_dict[nic][ICMP_INGRESS].has_key(allowedCidr):\n self.nic_rule_dict[nic][ICMP_INGRESS][allowedCidr] = list(sg.get_icmp_ingress_rule_by_addr(allowedCidr))\n else:\n self.nic_rule_dict[nic][ICMP_INGRESS][allowedCidr].extend(sg.get_icmp_ingress_rule_by_addr(allowedCidr))\n for allowedCidr in sg.get_icmp_egress_all_addr():\n if not self.nic_rule_dict[nic][ICMP_EGRESS].has_key(allowedCidr):\n self.nic_rule_dict[nic][ICMP_EGRESS][allowedCidr] = list(sg.get_icmp_egress_rule_by_addr(allowedCidr))\n else:\n self.nic_rule_dict[nic][ICMP_EGRESS][allowedCidr].extend(sg.get_icmp_egress_rule_by_addr(allowedCidr))\n\n def update(self):\n self._check_vm_destroyed()\n self._check_sg_destroyed()\n self._consolidate_nic_rules()\n\n def check(self):\n import zstackwoodpecker.zstack_test.checker_factory as checker_factory\n self.update()\n checker = checker_factory.CheckerFactory().create_checker(self)\n checker.check()\n super(ZstackTestSgVm , self).check()\n","sub_path":"zstackwoodpecker/zstackwoodpecker/zstack_test/zstack_test_sg_vm.py","file_name":"zstack_test_sg_vm.py","file_ext":"py","file_size_in_byte":16411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"26397561","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*\n\n# import the library\nfrom appJar import gui\nimport datetime\n\n# create a GUI variable called app\napp = gui()\n\n# add & configure widgets - widgets get a name, to help referencing them later\napp.addLabel(\"title\", \"Rate how well you feel in score from 1-10\")\napp.addLabelEntry(\"Score\")\n\n# add fuction to button\ndef press(button):\n if button == \"Cancel\":\n app.stop()\n else:\n today = datetime.datetime.now()\n fullscore = today.strftime(\"[%d/%m/%Y %H:%M:%S] \") + score + '\\n'\n score = app.getEntry(\"Score\")\n f=open('score.txt','a+')\n f.write(fullscore)\n\n# link the buttons to the function called press\napp.addButtons([\"Submit\", \"Cancel\"], press)\n\n# start the GUI\napp.go()\n","sub_path":"Diary/score_gui.py","file_name":"score_gui.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"541775060","text":"from __future__ import absolute_import\nimport os\nimport sys\nimport logging\n\n__version__ = '0.0.1'\n\n\nif 'PROJECT_ROOT' not in os.environ:\n print(\"Could not find environmental variable 'PROJECT_ROOT'\")\n print(\"You need to run 'source bin/env.sh' first!\")\n sys.exit(-1)\nPROJECT_ROOT = os.environ['PROJECT_ROOT']\n\n# logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n# add loggers\nch = logging.StreamHandler()\nif not os.environ.get(\"DEBUG\", False):\n ch.setLevel(logging.ERROR)\nelse:\n ch.setLevel(logging.DEBUG)\n# log format\nformatter = logging.Formatter(\n '%(asctime)s [%(name)s] %(levelname)s: %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n","sub_path":"cmsl1t/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"202398728","text":"'''\nECE276A WI21 PR1: Color Classification and Recycling Bin Detection\n'''\n\n\nfrom __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt; plt.ion()\nimport os, cv2\nfrom scipy.stats import multivariate_normal\n\n#from generate_rgb_data import read_pixels\n#from pixel_classifier import PixelClassifier\n\nif __name__ == '__main__':\n # test the classifier\n \n folder = 'data_capture/blue_bin'\n \n n=0\n x_r=[]\n x_g=[]\n x_b=[]\n X=[]\n for filename in os.listdir(folder):\n if filename.split('.')[-1]!='npy':\n continue\n\n tmp=np.load(os.path.join(folder,filename),allow_pickle=True)\n n+=len(tmp)\n\n #n+=len(tmp)\n for i in tmp:\n X.append(i)\n x_r.append(i[0])\n x_g.append(i[1])\n x_b.append(i[2])\n print(tmp)\n #gaussian = SimpleGaussian(X)\n #print(gaussian.predict(X))\n\n mean=np.mean(X, axis=0)\n cov=np.cov(np.transpose(X))\n #print(multivariate_normal.pdf(X, mean, cov))\n #R_mean=(sum(X)/len(X))[0]\n #G_mean=(sum(X)/len(X))[1]\n #B_mean=(sum(X)/len(X))[2]\n\n\n\n #print(mean)\n #print(cov)\n\n\n '''\n sigma_square_R = 0.0\n sigma_square_G = 0.0\n sigma_square_B = 0.0\n for i in X:\n sigma_square_R += (i[0] - R_mean) ** 2\n sigma_square_G += (i[1] - G_mean) ** 2\n sigma_square_B += (i[2] - B_mean) ** 2\n\n sigma_square_R /= (len(X) - 1)\n sigma_square_G /= (len(X) - 1)\n sigma_square_B /= (len(X) - 1)\n\n\n print(\"Mean: \")\n print(R_mean)\n print(G_mean)\n print(B_mean)\n\n\n print(\"sigma: \")\n print(sigma_square_R)\n print(sigma_square_G)\n print(sigma_square_B)\n\n '''\n #print(len(X))\n","sub_path":"bin_detection/test_data_capture.py","file_name":"test_data_capture.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"410785355","text":"import discord\nfrom config import settings #импортируем из config.py настройки\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\n\nbot = commands.Bot(command_prefix='!') #устанавливаем префикс\n\n\n@bot.event #когда бот запустился\nasync def on_ready(): \n print('Бот включен') #выводим это в КОНСОЛЬ\n\n@bot.command() #Выводит картинку при команде !test\nasync def test(ctx):\n await ctx.send(\"https://i.imgur.com/p3wZM8L.jpg\")\n\n#Embed(Команда - !emb)\n@bot.command()\nasync def emb(ctx):\n em = discord.Embed(title='**Название**', description='Описание', color=ctx.author.color)\n \n em.add_field(name='Опция(1)', value='маленькая опция') #(add_field можно дублировать для создания большего кол-во строк)\n em.set_thumbnail(url = 'https://i.imgur.com/pJv1Wyw.jpg') #Маленькая картинка справа от текста\n em.set_image(url = 'https://i.imgur.com/pJv1Wyw.jpg') #Большая картинка снизу\n await ctx.send(embed=em)\n#Об других функциях можете почитать в документации\n\n\nbot.run(settings['Token']) #тут можно ничего не трогать\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"437918380","text":"#\n# Copyright (c) 2021 Nutanix Inc. All rights reserved.\n#\n# Authors: John Levon \n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of Nutanix nor the names of its contributors may be\n# used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n# DAMAGE.\n#\n\n#\n# Note that we don't use enum here, as class.value is a little verbose\n#\n\nfrom collections import namedtuple\nfrom types import SimpleNamespace\nimport ctypes as c\nimport json\nimport mmap\nimport os\nimport pathlib\nimport socket\nimport struct\nimport syslog\n\n# from linux/pci_regs.h and linux/pci_defs.h\n\nPCI_HEADER_TYPE_NORMAL = 0\n\nPCI_STD_HEADER_SIZEOF = 64\n\nPCI_BARS_NR = 6\n\nPCI_PM_SIZEOF = 8\n\nPCI_CFG_SPACE_SIZE = 256\nPCI_CFG_SPACE_EXP_SIZE = 4096\n\nPCI_CAP_LIST_NEXT = 1\n\nPCI_CAP_ID_PM = 0x1\nPCI_CAP_ID_VNDR = 0x9\nPCI_CAP_ID_EXP = 0x10\n\nPCI_EXP_DEVCTL2 = 40\nPCI_EXP_LNKCTL2 = 48\n\nPCI_EXT_CAP_ID_DSN = 0x03\nPCI_EXT_CAP_ID_VNDR = 0x0b\n\nPCI_EXT_CAP_DSN_SIZEOF = 12\n\nPCI_EXT_CAP_VNDR_HDR_SIZEOF = 8\n\n# from linux/vfio.h\n\nVFIO_DEVICE_FLAGS_RESET = (1 << 0)\nVFIO_DEVICE_FLAGS_PCI = (1 << 1)\n\nVFIO_REGION_INFO_FLAG_READ = (1 << 0)\nVFIO_REGION_INFO_FLAG_WRITE = (1 << 1)\nVFIO_REGION_INFO_FLAG_MMAP = (1 << 2)\nVFIO_REGION_INFO_FLAG_CAPS = (1 << 3)\n\nVFIO_REGION_TYPE_MIGRATION = 3\nVFIO_REGION_SUBTYPE_MIGRATION = 1\n\nVFIO_REGION_INFO_CAP_SPARSE_MMAP = 1\nVFIO_REGION_INFO_CAP_TYPE = 2\n\nVFIO_IRQ_INFO_EVENTFD = (1 << 0)\n\nVFIO_IRQ_SET_DATA_NONE = (1 << 0)\nVFIO_IRQ_SET_DATA_BOOL = (1 << 1)\nVFIO_IRQ_SET_DATA_EVENTFD = (1 << 2)\nVFIO_IRQ_SET_ACTION_MASK = (1 << 3)\nVFIO_IRQ_SET_ACTION_UNMASK = (1 << 4)\nVFIO_IRQ_SET_ACTION_TRIGGER = (1 << 5)\n\n# libvfio-user defines\n\nVFU_TRANS_SOCK = 0\nLIBVFIO_USER_FLAG_ATTACH_NB = (1 << 0)\nVFU_DEV_TYPE_PCI = 0\n\nLIBVFIO_USER_MAJOR = 0\nLIBVFIO_USER_MINOR = 1\n\nVFIO_USER_CLIENT_MAX_FDS_LIMIT = 1024\n\nSERVER_MAX_FDS = 8\n\nONE_TB = (1024 * 1024 * 1024 * 1024)\n\nVFIO_USER_DEFAULT_MAX_DATA_XFER_SIZE = (1024 * 1024)\nSERVER_MAX_DATA_XFER_SIZE = VFIO_USER_DEFAULT_MAX_DATA_XFER_SIZE\nSERVER_MAX_MSG_SIZE = SERVER_MAX_DATA_XFER_SIZE + 16 + 16\n\nMAX_DMA_REGIONS = 16\nMAX_DMA_SIZE = (8 * ONE_TB)\n\n# enum vfio_user_command\nVFIO_USER_VERSION = 1\nVFIO_USER_DMA_MAP = 2\nVFIO_USER_DMA_UNMAP = 3\nVFIO_USER_DEVICE_GET_INFO = 4\nVFIO_USER_DEVICE_GET_REGION_INFO = 5\nVFIO_USER_DEVICE_GET_REGION_IO_FDS = 6\nVFIO_USER_DEVICE_GET_IRQ_INFO = 7\nVFIO_USER_DEVICE_SET_IRQS = 8\nVFIO_USER_REGION_READ = 9\nVFIO_USER_REGION_WRITE = 10\nVFIO_USER_DMA_READ = 11\nVFIO_USER_DMA_WRITE = 12\nVFIO_USER_DEVICE_RESET = 13\nVFIO_USER_DIRTY_PAGES = 14\nVFIO_USER_MAX = 15\n\nVFIO_USER_F_TYPE_COMMAND = 0\nVFIO_USER_F_TYPE_REPLY = 1\n\nSIZEOF_VFIO_USER_HEADER = 16\n\nVFU_PCI_DEV_BAR0_REGION_IDX = 0\nVFU_PCI_DEV_BAR1_REGION_IDX = 1\nVFU_PCI_DEV_BAR2_REGION_IDX = 2\nVFU_PCI_DEV_BAR3_REGION_IDX = 3\nVFU_PCI_DEV_BAR4_REGION_IDX = 4\nVFU_PCI_DEV_BAR5_REGION_IDX = 5\nVFU_PCI_DEV_ROM_REGION_IDX = 6\nVFU_PCI_DEV_CFG_REGION_IDX = 7\nVFU_PCI_DEV_VGA_REGION_IDX = 8\nVFU_PCI_DEV_MIGR_REGION_IDX = 9\nVFU_PCI_DEV_NUM_REGIONS = 10\n\nVFU_REGION_FLAG_READ = 1\nVFU_REGION_FLAG_WRITE = 2\nVFU_REGION_FLAG_RW = (VFU_REGION_FLAG_READ | VFU_REGION_FLAG_WRITE)\nVFU_REGION_FLAG_MEM = 4\n\nVFIO_USER_F_DMA_REGION_READ = (1 << 0)\nVFIO_USER_F_DMA_REGION_WRITE = (1 << 1)\n\nVFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP = (1 << 0)\n\nVFIO_IOMMU_DIRTY_PAGES_FLAG_START = (1 << 0)\nVFIO_IOMMU_DIRTY_PAGES_FLAG_STOP = (1 << 1)\nVFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP = (1 << 2)\n\n# enum vfu_dev_irq_type\nVFU_DEV_INTX_IRQ = 0\nVFU_DEV_MSI_IRQ = 1\nVFU_DEV_MSIX_IRQ = 2\nVFU_DEV_ERR_IRQ = 3\nVFU_DEV_REQ_IRQ = 4\nVFU_DEV_NUM_IRQS = 5\n\n# enum vfu_reset_type\nVFU_RESET_DEVICE = 0\nVFU_RESET_LOST_CONN = 1\nVFU_RESET_PCI_FLR = 2\n\n# vfu_pci_type_t\nVFU_PCI_TYPE_CONVENTIONAL = 0\nVFU_PCI_TYPE_PCI_X_1 = 1\nVFU_PCI_TYPE_PCI_X_2 = 2\nVFU_PCI_TYPE_EXPRESS = 3\n\nVFU_CAP_FLAG_EXTENDED = (1 << 0)\nVFU_CAP_FLAG_CALLBACK = (1 << 1)\nVFU_CAP_FLAG_READONLY = (1 << 2)\n\nVFU_MIGR_CALLBACKS_VERS = 1\n\nSOCK_PATH = b\"/tmp/vfio-user.sock.%d\" % os.getpid()\n\ntopdir = os.path.realpath(os.path.dirname(__file__) + \"/../..\")\nbuild_type = os.getenv(\"BUILD_TYPE\", default=\"dbg\")\nlibname = \"%s/build/%s/lib/libvfio-user.so\" % (topdir, build_type)\nlib = c.CDLL(libname, use_errno=True)\nlibc = c.CDLL(\"libc.so.6\", use_errno=True)\n\n#\n# Structures\n#\n\nclass Structure(c.Structure):\n def __len__(self):\n \"\"\"Handy method to return length in bytes.\"\"\"\n return len(bytes(self))\n\n @classmethod\n def pop_from_buffer(cls, buf):\n \"\"\"\"Pop a new object from the given bytes buffer.\"\"\"\n obj = cls.from_buffer_copy(buf)\n return obj, buf[c.sizeof(obj):]\n\nclass vfu_bar_t(c.Union):\n _pack_ = 1\n _fields_ = [\n (\"mem\", c.c_int32),\n (\"io\", c.c_int32)\n ]\n\nclass vfu_pci_hdr_intr_t(Structure):\n _pack_ = 1\n _fields_ = [\n (\"iline\", c.c_byte),\n (\"ipin\", c.c_byte)\n ]\n\nclass vfu_pci_hdr_t(Structure):\n _pack_ = 1\n _fields_ = [\n (\"id\", c.c_int32),\n (\"cmd\", c.c_uint16),\n (\"sts\", c.c_uint16),\n (\"rid\", c.c_byte),\n (\"cc_pi\", c.c_byte),\n (\"cc_scc\", c.c_byte),\n (\"cc_bcc\", c.c_byte),\n (\"cls\", c.c_byte),\n (\"mlt\", c.c_byte),\n (\"htype\", c.c_byte),\n (\"bist\", c.c_byte),\n (\"bars\", vfu_bar_t * PCI_BARS_NR),\n (\"ccptr\", c.c_int32),\n (\"ss\", c.c_int32),\n (\"erom\", c.c_int32),\n (\"cap\", c.c_byte),\n (\"res1\", c.c_byte * 7),\n (\"intr\", vfu_pci_hdr_intr_t),\n (\"mgnt\", c.c_byte),\n (\"mlat\", c.c_byte)\n ]\n\nclass iovec_t(Structure):\n _fields_ = [\n (\"iov_base\", c.c_void_p),\n (\"iov_len\", c.c_int32)\n ]\n\nclass vfio_irq_info(Structure):\n _pack_ = 1\n _fields_ = [\n (\"argsz\", c.c_uint32),\n (\"flags\", c.c_uint32),\n (\"index\", c.c_uint32),\n (\"count\", c.c_uint32),\n ]\n\nclass vfio_irq_set(Structure):\n _pack_ = 1\n _fields_ = [\n (\"argsz\", c.c_uint32),\n (\"flags\", c.c_uint32),\n (\"index\", c.c_uint32),\n (\"start\", c.c_uint32),\n (\"count\", c.c_uint32),\n ]\n\nclass vfio_user_device_info(Structure):\n _pack_ = 1\n _fields_ = [\n (\"argsz\", c.c_uint32),\n (\"flags\", c.c_uint32),\n (\"num_regions\", c.c_uint32),\n (\"num_irqs\", c.c_uint32),\n ]\n\nclass vfio_region_info(Structure):\n _pack_ = 1\n _fields_ = [\n (\"argsz\", c.c_uint32),\n (\"flags\", c.c_uint32),\n (\"index\", c.c_uint32),\n (\"cap_offset\", c.c_uint32),\n (\"size\", c.c_uint64),\n (\"offset\", c.c_uint64),\n ]\n\nclass vfio_region_info_cap_type(Structure):\n _pack_ = 1\n _fields_ = [\n (\"id\", c.c_uint16),\n (\"version\", c.c_uint16),\n (\"next\", c.c_uint32),\n (\"type\", c.c_uint32),\n (\"subtype\", c.c_uint32),\n ]\n\nclass vfio_region_info_cap_sparse_mmap(Structure):\n _pack_ = 1\n _fields_ = [\n (\"id\", c.c_uint16),\n (\"version\", c.c_uint16),\n (\"next\", c.c_uint32),\n (\"nr_areas\", c.c_uint32),\n (\"reserved\", c.c_uint32),\n ]\n\nclass vfio_region_sparse_mmap_area(Structure):\n _pack_ = 1\n _fields_ = [\n (\"offset\", c.c_uint64),\n (\"size\", c.c_uint64),\n ]\n\nclass vfio_user_dma_map(Structure):\n _pack_ = 1\n _fields_ = [\n (\"argsz\", c.c_uint32),\n (\"flags\", c.c_uint32),\n (\"offset\", c.c_uint64),\n (\"addr\", c.c_uint64),\n (\"size\", c.c_uint64),\n ]\n\nclass vfu_dma_info_t(Structure):\n _fields_ = [\n (\"iova\", iovec_t),\n (\"vaddr\", c.c_void_p),\n (\"mapping\", iovec_t),\n (\"page_size\", c.c_size_t),\n (\"prot\", c.c_uint32)\n ]\n\nclass vfio_user_dirty_pages(Structure):\n _pack_ = 1\n _fields_ = [\n (\"argsz\", c.c_uint32),\n (\"flags\", c.c_uint32)\n ]\n\nclass vfio_user_bitmap(Structure):\n _pack_ = 1\n _fields_ = [\n (\"pgsize\", c.c_uint64),\n (\"size\", c.c_uint64)\n ]\n\nclass vfio_user_bitmap_range(Structure):\n _pack_ = 1\n _fields_ = [\n (\"iova\", c.c_uint64),\n (\"size\", c.c_uint64),\n (\"bitmap\", vfio_user_bitmap)\n ]\n\ntransition_cb_t = c.CFUNCTYPE(c.c_int, c.c_void_p, c.c_int)\nget_pending_bytes_cb_t = c.CFUNCTYPE(c.c_uint64, c.c_void_p)\nprepare_data_cb_t = c.CFUNCTYPE(c.c_void_p, c.POINTER(c.c_uint64),\n c.POINTER(c.c_uint64))\nread_data_cb_t = c.CFUNCTYPE(c.c_ssize_t, c.c_void_p, c.c_void_p,\n c.c_uint64, c.c_uint64)\nwrite_data_cb_t = c.CFUNCTYPE(c.c_ssize_t, c.c_void_p, c.c_uint64)\ndata_written_cb_t = c.CFUNCTYPE(c.c_int, c.c_void_p, c.c_uint64)\n\nclass vfu_migration_callbacks_t(Structure):\n _fields_ = [\n (\"version\", c.c_int),\n (\"transition\", transition_cb_t),\n (\"get_pending_bytes\", get_pending_bytes_cb_t),\n (\"prepare_data\", prepare_data_cb_t),\n (\"read_data\", read_data_cb_t),\n (\"write_data\", write_data_cb_t),\n (\"data_written\", data_written_cb_t),\n ]\n\nclass dma_sg_t(Structure):\n _fields_ = [\n (\"dma_addr\", c.c_void_p),\n (\"region\", c.c_int),\n (\"length\", c.c_uint64),\n (\"offset\", c.c_uint64),\n (\"writeable\", c.c_bool),\n (\"le_next\", c.c_void_p), # FIXME add struct for LIST_ENTRY \n (\"le_prev\", c.c_void_p),\n ]\n\n#\n# Util functions\n#\n\nlib.vfu_create_ctx.argtypes = (c.c_int, c.c_char_p, c.c_int,\n c.c_void_p, c.c_int)\nlib.vfu_create_ctx.restype = (c.c_void_p)\nlib.vfu_setup_log.argtypes = (c.c_void_p, c.c_void_p, c.c_int)\nlib.vfu_realize_ctx.argtypes = (c.c_void_p,)\nlib.vfu_attach_ctx.argtypes = (c.c_void_p,)\nlib.vfu_run_ctx.argtypes = (c.c_void_p,)\nlib.vfu_destroy_ctx.argtypes = (c.c_void_p,)\nvfu_region_access_cb_t = c.CFUNCTYPE(c.c_int, c.c_void_p, c.POINTER(c.c_char),\n c.c_ulong, c.c_long, c.c_bool)\nlib.vfu_setup_region.argtypes = (c.c_void_p, c.c_int, c.c_ulong,\n vfu_region_access_cb_t, c.c_int, c.c_void_p,\n c.c_uint32, c.c_int, c.c_ulong)\nvfu_reset_cb_t = c.CFUNCTYPE(c.c_int, c.c_void_p, c.c_int)\nlib.vfu_setup_device_reset_cb.argtypes = (c.c_void_p, vfu_reset_cb_t)\nlib.vfu_pci_get_config_space.argtypes = (c.c_void_p,)\nlib.vfu_pci_get_config_space.restype = (c.c_void_p)\nlib.vfu_setup_device_nr_irqs.argtypes = (c.c_void_p, c.c_int, c.c_uint32)\nlib.vfu_pci_init.argtypes = (c.c_void_p, c.c_int, c.c_int, c.c_int)\nlib.vfu_pci_add_capability.argtypes = (c.c_void_p, c.c_ulong, c.c_int,\n c.POINTER(c.c_byte))\nlib.vfu_pci_find_capability.argtypes = (c.c_void_p, c.c_bool, c.c_int)\nlib.vfu_pci_find_capability.restype = (c.c_ulong)\nlib.vfu_pci_find_next_capability.argtypes = (c.c_void_p, c.c_bool, c.c_ulong,\n c.c_int)\nlib.vfu_pci_find_next_capability.restype = (c.c_ulong)\nlib.vfu_irq_trigger.argtypes = (c.c_void_p, c.c_uint)\nvfu_dma_register_cb_t = c.CFUNCTYPE(None, c.c_void_p, c.POINTER(vfu_dma_info_t))\nvfu_dma_unregister_cb_t = c.CFUNCTYPE(c.c_int, c.c_void_p,\n c.POINTER(vfu_dma_info_t))\nlib.vfu_setup_device_dma.argtypes = (c.c_void_p, vfu_dma_register_cb_t,\n vfu_dma_unregister_cb_t)\nlib.vfu_setup_device_migration_callbacks.argtypes = (c.c_void_p,\n c.POINTER(vfu_migration_callbacks_t), c.c_uint64)\nlib.vfu_addr_to_sg.argtypes = (c.c_void_p, c.c_void_p, c.c_size_t,\n c.POINTER(dma_sg_t), c.c_int, c.c_int)\nlib.vfu_map_sg.argtypes = (c.c_void_p, c.POINTER(dma_sg_t), c.POINTER(iovec_t),\n c.c_int, c.c_int)\nlib.vfu_unmap_sg.argtypes = (c.c_void_p, c.POINTER(dma_sg_t),\n c.POINTER(iovec_t), c.c_int)\n\ndef to_byte(val):\n \"\"\"Cast an int to a byte value.\"\"\"\n return val.to_bytes(1, 'little')\n\ndef skip(fmt, buf):\n \"\"\"Return the data remaining after skipping the given elements.\"\"\"\n return buf[struct.calcsize(fmt):]\n\ndef parse_json(json_str):\n \"\"\"Parse JSON into an object with attributes (instead of using a dict).\"\"\"\n return json.loads(json_str, object_hook=lambda d: SimpleNamespace(**d))\n\ndef eventfd(initval=0, flags=0):\n libc.eventfd.argtypes = (c.c_uint, c.c_int)\n return libc.eventfd(initval, flags)\n\ndef connect_sock():\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.connect(SOCK_PATH)\n return sock\n\ndef connect_client(ctx):\n sock = connect_sock()\n\n json = b'{ \"capabilities\": { \"max_msg_fds\": 8 } }'\n # struct vfio_user_version\n payload = struct.pack(\"HH%dsc\" % len(json), LIBVFIO_USER_MAJOR,\n LIBVFIO_USER_MINOR, json, b'\\0')\n hdr = vfio_user_header(VFIO_USER_VERSION, size=len(payload))\n sock.send(hdr + payload)\n vfu_attach_ctx(ctx, expect=0)\n payload = get_reply(sock, expect=0)\n return sock\n\ndef disconnect_client(ctx, sock):\n sock.close()\n\n # notice client closed connection\n vfu_run_ctx(ctx)\n\ndef get_reply(sock, expect=0):\n buf = sock.recv(4096)\n (msg_id, cmd, msg_size, flags, errno) = struct.unpack(\"HHIII\", buf[0:16])\n assert (flags & VFIO_USER_F_TYPE_REPLY) != 0\n assert errno == expect\n return buf[16:]\n\ndef msg(ctx, sock, cmd, payload, expect=0, fds=None):\n \"\"\"Round trip a request and reply to the server.\"\"\"\n hdr = vfio_user_header(cmd, size=len(payload))\n\n if fds:\n sock.sendmsg([hdr + payload], [(socket.SOL_SOCKET, socket.SCM_RIGHTS,\n struct.pack(\"I\" * len(fds), *fds))])\n else:\n sock.send(hdr + payload)\n\n vfu_run_ctx(ctx)\n return get_reply(sock, expect=expect)\n\ndef get_pci_header(ctx):\n ptr = lib.vfu_pci_get_config_space(ctx)\n return c.cast(ptr, c.POINTER(vfu_pci_hdr_t)).contents\n\ndef get_pci_cfg_space(ctx):\n ptr = lib.vfu_pci_get_config_space(ctx)\n return c.cast(ptr, c.POINTER(c.c_char))[0:PCI_CFG_SPACE_SIZE]\n\ndef get_pci_ext_cfg_space(ctx):\n ptr = lib.vfu_pci_get_config_space(ctx)\n return c.cast(ptr, c.POINTER(c.c_char))[0:PCI_CFG_SPACE_EXP_SIZE]\n\ndef read_pci_cfg_space(ctx, buf, count, offset, extended=False):\n space = get_pci_ext_cfg_space(ctx) if extended else get_pci_cfg_space(ctx)\n\n for i in range(count):\n buf[i] = space[offset+i]\n return count\n\ndef write_pci_cfg_space(ctx, buf, count, offset, extended=False):\n max_offset = PCI_CFG_SPACE_EXP_SIZE if extended else PCI_CFG_SPACE_SIZE\n\n assert offset + count <= max_offset\n\n space = c.cast(lib.vfu_pci_get_config_space(ctx), c.POINTER(c.c_char))\n\n for i in range(count):\n space[offset+i] = buf[i]\n return count\n\ndef access_region(ctx, sock, is_write, region, offset, count,\n data=None, expect=0):\n # struct vfio_user_region_access\n payload = struct.pack(\"QII\", offset, region, count)\n if is_write:\n payload += data\n\n cmd = VFIO_USER_REGION_WRITE if is_write else VFIO_USER_REGION_READ\n hdr = vfio_user_header(cmd, size=len(payload))\n sock.send(hdr + payload)\n vfu_run_ctx(ctx)\n result = get_reply(sock, expect=expect)\n\n if is_write:\n return None\n\n return skip(\"QII\", result)\n\ndef write_region(ctx, sock, region, offset, count, data, expect=0):\n access_region(ctx, sock, True, region, offset, count, data, expect=expect)\n\ndef read_region(ctx, sock, region, offset, count, expect=0):\n return access_region(ctx, sock, False, region, offset, count, expect=expect)\n\ndef ext_cap_hdr(buf, offset):\n \"\"\"Read an extended cap header.\"\"\"\n\n # struct pcie_ext_cap_hdr\n cap_id, cap_next = struct.unpack_from('HH', buf, offset)\n cap_next >>= 4\n return cap_id, cap_next\n\n#\n# Library wrappers\n#\n\nmsg_id = 1\n\n@c.CFUNCTYPE(None, c.c_void_p, c.c_int, c.c_char_p)\ndef log(ctx, level, msg):\n print(msg.decode(\"utf-8\"))\n\ndef vfio_user_header(cmd, size, no_reply=False, error=False, error_no=0):\n global msg_id\n\n buf = struct.pack(\"HHIII\", msg_id, cmd, SIZEOF_VFIO_USER_HEADER + size,\n VFIO_USER_F_TYPE_COMMAND, error_no)\n\n msg_id += 1\n\n return buf\n\ndef vfu_create_ctx(trans=VFU_TRANS_SOCK, sock_path=SOCK_PATH, flags=0,\n private=None, dev_type=VFU_DEV_TYPE_PCI):\n if os.path.exists(sock_path):\n os.remove(sock_path)\n\n ctx = lib.vfu_create_ctx(trans, sock_path, flags, private, dev_type)\n\n if ctx:\n lib.vfu_setup_log(ctx, log, syslog.LOG_DEBUG)\n\n return ctx\n\ndef vfu_realize_ctx(ctx):\n return lib.vfu_realize_ctx(ctx)\n\ndef vfu_attach_ctx(ctx, expect=0):\n ret = lib.vfu_attach_ctx(ctx)\n if expect == 0:\n assert ret == 0\n else:\n assert ret == -1\n assert c.get_errno() == expect\n return ret\n\ndef vfu_run_ctx(ctx):\n return lib.vfu_run_ctx(ctx)\n\ndef vfu_destroy_ctx(ctx):\n lib.vfu_destroy_ctx(ctx)\n ctx = None\n if os.path.exists(SOCK_PATH):\n os.remove(SOCK_PATH)\n\ndef vfu_setup_region(ctx, index, size, cb=None, flags=0,\n mmap_areas=None, nr_mmap_areas=None, fd=-1, offset=0):\n assert ctx != None\n\n c_mmap_areas = None\n\n if mmap_areas:\n c_mmap_areas = (iovec_t * len(mmap_areas))(*mmap_areas)\n\n if nr_mmap_areas is None:\n if mmap_areas:\n nr_mmap_areas = len(mmap_areas)\n else:\n nr_mmap_areas = 0\n\n # We're sending a file descriptor to ourselves; to pretend the server is\n # separate, we need to dup() here.\n if fd != -1:\n fd = os.dup(fd)\n\n ret = lib.vfu_setup_region(ctx, index, size,\n c.cast(cb, vfu_region_access_cb_t),\n flags, c_mmap_areas, nr_mmap_areas, fd, offset)\n\n if fd != -1 and ret != 0:\n os.close(fd)\n\n return ret\n\ndef vfu_setup_device_reset_cb(ctx, cb):\n assert ctx != None\n return lib.vfu_setup_device_reset_cb(ctx, c.cast(cb, vfu_reset_cb_t))\n\ndef vfu_setup_device_nr_irqs(ctx, irqtype, count):\n assert ctx != None\n return lib.vfu_setup_device_nr_irqs(ctx, irqtype, count)\n\ndef vfu_pci_init(ctx, pci_type=VFU_PCI_TYPE_EXPRESS,\n hdr_type=PCI_HEADER_TYPE_NORMAL):\n assert ctx != None\n return lib.vfu_pci_init(ctx, pci_type, hdr_type, 0)\n\ndef vfu_pci_add_capability(ctx, pos, flags, data):\n assert ctx != None\n\n databuf = (c.c_byte * len(data)).from_buffer(bytearray(data))\n return lib.vfu_pci_add_capability(ctx, pos, flags, databuf)\n\ndef vfu_pci_find_capability(ctx, extended, cap_id):\n assert ctx != None\n\n return lib.vfu_pci_find_capability(ctx, extended, cap_id)\n\ndef vfu_pci_find_next_capability(ctx, extended, offset, cap_id):\n assert ctx != None\n\n return lib.vfu_pci_find_next_capability(ctx, extended, offset, cap_id)\n\ndef vfu_irq_trigger(ctx, subindex):\n assert ctx != None\n\n return lib.vfu_irq_trigger(ctx, subindex)\n\ndef vfu_setup_device_dma(ctx, register_cb=None, unregister_cb=None):\n assert ctx != None\n\n return lib.vfu_setup_device_dma(ctx, c.cast(register_cb,\n vfu_dma_register_cb_t),\n c.cast(unregister_cb,\n vfu_dma_unregister_cb_t))\n\ndef vfu_setup_device_migration_callbacks(ctx, cbs=None, offset=0):\n assert ctx != None\n\n @c.CFUNCTYPE(c.c_int)\n def stub():\n return 0\n\n if not cbs:\n cbs = vfu_migration_callbacks_t()\n cbs.version = VFU_MIGR_CALLBACKS_VERS\n cbs.transition = c.cast(stub, transition_cb_t)\n cbs.get_pending_bytes = c.cast(stub, get_pending_bytes_cb_t)\n cbs.prepare_data = c.cast(stub, prepare_data_cb_t)\n cbs.read_data = c.cast(stub, read_data_cb_t)\n cbs.write_data = c.cast(stub, write_data_cb_t)\n cbs.data_written = c.cast(stub, data_written_cb_t)\n\n return lib.vfu_setup_device_migration_callbacks(ctx, cbs, offset)\n\ndef vfu_addr_to_sg(ctx, dma_addr, length, max_sg=1,\n prot=(mmap.PROT_READ | mmap.PROT_WRITE)):\n assert ctx != None\n\n sg = dma_sg_t()\n\n return (lib.vfu_addr_to_sg(ctx, dma_addr, length, sg, max_sg, prot), sg)\n\n\ndef vfu_map_sg(ctx, sg, iovec, cnt=1, flags=0):\n # FIXME not sure wheter cnt != 1 will work because iovec is an array\n return lib.vfu_map_sg(ctx, sg, iovec, cnt, flags)\n\ndef vfu_unmap_sg(ctx, sg, iovec, cnt=1):\n return lib.vfu_unmap_sg(ctx, sg, iovec, cnt)\n\n# ex: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab: #\n","sub_path":"test/py/libvfio_user.py","file_name":"libvfio_user.py","file_ext":"py","file_size_in_byte":21792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"43749647","text":"# -*- coding: utf-8 -*-\r\nfrom buff.defines import *\r\nfrom buff.object import Buff as CustomBuff\r\n\r\n#导表开始\nclass Buff(CustomBuff):\n\tname = \"混乱\"\n\ttype = BUFF_TYPE_DEBUFF\n#导表结束\r\n\r\n\tdef onSetup(self, w):\r\n\t\tself.addFunc(w, \"onCommand\", self.onCommand)\r\n\t\t\r\n\tdef onCommand(self, att):\r\n\t\ttargetList = []\r\n\t\twarObj = att.war\r\n\t\tfor w in warObj.idxList.itervalues():\r\n\t\t\tif w is att:\r\n\t\t\t\tcontinue\r\n\t\t\tif not w.isVisible(att):\r\n\t\t\t\tcontinue\r\n\t\t\ttargetList.append(w)\r\n\t\t\r\n\t\timport war.commands\r\n\t\tif targetList:\r\n\t\t\tw = targetList[rand(len(targetList))]\r\n\t\t\twar.commands.setCommand(warObj, att, CMD_TYPE_PHY, targetIdx=w.idx)\r\n\t\telse:\r\n\t\t\twar.commands.setCommand(warObj, att, CMD_TYPE_WAIT)\r\n\r\n\r\nfrom common import *\r\nfrom war.defines import *","sub_path":"logic/buff/bf904.py","file_name":"bf904.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"602260320","text":"from unittest import mock\n\nfrom waldur_core.core import utils as core_utils\nfrom waldur_mastermind.marketplace import models as marketplace_models\nfrom waldur_mastermind.marketplace.tests import factories as marketplace_factories\nfrom waldur_mastermind.marketplace_openstack import INSTANCE_TYPE, VOLUME_TYPE\nfrom waldur_openstack.openstack.tests import factories as openstack_factories\nfrom waldur_openstack.openstack_tenant import models as openstack_tenant_models\nfrom waldur_openstack.openstack_tenant.tests import (\n factories as openstack_tenant_factories,\n)\nfrom waldur_openstack.openstack_tenant.tests.fixtures import OpenStackTenantFixture\n\nfrom .. import tasks\nfrom .utils import BaseOpenStackTest\n\n\nclass TaskTest(BaseOpenStackTest):\n def setUp(self):\n super().setUp()\n self.fixture = OpenStackTenantFixture()\n self.offering = marketplace_factories.OfferingFactory()\n self.offering.scope = self.fixture.instance.service_settings\n self.offering.type = INSTANCE_TYPE\n self.offering.save()\n\n def test_create_resources_for_lost_instances_and_volumes(self):\n tasks.create_resources_for_lost_instances_and_volumes()\n self.assertTrue(\n marketplace_models.Resource.objects.filter(offering=self.offering).exists()\n )\n\n\n@mock.patch('waldur_mastermind.marketplace_openstack.utils.openstack_tenant_backend')\nclass TaskSyncTenantTest(BaseOpenStackTest):\n def setUp(self):\n super().setUp()\n self.instance = openstack_tenant_factories.InstanceFactory()\n self.volume = openstack_tenant_factories.VolumeFactory()\n self.tenant = openstack_factories.TenantFactory(\n service_settings=self.instance.service_settings,\n project=self.instance.project,\n )\n self.instance_offering = marketplace_factories.OfferingFactory()\n self.instance_offering.scope = self.instance.service_settings\n self.instance_offering.type = INSTANCE_TYPE\n self.instance_offering.save()\n\n self.volume_offering = marketplace_factories.OfferingFactory()\n self.volume_offering.scope = self.volume.service_settings\n self.volume_offering.type = VOLUME_TYPE\n self.volume_offering.save()\n\n def test_sync_instances_if_tenant_has_been_synchronized(self, mock_backend):\n mock_backend.OpenStackTenantBackend().get_importable_instances.return_value = [\n {'backend_id': self.instance.backend_id}\n ]\n mock_backend.OpenStackTenantBackend().get_importable_volumes.return_value = []\n mock_backend.OpenStackTenantBackend().import_instance.return_value = (\n self.instance\n )\n tasks.sync_instances_and_volumes_of_tenant(\n core_utils.serialize_instance(self.tenant)\n )\n self.assertTrue(\n marketplace_models.Resource.objects.filter(scope=self.instance).exists()\n )\n resource = marketplace_models.Resource.objects.get(scope=self.instance)\n\n # deleting of expired instance\n mock_backend.OpenStackTenantBackend().get_importable_instances.return_value = []\n mock_backend.OpenStackTenantBackend().get_expired_instances.return_value = [\n self.instance\n ]\n tasks.sync_instances_and_volumes_of_tenant(\n core_utils.serialize_instance(self.tenant)\n )\n resource.refresh_from_db()\n self.assertEqual(resource.state, marketplace_models.Resource.States.TERMINATED)\n self.assertRaises(\n openstack_tenant_models.Instance.DoesNotExist, self.instance.refresh_from_db\n )\n\n def test_sync_volumes_if_tenant_has_been_synchronized(self, mock_backend):\n mock_backend.OpenStackTenantBackend().get_importable_instances.return_value = []\n mock_backend.OpenStackTenantBackend().get_importable_volumes.return_value = [\n {'backend_id': self.volume.backend_id}\n ]\n mock_backend.OpenStackTenantBackend().import_volume.return_value = self.volume\n tasks.sync_instances_and_volumes_of_tenant(\n core_utils.serialize_instance(self.tenant)\n )\n self.assertTrue(\n marketplace_models.Resource.objects.filter(scope=self.volume).exists()\n )\n resource = marketplace_models.Resource.objects.get(scope=self.volume)\n\n # deleting of expired instance\n mock_backend.OpenStackTenantBackend().get_importable_volumes.return_value = []\n mock_backend.OpenStackTenantBackend().get_expired_instances.return_value = [\n self.volume\n ]\n tasks.sync_instances_and_volumes_of_tenant(\n core_utils.serialize_instance(self.tenant)\n )\n resource.refresh_from_db()\n self.assertEqual(resource.state, marketplace_models.Resource.States.TERMINATED)\n self.assertRaises(\n openstack_tenant_models.Volume.DoesNotExist, self.volume.refresh_from_db\n )\n","sub_path":"src/waldur_mastermind/marketplace_openstack/tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"280211762","text":"###########################################################\n# 006 ZigZag Conversion\n# \n# Description:\n# The string \"PAYPALISHIRING\" is written in a zigzag pattern\n# on a given number of rows like this: (you may want to\n# display this pattern in a fixed font for better legibility)\n#\n# P A H N\n# A P L S I I G\n# Y I R\n#\n# And then read line by line: \"PAHNAPLSIIGYIR\"\n# Write the code that will take a string and make this conversion given a number of rows:\n# string convert(string s, int numRows);\n# \n# Example:\n# Example 1:\n# Input: s = \"PAYPALISHIRING\", numRows = 3\n# Output: \"PAHNAPLSIIGYIR\"\n# \n# Example 2:\n# Input: s = \"PAYPALISHIRING\", numRows = 4\n# Output: \"PINALSIGYAHRPI\"\n# Explanation:\n# P I N\n# A L S I G\n# Y A H R\n# P I\n# \n# Solution: \n# 1 7\n# 2 6 8\n# 3 5 9\n# 4 10\n# 先找出第一行的数字 即 1 和 7\n# 然后在从 1 到 numRows-1 的 i\n# 加上 1,7,...左右两侧的 i 数\n# 最后再加上最后一行\n###########################################################\nclass Solution:\n def convert(self, s, numRows):\n strn = \"\"\n tk = []\n count=0\n strnlen = len(s)\n if strnlen<= numRows or numRows==1:\n return s\n while count0 and each-i | --guess-external-ip | -g]
\n\n Description:\n Sends a single RPC request to
. Parameters have to be JSON encoded.\n\n Options:\n --ip=
Use this IP for all sockets.\n --guess-external-ip, -g Guess the public facing IP of this machine and\n use it instead of the provided address.\n --timeout= RPC timeout. [default: 2.0]\n\n {COMMON_OPTIONS}\n \"\"\"\n\n short_description = 'Send a request message to some service and output the reply.'\n\n def run(self, **kwargs):\n client = Client.from_config(self.config, **kwargs)\n body = json.loads(self.args.get('', '{}'))\n try:\n timeout = float(self.args.get('--timeout'))\n except ValueError:\n print(\"--timeout requires a number number (e.g. --timeout=0.42)\")\n return 1\n response = client.request(self.args['
'], self.args[''], body, timeout=timeout)\n print(response.body)\n\n\nclass InspectCommand(Command):\n \"\"\"\n Usage: lymph inspect [--ip=
| --guess-external-ip | -g]
[options]\n\n Options:\n --ip=
Use this IP for all sockets.\n --guess-external-ip, -g Guess the public facing IP of this machine and\n use it instead of the provided address.\n\n {COMMON_OPTIONS}\n\n \"\"\"\n\n short_description = 'Describe the available rpc methods of a service.'\n\n def run(self):\n client = Client.from_config(self.config)\n address = self.args['
']\n try:\n result = client.request(address, 'lymph.inspect', {}).body\n except LookupFailure:\n logger.error(\"cannot resolve %s\", address)\n sys.exit(1)\n print\n for method in result['methods']:\n print(\"rpc {name}({params})\\n {help}\\n\".format(\n name=self.terminal.red(method['name']),\n params=', '.join(method['params']),\n help='\\n '.join(textwrap.wrap(method['help'], 70)),\n ))\n\n\nclass DiscoverCommand(Command):\n \"\"\"\n Usage: lymph discover [--instances] [--ip=
| --guess-external-ip | -g] [options]\n\n Show available services\n\n Options:\n\n --instances Show service instances.\n --ip=
Use this IP for all sockets.\n --guess-external-ip, -g Guess the public facing IP of this machine and\n use it instead of the provided address.\n\n {COMMON_OPTIONS}\n\n \"\"\"\n\n short_description = 'Show available services.'\n\n def run(self):\n client = Client.from_config(self.config)\n for service_type in sorted(client.container.discover()):\n p = client.container.lookup('lymph://%s' % service_type)\n print(\"%s [%s]\" % (self.terminal.red(service_type), len(p)))\n if self.args.get('--instances'):\n instances = sorted(p, key=lambda d: d.identity)\n for i, d in enumerate(p):\n prefix = u'└─' if i == len(instances) - 1 else u'├─'\n print(u'%s [%s] %s' % (prefix, d.identity[:10], d.endpoint))\n\n\nclass SubscribeCommand(Command):\n \"\"\"\n Usage: lymph subscribe [options]\n\n {COMMON_OPTIONS}\n \"\"\"\n\n short_description = 'Prints events to stdout.'\n\n def run(self):\n event_type = self.args.get('')\n\n class Subscriber(lymph.Interface):\n @lymph.event(event_type)\n def on_event(self, event):\n print('%s: %r' % (event.evt_type, event.body))\n\n client = Client.from_config(self.config, interface_cls=Subscriber)\n client.container.join()\n\n\nclass EmitCommand(Command):\n \"\"\"\n Usage: lymph emit []\n\n {COMMON_OPTIONS}\n \"\"\"\n\n short_description = 'Manually emits an event.'\n\n def run(self):\n event_type = self.args.get('')\n body = json.loads(self.args.get(''))\n\n client = Client.from_config(self.config)\n client.emit(event_type, body)\n","sub_path":"lymph/cli/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"287437933","text":"import os\nimport datetime\nimport sqlalchemy\nimport sqlalchemy.orm\nimport sqlalchemy.ext.declarative\nfrom sqlalchemy import Column, Integer, Date, String\n\nEntityBase = sqlalchemy.ext.declarative.declarative_base()\n\nclass Book(EntityBase):\n __tablename__ = \"Books\"\n id = Column(Integer, primary_key=True)\n sold_copies = Column(Integer, default=0)\n title = Column(String, nullable=False)\n published = Column(Date, default=datetime.datetime.now)\n\n\nclass DBORM:\n def __init__(self):\n conn_str = self.get_conn_string()\n self.engine = sqlalchemy.create_engine(conn_str, echo=True)\n EntityBase.metadata.create_all(self.engine)\n self.session_factory = sqlalchemy.orm.sessionmaker(self.engine)\n\n def get_conn_string(self):\n file = os.path.join(\n\n os.path.abspath('.'),\n 'data',\n 'sql_alc_orm.sqlite_db'\n )\n conn_str = 'sqlite:///' + file\n return conn_str\n\n def add_some_data(self):\n\n session = self.session_factory()\n\n count = session.query(Book).filter().count()\n print(\"There are {} books in the DB\".format(count))\n # if count > 0:\n # return\n\n book = Book()\n book.title = \"First time ORM games\"\n book.sold_copies = 27\n book.published = datetime.date(2013, 1,1)\n session.add(book)\n\n book = Book()\n book.title = \"More ORM games\"\n book.sold_copies = 100\n book.published = datetime.date(2014, 1,1)\n session.add(book)\n\n book = Book()\n book.title = \"SQL for fun and profit\"\n book.sold_copies = 10\n book.published = datetime.date(2014, 5,1)\n session.add(book)\n\n print(\"NEW\",session.new)\n print(\"DIRTY\",session.dirty)\n\n session.commit()\n\n print(\"After save: Id = {0}\".format(book.id) )\n\n def show_data(self):\n\n session = self.session_factory()\n\n print(\"Building query...\")\n books = session.query(Book)\n books = books.filter(Book.sold_copies > 0)\n books = books.order_by(Book.sold_copies.desc())\n print(\"Query done, running now...\")\n\n\n print(\"Most popular book is:\")\n print(books[0].__dict__)\n\n\n books[0].sold_copies += 42\n\n session.commit()\n\n print(\"Sliced data\")\n\n books = session.query(Book)\\\n .filter(Book.sold_copies > 0)\\\n .order_by(Book.sold_copies.desc())\n\n print(\"Second page books: {}\".format(len(books[5:10])))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"14_SQLAlchemy/db_orm.py","file_name":"db_orm.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"354001157","text":"import os, sys, optparse, subprocess, random, traci, sumolib\nimport numpy as np\nimport pandas as pd\nfrom sumolib import checkBinary\n\nif 'SUMO_HOME' in os.environ:\n tools = os.path.join(os.environ['SUMO_HOME'], 'tools')\n sys.path.append(tools)\nelse:\n sys.exit(\"please declare environment variable 'SUMO_HOME'\")\n\n\n# Obtener la lista de los ID's de todos los semaforos\ndef TurnOffTLS(TLSlist):\n ''' Apaga la programacion de los semaforos de la simulacion\n Entrada:\n TLSlist(list): Lista con el ID de los semaforos\n Ejemplo de la lista de entrada:\n TLSlist =('gneJ0','gneJ1', 'gneJ12', 'gneJ13', 'gneJ14', 'gneJ17', 'gneJ18', 'gneJ19', 'gneJ2', 'gneJ3', 'gneJ4', 'gneJ5', 'gneJ6', 'gneJ7', 'gneJ8', 'gneJ9')\n '''\n for j in range(0,len(TLSlist)):\n r = TLSlist[j]\n traci.trafficlight.setProgram(r,\"off\")\n# Obtener los semaforos aleatoreos\ndef RandomTLS(n, TLSlist):\n ''' Selecciona semafotos aleatorios de los semaforos previamente apagados\n y los enciende.\n Entradas:\n -n (Integer): El numero de semaforos a prender\n -TLSlist(List): Lista con el ID de los semaforos '''\n\n TLS_on = np.random.choice(TLSlist,n,replace= False)\n for k in range(0,len(TLS_on)):\n traci.trafficlight.setProgram(TLS_on[k], \"0\")\n return TLS_on\n# Toma las Screenshots del semaforo\ndef TakeScreenshot(i):\n traci.gui.screenshot(\"View #0\",\"Screenshots/\"+ TLSlist[0] +\" \"+ str(i)+\".png\")\ndef GetInLanes(NodoID,netFile):\n '''\n Funcion que regresa los Edges entrantes al nodo\n Inputs:\n - Nodo ID: (string) NodoID del que se quieren saber los Edges entrantes\n - netFile: (string) Nombre del archivo .net\n Salida: (List of Strings) Lista de los ID edges de entrata al nodo\n\n Ejemplo:\n GetInLanes( NodoID('0'), 'prueba1.net.xml')\n Edges de entrada: [,\n ]\n Salida: ['gneE0', 'gneE2']\n '''\n # net = sumolib.net.readNet('prueba1.net.xml')\n # InEdges = net.getNode('0').getIncoming()\n net = sumolib.net.readNet(netFile)\n InEdges = net.getNode(NodoID).getIncoming()\n i = 0\n LanesID = []\n while i < len(InEdges):\n a = str(InEdges[i])\n b = list(a.split())[1]\n r = (b.split(\"=\")[1]).rstrip('\"').lstrip('\"')\n LanesID.append(r)\n i = i + 1\n\n return LanesID\n#Obtiene mediciones realizadas al lane de entrada\ndef Measures(TLS_on,laneID):\n\n # Return the time if simulation in seconds\n SimulationTime = traci.simulation.getTime()\n # Return the time if simulation in ms\n SimulationTimeMS = traci.simulation.getCurrentTime()\n #Return the percentage of ocupacy in the las step\n percentOccupancy = traci.edge.getLastStepOccupancy(laneID)\n # Return the number of vehicles in the las step\n numberofvehicles = traci.edge.getLastStepVehicleNumber(laneID)\n # Return the number of halting vehicles\n hatingvehicles = traci.edge.getLastStepHaltingNumber(laneID)\n #Return the mean speed of the lane\n meanspeed = traci.edge.getLastStepMeanSpeed(laneID)\n #Returns the number of lanes of this edge\n LaneNumbers = traci.edge.getLaneNumber(laneID)\n # Return the id of the vehicles in this edge\n IdVehicle = traci.edge.getLastStepVehicleIDs(laneID)\n #Return the sum of the waiting time in the edge\n Waittime = traci.edge.getWaitingTime(laneID) # revisar y sacar el promedio ''\n if len(IdVehicle) == 0:\n IdVehicle = 0\n\n measures = [SimulationTime,TLS_on,laneID,percentOccupancy, numberofvehicles, hatingvehicles, meanspeed, LaneNumbers,IdVehicle, Waittime]\n return measures\n\ndef run():\n N_steps = 86401 # tiempo de simulacion\n step_1 = 0\n i = 0\n stephoto = range(step_1,N_steps,300)\n ListofMeasures = list()\n while traci.simulation.getCurrentTime() < 90000000: #tiempo de simulacion \n ''' Inicio simulacion ''' \n traci.simulationStep()\n # Condicion de paro de la simulacion cuando se tomen todas las imagenes\n # En el mismo periodo de tiempo\n if i == len(stephoto):\n break\n ''' Inicio de la obtenicion de los datos'''\n \n #Obtencion de los datos en semaforos activos cada cierto tiempo t\n if stephoto[i] == step_1:\n TakeScreenshot(i)\n i = i + 1 # toma de fotos\n # Obtencion de las otras medidas del simulador\n j = 0\n while j < len(TLS_on):\n LanesID = GetInLanes(TLS_on[j],'prueba1.net.xml')\n for k in range(0,len(LanesID)):\n ListofMeasures.append(Measures(TLS_on[j],LanesID[k]))\n j = j + 1\n ''' Inicio del algoritmo de RL''' \n if i == len(stephoto):\n \n QLearning(ListofMeasures)\n \n step_1 = step_1 + 1\n traci.close()\n return ListofMeasures\n\nsumoBinary = checkBinary('sumo-gui')\nsumoCmd = [sumoBinary, \"-c\", \"prueba1.sumocfg\"]\n\ntraci.start(sumoCmd)\nTLSlist = traci.trafficlight.getIDList()\nTurnOffTLS(TLSlist)\nTLS_on = RandomTLS(1,TLSlist)\n\nLanesID = GetInLanes(TLS_on[0],'prueba1.net.xml')\n\n\n\na = run()\ndf = pd.DataFrame(a,columns = ['SimulationTime','TLS_ID','laneID','percentOccupancy','numberofvehicles','hatingvehicles','meanspeed','LaneNumbers','IdVehicle','Waittime'])\n","sub_path":"RL/1por1/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"573886045","text":"from owlready2 import *\r\nimport types\r\nonto_path.append(r\"/home/tarangjain/KG_IMPRINT_II/KG IMPRINT II-20200816T091910Z-001/KG IMPRINT II\")\r\nonto = get_ontology(\"https://www.cse.iitb.ac.in/~amitpatil/AircraftAccident.owl\").load()\r\nonto.AircraftAccident\r\nnamespace=onto.get_namespace(\"http://www.cse.iitb.ac.in/~amitpatil/aircraft_sbase.owl#\")\r\ndef search5(qu):\r\n Aircraft =\"AircraftAccident.\"+ qu\r\n qp=' '\r\n qp1=''\r\n qp2=''\r\n\r\n with onto:\r\n l1=(list(onto.classes()))\r\n #qp2=list(onto.qu.get_relations())\r\n print(l1)\r\n #for i in l1:\r\n #print(list(i.ancestors()))\r\n for i in l1:\r\n #qp=' '.join([str(elem) for elem in i])\r\n qp=(str(i).strip('[]').__add__(\" \"))\r\n if(qp.__contains__(Aircraft)):\r\n qp2=list(i.ancestors())\r\n\r\n break\r\n print(qp2)\r\n\r\n\r\n return qp2\r\n","sub_path":"Query_Servicing/myproject/nlqapp/templates/nlqpy5.py","file_name":"nlqpy5.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"459024466","text":"#rotates and flips a picture for more test data\n\nimport cv2\nimport sys\nimport random\nimport glob\n\ncount = 0\nFILENAME = 'pos'\n\ndef process(pic,output):\n\tglobal count\n\n\timg = cv2.imread(pic)\n\timg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\tfor i in range(30):\n\t\tcount+=1\n\t\tcv2.imwrite(output + '/' + FILENAME + str(count) + '.png',img)\n\n\t\tcount+=1\n\t\tflip0 = cv2.flip(img,0)\n\t\tcv2.imwrite(output + '/' + FILENAME + str(count) + '.png',flip0)\n\n\t\tcount+=1\n\t\tflip1 = cv2.flip(img,1)\n\t\tcv2.imwrite(output + '/' + FILENAME + str(count) + '.png',flip1)\n\n\t\t(rows,cols) = img.shape[:2]\n\n\t\tM = cv2.getRotationMatrix2D(\t(cols/2,rows/2),random.randint(8,15),1)\n\t\timg = cv2.warpAffine(img,M,(cols,rows))\n\n\tprint(count)\n\n\nif __name__ == \"__main__\":\n\tinputfolder = sys.argv[1]\n\toutputfolder = sys.argv[2]\n\n\tinp = glob.glob('%s/*.png' % inputfolder)\n\n\tfor innie in inp:\n\t\tprocess(innie,outputfolder)\n","sub_path":"rotate_and_flip.py","file_name":"rotate_and_flip.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"649677180","text":"#!/usr/bin/env python\r\n# input() reads a string with a line of input, stripping the '\\n' (newline) at the end.\r\n# This is all you need for most Google Code Jam problems.\r\ncompleteArray = [0,1,2,3,4,5,6,7,8,9]\r\nt = int(input()) # read a line with a single integer\r\nfor i in range(1, t+1):\r\n n = int(input())\r\n numHolder = []\r\n finalNumber = 0\r\n multiplier = 1\r\n temp = int(n)\r\n if n == 0:\r\n finalNumber = \"INSOMNIA\"\r\n else:\r\n while not (completeArray == numHolder):\r\n digitHolder = [int(x) for x in str(temp)]\r\n for stuff in digitHolder:\r\n if not (stuff in numHolder):\r\n numHolder.append(stuff)\r\n finalNumber = temp\r\n #print (\"{} is not in numholder!\".format(stuff))\r\n temp = multiplier * n\r\n multiplier = multiplier + 1\r\n numHolder.sort()\r\n print(\"Case #{}: {}\".format(i, finalNumber))\r\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_Seirai_CountSheep.py","file_name":"16_0_1_Seirai_CountSheep.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"26839568","text":"NUM_EPOCHS = 30\nALPHA = 5e-3 # learning rate\nBATCH_SIZE = 10 # how many episodes we want to pack into an epoch\nGAMMA = 0.99 # discount rate\nHIDDEN_SIZE = 128 # number of hidden nodes we have in our dnn\nBETA = 0.1 # the entropy bonus multiplier\n\n\n\n\nmax_simulation_day = 30\nnum_minutes_per_trading_day = (6*2+1)*30\ndata_interval_minute = 5\nmax_simulation_length = int(max_simulation_day*num_minutes_per_trading_day/data_interval_minute) #in unit of interval\nmax_history_day = 2\nmin_history_length = int(max_history_day*num_minutes_per_trading_day/data_interval_minute) #in unit of interval, the 30 means 30 days\nmax_position = 10\ninit_cash_value = 1e5\n#we also observe what percent of the portfolio is in stock\n#therefore we need to add 1\n#however, since we use percentage change, we loose 1 because of the percentage change computation\nobservation_space_size = int(min_history_length-1+1) \naction_space_size = int(max_position+1) #we also can have 0 position","sub_path":"spy_many_discrete_actions/spy/reward_type_2/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"376456240","text":"#!/usr/bin/env python3\n\"\"\"Function that calculates the Shannon entropy\nand P affinities relative to a data point\"\"\"\n\nimport numpy as np\n\n\nP_init = __import__('2-P_init').P_init\nHP = __import__('3-entropy').HP\n\n\ndef P_affinities(X, tol=1e-5, perplexity=30.0):\n \"\"\"\n X is a numpy.ndarray of shape (n, d)\n containing the dataset to be transformed by t-SNE\n n is the number of data points\n d is the number of dimensions in each point\n perplexity is the perplexity for all Gaussian distributions\n tol is the maximum tolerance allowed (inclusive)\n Returns:\n P, a numpy.ndarray of shape (n, n) containing the symmetric P affinities\n \"\"\"\n D, P, betas, H = P_init(X, perplexity)\n for i in range(X.shape[0]):\n Di = np.append(D[i, :i], D[i, i+1:])\n Hi, Pi = HP(Di, betas[i])\n bmin = None\n bmax = None\n Hdiff = Hi - H\n while np.abs(Hdiff) > tol:\n if Hdiff > 0:\n bmin = betas[i].copy()\n if bmax is None:\n betas[i] = betas[i] * 2\n else:\n betas[i] = (betas[i] + bmax) / 2\n else:\n bmax = betas[i].copy()\n if bmin is None:\n betas[i] = betas[i] / 2\n else:\n betas[i] = (betas[i] + bmin) / 2\n Hi, Pi = HP(Di, betas[i])\n Hdiff = Hi - H\n P[i, np.concatenate((np.r_[0:i], np.r_[i+1:X.shape[0]]))] = Pi\n return (P.T + P) / (2 * X.shape[0])\n","sub_path":"unsupervised_learning/0x00-dimensionality_reduction/4-P_affinities.py","file_name":"4-P_affinities.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"481386390","text":"\"\"\"\nSkimmer for ParticleNet tagger inputs.\n\nAuthor(s): Cristina Mantilla Suarez, Raghav Kansal\n\"\"\"\nimport os\nimport pathlib\nimport warnings\nfrom typing import Dict\n\nimport awkward as ak\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\nimport uproot\nfrom coffea.analysis_tools import PackedSelection\nfrom coffea.nanoevents.methods import candidate\nfrom coffea.processor import ProcessorABC, dict_accumulator\n\nfrom .get_tagger_inputs import get_lep_features, get_met_features\n\n# from .run_tagger_inference import runInferenceTriton\nfrom .utils import FILL_NONE_VALUE, add_selection_no_cutflow, bkgs, sigs, tagger_gen_matching\n\nwarnings.filterwarnings(\"ignore\", message=\"Found duplicate branch \")\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nwarnings.filterwarnings(\"ignore\", message=\"Missing cross-reference index \")\nwarnings.filterwarnings(\"ignore\", message=\"divide by zero encountered in log\")\nnp.seterr(invalid=\"ignore\")\n\nP4 = {\n \"eta\": \"eta\",\n \"phi\": \"phi\",\n \"mass\": \"mass\",\n \"pt\": \"pt\",\n}\n\n\nclass InputProcessor(ProcessorABC):\n \"\"\"\n Produces a flat training ntuple from PFNano.\n \"\"\"\n\n def __init__(self, label, inference, output_location=\"./outfiles/\"):\n \"\"\"\n :param num_jets: Number of jets to save\n :type num_jets: int\n \"\"\"\n\n \"\"\"\n Skimming variables\n \"\"\"\n self.label = label\n self.inference = inference\n self._output_location = output_location\n\n self.skim_vars = {\n \"Event\": {\n \"event\": \"event\",\n },\n \"FatJet\": {\n **P4,\n \"msoftdrop\": \"msoftdrop\",\n },\n \"GenPart\": [\n \"fj_genjetmass\",\n \"fj_genRes_pt\",\n \"fj_genRes_eta\",\n \"fj_genRes_phi\",\n \"fj_genRes_mass\",\n \"fj_nprongs\",\n \"fj_ncquarks\",\n \"fj_lepinprongs\",\n \"fj_nquarks\",\n \"fj_H_VV_4q\",\n \"fj_H_VV_elenuqq\",\n \"fj_H_VV_munuqq\",\n \"fj_H_VV_leptauelvqq\",\n \"fj_H_VV_leptaumuvqq\",\n \"fj_H_VV_hadtauvqq\",\n \"fj_QCDb\",\n \"fj_QCDbb\",\n \"fj_QCDc\",\n \"fj_QCDcc\",\n \"fj_QCDothers\",\n \"fj_V_2q\",\n \"fj_V_elenu\",\n \"fj_V_munu\",\n \"fj_V_taunu\",\n \"fj_Top_nquarksnob\",\n \"fj_Top_nbquarks\",\n \"fj_Top_ncquarks\",\n \"fj_Top_nleptons\",\n \"fj_Top_nele\",\n \"fj_Top_nmu\",\n \"fj_Top_ntau\",\n \"fj_Top_taudecay\",\n ],\n # formatted to match weaver's preprocess.json\n \"MET\": {\n \"met_features\": {\n \"var_names\": [\n \"met_relpt\",\n \"met_relphi\",\n ],\n },\n \"met_points\": {\"var_length\": 1},\n },\n \"Lep\": {\n \"fj_features\": {\n \"fj_lep_dR\",\n \"fj_lep_pt\",\n \"fj_lep_iso\",\n \"fj_lep_miniiso\",\n },\n },\n }\n\n self.tagger_resources_path = str(pathlib.Path(__file__).parent.resolve()) + \"/tagger_resources/\"\n\n self.fatjet_label = \"FatJet\"\n self.pfcands_label = \"FatJetPFCands\"\n self.svs_label = \"FatJetSVs\"\n\n self._accumulator = dict_accumulator({})\n\n @property\n def accumulator(self):\n return self._accumulator\n\n def save_dfs_parquet(self, df, fname):\n if self._output_location is not None:\n PATH = f\"{self._output_location}/parquet/\"\n if not os.path.exists(PATH):\n os.makedirs(PATH)\n\n table = pa.Table.from_pandas(df)\n if len(table) != 0: # skip dataframes with empty entries\n pq.write_table(table, f\"{PATH}/{fname}.parquet\")\n\n def ak_to_pandas(self, output_collection: ak.Array) -> pd.DataFrame:\n output = pd.DataFrame()\n for field in ak.fields(output_collection):\n output[field] = ak.to_numpy(output_collection[field])\n return output\n\n def dump_root(self, skimmed_vars: Dict[str, np.array], fname: str) -> None:\n \"\"\"\n Saves ``jet_vars`` dict as a rootfile to './outroot'\n \"\"\"\n local_dir = os.path.abspath(os.path.join(self._output_location, \"outroot\"))\n os.system(f\"mkdir -p {local_dir}\")\n\n with uproot.recreate(f\"{local_dir}/{fname}.root\", compression=uproot.LZ4(4)) as rfile:\n rfile[\"Events\"] = ak.Array(skimmed_vars)\n rfile[\"Events\"].show()\n\n def process(self, events: ak.Array):\n import time\n\n start = time.time()\n\n def build_p4(cand):\n return ak.zip(\n {\n \"pt\": cand.pt,\n \"eta\": cand.eta,\n \"phi\": cand.phi,\n \"mass\": cand.mass,\n \"charge\": cand.charge,\n },\n with_name=\"PtEtaPhiMCandidate\",\n behavior=candidate.behavior,\n )\n\n electrons = events[\"Electron\"][events[\"Electron\"].pt > 40]\n muons = events[\"Muon\"][events[\"Muon\"].pt > 30]\n leptons = ak.concatenate([electrons, muons], axis=1)\n leptons = leptons[ak.argsort(leptons.pt, ascending=False)]\n fatjets = events[self.fatjet_label]\n candidatelep_p4 = build_p4(ak.firsts(leptons))\n\n fj_idx_lep = ak.argmin(fatjets.delta_r(candidatelep_p4), axis=1, keepdims=True)\n fatjet = ak.firsts(fatjets[fj_idx_lep])\n\n # selection\n selection = PackedSelection()\n add_selection_no_cutflow(\"fjselection\", (fatjet.pt > 200), selection)\n\n if np.sum(selection.all(*selection.names)) == 0:\n return {}\n\n # variables\n FatJetVars = {\n f\"fj_{key}\": ak.fill_none(fatjet[var], FILL_NONE_VALUE) for (var, key) in self.skim_vars[\"FatJet\"].items()\n }\n LepVars = {\n **get_lep_features(\n self.skim_vars[\"Lep\"],\n events,\n fatjet,\n candidatelep_p4,\n ),\n }\n\n METVars = {\n **get_met_features(\n self.skim_vars[\"MET\"],\n events,\n fatjet,\n \"MET\",\n normalize=False,\n ),\n }\n\n genparts = events.GenPart\n matched_mask, genVars = tagger_gen_matching(\n events,\n genparts,\n fatjet,\n # candidatelep_p4,\n self.skim_vars[\"GenPart\"],\n label=self.label,\n )\n # add_selection_no_cutflow(\"gen_match\", matched_mask, selection)\n\n skimmed_vars = {**FatJetVars, **{\"matched_mask\": matched_mask}, **genVars, **METVars, **LepVars}\n\n # apply selections\n skimmed_vars = {\n key: np.squeeze(np.array(value[selection.all(*selection.names)])) for (key, value) in skimmed_vars.items()\n }\n\n # fill inference\n if self.inference:\n from .run_tagger_inference import runInferenceTriton\n\n for model_name in [\"ak8_MD_vminclv2ParT_manual_fixwrap_all_nodes\"]:\n pnet_vars = runInferenceTriton(\n self.tagger_resources_path,\n events[selection.all(*selection.names)],\n fj_idx_lep[selection.all(*selection.names)],\n model_name=model_name,\n )\n\n # pnet_df = self.ak_to_pandas(pnet_vars)\n pnet_df = pd.DataFrame(pnet_vars)\n\n num = pnet_df[sigs].sum(axis=1)\n den = pnet_df[sigs].sum(axis=1) + pnet_df[bkgs].sum(axis=1)\n\n scores = {\"fj_ParT_inclusive_score\": (num / den).values}\n reg_mass = {\"fj_ParT_mass\": pnet_vars[\"fj_ParT_mass\"]}\n\n hidNeurons = {}\n for key in pnet_vars:\n if \"hidNeuron\" in key:\n hidNeurons[key] = pnet_vars[key]\n\n skimmed_vars = {**skimmed_vars, **scores, **reg_mass, **hidNeurons}\n\n for key in skimmed_vars:\n skimmed_vars[key] = skimmed_vars[key].squeeze()\n\n # convert output to pandas\n df = pd.DataFrame(skimmed_vars)\n\n df = df.dropna() # very few events would have genjetmass NaN for some reason\n\n print(f\"convert: {time.time() - start:.1f}s\")\n\n print(df)\n\n # save the output\n fname = events.behavior[\"__events_factory__\"]._partition_key.replace(\"/\", \"_\")\n fname = \"condor_\" + fname\n\n self.save_dfs_parquet(df, fname)\n\n print(f\"dump parquet: {time.time() - start:.1f}s\")\n\n # TODO: drop NaNs from rootfiles\n self.dump_root(skimmed_vars, fname)\n print(f\"dump rootfile: {time.time() - start:.1f}s\")\n\n # for now do something like this to dump the parquets in root\n # OUTPATH = \"../datafiles/ntuples/\"\n\n # for sample in samples:\n # print(sample)\n\n # for file in os.listdir(f\"{OUTPATH}/{sample}/train/\"):\n # if \"parquet\" not in file:\n # continue\n\n # d = pd.read_parquet(f\"{OUTPATH}/{sample}/train/{file}\")\n\n # with uproot.recreate(f\"{OUTPATH}/{sample}/train/out.root\", compression=uproot.LZ4(4)) as rfile:\n # rfile[\"Events\"] = ak.Array(d.to_dict(orient=\"list\", index=True))\n # rfile[\"Events\"].show()\n\n # for file in os.listdir(f\"{OUTPATH}/{sample}/test/\"):\n # if \"parquet\" not in file:\n # continue\n\n # d = pd.read_parquet(f\"{OUTPATH}/{sample}/test/{file}\")\n\n # with uproot.recreate(f\"{OUTPATH}/{sample}/test/out.root\", compression=uproot.LZ4(4)) as rfile:\n # rfile[\"Events\"] = ak.Array(d.to_dict(orient=\"list\", index=True))\n # rfile[\"Events\"].show()\n # print(\"--------------------------\")\n\n return {}\n\n def postprocess(self, accumulator):\n pass\n","sub_path":"boostedhiggs/inputprocessor.py","file_name":"inputprocessor.py","file_ext":"py","file_size_in_byte":10284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"581059873","text":"class Solution:\n\n def minTimeToVisitAllPoints(self, points):\n '''\n Time Complexity = O(N)\n Space Complexity = O(1)\n '''\n total = 0\n for i in range(len(points) - 1):\n total += max(abs(points[i][0] - points[i + 1][0]),\n abs(points[i][1] - points[i + 1][1]))\n return total\n\n\nif __name__ == '__main__':\n\n import ipdb\n ipdb.set_trace()\n\n points = [[1, 1], [3, 4], [-1, 0]]\n solution = Solution()\n answer = solution.minTimeToVisitAllPoints(points)\n print(answer)\n # output 7\n\n points = [[3, 2], [-2, 2]]\n solution = Solution()\n answer = solution.minTimeToVisitAllPoints(points)\n print(answer)\n # output 5\n","sub_path":"easy/1266_MinimumTimeVisitingAllPoints.py","file_name":"1266_MinimumTimeVisitingAllPoints.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"248336848","text":"\"\"\"Player module.\"\"\"\n\nfrom brainstorm.utils.colors import menu\nfrom PyInquirer import prompt\n\n\ndef is_ready():\n \"\"\"Check player ready.\n\n Returns:\n bool: True if Player ready else False\n \"\"\"\n question = [\n {\n \"type\": \"confirm\",\n \"message\": \"Are you ready?\",\n \"name\": \"continue\",\n \"default\": True,\n },\n ]\n\n return prompt(\n question,\n style=menu,\n ).get(\"continue\")\n\n\ndef get_name():\n \"\"\"Ask for the player's name.\n\n Returns:\n str: Player name\n \"\"\"\n question = [\n {\n \"type\": \"input\",\n \"name\": \"player\",\n \"message\": \"What's your name:\",\n },\n ]\n\n return prompt(\n question,\n style=menu,\n ).get(\"player\")\n","sub_path":"brainstorm/utils/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"426756648","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views import View\n\nfrom hello_django.calc.models import History\n# Create your views here.\n\n\nclass IndexView(View):\n\n def get(self, request, *args, **kwargs):\n a = kwargs.get('a', 0)\n b = kwargs.get('b', 0)\n summ = a + b\n History(value=summ).save()\n return render(\n request, 'calc/index.html',\n context={'num1': a, 'num2': b, 'summ': summ}\n )\n # return HttpResponse('Sum of {} and {} is {}'.format(a, b, summ))\n # return HttpResponse('{} + {} = {}'.format(a, b, summ))\n\n\nclass HistoryView(View):\n\n def get(self, request, *args, **kwargs):\n last_ten = History.objects.all().order_by('-timestamp')[:10]\n\n return render(request, 'calc/history.html', context={'story_list': last_ten})\n\n\n# def index(request):\n# return HttpResponse('calc')\n","sub_path":"hello_django/calc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"591637085","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport datetime, time\n\ndef genPlot(plotName,arrayFitnessMejores, arrayFitnessMedio):\n plt.figure(figsize=((15,5)))\n plt.hold(True)\n plt.plot(arrayFitnessMejores, 'bo-', label='Mejor')\n plt.plot(arrayFitnessMedio, 'ro-', label='Media')\n plt.legend(loc=4)\n plt.xlabel('Generacion')\n plt.ylabel('Fitness')\n plt.ylim(np.min([arrayFitnessMejores, arrayFitnessMedio])*0.95,\n np.max([arrayFitnessMejores, arrayFitnessMedio])*1.05)\n\n #plt.savefig('../Graficas/' + plotName + '.png')\n #print \"PLOTTING...\"\n #plotName = 'Graficas/'+ str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))+'.png'\n #plotName = 'Graficas/1.png'\n plt.savefig('Graficas/'+str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))+'.png')\n return","sub_path":"P4/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"96636756","text":"from django.contrib.sites.models import Site\n\nfrom pinax_theme_bootstrap.conf import settings\n\n\ndef theme(request):\n # Copy of pinax_theme_bootstrap.context_processors.theme\n # that uses request.site\n ctx = {\n \"THEME_ADMIN_URL\": settings.THEME_ADMIN_URL,\n \"THEME_CONTACT_EMAIL\": settings.THEME_CONTACT_EMAIL,\n }\n\n if Site._meta.installed:\n ctx.update({\n \"SITE_NAME\": request.site.name,\n \"SITE_DOMAIN\": request.site.domain\n })\n\n return ctx\n","sub_path":"src/dcl/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"415625002","text":"\"\"\"\nCollection of Container classes for interacting with aligned and hierarchical dynamic tables\n\"\"\"\nfrom collections import OrderedDict\n\nimport numpy as np\nimport pandas as pd\n\nfrom . import register_class\nfrom .table import DynamicTable\nfrom ..utils import docval, getargs, call_docval_func, popargs, get_docval\n\n\n@register_class('AlignedDynamicTable')\nclass AlignedDynamicTable(DynamicTable):\n \"\"\"\n DynamicTable container that supports storing a collection of subtables. Each sub-table is a\n DynamicTable itself that is aligned with the main table by row index. I.e., all\n DynamicTables stored in this group MUST have the same number of rows. This type effectively\n defines a 2-level table in which the main data is stored in the main table implemented by this type\n and additional columns of the table are grouped into categories, with each category being'\n represented by a separate DynamicTable stored within the group.\n \"\"\"\n __fields__ = ({'name': 'category_tables', 'child': True}, )\n\n @docval(*get_docval(DynamicTable.__init__),\n {'name': 'category_tables', 'type': list,\n 'doc': 'List of DynamicTables to be added to the container. NOTE: Only regular '\n 'DynamicTables are allowed. Using AlignedDynamicTable as a category for '\n 'AlignedDynamicTable is currently not supported.', 'default': None},\n {'name': 'categories', 'type': 'array_data',\n 'doc': 'List of names with the ordering of category tables', 'default': None})\n def __init__(self, **kwargs): # noqa: C901\n in_category_tables = popargs('category_tables', kwargs)\n in_categories = popargs('categories', kwargs)\n if in_category_tables is not None:\n # Error check to make sure that all category_table are regular DynamicTable\n for i, v in enumerate(in_category_tables):\n if not isinstance(v, DynamicTable):\n raise ValueError(\"Category table with index %i is not a DynamicTable\" % i)\n if isinstance(v, AlignedDynamicTable):\n raise ValueError(\"Category table with index %i is an AlignedDynamicTable. \"\n \"Nesting of AlignedDynamicTable is currently not supported.\" % i)\n # set in_categories from the in_category_tables if it is empy\n if in_categories is None and in_category_tables is not None:\n in_categories = [tab.name for tab in in_category_tables]\n # check that if categories is given that we also have category_tables\n if in_categories is not None and in_category_tables is None:\n raise ValueError(\"Categories provided but no category_tables given\")\n # at this point both in_categories and in_category_tables should either both be None or both be a list\n if in_categories is not None:\n if len(in_categories) != len(in_category_tables):\n raise ValueError(\"%s category_tables given but %s categories specified\" %\n (len(in_category_tables), len(in_categories)))\n # Initialize the main dynamic table\n call_docval_func(super().__init__, kwargs)\n # Create and set all sub-categories\n dts = OrderedDict()\n # Add the custom categories given as inputs\n if in_category_tables is not None:\n # We may need to resize our main table when adding categories as the user may not have set ids\n if len(in_category_tables) > 0:\n # We have categories to process\n if len(self.id) == 0:\n # The user did not initialize our main table id's nor set columns for our main table\n for i in range(len(in_category_tables[0])):\n self.id.append(i)\n # Add the user-provided categories in the correct order as described by the categories\n # This is necessary, because we do not store the categories explicitly but we maintain them\n # as the order of our self.category_tables. In this makes sure look-ups are consistent.\n lookup_index = OrderedDict([(k, -1) for k in in_categories])\n for i, v in enumerate(in_category_tables):\n # Error check that the name of the table is in our categories list\n if v.name not in lookup_index:\n raise ValueError(\"DynamicTable %s does not appear in categories %s\" % (v.name, str(in_categories)))\n # Error check to make sure no two tables with the same name are given\n if lookup_index[v.name] >= 0:\n raise ValueError(\"Duplicate table name %s found in input dynamic_tables\" % v.name)\n lookup_index[v.name] = i\n for table_name, tabel_index in lookup_index.items():\n # This error case should not be able to occur since the length of the in_categories and\n # in_category_tables must match and we made sure that each DynamicTable we added had its\n # name in the in_categories list. We, therefore, exclude this check from coverage testing\n # but we leave it in just as a backup trigger in case something unexpected happens\n if tabel_index < 0: # pragma: no cover\n raise ValueError(\"DynamicTable %s listed in categories but does not appear in category_tables\" %\n table_name) # pragma: no cover\n # Test that all category tables have the correct number of rows\n category = in_category_tables[tabel_index]\n if len(category) != len(self):\n raise ValueError('Category DynamicTable %s does not align, it has %i rows expected %i' %\n (category.name, len(category), len(self)))\n # Add the category table to our category_tables.\n dts[category.name] = category\n # Set the self.category_tables attribute, which will set the parent/child relationships for the category_tables\n self.category_tables = dts\n\n def __contains__(self, val):\n \"\"\"\n Check if the given value (i.e., column) exists in this table\n\n :param val: If val is a string then check if the given category exists. If val is a tuple\n of two strings (category, colname) then check for the given category if the given colname exists.\n \"\"\"\n if isinstance(val, str):\n return val in self.category_tables or val in self.colnames\n elif isinstance(val, tuple):\n if len(val) != 2:\n raise ValueError(\"Expected tuple of strings of length 2 got tuple of length %i\" % len(val))\n return val[1] in self.get_category(val[0])\n else:\n return False\n\n @property\n def categories(self):\n \"\"\"\n Get the list of names the categories\n\n Short-hand for list(self.category_tables.keys())\n\n :raises: KeyError if the given name is not in self.category_tables\n \"\"\"\n return list(self.category_tables.keys())\n\n @docval({'name': 'category', 'type': DynamicTable, 'doc': 'Add a new DynamicTable category'},)\n def add_category(self, **kwargs):\n \"\"\"\n Add a new DynamicTable to the AlignedDynamicTable to create a new category in the table.\n\n NOTE: The table must align with (i.e, have the same number of rows as) the main data table (and\n other category tables). I.e., if the AlignedDynamicTable is already populated with data\n then we have to populate the new category with the corresponding data before adding it.\n\n :raises: ValueError is raised if the input table does not have the same number of rows as the main table.\n ValueError is raised if the table is an AlignedDynamicTable instead of regular DynamicTable.\n \"\"\"\n category = getargs('category', kwargs)\n if len(category) != len(self):\n raise ValueError('New category DynamicTable does not align, it has %i rows expected %i' %\n (len(category), len(self)))\n if category.name in self.category_tables:\n raise ValueError(\"Category %s already in the table\" % category.name)\n if isinstance(category, AlignedDynamicTable):\n raise ValueError(\"Category is an AlignedDynamicTable. Nesting of AlignedDynamicTable \"\n \"is currently not supported.\")\n self.category_tables[category.name] = category\n category.parent = self\n\n @docval({'name': 'name', 'type': str, 'doc': 'Name of the category we want to retrieve', 'default': None})\n def get_category(self, **kwargs):\n name = popargs('name', kwargs)\n if name is None or (name not in self.category_tables and name == self.name):\n return self\n else:\n return self.category_tables[name]\n\n @docval(*get_docval(DynamicTable.add_column),\n {'name': 'category', 'type': str, 'doc': 'The category the column should be added to',\n 'default': None})\n def add_column(self, **kwargs):\n \"\"\"\n Add a column to the table\n\n :raises: KeyError if the category does not exist\n\n \"\"\"\n category_name = popargs('category', kwargs)\n if category_name is None:\n # Add the column to our main table\n call_docval_func(super().add_column, kwargs)\n else:\n # Add the column to a sub-category table\n try:\n category = self.get_category(category_name)\n except KeyError:\n raise KeyError(\"Category %s not in table\" % category_name)\n category.add_column(**kwargs)\n\n @docval({'name': 'data', 'type': dict, 'doc': 'the data to put in this row', 'default': None},\n {'name': 'id', 'type': int, 'doc': 'the ID for the row', 'default': None},\n {'name': 'enforce_unique_id', 'type': bool, 'doc': 'enforce that the id in the table must be unique',\n 'default': False},\n allow_extra=True)\n def add_row(self, **kwargs):\n \"\"\"\n We can either provide the row data as a single dict or by specifying a dict for each category\n \"\"\"\n data, row_id, enforce_unique_id = popargs('data', 'id', 'enforce_unique_id', kwargs)\n data = data if data is not None else kwargs\n\n # extract the category data\n category_data = {k: data.pop(k) for k in self.categories if k in data}\n\n # Check that we have the approbriate categories provided\n missing_categories = set(self.categories) - set(list(category_data.keys()))\n if missing_categories:\n raise KeyError(\n '\\n'.join([\n 'row data keys do not match available categories',\n 'missing {} category keys: {}'.format(len(missing_categories), missing_categories)\n ])\n )\n # Add the data to our main dynamic table\n data['id'] = row_id\n data['enforce_unique_id'] = enforce_unique_id\n call_docval_func(super().add_row, data)\n\n # Add the data to all out dynamic table categories\n for category, values in category_data.items():\n self.category_tables[category].add_row(**values)\n\n @docval({'name': 'ignore_category_ids', 'type': bool,\n 'doc': \"Ignore id columns of sub-category tables\", 'default': False})\n def to_dataframe(self, **kwargs):\n \"\"\"Convert the collection of tables to a single pandas DataFrame\"\"\"\n dfs = [super().to_dataframe().reset_index(), ]\n if getargs('ignore_category_ids', kwargs):\n dfs += [category.to_dataframe() for category in self.category_tables.values()]\n else:\n dfs += [category.to_dataframe().reset_index() for category in self.category_tables.values()]\n names = [self.name, ] + list(self.category_tables.keys())\n res = pd.concat(dfs, axis=1, keys=names)\n res.set_index((self.name, 'id'), drop=True, inplace=True)\n return res\n\n def __getitem__(self, item):\n \"\"\"\n :param item: Selection defining the items of interest. This may be a\n\n * **int, list, array, slice** : Return one or multiple row of the table as a DataFrame\n * **string** : Return a single category table as a DynamicTable or a single column of the\n primary table as a\n * **tuple**: Get a column, row, or cell from a particular category. The tuple is expected to consist\n of (category, selection) where category may be a string with the name of the sub-category\n or None (or the name of this AlignedDynamicTable) if we want to slice into the main table.\n\n :returns: DataFrame when retrieving a row or category. Returns scalar when selecting a cell.\n Returns a VectorData/VectorIndex when retrieving a single column.\n \"\"\"\n if isinstance(item, (int, list, np.ndarray, slice)):\n # get a single full row from all tables\n dfs = ([super().__getitem__(item).reset_index(), ] +\n [category[item].reset_index() for category in self.category_tables.values()])\n names = [self.name, ] + list(self.category_tables.keys())\n res = pd.concat(dfs, axis=1, keys=names)\n res.set_index((self.name, 'id'), drop=True, inplace=True)\n return res\n elif isinstance(item, str) or item is None:\n if item in self.colnames:\n # get a specific column\n return super().__getitem__(item)\n else:\n # get a single category\n return self.get_category(item).to_dataframe()\n elif isinstance(item, tuple):\n if len(item) == 2:\n return self.get_category(item[0])[item[1]]\n elif len(item) == 3:\n return self.get_category(item[0])[item[1]][item[2]]\n else:\n raise ValueError(\"Expected tuple of length 2 or 3 with (category, column, row) as value.\")\n","sub_path":"src/hdmf/common/alignedtable.py","file_name":"alignedtable.py","file_ext":"py","file_size_in_byte":14125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"558763209","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 8 12:10:31 2017\n\n@author: ro\nseoultech data sciences Silro Jeong\n\n2016.12.26 \n전력 사용량 예측 모델 - data input, preprocessing\n\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\n\n# data input\npath = 'C:/Users/ro/Desktop/energy/'\nfname = 'data_csv.csv' ### 2013년\nwname = 'p_data.csv'\n\ndata = pd.read_csv(path+fname) #초기 변수 45개\n\n# data delete\n# 1000 < Y < 6000 : 전력 사용량 이상치 제거\n\ndata = data.loc[lambda data:data['ees_13']<6000]\ndata = data.loc[lambda data:1000 > > overall (total)\ndel data['h2_13'] # 거주층수와의 상관성이 높음\n#변수개수 20개\n# Dataframe column rename\n\ndata=data.rename(index=str, columns={\n 'h1_13':'주택형태',\n 'h3_13':'거주층수',\n 'h4_13':'주택방향',\n 'h5_13':'건축년도',\n 'h7_13':'침실',\n 'h9_13':'욕실 수',\n 'h11_13':'거주년수',\n 'h14_13':'보조난방방식',\n 'h16_13':'냉방방식',\n 'h20_13':'경제활동 가구원수',\n 'h25_13':'가구주 성별',\n 'h26_13':'가구주 연령대',\n 'h27_13':'가구주 교육정도',\n 'h28_13':'가구주 직업',\n 'rh6_13':'주택면적',\n 'rh31_13':'월평균소득',\n 'rh19_13':'*가구원수',\n 'ees_13':'전력사용량'})\n\n# 'gcity':'도시규모', 'city_13':\"시도\",\n\n# columns types dic\ndic=data.dtypes\n\n# data DataFrame sort & reindex\ndata = data.sort('전력사용량')\ndata.index=range(len(data))\n\n# not change columns > 이산형 변수\n#a=['거주층수','침실','욕실 수','거주년수','경제활동 가구원수','*가구원수']\na=['침실','욕실 수','경제활동 가구원수']\nln = ['거주층수','거주년수','*가구원수']\ne = ['전력사용량']\n############################\n#수치형 자료 data \n\nfor v in a+ln: \n dic[v]=float\n\n# 이산형 변수 Scaling\nfor x in a+ln:\n data[x]=preprocessing.maxabs_scale(data[x]) # range(-1,1) normalization\n\n#ln - variable transform\ndata['전력사용량'] = np.log(data['전력사용량'])\ndata[ln] = np.log(data[ln])\ndata_sqrt=np.sqrt(data[a+ln+e])\ndata_log=np.log(data[a+ln+e])\n#이산형 dataframe\ntype(data['전력사용량'])\n\ndata_num = (pd.DataFrame.from_records(data[a+ln+e]))\n\nnum_corr=data_num.corr()\npoly = preprocessing.PolynomialFeatures(degree=2)\nex1=poly.fit_transform(data_num)\n\n############################\n\n# make dummy\nfor v in filter(lambda x: dic[x]=='int64',data.keys()):\n #create dummy\n dummy=pd.get_dummies(data[v],prefix=v)\n \n #remove old v\n #dic.pop(v)#데이터 삭제\n \n #add new dummy v to dic\n for dummy_v in dummy.columns:\n dic[dummy_v]='nominal'\n \n #add dummy v to main df\n data=data.drop(v,axis=1) #제외하고 출력\n data=data.join(dummy)\n \n\n### dummy value del\ndel data['보조난방방식_0'] #2는 전력을 사용한 난방 \n\n#####\n\n#correration maxtrix\ncorr=pd.DataFrame(data.corr())\n\n# Lasso 에 의한 변수 제거 10개 \n\ndel data['건축년도_3']\ndel data['주택소유형태_2']\ndel data['가구주 연령대_4']\ndel data['가구주 교육정도_2']\ndel data['가구주 교육정도_4']\ndel data['가구주 직업_1']\ndel data['주택형태_1']\ndel data['주택방향_7']\ndel data['건축년도_1']\n\n#상관성에 의한 변수 소거\n\ndel data['가구주 성별_2'] #1은 남자 2는 여자\ndel data['주택면적_2'] #corr에 의한 삭제 침실 수와 corr이 높다\n\n##### 범주형 변수_dummy\n\ndata_category=data\ndata_category=data_category.drop(data_num.columns,axis=1)\nX = data_category\nY = data['전력사용량']\ndel X['전력사용량']\n\n# write csv file\npd.DataFrame.to_csv(data_sqrt,path+wname)\n\n#############################\n# train / test\n\n#Y=preprocessing.maxabs_scale(Y)","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465020856","text":"\"\"\"Mission Pinball Framework Media Controller (mpf-mc) setup.py\"\"\"\n\n\nimport sys\nimport re\n\nfrom copy import deepcopy\nimport os\nfrom os.path import join, dirname, sep, exists, basename, isdir\nfrom os import walk, environ\nfrom distutils.version import LooseVersion\nfrom collections import OrderedDict\nfrom time import sleep\nfrom setuptools import setup, Extension\n\n\n# fix error with py3's LooseVersion comparisons\ndef ver_equal(self, other):\n return self.version == other\n\nLooseVersion.__eq__ = ver_equal\n\n\nMIN_CYTHON_STRING = '0.23'\nMIN_CYTHON_VERSION = LooseVersion(MIN_CYTHON_STRING)\nMAX_CYTHON_STRING = '0.24.1'\nMAX_CYTHON_VERSION = LooseVersion(MAX_CYTHON_STRING)\nCYTHON_UNSUPPORTED = ()\n\nPACKAGE_FILES_ALLOWED_EXT = ('py', 'yaml', 'png', 'md', 'zip', 'gif', 'jpg',\n 'mp4', 'm4v', 'so', 'pyd', 'dylib', 'wav', 'ogg',\n 'pxi', 'pyx', 'c', 'h', 'ttf')\n\n\ndef getoutput(cmd, env=None):\n import subprocess\n p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, env=env)\n p.wait()\n if p.returncode: # if not returncode == 0\n print('WARNING: A problem occurred while running {0} (code {1})\\n'\n .format(cmd, p.returncode))\n stderr_content = p.stderr.read()\n if stderr_content:\n print('{0}\\n'.format(stderr_content))\n return \"\"\n return p.stdout.read()\n\n\ndef pkgconfig(*packages, **kw):\n flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}\n lenviron = None\n pconfig = join(dirname(sys.executable), 'libs', 'pkgconfig')\n\n if isdir(pconfig):\n lenviron = environ.copy()\n lenviron['PKG_CONFIG_PATH'] = '{};{}'.format(\n environ.get('PKG_CONFIG_PATH', ''), pconfig)\n cmd = 'pkg-config --libs --cflags {}'.format(' '.join(packages))\n results = getoutput(cmd, lenviron).split()\n for token in results:\n ext = token[:2].decode('utf-8')\n flag = flag_map.get(ext)\n if not flag:\n continue\n kw.setdefault(flag, []).append(token[2:].decode('utf-8'))\n return kw\n\n\n# -----------------------------------------------------------------------------\n# Determine on which platform we are\n\nplatform = sys.platform\n\n# Detect 32/64bit for OSX (http://stackoverflow.com/a/1405971/798575)\nif sys.platform == 'darwin':\n if sys.maxsize > 2 ** 32:\n osx_arch = 'x86_64'\n else:\n osx_arch = 'i386'\n\nif exists('/opt/vc/include/bcm_host.h'):\n platform = 'rpi'\nif exists('/usr/lib/arm-linux-gnueabihf/libMali.so'):\n platform = 'mali'\n\n# -----------------------------------------------------------------------------\n# Detect options\n#\nc_options = OrderedDict()\nc_options['use_rpi'] = platform == 'rpi'\nc_options['use_mali'] = platform == 'mali'\nc_options['use_osx_frameworks'] = platform == 'darwin'\n\n# SDL2 and GStreamer are required for mpfmc\nc_options['use_sdl2'] = True\nc_options['use_gstreamer'] = True\n\n# now check if environ is changing the default values\nfor key in list(c_options.keys()):\n ukey = key.upper()\n if ukey in environ:\n value = bool(int(environ[ukey]))\n print('Environ change {0} -> {1}'.format(key, value))\n c_options[key] = value\n\nif not c_options['use_sdl2']:\n print('SDL2 framework is required for mpfmc compilation')\n raise EnvironmentError('SDL2 framework is required for mpfmc compilation')\n\nif not c_options['use_gstreamer']:\n print('GStreamer framework is required for mpfmc compilation')\n raise EnvironmentError('GStreamer framework is required for mpfmc compilation')\n\n\n# -----------------------------------------------------------------------------\n# Cython check\n#\ncython_unsupported_append = '''\n\n Please note that the following versions of Cython are not supported\n at all: {}\n'''.format(', '.join(map(str, CYTHON_UNSUPPORTED)))\n\ncython_min = '''\\\n This version of Cython is not compatible with Kivy. Please upgrade to\n at least version {0}, preferably the newest supported version {1}.\n\n If your platform provides a Cython package, make sure you have upgraded\n to the newest version. If the newest version available is still too low,\n please remove it and install the newest supported Cython via pip:\n\n pip install -I Cython=={1}{2}\\\n'''.format(MIN_CYTHON_STRING, MAX_CYTHON_STRING,\n cython_unsupported_append if CYTHON_UNSUPPORTED else '')\n\ncython_max = '''\\\n This version of Cython is untested with Kivy. While this version may\n work perfectly fine, it is possible that you may experience issues. If\n you do have issues, please downgrade to a supported version. It is\n best to use the newest supported version, {1}, but the minimum\n supported version is {0}.\n\n If your platform provides a Cython package, check if you can downgrade\n to a supported version. Otherwise, uninstall the platform package and\n install Cython via pip:\n\n pip install -I Cython=={1}{2}\\\n'''.format(MIN_CYTHON_STRING, MAX_CYTHON_STRING,\n cython_unsupported_append if CYTHON_UNSUPPORTED else '')\n\ncython_unsupported = '''\\\n This version of Cython suffers from known bugs and is unsupported.\n Please install the newest supported version, {1}, if possible, but\n the minimum supported version is {0}.\n\n If your platform provides a Cython package, check if you can install\n a supported version. Otherwise, uninstall the platform package and\n install Cython via pip:\n\n pip install -I Cython=={1}{2}\\\n'''.format(MIN_CYTHON_STRING, MAX_CYTHON_STRING,\n cython_unsupported_append)\n\nhave_cython = False\nskip_cython = False\ntry:\n # check for cython\n from Cython.Distutils import build_ext\n have_cython = True\n import Cython\n cy_version_str = Cython.__version__\n cy_ver = LooseVersion(cy_version_str)\n print('\\nDetected Cython version {}'.format(cy_version_str))\n if cy_ver < MIN_CYTHON_VERSION:\n print(cython_min)\n raise ImportError('Incompatible Cython Version')\n if cy_ver in CYTHON_UNSUPPORTED:\n print(cython_unsupported)\n raise ImportError('Incompatible Cython Version')\n if cy_ver > MAX_CYTHON_VERSION:\n print(cython_max)\n sleep(1)\nexcept ImportError:\n print('\\nCython is missing, its required for compiling mpfmc !\\n\\n')\n raise\n\nif not have_cython:\n from distutils.command.build_ext import build_ext\n\n# -----------------------------------------------------------------------------\n# Setup classes\n\n# the build path where mpfmc is being compiled\nsrc_path = build_path = dirname(__file__)\n\nif platform == 'darwin':\n if c_options['use_osx_frameworks']:\n if osx_arch == \"i386\":\n print(\"Warning: building with frameworks fail on i386\")\n else:\n print(\"OSX framework used, force to x86_64 only\")\n environ[\"ARCHFLAGS\"] = environ.get(\"ARCHFLAGS\", \"-arch x86_64\")\n print(\"OSX ARCHFLAGS are: {}\".format(environ[\"ARCHFLAGS\"]))\n\ngst_flags = {}\n\n# detect gstreamer, only on desktop\n# works if we forced the options or in autodetection\nif platform not in ('ios', 'android') and (c_options['use_gstreamer']\n in (None, True)):\n if c_options['use_osx_frameworks'] and platform == 'darwin':\n # check the existence of frameworks\n f_path = '/Library/Frameworks/GStreamer.framework'\n if not exists(f_path):\n c_options['use_gstreamer'] = False\n print('Missing GStreamer framework {}'.format(f_path))\n raise EnvironmentError('Missing GStreamer framework {}'.format(f_path))\n\n else:\n c_options['use_gstreamer'] = True\n gst_flags = {\n 'extra_link_args': [\n '-F/Library/Frameworks',\n '-Xlinker', '-rpath',\n '-Xlinker', '/Library/Frameworks',\n '-Xlinker', '-headerpad',\n '-Xlinker', '190',\n '-framework', 'GStreamer'],\n 'include_dirs': [join(f_path, 'Headers')]}\n\n else:\n # use pkg-config approach instead\n gst_flags = pkgconfig('gstreamer-1.0')\n if 'libraries' in gst_flags:\n c_options['use_gstreamer'] = True\n\n\n# detect SDL2, only on desktop and iOS, or android if explicitly enabled\n# works if we forced the options or in autodetection\nsdl2_flags = {}\nif c_options['use_sdl2'] or (\n platform not in ('android',) and c_options['use_sdl2'] is None):\n\n if c_options['use_osx_frameworks'] and platform == 'darwin':\n # check the existence of frameworks\n sdl2_valid = True\n sdl2_flags = {\n 'extra_link_args': [\n '-F/Library/Frameworks',\n '-Xlinker', '-rpath',\n '-Xlinker', '/Library/Frameworks',\n '-Xlinker', '-headerpad',\n '-Xlinker', '190'],\n 'include_dirs': [],\n 'extra_compile_args': ['-F/Library/Frameworks']\n }\n f_path = '/Library/Frameworks/{}.framework'.format('SDL2')\n if exists(f_path):\n sdl2_flags['extra_link_args'] += ['-framework', 'SDL2']\n sdl2_flags['include_dirs'] += [join(f_path, 'Headers')]\n print('Found sdl2 frameworks: {}'.format(f_path))\n else:\n print('Missing framework {}'.format(f_path))\n sdl2_valid = False\n\n if not sdl2_valid:\n c_options['use_sdl2'] = False\n print('Cannot perform mpfmc compilation due to missing SDL2 framework')\n raise EnvironmentError('Cannot perform mpfmc compilation due to missing SDL2 framework')\n else:\n c_options['use_sdl2'] = True\n print('Activate SDL2 compilation')\n\n elif platform != \"ios\":\n # use pkg-config approach instead\n sdl2_flags = pkgconfig('sdl2')\n if 'libraries' in sdl2_flags:\n c_options['use_sdl2'] = True\n else:\n print('Cannot perform mpfmc compilation due to missing SDL2 framework')\n raise EnvironmentError('Cannot perform mpfmc compilation due to missing SDL2 framework')\n\n\n# -----------------------------------------------------------------------------\n# declare flags\n\n\ndef get_modulename_from_file(filename):\n print(filename)\n filename = filename.replace(sep, '/')\n pyx = '.'.join(filename.split('.')[:-1])\n pyxl = pyx.split('/')\n while pyxl[0] != 'mpfmc':\n pyxl.pop(0)\n if pyxl[1] == 'mpfmc':\n pyxl.pop(0)\n return '.'.join(pyxl)\n\n\ndef expand(root, *args):\n return join(root, 'mpfmc', *args)\n\n\nclass CythonExtension(Extension):\n\n def __init__(self, *args, **kwargs):\n Extension.__init__(self, *args, **kwargs)\n self.cython_directives = {\n 'c_string_encoding': 'utf-8',\n 'profile': 'USE_PROFILE' in environ,\n 'embedsignature': 'USE_EMBEDSIGNATURE' in environ}\n # XXX with pip, setuptools is imported before distutils, and change\n # our pyx to c, then, cythonize doesn't happen. So force again our\n # sources\n self.sources = args[1]\n\n\ndef merge(d1, *args):\n d1 = deepcopy(d1)\n for d2 in args:\n for key, value in d2.items():\n value = deepcopy(value)\n if key in d1:\n d1[key].extend(value)\n else:\n d1[key] = value\n return d1\n\n\ndef determine_base_flags():\n flags = {\n 'libraries': [],\n 'include_dirs': [],\n 'extra_link_args': [],\n 'extra_compile_args': []}\n if platform.startswith('freebsd'):\n flags['include_dirs'] += [join(\n environ.get('LOCALBASE', '/usr/local'), 'include')]\n flags['extra_link_args'] += ['-L', join(\n environ.get('LOCALBASE', '/usr/local'), 'lib')]\n elif platform == 'darwin':\n v = os.uname()\n if v[2] >= '13.0.0':\n # use xcode-select to search on the right Xcode path\n # XXX use the best SDK available instead of a specific one\n import platform as _platform\n xcode_dev = getoutput('xcode-select -p').splitlines()[0]\n sdk_mac_ver = '.'.join(_platform.mac_ver()[0].split('.')[:2])\n print('Xcode detected at {}, and using OS X{} sdk'.format(\n xcode_dev, sdk_mac_ver))\n sysroot = join(\n xcode_dev.decode('utf-8'),\n 'Platforms/MacOSX.platform/Developer/SDKs',\n 'MacOSX{}.sdk'.format(sdk_mac_ver),\n 'System/Library/Frameworks')\n else:\n sysroot = ('/System/Library/Frameworks/'\n 'ApplicationServices.framework/Frameworks')\n flags['extra_compile_args'] += ['-F%s' % sysroot]\n flags['extra_link_args'] += ['-F%s' % sysroot]\n return flags\n\n\ndef determine_sdl2():\n flags = {}\n if not c_options['use_sdl2']:\n return flags\n\n sdl2_path = environ.get('KIVY_SDL2_PATH', None)\n\n if sdl2_flags and not sdl2_path and platform == 'darwin':\n return sdl2_flags\n\n # no pkgconfig info, or we want to use a specific sdl2 path, so perform\n # manual configuration\n flags['libraries'] = ['SDL2',]\n split_chr = ';' if platform == 'win32' else ':'\n sdl2_paths = sdl2_path.split(split_chr) if sdl2_path else []\n\n if not sdl2_paths:\n sdl_inc = join(dirname(sys.executable), 'include', 'SDL2')\n if isdir(sdl_inc):\n sdl2_paths = [sdl_inc]\n sdl2_paths.extend(['/usr/local/include/SDL2', '/usr/include/SDL2'])\n\n flags['include_dirs'] = sdl2_paths\n\n flags['extra_link_args'] = []\n flags['extra_compile_args'] = []\n flags['extra_link_args'] += (\n ['-L' + p for p in sdl2_paths] if sdl2_paths else\n ['-L/usr/local/lib/'])\n\n # ensure headers for all the SDL2 library is available\n libs_to_check = ['SDL',]\n can_compile = True\n for lib in libs_to_check:\n found = False\n for d in flags['include_dirs']:\n fn = join(d, '{}.h'.format(lib))\n if exists(fn):\n found = True\n print('SDL2: found {} header at {}'.format(lib, fn))\n break\n\n if not found:\n print('SDL2: missing library {}'.format(lib))\n can_compile = False\n\n if not can_compile:\n c_options['use_sdl2'] = False\n print('Cannot perform mpfmc compilation due to missing SDL2 framework')\n raise EnvironmentError('Cannot perform mpfmc compilation due to missing SDL2 framework')\n\n return flags\n\n\nbase_flags = determine_base_flags()\ngl_flags = {}\n\n# -----------------------------------------------------------------------------\n# sources to compile\nsources = {}\n\nif c_options['use_sdl2'] and c_options['use_gstreamer']:\n sdl2_flags = determine_sdl2()\n if sdl2_flags:\n sdl2_depends = {'depends': ['core/audio/sdl2_helper.h', 'core/audio/sdl2.pxi',]}\n gst_depends = {'depends': ['core/audio/gstreamer_helper.h', 'core/audio/gstreamer.pxi',]}\n for source_file in ('core/audio/audio_interface.pyx',):\n sources[source_file] = merge(\n base_flags, gst_flags, gst_depends, sdl2_flags, sdl2_depends)\n\n\n# -----------------------------------------------------------------------------\n# extension modules\n\ndef get_extensions_from_sources(sources):\n ext_modules = []\n if environ.get('KIVY_FAKE_BUILDEXT'):\n print('Fake build_ext asked, will generate only .h/.c')\n return ext_modules\n for pyx, flags in sources.items():\n pyx = expand(src_path, pyx)\n depends = [expand(src_path, x) for x in flags.pop('depends', [])]\n c_depends = [expand(src_path, x) for x in flags.pop('c_depends', [])]\n if not have_cython:\n pyx = '%s.c' % pyx[:-4]\n f_depends = [x for x in depends if x.rsplit('.', 1)[-1] in (\n 'c', 'cpp', 'm')]\n module_name = get_modulename_from_file(pyx)\n flags_clean = {'depends': depends}\n for key, value in flags.items():\n if len(value):\n flags_clean[key] = value\n ext_modules.append(CythonExtension(\n module_name, [pyx] + f_depends + c_depends, **flags_clean))\n return ext_modules\n\nprint(sources)\next_modules = get_extensions_from_sources(sources)\n\n# -----------------------------------------------------------------------------\n# Get the version number of mpf-mc and the required version of MPF by reading\n# the file directly. We can't import it because that would import mpf and\n# break the setup. Details here:\n# http://stackoverflow.com/questions/458550/standard-way-to-embed-version\n# -into-python-package\nversion_file = \"mpfmc/_version.py\"\nversion_file_content = open(version_file, \"rt\").read()\nversion_re = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"\nmo = re.search(version_re, version_file_content, re.M)\nif mo:\n mc_version = mo.group(1)\nelse:\n raise RuntimeError(\n \"Unable to find version string in %s.\" % (version_file,))\n\n# This section pulls the MPF required version from the mpf-mc version file so\n# we can write that as a requirement below\nmpf_version_re = r\"^__mpf_version_required__ = ['\\\"]([^'\\\"]*)['\\\"]\"\nmo = re.search(mpf_version_re, version_file_content, re.M)\nif mo:\n mpf_version = mo.group(1)\nelse:\n raise RuntimeError(\"Unable to find MPF version string in %s.\" % (\n version_file,))\n\n\ninstall_requires = ['ruamel.yaml>=0.10,<0.11',\n 'mpf>={}'.format(mpf_version),\n ]\n\nif platform == 'win32':\n install_requires += ['pypiwin32',\n 'kivy.deps.sdl2',\n 'kivy.deps.sdl2_dev',\n 'kivy.deps.glew',\n 'kivy',\n ]\n\n# -----------------------------------------------------------------------------\n# automatically detect package files\npackage_files = dict(mpfmc=list())\nfor root, subFolders, files in walk('mpfmc'):\n for fn in files:\n ext = fn.split('.')[-1].lower()\n if ext not in PACKAGE_FILES_ALLOWED_EXT:\n continue\n\n filename = join(root, fn)\n directory = dirname(filename)\n package_files['mpfmc'].append('/'.join(filename.split(os.sep)[1:]))\n\n# -----------------------------------------------------------------------------\n# setup !\nsetup(\n name='mpf-mc',\n version=mc_version,\n description='Mission Pinball Framework Media Controller',\n long_description='''Graphics, video, and audio engine for the\n Mission Pinball Framework.\n\n The Mission Pinball Framework Media Controller (MPF-MC) is a component\n of the Mission Pinball Framework (MPF) that controls graphics and\n sound, including dot matrix displays (DMDs), LCD displays, and color\n RGB LED displays.\n\n (The MPF media controller architecture is modular, so you can use this\n MPF-MC package or another one.)\n\n The MPF-MC is built on Kivy and leverages SDL2, OpenGL, and\n GPU-accelerated hardware.\n\n MPF is a work-in-progress that is not yet complete, though we're\n actively developing it and checking in several commits a week. It's\n MIT licensed, actively developed by fun people, and supported by a\n vibrant pinball-loving community.''',\n\n url='http://missionpinball.org',\n author='The Mission Pinball Framework Team',\n author_email='brian@missionpinball.org',\n license='MIT',\n\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.4',\n 'Natural Language :: English',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX :: Linux',\n 'Topic :: Artistic Software',\n 'Topic :: Games/Entertainment :: Arcade'\n ],\n\n keywords='pinball',\n ext_modules=ext_modules,\n\n packages=['mpfmc',],\n package_dir={'mpfmc': 'mpfmc'},\n package_data=package_files,\n zip_safe=False,\n\n install_requires=install_requires,\n\n tests_require=[],\n\n entry_points=\"\"\"\n [mpf.config_player]\n sound_player=mpfmc.config_players.plugins.sound_player:register_with_mpf\n widget_player=mpfmc.config_players.plugins.widget_player:register_with_mpf\n slide_player=mpfmc.config_players.plugins.slide_player:register_with_mpf\n\n [mpf.command]\n mc=mpfmc.commands.mc:get_command\n \"\"\",\n setup_requires=['cython>=' + MIN_CYTHON_STRING] if not skip_cython else [])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":20535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"26779204","text":"import os\nimport sys\nglobe=5\nos.system(\"clear\");\nwhile globe==5:\n\t\tprint(\"\\t1.To Change Directory\");\n\t\tprint(\"\\t2.To return Back\");\n\t\tchoice=int(input(\"Enter your choice:\"));\n\t\tif choice==1:\n\t\t\ty=input(\"\\tEnter Destination_Location ...example : /root/Desktop/ :\");\n\t\t\tk=os.system(\"cd \"+y); \t\t\t\n\t\t\tif k==0:\n\t\t\t\tprint(\"\\tDirectory Successfully changed...\\n\\n\");\n\t\t\telse:\n\t\t\t\tprint(\"\\tDirectory Changing Failed...\\n\\n\");\n\t\telif choice==2:\n\t\t\tsys.exit();\n\t\telse:\n\t\t\tprint(\"Invalid Choice\");\n","sub_path":"Projects/python/pyh-pro/change_directory.py","file_name":"change_directory.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"55308775","text":"from utilitaire import *\r\nimport random\r\nimport tkinter as Tk\r\n\r\ndef CollegeMPResult(main, userInput, resultat):\r\n clean(main)\r\n if userInput.get() == resultat:\r\n Label(main, text=\"Bravo!\").pack()\r\n else:\r\n Label(main, text=\"Perdu...\").pack()\r\n Button(main, text=\"Encore !\", command=lambda: CollegeMPStart(main)).pack()\r\n\r\n\r\ndef CollegeMPStart(main):\r\n clean(main)\r\n Button(main, text=\"NOUVEAU\", command=lambda: CollegeMPStart(main)).pack()\r\n\r\n i = random.randint(1, 60)\r\n e= random.randint(1, 60)\r\n f= random.randint(1,60)\r\n\r\n result = int(e+f)\r\n string = str(i)+\"^\" + str(e) + \" x \" + str(i)+\"^\" + str(f)+ \" = \"\r\n Label(main, text=string).pack()\r\n Label(main, text=\"Simplifier cette multiplication en utilisant les propriétés de calcul des puissances. Ne repondre que par la valeur de l'exposant.\").pack()\r\n r= str(i)+\"^...\"\r\n Label(main,text= r).pack()\r\n userInput = IntVar()\r\n\r\n Entry(main, textvariable=userInput).pack()\r\n Button(main, text=\"Valider\", command=lambda: CollegeMPResult(main, userInput, result)).pack()\r\n\r\n","sub_path":"CollegeMP.py","file_name":"CollegeMP.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"385675724","text":"from typing import Hashable, List\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n\ndef bfs(g: nx.Graph, start_node: Hashable) -> List[Hashable]:\n \"\"\"\n Do an breadth-first search and returns list of nodes in the visited order\n\n :param g: input graph\n :param start_node: starting node for search\n :return: list of nodes in the visited order\n \"\"\"\n print(g.nodes, start_node)\n viewed = [start_node, ]\n queue = [start_node, ]\n while queue:\n n = queue.pop(0)\n for neighbor in g.neighbors(n):\n if neighbor not in viewed:\n queue.append(neighbor)\n viewed.append(neighbor)\n\n return viewed\n\n\nif __name__ == '__main__':\n graph = nx.Graph()\n graph.add_nodes_from(\"ABCDEFGHIJ\")\n graph.add_edges_from([\n ('A', 'B'),\n ('A', 'F'),\n ('B', 'G'),\n ('F', 'G'),\n ('G', 'C'),\n ('G', 'H'),\n ('G', 'I'),\n ('C', 'H'),\n ('I', 'H'),\n ('H', 'D'),\n ('H', 'E'),\n ('H', 'J'),\n ('E', 'D'),\n ])\n # nx.draw(graph, with_labels=True)\n # plt.show()\n print('!')\n bfs(graph, 'A')","sub_path":"Tasks/e0_breadth_first_search.py","file_name":"e0_breadth_first_search.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"323071055","text":"import math\n\ngoal = float(input())\nfantasyBooks = int(input())\nhorrorBooks = int(input())\nromanticBooks = int(input())\n\nfantasyTotal = fantasyBooks * 14.9\nhorrorTotal = horrorBooks * 9.8\nromanticTotal = romanticBooks * 4.3\n\ntotalBooks = fantasyTotal + horrorTotal + romanticTotal\ntotalBooksBezDDS = totalBooks * 0.8\n\nsellersReceive = math.floor((totalBooksBezDDS - goal) * 0.1)\n\nif totalBooksBezDDS >= goal:\n print(\"%.2f leva donated.\" % (totalBooksBezDDS - sellersReceive))\n print(\"Sellers will receive %.0f leva.\" % sellersReceive)\nelse:\n print(\"%.2f money needed.\" % (goal - totalBooksBezDDS))\n","sub_path":"General/Learning/SoftUni Test/ProgrammingBasics/ChristmasMartket.py","file_name":"ChristmasMartket.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"384216400","text":"import time\nfrom pathlib import Path\n\nfrom pulp import *\n\nfrom dimacs import loadGraph, edgeList, saveSolution\n\n\ndef add_variables(graph):\n variables = []\n for idx in range(1, len(graph) - 1):\n var = LpVariable(\"x\" + str(idx), cat=\"Binary\")\n variables.append(var)\n\n return variables\n\n\ndef add_cost_function(model, variables):\n model += sum(variables)\n\n\ndef add_constraints(model, variables, edges):\n for edge in edges:\n model += variables[edge[0] - 1] + variables[edge[1] - 1] >= 1\n\n\ndef get_answer(variables):\n return set([int(v.name[1:]) for v in variables if v.varValue])\n\n\ndef solve(graph):\n model = LpProblem(\"VertexCover\", LpMinimize)\n\n variables = add_variables(graph)\n add_cost_function(model, variables)\n add_constraints(model, variables, edgeList(graph))\n\n model.solve(PULP_CBC_CMD(msg=True))\n\n return get_answer(model.variables())\n\n\ndef solution(path):\n graph = loadGraph(path)\n vertex_cover = solve(graph)\n\n return vertex_cover\n\n\ntests = [file for file in os.listdir(\"graph/\") if os.path.splitext(file)[1] != '.sol']\n# tests = [\"e5\", \"e10\", \"e20\"]\n\nfor i in tests:\n if not Path('graph/' + i + '.sol').is_file() and i[0] == \"r\":\n print(i)\n time1 = time.time()\n res = solution('graph/' + i)\n time2 = time.time()\n\n print(\"The vertex cover for graph \" + i + \" is \" + str(res))\n print(\"It took \", time2 - time1, \"s time\\n\\n\")\n saveSolution('graph/' + i + \".sol\", res)\n","sub_path":"Lab6/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"359106665","text":"\"\"\"\nUtility functions for Scenario_A_Model_Obs_Compare_Currents.ipynb\n\"\"\"\n\nfrom lxml import etree\nfrom io import BytesIO\nfrom warnings import warn\nfrom IPython.display import HTML\ntry:\n from urllib.request import urlopen\nexcept ImportError:\n from urllib import urlopen\n\n# Scientific stack.\nimport numpy as np\nfrom pandas import DataFrame, concat, read_csv\n\n# Custom IOOS/ASA modules (available at PyPI).\nfrom owslib import fes\nfrom owslib.ows import ExceptionReport\n\n\ndef date_range(start_date='1900-01-01', stop_date='2100-01-01',\n constraint='overlaps'):\n \"\"\"Hopefully something like this will be implemented in fes soon.\"\"\"\n if constraint == 'overlaps':\n propertyname = 'apiso:TempExtent_begin'\n start = fes.PropertyIsLessThanOrEqualTo(propertyname=propertyname,\n literal=stop_date)\n propertyname = 'apiso:TempExtent_end'\n stop = fes.PropertyIsGreaterThanOrEqualTo(propertyname=propertyname,\n literal=start_date)\n elif constraint == 'within':\n propertyname = 'apiso:TempExtent_begin'\n start = fes.PropertyIsGreaterThanOrEqualTo(propertyname=propertyname,\n literal=start_date)\n propertyname = 'apiso:TempExtent_end'\n stop = fes.PropertyIsLessThanOrEqualTo(propertyname=propertyname,\n literal=stop_date)\n return start, stop\n\n\ndef get_Coops_longName(station):\n \"\"\"Get longName for specific station from COOPS SOS using DescribeSensor\n request.\"\"\"\n url = ('http://opendap.co-ops.nos.noaa.gov/ioos-dif-sos/SOS?service=SOS&'\n 'request=DescribeSensor&version=1.0.0&'\n 'outputFormat=text/xml;subtype=\"sensorML/1.0.1\"&'\n 'procedure=urn:ioos:station:NOAA.NOS.CO-OPS:%s') % station\n tree = etree.parse(urlopen(url))\n root = tree.getroot()\n path = \"//sml:identifier[@name='longName']/sml:Term/sml:value/text()\"\n namespaces = dict(sml=\"http://www.opengis.net/sensorML/1.0.1\")\n longName = root.xpath(path, namespaces=namespaces)\n if len(longName) == 0:\n longName = station\n return longName[0]\n\n\ndef coops2df(collector, coops_id, sos_name):\n \"\"\"Request CSV response from SOS and convert to Pandas DataFrames.\"\"\"\n\n collector.features = [coops_id]\n collector.variables = [sos_name]\n long_name = get_Coops_longName(coops_id)\n\n try:\n response = collector.raw(responseFormat=\"text/csv\")\n data_df = read_csv(BytesIO(response.encode('utf-8')),\n parse_dates=True,\n index_col='date_time')\n col = 'wind_speed (m/s)'\n\n data_df['Observed Data'] = data_df[col]\n except ExceptionReport as e:\n warn(\"Station %s is not NAVD datum. %s\" % (long_name, e))\n data_df = DataFrame() # Assing an empty DataFrame for now.\n\n data_df.name = long_name\n return data_df\n\n\ndef mod_df(arr, timevar, istart, istop, mod_name, ts):\n \"\"\"Return time series (DataFrame) from model interpolated onto uniform time\n base.\"\"\"\n t = timevar.points[istart:istop]\n jd = timevar.units.num2date(t)\n\n # Eliminate any data that is closer together than 10 seconds this was\n # required to handle issues with CO-OPS aggregations, I think because they\n # use floating point time in hours, which is not very accurate, so the\n # FMRC aggregation is aggregating points that actually occur at the same\n # time.\n dt = np.diff(jd)\n s = np.array([ele.seconds for ele in dt])\n ind = np.where(s > 10)[0]\n arr = arr[ind+1]\n jd = jd[ind+1]\n\n b = DataFrame(arr, index=jd, columns=[mod_name])\n # Eliminate any data with NaN.\n b = b[np.isfinite(b[mod_name])]\n # Interpolate onto uniform time base, fill gaps up to:\n # (10 values @ 6 min = 1 hour).\n c = concat([b, ts], axis=1).interpolate(limit=10)\n return c\n\n\ndef service_urls(records, service='odp:url'):\n \"\"\"Extract service_urls of a specific type (DAP, SOS) from records.\"\"\"\n service_string = 'urn:x-esri:specification:ServiceType:' + service\n urls = []\n for key, rec in records.iteritems():\n # Create a generator object, and iterate through it until the match is\n # found if not found, gets the default value (here \"none\").\n url = next((d['url'] for d in rec.references if\n d['scheme'] == service_string), None)\n if url is not None:\n urls.append(url)\n return urls\n\n\ndef nearxy(x, y, xi, yi):\n \"\"\"Find the indices x[i] of arrays (x,y) closest to the points (xi, yi).\"\"\"\n ind = np.ones(len(xi), dtype=int)\n dd = np.ones(len(xi), dtype='float')\n for i in np.arange(len(xi)):\n dist = np.sqrt((x-xi[i])**2 + (y-yi[i])**2)\n ind[i] = dist.argmin()\n dd[i] = dist[ind[i]]\n return ind, dd\n\n\ndef find_ij(x, y, d, xi, yi):\n \"\"\"Find non-NaN cell d[j,i] that are closest to points (xi, yi).\"\"\"\n index = np.where(~np.isnan(d.flatten()))[0]\n ind, dd = nearxy(x.flatten()[index], y.flatten()[index], xi, yi)\n j, i = ind2ij(x, index[ind])\n return i, j, dd\n\n\ndef find_timevar(cube):\n \"\"\"Return the time variable from Iris. This is a workaround for iris having\n problems with FMRC aggregations, which produce two time coordinates.\"\"\"\n try:\n cube.coord(axis='T').rename('time')\n except: # Be more specific.\n pass\n timevar = cube.coord('time')\n return timevar\n\n\ndef ind2ij(a, index):\n \"\"\"Returns a[j, i] for a.ravel()[index].\"\"\"\n n, m = a.shape\n j = np.int_(np.ceil(index//m))\n i = np.remainder(index, m)\n return i, j\n\n\ndef get_coordinates(bounding_box, bounding_box_type=''):\n \"\"\"Create bounding box coordinates for the map.\"\"\"\n coordinates = []\n if bounding_box_type == \"box\":\n coordinates.append([bounding_box[1], bounding_box[0]])\n coordinates.append([bounding_box[1], bounding_box[2]])\n coordinates.append([bounding_box[3], bounding_box[2]])\n coordinates.append([bounding_box[3], bounding_box[0]])\n coordinates.append([bounding_box[1], bounding_box[0]])\n return coordinates\n\n\ndef inline_map(m):\n \"\"\"From http://nbviewer.ipython.org/gist/rsignell-usgs/\n bea6c0fe00a7d6e3249c.\"\"\"\n m._build_map()\n srcdoc = m.HTML.replace('\"', '"')\n embed = HTML(''.format(srcdoc=srcdoc))\n return embed\n\n\ndef css_styles():\n return HTML(\"\"\"\n \n \"\"\")\n\n","sub_path":"Theme_2_Extreme_Events/Scenario_2A/ModelDataCompare_Winds/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":7234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"377725423","text":"def main():\n \n lines = readFile()\n writeFile(lines)\n\ndef readFile():\n fname = input(\"Enter a filename: \")\n fp = open(fname, 'r')\n lines = fp.readlines()\n fp.close()\n return lines\n\ndef writeFile(data):\n fp = open('output','a')\n for i in range(0, len(data), 1):\n fp.write(str(i) + ' ' + data[i])\n fp.close() \n\nmain()\n","sub_path":"Practice/loops/challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"563076658","text":"# coding = utf-8\n# author = 'xyzhang16'\n\"\"\" contain some data processing methods\"\"\"\n\nimport numpy as np\nimport gensim\nimport pickle\nimport torch\nfrom torch.utils import data\nfrom torch.nn import Embedding\n\n\ndef pads(idxs, pad_token=0):\n \"\"\"\n use 'pad_token' to expand idxs to the max length\n :param idxs: indexes, list of list\n :param pad_token: index of pad_token, int\n :return: (expanded indexes, origin length of indexes), (list of list, list)\n \"\"\"\n idxs_len = [len(i) for i in idxs]\n max_len = max(idxs_len)\n return [i + [pad_token]*(max_len - len(i)) for i in idxs], idxs_len\n\n\ndef get_iter(datas, batch_size, shuffle, drop_last):\n \"\"\"\n get an iter about datas\n :param datas: list of data,\n such as [x_data1, x_data2, y_data], x_data1 is a list of indexes\n The first dimension of each data must be same\n Each data can be converted into a numpy matrix\n :param batch_size: .\n :param shuffle: .\n :param drop_last: .\n :return: a dataloader instance\n \"\"\"\n datas = [torch.from_numpy(np.array(d)) for d in datas]\n data_set = data.TensorDataset(*datas)\n data_iter = data.DataLoader(\n dataset=data_set,\n batch_size=batch_size,\n shuffle=shuffle,\n drop_last=drop_last\n )\n return data_iter\n\n\ndef cut(batch_data, batch_data_len):\n \"\"\"\n cut off too much pad_token from batch_data\n :param batch_data: indexes, tensor\n :param batch_data_len: origin length of indexes, tensor\n :return: revised batch_data, tensor\n \"\"\"\n max_len = max(batch_data_len.numpy())\n return batch_data[:, : max_len]\n\n\ndef get_embedding(vocab, dim=None, embedding=None):\n \"\"\"\n return random embedding or trained embedding\n :param vocab: a Vocab instance\n :param dim: vector's dim, if not None, return random embedding\n :param embedding: file path about a Word2Vec instance\n :return: torch.nn.Embedding instance\n \"\"\"\n\n num_words = len(vocab.w2i)\n # random vector\n if dim:\n return Embedding(num_embeddings=num_words, embedding_dim=dim)\n # trained vector\n elif embedding:\n embedding = gensim.models.Word2Vec.load(embedding)\n dim = embedding.wv.vector_size\n weight = np.zeros((num_words, dim))\n for i in range(num_words):\n if vocab.i2w[i] in embedding.wv:\n weight[i] = embedding.wv[vocab.i2w[i]]\n else:\n weight[i] = np.random.normal(size=dim)\n weight = torch.Tensor(weight)\n return Embedding(num_embeddings=num_words, embedding_dim=dim, _weight=weight)\n else:\n print('get wrong input(get_embedding)')\n exit()\n\n\ndef load_data(file_path, lang):\n \"\"\"\n load data, index, padding\n :param file_path:\n :param lang: a vocab instance\n :return: content, content_len, query, query_len, summary, summary_len\n \"\"\"\n with open(file_path, 'rb') as file:\n content, query, summary = pickle.load(file)\n\n content = [lang.words2idxs(words, use_sos=False, use_eos=True) for words in content]\n content, content_len = pads(content)\n query = [lang.words2idxs(words, use_sos=False, use_eos=True) for words in query]\n query, query_len = pads(query)\n summary = [lang.words2idxs(words, use_sos=True, use_eos=True)for words in summary]\n summary, summary_len = pads(summary)\n\n return content, content_len, query, query_len, summary, summary_len\n\n\ndef deal_batch(batchs):\n \"\"\"\n cut, sort, cuda\n :param batchs: list,\n [content_batch, content_batch_len, query_batch, query_batch_len, summary_batch, summary_batch_len]\n :return: revised batch\n \"\"\"\n batch_content, batch_content_len, batch_query, batch_query_len, batch_summary, batch_summary_len = batchs\n\n # cut\n batch_content = cut(batch_content, batch_content_len)\n batch_query = cut(batch_query, batch_query_len)\n batch_summary = cut(batch_summary, batch_summary_len)\n\n # sort, cuda\n _, s = torch.sort(batch_content_len, descending=True)\n batch_content = batch_content[s].cuda()\n batch_content_len = batch_content_len[s].cuda()\n batch_query = batch_query[s].cuda()\n batch_query_len = batch_query_len[s].cuda()\n batch_summary = batch_summary[s].cuda()\n batch_summary_len = batch_summary_len[s].cuda()\n\n return batch_content, batch_content_len, batch_query, batch_query_len, batch_summary, batch_summary_len\n","sub_path":"data_helper.py","file_name":"data_helper.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516361000","text":"import requests\nimport json\nimport sys\nimport re\nfrom bs4 import BeautifulSoup\nurl = sys.argv[1]\n\ntry:\n\n link = requests.get(url)\n beauti_soup = BeautifulSoup(link.content, 'html.parser')\n b_link = beauti_soup.findAll('a', class_=\"reference external\")\n m_list = []\n for key in b_link:\n ltitle = requests.get(key.get('href'))\n lsoup = BeautifulSoup(ltitle.content, 'html.parser')\n title = beauti_soup.find('title')\n m_list.append({\"link_text\": key.contents[0], \"url\": key.get(\n 'href'), \"title\": title.string})\n jsonString = json.dumps(m_list)\n head = beauti_soup.find(\"h1\").string\n print(head)\n\n with open(head, 'w') as f:\n json.dump(all_dicts, f, sort_keys=False, indent=1, ensure_ascii=False)\n\nexcept Exception as exp:\n exp\n","sub_path":"t11_soup/soup.py","file_name":"soup.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"415021056","text":"import os\nimport shutil\nimport tkinter as tk\nimport glob\nfrom pathlib import Path\n\n\nwindow = tk.Tk()\nwindow.title('Organiser')\nwindow.geometry(\"480x360\")\n\n#Label - Location\nlabel1=tk.Label(text=\"please enter the location: \")\nlabel1.pack()\n#grid(column=0, row=1)\t\t---- cannot use grid() with pack()\n\n#Entry - Location\nentry1=tk.Entry()\nentry1.pack()\nentry1=tk.StringVar()\t\t#---- maybe we cannot use this with entry() variable\n#grid(column=2, row=1)\t\t---- cannot use grid() with pack()\n\n\n#Function Submit\ndef Submit():\n\tSorter(all=i1.get(),Docs=i2.get(),Images=i3.get(),Videos=i4.get(),WebPages=i9.get(),ArchiveFiles=i5.get(),AudioFiles=i6.get(),Setups=i7.get(), ShellScripts=i8.get(), XML=i10.get())\n\n#for i in range(0 to 7)\t\t---- tried using for loop, unable, try again\ni1=tk.IntVar()\ni2=tk.IntVar()\ni3=tk.IntVar()\ni4=tk.IntVar()\ni5=tk.IntVar()\ni6=tk.IntVar()\ni7=tk.IntVar()\ni8=tk.IntVar()\ni9=tk.IntVar()\ni10=tk.IntVar()\n# Actual Organiser\n\nDIRECTORIES = {\n\"WebPages\":[\"html5\", \"html\", \"htm\", \"xhtml\"],\n\"Images\":[\"jpeg\", \"jpg\", \"tiff\", \"gif\", \"bmp\", \"png\", \"bpg\", \"svg\",\"heif\", \"psd\"],\n\"Videos\":[\"avi\", \"flv\", \"wmv\", \"mov\", \"mp4\", \"webm\", \"vob\", \"mng\", \"qt\", \"mpg\", \"mpeg\", \"3gp\", \"mkv\"],\n\"Documents\":[\"txt\", \"in\", \"out\",\"pdf\",\"oxps\", \"epub\", \"pages\", \"docx\", \"doc\", \"fdf\", \"ods\",\"odt\", \"pwi\", \"xsn\", \"xps\", \"dotx\", \"docm\", \"dox\",\"rvg\", \"rtf\", \"rtfd\", \"wpd\", \"xls\", \"xlsx\", \"ppt\",\"pptx\"],\n\"ArchiveFiles\":[\"a\", \"ar\", \"cpio\", \"iso\", \"tar\", \"gz\", \"rz\", \"7z\",\"dmg\", \"rar\", \"xar\", \"zip\"],\n\"AudioFiles\":[\"aac\", \"aa\", \"aac\", \"dvf\", \"m4a\", \"m4b\", \"m4p\", \"mp3\",\".msv\", \"ogg\", \"oga\", \"raw\", \"vox\", \"wav\", \"wma\"],\n\"XML\":[\"xml\"],\n\"Setups\":[\"exe\"],\n\"ShellScripts\":[\"sh\"],\n}\n\nWebPages=[\"html5\", \"html\", \"htm\", \"xhtml\"]\nImages=[\"jpeg\", \"jpg\", \"tiff\", \"gif\", \"bmp\", \"png\", \"bpg\", \"svg\",\"heif\", \"psd\"]\nVideos=[\"avi\", \"flv\", \"wmv\", \"mov\", \"mp4\", \"webm\", \"vob\", \"mng\",\"qt\", \".mpg\", \".mpeg\", \".3gp\", \".mkv\"]\nDocuments=[\"txt\", \"in\", \"out\",\"pdf\",\"oxps\", \"epub\", \"pages\", \"docx\", \"doc\", \"fdf\", \"ods\",\"odt\", \"pwi\", \"xsn\", \"xps\", \"dotx\", \"docm\", \"dox\",\"rvg\", \"rtf\", \"rtfd\", \"wpd\", \"xls\", \"xlsx\", \"ppt\",\"pptx\"]\nArchiveFiles=[\"a\", \"ar\", \"cpio\", \"iso\", \"tar\", \"gz\", \"rz\", \"7z\",\"dmg\", \"rar\", \"xar\", \"zip\"] \nAudioFiles=[\"aac\", \"aa\", \"aac\", \"dvf\", \"m4a\", \"m4b\", \"m4p\", \"mp3\",\"msv\", \"ogg\", \"oga\", \"raw\", \"vox\", \"wav\", \"wma\"]\n# PLAINTEXT_LIST=[] \n# PYTHON_LIST=[\".py\"]\nXML=[\"xml\"]\nSetups=[\"exe\"]\nShellScripts=[\"sh\"]\n\n\nFILE_FORMATS = {file_format: directory \n for directory, file_formats in DIRECTORIES.items() \n for file_format in file_formats} \n\nos.getcwd() #os.getcwd() gets current working directory\npath = str(input(\"Enter Path of the folder you want to organise: \"))\nfiles = glob.glob(path + '/*')\n\ndef Sorter(**kwargs):\n\tfor file in files:\n\t\t\tif Path(file).is_dir():\n\t\t\t\tcontinue\n\t\t\t# print(file)\n\t\t\tfile_extension = file.split(\".\")[-1].lower()\n\t\t\tif file_extension in FILE_FORMATS:\n\t\t\t\tto_move_path = Path(FILE_FORMATS[file_extension]) \n\t\t\t\tif kwargs['all']==1:\n\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\t\tif kwargs['Docs']==1:\n\t\t\t\t\tif file_extension in Documents:\n\t\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\t\tif kwargs['Images']==1:\n\t\t\t\t\tif file_extension in Images:\n\t\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\t\tif kwargs['Videos']==1:\n\t\t\t\t\tif file_extension in Videos:\n\t\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\t\tif kwargs['WebPages']==1:\n\t\t\t\t\tif file_extension in WebPages:\n\t\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\t\tif kwargs['ArchiveFiles']==1:\n\t\t\t\t\tif file_extension in ArchiveFiles:\n\t\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\t\tif kwargs['AudioFiles']==1:\n\t\t\t\t\tif file_extension in AudioFiles:\n\t\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\t\tif kwargs['XML']==1:\n\t\t\t\t\tif file_extension in XML:\n\t\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\t\tif kwargs['Setups']==1:\n\t\t\t\t\tif file_extension in Setups:\n\t\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\t\tif kwargs['ShellScripts']==1:\n\t\t\t\t\tif file_extension in ShellScripts:\n\t\t\t\t\t\tos.makedirs(to_move_path, exist_ok=True)\n\t\t\t\t\t\tshutil.move(file, to_move_path)\n\t\t\n#Check_Box1\nc1=tk.Checkbutton(window, text=\"All\", variable=i1)\nc1.pack()\nc2=tk.Checkbutton(window, text=\"Documents\", variable=i2)\nc2.pack()\nc3=tk.Checkbutton(window, text=\"Images\", variable=i3)\nc3.pack()\nc4=tk.Checkbutton(window, text=\"Videos\", variable=i4)\nc4.pack()\nc5=tk.Checkbutton(window, text=\"Archives\", variable=i5)\nc5.pack()\nc6=tk.Checkbutton(window, text=\"Audio\", variable=i6)\nc6.pack()\nc7=tk.Checkbutton(window, text=\"Exe\", variable=i7)\nc7.pack()\nc8=tk.Checkbutton(window, text=\"ShellScripts\", variable=i7)\nc8.pack()\nc9=tk.Checkbutton(window, text=\"WebPages\", variable=i7)\nc9.pack()\nc10=tk.Checkbutton(window, text=\"WebPages\", variable=i7)\nc10.pack()\n\n\n#Button\nb1=tk.Button(window, text=\"Submit\", command=Submit)\nb1.pack()\n\n\nwindow.mainloop()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"40869807","text":"\"\"\"\nВыведите таблицу размером n×nn×n, заполненную числами от 11 до n2n2 по спирали,\nвыходящей из левого верхнего угла и закрученной по часовой стрелке.\n\n\"\"\"\n\nn=int(input())\n\n\n\n#Заполняем\n\nl=k=1\ni=x=d=r=u=c_i=c_j=0\n\nx=n\n\nwhile k <= (n*n):\n#право\n\tif l==1:\n\t\tl=0\n\t\td=1\n\t\tfor j in range (c_j,x):\n\t\t\tprint (\"пр:\",c_i,j,k)\n\t\t\tk+=1\n\t\tc_j=j\n\t\tc_i+=1\n\n\t\t\n#вниз\n\telif d==1:\n\t\td=0\n\t\tr=1\n\t\tfor i in range (c_i,x):\n\t\t\tprint (\"вн:\",i,c_j,k)\n\t\t\tk+=1\n\t\tc_i=i\n\t\tc_j-=1\n\t\tx-=1\n\t\t\n\n#влево\n\telif r==1:\n\t\tr=0\n\t\tu=1\n\t\tfor j in range (x,c_j,-1):\n\t\t\tprint (\"вл:\",c_i,j,k)\n\t\t\tk+=1\n\t\tc_j=j\n\t\tc_i-=1\n\t\t\n\t\t\n\n#вверх\n\telif u==1:\n\t\tu=0\n\t\tl=1\n\t\tfor i in range (x,c_i,-1):\n\t\t\tprint (\"вв:\",i,c_j,k)\n\t\t\tk+=1\n\t\tc_i=i\n\t\tc_j+=1\n\t\t\n\t\t\n\n\n\n\n\n\n\n","sub_path":"program30_3.py","file_name":"program30_3.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"323457907","text":"'''\nCreated By: Bazil Muzaffar Kotriwala\nStudent ID: 27012336\n'''\n\n\nclass Node:\n\n def __init__(self, item, link = None):\n '''\n This function creates a node and a link\n :param: item and link\n :precondition: None\n :postcondition: None\n :oomplexity: Best Case = Worst Case = O(1), constant time complexity.\n '''\n\n self.item = item\n self.next = link\n\n def __str__(self):\n '''\n This function returns the item in string format\n :param: item and link\n :precondition: None\n :postcondition: None\n :oomplexity: Best Case = Worst Case = O(1), constant time complexity.\n '''\n\n return str(self.item)\n\nclass LinkedList:\n\n def __init__(self):\n '''\n This function creates the linked list by creating the head which acts as a pointer for the linked list and count at start is 0 as list is empty\n :param: None\n :precondition: None\n :postcondition: None\n :complexity: Best Case = Worst Case = O(1), constant time complexity.\n '''\n\n self.head = None\n self.count = 0\n\n def is_empty(self):\n '''\n This function returns the linked list if it is empty i.e. when the count is 0\n :param: None\n :precondition: None\n :postcondition: None\n :complexity: Best Case = Worst Case = O(1), constant time complexity.\n '''\n\n return self.count == 0\n\n def is_full(self):\n '''\n This function tells us that the linked list can never be full, hence if he checks if the linked list is full it will always return false.\n :param: None\n :precondition: None\n :postcondition: None\n :complexity: Best Case = Worst Case = O(1), constant time complexity.\n '''\n\n return False\n\n def reset(self):\n '''\n This function resets the link list to empty as it was at the start when it was created.\n :param: None\n :precondition: None\n :postcondition: None\n :complexity: Best Case = Worst Case = O(1), constant time complexity.\n '''\n\n self.__init__()\n\n def __len__(self):\n '''\n This function returns number of items in the list i.e. the count of the linked list.\n :param: None\n :precondition: None\n :postcondition: None\n :complexity: Best Case = Worst Case = O(1), constant time complexity.\n '''\n\n return self.count\n\n def __get_node__(self, index):\n '''\n This function gets the node of the next item till the end of the list\n :param: index\n :precondition: None\n :postcondition: None\n :complexity: Best Case = O(1), Worst Case = O(n)\n '''\n\n node = self.head\n for i in range(index):\n node = node.next\n return node\n\n def insert(self, index, item):\n '''\n This function is used to insert item into the list\n :param: Index and item to insert\n :precondition: None\n :postcondition: None\n :complexity: Best Case = Worst Case = O(n)\n '''\n\n if index < 0:\n index = 0\n elif index > len(self):\n index = len(self)\n if index == 0:\n self.head = Node(item, self.head)\n else:\n node = self.__get_node__(index - 1)\n node.next = Node(item, node.next)\n self.count += 1\n\n def __getitem__(self, index):\n '''\n This function returns the item at the head\n :param: index\n :precondition: None\n :postcondition: None\n :complexity: Best Case = O(1), Worst Case = O(n)\n '''\n current_node = self.head\n while index > 0:\n current_node = current_node.next\n index -= 1\n return current_node.item\n\n def __setitem__(self, index, value):\n '''\n This function sets the item at the head\n :param: index and value to set\n :precondition: None\n :postcondition: None\n :complexity: Best Case = O(1), Worst Case = O(n)\n '''\n\n current_node = self.head\n while index > 0:\n current_node = current_node.next\n index -= 1\n current_node.item = value\n\nclass SeperateChainingHashTable:\n\n def __init__(self, size, b):\n\n '''\n When an object is created using the SeperateChainingHashTable, a table with linear probing of a default size is created.\n :param: Size of the table (size is a prime number)\n :precondition: None\n :postcondition: None\n :complexity: Best Case = Worst Case = O(1), constant time complexity, since there are single statements being executed.\n '''\n\n self.array = [None] * size\n self.table_size = size\n self.count = 0\n self.b = b\n self.collision_counter = 0\n\n def hash(self, key):\n '''\n This function is the universal hash function which calculates the hash value for the given key.\n :param: The keys in the hash table\n :precondition: None\n :postcondition: None\n :complexity: Best Case = Worst Case = O(n), where n is the length of hash table\n '''\n\n value = 0\n a = 31415\n b = self.b\n for i in range(len(key)):\n value = (ord(key[i]) + a * value) % self.table_size\n a = a * b % (self.table_size - 1)\n return value\n\n def __setitem__(self, key, value):\n '''\n This function creates a linkedlist at the position if the position is empty in the Hash Table or\n updates a value if there is something in the position with the same key or finds a new empty spot if there is\n already something there with a different key.\n :param: Key and its corresponding value\n :precondition: None\n :postcondition: None\n :complexity: Best Case O(1), constant time complexity\n Worst Case O(n), linear time complexity\n '''\n\n position = self.hash(key)\n if self.array[position] is None: # if the slot is empty in the table it sets the value at that position\n self.array[position] = LinkedList() # create a linkedlist at the empty position\n self.array[position].insert(self.array[position].count, (key, value)) # once linkedlist is created, you insert item into the list\n self.count += 1\n return\n elif self.array[position][0][0] == key: # if the same key is found it updates the value at that position\n self.array[position][0] = (key, value)\n return\n else:\n self.array[position].insert(self.array[position].count, (key,value))\n self.collision_counter += 1\n return\n\n def __getitem__(self, key):\n '''\n This function returns the value corresponding to the key at the position in the Hash Table. The function raises\n a KeyError if the key does not exist in the Hash Table\n :param: The key which may or may not exist in the Hash Table\n :precondition: None\n :postcondition: The value is returned corresponding to the key in the hash table or a KeyError if key does not exist\n :complexity: Best Case = Worst Case = O(n)\n '''\n\n position = self.hash(key)\n if self.array[position] is None: # if the linkedlist is empty, raise keyError as key is not found\n raise KeyError\n current = self.array[position].head\n while current.item != None:\n if current.item[0] == key:\n return current.item[1]\n else:\n current = current.next\n raise KeyError # if the is found we return the value at that key\n # if the key is not found, we look for the next position # if the for loop exits without returning means key does\n # not exist the hash table\n\n def __contains__(self, key):\n '''\n This function returns True if key is in the table and False otherwise.\n :param: The key which may or may not exist in the table\n :precondition: A hash table must already exist\n :postcondition: Returns true or false depending on whether the key exists in the table or not\n :complexity: Best Case = Worst Case = O(n), where n is the size of the hash table\n '''\n\n position = self.hash(key)\n if self.array[position] is None: # if the linkedlist is empty, raise keyError as key is not found\n return False\n current = self.array[position].head\n while current.item != None:\n if current.item[0] == key:\n return True # if the same key is found we return true as the key is found\n else:\n current = current.next # if the key is not found, we look for the next position in the hash table\n return False\n\n def no_collisions(self):\n '''\n This function returns the number of collisions\n :param: None\n :precondition: None\n :postcondition: None\n :complexity: Best Case = Worst Case = O(1), constant time complexity.\n '''\n\n return self.collision_counter\n\n\ndef read_file(filename,L):\n\n '''\n This function takes a filename as an input by the user and reads the contents of the file into a hash table, storing each line as a single item in the hash table\n :param: filename inputted by the user\n :precondition: A file must exist from which the contents of the file can be read\n :postcondition: A Hash table is filled with each line in the file stored as a single item in the hash table\n :complexity: Best Case = Worst Case = O(n), where n is the length of the contents in the file, even if the contents are empty or filled the loop will run n times\n '''\n\n infile = open(filename, 'r')\n contents = infile.readlines()\n for i in range(len(contents)):\n L[contents[i].rstrip('\\n')] = contents[i].rstrip('\\n')\n infile.close()\n\nif __name__ == '__main__':\n\n filename = input('Enter the filename: ')\n\n b_list = [1, 27183, 250726]\n table_size = [250727, 402221, 1000081]\n for b in b_list:\n for size in table_size:\n if b == 250726 and size == 250727:\n continue\n h = SeperateChainingHashTable(size, b)\n import timeit\n start = timeit.default_timer()\n read_file(filename, h)\n time_taken = (timeit.default_timer() - start)\n print(time_taken)\n print(h.no_collisions())","sub_path":"Abstract Data Types (ADTs)/HashTable/SeperateChainingHT.py","file_name":"SeperateChainingHT.py","file_ext":"py","file_size_in_byte":10990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"15473368","text":"from time import time\r\nfrom pyspark.sql import SparkSession\r\nfrom pyspark.ml.recommendation import ALS\r\nimport os\r\n'''\r\nTo Run:\r\nspark-submit --conf spark.driver.memory=16g --conf spark.executor.memory=16g Trainer.py\r\n'''\r\n\r\ndef Trainer(spark,df_train,rank,regParam,alpha,K = 500):\r\n output_file = 'ALSModel_%s_%s__%s' %(str(rank),str(regParam),str(alpha))\r\n FileExistFlag = os.system('hadoop fs -test -e %s' %output_file)\r\n if not FileExistFlag == 0:\r\n beg = time()\r\n als = ALS(rank=rank, maxIter=10, regParam=regParam, alpha=alpha, implicitPrefs = True,\r\n userCol=\"user_id_numeric\", itemCol=\"track_id_numeric\", ratingCol=\"count\",\r\n coldStartStrategy=\"drop\")\r\n model = als.fit(df_train)\r\n print('Train Finished')\r\n model.write().overwrite().save(output_file)\r\n end = time()\r\n print('ALSModel_%s_%s__%s Saved. Took %f s' %(str(rank),str(regParam),str(alpha),end-beg))\r\n else:\r\n print('ALSModel_%s_%s__%s Already Exist.' %(str(rank),str(regParam),str(alpha)))\r\n return\r\n\r\nif __name__ == \"__main__\":\r\n spark = SparkSession.builder.appName('main').getOrCreate()\r\n\r\n formatted_train_address = \"data/train_formatted.parquet\"\r\n df_train = spark.read.parquet(formatted_train_address)\r\n print('File Reading Finished')\r\n for rank in [5,10,15]:\r\n for regParam in [0.01,0.1,0.2,0.3,0.5]:\r\n for alpha in [0.5,1,3,5,10]:\r\n Trainer(spark,df_train,rank,regParam,alpha)","sub_path":"Trainer.py","file_name":"Trainer.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"158514569","text":"import asyncio\nimport logging\nfrom typing import Dict, Optional\nimport json\nfrom functools import partial\nfrom dataclasses import dataclass, InitVar\nfrom urllib.parse import urlparse\n\ntry:\n import httpx\nexcept ImportError: # pragma: no cover\n httpx = None # type: ignore\n\ntry:\n import boto3\n from botocore.auth import SigV4Auth\n from botocore.awsrequest import AWSRequest\nexcept ImportError: # pragma: no cover\n boto3 = None # type: ignore\n\n\nfrom .base import WebSocketBackend\nfrom ..exceptions import WebSocketError, ConfigurationError\nfrom ..types import Scope\n\n\ndef get_sigv4_headers(\n method: str,\n url: str,\n data: Optional[bytes] = None,\n region_name: Optional[str] = None,\n) -> Dict:\n session = boto3.Session()\n credentials = session.get_credentials()\n creds = credentials.get_frozen_credentials()\n region = region_name or session.region_name\n\n request = AWSRequest(method=method, url=url, data=data)\n SigV4Auth(creds, \"execute-api\", region).add_auth(request)\n\n return dict(request.headers)\n\n\n@dataclass\nclass WebSocket:\n \"\"\"\n A `WebSocket` connection handler interface for the\n selected `WebSocketBackend` subclass\n \"\"\"\n\n dsn: InitVar[Optional[str]]\n api_gateway_endpoint_url: str\n api_gateway_region_name: Optional[str] = None\n\n def __post_init__(self, dsn: Optional[str]) -> None:\n if boto3 is None: # pragma: no cover\n raise WebSocketError(\"boto3 must be installed to use WebSockets.\")\n\n if httpx is None: # pragma: no cover\n raise WebSocketError(\"httpx must be installed to use WebSockets.\")\n\n if dsn is None:\n raise ConfigurationError(\n \"The `dsn` parameter must be provided for WebSocket connections.\"\n )\n\n self.logger: logging.Logger = logging.getLogger(\"mangum.backends\")\n parsed_dsn = urlparse(dsn)\n if not any((parsed_dsn.hostname, parsed_dsn.path)):\n raise ConfigurationError(\"Invalid value for `dsn` provided.\")\n\n scheme = parsed_dsn.scheme\n self.logger.debug(\n f\"Attempting WebSocket backend connection using scheme: {scheme}\"\n )\n\n if scheme == \"sqlite\":\n self.logger.info(\n \"The `SQLiteBackend` should be only be used for local \"\n \"debugging. It will not work in a deployed environment.\"\n )\n from mangum.backends.sqlite import SQLiteBackend\n\n self._Backend = SQLiteBackend # type: ignore\n\n elif scheme == \"dynamodb\":\n from mangum.backends.dynamodb import DynamoDBBackend\n\n self._Backend = DynamoDBBackend # type: ignore\n\n elif scheme == \"s3\":\n from mangum.backends.s3 import S3Backend\n\n self._Backend = S3Backend # type: ignore\n\n elif scheme in (\"postgresql\", \"postgres\"):\n from mangum.backends.postgresql import PostgreSQLBackend\n\n self._Backend = PostgreSQLBackend # type: ignore\n\n elif scheme == \"redis\":\n from mangum.backends.redis import RedisBackend\n\n self._Backend = RedisBackend # type: ignore\n\n else:\n raise ConfigurationError(f\"{scheme} does not match a supported backend.\")\n\n self.dsn = dsn\n\n self.logger.info(\"WebSocket backend connection established.\")\n\n async def load_scope(self, backend: WebSocketBackend, connection_id: str) -> Scope:\n loaded_scope = await backend.retrieve(connection_id)\n scope = json.loads(loaded_scope)\n scope.update(\n {\n \"query_string\": scope[\"query_string\"].encode(),\n \"headers\": [[h[0].encode(), h[1].encode()] for h in scope[\"headers\"]],\n \"client\": tuple(scope[\"client\"]),\n \"server\": tuple(scope[\"server\"]),\n }\n )\n\n return scope\n\n async def save_scope(\n self, backend: WebSocketBackend, connection_id: str, scope: Scope\n ) -> None:\n scope.update(\n {\n \"query_string\": scope[\"query_string\"].decode(),\n \"headers\": [[h[0].decode(), h[1].decode()] for h in scope[\"headers\"]],\n }\n )\n json_scope = json.dumps(scope)\n await backend.save(connection_id, json_scope=json_scope)\n\n async def on_connect(self, connection_id: str, initial_scope: Scope) -> None:\n self.logger.debug(\"Creating scope entry for %s\", connection_id)\n async with self._Backend(self.dsn) as backend: # type: ignore\n await self.save_scope(backend, connection_id, initial_scope)\n\n async def on_message(self, connection_id: str) -> Scope:\n self.logger.debug(\"Retrieving scope entry for %s\", connection_id)\n async with self._Backend(self.dsn) as backend: # type: ignore\n scope = await self.load_scope(backend, connection_id)\n return scope\n\n async def on_disconnect(self, connection_id: str) -> None:\n self.logger.debug(\"Deleting scope entry for %s\", connection_id)\n async with self._Backend(self.dsn) as backend: # type: ignore\n await backend.delete(connection_id)\n\n async def post_to_connection(self, connection_id: str, body: bytes) -> None:\n async with httpx.AsyncClient() as client:\n await self._post_to_connection(connection_id, client=client, body=body)\n\n async def delete_connection(self, connection_id: str) -> None:\n async with httpx.AsyncClient() as client:\n await self._request_to_connection(\"DELETE\", connection_id, client=client)\n\n async def _post_to_connection(\n self,\n connection_id: str,\n *,\n client: \"httpx.AsyncClient\",\n body: bytes,\n ) -> None: # pragma: no cover\n response = await self._request_to_connection(\n \"POST\", connection_id, client=client, body=body\n )\n\n if response.status_code == 410:\n await self.on_disconnect(connection_id)\n elif response.status_code != 200:\n raise WebSocketError(f\"Error: {response.status_code}\")\n\n async def _request_to_connection(\n self,\n method: str,\n connection_id: str,\n *,\n client: \"httpx.AsyncClient\",\n body: Optional[bytes] = None,\n ) -> \"httpx.Response\":\n loop = asyncio.get_event_loop()\n url = f\"{self.api_gateway_endpoint_url}/{connection_id}\"\n headers = await loop.run_in_executor(\n None,\n partial(\n get_sigv4_headers,\n method,\n url,\n body,\n self.api_gateway_region_name,\n ),\n )\n\n return await client.request(method, url, content=body, headers=headers)\n","sub_path":"mangum/backends/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"300553257","text":"# coding:utf-8\nimport pymysql\nimport configparser\n\nconn = pymysql.connect(host='10.20.5.3', user='root', password='Isysc0re', port=63306,\n db='cloudteam', cursorclass=pymysql.cursors.DictCursor) # 使用字典游标查询)\n\ncf = configparser.ConfigParser()\ncf.read(\"/home/airflow/airflow/dags/cloudteam_dev/start_time.cnf\")\ncf.read(\"/home/airflow/airflow/dags/cloudteam_dev/end_time.cnf\")\noptions_start = cf['start_time']\noptions_end = cf['end_time']\n\nstart_time = options_start['start_time']\nend_time = options_end['end_time']\n\n# start_time = '2020-07-01'\n# end_time = '2020-08-01'\n\ndef getPros():\n\n if (start_time == None and start_time == None):\n selectPros = '''\n select product_id from cloudteam_data_warehouse.st_production_daily_record record\n where record.ymd = date_format(now(),'%Y-%m-%d') \n group by product_id\n '''\n else:\n selectPros = '''\n select product_id from cloudteam_data_warehouse.st_production_daily_record record\n where record.ymd >= '%s'\n and record.ymd <= '%s'\n group by product_id\n ''' % (start_time, end_time)\n resultArray = []\n cursor.execute(selectPros)\n for row3 in cursor.fetchall():\n resultArray.append(row3['product_id'])\n\n return resultArray\n\n\nwith conn.cursor() as cursor:\n\n # if (options_start['start_time'] == None and options_end['end_time'] == None):\n if (start_time == None and start_time == None):\n selectPros = '''\n select product_id,ymd from cloudteam_data_warehouse.st_production_daily_record record\n where record.ymd = date_format(now(),'%Y-%m-%d') \n group by record.ymd,product_id\n '''\n else:\n selectPros = '''\n select product_id,ymd from cloudteam_data_warehouse.st_production_daily_record record\n where record.ymd >= '%s'\n and record.ymd <= '%s'\n group by record.ymd,product_id\n ''' %(start_time,end_time)\n\n cursor.execute(selectPros)\n\n for row in cursor.fetchall():\n productId = row['product_id']\n ymd = row['ymd']\n #根据产品查出产品所使用的设备列表\n selectEquips = '''\n select equipRel.equipment_id from isyscore_product_sequence_rel sequenceRel \n left join isyscore_pro_seq_equip_rel equipRel \n on sequenceRel.id = equipRel.seq_pro_rel_id\n where sequenceRel.del_flag = '0' and equipRel.del_flag = '0'\n and sequenceRel.product_id = '%s'\n and equipRel.is_select = '1'\n ''' %(productId)\n cursor.execute(selectEquips)\n for row in cursor.fetchall():\n equipmentId = row['equipment_id']\n selectEquipPros = '''\n select sequenceRel.product_id from isyscore_pro_seq_equip_rel equipRel\n left join isyscore_product_sequence_rel sequenceRel \n on sequenceRel.id = equipRel.seq_pro_rel_id\n where sequenceRel.del_flag = '0' and equipRel.del_flag = '0'\n and equipRel.equipment_id = '%s'\n group by sequenceRel.product_id\n ''' %(equipmentId)\n cursor.execute(selectEquipPros)\n equipSelectProIdArray = []\n for row1 in cursor.fetchall():\n prodId = row1['product_id']\n if(prodId in getPros()):\n equipSelectProIdArray.append(prodId)\n else:\n continue\n totalCost = 0\n currentCost = 0\n for index in range(len(equipSelectProIdArray)):\n proId = equipSelectProIdArray[0]\n #sum * equipment time\n selectTime = '''\n select distinct sequenceRel.sequence_standare_time time from isyscore_pro_seq_equip_rel equipRel\n left join isyscore_product_sequence_rel sequenceRel \n on sequenceRel.id = equipRel.seq_pro_rel_id\n where sequenceRel.del_flag = '0' and equipRel.del_flag = '0'\n and equipRel.equipment_id = '%s'\n and sequenceRel.product_id = '%s'\n ''' %(equipmentId,proId)\n cursor.execute(selectTime)\n stardardTime = cursor.fetchone() #当前工序的标准工时\n selectPassNum = '''\n select actural_pass_num from cloudteam_data_warehouse.st_production_daily_record record\n where record.ymd = '%s' and record.product_id = '%s'\n and record.is_last = 1\n ''' %(ymd,proId)\n cursor.execute(selectPassNum)\n passNum = cursor.fetchone() #当前产品的合格数量\n caculateTime = stardardTime['time']*int(passNum['actural_pass_num'])\n totalCost+=caculateTime\n if(productId == proId):\n currentCost = caculateTime\n\n ratio = currentCost/totalCost #分摊比例\n selectEquipCost = '''\n select cost from cloudteam_data_warehouse.st_equip_repair_info\n where ymd = '%s' and equip_id = '%s'\n ''' %(ymd[0:7],equipmentId)\n cursor.execute(selectEquipCost)\n costObj = cursor.fetchone()\n cost = costObj['cost'] #设备的维修平均一天的总费用\n proEquipCost = cost*float(ratio) #当前设备在这天分摊到该产品总的维修费\n\n selectEquipType = '''\n select type from cloudteam_data_warehouse.st_equip_repair_info\n where equip_id = '%s'\n group by equip_id\n ''' %(equipmentId)\n cursor.execute(selectEquipType)\n type = cursor.fetchone()\n typeCode = type['type']\n\n insertSql = '''\n insert into cloudteam_data_warehouse.st_equip_pro_repair_cost values\n (%s,%s,%s,%s,%s)\n '''\n\n cursor.execute(insertSql,[ymd,equipmentId,productId,proEquipCost,typeCode])\n\n conn.commit()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"demo/airflow/equipment_depreciation/per_pro_equip_repair_into_db.py","file_name":"per_pro_equip_repair_into_db.py","file_ext":"py","file_size_in_byte":6256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"483479081","text":"from kimonet.system.generators import regular_system, crystal_system\nfrom kimonet.analysis import visualize_system, TrajectoryAnalysis\nfrom kimonet.system.molecule import Molecule\nfrom kimonet import system_test_info\nfrom kimonet.core.processes.couplings import forster_coupling, dexter_coupling, forster_coupling_extended\nfrom kimonet.core.processes.decays import einstein_radiative_decay\nfrom kimonet.core.processes import GoldenRule, DecayRate, DirectRate\nfrom kimonet.system.vibrations import MarcusModel, LevichJortnerModel, EmpiricalModel\nfrom kimonet.fileio import store_trajectory_list, load_trajectory_list\nfrom kimonet.analysis import plot_polar_plot\nfrom kimonet import calculate_kmc, calculate_kmc_parallel\nfrom kimonet.system.state import State\nimport numpy as np\n\n# list of transfer functions by state\ntransfer_scheme = [GoldenRule(initial=('s1', 'gs'), final=('gs', 's1'),\n electronic_coupling_function=forster_coupling,\n description='Forster')\n ]\n\n# list of decay functions by state\ndecay_scheme = [DecayRate(initial='s1', final='gs',\n decay_rate_function=einstein_radiative_decay,\n description='singlet_radiative_decay')\n ]\n\nmolecule = Molecule(states=[State(label='gs', energy=0.0), # eV\n State(label='s1', energy=4.0)], # eV\n vibrations=MarcusModel(reorganization_energies={('s1', 'gs'): 0.08, # eV\n ('gs', 's1'): 0.08},\n temperature=300), # Kelvin\n transition_moment={('s1', 'gs'): [0.1, 0.0]}, # Debye\n decays=decay_scheme,\n )\n\n\n# physical conditions of the system\nconditions = {'refractive_index': 1}\n\n# define system as a crystal\nsystem = crystal_system(conditions=conditions,\n molecules=[molecule], # molecule to use as reference\n scaled_site_coordinates=[[0.0, 0.0]],\n unitcell=[[5.0, 1.0],\n [1.0, 5.0]],\n dimensions=[2, 2], # supercell size\n orientations=[[0.0, 0.0, np.pi/2]]) # if element is None then random, if list then Rx Ry Rz\n\n# set initial exciton\nsystem.add_excitation_index('s1', 0)\n\n# set additional system parameters\nsystem.transfer_scheme = transfer_scheme\nsystem.cutoff_radius = 8 # interaction cutoff radius in Angstrom\n\n# some system analyze functions\nsystem_test_info(system)\nvisualize_system(system)\nvisualize_system(system, dipole='s1')\n\n# do the kinetic Monte Carlo simulation\ntrajectories = calculate_kmc(system,\n num_trajectories=5, # number of trajectories that will be simulated\n max_steps=100000, # maximum number of steps for trajectory allowed\n silent=False)\n\n# specific trajectory plot\ntrajectories[0].plot_graph().show()\ntrajectories[0].plot_2d().show()\n\n# resulting trajectories analysis\nanalysis = TrajectoryAnalysis(trajectories)\n\nfor state in analysis.get_states():\n print('\\nState: {}\\n--------------------------------'.format(state))\n print('diffusion coefficient: {:9.5e} Angs^2/ns'.format(analysis.diffusion_coefficient(state)))\n print('lifetime: {:9.5e} ns'.format(analysis.lifetime(state)))\n print('diffusion length: {:9.5e} Angs'.format(analysis.diffusion_length(state)))\n print('diffusion tensor (angs^2/ns)')\n print(analysis.diffusion_coeff_tensor(state))\n\n print('diffusion length tensor (Angs)')\n print(analysis.diffusion_length_square_tensor(state))\n\n plot_polar_plot(analysis.diffusion_coeff_tensor(state),\n title='Diffusion', plane=[0, 1])\n\n plot_polar_plot(analysis.diffusion_length_square_tensor(state),\n title='Diffusion length square', crystal_labels=True, plane=[0, 1])\n\n\nanalysis.plot_excitations('s1').show()\nanalysis.plot_2d('s1').show()\nanalysis.plot_distances('s1').show()\nanalysis.plot_histogram('s1').show()\nanalysis.plot_histogram('s1').savefig('histogram_s1.png')\n\nstore_trajectory_list(trajectories, 'example_simple.h5')\n","sub_path":"examples/2d_simple.py","file_name":"2d_simple.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"572262380","text":"import logging\n\nfrom cliff.command import Command\nfrom cliff.lister import Lister\nfrom cliff.show import ShowOne\n\n\nclass IntraExtensionCreate(Command):\n \"\"\"Create a new Intra_Extension.\"\"\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(IntraExtensionCreate, self).get_parser(prog_name)\n parser.add_argument(\n 'name',\n metavar='',\n help='New IntraExtension name',\n )\n parser.add_argument(\n '--policy_model',\n metavar='',\n help='Policy model name (Template for the new IntraExtension)',\n )\n parser.add_argument(\n '--description',\n metavar='',\n help='New IntraExtension description',\n default=\"\"\n )\n return parser\n\n def take_action(self, parsed_args):\n post_data = {\n \"name\": parsed_args.name,\n \"policymodel\": parsed_args.policy_model,\n \"description\": parsed_args.description\n }\n ie = self.app.get_url(\"/v3/OS-MOON/intra_extensions\", post_data=post_data, authtoken=True)\n if \"id\" not in ie:\n raise Exception(\"Error in command {}\".format(ie))\n self.app.stdout.write(\"IntraExtension created: {}\\n\".format(ie[\"id\"]))\n return\n\n\nclass IntraExtensionList(Lister):\n \"\"\"List all Intra_Extensions.\"\"\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(IntraExtensionList, self).get_parser(prog_name)\n return parser\n\n def take_action(self, parsed_args):\n ie = self.app.get_url(\"/v3/OS-MOON/intra_extensions\", authtoken=True)\n if \"intra_extensions\" not in ie:\n raise Exception(\"Error in command {}\".format(ie))\n return (\n (\"id\",),\n ((_id, ) for _id in ie[\"intra_extensions\"])\n )\n\n\nclass IntraExtensionDelete(Command):\n \"\"\"Delete an Intra_Extension.\"\"\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(IntraExtensionDelete, self).get_parser(prog_name)\n parser.add_argument(\n 'uuid',\n metavar='',\n help='IntraExtension UUID',\n )\n return parser\n\n def take_action(self, parsed_args):\n ie = self.app.get_url(\"/v3/OS-MOON/intra_extensions/{}\".format(parsed_args.uuid),\n method=\"DELETE\",\n authtoken=True)\n return\n\n\nclass IntraExtensionShow(ShowOne):\n \"\"\"Show detail about one Intra_Extension.\"\"\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(IntraExtensionShow, self).get_parser(prog_name)\n parser.add_argument(\n 'uuid',\n metavar='',\n help='IntraExtension UUID',\n )\n return parser\n\n def take_action(self, parsed_args):\n ie = self.app.get_url(\"/v3/OS-MOON/intra_extensions/{}\".format(parsed_args.uuid), authtoken=True)\n if \"intra_extensions\" not in ie:\n raise Exception(\"Error in command {}\".format(ie))\n try:\n columns = (\n \"id\",\n \"name\",\n \"description\",\n \"tenant\",\n \"enabled\",\n \"model\",\n \"genre\"\n )\n data = (\n ie[\"intra_extensions\"][\"id\"],\n ie[\"intra_extensions\"][\"name\"],\n ie[\"intra_extensions\"][\"description\"],\n ie[\"intra_extensions\"][\"tenant\"],\n ie[\"intra_extensions\"][\"enabled\"],\n ie[\"intra_extensions\"][\"model\"],\n ie[\"intra_extensions\"][\"genre\"]\n )\n return columns, data\n except Exception as e:\n self.app.stdout.write(str(e))\n\n\nclass TenantSet(Command):\n \"\"\"Set the tenant for a intra_extension.\"\"\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(TenantSet, self).get_parser(prog_name)\n parser.add_argument(\n 'intraextension_uuid',\n metavar='',\n help='IntraExtension UUID',\n )\n parser.add_argument(\n 'tenant_name',\n metavar='',\n help='Tenant Name',\n )\n return parser\n\n def take_action(self, parsed_args):\n self.app.get_url(\"/v3/OS-MOON/intra_extensions/{}/tenant\".format(parsed_args.intraextension_uuid),\n post_data={\"tenant_id\": parsed_args.tenant_name},\n authtoken=True)\n\n","sub_path":"moonclient/intraextension.py","file_name":"intraextension.py","file_ext":"py","file_size_in_byte":4754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"304348879","text":"import os\nimport cv2\nimport pickle\n\nctr = 0\ncap = cv2.VideoCapture(0)\ncap.set(3, 640) #WIDTH\ncap.set(4, 480) #HEIGHT\n\nface_cascade = cv2.CascadeClassifier('weights/haarcascade_frontalface_default.xml')\n\n# Ask user for subject's name\nname = raw_input()\n\n# Check if \"img/name\" exists, if not, create \"img/name\"\nif not os.path.exists('img/'+name):\n os.makedirs('img/'+name)\n\nname = name+'/'\nwhile(True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n # Frame operator\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n # Display Frame\n for (x,y,w,h) in faces:\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = frame[y:y+h, x:x+w]\n img_item = \"img/\"+name+str(ctr)+\".png\"\n # Save image as \"img/name/ctr.png\" to be used for training\n cv2.imwrite(img_item, roi_color)\n cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\n ctr += 1\n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Release capture\ncap.release()\ncv2.destroyAllWindows()","sub_path":"face_capture.py","file_name":"face_capture.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"99840445","text":"import math\r\n\r\ndef insertion_cost(mes, j):\r\n return 1\r\n\r\n\r\ndef deletion_cost(mes, j):\r\n return 1\r\n\r\n\r\nadj_chars = [('a', 'q'), ('a', 's'), ('a', 'z'), ('b', 'g'), ('b', 'm'),\r\n ('b', 'n'), ('b', 'v'), ('c', 'd'),\r\n ('c', 'v'), ('c', 'x'), ('d', 'c'), ('d', 'e'), ('d',\r\n 'f'),\r\n ('d', 's'), ('e', 'd'), ('e', 'r'),\r\n ('e', 'w'), ('f', 'd'), ('f', 'g'), ('f', 'r'), ('f',\r\n 'v'),\r\n ('g', 'b'), ('g', 'f'), ('g', 'h'),\r\n ('g', 't'), ('h', 'g'), ('h', 'j'), ('h', 'm'), ('h',\r\n 'n'),\r\n ('h', 'y'), ('i', 'k'), ('i', 'o'),\r\n ('i', 'u'), ('j', 'h'), ('j', 'k'), ('j', 'u'), ('k',\r\n 'i'),\r\n ('k', 'j'), ('k', 'l'), ('l', 'k'),\r\n ('l', 'o'), ('m', 'b'), ('m', 'h'), ('n', 'b'), ('n',\r\n 'h'),\r\n ('o', 'i'), ('o', 'l'), ('o', 'p'),\r\n ('p', 'o'), ('q', 'a'), ('q', 'w'), ('r', 'e'), ('r',\r\n 'f'),\r\n ('r', 't'), ('s', 'a'), ('s', 'd'),\r\n ('s', 'w'), ('s', 'x'), ('t', 'g'), ('t', 'r'), ('t',\r\n 'y'),\r\n ('u', 'i'), ('u', 'j'), ('u', 'y'),\r\n ('v', 'b'), ('v', 'c'), ('v', 'f'), ('w', 'e'), ('w',\r\n 'q'),\r\n ('w', 's'), ('x', 'c'), ('x', 's'),\r\n ('x', 'z'), ('y', 'h'), ('y', 't'), ('y', 'u'), ('z', 'a'), ('z', 'x')]\r\n\r\n\r\ndef subst_cost(query, message, i, j):\r\n if query[i-1] == message[j-1]:\r\n return 0\r\n elif (query[i-1], message[j-1]) in adj_chars:\r\n return 1.75\r\n else:\r\n return 2\r\n\r\n\r\ndef edit_matrix(query, message, thresh):\r\n m = len(query) + 1\r\n n = len(message) + 1\r\n\r\n chart = {(0, 0): 0}\r\n for i in range(1, m):\r\n chart[i, 0] = chart[i-1, 0] + insertion_cost(query, i)\r\n for j in range(1, n):\r\n chart[0, j] = chart[0, j-1] + deletion_cost(message, j)\r\n for i in range(1, m):\r\n exceeded_max = True\r\n for j in range(1, n):\r\n chart[i, j] = min(\r\n chart[i-1, j] + deletion_cost(query, i),\r\n chart[i, j-1] + insertion_cost(message, j),\r\n chart[i-1, j-1] + subst_cost(query, message, i, j)\r\n )\r\n # NEW : Check to see if any are below the thresh\r\n exceeded_max = exceeded_max and (chart[i, j] >= thresh)\r\n # NEW : exceeded_max means already not the minimum edit_distance, won't be the typo\r\n if exceeded_max: # NEW : this means all exceeded the maximum\r\n chart[len(query), len(message)] = thresh + 1 # NEW : set it to above the maximum\r\n return chart\r\n return chart\r\n\r\n\r\ndef edit_distance(query, message, thresh):\r\n query = query.lower()\r\n message = message.lower()\r\n\r\n matrix = edit_matrix(query, message, thresh)\r\n return matrix[(len(query), len(message))]\r\n\r\n\r\ndef closest_word(query, alt_opts):\r\n \"\"\"\r\n Returns a tuple (res, dist) where res is the closest word query is to in \r\n alt_opts and dist is the edit distance. \r\n \"\"\"\r\n result = []\r\n curr_min = math.inf # NEW: Keep track of the miniumum edit distance\r\n for i in range(len(alt_opts)):\r\n if abs(len(query) - len(alt_opts[i])) <= 3:\r\n dist = edit_distance(query, alt_opts[i], curr_min)\r\n if dist < curr_min:\r\n curr_min = dist\r\n result.append((alt_opts[i], dist))\r\n result.sort(key=lambda t: t[1])\r\n if result: \r\n return result[0]\r\n else: \r\n return None\r\n","sub_path":"app/jokes/controllers/typo_lib.py","file_name":"typo_lib.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"281261415","text":"\nimport argparse\nfrom math import ceil, log\n\n\ndef format_months(months):\n years_str = months_str = separator = ''\n years = months // 12\n months = months % 12\n if years != 0:\n years_str += f'{years} year'\n if years != 1:\n years_str += 's'\n if months != 0:\n months_str += f'{months} month'\n if months != 1:\n months_str += 's'\n if not(months == 0 or years == 0):\n separator += ' and '\n\n return years_str + separator + months_str\n\n\ndef calc_months(principal, monthly_payment, interest):\n months = ceil(log(monthly_payment / (monthly_payment - interest * principal), 1 + interest))\n print(f' You need {format_months(months)} to repay this credit!')\n overpayment = principal - monthly_payment * months\n print(f'Overpayment = {overpayment}')\n\n\ndef calc_annuity(principal, months, interest):\n annuity = ceil(principal * (interest * pow(1 + interest, months) / (pow(1 + interest, months) - 1)))\n print(f'Your annuity payment = {annuity}!')\n overpayment = principal - annuity * months\n print(f'Overpayment = {overpayment}')\n\n\ndef calc_principal(monthly_payment, months, interest):\n principal = ceil(monthly_payment / (interest * pow(1 + interest, months) / (pow(1 + interest, months) - 1)))\n print(f'Your credit principal = {principal}!')\n overpayment = principal - monthly_payment * months\n print(f'Overpayment = {overpayment}')\n\n\ndef calc_differentiated_payments(principal, months, interest):\n total_payment = 0\n for month in range(1, months + 1):\n payment = ceil(principal / months + interest * (principal - (principal * (month - 1)) / months))\n total_payment += payment\n print(f'Month {month}: {payment}')\n overpayment = principal - total_payment\n print(f'Overpayment = {overpayment}')\n\n\ndef correct_args(principal, payment, periods, interest):\n sum_ = 0\n if principal is not None:\n sum_ += 1\n if payment is not None:\n sum_ += 1\n if periods is not None:\n sum_ += 1\n if interest is not None:\n sum_ += 1\n if sum_ < 3:\n return False\n return True\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--type', type=str)\n parser.add_argument('--principal', type=int)\n parser.add_argument('--payment', type=int)\n parser.add_argument('--periods', type=int)\n parser.add_argument('--interest', type=float)\n args = parser.parse_args()\n\n if not correct_args(args.principal, args.payment, args.periods, args.interest):\n print('Incorrect parameters')\n elif args.type != 'diff' and args.type != 'annuity' or args.type is None:\n print('Incorrect parameters')\n elif args.type == 'diff':\n if args.principal < 0 or args.periods < 0 or args.interest < 0:\n print('Incorrect parameters')\n else:\n calc_differentiated_payments(args.principal, args.periods, args.interest / 1200)\n else:\n if args.principal is None:\n if args.payment < 0 or args.periods < 0 or args.interest < 0:\n print('Incorrect parameters')\n else:\n calc_principal(args.payment, args.periods, args.interest / 1200)\n elif args.payment is None:\n if args.principal < 0 or args.periods < 0 or args.interest < 0:\n print('Incorrect parameters')\n else:\n calc_annuity(args.principal, args.periods, args.interest / 1200)\n elif args.periods is None:\n if args.principal < 0 or args.payment < 0 or args.interest < 0:\n print('Incorrect parameters')\n else:\n calc_months(args.principal, args.payment, args.interest / 1200)\n\nmain()\n","sub_path":"creditcalc.py","file_name":"creditcalc.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"407044938","text":"'''\r\nCopyright (C) 2018 CG Cookie\r\nhttps://github.com/CGCookie/retopoflow\r\n This program is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see .\r\n'''\r\n\r\nimport inspect\r\n\r\nimport bpy\r\nimport gpu\r\nimport mathutils\r\nfrom bpy_extras import view3d_utils\r\nfrom gpu_extras.batch import batch_for_shader\r\nfrom mathutils import Matrix, Vector\r\nfrom mathutils.bvhtree import BVHTree\r\nfrom mathutils.geometry import intersect_line_sphere\r\n\r\n\r\nclass CookieCutter_FSM:\r\n '''- register finite state machine state callbacks with the CookieCutter.FSM_State(state) function decorator\r\n - state can be any string that is a state in your FSM\r\n - Must provide at least a 'main' state\r\n - return values of each FSM_State decorated function tell FSM which state to switch into\r\n - None, '', or no return: stay in same state'''\r\n class FSM_State:\r\n @staticmethod\r\n def get_state(state, substate):\r\n return '%s__%s' % (str(state), str(substate))\r\n\r\n def __init__(self, state, substate='main'):\r\n self.state = state\r\n self.substate = substate\r\n\r\n def __call__(self, fn):\r\n self.fn = fn\r\n self.fnname = fn.__name__\r\n\r\n def run(*args, **kwargs):\r\n try:\r\n return fn(*args, **kwargs)\r\n except Exception as e:\r\n print('Caught exception in function \"%s\" (\"%s\", \"%s\")' % (\r\n self.fnname, self.state, self.substate\r\n ))\r\n print (e)\r\n return\r\n run.fnname = self.fnname\r\n run.fsmstate = CookieCutter_FSM.FSM_State.get_state(self.state, self.substate)\r\n return run\r\n\r\n def find_fns(self, key):\r\n c = type(self)\r\n objs = [getattr(c,k) for k in dir(c)]\r\n fns = [fn for fn in objs if inspect.isfunction(fn)]\r\n return [(getattr(fn,key),fn) for fn in fns if hasattr(fn,key)]\r\n\r\n def fsm_init(self):\r\n self._state_next = 'main'\r\n self._state = None\r\n self._fsm_states = {}\r\n for (m, fn) in self.find_fns('fsmstate'):\r\n assert m not in self._fsm_states, 'Duplicate states registered!'\r\n self._fsm_states[m] = fn\r\n\r\n def _fsm_call(self, state, substate='main', fail_if_not_exist=False):\r\n s = CookieCutter_FSM.FSM_State.get_state(state, substate)\r\n if s not in self._fsm_states:\r\n assert not fail_if_not_exist\r\n return\r\n try:\r\n return self._fsm_states[s](self)\r\n except Exception as e:\r\n print('Caught exception in state (\"%s\")' % (s))\r\n print(e)\r\n return\r\n\r\n def fsm_update(self):\r\n if self._state_next is not None and self._state_next != self._state:\r\n if self._fsm_call(self._state, substate='can exit') == False:\r\n # print('Cannot exit %s' % str(self._state))\r\n self._state_next = None\r\n return\r\n if self._fsm_call(self._state_next, substate='can enter') == False:\r\n # print('Cannot enter %s' % str(self._state_next))\r\n self._state_next = None\r\n return\r\n # print('%s -> %s' % (str(self._state), str(self._state_next)))\r\n self._fsm_call(self._state, substate='exit')\r\n self._state = self._state_next\r\n self._fsm_call(self._state, substate='enter')\r\n self._state_next = self._fsm_call(self._state, fail_if_not_exist=True)\r\n\r\n\r\nclass ModalCommon:\r\n \"\"\"Common Operator methods for garment editing are defined here\"\"\"\r\n\r\n _handle_draw_verts = None\r\n _handle_draw_text = None\r\n\r\n patter_segments_cache = {}\r\n garment_index = 0\r\n event = None\r\n context = None\r\n allow_nav = False\r\n done = False\r\n\r\n @staticmethod\r\n def draw_text(self, context):\r\n '''Cos self is passed by handler'''\r\n pass\r\n\r\n @staticmethod\r\n def draw_px(self, context):\r\n '''Cos self is passed by handler'''\r\n pass\r\n\r\n shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR')\r\n\r\n @staticmethod\r\n def visible_objects_and_duplis(context):\r\n \"\"\"Loop over (object, matrix) pairs (mesh only)\"\"\"\r\n for obj in context.visible_objects:\r\n if obj.type == 'CURVE':\r\n yield (obj)\r\n\r\n @staticmethod\r\n def scene_objects_and_duplis(context):\r\n \"\"\"Loop over (object, matrix) pairs (mesh only)\"\"\"\r\n for obj in context.scene.objects:\r\n if obj.type == 'CURVE':\r\n yield (obj)\r\n\r\n @staticmethod\r\n def get_segments_len(segments_points):\r\n '''Return segments points len '''\r\n out_segments_lens = []\r\n for points in segments_points:\r\n previous_point = points[0]\r\n segment_len = 0\r\n for point in points:\r\n point_diff_vec = point - previous_point\r\n segment_len += point_diff_vec.length\r\n previous_point = point\r\n out_segments_lens.append(segment_len)\r\n return out_segments_lens\r\n\r\n @staticmethod\r\n def curve_resample(curve_obj, resolution):\r\n '''Return list of points for each 2D curve segment. Assume curve obj, has segment count dict assigned '''\r\n spline = curve_obj.data.splines[0]\r\n points_count = len(spline.bezier_points)\r\n output_points = []\r\n for i in range(points_count):\r\n knot1 = spline.bezier_points[i].co\r\n handle1 = spline.bezier_points[i].handle_right\r\n knot2 = spline.bezier_points[(i+1) % points_count].co\r\n handle2 = spline.bezier_points[(i+1) % points_count].handle_left\r\n interpolated = mathutils.geometry.interpolate_bezier(knot1, handle1, handle2, knot2, resolution)\r\n output_points.append([curve_obj.matrix_world @ point for point in interpolated])\r\n return output_points\r\n\r\n def obj_ray_cast(self, obj, ray_origin, ray_target):\r\n \"\"\"Wrapper for ray casting that moves the ray into object space\"\"\"\r\n # get the ray relative to the object\r\n ray_direction = ray_target - ray_origin\r\n sourceTri_BVHT = self.construct_pattern_BVHTree(obj) # [0,1,2] - polygon == vert indices list\r\n # location, normal, index, dist =\r\n return sourceTri_BVHT.ray_cast(ray_origin, ray_direction, 600)\r\n\r\n def curve_ray_cast(self, obj, ray_origin, ray_target):\r\n \"\"\"Wrapper for ray casting that moves the ray into object space\"\"\"\r\n # get the ray relative to the object\r\n ray_direction = ray_target - ray_origin\r\n resampled_curve_segments = self.patter_segments_cache[obj.name]\r\n segments_points_flat = []\r\n for segment in resampled_curve_segments: # add cloth sillayette\r\n segments_points_flat.extend(segment[:-1])\r\n # cast the ray\r\n sourceTri_BVHT = BVHTree.FromPolygons(segments_points_flat, [tuple(i for i in range(len(\r\n segments_points_flat)))], all_triangles=False) # [0,1,2] - polygon == vert indices list\r\n # location, normal, index, dist =\r\n return sourceTri_BVHT.ray_cast(ray_origin, ray_direction, 600)\r\n\r\n def construct_pattern_BVHTree(self, obj):\r\n # give world space points ( multiplied by obj.mat_world)\r\n resampled_curve_segments = self.patter_segments_cache[obj.name]\r\n segments_points_flat = []\r\n for segment in resampled_curve_segments: # add cloth sillayette\r\n segments_points_flat.extend(segment[:-1])\r\n\r\n # cast the ray\r\n sourceTri_BVHT = BVHTree.FromPolygons(segments_points_flat, [tuple(i for i in range(len(\r\n segments_points_flat)))], all_triangles=False) # [0,1,2] - polygon == vert indices list\r\n return sourceTri_BVHT\r\n\r\n def find_curve_under_cursor(self, context, event):\r\n \"\"\"Run this function on left mouse, execute the ray cast\"\"\"\r\n # get the context arguments\r\n scene = context.scene\r\n region = context.region\r\n rv3d = context.region_data\r\n coord = event.mouse_region_x, event.mouse_region_y\r\n\r\n # get the ray from the viewport and mouse\r\n view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)\r\n ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)\r\n\r\n ray_target = ray_origin + view_vector\r\n\r\n # cast rays and find the closest object\r\n best_length_squared = -1.0\r\n best_obj = None\r\n\r\n for obj in self.visible_objects_and_duplis(context):\r\n if obj.type == 'CURVE':\r\n hit_world, normal, face_index, dist = self.obj_ray_cast(obj, ray_origin, ray_target)\r\n if hit_world is not None:\r\n length_squared = (hit_world - ray_origin).length_squared\r\n if best_obj is None or length_squared < best_length_squared:\r\n best_length_squared = length_squared\r\n best_obj = obj\r\n\r\n # now we have the object under the mouse cursor,\r\n return best_obj\r\n\r\n def hit_obj_pos(self, context, hit_obj):\r\n ''' Return index of pin closest to mouse'''\r\n \"\"\"Run this function on left mouse, execute the ray cast\"\"\"\r\n region = context.region\r\n rv3d = context.region_data\r\n coord = self.event.mouse_region_x, self.event.mouse_region_y\r\n\r\n # get the ray from the viewport and mouse\r\n view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)\r\n ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)\r\n\r\n ray_target = ray_origin + view_vector\r\n # cast rays and find the closest object\r\n hit_world, normal, face_index, dist = self.obj_ray_cast(hit_obj, ray_origin, ray_target)\r\n hit_local = hit_obj.matrix_world.inverted() @ hit_world if hit_world else None\r\n if hit_local is not None:\r\n hit_local.z = 0 # cos it is flat\r\n return hit_local\r\n\r\n def assign_target_obj_to_garment(self, target_obj):\r\n for pattern in self.garment.sewing_patterns:\r\n if pattern.pattern_obj == target_obj:\r\n return\r\n self.garment.sewing_patterns.add()\r\n self.garment.sewing_patterns[-1].pattern_obj = target_obj\r\n\r\n # @CookieCutter_FSM.FSM_State('main')\r\n # def modal_main(self):\r\n # pass\r\n\r\n def end_cancel(self):\r\n self.disable_handlers()\r\n bpy.ops.ed.undo()\r\n bpy.ops.garment.cleanup(garment_index=self.garment_index)\r\n self.done = 'CANCELLED'\r\n\r\n def end_commit(self):\r\n self.disable_handlers()\r\n bpy.ops.garment.cleanup(garment_index=self.garment_index)\r\n self.done = 'FINISHED'\r\n\r\n def disable_handlers(self):\r\n if self._handle_draw_verts:\r\n bpy.types.SpaceView3D.draw_handler_remove(self._handle_draw_verts, 'WINDOW')\r\n if self._handle_draw_text:\r\n bpy.types.SpaceView3D.draw_handler_remove(self._handle_draw_text, 'WINDOW')\r\n\r\n\r\n\r\n def invoke_common(self, context, event):\r\n bpy.ops.garment.cleanup(garment_index=self.garment_index)\r\n bpy.ops.ed.undo_push()\r\n for obj in context.view_layer.objects:\r\n obj.select_set(False)\r\n\r\n self.event = event\r\n self.context = context\r\n self.allow_nav = False\r\n self.done = False\r\n\r\n self.garment = context.scene.cloth_garment_data[self.garment_index]\r\n self.patter_segments_cache.clear()\r\n\r\n #maybe do this on pocket picking? But we need it for hover before\r\n for obj in self.visible_objects_and_duplis(context):\r\n if obj.type == 'CURVE':\r\n resampled_curve_segments = self.curve_resample(obj, 8)\r\n segment_len = self.get_segments_len(resampled_curve_segments)\r\n self.patter_segments_cache[obj.name] = resampled_curve_segments\r\n self.patter_segments_cache[obj.name+'_len'] = segment_len\r\n\r\n args = (self, context)\r\n if not self._handle_draw_verts:\r\n self._handle_draw_verts = bpy.types.SpaceView3D.draw_handler_add(self.draw_px, args, 'WINDOW', 'POST_VIEW')\r\n if not self._handle_draw_text:\r\n self._handle_draw_text = bpy.types.SpaceView3D.draw_handler_add(self.draw_text, args, 'WINDOW', 'POST_PIXEL')\r\n\r\n\r\n\r\n","sub_path":"All_In_One/addons/garment_tool/utils/fsm_oper.py","file_name":"fsm_oper.py","file_ext":"py","file_size_in_byte":12968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"125385593","text":"from pygears.core.hier_node import HierVisitorBase\n\n\nclass RTLConnectVisitor(HierVisitorBase):\n def HierNode(self, rtl_gear):\n super().HierNode(rtl_gear)\n if hasattr(rtl_gear, 'connect'):\n rtl_gear.connect()\n\n\ndef rtl_connect(top, conf):\n v = RTLConnectVisitor()\n v.visit(top)\n # for rtl_gear in top.child:\n # v.visit(rtl_gear)\n\n return top.node\n","sub_path":"pygears/rtl/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465378754","text":"import unittest\n\nfrom nmigen import *\n\nfrom cores.ring_buffer_address_storage import RingBufferAddressStorage\nfrom util.stream import StreamEndpoint\nfrom util.sim import SimPlatform\nfrom cores.axi.axi_endpoint import AxiEndpoint, Response, AddressChannel, BurstType, DataChannel\nfrom cores.axi.buffer_writer import AxiBufferWriter, AddressGenerator\nfrom util.sim import wait_for, pulse, do_nothing\n\n\ndef answer_channel(channel, always_ready=True):\n if always_ready:\n yield channel.ready.eq(1)\n yield from wait_for(channel.valid)\n if isinstance(channel, AddressChannel):\n to_return = (\n (yield channel.value),\n (yield channel.burst_len) + 1,\n (yield channel.burst_type),\n (yield channel.beat_size_bytes)\n )\n elif isinstance(channel, DataChannel):\n to_return = ((yield channel.value), (yield channel.last), (yield channel.byte_strobe))\n if not always_ready:\n yield from pulse(channel.ready)\n else:\n yield channel.ready.eq(0)\n return to_return\n\n\ndef respond_channel(channel, resp=Response.OKAY):\n yield channel.resp.eq(resp)\n pulse(channel.valid)\n\n\ndef answer_write_burst(axi: AxiEndpoint):\n memory = {}\n addr, burst_len, burst_type, beat_size_bytes = yield from answer_channel(axi.write_address)\n assert 2 ** beat_size_bytes == axi.data_bytes\n assert burst_type == BurstType.INCR.value\n accepted = 0\n for i in range(burst_len):\n value, last, byte_strobe = yield from answer_channel(axi.write_data)\n if i == burst_len - 1:\n assert last\n if byte_strobe != 0:\n memory[addr + i * axi.data_bytes] = value\n accepted += 1\n respond_channel(axi.write_response)\n\n return memory, accepted\n\n\nclass TestSimAxiWriter(unittest.TestCase):\n def test_buffer_change(self, data_len=50):\n axi = AxiEndpoint(addr_bits=32, data_bits=64, master=False, lite=False, id_bits=12)\n\n ringbuffer = RingBufferAddressStorage(0x1000, 2, base_address=0)\n stream_source = StreamEndpoint(64, is_sink=False, has_last=True)\n\n dut = AxiBufferWriter(ringbuffer, stream_source, axi, fifo_depth=data_len)\n\n def testbench():\n gold = {}\n\n gold_gen = {\n \"current_buffer\": 0,\n \"current_address\": ringbuffer.buffer_base_list[0]\n }\n\n def change_buffer():\n gold_gen[\"current_buffer\"] = (gold_gen[\"current_buffer\"] + 1) % len(ringbuffer.buffer_base_list)\n gold_gen[\"current_address\"] = ringbuffer.buffer_base_list[gold_gen[\"current_buffer\"]]\n yield stream_source.last.eq(1)\n\n def put_data(data):\n gold[gold_gen[\"current_address\"]] = data\n gold_gen[\"current_address\"] += axi.data_bytes\n yield stream_source.valid.eq(1)\n yield stream_source.payload.eq(data)\n\n # first, fill in some data:\n for i in range(data_len):\n yield from put_data(i)\n # yield dut.change_buffer.eq(0)\n yield from change_buffer()\n yield\n yield stream_source.valid.eq(0)\n\n memory = {}\n accepted = 0\n while accepted < data_len:\n memory_fragment, accepted_frag = (yield from answer_write_burst(axi))\n memory.update(memory_fragment)\n accepted += accepted_frag\n yield\n\n self.assertEqual(gold, memory)\n self.assertFalse((yield dut.error))\n\n platform = SimPlatform()\n platform.add_sim_clock(\"sync\", 100e6)\n platform.sim(dut, testbench)\n\n def test_basic(self, data_len=50):\n axi = AxiEndpoint(addr_bits=32, data_bits=64, master=False, lite=False, id_bits=12)\n\n ringbuffer = RingBufferAddressStorage(0x1000, 2, base_address=0)\n stream_source = StreamEndpoint(64, is_sink=False, has_last=True)\n\n dut = AxiBufferWriter(ringbuffer, stream_source, axi, fifo_depth=data_len)\n\n def testbench():\n # first, fill in some data:\n for i in range(data_len):\n yield stream_source.payload.eq(i)\n yield stream_source.valid.eq(1)\n yield\n yield stream_source.valid.eq(0)\n\n memory = {}\n while len(memory) < 50:\n memory.update((yield from answer_write_burst(axi))[0])\n\n self.assertEqual({ringbuffer.buffer_base_list[0] + i * axi.data_bytes: i for i in range(50)}, memory)\n self.assertFalse((yield dut.error))\n\n platform = SimPlatform()\n platform.add_sim_clock(\"sync\", 100e6)\n platform.sim(dut, testbench)\n\n def test_memory(self):\n m = Module()\n memory = Memory(width=8, depth=8)\n read_port = m.submodules.read_port = memory.read_port(transparent=False)\n write_port = m.submodules.write_port = memory.write_port()\n lol = Signal()\n m.d.sync += lol.eq(Cat(read_port.en, read_port.data, read_port.addr, write_port.en, write_port.data, write_port.addr))\n\n def testbench():\n for i in range(8):\n yield write_port.addr.eq(i)\n yield write_port.data.eq(i)\n yield write_port.en.eq(1)\n yield\n yield write_port.en.eq(0)\n for i in range(8):\n yield read_port.addr.eq(i)\n yield read_port.en.eq(1)\n yield\n yield read_port.en.eq(0)\n\n platform = SimPlatform()\n platform.add_sim_clock(\"sync\", 100e6)\n platform.sim(m, testbench)\n\n\nclass TestAddressGenerator(unittest.TestCase):\n def test_basic(self, inc=5):\n ringbuffer = RingBufferAddressStorage(0x1000, 2, base_address=0)\n dut = AddressGenerator(ringbuffer, addr_bits=32, max_incr=inc)\n\n def testbench():\n yield dut.inc.eq(inc)\n for i in range(10):\n yield from pulse(dut.request)\n yield from wait_for(dut.valid, must_clock=False)\n self.assertEqual(ringbuffer.buffer_base_list[0] + i * inc, (yield dut.addr))\n yield from pulse(dut.done)\n yield from pulse(dut.change_buffer)\n yield from do_nothing()\n for i in range(10):\n yield from pulse(dut.request)\n yield from wait_for(dut.valid)\n self.assertEqual(ringbuffer.buffer_base_list[1] + i * inc, (yield dut.addr))\n yield from pulse(dut.done)\n\n platform = SimPlatform()\n platform.add_sim_clock(\"sync\", 100e6)\n platform.sim(dut, testbench, [dut.request, dut.change_buffer, dut.addr, dut.valid, dut.done])\n","sub_path":"src/cores/axi/buffer_writer_test.py","file_name":"buffer_writer_test.py","file_ext":"py","file_size_in_byte":6752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"310895085","text":"import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pickle\n\n#A = np.load(\"Seattle_Loop_Dataset/Loop_Seattle_2015_A.npy\")\nwith open('data/pems_bay/adj_mx_bay.pkl', 'rb') as f:\n sensor_ids, sensor_id_to_ind, A = pickle.load(f, encoding='latin-1')\n#X = np.load(\"Seattle_Loop_Dataset/Loop_Seattle_2015_A.npy\")\n#mp = pd.read_csv(\"Seattle_Loop_Dataset/nodes_loop_mp_list.csv\")[\"milepost\"]\n#mp = list(map(lambda entry: entry[1:4], mp))\n#col = list(map(lambda entry: 'b' if entry=='090' else 'g' if entry=='405' else 'r' if entry=='520' else 'k', mp))\nprint(np.shape(A))\nprint(A)\n\nall_layouts = [\n #nx.circular_layout,\n #nx.kamada_kawai_layout,\n #nx.random_layout,\n #nx.shell_layout,\n #nx.spring_layout,\n #nx.spectral_layout,\n #nx.fruchterman_reingold_layout,\n nx.spiral_layout,\n]\n\ng = nx.convert_matrix.from_numpy_matrix(A)\npos = np.load('data/pems_bay/pos_bay.npy')\nprint(g.nodes.values())\nfor layout in all_layouts:\n #nx.draw(g, node_color=col, node_size=50, pos=layout(g))\n nx.draw(g, pos=pos)\n plt.show()\n","sub_path":"graph_vis.py","file_name":"graph_vis.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"12003277","text":"from flask import Flask, render_template, request\nimport sqlite3\nfrom init_db import DATABASE\napp = Flask(__name__)\n\n# helper function to connect to db\ndef connect_db():\n\treturn sqlite3.connect(DATABASE)\n\n\n@app.route('/')\ndef index():\n\tdb = connect_db()\n\tcursor = db.execute('select id, username, learning, love from people')\n\tentries = [dict(id=row[0], username=row[1], learning=row[2], love=row[3]) for row in cursor.fetchall()]\n\t# print(\"Current entries in DB: {}\".format(entries))\n\treturn render_template('profile_list.html', entries=entries)\n\n\n@app.route('/addprofile', methods=['GET', 'POST'])\ndef add_profile_form():\n\treturn render_template('add_profile.html')\n\n\n@app.route('/profile')\ndef add_profile():\n\t# get the 'username', 'learning' and 'love' names from\n\t# the add_profile.html form upon user submitting it\n\tusername = request.args.get('username')\n\tlearning_what = request.args.get('learning')\n\tloving_what = request.args.get('love')\n\n\t# connect to flask_basics DB and inserts the fields above\n\tdb = connect_db()\n\tsql = 'insert into people (username, learning, love) values(?,?,?)'\n\tdb.execute(sql, [username, learning_what, loving_what] )\n\tdb.commit()\n\tdb.close()\n\n\t# now pass them to my_profile.html template\n\treturn render_template('my_profile.html', name=username,\n\t\t learning=learning_what,\n\t\t love=loving_what)\n\n\n# update profile\n@app.route('/editprofile')\ndef editprofile():\n\tid = request.args.get('id')\n\tdb = connect_db()\n\t\n\tcursor = db.execute('select id, username, learning, love from people where id=?', [id])\n\trow = cursor.fetchall()\n\tperson = row[0]\n\n\tcursor.close()\n\tdb.close()\n\n\treturn render_template('edit_profile.html', person=person)\n\n@app.route('/updateprofile')\ndef updatepofile():\n\tid = request.args.get('id')\n\tusername = request.args.get('username')\n\tlearning_what = request.args.get('learning')\n\tloving_what = request.args.get('love')\n\n\tdb = connect_db()\n\tsql = 'update people set username=?, learning=?, love=? where id=?'\n\tdb.execute(sql, [username, learning_what, loving_what, id] )\n\tdb.commit()\n\tdb.close()\n\n\t# return the index page with the profiles list showing the changes made\n\treturn index()\n\n@app.route('/deleteprofile')\ndef deletepofile():\n\tid = request.args.get('id')\n\n\tdb = connect_db()\n\tsql = 'delete from people where id=?'\n\tdb.execute(sql, [id])\n\tdb.commit()\n\tdb.close()\n\n\t# return the index page with the profiles list showing the changes made\n\treturn index()\nif __name__ == '__main__':\n\tapp.run(debug=True)","sub_path":"flask_basics/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"515494711","text":"from enum import Enum, auto\n\n\nclass ConflictPolicy(Enum):\n #: replace the existing schedule with a new one\n replace = auto()\n #: keep the existing schedule as-is and drop the new schedule\n do_nothing = auto()\n #: raise an exception if a conflict is detected\n exception = auto()\n\n\nclass CoalescePolicy(Enum):\n #: run once, with the earliest fire time\n earliest = auto()\n #: run once, with the latest fire time\n latest = auto()\n #: submit one job for every accumulated fire time\n all = auto()\n","sub_path":"apscheduler/policies.py","file_name":"policies.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"126793164","text":"# coding=utf-8\n# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport logging\nimport re\nfrom abc import abstractmethod\n\nfrom pants.build_graph.source_mapper import SpecSourceMapper\nfrom pants.goal.workspace import ScmWorkspace\nfrom pants.util.meta import AbstractClass\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ChangeCalculator(AbstractClass):\n \"\"\"An abstract class for changed target calculation.\"\"\"\n\n def __init__(self, scm, workspace=None, changes_since=None, diffspec=None):\n self._scm = scm\n self._workspace = workspace or ScmWorkspace(scm)\n self._changes_since = changes_since\n self._diffspec = diffspec\n\n def changed_files(self, changes_since=None, diffspec=None):\n \"\"\"Determines the files changed according to SCM/workspace and options.\"\"\"\n diffspec = diffspec or self._diffspec\n if diffspec:\n return self._workspace.changes_in(diffspec)\n\n changes_since = changes_since or self._changes_since or self._scm.current_rev_identifier()\n return self._workspace.touched_files(changes_since)\n\n @abstractmethod\n def changed_target_addresses(self):\n \"\"\"Find changed targets, according to SCM.\"\"\"\n\n\nclass BuildGraphChangeCalculator(ChangeCalculator):\n \"\"\"A `BuildGraph`-based helper for calculating changed target addresses.\"\"\"\n\n def __init__(self,\n scm,\n workspace,\n address_mapper,\n build_graph,\n include_dependees,\n fast=False,\n changes_since=None,\n diffspec=None,\n exclude_target_regexp=None):\n super(BuildGraphChangeCalculator, self).__init__(scm, workspace, changes_since, diffspec)\n self._address_mapper = address_mapper\n self._build_graph = build_graph\n self._include_dependees = include_dependees\n self._fast = fast\n self._exclude_target_regexp = exclude_target_regexp or []\n self._mapper = SpecSourceMapper(address_mapper, build_graph, fast)\n\n def _directly_changed_targets(self):\n # Internal helper to find target addresses containing SCM changes.\n targets_for_source = self._mapper.target_addresses_for_source\n result = set()\n for src in self.changed_files(self._changes_since, self._diffspec):\n result.update(set(targets_for_source(src)))\n return result\n\n def _find_changed_targets(self):\n # Internal helper to find changed targets, optionally including their dependees.\n changed = self._directly_changed_targets()\n\n # Skip loading the graph or doing any further work if no directly changed targets found.\n if not changed:\n return changed\n\n if self._include_dependees == 'none':\n return changed\n\n # Load the whole build graph since we need it for dependee finding in either remaining case.\n for address in self._address_mapper.scan_addresses():\n self._build_graph.inject_address_closure(address)\n\n if self._include_dependees == 'direct':\n return changed.union(*[self._build_graph.dependents_of(addr) for addr in changed])\n\n if self._include_dependees == 'transitive':\n return set(t.address for t in self._build_graph.transitive_dependees_of_addresses(changed))\n\n # Should never get here.\n raise ValueError('Unknown dependee inclusion: \"{}\"'.format(self._include_dependees))\n\n def changed_target_addresses(self):\n \"\"\"Find changed targets, according to SCM.\n\n This is the intended entry point for finding changed targets unless callers have a specific\n reason to call one of the above internal helpers. It will find changed targets and:\n - Optionally find changes in a given diffspec (commit, branch, tag, range, etc).\n - Optionally include direct or transitive dependees.\n - Optionally filter targets matching exclude_target_regexp.\n\n :returns: A set of target addresses.\n \"\"\"\n # Find changed targets (and maybe their dependees).\n changed = self._find_changed_targets()\n\n # Remove any that match the exclude_target_regexp list.\n excludes = [re.compile(pattern) for pattern in self._exclude_target_regexp]\n return set([\n t for t in changed if not any(exclude.search(t.spec) is not None for exclude in excludes)\n ])\n","sub_path":"src/python/pants/scm/change_calculator.py","file_name":"change_calculator.py","file_ext":"py","file_size_in_byte":4388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"69002077","text":"\"\"\"empty message\n\nRevision ID: 2a5162bc0ff4\nRevises: f2ed4d23c760\nCreate Date: 2020-04-01 12:42:12.640661\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2a5162bc0ff4'\ndown_revision = 'f2ed4d23c760'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('result', 'date')\n op.drop_column('result', 'rndTesti')\n op.drop_column('result', 'date_modified')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('result', sa.Column('date_modified', sa.DATETIME(), nullable=True))\n op.add_column('result', sa.Column('rndTesti', sa.VARCHAR(length=144), nullable=True))\n op.add_column('result', sa.Column('date', sa.DATETIME(), nullable=True))\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/2a5162bc0ff4_.py","file_name":"2a5162bc0ff4_.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"218766388","text":"from django.urls import path\nfrom django.contrib.auth import views as auth_views\nfrom .views import *\n\nurlpatterns = [\n\n path('register/',register,name='register'),\n path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'),\n path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'),\n path('profile/',profile,name='profile'),\n path('profile/delete_announcement//',delete_announcement,name='delete_announcement'),\n \n]","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"559171360","text":"import logging\nimport os\nfrom pprint import pprint\n\nimport tensorflow as tf\nfrom config import parser\nfrom data_helper import create_pretrain_datasets\nfrom pretrain_metrics import Recorder\nfrom model import CGXMultiModal\nfrom util import test_spearmanr\n\n\ndef train(args):\n # 1. create dataset and set num_labels to args\n train_dataset, val_dataset = create_pretrain_datasets(args)\n # 2. build model\n model = CGXMultiModal(args)\n # 3. save checkpoints\n checkpoint = tf.train.Checkpoint(model=model, step=tf.Variable(0))\n checkpoint_manager = tf.train.CheckpointManager(checkpoint, args.pretrain_savedmodel_path, args.max_to_keep)\n checkpoint.restore(checkpoint_manager.latest_checkpoint)\n if checkpoint_manager.latest_checkpoint:\n logging.info(\"Restored from {}\".format(checkpoint_manager.latest_checkpoint))\n else:\n logging.info(\"Initializing from scratch.\")\n # 4. create loss_object and recorders\n loss_object1 = tf.losses.mean_squared_error\n loss_object2 = tf.keras.losses.BinaryCrossentropy(reduction=tf.keras.losses.Reduction.NONE)\n loss_object = tf.keras.losses.BinaryCrossentropy(reduction=tf.keras.losses.Reduction.NONE)\n train_recorder, val_recorder = Recorder(), Recorder()\n\n @tf.function\n def cal_loss(query_labels, candidate_labels, score, predictions, query_label_prediction,\n candidate_label_prediction):\n change_score = tf.nn.sigmoid(3 * score)\n return loss_object1(change_score, predictions) + loss_object2(query_labels,\n query_label_prediction) + loss_object2(\n candidate_labels, candidate_label_prediction)\n\n # 5. define train and valid step function\n @tf.function\n def train_step(inputs):\n vids = inputs['vid']\n query_labels = inputs['labels']\n candidate_labels = inputs['labels']\n score = tf.ones([query_labels.shape[0], 1], tf.float32)\n\n convert_inputs = {\n \"query_vid\": inputs['vid'],\n \"input_query_ids\": inputs['input_ids'],\n \"query_mask\": inputs['mask'],\n \"query_asr_input_ids\": inputs['asr_input_ids'],\n \"query_asr_mask\": inputs['asr_mask'],\n \"query_frames\": inputs['frames'],\n \"query_num_frames\": inputs['num_frames'],\n \"candidate_vid\": inputs['vid'],\n \"input_candidate_ids\": inputs['input_ids'],\n \"candidate_mask\": inputs['mask'],\n \"candidate_asr_input_ids\": inputs['asr_input_ids'],\n \"candidate_asr_mask\": inputs['asr_mask'],\n \"candidate_frames\": inputs['frames'],\n \"candidate_num_frames\": inputs['num_frames']\n }\n with tf.GradientTape() as tape:\n predictions, query_embeddings, candidate_embeddings, query_label_prediction, candidate_label_prediction = model(\n convert_inputs, training=True)\n loss = cal_loss(query_labels, candidate_labels, score, predictions, query_label_prediction,\n candidate_label_prediction) * query_labels.shape[-1] # convert mean back to sum\n gradients = tape.gradient(loss, model.get_variables())\n model.optimize(gradients)\n train_recorder.record(loss, query_labels, query_label_prediction)\n\n @tf.function\n def val_step(inputs):\n vids = inputs['vid']\n labels = inputs['labels']\n score = tf.ones([labels.shape[0], 1], tf.float32)\n convert_inputs = {\n \"query_vid\": inputs['vid'],\n \"input_query_ids\": inputs['input_ids'],\n \"query_mask\": inputs['mask'],\n \"query_asr_input_ids\": inputs['asr_input_ids'],\n \"query_asr_mask\": inputs['asr_mask'],\n \"query_frames\": inputs['frames'],\n \"query_num_frames\": inputs['num_frames'],\n \"candidate_vid\": inputs['vid'],\n \"input_candidate_ids\": inputs['input_ids'],\n \"candidate_mask\": inputs['mask'],\n \"candidate_asr_input_ids\": inputs['asr_input_ids'],\n \"candidate_asr_mask\": inputs['asr_mask'],\n \"candidate_frames\": inputs['frames'],\n \"candidate_num_frames\": inputs['num_frames']\n }\n predictions, query_embeddings, candidate_embeddings, query_label_prediction, candidate_label_prediction = model(\n convert_inputs, training=True)\n loss = loss_object(labels, query_label_prediction) * labels.shape[-1] # convert mean back to sum\n\n val_recorder.record(loss, labels, query_label_prediction)\n return vids, query_embeddings\n\n # 6. training\n for epoch in range(args.start_epoch, args.epochs):\n for train_batch in train_dataset:\n checkpoint.step.assign_add(1)\n step = checkpoint.step.numpy()\n if step > args.total_steps:\n break\n train_step(train_batch)\n if step % args.print_freq == 0:\n train_recorder.log(epoch, step)\n train_recorder.reset()\n\n # 7. validation\n if step % args.eval_freq == 0:\n vid_embedding = {}\n for val_batch in val_dataset:\n vids, embeddings = val_step(val_batch)\n for vid, embedding in zip(vids.numpy(), embeddings.numpy()):\n vid = vid.decode('utf-8')\n vid_embedding[vid] = embedding\n # 8. test spearman correlation\n spearmanr = test_spearmanr(vid_embedding, args.annotation_file)\n val_recorder.log(epoch, step, prefix='Validation result is: ', suffix=f', spearmanr {spearmanr:.4f}')\n val_recorder.reset()\n\n # 9. save checkpoints\n if spearmanr > 0.55:\n checkpoint_manager.save(checkpoint_number=step)\n\n\ndef main():\n logging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n args = parser.parse_args()\n\n if not os.path.exists(args.pretrain_savedmodel_path):\n os.makedirs(args.pretrain_savedmodel_path)\n\n pprint(vars(args))\n train(args)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"code_review_xc/src/pre_train.py","file_name":"pre_train.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"82354333","text":"#购物中心主界面\r\nfrom . import shopping\r\nfrom . import shop_card\r\nfrom . import pay\r\nfrom Main import main\r\nimport os,sys,time,json\r\nBASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\nsys.path.append(BASE_DIR)\r\nDIR=BASE_DIR+r'\\database\\card.text'#购物车\r\nDIR2=BASE_DIR+r'\\database\\creditcart'#信用卡\r\nDIR3=BASE_DIR+r'\\database\\session.text'\r\nDIR4=BASE_DIR+r'\\database\\Item.text'#流水账\r\nDIR5=BASE_DIR+r'\\Renzheng\\user.text'\r\ndef center_list():\r\n print('-------欢迎进入购物中心-------')\r\n while True:\r\n a = '''\r\n 1 购物商城\r\n 2 购物车\r\n 3 购物结算\r\n 4 个人中心\r\n '''\r\n print(a)\r\n choose = input('请输入您的选择,[b]返回商城主页:')\r\n if choose=='1':\r\n shopping.shop()#购物中心\r\n if choose=='2':\r\n shop_card.card()\r\n if choose=='3':\r\n choose2=input('确认结算?[y]结算[b]退出')\r\n if choose2=='y':\r\n card = []\r\n s=0\r\n with open(DIR, 'r', encoding='utf-8') as f:\r\n a = f.readlines()\r\n if a==[]:\r\n print(\"购物车是空的噢,请先去购物吧~~\")\r\n else:\r\n for i, item in enumerate(a):\r\n line = item.strip().split()\r\n card.append(int(line[1])) # 将str的价格转换为int类型\r\n s += card[i] # 购物车总价\r\n pay.pay_bill(s)\r\n continue\r\n else:\r\n continue\r\n if choose=='4':\r\n x='''\r\n 1 修改密码\r\n 2 查看购物流水记录\r\n '''\r\n while True:\r\n print(x)\r\n choose3=input('请输入您的选择,[b]返回上一层:')\r\n if choose3=='1':\r\n change_pwd()\r\n if choose3=='2':\r\n with open(DIR4,'r',encoding='utf-8')as f:\r\n for i in f.readlines():\r\n line=i.strip()\r\n print(line)\r\n if choose3=='b':\r\n break\r\n else:\r\n print('请输入正确的选择!')\r\n\r\n if choose=='b':\r\n main.list()\r\n else:\r\n print('请输入正确的编号!')\r\n continue\r\n\r\ndef change_pwd():\r\n with open(DIR2,'r')as f,open(DIR3,'r')as h,open(DIR5,'r')as p:\r\n name=h.read()\r\n user_dict=json.loads(f.read())\r\n user=json.loads(p.read())\r\n print('原密码:%s'%user_dict['%s'%name]['password'])\r\n pwd=input('新密码:')\r\n confirm=input('确认要修改密码?[y][n]')\r\n if confirm=='y':\r\n user_dict['%s' % name]['password']=pwd\r\n user['%s'%name]=pwd\r\n with open(DIR2,'w')as f,open(DIR5,'w')as p:\r\n f.write(json.dumps(user_dict))\r\n p.write(json.dumps(user))\r\n print('修改成功!')\r\n\r\n\r\n","sub_path":"Bin/center.py","file_name":"center.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"361746940","text":"# -*- coding: utf-8 -*-\r\n__author__ = \"Sartori Davide 4CI\"\r\n__version__ = \"1.0\"\r\n\r\nimport sys\r\nimport os\r\nimport datetime\r\nimport time\r\nimport sendmail\r\n\r\nboold = False\r\n\r\n\r\ndef get_conf(path):\r\n conf_dict = {\"notifications\": False, \"file_path\": False, \"tracelog_path\": False, \"program_execution_string\": False,\r\n \"mail_sender\": False, \"mail_receivers\": False, \"smtp_server\": False}\r\n\r\n for line in open(path):\r\n if (line.split(\"=\")[0]).strip() == \"notifications\":\r\n conf_dict[\"notifications\"] = (line.split(\"=\")[1]).strip()\r\n elif (line.split(\"=\")[0]).strip() == \"file_path\":\r\n conf_dict[\"file_path\"] = (line.split(\"=\")[1]).strip()\r\n elif (line.split(\"=\")[0]).strip() == \"tracelog_path\":\r\n conf_dict[\"tracelog_path\"] = (line.split(\"=\")[1]).strip()\r\n elif (line.split(\"=\")[0]).strip() == \"program_execution_string\":\r\n conf_dict[\"program_execution_string\"] = (line.split(\"=\")[1]).strip()\r\n elif (line.split(\"=\")[0]).strip() == \"mail_sender\":\r\n conf_dict[\"mail_sender\"] = (line.split(\"=\")[1]).strip()\r\n elif (line.split(\"=\")[0]).strip() == \"mail_receivers\":\r\n conf_dict[\"mail_receivers\"] = (line.split(\"=\")[1]).strip().split(\",\")\r\n elif (line.split(\"=\")[0]).strip() == \"smtp_server\":\r\n conf_dict[\"smtp_server\"] = (line.split(\"=\")[1]).strip()\r\n\r\n for element in conf_dict.values():\r\n if not element:\r\n if boold:\r\n print(\"File di configurazione non valido\")\r\n exit(-1)\r\n\r\n return conf_dict\r\n\r\n\r\ndef log_text(new_text):\r\n \"\"\" Registra le informazioni nel file di log \"\"\"\r\n text = \"\"\r\n\r\n for line in new_text.split(\"\\n\"):\r\n if line != \"\":\r\n timestamp = datetime.date.today().strftime('%Y-%m-%d') + \" \" + time.strftime('%H:%M:%S')\r\n text += timestamp + \"§\" + line + \"\\n\"\r\n\r\n return text\r\n\r\n\r\ndef get_publication_date(path):\r\n \"\"\" Ritorna la data di pubblicazione dell'ultimo flusso di file \"\"\"\r\n file_in = open(path)\r\n text = file_in.read()\r\n file_in.close()\r\n\r\n return text.split(\"\\n\")[-2].split(\"§\")[1]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n conf_path = \"hids.conf\"\r\n tracelog_text = \"\"\r\n mail_text = \"\"\r\n conf = {}\r\n\r\n for arg in sys.argv:\r\n if arg == \"-v\":\r\n boold = True\r\n if arg == \"-f\":\r\n try:\r\n conf_path = sys.argv[sys.argv.index(\"-f\") + 1]\r\n except IndexError:\r\n if boold:\r\n print(\"Inserire un file valido\")\r\n\r\n exit(-1)\r\n\r\n try:\r\n conf = get_conf(conf_path)\r\n except IOError:\r\n tracelog_text += os.environ['USERNAME'] + \"§File di configurazione non trovato\\n\"\r\n\r\n if boold:\r\n print(\"File di configurazione non trovato\")\r\n\r\n exit(-1)\r\n\r\n boolmail = conf[\"notifications\"]\r\n file_path = conf[\"file_path\"]\r\n tracelog_path = conf[\"tracelog_path\"]\r\n program_execution_string = conf[\"program_execution_string\"]\r\n mail_sender = conf[\"mail_sender\"]\r\n mail_receivers = conf[\"mail_receivers\"]\r\n smtp_server = conf[\"smtp_server\"]\r\n\r\n try:\r\n open(tracelog_path)\r\n except IOError:\r\n open(tracelog_path, \"w\")\r\n\r\n if boold:\r\n print(\"Start hids\")\r\n\r\n if boold:\r\n print(\"Controllo data di pubblicazione..\")\r\n\r\n tracelog_text += os.environ['USERNAME'] + \"§Controllo data di pubblicazione\\n\"\r\n\r\n if get_publication_date(file_path) == datetime.date.today().strftime('%Y/%m/%d'):\r\n tracelog_text += os.environ['USERNAME'] + \"§Inizio processo di carimento file\\n\"\r\n\r\n if boold:\r\n print(\"Caricamento file..\")\r\n\r\n try:\r\n os.system(program_execution_string)\r\n tracelog_text += os.environ['USERNAME'] + \"§Programma eseguito con successo\\n\"\r\n except IOError:\r\n tracelog_text += os.environ['USERNAME'] + \"§Programma non trovato o stringa di esecuzione non valida\\n\"\r\n\r\n if boold:\r\n print(\"Programma non trovato\")\r\n\r\n if conf[\"notifications\"] == \"yes\":\r\n tracelog_text += os.environ['USERNAME'] + \"§Invio notifica email\\n\"\r\n if boold:\r\n print(\"Invio notifica mail..\")\r\n\r\n mail_text = log_text(log_text(tracelog_text))\r\n if not sendmail.sendmail(mail_sender, mail_receivers, smtp_server, mail_text, \"Flussi\"):\r\n tracelog_text += os.environ['USERNAME'] + \"§Impossibile inviare la mail\\n\"\r\n open(tracelog_path, \"a\").write(log_text(tracelog_text))\r\n\r\n else:\r\n tracelog_text = os.environ['USERNAME'] + \"§Data di pubblicazione non corrispondente alla data odierna\\n\"\r\n open(tracelog_path, \"a\").write(log_text(tracelog_text))\r\n\r\n if boold:\r\n print(\"Stop hids\")\r\n","sub_path":"orario/bin/hids.py","file_name":"hids.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"255202101","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''Ez egy próba a https://abuseipdb.com APIv2 használatára, valószínűleg kisség túlbonyolítva,\nmert a pycurl modult használom, holott lehet, hogy a requests használata egyszerűbb lenne\nKell hozzá egy abuseipdb.key fájl, amiben a site-on generált saját kulcsot kell tárolni,\nez értelemszerűen ignorálva van a gitignore által, mert privát infó.\n\nLényegében a https://www.abuseipdb.com/api/v2/check URL-re kell hivatkozni, ha egy IP címről\nakarok adatokat lekérni. Itt már a kulcsot a http headerben kell elküldeni, nem get paraméterként\n\nAz API leírása: https://docs.abuseipdb.com/\n'''\nimport json\nimport requests\nimport sys\nimport pycurl\nfrom urllib.parse import urlencode\nfrom io import BytesIO\n\n\ndef get_api_key():\n\twith open(\"abuseipdb.key\",\"r\") as keyfile:\n\t\tkey = keyfile.readline().rstrip(\"\\n\")\n\treturn key\n\n\nclass AbuseIPDB():\n\tdef __init__(self, key):\n\t\tself.key = key\n\t\tself.curlObject = pycurl.Curl()\n\n\n\tdef check(self, ipaddr):\n\t\treturn None\n\n\tdef get_blacklist(self):\n\t\treturn None\n\n\tdef check_block(self, netaddr):\n\t\treturn None\n\n\tdef report(self, ipaddr, *args):\n\t\treturn None\n\n\tdef bulk_report(self, ):\n\t\tpass\n\napi_key = get_api_key()\n\nif len(sys.argv)>1:\n\tip_addr = sys.argv[1]\nelse:\n\tip_addr = '127.0.0.1'\n\n\nc = pycurl.Curl()\nc.setopt(pycurl.HTTPHEADER, [ \"Key:\" + api_key, \"Accept: application/json\" ])\n\npost_data = {\"ipAddress\":ip_addr, \"verbose\":\"True\", \"maxAgeInDays\":\"90\" }\npostfields = urlencode(post_data)\nstorage = BytesIO()\n\nc.setopt(pycurl.HTTPGET,1)\nc.setopt(pycurl.URL, \"https://www.abuseipdb.com/api/v2/check\" + '?' + postfields)\nc.setopt(pycurl.WRITEFUNCTION, storage.write)\nc.perform()\nc.close()\n\nprint(storage.getvalue())\n\n#for i in response:\n#\tprint(i)\n\n","sub_path":"probak/checkip.py","file_name":"checkip.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"463762742","text":"import sys\nimport math\nimport numpy as np\nfrom numpy.linalg import norm\nfrom itertools import product, count\n\n\ndef debug(text, *params, **keyword_params):\n print(text.format(*params, **keyword_params), file=sys.stderr)\n\n\nMAX_ROT_DIFF_PER_STEP = 15\nGRAVITY = 3.711\nLANDING_WIDTH = 1000\n\n\ndef read_surface_and_landing():\n surface_n = int(input()) # the number of points used to draw the surface of Mars.\n landing_x = []\n landing_y = -1\n for i in range(surface_n):\n # land_x: X coordinate of a surface point. (0 to 6999)\n # land_y: Y coordinate of a surface point.\n # By linking all the points together in a sequential fashion, you form the surface of Mars.\n land_x, land_y = [int(j) for j in input().split()]\n if landing_y == land_y and land_x - landing_x[0] >= LANDING_WIDTH:\n landing_x.append(land_x)\n elif len(landing_x) < 2:\n landing_y = land_y\n landing_x = [land_x]\n landing_x = np.array(landing_x)\n debug(\"Landing area {} on height {}. Total surface points {}.\", landing_x, landing_y, surface_n)\n return landing_x, landing_y\n\n\ninfinite = float(\"Inf\")\n\n\ndef get_accel(rot, thrust):\n rot_in_rad = rot * math.pi / 180\n return np.array([math.sin(-rot_in_rad) * thrust, math.cos(rot_in_rad) * thrust - GRAVITY])\n\n\n# Any positive integer, should be <= MAX_ANGLE_DIFF_PER_STEP and must be dividend of 90\nrotation_delta = MAX_ROT_DIFF_PER_STEP\npossible_rotations = [i * rotation_delta for i in range(-6, 7)]\npossible_thrusts = [i for i in range(0, 5)]\npossible_rot_thrusts = [(rot, thrust) for rot, thrust in product(possible_rotations, possible_thrusts)]\npossible_accels = [get_accel(rot, thrust) for rot, thrust in possible_rot_thrusts]\nextreme_descend_rot_thrusts = [(rot, thrust) for rot, thrust in possible_rot_thrusts\n if abs(rot) == 90 or (rot == 0 and thrust == 0)]\nextreme_descend_accels = [get_accel(rot, thrust) for rot, thrust in extreme_descend_rot_thrusts]\n\n\ndef arg_min(function, parameters):\n min_value = infinite\n best_parameter = None\n best_index = -1\n for index, parameter in enumerate(parameters):\n value = function(parameter)\n if value < min_value:\n min_value = value\n best_parameter = parameter\n best_index = index\n return best_index, best_parameter\n\n\ndef find_closest_rot_thrust_by_norm(to_accel):\n index, accel = arg_min(lambda acc: norm(to_accel - acc), possible_accels)\n return possible_rot_thrusts[index] + (accel,)\n\n\ndef get_exact_rot(to_accel):\n angle = math.atan2(to_accel[1], to_accel[0]) # between -pi and pi\n # Convert to rot that represents the same angle in the circle that got offset by -GRAVITY\n # For this solve the quadratic equation (r cos(a))²+(r sin(a) + GRAVITY)² = 16 for positive r\n sin_angle = math.sin(angle)\n first_term = -GRAVITY * sin_angle\n second_term = math.sqrt(GRAVITY * GRAVITY * sin_angle * sin_angle - GRAVITY * GRAVITY + 4 * 4)\n r = max(first_term - second_term, first_term + second_term)\n\n real_angle = math.atan2(r * sin_angle + GRAVITY, r * math.cos(angle))\n if real_angle < 0:\n return None\n # Finally convert to rot\n rot = real_angle - math.pi / 2\n return int(rot * 180 / math.pi + 0.5) # to degrees\n\n\ndef find_closest_rot_thrust(to_accel):\n if to_accel[1] >= 0:\n # We want to ascend, get exact rotation and enforce thrust=4\n rot = get_exact_rot(to_accel)\n thrust = 4\n return rot, thrust, get_accel(rot, thrust)\n # We want to descend\n rot = get_exact_rot(to_accel) # Could be out of [-90, 90] interval\n if rot is not None:\n thrust = 4\n return rot, thrust, get_accel(rot, thrust)\n\n to_angle = math.atan2(to_accel[1], to_accel[0])\n\n def angle_diff(acc):\n angle = math.atan2(acc[1], acc[0]) # between -pi and pi\n return min(abs(angle - to_angle), abs(2 * math.pi + angle - to_angle), abs(2 * math.pi + to_angle - angle))\n\n index, accel = arg_min(angle_diff, extreme_descend_accels)\n return extreme_descend_rot_thrusts[index] + (accel,)\n\n\ndef change_by_max_step(value, target_value, max_step):\n return min(max(target_value, value - max_step), value + max_step)\n\n\ndef linear_change(start_value, end_value, step):\n # Generates an infinite sequence in interval [start_value, end_value] with two successive points\n # being at most abs(step) from each other\n return (change_by_max_step(start_value, end_value, i * step) for i in count())\n\n\ndef advance_state(state, target_rot=None, target_thrust=None):\n def advance_to_target(target_rot, target_thrust):\n target_rot = target_rot if target_rot is not None else state[\"rot\"]\n target_thrust = target_thrust if target_thrust is not None else state[\"thrust\"]\n\n # Assume changes order: pos before speed before accel before fuel before rot/thrust\n state[\"pos\"] += state[\"speed\"]\n state[\"speed\"] += get_accel(state[\"rot\"], state[\"thrust\"])\n state[\"fuel\"] -= state[\"thrust\"]\n state[\"rot\"] = change_by_max_step(state[\"rot\"], target_rot, MAX_ROT_DIFF_PER_STEP)\n state[\"thrust\"] = change_by_max_step(state[\"thrust\"], target_thrust, 1)\n return state[\"rot\"] == target_rot and state[\"thrust\"] == target_thrust\n\n count = 1\n while not advance_to_target(target_rot, target_thrust):\n count += 1\n return count\n\n\ndef copy_state(state):\n return make_state(state[\"pos\"][0], state[\"pos\"][1],\n state[\"speed\"][0], state[\"speed\"][1],\n state[\"fuel\"],\n state[\"rot\"],\n state[\"thrust\"])\n\n\ndef make_state(x, y, speed_x, speed_y, fuel, rotate, thrust):\n return {\"pos\": np.array([x, y]),\n \"speed\": np.array([speed_x, speed_y]),\n \"fuel\": fuel,\n \"rot\": rotate,\n \"thrust\": thrust}\n\n\ndef _calculate_steps(s0, s, accel, speed):\n a = 0.5 * accel\n b = speed\n c = s0 - s\n if a == 0:\n return infinite if b == 0 or -c / b < 0 else -c / b\n discr = b * b - 4 * a * c\n if discr < 0:\n return infinite\n results = (-b + math.sqrt(discr)) / (2 * a), (-b - math.sqrt(discr)) / (2 * a)\n return int((min(results) if min(results) > 0 else max(results)) + 0.5)\n\n\ndef _calculate_steps_for_speed(v0, v, accel):\n if accel == 0:\n return 0 if v0 == v else infinite\n return int((v - v0) / accel + 0.5)\n\n\ndef estimate_steps_between_states(start_state, end_state, only_speed=False):\n accel = get_accel(start_state[\"rot\"], start_state[\"thrust\"])\n if only_speed:\n return np.array([_calculate_steps_for_speed(start_state[\"speed\"][i], end_state[\"speed\"][i], accel[i])\n for i in range(2)])\n # Under the assumption that start state rotation and thrust and therefore the acceleration do not change\n # Also ignore the speed, rot and thrust of target state, only the position is relevant here\n # s = 1/2*a*t² + v*t + s0 for x and y direction with\n # a being the acceleration, t the steps, s0 the start position, s the target position, v the start speed\n return np.array([_calculate_steps(start_state[\"pos\"][i], end_state[\"pos\"][i], accel[i], start_state[\"speed\"][i])\n for i in range(2)])\n\n\ndef read_state():\n values = [int(i) for i in input().split()]\n return make_state(*values)\n\n\nlanding_area_x, landing_area_y = read_surface_and_landing()\n\n# game loop\ndebug(\"Starting game loop\")\ntarget_state = make_state(np.mean(landing_area_x), landing_area_y, 0, 0, 0, 0, 0)\nstart_speed_x = None\nemergency_x_break = False\nwhile True:\n # h_speed: the horizontal speed (in m/s), can be negative.\n # v_speed: the vertical speed (in m/s), can be negative.\n # fuel: the quantity of remaining fuel in liters.\n # rotate: the rotation angle in degrees (-90 to 90).\n # power: the thrust power (0 to 4).\n curr_state = read_state()\n if start_speed_x is None:\n start_speed_x = curr_state[\"speed\"][0]\n if abs(start_speed_x) > 20:\n emergency_x_break = True\n\n debug(\"Current {}\", curr_state)\n debug(\"Target {}\", target_state)\n\n steps_without_changes = estimate_steps_between_states(curr_state, target_state)\n debug(\"Steps when not changing anything {})\", steps_without_changes)\n\n if abs(curr_state[\"speed\"][0]) < 20:\n emergency_x_break = False\n if emergency_x_break:\n debug(\"EMERGENCY BRAKING TO SLOW DOWN X SPEED!\")\n target_rot, target_thrust, _ = find_closest_rot_thrust([-start_speed_x, 0])\n\n print(target_rot, target_thrust)\n continue\n dist_to_move = target_state[\"pos\"] - curr_state[\"pos\"]\n target_rot, target_thrust, target_accel = find_closest_rot_thrust(dist_to_move)\n\n power_state = copy_state(curr_state)\n steps_to_power_state = advance_state(power_state, target_rot, target_thrust)\n\n steps_to_target = steps_to_power_state + estimate_steps_between_states(power_state, target_state)\n\n debug(\"Steps when moving in fastest way {})\", steps_to_target)\n\n debug(\"Target rot {}, target thrust {} when minimizing distance {}\",\n target_rot, target_thrust, dist_to_move)\n if min(steps_to_target) < infinite:\n speed_to_change = target_state[\"speed\"] - curr_state[\"speed\"]\n break_rot, break_thrust, break_accel = find_closest_rot_thrust(speed_to_change)\n break_state = copy_state(power_state)\n steps_to_break_state = advance_state(break_state, break_rot, break_thrust)\n steps_to_break = steps_to_power_state + steps_to_break_state + estimate_steps_between_states(break_state,\n target_state,\n only_speed=True)\n\n debug(\"Current speed to change {}\", speed_to_change)\n debug(\"Best rot {}, best thrust {} when asking break\", break_rot, break_thrust)\n debug(\"Required steps for breaking {} (to break state are {})\", steps_to_break, steps_to_break_state)\n if ((steps_to_break[0] >= steps_to_target[0] and (\n steps_without_changes[0] is infinite or abs(curr_state[\"speed\"][0]) >= 15))\n or (steps_to_break[1] >= steps_to_target[1] and (steps_without_changes[1] is infinite or abs(\n curr_state[\"speed\"][1]) >= 35))): # TODO maybe try comparing x/y separately\n debug(\"NEED TO BREAK\")\n target_rot = break_rot\n target_thrust = break_thrust\n\n dist_to_edge_x = landing_area_x - curr_state[\"pos\"][0]\n speed_x, speed_y = curr_state[\"speed\"]\n steps_to_landing_area_x = dist_to_edge_x[1] / speed_x if speed_x < 0 else (\n dist_to_edge_x[0] / speed_x if speed_x > 0 else infinite)\n over_landing_area = landing_area_x[0] <= curr_state[\"pos\"][0] <= landing_area_x[1]\n if over_landing_area:\n debug(\"OVER LANDING AREA!\")\n if abs(speed_x) <= 20:\n steps_over_land_x = dist_to_edge_x[0] / speed_x if speed_x < 0 else (\n dist_to_edge_x[1] / speed_x if speed_x > 0 else infinite)\n steps_over_land_x = 0 if steps_over_land_x < 0 else steps_over_land_x\n steps_to_land_y = _calculate_steps(curr_state[\"pos\"][1], landing_area_y,\n get_accel(curr_state[\"rot\"], curr_state[\"thrust\"])[1],\n curr_state[\"speed\"][1])\n debug(\"Dist to edge {}, steps over land {}, steps to land y {}\", dist_to_edge_x, steps_over_land_x,\n steps_to_land_y)\n if (abs(speed_x) <= 2 or speed_y >= 0 or abs(target_state[\"pos\"][1] - curr_state[\"pos\"][1]) <= 2 * abs(\n speed_y)\n or (steps_over_land_x > 0 and steps_over_land_x >= steps_to_land_y)):\n target_rot = 0\n target_thrust = 0\n else:\n target_rot = int(math.copysign(15, speed_x))\n target_thrust = 3\n if abs(speed_y) > 30:\n target_thrust = 4\n elif 5 > steps_to_landing_area_x > 0 and abs(speed_x) <= 20:\n debug(\"ALMOST OVER LANDING AREA!\")\n target_rot = 0\n target_thrust = 0\n if abs(speed_y) > 30:\n target_thrust = 4\n # rotate power. rotate is the desired rotation angle. power is the desired thrust power.\n print(target_rot, target_thrust)\n","sub_path":"Puzzles/SinglePlayer/Medium/MarsLanderLevel2.py","file_name":"MarsLanderLevel2.py","file_ext":"py","file_size_in_byte":12476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"272174845","text":"# sam little\n# aoc day 6\n\nwith open('day6-input.txt', 'r') as f:\n data = f.read()\n\ndata = data.split('\\n\\n')\n\ngroups = []\nfor g in data:\n groups.append(g.split('\\n'))\n\ntotal = 0\nfor g in groups:\n sets = []\n for p in g:\n ys = set()\n for x in p:\n ys.add(x)\n sets.append(ys)\n\n i = sets.pop()\n for s in sets:\n i = i.intersection(s)\n\n total += len(i)\n\nprint(total)\n","sub_path":"day6/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":"55"} +{"seq_id":"115759176","text":"from typing import List\nimport sys\n\ndef embed_eq(embed1, embed2, full=False, attrs=None):\n if embed1 == embed2:\n return True\n if embed1 is None and embed2 is not None:\n return False\n if embed2 is None and embed1 is not None:\n return False\n\n\n embed1_data = embed1.to_dict()\n embed2_data = embed2.to_dict()\n\n if full:\n return embed1_data == embed2_data\n elif attrs is not None:\n attr_comp = []\n for attr in attrs:\n try:\n if isinstance(attr, List):\n # Since an iterable was passed, assume its to compare subelements of a proxy field\n value1 = embed1_data\n value2 = embed2_data\n for subattr in attr:\n value1 = value1.get(subattr, None)\n value2 = value2.get(subattr, None)\n if value1 is None or value2 is None:\n break\n attr_comp.append(value1 == value2)\n else:\n attr_comp.append(embed1_data.get(attr, None) == embed2_data.get(attr, None))\n except KeyError:\n attr_comp.append(False)\n\n return all(attr_comp)\n else:\n return all([embed1.title == embed2.title,\n embed1.description == embed2.description,\n embed1.url == embed2.url,\n embed1.footer.text == embed2.footer.text,\n embed1.image.url == embed2.image.url])\n\n\ndef embed_proxy_eq(embed_proxy1, embed_proxy2):\n return embed_proxy1.__repr__ == embed_proxy2.__repr__\n\n\ndef compare_dicts(got, exp) -> str:\n try:\n import difflib\n import pprint\n return 'Diff:\\n' + '\\n'.join(difflib.ndiff(pprint.pformat(got).splitlines(), pprint.pformat(exp).splitlines()))\n except ImportError:\n return f\"Got:\\n{got}\\nExpected:\\n{exp}\"\n","sub_path":"discord/ext/test/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"272812438","text":"# -*- coding: utf-8 -*-\n'''\n @File : controlIrtopBox.py\n @Time : 2018/12/13 17:16\n @Author : Chenzd\n @Project : 随机控制机顶盒\n @Software: PyCharm\n'''\nimport unittest\nfrom page.appiumDriver import MyDriver\nfrom page.common.homePage import HomePage\nfrom page.ZigBee.wifiInfraRed.add_WifiIR import Add_wifiIr\nfrom page.ZigBee.wifiInfraRed.controlIrPage import ControlIrPage\nclass ControlIrtopBox(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.driver = MyDriver.cur_driver()\n cls.addControl1 = '智能影音中控主机'\n cls.addControl2 = '智能影音中控主机62016'\n cls.count = 0\n cls.i = 0\n cls.num = 8000\n\n def test_controlIrtopBox(self):\n HomePage(self.driver).more_click()\n aw = Add_wifiIr(self.driver)\n aw.device_management_click()\n aw.name_click(self.addControl1)\n aw.name_click(self.addControl2)\n cip = ControlIrPage(self.driver)\n cip.xmgd_control()\n while self.count < self.num:\n cip.topBox_control()\n self.count += 1\n cip.swipe_up_Big()\n while self.i < self.num:\n cip.topBox_control2()\n self.i += 1\n aw.back_click()\n aw.back_click()\n aw.back_click()\n HomePage(self.driver).home_click()\n\n @classmethod\n def tearDownClass(cls):\n print('红外控制器厦门广电机顶盒用例控制结束')","sub_path":"testCase/ZigBee/wifiIrCase/controlIrtopBox.py","file_name":"controlIrtopBox.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"392386795","text":"import unittest\n\n\ndef compress(str_):\n out, prev, counter = '', '', 0\n for i in str_:\n if not out or i != prev:\n if counter > 0:\n out += str(counter)\n counter = 0\n out += i\n prev = i\n counter += 1\n out += str(counter)\n return out if len(out) < len(str_) else str_\n\n\nclass TestStringCompression(unittest.TestCase):\n TEST_DATA = [\n ('a', 'a'),\n ('aabcccccaaa', 'a2b1c5a3'),\n ('abc', 'abc'),\n ('zzzzzzzz', 'z8')\n ]\n\n def test_string_compression(self):\n for str_, res in self.TEST_DATA:\n self.assertEqual(compress(str_), res)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Ch1/q1_6.py","file_name":"q1_6.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"394333106","text":"import discord\r\nfrom discord.ext.commands import Bot\r\nfrom discord.ext import commands\r\nimport asyncio\r\nimport random\r\nimport pickle\r\nimport os\r\nimport requests\r\nimport json\r\n\r\nClient = discord.Client()\r\nbot_prefix= \"p!\"\r\nclient = commands.Bot(command_prefix=bot_prefix)\r\n\r\n'''\r\nEVENTS\r\n'''\r\n# TELLS YOU WHEN THE BOT IS READY\r\n@client.event\r\nasync def on_ready():\r\n print(\"====================\")\r\n print(\"Connected!\")\r\n print(\"====================\")\r\n print(\"Name: {}\".format(client.user.name))\r\n print(\"ID: {}\".format(client.user.id))\r\n print(\"====================\")\r\n print('Logged in as '+client.user.name+' (ID:'+client.user.id+') | '+str(len(client.servers))+' servers')\r\n await client.change_presence(game=discord.Game(name='Use p!help'))\r\n\r\n# CLEVER BOT\r\nCBuser = 'hTitan8XcqVKE5qt'\r\nCBkey = 'jrUn80fYMmc1P6MTqqDwjCCoRo7yt5P5'\r\n@client.event\r\nasync def on_message(message):\r\n if not message.author.bot and (message.server == None or client.user in message.mentions):\r\n await client.send_typing(message.channel)\r\n txt = message.content.replace(message.server.me.mention,'') if message.server else message.content\r\n r = json.loads(requests.post('https://cleverbot.io/1.0/ask', json={'user':CBuser, 'key':CBkey, 'nick':'Paradise', 'text':txt}).text)\r\n if r['status'] == 'success':\r\n await client.send_message(message.channel, r['response'] )\r\n else:\r\n await client.process_commands(message)\r\n\r\n'''\r\nCOMMANDS\r\n'''\r\n# HELP COMMAND\r\nclient.remove_command('help')\r\n@client.command(pass_context=True)\r\nasync def help(ctx):\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n embed1 = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n embed1.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n embed1.title = \"COMMANDS FOR EVERYONE\"\r\n embed1.add_field(name= \"p!help\", value= \"Shows you this!\", inline=True)\r\n embed1.add_field(name= \"p!play\", value= \"plays the music in voice chat!\", inline=True)\r\n embed1.add_field(name= \"p!invite\", value= \"invites the bot\", inline=True)\r\n embed1.add_field(name= \"p!server\", value= \"invites to the paradise server!\", inline=True)\r\n embed1.add_field(name= \"p!ping\", value= \"Pings the bot!\", inline=True)\r\n embed1.add_field(name= \"p!serverinfo\", value= \"Gives you information about the server!\", inline=True)\r\n embed1.add_field(name= \"p!quote\", value= \"Gives you a random quote!\", inline=True)\r\n embed1.add_field(name= \"p!eightball (question)\", value= \"Ask the magic eightball a question!\", inline=True)\r\n embed1.add_field(name= \"p!suicide\", value= \"Gives you suicide fact!\", inline=True)\r\n embed1.add_field(name= \"p!heaven\", value= \"Gives you Heaven fact!\", inline=True)\r\n embed1.add_field(name= \"p!say (text)\", value= \"Forces the bot to say something!\", inline=True)\r\n embed1.add_field(name= \"p!profile (user)\", value= \"Shows you information about the mentioned user!\", inline=True)\r\n embed1.set_footer(text=footer_text)\r\n\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n embed2 = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n embed2.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n embed2.title = \"FUN COMMANDS\"\r\n embed2.add_field(name= \"p!retard\", value= \"Turns the mentioned user into a retard!\", inline=True)\r\n embed2.add_field(name= \"p!kill (user)\", value= \"Kills someone!\", inline=True)\r\n embed2.add_field(name= \"p!roast (user)\", value= \"Roasts someone!\", inline=True)\r\n embed2.set_footer(text=footer_text)\r\n \r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n embed3 = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n embed3.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n embed3.title = \"MODERATION COMMANDS\"\r\n embed3.add_field(name= \"p!ban (user)\", value= \"Bans the mentioned user!\", inline=True)\r\n embed3.add_field(name= \"p!kick (user)\", value= \"Kicks the mentioned user!\", inline=True)\r\n embed3.add_field(name= \"p!prune (number)\", value= \"Deletes a number of messages!\", inline=True)\r\n embed3.add_field(name= \"p!unban (id)\", value= \"Unbans the user with the matching ID!\", inline=True)\r\n embed3.add_field(name= \"p!giverole (user) (role)\", value= \"Gives the mentioned user a specified role!\", inline=True)\r\n embed3.add_field(name= \"p!takerole (user) (role)\", value= \"Removes a specified role from the mentioned user!\", inline=True)\r\n embed3.add_field(name= \"p!rawsay (text)\", value= \"Forces the bot the say something without any formatting!\", inline=True)\r\n embed3.set_footer(text=footer_text)\r\n\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":incoming_envelope: \", value= \"A list of commands is coming your way!\\nCheck your DMs, {}!\".format(author))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n await client.send_message(author, embed=embed1)\r\n await client.send_message(author, embed=embed2)\r\n await client.send_message(author, embed=embed3)\r\n\r\n# PING COMMAND \r\n@client.command(pass_context=True)\r\nasync def ping(ctx):\r\n pingmsg = [\"I'm here!\", \"Yes, I am here. You don't have to ping me!\", \"Hello?\", \"Oh, hi!\", \"Hey, how are you?\", \"Hello!\", \"Pong!\"]\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":satellite: Pinging...\", value= \"{}\".format(random.choice(pingmsg)))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"PING COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n# SERVER INFO COMMAND\r\n@client.command(pass_context=True)\r\nasync def serverinfo(ctx):\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \":page_with_curl: SERVER INFORMATION\"\r\n msg.add_field(name=\"MEMBERS\", value=(len(ctx.message.server.members)), inline=True)\r\n msg.add_field(name=\"CHANNELS\", value=(len(ctx.message.server.channels)), inline=True)\r\n msg.add_field(name=\"EMOJIS\", value=(len(ctx.message.server.emojis)), inline=True)\r\n msg.add_field(name=\"ID\", value=(ctx.message.server.id), inline=True)\r\n msg.add_field(name=\"REGION\", value=(ctx.message.server.region), inline=True)\r\n msg.add_field(name=\"ROLES\", value=(len(ctx.message.server.roles)), inline=True)\r\n msg.add_field(name=\"OWNER\", value=(ctx.message.server.owner), inline=True)\r\n msg.add_field(name=\"CREATED AT\", value=(ctx.message.server.created_at), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"SERVERINFO COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n# p!retard (user) - TURNS PPL INTO RETARDS\r\n@client.command(pass_context=True)\r\nasync def retard(context, userName: discord.User):\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.add_field(name= \":rofl: Retard Maker 3000\", value= \"`{} is now officially a retard!`\\n`Research shows that most retards are good people!`\".format(userName.display_name))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"RETARD COMMAND\")\r\n print(\"{}\".format(context.message.author))\r\n print(\"============================================================\")\r\n\r\n# QUOTE COMMAND\r\n@client.command(pass_context=True)\r\nasync def quote(ctx):\r\n quotes = [\"If you want to achieve greatness stop asking for permission.\",\r\n \"Things work out best for those who make the best of how things work out.\",\r\n \"To live a creative life, we must lose our fear of being wrong.\",\r\n \"What hurts you, but doesn't kill you, makes you stronger.\",\r\n \" If you are not willing to risk the usual you will have to settle for the ordinary.\",\r\n \"Trust because you are willing to accept the risk, not because it’s safe or certain.\",\r\n \"Once you choose hope, anything is possible.\",\r\n \"A positive attitude gives you power over your circumstances instead of your circumstances having power over you.\",\r\n \"Character cannot be developed in ease and quiet. Only through experience of trial and suffering can the soul be strengthened, ambition inspired, and success achieved.\",\r\n \"Keep yourself busy if you want to avoid depression. For me, inactivity is the enemy.\",\r\n \"Sometimes, you gotta pretend everything is okay.\",\r\n \"It’s always worse than it seems.\",\r\n \"I get lost inside my mind”.\",\r\n \"All alone! Whether you like it or not, alone is something you'll be quite a lot!\",\r\n \"Twinkle, twinkle little star. Let me get hit by a car. Oh, how I really want to die, jump off the roof and try to fly. Twinkle, twinkle little knife, help me end this fucking life!\",\r\n \"There’s death all around us. Everywhere we look. 1.8 people kill themselves every second. We just don’t pay attention. Until we do.\",\r\n \"I guess that’s what saying good-bye is always like–like jumping off an edge. The worst part is making the choice to do it. Once you’re in the air, there’s nothing you can do but let go.\",\r\n \"The sun kept on with its slipping away, and I thought how many small good things in the world might be resting on the shoulders of something terrible.\",\r\n \"As the light begins to intensify, so does my misery, and I wonder how it is possible to hurt so much when nothing is wrong.\",\r\n \"But grief makes a monster out of us sometimes . . . and sometimes you say and do things to the people you love that you can’t forgive yourself for.\",\r\n \"Have you ever wondered what a human life is worth? That morning, my brother’s was worth a pocket watch.\",\r\n \"A lot of you cared, just not enough.\",\r\n \"Breathing is hard. When you cry so much, it makes you realize that breathing is hard.\",\r\n \"It's not I can or I can't, it's I want or I don't want!\",\r\n \"It’s raining in my heart like it’s raining in the city. What is this sadness that pierces my heart?\",\r\n \"At some point, you have to realize that some people can stay in your heart but not in your life.\",\r\n \"I forgive, but I don't forget.\",\r\n \"I hate getting flashbacks from things I don't want to remember.\",\r\n \"Do you know the feeling of drowning while everyone around you is breathing?\",\r\n \"Fake friends are like shadows. They follow you in the sun but leave you in the dark.\",\r\n \"You laugh, but you wanna cry. You talk, but you wanna be quiet. Yes, you're smiling, but inside, you're dying.\",\r\n \"This life is like a war, you either win with a scar or die trying.\",\r\n \"I'm fine.\",\r\n \"If I killed myself tonight, the sun will still rise, the stars would still appear, the Earth will still rotate, the seasons will still change... so why not?\",\r\n \"No amount of sleep can cure the tiredness I feel.\",\r\n \"Even the devil, was once an angel.\",\r\n \"I like my music so loud, I can't hear my thoughts.\",\r\n \"I smile all the time so that nobody knows how sad and lonely I really am.\",\r\n \"My mind was a mess, then I found a razor. Now my body is a mess too.\",\r\n \"I draw with silver and it becomes red. Magic!\",\r\n \"Why am I so different from everyone else?\",\r\n \"Emotionally: I'm done. Mentally: I'm drained. Spiritually: I'm dead. Physically: I smile.\",\r\n \"It hurts when you smile just to stop the tears from falling.\",\r\n \"My blood is red. My wounds are wide. My heart hurts. I'm dead inside.\",\r\n \"I'm not totally useless. I can be used as a bad example.\",\r\n \"I'm pretending to be fine. So are they pretending to care?\",\r\n \"I'm slowly, but surely, giving up.\",\r\n \"People don't cry cause they are weak. They cry cause they were strong for too long.\",\r\n \"When I get angry, I don't yell, I don't hit, I don't show rage... I just think about ending it all.\",\r\n \"There is a hell, believe me, I've seen it.\",\r\n \"Everyone who hurt you, who left you, who didn't understand you, one day will regret it all.\",\r\n \"Walking with a friend in the dark is better than walking alone in the light.\",\r\n \"Remember, you are not alone. Darkness is and always will be with you.\",\r\n \"I don't care if I live or not.\",\r\n \"Stop trying to find a point or a meaning. There is no such thing.\",\r\n \"Not all scars show. Not all wounds heal. You can't always see the pain that others feel.\",\r\n \"We're scared to get close, cause everyone who promised they'll stay, turned their back and left.\",\r\n \"I don't like being too happy.\",\r\n \"I wanna sleep... forever.\",\r\n \"You shall not pass!\",\r\n \"You're adopted.\",\r\n \"Why should I apologize for being a monster? When no one apologized for turning me into one.\",\r\n \"You may not be my happy ending, but you are the best chapter of my life.\"]\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":scroll: Scroll of quotes\", value= \"{}\".format(random.choice(quotes)))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"QUOTE COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n@client.command(pass_context=True)\r\nasync def invite(ctx):\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"BOT INVITE :incoming_envelope:\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":white_check_mark: \", value= \"Your Bot invite have been send check your DMs, {}!\".format(author))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n await client.send_message(ctx.message.author, \"Heres Your invite link bot and the perfix is p!help enjoy and thanks for using it :) **NOTE:** to have moderation commands you should create role Paradise Bot with the caps on it and then give it to the bot role and ur self https://discordapp.com/api/oauth2/authorize?client_id=401419300096704525&permissions=0&scope=bot\")\r\n\r\n@client.command(pass_context=True)\r\nasync def server(ctx):\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"SERVER INVITE :bulb: \"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":white_check_mark: \", value= \"Your server invite have been send check your DMs, {}!\".format(author))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n await client.send_message(ctx.message.author, \"DISCORD LINK https://discord.gg/Tk8RCer \")\r\n\r\n# EIGHT BALL COMMAND\r\n@client.command(pass_context=True)\r\nasync def eightball(ctx, *, args):\r\n answer = [\"Yes!\",\r\n \"No!\",\r\n \"Probably!\",\r\n \"Most likely!\",\r\n \"Probably not!\",\r\n \"Definately!\",\r\n \"Definately not!\",\r\n \"Of course!\",\r\n \"Of course not!\",\r\n \"WTF no!\",\r\n \"Hell yeah!\"]\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"Magic Eight Ball\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":grey_question: Question:\", value= \"{}\".format(args), inline=True)\r\n msg.add_field(name= \"\\n:8ball: Eight Ball:\", value=\"{}\".format(random.choice(answer)), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"EIGHTBALL COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n# KILL COMMAND\r\n@client.command(pass_context=True)\r\nasync def kill(context, userName: discord.User):\r\n killmsgs = [\"died by getting beaten with a baseball bat covered with barbed wire!\",\r\n \"died by getting all their bones broken with chains!\",\r\n \"died from a nuclear explosion!\",\r\n \"died by getting shot in the head by an intruder!\",\r\n \"died by drowning in the ocean!\",\r\n \"died by getting eaten by a shark!\",\r\n \"got roasted so hard, they started burning and died!\",\r\n \"died by forgetting how to breathe!\",\r\n \"died by falling off the 30th floor!\",\r\n \"died by getting crushed by a meteor!\",\r\n \"died from radiation!\",\r\n \"died trying to fight an anaconda!\",\r\n \"died trying to fight darkness!\",\r\n \"died by aids!\",\r\n \"died from cancer!\",\r\n \"had a very stupid death, rather not tell what happened!\",\r\n \"died in a volcano!\",\r\n \"died by trying to leave the server! Do not try that, they were later revived in a more hell-ish version of their past life!\",\r\n \"died from not having memes to look at!\",\r\n \"died from a plane crash!\",\r\n \"were killed by an mysterious human-like figure!\",\r\n \"were killed cause they were a grammar nazi!\",\r\n \"were beaten to death by the bullies!\",\r\n \", m8 u ded lol?\",\r\n \"died fro- lol jk u not die yet\",\r\n \"got their memes stolen and died from a heart attack!\",\r\n \"died?\",\r\n \"died! Only 2 players left!\",\r\n \"were killed in the hunger games!\",\r\n \"were killed before they even had a chance to live!\",\r\n \"died lmao get r3kt\",\r\n \"were killed... BY ME!\",\r\n \"tried to cheat on a math test, almost got away with it! Their body was found in a dumpster with a big F on their chest.\",\r\n \"was killed by a cute little bunny :3\",\r\n \"was killed by Lucifer!\",\r\n \"died by watching furry porn!\",\r\n \"died.. about time.. JK JK!!\",\r\n \"got killed by a true slav!\",\r\n \"died by not squating like a true slav!\",\r\n \"died by not using google!\",\r\n \"died by opening internet explorer!\",\r\n \"died from living!\",\r\n \"died from acid rain!\",\r\n \"got hit by lightning and died!\",\r\n \"was a good person! They had a nice family and a nice house, the whole world lived in harmony and peace... until the fire nation attacked!\",\r\n \"died by reading a book!\",\r\n \"died trying!\",\r\n \"died by watching the emoji movie!\",\r\n \"died by watching the bee movie!\",\r\n \"was killed lol\",\r\n \"left the game!\",\r\n \"died trying to do a backflip!\",\r\n \"got their heart ripped out!\",\r\n \"wasn't even born, what are you on about?\",\r\n \"can't die, they are already dead!\",\r\n \"died from looking at old memes!\",\r\n \"was killed by a fidget spinner!\",\r\n \"was killed by an attack helicopter!\",\r\n \"went inside a white van and never came out!\",\r\n \"got their head ripped off!\",\r\n \"starved in a supermarket while there was a zombie apocalypse!\",\r\n \"died while trying to steal Zero's chocolate!\",\r\n \"died by trying to hit a cat!\",\r\n \"died by trying to fly!\",\r\n \"died by getting hit with an anvil!\",\r\n \"died by setting their hair on fire!\",\r\n \"was killed by a kat!\",\r\n \"was last seen entering a white van!\",\r\n \"died by having no internet connection for more than 5 seconds!\",\r\n \"died by loosing their hentai stash!\",\r\n \"was killed after someone stole their memes!\",\r\n \"was killed by a retarded chicken!\",\r\n \"died by sun light!\",\r\n \"died after commiting suicide!\",\r\n \"died trying to perform a magic trick!\",\r\n \"left the game.\",\r\n \"was always the type of person who fights fire with fire... that didn't end well. They were a fireman!\",\r\n \"was killed by a bunneh!\",\r\n \"died before they had a chance to live!\",\r\n \"died... inside!\",\r\n \"had a boring death!\",\r\n \"died being a hero!\"]\r\n \r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.add_field(name=\"NEWS :gun:\", value=\"`{} {}`\".format(userName.display_name, random.choice(killmsgs)))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"KILL COMMAND\")\r\n print(\"{}\".format(context.message.author))\r\n print(\"============================================================\")\r\n\r\n# ROAST COMMAND\r\n@client.command(pass_context=True)\r\nasync def roast(context, userName: discord.User):\r\n roasts = [\"I saw a piece of shit today. It reminded me of you.\",\r\n \"your face is a physical weapon.\",\r\n \"I know you from somewhere. Oh yea, I see you in the trashcan.\"\r\n \"don't worry, you're not adopted... yet. We still haven't found anyone who wants you.\",\r\n \"unless your name is 'Google', stop acting like you know everything.\",\r\n \"if I wanted to kill myself I would climb up your ego and jump in your IQ\",\r\n \"you are so stupid that you got hit by a parked car.\",\r\n \"you're so fat that when god created light, you were asked to move out of the way.\",\r\n \"I heard you were taken to a dog show and you won.\",\r\n \"you suck so much, I can use you as a vacumcleaner.\",\r\n \"maybe you should stop making fun of others just to get attention, cause the world doesn't rotate around your crap looking ass.\",\r\n \"try not to spit when you talk, we don't need a public shower here.\",\r\n \"you remind me of the owner, eew.\",\r\n \"I can't breathe when I see you... cause I'm suffocating of your bullshit.\",\r\n \"your mom is twice the man you will ever be.\",\r\n \"you have the right to remain silent, cause what ever you say will be stupid anyways.\",\r\n \"the only thing you are good at is being a cunt.\",\r\n \"it's hard for you isn't it? Not to be a dick.\",\r\n \"it's hard to ignore you, mostly cause you smell like shit.\",\r\n \"you must've fallen from Mars, cause you clearly can't understand anything happening around you.\",\r\n \"did you fall from Heaven? Cause so did Satan.\",\r\n \"you're so ugly, you went to an ugly competition and they said 'No professionals allowed!'.\",\r\n \"you really shouldn't try cooking, cause the last time you did, it ended with 3 houses being on fire.\",\r\n \"did Satan send you to kill people? Cause your smell is killing me.\",\r\n \"I'd give you a nasty look but you've already got one.\",\r\n \"if laughter is the best medicine, your face must be curing the world.\",\r\n \"the only way you'll ever get laid is if you crawl up a chicken's ass and wait.\",\r\n \"scientists say the universe is made up of neutrons, protons and electrons. They forgot to mention morons.\",\r\n \"your family tree must be a cactus because everyone on it is a prick.\",\r\n \"someday you'll go far... and I hope you stay there.\",\r\n \"save your breath, you'll need it to blow your date.\",\r\n \"the zoo called. They're wondering how you got out of your cage?\",\r\n \"you have something on your chin... no, the 3rd one down.\",\r\n \"thought of you today. It reminded me to take the garbage out.\",\r\n \"you're so ugly when you look in the mirror, your reflection looks away.\",\r\n \"it's better to let someone think you're stupid than open your mouth and prove it.\",\r\n \"were you born this stupid or did you take lessons?\",\r\n \"calling you an idiot would be an insult to all stupid people.\",\r\n \"I just stepped in something that was smarter than you... and smelled better too.\"]\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.add_field(name=\":fire: Roast Machine\", value=\"`{}, {}`\".format(userName.display_name, random.choice(roasts)))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"ROAST COMMAND\")\r\n print(\"{}\".format(context.message.author))\r\n print(\"============================================================\")\r\n\r\n# HEAVEN COMMAND\r\n@client.command(pass_context=True)\r\nasync def heaven(ctx):\r\n heaven = [\"Heaven is Real – God created it\",\r\n \"Jesus, the Christ came down to Earth from Heaven\",\r\n \"Jesus went back to Heaven when He rose from the dead\",\r\n \"Jesus is now seated at the right hand of God (the Majesty) in Heaven\",\r\n \"heaven is also known as a place where the birds fly and the clouds float – the Bible also calls this the firmament\",\r\n \"heaven is a place where the stars, sun and constellations shine – this is the stellar heaven\",\r\n \"Heaven is where the believer goes when he leaves this planet – it is home\",\r\n \"Believers can look forward to a new heaven – it is the blessed hope and a perfect place\",\r\n \"Heaven is God’s home and He existed before His creation – this is the Heaven of heavens; the high and holy place\",\r\n \"Before creation, Jesus (God’s Son) and Holy Spirit lived in Heaven with God\",]\r\n author = ctx.message.author\r\n footer_text = \"Paradise\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":angel: Heaven Facts\", value= \"{}\".format(random.choice(heaven)))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"HEAVEN COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n\r\n# SUICIDE COMMAND\r\n@client.command(pass_context=True)\r\nasync def suicide(ctx):\r\n suicide = [\"In 2015 (latest available data), there were 44,193 reported suicide deaths in the U.S.\",\r\n \"Suicide is the 2nd leading cause of death for those between the ages of 15 and 34 in the United States.\",\r\n \"Currently, suicide is the 10th leading cause of death in the United States.\",\r\n \"A person dies by suicide about every 12.8 minutes in the United States.\",\r\n \"Every day, approximately 121 Americans take their own life.\",\r\n \"Ninety percent of all people who die by suicide have a diagnosable psychiatric disorder at the time of their death.\",\r\n \"There are four male suicides for every female suicide, but three times as many females as males attempt suicide.\",\r\n \"494,169 people visited a hospital for injuries due to self-harm behavior, suggesting that approximately 12 people harm themselves (not necessarily intending to take their lives) for every reported death by suicide.\",\r\n \"25 million Americans suffer from depression each year.\",\r\n \"Over 50 percent of all people who die by suicide suffer from major depression. If one includes alcoholics who are depressed, this figure rises to over 75 percent.\",\r\n \"Depression affects nearly 5-8 percent of Americans ages 18 and over in a given year.\",\r\n \"Depression is among the most treatable of psychiatric illnesses. Between 80 percent and 90 percent of people with depression respond positively to treatment, and almost all patients gain some relief from their symptoms. But first, depression has to be recognized.\",\r\n \"More Americans suffer from depression than coronary heart disease, cancer, and HIV/AIDS.\",\r\n \"Nearly 30,000 Americans commit suicide every year.\",\r\n \"In the U.S., suicide rates are highest during the spring.\",\r\n \"Suicide is the 3rd leading cause of death for 15 to 24-year-olds and 2nd for 24 to 35-year-olds.\",\r\n \"On average, 1 person commits suicide every 16.2 minutes.\",\r\n \"Each suicide intimately affects at least 6 other people.\",\r\n \"About 2/3 of people who complete suicide are depressed at the time of their deaths. Depression that is untreated, undiagnosed, or ineffectively treated is the number 1 cause of suicide.\",\r\n \"There is 1 suicide for every 25 attempted suicides.\",\r\n \"Males make up 79% of all suicides, while women are more prone to having suicidal thoughts.\",\r\n \" in 65,000 children ages 10 to 14 commit suicide each year.\",]\r\n author = ctx.message.author\r\n footer_text = \"Paradise \"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":skull: Suicide Facts\", value= \"{}\".format(random.choice(suicide)))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"SUICIDE COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n \r\n\r\n# SAY COMMAND\r\n@client.command(pass_context=True)\r\nasync def say(context, *, args):\r\n await client.say(\"`{}`\".format(args))\r\n print(\"============================================================\")\r\n print(\"SAY COMMAND\")\r\n print(\"{}\".format(context.message.author))\r\n print(\"============================================================\")\r\n\r\n# USER INFO COMMAND\r\n@client.command(pass_context=True)\r\nasync def profile(context, userName: discord.Member):\r\n imageurl = userName.avatar_url\r\n author = context.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \":page_with_curl: USER INFORMATION\"\r\n msg.set_thumbnail(url=imageurl)\r\n msg.set_author(name=str(userName), icon_url=userName.avatar_url)\r\n msg.add_field(name=\"NAME:\", value=(userName), inline=True)\r\n msg.add_field(name=\"ID:\", value=(userName.id), inline=True)\r\n msg.add_field(name=\"CREATED AT:\", value=(userName.created_at), inline=True)\r\n msg.add_field(name=\"JOINED AT:\", value=(userName.joined_at), inline=True)\r\n msg.add_field(name=\"STATUS:\", value=(userName.status), inline=True)\r\n msg.add_field(name=\"IS BOT:\", value=(userName.bot), inline=True)\r\n msg.add_field(name=\"GAME:\", value=(userName.game), inline=True)\r\n msg.add_field(name=\"NICKNAME:\", value=(userName.nick), inline=True)\r\n msg.add_field(name=\"TOP ROLE:\", value=(userName.top_role), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"PROFILE COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n'''\r\nMODERATION COMMANDS\r\n'''\r\n\r\n# RAW SAY COMMAND\r\n@client.command(pass_context=True)\r\nasync def rawsay(context, *, args):\r\n for role in context.message.author.roles:\r\n if role.name == \"Paradise Bot\":\r\n await client.say(\"{}\".format(args))\r\n print(\"============================================================\")\r\n print(\"RAWSAY COMMAND\")\r\n print(\"{}\".format(context.message.author))\r\n print(\"============================================================\")\r\n\r\n# TAKE/GIVE ROLE COMMAND\r\n@client.command(pass_context=True)\r\nasync def takerole(ctx, userName: discord.Member, *, rolename):\r\n for role in ctx.message.author.roles:\r\n if role.name == \"Paradise Bot\":\r\n rolename2 = discord.utils.get(ctx.message.server.roles, name='{}'.format(rolename))\r\n await client.remove_roles(userName, rolename2)\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":outbox_tray: Taking away role...\", value= \"`{} has removed {} from {}`\".format(ctx.message.author, rolename2, userName.display_name), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"TAKEROLE COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n@client.command(pass_context=True)\r\nasync def giverole(ctx, userName: discord.Member, *, rolename):\r\n for role in ctx.message.author.roles:\r\n if role.name == \"Paradise Bot\":\r\n rolename2 = discord.utils.get(ctx.message.server.roles, name='{}'.format(rolename))\r\n await client.add_roles(userName, rolename2)\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":inbox_tray: Giving role...\", value= \"`{} has given {} to {}`\".format(ctx.message.author, rolename2, userName.display_name), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"GIVEROLE COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n# UNBAN COMMAND\r\n@client.command(pass_context=True)\r\nasync def unban(ctx, userID):\r\n for role in ctx.message.author.roles:\r\n if role.name == \"Paradise Bot\":\r\n banned_users = await client.get_bans(ctx.message.server)\r\n user = discord.utils.get(banned_users,id=userID)\r\n if user is not None:\r\n await client.unban(ctx.message.server, user)\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":tools: UNBAN TOOLS\", value= \"`{}#{} has been unbanned by {}!`\".format(user.name, user.discriminator, ctx.message.author), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"UNBAN COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n else:\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":octagonal_sign: ERROR\", value= \"`{} isn't banned!`\".format(user.name), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"UNBAN COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n# KICK COMMAND\r\n@client.command(pass_context=True)\r\nasync def kick(ctx, userName: discord.Member):\r\n for role in ctx.message.author.roles:\r\n if role.name == \"Paradise Bot\":\r\n await client.kick(userName)\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":boot: KICK BOOT\", value= \"`{} has been kicked by {}!`\".format(userName.display_name, ctx.message.author), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"KICK COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n# BAN COMMAND\r\n@client.command(pass_context=True)\r\nasync def ban(ctx, userName: discord.Member, days=None):\r\n for role in ctx.message.author.roles:\r\n if role.name == \"Paradise Bot\":\r\n if days == None:\r\n await client.ban(userName)\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":hammer: BAN HAMMER\", value= \"`{} has been banned by {}! No messages were deleted!`\".format(userName.display_name, ctx.message.author), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"BAN COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n else:\r\n await client.ban(userName, delete_message_days=days)\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":hammer: BAN HAMMER\", value= \"`{} has been banned by {}! Deleting messages from the past {} days...`\".format(userName.display_name, ctx.message.author, days), inline=True)\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"BAN COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n@client.command(pass_context=True)\r\nasync def prune(ctx, number : int):\r\n for role in ctx.message.author.roles:\r\n if role.name == \"Paradise Bot\":\r\n deleted = await client.purge_from(ctx.message.channel, limit=number)\r\n author = ctx.message.author\r\n footer_text = \"Paradise ☁\"\r\n msg = discord.Embed(colour=random.randint(0, 0xFFFFFF), description= \"\")\r\n msg.title = \"\"\r\n msg.set_author(name=str(author.name), icon_url=author.avatar_url)\r\n msg.add_field(name= \":wastebasket: CHAT CLEANER\", value= \"`Deleted {} message(s)!`\".format(len(deleted), inline=True))\r\n msg.set_footer(text=footer_text)\r\n await client.say(embed=msg)\r\n print(\"============================================================\")\r\n print(\"PRUNE COMMAND\")\r\n print(\"{}\".format(author))\r\n print(\"============================================================\")\r\n\r\n'''\r\n'''\r\n# THIS WILL TURN ON YOUR BOT\r\nrequests.post('https://cleverbot.io/1.0/create', json={'user':CBuser, 'key':CBkey, 'nick':'Paradise'})\r\n\r\nclient.run('NDAxNDE5MzAwMDk2NzA0NTI1.DUC_6g.fBLV2RXYxMqyY384u5lu4wtty04')\r\n","sub_path":"virusTEST.py","file_name":"virusTEST.py","file_ext":"py","file_size_in_byte":42409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"623033009","text":"print(\"+++ List Bindings (SID, identity, type, address:phone number).\")\nimport os\nfrom twilio.rest import Client\naccount_sid = os.environ.get(\"ACCOUNT_SID\")\nauth_token = os.environ.get(\"AUTH_TOKEN\")\nclient = Client(account_sid, auth_token)\nnotifyServiceSid = os.environ.get(\"NOTIFY_SERVICE_SID\")\nbindings = client.notify.services(notifyServiceSid).bindings \\\n .list(tag='all')\nfor binding in bindings:\n print(\"+ \" + binding.sid + \" \" + binding.identity + \" \" + binding.binding_type + \" \" + binding.address)\nprint(\"+ End of list.\")","sub_path":"notify/listBindings2_1.py","file_name":"listBindings2_1.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"486072222","text":"# -*- coding: utf-8 -*-\nimport re\nimport os\nimport json\n\ndef getBucket(arr_card):\n # 创建数组\n bucket = []\n for i in range(6):\n bucket.append([])\n for j in range(16):\n bucket[i].append(0)\n # 赋值有牌的地方\n for i in arr_card:\n a = int(i/4)\n b = i % 4 + 1\n bucket[b][a] = 1\n return bucket\ndef CardVal(cards_):\n for i in range(2, 15):\n sum = 0\n for j in range(1, 5):\n if cards_[j][i] == 1:\n sum = sum + 1\n cards_[5][i] = sum\n for i in range(1, 5):\n sum = 0\n for j in range(2, 15):\n if cards_[i][j] == 1:\n sum = sum + 1\n cards_[i][15] = sum\n return cards_\n","sub_path":"water.py","file_name":"water.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"216318634","text":"# -*- coding: utf-8 -*-\n\n\n#Unicode\nimport unicodedata as unicode\n\n#Qt Classes\nfrom PyQt5.QtGui import QFont\n\n\n#WIDGETS\nfrom PyQt5.QtWidgets import QTextEdit\n\n\n#PARAMETERS\nfrom parameters import FONT_SIZE\n\n\n\nclass MYTextEdit(QTextEdit):\n \n #INIT\n def __init__(self, parent=None):\n super(MYTextEdit, self).__init__()\n \n \n # ATTRIBUTES-------------------------------------\n # END ATTRIBUTES---------------------------------\n \n\n # PARMS------------------------------------------\n if parent: self.setParent(parent)\n\n font = QFont()\n font.setPointSize(FONT_SIZE)\n\n self.setFont(font)\n \n # END PARMS--------------------------------------\n\n\n\n \n #EVENTS-----------------------------------------------\n #END EVENTS-------------------------------------------\n \n \n \n # METHODES--------------------------------------------\n # END METHODES----------------------------------------\n \n \nif __name__ == '__main__':\n from PyQt5.QtWidgets import QApplication\n from PyQt5.QtWidgets import QPushButton\n app = QApplication([])\n p = QPushButton()\n win = MYTextEdit()\n win.show()\n p.show()\n app.exec_()","sub_path":"Widgets/TextEdit.py","file_name":"TextEdit.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"19097125","text":"import os\nimport csv\n\nprint(\"Election Results\")\nprint(\"-----------------------------\")\n\ncsvpath = os.path.join('..', 'PyPoll', 'election_data.csv')\n\nwith open(csvpath, newline='') as csvfile:\n\n csvreader = csv.reader(csvfile, delimiter=',')\n \n #eliminate header\n csv_header = next(csvfile)\n\n totalvotes = 0\n khan = 0\n correy = 0\n li = 0\n otooley = 0\n for row in csvreader:\n totalvotes += 1\n\n if str(row[2]) == \"Khan\":\n khan += 1\n if str(row[2]) == \"Correy\":\n correy += 1\n if str(row[2]) == \"Li\":\n li += 1\n if str(row[2]) == \"O'Tooley\":\n otooley += 1\n\n\n khanper = (khan/totalvotes) * 100\n correyper = (correy/totalvotes) * 100\n liper = (li/totalvotes) * 100\n otooleyper = (otooley/totalvotes) * 100\n\n winner = \"\"\n if khan > correy and khan > li and khan > otooley:\n winner = \"Khan\"\n if correy > khan and correy > li and correy > otooley:\n winner = \"Correy\"\n if li > khan and li > correy and li > otooley:\n winner = \"Li\"\n if otooley > khan and otooley > correy and otooley > li:\n winner = \"O'Tooley\"\n \n\n \n print(\"Total Votes: \" + str(totalvotes))\n print(\"----------------------------------\")\n print(\"Khan: \" + str(round(khanper,5)) + \"% (\" + str(khan) + \")\")\n print(\"Correy: \" + str(round(correyper,5)) + \"% (\" + str(correy) + \")\")\n print(\"Li: \" + str(round(liper,5)) + \"% (\" + str(li) + \")\")\n print(\"O'Tooley: \" + str(round(otooleyper,5)) + \"% (\" + str(otooley) + \")\")\n print(\"Winner: \" + winner)\n\n\n#round(,2)\n","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"127525739","text":"from django.shortcuts import render, redirect\nfrom django.http import Http404, HttpResponse\nfrom django.template import RequestContext, loader\nfrom django.core.exceptions import PermissionDenied\nfrom cardapio.models import PromocoesDaPizzaria, Produto, Ingrediente, Item\n\ndef promoIndex(request):\n\treturn render(request, 'promocao/index.html')\n\ndef promoCriar(request):\n\tlatest_produto_list = Produto.objects.all().order_by('-id')\n\tlatest_ingrediente_list = Ingrediente.objects.all().order_by('-id')\n\tcontext = {'latest_produto_list': latest_produto_list, 'latest_ingrediente_list' : latest_ingrediente_list}\n\treturn render(request, 'promocao/criar.html', context)\n\ndef promoAdicionar(request):\n\tif request.method == 'POST':\n\t\ttry:\n\t\t\tpromocao = PromocoesDaPizzaria.objects.get(nome=request.POST['nome'])\n\t\t\traise PermissionDenied\n\t\texcept (PromocoesDaPizzaria.DoesNotExist):\n\t\t\tnome=request.POST['nome']\n\t\t\tdataInicio=request.POST['dataInicio']\n\t\t\tdataTermino=request.POST['dataTermino']\n\t\t\tdesconto=request.POST['desconto']\n\t\t\titemExtra=request.POST['itemExtra']\n\t\t\tprodutoBase = request.POST['produtoBase']\n\t\t\tquantiaProdutoBase = request.POST['quantiaProdutoBase']\n\t\t\tingredienteBase = request.POST['ingredienteBase']\n\t\t\tif int(produtoBase) > 0:\n\t\t\t\tingredienteBase = 0\n\t\t\telif int(ingredienteBase) > 0:\n\t\t\t\tprodutoBase = 0\n\t\t\t\tquantiaProdutoBase = 0\n\t\t\tpromocao = PromocoesDaPizzaria(nome=nome, dataInicio=dataInicio, dataTermino=dataTermino, desconto=desconto, itemExtra=itemExtra, produtoBase=produtoBase, quantiaProdutoBase=quantiaProdutoBase, ingredienteBase=ingredienteBase)\n\t\t\tpromocao.save()\n\t\t\treturn redirect('/promocao/%d' % promocao.id)\n\telse:\n\t\traise PermissionDenied\n\t\treturn render(request, 'promocao/index.html')\n\t\t\ndef promoListar(request):\n\tlatest_promo_list = PromocoesDaPizzaria.objects.all().order_by('-id')\n\tcontext = {'latest_promo_list': latest_promo_list}\n\treturn render(request, 'promocao/listar.html', context)\n\t\ndef promoEditar(request, promocao_id):\n\tif request.method == 'POST':\n\t\ttry:\n\t\t\tpromocao = PromocoesDaPizzaria.objects.get(pk=promocao_id)\n\t\t\tpromocao.nome = request.POST['nome']\n\t\t\tpromocao.dataInicio = request.POST['dataInicio']\n\t\t\tpromocao.dataTermino = request.POST['dataTermino']\n\t\t\tpromocao.desconto = request.POST['desconto']\n\t\t\tpromocao.itemExtra = request.POST['itemExtra']\n\t\t\tprodutoBase = request.POST['produtoBase']\n\t\t\tquantiaProdutoBase = request.POST['quantiaProdutoBase']\n\t\t\tingredienteBase = request.POST['ingredienteBase']\n\t\t\tif int(produtoBase) > 0:\n\t\t\t\tpromocao.produtoBase = produtoBase\n\t\t\t\tpromocao.quantiaProdutoBase = quantiaProdutoBase\n\t\t\t\tpromocao.ingredienteBase = 0\n\t\t\telif int(ingredienteBase) > 0:\n\t\t\t\tpromocao.produtoBase = 0\n\t\t\t\tpromocao.quantiaProdutoBase = 0\n\t\t\t\tpromocao.ingredienteBase = ingredienteBase\n\t\t\tpromocao.save()\n\t\texcept (PromocoesDaPizzaria.DoesNotExist):\n\t\t\traise Http404\n\t\treturn redirect('/promocao/%d' % promocao.id)\n\telse:\n\t\traise PermissionDenied\n\ndef promoExcluir(request, promocao_id):\n\ttry:\n\t\tpromocao = PromocoesDaPizzaria.objects.get(pk=promocao_id)\n\t\tpromocao.delete()\n\texcept (PromocoesDaPizzaria.DoesNotExist):\n\t\traise Http404\n\tlatest_promo_list = PromocoesDaPizzaria.objects.all().order_by('-id')\n\tcontext = {'latest_promo_list': latest_promo_list}\n\treturn render(request, 'promocao/listar.html', context)\n\ndef promoConsultar(request, promocao_id):\n\ttry:\n\t\tpromocao = PromocoesDaPizzaria.objects.get(pk=promocao_id)\n\t\tlatest_produto_list = Produto.objects.all().order_by('-id')\n\t\tlatest_ingrediente_list = Ingrediente.objects.all().order_by('-id')\n\t\t\n\t\tstringDataInicio = str(promocao.dataInicio.year)\n\t\tif promocao.dataInicio.month >= 10:\n\t\t\tstringDataInicio += '-'+str(promocao.dataInicio.month)\n\t\telse:\n\t\t\tstringDataInicio += '-0'+str(promocao.dataInicio.month)\n\t\tif promocao.dataInicio.day >= 10:\n\t\t\tstringDataInicio += '-'+str(promocao.dataInicio.day)\n\t\telse:\n\t\t\tstringDataInicio += '-0'+str(promocao.dataInicio.day)\n\t\t\n\t\tstringDataTermino = str(promocao.dataTermino.year)\n\t\tif promocao.dataTermino.month >= 10:\n\t\t\tstringDataTermino += '-'+str(promocao.dataTermino.month)\n\t\telse:\n\t\t\tstringDataTermino += '-0'+str(promocao.dataTermino.month)\n\t\tif promocao.dataTermino.day >= 10:\n\t\t\tstringDataTermino += '-'+str(promocao.dataTermino.day)\n\t\telse:\n\t\t\tstringDataTermino += '-0'+str(promocao.dataTermino.day)\n\t\t\n\t\tif int(promocao.produtoBase) == 0:\n\t\t\tcheckProduto=False\n\t\telif int(promocao.ingredienteBase) == 0:\n\t\t\tcheckProduto=True\n\t\tcontext = {'latest_produto_list': latest_produto_list, 'latest_ingrediente_list' : latest_ingrediente_list, 'promocao': promocao, 'checkProduto': checkProduto, 'stringDataInicio': stringDataInicio, 'stringDataTermino': stringDataTermino}\n\texcept PromocoesDaPizzaria.DoesNotExist:\n\t\traise Http404\n\treturn render(request, 'promocao/promocao.html', context )\n","sub_path":"Web/promocao/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8364580","text":"import sys\nfrom typing import List\nfrom bisect import bisect\n\ndef search(array: list(), in_search: int) -> int:\n point_of_rotation = find_point_of_rotation(array)\n print(f'Point of Rotation: {point_of_rotation}, InSearch: {in_search}')\n\n lo = 0\n hi = len(array)\n if (array[lo] < in_search and array[point_of_rotation - 1] >= in_search):\n hi = point_of_rotation\n else:\n lo = point_of_rotation\n\n binary_search = bisect(array, in_search, lo, hi)\n return binary_search - 1\n\n\ndef find_point_of_rotation(array: List[int]) -> int:\n lo = 0\n hi = len(array)\n last_element = array[len(array) - 1]\n mid = None\n while (lo < hi):\n mid = int((lo + hi) / 2)\n if (array[mid - 1] > array[mid]):\n break\n # If the point in consideration is bigger than the last element, then the point of rotaton is towards the right\n if (array[mid] >= last_element):\n lo = mid + 1\n else:\n hi = mid - 1\n\n return mid\n\n\nif __name__ == \"__main__\":\n array1 = None\n in_search = None\n\n if (len(sys.argv) == 1):\n array1 = list(map(int, input().strip().split()))\n elif (len(sys.argv) == 3):\n array1 = list(map(int, sys.argv[1].split(\",\")))\n in_search = int(sys.argv[2].strip())\n\n else:\n raise Exception(\"Incorrect number of arguments\")\n search_index = search(array1, in_search)\n print(search_index)\n\n","sub_path":"LeetCode/search_in_rotated_array.py","file_name":"search_in_rotated_array.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"262069854","text":"#\n# Copyright (c) 2020-2021 Arm Limited and Contributors. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\nimport pathlib\nfrom unittest import TestCase\nfrom mbed_tools.devices._internal.candidate_device import CandidateDevice\n\n\ndef build_candidate_data(**overrides):\n defaults = {\n \"product_id\": \"0x1234\",\n \"vendor_id\": \"0x5678\",\n \"mount_points\": (pathlib.Path(\"./foo\"),),\n \"serial_number\": \"qwer\",\n \"serial_port\": \"COM1\",\n }\n return {**defaults, **overrides}\n\n\nclass TestCandidateDevice(TestCase):\n def test_produces_a_valid_candidate(self):\n candidate_data = build_candidate_data()\n candidate = CandidateDevice(**candidate_data)\n\n self.assertEqual(candidate.product_id, candidate_data[\"product_id\"])\n self.assertEqual(candidate.vendor_id, candidate_data[\"vendor_id\"])\n self.assertEqual(candidate.mount_points, candidate_data[\"mount_points\"])\n self.assertEqual(candidate.serial_number, candidate_data[\"serial_number\"])\n self.assertEqual(candidate.serial_port, candidate_data[\"serial_port\"])\n\n def test_raises_when_product_id_is_empty(self):\n candidate_data = build_candidate_data(product_id=\"\")\n with self.assertRaisesRegex(ValueError, \"product_id\"):\n CandidateDevice(**candidate_data)\n\n def test_raises_when_product_id_is_not_hex(self):\n candidate_data = build_candidate_data(product_id=\"TEST\")\n with self.assertRaisesRegex(ValueError, \"product_id\"):\n CandidateDevice(**candidate_data)\n\n def test_prefixes_product_id_hex_value(self):\n candidate_data = build_candidate_data(product_id=\"ff01\")\n candidate = CandidateDevice(**candidate_data)\n self.assertEqual(candidate.product_id, \"0xff01\")\n\n def test_raises_when_vendor_id_is_empty(self):\n candidate_data = build_candidate_data(vendor_id=\"\")\n with self.assertRaisesRegex(ValueError, \"vendor_id\"):\n CandidateDevice(**candidate_data)\n\n def test_raises_when_vendor_id_is_not_hex(self):\n candidate_data = build_candidate_data(vendor_id=\"TEST\")\n with self.assertRaisesRegex(ValueError, \"vendor_id\"):\n CandidateDevice(**candidate_data)\n\n def test_prefixes_vendor_id_hex_value(self):\n candidate_data = build_candidate_data(vendor_id=\"cbad\")\n candidate = CandidateDevice(**candidate_data)\n self.assertEqual(candidate.vendor_id, \"0xcbad\")\n\n def test_raises_when_mount_points_are_empty(self):\n with self.assertRaisesRegex(ValueError, \"mount_points\"):\n CandidateDevice(product_id=\"1234\", vendor_id=\"1234\", mount_points=[], serial_number=\"1234\")\n\n def test_raises_when_serial_number_is_empty(self):\n candidate_data = build_candidate_data(serial_number=\"\")\n with self.assertRaisesRegex(ValueError, \"serial_number\"):\n CandidateDevice(**candidate_data)\n","sub_path":"tests/devices/_internal/test_candidate_device.py","file_name":"test_candidate_device.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"577891781","text":"from flask import Flask, jsonify, request\nfrom flask_cors import CORS \nimport sqlite3\nimport random\nimport string\nfrom datetime import datetime\n\ndef createUser_table():\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n c.execute('''\n CREATE TABLE IF NOT EXISTS user(\n\tuserID INTEGER PRIMARY KEY,\n\tusername VARCHAR(20) NOT NULL,\n\tdocument VARCHAR(20) NOT NULL UNIQUE,\n\ttelephone VARCHAR(10) NOT NULL,\n\temail VARCHAR(20) NOT NULL UNIQUE,\n\tdepartment VARCHAR(20) NOT NULL,\n\tcity VARCHAR(20) NOT NULL,\n\taddress VARCHAR(20) NOT NULL,\n\tpassword VARCHAR(20) NOT NULL,\n token VARCHAR(16) DEFAULT 0);\n ''')\n conn.commit()\n c.close()\n conn.close()\n\ndef createAdmin_table():\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n c.execute('''\n CREATE TABLE IF NOT EXISTS admin(\n\tuserID INTEGER PRIMARY KEY,\n\tusername VARCHAR(20) NOT NULL,\n\temail VARCHAR(20) NOT NULL UNIQUE,\n\tpassword VARCHAR(20) NOT NULL,\n token VARCHAR(16) DEFAULT 0);\n ''')\n conn.commit()\n c.close()\n conn.close()\n\ndef createWish_table():\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n c.execute('''\n CREATE TABLE IF NOT EXISTS wish(\n\torderId INTEGER PRIMARY KEY,\n\tcodUser INTEGER NOT NULL,\n\tcodProduct INTEGER NOT NULL,\n description VARCHAR(20) NOT NULL,\n\tunits INTEGER NOT NULL DEFAULT 1,\n\tdate VARCHAR(30) NOT NULL,\n priceUnit INTEGER NOT NULL,\n total INTEGER NOT NULL,\n FOREIGN KEY(\"codUser\") REFERENCES \"user\"(\"userID\"),\n\tFOREIGN KEY(\"codProduct\") REFERENCES \"product\"(\"productId\"));\n ''')\n conn.commit()\n c.close()\n conn.close()\n \ndef createProduct_table():\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n c.execute('''\n CREATE TABLE IF NOT EXISTS product(\n\tproductId VARCHAR(11) NOT NULL PRIMARY KEY,\n\tdescription VARCHAR(20) NOT NULL,\n\tprice INTEGER NOT NULL);\n ''')\n conn.commit()\n c.close()\n conn.close()\n\ndef data_entry(name,document,telephone,email,department,city,address,password): #Para registrar un usuario\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n c.execute(\"INSERT INTO user (userName, document, telephone, email,department,city,address,password) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\",\n (name,document,telephone,email,department,city,address,password))\n conn.commit()\n c.close()\n conn.close() \n \n\ndef token_entry(token,email,table): #Para asignar el token a un usuario\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n c.execute(\"UPDATE \"+table+\" SET token=? WHERE email=?\", (token,email))\n conn.commit()\n c.close()\n conn.close()\n \ndef verifyLogin(email,password,table):\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n find_user = (\"SELECT * FROM \"+table+\" WHERE email = ? AND password = ?\")\n c.execute(find_user,[(email),(password)])\n if c.fetchone() is not None:\n digits=\"\"\n for i in range(16):\n letters = string.ascii_lowercase\n digits = ''.join(random.choice(letters) for i in range(16))\n token_entry(digits, email,table)\n conn.commit()\n c.close()\n conn.close()\n return digits\n else:\n conn.commit()\n c.close()\n conn.close()\n return False \n\ndef make_order(token,product,units):\n fecha = datetime.now()\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n find_user = (\"SELECT userID FROM user WHERE token = ?\")\n c.execute(find_user,[(token)])\n user = c.fetchone()\n c.execute(\"SELECT units FROM wish WHERE codUser = ? AND codProduct = ? \",(user[0],product))\n exist = c.fetchone()\n if exist is not None: \n newunits = int(exist[0])+int(units)\n c.execute(\"UPDATE wish SET units=? WHERE codUser = ? AND codProduct = ?\",(newunits,user[0],product))\n find_price = (\"SELECT price FROM product WHERE productId = ?\")\n c.execute(find_price,[(product)])\n price = c.fetchone()\n c.execute(\"UPDATE wish SET total=? WHERE codUser = ? AND codProduct = ?\",(newunits*int(price[0]),user[0],product))\n conn.commit()\n c.close()\n conn.close()\n else:\n find_description = (\"SELECT description,price FROM product WHERE productId = ?\")\n c.execute(find_description,[(product)])\n description = c.fetchone()\n c.execute(\"INSERT INTO wish(codUser,codProduct,description,units,date,priceUnit,total) VALUES(?,?,?,?,?,?,?)\",(user[0],product,description[0],units,fecha,description[1],int(description[1])*int(units)))\n c.execute(\"UPDATE wish SET date=? WHERE codUser = ? AND codProduct = ?\",(fecha,user[0],product))\n conn.commit()\n c.close()\n conn.close()\n \ndef update_user_order(cod,product,units):\n fecha = datetime.now()\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n c.execute(\"SELECT units FROM wish WHERE codUser = ? AND codProduct = ? \",(cod,product))\n exist = c.fetchone()\n if exist is not None: \n newunits = int(exist[0])+int(units)\n c.execute(\"UPDATE wish SET units=? WHERE codUser = ? AND codProduct = ?\",(newunits,cod,product))\n find_price = (\"SELECT price FROM product WHERE productId = ?\")\n c.execute(find_price,[(product)])\n price = c.fetchone()\n c.execute(\"UPDATE wish SET total=? WHERE codUser = ? AND codProduct = ?\",(newunits*int(price[0]),cod,product))\n c.execute(\"UPDATE wish SET date=? WHERE codUser = ? AND codProduct = ?\",(fecha,cod,product))\n conn.commit()\n c.close()\n conn.close()\n\n else:\n find_description = (\"SELECT description,price FROM product WHERE productId = ?\")\n c.execute(find_description,[(product)])\n description = c.fetchone()\n c.execute(\"INSERT INTO wish(codUser,codProduct,description,units,date,priceUnit,total) VALUES(?,?,?,?,?,?,?)\",(cod,product,description[0],units,fecha,description[1],int(description[1])*int(units)))\n conn.commit()\n c.close()\n conn.close()\n\ndef consult_order(token):\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n find_user = (\"SELECT userID FROM user WHERE token = ?\")\n c.execute(find_user,[(token)])\n user = c.fetchone()\n if user is not None:\n find_products = (\"SELECT codProduct,units,description,total FROM wish WHERE codUser = ?\")\n c.execute(find_products,[(user[0])])\n data = c.fetchall()\n conn.commit()\n c.close()\n conn.close()\n return data\n else:\n conn.commit()\n c.close()\n conn.close()\n return False\n\ndef admin_consult_order(cod):\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n find_products = (\"SELECT codProduct,units,description,total FROM wish WHERE codUser = ?\")\n c.execute(find_products,[(cod)])\n data = c.fetchall()\n conn.commit()\n c.close()\n conn.close()\n return data\n \ndef delete_order(token,product):\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n find_user = (\"SELECT userID FROM user WHERE token = ?\")\n c.execute(find_user,[(token)])\n user = c.fetchone()\n if user is not None:\n c.execute(\"DELETE FROM wish WHERE codProduct = ? AND codUser = ?\", (product,user[0]))\n conn.commit()\n c.close()\n conn.close()\n return True\n else:\n c.close()\n conn.close()\n return False\n \ndef delete_user_order(cod):\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n c.execute(\"DELETE FROM wish WHERE codUser = ?\", (cod))\n conn.commit()\n c.close()\n conn.close()\n \n \ndef logout_user(token,table):\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n if token == 0:\n c.close()\n conn.close()\n return False\n else:\n find_user = (\"SELECT userID FROM \"+table+\" WHERE token = ?\")\n c.execute(find_user,[(token)])\n user = c.fetchone()\n c.execute(\"UPDATE \"+table+\" SET token=? WHERE userID=?\", (\"0\",user[0]))\n conn.commit()\n c.close()\n conn.close()\n return True\n \ndef validate_token(token,table):\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n query = 'SELECT userID FROM '+table+' WHERE token=\\\"'+token+\"\\\"\"\n c.execute(query)\n user = c.fetchone()\n if user is not None:\n conn.commit()\n c.close()\n conn.close()\n return True\n else:\n conn.commit()\n c.close()\n conn.close()\n return False\n \n \n \ndef search_user_order(cod):\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n find_user = (\"SELECT username,document FROM user WHERE userID = ?\")\n c.execute(find_user,[(cod)])\n data = c.fetchall()\n if data is not None:\n find_order = (\"SELECT units FROM wish WHERE codUser = ?\")\n c.execute(find_order,[(cod)])\n order = c.fetchall()\n conn.commit()\n c.close()\n conn.close()\n return order,data\n else:\n conn.commit()\n c.close()\n conn.close()\n return False\n\ndef search_product(product):\n conn = sqlite3.connect('tienda.db')\n c = conn.cursor()\n find_product = (\"SELECT price FROM product WHERE productId = ?\")\n c.execute(find_product,[(product)])\n data = c.fetchone()\n if data is not None:\n return True\n else:\n return False\n \n\n \napp = Flask(__name__) \nCORS(app) \n \n@app.route('/layout2', methods =['POST']) \ndef layout2():\n createUser_table()\n data_entry(request.json['userName'],request.json['userDocument'],request.json['userTelephone'],request.json['userEmail'],request.json['userDepartment'],request.json['userCity'],request.json['userAddress'],request.json['userPassword'])\n return jsonify({\"Result\":request.json['userName']}) \n\n@app.route('/login', methods =['POST']) \ndef login():\n createUser_table()\n log = verifyLogin(request.json['userEmail'],request.json['userPassword'],\"user\")\n if log == False: \n return jsonify({\"token\":0})\n else:\n return jsonify({\"token\": log})\n\n@app.route('/loginAdmin', methods =['POST']) \ndef loginAdmin():\n createAdmin_table()\n log = verifyLogin(request.json['userEmail'],request.json['userPassword'],\"admin\")\n if log == False: \n return jsonify({\"token\":0})\n else:\n return jsonify({\"token\": log})\n\n@app.route('/makeOrder', methods =['POST']) \ndef makeOrder():\n createWish_table()\n make_order(request.json['userToken'], request.json['userProduct'], request.json['productUnits'])\n return jsonify({\"Result\": \"user\"}) \n\n@app.route('/consult', methods =['POST']) \ndef consult():\n createWish_table()\n data = consult_order(request.json['userToken'])\n if data == False:\n return jsonify({\"products\": 0}) \n else:\n return jsonify({\"products\": data}) \n \n@app.route('/consult_delete', methods =['POST']) \ndef consult_element():\n delete = delete_order(request.json['userToken'], request.json['userProduct'])\n if delete == False:\n return jsonify({\"result\": \"no borrado\"}) \n else:\n return jsonify({\"result\": delete}) \n\n@app.route('/logout', methods =['POST']) \ndef logout():\n logoutUser = logout_user(request.json['userToken'],\"user\")\n if logoutUser == False:\n return jsonify({\"result\": 0}) \n else:\n return jsonify({\"result\": 1}) \n \n@app.route('/logout_admins', methods =['POST']) \ndef logout_admins():\n logoutUser = logout_user(request.json['userToken'],\"admin\")\n if logoutUser == False:\n return jsonify({\"result\": 0}) \n else:\n return jsonify({\"result\": 1}) \n \n@app.route('/tokenValidate', methods =['POST']) \ndef tokenValidate():\n token = validate_token(request.json['userToken'],\"user\")\n if token == False:\n return jsonify({\"result\": 0}) \n else:\n return jsonify({\"result\": 1}) \n \n@app.route('/token_admin', methods =['POST']) \ndef token_admin():\n token = validate_token(request.json['userToken'], \"admin\")\n if token == False:\n return jsonify({\"result\": 0}) \n else:\n return jsonify({\"result\": 1}) \n \n@app.route('/search_order', methods =['POST']) \ndef search_order():\n order,data = search_user_order(request.json['userCod'])\n return jsonify({\"result\": order,\n \"data\":data }) \n\n@app.route('/deleteU_order', methods =['POST']) \ndef deleteU_order():\n delete_user_order(request.json['userCod'])\n return jsonify({\"result\": request.json['userCod'] }) \n \n@app.route('/add_product', methods =['POST']) \ndef add_product():\n if search_product( request.json['userProduct']) is False:\n return jsonify({\"result\": 0 }) \n else:\n update_user_order(request.json['userCod'], request.json['userProduct'], request.json['productUnits'])\n return jsonify({\"result\": request.json['userCod'] }) \n \n@app.route('/admin_consult', methods =['POST']) \ndef admin_consult():\n data = admin_consult_order(request.json['userCod'])\n return jsonify({\"products\": data}) \n \n\nif __name__ == '__main__': \n\tapp.run(debug = True) \n ","sub_path":"Pavan/backend/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":13062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"418899963","text":"import urllib\nimport urllib.request\nfrom http.cookiejar import CookieJar\n\n# from Tools.scripts.treesync import raw_input\nfrom bs4 import BeautifulSoup\nimport re\nimport datetime\n\nfrom numpy.distutils.fcompiler import none\n\n\ndef content(theurl,label):\n #theurl = a\n thepage = urllib.request.urlopen(theurl)\n soup = BeautifulSoup(thepage, \"html.parser\")\n\n target = open(\"MatchDetail.txt\", 'a')\n # print(\"HERE \"+theurl+'\\n')\n target.write(\"Label: \"+label+'\\n')\n try:\n div = soup.find_all('p', class_=\"SpecialsHead\")\n # print(div)\n # print()\n # print(div.find_all('a'))\n for line in div:\n links = line.findAll('a', class_=\"SpecialsHead\")\n for a in links:\n # print\n # if 'story'in a['href']:\n # print('found a url with Story in the link')\n var = 'http://www.espncricinfo.com' + a['href']\n target.write(var)\n target.write('\\n')\n print(var)\n # s = str(links)\n # s=s+'\\n'\n # print(s)\n # print('\\n')\n # target.write(s)\n\n except Exception as e:\n print\n str(e)\n target.write('\\n\\n')\n a = soup.find('a', href=True, class_=\"PaginationLink\")\n if a:\n Link=theurl.split(\"?\")\n link =Link[0]+a[\"href\"]\n print(theurl)\n print()\n print(\"LINK \"+link)\n print(a.text)\n s=str(a.text)\n if(\"Next\" in s):\n content(link, label)\n\n\n\ndef main():\n # theurl = \"http://www.espncricinfo.com/icc-world-twenty20-2016/content/story/index.html?object=951373\"\n # content(theurl,\"dfvdfv\")\n line_number = 1\n i=0;\n # target = open(\"MatchDetail.txt\", 'a')\n s1 = \"\"\n temp=0\n with open('MatchLink.txt', encoding='utf-8') as a_file:\n for a_line in a_file:\n # print('{:>4} {}'.format(line_number, a_line.rstrip()))\n s=a_line.rstrip()\n # print(\"HII\"+s)\n if (i % 2 == 0):\n # target.write(s+'\\n')\n # print('here')\n # if 'ODI' in s:\n # print(s)\n s1=s\n # print(s1)\n else:\n content(s,s1)\n line_number += 1\n temp=0\n i=i+1\n\nmain()\n","sub_path":"T202016/MatchLInk.py","file_name":"MatchLInk.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"79364182","text":"__author__ = 'Steve'\n\nimport unittest\nfrom auto.Instance import set_instance, get_user, dict_iterator\nfrom auto.BasePage import enter_page\n\nclass Test(unittest.TestCase):\n\n def setUp(self):\n self.verificationErrors = []\n self.accept_next_alert = True\n\n def test1_pages(self):\n\n # load hiring man browser instance\n employer_instance = set_instance(\"ie\")\n employer_object = get_user(\"Kevin\")\n employer = enter_page(employer_instance)\n employer.login(employer_object)\n\n # load the recruiter browser instance\n recruiter_instance = set_instance(\"opera\")\n recruiter_object = get_user('Kevyn')\n recruiter = enter_page(recruiter_instance)\n recruiter.login(recruiter_object)\n\n # load the jobseeker browser instance\n jobseeker_instance = set_instance('firefox')\n jobseeker_object = get_user(\"Dian\")\n jobseeker = enter_page(jobseeker_instance)\n jobseeker.login(jobseeker_object)\n\n # load the anonymous browser instance\n anonymous_instance = set_instance()\n anonymous = enter_page(anonymous_instance)\n\n\n links = ['http://front.jobularity.com/zumay/testinginbox1','http://front.jobularity.com/company/testingsitesqa1447759064/truck-driver-heavy-tractor-trailer']\n\n for link in links:\n\n employer.get_url(link)\n employer.wait()\n recruiter.get_url(link)\n recruiter.wait()\n jobseeker.get_url(link)\n jobseeker.wait()\n anonymous.get_url(link)\n anonymous.wait()\n r = raw_input(\"continue\")\n\n def tearDown(self):\n self.assertEqual([], self.verificationErrors)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"216761673","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\nprint(cv2.__version__)\n\ncritaria = (cv2.TermCriteria_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n\nobjp = np.zeros((7*7, 3), np.float32)\nobjp[:, :2] = np.mgrid[0:7,0:7].T.reshape(-1,2)\n\nobjpoints = []\nimgpoints = []\n\n\ncap = cv2.VideoCapture(0)\n\ni=0\nwhile(i<=25):\n ret, frame = cap.read()\n img = frame\n # cv2.imshow('frame', frame)\n # plt.show()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n ret2, corners = cv2.findChessboardCorners(gray, (7,7),None)\n\n print(corners, ret2)\n if ret2 == True:\n i += 1\n objpoints.append(objp)\n\n corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),critaria)\n imgpoints.append(corners2)\n print(corners2)\n imgk = cv2.drawChessboardCorners(frame, (7,7), corners2,ret)\n cv2.imshow('img',frame)\n cv2.waitKey(500)\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n # ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)\n\n # print('ret:=', ret,'mtx:=', mtx, 'dist:=', dist, 'rvecs:=', rvecs, 'tvecs:=', tvecs)\n break\n\ncap.release()\ncv2.destroyAllWindows()\n\nprint(objpoints)\nret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)\n\nprint('ret:=', ret,'mtx:=', mtx, 'dist:=', dist, 'rvecs:=', rvecs, 'tvecs:=', tvecs)\n\nnp.savez('calibData', ret=ret, mtx=mtx, dist=dist, rvecs=rvecs, tvecs=tvecs)\nimg = cv2.imread('imgT2.jpg')\nh, w = img.shape[:2]\nprint(h, w)\nnewcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))\n\n# undistort\n# dst = cv2.undistort(img, mtx, dist, None, newcameramtx)\nmapx, mapy = cv2.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (w,h), 5)\ndst = cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR)\n\n# crop the image\nx,y,w,h = roi\n\nprint(x,y,w,h)\ndst = dst[y:y+h, x:x+w]\ncv2.imwrite('calibresult.png',dst)\n\nmean_error = 0\nfor i in range(len(objpoints)):\n imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)\n error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2)\n mean_error += error\n\nprint (\"total error: \", mean_error/len(objpoints))","sub_path":"cameraCalib.py","file_name":"cameraCalib.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"138506732","text":"\"\"\"\n@File: sequence_test\n@Date: 2019/10/13\n@Author: Chensy\n@Des: \n\"\"\"\nfrom abc import abstractmethod\nfrom collections import abc\n\na = [1, 2]\nc = a + [3, 4]\nprint(c)\na.extend((5, 6))\nprint(a)\nprint(c)","sub_path":"study/06 - AdvancePython/chapter04/sequence_test.py","file_name":"sequence_test.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"435763724","text":"import re\nimport traceback\nimport os\nimport numpy as np\nimport numpy.testing as nptest\n\nfrom tesseract_robotics.tesseract_common import ResourceLocator, SimpleLocatedResource\nfrom tesseract_robotics.tesseract_environment import Environment\nfrom tesseract_robotics.tesseract_common import FilesystemPath, Isometry3d, Translation3d, Quaterniond, \\\n ManipulatorInfo\nfrom tesseract_robotics.tesseract_command_language import JointWaypoint, CartesianWaypoint, Waypoint, \\\n MoveInstructionType_LINEAR, MoveInstructionType_START, MoveInstruction, Instruction, \\\n isMoveInstruction, isStateWaypoint, CompositeInstruction, flatten, isMoveInstruction, isStateWaypoint, \\\n ProfileDictionary\nfrom tesseract_robotics.tesseract_motion_planners import PlannerRequest, PlannerResponse, generateSeed, \\\n DESCARTES_DEFAULT_NAMESPACE\nfrom tesseract_robotics.tesseract_motion_planners_descartes import DescartesDefaultPlanProfileD, \\\n DescartesMotionPlannerD, DescartesMotionPlannerStatusCategory, DescartesPlanProfileD, \\\n ProfileDictionary_addProfile_DescartesPlanProfileD, cast_DescartesPlanProfileD\nfrom ..tesseract_support_resource_locator import TesseractSupportResourceLocator\n\ndef get_environment():\n locator = TesseractSupportResourceLocator()\n env = Environment()\n tesseract_support = os.environ[\"TESSERACT_SUPPORT_DIR\"]\n urdf_path = FilesystemPath(os.path.join(tesseract_support, \"urdf/abb_irb2400.urdf\"))\n srdf_path = FilesystemPath(os.path.join(tesseract_support, \"urdf/abb_irb2400.srdf\"))\n assert env.init(urdf_path, srdf_path, locator)\n manip_info = ManipulatorInfo()\n manip_info.tcp_frame = \"tool0\"\n manip_info.manipulator = \"manipulator\"\n manip_info.manipulator_ik_solver = \"OPWInvKin\"\n manip_info.working_frame = \"base_link\"\n joint_names = list(env.getJointGroup(\"manipulator\").getJointNames())\n \n return env, manip_info, joint_names\n\ndef test_descartes_freespace_fixed_poses():\n\n env, manip, joint_names = get_environment()\n kin_group = env.getKinematicGroup(manip.manipulator,manip.manipulator_ik_solver)\n\n cur_state = env.getState()\n\n wp1 = CartesianWaypoint(Isometry3d.Identity() * Translation3d(0.8,-0.2,0.8) * Quaterniond(0,0,-1.0,0))\n wp2 = CartesianWaypoint(Isometry3d.Identity() * Translation3d(0.8,0.2,0.8) * Quaterniond(0,0,-1.0,0))\n\n start_instruction = MoveInstruction(Waypoint(wp1), MoveInstructionType_START, \"TEST_PROFILE\", manip)\n plan_f1 = MoveInstruction(Waypoint(wp2), MoveInstructionType_LINEAR, \"TEST_PROFILE\", manip)\n\n program = CompositeInstruction()\n program.setStartInstruction(Instruction(start_instruction))\n program.setManipulatorInfo(manip)\n program.append(Instruction(plan_f1))\n\n seed = generateSeed(program, cur_state, env, 3.14, 1.0, 3.14, 10)\n\n plan_profile = DescartesDefaultPlanProfileD()\n # DescartesDefaultPlanProfileD is not upcasting automatically, use helper function\n plan_profile1 = cast_DescartesPlanProfileD(plan_profile)\n\n profiles = ProfileDictionary()\n ProfileDictionary_addProfile_DescartesPlanProfileD(profiles,DESCARTES_DEFAULT_NAMESPACE,\"TEST_PROFILE\",plan_profile1)\n \n single_descartes_planner = DescartesMotionPlannerD()\n plan_profile.num_threads = 1\n \n\n request = PlannerRequest()\n request.seed = seed\n request.instructions = program\n request.env = env\n request.env_state = cur_state\n request.profiles = profiles\n \n response = PlannerResponse()\n\n assert single_descartes_planner.solve(request, response)\n assert response.status.value() == DescartesMotionPlannerStatusCategory.SolutionFound\n\n results = flatten(response.results)\n\n assert len(results) == 11\n for instr in results:\n assert isMoveInstruction(instr)\n move_instr=instr.as_MoveInstruction()\n wp1 = move_instr.getWaypoint()\n assert isStateWaypoint(wp1)\n wp = wp1.as_StateWaypoint()\n assert len(wp.joint_names) == 6\n assert isinstance(wp.position,np.ndarray)\n assert len(wp.position) == 6\n","sub_path":"tesseract_python/tests/tesseract_motion_planning/test_descartes_planner.py","file_name":"test_descartes_planner.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"142569625","text":"# This module includes SIMDP class\n# which responsible for stationary\n# Infinite-Horizon MDP models. It is\n# inherited from SMDP class\n\nimport utils_ as utils\nfrom s_mdp import SMDP\nimport numpy as np\n\n\nclass SIMDP(SMDP):\n\n def __init__(self, transition_prob, rewards, n_state, n_action, discount_factor):\n\n SMDP.__init__(self, transition_prob, rewards, n_state, n_action)\n self.discount_factor = discount_factor\n\n def value_iteration(self):\n\n \"\"\"\n Performs value iteration and finds the optimal policy.\n\n :return: % INPLACE % + Returns the history\n\n Caution: History means that evaluation of value function over time\n \"\"\"\n\n history = [[] for s in range(self.n_state)] # For plotting\n\n self.values = np.zeros(shape=self.n_state)\n\n # Compute optimal value function\n\n while True:\n\n delta = 0\n\n # For plotting\n for s in range(self.n_state):\n history[s].append(self.values[s])\n\n for s in range(self.n_state):\n s_prev = self.values[s]\n self.values[s] = self.discount_factor * max([self.rewards[s, a] +\n np.sum(self.transition_probs[s, a, :] * self.values[:])\n for a in range(self.n_action)])\n delta = max(delta, abs(self.values[s] - s_prev))\n\n if delta < 1e-6:\n break\n\n # Extract the optimal policy from the optimal values.\n\n for s in range(self.n_state):\n self.policy[s] = np.argmax(np.array([np.sum(self.transition_probs[s, a] * self.values[:])\n for a in range(self.n_action)]))\n\n return history # return the history for further plotting options\n\n def solve(self):\n\n history = self.value_iteration()\n return history\n\n def plot_policy(self):\n\n utils.plot_si_policy(self.policy, self.n_state, self.n_action)\n","sub_path":"si_mdp.py","file_name":"si_mdp.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"379035668","text":"\"\"\"Physical DMD.\"\"\"\nimport struct\nfrom kivy.clock import Clock\nfrom kivy.graphics.fbo import Fbo\nfrom kivy.graphics.opengl import glReadPixels, GL_RGB, GL_UNSIGNED_BYTE\nfrom kivy.graphics.texture import Texture\nfrom kivy.uix.effectwidget import EffectWidget, EffectBase\n\nfrom mpfmc.widgets.dmd import Gain\n\n\nclass PhysicalDmdBase(object):\n\n \"\"\"Base class for DMD devices.\"\"\"\n\n dmd_name_string = 'Physical DMD'\n\n def __init__(self, mc, name, config):\n \"\"\"Initialise DMD.\"\"\"\n\n self.mc = mc\n self.name = name\n\n self.mc.log.info('Initializing Physical DMD')\n\n self.config = self._get_validated_config(config)\n\n self.source = self.mc.displays[self.config['source_display']]\n self.prev_data = None\n\n # put the widget canvas on a Fbo\n texture = Texture.create(size=self.source.size, colorfmt='rgb')\n self.fbo = Fbo(size=self.source.size, texture=texture)\n\n self.effect_widget = EffectWidget()\n\n effect_list = list()\n effect_list.append(FlipVertical())\n\n if self.config['brightness'] != 1.0:\n if not 0.0 <= self.config['brightness'] <= 1.0:\n raise ValueError(\"DMD brightness value should be between 0.0 \"\n \"and 1.0. Yours is {}\".format(self.config['brightness']))\n\n effect_list.append(Gain(gain=self.config['brightness']))\n\n self.effect_widget.effects = effect_list\n self.effect_widget.size = self.source.size\n\n self.fbo.add(self.effect_widget.canvas)\n\n self._set_dmd_fps()\n\n def _get_validated_config(self, config):\n raise NotImplementedError\n\n def _set_dmd_fps(self):\n # fps is the rate that the connected client requested. We'll use the\n # lower of the two\n\n mc_fps = self.config['fps']\n\n if mc_fps == 0:\n # pylint: disable-msg=protected-access\n mc_fps = Clock._max_fps\n\n # pylint: disable-msg=protected-access\n if mc_fps > Clock._max_fps:\n self.mc.log.warning(\"%s fps is higher than mpf-mc fps. \"\n \"Will use mpf-mc fps setting for the DMD.\",\n PhysicalDmdBase.dmd_name_string)\n # pylint: disable-msg=protected-access\n fps = Clock._max_fps\n update = 0\n # pylint: disable-msg=protected-access\n elif Clock._max_fps > mc_fps > 0:\n fps = mc_fps\n update = 1 / fps\n else:\n # pylint: disable-msg=protected-access\n fps = Clock._max_fps\n update = 0\n\n Clock.schedule_interval(self.tick, update)\n self.mc.log.info(\"Setting %s to %sfps\",\n PhysicalDmdBase.dmd_name_string, fps)\n\n def tick(self, dt):\n \"\"\"Draw image for DMD and send it.\"\"\"\n del dt\n widget = self.source\n fbo = self.fbo\n\n # detach the widget from the parent\n parent = widget.parent\n if parent:\n parent.remove_widget(widget)\n\n self.effect_widget.add_widget(widget)\n\n # clear the fbo background\n fbo.bind()\n fbo.clear_buffer()\n fbo.release()\n\n fbo.draw()\n\n fbo.bind()\n data = glReadPixels(0, 0, widget.native_size[0], widget.native_size[1],\n GL_RGB, GL_UNSIGNED_BYTE)\n fbo.release()\n\n # reattach to the parent\n if parent:\n self.effect_widget.remove_widget(widget)\n parent.add_widget(widget)\n\n if not self.config['only_send_changes'] or self.prev_data != data:\n self.prev_data = data\n self.send(data)\n\n def send(self, data):\n \"\"\"Send data to DMD via BCP.\"\"\"\n raise NotImplementedError\n\n\nclass PhysicalDmd(PhysicalDmdBase):\n\n \"\"\"Physical monochrome DMD.\"\"\"\n\n def _get_validated_config(self, config):\n return self.mc.config_validator.validate_config('physical_dmds', config)\n\n @classmethod\n def _convert_to_single_bytes(cls, data):\n new_data = bytearray()\n loops = 0\n\n for r, g, b in struct.iter_unpack('BBB', data):\n loops += 1\n try:\n pixel_weight = ((r * .299) + (g * .587) + (b * .114)) / 255.\n new_data.append(int(round(pixel_weight * 15)))\n\n except ValueError:\n raise ValueError(loops, r, g, b)\n\n return bytes(new_data)\n\n def send(self, data):\n \"\"\"Send data to DMD via BCP.\"\"\"\n data = self._convert_to_single_bytes(data)\n\n self.mc.bcp_processor.send('dmd_frame', rawbytes=data, name=self.name)\n\n\nclass PhysicalRgbDmd(PhysicalDmdBase):\n\n \"\"\"Physical RGB DMD.\"\"\"\n\n dmd_name_string = 'Physical RGB DMD'\n\n def _get_validated_config(self, config):\n return self.mc.config_validator.validate_config('physical_rgb_dmds',\n config)\n\n def send(self, data):\n \"\"\"Send data to DMD via BCP.\"\"\"\n self.mc.bcp_processor.send('rgb_dmd_frame', rawbytes=data, name=self.name)\n\n\nclass FlipVertical(EffectBase):\n \"\"\"GLSL effect to veritically flip a texture\"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.glsl = '''\n\n vec4 effect(vec4 color, sampler2D texture, vec2 tex_coords, vec2 coords)\n\n {{\n return texture2D(texture, vec2(tex_coords.x, 1.0 - tex_coords.y));\n }}\n '''","sub_path":"mpfmc/core/physical_dmd.py","file_name":"physical_dmd.py","file_ext":"py","file_size_in_byte":5428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"67039238","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom moviesRecommendationSystem.models import user, watchlist, requestMovieModel\n# from builtins import print\n\nfrom sklearn.metrics.pairwise import linear_kernel\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\nfrom scipy.sparse.linalg import svds\nfrom sklearn.neighbors import NearestNeighbors\nfrom math import sqrt\nfrom sklearn.metrics import mean_squared_error\n\n# from moviesRecommendationSystem.test import get_similar_movies_based_on_content\nratings = pd.read_csv('./Dataset/ratings.csv')\nmovie_list = pd.read_csv('./Dataset/movies.csv')\ntags = pd.read_csv('./Dataset/tags.csv')\n\nratings = ratings[['userId', 'movieId', 'rating']]\nmovie_list1 = movie_list[['movieId', 'genres', 'title']]\nratings1 = ratings[['userId', 'movieId', 'rating']]\n\nratings_df = ratings.groupby(['userId', 'movieId']).aggregate(np.max)\n\ncount_ratings = ratings.groupby('rating').count()\ncount_ratings['perc_total'] = round(count_ratings['userId'] * 100 / count_ratings['userId'].sum(), 1)\n\ngenres = movie_list['genres']\n\ngenre_list = \"\"\nfor index, row in movie_list.iterrows():\n genre_list += row.genres + \"|\"\n\n# split the string into a list of values\ngenre_list_split = genre_list.split('|')\n# de-duplicate values\nnew_list = list(set(genre_list_split))\n# remove the value that is blank\nnew_list.remove('')\n# inspect list of genres\n\nmovies_with_genres = movie_list.copy()\n\nfor genre in new_list:\n movies_with_genres[genre] = movies_with_genres.apply(lambda _: int(genre in _.genres), axis=1)\n\nno_of_users = len(ratings['userId'].unique())\nno_of_movies = len(ratings['movieId'].unique())\n\nsparsity = round(1.0 - len(ratings) / (1.0 * (no_of_movies * no_of_users)), 3)\n\navg_movie_rating = pd.DataFrame(ratings.groupby('movieId')['rating'].agg(['mean', 'count']))\n\n# Get the average movie rating across all movies\navg_rating_all = ratings['rating'].mean()\n\n# set a minimum threshold for number of reviews that the movie has to have\nmin_reviews = 0\n\nmovie_score = avg_movie_rating.loc[avg_movie_rating['count'] > min_reviews]\n\n\ndef weighted_rating(x, m=min_reviews, C=avg_rating_all):\n v = x['count']\n R = x['mean']\n # Calculation based on the IMDB formula\n return (v / (v + m) * R) + (m / (m + v) * C)\n\n\nmovie_score['weighted_score'] = movie_score.apply(weighted_rating, axis=1)\n\n# join movie details to movie ratings\nmovie_score = pd.merge(movie_score, movies_with_genres, on='movieId')\n\npd.DataFrame(movie_score.sort_values(['weighted_score'], ascending=False)[\n ['title', 'count', 'mean', 'weighted_score', 'genres']][:10])\n\n\ndef best_movies_by_genre(genre, top_n):\n return pd.DataFrame(movie_score.loc[(movie_score[genre] == 1)].sort_values(['weighted_score'], ascending=False)[\n ['title', 'count', 'mean', 'weighted_score']][:top_n])\n\n\nratings_df = pd.pivot_table(ratings, index='userId', columns='movieId', aggfunc=np.max)\n\nratings_movies = pd.merge(ratings, movie_list, on='movieId')\n\n\ndef get_other_movies(movie_name):\n # get all users who watched a specific movie\n df_movie_users_series = ratings_movies.loc[ratings_movies['title'] == movie_name]['userId']\n # convert to a data frame\n df_movie_users = pd.DataFrame(df_movie_users_series, columns=['userId'])\n # get a list of all other movies watched by these users\n other_movies = pd.merge(df_movie_users, ratings_movies, on='userId')\n # get a list of the most commonly watched movies by these other user\n other_users_watched = pd.DataFrame(other_movies.groupby('title')['userId'].count()).sort_values('userId',\n ascending=False)\n other_users_watched['perc_who_watched'] = round(\n other_users_watched['userId'] * 100 / other_users_watched['userId'][0], 1)\n return other_users_watched\n\n\nmovie_plus_10_ratings = avg_movie_rating.loc[avg_movie_rating['count'] >= 10]\n\nfiltered_ratings = pd.merge(movie_plus_10_ratings, ratings, on=\"movieId\")\n\nmovie_wide = filtered_ratings.pivot(index='movieId', columns='userId', values='rating').fillna(0)\n\nmodel_knn = NearestNeighbors(metric='cosine', algorithm='brute')\nmodel_knn.fit(movie_wide)\n\nmovie_content_df_temp = movies_with_genres.copy()\nmovie_content_df_temp.set_index('movieId')\nmovie_content_df = movie_content_df_temp.drop(columns=['movieId', 'title', 'genres'])\nmovie_content_df = movie_content_df.values\n\ncosine_sim = linear_kernel(movie_content_df, movie_content_df)\n\n# get ordered list of movieIds\nitem_indices = pd.DataFrame(sorted(list(set(ratings['movieId']))), columns=['movieId'])\n# add in data frame index value to data frame\nitem_indices['movie_index'] = item_indices.index\n# inspect data frame\nitem_indices.head()\n\n# get ordered list of movieIds\nuser_indices = pd.DataFrame(sorted(list(set(ratings['userId']))), columns=['userId'])\n# add in data frame index value to data frame\nuser_indices['user_index'] = user_indices.index\n# inspect data frame\nuser_indices.head()\n\n# join the movie indices\ndf_with_index = pd.merge(ratings, item_indices, on='movieId')\n# join the user indices\ndf_with_index = pd.merge(df_with_index, user_indices, on='userId')\n# inspec the data frame\ndf_with_index.head()\n\n# import train_test_split module\n# take 80% as the training set and 20% as the test set\ndf_train, df_test = train_test_split(df_with_index, test_size=0.2)\n\nn_users = ratings.userId.unique().shape[0]\nn_items = ratings.movieId.unique().shape[0]\n\n# Create two user-item matrices, one for training and another for testing\ntrain_data_matrix = np.zeros((n_users, n_items))\n# for every line in the data\nfor line in df_train.itertuples():\n # set the value in the column and row to\n # line[1] is userId, line[2] is movieId and line[3] is rating, line[4] is movie_index and line[5] is user_index\n train_data_matrix[line[5], line[4]] = line[3]\n# train_data_matrix.shape\n\n# Create two user-item matrices, one for training and another for testing\ntest_data_matrix = np.zeros((n_users, n_items))\n# for every line in the data\nfor line in df_test[:1].itertuples():\n # set the value in the column and row to\n # line[1] is userId, line[2] is movieId and line[3] is rating, line[4] is movie_index and line[5] is user_index\n test_data_matrix[line[5], line[4]] = line[3]\n # train_data_matrix[line['movieId'], line['userId']] = line['rating']\n\n\ndef rmse(prediction, ground_truth):\n # select prediction values that are non-zero and flatten into 1 array\n prediction = prediction[ground_truth.nonzero()].flatten()\n # select test values that are non-zero and flatten into 1 array\n ground_truth = ground_truth[ground_truth.nonzero()].flatten()\n # return RMSE between values\n return sqrt(mean_squared_error(prediction, ground_truth))\n\n\n# Calculate the rmse sscore of SVD using different values of k (latent features)\nrmse_list = []\nfor i in [1, 2, 5, 20, 40]:\n # apply svd to the test data\n u, s, vt = svds(train_data_matrix, k=i)\n # get diagonal matrix\n s_diag_matrix = np.diag(s)\n # predict x with dot product of u s_diag and vt\n X_pred = np.dot(np.dot(u, s_diag_matrix), vt)\n # calculate rmse score of matrix factorisation predictions\n rmse_score = rmse(X_pred, test_data_matrix)\n rmse_list.append(rmse_score)\n\n# Convert predictions to a DataFrame\nmf_pred = pd.DataFrame(X_pred)\n\ndf_names = pd.merge(ratings, movie_list, on='movieId')\n\n\n# choose a user ID\n\ndef getRecommendedMovies(user_id):\n # get movies rated by this user id\n users_movies = df_names.loc[df_names[\"userId\"] == user_id]\n\n user_index = df_train.loc[df_train[\"userId\"] == user_id]['user_index'][:1].values[0]\n # get movie ratings predicted for this user and sort by highest rating prediction\n sorted_user_predictions = pd.DataFrame(mf_pred.iloc[user_index].sort_values(ascending=False))\n # rename the columns\n sorted_user_predictions.columns = ['ratings']\n # save the index values as movie id\n sorted_user_predictions['movieId'] = sorted_user_predictions.index\n # display the top 10 predictions for this user\n return pd.merge(sorted_user_predictions, movie_list, on='movieId')[:10]\n\n\ndef home(request):\n if (request.session.get('id')):\n return redirect('profile')\n else:\n tempMovieNames = getMovieByData(pd.DataFrame(movie_score.sort_values(['weighted_score'], ascending=False)[\n ['title', 'count', 'mean', 'weighted_score', 'genres']][:10]))\n movieNames = []\n\n for movies in tempMovieNames:\n movieNames.append(movies[1:])\n\n movieNames1 = []\n movies_index = []\n genres = []\n ratings = []\n for movie in movieNames:\n for i in range(len(movie_list1)):\n if movie_list1.title[i] == movie:\n movies_index.append(movie_list1.movieId[i])\n genres.append(movie_list1.genres[i])\n movieNames1.append(movie_list1.title[i])\n break\n\n for i in range(len(movies_index)):\n count = 0\n sum = 0\n for j in range(len(ratings1)):\n if ratings1.movieId[j] == movies_index[i]:\n sum = sum + ratings1.rating[j]\n count = count + 1\n\n if sum == 0 or count == 0:\n ratings.append(0)\n else:\n ratings.append(round(sum / count, 1))\n\n data = []\n for i in range(len(ratings)):\n Dict = {}\n Dict['rating'] = ratings[i]\n Dict['genre'] = genres[i]\n Dict['movie'] = movieNames[i]\n Dict['index'] = movies_index[i]\n data.append(Dict)\n return render(request, 'home.html', {'data': data})\n\n\ndef doLogin(request):\n if (request.session.get('id')):\n return redirect(profile)\n\n else:\n return redirect(login)\n\n\ndef profile(request):\n if (request.session.get('id')):\n id = request.session['id']\n users = user.objects.filter(id=id)\n tempMovieNames = getMovieByData(pd.DataFrame(movie_score.sort_values(['weighted_score'], ascending=False)[\n ['title', 'count', 'mean', 'weighted_score', 'genres']][:10]))\n\n movieNames = []\n\n for movies in tempMovieNames:\n movieNames.append(movies[1:])\n\n movieNames1 = []\n movies_index = []\n genres = []\n ratings = []\n for movie in movieNames:\n for i in range(len(movie_list1)):\n if movie_list1.title[i] == movie:\n movies_index.append(movie_list1.movieId[i])\n genres.append(movie_list1.genres[i])\n movieNames1.append(movie_list1.title[i])\n break\n\n for i in range(len(movies_index)):\n count = 0\n sum = 0\n for j in range(len(ratings1)):\n if ratings1.movieId[j] == movies_index[i]:\n sum = sum + ratings1.rating[j]\n count = count + 1\n\n if sum == 0 or count == 0:\n ratings.append(0)\n else:\n ratings.append(round(sum / count, 1))\n\n data = []\n for i in range(5):\n Dict = {}\n Dict['rating'] = ratings[i]\n Dict['genre'] = genres[i]\n Dict['movie'] = movieNames[i]\n Dict['index'] = movies_index[i]\n data.append(Dict)\n\n recommendedMoviesIndices = getRecommendedMovies(id).movieId\n\n recommendedMoviesNames = []\n recommendedMoviesGenres = []\n recommendedMoviesRatings = []\n\n for i in range(len(recommendedMoviesIndices)):\n for j in range(len(movie_list1)):\n if movie_list1.movieId[j] == recommendedMoviesIndices[i]:\n recommendedMoviesNames.append(movie_list1.title[j])\n recommendedMoviesGenres.append(movie_list1.genres[j])\n break\n\n for i in range(len(recommendedMoviesIndices)):\n count1 = 0\n sum1 = 0\n for j in range(len(ratings1)):\n if ratings1.movieId[j] == recommendedMoviesIndices[i]:\n sum1 = sum1 + ratings1.rating[j]\n count1 = count1 + 1\n\n if sum1 == 0 or count1 == 0:\n recommendedMoviesRatings.append(0)\n else:\n recommendedMoviesRatings.append(round(sum1 / count1, 1))\n\n recommendedData = []\n\n for k in range(5):\n recommendedDict = {}\n recommendedDict['rating'] = recommendedMoviesRatings[k]\n recommendedDict['genre'] = recommendedMoviesGenres[k]\n recommendedDict['movie'] = recommendedMoviesNames[k]\n recommendedDict['index'] = recommendedMoviesIndices[k]\n recommendedData.append(recommendedDict)\n\n return render(request, 'profile.html', {'user': users[0], 'data': data, 'recommendedData': recommendedData})\n\n else:\n return redirect(login)\n\n\ndef logout(request):\n if (request.session.get('id')):\n del request.session['id']\n return render(request, 'LogoutSuccessful.html')\n\n\ndef login(request):\n if request.method == 'POST':\n email = request.POST['email']\n password = request.POST['password']\n users = user.objects.filter(email=email, password=password)\n if (users):\n request.session['id'] = users[0].id\n return redirect(profile)\n else:\n return render(request, 'InvalidCredentials.html')\n\n elif request.method == \"GET\":\n return render(request, 'login.html')\n\n\ndef doRegister(request):\n if request.method == 'POST':\n firstName = request.POST.get('firstName')\n lastName = request.POST.get('lastName')\n email = request.POST['email']\n password = request.POST['password']\n users = user.objects.filter(email=email, password=password)\n for i in users:\n print(i.email)\n u = user()\n u.firstName = firstName\n u.lastName = lastName\n u.email = email\n u.password = password\n u.status = True\n u.save()\n if (request.session.get('id')):\n del request.session['id']\n return redirect(registered)\n\n\ndef registered(request):\n return render(request, 'registered.html')\n\n\ndef register(request):\n return render(request, 'register.html')\n\n\ndef getMovieData(temp):\n temp = str(temp).split('\\n')\n\n temp2 = []\n for i in range(3, len(temp)):\n temp3 = temp[i].split()[0:-2]\n temp4 = \"\"\n for j in temp3:\n temp4 = temp4 + \" \" + j\n temp2.append(temp4.strip())\n return temp2\n\n\ndef getMovie(request):\n sum = 0\n count = 0\n index_movie = int(request.GET['movieId'])\n\n for i in range(len(movie_list1)):\n if movie_list1.movieId[i] == index_movie:\n genres1 = movie_list1.genres[i]\n movieName = movie_list1.title[i]\n break\n\n # tempSimilarMovies = get_other_movies(movieName)[:10]\n #\n # similarMovies = getMovieData(tempSimilarMovies)\n # indexesOfSimilarMovies = []\n #\n # for i in range(len(similarMovies)):\n # for j in range(len(movie_list1)):\n # if similarMovies[i] == movie_list1.title[j]:\n # indexesOfSimilarMovies.append(movie_list1.movieId[j])\n #\n # data = []\n # for i in range(4):\n # Dict = {}\n # Dict['movie'] = similarMovies[i]\n # Dict['index'] = indexesOfSimilarMovies[i]\n # data.append(Dict)\n\n for i in range(len(ratings1)):\n if ratings1.movieId[i] == index_movie:\n sum = sum + ratings1.rating[i]\n count = count + 1\n\n if sum == 0 or count == 0:\n avg_rating = 0\n else:\n avg_rating = sum / count\n if (request.session.get('id')):\n return render(request, 'getMovieWithLogin.html',\n {'movie_name': movieName, 'rating': round(avg_rating, 1), 'genres': genres1,\n 'movie_id': index_movie})\n\n else:\n return render(request, 'getMovieWithoutLogin.html',\n {'movie_name': movieName, 'rating': round(avg_rating, 1), 'genres': genres1,\n 'movie_id': index_movie})\n\n\ndef addToWatchList(request):\n if (request.session.get('id')):\n id = int(request.session['id'])\n movieId = int(request.GET['movieId'])\n getMovieData = watchlist.objects.filter(movieId=movieId)\n\n flag = 0\n for movieData in getMovieData:\n if movieData.movieId == movieId:\n flag = 1\n break\n\n if flag == 0:\n w = watchlist()\n w.userId = id\n w.movieId = movieId\n w.save()\n return render(request, 'addedToWatchList.html')\n else:\n return render(request, 'alreadyAddedTOWatchlist.html')\n\n else:\n return redirect(login)\n\n\ndef getWatchList(request):\n if (request.session.get('id')):\n id = request.session['id']\n movies = watchlist.objects.filter(userId=id)\n\n avg_rating = []\n genre = []\n movie_name = []\n index_movie = []\n for movie in movies:\n for i in range(len(movie_list1)):\n if movie.movieId == movie_list1.movieId[i]:\n index_movie.append(movie_list1.movieId[i])\n movie_name.append(movie_list1.title[i])\n genre.append(movie_list1.genres[i])\n\n for i in index_movie:\n count = 0\n sum = 0\n for j in range(len(ratings1)):\n if i == ratings1.movieId[j]:\n count = count + 1\n sum = sum + ratings1.rating[j]\n if (sum == 0):\n avg_rating.append(0)\n else:\n avg_rating.append(round(sum / count, 1))\n\n data = []\n for i in range(len(avg_rating)):\n Dict = {}\n Dict['rating'] = avg_rating[i]\n Dict['genre'] = genre[i]\n Dict['movie'] = movie_name[i]\n Dict['index'] = index_movie[i]\n data.append(Dict)\n\n return render(request, 'getWatchList.html', {'data': data})\n\n else:\n return redirect(login)\n\n\ndef requestMovie(request):\n if (request.session.get('id')):\n return render(request, 'requestMovie.html')\n else:\n return redirect(login)\n\n\ndef doRequestMovie(request):\n if request.method == 'POST':\n id = request.session['id']\n movie = request.POST['movie']\n\n rm = requestMovieModel()\n rm.userId = id\n rm.movieName = movie\n rm.save()\n return render(request, 'requestSubmitted.html')\n\n\ndef search(request):\n avg_rating = 0\n movieName = request.GET['movieName']\n flag = 0\n sum = 0\n count = 0\n for i in range(len(movie_list1)):\n if movie_list1.title[i] == movieName:\n index_movie = movie_list1.movieId[i]\n genre = movie_list1.genres[i]\n flag = 1\n break\n\n if flag == 0 and request.session.get('id'):\n return render(request, 'resultNotFoundWithLogin.html')\n\n elif flag == 0:\n return render(request, 'resultNotFound.html')\n elif flag == 1 and request.session.get('id'):\n for i in range(len(ratings1)):\n if ratings1.movieId[i] == index_movie:\n sum = sum + ratings1.rating[i]\n count = count + 1\n if sum == 0 or count == 0:\n avg_rating == 0\n else:\n avg_rating = sum / count\n\n return render(request, 'resultWithLogin.html',\n {'movie_name': movieName, 'rate': round(avg_rating, 1), 'genre': genre, 'index': index_movie})\n else:\n for i in range(len(ratings1)):\n if ratings1.movieId[i] == index_movie:\n sum = sum + ratings1.rating[i]\n count = count + 1\n if sum == 0 or count == 0:\n avg_rating == 0\n else:\n avg_rating = sum / count\n\n return render(request, 'result.html',\n {'movie_name': movieName, 'rate': round(avg_rating, 1), 'genre': genre, 'index': index_movie})\n\n\ndef genres(request):\n data = ['Adventure', 'Musical', 'Drama', 'Romance', 'Animation', 'Sci-Fi', 'Thriller', 'Crime', 'Fantasy',\n 'Mystery', 'Action']\n if (request.session.get('id')):\n\n return render(request, 'genreWithLogin.html', {'data': data})\n else:\n return render(request, 'genreWithoutLogin.html', {'data': data})\n\n\ndef getMovieByData(data):\n temp = str(data.title)\n arr_data = []\n temp = temp.split('\\n')\n for i in temp:\n temp2 = i.split()\n temp3 = \"\"\n for j in range(1, len(temp2)):\n temp3 = temp3 + ' ' + temp2[j]\n temp3.strip()\n temp3.lstrip()\n temp3.rstrip()\n arr_data.append(temp3)\n return arr_data\n\n\ndef getMoviesByGenre(request):\n genre = request.GET['genre']\n tempMovieNames = getMovieByData(best_movies_by_genre(genre, 10))\n movieNames = []\n\n for movies in tempMovieNames:\n movieNames.append(movies[1:])\n\n movieNames1 = []\n movies_index = []\n genres = []\n ratings = []\n for movie in movieNames:\n for i in range(len(movie_list1)):\n if movie_list1.title[i] == movie:\n movies_index.append(movie_list1.movieId[i])\n genres.append(movie_list1.genres[i])\n movieNames1.append(movie_list1.title[i])\n break\n\n for i in range(len(movies_index)):\n count = 0\n sum = 0\n for j in range(len(ratings1)):\n if ratings1.movieId[j] == movies_index[i]:\n sum = sum + ratings1.rating[j]\n count = count + 1\n\n if sum == 0 or count == 0:\n ratings.append(0)\n else:\n ratings.append(round(sum / count, 1))\n\n data = []\n for i in range(len(ratings)):\n Dict = {}\n Dict['rating'] = ratings[i]\n Dict['genre'] = genres[i]\n Dict['movie'] = movieNames[i]\n Dict['index'] = movies_index[i]\n data.append(Dict)\n\n if request.session.get('id'):\n return render(request, 'getMoviesByGenreWithLogin.html', {'data': data, 'genre': genre})\n else:\n return render(request, 'getMoviesByGenreWithoutLogin.html', {'data': data, 'genre': genre})\n\n\ndef topRated(request):\n tempMovieNames = getMovieByData(pd.DataFrame(movie_score.sort_values(['weighted_score'], ascending=False)[\n ['title', 'count', 'mean', 'weighted_score', 'genres']][:10]))\n\n movieNames = []\n\n for movies in tempMovieNames:\n movieNames.append(movies[1:])\n\n movieNames1 = []\n movies_index = []\n genres = []\n ratings = []\n for movie in movieNames:\n for i in range(len(movie_list1)):\n if movie_list1.title[i] == movie:\n movies_index.append(movie_list1.movieId[i])\n genres.append(movie_list1.genres[i])\n movieNames1.append(movie_list1.title[i])\n break\n\n for i in range(len(movies_index)):\n count = 0\n sum = 0\n for j in range(len(ratings1)):\n if ratings1.movieId[j] == movies_index[i]:\n sum = sum + ratings1.rating[j]\n count = count + 1\n\n if sum == 0 or count == 0:\n ratings.append(0)\n else:\n ratings.append(round(sum / count, 1))\n\n data = []\n for i in range(len(ratings)):\n Dict = {}\n Dict['rating'] = ratings[i]\n Dict['genre'] = genres[i]\n Dict['movie'] = movieNames[i]\n Dict['index'] = movies_index[i]\n data.append(Dict)\n\n if (request.session.get('id')):\n return render(request, 'topRatedWithLogin.html', {'data': data})\n else:\n return render(request, 'topRatedWithoutLogin.html', {'data': data})\n\n\ndef removeFromWatchList(request):\n movieId = int(request.GET['movieId'])\n id = int(request.session.get('id'))\n\n movie = watchlist.objects.get(userId=id, movieId=movieId)\n movie.delete()\n return render(request, 'removedFromWatchList.html')\n","sub_path":"moviesRecommendationSystem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"336451327","text":"#!/usr/bin/env python\nFILE_NAME = 'DATA/wombat.txt'\n\nclass AmadeusError(Exception):\n pass\n\n\ndef main():\n read_file()\n print_numerical_results()\n try_amadeus()\n\ndef read_file():\n try:\n with open(FILE_NAME) as file_in:\n for line in file_in:\n print(line, end='')\n except FileNotFoundError as err:\n print(err)\n\ndef print_numerical_results():\n values = 5, 8, 0, 9, \"ABC\", 4\n for value in values:\n try:\n result = 26 / value\n except Exception as err:\n print(err)\n else:\n print(result)\n\ndef raise_amadeus():\n print(\"Hello\")\n raise AmadeusError(\"THIS IS A TEST\")\n\ndef try_amadeus():\n try:\n raise_amadeus()\n except AmadeusError as err:\n print(err)\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"exception_handling.py","file_name":"exception_handling.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"112316520","text":"from datetime import datetime, timedelta\n\nfrom airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\n\nfrom provider_api_scripts import metropolitan_museum_of_art\nfrom util.operator_util import get_log_operator\n\n\nDAG_DEFAULT_ARGS = {\n 'owner': 'data-eng-admin',\n 'depends_on_past': False,\n 'start_date': datetime(2020, 1, 1),\n 'email_on_retry': False,\n 'retries': 3,\n 'retry_delay': timedelta(minutes=15),\n}\n\nDAG_ID = 'metropolitan_museum_workflow'\n\n\ndef get_runner_operator(dag):\n return PythonOperator(\n task_id='pull_metropolitan_museum_data',\n python_callable=metropolitan_museum_of_art.main,\n op_args=['{{ ds }}'],\n depends_on_past=False,\n dag=dag\n )\n\n\ndef create_dag():\n dag = DAG(\n dag_id=DAG_ID,\n default_args=DAG_DEFAULT_ARGS,\n concurrency=1,\n max_active_runs=1,\n start_date=datetime(2020, 1, 1),\n schedule_interval='@daily',\n catchup=False,\n )\n\n with dag:\n start_task = get_log_operator(dag, DAG_ID, 'Starting')\n run_task = get_runner_operator(dag)\n end_task = get_log_operator(dag, DAG_ID, 'Finished')\n\n start_task >> run_task >> end_task\n\n return dag\n\n\nglobals()[DAG_ID] = create_dag()\n","sub_path":"src/cc_catalog_airflow/dags/metropolitan_museum_workflow.py","file_name":"metropolitan_museum_workflow.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"573185421","text":"from django.test import TestCase, RequestFactory\nfrom django.contrib.messages.storage.fallback import FallbackStorage\n\n\n_views = __import__(\"MVC Structure.Controller.views\")\n_views = _views.Controller.views\n\n# from Model.models import User, Profile, BillingAddress\n_models = __import__(\"MVC Structure.Model.models\")\n_models = _models.Model.models\n\n\nclass ViewsTest(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n self.user = _models.User.objects._create_user(email=\"test@gmail.com\",password=\"top_secret\")\n self.category = _models.Category()\n self.category.title = \"mix\"\n self.category.save()\n self.product = _models.Product()\n self.product.name = \"Iphone 12 pro max\"\n self.product.category = self.category\n self.product.preview_text = \"Iphone 12 pro max for sell\"\n self.product.detail_text = \"Iphone 12 pro max with 12 gb ram\"\n self.product.old_price = 120000\n self.product.price = 100000\n self.product.save()\n\n self.request = self.factory.get('/shop/add/1')\n self.request.user = self.user\n setattr(self.request, 'session', 'session')\n messages = FallbackStorage(self.request)\n setattr(self.request, '_messages', messages)\n self.response = _views.add_to_cart(self.request,1)\n\n\n def test_add_to_cart(self):\n\n cart = _models.Cart.objects.get(user=self.user)\n self.assertEqual(cart.quantity, 1, \"quantity of an item should be 1 at first time.\")\n\n self.response = _views.add_to_cart(self.request,1)\n self.response = _views.add_to_cart(self.request,1)\n self.response = _views.add_to_cart(self.request,1)\n\n cart = _models.Cart.objects.get(user=self.user)\n\n self.assertEqual(self.response.status_code, 302, \"Should get a successfull response.\")\n self.assertEqual(cart.quantity, 4, \"Same product should add to the same cart 3 time.\")\n self.assertFalse(cart.purchased, \"Purchased should be false by default.\")\n self.assertEqual(cart.item.name, \"Iphone 12 pro max\", \"Should add the 1st product in the cart.\")\n\n def test_increase_cart(self):\n request = self.factory.get('/shop/increase/1')\n request.user = self.user\n setattr(request, 'session', 'session')\n messages = FallbackStorage(request)\n setattr(request, '_messages', messages)\n response = _views.increase_cart(request,1)\n cart = _models.Cart.objects.get(user=request.user)\n\n self.assertEqual(response.status_code, 302, \"Should get a successfull response.\")\n self.assertEqual(cart.quantity, 2, \"quantity of an item should be zero at first time.\")\n self.assertFalse(cart.purchased, \"Purchased should be false by default.\")\n self.assertEqual(cart.item.name, \"Iphone 12 pro max\", \"Should add the 1st product in the cart.\")\n\n def test_decrease_item(self):\n response = _views.add_to_cart(self.request,1)\n request = self.factory.get('/shop/decrease/1')\n request.user = self.user\n setattr(request, 'session', 'session')\n messages = FallbackStorage(request)\n setattr(request, '_messages', messages)\n response = _views.decrease_item(request,1)\n cart = _models.Cart.objects.get(user=request.user)\n\n self.assertEqual(response.status_code, 302, \"Should get a successfull response.\")\n self.assertEqual(cart.quantity, 1, \"quantity of an item should be zero at first time.\")\n self.assertFalse(cart.purchased, \"Purchased should be false by default.\")\n self.assertEqual(cart.item.name, \"Iphone 12 pro max\", \"Should add the 1st product in the cart.\")\n\n def test_remove_from_cart(self):\n request = self.factory.get('/shop/remove/1')\n request.user = self.user\n setattr(request, 'session', 'session')\n messages = FallbackStorage(request)\n setattr(request, '_messages', messages)\n response = _views.remove_from_cart(request,1)\n order_item = _models.Cart.objects.filter(item=self.product, user=request.user, purchased=False)\n\n self.assertEqual(response.status_code, 302, \"Should get a successfull response.\")\n self.assertEqual(len(order_item), 0 , \"Cart should be remove from order\")\n","sub_path":"TestCode/ViewsTest.py","file_name":"ViewsTest.py","file_ext":"py","file_size_in_byte":4264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"508641169","text":"##########################################################################\n# \n# Copyright (c) 2011-2012, John Haddon. All rights reserved.\n# Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# * Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n# \n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with\n# the distribution.\n# \n# * Neither the name of John Haddon nor the names of\n# any other contributors to this software may be used to endorse or\n# promote products derived from this software without specific prior\n# written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# \n##########################################################################\n\nimport Gaffer\nimport GafferUI\n\nclass CompoundNumericPlugValueWidget( GafferUI.PlugValueWidget ) :\n\n\tdef __init__( self, plug, **kw ) :\n\t\n\t\tself.__row = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing=4 )\n\t\t\n\t\tGafferUI.PlugValueWidget.__init__( self, self.__row, plug, **kw )\n\n\t\tcomponentPlugs = plug.children()\n\t\tfor p in componentPlugs :\n\t\t\tw = GafferUI.NumericPlugValueWidget( p )\n\t\t\tself.__row.append( w )\n\t\n\tdef setReadOnly( self, readOnly ) :\n\t\n\t\tif readOnly == self.getReadOnly() :\n\t\t\treturn\n\t\t\n\t\tGafferUI.PlugValueWidget.setReadOnly( self, readOnly )\n\t\t\n\t\tfor w in self.__row :\n\t\t\tif isinstance( w, GafferUI.PlugValueWidget ) :\n\t\t\t\tw.setReadOnly( readOnly )\n\t\t\t\t\n\tdef _updateFromPlug( self ) :\n\n\t\tpass\n\t\n\t## Returns the ListContainer used as the main layout for this Widget.\n\t# Derived classes may use it to add to the layout.\t\n\tdef _row( self ) :\n\t\n\t\treturn self.__row\t\n\t\t\nGafferUI.PlugValueWidget.registerType( Gaffer.V2fPlug.staticTypeId(), CompoundNumericPlugValueWidget )\nGafferUI.PlugValueWidget.registerType( Gaffer.V3fPlug.staticTypeId(), CompoundNumericPlugValueWidget )\nGafferUI.PlugValueWidget.registerType( Gaffer.V2iPlug.staticTypeId(), CompoundNumericPlugValueWidget )\nGafferUI.PlugValueWidget.registerType( Gaffer.V3iPlug.staticTypeId(), CompoundNumericPlugValueWidget )\n\n","sub_path":"python/GafferUI/CompoundNumericPlugValueWidget.py","file_name":"CompoundNumericPlugValueWidget.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"647953721","text":"from django.db import models\n\n# Create your models here.\n\nclass manage_ad(models.Model):\n \"\"\"create a project list\"\"\"\n class Meta:\n db_table = 'manage_ad'\n\n id = models.AutoField(max_length=100, db_column=\"id\", primary_key=True)\n image = models.CharField(max_length=500, db_column=\"image\", blank=True)\n replacead = models.CharField(max_length=100, db_column=\"replacead\", blank=True)\n removead = models.CharField(max_length=100, db_column=\"removead\", blank=True)\n\n","sub_path":"delad/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"429655602","text":"import numpy as np\nimport sys\nimport random\nfrom gym.envs.toy_text import discrete\nimport random\n\nUP = 0\nRIGHT = 1\nDOWN = 2\nLEFT =3\n\nclass GridworldEnv(discrete.DiscreteEnv):\n metadata = {'render.modes':['human', 'ansi']}\n \n \n def _limit_coordinates(self, coord):\n coord[0] = min(coord[0], self.shape[0] -1)\n coord[0] = max(coord[0],0)\n \n coord[1] = min(coord[1], self.shape[1] -1)\n coord[1] = max(coord[1], 0)\n \n return coord\n \n def _calculate_transition_prob(self, current, delta):\n nS = np.prod(self.shape)\n new_position = np.array(current) + np.array(delta)\n new_position = self._limit_coordinates(new_position).astype(int)\n new_state = np.ravel_multi_index(tuple(new_position), self.shape)\n \n \n #for i in range(0,3):\n # if new_state==self.target[i]:\n # self.t[i]=1\n reward = -3.0 + sum(self.t)\n\n is_done = all(tar ==1 for tar in self.t)\n\n \n\n return [(1.0, new_state, reward, is_done)]\n\n def step(self, a):\n nS = np.prod(self.shape)\n transitions = self.P[self.s][a]\n #i = categorical_sample([t[0] for t in transitions], self.np_random)\n p,s,r,d = transitions[0]\n self.target[0] = random.randint(-1,nS-1)\n self.target[1] = random.randint(-1,nS-1)\n self.target[2] = random.randint(-1,nS-1)\n #print(self.target)\n for i in range(0,3):\n if s==self.target[i]:\n self.t[i]=1\n d = all(tar ==1 for tar in self.t)\n r = 0.0 if d else -1.0\n \n self.s = s\n self.lastaction = a\n return (s, r, d, {\"prob\" : p})\n \n def __init__(self):\n self.shape = (4,4)\n \n nS = np.prod(self.shape) #number of states\n nA = 4 #number of actions\n\n self.t = [0,0,0]\n\n self.target = [1,7,nS-1]\n \n #calculate transistion probabilities\n P = {}\n for s in range(nS):\n position = np.unravel_index(s, self.shape)\n P[s] = {a : [] for a in range (nA)}\n \n P[s][UP] = self._calculate_transition_prob(position, [-1,0])\n P[s][RIGHT] = self._calculate_transition_prob(position, [0,1])\n P[s][DOWN] = self._calculate_transition_prob(position,[1,0])\n P[s][LEFT] = self._calculate_transition_prob(position, [0,-1])\n \n #we always start in state (3,0)\n isd = np.zeros(nS)\n isd[np.ravel_multi_index((3,0) , self.shape)] = 1.0\n \n super(GridworldEnv, self).__init__(nS,nA,P,isd)\n \n def render(self,mode='human', close=False):\n self._render(mode, close)\n \n def _render(self, mode='human', close=False):\n if close:\n return\n \n\n outfile = StringIO() if mode=='ansi' else sys.stdout\n print(self.target)\n \n for s in range(self.nS):\n position = np.unravel_index(s, self.shape)\n if self.s == s:\n output = \" x \"\n elif any(tar ==s for tar in self.target):\n output = \" T \"\n else:\n output = \" o \"\n \n if position[1] == 0:\n output = output.lstrip()\n if position[1] == self.shape[1] -1:\n output = output.rstrip()\n output += \"\\n\"\n \n outfile.write(output)\n outfile.write(\"\\n\")\n","sub_path":"lib/envs/walking_popup.py","file_name":"walking_popup.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"159972480","text":"'''\nYou have an array of integers\nYou need to perform operation on these numbers so that all becomes 1\noperation: replace any two adjacent numbers with GCD of these two numbers\nprint number of operation needed or -1 if it can not be done\nExamples\ninput\n5\n2 2 3 4 6\noutput\n5\ninput\n4\n2 4 6 8\noutput\n-1\ninput\n3\n2 6 9\noutput\n4\nstartegy: GCD of any two numbers would be 1 if either of them is 1\nor if all of them are primes\nIf even one 1 is avaible in array , it can be used to convert others to one\nIn that case nop needed is number of element -1\nSo first count how many 1 is available . Answer would be len array - count\nIn case no 1 is available startegy would be to sequentially try to convert\nnumber with their gcd till we get 1 as gcd.\nnop = nop done + length of remaining array\n'''\n\n\nfrom math import gcd\nn=int(input())\na=list(map(int, input().split()))\nonecnt = a.count(1)\nif onecnt > 0:\n print(n - onecnt)\nelse:\n nop = 0\n flag=True\n while (a.count(1)==0):\n if (len(a)-nop==1 and a[0]!=1):\n flag = False\n break\n nop+=1\n for i in range(len(a)-nop):\n a[i]=gcd(a[i], a[i+1])\n print([-1,nop+n -1][flag])\n","sub_path":"codechef/pride_892_C.py","file_name":"pride_892_C.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"252820604","text":"import copy\nfrom datetime import datetime\n\nfrom tax_report_generator.pathfinding import pathfinder\nfrom tax_report_generator.data_wrangling import transform_data\nfrom tax_report_generator.data_wrangling import pandas_functions\nfrom tax_report_generator.xml_generating import xml_generator\nfrom tax_report_generator.xml_generating import lxml_functions\nfrom tax_report_generator.settings import xml_settings\nfrom tax_report_generator.settings import report_settings\nfrom tax_report_generator.settings import data_settings\n\n\n\nclass OPZGenerator(xml_generator.XMLGenerator):\n def __init__(self, data_wrapper):\n self.__SetDataFrames(data_wrapper)\n \n report_name = xml_settings.opz_template\n self.SetAndLoadRootElements(report_name)\n \n self.ConstructReport()\n \n lxml_functions.WriteTreeToFile(self.wrapper_tree, xml_settings.opz_output_file)\n \n def __SetDataFrames(self, data_wrapper):\n name, extension = pathfinder.SplitFileNameIntoNameAndExtension(data_settings.invoices_file)\n self.invoices = copy.deepcopy(data_wrapper.data_frames[name])\n \n name, extension = pathfinder.SplitFileNameIntoNameAndExtension(data_settings.customers_file)\n self.customers = copy.deepcopy(data_wrapper.data_frames[name])\n \n \n \n def CreateAndFillOutBody(self):\n body_element = self.__ExtractBodyElement()\n children = lxml_functions.GetSubElements(body_element)\n \n customers_element = self.__FillOutCustomers()\n lxml_functions.InsertChildElementIntoElementAtIndex(customers_element, body_element, 0)\n \n for child_element in children:\n data = False\n child_tag = lxml_functions.GetTag(child_element)\n \n if child_tag == \"UkupanIznosRacunaObrasca\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"K5\", customers_element)\n \n elif child_tag == \"UkupanIznosPdvObrasca\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"K6\", customers_element)\n \n elif child_tag == \"UkupanIznosRacunaSPdvObrasca\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"K7\", customers_element)\n \n elif child_tag == \"UkupniPlaceniIznosRacunaObrasca\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"K8\", customers_element)\n \n elif child_tag == \"NeplaceniIznosRacunaObrasca\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"K9\", customers_element)\n \n elif child_tag == \"OPZUkupanIznosRacunaSPdv\":\n data = 0.0\n \n elif child_tag == \"OPZUkupanIznosPdv\":\n data = 0.0\n \n if (data != False):\n lxml_functions.SetElementText(child_element, data)\n \n return body_element\n \n\n \n def __FillOutCustomers(self):\n customers_element = lxml_functions.CreateElement(\"Kupci\")\n \n customer_counter = 1\n while (pandas_functions.IsFrameNotEmpty(self.invoices)):\n customer_name = pandas_functions.GetFirstValueFromColumnFromFrame(data_settings.invoices_customer_name, self.invoices)\n \n invoice_batch, self.invoices = pandas_functions.SplitFrameAlongColumnWithValue(self.invoices, data_settings.invoices_customer_name, customer_name)\n \n customer_element = self.__FillOutCustomerNumber(invoice_batch, customer_counter)\n lxml_functions.AddChildElementToElement(customer_element, customers_element)\n \n customer_counter += 1\n \n return customers_element\n \n def __FillOutCustomerNumber(self, invoice_batch, number):\n customer_element = self.__ExtractCustomerElement()\n children = lxml_functions.GetSubElements(customer_element)\n \n invoices_element = self.__FillOutInvoices(invoice_batch)\n lxml_functions.AddChildElementToElement(invoices_element, customer_element)\n \n customer_name = pandas_functions.GetFirstValueFromColumnFromFrame(data_settings.invoices_customer_name, invoice_batch)\n \n for child_element in children:\n data = False\n child_tag = lxml_functions.GetTag(child_element)\n \n if child_tag == \"K1\":\n data = number\n \n elif child_tag == \"K2\":\n data = 1\n \n elif child_tag == \"K3\":\n number = pandas_functions.GetValueFromColumnFromFrameIfColumnHasValue(data_settings.customers_tax_number, self.customers, data_settings.customers_name, customer_name)\n data = transform_data.AddLeadingZerosToStringUntilLength(number, 11)\n \n elif child_tag == \"K4\":\n data = customer_name\n \n elif child_tag == \"K5\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"R6\", invoices_element)\n \n elif child_tag == \"K6\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"R7\", invoices_element)\n \n elif child_tag == \"K7\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"R8\", invoices_element)\n \n elif child_tag == \"K8\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"R9\", invoices_element)\n \n elif child_tag == \"K9\":\n data = lxml_functions.GetSumOfAllSubElementsWithTagPatternOfElement(\"R10\", invoices_element)\n \n if (data != False):\n lxml_functions.SetElementText(child_element, data)\n \n return customer_element\n \n def __FillOutInvoices(self, invoice_batch):\n invoices_element = lxml_functions.CreateElement(\"Racuni\")\n \n invoice_counter = 1\n for index, invoice in invoice_batch.iterrows():\n invoice_element = self.__FillOutInvoiceNumber(invoice, invoice_counter)\n \n lxml_functions.AddChildElementToElement(invoice_element, invoices_element)\n \n invoice_counter += 1\n \n return invoices_element\n \n def __FillOutInvoiceNumber(self, invoice, number):\n invoice_element = self.__ExtractInvoiceElement()\n all_children = lxml_functions.GetAllSubElements(invoice_element)\n \n for child_element in all_children:\n data = False\n child_tag = lxml_functions.GetTag(child_element)\n \n if child_tag == \"R1\":\n data = number\n \n elif child_tag == \"R2\":\n data = invoice[u'Invoice Nr']\n \n elif child_tag == \"R3\":\n data = invoice[u'Posting date']\n \n elif child_tag == \"R4\": \n data = invoice[u'Due Date']\n \n elif child_tag == \"R5\":\n data = self.__GetPaymentDelay(invoice[u'Due Date'])\n \n elif child_tag == \"R6\":\n data = invoice[data_settings.invoices_amount] / (1.0 + report_settings.tax_rate)\n \n elif child_tag == \"R7\":\n data = invoice[data_settings.invoices_amount] - invoice[data_settings.invoices_amount] / (1.0 + report_settings.tax_rate)\n \n elif child_tag == \"R8\":\n data = invoice[data_settings.invoices_amount]\n \n elif child_tag == \"R9\":\n data = invoice[data_settings.invoices_amount] - invoice[data_settings.invoices_open_amount]\n \n elif child_tag == \"R10\":\n data = invoice[data_settings.invoices_open_amount]\n \n if (data != False):\n lxml_functions.SetElementText(child_element, data)\n \n return invoice_element\n \n \n \n def __GetPaymentDelay(self, payment_date):\n report_date = datetime.strptime(report_settings.NisuNaplaceniDo, \"%Y-%m-%d\")\n return report_date - payment_date\n \n \n \n def __ExtractBodyElement(self):\n body_element = copy.deepcopy(self.body_root)\n body_element.remove(body_element[0])\n \n return body_element\n \n def __ExtractCustomerElement(self):\n body_children = lxml_functions.GetAllSubElements(self.body_root)\n for element in body_children:\n if element.tag == \"Kupac\":\n customer_element = copy.deepcopy(element)\n customer_element.remove(customer_element[-1])\n \n return customer_element\n \n def __ExtractInvoiceElement(self):\n body_children = lxml_functions.GetAllSubElements(self.body_root)\n for element in body_children:\n if element.tag == \"Racun\":\n invoice_element = copy.deepcopy(element)\n \n return invoice_element\n ","sub_path":"tax_report_generator/old/xml_generating/opz_generator.py","file_name":"opz_generator.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"651415963","text":"\"\"\"An example for using the TackEverything package\nThis example uses an Head Detection model from AVAuco/ssd_head_keras github repo\nfor detecting heads. It also uses a Face Mask classification model from\nchandrikadeb7/Face-Mask-Detection github repo for the classification.\nIt can now easly detect, classify and track heads with/without masks in a video\nusing a few lines of code.\nThe use of the TrackEverything package make the models much more accurate\nand robust, using tracking features and statistics.\n\"\"\"\nimport os\n#hide some tf loading data\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n# pylint: disable=wrong-import-position\n\nfrom TrackEverything.detector import Detector\nfrom TrackEverything.tool_box import InspectorVars\nfrom TrackEverything.statistical_methods import StatisticalCalculator, StatMethods\nfrom TrackEverything.visualization_utils import VisualizationVars\n\nfrom detection_vars import get_det_vars_1\nfrom classification_vars import get_class_vars\nfrom play_video import run_video\n# pylint: enable=wrong-import-position\n\nCLASS_MODEL_PATH=\"classification_models/\" \\\n\"mask_class.model\"\n\n\n#set the detector\ndetector_1=Detector(\n det_vars=get_det_vars_1(),\n class_vars=get_class_vars(CLASS_MODEL_PATH),\n inspector_vars=InspectorVars(\n stat_calc=StatisticalCalculator(method=StatMethods.FMA)\n ),\n visualization_vars=VisualizationVars(\n labels=[\"No Mask\",\"Mask\"],\n colors=[\"Red\",\"Green\",\"Cyan\"],#last color for trackers\n show_trackers=True,\n uncertainty_threshold=0.1,\n uncertainty_label=\"Collecting Info\"\n )\n)\n\n#Test it on a video\nVIDEO_PATH=\"video/OxfordStreet.mp4\"\n#since the head detction model requires a 512x512 image input\nrun_video(VIDEO_PATH,(512,512),detector_1)\n# from play_video import save_video\n# save_video(VIDEO_PATH,(512,512),detector_1,\"video/mask_01.avi\")\n","sub_path":"mask_example/mask_detection_ex1.py","file_name":"mask_detection_ex1.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"257203421","text":"# 560. Subarray Sum Equals K\n\n# 2021/04/13\n# Runtime: 260 ms, faster than 50.50% of Python3 online submissions for Subarray Sum Equals K.\n# Memory Usage: 16.8 MB, less than 25.01% of Python3 online submissions for Subarray Sum Equals K.\n\n#哈希表 + 前缀和。与lc523基本一样。\n# 用哈希表查找是否之前有比当前前缀和小k的前缀和。如果有的话将count加上即可。\n# 哈希表中存放的是前缀和出现的次数。\n\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n sums, ans = 0, 0\n seen = {0: 1}\n for i in range(len(nums)):\n sums += nums[i]\n if sums - k in seen:\n ans += seen[sums - k]\n seen[sums] = seen.get(sums, 0) + 1\n return ans\n","sub_path":"0560. Subarray Sum Equals K.py","file_name":"0560. Subarray Sum Equals K.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"640040589","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n#\n# VM NAT rules\n# ============\n# Environment: NAT and VDC with NAT IP\n\n# Add NAT rules to VM\n# -------------------\n\n# Requires:\n# * 1 x VM\n# * With private IP to add NAT rules\n\n# Steps\n# * Get VM with private IP without NAT rules by vmlabel\n# * Get first private IP to add to NAT rules JSON\n# * Get VDC of VM (use in part 2 also)\n# * Get NAT IPs of VDC to add to NAT rules JSON, use first NAT IP\n# * Create NAT rules with private IP/NAT IP\n#\n#\nimport copy\nimport json\nfrom abiquo.client import Abiquo\nfrom abiquo.client import check_response\nimport sys\n\n# For test environment disable SSL warning\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n# Constants for NAT rules\nDNATPORTORIGINAL = 36911\nDNATPORTTRANSLATED = 22\nDNATPROTOCOL = \"TCP\"\nVMLABEL = \"NATADD\"\nLOCALDOMAINAPI = \".abq.example.com/api\"\n\n\ndef main():\n # For test pass in the local system, username and password\n localsystem = sys.argv[1]\n username = sys.argv[2]\n password = sys.argv[3]\n dnatportorigin = DNATPORTORIGINAL\n API_URL = \"https://\" + localsystem + LOCALDOMAINAPI\n api = Abiquo(API_URL, auth=(username, password), verify=False)\n\n# Another option:\n# API_URL = input(\"Enter Abiquo API URL,\n# e.g 'https://abq.example.abiquo.com/api': \")\n# username = input(\"Username: \")\n# password = input(\"Password: \")\n # Assuming test environment with self-signed certificate\n# api = Abiquo(API_URL, auth=(username, password), verify=False)\n\n# Get VMs with VM to add NAT rules, use vmlabel filter\n code, virtualmachines = api.cloud.virtualmachines.get(\n headers={'Accept': 'application/vnd.abiquo.virtualmachines+json'},\n params={'vmlabel': VMLABEL})\n check_response(201, code, virtualmachines)\n print(\"Get VM, Response code is: \", code)\n\n# Check that there is only one VM with the label,\n# that there are no existing NAT rules, and that the VM has a NIC\n if virtualmachines.totalSize > 1:\n print(\"Warning! Multiple VMs with same label!\")\n for vm in virtualmachines:\n dnatportorigin = dnatportorigin + 1\n print(\"NATADD VM: \", str(vm.label))\n if vm.natrules:\n print(\"Warning! VM already has NAT Rules!\")\n continue\n if not vm.nic0:\n print(\"Warning! VM has no NICs\")\n break\n else:\n # Get link to any private IPs in the VM to use in NAT rules\n privateIPLinks = list(filter(\n lambda vmlink: \"privateip\" in vmlink[\"type\"],\n vm.json[\"links\"]))\n\n # Use the first private IP\n pipLink = privateIPLinks[0]\n print(\"Private IP link:\", json.dumps(pipLink, indent=2))\n\n # Get VDC of VM (use in part 2 also)\n code, vdc = vm.follow('virtualdatacenter').get(\n headers={'accept': 'application/vnd.abiquo.virtualdatacenter+json'})\n print(\"Response code is: \", code)\n print(\"VM belongs to VDC: \", vdc.name)\n\n # Get NAT IPs of VDC to use in NAT rules\n code, natips = vdc.follow('natips').get(\n headers={'accept': 'application/vnd.abiquo.natips+json'},\n params={'usable': True})\n print(\"Response code is: \", code)\n\n # Filter natips to get the NAT IPs that are not the default SNAT\n nonDefaultSNATIPs = list(filter(\n lambda nsnatip: nsnatip.json[\"defaultSnat\"] == False,\n natips))\n\n # Get first NAT IP of VDC that is not the default SNAT\n ndsnaip = nonDefaultSNATIPs[0]\n print(\"ndsnaip: \", json.dumps(ndsnaip.json, indent=2))\n\n # Get the self link of the NAT IP\n natipLinks = list(filter(lambda link: link[\"rel\"] == \"self\",\n ndsnaip.json[\"links\"]))\n natipLink = natipLinks[0]\n print(\"natipLink: \", json.dumps(natipLink, indent=2))\n\n # Create NAT rules with private IP/NAT IP\n addnatrules = []\n\n # Create snat rule\n snatrule = {}\n snatrule[\"snat\"] = True\n snatrule[\"links\"] = []\n snatruleOriginalLink = copy.deepcopy(pipLink)\n snatruleOriginalLink[\"rel\"] = \"original\"\n snatrule[\"links\"].append(snatruleOriginalLink)\n snatruleTranslatedLink = copy.deepcopy(natipLink)\n snatruleTranslatedLink[\"rel\"] = \"translated\"\n snatrule[\"links\"].append(snatruleTranslatedLink)\n print(\"snatrule: \", json.dumps(snatrule, indent=2))\n addnatrules.append(snatrule)\n\n # Create dnat rule\n dnatrule = {}\n dnatrule[\"snat\"] = False\n dnatrule[\"originalPort\"] = DNATPORTORIGINAL\n dnatrule[\"translatedPort\"] = DNATPORTTRANSLATED\n dnatrule[\"protocol\"] = DNATPROTOCOL\n dnatruleOriginalLink = copy.deepcopy(natipLink)\n dnatruleOriginalLink[\"rel\"] = \"original\"\n dnatrule[\"links\"] = []\n dnatrule[\"links\"].append(dnatruleOriginalLink)\n dnatruleTranslatedLink = copy.deepcopy(pipLink)\n dnatruleTranslatedLink[\"rel\"] = \"translated\"\n dnatrule[\"links\"].append(dnatruleTranslatedLink)\n print(\"dnatrule: \", json.dumps(dnatrule, indent=2))\n addnatrules.append(dnatrule)\n\n # Get edit link of VM to use for put request\n vmEditLinks = list(filter(\n lambda link: link[\"rel\"] == \"edit\", vm.json[\"links\"]))\n vmEditLink = vmEditLinks[0]\n print(\"vm edit link: \", json.dumps(vmEditLink, indent=2))\n\n # Add the nat rules to the original VM object\n vm.json[\"natrules\"] = addnatrules[:]\n\n # Send a PUT request to the VM edit link and update the VM\n code, vmaddnr = vm.follow('edit').put(\n headers={'accept': 'application/vnd.abiquo.acceptedrequest+json',\n 'content-type': 'application/vnd.abiquo.virtualmachine+json'},\n data=json.dumps(vm.json))\n\n # Response code should be 2XX depending on deployed/undeployed VM\n print(\"Update VM, response code is: \", code)\n\n\n# Calls the main() function\nif __name__ == '__main__':\n main()\n","sub_path":"api_howtos/vm_add_nat_rules.py","file_name":"vm_add_nat_rules.py","file_ext":"py","file_size_in_byte":6307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"414132083","text":"import json, time, urllib.request\nfrom pprint import pprint\n\n\"\"\"global vars\"\"\"\napiURL = \"\"\napItems = [3089, 3157, 3285, 3116, 3003, 3027, 3151, 3135, 3115, 3152, 3165, 3174]\nitemsByChamp = {}\nitemStats = {}\n\n\"\"\"set up item stats object\"\"\"\nprint(\"Gathering artifacts.\")\nfor i in apItems:\n itemURL = \"https://global.api.pvp.net/api/lol/static-data/na/v1.2/item/\" + str(i) + apiURL\n itemRequest = urllib.request.urlopen(itemURL)\n itemData = json.loads(itemRequest.read().decode(\"utf8\"))\n itemRequest.close()\n\n itemStats[str(i)] = {\"name\": itemData[\"name\"]}\n itemStats[str(i)][\"purchased\"] = 0\n itemStats[str(i)][\"won\"] = 0\n itemStats[str(i)][\"priority\"] = [{}, {}, {}, {}, {}, {}, {}, {}]\n for j in range(len(itemStats[str(i)][\"priority\"])):\n itemStats[str(i)][\"priority\"][j] = { \"purchased\": 0, \"won\": 0 }\n\n\"\"\"load match json\"\"\"\nwith open('./5.11/RANKED_SOLO/NA.json', 'r') as matchFile:\n matchList = json.load(matchFile)\n\n\"\"\"fetch match data\"\"\"\ncounter = 0;\nwhile counter < len(matchList):\n matchURL = 'https://na.api.pvp.net/api/lol/na/v2.2/match/' + str(matchList[counter])\n endURL = '?includeTimeline=true&api_key=983ca0c5-07fe-43ea-acba-db1411006b49'\n try:\n matchRequest = urllib.request.urlopen(matchURL + endURL)\n matchData = json.loads(matchRequest.read().decode(\"utf8\"))\n matchRequest.close()\n playerData = matchData[\"participants\"]\n frameData = matchData[\"timeline\"][\"frames\"]\n\n blueTeamWon = playerData[0][\"stats\"][\"winner\"]\n\n champList = {}\n for player in playerData:\n champList[player[\"participantId\"]] = {\"champion\":player[\"championId\"],\"purchased\":0}\n\n for frame in frameData:\n if \"events\" in frame:\n for event in frame[\"events\"]:\n if event[\"eventType\"] == \"ITEM_UNDO\":\n item = event[\"itemBefore\"]\n if item in apItems:\n itemStats[str(item)][\"purchased\"] -= 1\n champList[event[\"participantId\"]][\"purchased\"] -= 1\n itemStats[str(item)][\"priority\"][champList[event[\"participantId\"]][\"purchased\"]][\"purchased\"] -= 1\n itemsByChamp[champList[event[\"participantId\"]][\"champion\"]][str(item)][\"purchased\"] -= 1\n\n champId = champList[event[\"participantId\"]][\"champion\"]\n if event[\"participantId\"] > 5 and not blueTeamWon:\n itemStats[str(item)][\"won\"] -= 1\n itemsByChamp[champId][str(item)][\"won\"] -= 1\n itemStats[str(item)][\"priority\"][champList[event[\"participantId\"]][\"purchased\"]][\"won\"] -= 1\n if event[\"participantId\"] < 6 and blueTeamWon:\n itemStats[str(item)][\"won\"] -= 1\n itemsByChamp[champId][str(item)][\"won\"] -= 1\n itemStats[str(item)][\"priority\"][champList[event[\"participantId\"]][\"purchased\"]][\"won\"] -= 1\n if event[\"eventType\"] == \"ITEM_PURCHASED\":\n item = event[\"itemId\"]\n if item in apItems and champList[event[\"participantId\"]][\"purchased\"] < 8:\n itemStats[str(item)][\"purchased\"] += 1\n itemStats[str(item)][\"priority\"][champList[event[\"participantId\"]][\"purchased\"]][\"purchased\"] += 1\n\n champId = champList[event[\"participantId\"]][\"champion\"]\n if champId not in itemsByChamp:\n champURL = \"https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion/\" + str(champId) + apiURL\n champRequest = urllib.request.urlopen(champURL)\n champData = json.loads(champRequest.read().decode(\"utf8\"))\n champRequest.close()\n\n itemsByChamp[champId] = {\"name\": champData[\"name\"]}\n if str(item) not in itemsByChamp[champId]:\n itemsByChamp[champId][str(item)] = { \"purchased\": 1, \"won\": 0 }\n else:\n itemsByChamp[champId][str(item)][\"purchased\"] += 1\n\n if event[\"participantId\"] > 5 and not blueTeamWon:\n itemStats[str(item)][\"won\"] += 1\n itemsByChamp[champId][str(item)][\"won\"] += 1\n itemStats[str(item)][\"priority\"][champList[event[\"participantId\"]][\"purchased\"]][\"won\"] += 1\n if event[\"participantId\"] < 6 and blueTeamWon:\n itemStats[str(item)][\"won\"] += 1\n itemsByChamp[champId][str(item)][\"won\"] += 1\n itemStats[str(item)][\"priority\"][champList[event[\"participantId\"]][\"purchased\"]][\"won\"] += 1\n\n champList[event[\"participantId\"]][\"purchased\"] += 1\n print(counter)\n counter += 1\n time.sleep(1.3)\n except urllib.error.HTTPError as err:\n if err.code == 429:\n print(\"Creep blocked!\")\n time.sleep(2.5)\n\nchampJSON = json.dumps(itemsByChamp)\nitemJSON = json.dumps(itemStats)\nchampJSON_f = json.dumps(itemsByChamp, sort_keys=True, indent=2, separators=(',', ': '))\nitemJSON_f = json.dumps(itemStats, sort_keys=True, indent=2, separators=(',', ': '))\n\nwith open('public/data/5.11/ranked/champs.json', 'w') as champFile:\n champFile.write(champJSON)\nwith open('public/data/5.11/ranked/items.json', 'w') as itemFile:\n itemFile.write(itemJSON)\nwith open('public/data/5.11/ranked/champs_formatted.json', 'w') as champFile:\n champFile.write(champJSON_f)\nwith open('public/data/5.11/ranked/items_formatted.json', 'w') as itemFile:\n itemFile.write(itemJSON_f)\n\nprint(\"done\")\n","sub_path":"ProcessMatches.py","file_name":"ProcessMatches.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"245928993","text":"_schema = {\n\n 'Account': {'type': 'dict',\n # 'schema': {'AccountId': {'type': 'integer'},\n # 'AccountNo': {'type': 'integer'}}\n },\n # 'ActiveLabel': {'type': 'string'},\n # 'CancellationDate': None,\n # 'CancellationTypeId': None,\n 'Comment': {'type': 'string', 'default': ''},\n 'Contact': {'type': 'dict', 'default': {}},\n # 'ContactId': {'type': 'integer'},\n 'Created': {'type': 'datetime'},\n 'DescribingName': {'type': 'string', 'default': ''},\n 'IsActive': {'type': 'boolean'},\n 'LocalCouncilId': {'type': 'integer'},\n 'LocalCouncilName': {'type': 'string', 'default': ''},\n 'Modified': {'type': 'datetime'},\n 'NIFOrganizationNumber': {'type': 'string', 'default': ''},\n 'Name': {'type': 'string', 'default': ''},\n 'OrgId': {'type': 'integer', 'unique': True},\n 'OrgStructuresDown': {'type': 'list',\n 'schema': {'type': 'dict',\n 'schema': {'id': {'type': 'integer'},\n 'type': {'type': 'integer',\n 'data_relation': {'resource': 'organization/types',\n 'field': 'OrgTypeId',\n 'embeddable': True\n }}}}\n },\n 'OrgStructuresUp': {'type': 'list',\n 'schema': {'type': 'dict',\n 'schema': {'id': {'type': 'integer'},\n 'type': {'type': 'integer'}}}\n },\n # 'data_relation': {\n # 'resource': 'users',\n # 'field': '_id',\n # 'embeddable': True\n # },\n\n 'OrganizationTypeId': {'type': 'integer'},\n 'ParentOrganizationId': {'type': 'integer'},\n 'RegisterAuthorityOrganizationNumber': {'type': 'string'},\n 'ShortName': {'type': 'string'},\n 'Activities': {'type': 'list', 'schema': {'type': 'dict', 'schema': {\n 'ActivityCode': {'type': 'string'},\n 'ActivityId': {'type': 'integer'},\n 'Name': {'type': 'string'}\n\n }}},\n 'MainActivity': {'type': 'dict',\n 'schema': {'ActivityCode': {'type': 'string'},\n 'ActivityId': {'type': 'integer'},\n 'Name': {'type': 'string'}\n },\n }\n}\n\ndefinition = {\n 'item_title': 'organizations',\n 'datasource': {'source': 'organizations',\n },\n 'additional_lookup': {\n 'url': 'regex(\"[\\d{1,9}]+\")',\n 'field': 'OrgId',\n },\n 'extra_response_fields': ['OrgId'],\n 'versioning': False,\n 'resource_methods': ['GET', 'POST', 'DELETE'],\n 'item_methods': ['GET', 'PATCH', 'PUT'],\n\n 'schema': _schema\n}\n","sub_path":"domain/organizations.py","file_name":"organizations.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"180677863","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.layers.core import Flatten, Dense, Dropout, Activation\n#from keras.layers import Merge\nfrom keras.models import Sequential\n\nfrom keras.optimizers import *\nfrom keras.models import *\n#from keras.utils import plot_model\nfrom keras.layers.normalization import BatchNormalization\n\n\npose_file = '/media/chuck/DATA/dataset/poses/00.txt'\nfeatures_path = '/media/chuck/DATA/dataset/sequences/00/image_0/'\n\n\nrows = 224\ncols = 224\n\n#resize the image to 224x224\ndef preprocessing(img):\n\tresized = cv2.resize(img, (cols, rows))\n\treturn resized\n\n\n#define the function to save the model\ndef model_save(model_json,model_h5):\n json_model = model.to_json()\n with open(model_json, \"w\") as f:\n f.write(json_model)\n model.save_weights(model_h5)\n\n\n\n#load poses in kitti dataset, change them to a new form - motion between two sequent images\n#this function return a list 'labels', if totally n images, labels has (n-2) elements\ndef load_labels(pose_file):\n\t#TR is a list which saving original pose\n\ttry:\n\t\tTR = []\n\t\twith open(pose_file, 'r') as f:\n\t\t\tfor line in f.readlines():\n\t\t\t\tT = np.fromstring(line, dtype=float, sep=' ')\n\t\t\t\tT = T.reshape(3,4)\n\t\t\t\tT = np.vstack((T, [0,0,0,1]))\n\t\t\t\tTR.append(T)\n\t\t#print('done.')\n\n\texcept FileNotFoundError:\n\t\tprint('Groun Truth poses folder are not avaiable.')\n\n\n\t#labels is a two dimension list, each element (list) indicates the distance changes in x and z direction\n\tlabels = []\n\tfor i in range(len(TR)-2):\n\t\tP1 = np.dot(TR[i+1], TR[0])\n\t\tP2 = np.dot(TR[i+2], TR[0])\n\t\tP21 = [P2[0,3]-P1[0,3],P2[2,3]-P1[2,3]]\n\t\tlabels.append([P21[0],P21[1]])\n\treturn labels\n\n\n#load images and labels\ndef load_features(features_path):\n\tfeatures = []\n\tfor i in range(4541):\n\t\tif i < 10:\n\t\t\timg_path = features_path + '00000' + '{}'.format(i) + '.png'\n\t\telif i>=10 and i < 100:\n\t\t\timg_path = features_path + '0000' + '{}'.format(i) + '.png'\n\t\telif i>=100 and i < 1000:\n\t\t\timg_path = features_path + '000' + '{}'.format(i) + '.png'\n\t\telse:\n\t\t\timg_path = features_path + '00' + '{}'.format(i) + '.png'\n\t\t\n\t\t#read image\n\t\ttry:\n\t\t\timg = plt.imread(img_path)\n\t\texcept:\n\t\t\tprint('image {} read fail'.format(i))\n\n\t\t#append image features\n\t\ttry:\n\t\t\tfeatures.append(preprocessing(img))\n\t\texcept:\n\t\t\tprint('Wrong to append image {}'.format(i))\n\treturn features\n\n\nfeatures = load_features(features_path)\nlabels = load_labels(pose_file)\ninput_img_x = features[0:(len(features)-2)]\ninput_img_y = features[1:(len(features)-1)]\n#print('\\nLoad image done!\\n\\nTotally {} images'.format(len(features)))\n\n#transform raw data and labels to numpy array\ninput_img_x = np.array(input_img_x).astype('float32')\ninput_img_y = np.array(input_img_y).astype('float32')\n#features = np.array(features).astype('float32')\nlabels = np.array(labels).astype('float32')\n\n#reshape the data to feed into the network\ninput_img_x = input_img_x.reshape(input_img_x.shape[0], rows, cols, 1)\ninput_img_y = input_img_x.reshape(input_img_y.shape[0], rows, cols, 1)\n#features = features.reshape(features.shape[0], rows, cols, 1)\n\nfeatures = np.concatenate((input_img_x, input_img_y), axis=3)\n\n#print('donedone')\n\ndef build_model():\n\t#define channel 1 _ input is input_img_x\n\t#Conv_layer 1 and pooling layer 1\n\tchannel_1 = Sequential()\n\tchannel_1.add(Conv2D(48, 11, strides=(4,4), padding='same', activation='relu', kernel_initializer='TruncatedNormal', bias_initializer='zeros', input_shape=(224,224,2)))\n\tchannel_1.add(BatchNormalization())\n\tchannel_1.add(MaxPooling2D(strides=None, pool_size=(2,2)))\n\n\t#Conv_layer 2 and pooling layer 2\n\tchannel_1.add(Conv2D(128, 5, strides=(1,1), padding='same', activation='relu', kernel_initializer='TruncatedNormal', bias_initializer='zeros'))\n\tchannel_1.add(BatchNormalization())\n\tchannel_1.add(MaxPooling2D(strides=None, pool_size=(2,2)))\n\n\t#Conv_layer 3,4,5\n\tchannel_1.add(Conv2D(192, 3, strides=(1,1), padding='same', activation='relu', kernel_initializer='TruncatedNormal', bias_initializer='zeros'))\n\tchannel_1.add(BatchNormalization())\n\tchannel_1.add(Conv2D(192, 3, strides=(1,1), padding='same', activation='relu', kernel_initializer='TruncatedNormal', bias_initializer='zeros'))\n\tchannel_1.add(BatchNormalization())\n\tchannel_1.add(Conv2D(192, 3, strides=(1,1), padding='same', activation='relu', kernel_initializer='TruncatedNormal', bias_initializer='zeros'))\n\tchannel_1.add(BatchNormalization())\n\n\t#pooling layer 3\n\tchannel_1.add(MaxPooling2D(strides=None, pool_size=(2,2)))\n\n\t#flatten and FC layer\n\tchannel_1.add(Flatten())\n\t#channel_1.add(Dropout(0.2))\n\tchannel_1.add(Dense(2048, activation='relu', kernel_initializer='glorot_normal', bias_initializer='zeros'))\n\tchannel_1.add(BatchNormalization())\n\tchannel_1.add(Dropout(0.4))\n\tchannel_1.add(Dense(1024, activation='relu',kernel_initializer='glorot_normal', bias_initializer='zeros'))\n\tchannel_1.add(BatchNormalization())\n\tchannel_1.add(Dropout(0.4))\n\tchannel_1.add(Dense(256, activation='relu',kernel_initializer='glorot_normal', bias_initializer='zeros'))\n\tchannel_1.add(BatchNormalization())\n\tchannel_1.add(Dropout(0.4))\n\tchannel_1.add(Dense(2, activation='relu', kernel_initializer='glorot_normal', bias_initializer='zeros'))\n\tchannel_1.add(BatchNormalization())\n\tchannel_1.add(Activation('linear'))\n\n\tchannel_1.summary()\n\n\treturn channel_1\n\n\n\n#optimize\nmodel = build_model()\n\n#plot_model(model, to_file='./VONet.png')\n\nadam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-04, decay=0.0)\nmodel.compile(loss='mean_squared_error',optimizer='adam')\nprint('Model Compiled\\n\\nstart training...')\n\n#training with validation\n#history = model.fit([input_img_x, input_img_y], labels, validation_split=0.2, batch_size=32, nb_epoch=10,verbose=1)\n\n#training without validation\n#history = model.fit([input_img_x, input_img_y], labels, batch_size=32, nb_epoch=10,verbose=1)\nhistory = model.fit(features, labels, batch_size=32, nb_epoch=30,verbose=1)\n\n\n#save the model architecture and parameters\nmodel_json = '../model/model.json'\nmodel_h5 = '../model/model.h5'\nmodel_save(model_json,model_h5)","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"203040245","text":"import time\nimport pytest\n\nfrom swsscommon import swsscommon\n\nTUNNEL_TYPE_MAP = \"COUNTERS_TUNNEL_TYPE_MAP\"\nNUMBER_OF_RETRIES = 10\nCPU_PORT_OID = \"0x0\"\n\ncounter_group_meta = {\n 'port_counter': {\n 'key': 'PORT',\n 'group_name': 'PORT_STAT_COUNTER',\n 'name_map': 'COUNTERS_PORT_NAME_MAP',\n 'post_test': 'post_port_counter_test',\n },\n 'queue_counter': {\n 'key': 'QUEUE',\n 'group_name': 'QUEUE_STAT_COUNTER',\n 'name_map': 'COUNTERS_QUEUE_NAME_MAP',\n },\n 'rif_counter': {\n 'key': 'RIF',\n 'group_name': 'RIF_STAT_COUNTER',\n 'name_map': 'COUNTERS_RIF_NAME_MAP',\n 'pre_test': 'pre_rif_counter_test',\n 'post_test': 'post_rif_counter_test',\n },\n 'buffer_pool_watermark_counter': {\n 'key': 'BUFFER_POOL_WATERMARK',\n 'group_name': 'BUFFER_POOL_WATERMARK_STAT_COUNTER',\n 'name_map': 'COUNTERS_BUFFER_POOL_NAME_MAP',\n },\n 'port_buffer_drop_counter': {\n 'key': 'PORT_BUFFER_DROP',\n 'group_name': 'PORT_BUFFER_DROP_STAT',\n 'name_map': 'COUNTERS_PORT_NAME_MAP',\n },\n 'pg_watermark_counter': {\n 'key': 'PG_WATERMARK',\n 'group_name': 'PG_WATERMARK_STAT_COUNTER',\n 'name_map': 'COUNTERS_PG_NAME_MAP',\n },\n 'trap_flow_counter': {\n 'key': 'FLOW_CNT_TRAP',\n 'group_name': 'HOSTIF_TRAP_FLOW_COUNTER',\n 'name_map': 'COUNTERS_TRAP_NAME_MAP',\n 'post_test': 'post_trap_flow_counter_test',\n },\n 'tunnel_counter': {\n 'key': 'TUNNEL',\n 'group_name': 'TUNNEL_STAT_COUNTER',\n 'name_map': 'COUNTERS_TUNNEL_NAME_MAP',\n 'pre_test': 'pre_vxlan_tunnel_counter_test',\n 'post_test': 'post_vxlan_tunnel_counter_test',\n },\n 'acl_counter': {\n 'key': 'ACL',\n 'group_name': 'ACL_STAT_COUNTER',\n 'name_map': 'ACL_COUNTER_RULE_MAP',\n 'pre_test': 'pre_acl_tunnel_counter_test',\n 'post_test': 'post_acl_tunnel_counter_test',\n }\n}\n\n\nclass TestFlexCounters(object):\n\n def setup_dbs(self, dvs):\n self.config_db = dvs.get_config_db()\n self.flex_db = dvs.get_flex_db()\n self.counters_db = dvs.get_counters_db()\n self.app_db = dvs.get_app_db()\n\n def wait_for_table(self, table):\n for retry in range(NUMBER_OF_RETRIES):\n counters_keys = self.counters_db.db_connection.hgetall(table)\n if len(counters_keys) > 0:\n return\n else:\n time.sleep(1)\n\n assert False, str(table) + \" not created in Counters DB\"\n\n def wait_for_table_empty(self, table):\n for retry in range(NUMBER_OF_RETRIES):\n counters_keys = self.counters_db.db_connection.hgetall(table)\n if len(counters_keys) == 0:\n return\n else:\n time.sleep(1)\n\n assert False, str(table) + \" is still in Counters DB\"\n\n def wait_for_id_list(self, stat, name, oid):\n for retry in range(NUMBER_OF_RETRIES):\n id_list = self.flex_db.db_connection.hgetall(\"FLEX_COUNTER_TABLE:\" + stat + \":\" + oid).items()\n if len(id_list) > 0:\n return\n else:\n time.sleep(1)\n\n assert False, \"No ID list for counter \" + str(name)\n\n def wait_for_id_list_remove(self, stat, name, oid):\n for retry in range(NUMBER_OF_RETRIES):\n id_list = self.flex_db.db_connection.hgetall(\"FLEX_COUNTER_TABLE:\" + stat + \":\" + oid).items()\n if len(id_list) == 0:\n return\n else:\n time.sleep(1)\n\n assert False, \"ID list for counter \" + str(name) + \" is still there\"\n\n def wait_for_interval_set(self, group, interval):\n interval_value = None\n for retry in range(NUMBER_OF_RETRIES):\n interval_value = self.flex_db.db_connection.hget(\"FLEX_COUNTER_GROUP_TABLE:\" + group, 'POLL_INTERVAL')\n if interval_value == interval:\n return\n else:\n time.sleep(1)\n\n assert False, \"Polling interval is not applied to FLEX_COUNTER_GROUP_TABLE for group {}, expect={}, actual={}\".format(group, interval, interval_value)\n\n def verify_no_flex_counters_tables(self, counter_stat):\n counters_stat_keys = self.flex_db.get_keys(\"FLEX_COUNTER_TABLE:\" + counter_stat)\n assert len(counters_stat_keys) == 0, \"FLEX_COUNTER_TABLE:\" + str(counter_stat) + \" tables exist before enabling the flex counter group\"\n\n def verify_no_flex_counters_tables_after_delete(self, counter_stat):\n for retry in range(NUMBER_OF_RETRIES):\n counters_stat_keys = self.flex_db.get_keys(\"FLEX_COUNTER_TABLE:\" + counter_stat + \":\")\n if len(counters_stat_keys) == 0:\n return\n else:\n time.sleep(1)\n assert False, \"FLEX_COUNTER_TABLE:\" + str(counter_stat) + \" tables exist after removing the entries\"\n\n def verify_flex_counters_populated(self, map, stat):\n counters_keys = self.counters_db.db_connection.hgetall(map)\n for counter_entry in counters_keys.items():\n name = counter_entry[0]\n oid = counter_entry[1]\n self.wait_for_id_list(stat, name, oid)\n\n def verify_tunnel_type_vxlan(self, meta_data, type_map):\n counters_keys = self.counters_db.db_connection.hgetall(meta_data['name_map'])\n for counter_entry in counters_keys.items():\n oid = counter_entry[1]\n fvs = self.counters_db.get_entry(type_map, \"\")\n assert fvs != {}\n assert fvs.get(oid) == \"SAI_TUNNEL_TYPE_VXLAN\"\n\n def verify_only_phy_ports_created(self, meta_data):\n port_counters_keys = self.counters_db.db_connection.hgetall(meta_data['name_map'])\n port_counters_stat_keys = self.flex_db.get_keys(\"FLEX_COUNTER_TABLE:\" + meta_data['group_name'])\n for port_stat in port_counters_stat_keys:\n assert port_stat in dict(port_counters_keys.items()).values(), \"Non PHY port created on PORT_STAT_COUNTER group: {}\".format(port_stat)\n\n def set_flex_counter_group_status(self, group, map, status='enable'):\n group_stats_entry = {\"FLEX_COUNTER_STATUS\": status}\n self.config_db.create_entry(\"FLEX_COUNTER_TABLE\", group, group_stats_entry)\n if status == 'enable':\n self.wait_for_table(map)\n else:\n self.wait_for_table_empty(map)\n\n def set_flex_counter_group_interval(self, key, group, interval):\n group_stats_entry = {\"POLL_INTERVAL\": interval}\n self.config_db.create_entry(\"FLEX_COUNTER_TABLE\", key, group_stats_entry)\n self.wait_for_interval_set(group, interval)\n\n @pytest.mark.parametrize(\"counter_type\", counter_group_meta.keys())\n def test_flex_counters(self, dvs, counter_type):\n \"\"\"\n The test will check there are no flex counters tables on FlexCounter DB when the counters are disabled.\n After enabling each counter group, the test will check the flow of creating flex counters tables on FlexCounter DB.\n For some counter types the MAPS on COUNTERS DB will be created as well after enabling the counter group, this will be also verified on this test.\n \"\"\"\n self.setup_dbs(dvs)\n meta_data = counter_group_meta[counter_type]\n counter_key = meta_data['key']\n counter_stat = meta_data['group_name']\n counter_map = meta_data['name_map']\n pre_test = meta_data.get('pre_test')\n post_test = meta_data.get('post_test')\n\n self.verify_no_flex_counters_tables(counter_stat)\n\n if pre_test:\n cb = getattr(self, pre_test)\n cb(meta_data)\n\n self.set_flex_counter_group_status(counter_key, counter_map)\n self.verify_flex_counters_populated(counter_map, counter_stat)\n self.set_flex_counter_group_interval(counter_key, counter_stat, '2500')\n\n if post_test:\n cb = getattr(self, post_test)\n cb(meta_data)\n\n def pre_rif_counter_test(self, meta_data):\n self.config_db.db_connection.hset('INTERFACE|Ethernet0', \"NULL\", \"NULL\")\n self.config_db.db_connection.hset('INTERFACE|Ethernet0|192.168.0.1/24', \"NULL\", \"NULL\")\n\n def pre_vxlan_tunnel_counter_test(self, meta_data):\n self.config_db.db_connection.hset(\"VLAN|Vlan10\", \"vlanid\", \"10\")\n self.config_db.db_connection.hset(\"VXLAN_TUNNEL|vtep1\", \"src_ip\", \"1.1.1.1\")\n self.config_db.db_connection.hset(\"VXLAN_TUNNEL_MAP|vtep1|map_100_Vlan10\", \"vlan\", \"Vlan10\")\n self.config_db.db_connection.hset(\"VXLAN_TUNNEL_MAP|vtep1|map_100_Vlan10\", \"vni\", \"100\")\n\n def pre_acl_tunnel_counter_test(self, meta_data):\n self.config_db.create_entry('ACL_TABLE', 'DATAACL',\n {\n 'STAGE': 'INGRESS',\n 'PORTS': 'Ethernet0',\n 'TYPE': 'L3'\n }\n )\n self.config_db.create_entry('ACL_RULE', 'DATAACL|RULE0',\n {\n 'ETHER_TYPE': '2048',\n 'PACKET_ACTION': 'FORWARD',\n 'PRIORITY': '9999'\n }\n )\n\n def post_rif_counter_test(self, meta_data):\n self.config_db.db_connection.hdel('INTERFACE|Ethernet0|192.168.0.1/24', \"NULL\")\n\n def post_port_counter_test(self, meta_data):\n self.verify_only_phy_ports_created(meta_data)\n\n def post_trap_flow_counter_test(self, meta_data):\n \"\"\"Post verification for test_flex_counters for trap_flow_counter. Steps:\n 1. Disable test_flex_counters\n 2. Verify name map and counter ID list are cleared\n 3. Clear trap ids to avoid affecting further test cases\n\n Args:\n meta_data (object): flex counter meta data\n \"\"\"\n counters_keys = self.counters_db.db_connection.hgetall(meta_data['name_map'])\n self.set_flex_counter_group_status(meta_data['key'], meta_data['group_name'], 'disable')\n\n for counter_entry in counters_keys.items():\n self.wait_for_id_list_remove(meta_data['group_name'], counter_entry[0], counter_entry[1])\n self.wait_for_table_empty(meta_data['name_map'])\n\n def post_vxlan_tunnel_counter_test(self, meta_data):\n self.verify_tunnel_type_vxlan(meta_data, TUNNEL_TYPE_MAP)\n self.config_db.delete_entry(\"VLAN\",\"Vlan10\")\n self.config_db.delete_entry(\"VLAN_TUNNEL\",\"vtep1\")\n self.config_db.delete_entry(\"VLAN_TUNNEL_MAP\",\"vtep1|map_100_Vlan10\")\n self.verify_no_flex_counters_tables_after_delete(meta_data['group_name'])\n\n def post_acl_tunnel_counter_test(self, meta_data):\n self.config_db.delete_entry('ACL_RULE', 'DATAACL|RULE0')\n self.config_db.delete_entry('ACL_TABLE', 'DATAACL')\n\n def test_add_remove_trap(self, dvs):\n \"\"\"Test steps:\n 1. Enable trap_flow_counter\n 2. Remove a COPP trap\n 3. Verify counter is automatically unbind\n 4. Add the COPP trap back\n 5. Verify counter is added back\n\n Args:\n dvs (object): virtual switch object\n \"\"\"\n self.setup_dbs(dvs)\n meta_data = counter_group_meta['trap_flow_counter']\n self.set_flex_counter_group_status(meta_data['key'], meta_data['name_map'])\n\n removed_trap = None\n changed_group = None\n trap_ids = None\n copp_groups = self.app_db.db_connection.keys('COPP_TABLE:*')\n for copp_group in copp_groups:\n trap_ids = self.app_db.db_connection.hget(copp_group, 'trap_ids')\n if trap_ids and ',' in trap_ids:\n trap_ids = [x.strip() for x in trap_ids.split(',')]\n removed_trap = trap_ids.pop()\n changed_group = copp_group.split(':')[1]\n break\n\n if not removed_trap:\n pytest.skip('There is not copp group with more than 1 traps, skip rest of the test')\n\n oid = None\n for _ in range(NUMBER_OF_RETRIES):\n counters_keys = self.counters_db.db_connection.hgetall(meta_data['name_map'])\n if removed_trap in counters_keys:\n oid = counters_keys[removed_trap]\n break\n else:\n time.sleep(1)\n\n assert oid, 'trap counter is not created for {}'.format(removed_trap)\n self.wait_for_id_list(meta_data['group_name'], removed_trap, oid)\n\n app_copp_table = swsscommon.ProducerStateTable(self.app_db.db_connection, 'COPP_TABLE')\n app_copp_table.set(changed_group, [('trap_ids', ','.join(trap_ids))])\n self.wait_for_id_list_remove(meta_data['group_name'], removed_trap, oid)\n counters_keys = self.counters_db.db_connection.hgetall(meta_data['name_map'])\n assert removed_trap not in counters_keys\n\n trap_ids.append(removed_trap)\n app_copp_table.set(changed_group, [('trap_ids', ','.join(trap_ids))])\n\n oid = None\n for _ in range(NUMBER_OF_RETRIES):\n counters_keys = self.counters_db.db_connection.hgetall(meta_data['name_map'])\n if removed_trap in counters_keys:\n oid = counters_keys[removed_trap]\n break\n else:\n time.sleep(1)\n\n assert oid, 'Add trap {}, but trap counter is not created'.format(removed_trap)\n self.wait_for_id_list(meta_data['group_name'], removed_trap, oid)\n self.set_flex_counter_group_status(meta_data['key'], meta_data['group_name'], 'disable')\n\n def test_remove_trap_group(self, dvs):\n \"\"\"Remove trap group and verify that all related trap counters are removed\n\n Args:\n dvs (object): virtual switch object\n \"\"\"\n self.setup_dbs(dvs)\n meta_data = counter_group_meta['trap_flow_counter']\n self.set_flex_counter_group_status(meta_data['key'], meta_data['name_map'])\n\n removed_group = None\n trap_ids = None\n copp_groups = self.app_db.db_connection.keys('COPP_TABLE:*')\n for copp_group in copp_groups:\n trap_ids = self.app_db.db_connection.hget(copp_group, 'trap_ids')\n if trap_ids and trap_ids.strip():\n removed_group = copp_group.split(':')[1]\n break\n\n if not removed_group:\n pytest.skip('There is not copp group with at least 1 traps, skip rest of the test')\n\n trap_ids = [x.strip() for x in trap_ids.split(',')]\n for _ in range(NUMBER_OF_RETRIES):\n counters_keys = self.counters_db.db_connection.hgetall(meta_data['name_map'])\n found = True\n for trap_id in trap_ids:\n if trap_id not in counters_keys:\n found = False\n break\n if found:\n break\n else:\n time.sleep(1)\n\n assert found, 'Not all trap id found in name map'\n for trap_id in trap_ids:\n self.wait_for_id_list(meta_data['group_name'], trap_id, counters_keys[trap_id])\n\n app_copp_table = swsscommon.ProducerStateTable(self.app_db.db_connection, 'COPP_TABLE')\n app_copp_table._del(removed_group)\n\n for trap_id in trap_ids:\n self.wait_for_id_list_remove(meta_data['group_name'], trap_id, counters_keys[trap_id])\n\n counters_keys = self.counters_db.db_connection.hgetall(meta_data['name_map'])\n for trap_id in trap_ids:\n assert trap_id not in counters_keys\n\n self.set_flex_counter_group_status(meta_data['key'], meta_data['group_name'], 'disable')\n","sub_path":"tests/test_flex_counters.py","file_name":"test_flex_counters.py","file_ext":"py","file_size_in_byte":15496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"420562307","text":"from django.shortcuts import render\n# from index.models import Message, Progress\nfrom django.template import loader,Context\nfrom django.http import HttpResponse, JsonResponse\nimport json\nfrom utils.api import APIView\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nimport traceback\n# from aliyunsdkcore.client import AcsClient\n# from aliyunsdkvod.request.v20170321 import GetPlayInfoRequest, GetVideoPlayAuthRequest\nfrom multiprocessing import Process\nimport subprocess\nimport docker\nfrom django.conf import settings\nimport redis\nimport requests\n\n# Create your views here.\n\nclass CodeAPI(APIView):\n \n def post(self, request):\n if request.method == \"POST\":\n code_value = json.loads(request.body).get(\"code\")\n cin_value = json.loads(request.body).get(\"cin\")\n timestamp = str(json.loads(request.body).get(\"timestamp\"))\n language = json.loads(request.body).get(\"language\")\n print(cin_value)\n print(code_value)\n print(timestamp)\n print(language)\n\n language_postfix = {\"python\": \".py\", \"cpp\": \".cpp\"}\n print(language_postfix[\"python\"])\n # f = open(\"./compile/1.in\", \"w\")\n f = open(\"./compile/\"+timestamp+\".in\", \"w\")\n f.write(cin_value)\n f.close()\n # f = open(\"./compile/1.cpp\", \"w\")\n f = open(\"./compile/\"+timestamp+language_postfix[language], \"w\")\n f.write(code_value)\n f.close()\n\n # p = subprocess.Popen(args=\"timeout -s 9 2s ./compile/compileandrun.sh\"+\" \"+timestamp, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n compiler_url = \"http://127.0.0.1:5000/compile\"\n payload = {\"code\": code_value, \"cin\": cin_value, \"timestamp\": timestamp, \"language\": language}\n r = requests.post(compiler_url, data=payload)\n res = r.text\n print(type(res))\n print(res)\n return HttpResponse(json.dumps(res))\n\n # out_put_logs = []\n # while p.poll() is None:\n # out_put_log = str(p.stdout.readline(), encoding = \"utf-8\")\n # # print(out_put_log)\n # out_put_logs.append(out_put_log)\n \n # print(p.returncode)\n # if p.returncode != 0:\n # return HttpResponse(\"运行超时!\")\n\n # log = open(\"./compile/\"+timestamp+\".log\", \"w\")\n # log.writelines(out_put_logs)\n # log.close()\n \n # log = open(\"./compile/\"+timestamp+\".log\", \"r\")\n # # print(type(log.read()))\n # # print(log.read())\n # res = log.read()\n # # print(type(res))\n # print(res)\n # return HttpResponse(res)\n\n # return HttpResponse(\"POST success\")\n\n def get(self, request):\n log = open(\"./compile/log.txt\", \"r\")\n return HttpResponse(log.read())\n\nclass CodeMonitor(APIView):\n\n pool = None\n r = None\n\n def __init__(self):\n self.pool = redis.ConnectionPool(host='127.0.0.1', port=6379)\n self.r = redis.Redis(connection_pool=self.pool)\n\n def post(self, request):\n if request.method == \"POST\":\n # generate a username automatically and return\n usertype = json.loads(request.body).get(\"usertype\")\n if not (self.r.get(usertype)):\n self.r.set(usertype, 1)\n number = str(self.r.get(usertype), encoding = 'utf-8')\n uid = usertype + number\n self.r.set(usertype, int(number) + 1)\n return HttpResponse(uid)\n\n\n return HttpResponse(\"POST success\") ","sub_path":"index/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"217862758","text":"##############################################################################\n#\n# Copyright (c) 2010 Vifib SARL and Contributors. All Rights Reserved.\n#\n# WARNING: This program as such is intended to be used by professional\n# programmers who take the whole responsibility of assessing all potential\n# consequences resulting from its eventual inadequacies and bugs\n# End users who are looking for a ready-to-use solution with commercial\n# guarantees and support are strongly adviced to contract a Free Software\n# Service Company\n#\n# This program is Free Software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 3\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n##############################################################################\nfrom slapos.recipe.librecipe import BaseSlapRecipe\nimport os\nimport pkg_resources\nimport hashlib\nimport operator\nimport sys\nimport zc.buildout\nimport zc.recipe.egg\nimport ConfigParser\nimport re\nimport traceback\n\nTRUE_VALUES = ['y', 'yes', '1', 'true']\n\nclass Recipe(BaseSlapRecipe):\n\n def getTemplateFilename(self, template_name):\n return pkg_resources.resource_filename(__name__,\n 'template/%s' % template_name)\n\n def _install(self):\n # Define directory not defined in deprecated lib\n self.service_directory = os.path.join(self.etc_directory, 'service')\n\n # Check for mandatory arguments\n frontend_domain_name = self.parameter_dict.get(\"domain\")\n if frontend_domain_name is None:\n raise zc.buildout.UserError('No domain name specified. Please define '\n 'the \"domain\" instance parameter.')\n\n # Define optional arguments\n frontend_port_number = self.parameter_dict.get(\"port\", 4443)\n frontend_plain_http_port_number = self.parameter_dict.get(\n \"plain_http_port\", 8080)\n base_varnish_port = 26009\n slave_instance_list = self.parameter_dict.get(\"slave_instance_list\", [])\n\n self.path_list = []\n self.requirements, self.ws = self.egg.working_set()\n\n # self.cron_d is a directory, where cron jobs can be registered\n self.cron_d = self.installCrond()\n self.killpidfromfile = zc.buildout.easy_install.scripts(\n [('killpidfromfile', 'slapos.toolbox.killpidfromfile',\n 'killpidfromfile')], self.ws, sys.executable, self.bin_directory)[0]\n self.path_list.append(self.killpidfromfile)\n\n rewrite_rule_list = []\n rewrite_rule_https_only_list = []\n rewrite_rule_zope_list = []\n rewrite_rule_zope_path_list = []\n slave_dict = {}\n service_dict = {}\n\n # Sort slave instance by reference to avoid most security issues\n slave_instance_list = sorted(slave_instance_list,\n key=operator.itemgetter('slave_reference'))\n\n # dict of used domains, only used to track duplicates\n domain_dict = {}\n\n for slave_instance in slave_instance_list:\n # Sanitize inputs\n backend_url = slave_instance.get(\"url\", None)\n reference = slave_instance.get(\"slave_reference\")\n enable_cache = slave_instance.get('enable_cache', '').lower() in TRUE_VALUES\n slave_type = slave_instance.get('type', '').lower() or None\n\n https_only = slave_instance.get('https-only', '').lower() in TRUE_VALUES\n\n # Set scheme (http? https?)\n if https_only:\n scheme = 'https://'\n else:\n scheme = 'http://'\n\n self.logger.info('Processing slave instance: %s' % reference)\n\n # Check for mandatory slave fields\n if backend_url is None:\n self.logger.warn('No \"url\" parameter is defined for %s slave'\\\n 'instance. Ignoring it.' % reference)\n continue\n\n # Check for custom domain (like mypersonaldomain.com)\n # If no custom domain, use generated one.\n # Note: if we get an empty custom_domain parameter, we ignore it\n domain = slave_instance.get('custom_domain')\n if isinstance(domain, basestring):\n domain = domain.strip()\n if domain is None or domain.strip() == '':\n domain = \"%s.%s\" % (reference.replace(\"-\", \"\").lower(),\n frontend_domain_name)\n\n if domain_dict.get(domain):\n # This domain already has been processed, skip this new one\n continue\n else:\n domain_dict[domain] = True\n\n # Define the URL where the instance will be available\n # WARNING: we use default ports (443, 80) here.\n slave_dict[reference] = \"%s%s/\" % (scheme, domain)\n\n # Check if we want varnish+stunnel cache.\n #if enable_cache:\n # # XXX-Cedric : need to refactor to clean code? (to many variables)\n # rewrite_rule = self.configureVarnishSlave(\n # base_varnish_port, backend_url, reference, service_dict, domain)\n # base_varnish_port += 2\n #else:\n # rewrite_rule = \"%s %s\" % (domain, backend_url)\n # Temporary forbid activation of cache until it is properly tested\n rewrite_rule = \"%s %s\" % (domain, backend_url)\n\n # Finally, if successful, we add the rewrite rule to our list of rules\n # We have 4 RewriteMaps:\n # - One for generic (non-zope) websites, accepting both HTTP and HTTPS\n # - One for generic websites that only accept HTTPS\n # - Two for Zope-based websites\n if rewrite_rule:\n # We check if we have a zope slave. It requires different rewrite\n # rule structure.\n # So we will have one RewriteMap for normal websites, and one\n # RewriteMap for Zope Virtual Host Monster websites.\n if slave_type in ['zope']:\n rewrite_rule_zope_list.append(rewrite_rule)\n # For Zope, we have another dict containing the path e.g '/erp5/...\n rewrite_rule_path = \"%s %s\" % (domain, slave_instance.get('path', ''))\n rewrite_rule_zope_path_list.append(rewrite_rule_path)\n else:\n if https_only:\n rewrite_rule_https_only_list.append(rewrite_rule)\n else:\n rewrite_rule_list.append(rewrite_rule)\n\n # Certificate stuff\n valid_certificate_str = self.parameter_dict.get(\"domain_ssl_ca_cert\")\n valid_key_str = self.parameter_dict.get(\"domain_ssl_ca_key\")\n if valid_certificate_str is None and valid_key_str is None:\n ca_conf = self.installCertificateAuthority()\n key, certificate = self.requestCertificate(frontend_domain_name)\n else:\n ca_conf = self.installValidCertificateAuthority(\n frontend_domain_name, valid_certificate_str, valid_key_str)\n key = ca_conf.pop(\"key\")\n certificate = ca_conf.pop(\"certificate\")\n if service_dict != {}:\n if valid_certificate_str is not None and valid_key_str is not None:\n self.installCertificateAuthority()\n stunnel_key, stunnel_certificate = \\\n self.requestCertificate(frontend_domain_name)\n else:\n stunnel_key, stunnel_certificate = key, certificate\n self.installStunnel(service_dict,\n stunnel_certificate, stunnel_key,\n ca_conf[\"ca_crl\"],\n ca_conf[\"certificate_authority_path\"])\n\n apache_parameter_dict = self.installFrontendApache(\n ip_list=[\"[%s]\" % self.getGlobalIPv6Address(),\n self.getLocalIPv4Address()],\n port=frontend_port_number,\n plain_http_port=frontend_plain_http_port_number,\n name=frontend_domain_name,\n rewrite_rule_list=rewrite_rule_list,\n rewrite_rule_https_only_list=rewrite_rule_https_only_list,\n rewrite_rule_zope_list=rewrite_rule_zope_list,\n rewrite_rule_zope_path_list=rewrite_rule_zope_path_list,\n key=key, certificate=certificate)\n\n # Send connection informations about each slave\n for reference, url in slave_dict.iteritems():\n self.logger.debug(\"Sending connection parameters of slave \"\n \"instance: %s\" % reference)\n try:\n connection_dict = {\n # Send the public IPs (if possible) so that user knows what IP\n # to bind to its domain name\n 'frontend_ipv6_address': self.getGlobalIPv6Address(),\n 'frontend_ipv4_address': self.parameter_dict.get(\"public-ipv4\",\n self.getLocalIPv4Address()),\n 'site_url': url,\n }\n self.setConnectionDict(connection_dict, reference)\n except:\n self.logger.fatal(\"Error while sending slave %s informations: %s\",\n reference, traceback.format_exc())\n\n # Then set it for master instance\n self.setConnectionDict(\n dict(site_url=apache_parameter_dict[\"site_url\"],\n frontend_ipv6_address=self.getGlobalIPv6Address(),\n frontend_ipv4_address=self.getLocalIPv4Address()))\n\n # Promises\n promise_config = dict(\n hostname=self.getGlobalIPv6Address(),\n port=frontend_port_number,\n python_path=sys.executable,\n )\n promise_v6 = self.createPromiseWrapper(\n 'apache_ipv6',\n self.substituteTemplate(\n pkg_resources.resource_filename(\n 'slapos.recipe.check_port_listening',\n 'template/socket_connection_attempt.py.in'),\n promise_config))\n self.path_list.append(promise_v6)\n\n promise_config = dict(\n hostname=self.getLocalIPv4Address(),\n port=frontend_port_number,\n python_path=sys.executable,\n )\n promise_v4 = self.createPromiseWrapper(\n 'apache_ipv4',\n self.substituteTemplate(\n pkg_resources.resource_filename(\n 'slapos.recipe.check_port_listening',\n 'template/socket_connection_attempt.py.in'),\n promise_config))\n self.path_list.append(promise_v4)\n\n return self.path_list\n\n def configureVarnishSlave(self, base_varnish_port, url, reference,\n service_dict, domain):\n # Varnish should use stunnel to connect to the backend\n base_varnish_control_port = base_varnish_port\n base_varnish_port += 1\n # Use regex\n host_regex = \"((\\[\\w*|[0-9]+\\.)(\\:|)).*(\\]|\\.[0-9]+)\"\n slave_host = re.search(host_regex, url).group(0)\n port_regex = \"\\w+(\\/|)$\"\n matcher = re.search(port_regex, url)\n if matcher is not None:\n slave_port = matcher.group(0)\n slave_port = slave_port.replace(\"/\", \"\")\n elif url.startswith(\"https://\"):\n slave_port = 443\n else:\n slave_port = 80\n service_name = \"varnish_%s\" % reference\n varnish_ip = self.getLocalIPv4Address()\n stunnel_port = base_varnish_port + 1\n self.installVarnishCache(service_name,\n ip=varnish_ip,\n port=base_varnish_port,\n control_port=base_varnish_control_port,\n backend_host=varnish_ip,\n backend_port=stunnel_port,\n size=\"1G\")\n service_dict[service_name] = dict(public_ip=varnish_ip,\n public_port=stunnel_port,\n private_ip=slave_host.replace(\"[\", \"\").replace(\"]\", \"\"),\n private_port=slave_port)\n return \"%s http://%s:%s\" % \\\n (domain, varnish_ip, base_varnish_port)\n\n def requestCertificate(self, name):\n hash = hashlib.sha512(name).hexdigest()\n key = os.path.join(self.ca_private, hash + self.ca_key_ext)\n certificate = os.path.join(self.ca_certs, hash + self.ca_crt_ext)\n parser = ConfigParser.RawConfigParser()\n parser.add_section('certificate')\n parser.set('certificate', 'name', name)\n parser.set('certificate', 'key_file', key)\n parser.set('certificate', 'certificate_file', certificate)\n parser.write(open(os.path.join(self.ca_request_dir, hash), 'w'))\n return key, certificate\n\n def installCrond(self):\n timestamps = self.createDataDirectory('cronstamps')\n cron_output = os.path.join(self.log_directory, 'cron-output')\n self._createDirectory(cron_output)\n catcher = zc.buildout.easy_install.scripts([('catchcron',\n __name__ + '.catdatefile', 'catdatefile')], self.ws, sys.executable,\n self.bin_directory, arguments=[cron_output])[0]\n self.path_list.append(catcher)\n cron_d = os.path.join(self.etc_directory, 'cron.d')\n crontabs = os.path.join(self.etc_directory, 'crontabs')\n self._createDirectory(cron_d)\n self._createDirectory(crontabs)\n wrapper = zc.buildout.easy_install.scripts([('crond',\n 'slapos.recipe.librecipe.execute', 'execute')], self.ws, sys.executable,\n self.service_directory, arguments=[\n self.options['dcrond_binary'].strip(), '-s', cron_d, '-c', crontabs,\n '-t', timestamps, '-f', '-l', '5', '-M', catcher]\n )[0]\n self.path_list.append(wrapper)\n return cron_d\n\n def installValidCertificateAuthority(self, domain_name, certificate, key):\n ca_dir = os.path.join(self.data_root_directory, 'ca')\n ca_private = os.path.join(ca_dir, 'private')\n ca_certs = os.path.join(ca_dir, 'certs')\n ca_crl = os.path.join(ca_dir, 'crl')\n self._createDirectory(ca_dir)\n for path in (ca_private, ca_certs, ca_crl):\n self._createDirectory(path)\n key_path = os.path.join(ca_private, domain_name + \".key\")\n certificate_path = os.path.join(ca_certs, domain_name + \".crt\")\n self._writeFile(key_path, key)\n self._writeFile(certificate_path, certificate)\n return dict(certificate_authority_path=ca_dir,\n ca_crl=ca_crl,\n certificate=certificate_path,\n key=key_path)\n\n def installCertificateAuthority(self, ca_country_code='XX',\n ca_email='xx@example.com', ca_state='State', ca_city='City',\n ca_company='Company'):\n backup_path = self.createBackupDirectory('ca')\n self.ca_dir = os.path.join(self.data_root_directory, 'ca')\n self._createDirectory(self.ca_dir)\n self.ca_request_dir = os.path.join(self.ca_dir, 'requests')\n self._createDirectory(self.ca_request_dir)\n config = dict(ca_dir=self.ca_dir, request_dir=self.ca_request_dir)\n self.ca_private = os.path.join(self.ca_dir, 'private')\n self.ca_certs = os.path.join(self.ca_dir, 'certs')\n self.ca_crl = os.path.join(self.ca_dir, 'crl')\n self.ca_newcerts = os.path.join(self.ca_dir, 'newcerts')\n self.ca_key_ext = '.key'\n self.ca_crt_ext = '.crt'\n for d in [self.ca_private, self.ca_crl, self.ca_newcerts, self.ca_certs]:\n self._createDirectory(d)\n for f in ['crlnumber', 'serial']:\n if not os.path.exists(os.path.join(self.ca_dir, f)):\n open(os.path.join(self.ca_dir, f), 'w').write('01')\n if not os.path.exists(os.path.join(self.ca_dir, 'index.txt')):\n open(os.path.join(self.ca_dir, 'index.txt'), 'w').write('')\n openssl_configuration = os.path.join(self.ca_dir, 'openssl.cnf')\n config.update(\n working_directory=self.ca_dir,\n country_code=ca_country_code,\n state=ca_state,\n city=ca_city,\n company=ca_company,\n email_address=ca_email,\n )\n self._writeFile(openssl_configuration, pkg_resources.resource_string(\n __name__, 'template/openssl.cnf.ca.in') % config)\n\n # XXX-Cedric: Don't use this, but use slapos.recipe.certificate_authority\n # from the instance profile.\n self.path_list.extend(zc.buildout.easy_install.scripts([\n ('certificate_authority', __name__ + '.certificate_authority',\n 'runCertificateAuthority')],\n self.ws, sys.executable, self.service_directory, arguments=[dict(\n openssl_configuration=openssl_configuration,\n openssl_binary=self.options['openssl_binary'],\n certificate=os.path.join(self.ca_dir, 'cacert.pem'),\n key=os.path.join(self.ca_private, 'cakey.pem'),\n crl=os.path.join(self.ca_crl),\n request_dir=self.ca_request_dir\n )]))\n\n # configure backup\n backup_cron = os.path.join(self.cron_d, 'ca_rdiff_backup')\n open(backup_cron, 'w').write(\n '''0 0 * * * %(rdiff_backup)s %(source)s %(destination)s'''%dict(\n rdiff_backup=self.options['rdiff_backup_binary'],\n source=self.ca_dir,\n destination=backup_path))\n self.path_list.append(backup_cron)\n\n return dict(\n ca_certificate=os.path.join(config['ca_dir'], 'cacert.pem'),\n ca_crl=os.path.join(config['ca_dir'], 'crl'),\n certificate_authority_path=config['ca_dir']\n )\n\n def _getApacheConfigurationDict(self, name, ip_list, port):\n apache_conf = dict()\n apache_conf['server_name'] = name\n apache_conf['pid_file'] = self.options['pid-file']\n apache_conf['lock_file'] = os.path.join(self.run_directory,\n name + '.lock')\n apache_conf['document_root'] = os.path.join(self.data_root_directory,\n 'htdocs')\n apache_conf['instance_home'] = os.path.join(self.work_directory)\n apache_conf['httpd_home'] = self.options['httpd_home']\n apache_conf['ip_list'] = ip_list\n apache_conf['port'] = port\n apache_conf['server_admin'] = 'admin@'\n apache_conf['error_log'] = self.options['error-log']\n apache_conf['access_log'] = self.options['access-log']\n return apache_conf\n\n def installVarnishCache(self, name, ip, port, control_port, backend_host,\n backend_port, size=\"1G\"):\n \"\"\"\n Install a varnish daemon for a certain address\n \"\"\"\n directory = self.createDataDirectory(name)\n varnish_config = dict(\n directory=directory,\n pid = \"%s/varnish.pid\" % directory,\n port=\"%s:%s\" % (ip, port),\n varnishd_binary=self.options[\"varnishd_binary\"],\n control_port=\"%s:%s\" % (ip, control_port),\n storage=\"file,%s/storage.bin,%s\" % (directory, size))\n\n config_file = self.createConfigurationFile(\"%s.conf\" % name,\n self.substituteTemplate(self.getTemplateFilename('varnish.vcl.in'),\n dict(backend_host=backend_host, backend_port=backend_port)))\n\n varnish_argument_list = [varnish_config['varnishd_binary'].strip(),\n \"-F\", \"-n\", directory, \"-P\", varnish_config[\"pid\"], \"-p\",\n \"cc_command=exec %s \" % self.options[\"gcc_binary\"] +\\\n \"-fpic -shared -o %o %s\",\n \"-f\", config_file,\n \"-a\", varnish_config[\"port\"], \"-T\", varnish_config[\"control_port\"],\n \"-s\", varnish_config[\"storage\"]]\n environment = dict(PATH=\"%s:%s\" % (self.options[\"binutils_directory\"],\n os.environ.get('PATH')))\n wrapper = zc.buildout.easy_install.scripts([(name,\n 'slapos.recipe.librecipe.execute', 'executee')], self.ws,\n sys.executable, self.service_directory, arguments=[varnish_argument_list,\n environment])[0]\n self.path_list.append(wrapper)\n\n return varnish_config\n\n def installStunnel(self, service_dict, certificate,\n key, ca_crl, ca_path):\n \"\"\"Installs stunnel\n service_dict =\n { name: (public_ip, private_ip, public_port, private_port),}\n \"\"\"\n template_filename = self.getTemplateFilename('stunnel.conf.in')\n template_entry_filename = self.getTemplateFilename('stunnel.conf.entry.in')\n\n log = os.path.join(self.log_directory, 'stunnel.log')\n pid_file = os.path.join(self.run_directory, 'stunnel.pid')\n stunnel_conf = dict(\n pid_file=pid_file,\n log=log,\n cert = certificate,\n key = key,\n ca_crl = ca_crl,\n ca_path = ca_path,\n entry_str=''\n )\n entry_list = []\n for name, parameter_dict in service_dict.iteritems():\n parameter_dict[\"name\"] = name\n entry_str = self.substituteTemplate(template_entry_filename,\n parameter_dict)\n entry_list.append(entry_str)\n\n stunnel_conf[\"entry_str\"] = \"\\n\".join(entry_list)\n stunnel_conf_path = self.createConfigurationFile(\"stunnel.conf\",\n self.substituteTemplate(template_filename,\n stunnel_conf))\n wrapper = zc.buildout.easy_install.scripts([('stunnel',\n 'slapos.recipe.librecipe.execute', 'execute_wait')], self.ws,\n sys.executable, self.service_directory, arguments=[\n [self.options['stunnel_binary'].strip(), stunnel_conf_path],\n [certificate, key]]\n )[0]\n self.path_list.append(wrapper)\n return stunnel_conf\n\n def installFrontendApache(self, ip_list, key, certificate, name,\n port=4443, plain_http_port=8080,\n rewrite_rule_list=None,\n rewrite_rule_zope_list=None,\n rewrite_rule_https_only_list=None,\n rewrite_rule_zope_path_list=None,\n access_control_string=None):\n if rewrite_rule_list is None:\n rewrite_rule_list = []\n if rewrite_rule_https_only_list is None:\n rewrite_rule_zope_path_list = []\n if rewrite_rule_zope_list is None:\n rewrite_rule_zope_list = []\n if rewrite_rule_zope_path_list is None:\n rewrite_rule_zope_path_list = []\n\n # Create htdocs, populate it with default 404 document\n htdocs_location = os.path.join(self.data_root_directory, 'htdocs')\n self._createDirectory(htdocs_location)\n notfound_file_location = os.path.join(htdocs_location, 'notfound.html')\n notfound_template_file_location = self.getTemplateFilename(\n 'notfound.html')\n notfound_file_content = open(notfound_template_file_location, 'r').read()\n self._writeFile(notfound_file_location, notfound_file_content)\n\n # Create mod_ssl cache directory\n cache_directory_location = os.path.join(self.var_directory, 'cache')\n mod_ssl_cache_location = os.path.join(cache_directory_location,\n 'httpd_mod_ssl')\n self._createDirectory(cache_directory_location)\n self._createDirectory(mod_ssl_cache_location)\n\n # Create \"custom\" apache configuration files if it does not exist.\n # Note : Those files won't be erased or changed by slapgrid.\n # It can be freely customized by node admin.\n custom_apache_configuration_directory = os.path.join(\n self.data_root_directory, 'apache-conf.d')\n self._createDirectory(custom_apache_configuration_directory)\n # First one is included in the end of the apache configuration file\n custom_apache_configuration_file_location = os.path.join(\n custom_apache_configuration_directory, 'apache_frontend.custom.conf')\n if not os.path.exists(custom_apache_configuration_file_location):\n open(custom_apache_configuration_file_location, 'w')\n # Second one is included in the virtualhost of apache configuration file\n custom_apache_virtual_configuration_file_location = os.path.join(\n custom_apache_configuration_directory,\n 'apache_frontend.virtualhost.custom.conf')\n if not os.path.exists(custom_apache_virtual_configuration_file_location):\n open(custom_apache_virtual_configuration_file_location, 'w')\n\n # Create backup of custom apache configuration\n backup_path = self.createBackupDirectory('custom_apache_conf_backup')\n backup_cron = os.path.join(self.cron_d, 'custom_apache_conf_backup')\n open(backup_cron, 'w').write(\n '''0 0 * * * %(rdiff_backup)s %(source)s %(destination)s'''%dict(\n rdiff_backup=self.options['rdiff_backup_binary'],\n source=custom_apache_configuration_directory,\n destination=backup_path))\n self.path_list.append(backup_cron)\n\n # Create configuration file and rewritemaps\n apachemap_path = self.createConfigurationFile(\n \"apache_rewritemap_generic.txt\",\n \"\\n\".join(rewrite_rule_list)\n )\n apachemap_httpsonly_path = self.createConfigurationFile(\n \"apache_rewritemap_httpsonly.txt\",\n \"\\n\".join(rewrite_rule_https_only_list)\n )\n apachemap_zope_path = self.createConfigurationFile(\n \"apache_rewritemap_zope.txt\",\n \"\\n\".join(rewrite_rule_zope_list)\n )\n apachemap_zopepath_path = self.createConfigurationFile(\n \"apache_rewritemap_zopepath.txt\",\n \"\\n\".join(rewrite_rule_zope_path_list)\n )\n\n apache_conf = self._getApacheConfigurationDict(name, ip_list, port)\n apache_conf['ssl_snippet'] = self.substituteTemplate(\n self.getTemplateFilename('apache.ssl-snippet.conf.in'),\n dict(login_certificate=certificate,\n login_key=key,\n httpd_mod_ssl_cache_directory=mod_ssl_cache_location,\n )\n )\n\n apache_conf[\"listen\"] = \"\\n\".join([\n \"Listen %s:%s\" % (ip, port)\n for port in (plain_http_port, port)\n for ip in ip_list\n ])\n\n path = self.substituteTemplate(\n self.getTemplateFilename('apache.conf.path-protected.in'),\n dict(path='/',\n access_control_string='none',\n document_root=apache_conf['document_root'],\n )\n )\n\n apache_conf.update(**dict(\n path_enable=path,\n apachemap_path=apachemap_path,\n apachemap_httpsonly_path=apachemap_httpsonly_path,\n apachemapzope_path=apachemap_zope_path,\n apachemapzopepath_path=apachemap_zopepath_path,\n apache_domain=name,\n https_port=port,\n plain_http_port=plain_http_port,\n custom_apache_conf=custom_apache_configuration_file_location,\n custom_apache_virtualhost_conf=custom_apache_virtual_configuration_file_location,\n ))\n\n apache_conf_string = self.substituteTemplate(\n self.getTemplateFilename('apache.conf.in'), apache_conf)\n\n apache_config_file = self.createConfigurationFile('apache_frontend.conf',\n apache_conf_string)\n self.path_list.append(apache_config_file)\n\n self.path_list.extend(zc.buildout.easy_install.scripts([(\n 'frontend_apache', 'slapos.recipe.erp5.apache', 'runApache')], self.ws,\n sys.executable, self.service_directory, arguments=[\n dict(\n required_path_list=[key, certificate],\n binary=self.options['httpd_binary'],\n config=apache_config_file)\n ]))\n\n return dict(site_url=\"https://%s:%s/\" % (name, port))\n","sub_path":"slapos/recipe/apache_frontend/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":25843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"647005327","text":"def is_prime(a):\n if a % 2 == 0:\n return a == 2\n d = 3\n while d * d <= a and a % d != 0:\n d += 2\n return d * d > a\n\n\nprint(is_prime(int(input(\"Enter a number: \"))))\nprint('True' for i in range(1, 100) if is_prime(i))","sub_path":"task6/task6.py","file_name":"task6.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"437362457","text":"# https://s-nako.work/2020/10/bidirectional-dict-in-python/\n\n\nclass Bidict:\n def __init__(self, init_dict):\n self.dict_normal = {} # normal dict to store (key, values)\n self.dict_inverse = {} # normal dict to store (value. keys)\n for key in init_dict.keys():\n self.add_item(key, init_dict[key])\n\n def add_item(self, key, value):\n if key in self.dict_normal:\n self.dict_normal[key].append(value)\n else:\n self.dict_normal[key] = [value]\n if value in self.dict_inverse:\n self.dict_inverse[value].append(key)\n else:\n self.dict_inverse[value] = [key]\n\n def fetch(self, key, inverse=False):\n if inverse:\n return self.dict_inverse[key]\n return self.dict_normal[key]\n","sub_path":"prj/pytorch_2/src/util/bidict.py","file_name":"bidict.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"637104627","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom time import sleep\nimport random\nimport os\n\ndriver = webdriver.Chrome(executable_path=\"/Users/home/Desktop/chromedriver\")\n\nAPP_IP = os.environ['MASTER_PUBLIC_IP']\nurl = \"http://\"+APP_IP.strip()+\":8080/\"\n\ndriver.get(url)\nsleep(2)\n\nowners_link = driver.find_element_by_link_text(\"OWNERS\")\nowners_link.click()\nsleep(2)\n\nall_link = driver.find_element_by_link_text(\"REGISTER\")\nall_link.click()\nsleep(2)\n\n# Register new Owner to Petclinic App\nfn_field = driver.find_element_by_name('firstName')\nfn = 'Matt' + str(random.randint(0, 100))\nfn_field.send_keys(fn)\nsleep(1)\n\nfn_field = driver.find_element_by_name('lastName')\nfn_field.send_keys('Clarusway')\nsleep(1)\n\nfn_field = driver.find_element_by_name('address')\nfn_field.send_keys('Ridge Corp. Street')\nsleep(1)\n\nfn_field = driver.find_element_by_name('city')\nfn_field.send_keys('McLean')\nsleep(1)\n\nfn_field = driver.find_element_by_name('telephone')\nfn_field.send_keys('+1230576803')\nsleep(1)\n\nfn_field.send_keys(Keys.ENTER)\nsleep(1)\n\n# Wait 2 second to get updated Owner List\nsleep(6)\n\n# Verify that new user is added to Owner List\nif fn in driver.page_source:\n print(fn, 'is added and found in the Owners Table')\n print(\"Test Passed\")\nelse:\n print(fn, 'is not found in the Owners Table')\n print(\"Test Failed\")\ndriver.quit()","sub_path":"SecondTestPack/test_owners_register_headless copy.py","file_name":"test_owners_register_headless copy.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"399090379","text":"__author__ = 'patinbsb'\n'''This module is a testbed for working with the **Tkinter** library'''\n\n# Imports. All standard libraries\nimport Tkinter\nfrom Tkinter import *\nfrom threading import Timer\n\n# Setting up objects\ndatabase = [\"hello\", \"my\", \"name\", \"is\"] # fills the database with some elements to use\ntop = Tkinter.Tk()\nsv = StringVar() # user text entry callback\nsv.trace(\"w\", lambda name, index, mode, sv=sv: callback(sv)) # list box selection callback\n\n\ndef callback(sv):\n \"\"\"event callback logic for when letters typed into **text_input** and when **list_box** is selected by user\"\"\"\n\n list_box.delete(0, END) # clears the listbox for new input\n user_entry = sv.get()\n for entry in database:\n if user_entry in entry:\n list_box.insert(END, entry) # inputs all relevant entries into listbox\n\n\ndef immediately(e):\n user_selection = (list_box.get(list_box.curselection()))\n text_input.delete(0, END)\n text_input.insert(0, user_selection)\n\n\n'''Button logic, adds user input to the database on condition it's not already in'''\n\n\ndef update2():\n update(None) # Updates with the argument **None** because Tkinter requires inputs on functions\n\n\ndef update(e):\n user_input = text_input.get() # gets text input\n if user_input.isdigit():\n text_input.delete(0, END)\n return\n global database\n if user_input not in database: # logic dealing with duplicates\n database.append(user_input)\n else:\n text_input.delete(0, END)\n text_input.insert(0, user_input + \" already in database\")\n text_input.config(state=DISABLED)\n\n def cont():\n text_input.config(state=NORMAL)\n text_input.delete(0, END)\n\n Timer(1.5, cont).start() # waits for 1.5 seconds then continues\n return\n text_input.delete(0, END)\n return\n\n\ndef get(): # For a more developed database this would print to a GUI element\n for x in database:\n print(x)\n\n'''Defining and building the gui, requires some functions to be defined first.'''\n\ntext_input = Entry(top, textvariable=sv)\nlist_box = Listbox(top, selectmode=SINGLE)\nbutton_enter = Button(top, text=\"Enter\", command=update2)\nbutton_get = Button(top, text=\"Get\", command=get)\n\n# Packs the gui elements, order is important\ntext_input.pack()\nlist_box.pack()\nbutton_enter.pack()\nbutton_get.pack()\n\n''' Setting up keybindings '''\nlist_box.bind(\"<>\", immediately)\ntext_input.bind(\"\", update)\n\nif __name__ == \"__main__\":\n top.mainloop()","sub_path":"irc/gui_wrapper.py","file_name":"gui_wrapper.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"160218319","text":"import pymysql\nfrom xml.dom import minidom\nfrom urllib.request import urlopen\nfrom urllib.parse import urlencode, quote_plus, quote\nfrom collections import OrderedDict\nimport json\n\n'''\ninitialcall request 에 따른 response json파일을 만들어 반환한다.\nbusName, busId, busRoute, rideWeekdayRatio, rideWeekendRatio정보를 시간별로 반환한다.\n\nrideWeekdayRatio, rideWeekendRatio를 어떻게 구할 것인가(이용객이므로 승차만 고려)\n버스에 대해서 db에서 평일/휴일 이용객 전체 수를 구한다.\n버스에 대해서 db에서 시간대별 이용객 전체 수(1년간)를 구한다.\n버스에 대해서 dayrecord.use에서 1년간 평일/휴일 개수를 구한다.\n\n시간대별 평일 이용객 수\n평일 전체 이용객 수 * (그 시간대 이용객 수/전체 이용객수) / 평일의 수 \n\n시간대별 휴일 이용객 수\n휴일 전체 이용객 수 * (그 시간대 이용객 수/전체 이용객수) / 휴일의 수 \n\n\n'''\n\ndef makeJson(routeNum):\n resultJson = OrderedDict()\n conn = pymysql.connect(host='localhost', user='gosituser', password='', db='gosit', charset='utf8')\n \n numcheckSql = \"\"\"select * from seoulBusData where routeName = %s \"\"\"\n with conn.cursor() as curs:\n curs.execute(\"set names utf8\")\n curs.execute(numcheckSql, (routeNum))\n if len(curs.fetchall()) == 0:\n resultJson[\"status\"] = False\n return json.dumps(resultJson, ensure_ascii=False) \n else:\n resultJson[\"status\"] = True\n resultJson[\"busName\"] = routeNum\n curs.execute(numcheckSql, (routeNum))\n for row in curs.fetchall():\n resultJson[\"busId\"] = row[0]\n\n resultJson[\"busRoute\"] = []\n urlbase='http://210.96.13.82:8099/api/rest/busRouteInfo/getStaionByRoute.jsonp?busRouteId='\n \n url = urlbase + resultJson[\"busId\"]\n urldata = urlopen(url)\n jsontext = urldata.read().decode('utf8')[5:-1]\n jsondata = json.loads(jsontext)\n if(jsondata['outStationByRoute']['msgHeader']['headerMsg'] == \"결과가 없습니다.\"):\n print(routeNum)\n print('no result')\n f = open('./data/noRouteId.use', mode = 'a')\n f.write(routeNum +' no result\\n')\n f.close()\n resultJson[\"status\"] = False\n return json.dumps(resultJson, ensure_ascii=False)\n \n for item in jsondata['outStationByRoute']['msgBody']['itemList']:\n routedata = OrderedDict()\n routedata['index'] = item['seq']\n routedata['stationId'] = item['station']\n routedata['stationName'] = item['stationNm']\n routedata['arsId'] = item['arsId']\n resultJson['busRoute'] +=[routedata]\n\n\n resultJson[\"rideWeekdayRatio\"] = []\n resultJson[\"rideWeekendRatio\"] = []\n\n # weekday/ weekend total users\n weektotsql = \"\"\"select sum(weekDayRideRatio),sum(weekendRideRatio) \n from ratiobusstationuser\n where routeId = %s\"\"\"\n weekdaytotCnt = 0\n weekendtotCnt = 0\n with conn.cursor() as curs:\n curs.execute(weektotsql, resultJson['busId'])\n for row in curs.fetchall():\n weekdaytotCnt = int(row[0])\n weekendtotCnt = int(row[1])\n\n # the users for each time\n timeList = [str(i) for i in range(0,24)]\n timeusersql = \"select \"\n for t in timeList:\n timeusersql += \"sum(ride\"+t+\")\"\n if t!=\"23\":\n timeusersql+=\", \"\n timeusersql += \" from monthtimebususer where routeId = %s\"\n timeuserCnt = []\n with conn.cursor() as curs:\n curs.execute(timeusersql, resultJson['busId'])\n for row in curs.fetchall():\n for i in range(24):\n timeuserCnt+=[int(row[i])]\n\n # the total users\n totuserCnt = sum(timeuserCnt)\n\n # the num of weekday/weekend\n weekdayCntsql = \"select count(*) from dayType where kind='weekday'\"\n weekendCntsql = \"select count(*) from dayType where kind='weekend'\"\n weekdayCnt = 0\n weekendCnt = 0\n with conn.cursor() as curs:\n curs.execute(weekdayCntsql)\n for wc in curs.fetchall():\n weekdayCnt =int(wc[0])\n curs.execute(weekendCntsql)\n for wc in curs.fetchall():\n weekendCnt = int(wc[0])\n\n for i in range(24):\n if totuserCnt != 0 and weekdayCnt !=0:\n resultJson['rideWeekdayRatio'] +=[int(weekdaytotCnt*(timeuserCnt[i]/totuserCnt)/weekdayCnt)]\n else : \n resultJson['rideWeekdayRatio']+=[0]\n if totuserCnt!= 0 and weekendCnt!=0:\n resultJson['rideWeekendRatio'] +=[int(weekendtotCnt*(timeuserCnt[i]/totuserCnt)/weekendCnt)]\n else:\n resultJson['rideWeekendRatio'] +=[0]\n\n\n return json.dumps(resultJson, ensure_ascii=False)\n\ndef initialCall(routeNum):\n json_data = makeJson(routeNum)\n return json_data\n","sub_path":"server/src/initialBusCall.py","file_name":"initialBusCall.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"164696271","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /mnt/c/Users/TimHe/OneDrive/Programming/LookingGlass/lib/arp.py\n# Compiled at: 2019-02-26 09:19:09\n# Size of source mod 2**32: 2629 bytes\nimport os\nARP_FIELD_NAMES = ['Address', 'HWtype', 'HWaddress', 'Flags', 'Mask', 'Iface']\n\nclass ArpData:\n\n def __init__(self, address, hw_type, hw_address, flags, mask, interface):\n self.address = address\n self.hw_type = hw_type\n self.hw_address = hw_address\n self.flags = flags\n self.mask = mask\n self.interface = interface\n\n def __str__(self):\n d = self.as_dict()\n lines = []\n for k in d:\n lines.append('%s: %s' % (k, str(d[k])))\n\n return '\\n'.join(lines)\n\n def as_dict(self):\n d = {}\n d['ip'] = self.address\n d['hardware type'] = self.hw_type\n d['MAC address'] = self.hw_address\n d['ARP Flags'] = self.flags\n d['ARP Mask'] = self.mask\n d['network interface'] = self.interface\n return d\n\n @staticmethod\n def from_dict(record_data):\n return ArpData(address=(record_data['Address']),\n hw_type=(record_data['HWtype']),\n hw_address=(record_data['HWaddress']),\n flags=(record_data['Flags']),\n mask=(record_data['Mask']),\n interface=(record_data['Iface']))\n\n\ndef parse_arp_data(arp_data_string):\n arp_records = []\n is_header = True\n column_indexes = {}\n for line in arp_data_string.split('\\n'):\n if len(line.strip()) == 0:\n next\n elif is_header:\n previous_field = None\n for field in ARP_FIELD_NAMES:\n index = line.index(field)\n column_indexes[field] = {'start':index, 'end':len(line)}\n if previous_field is not None:\n column_indexes[previous_field]['end'] = index\n previous_field = field\n\n is_header = False\n else:\n record_data = {}\n for field in ARP_FIELD_NAMES:\n record_data[field] = line[column_indexes[field]['start']:column_indexes[field]['end']].strip()\n\n arp_records.append(ArpData.from_dict(record_data))\n\n return arp_records\n\n\ndef parse_arp_file(arp_file):\n if not os.path.exists(arp_file):\n raise Exception('File %s does not exist' % arp_file)\n with open(arp_file, 'r') as (f):\n return parse_arp_data(f.read())","sub_path":"pycfiles/looking_glass-1.0.4-py3-none-any/arp.cpython-36.py","file_name":"arp.cpython-36.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"105553951","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : \n# @Author : \n# @Site : \n# @File : auto_training.py\n# @IDE: PyCharm\n\"\"\"\nTrain lanenet script\n\"\"\"\nimport yaml\nimport numpy as np\nfrom trainner import tusimple_lanenet_single_gpu_trainner as single_gpu_trainner\nfrom trainner import tusimple_lanenet_multi_gpu_trainner as multi_gpu_trainner\nfrom local_utils.log_util import init_logger\nfrom local_utils.config_utils import parse_config_utils\n\nLOG = init_logger.get_logger(log_file_name_prefix='lanenet_train')\nCFG = parse_config_utils.lanenet_cfg\n\ndef update_paras(para_name, lr):\n file_data = ''\n with open('/workspace/lanenet-bisenetv2/config/tusimple_lanenet.yaml', 'r', encoding='utf-8') as f:\n for line in f:\n if para_name in line:\n line = para_name + str(lr) + '\\n'\n file_data += line\n with open('/workspace/lanenet-bisenetv2/config/tusimple_lanenet.yaml', 'w', encoding='utf-8') as f:\n f.write(file_data)\n\ndef train_model():\n \"\"\"\n\n :return:\n \"\"\"\n if CFG.TRAIN.MULTI_GPU.ENABLE:\n LOG.info('Using multi gpu trainner ...')\n worker = multi_gpu_trainner.LaneNetTusimpleMultiTrainer()\n else:\n LOG.info('Using single gpu trainner ...')\n worker = single_gpu_trainner.LaneNetTusimpleTrainer()\n\n worker.train()\n return\n\n\nif __name__ == '__main__':\n \"\"\"\n main function\n \"\"\"\n lr = np.array([0.001, 0.01, 0.1])\n for i, v in enumerate(lr):\n LOG.info('lr= {:3f}'.format(v))\n update_paras(' LR: ',v)\n train_model()\n\n","sub_path":"tools/auto_training.py","file_name":"auto_training.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"23051873","text":"# -*- coding: utf-8 -*- {{{\n# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:\n#\n# Copyright (2021) Battelle Memorial Institute\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# }}}\n\n''''\nInference engine running bayseian probability analysis to detect device and it's vulnerabilities\n'''\n\nimport sys\n\nstring_type = None\nif sys.version_info[0] >= 3:\n unicode = str\n string_type = str\nelse:\n string_type = basestring\n\nimport logging\nlogger = logging.getLogger(__name__)\nDEBUG = True\ndef printD(m):\n if DEBUG:\n logger.debug(m)\n\nimport os\nimport json\nfrom os import listdir\nfrom os.path import isfile, join\nfrom math import *\nfrom io import open\nimport gevent\nfrom gevent import socket as gsock\n\nfrom gevent import sleep\nfrom gevent.lock import BoundedSemaphore\n\nfrom time import sleep\nimport time\nimport datetime\n\nimport multiprocessing\nfrom multiprocessing import Manager\nfrom ipaddress import ip_address, ip_network\nimport threading\n\nfrom ..common.actor import Actor\ntry:\n import yaml\nexcept ImportError:\n raise RuntimeError('PyYAML must be installed before running this script ')\n\nimport sqlite3\nimport json\nfrom .Databases import dbManagerNew\nfrom . import statusTracker\n\nfrom . import decisionSimple\nfrom . import helper\nfrom . import identifyIP\nfrom . import identifyVulnerabilities\n\nfrom .identifyIP import IpIdentifier\n\n# Database files\nNEW_E_DB_FILE = \"new_e_db.sqlite\" # new evidence\nNEW_EVENTS_DB_FILE = \"new_events_db.sqlite\" # new events\nNEW_D_DB_FILE = \"new_d_db.sqlite\" # devices\nNEW_V_DB_FILE = \"new_v_db.sqlite\" # vendors\nNEW_R_DB_FILE = \"new_r_db.sqlite\" # requests\n\n# Ignore IP List\nIGNORE_IPS = []\n\n# Paths\nscans_path = \"ssasse_platform/InferenceEngine/Scans/\"\nvendor_profiles_path = \"ssasse_platform/InferenceEngine/Profiles/Vendors\"\ndevice_profiles_path = \"ssasse_platform/InferenceEngine/Profiles/Devices\"\n\nclass DeviceIdentificationEngine(Actor):\n def __init__(self, config, rmq_connection):\n printD(\"InferenceEngine.__init__()\")\n super(DeviceIdentificationEngine, self).__init__(config, rmq_connection)\n\n self.config = config\n\n thread = threading.Thread(target=self.geventLoop, args=())\n thread.daemon = True\n\n self.newPortEvidenceQueue = gevent.queue.Queue()\n self.vulnerabilityStatus = {}\n self.identifiedVulnerabilities = {}\n\n self.identifyIPQueue = multiprocessing.Queue()\n self.identifyVulnQueue = multiprocessing.Queue()\n\n self.DBManagerNew = dbManagerNew.DBManager()\n self.StatusTracker = statusTracker.StatusTracker()\n\n self.IpIdentifier = identifyIP.IpIdentifier(self.config, self.DBManagerNew, None)\n self.ServiceProcessor = identifyVulnerabilities.ServiceProcessor(self.config, self.DBManagerNew, None)\n #self.processEvidenceGreenlet = gevent.spawn(self.geventLoop)\n thread.start()\n gevent.spawn(self.setup_subscriptions)\n\n self.internal_range = self.config.internal_ip_range\n if self.internal_range is None:\n printD(\"inference -- ERROR: internal range not set. Defaulting to 192.168.0.0/24\")\n self.internal_range = \"192.168.0.0/24\"\n\n self.ping_sweep_processed = set()\n\n self.ipRangeScanStatus = dict()\n self.publishActor = None\n self.rmq_socket = self._connection._connection.socket\n\n def setup_subscriptions(self):\n #printD(\"InferenceEngine.setup_subscriptions()\")\n while not self.connection_ready:\n gevent.sleep(0.01)\n # Subscribe to receive evidence messages from Evidence Manager\n subscriptions = [dict(prefix='new_packet', queue_name='new_packet_queue', callback=self.new_packet_callback),\n dict(prefix='packet', queue_name='evidence_queue', callback=self.evidence_callback),\n dict(prefix='internal', queue_name='internal_queue', callback=self.internal_callback),\n dict(prefix=\"active.results\", queue_name=\"active_results_queue\", callback=self.active_callback)]\n self.add_subscriptions(subscriptions)\n\n def new_packet_callback(self, topic, message):\n #printD(\"InferenceEngine.new_packet_callback() - Received: {0}, {1}\".format(topic, message))\n pass\n\n def evidence_callback(self, topic, message):\n #printD(\"InferenceEngine.evidence_callback() - ip: {0}, evidence callback: {1}, {2}, CTR:{3}\".format(message.get(\"TARGET_IPADDR\", None), topic, message, message[\"CTR\"]))\n self.receiveEvidence(message, \"Passive\")\n #self.receiveQueue.put((message, \"Passive\"))\n\n def internal_callback(self, topic, message):\n printD(\"InferenceEngine.internal_callback() - ip: {0}, internal callback: {1}, {2}\".format(message.get(\"TARGET_IPADDR\", None), topic, message))\n self.receiveEvidence(message, \"Internal\")\n #self.receiveQueue.put((message, \"Internal\"))\n\n def active_callback(self, topic, message):\n printD(\"InferenceEngine.active_callback() - ip: {0}, active callback: {1}, {2}\".format(message.get(\"TARGET_IPADDR\", None), topic, message))\n\n mysteryDevice = message[\"TARGET_IPADDR\"]\n siteName = self.getSiteName(mysteryDevice)\n\n fromWho = \"Active\"\n if siteName != \"NA\":\n fromWho = fromWho + \" ({0})\".format(siteName)\n\n if message['SCAN_NAME'] == 'nmap_arp_ping_scan':\n printD(\"PING Got result for nmap_arp_ping_scan\")\n ipRange = message['TARGET_IPADDR']\n self.ipRangeScanStatus[ipRange][\"PROCESSING\"] = False\n self.ipRangeScanStatus[ipRange][\"ACTIVE_SCAN_TIME\"] = 0\n \n storedDevices = dbManagerNew.allIPs(NEW_E_DB_FILE)\n # Add IP as separate evidence\n scanResult = message['DISCOVERED_TARGETS']\n for ip, stats in scanResult.items():\n printD(\"PING: IP:{}, stats: {}\".format(ip, stats))\n if ip not in storedDevices:\n msg = stats\n msg['TARGET_IPADDR'] = ip\n printD(\"PING Adding IP to receiveEvidence: IP: {}, msg: {}\".format(ip, msg))\n self.receiveEvidence(msg, fromWho)\n else:\n self.DBManagerNew.insert(NEW_EVENTS_DB_FILE, mysteryDevice, {\"ACTIVE_SCAN_TIME\": [\"0\"]}, datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\"), \"Tracking - Active Scan Time\")\n self.receiveEvidence(message, fromWho)\n #self.receiveQueue.put((message, fromWho))\n\n #####\n #\n #####\n def getSiteName(self, mysteryDevice):\n fr = open(\"{0}zonemap.json\".format(scans_path), \"r\", encoding=\"utf-8\")\n zonemap = json.loads(fr.read())\n fr.close()\n siteName = \"NA\"\n\n for key,val in zonemap.items():\n # Exact IP match\n if mysteryDevice in val:\n return key\n\n for key,val in zonemap.items():\n # Check if IP in range\n for ip in val:\n try:\n ipObj = ip_address(mysteryDevice)\n netObj = ip_network(ip)\n if ipObj in netObj:\n return key\n except Exception as e:\n #printD(\"checking zonemap for ip warning: {0}\".format(e))\n pass\n return \"NA\"\n\n ##########################################################\n # vendorMap\n ##########################################################\n def vendorMap(self, vendor):\n #printD(\"InferenceEngine.vendorMap()\")\n v_names = dbManagerNew.allIPs(NEW_V_DB_FILE)\n for realVen in v_names:\n if helper.singleInList(vendor, dbManagerNew.select_all(NEW_V_DB_FILE, realVen)[\"VENDOR\"]):\n vendor = realVen\n break\n return vendor\n\n ##########################################################\n # modelMap\n ##########################################################\n def modelMap(self, model):\n #printD(\"InferenceEngine.modelMap()\")\n d_names = dbManagerNew.allIPs(NEW_D_DB_FILE)\n for realDev in d_names:\n if helper.singleInList(model, dbManagerNew.select_all(NEW_D_DB_FILE, realDev)[\"MODEL\"]):\n model = realDev\n break\n return model\n\n #####\n #\n #####\n def spawnIdentifyProcess(self, mysteryDevice):\n resultsDict = {}\n resultsDict[\"device\"] = mysteryDevice\n printD(\"spawnIdentifyProcess\")\n resultsDict = self.IpIdentifier.identifyIP(mysteryDevice, resultsDict, self.rmq_socket)\n if resultsDict is not None:\n self.identifyIPQueue.put(resultsDict)\n\n #####\n #\n #####\n def identifyProcess(self, mysteryDevice):\n self.DBManagerNew.insert(NEW_EVENTS_DB_FILE, mysteryDevice, {\"PROCESSING\": \"y\"}, datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\"), \"Identification\")\n p = multiprocessing.Process(target=self.spawnIdentifyProcess, args=[mysteryDevice])\n p.start()\n\n #####\n #\n #####\n def getFromIPQueue(self):\n if not self.identifyIPQueue.empty():\n resultsDict = self.identifyIPQueue.get()\n mysteryDevice = resultsDict[\"device\"]\n for internal in resultsDict[\"internal\"]:\n self.receiveEvidence(internal, \"Internal\")\n for external in resultsDict[\"external\"]:\n printD(\"publishing ip: {0}, external: {1}\".format(mysteryDevice, external))\n #self.publishActor.publish_request(external[\"ACTIVE_REQUEST_STRING\"], external[\"SCAN\"])\n self.publish_messages.append((external[\"ACTIVE_REQUEST_STRING\"], external[\"SCAN\"]))\n\n self.DBManagerNew.insert(NEW_EVENTS_DB_FILE, mysteryDevice, {\"PROCESSING\": \"n\"}, datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\"), \"Identification\")\n\n ##########################################################\n # startNmapScan: \n ##########################################################\n def startNmapScan(self, device, ports):\n prevStatus = {}\n prevStatus[\"device\"] = device\n prevStatus[\"port\"] = ports\n prevStatus[\"nmap\"] = 'yes'\n\n p = multiprocessing.Process(target=self.spawnProcessServiceForNmap, args=(device,ports, prevStatus))\n p.start()\n \n def spawnProcessServiceForNmap(self, device, ports, prevStatus):\n printD(\"SN: spawnProcessServiceForNmap: {}, {}, {}\".format(device, ports, prevStatus))\n currentStatus = self.ServiceProcessor.processNmap(device, ports, prevStatus, self.rmq_socket)\n # Put currentStatus in the multiprocess queue\n self.identifyVulnQueue.put(currentStatus)\n\n ##########################################################\n # identifyVulnerability: \n ##########################################################\n def identifyVulnerability(self, device, port, service):\n self.DBManagerNew.insert(NEW_EVENTS_DB_FILE, device, {\"PROCESSING\": \"y\"}, datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\"), \"Vulnerability\")\n printD(\"SN: identifying new vuln: {}, {}, {}\".format(device, port, service))\n\n prevStatus = {}\n identified = 'n'\n for ip_port in self.StatusTracker.IP_PORT:\n ip, pt = ip_port.split('_')\n if ip == device and port == pt:\n identified = 'y'\n break\n prevStatus['device'] = device\n prevStatus['port'] = port\n prevStatus['identified'] = identified\n prevStatus['nmap'] = 'done'\n printD(\"SN: about to start vuln multiprocess\")\n p = multiprocessing.Process(target=self.spawnProcessService, args=(device,port,service,prevStatus))\n p.start()\n printD(\"SN: just started vuln multiprocess\")\n\n def spawnProcessService(self, device, port, service, prevStatus):\n currentStatus = None\n currentStatus = self.ServiceProcessor.processService(device, port, service, prevStatus, self.rmq_socket)\n # Put currentStatus in the multiprocess queue\n if currentStatus is not None:\n self.identifyVulnQueue.put(currentStatus)\n\n ##########################################################\n # getFromVulnQueue: Get results from process queue and store it locally\n ##########################################################\n def getFromVulnQueue(self):\n if not self.identifyVulnQueue.empty():\n resultsDict = self.identifyVulnQueue.get()\n printD(\"SN: getFromVulnQueue() - resultsDict: {}\".format(resultsDict))\n mysteryDevice = resultsDict[\"device\"]\n for internal in resultsDict[\"internal\"]:\n self.receiveEvidence(internal, \"Internal\")\n for external in resultsDict[\"external\"]:\n printD(\"SN: publishing ip: {0}, external: {1}\".format(mysteryDevice, external))\n #self.publishActor.publish_request(external[\"ACTIVE_REQUEST_STRING\"], external[\"SCAN\"])\n self.publish_messages.append((external[\"ACTIVE_REQUEST_STRING\"], external[\"SCAN\"]))\n\n port = resultsDict[\"port\"]\n identified = 'n'\n identifiedKey = helper.singleInList(\"identified\", resultsDict.keys())\n if identifiedKey:\n identified = resultsDict[identifiedKey]\n\n if identified.lower() != 'n':\n ip_port = \"{}_{}\".format(mysteryDevice, port)\n if ip_port not in self.StatusTracker.IP_PORT: self.StatusTracker.IP_PORT.append(ip_port)\n\n self.DBManagerNew.insert(NEW_EVENTS_DB_FILE, mysteryDevice, {\"PROCESSING\": \"n\"}, datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\"), \"Vulnerability\")\n vulnProtocols = self.getVulnerabilityPorts(mysteryDevice)\n printD(\"SN: getFromVulnQueue() - IdentifiedVulnerabilities device: {}, ports: {}\".format(mysteryDevice, vulnProtocols))\n #printD(\"Identified Vulnerabilities: {}\".format(self.identifiedVulnerabilities))\n\n ##########################################################\n # geventLoop()\n ##########################################################\n def geventLoop(self):\n printD(\"InferenceEngine.geventLoop()\")\n while not self.connection_ready:\n time.sleep(0.01)\n self.publish_message(\"inference.start\", {})\n\n peekScanTime = time.time()\n\n while True:\n time.sleep(0.01)\n\n # print out debug info\n #printD(\"inference.geventLoop() - StatusTracker non-empties:\")\n #if len(self.StatusTracker.IDENTIFIED) > 0: printD(\"inference.geventLoop() - StatusTracker.identified: {0}\".format(self.StatusTracker.IDENTIFIED))\n #if len(self.StatusTracker.ID_QUEUE) > 0: printD(\"inference.geventLoop() - StatusTracker.id_queue: {0}\".format(self.StatusTracker.ID_QUEUE))\n if len(self.StatusTracker.COMPLETED) > 0: printD(\"inference.geventLoop() - StatusTracker.completed: {0}\".format(self.StatusTracker.COMPLETED))\n if len(self.StatusTracker.VULN_QUEUE) > 0: printD(\"inference.geventLoop() - StatusTracker.vuln_queue: {0}\".format(self.StatusTracker.VULN_QUEUE))\n if len(self.StatusTracker.IP_PORT) > 0: printD(\"inference.geventLoop() - StatusTracker.ip_port: {0}\".format(self.StatusTracker.IP_PORT))\n if len(self.StatusTracker.IP_PORT_SERVICE) > 0: printD(\"inference.geventLoop() - StatusTracker.ip_port_service: {0}\".format(self.StatusTracker.IP_PORT_SERVICE))\n\n ########## DEVICE IDENTIFICATION ##########\n self.processIdentification()\n\n ########## SERVICE PROCESSING / VULNERABILITY ##########\n self.processVulnerabilities()\n \n ########## GET FROM MULTIPROCESSING IP QUEUE ##########\n self.getFromIPQueue()\n\n ########## GET FROM MULTIPROCESSING VULNERABILITY QUEUE ##########\n self.getFromVulnQueue()\n \n userInput = self.checkForPingSweepUserInput()\n if userInput:\n printD(\"PING: Sending ping sweep: {}\".format(userInput))\n self.ping_sweep_handler(userInput)\n\n currentTime = time.time()\n if currentTime - peekScanTime >= 30:\n printD(\"PING: Checking for ExternalIPs\")\n devices = self.checkForExternalIPs()\n printD(\"PING: Device list from checkForExternalIPs: {}\".format(devices))\n peekScanTime = currentTime\n # Should be from frontend, but for testing purposes\n # ipRangeList = ['172.17.0.0/28']\n # self.ping_sweep_handler(ipRangeList)\n\n if len(devices) > 0:\n requestTimeStamp = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n requestDict = {}\n requestDict[\"MESSAGE\"] = [\"PING: Device list from checkForExternalIPs: {}\".format(devices)]\n self.DBManagerNew.insert(NEW_R_DB_FILE, requestTimeStamp, requestDict, requestTimeStamp, \"Requests\")\n\n ##########################################################\n # processIdentification()\n ##########################################################\n def processIdentification(self):\n printD(\"inference.geventLoop() - ID_QUEUE: {0}\".format(self.StatusTracker.ID_QUEUE))\n if not self.newPortEvidenceQueue.empty():\n printD(\"inference.geventLoop() - VULN_QUEUE: {0}\".format(self.newPortEvidenceQueue.peek()))\n\n ########## IDENTIFICATION ###########\n # Go through evidenceIP queue, find IP that has new evidence waiting\n # remove from list\n mysteryDevice = False\n for mD in self.StatusTracker.ID_QUEUE:\n mysteryEvidence = dbManagerNew.select_all(NEW_E_DB_FILE, mD)\n allEvents = dbManagerNew.select_all(NEW_EVENTS_DB_FILE, mD)\n processingKey = helper.singleInList(\"PROCESSING\", allEvents.keys())\n if self.ipInPolicy(mD) and (not processingKey or \"n\" in allEvents[processingKey]):\n mysteryDevice = mD\n break\n\n # If no new evidence, go through IPs currently in an active scan\n # (so we can see if timeout has passed)\n if mysteryDevice == False:\n devices = dbManagerNew.allIPs(NEW_E_DB_FILE)\n for mD in devices:\n mysteryEvidence = dbManagerNew.select_all(NEW_E_DB_FILE, mD)\n allEvents = dbManagerNew.select_all(NEW_EVENTS_DB_FILE, mD)\n activeScanTimeKey = helper.singleInList(\"ACTIVE_SCAN_TIME\", allEvents.keys())\n if self.ipInPolicy(mD) and activeScanTimeKey and \"0\" not in allEvents[activeScanTimeKey] and mysteryDevice not in self.StatusTracker.IDENTIFIED:\n mysteryDevice = mD\n break\n\n # run identification process on the chosen IP (mysteryDevice)\n if mysteryDevice != False:\n if mysteryDevice in self.StatusTracker.ID_QUEUE:\n try: self.StatusTracker.ID_QUEUE.remove(mysteryDevice)\n except: pass\n self.identifyProcess(mysteryDevice)\n\n #####\n #\n #####\n def checkForExternalIPs(self):\n externalDevices = []\n devices = dbManagerNew.allIPs(NEW_E_DB_FILE)\n for device in devices:\n ipAddr = ip_address(device)\n ipNetwk = ip_network(self.internal_range)\n if ipAddr not in ipNetwk and ipAddr not in self.ping_sweep_processed:\n printD(\"PING: ipAddr: {0} not in ipNetwk: {1}\".format(ipAddr, ipNetwk))\n self.ping_sweep_processed.add(ipAddr)\n externalDevices.append(device)\n #else:\n #printD(\"PING: ipAddr: {0} in ipNetwk: {1}\".format(ipAddr, ipNetwk))\n return externalDevices\n\n # TODO: handle communication between ssass-e and webpage for user input/requests/actions\n def checkForPingSweepUserInput(self):\n allRequestTimeStamps = dbManagerNew.allIPs(NEW_R_DB_FILE)\n for requestTimeStamp in allRequestTimeStamps:\n requestDict = dbManagerNew.select_all(NEW_R_DB_FILE, requestTimeStamp)\n if \"DONE\" not in requestDict and \"PINGSWEEP\" in requestDict:\n printD(\"PING: geventLoop() Ping sweep timestamp: {0}, response: {1}\".format(requestTimeStamp, requestDict[\"PINGSWEEP\"]))\n self.DBManagerNew.insert(NEW_R_DB_FILE, requestTimeStamp, {\"DONE\": [\"Y\"]}, requestTimeStamp, \"Requests\")\n return requestDict[\"PINGSWEEP\"]\n #else:\n #printD(\"PING: User input skipped {0}\".format(requestDict))\n return None\n\n def ping_sweep_handler(self, ipRangeList):\n #targetPorts = '21-23,80,443,502,20000'\n\n printD(\"PING: doing sweep on {0}\".format(ipRangeList))\n for ipRange in ipRangeList:\n # Check if input format is correct\n runScan = True\n if ipRange in self.ipRangeScanStatus.keys() and \"PROCESSING\" in self.ipRangeScanStatus[ipRange].keys():\n timeElapsed = self.ipRangeScanStatus[\"ACTIVE_SCAN_TIME\"]\n # Scan is under process and maximum time has not elapsed\n if timeElapsed < 100:\n runScan = False\n if runScan == True:\n # Get scan parameters\n categoryName = \"network_scan\"\n\n scan = self.IpIdentifier.getScanWithoutPolicyCheck(\"nmap_arp_ping_scan\", ipRange, {})\n printD(\"PING: Scan parameters for nmap_arp_ping_scan: {}\".format(scan))\n if scan == \"NA\":\n return scan\n\n scan[\"PARAMS\"][\"SCAN_NAME\"] = \"nmap_arp_ping_scan\"\n scan[\"PARAMS\"][\"TARGET_IPADDR\"] = ipRange\n# scan[\"TARGET_PORTS\"] = targetPorts\n if ipRange not in self.ipRangeScanStatus.keys():\n self.ipRangeScanStatus[ipRange] = dict()\n self.ipRangeScanStatus[\"PROCESSING\"] = True\n self.ipRangeScanStatus[\"ACTIVE_SCAN_TIME\"] = time.time()\n\n # siteName from zonemap, which came from user\n siteName = self.getSiteName(ipRange)\n\n # Kick off new ping sweep scan\n if siteName != \"NA\":\n printD(\"PING: Sending requestScan: ipRange: {}, scan: {} and siteName: {}\".format(ipRange, scan, siteName))\n # self.IpIdentifier.requestScan(ipRange, scan, siteName)\n # TODO add ping sweep status/history to webpage somehow\n # self.publish_request(\"active.requests.{0}\".format(siteName), scan[\"PARAMS\"])\n self.publish_messages.append((\"active.requests.{0}\".format(siteName), scan[\"PARAMS\"]))\n \n def processVulnerabilities(self):\n ###################################################################\n # If the device has been identified, then newPortEvidenceQueue will \n # not be empty because it will be ready to process the ports and \n # services it supports to check for vulnerabilities.\n ###################################################################\n mysteryDevice = False\n port = 0\n service = 0\n IP_PORT_SERVICE = None\n ips = self.StatusTracker.IP_PORT_SERVICE\n\n printD( \"VULN_QUEUE len: {}, entries: {}\".format(len(ips), ips))\n\n for ip_port_service in self.StatusTracker.IP_PORT_SERVICE:\n printD(\"SN: Retrieving from VULN_QUEUE db {}\".format(ip_port_service))\n\n mD, port, service = ip_port_service.split('|')\n mysteryEvidence = dbManagerNew.select_all(NEW_E_DB_FILE, mD)\n allEvents = dbManagerNew.select_all(NEW_EVENTS_DB_FILE, mD)\n processingKey = helper.singleInList(\"PROCESSING\", allEvents.keys())\n if not processingKey or helper.singleInList(\"n\", allEvents[processingKey]):\n mysteryDevice = mD\n IP_PORT_SERVICE = ip_port_service\n break\n\n # If no new evidence, go through IPs currently in an active scan\n # (so we can see if timeout has passed)\n if mysteryDevice == False:\n devices = dbManagerNew.allIPs(NEW_E_DB_FILE)\n for mD in devices:\n\n mysteryEvidence = dbManagerNew.select_all(NEW_E_DB_FILE, mD)\n allEvents = dbManagerNew.select_all(NEW_EVENTS_DB_FILE, mD)\n activeScanTimeKey = helper.singleInList(\"ACTIVE_SCAN_TIME\", allEvents.keys())\n if activeScanTimeKey and \"0\" not in allEvents[activeScanTimeKey] and \"nmap_service_scan\" in mysteryEvidence.get(\"SCAN_NAME\", []):\n\n #mysteryDevice = mD\n protocols = self.getProtocols(mD)\n \n # Check if port done with vulnerabilities check\n try:\n vulnProtococols = self.getVulnerabilityPorts(mD)\n keys_to_delete = []\n for k, p in protocols.items():\n if helper.singleInList(p, vulnProtococols):\n keys_to_delete.append(k)\n for k in keys_to_delete:\n del protocols[k] \n except KeyError:\n pass\n for p, s in protocols.items():\n port = p\n service = s\n break\n if p != 0 and service != 0:\n mysteryDevice = mD\n break\n\n # run identify vulnerability process on the chosen IP (mysteryDevice), PORT and SERVICE\n if mysteryDevice != False:\n printD(\"SN: Found ip port to scan: IP: {}, PORT: {}, SERVICE: {}, IP_PORT_SERVICE: {}\".format(mysteryDevice, port, service, IP_PORT_SERVICE))\n if IP_PORT_SERVICE is None:\n IP_PORT_SERVICE = \"{}|{}|{}\".format(mysteryDevice, port, service)\n if IP_PORT_SERVICE in self.StatusTracker.IP_PORT_SERVICE:\n try: self.StatusTracker.IP_PORT_SERVICE.remove(IP_PORT_SERVICE)\n except: pass\n self.identifyVulnerability(mysteryDevice, port, service)\n\n\n ##########################################################\n # Get Ports from evidence, vendor profile and device profile\n ##########################################################\n def getProtocols(self, mysteryDevice):\n mysteryEvidence = dbManagerNew.select_all(NEW_E_DB_FILE, mysteryDevice)\n #printD(\"getPorts: {}\".format(mysteryEvidence))\n vendorKey = helper.singleInList(\"VENDOR\", mysteryEvidence.keys())\n #if vendor is None or vendor[0].upper() not in ['SEL', 'GE']:\n # printD(\"getPorts for {} returning since vendor is not SEL:{}\".format(mysteryDevice, vendor))\n # return {}\n modelKey = helper.singleInList(\"MODEL\", mysteryEvidence.keys())\n protocols = {}\n # Check for ports info in the evidence\n protocolsKey = helper.singleInList(\"PROTOCOLS\", mysteryEvidence.keys())\n if protocolsKey:\n for scada_protocol in mysteryEvidence[protocolsKey]:\n portKey = helper.singleInList(\"{0}_PORT\".format(scada_protocol), mysteryEvidence.keys())\n if portKey:\n protocols[scada_protocol] = mysteryEvidence[portKey]\n \n if vendorKey:\n v = self.vendorMap(mysteryEvidence[vendorKey][0]).upper()\n printD(\"SN: VENDORMAP: INPUT: {}, MAPPED: {}\".format(mysteryEvidence[vendorKey][0], v))\n # Read from vendor profile\n vendorPath = \"{0}/{1}.json\".format(vendor_profiles_path, v)\n protocols = self.getProtocolsFromProfile(vendorPath)\n\n if modelKey:\n m = self.modelMap(mysteryEvidence[modelKey][0]).upper()\n printD(\"SN: MODELMAP: INPUT: {}, MAPPED: {}\".format(mysteryEvidence[modelKey][0], m))\n # Read from device profile\n if m.upper() == \"CONTROLWAVEREMOTEIO\":\n m = \"ControlWaveRemoteIO\"\n modelPath = \"{0}/{1}.json\".format(device_profiles_path, m)\n modelProtocols = self.getProtocolsFromProfile(modelPath)\n protocols.update(modelProtocols)\n return protocols\n \n ##########\n #\n ##########\n def getProtocolsFromProfile(self, profilePath):\n try:\n fr = open(profilePath, \"r\", encoding=\"utf-8\")\n profileConfig = json.loads(fr.read())\n fr.close()\n except IOError as e:\n printD(\"ERROR Cannot open file: {}\".format(e))\n return {}\n\n protocols = {}\n\n printD(\"profile Config: {}\".format(profileConfig))\n services = profileConfig.get(\"SERVICES\", {})\n scada = profileConfig.get(\"SCADA\", {})\n services.update(scada)\n\n for service, prts in services.items():\n printD(\"service: {}, ports: {}\".format(service, prts))\n try:\n service_key = service + \"_TCP\"\n protocols[service_key] = prts[\"TCP\"][0]\n except Exception as e:\n printD(\"getProtocolsFromProfile() - ERROR: {0}\".format(e))\n try:\n service_key = service + \"_UDP\"\n protocols[service_key] = prts[\"UDP\"][0]\n except Exception as e:\n printD(\"getProtocolsFromProfile() - ERROR: {0}\".format(e))\n printD(\"getFromProfile: {}\".format(protocols))\n return protocols\n\n #####\n #\n #####\n def processSignature(self, signature, ttl):\n partialEvidence = {}\n\n relays = []\n rtus = []\n\n d_devices = dbManagerNew.allIPs(NEW_D_DB_FILE)\n for device in d_devices:\n profile = dbManagerNew.select_all(NEW_D_DB_FILE, device)\n device_type = profile.get(\"DEVICE_TYPE\", None)\n if device_type is not None:\n tcpKey = helper.singleInList(\"TCP_SIG\", profile.keys())\n ttlKey = helper.singleInList(\"TTL\", profile.keys())\n if tcpKey and ttlKey:\n if helper.singleInList(signature, profile[tcpKey]) and helper.singleInList(ttl, profile[ttlKey]):\n if device_type[0] == \"relay\":\n relays.append(profile)\n elif device_type[0] == \"rtu\":\n rtus.append(profile)\n\n if len(relays) == 0 and len(rtus) > 0:\n modelKey = helper.singleInList(\"MODEL\", rtus[0].keys())\n vendorKey = helper.singleInList(\"VENDOR\", rtus[0].keys())\n if len(rtus) == 1 and modelKey and False:\n partialEvidence[\"MODEL\"] = rtus[0][modelKey][0]\n if vendorKey:\n partialEvidence[\"VENDOR\"] = rtus[0][vendorKey][0]\n partialEvidence[\"DEVICE_TYPE\"] = \"rtu\"\n\n elif len(rtus) == 0 and len(relays) > 0:\n modelKey = helper.singleInList(\"MODEL\", relays[0].keys())\n vendorKey = helper.singleInList(\"VENDOR\", relays[0].keys())\n if len(relays) == 1 and modelKey and False:\n partialEvidence[\"MODEL\"] = relays[0][modelKey][0]\n if vendorKey:\n partialEvidence[\"VENDOR\"] = relays[0][vendorKey][0]\n partialEvidence[\"DEVICE_TYPE\"] = \"relay\"\n\n printD(\"inference.processSignature() - partialEvidence: {0}\".format(partialEvidence))\n\n return partialEvidence\n\n #####\n #\n #####\n def ipInPolicy(self, mysteryDevice):\n fr = open(\"{0}policy.json\".format(scans_path), \"r\", encoding=\"utf-8\")\n policy = json.loads(fr.read())\n fr.close()\n\n if mysteryDevice in policy.keys():\n return True\n else:\n for key in policy.keys():\n if key != \"default\":\n try:\n ipObj = ip_address(mysteryDevice)\n netObj = ip_network(key)\n if ipObj in netObj:\n return True\n break\n except Exception as e:\n #printD(\"checking policy for ip warning: {0}\".format(e))\n pass\n printD(\"ipInPolicy() - ip: {0} not in policy\".format(mysteryDevice))\n return False\n\n ##########################################################\n # receiveEvidence(evidence)\n # get all existing evidence for this IP from DB\n # determine which recent evidence is NEW\n # add new evidence to DB (as is, no sanitize)\n # if IP not in queue, add it\n ##########################################################\n def receiveEvidence(self, rawEvidence, fromWho = \"\"):\n # get mysteryDevice (IP)\n if \"TARGET_IPADDR\" not in rawEvidence.keys():\n return False\n mysteryDevice = rawEvidence[\"TARGET_IPADDR\"]\n if mysteryDevice in IGNORE_IPS:\n return False\n\n rawEvidence = helper.breakDownDict(rawEvidence, \"\", {})\n\n #if mysteryDevice == \"172.17.0.13\" and \"SCAN_NAME\" in rawEvidence.keys() and \"http_TCP_header_probe\" == rawEvidence[\"SCAN_NAME\"]:\n # printD(\"Returning 172.17.0.13 header probe\")\n # return False\n\n existingEvidence = {}\n newEvidence = {}\n\n # first occurence of device\n e_devices = dbManagerNew.allIPs(NEW_E_DB_FILE)\n if mysteryDevice not in e_devices:\n printD(\"receive() - ip: {0}, FIRST\".format(mysteryDevice))\n rawEvidence[\"PROCESSING\"] = \"n\"\n rawEvidence[\"ACTIVE_SCAN_TIME\"] = \"0\"\n else:\n existingEvidence = dbManagerNew.select_all(NEW_E_DB_FILE, mysteryDevice)\n\n for rawKey,rawVal in rawEvidence.items():\n rawKey = str(rawKey).strip()\n\n if isinstance(rawVal, string_type) or isinstance(rawVal, int) or isinstance(rawVal, float):\n rawVal = str(rawVal).strip()\n pass\n else:\n # handle eventually\n continue\n\n # ignore\n if helper.singleInList(rawKey, [\"DEST_PORT\", \"SOURCE_PORT\", \"CTR\"]) or rawKey.upper().startswith(\"STATUS\") or len(rawVal) < 1 or helper.compareSingle(rawVal, \"none\"):\n continue\n\n # conversions\n if rawKey == \"PROTOCOL\":\n rawKey = \"PROTOCOLS\"\n\n # vendor mapping\n if rawKey == \"VENDOR\":\n oldVal = rawVal\n rawVal = self.vendorMap(rawVal)\n printD(\"receiveEvidence - ip: {0}, rawVendor: {1}, vendorMap: {2}\".format(mysteryDevice, oldVal, rawVal))\n\n # model mapping\n modelKeys = [\"MODEL\", \"PART_NO\", \"DEVICE_NAME\"]\n if helper.singleInList(rawKey, modelKeys):\n oldVal = rawVal\n #if \"MODEL\" not in newEvidence.keys():\n # newEvidence[\"MODEL\"] = []\n rawVal = self.modelMap(rawVal)\n #newEvidence[\"MODEL\"].append(rawVal)\n if rawKey not in existingEvidence.keys():\n if rawKey not in newEvidence.keys():\n newEvidence[rawKey] = []\n newEvidence[rawKey].append(rawVal)\n elif not helper.singleInList(rawVal, existingEvidence[rawKey]):\n if rawKey not in newEvidence.keys():\n newEvidence[rawKey] = []\n if rawVal not in newEvidence[rawKey]:\n newEvidence[rawKey].append(rawVal)\n printD(\"receiveEvidence - ip: {0}, rawModel: {1}, modelMap: {2}\".format(mysteryDevice, oldVal, rawVal))\n\n # signature processing\n if rawKey == \"TCP_SIG\" and \"TTL\" in rawEvidence.keys():\n partialEvidence = self.processSignature(rawVal, rawEvidence[\"TTL\"])\n for partialKey,partialVal in partialEvidence.items():\n if partialKey not in existingEvidence.keys():\n if partialKey not in newEvidence.keys():\n newEvidence[partialKey] = []\n newEvidence[partialKey].append(partialVal)\n elif not helper.singleInList(partialVal, existingEvidence[partialKey]):\n if partialKey not in newEvidence.keys():\n newEvidence[partialKey] = []\n if partialVal not in newEvidence[partialKey]:\n newEvidence[partialKey].append(partialVal)\n\n # new key\n if rawKey not in existingEvidence.keys():\n if rawKey not in newEvidence.keys():\n newEvidence[rawKey] = []\n if rawVal not in newEvidence[rawKey]:\n newEvidence[rawKey].append(rawVal)\n # existing key, new val\n elif not helper.singleInList(rawVal, existingEvidence[rawKey]):\n if rawKey not in newEvidence.keys():\n newEvidence[rawKey] = []\n if rawVal not in newEvidence[rawKey]:\n newEvidence[rawKey].append(rawVal)\n\n if len(newEvidence.keys()) > 0:\n printD(\"receive() - ip: {0}, EXISTING: {1}, NEW: {2}\".format(mysteryDevice, existingEvidence, newEvidence))\n\n # add event to events DB - only for passive/active\n if \"Passive\" in fromWho or \"Active\" in fromWho:\n eventTimestamp = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n event = {}\n event[\"TYPE\"] = [\"IDENTIFICATION\"]\n event[\"TARGET_IPADDR\"] = [mysteryDevice]\n\n if \"Passive\" in fromWho:\n event[\"SIGNATURE\"] = [\"Passive\"]\n if \"PROTOCOL\" in rawEvidence.keys():\n event[\"SIGNATURE\"] = [rawEvidence[\"PROTOCOL\"]]\n elif \"PROTOCOLS\" in rawEvidence.keys():\n event[\"SIGNATURE\"] = [rawEvidence[\"PROTOCOLS\"]]\n elif \"SERVICE\" in rawEvidence.keys():\n event[\"SIGNATURE\"] = [rawEvidence[\"SERVICE\"]]\n event[\"STATUS\"] = [\"New Evidence\"]\n\n elif \"Active\" in fromWho:\n event[\"SIGNATURE\"] = [\"Active\"]\n if \"SCAN_NAME\" in rawEvidence.keys():\n event[\"SIGNATURE\"] = [rawEvidence[\"SCAN_NAME\"]]\n fr = open(\"{0}scans.json\".format(scans_path), \"r\", encoding=\"utf-8\")\n scansDict = json.loads(fr.read())\n fr.close()\n scanDict = helper.getNested(scansDict, rawEvidence[\"SCAN_NAME\"])\n if mysteryDevice in self.StatusTracker.IDENTIFIED and scanDict != False and helper.singleInList(\"vulnerability\", scanDict.get(\"TYPE\", [])):\n event[\"TYPE\"] = [\"VULNERABILITY\"]\n event[\"STATUS\"] = [\"Results Received\"]\n event[\"INFO\"] = [json.dumps(newEvidence)]\n self.DBManagerNew.insert(NEW_EVENTS_DB_FILE, mysteryDevice, event, datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\"), event[\"TYPE\"][0])\n\n printD(\"inference inserting new evidence for ip {0}\".format(mysteryDevice))\n\n # insert new evidence into DB (as is, not sanitized)\n evidenceType = \"Internal\"\n if \"Passive\" in fromWho:\n evidenceType = \"Passive\"\n if \"Active\" in fromWho:\n evidenceType = \"Active\"\n self.DBManagerNew.insert(NEW_E_DB_FILE, mysteryDevice, newEvidence, datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\"), evidenceType)\n\n # check if NA vendor needs to be removed\n # if \"VENDOR\" in newEvidence.keys() and \"NA\" not in newEvidence[\"VENDOR\"]:\n # if \"VENDOR\" in existingEvidence.keys() and \"NA\" in existingEvidence[\"VENDOR\"]:\n # self.DBManager.removeVal(E_DB_FILE, mysteryDevice, \"VENDOR\", \"NA\")\n\n # check if identified\n modelKey = helper.singleInList(\"MODEL\", newEvidence.keys())\n if modelKey:\n if mysteryDevice not in self.StatusTracker.IDENTIFIED: self.StatusTracker.IDENTIFIED.append(mysteryDevice)\n if mysteryDevice in self.StatusTracker.ID_QUEUE:\n try: self.StatusTracker.ID_QUEUE.remove(mysteryDevice)\n except: pass\n\n deviceProfile = dbManagerNew.select_all(NEW_D_DB_FILE, newEvidence[modelKey][0])\n if \"DEVICE_TYPE\" in deviceProfile.keys():\n newEvidence[\"DEVICE_TYPE\"] = deviceProfile[\"DEVICE_TYPE\"]\n self.DBManagerNew.insert(NEW_E_DB_FILE, mysteryDevice, newEvidence, datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\"), (((\"Active\", \"Passive\")[\"Active\" in fromWho]), \"Internal\")[\"Passive\" in fromWho or \"Active\" in fromWho])\n\n # add IP to queue to be processed\n printD(\"receive before() - ID_QUEUE: {0}\".format(self.StatusTracker.ID_QUEUE))\n if mysteryDevice not in self.StatusTracker.IDENTIFIED and mysteryDevice not in self.StatusTracker.ID_QUEUE: self.StatusTracker.ID_QUEUE.append(mysteryDevice)\n printD(\"receive after() - ID_QUEUE: {0}\".format(self.StatusTracker.ID_QUEUE))\n\n scan = {}\n scan[\"PARAMS\"] = {\"key\": \"testing\"}\n# self.publish_request(\"active.requests.pacific\", scan[\"PARAMS\"])\n # preps vuln queue\n if True:\n if mysteryDevice in self.StatusTracker.IDENTIFIED:\n printD(\"SN: New evidence: {}\".format(newEvidence))\n printD(\"SN: Device is identified: {}\".format(mysteryDevice))\n if mysteryDevice not in self.ServiceProcessor.processStarted.keys():\n self.ServiceProcessor.serviceInfo[mysteryDevice] = protocols = self.getProtocols(mysteryDevice)\n # Kick off nmap scan\n pts = []\n for service, port in protocols.items():\n pts.append(port)\n printD(\"SN: starting Nmap Scan for mystery device: {}, ports: {}\".format(mysteryDevice, pts))\n self.startNmapScan(mysteryDevice, pts)\n self.ServiceProcessor.processStarted[mysteryDevice] = True\n\n # check if certain scan \"nmap_service_scan\" came back\n scanName = \"nmap_service_scan\"\n if helper.singleInList(scanName, dbManagerNew.select_all(NEW_E_DB_FILE, mysteryDevice).get(\"SCAN_NAME\", [])):\n printD(\"SN: nmap_service_scan received. mysteryDevice: {}, new evidence: {}\".format(mysteryDevice, newEvidence))\n\n # Check if port done with vulnerabilities check\n try:\n# printD(\"SN: IdentifiedVulnerabilities ports: {}\".format(self.identifiedVulnerabilities))\n protocols = self.ServiceProcessor.serviceInfo[mysteryDevice]\n vulnProtocols = self.getVulnerabilityPorts(mysteryDevice)\n printD(\"SN: IdentifiedVulnerabilities device: {}, ports: {}, protocols: {}\".format(mysteryDevice, vulnProtocols, protocols))\n keys_to_delete = []\n for k, p in protocols.items():\n if helper.singleInList(p, vulnProtocols):\n printD(\"SN: Port {} on Device: {} is vulnerability scanned.\".format(p, mysteryDevice))\n keys_to_delete.append(k)\n for k in keys_to_delete:\n del protocols[k] \n except Exception as e:\n printD(\"SN: Error: {0}\".format(e))\n for service, port in protocols.items():\n ip_port_service = \"{}|{}|{}\".format(mysteryDevice, port, service)\n #self.newPortEvidenceQueue.put(mysteryDevice, port, service)\n printD(\"SN: db entries: {}, ip_port_service: {}\".format(self.StatusTracker.IP_PORT_SERVICE, ip_port_service))\n if ip_port_service not in self.StatusTracker.IP_PORT_SERVICE: self.StatusTracker.IP_PORT_SERVICE.append(ip_port_service)\n printD(\"SN: ip_port_service: {}\".format(ip_port_service))\n #printD(\"SN: AFTER putting newPortEvidenceQueue: {}\".format(self.newPortEvidenceQueue))\n printD(\"inference.receive() - exiting\")\n\n def getVulnerabilityPorts(self, mysteryDevice):\n vulnProtococols = set()\n ip_ports = self.StatusTracker.IP_PORT\n for ip_port in ip_ports:\n ip, port = ip_port.split('_')\n if ip == mysteryDevice:\n vulnProtococols.add(port)\n \n return vulnProtococols\n","sub_path":"ssasse_platform/InferenceEngine/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":46154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"260598614","text":"import numpy as np\nimport os, sys\nimport tensorflow as tf\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nimport argparse\nimport open3d as o3d\nfrom termcolor import colored\nimport glob\nimport time\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--read_dir', required=True, help='path to mesh data')\nparser.add_argument('--write_dir', required=True, help='path to tfrecord data')\nopt = parser.parse_args()\n\nclasses = ['ceiling', 'floor', 'wall', 'beam', 'column', 'window', 'door',\n 'table', 'chair', 'sofa', 'bookcase', 'board', 'clutter']\nnum_classes = len(classes)\n\n\ndef _bytes_feature(value):\n \"\"\" Returns a bytes_list from a string / byte. \"\"\"\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef make_tfrecord_seg(meshPath, store_folder=\"\", visualize=False):\n AreaPath = os.path.dirname(meshPath)\n AreaID = meshPath.split('/')[-2]\n SceneID = meshPath.split('/')[-1].replace('_mesh.ply','')\n print(AreaID, SceneID, AreaPath)\n\n labelPath = meshPath.replace('_mesh.ply','.semseg')\n print('labelPath', labelPath)\n\n if not store_folder==\"\" and not os.path.exists(store_folder):\n os.mkdir(store_folder)\n\n print(\"========================make tfrecords of s3dis %s--%s========================\" % (AreaID, SceneID))\n # load mesh and the vertex labels;\n mesh = o3d.io.read_triangle_mesh(scenePath)\n mesh.compute_vertex_normals()\n seg_labels = np.loadtxt(labelPath, dtype=np.int32, delimiter=',')\n if visualize:\n o3d.visualization.draw_geometries([mesh],mesh_show_back_face=True)\n\n xyz = np.asarray(mesh.vertices, dtype=np.float32)\n face = np.asarray(mesh.triangles, dtype=np.int32)\n print(seg_labels.shape, xyz.shape)\n\n print(colored(np.unique(seg_labels), 'blue'))\n assert(np.all(seg_labels>=-1) & np.all(seg_labels 0:\n # voices_to_add = [initial_voicing[make_appear_voice[i % len(make_appear_voice)]] for i in range(delta)]\n # initial_voicing = list(sorted(initial_voicing + voices_to_add))\n\n C = None\n chords_result = []\n nb_voices = 0\n for chord, pitches, bass, direction, info in pitchess:\n voicing = []\n for inf in info:\n if inf.startswith('voicing_'):\n voicing = eval(inf.replace('*', 'chord'))\n nb_voices = len(voicing)\n\n if len(voicing) > 0:\n C = ChordVoicing(pitches=voicing)\n else:\n if bass is None:\n C = C.transition_to(ChordName(pitches=pitches), **kwargs)\n else:\n fixed_voice = [None] * nb_voices\n fixed_voice[0] = bass\n directions = [0] * nb_voices\n directions[0] = direction\n C = C.transition_to(ChordName(pitches=pitches), fixed_voice=fixed_voice, directions=directions, **kwargs)\n chords_result.append(C)\n # Reverse the transitions to egalize the number of voice troughout the piece ...\n\n return chords_result\n\ndef voicing_spaced(chord, octave, min_space, nb_voices):\n pitches, bass, direction = str_to_pitches(chord)\n if bass:\n pitches = [bass % 12] + [p % 12 for p in pitches if (p % 12) != (bass % 12)]\n else:\n pitches = [p % 12 for p in pitches]\n\n if nb_voices is not None:\n if nb_voices > len(pitches):\n to_add = nb_voices - len(pitches)\n for i in range(to_add):\n pitches.append(pitches[i % len(pitches)])\n\n result = [pitches[0] + 12 * octave]\n pitches = pitches[1:]\n\n while len(pitches) > 0:\n intervals = [increasing_distance_mod12(result[-1] % 12, p % 12) for p in pitches]\n filter = [i < min_space for i in intervals]\n # Take smallest candidate in intervals\n index = np.argmin(np.where(filter, 1000, np.asarray(intervals)))\n result.append(result[-1] + intervals[index])\n pitches.remove(pitches[index])\n\n return result\n\n\ndef voicings_to_matrix(voicings):\n \"\"\"\n Transform list of voicings to a matrix of pitches\n Need ChordVoicing to have same number of pitches each\n :param chords:\n :return:\n \"\"\"\n result = np.zeros((len(voicings[0].pitches), len(voicings)))\n for j, voicing in enumerate(voicings):\n for i, pitch in enumerate(voicing.pitches):\n result[i, j] = pitch\n\n return result\n\n\n\ndef voicings_to_score(voicings, repeat=False, rythm=None):\n \"\"\"\n e q e | e q e +\n e re e e | e re e e +\n q q | h +\n h | q q +\n\n :param voicings:\n :param rythm:\n :return:\n \"\"\"\n score = None\n matrix = voicings_to_matrix(voicings)\n if rythm is not None:\n rythm = parse_rythm(rythm)\n idx = 0\n for idx_voice, voice in enumerate(matrix):\n voice_res = []\n for idx_note, note in enumerate(voice):\n voice_res += [Note(note).augment(r) if not is_rest else R.augment(r) for r, is_rest in rythm[idx_voice % len(rythm)][idx_note % len(rythm[idx_voice % len(rythm)])]]\n voice_res = Serie(voice_res)\n if score is None:\n score = voice_res.set_track(idx)\n else:\n score *= voice_res.set_track(idx)\n idx += 1\n\n else:\n\n for idx, row in enumerate(matrix):\n voice = Serie([Note(n) for n in row])\n voice = voice.set_track(idx)\n if score is None:\n # score = voice\n score = voice\n else:\n score = score * voice\n score = score.h\n\n return score\n\n\ndef parse_chords_to_score(chords, counterpoint=True):\n # With each voice as result\n score = None\n voices = max([len(chord.pitches) for chord in chords])\n result = np.zeros((voices, len(chords)))\n\n for j, chord in enumerate(chords):\n for i, pitch in enumerate(chord.pitches):\n result[i, j] = pitch\n\n for idx, row in enumerate(result):\n voice = Serie([Note(n) for n in row])\n voice = voice.set_track(idx)\n if score is None:\n # score = voice\n score = voice\n else:\n score = score * voice\n return score.h\n\n","sub_path":"musiclang/compose/voice_leading.py","file_name":"voice_leading.py","file_ext":"py","file_size_in_byte":5605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"373198383","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110 - 1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\nbl_info = {\n \"name\": \"tkit\",\n \"description\": \"edgemode select ops w/ configurable hotkeys\",\n \"author\": \"Shams Kitz \",\n \"version\": (5,3),\n \"blender\": (2,78,0),\n \"location\": \"Mesh Tools, Edge Menu, and hotkeys in edge-select mode\",\n \"warning\": \"\",\n \"tracker_url\": \"https://github.com/dustractor/tkit\",\n \"wiki_url\": \"\",\n \"category\": \"Learnbgame\",\n }\n\nimport bpy\nimport bmesh\n\nselected = lambda _: _.select\nnotselected = lambda _: not _.select\ntagged = lambda _: _.tag\nnottagged = lambda _: not _.tag\n\nclass EdgeSelectMode:\n @classmethod\n def poll(self,context):\n return (context.active_object and\n context.active_object.type == 'MESH' and\n context.active_object.mode == 'EDIT' and\n context.scene.tool_settings.mesh_select_mode[1])\n\nclass TKIT:\n mapdata = []\n ops = []\n maps = []\n\n def __init__(self):\n def draw(s,c):\n if EdgeSelectMode.poll(c):\n for op in self.ops:\n s.layout.operator(op.bl_idname)\n self.menu = type(\"TKIT_MT_menu\",(bpy.types.Menu,),\n dict(\n bl_label=\"tkit\",\n bl_idname=\"tkit.menu\",\n draw=draw))\n\n @property\n def classes(self):\n return [self.menu] + self.ops\n\n @classmethod\n def op(cls,f):\n n = f.__name__.lower()\n lbl,ign,mapx = f.__doc__.partition(\":\")\n ncls = type(\n \"TKIT_OT_\"+n,\n (EdgeSelectMode,bpy.types.Operator),\n dict(\n bl_idname=\"tkit.\"+n,\n bl_label=lbl,\n bl_options={\"REGISTER\",\"UNDO\"},\n execute=f))\n cls.ops.append(ncls)\n if mapx:\n cls.maps.append((ncls.bl_idname,mapx))\n return ncls\n\n @staticmethod\n def menudraw(self,context):\n self.layout.menu(\"tkit.menu\")\n\ntkit = TKIT()\n\n@tkit.op\ndef ie(self,context):\n '''Inner edges : QUOTE '''\n bm = bmesh.from_edit_mesh(context.active_object.data)\n for e in bm.edges:\n e.tag = len(list(filter(selected,e.link_faces))) == 1\n for e in filter(tagged,bm.edges):\n e.select_set(0)\n e.tag = 0\n bm.select_flush_mode()\n context.area.tag_redraw()\n return {'FINISHED'}\n\n@tkit.op\ndef oe(self,context):\n '''Outer Edges : S+QUOTE '''\n bm = bmesh.from_edit_mesh(context.active_object.data)\n for e in bm.edges:\n e.tag = len(list(filter(selected,e.link_faces))) == 2\n for e in filter(tagged,bm.edges):\n e.select_set(0)\n e.tag = 0\n bm.select_flush_mode()\n context.area.tag_redraw()\n return {'FINISHED'}\n\n@tkit.op\ndef lon(self,context):\n ''' lon : RIGHT_BRACKET '''\n bm = bmesh.from_edit_mesh(context.active_object.data)\n for e in filter(selected,bm.edges):\n for v in e.verts:\n v.tag ^= 1\n for f in e.link_faces:\n f.tag = 1\n efs = {f.index for f in filter(tagged,bm.faces)}\n for v in filter(tagged,bm.verts):\n v.tag = 0\n for e in filter(notselected,v.link_edges):\n e.tag = {f.index for f in e.link_faces}.isdisjoint(efs)\n for e in filter(tagged,bm.edges):\n e.tag = 0\n e.select_set(1)\n for f in bm.faces:\n f.tag = 0\n bm.select_flush_mode()\n context.area.tag_redraw()\n return {'FINISHED'}\n\n@tkit.op\ndef lun(self,context):\n ''' lun (un-lon) : LEFT_BRACKET '''\n bm = bmesh.from_edit_mesh(context.active_object.data)\n for e in filter(selected,bm.edges):\n for v in e.verts:\n v.tag ^= 1\n for v in filter(tagged,bm.verts):\n v.tag = 0\n for e in filter(selected,v.link_edges):\n e.select_set(0)\n bm.select_flush_mode()\n context.area.tag_redraw()\n return {'FINISHED'}\n\n@tkit.op\ndef epz(self,context):\n ''' epz : CSA+END '''\n\n bm = bmesh.from_edit_mesh(context.active_object.data)\n for e in filter(selected,bm.edges):\n for v in e.verts:\n v.tag ^= 1\n for v in filter(tagged,bm.verts):\n for e in v.link_edges:\n e.select ^=1\n for e in bm.edges:\n e.select_set(e.select)\n for v in bm.verts:\n v.tag = 0\n bm.select_flush_mode()\n context.area.tag_redraw()\n return {'FINISHED'}\n\n@tkit.op\ndef ef1n(self,context):\n ''' ef1n : BACK_SLASH '''\n bm = bmesh.from_edit_mesh(context.active_object.data)\n for e in filter(selected,bm.edges):\n for f in filter(notselected,e.link_faces):\n for fe in filter(notselected,f.edges):\n fe.tag = len(list(filter(selected,fe.verts))) == 1\n for e in bm.edges:\n e.select_set(e.tag)\n e.tag = 0\n bm.select_flush_mode()\n context.area.tag_redraw()\n return {'FINISHED'}\n\n@tkit.op\ndef ef2n(self,context):\n ''' ef2n : S+BACK_SLASH '''\n bm = bmesh.from_edit_mesh(context.active_object.data)\n for e in filter(selected,bm.edges):\n for f in filter(notselected,e.link_faces):\n for fe in filter(notselected,f.edges):\n fe.tag = len(list(filter(notselected,fe.verts))) == 2\n for e in bm.edges:\n e.select_set(e.tag)\n e.tag = 0\n bm.select_flush_mode()\n context.area.tag_redraw()\n return {'FINISHED'}\n\n@tkit.op\ndef ef2np(self,context):\n ''' ef2np : CS+BACK_SLASH '''\n bm = bmesh.from_edit_mesh(context.active_object.data)\n for e in filter(selected,bm.edges):\n for f in filter(notselected,e.link_faces):\n for fe in filter(notselected,f.edges):\n fe.tag ^= len(list(filter(notselected,fe.verts))) == 2\n for e in bm.edges:\n e.select_set(e.tag)\n e.tag = 0\n bm.select_flush_mode()\n context.area.tag_redraw()\n return {'FINISHED'}\n\n@tkit.op\ndef ef2nx(self,context):\n ''' ef2nx : CSA+BACK_SLASH '''\n bm = bmesh.from_edit_mesh(context.active_object.data)\n for e in filter(selected,bm.edges):\n for f in filter(notselected,e.link_faces):\n for fe in filter(notselected,f.edges):\n fe.tag = 1\n for e in bm.edges:\n e.select_set(e.tag)\n e.tag = 0\n bm.select_flush_mode()\n context.area.tag_redraw()\n return {'FINISHED'}\n\nclass tkitPrefs(bpy.types.AddonPreferences):\n bl_idname = __name__\n def draw(self,context):\n layout = self.layout\n for op in tkit.ops:\n opn = op.bl_idname\n t = opn.partition(\".\")[2]\n layout.prop(self,t)\n\nfor opn,mapx in tkit.maps:\n t = opn.partition(\".\")[2]\n setattr(\n tkitPrefs,\n t,\n bpy.props.StringProperty(default=mapx))\n\ndef register():\n list(map(bpy.utils.register_class,tkit.classes))\n bpy.utils.register_class(tkitPrefs)\n\n prefs = bpy.context.user_preferences.addons[__name__].preferences\n wm = bpy.context.window_manager\n kc = wm.keyconfigs.addon\n if kc:\n km = kc.keymaps.new(\"Mesh\",space_type=\"EMPTY\")\n for op in tkit.ops:\n opn = op.bl_idname\n t = opn.partition(\".\")[2]\n mapx = getattr(prefs,t)\n modx = \"\"\n if \"+\" in mapx:\n modx,ign,mapt = mapx.partition(\"+\")\n else:\n mapt = mapx\n ctrl,shift,alt,oskey = map(lambda _:_ in modx.upper(),\"CSAO\")\n mapt = mapt.strip()\n kmi = km.keymap_items.new(\n opn, type=mapt, value=\"PRESS\",\n shift=shift, ctrl=ctrl, alt=alt, oskey=oskey)\n tkit.mapdata.append((km,kmi))\n bpy.types.VIEW3D_MT_edit_mesh_edges.append(tkit.menudraw)\n bpy.types.VIEW3D_PT_tools_meshedit.append(tkit.menu.draw)\n\ndef unregister():\n for km,kmi in tkit.mapdata:\n km.keymap_items.remove(kmi)\n tkit.mapdata.clear()\n bpy.types.VIEW3D_MT_edit_mesh_edges.remove(tkit.menudraw)\n bpy.types.VIEW3D_PT_tools_meshedit.remove(tkit.menu.draw)\n bpy.utils.unregister_class(tkitPrefs)\n list(map(bpy.utils.unregister_class,tkit.classes))\n\n","sub_path":"All_In_One/addons/tkit/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"534940515","text":"from parser import CharacterParser\nimport re\n\nfrom enum import Enum\n\nclass Interpreter:\n\n class Node:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n def __repr__(self):\n return str(self.__dict__)\n\n class Code(Enum):\n ERROR = -1\n VAR = 0\n IDENTIFIER = 1\n COMMA = 2\n AS = 3\n DATA_TYPE = 4\n START = 5\n STOP = 6\n COMMENT_OP = 7\n NEWLINE = 8\n CONCATENATOR = 9\n OUTPUT = 10\n STRING_CONST = 11\n ARITHMETIC_OP = 12\n NUMERIC_CONST = 13\n BOOLEAN_CONST = 14\n CHARACTER_CONST = 15\n EQUAL = 16\n IF = 17\n INPUT = 18\n ELSE = 19\n\n ASSIGNMENT_STMT = 100\n \n def __init__(self):\n self.charParser = CharacterParser()\n self.memory = []\n \n # STATEMENTS\n def validate(self, terms, startState, finalStates, deadStates, table, switcher, coder = None, debug = False, anyInputCode = -1, customGetCode = None):\n if(debug):\n print(terms)\n state = startState\n for term in terms:\n if((term is not None) & (term is not '')):\n if(coder is None):\n code = self.getCode(term)\n else:\n code = coder.getCode(term)\n if(code == self.Code.ERROR and customGetCode != None):\n code = customGetCode(term)\n code = switcher.get(code, -1)\n if(code == self.Code.ERROR):\n code = anyInputCode if anyInputCode != None else code\n if(debug):\n print('TERM', term, 'state: ', state, 'code: ', code, 'Sub Error:', anyInputCode)\n state = table[code][state]\n if(debug & (state in deadStates)):\n print(term, 'is DEAD code:', code)\n break\n return state in finalStates\n\n def isValidInitializationStatement(self, strLine, debug = False):\n state = 1\n table = [\n # 0 1 2 3 4 5\n [0, 2, 0, 0, 0, 0], # VAR\n [0, 0, 3, 0, 0, 0], # identifier\n [0, 0, 0, 2, 0, 0], # COMMA\n [0, 0, 0, 4, 0, 0], # AS\n [0, 0, 0, 0, 5, 0], # Data Type\n [0, 0, 3, 0, 0, 0] # AssignmentOperator\n ]\n \n # terms = re.split(' |(\\,)', strLine)\n terms = self.removeGarbageFromArray(re.split(\"(VAR)|(AS)|(INT)|(CHAR)|(BOOL)|(FLOAT)|(,)\", strLine))\n finalStates = [ 5 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.Code.VAR: 0,\n self.Code.IDENTIFIER : 1,\n self.Code.COMMA: 2,\n self.Code.AS: 3,\n self.Code.DATA_TYPE: 4,\n self.Code.ASSIGNMENT_STMT : 5\n }\n # Todo: Create Custome Get Code if ERROR is Caught\n def customCode (str):\n if(self.isValidAssignmentStatement(str)):\n return self.Code.ASSIGNMENT_STMT\n return self.Code.ERROR\n \n return self.validate(terms,state,finalStates, deadStates, table, mySwitcher, None, debug, None, customCode)\n \n def isValidCommentStatement(self, strLine, debug = False):\n state = 1\n table = [\n # 0 1 2\n [0, 2, 2], # *\n [0, 0, 2] # Any\n ]\n terms = re.split(' ',strLine)\n finalStates = [ 2 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.Code.COMMENT_OP: 0\n }\n return self.validate(terms,state,finalStates, deadStates, table, mySwitcher, None, debug, 1)\n\n def isValidStartStatement(self, strLine, debug = False):\n state = 1\n table = [\n # 0 1 2\n [0, 2, 0], # START\n [0, 0, 0] # Others\n ]\n terms = re.split(' ',strLine)\n finalStates = [ 2 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.Code.START: 0\n }\n return self.validate(terms,state,finalStates, deadStates, table, mySwitcher, None, debug, 1)\n\n def isValidStopStatement(self, strLine, debug = False):\n state = 1\n table = [\n # 0 1 2\n [0, 2, 0], # STOP\n [0, 0, 0] # Others\n ]\n terms = re.split(' ',strLine)\n finalStates = [ 2 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.Code.STOP: 0\n }\n return self.validate(terms,state,finalStates, deadStates, table, mySwitcher, None, debug, 1)\n\n def isValidWhileStatement(self, strLine, debug = False):\n terms = self.removeGarbageFromArray(re.split('(WHILE)',strLine))\n if(len(terms) != 2):\n return False\n if(terms[0] != \"WHILE\"):\n return False\n if(terms[1][0] != \"(\" or terms[1][-1] != \")\"):\n return False\n return self.isValidBooleanOperation(terms[1],debug)\n\n def isValidIFstatement(self, strLine, debug = False):\n terms = self.removeGarbageFromArray(re.split('(IF)',strLine))\n if(len(terms) != 2):\n return False\n if(terms[0] != \"IF\"):\n return False\n if(terms[1][0] != \"(\" or terms[1][-1] != \")\"):\n return False\n return self.isValidBooleanOperation(terms[1],debug) or self.isValidArithmeticOperation(terms[1],debug)\n\n def inValidINPUTStatement(self, strline, debug = False):\n state = 1\n table = [\n # 0, 1, 2, 3, 4\n [0, 2, 0, 0, 0], # OUTPUT\n [0, 0, 3, 0, 3], # Identifier\n [0, 0, 0, 4, 0], # Comma\n [0, 0, 0, 0, 0] # Others\n ]\n terms = self.removeGarbageFromArray(re.split('(INPUT:)|(,)',strline))\n print(terms)\n othersInput = 5\n finalStates = [ 3 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.Code.INPUT: 0,\n self.Code.IDENTIFIER: 1,\n self.Code.COMMA: 2\n }\n return self.validate(terms,state,finalStates, deadStates, table, mySwitcher, None, debug, othersInput)\n\n def isValidOutputStatement(self, strLine, debug = False):\n state = 1\n table = [\n # 0, 1, 2, 3, 4\n [0, 2, 0, 0, 0], # OUTPUT\n [0, 0, 3, 0, 3], # Identifier\n [0, 0, 3, 0, 3], # String Literal\n [0, 0, 0, 4, 0], # Concatenator\n [0, 0, 3, 0, 3], # New Line\n [0, 0, 0, 0, 0] # Others\n ]\n terms = self.removeGarbageFromArray(re.split('(OUTPUT:)|(&)',strLine))\n othersInput = 5\n finalStates = [ 3 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.Code.OUTPUT: 0,\n self.Code.IDENTIFIER: 1,\n self.Code.STRING_CONST: 2,\n self.Code.CONCATENATOR: 3,\n self.Code.NEWLINE: 4\n }\n return self.validate(terms,state,finalStates, deadStates, table, mySwitcher, None, debug, othersInput)\n\n def isValidBooleanOperation(self, strLine, debug = False):\n stack = []\n eqTerms = re.split('(\\()|(\\))|(\\=\\=)|(\\<\\=)|(\\>\\=)|(\\&\\&)|(\\|\\|)|(\\<)|(\\>)|(\\+)|(\\/)|(\\-)|(\\*)|(\\()|(\\))',strLine)\n eqTerms = self.removeGarbageFromArray(eqTerms)\n print(strLine,'TERMS',eqTerms)\n if \"=\" in eqTerms:\n return False\n nodeList = []\n for elem in eqTerms:\n if(self.isArithmeticOperator(elem)):\n return False\n temp = self.Node(elem)\n nodeList.append(temp)\n length = len(nodeList)\n newNode = self.nodeCreate(nodeList,[\"==\",\"<=\",\">=\",\"<\",\">\",\"&&\",\"||\"])\n return self.inorderTraverse(newNode) != None\n\n def isValidArithmeticOperation(self, strLine, debug = False):\n stack = []\n eqTerms = re.split(' |(\\+)|(\\/)|(\\-)|(\\*)|(\\%)|(\\()|(\\))',strLine)\n eqTerms = self.removeGarbageFromArray(eqTerms)\n nodeList = []\n for elem in eqTerms:#strLine.split():\n temp = self.Node(elem)\n nodeList.append(temp)\n length = len(nodeList)\n try:\n newNode = self.nodeCreate(nodeList)\n return self.inorderTraverse(newNode) != None\n except:\n return False\n \n def isValidAssignmentStatement(self, strLine, debug = False):\n state = 1\n table = [\n # 0 1 2 3 4\n [0, 2, 0, 4, 0], # identifier\n [0, 0, 3, 0, 3] # =\n ]\n terms = re.split(' |(\\=\\=)|(\\=)', strLine)\n terms = self.removeGarbageFromArray(terms)\n equation = \"\"\n indexOfEQ = 0\n for i, e in reversed(list(enumerate(terms))):\n if e == \"=\":\n break\n equation = e + equation\n indexOfEQ = i\n del terms[indexOfEQ:]\n finalStates = [ 3 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.Code.IDENTIFIER : 0,\n self.Code.EQUAL: 1,\n self.Code.NUMERIC_CONST: 2,\n self.Code.BOOLEAN_CONST: 2,\n self.Code.STRING_CONST: 2,\n self.Code.CHARACTER_CONST: 2\n }\n currentState = self.validate(terms,state,finalStates, deadStates, table, mySwitcher, None, debug, None)\n if currentState:\n try:\n return self.isValidArithmeticOperation(equation)\n except:\n pass\n try:\n return self.isValidBooleanOperation(equation)\n except:\n pass\n return False\n\n def isELSE(self, strLine):\n return strLine == \"ELSE\"\n\n def findPair(self,nodeList: [], index):\n stack = []\n retIndex = index\n for node in nodeList:\n if(node.value == '('):\n stack.append(node.value)\n elif(node.value == ')'):\n stack.pop()\n if len(stack) == 0:\n break\n retIndex = retIndex + 1\n return retIndex\n\n def nodeCreate(self,nodeList:[], operationSequence = ['*','/','%','+','-']):\n index = 0\n while index < len(nodeList):\n if (nodeList[index].value == '('):\n pairIndex= self.findPair(nodeList[index:],index)\n removedList = nodeList[index:pairIndex+1]\n del removedList[0]\n del removedList[-1]\n node = self.nodeCreate(removedList)\n del nodeList[index:pairIndex+1]\n node.value = \"TEMP\" # simulate SOLVED INPUT\n node.left = node.right = None\n nodeList.insert(index,node)\n index = index + 1\n for operation in operationSequence:\n index = 0\n while index < len(nodeList):\n if(nodeList[index].value == operation):\n if(index+1 < len(nodeList)):\n nodeList[index].right = nodeList[index+1]\n del nodeList[index+1]\n if(index-1 >= 0):\n nodeList[index].left = nodeList[index-1]\n del nodeList[index-1]\n index = index + 1\n return nodeList[0]\n\n\n def inorderTraverse(self,node):\n strRet = \"\"\n if node == None:\n return\n if node.left != None:\n strRet += self.inorderTraverse(node.left)\n strRet += node.value\n if node.right != None:\n strRet += self.inorderTraverse(node.right)\n return strRet\n\n # PARSERS\n\n def isValidIdentifier(self, str):\n state = 1\n table = [\n # 0 1 2\n [0, 2, 2], # _\n [0, 2, 2], # A-Z\n [0, 0, 2], # 0 - 9\n [0, 0, 0] # Others\n ]\n finalStates = [ 2 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.charParser.Code.UNDERSCORE: 0,\n self.charParser.Code.LETTER: 1,\n self.charParser.Code.DIGIT: 2\n }\n return self.validate(str, state, finalStates, deadStates, table, mySwitcher, self.charParser)\n \n def isValidStringConstant(self, str, debug = False):\n state = 1\n table = [\n # 0 1 2, 3, 4, 5\n [0, 2, 3, 0, 5, 0], # \"\n [0, 0, 4, 0, 5, 0], # [\n [0, 0, 0, 0, 0, 2], # ]\n [0, 0, 2, 0, 0, 0], # Digit\n [0, 0, 2, 0, 0, 0], # Letter\n [0, 0, 2, 0, 5, 0], # Any\n ]\n anyState = 5\n finalStates = [ 3 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.charParser.Code.QUOTE: 0,\n self.charParser.Code.OSQRBK: 1,\n self.charParser.Code.CSQRBK: 2,\n self.charParser.Code.DIGIT: 3,\n self.charParser.Code.LETTER: 4\n }\n return self.validate(str, state, finalStates, deadStates, table, mySwitcher, self.charParser, debug, anyState)\n\n def isValidNumericConstant(self, str, debug = False):\n state = 1\n table = [\n # 0 1 2, 3, 4\n [0, 2, 2, 4, 4], # Digit\n [0, 3, 3, 0, 0], # dot\n [0, 0, 0, 0, 0], # Any\n ]\n anyState = 5\n finalStates = [ 2, 4 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.charParser.Code.DIGIT: 0,\n self.charParser.Code.DOT: 0,\n }\n return self.validate(str, state, finalStates, deadStates, table, mySwitcher, self.charParser, debug, anyState)\n\n def isValidCharacterConstant(self, str, debug = False):\n state = 1\n table = [\n # 0 1 2, 3, 4, 5, 6\n [0, 2, 3, 0, 5, 0, 3], # '\n [0, 0, 4, 0, 5, 0, 0], # [\n [0, 0, 0, 0, 0, 6, 0], # ]\n [0, 0, 6, 0, 0, 0, 0], # Digit\n [0, 0, 6, 0, 0, 0, 0], # Letter\n [0, 0, 6, 0, 5, 0, 0], # Any\n ]\n anyState = 5\n finalStates = [ 3 ]\n deadStates = [ 0 ]\n mySwitcher = {\n self.charParser.Code.SINGLE_QUOTE: 0,\n self.charParser.Code.OSQRBK: 1,\n self.charParser.Code.CSQRBK: 2,\n self.charParser.Code.DIGIT: 3,\n self.charParser.Code.LETTER: 4\n }\n return self.validate(str, state, finalStates, deadStates, table, mySwitcher, self.charParser, debug, anyState)\n\n def isValidBooleanConstant(self, str, debug = False):\n return str == \"FALSE\" or str == \"TRUE\"\n # KEYWORDS\n\n def isValidVAR(self, str):\n return str == \"VAR\"\n\n def isValidAS(self, str):\n return str == \"AS\"\n \n def isValidDataType(self, str):\n return self.isIntDataType(str) | self.isCharDataType(str) | self.isBoolDataType(str) | self.isFloatDataType(str)\n \n def isIntDataType(self, str):\n return str == \"INT\"\n \n def isCharDataType(self, str):\n return str == \"CHAR\"\n \n def isBoolDataType(self, str):\n return str == \"BOOL\"\n \n def isFloatDataType(self, str):\n return str == \"FLOAT\"\n \n def isStart(self, str):\n return str == \"START\"\n \n def isStop(self, str):\n return str == \"STOP\"\n\n def isOutput(self, str):\n return str == \"OUTPUT:\"\n\n def isInput(self, str):\n return str == \"INPUT:\"\n\n def isANDOperator(self, str):\n return str == \"AND\"\n\n def isOROperator(self, str):\n return str == \"OR\"\n \n def isNOTOperator(self, str):\n return str == \"NOT\"\n\n def isCommentOperator(self, str):\n if len(str) != 1:\n return False\n return self.charParser.isMultiplySign(str[0])\n\n def isArithmeticOperator(self, str):\n code = self.charParser.getCode(str)\n opSwitcher = {\n self.charParser.Code.PLUS: True,\n self.charParser.Code.MINUS: True,\n self.charParser.Code.DIVIDE: True,\n self.charParser.Code.MULTIPLY: True,\n self.charParser.Code.MODULO: True\n }\n # print(opSwitcher.get(code,False))\n return opSwitcher.get(code,False)\n\n def isBooleanOperator(self, str):\n code = self.charParser.getCode(str)\n opSwitcher = {\n self.charParser.Code.EQEQ: True,\n self.charParser.Code.LTEQ: True,\n self.charParser.Code.LT: True,\n self.charParser.Code.GT: True,\n self.charParser.Code.GTEQ: True,\n self.charParser.Code.AND: True,\n self.charParser.Code.OR: True\n }\n return opSwitcher.get(code,False)\n\n def isNewLine(self, str):\n return True if (len(str) == 1) & (self.charParser.getCode(str[0]) == self.charParser.Code.SHARP) else False\n\n def isConcatenator(self, str):\n return True if (len(str) == 1) & (self.charParser.getCode(str[0]) == self.charParser.Code.AMPERSAND) else False\n\n def isIF(self, str):\n return str == \"IF\"\n\n def removeGarbageFromArray(str, terms, strip = True):\n terms = [x for x in terms if x is not None]\n terms = [x for x in terms if x is not ' ']\n terms = [x for x in terms if x is not '']\n if(strip):\n terms = [x.strip() for x in terms]\n return terms\n\n\n def isKeyWord(self, str):\n code = self.getCode(str)\n mySwitcher = {\n self.Code.VAR: 0,\n self.Code.AS: 1,\n self.Code.START: 2,\n self.Code.STOP: 3,\n self.Code.DATA_TYPE: 4,\n self.Code.OUTPUT: 5\n }\n code = mySwitcher.get(code, -1)\n return code != -1\n\n def getCode(self, str):\n # KEYWORDS\n if(self.isValidVAR(str)):\n return self.Code.VAR\n if(self.isValidAS(str)):\n return self.Code.AS\n if(self.isStart(str)):\n return self.Code.START\n if(self.isStop(str)):\n return self.Code.STOP\n if(self.isValidDataType(str)):\n return self.Code.DATA_TYPE\n if(self.isOutput(str)):\n return self.Code.OUTPUT\n if(self.isInput(str)):\n return self.Code.INPUT\n if(self.isIF(str)):\n return self.Code.IF\n if(self.isELSE(str)):\n return self.Code.ELSE\n # Dynamice\n if(self.isValidIdentifier(str)):\n return self.Code.IDENTIFIER\n if(self.isValidStringConstant(str)):\n return self.Code.STRING_CONST\n if(self.isValidNumericConstant(str)):\n return self.Code.NUMERIC_CONST\n if(self.isValidBooleanConstant(str)):\n return self.Code.BOOLEAN_CONST\n if(self.isValidCharacterConstant(str)):\n return self.Code.CHARACTER_CONST\n # characters\n if(self.charParser.isEqualSign(str)):\n return self.Code.EQUAL\n if(self.charParser.isComma(str)):\n return self.Code.COMMA\n if(self.isCommentOperator(str)):\n return self.Code.COMMENT_OP\n if(self.isConcatenator(str)):\n return self.Code.CONCATENATOR\n if(self.isNewLine(str)):\n return self.Code.NEWLINE\n if(self.isArithmeticOperator(str)):\n return self.Code.ARITHMETIC_OP\n return self.Code.ERROR\n","sub_path":"interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":19009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"146046870","text":"import unittest\n\nfrom classes_and_instances.exe.pizza_delivery import PizzaDelivery\n\n\nclass Tests(unittest.TestCase):\n def test_init(self):\n t = PizzaDelivery('Margarita', 12, {'cheese': 2, 'tomatoes': 1})\n self.assertEqual(t.name, 'Margarita')\n self.assertEqual(t.price, 12)\n self.assertEqual(t.ingredients, {'cheese': 2, 'tomatoes': 1})\n self.assertEqual(t.ordered, False)\n\n def test_add_extra_with_available_ingredient_should_increase_the_quantity(self):\n t = PizzaDelivery('Margarita', 12, {'cheese': 2, 'tomatoes': 1})\n t.add_extra('cheese', 1, 2)\n self.assertEqual(t.ingredients, {'cheese': 3, 'tomatoes': 1})\n self.assertEqual(t.price, 14)\n\n def test_add_extra_with_new_ingredient_should_add_the_quantity(self):\n t = PizzaDelivery('Margarita', 12, {'cheese': 2, 'tomatoes': 1})\n t.add_extra('mozzarella', 1, 2.5)\n self.assertEqual(t.ingredients, {'cheese': 2, 'tomatoes': 1, 'mozzarella': 1})\n self.assertEqual(t.price, 14.5)\n\n def test_remove_ingredients_not_included_in_pizza_should_return_message(self):\n t = PizzaDelivery('Margarita', 12, {'cheese': 2, 'tomatoes': 1})\n message = t.remove_ingredient('bacon', 1, 5)\n self.assertEqual(t.ingredients, {'cheese': 2, 'tomatoes': 1})\n self.assertEqual(message, 'Wrong ingredient selected! We do not use bacon in Margarita!')\n\n def test_remove_ingredients_with_quantity_higher_than_what_we_have_should_return_message(self):\n t = PizzaDelivery('Margarita', 12, {'cheese': 2, 'tomatoes': 1})\n message = t.remove_ingredient('tomatoes', 2, 2)\n self.assertEqual(t.ingredients, {'cheese': 2, 'tomatoes': 1})\n self.assertEqual(message, 'Please check again the desired quantity of tomatoes!')\n\n def test_remove_ingredients_with_quantity_equal_to_what_we_have_should_remove_the_ingredient(self):\n t = PizzaDelivery('Margarita', 12, {'cheese': 2, 'tomatoes': 1})\n t.remove_ingredient('tomatoes', 1, 2)\n self.assertEqual(t.ingredients, {'cheese': 2, 'tomatoes': 0})\n self.assertEqual(t.price, 10)\n\n def test_pizza_ordered(self):\n t = PizzaDelivery('Margarita', 12, {'cheese': 2, 'tomatoes': 1})\n result = t.make_order()\n self.assertEqual(t.ordered, True)\n self.assertEqual(result,\n \"You've ordered pizza Margarita prepared with cheese: 2, tomatoes: 1 and the price will be 12lv.\")\n\n def test_add_extra_after_pizza_is_ordered_should_return_message(self):\n t = PizzaDelivery('Margarita', 12, {'cheese': 2, 'tomatoes': 1})\n order = t.make_order()\n result = t.add_extra('mozzarella', 1, 2)\n self.assertEqual(order,\n \"You've ordered pizza Margarita prepared with cheese: 2, tomatoes: 1 and the price will be 12lv.\")\n self.assertEqual(result, \"Pizza Margarita already prepared and we can't make any changes!\")\n\n def test_remove_ingredient_after_pizza_is_ordered_should_return_message(self):\n t = PizzaDelivery('Margarita', 12, {'cheese': 2, 'tomatoes': 1})\n order = t.make_order()\n result = t.remove_ingredient('mozzarella', 1, 2)\n self.assertEqual(order,\n \"You've ordered pizza Margarita prepared with cheese: 2, tomatoes: 1 and the price will be 12lv.\")\n self.assertEqual(result, \"Pizza Margarita already prepared and we can't make any changes!\")\n\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"classes_and_instances/exe/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"333473880","text":"#!/usr/bin/python3\n#date: 12/09/2020\n'''\nConsumption\n\nCalculate a car's average consumption being provided the total distance traveled (in Km)\n and the spent fuel total (in liters).\n\nInput: The input file contains two values: one integer value X representing the total\n distance (in Km) and the second one is a floating point number Y representing the\n spent fuel total, with a digit after the decimal point.\n\nOutput: Present a value that represents the average consumption of a car with 3 digits\n after the decimal point, followed by the message \"km/l\".\n'''\n\ndef main():\n\t#If spent_fuel is given in km/l, then it's just divide the total distance per the spent fuel.\n\tt_distance = int(input())\n\tspent_fuel = float(input())\n\n\taverage_con = t_distance/spent_fuel\n\n\treturn print(\"{:.3f} km/l\".format(average_con))\nif __name__ == '__main__':\n\tmain()","sub_path":"URI-VOAL/1014.py","file_name":"1014.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"28472809","text":"# -*- coding: utf-8 -*-\n\"\"\"----------------------------------------------------------------------------\nAuthor:\n Huang Quanyong (wo1fSea)\n quanyongh@foxmail.com\nDate:\n 2017/11/12\nDescription:\n async_test.py\n----------------------------------------------------------------------------\"\"\"\n\nimport asyncio\nimport time\n\n\nasync def slow_operation(n):\n await asyncio.sleep(1)\n print(\"Slow operation {} complete\".format(n))\n\n\nasync def main():\n start = time.time()\n await asyncio.wait([slow_operation(1),\n slow_operation(2),\n slow_operation(3),\n ])\n end = time.time()\n print('Complete in {} second(s)'.format(end - start))\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(main())\n","sub_path":"async_test.py","file_name":"async_test.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"314545623","text":"from rest_framework.reverse import reverse\nfrom rest_framework.test import APITestCase\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework import status\n\nfrom core.models import (User, Group, Community, Chat,\n Message, ChatInvitation, GroupInvitation)\n\n\nclass TestUserAssociationWithJoinableFromUrls(APITestCase):\n \"\"\"User being associated with the entities she\n creates.\"\"\"\n\n def setUp(self):\n User.objects.create_user('test1', 'test1@test.t', 'test1')\n\n u = User.objects.create_user('user1', 'user1@test.t', 'user1')\n c = Community.objects.create(name='community1')\n g = Group.objects.create(name='group1', community=c)\n c = Chat.objects.create(name='group_chat1', group=g)\n Message.objects.create(content='test', sender=u,\n chat=c)\n self.user = User.objects.get(username='user1')\n self.token = Token.objects.get(user=self.user).key\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)\n\n def test_add_group_tied_to_user(self):\n \"\"\"Creates a group that has as only member the user\n that created it.\n \"\"\"\n url = reverse('group-list')\n community = Community.objects.first()\n community_link = '/communities/%d/' % community.id\n self.client.post(url, data={'name': 'group_test',\n 'community': community_link})\n group = Group.objects.get(name='group_test')\n self.assertTrue(group.users.filter(id=self.user.id).exists())\n\n def test_add_chat_tied_to_user(self):\n \"\"\"Creates a group chat that has as only member the\n user who create it.\n \"\"\"\n url = reverse('chat-list')\n group = Group.objects.first()\n group_url = '/groups/%d/' % group.id\n self.client.post(url,\n data={'name': 'group_chat_test',\n 'group': group_url})\n chat = self.user.chats.filter(name='group_chat_test')\n self.assertTrue(chat.exists())\n\n def test_add_message_with_sender(self):\n \"\"\"Creates a message that has as sender the\n user who create it.\n \"\"\"\n url = reverse('message-list')\n chat = Chat.objects.first()\n chat_url = '/chats/%d/' % chat.id\n self.client.post(url,\n data={'chat': chat_url,\n 'content': 'test'})\n message = Message.objects.filter(sender=self.user)\n self.assertTrue(message)\n\n def test_add_group_invitation_tied_to_user(self):\n \"\"\"Creates a group invitation that has as\n inviter the user who created it.\n \"\"\"\n url = reverse('groupinvitation-list')\n group = Group.objects.first()\n invitee = User.objects.get(username='test1')\n data = {\n 'group': '/groups/%d/' % group.id,\n 'invitee': '/users/%d/' % invitee.id\n }\n response = self.client.post(url, data=data)\n group_invitation = GroupInvitation.objects.filter(inviter=self.user)\n self.assertEquals(response.status_code, 201)\n self.assertTrue(group_invitation.exists())\n\n def test_add_chat_invitation_tied_to_user(self):\n \"\"\"Creates a chat invitation that has as\n inviter the user who created it.\n \"\"\"\n url = reverse('chatinvitation-list')\n chat = Chat.objects.first()\n invitee = User.objects.get(username='test1')\n data = {\n 'chat': '/chats/%d/' % chat.id,\n 'invitee': '/users/%d/' % invitee.id\n }\n response = self.client.post(url, data=data)\n chat_invitation = ChatInvitation.objects.filter(inviter=self.user)\n self.assertEquals(response.status_code, 201)\n self.assertTrue(chat_invitation.exists())\n\n\nclass TestFilterEntitiesByLoggedUser(APITestCase):\n \"\"\"Only the entities associated with the current user\n are returned.\n \"\"\"\n\n def setUp(self):\n tu1 = User.objects.create_user('test1', 'test1@test.t', 'test1')\n tu2 = User.objects.create_user('test2', 'test2@test.t', 'test2')\n # tu3 = User.objects.create_user('test3', 'test2@test.t', 'test3')\n\n u = User.objects.create_user('user1', 'user1@test.t', 'user1')\n c = Community.objects.create(name='community1')\n c.users.add(u, tu1, tu2)\n g = Group.objects.create(name='group1', community=c)\n self.c = c\n c = Chat.objects.create(name='group_chat1', group=g)\n c.users.add(u, tu1, tu2)\n Message.objects.create(content='test', sender=u,\n chat=c)\n self.user = User.objects.get(username='user1')\n print(self.user)\n self.token = Token.objects.get(user=self.user).key\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)\n\n def test_get_communities_of_logged_user(self):\n \"\"\"Returns communities of the logged user\"\"\"\n response = self.client.get('/communities/')\n communities_response = [x['url'] for x in response.data['results']]\n communities_user = ['http://testserver/communities/%d/' % x.id\n for x in self.user.communities.all()]\n self.assertListEqual(communities_response, communities_user)\n\n def test_groups_of_logged_user(self):\n \"\"\"Returns groups of the logged user.\"\"\"\n url_c = reverse('community-list') + '%d/'\n for i in range(3):\n with self.subTest(i=i):\n data = {'name': 'group_test%d' % i,\n 'community': url_c % self.c.id}\n response = self.client.post('/groups/', data=data)\n self.assertEquals(response.status_code, 201)\n\n response = self.client.get('/groups/')\n groups_response = [x['url'] for x in response.data['results']]\n groups_user = ['http://testserver/groups/%d/' % x.id\n for x in self.user.c_groups.all()]\n self.assertListEqual(groups_response, groups_user)\n\n\nclass TestChatAcceptRejectInvitation(APITestCase):\n \"\"\"Mechanics for accepting and rejecting invitations. Due\n to the fact that GroupInvitation and ChatInvitation share\n a lot of behavior, only the latter class is tested. The former,\n by extension, is assumed to be correct.\n \"\"\"\n\n def setUp(self):\n User.objects.create_user('test1', 't@t.t', 'test1')\n c = Chat.objects.create(name='chat1')\n self.user = User.objects.create_user('user1', 'u@u.u', 'user1')\n token = Token.objects.get(user=self.user).key\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + token)\n self.invitee = User.objects.get(username='test1')\n self.invitation = ChatInvitation.objects.create(\n inviter=self.user,\n invitee=self.invitee,\n chat=c)\n\n def perform_action(self, action, token):\n \"\"\"Performs the given action to an invitation.\n\n :param action: action taken with respect to the invitation.\n (accept/reject and invitation).\n :type action: str.\n \"\"\"\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + token)\n response = self.client.post('/chatinvitations/%d/%s/' %\n (self.invitation.id, action))\n return (response, self.invitee.received_chatinvitations.get(\n id=self.invitation.id))\n\n def perform_action_by_invitee(self, action):\n \"\"\"Performs the given action by the invitee. This\n uses the `perform_action` method and sets the auth\n token for the invitee user.\n \"\"\"\n token = Token.objects.get(user=self.invitee).key\n response, invitation = self.perform_action(action, token)\n self.assertEquals(response.status_code, status.HTTP_200_OK)\n return invitation\n\n def test_accept_invitation(self):\n \"\"\"Invitee accepts the invitation\"\"\"\n invitation = self.perform_action_by_invitee('accept')\n self.assertTrue(invitation.accepted)\n self.assertIn(self.invitation.chat, self.invitee.chats.all())\n\n def test_reject_invitation(self):\n \"\"\"User does not accept the invitation\"\"\"\n invitation = self.perform_action_by_invitee('reject')\n self.assertFalse(invitation.accepted)\n self.assertNotIn(self.invitation.chat, self.invitee.chats.all())\n\n def test_wrong_user_accepts(self):\n \"\"\"Wrong user accepts the invitation\"\"\"\n token = Token.objects.get(user__username='user1').key\n response, invitation = self.perform_action('accept', token)\n self.assertEquals(response.status_code, status.HTTP_403_FORBIDDEN)\n\n\nclass TestSentReceivedChatInvitations(APITestCase):\n \"\"\"Tests views for gettting the invitations that a user has\n sent and received. Same as before, we only test `ChatInvitation`\"\"\"\n\n def setUp(self):\n \"\"\"Create 3 users, u1, u2 and u3. Each one of these is going\n to send 2 invitations to the other two, so in total, every\n user will have 2 sent invitations and 2 received invitations.\"\"\"\n self.u1 = User.objects.create_user('u1', 'u1@u1.u1', 'u1')\n self.u2 = User.objects.create_user('u2', 'u2@u2.u2', 'u1')\n c = Chat.objects.create(name='c1')\n ChatInvitation.objects.create(\n inviter=self.u1,\n invitee=self.u2,\n chat=c\n )\n\n def check_invitations(self, user, type_):\n \"\"\"Checks that the specific type of invitations belong to\n the user.\"\"\"\n t = Token.objects.get(user=user).key\n should_be = ['http://testserver/chatinvitations/1/']\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + t)\n response = self.client.get('/chatinvitations/%s/' % type_)\n self.assertEquals(response.status_code, status.HTTP_200_OK)\n received = [x['url'] for x in response.data['results']]\n self.assertListEqual(should_be, received)\n\n def test_sent_invitations(self):\n \"\"\"User sees received invitations.\"\"\"\n self.check_invitations(self.u1, 'sent')\n\n def test_received_invitations(self):\n \"\"\"User sees sent invitations.\"\"\"\n self.check_invitations(self.u2, 'received')\n","sub_path":"core/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":10234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"492707325","text":"#!/anaconda3/bin/python\n\nimport sys\n\nclass Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if not matrix or not matrix[0]:\n return False\n m = len(matrix)\n n = len(matrix[0])\n up = 0\n down = m - 1\n left = 0\n right = n - 1\n flag = 0\n while up <= down:\n mid = (up + down) // 2\n if matrix[mid][0] <= target <= matrix[mid][right]:\n flag = 1\n break\n if target < matrix[mid][0]:\n down = mid - 1\n elif target > matrix[mid][right]:\n up = mid + 1\n if flag == 0:\n return False\n while left <= right:\n m = (left + right) // 2\n if matrix[mid][m] == target:\n return True\n if matrix[mid][m] < target:\n left = m + 1\n elif matrix[mid][m] > target:\n right = m - 1\n return False\n\nif __name__ == \"__main__\":\n a = Solution()\n matrix = [[]]\n target = 13\n print(a.searchMatrix(matrix, target))\n","sub_path":"q74.py","file_name":"q74.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"2185070","text":"import autograd.numpy as np\n\nfrom .component import Component, ComponentTree\nfrom . import operator\nfrom . import update\nfrom .interpolation import get_projection_slices\nfrom .observation import LowResObservation\n\nimport logging\n\nlogger = logging.getLogger(\"scarlet.source\")\n\n\nclass SourceInitError(Exception):\n \"\"\"Error during source initialization\n \"\"\"\n pass\n\n\ndef get_pixel_sed(sky_coord, observations):\n \"\"\"Get the SED at `position` in `img`\n\n Parameters\n ----------\n sky_coord: tuple\n Center of the source\n scene: `scarlet.observation.Scene`\n The scene that the model lives in.\n observations: list of `~scarlet.observation.Observation`\n Observations to extract SED from.\n\n Returns\n -------\n SED: `~numpy.array`\n SED for a single source\n \"\"\"\n\n sed = []\n band = 0\n for obs in observations:\n pixel = obs.get_pixel(sky_coord)\n\n sed = np.concatenate((sed, obs.images[:, np.int(pixel[0]), np.int(pixel[1])]))\n\n band += obs.B\n\n if np.all(sed[-1] <= 0):\n # If the flux in all bands is <=0,\n # the new sed will be filled with NaN values,\n # which will cause the code to crash later\n msg = \"Zero or negative flux at y={0}, x={1}\"\n raise SourceInitError(msg.format(*sky_coord))\n\n sed = np.array(sed)\n\n return sed.reshape(-1)\n\n\ndef get_scene_sed(sky_coord, observations):\n \"\"\"Get the SED at `position` in `img` in the scene. Function made for combined resolution images.\n\n\n Parameters\n ----------\n sky_coord: tuple\n Center of the source\n scene: `scarlet.observation.Scene`\n The scene that the model lives in.\n observations: list of `~scarlet.observation.Observation`\n Observations to extract SED from.\n\n Returns\n -------\n SED: `~numpy.array`\n SED for a single source\n \"\"\"\n\n sed = []\n band = 0\n for obs in observations:\n pixel = obs.get_pixel(sky_coord)\n sed.append(obs.images[:, np.int(pixel[0]), np.int(pixel[1])])\n band += obs.B\n sed = np.array(sed)\n if np.all(sed <= 0):\n # If the flux in all bands is <=0,\n # the new sed will be filled with NaN values,\n # which will cause the code to crash later\n msg = \"Zero or negative flux at y={0}, x={1}\"\n raise SourceInitError(msg.format(*sky_coord))\n return sed.reshape(-1)\n\n\ndef get_best_fit_seds(morphs, scene, observations):\n \"\"\"Calculate best fitting SED for multiple components.\n\n Solves min_A ||img - AS||^2 for the SED matrix A,\n assuming that the images only contain a single source.\n\n Parameters\n ----------\n morphs: list\n Morphology for each component in the source.\n scene: `scarlet.observation.Scene`\n The scene that the model lives in.\n observations: list of `~scarlet.observation.Observation`\n Observations to extract SEDs from.\n \"\"\"\n K = len(morphs)\n seds = np.zeros((K, scene.B), dtype=observations[0].images.dtype)\n band = 0\n _morph = morphs.reshape(K, -1)\n for obs in observations:\n images = obs.images\n data = images.reshape(obs.B, -1)\n sed = np.dot(np.linalg.inv(np.dot(_morph, _morph.T)), np.dot(_morph, data.T))\n seds[:, band:band + obs.B] = sed\n return seds\n\n\ndef build_detection_coadd(sed, bg_rms, observations, scene, thresh=1):\n \"\"\"Build a band weighted coadd to use for source detection\n\n Parameters\n ----------\n sed: array\n SED at the center of the source.\n bg_rms: array\n Background RMS in each band in observation.\n observation: `~scarlet.observation.Observation`\n Observation to use for the coadd.\n scene: `scarlet.observation.Scene`\n The scene that the model lives in.\n thresh: `float`\n Multiple of the backround RMS used as a\n flux cutoff.\n\n Returns\n -------\n detect: array\n 2D image created by weighting all of the bands by SED\n bg_cutoff: float\n The minimum value in `detect` to include in detection.\n \"\"\"\n B = scene.B\n\n weights = np.array([sed[b] / bg_rms[b] ** 2 for b in range(B)])\n jacobian = np.array([sed[b] ** 2 / bg_rms[b] ** 2 for b in range(B)]).sum()\n detect = np.einsum('i,i...', weights, observations.images) / jacobian\n\n # thresh is multiple above the rms of detect (weighted variance across bands)\n bg_cutoff = thresh * np.sqrt((weights ** 2 * bg_rms ** 2).sum()) / jacobian\n return detect, bg_cutoff\n\n\ndef init_extended_source(sky_coord, scene, observations, bg_rms, obs_idx=0,\n thresh=1., symmetric=True, monotonic=True):\n \"\"\"Initialize the source that is symmetric and monotonic\n See `ExtendedSource` for a description of the parameters\n \"\"\"\n try:\n iter(observations)\n except TypeError:\n observations = [observations]\n # determine initial SED from peak position\n sed = get_pixel_sed(sky_coord, observations) # amplitude is in sed\n\n morph, bg_cutoff = build_detection_coadd(sed, bg_rms, observations[obs_idx], scene, thresh)\n center = scene.get_pixel(sky_coord)\n\n # Apply the necessary constraints\n if symmetric:\n morph = operator.prox_uncentered_symmetry(morph, 0, center=center, use_soft=False)\n if monotonic:\n # use finite thresh to remove flat bridges\n prox_monotonic = operator.prox_strict_monotonic(morph.shape, use_nearest=False,\n center=center, thresh=.1)\n morph = prox_monotonic(morph, 0).reshape(morph.shape)\n\n # trim morph to pixels above threshold\n mask = morph > bg_cutoff\n if mask.sum() == 0:\n msg = \"No flux above threshold={2} for source at y={0} x={1}\"\n raise SourceInitError(msg.format(*sky_coord, bg_cutoff))\n morph[~mask] = 0\n\n # normalize to unity at peak pixel\n cy, cx = center\n center_morph = morph[cy, cx]\n morph /= center_morph\n return sed, morph\n\n\ndef init_combined_extended_source(sky_coord, scene, observations, bg_rms, obs_idx=0,\n thresh=1., symmetric=True, monotonic=True):\n \"\"\"Initialize the source that is symmetric and monotonic\n See `ExtendedSource` for a description of the parameters\n \"\"\"\n try:\n iter(observations)\n except TypeError:\n observations = [observations]\n\n # determine initial SED from peak position\n # SED in the scene for source detection\n\n sed = get_pixel_sed(sky_coord, observations)\n\n morph, bg_cutoff = build_detection_coadd(sed, bg_rms, observations[obs_idx], scene, thresh) # amplitude is in sed\n\n center = scene.get_pixel(sky_coord)\n\n # Apply the necessary constraints\n if symmetric:\n morph = operator.prox_uncentered_symmetry(morph, 0, center=center, use_soft=False)\n\n if monotonic:\n # use finite thresh to remove flat bridges\n prox_monotonic = operator.prox_strict_monotonic(morph.shape, use_nearest=False,\n center=center, thresh=.1)\n morph = prox_monotonic(morph, 0).reshape(morph.shape)\n\n # trim morph to pixels above threshold\n mask = morph > bg_cutoff\n if mask.sum() == 0:\n msg = \"No flux above threshold={2} for source at y={0} x={1}\"\n raise SourceInitError(msg.format(*center, bg_cutoff))\n morph[~mask] = 0\n\n # normalize to unity at peak pixel\n cy, cx = center\n\n center_morph = morph[np.int(cy), np.int(cx)]\n morph /= center_morph\n return sed, morph\n\n\ndef init_multicomponent_source(sky_coord, scene, observations, bg_rms, flux_percentiles=None, obs_idx=0,\n thresh=1., symmetric=True, monotonic=True):\n \"\"\"Initialize multiple components\n See `MultiComponentSource` for a description of the parameters\n \"\"\"\n try:\n iter(observations)\n except TypeError:\n observations = [observations]\n\n if flux_percentiles is None:\n flux_percentiles = [25]\n # Initialize the first component as an extended source\n sed, morph = init_extended_source(sky_coord, scene, observations, bg_rms, obs_idx,\n thresh, symmetric, monotonic)\n # create a list of components from base morph by layering them on top of\n # each other so that they sum up to morph\n K = len(flux_percentiles) + 1\n\n Ny, Nx = morph.shape\n morphs = np.zeros((K, Ny, Nx), dtype=morph.dtype)\n morphs[0, :, :] = morph[:, :]\n max_flux = morph.max()\n percentiles_ = np.sort(flux_percentiles)\n last_thresh = 0\n for k in range(1, K):\n perc = percentiles_[k - 1]\n flux_thresh = perc * max_flux / 100\n mask_ = morph > flux_thresh\n morphs[k - 1][mask_] = flux_thresh - last_thresh\n morphs[k][mask_] = morph[mask_] - flux_thresh\n last_thresh = flux_thresh\n\n # renormalize morphs: initially Smax\n for k in range(K):\n morphs[k] /= morphs[k].max()\n\n # optimal SEDs given the morphologies, assuming img only has that source\n seds = get_best_fit_seds(morphs, scene, observations)\n\n return seds, morphs\n\n\nclass PointSource(Component):\n \"\"\"Extended source intialized with a single pixel\n\n Point sources are initialized with the SED of the center pixel,\n and the morphology of a single pixel (the center) turned on.\n While the source can have any `constraints`, the default constraints are\n symmetry and monotonicity.\n\n Parameters\n ----------\n sky_coord: tuple\n Center of the source\n scene: `scarlet.observation.Scene`\n The scene that the model lives in.\n observations: list of `~scarlet.observation.Observation`\n Observations to extract SED from.\n symmetric: bool\n Whether or not the object is forced to be symmetric\n monotonic: bool\n Whether or not the object is forced to be monotonically decreasing\n center_step: int\n Number of steps to skip between centering routines\n delay_thresh: int\n Number of steps to skip before turning on thresholding.\n This is useful for point sources because it allows them to grow\n slightly before removing pixels with low significance.\n component_kwargs: dict\n Keyword arguments to pass to the component initialization.\n \"\"\"\n\n def __init__(self, sky_coord, scene, observations, symmetric=False, monotonic=True,\n center_step=5, delay_thresh=10, **component_kwargs):\n try:\n iter(observations)\n except TypeError:\n observations = [observations]\n # this ignores any broadening from the PSFs ...\n B, Ny, Nx = scene.shape\n morph = np.zeros((Ny, Nx), observations[0].images.dtype)\n pixel = scene.get_pixel(sky_coord)\n if scene.psfs is None:\n # Use a single pixel if there is no target PSF\n morph[pixel] = 1\n else:\n # A point source is a function of the target PSF\n assert len(scene.psfs.shape) == 2\n py, px = pixel\n sy, sx = (np.array(scene.psfs.shape) - 1) // 2\n cy, cx = (np.array(morph.shape) - 1) // 2\n yx0 = py - cy - sy, px - cx - sx\n bb, ibb, _ = get_projection_slices(scene.psfs, morph.shape, yx0)\n morph[bb] = scene.psfs[ibb]\n\n self.pixel_center = pixel\n\n sed = np.zeros((B,), observations[0].images.dtype)\n b0 = 0\n for obs in observations:\n pixel = obs.get_pixel(sky_coord)\n sed[b0:b0 + obs.B] = obs.images[:, pixel[0], pixel[1]]\n b0 += obs.B\n\n super().__init__(sed, morph, **component_kwargs)\n self.symmetric = symmetric\n self.monotonic = monotonic\n self.center_step = center_step\n self.delay_thresh = delay_thresh\n\n def update(self):\n \"\"\"Default update parameters for an ExtendedSource\n\n This method can be overwritten if a different set of constraints\n or update functions is desired.\n \"\"\"\n it = self._parent.it\n # Update the central pixel location (pixel_center)\n update.fit_pixel_center(self)\n if it > self.delay_thresh:\n update.threshold(self)\n\n if self.symmetric:\n # Translate to the centered frame\n update.translation(self, 1)\n # make the morphology perfectly symmetric\n update.symmetric(self, strength=1)\n # Translate back to the model frame\n update.translation(self, -1)\n\n if self.monotonic:\n # make the morphology monotonically decreasing\n if hasattr(self, \"bboxes\") and \"thresh\" in self.bboxes:\n update.monotonic(self, self.pixel_center, bbox=self.bboxes[\"thresh\"])\n else:\n update.monotonic(self, self.pixel_center)\n\n update.positive(self) # Make the SED and morph non-negative\n update.normalized(self) # Use MORPH_MAX normalization\n return self\n\n\nclass ExtendedSource(PointSource):\n \"\"\"Extended source intialized to match a set of observations\n\n Parameters\n ----------\n sky_coord: tuple\n Center of the source\n scene: `scarlet.observation.Scene`\n The scene that the model lives in.\n observations: list of `~scarlet.observation.Observation`\n Observations to extract SED from.\n bg_rms: array\n Background RMS in each band in observation.\n obs_idx: int\n Index of the observation in `observations` to use for\n initializing the morphology.\n thresh: `float`\n Multiple of the backround RMS used as a\n flux cutoff for morphology initialization.\n symmetric: `bool`\n Whether or not to enforce symmetry.\n monotonic: `bool`\n Whether or not to make the object monotonically decrease\n in flux from the center.\n component_kwargs: dict\n Keyword arguments to pass to the component initialization.\n \"\"\"\n\n def __init__(self, sky_coord, scene, observations, bg_rms, obs_idx=0, thresh=1,\n symmetric=False, monotonic=True, center_step=5, delay_thresh=0, **component_kwargs):\n self.symmetric = symmetric\n self.monotonic = monotonic\n self.coords = sky_coord\n center = scene.get_pixel(sky_coord)\n self.pixel_center = center\n self.center_step = center_step\n self.delay_thresh = delay_thresh\n\n sed, morph = init_extended_source(sky_coord, scene, observations, bg_rms, obs_idx,\n thresh, True, monotonic)\n\n Component.__init__(self, sed, morph, **component_kwargs)\n\n\nclass CombinedExtendedSource(PointSource):\n \"\"\"Extended source intialized to match a set of observations\n\n Parameters\n ----------\n sky_coord: tuple\n Center of the source\n scene: `scarlet.observation.Scene`\n The scene that the model lives in.\n observations: list of `~scarlet.observation.Observation`\n Observations to extract SED from.\n bg_rms: array\n Background RMS in each band in observation.\n obs_idx: int\n Index of the observation in `observations` to use for\n initializing the morphology.\n thresh: `float`\n Multiple of the backround RMS used as a\n flux cutoff for morphology initialization.\n symmetric: `bool`\n Whether or not to enforce symmetry.\n monotonic: `bool`\n Whether or not to make the object monotonically decrease\n in flux from the center.\n component_kwargs: dict\n Keyword arguments to pass to the component initialization.\n \"\"\"\n\n def __init__(self, sky_coord, scene, observations, bg_rms, obs_idx=0, thresh=1,\n symmetric=False, monotonic=True, center_step=5, delay_thresh=0, **component_kwargs):\n self.symmetric = symmetric\n self.monotonic = monotonic\n self.coords = sky_coord\n center = scene.get_pixel(sky_coord)\n self.pixel_center = center\n self.center_step = center_step\n self.delay_thresh = delay_thresh\n\n sed, morph = init_combined_extended_source(sky_coord, scene, observations, bg_rms, obs_idx,\n thresh, True, monotonic)\n\n Component.__init__(self, sed, morph, **component_kwargs)\n\n\nclass MultiComponentSource(ComponentTree):\n \"\"\"Create an extended source with multiple components layered vertically.\n Uses `~scarlet.source.ExtendedSource` to define the overall morphology,\n then erodes the outer footprint until it reaches the specified size percentile.\n For the narrower footprint, it evaluates the mean value at the perimeter and\n sets the inside to the perimeter value, creating a flat distribution inside.\n The subsequent component(s) is/are set to the difference between the flattened\n and the overall morphology.\n The SED for all components is calculated as the best fit of the multi-component\n morphology to the multi-band image in the region of the source.\n\n Parameters\n ----------\n flux_percentiles: list\n The flux percentile of each component. If `flux_percentiles` is `None`\n then `flux_percentiles=[25]`, a single component with 25% of the flux\n as the primary source.\n\n See `ExtendedSource` for a description of the parameters\n \"\"\"\n\n def __init__(self, sky_coord, scene, observations, bg_rms, flux_percentiles=None, obs_idx=0, thresh=1,\n symmetric=True, monotonic=True, **component_kwargs):\n seds, morphs = init_multicomponent_source(sky_coord, scene, observations, bg_rms, flux_percentiles,\n obs_idx, thresh, symmetric, monotonic)\n\n class MultiComponent(Component):\n def __init__(self, sed, morph, symmetric, monotonic, **kwargs):\n self.symmetric = symmetric\n self.monotonic = monotonic\n super().__init__(sed, morph, **kwargs)\n\n def update(self):\n if self.symmetric:\n update.symmetric_fit_center(self) # update the center position\n center = self.coords\n update.symmetric(self, center) # make the morph perfectly symmetric\n elif self.monotonic:\n update.fit_pixel_center(self)\n center = self.pixel_center\n if self.monotonic:\n update.monotonic(self, center) # make the morph monotonically decreasing\n update.positive(self) # Make the SED and morph non-negative\n update.normalized(self, type='morph_max')\n return self\n\n components = [\n MultiComponent(seds[k], morphs[k], symmetric, monotonic, **component_kwargs)\n for k in range(len(seds))\n ]\n super().__init__(components)\n","sub_path":"scarlet/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":18811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"354203410","text":"# -*- coding: utf-8 -*-\n# Copyright 2015 OpenMarket 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.\nfrom .api import MatrixHttpApi, MatrixRequestError\nfrom threading import Thread\nimport sys\n# TODO: Finish implementing this.\n\n\nclass MatrixClient(object):\n \"\"\" WORK IN PROGRESS\n The client API for Matrix. For the raw HTTP calls, see MatrixHttpApi.\n\n Usage (new user):\n client = MatrixClient(\"https://matrix.org\")\n token = client.register_with_password(username=\"foobar\",\n password=\"monkey\")\n room = client.create_room(\"myroom\")\n room.send_image(file_like_object)\n\n Usage (logged in):\n client = MatrixClient(\"https://matrix.org\", token=\"foobar\")\n rooms = client.get_rooms() # NB: From initial sync\n client.add_listener(func) # NB: event stream callback\n rooms[0].add_listener(func) # NB: callbacks just for this room.\n room = client.join_room(\"#matrix:matrix.org\")\n response = room.send_text(\"Hello!\")\n response = room.kick(\"@bob:matrix.org\")\n\n Incoming event callbacks (scopes):\n\n def user_callback(user, incoming_event):\n pass\n\n def room_callback(room, incoming_event):\n pass\n\n def global_callback(incoming_event):\n pass\n\n \"\"\"\n\n def __init__(self, base_url, token=None, valid_cert_check=True):\n self.api = MatrixHttpApi(base_url, token)\n self.api.validate_certificate(valid_cert_check)\n self.listeners = []\n self.rooms = {\n # room_id: Room\n }\n if token:\n self._sync()\n\n def register_with_password(self, username, password, limit=1):\n response = self.api.register(\n \"m.login.password\", user=username, password=password\n )\n self.user_id = response[\"user_id\"]\n self.token = response[\"access_token\"]\n self.hs = response[\"home_server\"]\n self.api.token = self.token\n self._sync(limit)\n return self.token\n\n def login_with_password(self, username, password, limit=1):\n response = self.api.login(\n \"m.login.password\", user=username, password=password\n )\n self.user_id = response[\"user_id\"]\n self.token = response[\"access_token\"]\n self.hs = response[\"home_server\"]\n self.api.token = self.token\n self._sync(limit)\n return self.token\n\n def create_room(self, alias=None, is_public=False, invitees=()):\n response = self.api.create_room(alias, is_public, invitees)\n return self._mkroom(response[\"room_id\"])\n\n def join_room(self, room_id_or_alias):\n response = self.api.join_room(room_id_or_alias)\n room_id = (\n response[\"room_id\"] if \"room_id\" in response else room_id_or_alias\n )\n return self._mkroom(room_id)\n\n def get_rooms(self):\n return self.rooms\n\n def add_listener(self, callback):\n self.listeners.append(callback)\n\n def listen_for_events(self, timeout=30000):\n response = self.api.event_stream(self.end, timeout)\n self.end = response[\"end\"]\n\n for chunk in response[\"chunk\"]:\n for listener in self.listeners:\n listener(chunk)\n if \"room_id\" in chunk:\n if chunk[\"room_id\"] not in self.rooms:\n self._mkroom(chunk[\"room_id\"])\n self.rooms[chunk[\"room_id\"]].events.append(chunk)\n for listener in self.rooms[chunk[\"room_id\"]].listeners:\n listener(chunk)\n\n def listen_forever(self, timeout=30000):\n while(True):\n self.listen_for_events(timeout)\n\n def start_listener_thread(self, timeout=30000):\n try:\n thread = Thread(target=self.listen_forever, args=(timeout, ))\n thread.daemon = True\n thread.start()\n except:\n e = sys.exc_info()[0]\n print(\"Error: unable to start thread. \" + str(e))\n\n def _mkroom(self, room_id):\n self.rooms[room_id] = Room(self, room_id)\n return self.rooms[room_id]\n\n def _sync(self, limit=1):\n response = self.api.initial_sync(limit)\n try:\n self.end = response[\"end\"]\n for room in response[\"rooms\"]:\n self._mkroom(room[\"room_id\"])\n\n current_room = self.get_rooms()[room[\"room_id\"]]\n for chunk in room[\"messages\"][\"chunk\"]:\n current_room.events.append(chunk)\n\n for state_event in room[\"state\"]:\n if \"type\" in state_event and state_event[\"type\"] == \"m.room.name\":\n current_room.name = state_event[\"content\"][\"name\"]\n if \"type\" in state_event and state_event[\"type\"] == \"m.room.topic\":\n current_room.topic = state_event[\"content\"][\"topic\"]\n if \"type\" in state_event and state_event[\"type\"] == \"m.room.aliases\":\n current_room.aliases = state_event[\"content\"][\"aliases\"]\n\n except KeyError:\n pass\n\n\nclass Room(object):\n\n def __init__(self, client, room_id):\n self.room_id = room_id\n self.client = client\n self.listeners = []\n self.events = []\n self.name = None\n self.aliases = []\n self.topic = None\n\n def send_text(self, text):\n return self.client.api.send_message(self.room_id, text)\n\n def send_emote(self, text):\n return self.client.api.send_emote(self.room_id, text)\n\n def add_listener(self, callback):\n self.listeners.append(callback)\n\n def get_events(self):\n return self.events\n\n def invite_user(self, user_id):\n \"\"\"Invite user to this room\n\n Return True if the invitation was sent\n \"\"\"\n try:\n response = self.client.api.invite_user(self.room_id, user_id)\n return True\n except MatrixRequestError:\n return False\n\n def kick_user(self, user_id, reason=\"\"):\n try:\n response = self.client.api.kick_user(self.room_id, user_id)\n return True\n except MatrixRequestError:\n return False\n\n def ban_user(self, user_id, reason):\n try:\n response = self.client.api.ban_user(self.room_id, user_id, reason)\n return True\n except MatrixRequestError:\n return False\n\n def leave(self, user_id):\n try:\n response = self.client.api.leave_room(self.room_id)\n self.client.rooms.remove(self.room_id)\n return True\n except MatrixRequestError:\n return False\n\n def update_room_name(self):\n \"\"\"Get room name\n\n Return True if the room name changed, False if not\n \"\"\"\n try:\n response = self.client.api.get_room_name(self.room_id)\n if \"name\" in response and response[\"name\"] != self.name:\n self.name = response[\"name\"]\n return True\n else:\n return False\n except MatrixRequestError:\n return False\n\n def update_room_topic(self):\n \"\"\"Get room topic\n\n Return True if the room topic changed, False if not\n \"\"\"\n try:\n response = self.client.api.get_room_topic(self.room_id)\n if \"topic\" in response and response[\"topic\"] != self.topic:\n self.topic = response[\"topic\"]\n return True\n else:\n return False\n except MatrixRequestError:\n return False\n\n def update_aliases(self):\n \"\"\"Get aliases information from room state\n\n Return True if the aliases changed, False if not\n \"\"\"\n try:\n response = self.client.api.get_room_state(self.room_id)\n for chunk in response:\n if \"content\" in chunk and \"aliases\" in chunk[\"content\"]:\n if chunk[\"content\"][\"aliases\"] != self.aliases:\n self.aliases = chunk[\"content\"][\"aliases\"]\n return True\n else:\n return False\n except MatrixRequestError:\n return False\n\n","sub_path":"matrix_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":8685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"384918300","text":"import numpy as np\nimport tensorflow as tf\nfrom tframe import console\n\n\nconsole.suppress_logging()\nconsole.start('Template')\n\n# Put your codes below\nx = np.arange(12).reshape(6, 2)\ntensor_x = tf.placeholder(dtype=tf.float32)\nwith tf.Session() as sess:\n console.eval_show(tensor_x, name='x', feed_dict={tensor_x: x})\n\n# End of the script\nconsole.end()\n","sub_path":"institute/tflab/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"135649644","text":"import datetime\r\n\r\nimport maya\r\nimport gsedit\r\nimport mail\r\n\r\nprint(\"\\n---------------------------\")\r\nyear, month, day = map(int, input(\"生年月日(yyyy mm dd): \").split())\r\nbirth_date = datetime.date(year, month, day)\r\n\r\nkin = maya.calc_kin(year, month, day)\r\n\r\nmirror_kin, out_tone, out_suncrest, out_wavespell = maya.calc_maya(kin)\r\n\r\nprint(\"生年月日 : \" + str(year) + \"年\" + str(month) + \"月\" + str(day) + \"日\")\r\nprint(\"kin : \" + str(kin))\r\nprint(\"太陽の紋章 : \" + str(out_suncrest) )\r\nprint(\"ウェブスペル : \" + str(out_wavespell) )\r\nprint(\"銀河の音 : \" + str(out_tone) )\r\nprint(\"---------------------------\\n\\n\")\r\n\r\n\r\nyear, month, day = map(int, input(\"入力日付(yyyy mm dd): \").split())\r\ninput_date = datetime.date(year, month, day)\r\n\r\nbirthdaytext = gsedit.get_birthdaytext(birth_date, input_date)\r\nsendtext = birthdaytext.replace(\"{name}\", \"松原\")\r\n\r\nprint(\"\\nsubject : \")\r\nprint(\"\\nsendtext : \", sendtext)\r\n\r\nif input(\"send mail ? (y/n) : \") == \"y\":\r\n msg1 = mail.create_message(\r\n from_addr = \"project01111011@gmail.com\", \r\n to_addr = \"nm1552jp@gmail.com\",\r\n subject = \"テスト送信 kin\", #件名\r\n body = sendtext #本文\r\n )\r\n\r\n mail.send(\r\n from_addr = \"project01111011@gmail.com\", \r\n to_addr = \"nm1552jp@gmail.com\", \r\n body_msg = msg1\r\n )\r\n\r\n print(\"::::メールの送信が完了しました。\\n\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"94070918","text":"import torch\nfrom torch import nn, optim\nimport numpy as np\nimport os\nimport time\nimport psutil\nimport pickle\nimport json\nimport random\nimport argparse\nimport pathlib\nimport visualization\nimport evaluation\nimport matplotlib.pyplot as plt\nfrom model.dyn_stg import SpatioTemporalGraphCVAEModel\nfrom model.model_registrar import ModelRegistrar\nfrom model.model_utils import cyclical_lr\nfrom tensorboardX import SummaryWriter\n#torch.autograd.set_detect_anomaly(True) # TODO Remove for speed\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--conf\", help=\"path to json config file for hyperparameters\",\n type=str, default='config.json')\nparser.add_argument(\"--offline_scene_graph\", help=\"whether to precompute the scene graphs offline, options are 'no' and 'yes'\",\n type=str, default='yes')\nparser.add_argument(\"--dynamic_edges\", help=\"whether to use dynamic edges or not, options are 'no' and 'yes'\",\n type=str, default='yes')\nparser.add_argument(\"--edge_radius\", help=\"the radius (in meters) within which two nodes will be connected by an edge\",\n type=float, default=3.0)\nparser.add_argument(\"--edge_state_combine_method\", help=\"the method to use for combining edges of the same type\",\n type=str, default='sum')\nparser.add_argument(\"--edge_influence_combine_method\", help=\"the method to use for combining edge influences\",\n type=str, default='attention')\nparser.add_argument('--edge_addition_filter', nargs='+', help=\"what scaling to use for edges as they're created\",\n type=float, default=[0.25, 0.5, 0.75, 1.0]) # We automatically pad left with 0.0\nparser.add_argument('--edge_removal_filter', nargs='+', help=\"what scaling to use for edges as they're removed\",\n type=float, default=[1.0, 0.0]) # We automatically pad right with 0.0\nparser.add_argument('--incl_robot_node', help=\"whether to include a robot node in the graph or simply model all agents\",\n action='store_true')\nparser.add_argument('--use_map_encoding', help=\"Whether to use map encoding or not\",\n action='store_true')\n\nparser.add_argument(\"--data_dir\", help=\"what dir to look in for data\",\n type=str, default='../data/processed')\nparser.add_argument(\"--train_data_dict\", help=\"what file to load for training data\",\n type=str, default='nuscenes_train_ph6_v1.pkl')\nparser.add_argument(\"--eval_data_dict\", help=\"what file to load for evaluation data\",\n type=str, default='nuscenes_val_ph6_v1.pkl')\nparser.add_argument(\"--log_dir\", help=\"what dir to save training information (i.e., saved models, logs, etc)\",\n type=str, default='../data/nuscenes/logs')\nparser.add_argument(\"--log_tag\", help=\"tag for the log folder\",\n type=str, default='')\n\nparser.add_argument('--device', help='what device to perform training on',\n type=str, default='cuda:0')\nparser.add_argument(\"--eval_device\", help=\"what device to use during evaluation\",\n type=str, default=None)\n\nparser.add_argument(\"--num_iters\", help=\"number of iterations to train for\",\n type=int, default=2000)\nparser.add_argument('--batch_multiplier', help='how many minibatches to run per iteration of training',\n type=int, default=1)\nparser.add_argument('--batch_size', help='training batch size',\n type=int, default=256)\nparser.add_argument('--eval_batch_size', help='evaluation batch size',\n type=int, default=256)\nparser.add_argument('--k_eval', help='how many samples to take during evaluation',\n type=int, default=50)\n\nparser.add_argument('--seed', help='manual seed to use, default is 123',\n type=int, default=123)\nparser.add_argument('--eval_every', help='how often to evaluate during training, never if None',\n type=int, default=None)\nparser.add_argument('--vis_every', help='how often to visualize during training, never if None',\n type=int, default=None)\nparser.add_argument('--save_every', help='how often to save during training, never if None',\n type=int, default=100)\nargs = parser.parse_args()\n\nif not torch.cuda.is_available() or args.device == 'cpu':\n args.device = torch.device('cpu')\nelse:\n if torch.cuda.device_count() == 1:\n # If you have CUDA_VISIBLE_DEVICES set, which you should,\n # then this will prevent leftover flag arguments from\n # messing with the device allocation.\n args.device = 'cuda:0'\n\n args.device = torch.device(args.device)\n\nif args.eval_device is None:\n args.eval_device = 'cpu'\n\nif args.seed is not None:\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(args.seed)\n\ndef main():\n # Load hyperparameters from json\n if not os.path.exists(args.conf):\n print('Config json not found!')\n with open(args.conf, 'r') as conf_json:\n hyperparams = json.load(conf_json)\n\n # Add hyperparams from arguments\n hyperparams['dynamic_edges'] = args.dynamic_edges\n hyperparams['edge_state_combine_method'] = args.edge_state_combine_method\n hyperparams['edge_influence_combine_method'] = args.edge_influence_combine_method\n hyperparams['edge_radius'] = args.edge_radius\n hyperparams['use_map_encoding'] = args.use_map_encoding\n hyperparams['edge_addition_filter'] = args.edge_addition_filter\n hyperparams['edge_removal_filter'] = args.edge_removal_filter\n hyperparams['batch_size'] = args.batch_size\n hyperparams['k_eval'] = args.k_eval\n hyperparams['offline_scene_graph'] = args.offline_scene_graph\n hyperparams['incl_robot_node'] = args.incl_robot_node\n\n print('-----------------------')\n print('| TRAINING PARAMETERS |')\n print('-----------------------')\n print('| iterations: %d' % args.num_iters)\n print('| batch_size: %d' % args.batch_size)\n print('| batch_multiplier: %d' % args.batch_multiplier)\n print('| effective batch size: %d (= %d * %d)' % (args.batch_size * args.batch_multiplier, args.batch_size, args.batch_multiplier))\n print('| device: %s' % args.device)\n print('| eval_device: %s' % args.eval_device)\n print('| Offline Scene Graph Calculation: %s' % args.offline_scene_graph)\n print('| edge_radius: %s' % args.edge_radius)\n print('| EE state_combine_method: %s' % args.edge_state_combine_method)\n print('| EIE scheme: %s' % args.edge_influence_combine_method)\n print('| dynamic_edges: %s' % args.dynamic_edges)\n print('| robot node: %s' % args.incl_robot_node)\n print('| map encoding: %s' % args.use_map_encoding)\n print('| edge_addition_filter: %s' % args.edge_addition_filter)\n print('| edge_removal_filter: %s' % args.edge_removal_filter)\n print('| MHL: %s' % hyperparams['minimum_history_length'])\n print('| PH: %s' % hyperparams['prediction_horizon'])\n print('-----------------------')\n\n # Create the log and model directiory if they're not present.\n model_dir = os.path.join(args.log_dir, 'models_' + time.strftime('%d_%b_%Y_%H_%M_%S', time.localtime()) + args.log_tag)\n pathlib.Path(model_dir).mkdir(parents=True, exist_ok=True)\n\n # Save config to model directory\n with open(os.path.join(model_dir, 'config.json'), 'w') as conf_json:\n json.dump(hyperparams, conf_json)\n\n log_writer = SummaryWriter(log_dir=model_dir)\n\n train_scenes = []\n train_data_path = os.path.join(args.data_dir, args.train_data_dict)\n with open(train_data_path, 'rb') as f:\n train_env = pickle.load(f, encoding='latin1')\n train_scenes = train_env.scenes\n print('Loaded training data from %s' % (train_data_path,))\n\n eval_scenes = []\n if args.eval_every is not None:\n eval_data_path = os.path.join(args.data_dir, args.eval_data_dict)\n with open(eval_data_path, 'rb') as f:\n eval_env = pickle.load(f, encoding='latin1')\n eval_scenes = eval_env.scenes\n print('Loaded evaluation data from %s' % (eval_data_path, ))\n\n # Calculate Scene Graph\n if hyperparams['offline_scene_graph'] == 'yes':\n print(f\"Offline calculating scene graphs\")\n for i, scene in enumerate(train_scenes):\n scene.calculate_scene_graph(train_env.attention_radius,\n hyperparams['state'],\n hyperparams['edge_addition_filter'],\n hyperparams['edge_removal_filter'])\n print(f\"Created Scene Graph for Scene {i}\")\n\n for i, scene in enumerate(eval_scenes):\n scene.calculate_scene_graph(eval_env.attention_radius,\n hyperparams['state'],\n hyperparams['edge_addition_filter'],\n hyperparams['edge_removal_filter'])\n print(f\"Created Scene Graph for Scene {i}\")\n\n model_registrar = ModelRegistrar(model_dir, args.device)\n\n # We use pre trained weights for the map CNN\n if args.use_map_encoding:\n inf_encoder_registrar = os.path.join(args.log_dir, 'weight_trans/model_registrar-1499.pt')\n model_dict = torch.load(inf_encoder_registrar, map_location=args.device)\n\n for key in model_dict.keys():\n if 'map_encoder' in key:\n model_registrar.model_dict[key] = model_dict[key]\n assert model_registrar.get_model(key) is model_dict[key]\n\n stg = SpatioTemporalGraphCVAEModel(model_registrar,\n hyperparams,\n log_writer, args.device)\n stg.set_scene_graph(train_env)\n stg.set_annealing_params()\n print('Created training STG model.')\n\n eval_stg = None\n if args.eval_every is not None or args.vis_every is not None:\n eval_stg = SpatioTemporalGraphCVAEModel(model_registrar,\n hyperparams,\n log_writer, args.device)\n eval_stg.set_scene_graph(eval_env)\n eval_stg.set_annealing_params() # TODO Check if necessary\n if hyperparams['learning_rate_style'] == 'const':\n optimizer = optim.Adam(model_registrar.parameters(), lr=hyperparams['learning_rate'])\n lr_scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma=1.0)\n elif hyperparams['learning_rate_style'] == 'exp':\n optimizer = optim.Adam(model_registrar.parameters(), lr=hyperparams['learning_rate'])\n lr_scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma=hyperparams['learning_decay_rate'])\n elif hyperparams['learning_rate_style'] == 'triangle':\n optimizer = optim.Adam(model_registrar.parameters(), lr=1.0)\n clr = cyclical_lr(100, min_lr=hyperparams['min_learning_rate'], max_lr=hyperparams['learning_rate'], decay=hyperparams['learning_decay_rate'])\n lr_scheduler = optim.lr_scheduler.LambdaLR(optimizer, [clr])\n\n print_training_header(newline_start=True)\n for curr_iter in range(args.num_iters):\n # Necessary because we flip the weights contained between GPU and CPU sometimes.\n model_registrar.to(args.device)\n\n # Setting the current iterator value for internal logging.\n stg.set_curr_iter(curr_iter)\n if args.vis_every is not None:\n eval_stg.set_curr_iter(curr_iter)\n\n # Stepping forward the learning rate scheduler and annealers.\n lr_scheduler.step()\n log_writer.add_scalar('train/learning_rate',\n lr_scheduler.get_lr()[0],\n curr_iter)\n stg.step_annealers()\n\n # Zeroing gradients for the upcoming iteration.\n optimizer.zero_grad()\n train_losses = dict()\n for node_type in train_env.NodeType:\n train_losses[node_type] = []\n for scene in np.random.choice(train_scenes, hyperparams['batch_size']):\n for mb_num in range(args.batch_multiplier):\n # Obtaining the batch's training loss.\n timesteps = np.array([hyperparams['maximum_history_length']])\n\n # Compute the training loss.\n train_loss_by_type = stg.train_loss(scene, timesteps, max_nodes=hyperparams['batch_size'])\n for node_type, train_loss in train_loss_by_type.items():\n if train_loss is not None:\n train_loss = train_loss / (args.batch_multiplier * hyperparams['batch_size'])\n train_losses[node_type].append(train_loss.item())\n\n # Calculating gradients.\n train_loss.backward()\n\n # Print training information. Also, no newline here. It's added in at a later line.\n print('{:9} | '.format(curr_iter), end='', flush=True)\n for node_type in train_env.NodeType:\n print('{}:{:10} | '.format(node_type.name[0], '%.2f' % sum(train_losses[node_type])), end='', flush=True)\n\n for node_type in train_env.NodeType:\n if len(train_losses[node_type]) > 0:\n log_writer.add_histogram(f\"{node_type.name}/train/minibatch_losses\", np.asarray(train_losses[node_type]), curr_iter)\n log_writer.add_scalar(f\"{node_type.name}/train/loss\", sum(train_losses[node_type]), curr_iter)\n\n # Clipping gradients.\n if hyperparams['grad_clip'] is not None:\n nn.utils.clip_grad_value_(model_registrar.parameters(), hyperparams['grad_clip'])\n\n # Performing a gradient step.\n optimizer.step()\n\n del train_loss # TODO Necessary?\n\n if args.vis_every is not None and (curr_iter + 1) % args.vis_every == 0:\n max_hl = hyperparams['maximum_history_length']\n ph = hyperparams['prediction_horizon']\n with torch.no_grad():\n # Predict random timestep to plot for train data set\n scene = np.random.choice(train_scenes)\n timestep = scene.sample_timesteps(1, min_future_timesteps=ph)\n predictions = stg.predict(scene,\n timestep,\n ph,\n num_samples_z=100,\n most_likely_z=False,\n all_z=False)\n\n # Plot predicted timestep for random scene\n fig, ax = plt.subplots(figsize=(5, 5))\n visualization.visualize_prediction(ax,\n predictions,\n scene.dt,\n max_hl=max_hl,\n ph=ph)\n ax.set_title(f\"{scene.name}-t: {timestep}\")\n log_writer.add_figure('train/prediction', fig, curr_iter)\n\n # Predict random timestep to plot for eval data set\n scene = np.random.choice(eval_scenes)\n timestep = scene.sample_timesteps(1, min_future_timesteps=ph)\n predictions = eval_stg.predict(scene,\n timestep,\n ph,\n num_samples_z=100,\n most_likely_z=False,\n all_z=False,\n max_nodes=4 * args.eval_batch_size)\n\n # Plot predicted timestep for random scene\n fig, ax = plt.subplots(figsize=(5, 5))\n visualization.visualize_prediction(ax,\n predictions,\n scene.dt,\n max_hl=max_hl,\n ph=ph)\n ax.set_title(f\"{scene.name}-t: {timestep}\")\n log_writer.add_figure('eval/prediction', fig, curr_iter)\n\n # Plot predicted timestep for random scene in map\n fig, ax = plt.subplots(figsize=(15, 15))\n visualization.visualize_prediction(ax,\n predictions,\n scene.dt,\n max_hl=max_hl,\n ph=ph,\n map=scene.map['PLOT'])\n ax.set_title(f\"{scene.name}-t: {timestep}\")\n log_writer.add_figure('eval/prediction_map', fig, curr_iter)\n\n # Predict random timestep to plot for eval data set\n predictions = eval_stg.predict(scene,\n timestep,\n ph,\n num_samples_gmm=50,\n most_likely_z=False,\n all_z=True,\n max_nodes=4 * args.eval_batch_size)\n\n # Plot predicted timestep for random scene\n fig, ax = plt.subplots(figsize=(5, 5))\n visualization.visualize_prediction(ax,\n predictions,\n scene.dt,\n max_hl=max_hl,\n ph=ph)\n ax.set_title(f\"{scene.name}-t: {timestep}\")\n log_writer.add_figure('eval/prediction_all_z', fig, curr_iter)\n\n if args.eval_every is not None and (curr_iter + 1) % args.eval_every == 0:\n max_hl = hyperparams['maximum_history_length']\n ph = hyperparams['prediction_horizon']\n with torch.no_grad():\n # Predict batch timesteps for training dataset evaluation\n train_batch_errors = []\n max_scenes = np.min([len(train_scenes), 5])\n for scene in np.random.choice(train_scenes, max_scenes):\n timesteps = scene.sample_timesteps(args.eval_batch_size)\n predictions = stg.predict(scene,\n timesteps,\n ph,\n num_samples_z=100,\n min_future_timesteps=ph,\n max_nodes=4*args.eval_batch_size)\n\n train_batch_errors.append(evaluation.compute_batch_statistics(predictions,\n scene.dt,\n max_hl=max_hl,\n ph=ph,\n node_type_enum=train_env.NodeType,\n map=scene.map))\n\n evaluation.log_batch_errors(train_batch_errors,\n log_writer,\n 'train',\n curr_iter,\n bar_plot=['kde'],\n box_plot=['ade', 'fde'])\n\n # Predict batch timesteps for evaluation dataset evaluation\n eval_batch_errors = []\n for scene in eval_scenes:\n timesteps = scene.sample_timesteps(args.eval_batch_size)\n\n predictions = eval_stg.predict(scene,\n timesteps,\n ph,\n num_samples_z=100,\n min_future_timesteps=ph,\n max_nodes=4 * args.eval_batch_size)\n\n eval_batch_errors.append(evaluation.compute_batch_statistics(predictions,\n scene.dt,\n max_hl=max_hl,\n ph=ph,\n node_type_enum=eval_env.NodeType,\n map=scene.map))\n\n evaluation.log_batch_errors(eval_batch_errors,\n log_writer,\n 'eval',\n curr_iter,\n bar_plot=['kde'],\n box_plot=['ade', 'fde'])\n\n\n # Predict maximum likelihood batch timesteps for evaluation dataset evaluation\n eval_batch_errors_ml = []\n for scene in eval_scenes:\n timesteps = scene.sample_timesteps(scene.timesteps)\n\n predictions = eval_stg.predict(scene,\n timesteps,\n ph,\n num_samples_z=1,\n min_future_timesteps=ph,\n most_likely_z=True,\n most_likely_gmm=True)\n\n eval_batch_errors_ml.append(evaluation.compute_batch_statistics(predictions,\n scene.dt,\n max_hl=max_hl,\n ph=ph,\n map=scene.map,\n node_type_enum=eval_env.NodeType,\n kde=False))\n\n evaluation.log_batch_errors(eval_batch_errors_ml,\n log_writer,\n 'eval/ml',\n curr_iter)\n\n eval_loss = []\n max_scenes = np.min([len(eval_scenes), 25])\n for scene in np.random.choice(eval_scenes, max_scenes):\n eval_loss.append(eval_stg.eval_loss(scene, timesteps))\n\n evaluation.log_batch_errors(eval_loss,\n log_writer,\n 'eval/loss',\n curr_iter)\n\n\n else:\n print('{:15} | {:10} | {:14}'.format('', '', ''),\n end='', flush=True)\n\n # Here's the newline that ends the current training information printing.\n print('')\n\n if args.save_every is not None and (curr_iter + 1) % args.save_every == 0:\n model_registrar.save_models(curr_iter)\n print_training_header()\n\n\ndef print_training_header(newline_start=False):\n if newline_start:\n print('')\n\n print('Iteration | Train Loss | Eval NLL Q (IS) | Eval NLL P | Eval NLL Exact')\n print('----------------------------------------------------------------------')\n\n\ndef memInUse():\n pid = os.getpid()\n py = psutil.Process(pid)\n memoryUse = py.memory_info()[0] / 2. ** 30 # memory use in GB...I think\n print('memory GB:', memoryUse)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"code_traj/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":24309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"113610284","text":"import sys\n\ndef solution(compress):\n answer = 0\n cnt = 0\n startIdx = -1\n for i, c in enumerate(compress):\n if c == '(':\n cnt += 1\n if startIdx == -1: startIdx = i\n elif c == ')':\n cnt -= 1\n if cnt == 0:\n answer += solution(compress[i + 1:])\n compress = compress[:i + 1]\n break\n\n if startIdx == -1: return len(compress)\n else: return len(compress[:startIdx - 1])\\\n + int(compress[startIdx - 1]) * solution(compress[startIdx + 1: -1]) + answer\n\n\nif __name__ == '__main__':\n compress = sys.stdin.readline()[:-1]\n\n sys.stdout.write('%d\\n'%solution(compress))","sub_path":"1~10000/1662/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"247674101","text":"import pathlib\nimport tempfile\nfrom typing import Tuple, Union\nfrom unittest.mock import patch\n\nimport ipywidgets as widgets\nimport numpy as np\nfrom hypothesis import assume, given, infer, settings, strategies\nfrom PIL import Image\n\nfrom ipyannotations.images.canvases.abstract_canvas import (\n AbstractAnnotationCanvas,\n)\nimport ipyannotations.images.canvases.image_utils\nfrom ipyannotations.images.canvases.image_utils import fit_image\n\n\nclass TestCanvas(AbstractAnnotationCanvas):\n \"\"\"Test canvas to test the abstract canvas.\"\"\"\n\n def init_empty_data(self):\n self.data = []\n\n\n@settings(deadline=None)\n@given(img=infer)\ndef test_that_loading_image_clears_data(\n img: Union[widgets.Image, np.ndarray, Image.Image]\n):\n\n with patch.object(\n AbstractAnnotationCanvas, \"init_empty_data\"\n ) as mock_init_empty_data:\n canvas = AbstractAnnotationCanvas()\n mock_init_empty_data.reset_mock()\n canvas.load_image(img)\n\n mock_init_empty_data.assert_called_once()\n\n\n@settings(deadline=None)\n@given(img=infer)\ndef test_that_loading_image_from_path_succeeds(img: Image.Image):\n\n with tempfile.TemporaryDirectory(dir=\".\") as tmp:\n tmp = pathlib.Path(tmp)\n tmp = tmp / \"testfile.jpg\"\n img.save(tmp)\n\n with patch.object(\n AbstractAnnotationCanvas, \"init_empty_data\"\n ) as mock_init_empty_data:\n canvas = AbstractAnnotationCanvas()\n mock_init_empty_data.reset_mock()\n canvas.load_image(tmp)\n\n mock_init_empty_data.assert_called_once()\n\n\n@given(img=infer)\ndef test_that_fit_image_always_fits_image(img: widgets.Image):\n\n with patch.object(AbstractAnnotationCanvas, \"init_empty_data\"):\n canvas = AbstractAnnotationCanvas()\n\n x0, y0, x1, y1, _, _ = fit_image(img, canvas)\n\n assert (x1, y1) < (canvas.width, canvas.height)\n\n\n@given(\n img=infer, click_x=strategies.floats(0, 1), click_y=strategies.floats(0, 1)\n)\ndef test_that_points_clicked_get_translated_correctly(\n img: widgets.Image, click_x: float, click_y: float\n):\n with patch.object(AbstractAnnotationCanvas, \"init_empty_data\"):\n canvas = AbstractAnnotationCanvas()\n canvas.load_image(img)\n\n x0, y0, width, height, img_width, img_height = fit_image(img, canvas)\n assume((img_width, img_height) > (20, 20))\n\n click_x = round(x0 + click_x * width)\n click_y = round(y0 + click_y * height)\n\n assert (\n (0, 0)\n <= canvas.canvas_to_image_coordinates((click_x, click_y))\n <= (img_width, img_height)\n )\n\n round_trip_x, round_trip_y = canvas.image_to_canvas_coordinates(\n canvas.canvas_to_image_coordinates((click_x, click_y))\n )\n assert np.isclose(round_trip_x, click_x) and np.isclose(\n round_trip_y, click_y, atol=1\n )\n\n\n@settings(deadline=None)\n@given(img=infer)\ndef test_that_images_are_adjusted(img: widgets.Image):\n with patch(\n \"ipyannotations.images.canvases.abstract_canvas.adjust\", autospec=True\n ) as mock_adjust:\n mock_adjust.return_value = img\n canvas = TestCanvas()\n canvas.image_brightness = 1.1\n canvas.image_contrast = 1.1\n canvas.load_image(img)\n\n mock_adjust.assert_called_once_with(\n img,\n contrast_factor=1.1,\n brightness_factor=1.1,\n )\n","sub_path":"tests/images/test_abstract_canvas.py","file_name":"test_abstract_canvas.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"59142977","text":"import requests\nfrom lxml import etree\n\nstatus_200 = []\nstatus_other = []\nstatus_none = []\ndef fetch(url):\n r = requests.get(url)\n if r.status_code != 200:\n r.raise_for_status()\n return r.text.replace('\\t', '')\n\ndef parse_univerity(link):\n try:\n status = requests.get(link).status_code\n if status != 200:\n status_other.append(link)\n else:\n status_200.append(link)\n except Exception:\n status_none.append(link)\n\n\nif __name__ == '__main__':\n selector = etree.HTML(fetch('http://www.hao123.com'))\n links = selector.xpath('//a/@href')\n for link in links:\n # if not link.startswith('http'):\n print(link)\n data = parse_univerity(link)\n print(status_200)\n print(status_other)\n print(status_none)","sub_path":"Code/PaChong/day02/homework/hao123.py","file_name":"hao123.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"147150338","text":"#!/usr/bin/python3\ndef fizzbuzz():\n \"\"\"prints from 1 to 100 separated by a space\n prints Fizz for multiples of three\n prints Buzz for multiples of five\n prints FizzBuzz for multiples of both three and five\n \"\"\"\n for num in range(1, 101):\n if num % 3 == 0 and num % 5 == 0:\n print(\"FizzBuzz \", end=\"\")\n elif num % 3 == 0:\n print(\"Fizz \", end=\"\")\n elif num % 5 == 0:\n print(\"Buzz \", end=\"\")\n else:\n print(\"{} \".format(num), end=\"\")\n","sub_path":"0x01-python-if_else_loops_functions/12-fizzbuzz.py","file_name":"12-fizzbuzz.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"504715614","text":"from ogusa_calibrate import (\n estimate_beta_j,\n bequest_transmission,\n demographics,\n macro_params,\n transfer_distribution,\n income,\n txfunc,\n)\nimport os\nimport numpy as np\nfrom ogusa.utils import safe_read_pickle, mkdirs\nimport pkg_resources\n\nCUR_PATH = os.path.split(os.path.abspath(__file__))[0]\n\n\nclass Calibration:\n \"\"\"OG-USA calibration class\"\"\"\n\n def __init__(\n self,\n p,\n estimate_tax_functions=False,\n estimate_beta=False,\n estimate_chi_n=False,\n tax_func_path=None,\n iit_reform={},\n guid=\"\",\n data=\"cps\",\n client=None,\n num_workers=1,\n ):\n\n self.estimate_tax_functions = estimate_tax_functions\n self.estimate_beta = estimate_beta\n self.estimate_chi_n = estimate_chi_n\n if estimate_tax_functions:\n self.tax_function_params = self.get_tax_function_parameters(\n p,\n iit_reform,\n guid,\n data,\n client,\n num_workers,\n run_micro=True,\n tax_func_path=tax_func_path,\n )\n if estimate_beta:\n self.beta_j = estimate_beta_j.beta_estimate(self)\n # if estimate_chi_n:\n # chi_n = self.get_chi_n()\n\n # Macro estimation\n self.macro_params = macro_params.get_macro_params()\n\n # eta estimation\n self.eta = transfer_distribution.get_transfer_matrix()\n\n # zeta estimation\n self.zeta = bequest_transmission.get_bequest_matrix()\n\n # earnings profiles\n self.e = income.get_e_interp(\n p.S, p.omega_SS, p.omega_SS_80, p.lambdas, plot=False\n )\n\n # demographics\n self.demographic_params = demographics.get_pop_objs(\n p.E, p.S, p.T, 1, 100, p.start_year\n )\n\n # Tax Functions\n def get_tax_function_parameters(\n self,\n p,\n iit_reform={},\n guid=\"\",\n data=\"\",\n client=None,\n num_workers=1,\n run_micro=False,\n tax_func_path=None,\n ):\n \"\"\"\n Reads pickle file of tax function parameters or estimates the\n parameters from microsimulation model output.\n Args:\n client (Dask client object): client\n run_micro (bool): whether to estimate parameters from\n microsimulation model\n tax_func_path (string): path where find or save tax\n function parameter estimates\n Returns:\n None\n \"\"\"\n # set paths if none given\n if tax_func_path is None:\n if p.baseline:\n pckl = \"TxFuncEst_baseline{}.pkl\".format(guid)\n tax_func_path = os.path.join(CUR_PATH, pckl)\n print(\"Using baseline tax parameters from \", tax_func_path)\n else:\n pckl = \"TxFuncEst_policy{}.pkl\".format(guid)\n tax_func_path = os.path.join(CUR_PATH, pckl)\n print(\n \"Using reform policy tax parameters from \", tax_func_path\n )\n # create directory for tax function pickles to be saved to\n mkdirs(os.path.split(tax_func_path)[0])\n # If run_micro is false, check to see if parameters file exists\n # and if it is consistent with Specifications instance\n if not run_micro:\n dict_params, run_micro = self.read_tax_func_estimate(tax_func_path)\n if run_micro:\n txfunc.get_tax_func_estimate( # pragma: no cover\n p.BW,\n p.S,\n p.starting_age,\n p.ending_age,\n p.baseline,\n p.analytical_mtrs,\n p.tax_func_type,\n p.age_specific,\n p.start_year,\n iit_reform,\n guid,\n tax_func_path,\n data,\n client,\n num_workers,\n )\n dict_params, _ = self.read_tax_func_estimate(p, tax_func_path)\n mean_income_data = dict_params[\"tfunc_avginc\"][0]\n try:\n frac_tax_payroll = np.append(\n dict_params[\"tfunc_frac_tax_payroll\"],\n np.ones(p.T + p.S - p.BW)\n * dict_params[\"tfunc_frac_tax_payroll\"][-1],\n )\n except KeyError:\n pass\n try:\n taxcalc_version = dict_params[\"taxcalc_version\"]\n except KeyError:\n taxcalc_version = \"No version recorded\"\n\n # Reorder indices of tax function and tile for all years after\n # budget window ends\n num_etr_params = dict_params[\"tfunc_etr_params_S\"].shape[2]\n # First check to see if tax parameters that are used were\n # estimated with a budget window and ages that are as long as\n # the those implied based on the start year and model age.\n # N.B. the tax parameters dictionary does not save the years\n # that correspond to the parameter estimates, so the start year\n # used there may name match what is used in a run that reads in\n # some cached tax function parameters. Likewise for age.\n params_list = [\"etr\", \"mtrx\", \"mtry\"]\n BW_in_tax_params = dict_params[\"tfunc_etr_params_S\"].shape[1]\n S_in_tax_params = dict_params[\"tfunc_etr_params_S\"].shape[0]\n if p.BW != BW_in_tax_params:\n print(\n \"Warning: There is a discrepency between the start\"\n + \" year of the model and that of the tax functions!!\"\n )\n # After printing warning, make it work by tiling\n if p.BW > BW_in_tax_params:\n for item in params_list:\n dict_params[\"tfunc_\" + item + \"_params_S\"] = np.concatenate(\n (\n dict_params[\"tfunc_\" + item + \"_params_S\"],\n np.tile(\n dict_params[\"tfunc_\" + item + \"_params_S\"][\n :, -1, :\n ].reshape(S_in_tax_params, 1, num_etr_params),\n (1, p.BW - BW_in_tax_params, 1),\n ),\n ),\n axis=1,\n )\n dict_params[\"tfunc_avg_\" + item] = np.append(\n dict_params[\"tfunc_avg_\" + item],\n np.tile(\n dict_params[\"tfunc_avg_\" + item][-1],\n (p.BW - BW_in_tax_params),\n ),\n )\n if p.S != S_in_tax_params:\n print(\n \"Warning: There is a discrepency between the ages\"\n + \" used in the model and those in the tax functions!!\"\n )\n # After printing warning, make it work by tiling\n if p.S > S_in_tax_params:\n for item in params_list:\n dict_params[\"tfunc_\" + item + \"_params_S\"] = np.concatenate(\n (\n dict_params[\"tfunc_\" + item + \"_params_S\"],\n np.tile(\n dict_params[\"tfunc_\" + item + \"_params_S\"][\n -1, :, :\n ].reshape(1, p.BW, num_etr_params),\n (p.S - S_in_tax_params, 1, 1),\n ),\n ),\n axis=0,\n )\n tax_param_dict = {\n \"etr_params\": dict_params[\"tfunc_etr_params_S\"],\n \"mtrx_params\": dict_params[\"tfunc_mtrx_params_S\"],\n \"mtry_params\": dict_params[\"tfunc_mtry_params_S\"],\n \"taxcalc_version\": taxcalc_version,\n \"mean_income_data\": mean_income_data,\n \"frac_tax_payroll\": frac_tax_payroll,\n }\n\n return tax_param_dict\n\n def read_tax_func_estimate(self, p, tax_func_path):\n \"\"\"\n This function reads in tax function parameters from pickle\n files.\n Args:\n tax_func_path (str): path to pickle with tax function\n parameter estimates\n Returns:\n dict_params (dict): dictionary containing arrays of tax\n function parameters\n run_micro (bool): whether to estimate tax function parameters\n \"\"\"\n flag = 0\n if os.path.exists(tax_func_path):\n print(\"Tax Function Path Exists\")\n dict_params = safe_read_pickle(tax_func_path)\n # check to see if tax_functions compatible\n current_taxcalc = pkg_resources.get_distribution(\"taxcalc\").version\n try:\n if current_taxcalc != dict_params[\"tax_calc_version\"]:\n print(\n \"WARNING: Tax function parameters estimated\"\n + \" from Tax Calculator version that is not \"\n + \" the one currently installed on this machine.\"\n )\n print(\n \"Current TC version is \",\n current_taxcalc,\n \", Estimated tax functions from version \",\n dict_params.get(\"tax_calc_version\", None),\n )\n flag = 1\n except KeyError:\n pass\n try:\n if p.start_year != dict_params[\"start_year\"]:\n print(\n \"Model start year not consistent with tax \"\n + \"function parameter estimates\"\n )\n flag = 1\n except KeyError:\n pass\n try:\n if p.BW != dict_params[\"BW\"]:\n print(\n \"Model budget window length is not \"\n + \"consistent with tax function parameter \"\n + \"estimates\"\n )\n flag = 1\n except KeyError:\n pass\n try:\n if p.tax_func_type != dict_params[\"tax_func_type\"]:\n print(\n \"Model tax function type is not \"\n + \"consistent with tax function parameter \"\n + \"estimates\"\n )\n flag = 1\n except KeyError:\n pass\n if flag >= 1:\n raise RuntimeError(\n \"Tax function parameter estimates at given path\"\n + \" are not consistent with model parameters\"\n + \" specified.\"\n )\n else:\n flag = 1\n print(\n \"Tax function parameter estimates do not exist at\"\n + \" given path. Running new estimation.\"\n )\n if flag >= 1:\n dict_params = None\n run_micro = True\n else:\n run_micro = False\n\n return dict_params, run_micro\n\n # method to return all newly calibrated parameters in a dictionary\n def get_dict(self):\n dict = {}\n if self.estimate_tax_functions:\n dict.update(self.tax_function_params)\n if self.estimate_beta:\n dict[\"beta_annual\"] = self.beta\n if self.estimate_chi_n:\n dict[\"chi_n\"] = self.chi_n\n dict[\"eta\"] = self.eta\n dict[\"zeta\"] = self.zeta\n dict.update(self.macro_params)\n dict[\"e\"] = self.e\n dict.update(self.demographic_params)\n\n return dict\n","sub_path":"ogusa_calibrate/calibrate.py","file_name":"calibrate.py","file_ext":"py","file_size_in_byte":11524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"492307678","text":"import pickle\nfrom typing import Iterable\n\nfrom motor.motor_asyncio import AsyncIOMotorClient\n\nfrom aiohttp_client_cache.backends import BaseCache, CacheBackend, ResponseOrKey\nfrom aiohttp_client_cache.forge_utils import extend_signature\n\n\nclass MongoDBBackend(CacheBackend):\n \"\"\"MongoDB cache backend\n\n Args:\n connection: Optional client object to use instead of creating a new one\n\n See :py:class:`.CacheBackend` for additional args.\n \"\"\"\n\n @extend_signature(CacheBackend.__init__)\n def __init__(\n self, cache_name: str = 'aiohttp-cache', connection: AsyncIOMotorClient = None, **kwargs\n ):\n super().__init__(cache_name=cache_name, **kwargs)\n self.responses = MongoDBPickleCache(cache_name, 'responses', connection)\n self.keys_map = MongoDBCache(cache_name, 'redirects', self.responses.connection)\n\n\nclass MongoDBCache(BaseCache):\n \"\"\"An async-compatible interface for caching objects in MongoDB\n\n Args:\n db_name: database name (be careful with production databases)\n collection_name: collection name\n connection: MongoDB connection instance to use instead of creating a new one\n \"\"\"\n\n def __init__(self, db_name, collection_name: str, connection: AsyncIOMotorClient = None):\n self.connection = connection or AsyncIOMotorClient()\n self.db = self.connection[db_name]\n self.collection = self.db[collection_name]\n\n async def clear(self):\n await self.collection.drop()\n\n async def contains(self, key: str) -> bool:\n return bool(await self.collection.find_one({'_id': key}))\n\n async def delete(self, key: str):\n spec = {'_id': key}\n if hasattr(self.collection, \"find_one_and_delete\"):\n await self.collection.find_one_and_delete(spec, {'_id': True})\n else:\n await self.collection.find_and_modify(spec, remove=True, fields={'_id': True})\n\n async def keys(self) -> Iterable[str]:\n return [d['_id'] for d in await self.collection.find({}, {'_id': True}).to_list(None)]\n\n async def read(self, key: str) -> ResponseOrKey:\n result = await self.collection.find_one({'_id': key})\n return result['data'] if result else None\n\n async def size(self) -> int:\n return await self.collection.count_documents({})\n\n async def values(self) -> Iterable[ResponseOrKey]:\n results = await self.collection.find({'data': {'$exists': True}}).to_list(None)\n return [x['data'] for x in results]\n\n async def write(self, key: str, item: ResponseOrKey):\n doc = {'_id': key, 'data': item}\n await self.collection.replace_one({'_id': key}, doc, upsert=True)\n\n\nclass MongoDBPickleCache(MongoDBCache):\n \"\"\"Same as :py:class:`MongoDBCache`, but pickles values before saving\"\"\"\n\n async def read(self, key):\n return self.unpickle(bytes(await super().read(key)))\n\n async def write(self, key, item):\n await super().write(key, pickle.dumps(item, protocol=-1))\n","sub_path":"aiohttp_client_cache/backends/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"81027056","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 21 13:42:08 2020\n\n@author: simiyu\n\"\"\"\n\n\n\"\"\"\nThis Script will be able to move or delete files and folders by file extension\nRemember if your source is file and not a directory, no filtering will be performed\n\"\"\"\n\n# importing os module \nimport os \n \n# importing shutil module \nimport shutil, glob\n\n\n#Move file and Create destination folder if it does not exist\ndef move_or_delete_one_file(sourcePath, action, dstDir=None):\n if dstDir is not None and os.path.isdir(dstDir) == False:\n # Create all the dierctories in the given path\n os.makedirs(dstDir);\n if action == \"M\":\n # Move each file to destination Directory\n shutil.move(sourcePath, dstDir);\n print(\"File Moved :\", sourcePath)\n if action == \"D\":\n os.remove(sourcePath)\n print(\"File Deleted :\", sourcePath) \n \n \n \n \n \n#Move all files in a directory to an another directory recursively and Create destination folder if it does not exist\ndef move_or_delete_all_files_in_dir(action, srcDir, dstDir=None, filter_extension=None):\n # Check if both the are directories\n if os.path.isdir(srcDir):\n if dstDir is not None and os.path.isdir(dstDir) == False:\n # Create all the dierctories in the given path\n os.makedirs(dstDir);\n # Iterate over all the files in source directory\n for filePath in glob.glob(srcDir + '\\*'):\n if (filter_extension is None or filePath.lower().endswith(filter_extension)):\n if action == \"M\":\n # Move each file to destination Directory\n shutil.move(filePath, dstDir);\n print(\"File Moved :\", filePath)\n if action == \"D\":\n os.remove(filePath)\n print(\"File Deleted :\", filePath)\n \n else:\n print(\"srcDir & dstDir should be Directories\")\n \n \n \ndef main():\n print(\"**** Follow the prompts carefully to move or delete files and folders ****\") \n \n choice = str(input(\"Enter 'M' for moving and 'D' for deletion : \"))\n \n if(choice != 'M' and choice != 'D'):\n main()\n \n \n \n # Enter Source \n source = str(input(\"Enter Absolute/Relative path of source file/folder : \"))\n if(os.path.exists(source) == False):\n print(\"Source File/Folder Does Not Exist\", source)\n main()\n print(\"Source File/Folder\", source)\n \n if(choice == 'M'):\n # Enter Destination\n dest = str(input(\"Enter Absolute/Relative path of destination folder : \"))\n print(\"Destination File/Folder\", dest)\n \n if os.path.exists(source) and os.path.isdir(source):\n # Enter Source \n f_extension = str(input(\"Enter File extensions (Leave Blank For All) : \"))\n print(\"Folder Copied to :\", move_or_delete_all_files_in_dir(choice, source, dest, f_extension))\n if os.path.exists(source) and os.path.isfile(source):\n print(\"File Copied to :\", move_or_delete_one_file(source, choice, dest))\n \n if(choice == 'D'):\n if os.path.exists(source) and os.path.isdir(source):\n # Enter Source \n f_extension = str(input(\"Enter File extensions (Leave Blank For All) : \"))\n print(\"Folder Copied to :\", move_or_delete_all_files_in_dir(choice, source, None, f_extension))\n if os.path.exists(source) and os.path.isfile(source):\n print(\"File Copied to :\", move_or_delete_one_file(source, choice))\n \n \nif __name__ == '__main__':\n main()\n ","sub_path":"scripting & automation/file_explorer/explorer.py","file_name":"explorer.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"14340599","text":"from geopy.geocoders import Nominatim\nfrom math import radians, sin, cos, acos\n\n\ndef price_for_transport(city1, city2):\n \"\"\"\n (str, str) -> int\n Return: a distance between two cities\n \"\"\"\n geolocator = Nominatim(user_agent=\"specify_your_app_name_here\")\n location = geolocator.geocode(city1)\n\n slat = radians(location.latitude)\n slon = radians(location.longitude)\n\n location = geolocator.geocode(city2)\n\n elat = radians(location.latitude)\n elon = radians(location.longitude)\n\n dist = 6371.01 * acos(sin(slat)*sin(elat) + cos(slat)*cos(elat)*cos(slon - elon))\n dist += dist * 0.12\n return dist\n","sub_path":"LogisticSystem/price_for_transportion.py","file_name":"price_for_transportion.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"512234486","text":"#!/usr/bin/env python3\n# Copyright (c) 2016-2017 Intel Corporation\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# -*- coding: utf-8 -*-\n\"\"\"\nmain test runner class\n\n\"\"\"\n\n\nimport os\nimport sys\nimport logging\nfrom datetime import datetime\n#pylint: disable=import-error\nimport PostRunner\nfrom TestInfoRunner import TestInfoRunner\nfrom UnitTestRunner import UnitTestRunner\nfrom ScriptsRunner import ScriptsRunner\nfrom PythonRunner import PythonRunner\n\n#pylint: enable=import-error\n\n\nclass TestRunner(PostRunner.PostRunner):\n \"\"\"Simple test runner\"\"\"\n logdir = \"\"\n test_list = []\n info = None\n test_info = None\n logger = None\n\n def __init__(self, info, test_list=None):\n self.info = info\n self.test_list = test_list\n self.log_dir_base = self.info.get_config('log_base_path')\n self.logger = logging.getLogger(\"TestRunnerLogger\")\n self.now = \"_{}\".format(datetime.now().isoformat().replace(':', '.'))\n\n def rename_output_directory(self):\n \"\"\" rename the output directory \"\"\"\n test_directives = self.test_info.get_directives()\n if os.path.exists(self.logdir):\n rename = str(test_directives.get('renameTestRun', \"no\")).lower()\n if rename == \"no\":\n newname = self.logdir\n else:\n if rename == \"yes\":\n newname = \"{}{}\".format(self.logdir, self.now)\n else:\n newdir = str(test_directives.get('renameTestRun'))\n logdir = os.path.dirname(self.logdir)\n newname = os.path.join(logdir, newdir)\n os.rename(self.logdir, newname)\n self.logger.info(\"TestRunner: test log directory\\n %s\", \\\n os.path.abspath(newname))\n\n dowhat = str(test_directives.get('printTestLogPath', \"no\")).lower()\n if dowhat == \"yes\":\n self.top_logdir(newname)\n elif dowhat == \"dump\":\n self.top_logdir(newname, dumpLogs=True)\n\n def post_testcase(self, subtest_results):\n \"\"\" post testcase run processing \"\"\"\n self.logger.info(\"TestRunner: tearDown begin\")\n self.test_logdir(subtest_results)\n subtest_results.create_test_set_results()\n self.test_info.dump_test_info(self.logdir)\n self.rename_output_directory()\n self.logger.info(\"TestRunner: tearDown end\\n\\n\")\n\n def run_testcases(self):\n \"\"\" execute test scripts \"\"\"\n\n rtn = 0\n sys.path.append(\"scripts\")\n file_hdlr = logging.FileHandler(\n os.path.join(self.log_dir_base, \"TestRunner.log\"))\n file_hdlr.setLevel(logging.DEBUG)\n self.logger.addHandler(file_hdlr)\n self.test_info = TestInfoRunner(self.info)\n for test_module_name in self.test_list:\n if self.test_info.load_testcases(test_module_name):\n return 1\n # All the log files need to be in the directory with a\n # subtest_results file for mapping to Maloo entries.\n # 'node' key is set by MultiRunner\n if self.info.get_config('node'):\n self.logdir = self.log_dir_base\n else:\n self.logdir = os.path.join(self.log_dir_base, \\\n str(self.test_info.get_test_info('testName')))\n try:\n os.makedirs(self.logdir)\n except OSError:\n newname = \"{}{}\".format(self.logdir, self.now)\n os.rename(self.logdir, newname)\n os.makedirs(self.logdir)\n testMode = self.test_info.get_test_info('directives', 'testMode')\n if testMode == \"scripts\":\n runner = ScriptsRunner(self.test_info, self.logdir)\n elif testMode == \"python\":\n runner = PythonRunner(self.test_info, self.logdir)\n else:\n runner = UnitTestRunner(self.test_info, self.logdir)\n self.test_info.add_default_env()\n self.logger.info(\"****************************************\\n\")\n self.logger.info(\"TestRunner: %s\",\n self.test_info.get_test_info('testName'))\n self.logger.info(\"\\n****************************************\")\n (rc, rtn_info) = runner.execute_strategy()\n rtn |= rc\n self.post_testcase(rtn_info)\n self.test_info.cleanup_test_info()\n del rtn_info\n del runner\n self.logger.info(\n \"\\n********************************************************\")\n file_hdlr.close()\n self.logger.removeHandler(file_hdlr)\n\n return rtn\n","sub_path":"test_runner/TestRunner.py","file_name":"TestRunner.py","file_ext":"py","file_size_in_byte":5710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"529798601","text":"from app import app\nfrom app.models.SQL_DB import User, db\n\napp.config.from_pyfile('config.py')\n\nprint(\"\\nCreating DB Tables\")\ntry:\n db.create_all()\n print(\"OK : Tables Created\")\nexcept:\n print(\"BAD : Problem creating tables. Check DB connection parameters\")\n\nprint(\"\\nCreating user Admin with username/pass : admin@example.com/admin\")\ntry:\n admin = User(\n '1',\n 'admin@example.com',\n '$2b$12$0wT4k2MD5r7tcTmADJ1.ROdTNKIff2TDFIXxtXiReXauBqkDaQpgq',\n 'Admin',\n 'Admin',\n '1'\n )\n db.session.add(admin)\n db.session.commit()\n\n print(\"OK : User Admin created\")\nexcept:\n print(\"BAD : Problem in User creation\")\n","sub_path":"db_seed.py","file_name":"db_seed.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"243549482","text":"import glob\nimport os\nimport re\nimport gc\nimport matplotlib\nimport pickle as pkl\nimport skvideo.io as sio\nimport xarray as xr\nimport numpy as np\nimport functools as fct\nimport holoviews as hv\nimport dask as da\nfrom copy import deepcopy\nfrom scipy import ndimage as ndi\nfrom scipy.io import loadmat\nfrom natsort import natsorted\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation as anim\nfrom collections import Iterable\nfrom tifffile import imsave, imread\nfrom pandas import Timestamp\nfrom IPython.core.debugger import set_trace\n\n# import caiman as cm\n# from caiman import motion_correction\n# from caiman.components_evaluation import estimate_components_quality\n# from caiman.miniscope.plot import plot_components\n# from caiman.source_extraction import cnmf\n\n\ndef load_videos(vpath, pattern='msCam[0-9]+\\.avi$'):\n \"\"\"Load videos from a folder.\n\n Load videos from the folder specified in `vpath` and according to the regex\n `pattern`, then concatenate them together across time and return a\n `xarray.DataArray` representation of the concatenated videos. The default\n assumption is video filenames start with ``msCam`` followed by at least a\n number, and then followed by ``.avi``. In addition, it is assumed that the\n name of the folder correspond to a recording session identifier.\n\n Parameters\n ----------\n vpath : str\n The path to search for videos\n pattern : str, optional\n The pattern that describes filenames of videos. (Default value =\n 'msCam[0-9]+\\.avi')\n\n Returns\n -------\n xarray.DataArray or None\n The labeled 3-d array representation of the videos with dimensions:\n ``frame``, ``height`` and ``width``. Returns ``None`` if no data was\n found in the specified folder.\n\n \"\"\"\n vpath = os.path.normpath(vpath)\n vlist = natsorted([\n vpath + os.sep + v for v in os.listdir(vpath) if re.search(pattern, v)\n ])\n if not vlist:\n print(\"No data with pattern {} found in the specified folder {}\".\n format(pattern, vpath))\n return\n else:\n print(\"loading {} videos in folder {}\".format(len(vlist), vpath))\n varray = [sio.vread(v, as_grey=True) for v in vlist]\n varray = np.squeeze(np.concatenate(varray))\n return xr.DataArray(\n varray,\n dims=['frame', 'height', 'width'],\n coords={\n 'frame': range(varray.shape[0]),\n 'height': range(varray.shape[1]),\n 'width': range(varray.shape[2])\n },\n name=os.path.basename(vpath))\n\n\ndef create_fig(varlist, nrows, ncols, **kwargs):\n if not isinstance(varlist, list):\n varlist = [varlist]\n if not (nrows or ncols):\n nrows = 1\n ncols = len(varlist)\n elif nrows and not ncols:\n ncols = np.ceil(np.float(len(varlist)) / nrows).astype(int)\n elif ncols and not nrows:\n nrows = np.ceil(np.float(len(varlist)) / ncols).astype(int)\n size = kwargs.pop('size', 5)\n aspect = kwargs.pop('aspect',\n varlist[0].sizes['width'] / varlist[0].sizes['height'])\n figsize = kwargs.pop('figsize', (aspect * size * ncols, size * nrows))\n fig, ax = plt.subplots(nrows, ncols, figsize=figsize)\n if not isinstance(ax, Iterable):\n ax = np.array([ax])\n return fig, ax, varlist, kwargs\n\n\ndef animate_video(varlist, nrows=None, ncols=None, framerate=30, **kwargs):\n fig, ax, varlist, kwargs = create_fig(varlist, nrows, ncols, **kwargs)\n frms = np.min([var.sizes['frame'] for var in varlist])\n f_update = fct.partial(\n multi_im,\n varlist,\n ax=ax,\n add_colorbar=False,\n animated=True,\n tight=False,\n **kwargs)\n f_init = fct.partial(\n multi_im, varlist, subidx={'frame': 0}, ax=ax, **kwargs)\n anm = anim.FuncAnimation(\n fig,\n func=lambda f: f_update(subidx={'frame': f}),\n init_func=f_init,\n frames=frms,\n interval=1000.0 / framerate)\n return fig, anm\n\n\ndef multi_im(varlist,\n subidx=None,\n ax=None,\n nrows=None,\n ncols=None,\n animated=False,\n tight=True,\n **kwargs):\n if ax is None:\n fig, ax, varlist, kwargs = create_fig(varlist, nrows, ncols, **kwargs)\n for ivar, cur_var in enumerate(varlist):\n if subidx:\n va = cur_var.loc[subidx]\n else:\n va = cur_var\n if animated:\n ax[ivar].findobj(matplotlib.collections.QuadMesh)[0].set_array(\n np.ravel(va))\n ax[ivar].set_title(\"frame = {}\".format(int(va.coords['frame'])))\n else:\n ax[ivar].clear()\n va.plot(ax=ax[ivar], **kwargs)\n if tight:\n ax[0].get_figure().tight_layout()\n return ax\n\n\ndef plot_fluorescence(varlist, ax=None, nrows=None, ncols=None, **kwargs):\n if ax is None:\n fig, ax, varlist, kwargs = create_fig(varlist, nrows, ncols, **kwargs)\n for ivar, cur_var in enumerate(varlist):\n cur_mean = cur_var.mean(dim='height').mean(dim='width')\n cur_max = cur_var.max(dim='height').max(dim='width')\n cur_min = cur_var.min(dim='height').min(dim='width')\n ax[ivar].plot(cur_mean.indexes['frame'], cur_mean)\n ax[ivar].fill_between(\n cur_mean.indexes['frame'], cur_min, cur_max, alpha=0.2)\n ax[ivar].set_xlabel('frame')\n ax[ivar].set_ylabel('fluorescence')\n ax[ivar].set_title(cur_var.name)\n return ax\n\n\ndef save_video(movpath, fname_mov_orig, fname_mov_rig, fname_AC, fname_ACbf,\n dsratio):\n \"\"\"\n\n Parameters\n ----------\n movpath :\n\n fname_mov_orig :\n\n fname_mov_rig :\n\n fname_AC :\n\n fname_ACbf :\n\n dsratio :\n\n\n Returns\n -------\n\n\n \"\"\"\n mov_orig = np.load(fname_mov_orig, mmap_mode='r')\n mov_rig = np.load(fname_mov_rig, mmap_mode='r')\n mov_ac = np.load(fname_AC, mmap_mode='r')\n mov_acbf = np.load(fname_ACbf, mmap_mode='r')\n vw = sio.FFmpegWriter(\n movpath, inputdict={'-framerate': '30'}, outputdict={'-r': '30'})\n for fidx in range(0, mov_orig.shape[0], dsratio):\n print(\"writing frame: \" + str(fidx))\n fm_orig = mov_orig[fidx, :, :] * 255\n fm_rig = mov_rig[fidx, :, :] * 255\n fm_acbf = mov_acbf[fidx, :, :] * 255\n fm_ac = mov_ac[fidx, :, :] * 255\n fm = np.concatenate(\n [\n np.concatenate([fm_orig, fm_rig], axis=1),\n np.concatenate([fm_acbf, fm_ac], axis=1)\n ],\n axis=0)\n vw.writeFrame(fm)\n vw.close()\n\n\ndef save_mp4(filename, dat):\n \"\"\"\n\n Parameters\n ----------\n filename :\n\n dat :\n\n\n Returns\n -------\n\n\n \"\"\"\n vw = sio.FFmpegWriter(\n filename,\n inputdict={'-framerate': '30'},\n outputdict={'-r': '30',\n '-vcodec': 'rawvideo'})\n for fid, f in enumerate(dat):\n print(\"writing frame: {}\".format(fid), end='\\r')\n vw.writeFrame(f)\n vw.close()\n\n\ndef mov_to_uint8(mov):\n \"\"\"\n\n Parameters\n ----------\n mov :\n\n\n Returns\n -------\n\n\n\n \"\"\"\n return np.uint8((mov - np.min(mov)) / (np.max(mov) - np.min(mov)) * 255)\n\n\ndef mov_to_float32(mov):\n \"\"\"\n\n Parameters\n ----------\n mov :\n\n\n Returns\n -------\n\n\n \"\"\"\n return np.float32((mov - np.min(mov)) / (np.max(mov) - np.min(mov)))\n\n\ndef varr_to_uint8(varr):\n varr_max = varr.max()\n varr_min = varr.min()\n return ((varr - varr_min) / (varr_max - varr_min) * 255).astype(\n np.uint8, copy=False)\n\n\ndef varr_to_float32(varr):\n varr = varr.astype(np.float32, copy=False)\n varr_max = varr.max()\n varr_min = varr.min()\n varr, varr_min_bd = xr.broadcast(varr, varr_min)\n varr_norm = varr - varr_min_bd\n del varr_min_bd\n gc.collect()\n varr_norm, varr_denom = xr.broadcast(varr_norm, (varr_max - varr_min))\n varr_norm = varr_norm / varr_denom\n del varr_denom\n return varr_norm\n\n\ndef scale_varr(varr, scale=(0, 1), inplace=True):\n copy = not inplace\n if np.issubdtype(varr.dtype, np.floating):\n dtype = varr.dtype\n else:\n dtype = np.float32\n varr_norm = varr.astype(dtype, copy=copy)\n varr_max = varr_norm.max()\n varr_min = varr_norm.min()\n varr_norm -= varr_min\n varr_norm *= 1 / (varr_max - varr_min)\n varr_norm *= (scale[1] - scale[0])\n varr_norm += scale[0]\n return varr_norm.astype(varr.dtype, copy=False)\n\n\ndef varray_to_tif(filename, varr):\n imsave(filename, varr.transpose('frame', 'height', 'width'))\n\n\ndef tif_to_varray(filename):\n arr = imread(filename)\n f = arr.shape[0]\n h = arr.shape[1]\n w = arr.shape[2]\n varr = xr.DataArray(\n arr,\n coords=dict(frame=range(f), height=range(h), width=range(w)),\n dims=['frame', 'height', 'width'])\n varr.to_netcdf(os.path.dirname(filename) + os.sep + 'varr_mc_int.nc')\n return varr\n\n\ndef resave_varr(path, pattern='^varr_mc_int.tif$'):\n path = os.path.normpath(path)\n tiflist = []\n for dirpath, dirnames, fnames in os.walk(path):\n tifnames = filter(lambda fn: re.search(pattern, fn), fnames)\n tif_paths = [os.path.join(dirpath, tif) for tif in tifnames]\n tiflist += tif_paths\n for itif, tif_path in enumerate(tiflist):\n print(\"processing {:2d} of {:2d}\".format(itif, len(tiflist)), end='\\r')\n cur_var = tif_to_varray(tif_path)\n if not cur_var.sizes['height'] == 480 or not cur_var.sizes['width'] == 752:\n print(\"file {} has modified size: {}\".format(\n tif_path, cur_var.sizes))\n\n\ndef plot_varr(varr):\n dvarr = hv.Dataset(varr, kdims=['width', 'height', 'frame'])\n layout = dvarr.to(hv.Image, ['width', 'height'])\n return layout\n\n\ndef save_cnmf(cnmf,\n dpath,\n save_pkl=True,\n from_pkl=False,\n unit_mask=None,\n meta_dict=None,\n order='C'):\n dpath = os.path.normpath(dpath)\n if from_pkl:\n with open(dpath + os.sep + 'cnm.pkl', 'rb') as f:\n cnmf = pkl.load(f)\n else:\n cnmf.dview = None\n if save_pkl:\n with open(dpath + os.sep + 'cnm.pkl', 'wb') as f:\n pkl.dump(cnmf, f)\n varr = xr.open_dataset(dpath + os.sep + 'varr_mc_int.nc')['varr_mc_int']\n f = varr.coords['frame']\n h = varr.coords['height']\n w = varr.coords['width']\n dims = cnmf.dims\n A = xr.DataArray(\n cnmf.A.toarray().reshape(dims + (-1, ), order=order),\n coords={'height': h,\n 'width': w,\n 'unit_id': range(cnmf.A.shape[-1])},\n dims=['height', 'width', 'unit_id'],\n name='A')\n C = xr.DataArray(\n cnmf.C,\n coords={'unit_id': range(cnmf.C.shape[0]),\n 'frame': f},\n dims=['unit_id', 'frame'],\n name='C')\n S = xr.DataArray(\n cnmf.S,\n coords={'unit_id': range(cnmf.S.shape[0]),\n 'frame': f},\n dims=['unit_id', 'frame'],\n name='S')\n YrA = xr.DataArray(\n cnmf.YrA,\n coords={'unit_id': range(cnmf.S.shape[0]),\n 'frame': f},\n dims=['unit_id', 'frame'],\n name='YrA')\n b = xr.DataArray(\n cnmf.b.reshape(dims + (-1, ), order=order),\n coords={\n 'height': h,\n 'width': w,\n 'background_id': range(cnmf.b.shape[-1])\n },\n dims=['height', 'width', 'background_id'],\n name='b')\n f = xr.DataArray(\n cnmf.f,\n coords={'background_id': range(cnmf.f.shape[0]),\n 'frame': f},\n dims=['background_id', 'frame'],\n name='f')\n ds = xr.merge([A, C, S, YrA, b, f])\n if from_pkl:\n ds.to_netcdf(dpath + os.sep + 'cnm.nc', mode='a')\n else:\n if unit_mask is None:\n unit_mask = np.arange(ds.sizes['unit_id'])\n if meta_dict is not None:\n pathlist = os.path.normpath(dpath).split(os.sep)\n ds = ds.assign_coords(\n **dict([(cdname, pathlist[cdval])\n for cdname, cdval in meta_dict.items()]))\n ds = ds.assign_attrs({\n 'unit_mask': unit_mask,\n 'file_path': dpath + os.sep + \"cnm.nc\"\n })\n ds.to_netcdf(dpath + os.sep + \"cnm.nc\")\n return ds\n\n\ndef save_varr(varr, dpath, name='varr_mc_int', meta_dict=None):\n dpath = os.path.normpath(dpath)\n ds = varr.to_dataset(name=name)\n if meta_dict is not None:\n pathlist = os.path.normpath(dpath).split(os.sep)\n ds = ds.assign_coords(**dict([(cdname, pathlist[cdval])\n for cdname, cdval in meta_dict.items()]))\n ds = ds.assign_attrs({'file_path': dpath + os.sep + name + '.nc'})\n ds.to_netcdf(dpath + os.sep + name + '.nc')\n return ds\n\n\ndef save_variable(var, fpath, fname, meta_dict=None):\n fpath = os.path.normpath(fpath)\n ds = var.to_dataset()\n if meta_dict is not None:\n pathlist = os.path.normpath(fpath).split(os.sep)\n ds = ds.assign_coords(**dict([(cdname, pathlist[cdval])\n for cdname, cdval in meta_dict.items()]))\n try:\n ds.to_netcdf(os.path.join(fpath, fname + '.nc'), mode='a')\n except FileNotFoundError:\n ds.to_netcdf(os.path.join(fpath, fname + '.nc'), mode='w')\n return ds\n\n\ndef update_meta(dpath, pattern=r'^varr_mc_int.nc$', meta_dict=None):\n for dirpath, dirnames, fnames in os.walk(dpath):\n fnames = filter(lambda fn: re.search(pattern, fn), fnames)\n for fname in fnames:\n f_path = os.path.join(dirpath, fname)\n pathlist = os.path.normpath(dirpath).split(os.sep)\n new_ds = xr.Dataset()\n with xr.open_dataset(f_path) as old_ds:\n new_ds.attrs = deepcopy(old_ds.attrs)\n new_ds = new_ds.assign_coords(\n **dict([(cdname, pathlist[cdval])\n for cdname, cdval in meta_dict.items()]))\n new_ds = new_ds.assign_attrs(dict(file_path=f_path))\n new_ds.to_netcdf(f_path, mode='a')\n print(\"updated: {}\".format(f_path))\n\n\n# def resave_varr_again(dpath, pattern=r'^varr_mc_int.nc$'):\n# for dirpath, dirnames, fnames in os.walk(dpath):\n# fnames = filter(lambda fn: re.search(pattern, fn), fnames)\n# for fname in fnames:\n# f_path = os.path.join(dirpath, fname)\n# with xr.open_dataset(f_path) as old_ds:\n# vname = list(old_ds.data_vars.keys())[0]\n# if vname == 'varr_mc_int':\n# continue\n# print(\"resaving {}\".format(f_path))\n# ds = old_ds.load().copy()\n# ds = ds.rename({vname: 'varr_mc_int'})\n# ds.to_netcdf(f_path, mode='w')\n\n\n# def resave_cnmf(dpath, pattern=r'^cnm.nc$'):\n# for dirpath, fdpath, fpath in os.walk(dpath):\n# f_list = filter(lambda fn: re.search(pattern, fn), fpath)\n# for cnm_path in f_list:\n# cnm_path = os.path.join(dirpath, cnm_path)\n# cur_cnm = xr.open_dataset(cnm_path)\n# newds = xr.Dataset()\n# newds.assign_coords(session=cur_cnm.coords['session'])\n# newds.assign_coords(animal=cur_cnm.coords['animal'])\n# newds.assign_coords(session_id=cur_cnm.coords['session_id'])\n# fpath = str(cur_cnm.attrs['file_path'])\n# cur_cnm.close()\n# print(\"writing to \".format(fpath))\n# newds.to_netcdf(fpath, mode='a')\n\n\ndef save_movies(cnmf, dpath, Y=None, mask=None, Y_only=True, order='C'):\n try:\n cnmd = vars(cnmf)\n except TypeError:\n cnmd = cnmf\n dims = cnmd['dims']\n if not Y_only:\n print(\"calculating A * C\")\n if mask is not None:\n A_dot_C = cnmd['A'].toarray()[:, mask].dot(\n cnmd['C'][mask, :]).astype(np.float32)\n else:\n A_dot_C = cnmd['A'].toarray().dot(cnmd['C']).astype(np.float32)\n print(\"calculating b * f\")\n b_dot_f = cnmd['b'].dot(cnmd['f']).astype(np.float32)\n A_dot_C = xr.DataArray(\n A_dot_C.reshape(dims + (-1, ), order=order),\n coords={\n 'height': range(dims[0]),\n 'width': range(dims[1]),\n 'frame': range(A_dot_C.shape[-1])\n },\n dims=['height', 'width', 'frame'],\n name='A_dot_C')\n b_dot_f = xr.DataArray(\n b_dot_f.reshape(dims + (-1, ), order=order),\n coords={\n 'height': range(dims[0]),\n 'width': range(dims[1]),\n 'frame': range(b_dot_f.shape[-1])\n },\n dims=['height', 'width', 'frame'],\n name='b_dot_f')\n if Y is not None:\n Y = np.moveaxis(Y.astype(np.float32), 0, -1)\n if not isinstance(Y, xr.DataArray):\n Y = xr.DataArray(\n Y,\n coords={\n 'height': range(Y.shape[0]),\n 'width': range(Y.shape[1]),\n 'frame': range(Y.shape[2])\n },\n dims=['height', 'width', 'frame'],\n name='Y')\n if not Y_only:\n print(\"calculating Yres\")\n Yres = Y.copy()\n Yres -= A_dot_C\n Yres -= b_dot_f\n Yres = Yres.rename('Yres')\n else:\n Yres = None\n if not Y_only:\n print(\"merging\")\n ds = xr.merge([Y, A_dot_C, b_dot_f, Yres])\n else:\n ds = Y\n print(\"writing to disk\")\n ds.to_netcdf(dpath + os.sep + \"movies.nc\")\n return ds\n\n\ndef save_cnmf_from_mat(matpath,\n dpath,\n vname=\"ms\",\n order='C',\n dims=None,\n T=None,\n unit_mask=None,\n meta_dict=None):\n dpath = os.path.normpath(dpath)\n mat = loadmat(matpath, squeeze_me=True, struct_as_record=False)\n try:\n cnmf = mat[vname]\n except KeyError:\n print(\"No variable with name {} was found in the .mat file: {}\".format(\n vname, matpath))\n return\n if not dims:\n dims = (cnmf.options.d1, cnmf.options.d2)\n dims_coord = (list(range(dims[0])), list(range(dims[1])))\n else:\n dims_coord = (np.linspace(0, dims[0] - 1, cnmf.options.d1),\n np.linspace(0, dims[1] - 1, cnmf.options.d2))\n dims = (cnmf.options.d1, cnmf.options.d2)\n if not T:\n T = cnmf.C.shape[1]\n T_coord = list(range(T))\n else:\n T_coord = np.linspace(0, T - 1, cnmf.C.shape[1])\n T = cnmf.C.shape[1]\n A = xr.DataArray(\n cnmf.A.reshape(dims + (-1, ), order=order),\n coords={\n 'height': dims_coord[0],\n 'width': dims_coord[1],\n 'unit_id': range(cnmf.A.shape[-1])\n },\n dims=['height', 'width', 'unit_id'],\n name='A')\n C = xr.DataArray(\n cnmf.C,\n coords={'unit_id': range(cnmf.C.shape[0]),\n 'frame': T_coord},\n dims=['unit_id', 'frame'],\n name='C')\n S = xr.DataArray(\n cnmf.S,\n coords={'unit_id': range(cnmf.S.shape[0]),\n 'frame': T_coord},\n dims=['unit_id', 'frame'],\n name='S')\n if cnmf.b.any():\n b = xr.DataArray(\n cnmf.b.reshape(dims + (-1, ), order=order),\n coords={\n 'height': dims_coord[0],\n 'width': dims_coord[1],\n 'background_id': range(cnmf.b.shape[-1])\n },\n dims=['height', 'width', 'background_id'],\n name='b')\n else:\n b = xr.DataArray(\n np.zeros(dims + (1, )),\n coords=dict(\n height=dims_coord[0], width=dims_coord[1], background_id=[0]),\n dims=['height', 'width', 'background_id'],\n name='b')\n if cnmf.f.any():\n f = xr.DataArray(\n cnmf.f,\n coords={'background_id': range(cnmf.f.shape[0]),\n 'frame': T_coord},\n dims=['background_id', 'frame'],\n name='f')\n else:\n f = xr.DataArray(\n np.zeros((1, T)),\n coords=dict(background_id=[0], frame=T_coord),\n dims=['background_id', 'frame'],\n name='f')\n ds = xr.merge([A, C, S, b, f])\n if unit_mask is None:\n unit_mask = np.arange(ds.sizes['unit_id'])\n if meta_dict is not None:\n pathlist = os.path.normpath(dpath).split(os.sep)\n ds = ds.assign_coords(\n **{cdname: pathlist[cdval]\n for cdname, cdval in meta_dict.items()})\n ds = ds.assign_attrs({\n 'unit_mask': unit_mask,\n 'file_path': dpath + os.sep + \"cnm_from_mat.nc\"\n })\n ds.to_netcdf(dpath + os.sep + \"cnm_from_mat.nc\")\n return ds\n\n\n# def process_data(dpath, movpath, pltpath, roi):\n# params_movie = {\n# 'niter_rig': 1,\n# 'max_shifts': (20, 20),\n# 'splits_rig': 28,\n# 'num_splits_to_process_rig': None,\n# 'strides': (48, 48),\n# 'overlaps': (24, 24),\n# 'splits_els': 28,\n# 'num_splits_to_process_els': [14, None],\n# 'upsample_factor_grid': 4,\n# 'max_deviation_rigid': 3,\n# 'p': 1,\n# 'merge_thresh': 0.9,\n# 'rf': 40,\n# 'stride_cnmf': 20,\n# 'K': 4,\n# 'is_dendrites': False,\n# 'init_method': 'greedy_roi',\n# 'gSig': [10, 10],\n# 'alpha_snmf': None,\n# 'final_frate': 30\n# }\n# if not dpath.endswith(os.sep):\n# dpath = dpath + os.sep\n# if not os.path.isfile(dpath + 'mc.npz'):\n# # start parallel\n# c, dview, n_processes = cm.cluster.setup_cluster(\n# backend='local', n_processes=None, single_thread=False)\n# dpattern = 'msCam*.avi'\n# dlist = sorted(glob.glob(dpath + dpattern),\n# key=lambda var: [int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)])\n# if not dlist:\n# print(\"No data found in the specified folder: \" + dpath)\n# return\n# else:\n# vdlist = list()\n# for vname in dlist:\n# vdlist.append(sio.vread(vname, as_grey=True))\n# mov_orig = cm.movie(\n# np.squeeze(np.concatenate(vdlist, axis=0))).astype(np.float32)\n# # column correction\n# meanrow = np.mean(np.mean(mov_orig, 0), 0)\n# addframe = np.tile(meanrow, (mov_orig.shape[1], 1))\n# mov_cc = mov_orig - np.tile(addframe, (mov_orig.shape[0], 1, 1))\n# mov_cc = mov_cc - np.min(mov_cc)\n# # filter\n# mov_ft = mov_cc.copy()\n# for fid, fm in enumerate(mov_cc):\n# mov_ft[fid] = ndi.uniform_filter(fm, 2) - ndi.uniform_filter(\n# fm, 40)\n# mov_orig = (mov_orig - np.min(mov_orig)) / (\n# np.max(mov_orig) - np.min(mov_orig))\n# mov_ft = (mov_ft - np.min(mov_ft)) / (\n# np.max(mov_ft) - np.min(mov_ft))\n# np.save(dpath + 'mov_orig', mov_orig)\n# np.save(dpath + 'mov_ft', mov_ft)\n# del mov_orig, dlist, vdlist, mov_ft\n# mc_data = motion_correction.MotionCorrect(\n# dpath + 'mov_ft.npy',\n# 0,\n# dview=dview,\n# max_shifts=params_movie['max_shifts'],\n# niter_rig=params_movie['niter_rig'],\n# splits_rig=params_movie['splits_rig'],\n# num_splits_to_process_rig=params_movie[\n# 'num_splits_to_process_rig'],\n# strides=params_movie['strides'],\n# overlaps=params_movie['overlaps'],\n# splits_els=params_movie['splits_els'],\n# num_splits_to_process_els=params_movie[\n# 'num_splits_to_process_els'],\n# upsample_factor_grid=params_movie['upsample_factor_grid'],\n# max_deviation_rigid=params_movie['max_deviation_rigid'],\n# shifts_opencv=True,\n# nonneg_movie=False,\n# roi=roi)\n# mc_data.motion_correct_rigid(save_movie=True)\n# mov_rig = cm.load(mc_data.fname_tot_rig)\n# np.save(dpath + 'mov_rig', mov_rig)\n# np.savez(\n# dpath + 'mc',\n# fname_tot_rig=mc_data.fname_tot_rig,\n# templates_rig=mc_data.templates_rig,\n# shifts_rig=mc_data.shifts_rig,\n# total_templates_rig=mc_data.total_template_rig,\n# max_shifts=mc_data.max_shifts,\n# roi=mc_data.roi)\n# del mov_rig\n# else:\n# print(\"motion correction data already exist. proceed\")\n# if not os.path.isfile(dpath + \"cnm.npz\"):\n# # start parallel\n# c, dview, n_processes = cm.cluster.setup_cluster(\n# backend='local', n_processes=None, single_thread=False)\n# fname_tot_rig = np.array_str(\n# np.load(dpath + 'mc.npz')['fname_tot_rig'])\n# mov, dims, T = cm.load_memmap(fname_tot_rig)\n# mov = np.reshape(mov.T, [T] + list(dims), order='F')\n# cnm = cnmf.CNMF(\n# n_processes,\n# k=params_movie['K'],\n# gSig=params_movie['gSig'],\n# merge_thresh=params_movie['merge_thresh'],\n# p=params_movie['p'],\n# dview=dview,\n# Ain=None,\n# rf=params_movie['rf'],\n# stride=params_movie['stride_cnmf'],\n# memory_fact=1,\n# method_init=params_movie['init_method'],\n# alpha_snmf=params_movie['alpha_snmf'],\n# only_init_patch=True,\n# gnb=1,\n# method_deconvolution='oasis')\n# cnm = cnm.fit(mov)\n# idx_comp, idx_comp_bad = estimate_components_quality(\n# cnm.C + cnm.YrA,\n# np.reshape(mov, dims + (T, ), order='F'),\n# cnm.A,\n# cnm.C,\n# cnm.b,\n# cnm.f,\n# params_movie['final_frate'],\n# Npeaks=10,\n# r_values_min=.7,\n# fitness_min=-40,\n# fitness_delta_min=-40)\n# A2 = cnm.A.tocsc()[:, idx_comp]\n# C2 = cnm.C[idx_comp]\n# cnm = cnmf.CNMF(\n# n_processes,\n# k=A2.shape,\n# gSig=params_movie['gSig'],\n# merge_thresh=params_movie['merge_thresh'],\n# p=params_movie['p'],\n# dview=dview,\n# Ain=A2,\n# Cin=C2,\n# f_in=cnm.f,\n# rf=None,\n# stride=None,\n# method_deconvolution='oasis')\n# cnm = cnm.fit(mov)\n# idx_comp, idx_comp_bad = estimate_components_quality(\n# cnm.C + cnm.YrA,\n# np.reshape(mov, dims + (T, ), order='F'),\n# cnm.A,\n# cnm.C,\n# cnm.b,\n# cnm.f,\n# params_movie['final_frate'],\n# Npeaks=10,\n# r_values_min=.75,\n# fitness_min=-50,\n# fitness_delta_min=-50)\n# cnm.A = cnm.A.tocsc()[:, idx_comp]\n# cnm.C = cnm.C[idx_comp]\n# cm.cluster.stop_server()\n# cnm.A = (cnm.A - np.min(cnm.A)) / (np.max(cnm.A) - np.min(cnm.A))\n# cnm.C = (cnm.C - np.min(cnm.C)) / (np.max(cnm.C) - np.min(cnm.C))\n# cnm.b = (cnm.b - np.min(cnm.b)) / (np.max(cnm.b) - np.min(cnm.b))\n# cnm.f = (cnm.f - np.min(cnm.f)) / (np.max(cnm.f) - np.min(cnm.f))\n# np.savez(\n# dpath + 'cnm',\n# A=cnm.A.todense(),\n# C=cnm.C,\n# b=cnm.b,\n# f=cnm.f,\n# YrA=cnm.YrA,\n# sn=cnm.sn,\n# dims=dims)\n# else:\n# print(\"cnm data already exist. proceed\")\n# try:\n# A = cnm.A\n# C = cnm.C\n# dims = dims\n# except NameError:\n# A = np.load(dpath + 'cnm.npz')['A']\n# C = np.load(dpath + 'cnm.npz')['C']\n# dims = np.load(dpath + 'cnm.npz')['dims']\n# plot_components(A, C, dims, pltpath)\n\n# def batch_process_data(animal_path, movroot, pltroot, roi):\n# for dirname, subdirs, files in os.walk(animal_path):\n# if files:\n# dirnamelist = dirname.split(os.sep)\n# dname = dirnamelist[-3] + '_' + dirnamelist[-2]\n# movpath = movroot + os.sep + dname\n# pltpath = pltroot + os.sep + dname\n# if not os.path.exists(movpath):\n# os.mkdir(movpath)\n# if not os.path.exists(pltpath):\n# os.mkdir(pltpath)\n# movpath = movpath + os.sep\n# pltpath = pltpath + os.sep\n# process_data(dirname, movpath, pltpath, roi)\n# else:\n# print(\"empty folder: \" + dirname + \" proceed\")\n","sub_path":"minian/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":28985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629381078","text":"import urllib.request\nimport datetime\nimport json\n\njsonResult = []\nsNode = 'news'\nsearch_text = '빅데이터'\nthe_number_of_news = 20\napp_id = 'CPEJTAuJERmw937Qegcz'\napp_pw = 'DbKVsbxnLD'\n\ndef get_request_url(url):\n req = urllib.request.Request(url)\n req.add_header(\"X-Naver-Client-Id\", app_id)\n req.add_header(\"X-Naver-Client-Secret\", app_pw)\n\n try:\n response = urllib.request.urlopen(req)\n if response.getcode() == 200:\n print(\"[검색 시간 : %s] '%s'에 대한 최신 %d건의 검색 결과입니다.\\n\" %(datetime.datetime.now(), search_text, the_number_of_news))\n return response.read().decode('utf-8')\n except Exception as e:\n print(e)\n print(\"[%s] Error for URL: %s\\n\" %(datetime.datetime.now(), url))\n return None\n\ndef getNaverSearchResult(sNode, search_text, page_start, display):\n base = \"https://openapi.naver.com/v1/search\"\n node = \"/%s.json\" %sNode\n parameters = \"?query=%s&start=%s&display=%s\" %(urllib.parse.quote(search_text), page_start, display)\n url = base + node + parameters\n retData = get_request_url(url)\n\n if(retData == None):\n return None\n else:\n return json.loads(retData)\n\njsonSearch = getNaverSearchResult(sNode, search_text, 1, the_number_of_news)\n\nindex = 1\nfor post in jsonSearch['items']:\n print(\"%s. %s - %s\" %(\"{0:0>2}\".format(index), post['title'], post['originallink']))\n index += 1\n","sub_path":"AI R&D/search_keyword_news.py","file_name":"search_keyword_news.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"552818900","text":"class Solution:\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n res = []\n copynum1 = list(set(nums1))\n copynum2 = list(set(nums2))\n maximum = 0\n if(len(copynum1) > len(copynum2)):\n maximum = len(copynum1)\n for i in range(0,maximum):\n if(copynum1[i] in copynum2):\n res.append(copynum1[i])\n else:\n for i in range(0,len(copynum2)):\n if(copynum2[i] in copynum1):\n res.append(copynum2[i])\n return res\n","sub_path":"349. Intersection of Two Arrays/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"484867160","text":"from random import choice\n\n\nclass TicTacToe:\n def __init__(self):\n self.game_over = False\n self.players = {'X': '', 'O': ''}\n self.players_moves = {'user': self.get_user_move, 'comp': self.get_ai_move}\n self.players_lvl = ['user', 'easy', 'medium', 'hard']\n self.current_move = 'X'\n self.field = [[' '] * 3 for _ in range(3)]\n\n def start(self):\n while True:\n init, *params = input('Input command: ').split()\n if init == 'exit':\n break\n self.__init__()\n check = self.game_params_handler(*params)\n if check:\n self.game_handler()\n\n def game_params_handler(self, pl1=None, pl2=None):\n if pl1 in self.players_lvl and pl2 in self.players_lvl:\n self.players['X'], self.players['O'] = pl1, pl2\n return True\n print('Bad parameters!')\n return False\n\n def game_handler(self):\n self.print_field()\n while not self.game_over:\n self.moves_handler(self.current_move)\n self.print_field()\n self.game_status_handler()\n self.current_move = 'O' if self.current_move == 'X' else 'X'\n\n def print_field(self):\n print('-' * 9)\n for row in self.field:\n print('|', *row, '|')\n print('-' * 9)\n\n def check_user_move(self, pos):\n if not all(spot.isdigit() for spot in pos):\n print('You should enter numbers!')\n elif not (0 < int(pos[0]) < 4) or not (0 < int(pos[1]) < 4):\n print('Coordinates should be from 1 to 3!')\n elif self.field[3 - int(pos[1])][int(pos[0]) - 1] != ' ':\n print('This cell is occupied! Choose another one!')\n else:\n return True\n\n def get_user_move(self):\n pos = input('Enter the coordinates: ').split()\n checked = self.check_user_move(pos)\n while not checked:\n pos = input('Enter the coordinates: ').split()\n checked = self.check_user_move(pos)\n return 3 - int(pos[1]), int(pos[0]) - 1\n\n def get_ai_move(self, lvl, x=None, y=None):\n print(f'Making move level \"{lvl}\"')\n if lvl == 'easy':\n free_cells = [(i, j) for i in range(3) for j in range(3) if self.field[i][j] == ' ']\n x, y = choice(free_cells)\n elif lvl == 'medium':\n res, x, y = self.minimax(self.current_move, 2)\n elif lvl == 'hard':\n res, x, y = self.minimax(self.current_move)\n return x, y\n\n def minimax(self, move, deep=None, cur_deep=0, x=None, y=None, alpha=-2, beta=2):\n free_cells = [(x, y) for x in range(3) for y in range(3) if self.field[x][y] == ' ']\n prev_move = 'O' if self.current_move == 'X' else 'X'\n init_res = 2 if prev_move == move else -2\n\n if self.is_winner([prev_move] * 3):\n return (1, 0, 0) if prev_move == move else (-1, 0, 0)\n if len(free_cells) == 0 or deep == cur_deep:\n return 0, 0, 0\n\n cur_deep += 1\n for i, j in free_cells:\n self.field[i][j] = self.current_move\n self.current_move = 'O' if self.current_move == 'X' else 'X'\n res, i_max, j_max = self.minimax(move, deep, cur_deep, alpha=alpha, beta=beta)\n self.current_move = 'O' if self.current_move == 'X' else 'X'\n self.field[i][j] = ' '\n if prev_move == move:\n if res < init_res:\n init_res, x, y = res, i, j\n if init_res <= alpha:\n return init_res, x, y\n if init_res < beta:\n beta = init_res\n\n elif prev_move != move:\n if res > init_res:\n init_res, x, y = res, i, j\n if init_res >= beta:\n return init_res, x, y\n if init_res > alpha:\n alpha = init_res\n\n return init_res, x, y\n\n def moves_handler(self, move):\n x, y = self.get_user_move() if self.players[move] == 'user' else self.get_ai_move(self.players[move])\n self.field[x][y] = self.current_move\n\n def is_winner(self, win_move):\n if (win_move in self.field or\n win_move in list(map(list, zip(*self.field))) or\n win_move == [self.field[i][i] for i in range(3)] or\n win_move == [self.field[i][2 - i] for i in range(3)]):\n return True\n return False\n\n def game_status_handler(self):\n if self.is_winner([self.current_move] * 3):\n self.game_over = True\n print(self.current_move, 'wins')\n else:\n free_cells = [(x, y) for x in range(3) for y in range(3) if self.field[x][y] == ' ']\n if len(free_cells) == 0:\n self.game_over = True\n print('Draw')\n\n\ngame = TicTacToe()\ngame.start()\n","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"614626535","text":"#!/usr/bin/env python3 \n\nfrom transformers import BertTokenizer\nbatch_input_str = ((\"Mary spends $20 on pizza\"), (\"She likes eating it\"), (\"The pizza was great\"))\ninput_str = ['hello', 'hello', 'hey']\ntok = BertTokenizer.from_pretrained('bert-base-uncased')\n\nimport ipdb\nipdb.set_trace()\nprint(tok.batch_encode_plus(batch_input_str, pad_to_max_length=True))\n","sub_path":"hf_issues/is_3237_batch_encode_plus.py","file_name":"is_3237_batch_encode_plus.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"572603933","text":"#\n# Copyright 2019 FMR LLC \n#\n# SPDX-License-Identifier: MIT\n#\n\"\"\"Display the last CloudTrail events in an account.\n\n## Overview\n\n`last` provides an easier way to review CloudTrail events in either an\ninteractive or non-interactive manner depending on whether or not the\n`--interactive` flag was supplied. In both cases, the events are grouped\ntogether by the user that caused them.\n\nWith no addition arguments besides specification of `--region`, the last\ncommand retrieves the past one hour of write events up to a maximum of 1,000\nevents per account/region pair. Newest events are shown at the top. If output\nis not being redirected, events from the same user are displayed in the same\ncolor.\n\n $ awsrun --account 100200300400 last --region us-east-1\n Loading events, 1000 max per acct/region, use --max-events to change\n 100200300400/us-east-1: 2020-04-08 00:43:43-05:00 logs.amazonaws.com CreateLogGroup ECSClusterRole/i-XXXXXXXXXXXXXXXXX\n 100200300400/us-east-1: 2020-04-08 00:43:39-05:00 logs.amazonaws.com CreateLogGroup ECSClusterRole/i-XXXXXXXXXXXXXXXXX\n 100200300400/us-east-1: 2020-04-08 00:43:38-05:00 logs.amazonaws.com CreateLogGroup ECSClusterRole/i-XXXXXXXXXXXXXXXXX\n 100200300400/us-east-1: 2020-04-08 00:43:35-05:00 logs.amazonaws.com CreateLogGroup ECSClusterRole/i-XXXXXXXXXXXXXXXXX\n\nThe first column of output is the account/region where the event was\ncollected. The second column is the event timestamp. The third column is the\nevent source. The fourth column is the event name. And the last column is the\n\"user\" that generated the event.\n\nUsers can specify time ranges using `--start` and `--end` flags. These take\nISO 8601 formatted dates: `2020-04-07T22:30:00-0500`. When specifying a time\nrange, use either `--last` HOURS or `--start`/`--end` flags, but not both at\nsame time. If none of these flags are specified, the past hour of events is\nretrieved by default. For example, the following command retrieves a 1-minute\nwindow of write events:\n\n $ awsrun --account 100200300400 last --region us-east-1 --start 2020-04-07T00:20:00-0500 --end 2020-04-07T00:21:00-0500\n\nAs stated before, only write events are retrieved, but Users can filter events\nby any of the supported lookup attributes in CloudTrail via the `--attribute`:\nEventId, EventName, ReadOnly, Username, ResourceType, ResourceName,\nEventSource, or AccessKeyId. To filter on console logins for the past 12\nhours:\n\n $ awsrun --account 100200300400 last --region us-east-1 --hours 12 --attribute EventName=ConsoleLogin\n Loading events, 1000 max per acct/region, use --max-events to change\n 100200300400/us-east-1: 2020-04-08 00:56:17-05:00 signin.amazonaws.com ConsoleLogin Operator/user@example.com\n\nTwo shorthand attribute filters exist. The `--all` flag will select all events\nincluding the read-only events. The `--console` flag will filter on console\nlogins as above:\n\n $ awsrun --account 100200300400 last --region us-east-1 --hours 12 --console\n Loading events, 1000 max per acct/region, use --max-events to change\n 100200300400/us-east-1: 2020-04-08 00:56:17-05:00 signin.amazonaws.com ConsoleLogin Operator/user@example.com\n\nTo minimize memory footprint and load on AWS servers, a maximum of 1,000\nevents are pulled from an account/region pair. Use the `--max-events` flag to\noverride the value.\n\nFinally, for a TUI (terminal user interface) that lets you interactively\nexplore events, specify the `--interactive` flag. Follow the on-screen\ninstructions to interact with the TUI. By default, the TUI uses a horizontal\nlayout. Specify the `--vertical` option to change to a vertical layout. The\ncolor used in the TUI can be changed via the `--color` option. Valid choices\ninclude blue, green, cyan, magenta, red, and white.\n\n## Reference\n\n### Synopsis\n\n $ awsrun [options] last [command options]\n\n### Configuration\n\nThe following is the syntax for the options that can be specified in the user\nconfiguration file:\n\n Commands:\n last:\n hours: INT\n max_events: INT\n region:\n - STRING\n all: BOOLEAN\n console: BOOLEAN\n attributes:\n STRING:\n - STRING\n interactive: BOOLEAN\n vertical: BOOLEAN\n color: STRING\n\n### Command Options\nSome options can be overridden on the awsrun CLI via command line flags. In\nthose cases, the CLI flags are specified next to the option name below:\n\n`hours`, `--hours INT`\n: Specifies the how many hours of events to retrieve. The default value is 1\nhour. Note: The number of events retrieved will not exceed `max_events`.\n\n`max_events`, `--max-events INT`\n: Specifies the upper limit on the number of events to retrieve on a per account\nper region basis. The default value is 1,000 events.\n\n`region`, `--region REGION`\n: Run the command in the specified regions. When specifying multiple values on\nthe command line, use multiple flags for each value.\n\n`all`, `--all`\n: Retrieve all CloudTrail events including read-only events. The default value\nis False. This option is mutually exclusive with the `console` and `attributes`\noptions.\n\n`console`, `--console`\n: Retrieve only console login CloudTrail events. The default is value is False.\nThis option is mutually exclusive with the `all` and `attributes` options.\n\n`attributes`, `--attribute KEY=VALUE`\n: Retrieve only CloudTrail events matching the attribute key and value. The\npossible key values are: `EventId`, `EventName`, `ReadOnly`, `Username`,\n`ResourceType`, `ResourceName`, `EventSource`, and `AccessKeyId`. Due to\nlimitations in the CloudTrail API, only one attribute can be specified. This\noption is mutually exclusive with the `all` and `console` options.\n\n`interactive`, `--interactive`\n: Open an interactive TUI (terminal user interface) instead of printing events\nto the console. The default value is False.\n\n`vertical`, `--vertical`\n: When using the `interactive` mode in a taller but narrow terminal, place the\nevent detail widget under the other for a single column grid layout. The default\nvalue is False.\n\n`color`, `--color COLOR`\n: Specify a color scheme to use when in interactive mode. Possible values\ninclude: white, yellow, red, cyan, magenta, green, blue. The default value is\ncyan.\n\nThe following is a sample configuration to add a permanent filter in your\nconfiguration file for `DeleteStack` events using the `attributes` configuration\noption:\n\n Commands:\n last:\n attributes:\n EventName:\n - DeleteStack\n\n\"\"\"\n\nimport json\nimport sys\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta, timezone\nfrom functools import partial\nfrom itertools import chain, cycle\n\nimport py_cui\nfrom colorama import Fore, Style, init\n\nfrom awsrun.argparse import AppendAttributeValuePair\nfrom awsrun.config import Bool, Choice, Dict, Int, Str, List\nfrom awsrun.runner import RegionalCommand\n\n\n# Lookup attributes supported by AWS CloudTrail\nLOOKUP_ATTRIBUTES = [\n \"EventId\",\n \"EventName\",\n \"ReadOnly\",\n \"Username\",\n \"ResourceType\",\n \"ResourceName\",\n \"EventSource\",\n \"AccessKeyId\",\n]\n\n\nclass CLICommand(RegionalCommand):\n \"\"\"Displays the last CloudTrail events in an account.\"\"\"\n\n @classmethod\n def regional_from_cli(cls, parser, argv, cfg):\n time_spec = parser.add_argument_group(\"Time specification\")\n time_spec.add_argument(\n \"--hours\",\n metavar=\"N\",\n type=int,\n default=cfg(\"hours\", type=Int, default=1),\n help=\"retrieve the last N hours of events\",\n )\n time_spec.add_argument(\n \"--start\",\n type=_isodate,\n help=\"lookup events starting at YYYY-MM-DDTHH:MM:SS-00:00\",\n )\n time_spec.add_argument(\n \"--end\",\n type=_isodate,\n help=\"lookup events ending at YYYY-MM-DDTHH:MM:SS-00:00\",\n )\n\n parser.add_argument(\n \"--max-events\",\n metavar=\"N\",\n type=int,\n default=cfg(\"max_events\", type=Int, default=1000),\n help=\"limit # of events retrieved\",\n )\n\n filters = parser.add_argument_group(\"Event filters\")\n mut_excl = filters.add_mutually_exclusive_group()\n mut_excl.add_argument(\n \"--all\",\n action=\"store_true\",\n default=cfg(\"all\", type=Bool, default=False),\n help=\"include read-only events\",\n )\n mut_excl.add_argument(\n \"--console\",\n action=\"store_true\",\n default=cfg(\"console\", type=Bool, default=False),\n help=\"include only ConsoleLogin events\",\n )\n mut_excl.add_argument(\n \"--attribute\",\n \"-a\",\n dest=\"attributes\",\n action=AppendAttributeValuePair,\n default=cfg(\"attributes\", type=Dict(Str, List(Str)), default={}),\n help=\"filter using attribute in form of ATTR=VALUE\",\n )\n\n tui = parser.add_argument_group(\"TUI options\")\n tui.add_argument(\n \"--interactive\",\n \"-i\",\n action=\"store_true\",\n default=cfg(\"interactive\", type=Bool, default=False),\n help=\"enter interactive mode to view results\",\n )\n tui.add_argument(\n \"--vertical\",\n action=\"store_true\",\n default=cfg(\"vertical\", type=Bool, default=False),\n help=\"use vertical layout for TUI\",\n )\n tui.add_argument(\n \"--color\",\n choices=TUI_COLOR_THEMES,\n default=cfg(\"color\", type=Choice(*TUI_COLOR_THEMES), default=\"cyan\"),\n help=f\"use color scheme: {', '.join(TUI_COLOR_THEMES)}\",\n )\n\n args = parser.parse_args(argv)\n\n # If user doesn't specify any filters, then exclude the read-only\n # events as there are far too many of these typically. While our\n # argument parser can support multipe key and values, the AWS\n # CloudTrail API is lacking considerably in ability to specify\n # filters. One can only use a single lookup attribute and that\n # attribute can only have a single value. We allow the user to\n # explicity set their own filter or use one of our the shorthand\n # filters such as --all or --console.\n\n if not (args.all or args.console or args.attributes):\n args.attributes[\"ReadOnly\"] = [\"false\"]\n\n elif args.console:\n args.attributes[\"EventName\"] = [\"ConsoleLogin\"]\n\n elif len(args.attributes) > 1:\n parser.error(f\"only one lookup attribute may be used per AWS\")\n\n elif any(len(v) > 1 for v in args.attributes.values()):\n parser.error(f\"only one lookup value may be specified per AWS\")\n\n elif any(a not in LOOKUP_ATTRIBUTES for a in args.attributes):\n parser.error(\n f\"invalid attribute, must be one of {', '.join(LOOKUP_ATTRIBUTES)}\"\n )\n\n # If no time spec flags provided, default to last of 1 hour of events.\n if not (args.hours or args.start or args.end):\n args.hours = 1\n\n # If only --hours was specified, then compute a start and end time as\n # our CLICommand doesn't support --last.\n if args.hours and not (args.start or args.end):\n args.end = datetime.now(timezone.utc)\n args.start = args.end - timedelta(hours=args.hours)\n\n elif args.hours and (args.start or args.end):\n parser.error(\"must specify either --hours OR --start/--end flags\")\n\n elif not (args.start and args.end):\n parser.error(\"must specify both --start and --end flags\")\n\n # Only allow use of TUI options with --interactive flag\n if args.vertical and not args.interactive:\n parser.error(\"can only use --vertical with --interactive mode\")\n\n del args.all\n del args.hours\n del args.console\n return cls(**vars(args))\n\n def __init__(\n self,\n regions,\n start=None,\n end=None,\n attributes=None,\n max_events=1000,\n interactive=False,\n vertical=False,\n color=\"blue\",\n ):\n super().__init__(regions)\n\n # Event settings\n self.start = start\n self.end = end\n self.max_events = max_events\n self.attributes = {} if attributes is None else attributes\n\n # TUI settings\n self.interactive = interactive\n self.vertical = vertical\n self.color = TUI_COLOR_THEMES.get(color, py_cui.WHITE_ON_BLACK)\n\n # Dict of events by \"username\", which we'll define as the unique\n # identifier for a particular session.\n self.events_by_user = defaultdict(list)\n\n # List of all events in reverse chronological order. We wouldn't have\n # to keep this list if event timestamps were more granular than a\n # second. Given that they are not, it's not possible to accurately\n # reconstruct the series of events from a dict of events by user.\n self.events = []\n\n def pre_hook(self):\n print(\n f\"Loading events, {self.max_events} max per acct/region, use --max-events to change\",\n file=sys.stderr,\n )\n\n if not self.interactive:\n init() # colorama only needed for the noninteractive version\n\n def regional_execute(self, session, acct, region):\n ct = session.client(\"cloudtrail\", region_name=region)\n events = self._retrieve_events(ct)\n\n if self.interactive:\n events_by_user = defaultdict(list)\n for e in events:\n events_by_user[e.username()].append(e)\n return events, events_by_user\n\n cf_map = defaultdict(lambda: next(COLOR_FUNCTIONS))\n return \"\".join(cf_map[e.username()](f\"{acct}/{region}: {e}\\n\") for e in events)\n\n def _retrieve_events(self, ct):\n events = []\n for page in _lookup_events(\n ct, start=self.start, end=self.end, attrs=self.attributes\n ):\n for event in page[\"Events\"]:\n event[\"CloudTrailEvent\"] = json.loads(event[\"CloudTrailEvent\"])\n events.append(_UserIdentityType.new(event))\n if self.interactive:\n print(\".\", end=\"\", file=sys.stderr, flush=True)\n if len(events) >= self.max_events:\n return events\n return events\n\n def regional_collect_results(self, acct, region, get_result):\n if not self.interactive:\n return super().regional_collect_results(acct, region, get_result)\n\n events, events_by_user = get_result()\n self.events.append(events)\n for username, events in events_by_user.items():\n self.events_by_user[username].extend(events)\n\n def post_hook(self):\n if not self.interactive:\n return\n\n # User wants the TUI, so let's fire it up! Keep in mind, the Python\n # library I found to make the TUI is barely alpha, so I've had to work\n # around many of its limitations that I will submit to the author.\n if self.vertical:\n root = _MyCUI(4, 1)\n user_list = root.add_my_scroll_menu(f\"Usernames\", 0, 0)\n event_list = root.add_my_scroll_menu(\"Events\", 1, 0)\n event_detail = root.add_my_scroll_menu(\"Event Detail\", 2, 0, row_span=2)\n\n else: # Default hybrid layout\n root = _MyCUI(3, 4)\n user_list = root.add_my_scroll_menu(f\"Usernames\", 0, 0, column_span=2)\n event_list = root.add_my_scroll_menu(\n \"Events\", 1, 0, row_span=2, column_span=2\n )\n event_detail = root.add_my_scroll_menu(\n \"Event Detail\", 0, 2, row_span=3, column_span=2\n )\n\n root.toggle_unicode_borders()\n root.set_title(\"CloudTrail Events\")\n root.set_status_bar_text(\"Press - q - to exit. TAB to move between widgets.\")\n\n # Override the default behavior and allow TAB to switch between\n # widgets and activate widgets.\n focus = cycle(root.widgets.values())\n\n def select_next_widget():\n root.move_focus(next(focus))\n\n root.add_key_command(py_cui.keys.KEY_TAB, select_next_widget)\n\n # Configure our user list\n def update_event_list():\n event_list.clear()\n event_list.add_item_list(self.events_by_user[user_list.get()])\n event_list.title = f\"Events ({len(event_list.get_item_list())})\"\n update_event_detail()\n\n def unfilter_event_list():\n event_list.clear()\n all_events = sorted(\n chain(*self.events), reverse=True, key=lambda e: e.event[\"EventTime\"]\n )\n event_list.add_item_list(all_events)\n event_list.title = f\"Events ({len(all_events)})\"\n update_event_detail()\n\n user_list.add_key_command(py_cui.keys.KEY_TAB, select_next_widget)\n user_list.add_key_command(py_cui.keys.KEY_ENTER, update_event_list)\n user_list.add_key_command(py_cui.keys.KEY_BACKSPACE, unfilter_event_list)\n user_list.add_key_command(py_cui.keys.KEY_PAGE_UP, user_list.page_up)\n user_list.add_key_command(py_cui.keys.KEY_PAGE_DOWN, user_list.page_down)\n user_list.add_key_command(py_cui.keys.KEY_Q_LOWER, lambda: root.stop())\n user_list.title = f\"Usernames ({len(self.events_by_user.keys())})\"\n user_list.set_focus_text(\n \"Press - q - to exit. TAB to move between widgets. ENTER to filter events. BACKSPACE to show all.\"\n )\n user_list.set_selected_color(self.color)\n user_list.add_item_list(\n sorted(self.events_by_user.keys(), key=lambda s: s.lower())\n )\n\n # Configure our event list\n def update_event_detail():\n event_detail.clear()\n event_detail.add_item_list(event_list.get().to_json().split(\"\\n\"))\n\n event_list.add_key_command(py_cui.keys.KEY_TAB, select_next_widget)\n event_list.add_key_command(py_cui.keys.KEY_ENTER, update_event_detail)\n event_list.add_key_command(py_cui.keys.KEY_PAGE_UP, event_list.page_up)\n event_list.add_key_command(py_cui.keys.KEY_PAGE_DOWN, event_list.page_down)\n event_list.add_key_command(py_cui.keys.KEY_Q_LOWER, lambda: root.stop())\n event_list.set_focus_text(\n \"Press - q - to exit. TAB to move between widgets. ENTER to display event detail.\"\n )\n event_list.set_selected_color(self.color)\n if user_list.get():\n update_event_list()\n\n # Configure our event detail\n event_detail.add_key_command(py_cui.keys.KEY_TAB, select_next_widget)\n event_detail.add_key_command(py_cui.keys.KEY_PAGE_UP, event_detail.page_up)\n event_detail.add_key_command(py_cui.keys.KEY_PAGE_DOWN, event_detail.page_down)\n event_detail.add_key_command(py_cui.keys.KEY_Q_LOWER, lambda: root.stop())\n event_detail.set_focus_text(\"Press - q - to exit. TAB to move between widgets.\")\n event_detail.set_selected_color(self.color)\n if event_list.get():\n update_event_detail()\n\n select_next_widget()\n\n # Fire up the main event loop\n root.start()\n\n\nclass _UserIdentityType:\n \"\"\"Represents a custom event object based on the user identity type.\n\n The event object wraps an event dict with a convenience method to compute\n the username for a given event. CloudTrail events seem to be a mess when it\n comes to normalizing the username (at least in our environment). The purpose\n of this class is to provide a means to extract a reasonable username from an\n event that can be used to group events together via the `username` method.\n\n The factory method `new` should be used to create instances of this type. It\n will dispatch to a custom subclass based on the user type. If no custom\n subclass exists, an instance of this class is created. If one wants to add\n new user types, just follow the patterns of the existing subclasses.\n \"\"\"\n\n @classmethod\n def new(cls, event):\n user_type = event[\"CloudTrailEvent\"][\"userIdentity\"].get(\"type\", \"AWSService\")\n klass = globals().get(f\"_{user_type}Type\", cls)\n return klass(event)\n\n def __init__(self, event):\n self.event = event\n self.ct_event = event[\"CloudTrailEvent\"]\n self.user_identity = self.ct_event[\"userIdentity\"]\n\n def type(self):\n \"\"\"Return the user identity type if present, otherwise NO_TYPE.\"\"\"\n return self.user_identity.get(\"type\", \"NO_TYPE\")\n\n def username(self):\n \"\"\"Return a the username associated with an event.\"\"\"\n if self.event[\"EventName\"].startswith(\"AssumeRole\"):\n user = self._parse_username_from_request_params()\n if user:\n return user\n return self._parse_username()\n\n def _parse_username(self):\n return self.event.get(\n \"Username\", self.user_identity.get(\"userName\", \"NO_USERNAME\")\n )\n\n def _find_resource(self, type_, default=None):\n for resource in self.event[\"Resources\"]:\n if resource[\"ResourceType\"] == type_:\n return resource[\"ResourceName\"]\n return default\n\n def _parse_username_from_request_params(self):\n params = self.ct_event.get(\"requestParameters\", {})\n arn = params.get(\"roleArn\")\n session_name = params.get(\"roleSessionName\")\n if arn and session_name:\n return _strip_to(\"/\", arn, greedy=True) + \"/\" + session_name\n\n def to_json(self):\n return json.dumps(self.event, default=str, indent=4)\n\n def __str__(self):\n src = self.event.get(\"EventSource\", \"\")\n time = self.event.get(\"EventTime\", \"\")\n name = self.event.get(\"EventName\", \"\")\n return f\"{time} {src:25.25} {name:30.30} {self.username()}\"\n\n\n#############################################################################\n# These classes are for custom handling of different user identity types. you\n# want to provide a custom username for a cloudtrail user identity type,\n# define your subclass below following the naming convention.\n#############################################################################\n\n\nclass _RootType(_UserIdentityType):\n def _parse_username(self):\n # Docs state that Root does not have a username unless an alias has\n # been set for the account, so we try to print the username, if not,\n # we return \"ROOT\".\n return self.user_identity.get(\"userName\", \"ROOT\")\n\n\nclass _AWSAccountType(_UserIdentityType):\n def _parse_username(self):\n acct = self.user_identity.get(\"accountId\", \"NO_ACCOUNT_ID\")\n principal = self.user_identity.get(\"principalId\", \"NO_PRINCIPAL_ID\")\n return f\"{acct}/{_strip_to(':', principal)}\"\n\n\nclass _AWSServiceType(_UserIdentityType):\n def _parse_username(self):\n return self.user_identity.get(\"invokedBy\", \"NO_USERNAME\")\n\n\nclass _AssumedRoleType(_UserIdentityType):\n def _parse_username(self):\n # For an assumed role type, we get username from the arn because it's\n # the only thing consistent throughout the other type of events, which\n # allows us to match a sequence of events.\n arn = self.user_identity.get(\"arn\")\n if arn:\n return _strip_to(\"/\", arn)\n return self.event.get(\"Username\")\n\n\n#############################################################################\n# Helper functions\n#############################################################################\n\n\ndef _isodate(string):\n return datetime.strptime(string, \"%Y-%m-%dT%H:%M:%S%z\")\n\n\ndef _strip_to(char, string, greedy=False):\n pos = string.rfind(char) if greedy else string.find(char)\n return string[pos + 1 :]\n\n\ndef _strip_after(char, string, greedy=False):\n pos = string.rfind(char) if greedy else string.find(char)\n return string if pos == -1 else string[:pos]\n\n\ndef _lookup_events(ct, start, end, attrs=None):\n attrs = {} if attrs is None else attrs\n return ct.get_paginator(\"lookup_events\").paginate(\n LookupAttributes=[\n {\"AttributeKey\": k, \"AttributeValue\": v}\n for k, vs in attrs.items()\n for v in vs\n ],\n StartTime=start,\n EndTime=end,\n )\n\n\ndef _colorize(color, string):\n return f\"{color}{string}{Style.RESET_ALL}\"\n\n\n# An infinite list of partially applied colorize functions\nCOLOR_FUNCTIONS = cycle(\n [\n partial(_colorize, f\"{s}{c}\")\n for s in (\"\", Style.DIM, Style.BRIGHT)\n for c in (\n Fore.BLUE,\n Fore.GREEN,\n Fore.YELLOW,\n Fore.RED,\n Fore.MAGENTA,\n Fore.CYAN,\n Fore.WHITE,\n )\n ]\n)\n\n# Make available any of the colors defined in py_cui\nTUI_COLOR_THEMES = {\n _strip_after(\"_\", k).lower(): v\n for k, v in vars(py_cui).items()\n if k.endswith(\"_ON_BLACK\")\n}\n\n\n#############################################################################\n# This code is for deficiencies in the py_cui library. I will actually make a\n# PR for the author of that project at some point.\n#############################################################################\n\n\nclass _MyCUI(py_cui.PyCUI):\n def add_my_scroll_menu(\n self, title, row, column, row_span=1, column_span=1, padx=1, pady=0\n ):\n id = \"Widget{}\".format(len(self.widgets.keys()))\n new_scroll_menu = _MyScrollMenu(\n id, title, self.grid, row, column, row_span, column_span, padx, pady\n )\n self.widgets[id] = new_scroll_menu\n if self.selected_widget is None:\n self.set_selected_widget(id)\n return new_scroll_menu\n\n\nclass _MyScrollMenu(py_cui.widgets.ScrollMenu):\n def __init__(\n self,\n id,\n title,\n grid,\n row,\n column,\n row_span,\n column_span,\n padx,\n pady,\n to_str=str,\n ):\n super().__init__(\n id, title, grid, row, column, row_span, column_span, padx, pady\n )\n self.to_str = to_str\n\n def page_up(self):\n shift_by = self.height - (2 * self.pady) - 3\n\n new_top_view = self.top_view - shift_by\n new_selected_item = self.selected_item - shift_by\n\n self.top_view = 0 if new_top_view < 0 else new_top_view\n self.selected_item = 0 if new_selected_item < 0 else new_selected_item\n\n def page_down(self):\n shift_by = self.height - (2 * self.pady) - 3\n last_item_idx = len(self.view_items) - 1\n\n new_top_view = self.top_view + shift_by\n new_selected_item = self.selected_item + shift_by\n\n self.top_view = (\n new_top_view - shift_by if new_top_view > last_item_idx else new_top_view\n )\n self.selected_item = (\n last_item_idx if new_selected_item > last_item_idx else new_selected_item\n )\n\n def draw(self):\n super(py_cui.widgets.ScrollMenu, self).draw()\n\n self.renderer.set_color_mode(\n self.selected_color if self.selected else self.color\n )\n self.renderer.draw_border(self)\n\n counter = self.pady + 1\n line_counter = 0\n for line in (self.to_str(i) for i in self.view_items):\n if line_counter < self.top_view:\n line_counter = line_counter + 1\n else:\n if counter >= self.height - self.pady - 1:\n break\n if line_counter == self.selected_item:\n self.renderer.draw_text(\n self, line, self.start_y + counter, selected=True\n )\n else:\n self.renderer.draw_text(self, line, self.start_y + counter)\n counter = counter + 1\n line_counter = line_counter + 1\n\n self.renderer.unset_color_mode(\n self.selected_color if self.selected else self.color\n )\n self.renderer.reset_cursor(self)\n","sub_path":"src/awsrun/commands/aws/last.py","file_name":"last.py","file_ext":"py","file_size_in_byte":28045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316315361","text":"class Account():\n\tdef __init__(self, name, money):\n\t\tself.user = name\n\t\tself.balance = money\n\n\tdef deposit(self, money):\n\t\tif money <= 0:\n\t\t\treturn None\n\t\telse:\n\t\t\tself.balance += money\n\t\t\treturn self.balance\n\n\tdef withdraw(self, money):\n\t\tif money <=self.balance:\n\t\t\tself.balance -= money\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef transfer(self, other, money):\n\t\tres = self.withdraw(money)\n\t\tif res:\n\t\t\tother.deposit(money)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef __str__(self):\n\t\treturn '{}:{}'.format(self.user, self.balance)\n\nif __name__ == '__main__':\n\tmy_acnt = Account('greg', 5000)\n\tyour_acnt = Account('john', 7000)\n\t\n\tprint(my_acnt)\n\tprint(your_acnt)\n\n\tmy_acnt.transfer(your_acnt,3000)\n\n\tprint(my_acnt)\n\tprint(your_acnt)\n\n\n","sub_path":"first/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"140307723","text":"import os \nimport csv \n\nbudgetCSV = (\"C:/Users/RogStrix/Downloads/03-Python/Instructions/PyBank/raw_data\")\n\n\nwith open(budgetCSV, 'r') as csvfile: \n \n csvreader = csv.reader(csvfile, delimiter=\",\")\n \n month = 0\n total_revenue = 0\n increased_value = [\"\", 0]\n decreased_value = [\"\", 0]\n \n for row in csvreader:\n #print(row[1])\n month += 1\n if month != 1:\n total_revenue = total_revenue + int(row[1])\n if lastmonth_value != 0 and (increased_value[1] < int(row[1]) - lastmonth_value[1]):\n increased_value[0] = row[0]\n increased_value[1] = int(row[1]) - lastmonth_value[1]\n \n \n # print(row[0])\n if lastmonth_value != 0 and (decreased_value[1] > int(row[1]) - lastmonth_value[1]):\n decreased_value[0] = row[0]\n decreased_value[1] = int(row[1]) - lastmonth_value[1]\n \n lastmonth_value[1] = int(row[1])\n lastmonth_value[0] = row[0]\n\nprint(\"Financial Analysis\")\nprint(\"----------------------------\")\nprint(\"Total Months: \" + str(month - 1))\nprint(\"Total Revenue: $\" + str(total_revenue))\nprint(\"Average Revenue Change: $\" + str(round(total_revenue / (month -1),2)))\nprint(\"Greatest Increase in Revenue: \" + str(increased_value[0]) + \" \" +\n (\"($\" + (str(increased_value[1]) + \")\")))\nprint(\"Greatest Decrease in revenue: \" + str(decreased_value[0]) + \" \" +\n (\"($\" + (str(decreased_value[1]) + \")\")))","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"618739544","text":"import keras.backend as K\nfrom networks.faceswap_gan_model import FaceswapGANModel\nfrom converter.video_converter import VideoConverter\nfrom detector.face_detector import MTCNNFaceDetector\nimport sys\ndef conversion(video_path, models_dir, save_mp4):\n \"\"\"\n\n :param video_path: .../video_name.mp4\n :param models_dir: .../models dir inculde encoder.h5 decoder_A.h5 decoder_B.h5 netDA.h5 netDB.h5\n :param save_mp4: .../out_video_name.mp4\n :return:\n \"\"\"\n\n K.set_learning_phase(0)\n\n # Input/Output resolution\n RESOLUTION = 128 # 64x64, 128x128, 256x256\n assert (RESOLUTION % 64) == 0, \"RESOLUTION should be 64, 128, 256\"\n\n # Architecture configuration\n arch_config = {}\n arch_config['IMAGE_SHAPE'] = (RESOLUTION, RESOLUTION, 3)\n arch_config['use_self_attn'] = True\n arch_config['norm'] = \"instancenorm\" # instancenorm, batchnorm, layernorm, groupnorm, none\n arch_config['model_capacity'] = \"standard\" # standard, lite\n\n model = FaceswapGANModel(**arch_config)\n\n model.load_weights(path=models_dir)\n\n mtcnn_weights_dir = \"./mtcnn_weights/\"\n\n fd = MTCNNFaceDetector(sess=K.get_session(), model_path=mtcnn_weights_dir)\n vc = VideoConverter()\n\n vc.set_face_detector(fd)\n vc.set_gan_model(model)\n\n options = {\n # ===== Fixed =====\n \"use_smoothed_bbox\": True,\n \"use_kalman_filter\": True,\n \"use_auto_downscaling\": False,\n \"bbox_moving_avg_coef\": 0.65,\n \"min_face_area\": 100 * 100,\n \"IMAGE_SHAPE\": model.IMAGE_SHAPE,\n # ===== Tunable =====\n \"kf_noise_coef\": 3e-3,\n \"use_color_correction\": \"hist_match\",\n \"detec_threshold\": 0.7,\n \"roi_coverage\": 0.85,\n \"enhance\": 0.5,\n \"output_type\": 1,\n \"direction\": \"AtoB\",\n }\n\n input_fn = video_path\n output_fn = save_mp4\n duration = None\n\n vc.convert(input_fn=input_fn, output_fn=output_fn, options=options, duration=duration)\n\n\nif (len(sys.argv)<4):\n print('파라미터오류')\nelse :\n conversion(video_path=sys.argv[1],models_dir=sys.argv[2],save_mp4=sys.argv[3])\n","sub_path":"conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"582944021","text":"from time import time\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport scipy.linalg as linalg\n\nfrom sklearn import datasets\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.externals.six.moves import xrange\nfrom sklearn.datasets.samples_generator import make_blobs, make_spd_matrix\n\ncolors = ['c', 'm', 'y', 'k',\n 'r', 'g', 'b', 'y',\n 'navy', 'turquoise', 'darkorange']\n\n\ndef covariances_(estimator):\n if estimator.precision_type is 'full':\n return [linalg.inv(prec) for prec in estimator.precisions_]\n elif estimator.precision_type is 'tied':\n return linalg.inv(estimator.precisions_)\n else:\n return 1. / estimator.precisions_\n\n\ndef generate_data(n_samples, means, covars):\n n_components = len(n_samples)\n X = np.vstack([rng.multivariate_normal(means[j], covars[j], n_samples[j])\n for j in range(n_components)])\n y = np.concatenate([j * np.ones(n_samples[j])\n for j in range(n_components)])\n return X, y\n\n\ndef plot_ellipses(means, covars, matrix_type, ax):\n for n in range(means.shape[0]):\n if matrix_type == 'full':\n cov = covars[n][:2, :2]\n elif matrix_type == 'tied':\n cov = covars[:2, :2]\n elif matrix_type == 'diag':\n cov = np.diag(covars[n][:2])\n else:\n cov = np.eye(4) * covars[n]\n v, w = np.linalg.eigh(cov)\n u = w[0] / np.linalg.norm(w[0])\n angle = np.arctan2(u[1], u[0])\n angle = 180 * angle / np.pi # convert to degrees\n v = 2 * np.sqrt(2) * np.sqrt(v)\n if(means.shape[0] > len(colors)):\n ell = mpl.patches.Ellipse(means[n, :2], v[0], v[1], 180 + angle)\n else:\n ell = mpl.patches.Ellipse(means[n, :2], v[0], v[1], 180 + angle,\n color=colors[n])\n ell.set_clip_box(ax.bbox)\n ell.set_alpha(0.5)\n ax.add_artist(ell)\n\n\ndef plot_data(X, y, estimator):\n plt.clf()\n h = plt.subplot(111)\n plt.axis('equal')\n for n, color in enumerate(range(n_components)):\n data = X[y == n]\n\n plt.scatter(data[:, 0], data[:, 1], s=0.8)\n plot_ellipses(estimator.means_, covariances_(estimator),\n estimator.covariance_type if isinstance(estimator, GaussianMixturePrecision) else\n estimator.precision_type, h)\n plt.draw()\n\n\ndef plot(fit, predict, gmm_error1, gmm_error2, sizes, xlabel, gmm_class_name1, gmm_class_name2):\n \"\"\"Plot the results.\"\"\"\n\n idx = np.arange(fit.shape[1])\n\n plt.figure( figsize=(14, 4))\n plt.plot( fit.mean(axis=0), c='b', label=\"Fitting\")\n plt.plot( predict.mean(axis=0), c='r', label=\"Prediction\")\n plt.plot( [0, fit.shape[1]], [1, 1], c='k', label=\"Baseline\" )\n\n plt.fill_between( idx, fit.min(axis=0), fit.max(axis=0), color='b', alpha=0.3 )\n plt.fill_between( idx, predict.min(axis=0), predict.max(axis=0), color='r', alpha=0.3 )\n\n plt.xticks(idx, sizes, rotation=65, fontsize=14)\n plt.xlabel('{}'.format(xlabel), fontsize=14)\n plt.ylabel('%s is x times faster than %s' %(gmm_class_name2, gmm_class_name1), fontsize=14)\n plt.legend(fontsize=12, loc=4)\n plt.show()\n\n\n plt.figure( figsize=(14, 4))\n plt.plot( 1 - gmm_error1.mean(axis=0), alpha=0.5, c='b', label=\"%s accuracy\" % gmm_class_name2)\n plt.plot( 1 - gmm_error2.mean(axis=0), alpha=0.5, c='r', label=\"%s accuracy\" % gmm_class_name1)\n\n plt.fill_between( idx, 1-gmm_error1.min(axis=0), 1-gmm_error1.max(axis=0), color='b', alpha=0.3 )\n plt.fill_between( idx, 1-gmm_error2.min(axis=0), 1-gmm_error2.max(axis=0), color='r', alpha=0.3 )\n\n plt.xticks( idx, sizes, rotation=65, fontsize=14)\n plt.xlabel( '{}'.format(xlabel), fontsize=14)\n plt.ylabel('Accuracy', fontsize=14)\n plt.legend(fontsize=14)\n plt.show()","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"550291283","text":"# Lab 8, CS104 Max increase in list\n# Student 1. Shurjo Maitra (sm47), Student 2. Oshomah Agbugui (ota2)\n# <10.29.15>\n\n# imports here\nfrom __future__ import division, print_function\ninput = raw_input \n# Constants here (if any)\n\n# Function declarations here (if any)\ndef isPrime(maxVal):\n 'Function returns True if n is prime and False otherwise'\n for i in range(2, int(maxVal/2) + 1):\n result = maxVal % i\n if result == 0:\n return False\n return True\n\ndef genPrimesList(topVal):\n 'Function generates a list of primes up to the value entered by user'\n PrimesList = []\n for i in range(2, topVal):\n if isPrime(i) == True:\n PrimesList.append(i)\n return PrimesList\n\n\n\n# main code here.\nmaxVal = int(input(\"Enter a number:\")) \nprimesList = genPrimesList(maxVal)\nprint(\"Prime numbers up to\", maxVal, \"are\", primesList)\n\ncount = 0\nfor e in range(4, maxVal + 1, 2):\n found = False\n for p in primesList:\n # finding the difference between \n if (e - p) in primesList:\n found = True\n print(\"Found\", e, \"is the sum of primes\", p, \"and\", e - p)\n break\n if found == False:\n print(\"Goldbach's conjecture is false for e\")\n count += maxVal\nprint(\"Goldbach's conjecture holds for all even numbers up to the one in input \")\n \n","sub_path":"lab8/lab8.py","file_name":"lab8.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"396904163","text":"import os\nimport time\nimport datetime\n\nfrom bs4 import BeautifulSoup\n\nfrom src.config import Config\n\ndef str2timestamp(time_str):\n if ':' in time_str:\n if '/' in time_str:\n return (time_str.split('/')[0], time.mktime(datetime.datetime.strptime(time_str, '%Y/%m/%d %H:%M:%S').timetuple()))\n return (time_str.split('-')[0], time.mktime(datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S').timetuple()))\n elif '/' in time_str:\n return (time_str.split('/')[0], time.mktime(datetime.datetime.strptime(time_str, '%Y/%m/%d %H-%M-%S').timetuple()))\n else:\n return (time_str.split('-')[0], time.mktime(datetime.datetime.strptime(time_str, '%Y-%m-%d %H-%M-%S').timetuple()))\n\ndef html2template():\n posts = []\n new_posts = os.listdir(os.path.join(Config.ROOT_PATH, 'data/html'))\n post_template_path = os.path.join(Config.ROOT_PATH, 'template/post')\n for template_file_name in os.listdir(post_template_path):\n if template_file_name not in new_posts:\n os.remove(os.path.join(post_template_path, template_file_name))\n for post_file_name in new_posts:\n if '.html' in post_file_name:\n post = {}\n post['title'] = post_file_name.replace('.html', '')\n post['id'] = post['title'].replace(' ', '')\n post_html_path = os.path.join(Config.ROOT_PATH, 'data/html/' + post_file_name)\n with open(post_html_path, 'r') as source_file:\n text = source_file.read()\n soup = BeautifulSoup(text, 'lxml')\n post['year'], post['timestamp'] = str2timestamp(soup.find('p').get_text())\n soup.find('p').decompose()\n post_link = ' ... 阅读全文' % post['id']\n abstract = str(soup.find('div', attrs={'class': 'a'}))\n if '

' in abstract:\n post['abstract'] = abstract.replace('

', post_link + '

')\n else:\n post['abstract'] = abstract.replace('', post_link + '')\n if post['abstract'] == str(None):\n post['abstract'] = str(soup.find('p')).replace('

', post_link + '

')\n template = (\n '{% extends \"../'\n + Config.ENV\n + '/base.html\" %}{% block description %}'\n + post['title']\n + '{% end %}{% block title %}' + post['title']\n + ' - Jackeriss{% end %}{% block section %}
'\n + str(soup.find('body')).replace(\n '',\n '
')\n + '
{% end %}')\n with open(os.path.join(Config.ROOT_PATH, 'template/post/%s.html' % post['title']), 'w') as template_file:\n template_file.write(template)\n posts.append(post)\n posts.sort(key=lambda x: x['timestamp'], reverse=True)\n return posts\n\nif __name__ == '__main__':\n POSTS = html2template()\n for p in POSTS:\n print(p['id'])\n","sub_path":"src/util/html2template.py","file_name":"html2template.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"150008286","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 1月 30, 2021 \n\n@file: get_config.py\n@desc: get parameters\n@author: laugh12321\n@contact: laugh12321@vip.qq.com\n\"\"\"\nimport json\nimport argparse\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Hyperspectral Unmixing\")\n parser.add_argument('--path', nargs='?', default='./datasets/',\n help='Input data path.')\n parser.add_argument('--dataset', nargs='?', default='urban',\n help='Choose a dataset.')\n parser.add_argument('--save_path', nargs='?', default='./results',\n help='Result save path.')\n parser.add_argument('--train_size', type=float or int, default=0.8,\n help='Training size.')\n parser.add_argument('--test_size', type=int, default=None,\n help='Number of pixels to subsample the test set .')\n parser.add_argument('--val_size', type=float, default=0.1,\n help='Represents the percentage of samples from the training set '\n 'to be extracted as a validation set.')\n parser.add_argument('--model_names', nargs='+', type=str, default='unmixing_cube_based_dcae',\n help='Name of the model, it serves as a key in the dictionary '\n 'holding all functions returning models.')\n parser.add_argument('--verbose', type=int, default=0,\n help='Verbosity mode used in training, (0, 1 or 2).')\n parser.add_argument('--batch_size', type=int, default=256,\n help='Size of the batch used in training phase, '\n 'it is the size of samples per gradient step.')\n parser.add_argument('--epochs', type=int, default=500,\n help='Number of epochs for model to train.')\n parser.add_argument('--runs', type=int, default=5,\n help='Number of total experiment runs.')\n parser.add_argument('--patience', type=int, default=10,\n help='Number of epochs without improvement in order to '\n 'stop the training phase.')\n return parser.parse_args()\n\n\ndef get_config(filename):\n args = parse_args()\n with open(filename, 'r') as f:\n args.__dict__ = json.load(f)\n return args\n","sub_path":"config/get_config.py","file_name":"get_config.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"447437485","text":"\"\"\"Поросячья латынь\nЭто «тайный язык», представляющий собой зашифрованный английский.\nЧтобы сделать поросяче-латинское слово из английского, нужно первые согласные\nзвуки в слове переместить в конец и прибавить ay (Например: «banana»\nпревращается в anana-bay). Подробнее о правилах читайте в Википедии\n\"\"\"\n\n\ndef make_pig_lat(word):\n punctuation_mark = \"\"\n if word[len(word) - 1] in \".,:!?\":\n punctuation_mark = word[len(word) - 1]\n word = word[:len(word) - 1]\n if word[0] not in \"aeiouy\":\n for i in range(len(word)):\n if word[i] in \"aeiouy\":\n word = word[i:] + word[:i] + \"ay\" + punctuation_mark\n break\n else:\n word = word + \"ay\" + punctuation_mark\n return word\n\n\ndef main():\n words = str(input(\"Введите ваше предложение на английском языке: \")).lower()\n words = words.split(\" \")\n for i in words:\n print(pig_lat(i))\n ext = input(\"\\nPress Entr to exit\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2018-2019/learning/pig_lat/pig_lat.py","file_name":"pig_lat.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"539893605","text":"import os\nimport errno\n\n\nclass Cache:\n \"\"\"Class for cache.\"\"\"\n\n def __init__(self, cache_path):\n self.cache_path = cache_path\n self.cache_file = cache_path + '/cache'\n\n # Create cache file if does not exist.\n if not os.path.exists(self.cache_file):\n open(self.cache_file, 'w+').close()\n\n # Create cache folder if does not exist.\n if not os.path.exists(self.cache_path):\n try:\n os.makedirs(self.cache_path)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n def save_art(self, art):\n \"\"\"Save art to cache folder.\"\"\"\n f = open(self.cache_path + '/cover.jpg', 'wb')\n f.write(art)\n f.close()\n\n def get_art_from_cache(self):\n \"\"\"Retreive art from the cache folder.\"\"\"\n f = open(self.cache_path + '/cover.jpg', 'rb')\n art = f.read()\n f.close()\n return art\n\n def is_cache_consistent(self):\n \"\"\"Checks if the cache is corrupt.\"\"\"\n if not os.path.exists(self.cache_file):\n return True\n\n def has_album_changed(self, player):\n \"\"\"Check if the album has changed since last run.\n This saves redownloading album art, except for in a few edge cases\"\"\"\n if not self.is_cache_consistent():\n # We will need to redownload anyway.\n return True\n\n album = player.get_album()\n artist = player.get_artist()\n\n # Check our cache\n cache = open(self.cache_file, 'r')\n cache_artist = cache.readline().rstrip()\n cache_album = cache.readline().rstrip()\n\n if (cache_artist == artist and cache_album == album):\n return False\n else:\n return True\n\n def update_cache(self, player):\n \"\"\"Update the cache.\"\"\"\n album = player.get_album()\n artist = player.get_artist()\n # Update cache\n os.remove(self.cache_file)\n new_cache = open(self.cache_file, 'w+')\n new_cache.write(artist + '\\n' + album + '\\n')\n","sub_path":"cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"288083056","text":"#Find count of distinct elements in every sub-array of fixed size k\n\ndef find_partition(arr, k):\n i = 0\n dists = []\n while i <= len(arr) - k:\n curr = arr[i:i+k]\n done = []\n distinct = 0\n for x in curr:\n if x not in done:\n done.append(x)\n distinct += 1\n dists.append(distinct)\n i += 1\n print(*dists)\n\narr = [2,1,2,3,2,1,4,5]\nk = 5\nfind_partition(arr, k)\n\n","sub_path":"TechDelight/Arrays/arr_k_partition_distinct.py","file_name":"arr_k_partition_distinct.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"544122657","text":"import cv2\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPool2D\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\nimport keras\n\n# MNIST Dataset\n\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\nprint(X_train.shape, y_train.shape, X_test.shape, y_test.shape)\n\n# Removing Noise\n\n_, X_train_th = cv2.threshold(X_train, 127, 255, cv2.THRESH_BINARY)\n_, X_test_th = cv2.threshold(X_test, 127, 255, cv2.THRESH_BINARY)\n\n# Reshape\n\nX_train = X_train_th.reshape(-1, 28, 28, 1)\nX_test = X_test_th.reshape(-1, 28, 28, 1)\n\n# Categorical output from 0 to 9\n\ny_train = to_categorical(y_train, num_classes=10)\ny_test = to_categorical(y_test, num_classes=10)\n\n# print(X_train.shape, y_train.shape)\n# print(X_test.shape, y_test.shape)\n\n# Creating CNN model\n\ninput_shape = (28, 28, 1)\nnumber_of_classes = 10\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\n\nmodel.add(Dropout(0.5))\nmodel.add(Dense(number_of_classes, activation='softmax'))\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=optimizers.Adadelta(), metrics=['accuracy'])\n\n#model.summary()\n\nhistory = model.fit(X_train, y_train, epochs=5, shuffle=True, batch_size=200, validation_data=(X_test, y_test))\n\nmodel.save(\"digit_classifier.h5\")\n","sub_path":"Text_Recognition/cnn_model/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"309819028","text":"from django.http import Http404\nfrom django.shortcuts import render, HttpResponse\nfrom MainApp.models import Items\nfrom django.core.exceptions import ObjectDoesNotExist\n# Create your views here.\ndef index(request):\n context = {\n \"name\": \"Евгений\",\n \"surname\": \"Юрченко\",\n \"hobbies\": [\"programming\", \"bike\", \"sleep\"]\n }\n return render(request, \"index.html\", context)\n\n\ndef about(request):\n name = 'Михаил'\n second_name = 'Викторович'\n surname = 'Никитенко'\n tel = '8-999-999-99-99'\n email = 'xm4dn355x@gmail.com'\n return HttpResponse(f'Имя: {name}
Отчество: {second_name}
'\n f'Фамилия: {surname}
Телефон: {tel}
'\n f'e-mail: {email}')\n\n\ndef items(request):\n items = Items.objects.all();\n context = {\"items\":items}\n return render(request, \"items_list.html\", context)\n\n\ndef item_details(request, id):\n try:\n items = Items.objects.get(pk=id);\n except ObjectDoesNotExist:\n raise Http404\n context = {\n \"item\": items\n }\n return render(request, \"item_page.html\", context)\n","sub_path":"MainApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"22955228","text":"# Copyright 2020 AI2Business. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test-Environment for data_visualization.\"\"\"\n\n\nfrom pathlib import Path\n\nimport seaborn as sns\n\nfrom ai2business.visualization import data_visualization as dav\n\niris_dataframe = sns.load_dataset(\"iris\")\n\n\ndef test_lineplot_white():\n data = dav.DataVisualization()\n builder = dav.DesignerDataVisualization(iris_dataframe)\n data.builder = builder\n data.lineplot()\n folder = \"tmp_white\"\n builder.figure.save_all_figures(folder=folder)\n assert len(list(Path(f\"{folder}\").glob(\"*.png\"))) == 1\n\n\ndef test_lineplot_dark():\n data = dav.DataVisualization()\n builder = dav.DesignerDataVisualization(\n iris_dataframe,\n dark_mode=True,\n )\n data.builder = builder\n data.lineplot()\n folder = \"tmp_dark\"\n builder.figure.save_all_figures(folder=folder)\n assert len(list(Path(f\"{folder}\").glob(\"*.png\"))) == 1\n\n\ndef test_lineplot_whitegrid():\n data = dav.DataVisualization()\n builder = dav.DesignerDataVisualization(iris_dataframe, grid=True)\n data.builder = builder\n data.lineplot()\n folder = \"tmp_whitegrid\"\n builder.figure.save_all_figures(folder=folder)\n assert len(list(Path(f\"{folder}\").glob(\"*.png\"))) == 1\n\n\ndef test_lineplot_darkgrid():\n data = dav.DataVisualization()\n builder = dav.DesignerDataVisualization(iris_dataframe, dark_mode=True, grid=True)\n data.builder = builder\n data.lineplot()\n folder = \"tmp_darkgrid\"\n builder.figure.save_all_figures(folder=folder)\n assert len(list(Path(f\"{folder}\").glob(\"*.png\"))) == 1\n","sub_path":"ai2business/visualization/test/test_data_visualization_grids.py","file_name":"test_data_visualization_grids.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"47507990","text":"from django.shortcuts import render_to_response, get_object_or_404\nfrom .models import Article\nfrom .models import ArticleCate\n\n\ndef article_list(request):\n context = dict()\n context['articleList'] = Article.objects.all()\n context['articleCount'] = Article.objects.all().count()\n return render_to_response('article_list.html', context)\n\n\ndef article_detail(request, article_pk):\n context = dict()\n context['articleDetail'] = get_object_or_404(Article, id=article_pk)\n return render_to_response('article_detail.html', context)\n\n\ndef articles_by_cate(request, article_cate_pk):\n context = dict()\n article_type = get_object_or_404(ArticleCate, id=article_cate_pk)\n context['articlesByCate'] = Article.objects.filter(article_cate=article_type)\n context['articleCate'] = article_type\n return render_to_response('articles_by_cate.html', context)\n\n","sub_path":"perch_env/perch/inote/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"310592778","text":"import pandas as pd\nimport numpy as np\nimport json\n# https://github.com/ianxxiao/reinforcement_learning_project/blob/master/code/rl_brain.py\n\nclass agent():\n def __init__(self, epsilon, lr, gamma, current_stock, IDs, action_space, expected_stock, forecasting, remove_only, forecast_hours, id):\n self.IDs = IDs\n self.actions = []\n self.remove_only = remove_only\n if self.remove_only:\n for i in action_space:\n self.actions.append(i)\n self.actions.append(0)\n else: \n for my_id in self.IDs:\n if my_id != id:\n for i in action_space:\n self.actions.append((i,my_id))\n self.actions.append((0,0))\n #else:\n # for i in action_space:\n # self.actions.append(i)\n # self.actions.append(-i)\n \n self.reward = 0\n self.epsilon = epsilon\n self.lr = lr\n self.gamma = gamma\n self.current_stock = current_stock\n self.q_table = pd.DataFrame(columns = self.actions, dtype = np.float64)\n self.hourly_action_history = []\n self.hourly_stock_history = []\n self.forecasting = forecasting\n if self.forecasting:\n self.expected_stock = expected_stock\n self.forecast_hours = forecast_hours\n self.id = id\n \n def choose_action(self, current_stock, ex, key, current_hour):\n self.check_state_exist(current_stock)\n self.current_stock = current_stock\n if self.forecasting:\n self.expected_stock = ex\n #print(f\"CURRENT_STOCK: {current_stock}\")\n try:\n avg_dict = int(round((current_stock + ex.get(key)[current_hour + self.forecast_hours])/2))\n #avg = int(round(0.5*current_stock + 0.5*ex))\n except:\n avg_dict = current_stock\n self.check_state_exist(avg_dict)\n valid_state_action = self.q_table.loc[avg_dict, :]\n else:\n valid_state_action = self.q_table.loc[current_stock, :]\n #print(f\"valid_state_action: {valid_state_action}\")\n if np.random.uniform() < self.epsilon:\n try:\n # find the action with the highest expected reward\n valid_state_action = valid_state_action.reindex(np.random.permutation(valid_state_action.index))\n #valid_state_action_cp = valid_state_action.copy()\n # for key in valid_state_action_cp.keys():\n # if(key[0] != 0):\n # if current_stock.get(str(key[0])) <= key[2]:\n # valid_state_action_cp.drop(index=key, inplace=True)\n action = valid_state_action.idxmax()\n except:\n # if action list is null, default to 0\n action = (0,0)\n else:\n # randomly choose an action\n # re-pick if the action leads to negative stock\n try:\n action = np.random.choice(valid_state_action.index)\n except:\n action = (0,0)\n if self.remove_only:\n self.hourly_action_history.append(action)\n else:\n self.hourly_action_history.append(action[0])\n self.hourly_stock_history.append(current_stock)\n return action\n \n def learn(self, current_stock, current_action, reward_received, new_stock, end_of_day, ex, key, current_hour):\n self.check_state_exist(new_stock)\n #q_predict = self.q_table.loc[current_stock, [current_action]]#(str(current_action[0]), str(current_action[1]), str(current_action[2]))]\n if self.forecasting:\n #print(f\"ex: {ex}\")\n if len(ex) > 1:\n avg_dict = int(round((current_stock + ex[self.forecast_hours])/2))\n else:\n avg_dict = current_stock\n self.check_state_exist(avg_dict)\n #print(f\"AVG_DICT: {json.dumps(avg_dict)}\")\n q_predict = self.q_table.loc[avg_dict, [current_action]]\n else:\n q_predict = self.q_table.loc[current_stock, [current_action]]\n if end_of_day == False:\n # Updated Q Target Value if it is not end of day \n q_target = reward_received + self.gamma * self.q_table.loc[new_stock, :].max()\n else:\n # Update Q Target Value as Immediate reward if end of day\n q_target = reward_received\n #print(f\"current_stock: {current_stock}\")\n #print(f\"q_target: {q_target}\")\n #print(f\"q_predict: {q_predict}\")\n self.q_table.loc[current_stock, [current_action]] += self.lr * (q_target - q_predict)\n return\n \n \n def check_state_exist(self, state):\n # Add a new row with state value as index if not exist\n if state not in self.q_table.index:\n self.q_table = self.q_table.append(\n pd.Series(\n [0]*len(self.actions), \n index = self.q_table.columns,\n name = state\n )\n )\n return\n \n def find_valid_action(self, state_action):\n for action in self.actions:\n if self.current_stock + action < 0:\n state_action.drop(index = action, inplace = True)\n return state_action\n \n\n def print_q_table(self):\n print(self.q_table)\n\n def get_q_table(self):\n return self.q_table\n\n \n def get_hourly_actions(self):\n return self.hourly_action_history\n \n def get_hourly_stocks(self):\n #print(f\"get_hourly_stocks for ID {self.id}: {self.hourly_stock_history}\")\n return self.hourly_stock_history\n\n \n def reset_hourly_history(self):\n self.hourly_action_history = []\n self.hourly_stock_history = []","sub_path":"fedQlearning/distributed/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":5852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"461309319","text":"import os, sys\nimport re\nimport shutil\n\nfrom pprint import pprint\n\nfrom neolib.file_util import find_files_simple\nfrom neolib.neo_class import NeoRunnableClass\nprint(\"start\")\nprint(sys.argv)\n\n\ndef safe_copy(org_path, dst_file):\n\torg_path = os.path.abspath(org_path)\n\tdst_file = os.path.abspath(dst_file)\n\tdst_dir = os.path.dirname(dst_file)\n\tif not os.path.exists(dst_dir):\n\t\tos.makedirs(dst_dir)\n\n\tshutil.copy2(org_path, dst_file)\n\tprint(\"copied\", org_path, \"\\n\\t-->\", dst_file)\n\ndef make_normal_abs(path_name):\n\treturn os.path.abspath(path_name).replace(\"\\\\\",\"/\")\n\nclass ReleaseClass(NeoRunnableClass):\n\tdef init(self):\n\t\tprint(self.map_args)\n\t\tself.cmd = self.map_args.get(\"cmd\")\n\t\tself.header_path = self.map_args.get(\"input_dir\")\n\t\tself.base_pub_dir = self.map_args.get(\"out_dir\")\n\t\tself.not_recursive = self.map_args.get(\"not_recursive\",False)\n\t\tself.ext_name = self.map_args.get(\"ext_name\")\n\t\tself.reg_exp = self.map_args.get(\"reg\")\n\t\tself.str_forbidden = self.map_args.get(\"forbidden\")\n\t\tself.platform = self.map_args.get(\"platform\")\n\t\t\n\t\t\n\t\t\n\t\tself.list_ext = [f\".{tmp}\" for tmp in self.ext_name.split('|')]\n\t\t\n\t\t\n\t\tpass\n\t\n\tdef _ft_copy(self):\n\t\theader_path = make_normal_abs(self.header_path)\n\t\tbase_pub_dir = make_normal_abs(self.base_pub_dir)\n\t\t\n\t\tfor root, subFolder, files in os.walk(header_path):\n\t\t\t\n\t\t\tprint(\"root:\", root)\n\t\t\tprint(\"header_path:\", header_path)\n\t\t\tif self.not_recursive and root != header_path:\n\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t\n\t\t\tfor item in files:\n\t\t\t\tfileNamePath = os.path.join(root, item)\n\t\t\t\t#print(header_path)\n\t\t\t\t#print(root)\n\t\t\t\tsubpath = root.replace(header_path, \"\").replace(\"\\\\\", \"/\").strip(\"/\")\n\t\t\t\t#print(subpath)\n\t\t\t\t# print(subpath.strip(\"/\"))\n\t\n\t\t\t\tdst_file = os.path.abspath(os.path.join(base_pub_dir, subpath, item))\n\t\t\t\tyield fileNamePath, dst_file\n\t\n\tdef copy_ext(self):\n\t\tft = self._ft_copy()\n\t\n\t\tfor fileNamePath, dst_file in ft:\n\t\t\t_, ext = os.path.splitext(fileNamePath)\n\t\t\tif ext.lower() in self.list_ext:\n\t\t\t\tsafe_copy(fileNamePath, dst_file)\n\t\n\tdef copy_reg(self):\n\t\t\n\t\tprint(\"copy_files_by_reg\", self.reg_exp,self.str_forbidden)\n\t\tft = self._ft_copy()\n\t\tlistStr_forbidden = [tmp.strip() for tmp in self.str_forbidden.split(\"|\") if tmp.strip() !=\"\"]\n\t\tfor fileNamePath, dst_file in ft:\n\t\t\tis_forbidden = False\n\t\t\tfor str_forbidden in listStr_forbidden:\n\t\t\t\tif str_forbidden!=\"\" and str_forbidden in fileNamePath:\n\t\t\t\t\tprint(fileNamePath,\"is forbidden\",file=sys.stderr)\n\t\t\t\t\tis_forbidden = True\n\t\t\t\t\tbreak\n\t\t\tif is_forbidden: continue\n\t\t\tmat = re.search(self.reg_exp,fileNamePath )\n\t\t\tif mat:\n\t\t\t\tprint(\"match info\", mat)\n\t\t\t\tsafe_copy(fileNamePath, dst_file)\n\t\n\tdef header(self):\n\t\tself.list_ext = [\".h\", \".hpp\"]\n\t\tself.copy_ext()\n\t\n\t\n\tdef source(self):\n\t\tself.list_ext = [\".c\", \".cpp\"]\n\t\tself.copy_ext()\n\t\n\t\n\tdef target(self,lib_org_path, platform, base_pub_dir):\n\t\tdst_dir, file_name = os.path.split(lib_org_path)\n\t\tbase_pub_dir = os.path.join(base_pub_dir, platform, file_name)\n\t\n\t\tsafe_copy(lib_org_path, base_pub_dir)\n\t\t# dst_dir = os.path.dirname(base_pub_dir)\n\t\t# if not os.path.exists(dst_dir):\n\t\t#\tos.makedirs(dst_dir)\n\t\t# shutil.copy(lib_org_path,base_pub_dir)\n\t\n\t\tprint(lib_org_path)\n\t\tprint(base_pub_dir)\n\t\tpass\n\t\n\t\n\tdef check_files(self,base_dir):\n\t\tfor tmp in find_files_simple(base_dir):\n\t\t\tprint(tmp)\n\t\t\n\t\tpass\n\t\t\n\t\t\n\n\tdef do_run(self):\n\t\tprocees = getattr(self, self.cmd)\n\t\tprocees()\n\t\tpass\n","sub_path":"neolib/neocopy/release.py","file_name":"release.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"365619590","text":"# для TCP\nimport socket\n\n# сообщение\nreq = 'Hello tcp!'\n\n# новый объект сокет с двумя опциями\n# AF_INET - работа с сетевыми сокетами\n# локальные есть еще\n# SOCK_STREAM - указывает на то, что мы будем работать с TCP socket'ом\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# подключаемся к удаленой машине, ip адрес и порт\n# тройное рукопажатие\ns.connect(('127.0.0.1', 1234))\n# отправляем данные\ns.send(req.encode())\n# получаем данные не больше числа 1024\nrsp = s.recv(1024)\ns.close\n\n\n\n# пример TCP сервера\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# bind - связывается с адрессом\n# listen - необходимо принимать соединение с данного адресса\ns.bind(('127.0.0.1', 1234))\n# 10 длина очереди вызовов\ns.listen(10)\n\nwhile True:\n\t# accept - возвращается когда установлено новое соединение\n\t# сокет и адрес клиента\n\tconn, addr = s.accept()\n\twhile True:\n\t\tdata = conn.recv(1024)\n\t\tif not data: break\n\t\tconn.send(data.encode())\n\tconn.close()\n\n\n# как читать данные из сокета\n\ndef myreceive(sock, msglen):\n\tmsg = ''\n\n\twhile len(msg) < msglen:\n\t\tchunk = sock.recv(msglen - len(msg))\n\n\t\tif chunk == '':\n\t\t\traise RuntimeError('broken')\n\n\t\tmsg = msg + chunk\n\n\treturn msg\n\n\n# как записывать данные в сокет\n\ndef mysend(sock, msg):\n\ttotalsent = 0\n\n\twhile totalsent < len(msg):\n\t\t# send возвращает число, сколько байт уже отправленно\n\t\tsent = sock.send(msg[totalsent:])\n\n\t\tif sent == 0:\n\t\t\traise RuntimeError('broken')\n\t\ttotalsent = totalsent + sent\n\n\n\n\n# 1 задача на stepic\nimport socket\ns = socket.socket()\ns.bind(('0.0.0.0', 2222))\ns.listen(1)\n\nwhile True:\n conn, addr = s.accept()\n while True:\n data = conn.recv(1024)\n if data=='close' : break\n conn.send(data)\n conn.close()\n\n# 2 задача на stepic\n\nimport socket\nimport os \ns = socket.socket()\ns.bind(('0.0.0.0', 2222))\ns.listen(1)\npid = os.fork()\nwhile True:\n if pid == 0:\n while True:\n conn, addr = s.accept()\n data = conn.recv(1024)\n conn.send(data)\n conn.close()","sub_path":"web_tech/tcp_cl_ser.py","file_name":"tcp_cl_ser.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"323049950","text":"#===============================================================================\n#INFORMATIONS\n#===============================================================================\n\"\"\"\nCEFE - EPHE - BENCHMARK eDNA 2019\nmathon laetitia, guerin pierre-edouard\ncreer un fichier OBIFASTA a partir des sequences SPY.fas generes par VSEARCH\n\ndescription:\n\ninput:\n\noutput:\n\n\nusage:\n\npython2 vsearch_to_obifasta.py -f input_vsearch.fasta -o output_obifasta.fasta\n\n\n\"\"\"\n#===============================================================================\n#MODULES\n#===============================================================================\nimport argparse\nimport os\nimport Bio\nfrom Bio import SeqIO\nfrom Bio.Alphabet import IUPAC\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\n\n\n#===============================================================================\n#ARGUMENTS\n#===============================================================================\n\nparser = argparse.ArgumentParser('convert fasta to obiconvert format')\nparser.add_argument(\"-o\",\"--output\",type=str)\nparser.add_argument(\"-f\",\"--vsearch_fasta\",type=str)\n\n\n#===============================================================================\n#MAIN\n#===============================================================================\n\nargs = parser.parse_args()\nvsearchFile = args.vsearch_fasta\noutputFile = args.output\n\n#vsearch_fasta=\"Outputs/01_vsearch/main/grinder_teleo1_sample_S1-01.fasta\"\nmes_records=[]\nfor seq_record in SeqIO.parse(vsearchFile, \"fasta\", alphabet=IUPAC.unambiguous_dna):\n #seq_record_idSplit=seq_record.id.split(\";\")\n seq_record_DescriptionSplit=seq_record.description.split(\";\")\n local_id=\"\"\n for elem in seq_record_DescriptionSplit:\n if \"sample\" in elem:\n sampleName=elem.split('=')[1]\n local_id=local_id+\";\"+str(elem)\n elif \"size\" in elem:\n sizeSeq=elem.split('=')[1]\n else:\n local_id=local_id+\";\"+str(elem)\n local_id=local_id[1:]+\" count=\"+sizeSeq+\"; merged_sample={'\"+sampleName+\"': \"+sizeSeq+\"};\"\n local_seq=str(seq_record.seq.lower()).replace(\"'\",\"\")\n local_record=SeqRecord(Seq(local_seq,IUPAC.unambiguous_dna), id=local_id,description=\"\")\n mes_records.append(local_record)\nSeqIO.write(mes_records, outputFile, \"fasta\")\n","sub_path":"benchmark_simulated_dataset/07_complete_pipelines/assembled_pipeline/vsearch_to_obifasta.py","file_name":"vsearch_to_obifasta.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"76110478","text":"def find(target):\n if parent[target] < 0:\n return target\n else:\n parent[target] = find(parent[target])\n return parent[target]\n\ndef is_same(x, y):\n return find(x) == find(y)\n\ndef union(x, y):\n root_x = find(x)\n root_y = find(y)\n if root_x == root_y:\n return\n if parent[root_x] > parent[root_y]:\n root_x, root_y = root_y, root_x\n parent[root_x] += parent[root_y]\n parent[root_y] = root_x\n\n# 今回これ使わないけど、どこに誰がいるのかはこれでわかる\ndef members(n, x):\n root = find(x)\n return [i for i in range(n) if find(i) == root]\n\ndef get_size(x):\n return -parent[find(x)]\n\ndef get_root():\n return [i for i, root in enumerate(parent) if root < 0]\nn, m = map(int, input().split())\nparent = [-1 for _ in range(n)]\nfor _ in range(m):\n a, b = map(lambda x: int(x) - 1, input().split())\n union(a, b)\nans = 0\nfor i in range(n):\n ans = max(ans, get_size(i))\nprint(ans)","sub_path":"Python_codes/p02573/s763805247.py","file_name":"s763805247.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"645351427","text":"\"\"\"\nholds the queries and results used for tests in main.py\n\"\"\"\n\nallGroups_query = \"\"\"\n{\n allGroups {\n id\n name\n }\n}\n\"\"\"\nallGroups_value = {\n \"data\": {\n \"allGroups\": [\n {\n \"id\": \"1\",\n \"name\": \"General\"\n },\n {\n \"id\": \"2\",\n \"name\": \"Customer Service\"\n },\n {\n \"id\": \"3\",\n \"name\": \"Marketing\"\n }\n ]\n }\n}\n\ndepartments_query = \"\"\"\n{\n departments(group: 1) {\n id\n name\n }\n}\n\"\"\"\ndepartments_value = {\n \"data\": {\n \"departments\": [\n {\n \"id\": \"1\",\n \"name\": \"Tech\"\n },\n {\n \"id\": \"2\",\n \"name\": \"Buying and Merchandising\"\n },\n {\n \"id\": \"3\",\n \"name\": \"Finance\"\n },\n {\n \"id\": \"4\",\n \"name\": \"Operations\"\n },\n {\n \"id\": \"5\",\n \"name\": \"Languages\"\n },\n {\n \"id\": \"6\",\n \"name\": \"Products\"\n }\n ]\n }\n}\n\nmetricsByDepartment_query = \"\"\"\n{\n metricsByDepartment(department: 1) {\n id\n name\n }\n}\n\"\"\"\nmetricsByDepartment_value = {\n \"data\": {\n \"metricsByDepartment\": [\n {\n \"id\": \"1\",\n \"name\": \"number of commits\"\n }\n ]\n }\n}\n\nsubmetrics_query = \"\"\"\n{\n submetrics(metric: 1) {\n id\n func\n description\n high_bound\n low_bound\n }\n}\n\"\"\"\nsubmetrics_value = {\n \"data\": {\n \"submetrics\": [\n {\n \"id\": \"1\",\n \"func\": \"number_of_commits\",\n \"description\": \"number of commits from tech\",\n \"high_bound\": \"10\",\n \"low_bound\": \"1\"\n }\n ]\n }\n}\n\nsubmetricValues_query = \"\"\"\n{\n mostRecentSubmetricValues(submetric: 1) {\n id\n colour\n added_at\n display_val\n }\n}\n\"\"\"\nsubmetricValues_value = {\n \"data\": {\n \"mostRecentSubmetricValues\": [\n {\n \"id\": \"1\",\n \"colour\": \"red\",\n \"added_at\": \"Mon Jul 17 2017 15:15:40 GMT+0100 (BST)\",\n \"display_val\": \"0\"\n }\n ]\n }\n}\n\n\nmetricsByRepRate_query = \"\"\"\n{\n metricsByRepRate(rep_rate: 1) {\n id\n name\n }\n}\n\"\"\"\nmetricsByRepRate_value = {\n \"data\": {\n \"metricsByRepRate\": [\n {\n \"id\": \"1\",\n \"name\": \"number of commits\"\n },\n {\n \"id\": \"2\",\n \"name\": \"number of SKUs\"\n },\n {\n \"id\": \"3\",\n \"name\": \"is everyone being payed?\"\n },\n {\n \"id\": \"4\",\n \"name\": \"revenue per session\"\n }\n ]\n }\n}\n\ninsert_query = \"\"\"\nmutation {\n createSubmetricValue(\n submetric: 1\n colour: \"test\"\n display_val: \"test\"\n ) {\n id\n }\n}\n\"\"\"\ninsert_value = {\n \"data\": {\n \"createSubmetricValue\": {\n \"id\": \"5\"\n }\n }\n}\n","sub_path":"express/api_base_tests/values.py","file_name":"values.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"155922286","text":"global userName \r\nglobal name \r\nglobal charName \r\nglobal charRace \r\nglobal charAge \r\nglobal charHair \r\nglobal charSkin \r\nglobal charHight \r\nglobal charBody \r\nglobal HP \r\nglobal STR \r\nglobal MAG \r\nglobal SPD \r\nglobal LCK \r\nglobal DEF \r\nglobal RES \r\nglobal GOLD \r\nglobal SILVER \r\nglobal COPPER \r\nuserName = 'a'\r\nname = 'a'\r\ncharName = 'a'\r\ncharRace = 'a'\r\ncharAge = 'a'\r\ncharHair = 'a'\r\ncharSkin = 'a'\r\ncharHight = 'a'\r\ncharBody = 'a'\r\nHP = '0'\r\nSTR = '0'\r\nMAG = '0'\r\nSPD = '0'\r\nLCK = '0'\r\nDEF = '0'\r\nRES = '0'\r\nGOLD = '0'\r\nSILVER = '0'\r\nCOPPER = '0'\r\n","sub_path":"a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615298485","text":"'''\n750. Number Of Corner Rectangles My SubmissionsBack to Contest\n\nDifficulty: Medium\nGiven a grid where each entry is only 0 or 1, find the number of corner rectangles.\nA corner rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle.\nNote that only the corners need to have the value 1. Also, all four 1s used must be distinct.\n\nExample 1:\nInput: grid =\n[[1, 0, 0, 1, 0],\n [0, 0, 1, 0, 1],\n [0, 0, 0, 1, 0],\n [1, 0, 1, 0, 1]]\nOutput: 1\nExplanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].\nExample 2:\nInput: grid =\n[[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]]\nOutput: 9\nExplanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.\nExample 3:\nInput: grid =\n[[1, 1, 1, 1]]\nOutput: 0\nExplanation: Rectangles must have four distinct corners.\nNote:\nThe number of rows and columns of grid will each be in the range [1, 200].\nEach grid[i][j] will be either 0 or 1.\nThe number of 1s in the grid will be at most 6000.\n'''\nclass Solution(object):\n def countCornerRectangles(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n m=len(grid)\n n=len(grid[0])\n save={}\n for x in range(n):\n for y in range(x+1,n):\n save[(x,y)]=[]\n for i in range(m):\n for x in range(n):\n if grid[i][x]:\n for y in range(x+1,n):\n if grid[i][y]:\n save[(x,y)].append(i)\n count=0\n\n for i in save:\n count+=len(save[i])*(len(save[i])-1)/2\n return int(count)\n\nsol = Solution()\ngrid = [[1, 0, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [1, 0, 1, 0, 1]]\nprint(sol.countCornerRectangles(grid))","sub_path":"LeetCodeContests/63/750_corner_rectangles.py","file_name":"750_corner_rectangles.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"434911214","text":"#!/usr/bin/python3\n\"\"\"File Storage of objects \"\"\"\nimport json\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\n\n\nclass FileStorage:\n \"\"\"this class used for serialiez and deserilalize json files \"\"\"\n\n __file_path = \"file.json\"\n __objects = {}\n class_dict = {\"BaseModel\": BaseModel, \"User\": User, \"Place\": Place,\n \"Amenity\": Amenity, \"City\": City, \"Review\": Review,\n \"State\": State}\n\n def all(self):\n \"\"\"returns the dictionary __objects \"\"\"\n return self.__objects\n\n def new(self, obj):\n \"\"\"sets in __objects the obj with key .id \"\"\"\n if obj:\n key = '{}.{}'.format(obj.__class__.__name__, obj.id)\n self.__objects[key] = obj\n\n def save(self):\n \"\"\"serializes __objects to the JSON file \"\"\"\n my_dict = {}\n for key, obj in self.__objects.items():\n my_dict[key] = obj.to_dict()\n with open(self.__file_path, 'w') as f:\n json.dump(my_dict, f)\n\n def reload(self):\n \"\"\" deserializes the JSON file to __objects \"\"\"\n try:\n with open(self.__file_path, 'r') as f:\n new_obj = json.load(f)\n for key, val in new_obj.items():\n obj = self.class_dict[val['__class__']](**val)\n self.__objects[key] = obj\n except FileNotFoundError:\n pass\n","sub_path":"models/engine/file_storage.py","file_name":"file_storage.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"633934867","text":"# Copyright 2016-2018, Pulumi 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\"\"\"\nSupport for automatic stack components.\n\"\"\"\nfrom __future__ import absolute_import\n\nfrom ..resource import ComponentResource\nfrom .settings import get_project, get_stack, get_root_resource, set_root_resource\n\ndef run_in_stack(func):\n \"\"\"\n Run the given function inside of a new stack resource. This ensures that any stack export calls will end\n up as output properties on the resulting stack component in the checkpoint file. This is meant for internal\n runtime use only and is used by the Python SDK entrypoint program.\n \"\"\"\n Stack(func)\n\nclass Stack(ComponentResource):\n \"\"\"\n A synthetic stack component that automatically parents resources as the program runs.\n \"\"\"\n def __init__(self, func):\n # Ensure we don't already have a stack registered.\n if get_root_resource() is not None:\n raise Exception('Only one root Pulumi Stack may be active at once')\n\n # Now invoke the registration to begin creating this resource.\n name = '%s-%s' % (get_project(), get_stack())\n super(Stack, self).__init__('pulumi:pulumi:Stack', name, None, None)\n\n # Invoke the function while this stack is active and then register its outputs.\n self.outputs = dict()\n set_root_resource(self)\n try:\n func()\n finally:\n self.register_outputs(self.outputs)\n # Intentionally leave this resource installed in case subsequent async work uses it.\n\n def output(self, name, value):\n \"\"\"\n Export a stack output with a given name and value.\n \"\"\"\n self.outputs[name] = value\n","sub_path":"sdk/python/lib/pulumi/runtime/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"462084166","text":"\"\"\" \nThe commands module contains the base definition for\na generic Qubole command and the implementation of all \nthe specific commands\n\"\"\"\n\nfrom qubole import Qubole\nfrom resource import Resource\nfrom exception import ParseError\nfrom account import Account\nfrom qds_sdk.util import GentleOptionParser\nfrom qds_sdk.util import OptionParsingError\nfrom qds_sdk.util import OptionParsingExit\n\nimport boto\n\nimport time\nimport logging\nimport sys\nimport re\nimport os\nimport pipes\n\nlog = logging.getLogger(\"qds_commands\")\n\n# Pattern matcher for s3 path\n_URI_RE = re.compile(r's3://([^/]+)/?(.*)')\n\nclass Command(Resource):\n\n \"\"\"\n qds_sdk.Command is the base Qubole command class. Different types of Qubole\n commands can subclass this.\n \"\"\"\n\n \"\"\" all commands use the /commands endpoint\"\"\"\n rest_entity_path=\"commands\"\n\n @staticmethod\n def is_done(status):\n \"\"\"\n Does the status represent a completed command\n Args:\n ``status``: a status string\n\n Returns:\n True/False\n \"\"\"\n return (status == \"cancelled\" or status == \"done\" or status == \"error\")\n\n @staticmethod\n def is_success(status):\n return (status == \"done\")\n \n @classmethod\n def create(cls, **kwargs):\n \"\"\"\n Create a command object by issuing a POST request to the /command endpoint\n Note - this does not wait for the command to complete\n\n Args:\n `\\**kwargs` - keyword arguments specific to command type\n\n Returns:\n Command object\n \"\"\"\n\n conn=Qubole.agent()\n if kwargs.get('command_type') is None:\n kwargs['command_type'] = cls.__name__\n\n return cls(conn.post(cls.rest_entity_path, data=kwargs))\n\n\n @classmethod\n def run(cls, **kwargs):\n \"\"\"\n Create a command object by issuing a POST request to the /command endpoint\n Waits until the command is complete. Repeatedly polls to check status\n\n Args:\n `\\**kwargs` - keyword arguments specific to command type\n\n Returns:\n Command object\n \"\"\"\n cmd = cls.create(**kwargs)\n while not Command.is_done(cmd.status):\n time.sleep(Qubole.poll_interval)\n cmd = cls.find(cmd.id)\n\n return cmd\n\n @classmethod\n def cancel_id(cls, id):\n \"\"\"\n Cancels command denoted by this id\n\n Args:\n `id` - command id\n \"\"\"\n conn=Qubole.agent()\n data={\"status\":\"kill\"}\n conn.put(cls.element_path(id), data)\n \n\n def cancel(self):\n \"\"\"\n Cancels command represented by this object\n \"\"\"\n self.__class__.cancel_id(self.id)\n\n\n def get_log(self):\n \"\"\"\n Fetches log for the command represented by this object\n\n Returns:\n The log as a string\n \"\"\"\n log_path = self.meta_data['logs_resource']\n conn=Qubole.agent()\n r=conn.get_raw(log_path)\n return r.text\n\n def get_results(self, fp=sys.stdout, inline=True):\n \"\"\"\n Fetches the result for the command represented by this object\n\n @param fp: a file object to write the results to directly\n \"\"\"\n result_path = self.meta_data['results_resource']\n \n conn=Qubole.agent()\n \n r = conn.get(result_path , {'inline': inline})\n if r.get('inline'):\n fp.write(r['results'].encode('utf8'))\n else: \n acc = Account.find()\n boto_conn = boto.connect_s3(aws_access_key_id=acc.storage_access_key,\n aws_secret_access_key=acc.storage_secret_key)\n\n log.info(\"Starting download from result locations: [%s]\" % \",\".join(r['result_location']))\n\n for s3_path in r['result_location']:\n _download_to_local(boto_conn, s3_path, fp)\n\n\nclass HiveCommand(Command):\n\n usage = (\"hivecmd run [options]\")\n \n\n optparser = GentleOptionParser(usage=usage)\n optparser.add_option(\"-q\", \"--query\", dest=\"query\", help=\"query string\")\n\n optparser.add_option(\"-f\", \"--script_location\", dest=\"script_location\", \n help=\"Path where hive query to run is stored. Can be S3 URI or local file path\")\n\n optparser.add_option(\"--macros\", dest=\"macros\", \n help=\"expressions to expand macros used in query\")\n\n optparser.add_option(\"--sample_size\", dest=\"sample_size\", \n help=\"size of sample in bytes on which to run query\")\n\n @classmethod\n def parse(cls, args):\n \"\"\"\n Parse command line arguments to construct a dictionary of command\n parameters that can be used to create a command\n\n Args:\n `args` - sequence of arguments\n\n Returns:\n Dictionary that can be used in create method\n\n Raises:\n ParseError: when the arguments are not correct\n \"\"\"\n\n try:\n (options, args) = cls.optparser.parse_args(args)\n if options.query is None and options.script_location is None:\n raise ParseError(\"One of query or script location\"\n \" must be specified\", \n cls.optparser.format_help())\n except OptionParsingError as e:\n raise ParseError(e.msg, cls.optparser.format_help())\n except OptionParsingExit as e:\n return None\n\n if options.script_location is not None:\n if options.query is not None:\n raise ParseError(\n \"Both query and script_location cannot be specified\", \n cls.optparser.format_help())\n\n if ((options.script_location.find(\"s3://\") != 0) and\n (options.script_location.find(\"s3n://\") != 0)):\n\n # script location is local file\n \n try:\n q = open(options.script_location).read()\n except:\n raise ParseError(\"Unable to open script location: %s\" % \n options.script_location,\n cls.optparser.format_help())\n options.script_location = None\n options.query = q\n\n\n return vars(options)\n\nclass HadoopCommand(Command):\n subcmdlist = [\"jar\", \"s3distcp\", \"streaming\"]\n usage = \"hadoopcmd <%s> [arg2] ...\" % \" | \".join(subcmdlist)\n \n @classmethod\n def parse(cls, args):\n \"\"\"\n Parse command line arguments to construct a dictionary of command\n parameters that can be used to create a command\n\n Args:\n `args` - sequence of arguments\n\n Returns:\n Dictionary that can be used in create method\n\n Raises:\n ParseError: when the arguments are not correct\n \"\"\"\n parsed = {}\n \n if len(args) >= 1 and args[0] == \"-h\":\n sys.stderr.write(cls.usage + \"\\n\")\n return None\n\n if len(args) < 2:\n raise ParseError(\"Need at least two arguments\", cls.usage)\n \n subcmd = args.pop(0)\n if subcmd not in cls.subcmdlist:\n raise ParseError(\"First argument must be one of <%s>\" % \n \"|\".join(cls.subcmdlist))\n\n parsed[\"sub_command\"] = subcmd\n parsed[\"sub_command_args\"] = \" \".join(\"'\" + a + \"'\" for a in args)\n \n return parsed\n\n pass\n\nclass ShellCommand(Command):\n usage = (\"shellcmd run [options] [arg1] [arg2] ...\")\n \n\n optparser = GentleOptionParser(usage=usage)\n optparser.add_option(\"-s\", \"--script\", dest=\"inline\", help=\"inline script that can be executed by bash\")\n\n optparser.add_option(\"-f\", \"--script_location\", dest=\"script_location\", \n help=\"Path where bash script to run is stored. Can be S3 URI or local file path\")\n\n @classmethod\n def parse(cls, args):\n \"\"\"\n Parse command line arguments to construct a dictionary of command\n parameters that can be used to create a command\n\n Args:\n `args` - sequence of arguments\n\n Returns:\n Dictionary that can be used in create method\n\n Raises:\n ParseError: when the arguments are not correct\n \"\"\"\n\n try:\n (options, args) = cls.optparser.parse_args(args)\n if options.inline is None and options.script_location is None:\n raise ParseError(\"One of script or it's location\"\n \" must be specified\", \n cls.optparser.format_help())\n except OptionParsingError as e:\n raise ParseError(e.msg, cls.optparser.format_help())\n except OptionParsingExit as e:\n return None\n\n if options.script_location is not None:\n if options.inline is not None:\n raise ParseError(\n \"Both script and script_location cannot be specified\", \n cls.optparser.format_help())\n\n if ((options.script_location.find(\"s3://\") != 0) and\n (options.script_location.find(\"s3n://\") != 0)):\n\n # script location is local file\n \n try:\n s = open(options.script_location).read()\n except:\n raise ParseError(\"Unable to open script location: %s\" % \n options.script_location,\n cls.optparser.format_help())\n options.script_location = None\n options.inline = s\n\n if ((args is not None) and (len(args) > 0)):\n if options.inline is not None:\n raise ParseError(\n \"This sucks - but extra arguments can only be \"\n \"supplied with a script_location in S3 right now\",\n cls.optparser.format_help())\n\n setattr(options, 'parameters',\n \" \".join([pipes.quote(a) for a in args]))\n\n\n else:\n if ((args is not None) and (len(args) > 0)):\n raise ParseError(\n \"Extra arguments can only be supplied with a script_location\",\n cls.optparser.format_help()) \n\n return vars(options)\n\nclass PigCommand(Command):\n usage = (\"pigcmd run [options] [key1=value1] [key2=value2] ...\")\n \n\n optparser = GentleOptionParser(usage=usage)\n optparser.add_option(\"-s\", \"--script\", dest=\"latin_statements\",\n help=\"latin statements that has to be executed\")\n\n optparser.add_option(\"-f\", \"--script_location\", dest=\"script_location\", \n help=\"Path where bash script to run is stored. Can be S3 URI or local file path\")\n\n @classmethod\n def parse(cls, args):\n \"\"\"\n Parse command line arguments to construct a dictionary of command\n parameters that can be used to create a command\n\n Args:\n `args` - sequence of arguments\n\n Returns:\n Dictionary that can be used in create method\n\n Raises:\n ParseError: when the arguments are not correct\n \"\"\"\n\n try:\n (options, args) = cls.optparser.parse_args(args)\n if options.latin_statements is None and options.script_location is None:\n raise ParseError(\"One of script or it's location\"\n \" must be specified\", \n cls.optparser.format_help())\n except OptionParsingError as e:\n raise ParseError(e.msg, cls.optparser.format_help())\n except OptionParsingExit as e:\n return None\n\n if options.script_location is not None:\n if options.latin_statements is not None:\n raise ParseError(\n \"Both script and script_location cannot be specified\", \n cls.optparser.format_help())\n\n if ((options.script_location.find(\"s3://\") != 0) and\n (options.script_location.find(\"s3n://\") != 0)):\n\n # script location is local file\n \n try:\n s = open(options.script_location).read()\n except:\n raise ParseError(\"Unable to open script location: %s\" % \n options.script_location,\n cls.optparser.format_help())\n options.script_location = None\n options.latin_statements = s\n\n if ((args is not None) and (len(args) > 0)):\n if options.latin_statements is not None:\n raise ParseError(\n \"This sucks - but extra arguments can only be \"\n \"supplied with a script_location in S3 right now\",\n cls.optparser.format_help())\n\n p = {}\n for a in args:\n kv = a.split('=')\n if len(kv)!=2:\n raise ParseError(\"Arguments to pig script must be of this format k1=v1 k2=v2 k3=v3...\")\n p[kv[0]] = kv[1]\n setattr(options, 'parameters',p)\n\n else:\n if ((args is not None) and (len(args) > 0)):\n raise ParseError(\n \"Extra arguments can only be supplied with a script_location\",\n cls.optparser.format_help()) \n \n return vars(options)\n\nclass DbImportCommand(Command):\n @classmethod\n def parse(cls, args):\n raise ParseError(\"dbimport command not implemented yet\", \"\")\n pass\n\n\ndef _download_to_local(boto_conn, s3_path, fp):\n '''\n Downloads the contents of all objects in s3_path into fp\n \n @param boto_conn: S3 connection object\n @param s3_path: S3 path to be downloaded\n @param fp: The file object where data is to be downloaded\n \n '''\n #Progress bar to display download progress\n def _callback(downloaded, total):\n '''\n Call function for upload.\n @param key_name: File size already downloaded\n @type key_name: int\n @param key_prefix: Total file size to be downloaded\n @type key_prefix: int\n '''\n if ((total is 0) or (downloaded == total)):\n return\n progress = downloaded*100/total\n sys.stderr.write('\\r[{0}] {1}%'.format('#'*progress, progress))\n sys.stderr.flush()\n \n \n m = _URI_RE.match(s3_path) \n bucket_name = m.group(1)\n bucket = boto_conn.get_bucket(bucket_name)\n \n if s3_path.endswith('/') is False:\n #It is a file\n key_name = m.group(2) \n key_instance = bucket.get_key(key_name)\n \n log.info(\"Downloading file from %s\" % s3_path)\n key_instance.get_contents_to_file(fp) #cb=_callback\n \n else:\n #It is a folder\n key_prefix = m.group(2)\n bucket_paths = bucket.list(key_prefix)\n \n for one_path in bucket_paths:\n name = one_path.name\n \n # Eliminate _tmp_ files which ends with $folder$\n if name.endswith('$folder$'):\n continue\n \n log.info(\"Downloading file from %s\" % name)\n one_path.get_contents_to_file(fp) #cb=_callback\n","sub_path":"qds_sdk/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":15507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"78901873","text":"from os import write\r\nimport boto3\r\nimport json\r\nfrom google.protobuf.symbol_database import Default \r\nimport requests\r\nimport streamlit as st\r\nimport streamlit.components.v1 as components\r\n\r\nst.set_page_config(layout='wide')\r\n\r\nhide_streamlit_style = \"\"\"\r\n\r\n\r\n\"\"\"\r\nst.markdown(hide_streamlit_style, unsafe_allow_html=True) \r\n\r\n\r\n\r\n\r\nst.sidebar.title(\"NLP Services\")\r\nst.sidebar.image('img/sidepic.png', width=None)\r\nst.sidebar.subheader('Choose your service :bulb:')\r\nnav = st.sidebar.selectbox(\" \",['Translate','Medical NER','Sentiment Detection','Text-Speech'])\r\nst.sidebar.write(\" \")\r\nst.sidebar.write(\" \")\r\nst.sidebar.write(\" \")\r\nst.sidebar.write(\" \")\r\nst.sidebar.write(\" \")\r\nst.sidebar.write(\" \")\r\nst.sidebar.write(\" \")\r\nst.sidebar.write(\" \")\r\nst.sidebar.write(\" \")\r\nst.sidebar.subheader('About')\r\n\r\n\r\nst.sidebar.write(''' This webapp was developed by Archer Rozario J 3MDS''')\r\nif nav == 'Translate':\r\n\r\n st.subheader(\"TRANSLATION SERVICE\")\r\n st.image('img/translation-service-image.png', width=None)\r\n\r\n st.subheader(\"Enter input text\")\r\n sampText = st.text_area('')\r\n st.subheader('Enter Input Language Code')\r\n inpLang = st.text_input('')\r\n st.subheader('Output Language Code')\r\n outLang = st.text_input(' ')\r\n client = boto3.client('translate', region_name = \"us-east-1\")\r\n\r\n trans_button = st.button(\"Translate\")\r\n if trans_button:\r\n response = client.translate_text(Text = sampText,\r\n SourceLanguageCode = inpLang,\r\n TargetLanguageCode = outLang)\r\n\r\n output = response['TranslatedText']\r\n st.write(output)\r\n\r\nif nav == \"Medical NER\":\r\n st.subheader(\"Medical NER Service\")\r\n st.image('img/NER.png', width=None)\r\n client = boto3.client(service_name='comprehendmedical', region_name=\"us-east-1\")\r\n st.subheader('Enter input text') \r\n text1 = st.text_area(\" \")\r\n ner = st.button(\"Analyze Medical NER\")\r\n if ner:\r\n result = json.dumps(client.detect_entities(Text= text1, LanguageCode='en'), sort_keys=True, indent=4)\r\n res = json.loads(result)\r\n resEntities = res[\"body\"][\"Entities\"]\r\n resText = [i['Text'] for i in resEntities]\r\n resCategories = [i['Category'] for i in resEntities]\r\n entDict = dict(zip(resText, resCategories))\r\n st.write(entDict) \r\n \r\n \r\n\r\nif nav == \"Sentiment Detection\":\r\n st.subheader(\"SENTIMENT DETECTION\")\r\n st.image('img/sentiment-analysis.png', width=None)\r\n comprehend = boto3.client(service_name='comprehend', region_name='us-east-1')\r\n st.subheader('Enter text for detection') \r\n text = st.text_area(\" \")\r\n\r\n analyze = st.button(\"Analyze Sentiment\")\r\n if analyze:\r\n resp = json.dumps(comprehend.detect_sentiment(Text=text, LanguageCode='en'), sort_keys=True, indent=4)\r\n resp_dict = json.loads(resp)\r\n st.subheader(\"Sentimet\")\r\n st.write(resp_dict['Sentiment'])\r\n st.subheader(\"Sentiment Score\")\r\n st.write(resp_dict[\"SentimentScore\"])\r\n\r\nif nav == 'Text-Speech':\r\n st.subheader(\"Text-Speech\")\r\n st.image('img/t2s.jpg')\r\n polly = boto3.client(service_name='polly',region_name='us-east-1')\r\n st.subheader(\"Enter the text for speech conversion\")\r\n text2=st.text_area(\" \")\r\n audio = st.button(\"Generate Audio\")\r\n if audio:\r\n response = polly.synthesize_speech(OutputFormat='mp3', VoiceId='Brian',\r\n Text=text2)\r\n\r\n file = open('static/audio/speech.mp3', 'wb')\r\n file.write(response['AudioStream'].read())\r\n file.close()\r\n audio_file = open('static/audio/speech.mp3', 'rb')\r\n audio_bytes = audio_file.read()\r\n st.audio(audio_bytes, format='audio/mp3')\r\n ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"431750649","text":"import functools\nfrom multiprocessing.pool import Pool\n\nimport cv2\nimport numpy as np\nimport sys\nimport glob\nimport os\nimport operator\n\nfrom PIL import Image, ImageEnhance\n\nif len(sys.argv) != 2:\n print(\n## \"Give the path to the trained shape predictor model as the first \"\n## \"argument and then the directory containing the facial images.\\n\"\n## \"For example, if you are in the python_examples folder then \"\n## \"execute this program by running:\\n\"\n## \" ./face_landmark_detection.py shape_predictor_68_face_landmarks.dat ../examples/faces\\n\"\n## \"You can download a trained facial shape predictor from:\\n\"\n## \" http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2\")\n \"Give the directory containing the facial images.\\n\")\n exit()\n\n## predictor_path = sys.argv[1]\n## faces_folder_path = sys.argv[2]\n\n##predictor_path = \"./shape_predictor_68_face_landmarks.dat\"\nfaces_folder_path = sys.argv[1]\n\n# faces_folder_path = \"alignedFace\"\n\n\ndef find_between_r( s, first, last ):\n try:\n start = s.rindex( first ) + len( first )\n end = s.rindex( last, start )\n return s[start:end]\n except ValueError:\n return \"\"\n\ndef equalize(im):\n h = im.convert(\"L\").histogram()\n lut = []\n for b in range(0, len(h), 256):\n # step size\n step = functools.reduce(operator.add, h[b:b+256]) / 255\n # create equalization lookup table\n n = 0\n for i in range(256):\n lut.append(n / step)\n n = n + h[i+b]\n # map image through lookup table\n return im.point(lut*im.layers)\n\ndef run(f):\n # for f in glob.glob(os.path.join(faces_folder_path, \"*.jpg\")):\n\n # img1 = cv2.imread(f) #load rgb image\n # a = np.double(img1)\n # b = a + 15\n # img2 = np.uint8(b)\n ##cv2.imshow(\"frame\",img1)\n## cv2.imshow(\"frame2\",img2)\n## cv2.waitKey(0)\n## cv2.destroyAllWindows()\n img = Image.open(f)\n img = equalize(img)\n # img = ImageEnhance.Sharpness(img).enhance(3.0)\n # img.show()\n if not os.path.exists(\"enhanced\"):\n os.makedirs(\"enhanced\")\n print(\"enhanced/\"+find_between_r(f,\"\\\\\",\".jpg\")+\".jpg\")\n img.save(\"enhanced/\"+find_between_r(f,\"\\\\\",\".jpg\")+\".jpg\")\n\nif __name__ == '__main__':\n p = Pool()\n p.map_async(run,(glob.glob(os.path.join(faces_folder_path, \"*.jpg\"))))\n p.close()\n p.join()\n\n\n","sub_path":"imageEnhancment.py","file_name":"imageEnhancment.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"504244827","text":"import os\n\nDEBUG = False\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get('SECRET_KEY')\n\nALLOWED_HOSTS = ['www.canadaecigs.com']\n\n# from .email_info import EMAIL_HOST, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, EMAIL_PORT, EMAIL_USE_TLS, DEFAULT_FROM_EMAIL, BASE_URL, MANAGER_NAME\n\nEMAIL_HOST = 'mail.canadaecigs.com'\nEMAIL_HOST_USER = 'info@canadaecigs.com' \n# EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')\nEMAIL_HOST_PASSWORD = 'Ps3elokod+'\nEMAIL_PORT = 26\nEMAIL_USE_TLS = True\nDEFAULT_FROM_EMAIL = 'Canada E-Cigs '\nBASE_URL = 'http://www.canadaecigs.com'\n\nMANAGERS = (\n ('Canada E-Cigs', 'info@canadaecigs.com'),\n)\n\nADMINS = MANAGERS\n\n# SECURITY WARNING: don't run with debug turned on in production!\n\n# Application definition\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sitemaps',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n # third party\n 'storages',\n 'colorfield',\n 'tinymce',\n 'paypal.standard.ipn',\n\n #our apps\n 'accounts',\n 'addresses',\n 'analytics',\n 'blog',\n 'billing',\n 'carts',\n 'coupons',\n 'contact',\n 'marketing',\n 'orders',\n 'panel',\n 'products',\n 'search',\n 'shipping',\n 'tags',\n 'design',\n]\n\nSITE_ID = 1\n\nWSGI_APPLICATION = 'canadaecigs.wsgi.application'\n\nAUTH_USER_MODEL = 'accounts.User' #changes the built-in user model to ours\nLOGIN_URL = '/login/'\nLOGIN_URL_REDIRECT = '/'\nLOGOUT_URL = '/logout/'\n\nFORCE_SESSION_TO_ONE = False\nFORCE_INACTIVE_USER_ENDSESSION= False\n\nMAILCHIMP_API_KEY = os.environ.get(\"MAILCHIMP_API_KEY\")\nMAILCHIMP_DATA_CENTER = os.environ.get(\"MAILCHIMP_DATA_CENTER\")\nMAILCHIMP_EMAIL_LIST_ID = os.environ.get(\"MAILCHIMP_EMAIL_LIST_ID\")\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nLOGOUT_REDIRECT_URL = '/login/'\nROOT_URLCONF = 'canadaecigs.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\n\n# Database\n# https://docs.djangoproject.com/en/1.11/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\nimport dj_database_url\ndb_from_env = dj_database_url.config() #postgreSQL Database in heroku\nDATABASES['default'].update(db_from_env)\nDATABASES['default']['CONN_MAX_AGE'] = 500\n\n# Password validation\n# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.11/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.11/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, \"static\"),\n]\n\nSTATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"static_cdn\", \"static_root\")\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"static_cdn\", \"media_root\")\n\n# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\nSTATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\n\nPROTECTED_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"static_cdn\", \"protected_media\")\n\n# TINY MCE TEXT EDITOR\n# TINYMCE_JS_URL = os.path.join(STATIC_URL, \"tinymce/media/tiny_mce/tiny_mce.js\")\nTINYMCE_JS_URL = os.path.join(BASE_DIR, \"tinymce/media/tiny_mce/tiny_mce.js\")\n\nTINYMCE_DEFAULT_CONFIG = {\n 'plugins': \"table,spellchecker,paste,searchreplace\",\n 'theme': \"advanced\",\n 'cleanup_on_startup': True,\n 'custom_undo_redo_levels': 10,\n}\nTINYMCE_SPELLCHECKER = True\nTINYMCE_COMPRESSOR = True\n\n# django-paypal settigs\nPAYPAL_TEST = True\nPAYPAL_RECEIVER_EMAIL = \"info@canadaecigs.com\"\n\nfrom canadaecigs.aws.conf import *\n\n# SSL/TLS HTTPS\nCORS_REPLACE_HTTPS_REFERER = True\nHOST_SCHEME = \"https://\"\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\nSECURE_SSL_REDIRECT = True\nSESSION_COOKIE_SECURE = True\nCSRF_COOKIE_SECURE = True\nSECURE_HSTS_INCLUDE_SUBDOMAINS = True\nSECURE_HSTS_SECONDS = 1000000\nSECURE_FRAME_DENY = True\n\n\n\n\n\n\n\n\n","sub_path":"canadaecigs/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":5885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"518204714","text":"class Vector:\n capacity_beginning = 32\n\n def __init__(self):\n self.capacity = Vector.capacity_beginning\n self.container = [None] * self.capacity\n self.size = 0\n\n def double_itself_if_neccessary(self):\n if self.size == self.capacity:\n self.capacity *= 2\n # Double its size\n container_new = [None] * self.size\n # Copy itself\n for i in range(self.size):\n container_new[i] = self.container\n self.container = container_new\n\n def add(self, element):\n self.double_itself_if_neccessary()\n self.size += 1\n self.container[self.size] = element\n\n def insert(self, element, index):\n self.double_itself_if_neccessary()\n container_new = []\n\n for i in range(index):\n container_new[i] = self.container[i]\n\n container_new[index] = element\n\n for i in range(index, self.size):\n container_new[i+1] = self.container[i]\n\n self.container = container_new\n self.size += 1\n\n def get(self, index):\n return self.container[index]\n\n def remove(self, index):\n container_new = []\n\n for i in range(index):\n container_new[i] = self.container[i]\n\n for i in range(index, self.size - 1):\n container_new[i] = self.container[i+1]\n\n self.container = container_new\n self.size -= 1\n\n def get_size(self):\n return self.size\n\n def get_capacity(self):\n self.capacity\n\n def pop(self):\n popped = self.container[self.size - 1]\n self.container[self.size - 1] = None\n return popped\n","sub_path":"week1/1-Vector/Vector.py","file_name":"Vector.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"538558709","text":"import math\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\n# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n out += residual\n out = self.relu(out)\n\n return out\n\nclass Mininet(torch.nn.Module):\n def __init__(self):\n \"\"\"\n \"\"\"\n super(Mininet, self).__init__()\n self.conv1 = nn.Conv2d(1, 64, kernel_size=3, stride=2, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.convDownscale = nn.Conv2d(64, 64, kernel_size=5, stride=2)\n self.bnDownscale = nn.BatchNorm2d(64)\n # self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.block1 = BasicBlock(64, 64)\n self.conv2 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=0)\n self.bn2 = nn.BatchNorm2d(128)\n self.block2 = BasicBlock(128, 128)\n\n self.conv3 = nn.Conv2d(128, 256, kernel_size=3, stride=2)\n self.bn3 = nn.BatchNorm2d(256)\n self.block3 = BasicBlock(256,256)\n self.conv4 = nn.Conv2d(256, 128, kernel_size=3, stride=2)\n self.avgPool = nn.AvgPool2d(6)\n self.linear1 = nn.Linear(128, 64)\n self.linear2 = nn.Linear(64, 20)\n\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x):\n \"\"\"\n \"\"\"\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.convDownscale(out)\n out = self.bnDownscale(out)\n out = self.relu(out)\n # out = self.maxpool(out)\n out = self.block1(out)\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n out = self.block2(out)\n out = self.conv3(out)\n out = self.bn3(out)\n out = self.relu(out)\n out = self.block3(out)\n out = self.conv4(out)\n out = self.avgPool(out)\n out = self.linear1(out.view(-1, 128))\n out = self.relu(out)\n out = self.linear2(out)\n return out","sub_path":"assignment3/cropnet.py","file_name":"cropnet.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"7492761","text":"'''\n@author: ak\n'''\nimport threading\nimport time\nimport random\nfrom blinker import signal\nfrom GM_localViolations.Node import Node\nfrom GM_localViolations import Config\n\nclass Coordinator:\n '''\n class Coordinator\n models the Coordinator at a Geometric Monitoring network\n configuration via Config module\n '''\n\n\n def __init__(self, event, nodeNum):\n '''\n Constructor\n args:\n event: synchronizing event\n nodes: a node object list\n '''\n #thread configuration-synchronization\n self.event=event\n self.lock=threading.Lock()\n \n #coordinator data initialization\n self.nodeNum=nodeNum #network node number\n self.nodes={} #network node dictionary{key is nodeId:value is weight}\n self.thresh=Config.threshold #monitoring threshold\n self.v=0 #global statistics vector\n self.e=0 #estimate vector\n self.balancingSet=set() #balancing set (set of tuples) (nodeId,v_value,u_value})\n self.balancingNodeIdSet=set() #balancing set containing only nodeIds\n self.requestedNode=None #requested node flag\n \n #helper\n self.counter=0\n \n #signal configuration\n signal('init-node').connect(self.init)\n signal('rep').connect(self.nodeRep)\n \n #experimental results\n self.expCounter=0\n \n \n '''\n signal handlers\n '''\n def init(self,nodeId,**kargs):\n '''\n initialising global data\n '''\n self.counter+=1\n #DBG\n print('coord:init signal received by node %s, counter is %d, nodeNum is %d'%(nodeId,self.counter, self.nodeNum))\n \n #populating network dictionary\n self.nodes[nodeId]=kargs['w']\n self.v+=(kargs['w']*kargs['v'])/sum(self.nodes.values())\n self.e=self.v\n #when all data collected, new-est signal\n if self.counter==self.nodeNum:\n #DBG\n print('coord: send new estimate %0.2f'%self.e)\n signal('new-est').send(newE=self.e)\n \n def nodeRep(self, nodeId, **kargs):\n '''\n new local violation occured\n '''\n \n #DBG\n print('coord:node %s before lock'%nodeId)\n #XXX\n gotIt=self.lock.acquire()\n \n if (not len(self.balancingSet)) | bool(self.requestedNode==nodeId):\n \n #DBG\n print('coord:node %s got lock:%r'%(nodeId,gotIt))\n \n #DBG\n print('coord:rep signal received by node %s, u=%0.2f'%(nodeId,kargs['u']))\n \n #pause thread execution\n self.event.clear()\n \n #DBG\n #time.sleep(4)\n \n \n #add node to balancing set\n self.balancingSet.add((nodeId,kargs['v'],kargs['u']))\n self.balancingNodeIdSet.add(nodeId)\n \n #DBG\n print('##############set data##########################')\n print(self.balancingSet)\n print(self.balancingNodeIdSet)\n assert len(self.balancingNodeIdSet)==len(self.balancingSet)\n \n #balancing vector computation\n sw=0\n b=0\n for s in self.balancingSet:\n b+=self.nodes[s[0]]*s[2] #Sum(w_i*u_i)\n sw+=self.nodes[s[0]] #Sum(w_i)\n if sw:\n b=b/sw\n \n \n if b', methods=['GET'])\ndef get_course(course_id):\n course = try_course(course_id)\n return jsonify(generate_response(data=course.to_json()))\n\n\n# CREATE COURSE\n@app.route('/codigo/api/v1.0/courses/', methods=['POST'])\ndef post_course():\n if not request.json:\n abort(400)\n\n title = request.json.get('title', '')\n description = request.json.get('description', '')\n\n course = Course.new(title, description)\n if course is None:\n abort(422)\n\n return jsonify(generate_response(data=course.to_json()))\n\n\n# UPDATE\n@app.route('/codigo/api/v1.0/courses/', methods=['PUT'])\ndef put_course(course_id):\n course = try_course(course_id)\n if not request.json:\n abort(400)\n\n course.title = request.json.get('title', course.title)\n course.description = request.json.get('description', course.description)\n\n # Validate if new title there is not in db\n if course.save():\n return jsonify(generate_response(data=course.to_json()))\n else:\n abort(422)\n\n\n# DELETE\n@app.route('/codigo/api/v1.0/courses/', methods=['DELETE'])\ndef delete_course(course_id):\n course = try_course(course_id)\n if course.delete_instance():\n return jsonify(generate_response(data={}))\n else:\n abort(422)\n\n\ndef try_course(course_id):\n try:\n return Course.get(Course.id == course_id)\n except Course.DoesNotExist:\n abort(404)\n\n\ndef generate_response(status=200, data=None, error=None):\n return {\n 'status': status,\n 'data': data,\n 'error': error\n }\n\n\nif __name__ == '__main__':\n initialize()\n app.run(port=PORT, debug=DEBUG)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"602967209","text":"#!/usr/bin/python\n\n# This file is part of Ansible\n#\n# Ansible 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# Ansible 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 Ansible. If not, see .\n\nANSIBLE_METADATA = {'metadata_version': '1.0',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = '''\n---\n\nmodule: aci_bridge_domain\nshort_description: Direct access to the Cisco ACI APIC API\ndescription:\n - Offers direct access to the Cisco ACI APIC API\nauthor: \n- Swetha Chunduri (@schunduri)\n- Dag Wieers (@dagwieers)\nversion_added: '2.4'\nrequirements:\n - ACI Fabric 1.0(3f)+\nnotes: Tenant should already exist prior to using this module\noptions:\n tenant_name:\n description:\n - Name of the Tenant \n required: yes\n bd_name:\n description:\n - Name of the Bridge Domain\n required: yes\n vrf_name:\n description:\n - VRF name to associate to the Bridge Domain\n required: yes\n arp_flooding:\n description:\n - Enable or Disable ARP_Flooding\n default: yes\n choices: [ yes, no ]\n l2_unkwown_unicast: \n description:\n - \n default: proxy\n choices: [ proxy, flood ]\n l3_unknown_multicast:\n description:\n -\n default: flood\n choices: [ flood, opt-flood ]\n multi_dest:\n description:\n -\n default: bd-flood\n choices: [ bd-flood, drop, encap-flood ]\n gateway_ip:\n description:\n - Gateway IP for subnet\n subnet_mask:\n description:\n - Value of the subnet mask \n scope:\n description:\n - Subent Scope - can be private or public and shared \n default: private\n \n'''\n\nEXAMPLES = '''\n\n- name: Add a new bridge domain\n aci_bridge_domain:\n hostname: apic\n username: admin\n password: SomeSecretPassword\n tenant_name: production\n bd_name: Name of the bridge domain \n vrf_name: Name of the context \n arp_flooding: yes\n l2_unknown_unicast: proxy\n l3_unknown_multicast: flood\n multi_dest: bd-flood\n gateway_ip: 10.10.10.1\n subnet_mask: 24\n scope: 'public,shared'\n state: present\n\n- name: Remove bridge domain\n aci_bridge_domain:\n hostname: apic\n username: admin\n password: SomeSecretPassword\n tenant_name: production\n bd_name: Name of the bridge domain\n vrf_name: Name of the context\n state: absent\n\n- name: Query a bridge domain\n aci_bridge_domain :\n hostname: apic\n username: admin\n password: SomeSecretPassword\n tenant_name: production\n bd_name: Name of the bridge domain\n vrf_name: Name of the context\n state: query\n\n- name: Query all Bridge Domains\n aci_bridge_domain:\n hostname: apic\n username: admin\n password: SomeSecretPassword\n state: query\n\n'''\nRETURN = r'''\nstatus:\n description: The status code of the http request\n returned: upon making a successful GET, POST or DELETE request to the APIC\n type: int\n sample: 200\nresponse:\n description: Response text returned by APIC\n returned: when a HTTP request has been made to APIC\n type: string\n sample: '{\"totalCount\":\"0\",\"imdata\":[]}'\n\n'''\n\nimport json\n\nfrom ansible.module_utils.aci import ACIModule, aci_argument_spec\nfrom ansible.module_utils.basic import AnsibleModule\n\ndef main():\n argument_spec = aci_argument_spec\n argument_spec.update(\n tenant_name=dict(type='str', required=True),\n bd_name=dict(type='str', required=True),\n arp_flooding=dict(choices=['yes','no'], default=\"yes\"),\n l2_unknown_unicast=dict(choices=['proxy','flood'], default='proxy'),\n l3_unknown_multicast=dict(choices=['flood','opt-flood'], default='flood'),\n multi_dest=dict(choices=['bd-flood','drop','encap-flood'], default='bd-flood'),\n vrf_name=dict(type='str'),\n gateway_ip=dict(type='str', default=0, required=False),\n subnet_mask=dict(type='str', default=0, required=False),\n scope=dict(type='str',default='private'),\n host=dict(required=True),\n username=dict(type='str', default='admin'),\n password=dict(type='str'),\n protocol=dict(choices=['http', 'https'], default='http'),\n )\n \n module = AnsibleModule(\n argument_spec=agrument_spec,\n supports_check_mode=True,\n )\n\n tenant_name = module.params['tenant_name']\n bd_name = module.params['bd_name']\n arp_flooding = module.params['arp_flooding']\n l2_unknown_unicast = module.params['l2_unknown_unicast']\n l3_unknown_multicast = module.params['l3_unknown_multicast']\n multi_dest = module.params['multi_dest']\n vrf_name = module.params['vrf_name']\n state = module.params['state']\n\n #subnet\n gateway_ip = module.params['gateway_ip']\n subnet_mask = module.params['subnet_mask']\n if gateway_ip != 0 and subnet_mask != 0:\n ip = gateway_ip + \"/\" + subnet_mask\n else:\n ip = ''\n scope = module.params['scope']\n \n aci = ACIModule(module)\n \n if tenant_name is not None and bd_name is not None and vrf_name is not None:\n # Work with specific bridge domain \n path = 'api/mo/uni/tn-%(tenant_name)s/BD-%(bd_name)s.json' % module.params\n elif state == 'query':\n # query all bridge domains\n path = 'api/node/class/fvBD.json'\n else:\n module.fail_json(\"Parameter 'tenant_name' is required for state 'absent' or 'present'\")\n\n config_data = {\n \"fvBD\": {\n \"attributes\": {\n \"descr\": \"test\",\n \"arpFlood\": arp_flooding,\n \"unkMacUcastAct\":l2_unknown_unicast,\n \"unkMcastAct\": l3_unknown_multicast,\n \"multiDstPktAct\": multi_dest\n },\n \"children\":[{\n \"fvRsCtx\": {\n \"attributes\": {\n \"tnFvCtxName\": vrf_name\n }\n }\n }\n ]\n\n }\n }\n\n subnet_config_data = {\n \"fvSubnet\":{\n \"attributes\":{\n \"ip\": ip,\n \"scope\": scope\n }\n }\n }\n\n\n payload_data = json.dumps(config_data)\n subnet_payload_data = json.dumps(subnet_config_data)\n\n if action == 'post':\n req = requests.post(post_url, cookies=authenticate.cookies,\n data=payload_data, verify=False)\n if gateway_ip != 0:\n get_bd = requests.get(post_url, cookies=authenticate.cookies,\n data=payload_data, verify=False)\n data =json.loads(get_bd.text)\n count = data['totalCount']\n count = int(count)\n bridge_domain_list = []\n if get_bd.status_code == 200:\n for name in range(0,count):\n bd = data['imdata'][name]['fvBD']['attributes']['name']\n bridge_domain_list.append(bd)\n if bd_name in bridge_domain_list:\n subnet_req = requests.post(post_url, cookies=authenticate.cookies,\n data=subnet_payload_data, verify=False)\n else:\n module.fail_json(msg='Subnet creation failed.')\n elif action == 'get':\n req = requests.get(get_url, cookies=authenticate.cookies,\n data=payload_data, verify=False)\n elif action == 'delete':\n req = requests.delete(post_url, cookies=authenticate.cookies, data=payload_data, verify=False)\n\n response = req.text\n status = req.status_code\n \n changed = False\n if req.status_code == 200:\n if action == 'post':\n changed = True\n else:\n changed = False\n else:\n module.fail_json(msg=response,\n response=response, status=status)\n\n results = {}\n results['status'] = status\n results['response'] = response\n results['changed'] = changed\n module.exit_json(**results)\n\nfrom ansible.module_utils.basic import *\nif __name__ == '__main__':\n main()\n","sub_path":"library/aci_bridge_domain.py","file_name":"aci_bridge_domain.py","file_ext":"py","file_size_in_byte":8568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"403034221","text":"from django.shortcuts import *\nfrom django.contrib.auth.models import User\nfrom snsApp.models import *\n\n# Create your views here.\ndef profile(request, username):\n # print(username)\n try:\n profile_user = Profile.objects.get(user = User.objects.get(username = username))\n except User.DoesNotExist:\n return redirect('/')\n # print(profile_user)\n # print(profile_user.picture)\n print(request.user.username)\n data = {'profile_user': profile_user,\n 'username': username, \n # 'picture': profile_user.picture.url,\n 'num_of_playlists': profile_user.get_num_of_playlists(), \n 'num_of_followers': profile_user.get_num_of_follower(), \n 'num_of_following': profile_user.get_num_of_following(), \n 'music': '',\n 'bio': profile_user.bio}\n if profile_user.music:\n data['music'] = f\"{profile_user.music.title} - {profile_user.music.artist} \"\n return render(request, 'profile.html', data)\n\n\ndef myprofile(request):\n if request.user.is_authenticated:\n return redirect('/'+request.user.username)\n else:\n #로그인하지않음\n return redirect('/login')","sub_path":"DjangoProject/snsApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"490329236","text":"total=list()\nfname=input (\"Enter file name:\")\ntry:\n file=open(fname)\n\n\n for line in file:\n line=line.rstrip()\n pieces=line.split()\n for word in pieces:\n if word in total:\n continue\n total.append(word)\n total.sort()\n print (total)\nexcept:\n print (\"This file \"+fname+\" cannot be opened\")\n \n","sub_path":"py4e_assignment_8.4.py","file_name":"py4e_assignment_8.4.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"236040718","text":"import requests\r\nimport re\r\nimport json\r\nimport time\r\n\r\ndef get_one_page(url):\r\n r = requests.get(url)\r\n if r.status_code == 200:\r\n return r.text\r\n return None\r\n\r\ndef parse_one_page(html):\r\n pattern = re.compile(\"
.*?board-index.*?>(\\d+).*?data-src=\\\"(.*?)\\\".*?name\\\">(.*?).*?star\\\">(.*?)

.*?releasetime\\\">(.*?)

\"\r\n + \".*?integer\\\">(.*?).*?fraction\\\">(.*?).*?
\", re.S)\r\n items = re.findall(pattern, html)\r\n for i in items:\r\n yield{\r\n \"index\": i[0],\r\n \"image\": i[1],\r\n \"title\": i[2],\r\n \"actor\": i[3].strip()[3:],\r\n \"time\": i[4][5:],\r\n \"score\": i[5] + i[6]\r\n }\r\n \r\ndef write_to_file(content):\r\n with open(\"rank.txt\", \"a\", encoding=\"utf-8\") as f:\r\n f.write(json.dumps(content, ensure_ascii=False) + \"\\n\")\r\n \r\ndef main(offset):\r\n url = \"https://maoyan.com/board/4?offset=\" + str(offset)\r\n html = get_one_page(url)\r\n for p in parse_one_page(html):\r\n write_to_file(p)\r\n \r\nif __name__ == \"__main__\":\r\n for q in range(10):\r\n main(offset=q*10)\r\n time.sleep(1)","sub_path":"practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"317676603","text":"from django.conf import settings\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ModelViewSet\nfrom tenant_schemas.utils import get_public_schema_name\n\nfrom clients.models import Client\nfrom users.api.serializers import UserSerializer\nfrom users.models import UserProxy as User\n\n\nclass UserViewSet(ModelViewSet):\n permission_classes = (AllowAny,)\n\n def get_queryset(self):\n return User.objects.all()\n\n serializer_class = UserSerializer\n\n @action(methods=['GET'], detail=False, url_path='profile', permission_classes=[IsAuthenticated])\n def profile(self, request, **kwargs):\n user = User.objects.get(pk=request.user.pk)\n return Response(self.serializer_class(user).data, status=200)\n\n @action(methods=['GET'], detail=False, url_path='subdomain-by-host', permission_classes=[AllowAny])\n def subdomain_by_host(self, request, **kwargs):\n \"\"\"Carries URL param 'hostname' for a GET request\"\"\"\n hostname = self.request.query_params.get('hostname', '')\n domain = self.request.query_params.get('domain', '')\n match = hostname.replace(domain, settings.MAIN_DOMAIN_URL)\n subdomain = get_object_or_404(Client, domain_url=match)\n domain_url = subdomain.domain_url\n schema_name = subdomain.schema_name\n if schema_name == get_public_schema_name():\n return Response({'domain_url': domain_url.replace(schema_name + '.', ''),\n 'subdomain': schema_name.replace(schema_name, '')}, status=200)\n return Response({'domain_url': domain_url, 'subdomain': schema_name}, status=200)\n\n @action(methods=['GET'], detail=False, url_path='host-by-subdomain', permission_classes=[AllowAny])\n def host_by_subdomain(self, request, **kwargs):\n \"\"\"Carries URL param 'subdomain'\"\"\"\n subdomain = self.request.query_params.get('subdomain', get_public_schema_name())\n if not subdomain:\n subdomain = get_public_schema_name()\n subdomain = get_object_or_404(Client, schema_name=subdomain)\n domain_url = subdomain.domain_url\n if not settings.IS_GAE and request.META.get('SERVER_PORT') and str(request.META.get('SERVER_PORT')) not in \\\n ['80', '443']:\n domain_url += ':' + request.META.get('SERVER_PORT')\n if request.is_secure and 'localhost' not in request.get_host() and '127.0.0.1' not in request.get_host():\n domain_url = 'https://' + domain_url\n else:\n domain_url = 'http://' + domain_url\n return Response({'domain_url': domain_url})\n","sub_path":"users/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"455821189","text":"def premik(ukaz, x, y, smer):\r\n smeri = \"NESW\"\r\n premiki = [(0, -1), (1, 0), (0, 1), (-1, 0)]\r\n ismer = smeri.index(smer)\r\n if ukaz == \"DESNO\\n\":\r\n smer = smeri[(ismer + 1) % 4]\r\n elif ukaz == \"LEVO\\n\":\r\n smer = smeri[(ismer - 1) % 4]\r\n else:\r\n ukaz = int((ukaz.split(\" \")[1]))\r\n dx, dy = premiki[ismer]\r\n x += dx * ukaz\r\n y += dy * ukaz\r\n return x, y, smer\r\n\r\ndef izvedi(ime_datoteke):\r\n seznam = []\r\n x = 0\r\n y = 0\r\n smer = \"N\"\r\n\r\n seznam.append((x, y, smer))\r\n for vrstica in open(ime_datoteke):\r\n trojka = premik(vrstica, x, y, smer)\r\n x = trojka[0]\r\n y = trojka[1]\r\n smer = trojka[2]\r\n seznam.append((x, y, smer))\r\n return seznam\r\n\r\ndef opisi_stanje(x, y, smer):\r\n\r\n if smer == \"N\":\r\n arrow = \"^\"\r\n if smer == \"E\":\r\n arrow = \">\"\r\n if smer == \"S\":\r\n arrow = \"v\"\r\n if smer == \"W\":\r\n arrow = \"<\"\r\n\r\n s = \"{:>3}:{:<4}{}\"\r\n return s.format(x, y, arrow)\r\n\r\ndef prevedi(ime_vhoda, ime_izhoda):\r\n\r\n seznam = izvedi(ime_vhoda)\r\n izhod = open(ime_izhoda, \"w\")\r\n for x, y, smer in seznam:\r\n s = opisi_stanje(x, y, smer)\r\n izhod.write(\"{}\\n\".format(s))\r\n izhod.close()\r\n\r\ndef opisi_stanje_2(x, y, smer):\r\n\r\n if smer == \"N\":\r\n arrow = \"^\"\r\n if smer == \"E\":\r\n arrow = \">\"\r\n if smer == \"S\":\r\n arrow = \"v\"\r\n if smer == \"W\":\r\n arrow = \"<\"\r\n\r\n koorX = \"({}\".format(x)\r\n koorY = \"{})\".format(y)\r\n\r\n s = \"{}{:>5}:{}\"\r\n return s.format(arrow, koorX, koorY)\r\n\r\n\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN8-M-122.py","file_name":"DN8-M-122.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"169149956","text":"#coding:utf-8\n\nfrom django.urls import path\nfrom desk_center.views import *\n\n\nurlpatterns = [\n path(r'', login_entry ,name = \"login_\"),\n # path(r'/login/', login_entry ,name = \"login_\"),\n # path(r'/', login_entry ,name = \"login_\"),\n path(r'index/', home, name=\"home_in\"),\n path(r'log_out/', log_out, name=\"log_out\"),\n path(r'idc/', inde ,name = \"index_in\"),\n path(r'stagings/', stagings, name=\"stagings\"),\n path(r'task_project/get_project/', get_projectshow, name=\"get_project_show\"),\n path(r'task_project/addGroup_name/', addGroup_project, name=\"addGroup_project\"), #添加项目\n path(r'task_project/addGroup/', addGroup, name=\"addGroup\"), #添加分组名\n path(r'task_project/add_project/', add_project, name=\"add_project\"), #添加项目\n path(r'task_project/add_project/task_project_details/', task_project_details, name=\"task_project_details\"), #项目页面详情\n path(r'task_project/add_project/task_project_get_list/', task_project_get_list, name=\"task_project_get_list\"), #项目页面详情\n path(r'task_project/add_project/task_project_details/add_project_name/', add_project_name, name=\"add_project_name\"), #添加分组模块\n path(r'task_project/add_project/task_project_details/add_project_name/task_name', add_project_task_name, name=\"add_project_task_name\"), #添加项目任务名\n path(r'task_project/add_project/task_project_details/add_project_name/task_name/show_data', show_data, name=\"show_data\"), #添加项目模块\n path(r'task_project/', task_project, name=\"task_project\"),\n path(r'distribute/tack/', dis_tack, name=\"dis_tack\"),\n path(r'stagings/app/runtasks/run_myword/', run_word_my, name=\"run_word_my\"),\n path(r'stagings/app/runtasks/add_run/', runtask_addrun, name=\"runtask_addrun\"),\n path(r'stagings/app/runtasks/show_report/', show_reports, name=\"show_reports\"),\n path(r'stagings/app/runtask/', runtask, name=\"runtask\"),\n path(r'add_interface/', add_interface_http, name = \"add_http_req\"),\n path(r'updates/files/',add_files, name =\"add_files\"),\n\n]","sub_path":"test_project/desk_center/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"104709375","text":"import os,sys\nimport numpy as np\nimport torch\nimport h5py, time, itertools, datetime\nfrom torch_connectomics.utils.net import *\nfrom torch_connectomics.utils.vis import visualize_aff\nfrom tqdm import tqdm\nimport re\n\ndef test(args, test_loader, model, device, model_io_size, volume_shape, pad_size, result_path, result_file_pf, input_file_name, save_output):\n # switch to eval mode\n model.eval()\n ww = blend(model_io_size)\n result_skel = [np.zeros([1] + list(x), dtype=np.float32) for x in volume_shape]\n cropped_result_skel = []\n weight = [np.zeros(x, dtype=np.float32) for x in volume_shape]\n sz = tuple([1] + list(model_io_size))\n\n start = time.time()\n with torch.no_grad():\n for i, (pos, volume) in enumerate(test_loader):\n volume = volume.to(device)\n output = model(volume)\n\n for idx in range(output.size()[0]):\n st = pos[idx]\n result_skel[st[0]][:, st[1]:st[1] + sz[1], st[2]:st[2] + sz[2], st[3]:st[3] + sz[3]] \\\n += output[idx].cpu().detach().numpy().reshape(sz) * np.expand_dims(ww, axis=0)\n\n weight[st[0]][st[1]:st[1] + sz[1], st[2]:st[2] + sz[2], st[3]:st[3] + sz[3]]\\\n += ww\n\n end = time.time()\n print(\"prediction time:\", (end-start))\n\n for vol_id in range(len(result_skel)):\n result_skel[vol_id] = result_skel[vol_id] / (weight[vol_id] + np.finfo(np.float32).eps)\n data_skel = result_skel[vol_id]\n data_skel = data_skel[0,\n pad_size[0]:-pad_size[0],\n pad_size[1]:-pad_size[1],\n pad_size[2]:-pad_size[2]]\n cropped_result_skel.append(data_skel)\n if save_output == True:\n skeleton_path = result_path + 'skeleton_' + input_file_names[vol_id] + '_' + result_file_pf + '.h5'\n with h5py.File(skeleton_path, 'w') as hf:\n hf.create_dataset('main', data=data_skel, compression='gzip')\n print('Skeleton stored at: \\n' + gradient_path)\n return cropped_result_skel\n\ndef _run(args, save_output=True):\n print('0. initial setup')\n model_io_size, device = init(args)\n print('model I/O size:', model_io_size)\n\n print('1. setup data')\n test_loader, volume_shape, pad_size = get_input(args, model_io_size, 'test')\n\n print('2. setup model')\n model = setup_model(args, device, model_io_size=model_io_size, exact=True, non_linearity=(torch.sigmoid,))\n\n result_path = args.output + '/' + args.exp_name + '/'\n result_file_pf = re.split('_|.pth', os.path.basename(args.pre_model))[-2]\n print(result_file_pf)\n if not os.path.isdir(result_path):\n os.makedirs(result_path)\n save_cmd_line(args,\n result_path + 'commandArgs.txt') # Saving the command line args with machine name and time for later reference\n\n input_file_name = [os.path.basename(input_image)[:-3] for input_image in args.img_name.split('@')]\n\n print('3. start testing')\n result = test(args, test_loader, model, device, model_io_size, volume_shape, pad_size, result_path, result_file_pf,\n input_file_name, save_output)\n\n print('4. finish testing')\n return result\n\ndef run(input_args_string, save_output):\n return _run(get_args(mode='test', input_args=input_args_string), save_output)\n\nif __name__ == \"__main__\":\n _run(get_args(mode='test'))","sub_path":"scripts/testSkeleton.py","file_name":"testSkeleton.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"45447334","text":"import numpy as np\nimport copy\n\n\nclass Queen():\n\n def input_board(self, filename):\n \"\"\"\n input: filename\n output: a array like matrix\n ex:\n array([[0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 2.],\n [0., 0., 0., 4., 0.],\n [0., 3., 0., 0., 0.],\n [9., 0., 1., 0., 0.]])\n \"\"\"\n state = np.genfromtxt(filename, delimiter=',')\n state[np.isnan(state)] = 0\n return state\n\n def board_value(self, state):\n board = np.nonzero(state.T)[1]\n value = []\n for i in range(len(board)):\n value.append(state[board[i], i] ** 2)\n return value\n\n def heuristic_1(self, state):\n \"\"\"\n H1: The lightest Queen across all pairs of Queens attacking each other.\n ex: min(3,9, 9,1, 3,1, 4,2) = 1**1\n input: state\n ex:\n array([[0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 2.],\n [0., 0., 0., 4., 0.],\n [0., 3., 0., 0., 0.],\n [9., 0., 1., 0., 0.]])\n output: H1 score\n \"\"\"\n board = np.nonzero(state.T)[1]\n min_attact = []\n for i in range(len(board)):\n for j in range(i + 1, len(board)):\n # check same rows attack\n if board[i] == board[j]:\n min_attact.append(min(state[board[i], i], state[board[j], j]))\n # check diagonally attack\n offset = j - i\n if board[i] == board[j] - offset or board[i] == board[j] + offset:\n min_attact.append(min(state[board[i], i], state[board[j], j]))\n if min_attact == []:\n return 0\n else:\n h1 = min(min_attact) ** 2\n return h1\n\n def heuristic_2(self, state):\n \"\"\"\n H2: Sum across every pair of attacking Queens the weight of the lightest Queen.\n ex: min(3,9)**2 + min(9,1)**2 + min(3,1)**2 + min(4,2)**2 = 3**2 +1**2 +1**2 +2**2 = 15\n input: state\n output: H2 score\n \"\"\"\n board = np.nonzero(state.T)[1]\n min_attact = []\n for i in range(len(board)):\n for j in range(i + 1, len(board)):\n # check same rows attack\n if board[i] == board[j]:\n min_attact.append(min(state[board[i], i], state[board[j], j]))\n # check diagonally attack\n offset = j - i\n if board[i] == board[j] - offset or board[i] == board[j] + offset:\n min_attact.append(min(state[board[i], i], state[board[j], j]))\n\n if min_attact == []:\n return 0\n else:\n h2 = sum([i ** 2 for i in min_attact])\n return h2\n\n def near_state(self, state):\n \"\"\"\n input: state\n output: a list of all possible neighbours\n \"\"\"\n board = np.nonzero(state.T)[1]\n near_states = []\n\n for col in range(len(board)):\n for row in range(len(board)):\n if row != board[col]:\n neighbour = copy.deepcopy(state)\n neighbour[row, col] = state[board[col], col]\n neighbour[board[col], col] = 0\n\n near_states.append(neighbour)\n\n return near_states\n\n def near_state_position(self, state):\n \"\"\"\n input: state\n output: a list of all possible neighbours’ position\n \"\"\"\n board = np.nonzero(state.T)[1]\n near_states_positions = []\n\n for col in range(len(board)):\n for row in range(len(board)):\n if row != board[col]:\n neighbour_position = list(board)\n neighbour_position[col] = row # Switch column to empty\n near_states_positions.append(list(neighbour_position))\n\n return near_states_positions\n\n def cost(self, state1, state2):\n \"\"\"\n input: two states\n output: cost of take this step\n \"\"\"\n board1 = np.nonzero(state1.T)[1]\n board2 = np.nonzero(state2.T)[1]\n return np.dot(abs(board1 - board2), self.board_value(state1))\n\n\nif __name__ == \"__main__\":\n q = Queen()\n state = q.input_board('heavy queens board.csv')\n h1 = q.heuristic_1(state)\n h2 = q.heuristic_2(state)\n value = q.board_value(state)\n near_states = q.near_state(state)\n near_states_positions = q.near_state_position(state)\n print(state)\n print(h1)\n print(h2)\n print(value)\n print(near_states[0])\n print(near_states_positions[0])\n print(q.cost(state,near_states[0]))\n","sub_path":"part1 old/NQueens.py","file_name":"NQueens.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"637840380","text":"#!/bin/python\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the countingValleys function below.\r\ndef countingValleys(n, s):\r\n sea_level = 0; valleys = 0; mountains = 0\r\n for character in s:\r\n if sea_level == -1 and character == 'U':\r\n valleys += 1\r\n elif sea_level == 1 and character == 'D':\r\n mountains += 1\r\n \r\n if character == 'U':\r\n sea_level += 1\r\n elif character == 'D':\r\n sea_level -= 1\r\n return valleys\r\n\r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n n = int(raw_input())\r\n\r\n s = raw_input()\r\n\r\n result = countingValleys(n, s)\r\n\r\n fptr.write(str(result) + '\\n')\r\n\r\n fptr.close()\r\n","sub_path":"Easy - Counting Valleys.py","file_name":"Easy - Counting Valleys.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"389837712","text":"# Copyright 2020 G-Research\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\n\nlogger = logging.getLogger()\nlogger.level = logging.INFO\n\nimport unittest\nimport re\n\nfrom pyspark.sql import Row\nfrom py4j.java_gateway import JavaObject\n\nfrom spark_common import SparkTest\nfrom gresearch.spark.diff import Diff, DiffOptions, DiffMode\n\n\nclass DiffTest(SparkTest):\n\n @classmethod\n def setUpClass(cls):\n super(DiffTest, cls).setUpClass()\n\n cls.left_df = cls.spark.createDataFrame([\n (1, 1.0, 'one'),\n (2, 2.0, 'two'),\n (3, 3.0, 'three'),\n (4, None, None),\n (5, 5.0, 'five'),\n (7, 7.0, 'seven'),\n ], ['id', 'val', 'label'])\n\n cls.right_df = cls.spark.createDataFrame([\n (1, 1.1, 'one'),\n (2, 2.0, 'Two'),\n (3, 3.0, 'three'),\n (4, 4.0, 'four'),\n (5, None, None),\n (6, 6.0, 'six'),\n ], ['id', 'val', 'label'])\n\n diff_row = Row('diff', 'id', 'left_val', 'right_val', 'left_label', 'right_label')\n cls.expected_diff = [\n diff_row('C', 1, 1.0, 1.1, 'one', 'one'),\n diff_row('C', 2, 2.0, 2.0, 'two', 'Two'),\n diff_row('N', 3, 3.0, 3.0, 'three', 'three'),\n diff_row('C', 4, None, 4.0, None, 'four'),\n diff_row('C', 5, 5.0, None, 'five', None),\n diff_row('I', 6, None, 6.0, None, 'six'),\n diff_row('D', 7, 7.0, None, 'seven', None),\n ]\n\n diff_with_options_row = Row('d', 'id', 'l_val', 'r_val', 'l_label', 'r_label')\n cls.expected_diff_with_options = [\n diff_with_options_row('c', 1, 1.0, 1.1, 'one', 'one'),\n diff_with_options_row('c', 2, 2.0, 2.0, 'two', 'Two'),\n diff_with_options_row('n', 3, 3.0, 3.0, 'three', 'three'),\n diff_with_options_row('c', 4, None, 4.0, None, 'four'),\n diff_with_options_row('c', 5, 5.0, None, 'five', None),\n diff_with_options_row('i', 6, None, 6.0, None, 'six'),\n diff_with_options_row('r', 7, 7.0, None, 'seven', None),\n ]\n\n diff_with_changes_row = Row('diff', 'changes', 'id', 'left_val', 'right_val', 'left_label', 'right_label')\n cls.expected_diff_with_changes = [\n diff_with_changes_row('C', ['val'], 1, 1.0, 1.1, 'one', 'one'),\n diff_with_changes_row('C', ['label'], 2, 2.0, 2.0, 'two', 'Two'),\n diff_with_changes_row('N', [], 3, 3.0, 3.0, 'three', 'three'),\n diff_with_changes_row('C', ['val', 'label'], 4, None, 4.0, None, 'four'),\n diff_with_changes_row('C', ['val', 'label'], 5, 5.0, None, 'five', None),\n diff_with_changes_row('I', None, 6, None, 6.0, None, 'six'),\n diff_with_changes_row('D', None, 7, 7.0, None, 'seven', None),\n ]\n\n cls.expected_diff_in_column_by_column_mode = cls.expected_diff\n\n diff_in_side_by_side_mode_row = Row('diff', 'id', 'left_val', 'left_label', 'right_val', 'right_label')\n cls.expected_diff_in_side_by_side_mode = [\n diff_in_side_by_side_mode_row('C', 1, 1.0, 'one', 1.1, 'one'),\n diff_in_side_by_side_mode_row('C', 2, 2.0, 'two', 2.0, 'Two'),\n diff_in_side_by_side_mode_row('N', 3, 3.0, 'three', 3.0, 'three'),\n diff_in_side_by_side_mode_row('C', 4, None, None, 4.0, 'four'),\n diff_in_side_by_side_mode_row('C', 5, 5.0, 'five', None, None),\n diff_in_side_by_side_mode_row('I', 6, None, None, 6.0, 'six'),\n diff_in_side_by_side_mode_row('D', 7, 7.0, 'seven', None, None),\n ]\n\n diff_in_left_side_mode_row = Row('diff', 'id', 'left_val', 'left_label')\n cls.expected_diff_in_left_side_mode = [\n diff_in_left_side_mode_row('C', 1, 1.0, 'one'),\n diff_in_left_side_mode_row('C', 2, 2.0, 'two'),\n diff_in_left_side_mode_row('N', 3, 3.0, 'three'),\n diff_in_left_side_mode_row('C', 4, None, None),\n diff_in_left_side_mode_row('C', 5, 5.0, 'five'),\n diff_in_left_side_mode_row('I', 6, None, None),\n diff_in_left_side_mode_row('D', 7, 7.0, 'seven'),\n ]\n\n diff_in_right_side_mode_row = Row('diff', 'id', 'right_val', 'right_label')\n cls.expected_diff_in_right_side_mode = [\n diff_in_right_side_mode_row('C', 1, 1.1, 'one'),\n diff_in_right_side_mode_row('C', 2, 2.0, 'Two'),\n diff_in_right_side_mode_row('N', 3, 3.0, 'three'),\n diff_in_right_side_mode_row('C', 4, 4.0, 'four'),\n diff_in_right_side_mode_row('C', 5, None, None),\n diff_in_right_side_mode_row('I', 6, 6.0, 'six'),\n diff_in_right_side_mode_row('D', 7, None, None),\n ]\n\n diff_in_sparse_mode_row = Row('diff', 'id', 'left_val', 'right_val', 'left_label', 'right_label')\n cls.expected_diff_in_sparse_mode = [\n diff_in_sparse_mode_row('C', 1, 1.0, 1.1, None, None),\n diff_in_sparse_mode_row('C', 2, None, None, 'two', 'Two'),\n diff_in_sparse_mode_row('N', 3, None, None, None, None),\n diff_in_sparse_mode_row('C', 4, None, 4.0, None, 'four'),\n diff_in_sparse_mode_row('C', 5, 5.0, None, 'five', None),\n diff_in_sparse_mode_row('I', 6, None, 6.0, None, 'six'),\n diff_in_sparse_mode_row('D', 7, 7.0, None, 'seven', None),\n ]\n\n def test_dataframe_diff(self):\n diff = self.left_df.diff(self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff, diff)\n\n def test_dataframe_diff_with_default_options(self):\n diff = self.left_df.diff_with_options(self.right_df, DiffOptions(), 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff, diff)\n\n def test_dataframe_diff_with_options(self):\n options = DiffOptions('d', 'l', 'r', 'i', 'c', 'r', 'n', None)\n diff = self.left_df.diff_with_options(self.right_df, options, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_with_options, diff)\n\n def test_dataframe_diff_with_changes(self):\n options = DiffOptions().with_change_column('changes')\n diff = self.left_df.diff_with_options(self.right_df, options, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_with_changes, diff)\n\n def test_dataframe_diff_with_diff_mode_column_by_column(self):\n options = DiffOptions().with_diff_mode(DiffMode.ColumnByColumn)\n diff = self.left_df.diff_with_options(self.right_df, options, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_column_by_column_mode, diff)\n\n def test_dataframe_diff_with_diff_mode_side_by_side(self):\n options = DiffOptions().with_diff_mode(DiffMode.SideBySide)\n diff = self.left_df.diff_with_options(self.right_df, options, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_side_by_side_mode, diff)\n\n def test_dataframe_diff_with_diff_mode_left_side(self):\n options = DiffOptions().with_diff_mode(DiffMode.LeftSide)\n diff = self.left_df.diff_with_options(self.right_df, options, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_left_side_mode, diff)\n\n def test_dataframe_diff_with_diff_mode_right_side(self):\n options = DiffOptions().with_diff_mode(DiffMode.RightSide)\n diff = self.left_df.diff_with_options(self.right_df, options, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_right_side_mode, diff)\n\n def test_dataframe_diff_with_sparse_mode(self):\n options = DiffOptions().with_sparse_mode(True)\n diff = self.left_df.diff_with_options(self.right_df, options, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_sparse_mode, diff)\n\n def test_diff_of(self):\n diff = Diff().of(self.left_df, self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff, diff)\n\n def test_diff_of_with_default_options(self):\n options = DiffOptions()\n diff = Diff(options).of(self.left_df, self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff, diff)\n\n def test_diff_of_with_options(self):\n options = DiffOptions('d', 'l', 'r', 'i', 'c', 'r', 'n', None)\n diff = Diff(options).of(self.left_df, self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_with_options, diff)\n\n def test_diff_of_with_changes(self):\n options = DiffOptions().with_change_column('changes')\n diff = Diff(options).of(self.left_df, self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_with_changes, diff)\n\n def test_dataframe_diff_of_in_diff_mode_column_by_column(self):\n options = DiffOptions().with_diff_mode(DiffMode.ColumnByColumn)\n diff = Diff(options).of(self.left_df, self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_column_by_column_mode, diff)\n\n def test_dataframe_diff_of_in_diff_mode_side_by_side(self):\n options = DiffOptions().with_diff_mode(DiffMode.SideBySide)\n diff = Diff(options).of(self.left_df, self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_side_by_side_mode, diff)\n\n def test_dataframe_diff_of_in_diff_mode_left_side(self):\n options = DiffOptions().with_diff_mode(DiffMode.LeftSide)\n diff = Diff(options).of(self.left_df, self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_left_side_mode, diff)\n\n def test_dataframe_diff_of_in_diff_mode_right_side(self):\n options = DiffOptions().with_diff_mode(DiffMode.RightSide)\n diff = Diff(options).of(self.left_df, self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_right_side_mode, diff)\n\n def test_dataframe_diff_with_sparse_mode(self):\n options = DiffOptions().with_sparse_mode(True)\n diff = Diff(options).of(self.left_df, self.right_df, 'id').orderBy('id').collect()\n self.assertEqual(self.expected_diff_in_sparse_mode, diff)\n\n def test_diff_options_default(self):\n jvm = self.spark._jvm\n joptions = jvm.uk.co.gresearch.spark.diff.DiffOptions.default()\n options = DiffOptions()\n for attr in options.__dict__.keys():\n const = re.sub(r'_(.)', lambda match: match.group(1).upper(), attr)\n expected = getattr(joptions, const)()\n actual = getattr(options, attr)\n\n if type(expected) == JavaObject:\n class_name = re.sub(r'\\$.*$', '', expected.getClass().getName())\n if class_name in ['scala.None']: # how does the Some(?) look like?\n actual = 'Some({})'.format(actual) if actual is not None else 'None'\n expected = expected.toString()\n\n if attr == 'diff_mode':\n # does the Python default diff mode resolve to the same Java diff mode enum value?\n self.assertEqual(expected, actual._to_java(jvm).toString(), '{} == {} ?'.format(attr, const))\n else:\n self.assertEqual(expected, actual, '{} == {} ?'.format(attr, const))\n\n def test_diff_mode_consts(self):\n jvm = self.spark._jvm\n jmodes = jvm.uk.co.gresearch.spark.diff.DiffMode\n modes = DiffMode\n for attr in modes.__dict__.keys():\n if attr[0] != '_':\n actual = getattr(modes, attr)\n if isinstance(actual, DiffMode) and actual != DiffMode.Default:\n expected = getattr(jmodes, attr)()\n self.assertEqual(expected.toString(), actual.name, actual.name)\n self.assertIsNotNone(DiffMode.Default.name, jmodes.Default().toString())\n\n def test_diff_fluent_setters(self):\n default = DiffOptions()\n options = default \\\n .with_diff_column('d') \\\n .with_left_column_prefix('l') \\\n .with_right_column_prefix('r') \\\n .with_insert_diff_value('i') \\\n .with_change_diff_value('c') \\\n .with_delete_diff_value('r') \\\n .with_nochange_diff_value('n') \\\n .with_change_column('c') \\\n .with_diff_mode(DiffMode.SideBySide) \\\n .with_sparse_mode(True)\n\n self.assertEqual(options.diff_column, 'd')\n self.assertEqual(options.left_column_prefix, 'l')\n self.assertEqual(options.right_column_prefix, 'r')\n self.assertEqual(options.insert_diff_value, 'i')\n self.assertEqual(options.change_diff_value, 'c')\n self.assertEqual(options.delete_diff_value, 'r')\n self.assertEqual(options.nochange_diff_value, 'n')\n self.assertEqual(options.change_column, 'c')\n self.assertEqual(options.diff_mode, DiffMode.SideBySide)\n self.assertEqual(options.sparse_mode, True)\n\n self.assertNotEqual(options.diff_column, default.diff_column)\n self.assertNotEqual(options.left_column_prefix, default.left_column_prefix)\n self.assertNotEqual(options.right_column_prefix, default.right_column_prefix)\n self.assertNotEqual(options.insert_diff_value, default.insert_diff_value)\n self.assertNotEqual(options.change_diff_value, default.change_diff_value)\n self.assertNotEqual(options.delete_diff_value, default.delete_diff_value)\n self.assertNotEqual(options.nochange_diff_value, default.nochange_diff_value)\n self.assertNotEqual(options.change_column, default.change_column)\n self.assertNotEqual(options.diff_mode, default.diff_mode)\n self.assertNotEqual(options.sparse_mode, default.sparse_mode)\n\n without_change = options.without_change_column()\n self.assertEqual(without_change.diff_column, 'd')\n self.assertEqual(without_change.left_column_prefix, 'l')\n self.assertEqual(without_change.right_column_prefix, 'r')\n self.assertEqual(without_change.insert_diff_value, 'i')\n self.assertEqual(without_change.change_diff_value, 'c')\n self.assertEqual(without_change.delete_diff_value, 'r')\n self.assertEqual(without_change.nochange_diff_value, 'n')\n self.assertIsNone(without_change.change_column)\n self.assertEqual(without_change.diff_mode, DiffMode.SideBySide)\n self.assertEqual(without_change.sparse_mode, True)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"python/test/test_diff.py","file_name":"test_diff.py","file_ext":"py","file_size_in_byte":14988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"201151514","text":"#!/usr/bin/env python3\n# Copyright (c) 2016 janmagrot@gmail.com\n\nimport json\nimport time\n\nimport Application.Phase1.Api as Api\nimport Application.Phase1.DatabasesFeeder as Df\nimport Application.Phase1.DatabasesReader as Dr\nimport Application.Universal.InnerComunication as InCo\nimport Application.Universal.Logger as Lg\nimport Application.Universal.NetConsistence as Nc\nimport Application.Universal.Settings_Reader as Sr\nimport numpy as np\nimport copy\n\n\nclass DataConsistenceError(Exception):\n pass\n\n\nclass FetchFormatSaveData:\n \"\"\"\n Tato třída má na starost stahování obchodů. Jejich třídění\n a doplnění caches.\n \"\"\"\n\n def __init__(self, tempdir):\n self._log = Lg.Logging(tempdir)\n self._conf = Sr.Config()\n self._api = Api.PublicApi(tempdir)\n self._ct = Df.CreateTables(tempdir)\n self._ft = Df.FeedTables(tempdir)\n self._rt = Dr.ReadTables(tempdir)\n self._pairs = None\n self._candlesticksdict = None\n self._candlescounter = 0\n self._bigcachedict = None\n self._startcollectingtime = None\n self._stopcollectingtime = None\n self._equalizecache = None\n self._testcounter = 0\n\n def prepareClass(self):\n self._pairs = set(self._rt.pairsFromDatabase())\n return True\n\n def buildCaches(self):\n \"\"\"\n Deklarace proměnných a příprava třídy.\n :return:\n \"\"\"\n self._equalizecache = int((self._conf.candlestickLenght / self._conf.bigtickerfreq) / 5)\n self._equalizecache = self._equalizecache if self._equalizecache >= 5 else 5\n # Velký slovník:\n self._candlesticksdict = {\n p: {\n \"open\": None,\n \"close\": None,\n \"min\": None,\n \"max\": None,\n \"avg_buy\": None,\n \"avg_sell\": None,\n \"avg\": None,\n \"vol_whole_market\": None,\n \"vol_whole_base\": None\n } for p in self._pairs}\n\n self._bigcachedict = {\n p: {\n \"asks\": [],\n \"bids\": [],\n \"vol_whole_market\": [],\n \"vol_whole_base\": []\n } for p in self._pairs}\n return True\n\n def testingTicker(self):\n \"\"\"\n {\"MarketName\":\"BTC-2GIVE\",\"High\":0.00000110,\"Low\":0.00000096,\"Volume\":2127808.73470583,\"Last\":0.00000097,\n \"BaseVolume\":2.15711216,\"TimeStamp\":\"2018-03-11T00:57:05.82\",\"Bid\":0.00000096,\"Ask\":0.00000099,\n \"OpenBuyOrders\":137,\"OpenSellOrders\":1094,\"PrevDay\":0.00000098,\"Created\":\"2016-05-16T06:44:15.287\"}\n :return:\n \"\"\"\n toreturn = []\n if self._testcounter < 35:\n tofill = {\n \"MarketName\": None, \"High\": None, \"Low\": None, \"Volume\": None, \"Last\": None, \"BaseVolume\": None,\n \"Bid\": None, \"Ask\": None\n }\n for i in self._pairs:\n pdict = copy.deepcopy(tofill)\n pdict[\"MarketName\"] = str(i)\n pdict[\"High\"] = np.random.random(1)[0]\n pdict[\"Low\"] = np.random.random(1)[0]\n pdict[\"Volume\"] = np.random.random(1)[0]\n pdict[\"Last\"] = np.random.random(1)[0]\n pdict[\"BaseVolume\"] = np.random.random(1)[0]\n pdict[\"Bid\"] = np.random.random(1)[0]\n pdict[\"Ask\"] = np.random.random(1)[0]\n toreturn.append(pdict)\n else:\n toreturn = self._api.getMarketSummaries()\n return toreturn\n\n def retrieveAndSaveTicker(self):\n \"\"\"\n Obdrží data tickeru a propočítá průměry\n volumů.\n :return:\n \"\"\"\n\n def countVolumesAverage(dayvolume):\n dayinseconds = float(24 * 60 * 60)\n delitel = float(dayinseconds / self._conf.candlestickLenght)\n res = dayvolume / delitel\n return res\n\n ticker = self._api.getMarketSummaries()\n # ticker = self.testingTicker()\n if ticker:\n assert isinstance(ticker, list)\n assert len(ticker) > 0\n updateset = set()\n dbdict = {}\n for i in ticker:\n updateset.add(i[\"MarketName\"])\n if i[\"MarketName\"] in self._pairs:\n # přeřazení do cache:\n if i[\"MarketName\"] in self._bigcachedict.keys():\n pairdict = self._bigcachedict[i[\"MarketName\"]]\n pairdict[\"asks\"].append(i[\"Ask\"])\n pairdict[\"bids\"].append(i[\"Bid\"])\n pairdict[\"vol_whole_market\"].append(countVolumesAverage(i[\"Volume\"]))\n pairdict[\"vol_whole_base\"].append(countVolumesAverage(i[\"BaseVolume\"]))\n # přeřazení pro databázi:\n pair = str(i[\"MarketName\"])\n ask = float(i[\"Ask\"])\n bid = float(i[\"Bid\"])\n avg = float(ask + bid) / 2\n dbvalue = {\"bid\": bid, \"ask\": ask, \"avg\": avg}\n dbdict[pair] = dbvalue\n else:\n self._log.stage1logging(\"CRITICAL\",\n \"Cache candlesticků neobsahuje pár: \" + str(i[\"MarketName\"]))\n uptodate = True\n for i in self._pairs:\n if i not in updateset:\n uptodate = False\n if not uptodate:\n topop = set()\n self._ct.updateAll()\n self._pairs = set(self._rt.pairsFromDatabase())\n for q in self._bigcachedict.keys():\n if q not in self._pairs:\n topop.add(q)\n for i in topop:\n self._bigcachedict.pop(i)\n self._ft.saveticker(dbdict)\n else:\n self._equalizecache -= 1\n return True\n\n def countCandles(self):\n \"\"\"\n Propočítává candlesticky.\n :return:\n \"\"\"\n self._testcounter += 1\n dayinseconds = float(24 * 60 * 60)\n cndlsinday = float(dayinseconds / self._conf.candlestickLenght)\n\n def countopenorclose(pozition, askslist, bidslist):\n \"\"\"\n Spočítá open a close na základě zprůměrování\n jejich konců.\n :param pozition:\n :param askslist:\n :param bidslist:\n :return:\n \"\"\"\n # verifikace délky:\n if len(askslist) < 10:\n return 0\n if len(bidslist) < 10:\n return 0\n # Zprůměrování konců candlesticků, abychom se zbavili šumu.\n # délka průměru\n offcut = int(len(askslist)) / int(self._conf.candlestickLenght / 60)\n offcut = offcut if offcut >= 2 else 2\n offcut = int(offcut)\n\n if pozition == \"open\":\n a = askslist[:offcut]\n b = bidslist[:offcut]\n r = a + b\n return float(sum(r) / len(r))\n else:\n a = askslist[-offcut:]\n b = bidslist[-offcut:]\n r = a + b\n return float(sum(r) / len(r))\n\n def countCandlesticksVolumes():\n \"\"\"\n Type může být base nebo currency\n :param :\n :return:\n \"\"\"\n voldict = {o: {} for o in self._pairs}\n for k, v in self._bigcachedict.items():\n if len(v[\"vol_whole_market\"]) > 0:\n newdict = {k: {\"vol_whole_market\": None, \"vol_whole_base\": None}}\n marketvol = float(sum(v[\"vol_whole_market\"]) / len(v[\"vol_whole_market\"])) / cndlsinday\n newdict[k][\"vol_whole_market\"] = marketvol\n basevol = float(sum(v[\"vol_whole_base\"]) / len(v[\"vol_whole_base\"])) / cndlsinday\n newdict[k][\"vol_whole_base\"] = basevol\n voldict.update(newdict)\n else:\n voldict = False\n return voldict\n\n voldict = countCandlesticksVolumes()\n if voldict:\n for k, v in self._bigcachedict.items():\n # Kontola zda došlo k aktualizaci párů serverem.\n asks = v[\"asks\"]\n bids = v[\"bids\"]\n whole = asks + bids\n # Výpočet volumů pro candlestick\n volume = voldict[k][\"vol_whole_market\"]\n basevolume = voldict[k][\"vol_whole_base\"]\n\n op = countopenorclose(\"open\", asks, bids)\n clo = countopenorclose(\"close\", asks, bids)\n minimum = min(whole)\n maximum = max(whole)\n avg_buy = float(sum(asks) / len(asks))\n avg_sell = float(sum(bids) / len(bids))\n avg = float(sum(whole) / len(whole))\n\n self._candlesticksdict[k][\"open\"] = op\n self._candlesticksdict[k][\"close\"] = clo\n self._candlesticksdict[k][\"min\"] = minimum\n self._candlesticksdict[k][\"max\"] = maximum\n self._candlesticksdict[k][\"avg_buy\"] = avg_buy\n self._candlesticksdict[k][\"avg_sell\"] = avg_sell\n self._candlesticksdict[k][\"avg\"] = avg\n self._candlesticksdict[k][\"vol_whole_market\"] = volume\n self._candlesticksdict[k][\"vol_whole_base\"] = basevolume\n\n return self._candlesticksdict\n\n @property\n def equalizecache(self):\n ec = self._equalizecache\n self._equalizecache = int((self._conf.candlestickLenght / self._conf.bigtickerfreq) / 5)\n self._equalizecache = self._equalizecache if self._equalizecache >= 5 else 5\n return ec\n\n\nclass RunStage1:\n \"\"\"\n Tato třída má na starost kompletní běh cyklu na\n sběr dat.\n \"\"\"\n\n def __init__(self, tmpdir):\n self._conf = Sr.Config()\n self._log = Lg.Logging(tmpdir)\n self._fetch = FetchFormatSaveData(tmpdir)\n self._df = Df.FeedTables(tmpdir)\n self._tmpdir = tmpdir\n self._consist = None\n self._candlcounter = 0\n self._lastcndltime = None\n\n def runStage1(self):\n self._fetch.prepareClass()\n self._fetch.buildCaches()\n self._consist = Nc.WatchCandles(self._tmpdir)\n # Nastavení časů cyklů.\n start = int(time.time())\n end = int(start + self._conf.candlestickLenght)\n smallcyklusstart = start\n smallcyklusend = int(smallcyklusstart + self._conf.bigtickerfreq)\n self._log.stage2logging(\"INFO\", \"Začíná cyklus 1.fáze.\")\n # Loop:\n while True:\n # Cyklus candlesticku.\n if int(time.time()) < end:\n if int(time.time()) >= smallcyklusend:\n self._fetch.retrieveAndSaveTicker()\n # Kontrola zda nedošlo k příliš dlouhému zdržení:\n if int(time.time()) < int(smallcyklusend + self._conf.bigtickerfreq):\n smallcyklusstart = smallcyklusend\n smallcyklusend = int(smallcyklusstart + self._conf.bigtickerfreq)\n else:\n smallcyklusstart = int(time.time())\n smallcyklusend = int(smallcyklusstart + self._conf.bigtickerfreq)\n else:\n time.sleep(0.5)\n continue\n else:\n ecache = self._fetch.equalizecache\n if ecache <= 0:\n self._consist.missingcandlescounter = -1\n if int(time.time()) < int(end + self._conf.candlestickLenght):\n start = end\n end = start + int(self._conf.candlestickLenght)\n else:\n start = int(time.time())\n end = start + int(self._conf.candlestickLenght)\n continue\n else:\n candles = self._fetch.countCandles()\n self._consist.missingcandlescounter = 1\n if int(time.time()) < int(end + self._conf.candlestickLenght):\n start = end\n end = start + int(self._conf.candlestickLenght)\n else:\n start = int(time.time())\n end = start + int(self._conf.candlestickLenght)\n self._fetch.buildCaches()\n self._df.savecandles(candles)\n self._lastcndltime = int(time.time())\n self._candlcounter += 1\n # zápis\n path = str(self._tmpdir + \"/\" + InCo.APPSTATEFILE)\n jsonload = False\n while not jsonload:\n try:\n with open(path, \"r\") as jsondata:\n jsonload = json.load(jsondata)\n except json.JSONDecodeError:\n self._log.runtimeInfoLogging(\"Poškozená struktura JSON souboru, při čtení.\")\n continue\n json_data = dict(jsonload)\n json_data[\"phase1state\"][\"candlesticks_count\"] = self._candlcounter\n json_data[\"phase1state\"][\"last_candle_time\"] = int(time.time())\n with open(path, \"w\") as j:\n json.dump(json_data, j)\n continue\n","sub_path":"Application/APL_Stage1.py","file_name":"APL_Stage1.py","file_ext":"py","file_size_in_byte":13602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"144422340","text":"import binascii\nimport json\nimport os\nimport requests\nfrom requests_toolbelt.multipart import encoder, decoder\nimport sys\n\nimport torch as th\nimport syft as sy\nfrom syft.workers.base import BaseWorker\n\nfrom grid import utils as gr_utils\n\nMODEL_LIMIT_SIZE = (1024 ** 2) * 100 # 100MB\n\n\nclass GridClient(BaseWorker):\n \"\"\"GridClient.\"\"\"\n\n def __init__(self, addr: str, verbose: bool = True, hook=None, id=\"grid\", **kwargs):\n hook = sy.hook if hook is None else hook\n super().__init__(hook=hook, id=id, verbose=verbose, **kwargs)\n print(\n \"WARNING: Grid nodes publish datasets online and are for EXPERIMENTAL use only.\"\n \"Deploy nodes at your own risk. Do not use OpenGrid with any data/models you wish to \"\n \"keep private.\\n\"\n )\n self.addr = addr\n self._verify_identity()\n # We use ISO encoding for some serialization/deserializations\n # due to non-ascii characters.\n self._encoding = \"ISO-8859-1\"\n\n def _verify_identity(self):\n r = requests.get(self.addr + \"/identity/\")\n if r.text != \"OpenGrid\":\n raise PermissionError(\"App is not an OpenGrid app.\")\n\n def _send_msg(self, message: bin, location: BaseWorker) -> bin:\n raise NotImplementedError\n\n def _return_bool_result(self, result, return_key=None):\n if result[\"success\"]:\n return result[return_key] if return_key is not None else True\n elif result[\"error\"]:\n raise RuntimeError(result[\"error\"])\n else:\n raise RuntimeError(\n \"Something went wrong, check the server logs for more information.\"\n )\n\n def _send_http_request(\n self,\n route,\n data,\n request,\n N: int = 10,\n unhexlify: bool = True,\n return_response_text: bool = True,\n ):\n \"\"\"Helper function for sending http request to talk to app.\n\n Args:\n route: App route.\n data: Data to be sent in the request.\n request: Request type (GET, POST, PUT, ...).\n N: Number of tries in case of fail. Default is 10.\n unhexlify: A boolean indicating if we should try to run unhexlify on the response or not.\n return_response_text: If True return response.text, return raw response otherwise.\n Returns:\n If return_response_text is True return response.text, return raw response otherwise.\n \"\"\"\n url = os.path.join(self.addr, \"{}\".format(route))\n r = request(url, data=data) if data else request(url)\n r.encoding = self._encoding\n response = r.text if return_response_text else r\n\n # Try to request the message `N` times.\n for _ in range(N):\n try:\n if unhexlify:\n response = binascii.unhexlify(response[2:-1])\n return response\n except:\n if self.verbose:\n print(response)\n response = None\n r = request(url, data=data) if data else request(url)\n response = r.text\n\n return response\n\n def _send_streaming_post(self, route, data=None):\n \"\"\" Used to send large models / datasets using stream channel.\n\n Args:\n route : Service endpoint\n data : tensors / models to be uploaded.\n Return:\n response : response from server\n \"\"\"\n # Build URL path\n url = os.path.join(self.addr, \"{}\".format(route))\n\n # Send data\n session = requests.Session()\n form = encoder.MultipartEncoder(data)\n headers = {\"Prefer\": \"respond-async\", \"Content-Type\": form.content_type}\n resp = session.post(url, headers=headers, data=form)\n session.close()\n return resp.content\n\n def _send_post(self, route, data=None, **kwargs):\n return self._send_http_request(route, data, requests.post, **kwargs)\n\n def _send_get(self, route, data=None, **kwargs):\n return self._send_http_request(route, data, requests.get, **kwargs)\n\n def _recv_msg(self, message: bin, N: int = 10) -> bin:\n message = str(binascii.hexlify(message))\n return self._send_post(\"cmd\", data={\"message\": message}, N=N)\n\n def destroy(self):\n grid_name = self.addr.split(\"//\")[1].split(\".\")[0]\n gr_utils.execute_command(\n \"heroku destroy \" + grid_name + \" --confirm \" + grid_name\n )\n if self.verbose:\n print(\"Destroyed node: \" + str(grid_name))\n\n @property\n def models(self, N: int = 1):\n return json.loads(self._send_get(\"models/\", N=N))[\"models\"]\n\n def delete_model(self, model_id):\n result = json.loads(\n self._send_post(\n \"delete_model/\", data={\"model_id\": model_id}, unhexlify=False\n )\n )\n return self._return_bool_result(result)\n\n def download_model(self, model_id: str):\n \"\"\"Downloads a model to run it locally.\"\"\"\n\n def _is_large_model(result):\n return \"multipart/form-data\" in result.headers[\"Content-Type\"]\n\n # Check if we can get a copy of this model\n result = json.loads(\n self._send_get(\"is_model_copy_allowed/{}\".format(model_id), unhexlify=False)\n )\n\n if not result[\"success\"]:\n raise RuntimeError(result[\"error\"])\n\n try:\n # If the model is a plan we can just call fetch\n return sy.hook.local_worker.fetch_plan(model_id, self, copy=True)\n except AttributeError:\n result = self._send_get(\n \"get_model/{}\".format(model_id),\n unhexlify=False,\n return_response_text=False,\n )\n if result:\n if _is_large_model(result):\n # If model is large, receive it by a stream channel\n multipart_data = decoder.MultipartDecoder.from_response(result)\n model_bytes = b\"\".join(\n [part.content for part in multipart_data.parts]\n )\n serialized_model = model_bytes.decode(\"utf-8\").encode(\n self._encoding\n )\n else:\n # If model is small, receive it by a standard json\n result = json.loads(result.text)\n serialized_model = result[\"serialized_model\"].encode(self._encoding)\n\n model = sy.serde.deserialize(serialized_model)\n return model\n else:\n raise RuntimeError(\n \"There was a problem while getting the model, check the server logs for more information.\"\n )\n\n def _send_serve_model_post(\n self,\n serialized_model: bytes,\n model_id: str,\n allow_download: bool,\n allow_remote_inference: bool,\n ):\n if sys.getsizeof(serialized_model) >= MODEL_LIMIT_SIZE:\n return json.loads(\n self._send_streaming_post(\n \"serve-model/\",\n data={\n \"model\": (\n model_id,\n serialized_model,\n \"application/octet-stream\",\n ),\n \"encoding\": self._encoding,\n \"model_id\": model_id,\n \"allow_download\": str(allow_download),\n \"allow_remote_inference\": str(allow_remote_inference),\n },\n )\n )\n else:\n return json.loads(\n self._send_post(\n \"serve-model/\",\n data={\n \"model\": serialized_model,\n \"encoding\": self._encoding,\n \"model_id\": model_id,\n \"allow_download\": allow_download,\n \"allow_remote_inference\": allow_remote_inference,\n },\n unhexlify=False,\n )\n )\n\n def serve_encrypted_model(self, encrypted_model: sy.messaging.plan.Plan):\n \"\"\"Serve a model in a encrypted fashion using SMPC.\n\n A wrapper for sending the model. The worker is responsible for sharing the model using SMPC.\n\n Args:\n encrypted_model: A pĺan already shared with workers using SMPC.\n\n Returns:\n True if model was served successfully, raises a RunTimeError otherwise.\n \"\"\"\n # Send the model\n encrypted_model.send(self)\n res_model = encrypted_model.ptr_plans[self.id]\n\n # Serve the model so we can have a copy saved in the database\n serialized_model = sy.serde.serialize(res_model).decode(self._encoding)\n result = self._send_serve_model_post(\n serialized_model,\n res_model.id,\n allow_download=True,\n allow_remote_inference=False,\n )\n return self._return_bool_result(result)\n\n def serve_model(\n self,\n model,\n model_id: str = None,\n allow_download: bool = False,\n allow_remote_inference: bool = False,\n ):\n \"\"\"Hosts the model and optionally serve it using a Rest API.\n\n Args:\n model: A jit model or Syft Plan.\n model_id: An integer or string representing the model id used to retrieve the model\n later on using the Rest API. If this is not provided and the model is a Plan\n we use model.id, if the model is a jit model we raise an exception.\n allow_download: If other workers should be able to fetch a copy of this model to run it locally set this to True.\n allow_remote_inference: If other workers should be able to run inference using this model through a Rest API interface set this True.\n\n Returns:\n True if model was served sucessfully, raises a RunTimeError otherwise.\n\n Raises:\n ValueError: if model_id is not provided and model is a jit model (aka does not have an id attribute).\n RunTimeError: if there was a problem during model serving.\n \"\"\"\n if model_id is None:\n if isinstance(model, sy.Plan):\n model_id = model.id\n else:\n raise ValueError(\"Model id argument is mandatory for jit models.\")\n\n # If the model is a Plan we send the model\n # and host the plan version created after\n # the send operation\n if isinstance(model, sy.Plan):\n # We need to use the same id in the model\n # as in the POST request.\n model.id = model_id\n model.send(self)\n res_model = model.ptr_plans[self.id]\n else:\n res_model = model\n\n # Send post\n serialized_model = sy.serde.serialize(res_model).decode(self._encoding)\n result = self._send_serve_model_post(\n serialized_model, model_id, allow_download, allow_remote_inference\n )\n\n # Return result\n return self._return_bool_result(result)\n\n def run_remote_inference(self, model_id, data, N: int = 1):\n serialized_data = sy.serde.serialize(data)\n result = json.loads(\n self._send_get(\n \"models/{}\".format(model_id),\n data={\n \"data\": serialized_data.decode(self._encoding),\n \"encoding\": self._encoding,\n },\n N=N,\n )\n )\n\n return self._return_bool_result(result, return_key=\"prediction\")\n","sub_path":"grid/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":11708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"23355332","text":"import matplotlib.pyplot as plt\nimport time\nimport numpy as np\n\nfrom qutip import *\nfrom qutip.control.grape import cy_grape_unitary, grape_unitary_adaptive, plot_grape_control_fields, _overlap\n\nfrom scipy.interpolate import interp1d\nfrom qutip.ui.progressbar import TextProgressBar\nqutip.settings.auto_tidyup = False\n\nT = 1\ntimes = np.linspace(0, T, 500)\n\nU = toffoli()\n\nR = 5000\nH_ops = [# qubit 1: single-qubit control\n tensor(sigmax(), identity(2), identity(2)),\n tensor(sigmay(), identity(2), identity(2)),\n tensor(sigmaz(), identity(2), identity(2)),\n # qubit 1: single-qubit control\n tensor(identity(2), sigmax(), identity(2)),\n tensor(identity(2), sigmay(), identity(2)),\n tensor(identity(2), sigmaz(), identity(2)),\n # qubit 3: single-qubit control\n tensor(identity(2), identity(2), sigmax()),\n tensor(identity(2), identity(2), sigmay()),\n tensor(identity(2), identity(2), sigmaz()),\n # pairwise X-X interactions\n tensor(sigmax(), sigmax(), identity(2)),\n tensor(identity(2), sigmax(), sigmax()),\n tensor(sigmax(), identity(2), sigmax()),\n # pairwise Y-Y interactions\n tensor(sigmay(), sigmay(), identity(2)),\n tensor(identity(2), sigmay(), sigmay()),\n tensor(sigmay(), identity(2), sigmay()),\n # pairwise Z-Z interactions\n tensor(sigmaz(), sigmaz(), identity(2)),\n tensor(identity(2), sigmaz(), sigmaz()),\n tensor(sigmaz(), identity(2), sigmaz()),\n ]\n\nH_labels = [r'$u_{1x}$',\n r'$u_{1y}$',\n r'$u_{1z}$',\n \n r'$u_{2x}$',\n r'$u_{2y}$',\n r'$u_{2z}$',\n \n r'$u_{3x}$',\n r'$u_{3y}$',\n r'$u_{3z}$',\n \n r'$u_{xxi}$',\n r'$u_{ixx}$',\n r'$u_{xix}$',\n \n r'$u_{yyi}$',\n r'$u_{iyy}$',\n r'$u_{yiy}$',\n \n r'$u_{zzi}$',\n r'$u_{izz}$',\n r'$u_{ziz}$',\n ]\n\npi = 3.14\nH0 = 2 * pi * (tensor(sigmaz(), identity(2), identity(2)) + \n tensor(identity(2), sigmaz(), identity(2)) + \n tensor(identity(2), identity(2), sigmaz()))\n\nc_ops = []\n\n\n\nu0 = np.array([np.random.rand(len(times)) * 2 * pi * 0.01 for _ in range(len(H_ops))])\n\nu0 = [np.convolve(np.ones(10)/10, u0[idx,:], mode='same') for idx in range(len(H_ops))]\n\nprint(\"yes\")\nprint(U)\nresult = cy_grape_unitary(U, H0, H_ops, R, times, phase_sensitive=False,\n u_start=u0, progress_bar=TextProgressBar(),\n eps=2*pi*5)\n\nplot_grape_control_fields(times, result.u / (2 * pi), H_labels, uniform_axes=True)\n\nprint(U)\n\nresult.U_f.tidyup(1e-1)\n\nresult.U_f / result.U_f[0,0] #.tidyup(1e-1)\n\nabs(_overlap(U, result.U_f))**2\n\nop_basis = [[qeye(2), sigmax(), sigmay(), sigmaz()]] * 3\nop_label = [[\"i\", \"x\", \"y\", \"z\"]] * 3\n\nfig = plt.figure(figsize=(16,12))\n\nSU = spre(U) * spost(U.dag())\n\nchi = qpt(SU, op_basis)\n\nfig = qpt_plot_combined(chi, op_label, fig=fig, threshold=0.001)\n\nfig = plt.figure(figsize=(16,12))\n\nSU = spre(result.U_f) * spost(result.U_f.dag())\n\nchi = qpt(SU, op_basis)\n\nfig = qpt_plot_combined(chi, op_label, fig=fig, threshold=0.001)\n\nfrom qutip.ipynbtools import version_table\n\nversion_table()","sub_path":"qutip_grape.py","file_name":"qutip_grape.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"102343036","text":"#!/usr/bin/env python3\n\"\"\"Chapter 2.10 (Summary), A parameter study of nonstationary case,\npage 44\n\"\"\"\nimport time\nimport random\nfrom math import exp, log\nimport multiprocessing as mp\nfrom collections import defaultdict\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom fig2_2 import argmax, plot\n\n\ndef eps_greedy(steps, eps):\n \"\"\"Stationary 10-armed bandit problem.\n Sample-average epsilon-greedy method.\n\n :param steps: Number of timesteps\n :type steps: int\n :param eps: The probability of choosing the exploration vs exploitation.\n :type eps: float\n :return: Rewards\n :rtype: list\n \"\"\"\n q = list(np.random.normal(0, 1, size=10)) # true action values\n q_est = [0] * 10 # estimated action values\n action_counts = [0] * 10 # action counter\n rewards = list() # rewards on each step\n\n for i in range(steps):\n # choose an action\n if random.random() < 1 - eps: # exploitation\n action = argmax(q_est)\n else: # exploration\n action = random.randint(0, 9)\n action_counts[action] += 1 # update action counter\n rewards.append(np.random.normal(q[action], 1)) # get action normally distributed reward\n\n # update estimated values\n q_est[action] += (rewards[-1] - q_est[action]) / action_counts[action]\n\n return rewards\n\n\ndef grad_bline(steps, alpha):\n \"\"\"Stationary 10-armed bandit problem.\n Gradient Bandit Algorithm with baseline.\n\n :param steps: Number of timesteps\n :type steps: int\n :param alpha: Constant step-size\n :type alpha: float\n :return: Rewards\n :rtype: list\n \"\"\"\n q = list(np.random.normal(0, 1, size=10)) # true action values\n h = [0] * 10 # action preferences\n p = [0.1] * 10 # probabilities of choosing an action\n mean = 0 # mean reward initialisation\n rewards = list()\n\n for i in range(steps):\n action = random.choices(range(10), weights=p, k=1)[0] # choose an action\n reward = np.random.normal(q[action], 1) # get action reward\n rewards.append(reward)\n # update preferences\n mean = mean + (reward - mean) / (i + 1) # incremental formula for mean value\n h_exps = []\n for j, _ in enumerate(h):\n if j == action:\n h[j] = h[j] + alpha * (reward - mean) * (1 - p[j]) # preference for chosen action\n else:\n h[j] = h[j] - alpha * (reward - mean) * p[j] # preference for other actions\n h_exps.append(exp(h[j])) # exponents for each preference\n\n # update action probabilities\n h_exps_sum = sum(h_exps)\n p = [x / h_exps_sum for x in h_exps]\n\n return rewards\n\n\ndef ucb(steps, c):\n \"\"\"Stationary 10-armed bandit problem.\n Upper-Confidence-Bound Action Selection.\n\n :param steps: Number of time steps\n :type steps: int\n :param c: Degree of exploration\n :type c: float\n :return: Rewards\n :rtype: list\n \"\"\"\n q = list(np.random.normal(0, 1, size=10)) # true action values\n q_est = [0] * 10 # estimated action values\n action_counts = [0] * 10 # action counter\n ucb_q_est = [5] * 10 # ucb estimations\n rewards = list()\n\n for i in range(0, steps):\n action = argmax(ucb_q_est) # choose greedy\n rewards.append(np.random.normal(q[action], 1)) # get action reward\n\n # update ucb estimations\n for j in range(10):\n if action_counts[j] != 0:\n sqrt = (log(i) / action_counts[j]) ** 0.5\n ucb_q_est[j] = q_est[j] + c * sqrt\n action_counts[action] += 1 # update action counter\n\n # update estimated values\n q_est[action] += (rewards[-1] - q_est[action]) / action_counts[action]\n\n return rewards\n\n\ndef optimistic_greedy(steps, q0):\n \"\"\"Stationary 10-armed bandit problem.\n Constant step-size greedy method\n\n :param steps: Number of timesteps\n :type steps: int\n :param q0: Initial value for q estimation\n :type q0: float\n :return: Rewards\n :rtype: list\n \"\"\"\n q = list(np.random.normal(0, 1, size=10)) # true action values\n q_est = [q0] * 10 # estimated action values\n rewards = list() # rewards on each step\n\n for i in range(steps):\n action = argmax(q_est) # choose action\n rewards.append(np.random.normal(q[action], 1)) # get action normally distributed reward\n q_est[action] += (rewards[-1] - q_est[action]) * 0.1 # update estimated values\n\n return rewards\n\n\nif __name__ == '__main__':\n\n runs = int(2e3)\n steps = int(1e3)\n\n # parameter values (powers of 2)\n params = [2 ** i for i in range(-7, 3)]\n # string representations for parameter values\n x_ticks = ['1/128', '1/64', '1/32', '1/16', '1/8', '1/4', '1/2', '1', '2', '4']\n # indices for the slices of parameter values\n param_slices = {'eps_greedy': (0, 6),\n 'grad_bline': (2, 11),\n 'ucb': (3, 11),\n 'optimistic_greedy': (5, 11)}\n # dictionary to store obtained reward values for particular method\n rewards = defaultdict(list)\n\n # comment this line if run on windows or OS X (default method)\n mp.set_start_method('spawn')\n\n # parallel execution\n with mp.Pool(mp.cpu_count()) as pool:\n t0 = time.perf_counter()\n for method, _slice in param_slices.items():\n\n print(f'{method} started with parameters:')\n t1 = time.perf_counter()\n\n (start, stop) = _slice\n for param, x in zip(params[start:stop], x_ticks[start:stop]):\n print(f'{x}', end=' ')\n # mean reward across all runs\n arr = np.array(pool.starmap(locals()[method], [(steps, param)] * runs)).mean(axis=0)\n # overall mean reward\n rewards[method].append(arr.mean())\n\n t2 = time.perf_counter()\n print(f'done in {round(t2 - t1, 3)} sec')\n\n t3 = time.perf_counter()\n print(f'Overall execution time {round(t3 - t0, 3)} sec')\n\n # plotting\n # labels and colors\n labels = (r'$\\varepsilon$-greedy, $\\varepsilon$',\n r'gradient bandit, $\\alpha$',\n r'UCB, $c$',\n 'optimistic greedy\\n' r'$\\alpha=0.1, Q_0$')\n ylabel = 'Average reward over\\n first 1000 steps'\n xlabel = r'$\\varepsilon, \\alpha, c, Q_0$'\n colors = ('red', 'green', 'blue', 'black')\n\n # x axis values to correspond with parameter slices\n x = [list(range(10)[start:stop]) for (start, stop) in param_slices.values()]\n # plots\n ax = plot(rewards.values(), labels, ylabel, datax=x, xlabel=xlabel, colors=colors, fig_size=(15, 8))\n plt.xticks(range(10), x_ticks)\n\n plt.show()\n","sub_path":"chapter2/func/fig2_6.py","file_name":"fig2_6.py","file_ext":"py","file_size_in_byte":7397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"436274368","text":"#!/usr/bin/env python3\nimport sys\nimport numpy\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines\n\n\nfile = open('wynik.txt','w')\n\n#Rysowanie wykresów\ndraw_chart = (len(sys.argv)>1)\n\n#-------------------- ZMIENNE GLOBALNE --------------#\n\nm = 1\nE = -0.6\nv0 = 0\n\n#-------------------- FUNKCJE GLOBALNE --------------#\n\n#Pochodna pierwszego rzedu\ndef diff(x,dx,fun):\n\treturn (fun(x+dx)-fun(x-dx))/(2*dx)\n\n#Funkcja potencjalu V(x)\ndef potencjal(x):\n\treturn -numpy.exp(-x**2) -1.2*numpy.exp(-(x-2)**2)\n\n#Rysowanie potencjalu V(x)\n\ndef rysuj_potencjal(a,b,fun,fi,name):\n\tif fi:\n\t\tx = numpy.linspace(a,b,1000)\n\t\tfig, ax = plt.subplots()\n\t\tax.plot(x,fun(x))\n\t\tax.grid()\n\t\tax.set(xlabel = 'x', ylabel = 'V(x)')\n\t\tax.xaxis.label.set_size(18)\n\t\tax.yaxis.label.set_size(18)\n\t\tfig = plt.gcf()\n\t\tfig.set_size_inches(18.5, 10.5, forward = True)\n\t\tfig.savefig(name+'.png', dpi = 100)\n\t\tplt.show()\n\n#-------------------- ZADANIE 1 ---------------------#\n\n#Funkcja F\ndef funkcja_f1(x,E_0 = E):\n\treturn potencjal(x)-E_0\n\nrysuj_potencjal(-2,4,potencjal,draw_chart,'pot')\n\n#____________________ ZADANIE 1.1 ___________________#\n\n\n#Funckja liczaca miejsce zerowe funkcji fun metoda bisekcji\ndef bisekcja(err,a,b,fun):\n\tif not ((fun(a)>0 and fun(b)<0) or (fun(a)<0 and fun(b)>0)):\n\t\tprint('Podaj inne wartości graniczne:', a, b)\n\telse:\n\t\tTAB_x = [a,b]\n\t\tTAB_s = ['a','b']\n\t\tn = 0\n\t\twhile(abs(a - b) > err):\n\t\t\tmid = (a + b)/2\n\t\t\tn += 1\n\t\t\tTAB_x.append(mid)\n\t\t\tTAB_s.append(str(n))\n\t\t\tif fun(a) * fun(mid) < 0:\n\t\t\t\tb = mid\n\t\t\telif fun(b) * fun(mid) < 0:\n\t\t\t\ta = mid\n\n\t\t#Zwrot wynikow\n\t\tzad = '#____________________ ZADANIE 1.1 ___________________#'\n\t\thead = 'a = ' + \"{: .6f}\".format(TAB_x[0]) + ' b = ' + \"{: .6f}\".format(TAB_x[1]) + ' ERR = ' + \"{: .6f}\".format(err)\n\t\tprint(zad, '\\n', '\\n', head)\n\t\tfile.write(zad + '\\n' + '\\n' + head + '\\n')\n\t\tfor i in list(zip(TAB_x, TAB_s)):\n\t\t\tout = '{: .6f}'.format(i[0]) + '\\t' + \"{: .6f}\".format(fun(i[0])) + '\\t' + i[1]\n\t\t\tprint(out)\n\t\t\tfile.write(out + '\\n')\n\t\treturn [TAB_x,TAB_s,n]\n\n#Funkcje do rysowania wykresów\ndef rysuj_1_1(wynik,a,b,fi,legend,name):\n\tif fi:\n\t\ts = wynik[1]\n\t\tx = numpy.array(wynik[0])\n\t\txx = numpy.linspace(a,b,1000)\n\t\tfig, ax = plt.subplots()\n\t\tax.plot(xx, funkcja_f1(xx), color = 'green')\n\t\tax.plot(x,funkcja_f1(x), 'rd',)\n\t\tfor i in zip(s,x):\n\t\t\tax.text(i[1],0.03 + funkcja_f1(i[1]), i[0])\n\t\tax.grid()\n\t\tax.set(xlabel = 'x [m]', ylabel = 'F(x) [J]')\n\t\tpunkty = mlines.Line2D([], [], label = 'Punkty z metody bisekcji', color = 'red', linestyle = 'None', marker = 'd')\n\t\tlinia = mlines.Line2D([], [], label = 'Funkcja F(x)', color = 'green', linestyle = 'solid', marker = 'None')\n\t\tax.legend(handles = [punkty, linia], loc = legend)\n\t\tax.xaxis.label.set_size(18)\n\t\tax.yaxis.label.set_size(18)\n\t\tfig = plt.gcf()\n\t\tfig.set_size_inches(18.5, 10.5, forward = True)\n\t\tfig.savefig(name+'.png', dpi = 100)\n\t\tplt.show()\n\ndef rysuj_1_2(wynik,fi,name):\n\tif fi:\n\t\tx = numpy.array(wynik[0])\n\t\tn = numpy.arange(1,len(x)+1,1)\n\t\tfig, ax = plt.subplots()\n\t\tax.semilogy(n,abs(funkcja_f1(x)), 'rd',)\n\t\tax.grid()\n\t\tax.set(xlabel = 'Liczba iteracji i', ylabel = '|F(x)|')\n\t\tax.xaxis.label.set_size(18)\n\t\tax.yaxis.label.set_size(18)\n\t\tfig = plt.gcf()\n\t\tfig.set_size_inches(18.5, 10.5, forward = True)\n\t\tfig.savefig(name+'.png', dpi = 100)\n\t\tplt.show()\n\n#Punkty poczatkowe\na_1 = 1\nb_1 = 3\na_2 = -2\nb_2 = 0\n\n#Dopuszczalny blad err\nerr = 1e-6\n\n#Wynik 1\nWYNIK_1_1 = bisekcja(err,a_1,b_1,funkcja_f1)\n#Wynik 2\nWYNIK_1_2 = bisekcja(err,a_2,b_2,funkcja_f1)\n\n#Rysowanie wykresow\nrysuj_1_1(WYNIK_1_1, 0, 4, draw_chart,'upper left','1_1_1_1')\nrysuj_1_2(WYNIK_1_1,draw_chart, '1_1_1_2')\n\nrysuj_1_1(WYNIK_1_2, -3, 0, draw_chart,'lower left', '1_1_2_1')\nrysuj_1_2(WYNIK_1_2,draw_chart, '1_1_2_2')\n\n\n\n#____________________ ZADANIE 1.2 ___________________#\n\n\n#Funckja liczaca miejsce zerowe funkcji fun metoda Newtona-Raphsona\ndef new_rap(err,x_n,fun,dx):\n\tx_n1 = x_n - fun(x_n)/diff(x_n,dx,fun)\n\tTAB = [x_n, x_n1]\n\t\n\twhile(abs(x_n - x_n1) > err):\n\t\tx_n = x_n1\n\t\tx_n1 = x_n - fun(x_n)/diff(x_n,dx,fun)\n\t\tTAB.append(x_n1)\n\n\t#Zwrot wynikow\n\tzad = '#____________________ ZADANIE 1.2 ___________________#'\n\thead = 'x0 = ' + \"{: .6f}\".format(TAB[0]) + ' ERR = ' + \"{: .6f}\".format(err)\n\tprint(zad, '\\n', '\\n', head)\n\tfile.write(zad + '\\n' + '\\n' + head + '\\n')\n\tfor i in TAB:\n\t\tout = '{: .6f}'.format(i) + '\\t' + \"{: .6f}\".format(fun(i))\n\t\tprint(out)\n\t\tfile.write(out + '\\n')\n\treturn TAB\n\n#Funckje do rysowania wykresów\ndef rysuj_1_11(wynik,a,b,fi,legend,name):\n\tif fi:\n\t\ts = numpy.arange(0,len(wynik),1)\n\t\tx = numpy.array(wynik)\n\t\txx = numpy.linspace(a,b,1000)\n\t\tfig, ax = plt.subplots()\n\t\tax.plot(xx, funkcja_f1(xx), color = 'green')\n\t\tax.plot(x,funkcja_f1(x), 'rd',)\n\t\tfor i in zip(s,x):\n\t\t\tax.text(i[1],0.03 + funkcja_f1(i[1]), i[0])\n\t\tax.grid()\n\t\tax.set(xlabel = 'x [m]', ylabel = 'F(x) [J]')\n\t\tpunkty = mlines.Line2D([], [], label = 'Punkty z metody Newtona-Raphsona', color = 'red', linestyle = 'None', marker = 'd')\n\t\tlinia = mlines.Line2D([], [], label = 'Funkcja F(x)', color = 'green', linestyle = 'solid', marker = 'None')\n\t\tax.legend(handles = [punkty, linia], loc = legend)\n\t\tax.xaxis.label.set_size(18)\n\t\tax.yaxis.label.set_size(18)\n\t\tfig = plt.gcf()\n\t\tfig.set_size_inches(18.5, 10.5, forward = True)\n\t\tfig.savefig(name+'.png', dpi = 100)\n\t\tplt.show()\n\ndef rysuj_1_22(wynik,fi,name):\n\tif fi:\n\t\tx = numpy.array(wynik)\n\t\tn = numpy.arange(1,len(x)+1,1)\n\t\tfig, ax = plt.subplots()\n\t\tax.semilogy(n,abs(funkcja_f1(x)), 'rd',)\n\t\tax.grid()\n\t\tax.set(xlabel = 'Liczba iteracji i', ylabel = '|F(x)|')\n\t\tax.xaxis.label.set_size(18)\n\t\tax.yaxis.label.set_size(18)\n\t\tfig = plt.gcf()\n\t\tfig.set_size_inches(18.5, 10.5, forward = True)\n\t\tfig.savefig(name+'.png', dpi = 100)\n\t\tplt.show()\n\n\n#Punkty poczatkowe\na = 3\nb = 1\ndx = 0.01\n#Dopuszczalny blad err\nerr = 1e-6\n\nWYNIK_1_1 = new_rap(err,a,funkcja_f1,dx)\nWYNIK_1_2 = new_rap(err,b,funkcja_f1,dx)\n\n#Rysowanie wykresow\nrysuj_1_11(WYNIK_1_1, 0, 4, draw_chart,'upper left','1_2_1_1')\nrysuj_1_22(WYNIK_1_1,draw_chart, '1_2_1_2')\n\nrysuj_1_11(WYNIK_1_2, -3, 0, draw_chart,'lower left', '1_2_2_1')\nrysuj_1_22(WYNIK_1_2,draw_chart, '1_2_2_2')\n\n\n\n#-------------------- ZADANIE 2 ---------------------#\n\n#Funkcje do jawnego schematu Eulera\n\ndef predkosc(v0, x0, dt, dx, alpha = 0):\n\treturn v0 - 1/m * diff(x0,dx,potencjal)*dt - v0*alpha*dt\n\ndef polozenie(x0, v0, dt):\n\treturn x0 + v0 * dt\n\ndef energia_kinetyczna(v):\n\tdef energia(v):\n\t\treturn m*v**2/2\n\treturn list(map(energia,v))\n\ndef energia_potencjalna(x):\n\treturn list(map(potencjal,x))\n\ndef energia_cal(Ek, V):\n\treturn list(map(lambda x,y : x+y, Ek, V))\n\ndef funkcja_f2(t0, tk, v0, x0, dt, dx, alpha = 0):\n\tt = numpy.arange(t0, tk, dt)\n\tx = [x0]\n\tv = [v0]\n\tfor i in range(len(t)-1):\n\t\tvn = predkosc(v0,x0,dt,dx,alpha)\n\t\tv.append(vn)\n\t\tv0 = vn\n\t\txn = polozenie(x0,v0,dt)\n\t\tx.append(xn)\n\t\tx0 = xn\n\n\treturn (x,v,t)\n\ndef rysuj_2(x,y,fi,name,x_lab, y_lab):\n\tif fi:\n\t\tfig, ax = plt.subplots()\n\t\tax.plot(x,y, color = 'blue')\n\n\t\tax.grid()\n\t\tax.set(xlabel = x_lab, ylabel = y_lab)\n\t\tax.xaxis.label.set_size(18)\n\t\tax.yaxis.label.set_size(18)\n\t\tfig = plt.gcf()\n\t\tfig.set_size_inches(18.5, 10.5, forward = True)\n\t\tfig.savefig(name+'.png', dpi = 100)\n\t\tplt.show()\n\n\n\n#Punkty poczatkowe 2_1\nt0 = 0\ntk = 30\nx0 = WYNIK_1_1[-1]\ndt = 0.01\ndx = 0.01\n#Wyniki 2_1\nWYNIK_2_1 = funkcja_f2(t0, tk, v0, x0, dt, dx)\nrysuj_2(WYNIK_2_1[2], WYNIK_2_1[0], draw_chart, '2_1x', 't [s]', 'x [m]')\nrysuj_2(WYNIK_2_1[2], WYNIK_2_1[1], draw_chart, '2_1v', 't [s]', 'v [m/s]')\nE_k = energia_kinetyczna(WYNIK_2_1[1])\nrysuj_2(WYNIK_2_1[2], E_k, draw_chart, '2_1ek', 't [s]', '$E_k(t)$ [J]')\nV = energia_potencjalna(WYNIK_2_1[0])\nrysuj_2(WYNIK_2_1[0], V, draw_chart, '2_1vv', 'x [m]', '$V(x(t))$ [J]')\nEc = energia_cal(E_k,V)\nrysuj_2(WYNIK_2_1[2], Ec, draw_chart, '2_1ekv', 't [s]', '$E_k(t) + V(t)$ [J]')\n\n#Punkty poczatkowe 2_2_1\nt0 = 0\ntk = 100\nx0 = WYNIK_1_1[-1]\ndt = 0.01\ndx = 0.01\n#Wyniki 2_2_1\nWYNIK_2_2_1 = funkcja_f2(t0, tk, v0, x0, dt, dx)\nrysuj_2(WYNIK_2_2_1[0], WYNIK_2_2_1[1], draw_chart, '2_2_1', 'x [m]', 'v [m/s]')\n\n#Punkty poczatkowe 2_2_2\nt0 = 0\ntk = 1000\nx0 = WYNIK_1_1[-1]\ndt = 0.001\ndx = 0.01\n#Wyniki 2_2_2\nWYNIK_2_2_2 = funkcja_f2(t0, tk, v0, x0, dt, dx)\nrysuj_2(WYNIK_2_2_2[0], WYNIK_2_2_2[1], draw_chart, '2_2_2', 'x [m]', 'v [m/s]')\n\n\n\n#-------------------- ZADANIE 3 ---------------------#\n\ndef rysuj_3(x,y,fi,name,x_lab, y_lab):\n\tif fi:\n\t\tfig, ax = plt.subplots()\n\t\tax.semilogy(x,y, color = 'blue')\n\n\t\tax.grid()\n\t\tax.set(xlabel = x_lab, ylabel = y_lab)\n\t\tax.xaxis.label.set_size(18)\n\t\tax.yaxis.label.set_size(18)\n\t\tfig = plt.gcf()\n\t\tfig.set_size_inches(18.5, 10.5, forward = True)\n\t\tfig.savefig(name+'.png', dpi = 100)\n\t\tplt.show()\n\n#Punkty poczatkowe 3_3\nt0 = 0\ntk = 30\nx0 = WYNIK_1_1[-1]\ndt = 0.01\ndx = 0.01\n\n#Punkty poczatkowe 3_1\nalpha = 0.5\n#Wyniki 3_1\nWYNIK_3_1 = funkcja_f2(t0, tk, v0, x0, dt, dx, alpha)\nrysuj_2(WYNIK_3_1[0], WYNIK_3_1[1], draw_chart, '3_1', 'x [m]', 'v [m/s]')\n\n#Punkty poczatkowe 3_2\nalpha = 5\n#Wyniki 3_2\nWYNIK_3_2 = funkcja_f2(t0, tk, v0, x0, dt, dx, alpha)\nrysuj_2(WYNIK_3_2[0], WYNIK_3_2[1], draw_chart, '3_2', 'x [m]', 'v [m/s]')\n\n#Punkty poczatkowe 3_3\nalpha = 201\n#Wyniki 3_3\nWYNIK_3_3 = funkcja_f2(t0, tk, v0, x0, dt, dx, alpha)\nrysuj_3(WYNIK_3_3[0], WYNIK_3_3[1], draw_chart, '3_3', 'x [m]', 'v [m/s]')\n\n\n\n","sub_path":"MOFiT/LAB_1/lipior_mofit_lab1.py","file_name":"lipior_mofit_lab1.py","file_ext":"py","file_size_in_byte":9245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"634623568","text":"\"\"\"\nFirebird database backend for Django.\n\"\"\"\n\nimport sys\n\ntry:\n import fdb as Database\nexcept ImportError as e:\n from django.core.exceptions import ImproperlyConfigured\n raise ImproperlyConfigured(\"Error loading fdb module: %s\" % e)\n\nfrom fdb.ibase import charset_map\n\nfrom django.db import utils\nfrom django.db.backends import (\n BaseDatabaseFeatures,\n BaseDatabaseWrapper,\n BaseDatabaseValidation,\n)\nfrom django.db.backends.signals import connection_created\nfrom django.utils.encoding import smart_str\nfrom django.utils.functional import cached_property\nfrom django.utils import six\n\nfrom .operations import DatabaseOperations\nfrom .client import DatabaseClient\nfrom .creation import DatabaseCreation\nfrom .introspection import DatabaseIntrospection\nfrom .schema import DatabaseSchemaEditor\n\nDatabaseError = Database.DatabaseError\nIntegrityError = Database.IntegrityError\nOperationalError = Database.OperationalError\n\n\nclass DatabaseFeatures(BaseDatabaseFeatures):\n allows_group_by_pk = False # if the backend can group by just by PK\n supports_forward_references = False\n has_bulk_insert = False\n can_return_id_from_insert = True\n has_select_for_update = True\n has_select_for_update_nowait = False\n supports_forward_references = False\n supports_tablespaces = False\n supports_long_model_names = False\n supports_timezones = False\n has_zoneinfo_database = False\n uses_savepoints = True\n supports_paramstyle_pyformat = False\n #connection_persists_old_columns = True\n can_rollback_ddl = True\n requires_literal_defaults = True\n has_case_insensitive_like = False\n\n # In firebird, check constraint are table based, no column based\n supports_column_check_constraints = False\n\n can_introspect_boolean_field = False\n can_introspect_small_integer_field = True\n\n # If NULL is implied on columns without needing to be explicitly specified\n implied_column_null = True\n\n uppercases_column_names = True\n\n @cached_property\n def supports_transactions(self):\n return True\n\n\nclass DatabaseValidation(BaseDatabaseValidation):\n pass\n\n\nclass DatabaseWrapper(BaseDatabaseWrapper):\n vendor = 'firebird'\n operators = {\n 'exact': '= %s',\n 'iexact': '= UPPER(%s)',\n 'contains': \"LIKE %s ESCAPE'\\\\'\",\n 'icontains': \"LIKE UPPER(%s) ESCAPE'\\\\'\", # 'CONTAINING %s', #case is ignored\n 'gt': '> %s',\n 'gte': '>= %s',\n 'lt': '< %s',\n 'lte': '<= %s',\n 'startswith': \"LIKE %s ESCAPE'\\\\'\", # 'STARTING WITH %s', #looks to be faster than LIKE\n 'endswith': \"LIKE %s ESCAPE'\\\\'\",\n 'istartswith': \"LIKE UPPER(%s) ESCAPE'\\\\'\", # 'STARTING WITH UPPER(%s)',\n 'iendswith': \"LIKE UPPER(%s) ESCAPE'\\\\'\",\n 'regex': \"SIMILAR TO %s\",\n 'iregex': \"SIMILAR TO %s\", # Case Sensitive depends on collation\n }\n\n Database = Database\n\n def __init__(self, *args, **kwargs):\n super(DatabaseWrapper, self).__init__(*args, **kwargs)\n\n self._server_version = None\n self._db_charset = None\n self.encoding = None\n\n opts = self.settings_dict[\"OPTIONS\"]\n RC = Database.ISOLATION_LEVEL_READ_COMMITED\n self.isolation_level = opts.get('isolation_level', RC)\n\n self.features = DatabaseFeatures(self)\n self.ops = DatabaseOperations(self)\n self.client = DatabaseClient(self)\n self.creation = DatabaseCreation(self)\n self.introspection = DatabaseIntrospection(self)\n self.validation = DatabaseValidation(self)\n\n ##### Backend-specific methods for creating connections and cursors #####\n\n def get_connection_params(self):\n \"\"\"Returns a dict of parameters suitable for get_new_connection.\"\"\"\n settings_dict = self.settings_dict\n if settings_dict['NAME'] == '':\n from django.core.exceptions import ImproperlyConfigured\n raise ImproperlyConfigured(\n \"settings.DATABASES is improperly configured. \"\n \"Please supply the NAME value.\")\n\n conn_params = {'charset': 'UTF8'}\n conn_params['dsn'] = settings_dict['NAME']\n if settings_dict['HOST']:\n conn_params['dsn'] = ('%s:%s') % (settings_dict['HOST'], conn_params['dsn'])\n if settings_dict['PORT']:\n conn_params['port'] = settings_dict['PORT']\n if settings_dict['USER']:\n conn_params['user'] = settings_dict['USER']\n if settings_dict['PASSWORD']:\n conn_params['password'] = settings_dict['PASSWORD']\n options = settings_dict['OPTIONS'].copy()\n conn_params.update(options)\n\n self._db_charset = conn_params.get('charset')\n self.encoding = charset_map.get(self._db_charset, 'utf_8')\n\n return conn_params\n\n def get_new_connection(self, conn_params):\n \"\"\"Opens a connection to the database.\"\"\"\n return Database.connect(**conn_params)\n\n def init_connection_state(self):\n \"\"\"Initializes the database connection settings.\"\"\"\n pass\n\n def create_cursor(self):\n \"\"\"Creates a cursor. Assumes that a connection is established.\"\"\"\n cursor = self.connection.cursor()\n return FirebirdCursorWrapper(cursor, self.encoding)\n\n ##### Backend-specific transaction management methods #####\n\n def _set_autocommit(self, autocommit):\n \"\"\"\n Backend-specific implementation to enable or disable autocommit.\n\n FDB doesn't support auto-commit feature directly, but developers may\n achieve the similar result using explicit transaction start, taking\n advantage of default_action and its default value (commit).\n See:\n http://www.firebirdsql.org/file/documentation/drivers_documentation/python/fdb/usage-guide.html#auto-commit\n\n Pay attention at _close() method below\n \"\"\"\n pass\n\n ##### Backend-specific wrappers for PEP-249 connection methods #####\n\n def _close(self):\n if self.connection is not None:\n with self.wrap_database_errors:\n if self.autocommit is True:\n self.connection.commit()\n return self.connection.close()\n\n ##### Connection termination handling #####\n\n def is_usable(self):\n \"\"\"\n Tests if the database connection is usable.\n This function may assume that self.connection is not None.\n \"\"\"\n try:\n cur = self.connection.cursor()\n cur.execute('SELECT 1 FROM RDB$DATABASE')\n except DatabaseError:\n return False\n else:\n return True\n\n @cached_property\n def server_version(self):\n \"\"\"\n Access method for engine_version property.\n engine_version return a full version in string format\n (ie: 'WI-V6.3.5.4926 Firebird 1.5' )\n \"\"\"\n if not self._server_version:\n if not self.connection:\n self.cursor()\n self._server_version = self.connection.db_info(Database.isc_info_firebird_version)\n return self._server_version\n\n def schema_editor(self, *args, **kwargs):\n \"Returns a new instance of this backend's SchemaEditor\"\n return DatabaseSchemaEditor(self, *args, **kwargs)\n\n\nclass FirebirdCursorWrapper(object):\n \"\"\"\n Django uses \"format\" style placeholders, but firebird uses \"qmark\" style.\n This fixes it -- but note that if you want to use a literal \"%s\" in a query,\n you'll need to use \"%%s\".\n \"\"\"\n codes_for_integrityerror = (-803, -625, -530)\n\n def __init__(self, cursor, encoding):\n self.cursor = cursor\n self.encoding = encoding\n\n def execute(self, query, params=None):\n if params is None:\n params = []\n try:\n q = self.convert_query(query, len(params))\n return self.cursor.execute(q, params)\n except Database.IntegrityError as e:\n six.reraise(utils.IntegrityError, utils.IntegrityError(*self.error_info(e, query, params)), sys.exc_info()[2])\n except Database.DatabaseError as e:\n # Map some error codes to IntegrityError, since they seem to be\n # misclassified and Django would prefer the more logical place.\n # fdb: raise exception as tuple with (error_msg, sqlcode, error_code)\n if e.args[1] in self.codes_for_integrityerror:\n six.reraise(utils.IntegrityError, utils.IntegrityError(*self.error_info(e, query, params)), sys.exc_info()[2])\n #six.reraise(utils.DatabaseError, utils.DatabaseError(*self.error_info(e, query, params)), sys.exc_info()[2])\n raise\n\n def executemany(self, query, param_list):\n try:\n q = self.convert_query(query, len(param_list[0]))\n return self.cursor.executemany(q, param_list)\n except Database.IntegrityError as e:\n six.reraise(utils.IntegrityError, utils.IntegrityError(*self.error_info(e, query, param_list[0])), sys.exc_info()[2])\n except Database.DatabaseError as e:\n # Map some error codes to IntegrityError, since they seem to be\n # misclassified and Django would prefer the more logical place.\n # fdb: raise exception as tuple with (error_msg, sqlcode, error_code)\n if e.args[1] in self.codes_for_integrityerror:\n six.reraise(utils.IntegrityError, utils.IntegrityError(*self.error_info(e, query, param_list[0])), sys.exc_info()[2])\n #six.reraise(utils.DatabaseError, utils.DatabaseError(*self.error_info(e, query, param_list[0])), sys.exc_info()[2])\n raise\n\n def convert_query(self, query, num_params):\n # kinterbasdb tries to convert the passed SQL to string.\n # But if the connection charset is NONE, ASCII or OCTETS it will fail.\n # So we convert it to string first.\n if num_params == 0:\n return smart_str(query, self.encoding)\n return smart_str(query % tuple(\"?\" * num_params), self.encoding)\n\n def error_info(self, e, q, p):\n # fdb: raise exception as tuple with (error_msg, sqlcode, error_code)\n # just when it uses exception_from_status function. Ticket #44.\n try:\n error_msg = e.args[0]\n except IndexError:\n error_msg = ''\n\n try:\n sql_code = e.args[1]\n except IndexError:\n sql_code = None\n\n try:\n error_code = e.args[2]\n except IndexError:\n error_code = None\n\n if q:\n sql_text = q % tuple(p)\n else:\n sql_text = q\n return tuple([error_msg, sql_code, error_code, {'sql': sql_text, 'params': p}])\n\n def __getattr__(self, attr):\n if attr in self.__dict__:\n return self.__dict__[attr]\n else:\n return getattr(self.cursor, attr)\n\n def __iter__(self):\n return iter(self.cursor)\n","sub_path":"firebird/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"36393305","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import filedialog\nimport tkinter.messagebox as tkmsg\nimport create_schedule, pathlib, schedule, utils\n\n\nclass StartingPage:\n \n def __init__(self, root: tk.Tk, root_frame: tk.Frame):\n self._root = root\n self._root_frame = root_frame\n \n self._frame = tk.Frame(self._root_frame)\n self._frame.grid(row = 0, column = 0, sticky = tk.NSEW)\n self._frame.columnconfigure(0, weight = 10)\n self._frame.columnconfigure(2, weight = 10)\n self._frame.rowconfigure(2, weight = 1)\n \n self._root.bind('', self.new_schedule)\n self._root.bind('', self.open_schedule)\n self._root.bind('', self.open_recent)\n \n if utils.START_MENU is None:\n self._menu = tk.Menu(self._root)\n file_menu = tk.Menu(self._menu, tearoff = 0)\n file_menu.add_command(label = 'New Schedule', accelerator = 'Ctrl+N', command = self.new_schedule)\n file_menu.add_command(label = 'Open Schedule', accelerator = 'Ctrl+O', command = self.open_schedule)\n file_menu.add_command(label = 'Open Most Recent', accelerator = 'Ctrl+R', command = self.open_recent)\n file_menu.add_command(label = 'Quit', accelerator = 'Ctrl+Q', command = lambda: self._root.destroy())\n self._menu.add_cascade(label = 'File', menu = file_menu)\n utils.START_MENU = self._menu\n \n utils.set_menu(self._root, utils.START_MENU)\n \n utils.create_title(self._frame, 'School Manager', 3)\n ttk.Button(self._frame, text = 'Create New Schedule', command = self.new_schedule).grid(row = 2, column = 0, padx = 10, sticky = tk.E)\n ttk.Button(self._frame, text = 'Open Existing Schedule', command = self.open_schedule).grid(row = 2, column = 1, padx = 10)\n ttk.Button(self._frame, text = 'Open Recent Schedule', command = self.open_recent).grid(row = 2, column = 2, padx = 10, sticky = tk.W)\n tk.Label(self._frame, text = 'By Anthony Navarrette', font = 'Tahoma 10 bold').grid(row = 3, column = 0, pady = 10, sticky = tk.NSEW, columnspan = 3)\n \n self.load_start()\n \n self._schedule = None\n self._courses = None\n \n def open_schedule(self, event = None) -> None:\n schedule_dir = None\n file = None\n try:\n schedule_dir = filedialog.askopenfilename(initialdir = pathlib.Path('schedules'), filetypes =(('JSON Files', \"*.json\"),), title = 'Open File')\n file = open(schedule_dir)\n except FileNotFoundError:\n if schedule_dir != '':\n tkmsg.showinfo('Error', f'File cannot be opened at the given path.\\n{schedule_dir}')\n else: \n file.close()\n recent = open(pathlib.Path('schedules/recent.txt'), 'w')\n recent.write(pathlib.Path(schedule_dir).parts[-1].replace('.track', ''))\n recent.close()\n schedule.open_schedule(self._root, self._root_frame, open(schedule_dir), self)\n \n def new_schedule(self, event = None) -> None:\n reset = True\n if self._schedule is not None:\n reset = self._schedule.is_default()\n \n if reset:\n if self._schedule is None:\n self._schedule = create_schedule.TkCreateSchedule(self._root, self._root_frame, self)\n else:\n self._schedule.load_schedule()\n \n def open_recent(self, event = None) -> None:\n recent = open('schedules/recent.txt', 'r')\n \n recent_name = recent.readline().rstrip()\n if recent_name != '':\n file = None\n try:\n file = open(pathlib.Path(f'schedules/{recent_name}'))\n except FileNotFoundError:\n tkmsg.showinfo('Warning', f'{recent_name} cannot be found.')\n \n if file is not None:\n file.close()\n schedule.open_schedule(self._root, self._root_frame, open(pathlib.Path(f'schedules/{recent_name}')), self)\n else:\n tkmsg.showinfo('Warning', f'You have no recently opened schedules.')\n \n def load_start(self) -> None:\n self._schedule = None\n self._frame.tkraise()\n self._root.config(menu = self._menu)\n \n \n \n \n ","sub_path":"src/starting_page.py","file_name":"starting_page.py","file_ext":"py","file_size_in_byte":4429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"485744136","text":"# CLIENT PROGRAM\nimport os\nimport socket\nimport sys\ncls = 'os.system(\"cls\")'\n\ndef getnum():\n num = False\n while not num:\n try:\n num = int(raw_input(\"=> \"))\n return num\n except:\n print(\"Invalid number\")\n\nclass Client():\n\n cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n suits = ['H', 'C', 'D', 'S']\n names = {'A':'Ace', 'J':'Jack', 'Q':'Queen', 'K':'King',\n 'H':'Hearts', 'C':'Clubs', 'D':'Diamonds', 'S':'Spades'}\n \n cardlist = []\n for x in suits:\n for y in cards:\n cardlist.append(y+x)\n del x, y\n\n values = {}\n for x in range(len(cards)):\n if cards[x] not in ['J', 'Q', 'K']: values[cards[x]] = x + 1\n else: values[cards[x]] = 10\n\n def repr(self, card):\n s = ''\n if card[0:-1] in self.names: s += (self.names[card[0:-1]])\n elif card[0:-1] not in self.names: s += (card[0:-1])\n s += (\" of \")\n if card[-1] in self.names: s += (self.names[card[-1]])\n elif card[-1] not in self.names: s += (card[-1])\n return s\n\n def returnvalue(self, card):\n return self.values[card[0:-1]]\n\n def checkscore21(self, cardlist):\n score = 0\n aces = 0\n for x in cardlist:\n if x[0] != 'A': score += self.returnvalue(x)\n elif x[0] == 'A': aces += 1\n for x in range(aces):\n if score <= 10:\n score += 11\n elif score > 10:\n score += 1\n return score\n\n def turn(self):\n print(\"1) Hit\\n2) Stand\")\n choice = getnum()\n if choice == 1: return '00'\n if choice == 2: return '01'\n\n def log(self):\n self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.client.connect((self.addr, self.port))\n # Capture the list of computer cards\n self.compcards = self.client.recv(1024)\n print(self.compcards)\n self.compcards = eval(self.compcards)\n # Capture the list of player1 cards\n self.player1cards = self.client.recv(1024)\n print(self.player1cards)\n self.player1cards = eval(self.player1cards)\n # Capture the list of your cards\n self.player2cards = self.client.recv(1024)\n print(self.player2cards)\n self.player2cards = eval(self.player2cards)\n raw_input()\n self.client.send(\"0\")\n code = ''\n compcode = ''\n\n # Player 1's Turn:\n while True:\n eval(cls)\n print(\"Dealer shows:\")\n print(str(self.repr(self.compcards[1])))\n print(\"\")\n print(\"Player 1 Shows:\")\n print(str(self.repr(self.player1cards[1])))\n if len(self.player1cards) > 2:\n for x in self.player1cards[2:]:\n print(str(self.repr(x)))\n print(\"\")\n print(\"Your hand:\")\n for x in self.player2cards:\n print(str(self.repr(x)))\n print(\"Total: \"+str(self.checkscore21(self.player2cards)))\n print(\"\")\n code = ''\n code = self.client.recv(1024)\n if code == '0F':\n self.player1cards.append(self.client.recv(1024))\n print(\"Player 1 BUSTS: \"+str(self.checkscore21(self.player1cards))); code = '22'; break\n if code == '01': break\n if code == '00': self.player1cards.append(self.client.recv(1024))\n\n # Player 2's Turn:\n code = ''\n while True:\n eval(cls)\n print(\"Dealer shows:\")\n print(str(self.repr(self.compcards[1])))\n print(\"\")\n print(\"Player 1 Shows:\")\n for x in self.player1cards:\n print(str(self.repr(x)))\n print(\"Total: \"+str(self.checkscore21(self.player1cards)))\n print(\"\")\n print(\"Your hand:\")\n for x in self.player2cards:\n print(str(self.repr(x)))\n print(\"Total: \"+str(self.checkscore21(self.player2cards)))\n print(\"\")\n if self.checkscore21(self.player2cards) == 21: print(\"It is recommended that you stand\")\n print(\"\")\n print(self.player2cards)\n code = ''\n code = self.turn()\n self.client.send(code)\n code = self.client.recv\n if code != '0F' or code != '22' or code != '01': self.player2cards.append(self.client.recv(1024))\n if code == '0F' or code == '22': print(\"YOU BUST: \"+str(self.checkscore21(self.player2cards))); code = '22'; break\n if code == '01': break\n print(\"\")\n\n raw_input()\n\n # Comp Turn:\n \n\n def __init__(self, addr='192.168.0.100', port=3000):\n self.addr = addr\n self.port = port\n self.log()\n raw_input(\"Thank you for running!\\nPlease press 'Enter' to quit\")\n\ndef run():\n while True:\n C = Client()\n\nrun()\n","sub_path":"Python/Python scripts/client/games/Cards/CardClient.py","file_name":"CardClient.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"66890072","text":"#!/usr/bin/env python3\n\nimport fileinput\nimport logging as log\nfrom typing import Optional\n\nlog.basicConfig(format=\"\\033[1;34m%(levelname)s\\033[0m: %(message)s\", level=log.WARN)\n\n\nclass BNode(object):\n\n h_code = \"\\033[1;32m\"\n o_code = \"\\033[0m\"\n\n def __init__(self, l, r) -> None:\n self.l = l\n self.r = r\n self.marked = False\n self.l_marked = False\n self.r_marked = False\n\n def unmark(self) -> None:\n self.marked = False\n self.l_marked = False\n self.r_marked = False\n if isinstance(self.l, BNode):\n self.l.unmark()\n if isinstance(self.r, BNode):\n self.r.unmark()\n\n def magnitude(self) -> int:\n l = 0\n if isinstance(self.l, int):\n l = self.l\n else:\n l = self.l.magnitude()\n\n r = 0\n if isinstance(self.r, int):\n r = self.r\n else:\n r = self.r.magnitude()\n\n return 3 * l + 2 * r\n\n def __repr__(self) -> str:\n repr_str = \"\"\n if self.marked:\n repr_str += BNode.h_code\n repr_str += \"[\"\n\n if self.l_marked:\n repr_str += BNode.h_code\n repr_str += f\"{self.l}\"\n if self.l_marked and not self.marked:\n repr_str += BNode.o_code\n repr_str += \",\"\n\n if self.r_marked:\n repr_str += BNode.h_code\n repr_str += f\"{self.r}\"\n if self.r_marked and not self.marked:\n repr_str += BNode.o_code\n\n repr_str += \"]\"\n if self.marked:\n repr_str += BNode.o_code\n return repr_str\n\n def __add__(self, other: \"BNode\") -> \"BNode\":\n return BNode(self, other)\n\n\ndef parse(a: str) -> BNode:\n depth = 0\n l_split = \"\"\n r_split = \"\"\n for idx, c in enumerate(a):\n if c == \"[\":\n depth += 1\n continue\n if c == \"]\":\n depth -= 1\n continue\n if c == \",\" and depth == 1:\n l_split = a[1:idx]\n r_split = a[idx + 1 : -1]\n break\n l = \"\"\n r = \"\"\n\n try:\n l = int(l_split)\n except ValueError:\n l = parse(l_split)\n\n try:\n r = int(r_split)\n except ValueError:\n r = parse(r_split)\n\n return BNode(l, r)\n\n\ndef check_explode(a: BNode, depth: int = 0) -> bool:\n if depth >= 4 and isinstance(a.l, int) and isinstance(a.r, int):\n return True\n\n check_l = False\n if isinstance(a.l, BNode):\n check_l = check_explode(a.l, depth + 1)\n if check_l:\n return True\n\n check_r = False\n if isinstance(a.r, BNode):\n check_r = check_explode(a.r, depth + 1)\n if check_r:\n return True\n\n return False\n\n\ndef check_split(a: BNode) -> bool:\n if isinstance(a.l, int):\n if a.l >= 10:\n return True\n else:\n ls = check_split(a.l)\n if ls:\n return True\n\n if isinstance(a.r, int):\n if a.r >= 10:\n return True\n else:\n rs = check_split(a.r)\n if rs:\n return True\n\n return False\n\n\ndef split(a: BNode) -> tuple[BNode, bool]:\n if isinstance(a.l, int):\n if a.l > 9:\n vl = a.l // 2\n vr = a.l - vl\n a.l = BNode(vl, vr)\n a.l.marked = True\n return (a, True)\n\n if isinstance(a.l, BNode):\n _, has_split = split(a.l)\n if has_split:\n return (a, True)\n\n if isinstance(a.r, int):\n if a.r > 9:\n vl = a.r // 2\n vr = a.r - vl\n a.r = BNode(vl, vr)\n a.r.marked = True\n return (a, True)\n\n if isinstance(a.r, BNode):\n _, has_split = split(a.r)\n if has_split:\n return (a, True)\n\n return (a, False)\n\n\ndef explode(a: BNode) -> BNode:\n def get_by_hash(node: BNode, node_hash: str) -> BNode:\n log.debug(f\"\\tsearching for {node_hash}\")\n current = node\n for c in node_hash:\n current = current.l if c == \"l\" else current.r\n return current\n\n def get_next_l(node: BNode, node_hash: str) -> Optional[tuple[int, str]]:\n cs = node_hash\n cs = cs.rstrip(\"l\")\n\n log.debug(f\"\\tget_next_l cs pre strip: {cs}\")\n if len(cs) == 0:\n log.debug(\"\\t\\tcs null\")\n return None\n cs = cs[:-1] + \"l\"\n\n log.debug(f\"\\tget_next_l cs post strip: {cs}\")\n current = get_by_hash(node, cs)\n while not isinstance(current, int):\n log.debug(f\"{current} not int\")\n cs += \"r\"\n\n log.debug(f\"\\tget_next_l cs: {cs}\")\n current = get_by_hash(node, cs)\n return (current, cs)\n\n def get_next_r(node: BNode, node_hash: str) -> Optional[tuple[int, str]]:\n cs = node_hash\n cs = cs.rstrip(\"r\")\n\n log.debug(f\"\\tget_next_r cs pre strip: {cs}\")\n if len(cs) == 0:\n log.debug(\"\\t\\tcs null\")\n return None\n cs = cs[:-1] + \"r\"\n\n log.debug(f\"\\tget_next_r cs post strip: {cs}\")\n current = get_by_hash(node, cs)\n while not isinstance(current, int):\n log.debug(f\"{current} not int\")\n cs += \"l\"\n\n log.debug(f\"\\tget_next_r cs: {cs}\")\n current = get_by_hash(node, cs)\n return (current, cs)\n\n def find_ex_pair(\n node: BNode, node_hash: str, depth: int = 0\n ) -> Optional[tuple[int, int, str]]:\n if depth >= 4:\n log.debug(f\"\\t depht: {depth}, hash: {node_hash} → {node}\")\n if isinstance(node.l, int) and isinstance(node.r, int):\n log.debug(f\"\\t\\tfound explosion pair\")\n return (node.l, node.r, node_hash)\n if isinstance(node.l, BNode):\n l = find_ex_pair(node.l, node_hash + \"l\", depth + 1)\n if l:\n return l\n if isinstance(node.r, BNode):\n r = find_ex_pair(node.r, node_hash + \"r\", depth + 1)\n if r:\n return r\n\n log.debug(\"search for explosion pair\")\n pair = find_ex_pair(a, \"\")\n if pair:\n pl, pr, ploc = pair\n\n log.debug(\"search for l\")\n l = get_next_l(a, ploc)\n if l:\n data, loc = l\n\n log.debug(f\"found l {data} at {loc}\")\n data = data + pl\n log.debug(\"find l parent node\")\n parent_node = get_by_hash(a, loc[:-1])\n if loc[-1] == \"l\":\n parent_node.l = data\n parent_node.l_marked = True\n else:\n parent_node.r = data\n parent_node.r_marked = True\n\n log.debug(\"search for r\")\n r = get_next_r(a, ploc)\n if r:\n data, loc = r\n log.debug(f\"found r {data} at {loc}\")\n data = data + pr\n log.debug(\"find r parent node\")\n parent_node = get_by_hash(a, loc[:-1])\n if loc[-1] == \"l\":\n parent_node.l = data\n parent_node.l_marked = True\n else:\n parent_node.r = data\n parent_node.r_marked = True\n\n log.debug(\"find pair root node\")\n parent_node = get_by_hash(a, ploc[:-1])\n if ploc[-1] == \"l\":\n parent_node.l = 0\n parent_node.l_marked = True\n else:\n parent_node.r = 0\n parent_node.r_marked = True\n\n return a\n\n\ndef read_input() -> list[str]:\n return [str(line.strip()) for line in fileinput.input(\"input.txt\")]\n\n\ndef reduce(node: BNode, add_nr: int) -> BNode:\n\n log.info(f\"\\033[1;31m{node}\\033[0m\")\n exp = check_explode(node)\n spl = check_split(node)\n\n current = node\n i = 0\n last = str(current)\n while exp or spl:\n i += 1\n if exp:\n current = explode(current)\n log.info(f\"{add_nr}.{i}: after explode: {current}\")\n if spl and not exp:\n current, _ = split(current)\n log.info(f\"{add_nr}.{i}: after split: {current}\")\n\n node.unmark()\n exp = check_explode(node)\n spl = check_split(node)\n if last == str(current):\n log.warning(\"No change!\")\n raise ValueError\n\n return current\n\n\ndef main() -> None:\n in_lst = read_input()\n\n acc = parse(in_lst[0])\n for add_nr, line in enumerate(in_lst[1:]):\n cur = parse(line)\n log.info(f\"{acc} + {cur}\")\n a = acc + cur\n log.info(f\"{acc} + {cur} = {a}\")\n acc = reduce(a, add_nr)\n log.info(f\"\\033[1;31m{acc}\\033[0m\")\n\n print(f\"\\033[1;33mSolution {acc.magnitude()}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2021/18/18.1/proto.py","file_name":"proto.py","file_ext":"py","file_size_in_byte":8602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"479947066","text":"import numpy as np\nimport math\n\nfrom Code.learners.Learner import Learner\n\n'''\nUCB learner. Selects arm by creating bounds of range \n(y_ - 1.96 * sigma, y_ + 1.96 * sigma) and taking the arm s.t.\nupper bound is higher. Sigma depends also on number of samples.\n'''\n\n\nclass UCB_Learner(Learner):\n def __init__(self, arms, idx_c, idx_s, sigma, batch_size, window=None):\n name_learner = \"UCB learner\"\n if window is not None:\n name_learner += \" with window {}\".format(window)\n super().__init__(arms=arms, batch_size=batch_size, window=window, idx_c=idx_c, idx_s=idx_s, name_learner=name_learner, sigma=sigma)\n\n self.average_rewards = np.array([float(\"+inf\") for _ in self.arms])# np.zeros(self.n_arms)\n self.delta = np.zeros(self.n_arms)\n\n \"\"\"\n Best arm is the one having higher upper bound\n \"\"\"\n def best_arm(self):\n return np.argmax(self.average_rewards + self.delta)\n\n '''\n Updates Learner observation + average rewards and delta \n '''\n\n def update(self, idx_arm):\n tot_n = len(self.rewards_per_arm[idx_arm])\n N = min(self.compute_current_N(), tot_n)\n windowed_rewards = self.rewards_per_arm[idx_arm][-N:]\n\n self.average_rewards[idx_arm] = np.sum(windowed_rewards) / N\n self.delta[idx_arm] = math.sqrt(2 * math.log(self.t) / N)","sub_path":"learners/UCB_Learner.py","file_name":"UCB_Learner.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"478975792","text":"import re\nimport pickle\n\n#load tables, figures, chapters, and sections from pickled files\ntables = pickle.load(open('table.pkl'))\nfigures = pickle.load(open('figure.pkl'))\nchapters = pickle.load(open('top_sections2.pkl'))\nsections = pickle.load(open('sub_sections.pkl'))\n \n\n#build the lists to loop through and combine all\n#the separate dicitionaries into chapters dictionary\n\nt_keys = tables.keys()\nf_keys = figures.keys()\nc_keys = chapters.keys()\ns_keys = sections.keys()\n\n\nfor chp in c_keys:\n\tfor top_section in chapters[chp]['sections'].keys():\n\t\tfor table in t_keys:\n\t\t\tif re.search(top_section, table):\n\t\t\t\tchapters[chp]['sections'][top_section]['tables'][table] = tables[table]\n\t\tfor figure in f_keys:\n\t\t\tif re.search(top_section, figure):\n\t\t\t\tchapters[chp]['sections'][top_section]['figures'][figure] = figures[figure]\n\t\tfor section in s_keys:\n\t\t\tif re.search(top_section, section):\n\t\t\t\tchapters[chp]['sections'][top_section]['sections'][section] = sections[section]\n\noutput = open('part1.pkl','w')\npickle.dump(chapters,output)\noutput.close()\t\n\n\n\t\t\n\t\t\n\n\n","sub_path":"part1/code_builder_combiner.py","file_name":"code_builder_combiner.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"233551185","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.template import RequestContext\nfrom .models import Institution, Informes, Director\nfrom .forms import InstitucionForm, InformeForm, DirectorForm\n\nfrom django.core.urlresolvers import reverse\n\n@login_required\ndef calendar(request):\n\treturn render(request,'index.html')\n\n@login_required\ndef institucion(request):\n\tinstituciones=Institution.objects.all()\n\tcantidad_registros=instituciones.count()\n\treturn render(request,'informes/institution.html', {\"instituciones\":instituciones, 'cantidad':cantidad_registros})\n\n@login_required\ndef addInstitution(request):\n\tif request.method=='POST':\n\t\tmodelform=InstitucionForm(request.POST)\n\t\tif modelform.is_valid():\n\t\t\tmodelform.save()\n\t\t\treturn redirect(reverse('informes_app:institution'))\n\telse:\n\t\tmodelform=InstitucionForm()\n\n\treturn render(request,'informes/addInstitution.html', {'form':modelform})\n\n@login_required\ndef editInstitution (request, id):\n\tobj_edit=Institution.objects.get(pk=id)\n\tif request.method=='POST':\n\t\tformulario=InstitucionForm(request.POST, instance=obj_edit)\n\t\tif formulario.is_valid():\n\t\t\tformulario.save()\n\t\t\treturn redirect(reverse('informes_app:institution'))\n\telse:\n\t\tformulario=InstitucionForm(instance=obj_edit)\n\treturn render(request,'informes/updInstitution.html', {'form':formulario},context_instance = RequestContext(request))\n\n@login_required\t\ndef deleteInstitution(request, id, template_name='informes/delInstitution.html'):\n obj_delete = Institution.objects.get(pk=id) \n if request.method=='POST':\n obj_delete.delete()\n return redirect(reverse('informes_app:institution'))\n return render(request, template_name, {'object':obj_delete})\n\n# informes\n@login_required\ndef informes(request):\n\tobj_inf=Informes.objects.all()\n\tcantidad=obj_inf.count()\n\treturn render(request,'informes/informes.html', {\"informes\":obj_inf, 'cantidad':cantidad})\n\n@login_required\ndef addInforme(request):\n\tif request.method=='POST':\n\t\tmodelform=InformeForm(request.POST,request.FILES)\n\t\tif modelform.is_valid():\n\t\t\t# modelform=Informes()\n\t\t\tmodelform.save()\n\t\t\treturn redirect(reverse('informes_app:informe'))\n\telse:\n\t\tmodelform=InformeForm()\n\treturn render(request,'informes/addInforme.html',{'form':modelform})\n\n@login_required\ndef updateInforme (request, id):\n\tobj_update=Informes.objects.get(pk=id)\n\tif request.method=='POST':\n\t\tmodelform=InformeForm(request.POST, request.FILES, instance=obj_update) #ojo\n\t\tif modelform.is_valid():\n\t\t\tmodelform.save()\n\t\t\treturn redirect(reverse('informes_app:informe'))\n\telse:\n\t\tmodelform=InformeForm(instance=obj_update)\n\treturn render(request,'informes/updInforme.html', {'form':modelform},context_instance = RequestContext(request))\n\n@login_required\ndef deleteInforme(request, id, template_name='informes/delInforme.html'):\n obj_delete = Informes.objects.get(pk=id) \n if request.method=='POST':\n obj_delete.delete()\n return redirect(reverse('informes_app:informe'))\n return render(request, template_name, {'object':obj_delete})\n\n\n# director\n@login_required\ndef director(request):\n\tobj_dir=Director.objects.all()\n\tcantidad=obj_dir.count()\n\treturn render(request,'informes/director.html', {\"manager\":obj_dir, 'cantidad':cantidad})\n\n@login_required\ndef addDirector(request):\n\tif request.method=='POST':\n\t\tmodelform=DirectorForm(request.POST)\n\t\tif modelform.is_valid():\n\t\t\tmodelform.save()\n\t\t\treturn redirect(reverse('informes_app:director'))\n\telse:\n\t\tmodelform=DirectorForm()\n\treturn render(request,'informes/addDirector.html',{'form':modelform})\n\n@login_required\ndef updDirector (request, id):\n\tobj_update=Director.objects.get(pk=id)\n\tif request.method=='POST':\n\t\tmodelform=DirectorForm(request.POST, instance=obj_update)\n\t\tif modelform.is_valid():\n\t\t\tmodelform.save()\n\t\t\treturn redirect(reverse('informes_app:director'))\n\telse:\n\t\tmodelform=DirectorForm(instance=obj_update)\n\treturn render(request,'informes/updDirector.html', {'form':modelform},context_instance = RequestContext(request))\n\n@login_required\ndef delDirector(request, id, template_name='informes/delDirector.html'):\n obj_delete = Director.objects.get(pk=id) \n if request.method=='POST':\n obj_delete.delete()\n return redirect(reverse('informes_app:director'))\n return render(request, template_name, {'object':obj_delete})","sub_path":"apps/informes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"87651768","text":"class Node:\n def __init__(self, data=None):\n self.data = data\n self.next = None\n \nclass Hash:\n def __init__(self):\n node0 = Node()\n node1 = Node()\n node2 = Node()\n node3 = Node()\n node4 = Node()\n node5 = Node()\n node6 = Node()\n node7 = Node()\n node8 = Node()\n node9 = Node()\n node10 = Node()\n\n self.arr= [node0,node1,node2,node3,node4,node5,node6,node7,node8,node8,node9,node10]\n\n def insert(self,value):\n n = Node(value) #create a node \n res = int(value.data%11) #calc hash value\n node = self.arr[res] #node var points to array index\n if node is None:\n node = n\n else:\n ptr = self.arr[res]\n while ptr.next is not None: #traversing to end element in link\n ptr = ptr.next \n ptr.next = n #storing node in last position of hash index\n\n def display(self):\n res = None\n for i in range(len(self.arr)):\n print(\"Remainder\", i ,\"has following values\",end=\" \") \n ptr = self.arr[i]\n if ptr == None: #Hash value has no data\n print(\"None\")\n else: \n while ptr.next != None: \n print(ptr.data , end=\",\") #print all values in that hash position\n ptr = ptr.next\n print(ptr.data)\n print()\n\nhash = Hash()\nans = int(input(\"Enter the number of values\"))\nprint(\"Enter \",ans,\" value\")\nfor i in range(ans):\n val = int(input())\n n = Node(val)\n hash.insert(n)\nhash.display()\n\n\n\n\n\n","sub_path":"Week2/hashing.py","file_name":"hashing.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"559770213","text":"#! /usr/bin/python\n\n# Author: VIKASH KUMAR PATEL\n\n# Time-Complexity: O(N*Q*log(N))\n\n# Where, N is number of images\n\n# Q is number of POIs\n\n# To extract co-ordinate, we will use a tool--> parser from library pymkl\n\nfrom pykml import parser\n\nfrom os import path\n\nimport math\n\n# defining a function which gives us distance between to points in space.\n\ndef Distance_cal(lati1,long1,lati2,long2):\n\n # R is radius of Earth\n\n R = 6371000\n\n # Getting values of Lattitude and Longitude in rad.\n\n radLati = ((math.pi)*(lati2-lati1))/180\n\n radLong = (math.pi*(long2-long1))/180\n\n # Calculating distance between two points in space by Haversine formula.\n\n # Refer to: https://www.movable-type.co.uk/scripts/latlong.html\n\n a = math.sin(radLati/2) * math.sin(radLati/2)\n + math.cos((math.pi*(lati1))/180)*math.cos((math.pi*(lati2))/180) * math.sin(radLong/2) * math.sin(radLong/2)\n \n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))\n\n d = R * c\n\n # returning distance\n return d;\n\n# Opening input file\n\nfile_object = open('assets.csv','r')\n\n# Creating another asset file to write\n\nfile_object1 = open('Answer.csv','w')\n\n\n# Reading file_object\n\ndata = file_object.read()\n\nList = data.split(\"\\n\")\n\nList_size = len(List)\n\n# Here we can change the value of POIs and Images\n\n# In this case we have given Distance = 50\n\nDistance = 50\n\ncnt = 0\n\nmylist = []\n\nvarr = List[0].split(\",\")\n\nfile_object1.write(varr[0]+\",\"+varr[2]+\",\"+varr[1]+\",\"+varr[3]+\"\\n\")\n\n# Iterating through all given POIs\n\nfor i in range(1,List_size):\n\n v_point = List[i].split(\",\")\n\n kml_file = path.join('doc.kml')\n\n with open(kml_file) as f:\n docc = parser.parse(f).getroot()\n\n for it in docc.Document.Placemark:\n\n co_or = it.Point.coordinates.text.split(',')\n\n # Check whether Images are in range of POIs Or not. \n\n if Distance_cal((float)(v_point[1]),(float)(v_point[2]),(float)(co_or[0]),(float)(co_or[1])) <= Distance:\n \n co_or = it.description.text\n\n mylist.append(co_or)\n\n # Write POIs ,latitude and Longitude.\n\n file_object1.write(List[i]+\"\\n\")\n\n for ip in mylist:\n\n file_object1.write(\",,,\"+ip+\"\\n\")\n\n # Clear List\n\n mylist[:] = []\n\nfile_object1.close()\nfile_object.close()\n","sub_path":"project2/Skylark_POI.py","file_name":"Skylark_POI.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"341421892","text":"#\n# Hello World client in Python\n# Connects REQ socket to tcp://localhost:5555\n# Sends \"Hello\" to server, expects \"World\" back\n#\n\nimport zmq\n\ncontext = zmq.Context()\n\n# Socket to talk to server\nsocket = context.socket(zmq.PAIR)\nsocket.connect(\"tcp://localhost:9876\")\n\n# Do 10 requests, waiting each time for a response\n#for request in range(100):\nwhile True:\n # Get the reply.\n message = socket.recv()\n print(\"Received [ %s ]\" % (message))\n","sub_path":"testing_and_examples/client_1.py","file_name":"client_1.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"85852134","text":"from typing import List\n\nfrom jasmin_builder.instruction import Instruction\n\n# ACC_PUBLIC\t0x0001\tDeclared public; may be accessed from outside its package.\n# ACC_PRIVATE\t0x0002\n# Declared private; accessible only within the defining class and other classes belonging to the same nest (§5.4.4).\n#\n# ACC_PROTECTED\t0x0004\tDeclared protected; may be accessed within subclasses.\n# ACC_STATIC\t0x0008\tDeclared static.\n# ACC_FINAL\t0x0010\tDeclared final; must not be overridden (§5.4.5).\n# ACC_SYNCHRONIZED\t0x0020\tDeclared synchronized; invocation is wrapped by a monitor use.\n# ACC_BRIDGE\t0x0040\tA bridge method, generated by the compiler.\n# ACC_VARARGS\t0x0080\tDeclared with variable number of arguments.\n# ACC_NATIVE\t0x0100\tDeclared native; implemented in a language other than the Java programming language.\n# ACC_ABSTRACT\t0x0400\tDeclared abstract; no implementation is provided.\n# ACC_STRICT\t0x0800\tDeclared strictfp; floating-point mode is FP-strict.\n# ACC_SYNTHETIC\t0x1000\tDeclared synthetic; not present in the source code.\nMOD_PUBLIC = \"public\"\nMOD_PRIVATE = \"private\"\nMOD_PROTECTED = \"protected\"\nMOD_STATIC = \"static\"\nMOD_FINAL = \"final\"\nMOD_SYNCHRONIZED = \"synchronized\"\nMOD_BRIDGE = \"bridge\"\nMOD_VARARGS = \"varargs\"\nMOD_NATIVE = \"native\"\nMOD_ABSTRACT = \"abstract\"\nMOD_STRICTFP = \"strictfp\"\nMOD_SYNTHETIC = \"synthetic\"\n\nMODIFIER_LIST = [MOD_PUBLIC, MOD_PRIVATE, MOD_PROTECTED, MOD_STATIC, MOD_FINAL, MOD_SYNCHRONIZED, MOD_BRIDGE,\n MOD_VARARGS, MOD_NATIVE, MOD_ABSTRACT, MOD_STRICTFP, MOD_SYNTHETIC]\n\n\nclass Method:\n instructions = [] # type: List[Instruction]\n name = ''\n modifiers = [] # type: List[str]\n args = []\n stack_limit = -1\n locals_limit = -1\n cls = None\n ret = ''\n\n def __init__(self, name: str, args: List, modifiers: List[str], return_: str = \"V\", stack_limit: int = -1,\n locals_limit: int = -1):\n self.name = name\n self.args = args\n self.modifiers = modifiers\n for i in self.modifiers:\n assert i in MODIFIER_LIST, \"Invalid modifier: \" + i\n self.stack_limit = stack_limit\n self.locals_limit = locals_limit\n self.instructions = []\n self.ret = return_\n\n def add_modifier(self, mod: str):\n assert mod in MODIFIER_LIST, \"Invalid modifier: \" + mod\n self.modifiers.append(mod)\n\n def insert_instructon(self, instr, label=\"\"):\n instr.label = label\n self.instructions.append(instr)\n\n def format_args(self):\n return \"\".join(map(str, self.args))\n\n def __str__(self):\n return f\".method {' '.join(self.modifiers)} {self.name}({self.format_args()}){self.ret}\\n\" + \\\n (f\"\\t.limit stack {self.stack_limit}\\n\" if self.stack_limit != -1 else '') + \\\n (f\"\\t.limit locals {self.locals_limit}\\n\" if self.locals_limit != -1 else '') + \\\n \"\".join([str(instr) for instr in self.instructions]) + \\\n \".end method\"\n","sub_path":"jasmin_builder/method.py","file_name":"method.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"270032719","text":"tc = int(input())\n\nfor x in range(tc):\n\ta,b,c,d = map(str, input().split()) # ingredients for first dish\n\tp,q,r,s = map(str, input().split()) # ingredients for first dish\n\n\td1 = [a,b,c,d] # dish one\n\td2 = [p,q,r,s] # dish two\n\n\tz = set(d1) & set(d2) # intersection of d1 and d2\n\n\tif len(list(z)) >= 2:\n\t\tprint(\"similar\")\n\telse:\n\t\tprint(\"dissimilar\")\n","sub_path":"practice/SIMDISH.py","file_name":"SIMDISH.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"652466784","text":"\n#-- UI lib imports\nimport tkinter as tk\nimport tkinter.font\nfrom tkinter import messagebox\n\n#-- Utils\nimport platform\nimport threading\n\n#-- Celer libs\nfrom encrypt import *\n\n\n#--------#\n# Colors #\n#--------#\n\nBACKGROUND = \"#2d2e38\"\nFOREGROUND = \"#ffffff\"\nSV_LIST = \"#5e72a1\"\nTEXT_ENTRY = \"#45485b\"\n\n\n# A scrollable Frame\nclass ScrollableFrame(tk.Frame):\n\tdef __init__(self, container, *args, **kwargs):\n\t\tsuper().__init__(container, *args, **kwargs)\n\t\tself.canvas = tk.Canvas(self, bg = SV_LIST)\n\t\tscrollbar = tk.Scrollbar(self, orient = \"vertical\", command = self.canvas.yview)\n\t\tself.scrollable_frame = tk.Canvas(self.canvas)\n\n\t\tself.scrollable_frame.bind(\n\t\t\t\"\",\n\t\t\tlambda e: self.canvas.configure(\n\t\t\t\tscrollregion=self.canvas.bbox(\"all\")\n\t\t\t)\n\t\t)\n\t\t\n\t\t#self.scrollable_frame.pack(fill = \"both\", expand = True)\n\t\tself.canvas.create_window((0, 0), window = self.scrollable_frame, anchor = \"nw\")\n\t\tself.canvas.configure(yscrollcommand = scrollbar.set)\n\t\t\n\t\tscrollbar.pack(side = \"left\", fill = \"y\")\n\t\tself.canvas.pack(side = \"left\", fill = \"both\", expand=True)\n\n\tdef clear(self):\n\t\t# Destroying and recreating the canvas\n\t\tself.scrollable_frame.destroy()\n\n\t\tself.scrollable_frame = tk.Canvas(self.canvas)\n\t\tself.scrollable_frame.bind(\n\t\t\t\"\",\n\t\t\tlambda e: self.canvas.configure(\n\t\t\t\tscrollregion=self.canvas.bbox(\"all\")\n\t\t\t)\n\t\t)\n\n\t\tself.canvas.create_window((0, 0), window = self.scrollable_frame, anchor = \"nw\")\n\n\nclass Celer:\n\tdef __init__(self, user, network):\n\t\tself.user = user\n\t\tself.network = network\n\t\tself.running = True\n\t\n\t\tself.labels = []\n\n\t\t#-- User datas\n\t\tself.key = None\t\t\t# Key of the server we currently are\n\t\tself.sv_code = None\t\t# Key of the server when we look in sv info\n\t\tself.server_list = []\n\t\n\t\t#-- Calling startup functions\n\t\tself.__setup_window()\t\n\n\t\t#-- Fonts\n\t\tself.font = tk.font.Font(family = 'Bahnschrift Light', size = 15)\n\t\tself.font_2 = tk.font.Font(family = \"Bahnschrift Light\", size = 10)\n\n\tdef __setup_window(self):\t\n\t\t#-- Settingup window\n\t\tself.root = tk.Tk()\n\t\t\n\t\t#Checks for the type of the os for fullscreen\n\t\tif platform.system() == \"Linux\":\n\t\t\tself.root.attributes('-zoomed', True)\n\t\telif platform.system() == \"Windows\":\n\t\t\tself.root.state(\"zoomed\")\t\n\t\t\n\t\tself.canvas = tk.Canvas(self.root, bg = BACKGROUND)\n\t\tself.canvas.pack(fill = \"both\", expand = True)\n\n\t#----------------#\n\t# Event Handlers #\n\t#----------------#\n\n\tdef __create_sv_ui(self):\n\t\tself.create_sv_window = tk.Toplevel(self.canvas)\n\t\t\n\t\t# Settings for window\n\t\tself.create_sv_window.resizable(False, False)\n\t\tself.create_sv_window.title(\"Create Server\")\n\t\tself.create_sv_window.geometry(\"390x180\")\n\n\t\t# Adding widgets\n\t\tlabel = tk.Label(self.create_sv_window, text = 'Server Name', font = self.font_2)\n\t\tlabel.place(x = 45, y = 65)\n\n\t\tself.sv_name_entry = tk.Entry(self.create_sv_window, width = 20, font = self.font)\n\t\tself.sv_name_entry.place(relx = 0.1, rely = 0.5, relwidth = 0.8, relheight = 0.2)\n\n\t\tself.sv_name_entry.bind(\"\", self.__create_sv)\n\n\tdef __get_join_data(self, e):\n\t\tsv_code = self.sv_key_entry.get()\n\t\tself.__join_sv(sv_code)\n\t\tself.join_sv_window.destroy()\n\n\tdef __join_sv_ui(self):\t\t\n\t\tself.join_sv_window = tk.Toplevel(self.canvas)\n\n\t\t# Setting up window\n\t\tself.join_sv_window.resizable(False, False)\n\t\tself.join_sv_window.title(\"Join Server\")\n\t\tself.join_sv_window.geometry(\"390x180\")\n\n\t\t# Adding widgets\n\t\tlabel = tk.Label(self.join_sv_window, text = 'Server Key', font = self.font_2)\n\t\tlabel.place(x = 45, y = 65)\n\n\t\tself.sv_key_entry = tk.Entry(self.join_sv_window, width = 20, font = self.font)\n\t\tself.sv_key_entry.place(relx = 0.1, rely = 0.5, relwidth = 0.8, relheight = 0.2)\n\n\t\tself.sv_key_entry.bind(\"\", self.__get_join_data)\n\t\t\n\tdef __add_button_popup(self):\n\t\t# Displays the selection between create or join server\n\t\t\n\t\tx = self.root.winfo_pointerx()\n\t\ty = self.root.winfo_pointery()\n\n\t\tself.popup_1 = tk.Menu(self.canvas, tearoff = 0)\n\n\t\tself.popup_1.add_command(label = \"Create server\", command = self.__create_sv_ui)\n\t\tself.popup_1.add_command(label = \"Join server\" , command = self.__join_sv_ui)\n\n\t\tself.popup_1.tk_popup(x, y, 0)\n\n\tdef __show_sv_info(self, e):\n\t\t# Shows some information about the server u just selected\n\n\t\tlabel = e.widget\n\t\tsv_id = label.cget(\"text\").split(\":\")[0]\n\t\tself.sv_code = self.server_list[int(sv_id)][0]\t\n\n\t\tx = self.root.winfo_pointerx()\n\t\ty = self.root.winfo_pointery()\n\n\t\tself.popup_2 = tk.Menu(self.canvas, tearoff = 0)\n\n\t\tself.popup_2.add_command(label = self.sv_code)\n\t\tself.popup_2.add_command(label = \"Leave server\", command = self.__leave_server)\n\t\n\t\tself.popup_2.tk_popup(x, y, 0)\n\n\n\t#-------------#\n\t# Ui Elements #\n\t#-------------#\n\n\tdef __draw_sv_list(self):\n\t\tself.sv_list = ScrollableFrame(self.canvas)\n\t\tself.sv_list.config(width = 10)\n\t\tself.sv_list.place(relx = 0.02, rely = 0.13, relwidth = 0.052, relheight = 0.85)\n\n\tdef __draw_chat_box(self):\n\t\tself.chat_box = tk.Text(self.canvas, bg = BACKGROUND, fg = FOREGROUND)\n\t\t#self.chat_box.place(relx = 0.1, rely = 0.13, relwidth = 0.75, relheight = 0.78)\n\t\tself.chat_box.configure(state = \"disabled\")\n\n\tdef __draw_text_entry(self):\n\t\tself.text_entry = tk.Entry(self.canvas, bg = TEXT_ENTRY, fg = FOREGROUND)\n\t\t#self.text_entry.place(relx = 0.1, rely = 0.93, relwidth = 0.75, relheight = 0.05)\n\t\tself.text_entry.bind(\"\", self.__send_msg)\n\n\tdef __draw_member_list(self):\n\t\t#[TODO] make a member list\n\t\tpass\n\n\tdef __add_button(self):\n\t\tself.add_button = tk.Button(self.canvas, text = \"+\", command = self.__add_button_popup)\n\t\tself.add_button.place(relx = 0.02, rely = 0.05, relwidth = 0.052, relheight = 0.05)\n\t\t\n\n\t#------------#\n\t# Networking #\n\t#------------#\n\n\tdef __create_sv(self, e):\n\t\tif e != \"retry\":\n\t\t\tself.sv_name = self.sv_name_entry.get()\n\t\t\tself.create_sv_window.destroy()\n\t\t\n\t\t# Sending the server the info about creating a server\n\t\ttoken = \"[NEW_SV]\"\n\t\tself.key = generate_key()\n\t\tinfo = f\"{token} key:{self.key} name:{self.sv_name}\"\n\t\tself.network.send(info)\n\n\tdef __join_sv(self, key):\t\n\t\t# Sending the server the info about joining a server\n\t\ttoken = \"[JOIN]\"\n\t\tinfo = f\"{token} name:{self.user} key:{key}\"\n\t\tself.network.send(info)\n\n\tdef __leave_server(self):\n\t\ttoken = \"[LEAVE]\"\n\t\tinfo = f\"{token} username:{self.user} key:{self.sv_code}\"\n\t\tself.network.send(info)\n\n\t\t# Reseting the key\n\t\tif self.key == self.sv_code:\n\t\t\tself.key == None\n\n\tdef __select_server(self, e):\n\t\tfor i in self.labels:\n\t\t\ti.configure(bg = \"white\")\n\n\t\tlabel = e.widget\n\t\tlabel.configure(bg = TEXT_ENTRY)\n\t\tsv_id = label.cget(\"text\").split(\":\")[0]\n\t\tself.key = self.server_list[int(sv_id)][0]\t\n\t\t\n\t\t# Sending the server which server I selected\n\t\ttoken = \"[SELECT]\"\n\t\tinfo = f\"{token} {self.key}\"\n\n\t\tself.network.send(info)\n\t\t\n\t\t# Redrawing the chatbox and text entry\n\t\tself.chat_box.place(relx = 0.1, rely = 0.13, relwidth = 0.75, relheight = 0.78)\n\t\tself.text_entry.place(relx = 0.1, rely = 0.93, relwidth = 0.75, relheight = 0.05)\n\t\t\n\t\tself.chat_box.config(state = \"normal\")\n\t\tself.chat_box.delete(\"1.0\", \"end\")\n\t\tself.chat_box.config(state = \"disabled\")\n\n\tdef __send_msg(self, e):\n\t\tif self.key:\t# Only if we have selected a server\n\t\t\tmsg = self.text_entry.get()\n\t\t\tif msg != \"\":\n\t\t\t\t# Clearing the text entry\n\t\t\t\tself.text_entry.delete(0, \"end\")\n\n\t\t\t\t# Sending the encrypted msg to server\n\t\t\t\ttoken = \"[MSG]\"\n\t\t\t\tenc_msg = encrypt(f\"[{self.user}]: {msg}\\n\", self.key)\n\t\t\t\tinfo = f\"{token} {enc_msg}\"\n\t\t\t\tself.network.send(info)\n\n\tdef __receiver(self):\n\t\t# Listens for the upcoming data from the server\n\n\t\twhile self.running:\n\t\t\trecv_info = self.network.recv()\n\t\t\ttokens = recv_info.split(\" \")\n\n\t\t\tif tokens[0] == \"[DISCONNECT]\":\n\t\t\t\tself.running = False\n\n\t\t\telif tokens[0] == \"[SERVER]\":\n\t\t\t\ttokens.pop(0)\n\t\t\t\t\n\t\t\t\t# Resetting\n\t\t\t\tself.key = None\n\t\t\t\tself.chat_box.place_forget()\n\t\t\t\tself.text_entry.place_forget()\n\n\t\t\t\t# Refreshing client side server storage\n\t\t\t\tself.server_list.clear()\n\t\t\t\tfor i in tokens:\n\t\t\t\t\tkey = i.split(\":\")[0]\n\t\t\t\t\tname = i.split(\":\")[1]\n\t\t\t\t\tself.server_list.append((key, name))\n\n\t\t\t\t# Pushing server names\n\t\t\t\tself.sv_list.clear()\n\t\t\t\tself.labels.clear()\n\n\t\t\t\tfor n, i in enumerate(tokens):\n\t\t\t\t\tserver = i.split(\":\")\n\t\t\t\t\tname = server[1]\n\t\t\t\t\n\t\t\t\t\tif len(name) > 1:\n\t\t\t\t\t\tnew_name = str(n) + \":\" + name[0] + name[1]\n\t\t\t\t\telse:\n\t\t\t\t\t\tnew_name = str(n) + \":\" + name[0]\n\n\t\t\t\t\tlabel = tk.Label(self.sv_list.scrollable_frame, text = new_name, bg = \"white\", width=4, height=2, borderwidth=1, relief=\"solid\", font=self.font)\n\t\t\t\t\tlabel.pack(side = \"top\", fill = \"x\", expand = True)\n\t\t\t\t\tlabel.bind(\"\", self.__select_server)\n\t\t\t\t\tlabel.bind(\"\", self.__show_sv_info)\n\n\t\t\t\t\tself.labels.append(label)\n\n\t\t\t# When it catches a msg\n\t\t\telif tokens[0] == \"[MSG]\":\n\t\t\t\tif len(tokens) > 1:\n\t\t\t\t\tself.chat_box.config(state = \"normal\")\n\n\t\t\t\t\ttokens.pop(0)\n\t\t\t\t\tenc_msg = \" \".join(tokens)\n\t\t\t\t\tdec_msg = decrypt(enc_msg, self.key)\n\t\t\t\t\tself.chat_box.insert(\"end\", dec_msg)\n\t\t\t\t\t\n\t\t\t\t\tself.chat_box.see(\"end\")\n\t\t\t\t\tself.chat_box.config(state = \"disabled\")\n\t\t\n\t\t\t# When server creation failed\n\t\t\telif tokens[0] == \"[REJECTED]\":\n\t\t\t\tself.__create_sv(\"retry\")\t\n\t\t\telif tokens[0] == \"[ACCEPTED]\":\n\t\t\t\tself.__join_sv(self.key)\n\n\tdef __launch_reciver(self):\n\t\trecv_thread = threading.Thread(target = self.__receiver)\n\t\trecv_thread.start()\n\n\t#------#\n\t# Main #\n\t#------#\n\n\tdef __render(self):\n\t\tself.__draw_sv_list()\n\t\tself.__draw_chat_box()\n\t\tself.__draw_text_entry()\n\t\tself.__add_button()\n\n\tdef run(self):\n\t\tself.__render()\n\t\tself.__launch_reciver()\n\t\tself.root.mainloop()\n\n\n","sub_path":"App/celer.py","file_name":"celer.py","file_ext":"py","file_size_in_byte":9490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"269532101","text":"__author__ = 'Scott'\nimport pandas as pd\nimport xlrd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('ggplot')\n\n# from matplotlib import rcParams\n# rcParams['figure.dpi'] = 300\n\ndef import_data():\n \"\"\"\n imports data from the files.\n :return:\n \"\"\"\n src_prep_files = [ \"S:\\Team CG\\SRC Run Results\\Tool 3 SRC Coils-sd.xlsx\",\n \"S:\\Team CG\\SRC Run Results\\Tool 4 SRC Coils-sd.xlsx\",\n \"S:\\Team CG\\SRC Run Results\\Tool 6 SRC Coils-sd.xlsx\",\n \"S:\\Team CG\\SRC Run Results\\Tool 09 SRC Coils-sd.xlsx\",\n \"S:\\Team CG\\SRC Run Results\\Tool 11 SRC Coils-sd.xlsx\"\n ]\n src_prep_sheets = ['SRC3', 'SRC4', 'SRC6', 'SRC9', 'SRC11']\n\n # the zero based columns to import from the \"Tool X SRC Coil.xlsx\" spreadsheet\n src_cols = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\n\n cg_schedule = \"S:\\Team CG\\CG Schedule 2015.xls\"\n cg_sheets = [\"AlN3\", \"AlN4\", \"AlN6\", \"AlN9\", \"AlN11\"]\n\n # These are the column numbers to import for each sheet in the\n # \"CG schedule 2015.xlsx\" file\n cg_cols = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17],\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17],\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17],\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17]]\n\n # the row at which to begin importing data\n rows_skip = [62,0,0,0,0]\n\n # this is a map of the datatypes for each column\n src_df_datatypes = {'Reactor' : int,\n 'Temp' : int,\n 'Coil Height' : int,\n 'Crucible Mk' : float,\n 'Crucible Ht' : float,\n 'Crucible Parts' : int,\n 'Packed Wt' : int,\n 'Susceptor Mk' : int,\n 'Crucible Wall Thickness' : float,\n 'Duration' : int,\n 'Mandrel' : float,\n 'Foil Mat' : str,\n 'Broken Btm Foil': bool,\n 'Source Ht' : int,\n 'Source Wt' : int,\n 'Flip' : str,\n 'Pwr Out (w)' : int\n }\n\n src_prep_dfs = []\n\n for sheet, file in zip(cg_sheets, src_prep_files):\n src_prep_dfs.append(pd.io.excel.read_excel(file, sheetname=sheet,\n index_col=0,\n parse_cols=src_cols,\n engine='xlrd',))\n\n # Prepare the large dataframe from all the src prep files that Tanya keeps.\n src_df = pd.concat(src_prep_dfs)\n src_df.dropna(axis=0,how='all', inplace=True)\n src_df['Run_Number'] = src_df.index\n src_df['Reactor'] = src_df['Run_Number'].str[:2]\n src_df['Reactor'] = src_df['Reactor'].astype(int)\n src_df = src_df.drop(['Foil Mat', 'Packed Wt', 'Broken Btm Foil'], axis=1)\n\n src_df = src_df.convert_objects(convert_numeric=True)\n\n cg_schedules = []\n for sheet, cols, rows in zip(cg_sheets, cg_cols, rows_skip):\n xls = pd.ExcelFile(cg_schedule)\n cg_schedules.append(xls.parse(sheetname=sheet,\n index_col=1,\n skiprows=rows,\n engine='xlrd',\n parse_cols=cols,\n ))\n\n cg_df = pd.concat(cg_schedules)\n\n # combine the columns that all refer to the crucible parts weight\n cg_df['Crucible Total Weight'].fillna(cg_df['Crucible Parts Set Total Weight'], inplace=True)\n cg_df['Crucible Total Weight'].fillna(cg_df['Crucible Parts Total Weight'], inplace=True)\n cg_df = cg_df.drop(['Crucible Parts Set Total Weight'], axis=1)\n cg_df = cg_df.drop(['Crucible Parts Total Weight'], axis=1)\n\n # drop the nan indexes\n cg_df = cg_df.reset_index()\n cg_df = cg_df.dropna(subset=['Run']).set_index('Run')\n cg_df = cg_df[cg_df.index != 'Holiday Shutdown']\n print(cg_df.head())\n\n\n\n\ndef create_plots():\n \"\"\"\n Creates plots from imported Source Prep Data\n :return:\n \"\"\"\n\n # src_df['Source Height'] = src_df['Source Height'].str[:]\n\n # fig = plt.figure(figsize=(12,12))\n # ax = fig.add_subplot(111)\n # ax.grid(False)\n # ax.set_frame_on(False)\n # ax.lines[0].set_visible(False)\n\n # spm = pd.scatter_matrix(src_df,\n # alpha=0.2,\n # figsize=(12,12),\n # diagonal='kde')\n\n flier_props = {'color':'g', 'marker':'o'}\n\n\n src_wt_df = src_df[['Crucible Mk', 'Source Weight', 'Reactor']].dropna(subset=['Source Weight'])\n print('df len is:',len(src_wt_df))\n print(src_wt_df)\n src_wt_mk2_df = src_df.loc[src_wt_df['Crucible Mk'] == 2.0]\n\n ax1 = src_wt_mk2_df.boxplot(column=['Source Weight'],\n by=['Reactor'],\n positions=src_wt_mk2_df['Reactor'].dropna().unique(),\n showmeans=True,\n figsize=(10,8),\n flierprops=flier_props)\n\n for i in src_wt_mk2_df['Reactor'].unique():\n y = src_wt_mk2_df['Source Weight'].loc[src_wt_mk2_df['Reactor'] == i].values\n x = np.random.normal(i, 0.04, size=len(y))\n plt.plot(x,y,'r.',alpha=.5)\n\n plt.show()\n src_ht_df = src_df[['Source Height', 'Reactor']].dropna()\n # print('reactor data type:', type(src_ht_df['Reactor'][0]))\n # print('source height data type:', type(src_ht_df['Source Height'][0]))\n\n bp = src_ht_df.boxplot(column=['Source Height'],\n by=['Reactor'],\n figsize= (10,8),\n positions=src_df['Reactor'].dropna().unique(),\n showmeans=True,\n flierprops=flier_props)\n\n total_x = 0\n total_y = 0\n for i in src_ht_df['Reactor'].unique():\n y = src_ht_df['Source Height'].loc[src_ht_df['Reactor'] == i].values\n total_y += len(y)\n x = np.random.normal(i, 0.04, size=len(y))\n total_x += len(x)\n # print('{:4d}, {:4d}, {:4d}, {:4d}'.format(len(x), total_x, len(y), total_y))\n # print(x,y)\n plt.plot(x,y,'r.',alpha=0.2)\n\n\n plt.show()\n # plt.tight_layout()\n\n # plt.savefig(r\"src_prep_scatter_matrix.png\")\n\nimport_data()","sub_path":"source_prep_analysis.py","file_name":"source_prep_analysis.py","file_ext":"py","file_size_in_byte":6604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"335575904","text":"import os\nimport time\nimport numpy as np\n\nfrom astromodels import ModelAssertionViolation, use_astromodels_memoization\nfrom threeML.bayesian.sampler_base import UnitCubeSampler\nfrom threeML.config.config import threeML_config\nfrom threeML.io.logging import setup_logger\nimport logging\n\n\ntry:\n\n import ultranest\n\nexcept:\n\n has_ultranest = False\n\nelse:\n\n has_ultranest = True\n\n\ntry:\n\n # see if we have mpi and/or are using parallel\n\n from mpi4py import MPI\n\n if MPI.COMM_WORLD.Get_size() > 1: # need parallel capabilities\n using_mpi = True\n\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n\n else:\n\n using_mpi = False\nexcept:\n\n using_mpi = False\n\n\nun_logger = logging.getLogger(\"ultranest\")\nun_logger.propagate = False\n \nlog = setup_logger(__name__)\n\nclass UltraNestSampler(UnitCubeSampler):\n def __init__(self, likelihood_model=None, data_list=None, **kwargs):\n\n assert has_ultranest, \"You must install UltraNest to use this sampler\"\n\n super(UltraNestSampler, self).__init__(likelihood_model, data_list, **kwargs)\n\n def setup(\n self,\n min_num_live_points=400,\n dlogz=0.5,\n chain_name=None,\n wrapped_params=None,\n **kwargs\n ):\n log.debug(f\"Setup for UltraNest sampler: min_num_live_points:{min_num_live_points}, \"\\\n f\"chain_name:{chain_name}, dlogz: {dlogz}, wrapped_params: {wrapped_params}. \"\\\n f\"Other input: {kwargs}\")\n self._kwargs = {}\n self._kwargs[\"min_num_live_points\"] = min_num_live_points\n self._kwargs[\"dlogz\"] = dlogz\n self._kwargs[\"chain_name\"] = chain_name\n\n self._wrapped_params = wrapped_params\n\n for k, v in kwargs.items():\n\n self._kwargs[k] = v\n\n self._is_setup = True\n\n def sample(self, quiet=False):\n \"\"\"\n sample using the UltraNest numerical integration method\n :rtype: \n\n :returns: \n\n \"\"\"\n if not self._is_setup:\n\n log.info(\"You forgot to setup the sampler!\")\n return\n\n loud = not quiet\n\n self._update_free_parameters()\n\n param_names = list(self._free_parameters.keys())\n\n n_dim = len(param_names)\n\n loglike, ultranest_prior = self._construct_unitcube_posterior(return_copy=True)\n\n # We need to check if the MCMC\n # chains will have a place on\n # the disk to write and if not,\n # create one\n\n chain_name = self._kwargs.pop(\"chain_name\")\n if chain_name is not None:\n mcmc_chains_out_dir = \"\"\n tmp = chain_name.split(\"/\")\n for s in tmp[:-1]:\n mcmc_chains_out_dir += s + \"/\"\n\n if using_mpi:\n\n # if we are running in parallel and this is not the\n # first engine, then we want to wait and let everything finish\n\n if rank != 0:\n\n # let these guys take a break\n time.sleep(1)\n\n else:\n\n # create mcmc chains directory only on first engine\n\n if not os.path.exists(mcmc_chains_out_dir):\n log.debug(f\"Create {mcmc_chains_out_dir} for ultranest output\")\n os.makedirs(mcmc_chains_out_dir)\n\n else:\n\n if not os.path.exists(mcmc_chains_out_dir):\n log.debug(f\"Create {mcmc_chains_out_dir} for ultranest output\")\n os.makedirs(mcmc_chains_out_dir)\n\n # Multinest must be run parallel via an external method\n # see the demo in the examples folder!!\n\n if threeML_config[\"parallel\"][\"use-parallel\"]:\n\n raise RuntimeError(\n \"If you want to run ultranest in parallell you need to use an ad-hoc method\"\n )\n\n else:\n\n sampler = ultranest.ReactiveNestedSampler(\n param_names,\n loglike,\n transform=ultranest_prior,\n log_dir=chain_name,\n vectorized=False,\n wrapped_params=self._wrapped_params,\n )\n\n with use_astromodels_memoization(False):\n log.debug(\"Start ultranest run\")\n sampler.run(show_status=loud, **self._kwargs)\n log.debug(\"Ultranest run done\")\n\n process_fit = False\n\n if using_mpi:\n\n # if we are running in parallel and this is not the\n # first engine, then we want to wait and let everything finish\n\n if rank != 0:\n\n # let these guys take a break\n time.sleep(5)\n\n # these engines do not need to read\n process_fit = False\n\n else:\n\n # wait for a moment to allow it all to turn off\n time.sleep(5)\n\n process_fit = True\n\n else:\n\n process_fit = True\n\n if process_fit:\n\n results = sampler.results\n\n self._sampler = sampler\n\n ws = results[\"weighted_samples\"]\n\n # Workaround to support older versions of ultranest\n try:\n wsamples = ws['v']\n weights = ws['w']\n logl = ws['L']\n except KeyError:\n wsamples = ws['points']\n weights = ws['weights']\n logl = ws['logl']\n\n # Get the log. likelihood values from the chain\n\n SQRTEPS = (float(np.finfo(np.float64).eps)) ** 0.5\n if abs(np.sum(weights) - 1.0) > SQRTEPS: # same tol as in np.random.choice.\n raise ValueError(\"weights do not sum to 1\")\n\n rstate = np.random\n\n N = len(weights)\n\n # make N subdivisions, and choose positions with a consistent random offset\n positions = (rstate.random() + np.arange(N)) / N\n\n idx = np.zeros(N, dtype=np.int)\n cumulative_sum = np.cumsum(weights)\n i, j = 0, 0\n while i < N:\n if positions[i] < cumulative_sum[j]:\n idx[i] = j\n i += 1\n else:\n j += 1\n\n self._log_like_values = logl[idx]\n\n self._raw_samples = wsamples[idx]\n\n # now get the log probability\n\n self._log_probability_values = self._log_like_values + np.array(\n [self._log_prior(samples) for samples in self._raw_samples]\n )\n\n self._build_samples_dictionary()\n\n self._marginal_likelihood = sampler.results[\"logz\"] / np.log(10.0)\n\n self._build_results()\n\n # Display results\n if loud:\n self._results.display()\n\n # now get the marginal likelihood\n\n return self.samples\n","sub_path":"threeML/bayesian/ultranest_sampler.py","file_name":"ultranest_sampler.py","file_ext":"py","file_size_in_byte":6827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"347445102","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division, unicode_literals\nimport re\nfrom pygments.lexer import *\nfrom pygments.token import *\n\nclass CSSLexer(RegexLexer):\n name = \"CSS\"\n aliases = ['css']\n filenames = ['*.css']\n flags=re.DOTALL\n\n tokens = {\n b\"root\": [\n (r\"\", Text, b\"rules\"),\n ],\n b\"comment\": [\n (r\"\\*/\", Comment, b\"#pop\"),\n (r\".\", Comment)\n ],\n b\"at-rule\": [\n include(b\"values\"),\n (r\";\", Punctuation, b\"#pop\"),\n (r\"{\\s*}\", Punctuation, b\"#pop\"),\n (r\"{(?=[^;}]*{)\", Punctuation, (b\"#pop\", b\"rules\")),\n (r\"{(?=[^{}]*;)\", Punctuation, (b\"#pop\", b\"decls\")),\n (r\"\", Text, b\"#pop\")\n ],\n b\"rules\": [\n (r\"/\\*\", Comment, b\"comment\"),\n (r\"\\s+\", Text),\n (r\"@[\\w-]+\", Name, b\"at-rule\"),\n (r\"}\", Punctuation, b\"#pop\"),\n (r\"([^{]+)({)\", bygroups(Name.Tag, Punctuation), b\"decls\"),\n ],\n b\"decls\": [\n (r\";\", Punctuation),\n (r\"@[\\w-]+\", Name, b\"at-rule\"),\n (r\"([\\w-]+)\\s*(:)\", bygroups(Keyword, Punctuation)),\n include(b\"values\"),\n (r\"}\", Punctuation, b\"#pop\"),\n (r\".+\", Text)\n ],\n b\"values\": [\n (r\"/\\*\", Comment, b\"comment\"),\n (r\"[(),/]\", Punctuation),\n (r\"(\\d+)([\\w-]+)\", bygroups(Literal.Number, Literal)),\n (r\"\\d+%?\", Literal.Number),\n (r\"(url)(\\()([^)]*)(\\))\", bygroups(Name.Function, Punctuation, Literal.String, Punctuation)),\n (r\"([\\w-]+)(\\()\", bygroups(Name.Function, Punctuation)),\n (r\"\\\"[^\\\"]*\\\"\", Literal.String),\n (r\"'[^']*'\", Literal.String),\n (r\"#?[\\w-]+\", Text),\n (r\"\\s+\", Text)\n ]\n }\n","sub_path":"bikeshed/lexers.py","file_name":"lexers.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"299539031","text":"#project3-linhanning-auto52-2150504042\nimport cv2 as cv\nimport numpy as np\nfrom histogram_matching import ExactHistogramMatcher\n#OOP create class Pic\nclass Pic:\n def __init__(self, name, path):\n self.name=name\n self.path=path\n self.img=cv.imread(path)\n self.target_img=self.img\n print(\"[LOG]:Object {} created successfully!\".format(self.name))\n def drawHist(self):\n h = np.zeros((256,256,3))\n bins = np.arange(256).reshape(256,1)\n color = [ (255,0,0),(0,255,0),(0,0,255) ] #BGR三种颜色 \n for ch, col in enumerate(color): \n originHist = cv.calcHist([self.img],[ch],None,[256],[0,256]) \n cv.normalize(originHist, originHist,0,255*0.9,cv.NORM_MINMAX) \n hist=np.int32(np.around(originHist)) \n pts = np.column_stack((bins,hist)) \n cv.polylines(h,[pts],False,col) \n h=np.flipud(h)\n # cv.imshow(\"Hist\",h)\n cv.imwrite('Hist_of_{}.bmp'.format(self.name),h)\n print(\"[LOG]:Hist_of_{}.bmp created Successfully!\".format(self.name))\n # cv.waitKey(0)\n # cv.destroyAllWindows()\n def equalizeH(self):\n gray = cv.cvtColor(self.img, cv.COLOR_BGR2GRAY)\n dst=cv.equalizeHist(gray)\n #test\n # cv.imshow(\"Equalized\",dst)\n # cv.waitKey(0)\n # cv.destroyAllWindows()\n cv.imwrite('2-equalized_of_{}.bmp'.format(self.name),dst)\n print(\"[LOG]:2-equalized_of_{}.bmp created successfully!\".format(self.name))\n def histogramMatching(self,reference_img):\n self.target_img = self.img\n # reference_img is the one to be learned\n reference_histogram = ExactHistogramMatcher.get_histogram(reference_img)\n new_target_img = ExactHistogramMatcher.match_image_to_histogram(self.target_img, reference_histogram)\n new_target_img = new_target_img.astype(np.uint16)\n print(\"[LOG]:Pic \\\"3-histogrammatching_of_{}.bmp\\\"lib called successfully!\".format(self.name))\n self.target_img=new_target_img\n cv.imwrite('3-histogrammatching_of_{}.bmp'.format(self.name),self.target_img)\n print(\"[LOG]:3-histogrammatching_of_{}.bmp created sucessfully!\".format(self.name))\n # # misc.imsave('F:/grey_out.png', new_target_img)\n # filename = 'F:/grey_out.png'\n # with open(filename, 'wb') as f:\n # writer = png.Writer(width=new_target_img.shape[1], height=new_target_img.shape[0], bitdepth=16, greyscale=True)\n # zgray2list = new_target_img.tolist()\n # writer.write(f, zgray2list)\n def LocalEnhancement(self):\n E = 2\n para0 = 0.4\n para1 = 0.02\n para2 = 0.4\n height,width,channels = self.img.shape\n new_img = np.zeros([height, width], np.uint8)\n (mean, stddev) = cv.meanStdDev(self.img)\n var = stddev * stddev\n for i in range(height):\n for j in range(width):\n localm = 0\n localv = 0\n for k in range(i-3,i+4):\n if k < 0:\n kk = abs(k)\n elif k > height-1:\n kk = 2*height - 1 - k\n else:\n kk = k\n for l in range(j-3,j+4):\n if l < 0:\n ll = abs(l)\n elif l > width-1:\n ll = 2*width-1 - l\n else:\n ll = l\n localm = localm + self.img[kk][ll][0]\n localm = localm/(7*7)\n for k in range(i-3,i+4):\n if k < 0:\n kk = abs(k)\n elif k > height-1:\n kk = 2*height-1 - k\n else:\n kk = k\n for l in range(j-3,j+4):\n if l < 0:\n ll = abs(l)\n elif l > width-1:\n ll = 2*width-1 - l\n else:\n ll = l\n localv = localv + (localm - self.img[kk][ll][0]) ** 2\n localv = localv/48\n if localm <= para0 * mean[0] and localv >= para1 * var[0] and localv <= para2 * var[0]:\n new_img[i][j] = E * self.img[i][j][0]\n else:\n new_img[i][j] = self.img[i][j][0]\n cv.imwrite('4-Local_Enhancement_of_{}.bmp'.format(self.name),new_img)\n print(\"[LOG]:4-Local_Enhancement_of_{}.bmp created sucessfully!\".format(self.name))\n \n \n\n def histogramSegementation(self):\n gray=cv.cvtColor(self.img,cv.COLOR_BGR2GRAY)\n ret2,th2 = cv.threshold(gray,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)\n cv.imwrite('5-histogramSegmentation_of_{}.bmp'.format(self.name),th2)\n print(\"[LOG]:5-histogramSegmentation_of_{}.bmp created sucessfully!\".format(self.name))\n \n#3-1\nprint(\"-------------------------------------\")\nprint(\"#ANS:3-1 Show Histgram\\n\")\nelain=Pic(\"elain\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/elain.bmp\")\nelain1=Pic(\"elain1\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/elain1.bmp\")\nelain2=Pic(\"elain2\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/elain2.bmp\")\nelain3=Pic(\"elain3\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/elain3.bmp\")\ncitywall=Pic(\"citywall\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/citywall.bmp\")\ncitywall1=Pic(\"citywall1\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/citywall1.bmp\")\ncitywall2=Pic(\"citywall2\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/citywall2.bmp\")\nlena=Pic(\"lena\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/lena.bmp\")\nlena1=Pic(\"lena1\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/lena1.bmp\")\nlena2=Pic(\"lena2\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/lena2.bmp\")\nlena4=Pic(\"lena4\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/lena4.bmp\")\nwoman=Pic(\"woman\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/woman.bmp\")\nwoman1=Pic(\"woman1\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/woman1.bmp\")\nwoman2=Pic(\"woman2\",\"/home/hanninglin/Documents/CV/PROJECT/hw3/3rd-pro/woman2.bmp\")\nelain.drawHist()\nelain1.drawHist()\nelain2.drawHist()\nelain3.drawHist()\ncitywall.drawHist()\ncitywall1.drawHist()\ncitywall2.drawHist()\nlena.drawHist()\nlena1.drawHist()\nlena2.drawHist()\nlena4.drawHist()\nwoman.drawHist()\nwoman1.drawHist()\nwoman2.drawHist()\n3-2\nprint(\"-------------------------------------\")\nprint(\"#ANS:3-2 equalized Based on Histgram\\n\")\nelain.equalizeH()\nelain1.equalizeH()\nelain2.equalizeH()\nelain3.equalizeH()\ncitywall.equalizeH()\ncitywall1.equalizeH()\ncitywall2.equalizeH()\nlena.equalizeH()\nlena1.equalizeH()\nlena2.equalizeH()\nlena4.equalizeH()\nwoman.equalizeH()\nwoman1.equalizeH()\nwoman2.equalizeH()\nprint(\"-------------------------------------\")\nprint(\"#ANS:3-3 Histgram matching\\n\")\nelain.histogramMatching(lena2.img)\nlena.histogramMatching(lena1.img)\nprint(\"-------------------------------------\")\nprint(\"#ANS:3-4 Local Enhancement\\n\")\nelain.LocalEnhancement()\nlena.LocalEnhancement()\nprint(\"-------------------------------------\")\nprint(\"#ANS:3-5 Histogram Segementation\\n\")\nelain.histogramSegementation()\nwoman.histogramSegementation()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# elain\n# elain1\n# elain2\n# elain3\n# citywall\n# citywall1\n# citywall2\n# lena\n# lena1\n# lena2\n# lena4\n# woman\n# woman1\n# woman2","sub_path":"3rd-proj.py","file_name":"3rd-proj.py","file_ext":"py","file_size_in_byte":7401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"312810044","text":"#Importing libraries\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.cluster.hierarchy import single, complete, average, dendrogram, cut_tree\nfrom sklearn.cluster import AgglomerativeClustering, KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\n\n\n# Change working directory\nos.chdir(\"C:\\\\Users\\\\jef35\\\\OneDrive\\\\Informatics MS\\\\Semester 2\\\\Machine Learning\\\\Homework 2\\\\unsupervised-clustering\"\n \"-DrPancakesMD/\")\n\n# Importing labels\nfilename = \"lab.txt\"\nlabels = open(filename, \"r\")\ndf_labels = pd.read_csv(labels, sep='\\t', header=None)\ndf_labels.columns = [\"True Labels\"]\n\n# Importing data\nfilename = \"dat.txt\"\ndata = open(filename, \"r\")\ndf = pd.read_csv(data, sep='\\t', header=None)\n\n\n# Subsetting the data of 0's and 1's based on true labels\ndf_sub = df[(df_labels <= 1).values]\n\n# Checking if subsetting is correct\nprint(\"The dimensions of dat.txt subset is:\" + str(df_sub.shape))\n\n### Hiearchical clustering using Euclidean distances as the dissimilarity measure:\nclustering = AgglomerativeClustering(affinity = 'euclidean', n_clusters = 2).fit(df_sub)\n\n# Finding the original row number and the true label value\ndf_labels_sub = df_labels[(df_labels <= 1).values].astype(int).reset_index(drop=True)\n\n# Inverting the labels\nclustering.labels_ ^= 1\n\n# Comparing the true labels against hiearchical clustering\nclustering_labels = pd.DataFrame(clustering.labels_, columns = [\"Clustering\"])\ndisplay(pd.concat([df_labels_sub, clustering_labels], axis=1))\n\n# Dendrogram\nplt.suptitle(\"Dendrograms\")\n\n# Single\nax1 = plt.subplot(2, 2, 1)\ndf_sub_single = single(df_sub)\ndendrogram(df_sub_single)\nax1.set_title(\"Single\")\n\n# Complete\nax2 = plt.subplot(2, 2, 2)\ndf_sub_complete = complete(df_sub)\ndendrogram(df_sub_complete)\nax2.set_title(\"Complete\")\n\n# Average\nax3 = plt.subplot(2, 2, 3)\ndf_sub_average = average(df_sub)\ndendrogram(df_sub_average)\nax3.set_title(\"Average\")\n\n# Single\ndf_sub_single_cut = pd.DataFrame(cut_tree(df_sub_single, n_clusters=2).flatten())\ndf_sub_single_cut.columns = [\"Single Linkage\"]\ndf_sub_single_concat = pd.concat([df_labels_sub, df_sub_single_cut], axis=1)\ndisplay(pd.crosstab(df_sub_single_concat[\"True Labels\"], df_sub_single_concat[\"Single Linkage\"], margins=True))\n\n# Complete\ndf_sub_complete_cut = pd.DataFrame(cut_tree(df_sub_complete, n_clusters=2).flatten())\ndf_sub_complete_cut.columns = [\"Complete Linkage\"]\ndf_sub_complete_concat = pd.concat([df_labels_sub, df_sub_complete_cut], axis=1)\ndisplay(pd.crosstab(df_sub_complete_concat[\"True Labels\"], df_sub_complete_concat[\"Complete Linkage\"], margins=True))\n\n# Average\ndf_sub_average_cut = pd.DataFrame(cut_tree(df_sub_average, n_clusters=2).flatten())\ndf_sub_average_cut.columns = [\"Average Linkage\"]\ndf_sub_average_concat = pd.concat([df_labels_sub, df_sub_average_cut], axis=1)\ndisplay(pd.crosstab(df_sub_average_concat[\"True Labels\"], df_sub_average_concat[\"Average Linkage\"], margins=True))\n\nprint(\"It appears that the average linkage is the best at clustering.\\n\\nSingle linkage leads to poor clustering between 0 and 1. This is evidenced by the fact that nearly all the values from single linkaged fell into the '0' box. This led to 84 mistakes (True Label = 0 and Single Linkage = 0).\\n\\nThe complete linkage does better, with nearly half of the incorrectly labeled '0s' going to the other cluster. There were 40 mistakes (True Label = 0 and Complete Linkage = 0).\\n\\nAverage linkage does the best, making what appears to be only 4 mistakes (True label = 0 and Average Linkage= 0).\")\n\n# Using default KMeans clustering algorithm\nkmeans_smart = KMeans(n_clusters = 10).fit(df)\nkmeans_smart_centers = kmeans_smart.cluster_centers_\n\n# Plotting Kmeans Smart\nfig = plt.figure(2)\nplt.suptitle(\"KMeans Smart\")\nfor i in range(len(kmeans_smart_centers)):\n fig.add_subplot(2, 5, i+1)\n plt.imshow(kmeans_smart_centers[i].reshape(28, 28), cmap=\"gray\")\nplt.show()\n\n# Using default KMeans clustering algorithm\nkmeans_random = KMeans(n_clusters=10, init=\"random\", n_init=10).fit(df)\nkmeans_random_centers = kmeans_random.cluster_centers_\n\n# Plotting Kmeans Random\nfig = plt.figure(3)\nplt.suptitle(\"KMeans Random\")\nfor i in range(len(kmeans_random_centers)):\n fig.add_subplot(2, 5, i+1)\n plt.imshow(kmeans_random_centers[i].reshape(28, 28), cmap=\"gray\")\nplt.show()\n\n# Generating PCA matrix\npca_matrix = PCA().fit(df)\n\n# Variance explained by each component\nvariance_per_pc = pca_matrix.explained_variance_ratio_\n# Cumulative variance\nvariance_cumulative = np.cumsum(variance_per_pc)\n\n# Setting axis labels, title and style\nplt.ylabel('Variance Explained')\nplt.xlabel('Number of Features')\nplt.title('PCA Analysis')\nplt.style.context('seaborn-whitegrid')\n\n# Plotting lines\nplt.plot(variance_cumulative, label='Cumulative')\nplt.plot(variance_per_pc, label='Eigen Value')\n\n# Adding line labels\nplt.legend()\n\nprint(\"The PCA analysis did not need standardization. All the variables are of the same unit and range of magnitude. Therefore, standardization may even hurt our outcomes. This may be more useful if we were comparing values of different units or the alike.\")\n\n# Making a PCA of the first 2 principal components\npca_matrix2 = PCA().fit_transform(df)\n\n# Plotting scatter plot of PCA1 and PCA2\nplt.figure(figsize=(20, 15), dpi = 600)\nplt.scatter(pca_matrix2[:, 0], pca_matrix2[:, 1],\n c = df_labels['True Labels'], edgecolor = 'none', alpha = 0.5,\n cmap = plt.cm.get_cmap('gist_rainbow', 10))\n\n# Setting plot labels, title and color bar\nplt.xlabel('PCA 1')\nplt.ylabel('PCA 2')\nplt.title('PCA Analysis')\nplt.colorbar();\n\n# Please wait for image to load, DPI is set to 600.\n\n# Making a t-SNE of the first 2 principal components\ndf_tsne = TSNE().fit_transform(df)\n\n# Plotting plot of t-SNE\nplt.figure(figsize=(20, 15), dpi = 600)\nplt.scatter(df_tsne[:, 0], df_tsne[:, 1],\n c = df_labels['True Labels'], edgecolor = 'none', alpha = 0.5,\n cmap = plt.cm.get_cmap('gist_rainbow', 10))\n\n# Setting plot labels, title and color bar\nplt.xlabel('t-SNE 1')\nplt.ylabel('t-SNE 2')\nplt.title('t-SNE')\nplt.colorbar();","sub_path":"Clustering.py","file_name":"Clustering.py","file_ext":"py","file_size_in_byte":6116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"604822133","text":"# Задание # 2\n#\n# Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить\n# подсчет количества строк, количества слов в каждой строке.\n\n# file_name = 'lesson_5_task_2_text.txt'\nfile_name = input('Введите пожалуйста файл из которого нужно прочитать данные: ')\n\nlines_count = 0\nwords_count = 0\n\nwith open(file_name, 'r', encoding='utf-8') as file_obj:\n for line_in_file in file_obj:\n lines_count += 1\n words_count += len(line_in_file.split())\n\nprint(f'В файле {file_name} насчитывается {lines_count} строк(-и, -а) и {words_count} слов(-ово) и знаков пунктуации.')\n","sub_path":"I четверть/Основы языка Python (Вебинар)/lesson-5/hw_5_2.py","file_name":"hw_5_2.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"230483472","text":"# -*- coding: utf-8 -*-\n\"\"\"\ncoord_sys\nmantém os detalhes de um sistema de coordenadas\n\n2015.nov 0.2 mlabru pep8 style conventions\n2014.nov 0.1 mlabru initial version (Linux/Python)\n\"\"\"\n# < imports >----------------------------------------------------------------------------------\n\n# python library\nimport collections\nimport logging\nimport math\n\n# local\nimport coords.coord_conv as cnv\nimport coords.coord_defs as cdf\n#import coords.coord_geod as geod\nimport coords.coord_geog as geog\nimport coords.coord_model as model\n\n# < logging >----------------------------------------------------------------------------------\n\n# logger\nM_LOG = logging.getLogger(__name__)\nM_LOG.setLevel(cdf.DI_LOG_LEVEL)\n\n# < CCoordSys >--------------------------------------------------------------------------------\n\nclass CCoordSys(model.CCoordModel):\n \"\"\"\n mantém os detalhes de um sistema de coordenadas\n \"\"\"\n # -----------------------------------------------------------------------------------------\n def __init__(self, ff_ref_lat=cdf.M_REF_LAT, ff_ref_lng=cdf.M_REF_LNG, ff_dcl_mag=cdf.M_DCL_MAG):\n \"\"\"\n constructor\n \"\"\"\n # logger\n M_LOG.info(\">> constructor\")\n\n # init super class\n super(CCoordSys, self).__init__(ff_ref_lat, ff_ref_lng, ff_dcl_mag)\n\n # herdados de CCoordModel\n # self.f_ref_lat # latitude de referência\n # self.f_ref_lng # longitude de referência\n # self.f_dcl_mag # declinação magnética de referência\n\n # coordenadas geográficas de referênica e declinação magnética\n CREF = collections.namedtuple(\"CREF\", \"lat lng decl_mag\")\n\n self.__nt_ref = CREF(lat=ff_ref_lat, lng=ff_ref_lng, decl_mag=ff_dcl_mag)\n assert self.__nt_ref\n\n # coordenadas de referência\n cdf.M_REF_LAT = ff_ref_lat\n cdf.M_REF_LNG = ff_ref_lng\n cdf.M_DCL_MAG = ff_dcl_mag\n\n # dicionário de fixos\n self.__dct_fix = None\n\n # dicionário de indicativos\n self.__dct_fix_indc = None\n\n # -----------------------------------------------------------------------------------------\n def decl_xyz(self, ff_x, ff_y, ff_z, ff_decl=0.):\n \"\"\"\n conversão de coordenadas geográficas em (x, y, z)\n \"\"\"\n # logger\n M_LOG.info(\">> decl_xyz\")\n\n # retorna a coordenada declinada x, y z\n return geog.decl_xyz(ff_x, ff_y, ff_z, ff_decl)\n\n # -----------------------------------------------------------------------------------------\n def from_dict(self, f_dict):\n \"\"\"\n conversão de um dicionário em latitude e longitude\n\n :param f_dict: dicionário\n\n :returns: lat, long\n \"\"\"\n # logger\n M_LOG.info(\">> from_dict\")\n\n # check input\n assert f_dict\n\n # get coords fields\n l_cpo_b = f_dict.get(\"cpoB\", None)\n l_cpo_c = f_dict.get(\"cpoC\", None)\n l_cpo_d = f_dict.get(\"cpoD\", None)\n\n # coordenada\n li_rc, lf_lat, lf_lng = self.new_coord(f_dict[\"tipo\"], f_dict[\"cpoA\"], l_cpo_b, l_cpo_c, l_cpo_d)\n\n # retorna a coordenada em latitude e longitude\n return lf_lat, lf_lng\n\n # -----------------------------------------------------------------------------------------\n def __geo_fixo(self, fs_cpo_a, f_dct_fix=None):\n \"\"\"\n encontra coordenada geográfica do fixo\n\n :param fs_cpo_a: fixo\n :param f_dct_fix: dicionário de fixos\n\n :returns: 0 se Ok, senão -1 = NOk\n \"\"\"\n # logger\n M_LOG.info(\">> __geo_fixo\")\n\n if f_dct_fix is None:\n # dicionário de fixos\n f_dct_fix = self.__dct_fix\n\n # indicativo do fixo\n ls_fix = str(fs_cpo_a).strip().upper()\n\n # fixo existe no dicionário ?\n if ls_fix in f_dct_fix:\n # o fixo é válido ?\n if f_dct_fix[ls_fix].v_fix_ok:\n # latitude\n lf_lat = f_dct_fix[ls_fix].f_fix_lat\n\n # longitude\n lf_lng = f_dct_fix[ls_fix].f_fix_lng\n\n # return\n return 0, lf_lat, lf_lng\n\n # return\n return -1, 0., 0.\n\n # -----------------------------------------------------------------------------------------\n def geo2xyz(self, f_lat, f_lng, f_alt=0.):\n \"\"\"\n conversão de coordenadas geográficas em (x, y, z)\n \"\"\"\n # logger\n M_LOG.info(\">> geo2xyz\")\n\n # retorna a coordenada em x, y z\n # return geog.geo2xyz(f_lat, f_lng, self.__nt_ref.lat, self.__nt_ref.lng)\n # return geod.geod2ecef(f_lat, f_lng, f_alt)\n return geog.geo2xyz_3(f_lat, f_lng, f_alt)\n\n # -----------------------------------------------------------------------------------------\n def __get_fixo_by_indc(self, fs_cpo_a, f_dct_fix_indc=None):\n \"\"\"\n encontra o número do fixo pelo indicativo\n\n :param fs_cpo_a: indicativo do fixo\n :param f_dct_fix_indc: dicionário de indicativos de fixos\n\n :returns: número do fixo ou -1\n \"\"\"\n # logger\n M_LOG.info(\">> __get_fixo_by_indc\")\n\n # check input\n assert fs_cpo_a\n\n if f_dct_fix_indc is None:\n # dicionário de indicativos\n f_dct_fix_indc = self.__dct_fix_indc\n\n # clear to go\n assert f_dct_fix_indc is not None\n\n # indicativo do fixo\n ls_fix = str(fs_cpo_a).strip().upper()\n\n # return\n return f_dct_fix_indc.get(ls_fix, -1)\n\n # -----------------------------------------------------------------------------------------\n def new_coord(self, fc_tipo, fs_cpo_a, fs_cpo_b=\"\", fs_cpo_c=\"\", fs_cpo_d=\"\"):\n \"\"\"\n cria uma coordenada\n \"\"\"\n # logger\n M_LOG.info(\">> new_coord\")\n\n # check input\n if fc_tipo not in cdf.D_SET_COORD_VALIDAS:\n # logger\n M_LOG.critical(f\"tipo de coordenada {fc_tipo} inválida.\")\n\n # cai fora\n return -1, -90., -180.\n\n # inicia os valores de resposta\n lf_lat = None\n lf_lng = None\n\n # coordenada distância/radial\n if 'D' == fc_tipo:\n #!!TipoD(lp_ref, fp_coord)\n\n # obtém as coordenadas geográficas do fixo(cpoA)\n li_rc, lf_lat, lf_lng = self.__geo_fixo(fs_cpo_a)\n\n if 0 != li_rc:\n # logger\n M_LOG.error(f\"fixo {fs_cpo_a} inexistente.\")\n\n # cai fora\n return li_rc, lf_lat, lf_lng\n\n # converte para cartesiana\n lf_x, lf_y, _ = self.geo2xyz(lf_lat, lf_lng)\n\n # distância(m)\n l_vd = float(fs_cpo_b) * cdf.D_CNV_NM2M\n\n # radial(radianos)\n l_vr = math.radians(cnv.azm2ang(float(fs_cpo_c)))\n\n # x, y do ponto\n lf_x += l_vd * math.cos(l_vr)\n lf_y += l_vd * math.sin(l_vr)\n\n # converte para geográfica\n lf_lat, lf_lng, _ = self.xyz2geo(lf_x, lf_y)\n\n # ok\n return li_rc, lf_lat, lf_lng\n\n # coordenada fixo\n elif 'F' == fc_tipo:\n # obtém as coordenadas geográficas do fixo(cpoA)\n li_rc, lf_lat, lf_lng = self.__geo_fixo(fs_cpo_a)\n\n if 0 != li_rc:\n # logger\n M_LOG.error(f\"fixo {fs_cpo_a} inexistente.\")\n\n # cai fora\n return li_rc, lf_lat, lf_lng\n\n # coordenada geográfica formato ICA ?(formato GGGMM.mmmH)\n elif 'G' == fc_tipo:\n # latitude\n lf_lat = cnv.parse_ica(str(fs_cpo_a))\n\n # longitude\n lf_lng = cnv.parse_ica(str(fs_cpo_b))\n\n # ok\n return 0, lf_lat, lf_lng\n\n # coordenada indicativo de fixo\n elif 'I' == fc_tipo:\n # obtém o número do fixo pelo indicativo\n li_rc = self.__get_fixo_by_indc(fs_cpo_a)\n\n if li_rc < 0:\n # logger\n M_LOG.error(f\"fixo {fs_cpo_a} inexistente.\")\n\n # cai fora\n return -1, -90., -180.\n\n # obtém as coordenadas geográficas do indicativo do fixo\n li_rc, lf_lat, lf_lng = self.__geo_fixo(li_rc)\n\n if li_rc < 0:\n # logger\n M_LOG.error(f\"fixo {fs_cpo_a} inexistente.\")\n\n # cai fora\n return li_rc, lf_lat, lf_lng\n\n # coordenada geográfica formato AISWEB ?(formato X:999:99:99.99)\n elif 'K' == fc_tipo:\n # latitude\n lf_lat = cnv.parse_aisweb(str(fs_cpo_a))\n\n # longitude\n lf_lng = cnv.parse_aisweb(str(fs_cpo_b))\n\n # ok\n return 0, lf_lat, lf_lng\n\n # coordenada geográfica formato decimal ?(formato +/-999.9999)\n elif 'L' == fc_tipo:\n # latitude\n lf_lat = float(fs_cpo_a)\n\n # longitude\n lf_lng = float(fs_cpo_b)\n\n # ok\n return 0, lf_lat, lf_lng\n\n # coordenada polar\n elif 'P' == fc_tipo:\n li_rc = -1\n\n lf_lat = -90.\n lf_lng = -180.\n\n # cai fora\n return li_rc, lf_lat, lf_lng\n\n # coordenada desconhecida\n elif 'X' == fc_tipo:\n li_rc = -1\n\n lf_lat = -90.\n lf_lng = -180.\n\n # cai fora\n return li_rc, lf_lat, lf_lng\n\n # senão, coordenada inválida\n else:\n # logger\n M_LOG.critical(f\"tipo de coordenada {fc_tipo} inválida.\")\n\n # cai fora\n return -1, -90., -180.\n\n # return\n return -1, -90., -180.\n\n # -----------------------------------------------------------------------------------------\n def xyz2geo(self, ff_x, ff_y, ff_z=0.):\n \"\"\"\n conversão de coordenadas geográficas em (x, y, z)\n \"\"\"\n # logger\n M_LOG.info(\">> xyz2geo\")\n\n # retorna a coordenada em latitude e longitude\n # return geog.xy2geo(ff_x, ff_y)\n # return geod.ecef2geod(ff_x, ff_y, ff_z)\n return geog.xyz2geo_3(ff_x, ff_y, ff_z)\n\n # =========================================================================================\n # data\n # =========================================================================================\n\n # -----------------------------------------------------------------------------------------\n @property\n def dct_fix(self):\n \"\"\"dicionário de fixos.\"\"\"\n return self.__dct_fix\n\n @dct_fix.setter\n def dct_fix(self, f_val):\n \"\"\"dicionário de fixos.\"\"\"\n self.__dct_fix = f_val\n\n # -----------------------------------------------------------------------------------------\n @property\n def dct_fix_indc(self):\n \"\"\"dicionário de indicativos.\"\"\"\n return self.__dct_fix_indc\n\n @dct_fix_indc.setter\n def dct_fix_indc(self, f_val):\n \"\"\"dicionário de indicativos.\"\"\"\n self.__dct_fix_indc = f_val\n\n # -----------------------------------------------------------------------------------------\n @property\n def nt_ref(self):\n \"\"\"referência.\"\"\"\n return self.__nt_ref\n\n @nt_ref.setter\n def nt_ref(self, f_val):\n \"\"\"referência.\"\"\"\n self.__nt_ref = f_val\n\n# < the end >----------------------------------------------------------------------------------\n","sub_path":"coords/coord_sys.py","file_name":"coord_sys.py","file_ext":"py","file_size_in_byte":11401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"478341152","text":"from sqlalchemy.orm import Session\nfrom .. import models\nfrom fastapi import FastAPI, Depends, status, HTTPException\n\ndef get_all(db: Session):\n blogs = db.query(models.Blog).all()\n return blogs\n\ndef create(request, db: Session):\n new_blog = models.Blog(title=request.title, body=request.body, creator_id=request.creator_id)\n db.add(new_blog)\n db.commit()\n db.refresh(new_blog)\n return new_blog\n\ndef show_one(id: int, db: Session):\n blog = db.query(models.Blog).filter(models.Blog.id == id).first()\n if not blog:\n # response.status_code = status.HTTP_404_NOT_FOUND\n # return {'detail': f\"The blog with the id: {id} is not available\"}\n raise HTTPException(status_code=404, detail=f\"The blog with the id: {id} is not available\")\n return blog\n\ndef destroy(id: int, db: Session):\n blog = db.query(models.Blog).filter(models.Blog.id == id)\n if not blog.first():\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"The blog of id: {id} is not found\")\n blog.delete(synchronize_session=False)\n db.commit()\n return {'detail': 'The instance has been deleted!'}\n\ndef update(id: int, request, db: Session):\n blog = db.query(models.Blog).filter(models.Blog.id == id)\n if not blog.first():\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"The blog of id: {id} is not found\")\n blog.update({models.Blog.title: request.title, models.Blog.body: request.body}, synchronize_session=False)\n db.commit()\n return \"the data has been updated!\"","sub_path":"blog/repository/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"181090249","text":"import os\n\nTPL_PATH = os.path.abspath(\n os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates/')\n)\nIMG_PATH = os.path.abspath(\n os.path.join(os.path.dirname(os.path.realpath(__file__)), \"images/\")\n)\n\nTOKEN_EXPIRATION_IN_SECONDS = 3600\nTOKEN_REPLACEMENT_IN_SECONDS = 10 * 60\n\nCLICKWRAP_BASE_HOST = 'https://demo.docusign.net'\nCLICKWRAP_BASE_URI = '/clickapi/v1/accounts'\nCLICKWRAP_TIME_DELTA_IN_MINUTES = 15\n\nCODE_GRANT_SCOPES = ['signature', 'click.manage']\nPERMISSION_SCOPES = ['signature', 'impersonation', 'click.manage']\n\nDS_RETURN_URL = os.environ.get('REACT_APP_DS_RETURN_URL')\nDS_AUTH_SERVER = os.environ.get('DS_AUTH_SERVER')\nDS_DEMO_SERVER = os.environ.get('REACT_APP_DS_DEMO_SERVER')","sub_path":"app/ds_config.py","file_name":"ds_config.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"214999689","text":"string = \"tthistorybookrrrrr\"\n\narray = list(string)\nk = {}\n\nfor letter in array:\n if letter in k:\n k[letter] += 1\n else:\n k[letter] = 1\n\nfor letter in k:\n if k[letter] > 1:\n print(\"{} repeated {} times\".format(letter, k[letter]))\n\n","sub_path":"repeats.py","file_name":"repeats.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"91514706","text":"#!/usr/bin/python\n#coding:utf-8\n\nimport MySQLdb\nimport time\n\nclass StageController():\n\tdef __init__(self, con):\n\t\tself.con = con\n\t\tself.con.ping(True)\n\t\tself.cur = self.con.cursor()\n\t\t'''\n\t\tsql = 'create table if not exists stageTable(id integer primary key AUTO_INCREMENT, \\\n\t\t\tpid integer not null, state integer default 0, content text not null)'\n\t\tself.cur.execute(sql)\n\t\t'''\n\t\tself.insertSql = 'insert into stageTable values(%s, %s, %s, %s)'\n\n\tdef createStage(self, stage):\n\t\tstate = 0\n\t\tcontent = None\n\t\tif 'state' in stage:\n\t\t\tstate = stage['state']\n\t\tif 'content' in stage:\n\t\t\tcontent = stage['content']\n\t\tself.cur.execute(self.insertSql, \n\t\t\t(0, stage['planId'], state, content))\n\t\tid = self.cur.lastrowid\n\t\treturn id\n\n\tdef deleteStageById(self, id):\n\t\tself.cur.execute('delete from stageTable where id = ' + str(id))\n\n\tdef deleteStagesByPlanId(self, planId):\n\t\tself.cur.execute('delete from stageTable where pid = ' + str(planId))\n\n\tdef getStageById(self, id):\n\t\tself.cur.execute('select * from stageTable where id = ' + str(id))\n\t\tstage = self.cur.fetchone()\n\t\tif stage:\n\t\t\treturn self.convertDataToStageDict(stage)\n\t\telse:\n\t\t\treturn None\n\n\tdef getStagesByPlanId(self, planId):\n\t\tself.cur.execute('select * from stageTable where pid = ' + str(planId))\n\t\tstages = self.cur.fetchall()\n\t\tresult = list()\n\t\tif stages:\n\t\t\tfor stage in stages:\n\t\t\t\tresult.append(self.convertDataToStageDict(stage))\n\t\treturn result\n\n\tdef updateStage(self, stage):\n\t\tsql = 'update stageTable set pid = \"' + str(stage['planId']) \\\n\t\t\t+ '\", state = \"' + str(stage['state']) \\\n\t\t\t+ '\", content = \"' + stage['content'] \\\n\t\t\t+ '\" where id = ' + str(stage['id'])\n\t\tself.cur.execute(sql)\n\n\tdef convertDataToStageDict(self, stage):\n\t\tresult = dict()\n\t\tresult['id'] = stage[0]\n\t\tresult['planId'] = stage[1]\n\t\tresult['state'] = stage[2]\n\t\tresult['content'] = stage[3]\n\t\treturn result\n\n\tdef __del__(self):\n\t\tself.cur.close()\n","sub_path":"project/web-v1/StageController.py","file_name":"StageController.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"631620611","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\nfrom ext import db\nfrom sqlalchemy import Column, String, Text\nfrom sqlalchemy import Integer, BigInteger, SmallInteger\nfrom helpers import BaseModel\nimport time\nimport flask.ext.whooshalchemy\nfrom category.models import Category\n\n\nclass Entry(db.Model, BaseModel):\n __tablename__ = 'entry'\n __searchable__ = ['title', 'content']\n\n id = Column('id', Integer, primary_key=True)\n title = Column('title', String(100), nullable=False)\n description = Column('description', String(200))\n content = Column('content', Text, nullable=False)\n created_at = Column('created_at', BigInteger, default=time.time())\n updated_at = Column(\n 'updated_at',\n BigInteger,\n default=time.time(),\n onupdate=time.time())\n slug = Column(\"slug\", String(100))\n category = Column('category', Integer)\n status = Column('status', SmallInteger)\n is_top = Column('is_top', SmallInteger)\n\n @classmethod\n def get_by_keyword(cls, keyword):\n if not isinstance(keyword, (str, unicode)):\n raise TypeError(\"String expected, but get %s\" % type(keyword))\n return cls.query.filter(\n (cls.title.contains(keyword)) | (cls.content.contains(keyword))\n )\\\n .distinct()\\\n .all()\n\n @classmethod\n def get_by_tag(cls, tag):\n pass\n\n @classmethod\n def get_by_top(cls):\n res = cls.query.filter(\n (cls.status == \"1\") & (cls.is_top == 1))\\\n .order_by(cls.updated_at.desc())\\\n .limit(3)\n return res\n\n @classmethod\n def get_all(cls):\n return cls.query.filter(\n cls.status == \"1\"\n ).all()\n\n @classmethod\n def get_by_slug(cls, slug):\n return cls.query.filter_by(slug=slug).first()\n\n\n @classmethod\n def get_recent(cls):\n return cls.query.with_entities(\n cls.id, cls.title\n )\\\n .filter(cls.status == \"1\")\\\n .order_by(cls.updated_at).limit(5)\n\n @classmethod\n def get_by_category(cls, cate_name):\n return cls.query.join(Category, cls.category == Category.id)\\\n .filter(Category.name.contains(cate_name))\\\n .order_by(cls.updated_at.desc())\\\n .all()\n","sub_path":"entry/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"372836571","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nThis is the OpenAPI validator library.\nValidates input using the OpenAPI specification version 3 from\nhttps://github.com/OAI/OpenAPI-Specification (a simplified version, ahem)\n\"\"\"\n\nimport functools\nimport json\nimport operator\nimport re\n\nimport yaml\n\n\nclass OpenAPIException(Exception):\n def __init__(self, message):\n self.message = message\n\n\n# Python type names to JSON type names\npy2JSON = {\n \"int\": \"integer\",\n \"float\": \"float\",\n \"str\": \"string\",\n \"list\": \"array\",\n \"dict\": \"object\",\n \"bool\": \"boolean\",\n}\n\nmcolors = {\n \"PUT\": \"#fca130\",\n \"DELETE\": \"#f93e3e\",\n \"GET\": \"#61affe\",\n \"POST\": \"#49cc5c\",\n \"PATCH\": \"#d5a37e\",\n}\n\n\nclass OpenAPI:\n def __init__(self, APIFile):\n \"\"\" Instantiates an OpenAPI validator given a YAML specification\"\"\"\n if APIFile.endswith(\".json\") or APIFile.endswith(\".js\"):\n self.API = json.load(open(APIFile))\n else:\n self.API = yaml.safe_load(open(APIFile))\n\n def validateType(self, field, value, ftype):\n \"\"\" Validate a single field value against an expected type \"\"\"\n\n # Get type of value, convert to JSON name of type.\n pyType = type(value).__name__\n jsonType = py2JSON[pyType] if pyType in py2JSON else pyType\n\n # Check if type matches\n if ftype != jsonType:\n raise OpenAPIException(\n \"OpenAPI mismatch: Field '%s' was expected to be %s, but was really %s!\"\n % (field, ftype, jsonType)\n )\n\n def validateSchema(self, pdef, formdata, schema=None):\n \"\"\" Validate (sub)parameters against OpenAPI specs \"\"\"\n\n # allOf: list of schemas to validate against\n if \"allOf\" in pdef:\n for subdef in pdef[\"allOf\"]:\n self.validateSchema(subdef, formdata)\n\n where = \"JSON body\"\n # Symbolic link??\n if \"schema\" in pdef:\n schema = pdef[\"schema\"][\"$ref\"]\n if \"$ref\" in pdef:\n schema = pdef[\"$ref\"]\n if schema:\n # #/foo/bar/baz --> dict['foo']['bar']['baz']\n pdef = functools.reduce(operator.getitem, schema.split(\"/\")[1:], self.API)\n where = \"item matching schema %s\" % schema\n\n # Check that all required fields are present\n if \"required\" in pdef:\n for field in pdef[\"required\"]:\n if not field in formdata:\n raise OpenAPIException(\n \"OpenAPI mismatch: Missing input field '%s' in %s!\"\n % (field, where)\n )\n\n # Now check for valid format of input data\n for field in formdata:\n if \"properties\" not in pdef or field not in pdef[\"properties\"]:\n raise OpenAPIException(\n \"Unknown input field '%s' in %s!\" % (field, where)\n )\n if \"type\" not in pdef[\"properties\"][field]:\n raise OpenAPIException(\n \"OpenAPI mismatch: Field '%s' was found in api.yaml, but no format was specified in specs!\"\n % field\n )\n ftype = pdef[\"properties\"][field][\"type\"]\n self.validateType(field, formdata[field], ftype)\n\n # Validate sub-arrays\n if ftype == \"array\" and \"items\" in pdef[\"properties\"][field]:\n for item in formdata[field]:\n if \"$ref\" in pdef[\"properties\"][field][\"items\"]:\n self.validateSchema(pdef[\"properties\"][field][\"items\"], item)\n else:\n self.validateType(\n field,\n formdata[field],\n pdef[\"properties\"][field][\"items\"][\"type\"],\n )\n\n # Validate sub-hashes\n if ftype == \"hash\" and \"schema\" in pdef[\"properties\"][field]:\n self.validateSchema(pdef[\"properties\"][field], formdata[field])\n\n def validateParameters(self, defs, formdata):\n #\n pass\n\n def validate(self, method=\"GET\", path=\"/foo\", formdata=None):\n \"\"\" Validate the request method and input data against the OpenAPI specification \"\"\"\n\n # Make sure we're not dealing with a dynamic URL.\n # If we find /foo/{key}, we fold that into the form data\n # and process as if it's a json input field for now.\n if not self.API[\"paths\"].get(path):\n for xpath in self.API[\"paths\"]:\n pathRE = re.sub(r\"\\{(.+?)\\}\", r\"(?P<\\1>[^/]+)\", xpath)\n m = re.match(pathRE, path)\n if m:\n for k, v in m.groupdict().items():\n formdata[k] = v\n path = xpath\n break\n\n if self.API[\"paths\"].get(path):\n defs = self.API[\"paths\"].get(path)\n method = method.lower()\n if method in defs:\n mdefs = defs[method]\n if formdata and \"parameters\" in mdefs:\n self.validateParameters(mdefs[\"parameters\"], formdata)\n elif formdata and \"requestBody\" not in mdefs:\n raise OpenAPIException(\n \"OpenAPI mismatch: JSON data is now allowed for this request type\"\n )\n elif (\n formdata\n and \"requestBody\" in mdefs\n and \"content\" in mdefs[\"requestBody\"]\n ):\n\n # SHORTCUT: We only care about JSON input for Kibble! Disregard other types\n if not \"application/json\" in mdefs[\"requestBody\"][\"content\"]:\n raise OpenAPIException(\n \"OpenAPI mismatch: API endpoint accepts input, but no application/json definitions found in api.yaml!\"\n )\n jdefs = mdefs[\"requestBody\"][\"content\"][\"application/json\"]\n\n # Check that required params are here\n self.validateSchema(jdefs, formdata)\n\n else:\n raise OpenAPIException(\n \"OpenAPI mismatch: Method %s is not registered for this API\"\n % method\n )\n else:\n raise OpenAPIException(\"OpenAPI mismatch: Unknown API path '%s'!\" % path)\n\n def dumpExamples(self, pdef, array=False):\n schema = None\n if \"schema\" in pdef:\n if \"type\" in pdef[\"schema\"] and pdef[\"schema\"][\"type\"] == \"array\":\n array = True\n schema = pdef[\"schema\"][\"items\"][\"$ref\"]\n else:\n schema = pdef[\"schema\"][\"$ref\"]\n if \"$ref\" in pdef:\n schema = pdef[\"$ref\"]\n if schema:\n # #/foo/bar/baz --> dict['foo']['bar']['baz']\n pdef = functools.reduce(operator.getitem, schema.split(\"/\")[1:], self.API)\n js = {}\n desc = {}\n if \"properties\" in pdef:\n for k, v in pdef[\"properties\"].items():\n if \"description\" in v:\n desc[k] = [v[\"type\"], v[\"description\"]]\n if \"example\" in v:\n js[k] = v[\"example\"]\n elif \"items\" in v:\n if v[\"type\"] == \"array\":\n js[k], foo = self.dumpExamples(v[\"items\"], True)\n else:\n js[k], foo = self.dumpExamples(v[\"items\"])\n return [js if not array else [js], desc]\n\n def toHTML(self):\n \"\"\" Blurps out the specs in a pretty HTML blob \"\"\"\n print(\n \"\"\"\n\n\n\n\n\n\"\"\"\n )\n li = \"

Overview:

    \"\n for path, spec in sorted(self.API[\"paths\"].items()):\n for method, mspec in sorted(spec.items()):\n method = method.upper()\n summary = mspec.get(\"summary\", \"No summary available\")\n linkname = \"%s%s\" % (method.lower(), path.replace(\"/\", \"-\"))\n li += \"
  • %s %s: %s
  • \\n\" % (\n linkname,\n method,\n path,\n summary,\n )\n li += \"
\"\n print(li)\n for path, spec in sorted(self.API[\"paths\"].items()):\n for method, mspec in sorted(spec.items()):\n method = method.upper()\n summary = mspec.get(\"summary\", \"No summary available\")\n resp = \"\"\n inp = \"\"\n inpvars = \"\"\n linkname = \"%s%s\" % (method.lower(), path.replace(\"/\", \"-\"))\n if \"responses\" in mspec:\n for code, cresp in sorted(mspec[\"responses\"].items()):\n for ctype, pdef in cresp[\"content\"].items():\n xjs, desc = self.dumpExamples(pdef)\n js = json.dumps(xjs, indent=4)\n resp += (\n \"
%s:\\n%s
\\n
\\n\"\n % (code, js)\n )\n\n if \"requestBody\" in mspec:\n for ctype, pdef in mspec[\"requestBody\"][\"content\"].items():\n xjs, desc = self.dumpExamples(pdef)\n if desc:\n for k, v in desc.items():\n inpvars += (\n \"%s: (%s) %s
\\n\"\n % (k, v[0], v[1])\n )\n js = json.dumps(xjs, indent=4)\n inp += (\n \"

Input examples:

%s:\\n%s
\\n
\"\n % (ctype, js)\n )\n\n if inpvars:\n inpvars = (\n \"
%s
\\n
\"\n % inpvars\n )\n\n print(\n \"\"\"\n
\n
\n \n\n
%s
\n\n \n %s\n
\n %s
\n
\n

JSON parameters:

\n %s\n
\n %s\n
\n
\n

Response examples:

\n
%s
\n
\n
\n
\n \"\"\"\n % (\n linkname,\n mcolors[method],\n mcolors[method],\n mcolors[method],\n method,\n path,\n summary,\n \"block\" if inp else \"none\",\n inpvars,\n inp,\n resp,\n )\n )\n # print(\"%s %s: %s\" % (method.upper(), path, mspec['summary']))\n print(\"\")\n","sub_path":"kibble/api/plugins/openapi.py","file_name":"openapi.py","file_ext":"py","file_size_in_byte":13255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"353510496","text":"from datetime import date, timedelta\nfrom calendar import day_name\n\nclass Chain():\n\n def __init__(self):\n self.habits = []\n\n def add_habit(self, habit):\n self.habits.append(habit)\n\n def remove_habit(self, habit):\n try:\n habit = int(habit)\n self.habits = map(lambda y: y[1], filter(lambda x: x[0]+1 != habit, enumerate(self.habits)))\n except ValueError:\n self.habits = filter(lambda x: x.name != habit, self.habits)\n\n def add_link(self, habit):\n try:\n habit = int(habit)\n h = filter(lambda x: x[0] == habit-1, enumerate(self.habits))[0][1]\n except ValueError:\n h = [x for x in self.habits if x.name == habit][0]\n\n h.add_entry()\n\n def undo_link(self, habit):\n try:\n habit = int(habit)\n h = filter(lambda x: x[0] == habit-1, enumerate(self.habits))[0][1]\n except ValueError:\n h = [x for x in self.habits if x.name == habit][0]\n\n h.delete_entry()\n\n def __iter__(self):\n for habit in self.habits:\n yield habit\n\n def display(self):\n \n if len(self.habits) == 0:\n print(\"No habits found. Add a habit.\")\n return\n\n left_padding = max([len(x.name) for x in self.habits]) + 6\n\n curr_day = date.today().weekday()\n print(' '*left_padding + (' '*3).join(map(lambda x: day_name[x % 7], range(curr_day-6, curr_day+1))))\n\n for e_habit in enumerate(self.habits):\n num, habit = e_habit\n log = habit.get_log()\n out = str(num+1) + '. ' + habit.name + ' '*(left_padding - len(habit.name) - len(str(num+1)) - 2)\n for x in range(-6, 1):\n this_day = date.today() + timedelta(x)\n length = len(day_name[this_day.weekday()])\n if this_day in log:\n fst = length/2 - 1\n snd = length - fst\n out += ' '*fst + '*' + ' '*snd\n else:\n out += ' '*length\n out += ' '*3\n print(out)\n","sub_path":"Chain.py","file_name":"Chain.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"124216202","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n# In[ ]:\r\n\r\n\r\ndef main():\r\n args = input().rstrip().split(' ')\r\n S = [c for c in args[0]]\r\n if(S[0]==S[1] and S[0]==S[2] and S[1]==S[2]):\r\n print('No')\r\n else:\r\n print('Yes')\r\n \r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n","sub_path":"beginner_158/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"428536112","text":"'''\n# UserIO module\n\n provides some handy functions for command line interfacing\n'''\nimport unicodedata,logging\ncancel = 'q'\nlogger = logging.getLogger('UserIO')\nclass UserCannceledException(Exception):\n def __init__(self, *args, **kwargs):\n logger.warn('Intercepted user canncel action')\n super().__init__(*args, **kwargs)\n\ndef get(*args,**kwargs):\n '''Input but wrapped with print() and added interruptions\n \n Set `ignore_cancel=True` if you don't want keyboard interruptions\n ''' \n ignore_cancel = kwargs['ignore_cancel'] if 'ignore_cancel' in kwargs.keys() else False\n\n kwargs = {k:v for k,v in kwargs.items() if not k in ['ignore_cancel']}\n # Reverved keyword agrument\n print(*args,**{'end':'>>>',**kwargs})\n try:\n result = input()\n except KeyboardInterrupt:\n result = cancel\n \n if result == cancel and not ignore_cancel:raise UserCannceledException('Cannceled.')\n return result\n\ndef scrlen(s):\n return sum([2 if unicodedata.east_asian_width(i) in 'WFA' else 1 for i in s])\n\ndef header(str,pad='_',total=50):\n return str + pad * (total - scrlen(str))\n\ndef listout(items,foreach=lambda x,i: x,title='LIST',showindex=True,reverse=False):\n '''Prints a list of dictionaries with their index and value processed by `foreach`'''\n print(header(title),sep='')\n items = list(items)\n if items:\n for index in reversed(range(0,len(items))) if reverse else range(0,len(items)):\n item = items[index]\n try:\n print(*('',str(index).ljust(5)) if showindex else '',foreach(item,index),sep=' ' if showindex else '')\n except Exception as e:\n print(*('',str(index).ljust(5)) if showindex else '','-',sep=' ' if showindex else '')\n else:\n print('X 无可用操作')\n print('_' * 50)\n","sub_path":"utils/myutils/userio.py","file_name":"userio.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"340117698","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\nfrom matplotlib import rcParams\nfrom matplotlib import rcParamsDefault\nimport numpy as np\n\ndef set_figure_settings(Figure_Type,**kwargs):\n rcParams.update(rcParamsDefault)\n params = {}\n if Figure_Type == 'paper':\n params = {'lines.linewidth': 2,\n 'lines.markersize': 5,\n 'legend.fontsize': 8,\n 'legend.borderpad': 0.2,\n 'legend.labelspacing': 0.2,\n 'legend.handletextpad' : 0.2,\n 'legend.borderaxespad' : 0.2,\n 'legend.scatterpoints' :1,\n 'xtick.labelsize' : 8,\n 'ytick.labelsize' : 8,\n 'axes.titlesize' : 8,\n 'axes.labelsize' : 8,\n 'figure.autolayout': True,\n 'font.family': 'Calibri',\n 'font.size': 8}\n elif Figure_Type == 'presentation':\n params = {'lines.linewidth' : 3,\n 'legend.handlelength' : 1.0,\n 'legend.handleheight' : 1.0,\n 'legend.fontsize': 16,\n 'legend.borderpad': 0.2,\n 'legend.labelspacing': 0.2,\n 'legend.handletextpad' : 0.2,\n 'legend.borderaxespad' : 0.2,\n 'legend.scatterpoints' :1,\n 'xtick.labelsize' : 16,\n 'ytick.labelsize' : 16,\n 'axes.titlesize' : 24,\n 'axes.labelsize' : 20,\n 'figure.autolayout': True,\n 'font.size': 16.0}\n rcParams.update(params)\n rcParams.update(kwargs)","sub_path":"jl_exp_deconv/plotting_tools.py","file_name":"plotting_tools.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"10448238","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import (\n render, redirect, reverse, get_object_or_404, HttpResponse\n)\nfrom django.views.decorators.http import require_POST\nfrom django.contrib import messages\nfrom django.conf import settings\n\nfrom .forms import OrderForm\nfrom products.models import ProductVariant\nfrom .models import Order, OrderLineItem\nfrom useraccount.models import UserAccount\nfrom useraccount.forms import UserAccountForm\nfrom cart.contexts import cart_content\n\nimport stripe\nimport json\n\n\n@require_POST\ndef cache_checkout_data(request):\n try:\n pid = request.POST.get('client_secret').split('_secret')[0]\n stripe.api_key = settings.STRIPE_SECRET_KEY\n stripe.PaymentIntent.modify(pid, metadata={\n 'cart': json.dumps(request.session.get('cart', {})),\n 'save_info': request.POST.get('save_info'),\n 'username': request.user,\n })\n return HttpResponse(status=200)\n except Exception as e:\n messages.error(request, 'Sorry, your payment cannot be \\\n processed right now. Please try again later.')\n return HttpResponse(content=e, status=400)\n\n\ndef checkout(request):\n \"\"\"\n A view to return the checkout page.\n Based on the Botique Ado CI Project and modified to fit this project.\n \"\"\"\n stripe_public_key = settings.STRIPE_PUBLIC_KEY\n stripe_secret_key = settings.STRIPE_SECRET_KEY\n\n if request.method == 'POST':\n cart = request.session.get('cart', {})\n\n form_data = {\n 'first_name': request.POST['first_name'],\n 'last_name': request.POST['last_name'],\n 'email': request.POST['email'],\n 'phone_number': request.POST['phone_number'],\n 'street_address1': request.POST['street_address1'],\n 'street_address2': request.POST['street_address2'],\n 'zipcode': request.POST['zipcode'],\n 'town_or_city': request.POST['town_or_city'],\n 'country': request.POST['country'],\n }\n order_form = OrderForm(form_data)\n if order_form.is_valid():\n order = order_form.save(commit=False)\n pid = request.POST.get('client_secret').split('_secret')[0]\n order.stripe_pid = pid\n order.original_cart = json.dumps(cart)\n order.save()\n for item_id, item_data in cart.items():\n try:\n productvariant =\\\n get_object_or_404(ProductVariant, pk=item_id)\n for item_id, item_data in cart[item_id].items():\n if item_id == 'qty':\n quantity = item_data\n\n order_line_item = OrderLineItem(\n order=order,\n productvariant=productvariant,\n quantity=quantity,\n )\n order_line_item.save()\n except ProductVariant.DoesNotExist:\n messages.error(request, (\n \"One of the products in your \\\n shoppincart wasn't found in our database.\")\n )\n order.delete()\n return redirect(reverse('view_cart'))\n request.session['save_info'] = 'save-info' in request.POST\n return redirect(reverse('checkout_success',\n args=[order.order_number]))\n else:\n messages.error(request, 'There was an error with your form. \\\n Please double check your information.')\n\n else:\n cart = request.session.get('cart', {})\n if not cart:\n messages.error(request,\n \"There's nothing in your \\\n shopping cart at the moment\")\n return redirect(reverse('view_cart'))\n current_cart = cart_content(request)\n total = current_cart['grand_total']\n stripe_total = round(total * 100)\n stripe.api_key = stripe_secret_key\n intent = stripe.PaymentIntent.create(\n amount=stripe_total,\n currency=settings.STRIPE_CURRENCY,\n )\n\n \"\"\"\n Attempt to prefill the form\n From datathe user maintains in their useraccount\n \"\"\"\n\n if request.user.is_authenticated:\n try:\n profile = UserAccount.objects.get(user=request.user)\n order_form = OrderForm(initial={\n 'first_name': profile.user.first_name,\n 'last_name': profile.user.last_name,\n 'email': profile.user.email,\n 'phone_number': profile.default_phone_number,\n 'country': profile.default_country,\n 'zipcode': profile.default_zipcode,\n 'town_or_city': profile.default_town_or_city,\n 'street_address1': profile.default_street_address1,\n 'street_address2': profile.default_street_address2,\n })\n except UserAccount.DoesNotExist:\n order_form = OrderForm()\n else:\n order_form = OrderForm()\n\n if not stripe_public_key:\n messages.warning(request, 'Stripe public key is missing. \\\n Did you forget to set in in your env?')\n\n template = 'checkout/checkout.html'\n context = {\n 'order_form': order_form,\n 'stripe_public_key': stripe_public_key,\n 'client_secret': intent.client_secret,\n }\n\n return render(request, template, context)\n\n\ndef checkout_success(request, order_number):\n \"\"\"\n Handle successful checkouts\n Based on the Botique Ado CI Project and modified to fit this project.\n \"\"\"\n\n save_info = request.session.get('save_info')\n order = get_object_or_404(Order, order_number=order_number)\n\n if request.user.is_authenticated:\n profile = UserAccount.objects.get(user=request.user)\n # Attach the user's profile to the order\n order.user_profile = profile\n order.save()\n\n # Save the user's info\n if save_info:\n profile_data = {\n 'default_phone_number': order.phone_number,\n 'default_country': order.country,\n 'default_zipcode': order.zipcode,\n 'default_town_or_city': order.town_or_city,\n 'default_street_address1': order.street_address1,\n 'default_street_address2': order.street_address2,\n }\n user_profile_form = UserAccountForm(profile_data, instance=profile)\n if user_profile_form.is_valid():\n user_profile_form.save()\n\n if 'cart' in request.session:\n del request.session['cart']\n\n template = 'checkout/checkout_success.html'\n context = {\n 'order': order,\n }\n\n return render(request, template, context)\n","sub_path":"checkout/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"611529560","text":"import requests\nfrom config.config import domain, webhook_url\nfrom discord import Webhook, WebhookAdapter, Embed, RequestsWebhookAdapter\n\n\nclass Ticket:\n\tdef __init__(self, raw_ticket, shorten = False):\n\t\tself.id = raw_ticket[\"id\"]\n\t\tself.message = raw_ticket[\"message\"]\n\n\t\t# this is used in views where we don't need FULL context\n\t\tif shorten and len(self.message) > 100:\n\t\t\tself.message = self.message[0:256]\n\t\t\tif self.message[-1:] == \" \":\n\t\t\t\tself.message = self.message[:len(self.message) - 1]\n\t\t\tself.message = self.message + \"...\\r\\n\\r\\n[ message shortened due to being too long ]\"\n\t\tself.author = raw_ticket[\"author\"]\n\t\tif self.author == \"\" or self.author.lower() == \"anon\":\n\t\t\tself.author = \"[ Anonymous ]\"\n\t\ttry:\n\t\t\tself.date_added = raw_ticket['date_added']\n\t\texcept KeyError:\n\t\t\tself.date_added = raw_ticket[b'date_added']\n\t\ttry:\n\t\t\tself.date_closed = raw_ticket['date_closed']\n\t\texcept KeyError:\n\t\t\tself.date_closed = raw_ticket[b'date_closed']\n\t\tself.is_open = raw_ticket[\"is_open\"]\n\t\tself.assigned_to = raw_ticket[\"assigned_to\"]\n\t\tself.closed_by = raw_ticket[\"closed_by\"]\n\t\tself.notes = raw_ticket[\"notes\"]\n\t\ttry:\n\t\t\tself.date_last_modified = raw_ticket[b\"date_last_modified\"]\n\t\texcept KeyError:\n\t\t\tself.date_last_modified = raw_ticket[\"date_last_modified\"]\n\t\tself.categoryID = raw_ticket[\"categoryID\"]\n\t\tself.category_name = raw_ticket[\"name\"]\n\t\tself.category_description = raw_ticket[\"description\"]\n\t\tself.urgency = raw_ticket[\"urgency\"]\n\t\tself.author_id = raw_ticket[\"author_id\"]\n\t\ttry:\n\t\t\tself.user_hash = raw_ticket[\"user_hash\"]\n\t\texcept:\n\t\t\tself.user_hash = \"\"\n\t\ttry:\n\t\t\tself.close_reason = raw_ticket[\"close_reason\"]\n\t\texcept IndexError:\n\t\t\tself.close_reason = None\n\n\tdef send_webhook_notification(self):\n\t\twebhook = Webhook.from_url(webhook_url, adapter = RequestsWebhookAdapter())\n\n\t\turl = \"https://\" + domain + \"/tickets/single?id=\" + str(self.id)\n\n\t\tem = Embed(title = \"New ticket from {} - WEB UI \".format(self.author), url = url)\n\t\tem.colour = 15667968\n\t\tem.add_field(name = \"ID\", value = self.id)\n\t\tem.add_field(name = \"Author\", value = self.author)\n\t\tem.add_field(name = \"Category\", value = self.category_name)\n\t\tem.add_field(name = \"Message\", value = self.message, inline = False)\n\t\tem.add_field(name = \"Date created\", value = str(self.date_added))\n\t\tem.add_field(name = \"Date modified\", value = str(self.date_last_modified))\n\t\tem.add_field(name = \"Link\", value = url)\n\t\ttry:\n\t\t\twebhook.send(embed = em)\n\t\texcept TypeError:\n\t\t\tpass # we think this is a bug in Discord.py, with some bad configs, so we're just praying and hoping\n","sub_path":"ticket_class.py","file_name":"ticket_class.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"297701130","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom app01 import models\n# Create your views here.\n\ndef publisher_list(request):\n ret = models.Publisher.objects.all()\n return render(request, 'publisher_list.html', {'publisher_list':ret})\n\ndef add_publisher(request):\n err_msg = \"\"\n if request.method == 'POST':\n new_name = request.POST.get('publisher_name')\n if new_name:\n models.Publisher.objects.create(name=new_name)\n return redirect('/publisher_list/')\n else:\n err_msg = \"出版社名称不能为空!\"\n return render(request, 'add_publisher.html', {\"error\":err_msg})\n\ndef delete_publisher(request):\n # 通过GET方法获取id\n del_id = request.GET.get('id', None)\n # 如果取到id,删除该数据并跳转到列表页,否则提示失败\n if del_id:\n # 通过id拿到药删除的数据对象\n del_obj = models.Publisher.objects.get(id=del_id)\n del_obj.delete()\n return redirect('/publisher_list/')\n else:\n return HttpResponse('删除失败,该出版社不存在')\n\n# 编辑出版社\ndef edit_publisher(request):\n # 如果是POST请求,说明是要更新出版社名称\n if request.method == 'POST':\n # 获取要更新的id\n edit_id = request.POST.get(\"id\", None)\n # 获取新的名字\n new_name = request.POST.get(\"publisher_name\")\n # 通过id获得出版社对象\n publisher_obj = models.Publisher.objects.get(id=edit_id)\n # 赋值新名字\n publisher_obj.name = new_name\n # 提交到数据库中执行\n publisher_obj.save()\n\n return redirect('/publisher_list/')\n\n edit_id = request.GET.get(\"id\", None)\n if edit_id:\n publisher_obj = models.Publisher.objects.get(id=edit_id)\n return render(request, 'edit_publisher.html', {\"publisher\":publisher_obj})\n else:\n return HttpResponse('编辑的出版社不存在!')\n\n# 展示全部书籍内容\ndef book_list(request):\n all_book = models.Book.objects.all()\n return render(request, \"book_list.html\", {\"book_list\":all_book})\n\ndef add_book(request):\n if request.method == 'POST':\n new_book_name = request.POST.get(\"book_name\")\n publisher_id = request.POST.get(\"publisher_id\")\n models.Book.objects.create(title=new_book_name, publisher_id=publisher_id)\n return redirect('/book_list/')\n all_publisher = models.Publisher.objects.all()\n return render(request, \"add_book.html\", {\"all_publisher\":all_publisher})\n\n\ndef delete_book(request):\n del_id = request.GET.get(\"id\")\n del_book_obj = models.Book.objects.get(id=del_id)\n del_book_obj.delete()\n return redirect('/book_list/')\n\ndef edit_book(request):\n if request.method == 'POST':\n edit_id = request.POST.get(\"id\")\n\n new_title = request.POST.get(\"book_title\")\n new_publisher_id = request.POST.get(\"publisher\")\n\n edit_obj = models.Book.objects.get(id=edit_id)\n edit_obj.title = new_title\n edit_obj.publisher_id = new_publisher_id\n edit_obj.save()\n return redirect('/book_list/')\n\n edit_id = request.GET.get(\"id\")\n edit_obj = models.Book.objects.get(id=edit_id)\n all_publisher = models.Publisher.objects.all()\n return render(request,\n \"edit_book.html\",\n {\"all_publisher\":all_publisher,\n \"edit_obj\":edit_obj\n }\n )","sub_path":"s9day63/mysiteday63/app01/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"506972004","text":"# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n# multiple iteration, loss calculation, stop condition, predication\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\nx_data_name = \"TemperatureControlXData.dat\"\ny_data_name = \"TemperatureControlYData.dat\"\n\n\nclass CData(object):\n def __init__(self, loss, w, b, epoch, iteration):\n self.loss = loss\n self.w = w\n self.b = b\n self.epoch = epoch\n self.iteration = iteration\n\n\ndef ReadData():\n Xfile = Path(x_data_name)\n Yfile = Path(y_data_name)\n if Xfile.exists() & Yfile.exists():\n X = np.load(Xfile)\n Y = np.load(Yfile)\n return X.reshape(1, -1), Y.reshape(1, -1)\n else:\n return None, None\n\n\ndef ForwardCalculationBatch(W, B, batch_x):\n Z = np.dot(W, batch_x) + B\n return Z\n\n\ndef BackPropagationBatch(batch_x, batch_y, batch_z):\n m = batch_x.shape[1]\n dZ = batch_z - batch_y\n dB = dZ.sum(axis=1, keepdims=True) / m\n dW = np.dot(dZ, batch_x.T) / m\n return dW, dB\n\n\ndef UpdateWeights(w, b, dW, dB, eta):\n w = w - eta * dW\n b = b - eta * dB\n return w, b\n\n\ndef InitialWeights(num_input, num_output, flag):\n if flag == 0:\n # zero\n W = np.zeros((num_output, num_input))\n elif flag == 1:\n # normalize\n W = np.random.normal(size=(num_output, num_input))\n elif flag == 2:\n # xavier\n W = np.random.uniform(\n -np.sqrt(6 / (num_input + num_output)),\n np.sqrt(6 / (num_input + num_output)),\n size=(num_output, num_input))\n\n B = np.zeros((num_output, 1))\n return W, B\n\n\ndef ShowResult(X, Y, w, b, iteration):\n # draw sample data\n plt.plot(X, Y, \"b.\")\n # draw predication data\n PX = np.linspace(0, 1, 10)\n PZ = w * PX + b\n plt.plot(PX, PZ, \"r\")\n plt.title(\"Air Conditioner Power\")\n plt.xlabel(\"Number of Servers(K)\")\n plt.ylabel(\"Power of Air Conditioner(KW)\")\n plt.show()\n print(\"iteration=\", iteration)\n print(\"w=%f,b=%f\" % (w, b))\n\n\ndef CheckLoss(W, B, X, Y):\n m = X.shape[1]\n Z = np.dot(W, X) + B\n LOSS = (Z - Y) ** 2\n loss = LOSS.sum() / m / 2\n return loss\n\n\ndef GetBatchSamples(X, Y, batch_size):\n Sample_index = np.random.permutation(X.shape[1])\n Sample_group = X.shape[1] // batch_size\n for every_batch in np.array_split(Sample_index, Sample_group):\n batch_x, batch_y = X[every_batch], Y[every_batch]\n yield batch_x, batch_y\n\n\ndef GetMinimalLossData(dict_loss):\n key = sorted(dict_loss.keys())[0]\n w = dict_loss[key].w\n b = dict_loss[key].b\n return w, b, dict_loss[key]\n\n\ndef ShowLossHistory(dict_loss, method):\n loss = []\n for key in dict_loss:\n loss.append(key)\n\n # plt.plot(loss)\n plt.plot(loss[30:800])\n plt.title(method)\n plt.xlabel(\"epoch\")\n plt.ylabel(\"loss\")\n plt.show()\n\n\ndef loss_2d(x, y, n, dict_loss, method, cdata):\n result_w = cdata.w[0, 0]\n result_b = cdata.b[0, 0]\n\n # show contour of loss\n s = 150\n W = np.linspace(result_w - 1, result_w + 1, s)\n B = np.linspace(result_b - 1, result_b + 1, s)\n LOSS = np.zeros((s, s))\n for i in range(len(W)):\n for j in range(len(B)):\n w = W[i]\n b = B[j]\n a = w * x + b\n loss = CheckLoss(w, b, x, y)\n LOSS[i, j] = np.round(loss, 2)\n # end for j\n # end for i\n print(\"please wait for 20 seconds...\")\n while (True):\n X = []\n Y = []\n is_first = True\n loss = 0\n for i in range(len(W)):\n for j in range(len(B)):\n if LOSS[i, j] != 0:\n if is_first:\n loss = LOSS[i, j]\n X.append(W[i])\n Y.append(B[j])\n LOSS[i, j] = 0\n is_first = False\n elif LOSS[i, j] == loss:\n X.append(W[i])\n Y.append(B[j])\n LOSS[i, j] = 0\n # end if\n # end if\n # end for j\n # end for i\n if is_first == True:\n break\n plt.plot(X, Y, '.')\n # end while\n\n # show w,b trace\n w_history = []\n b_history = []\n for key in dict_loss:\n w = dict_loss[key].w[0, 0]\n b = dict_loss[key].b[0, 0]\n if w < result_w - 1 or result_b - 1 < 2:\n continue\n if key == cdata.loss:\n break\n # end if\n w_history.append(w)\n b_history.append(b)\n # end for\n plt.plot(w_history, b_history)\n\n plt.xlabel(\"w\")\n plt.ylabel(\"b\")\n title = str.format(\"Method={0}, Epoch={1}, Iteration={2}, Loss={3:.3f}, W={4:.3f}, B={5:.3f}\", method, cdata.epoch,\n cdata.iteration, cdata.loss, cdata.w[0, 0], cdata.b[0, 0])\n plt.title(title)\n plt.show()\n\n\ndef InitializeHyperParameters(method):\n if method == \"SGD\":\n eta = 0.1\n max_epoch = 50\n batch_size = 1\n elif method == \"MiniBatch\":\n eta = 0.1\n max_epoch = 50\n batch_size = 10\n elif method == \"FullBatch\":\n eta = 0.5\n max_epoch = 1000\n batch_size = 200\n return eta, max_epoch, batch_size\n\n\nif __name__ == '__main__':\n\n # 修改method分别为下面三个参数,运行程序,对比不同的运行结果\n # SGD, MiniBatch, FullBatch\n method = \"MiniBatch\"\n\n eta, max_epoch, batch_size = InitializeHyperParameters(method)\n\n W, B = InitialWeights(1, 1, 0)\n # calculate loss to decide the stop condition\n loss = 5\n dict_loss = {}\n # read data\n X, Y = ReadData()\n # count of samples\n num_example = X.shape[1]\n num_feature = X.shape[0]\n\n # if num_example=200, batch_size=10, then iteration=200/10=20\n max_iteration = (int)(num_example / batch_size)\n for epoch in range(max_epoch):\n print(\"epoch=%d\" % epoch)\n for batch_x, batch_y in GetBatchSamples(X, Y, batch_size):\n # get x and y value for one sample\n # get z from x,y\n batch_z = ForwardCalculationBatch(W, B, batch_x)\n # calculate gradient of w and b\n dW, dB = BackPropagationBatch(batch_x, batch_y, batch_z)\n # update w,b\n W, B = UpdateWeights(W, B, dW, dB, eta)\n\n # calculate loss for this batch\n loss = CheckLoss(W, B, X, Y)\n print(epoch, iteration, loss, W, B)\n prev_loss = loss\n\n dict_loss[loss] = CData(loss, W, B, epoch, iteration)\n # end for\n # end for\n ShowLossHistory(dict_loss, method)\n w, b, cdata = GetMinimalLossData(dict_loss)\n print(cdata.w, cdata.b)\n print(\"epoch=%d, iteration=%d, loss=%f\" % (cdata.epoch, cdata.iteration, cdata.loss))\n\n # ShowResult(X, Y, W, B, epoch)\n print(w, b)\n\n x = 346 / 1000\n result = ForwardCalculationBatch(w, b, x)\n print(result)\n\n loss_2d(X, Y, 200, dict_loss, method, cdata)\n","sub_path":"tiduxiajiang.py","file_name":"tiduxiajiang.py","file_ext":"py","file_size_in_byte":7071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"486407076","text":"import requests\nimport os\n\n\ndef update_headers(session_to_update):\n session_to_update.headers.update({\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:45.0) Gecko/20100101 Firefox/45.0'\n })\n\n\ndef load_weather_page(city_id, year, month):\n url = \"https://www.gismeteo.ru/diary/{0}/{1}/{2}/\".format(int(city_id), int(year), int(month))\n return session.get(url).text\n\n\ndef load_weather_pages_to_files(year_from, month_from, year_to, month_to, city_id, city_name):\n prefix = \"./weather_story/\"\n subdir = \"/raw\"\n current_year = year_from\n current_month = month_from\n\n while current_year - year_to != -1 and current_month - month_to != -1:\n data = load_weather_page(city_id, current_year, current_month)\n\n final_path = prefix + city_name + subdir\n if not os.path.exists(final_path):\n os.makedirs(final_path)\n\n with open(final_path + \"/{0}_{1}.html\".format(int(current_year), int(current_month)),\n 'wb') as output_file:\n output_file.write(data.encode('utf8'))\n current_month -= 1\n\n if current_month == 0:\n current_month = 12\n current_year -= 1\n\n\nsession = requests.Session()\nupdate_headers(session)\n\n# fill in these params!\ncity_id_param = 14771\n# folder name actually\ncity_name_param = \"kronshtadt\"\n\nyear_from_param = 2018\nmonth_from_param = 3\nyear_to_param = 2015\nmonth_to_param = 1\n\nload_weather_pages_to_files(\n year_from_param,\n month_from_param,\n year_to_param,\n month_to_param,\n city_id_param,\n city_name_param)\n\n\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"109876200","text":"# Universidad del Valle de Guatemala\r\n# Graficas por Computadora - Seccion 10\r\n# Maria Fernanda Estrada 14198\r\n# Cargar un archivo obj y leer/mostrar lo que lleva dentro\r\n# Codigo base en ejemplo visto en clase\r\n\r\n\r\n\r\n\r\n\r\nimport struct\r\nimport Funciones2 as imagen\r\nfrom random import randint\r\nfrom collections import namedtuple\r\nfrom math import sin, cos\r\n\r\n# Vectores\r\nV2 = namedtuple('Vertex2', ['x', 'y'])\r\nV3 = namedtuple('Vertex3', ['x', 'y', 'z'])\r\n\r\n\r\n# Clase que carga el obj, lee el obj y dibuja el modelo\r\nclass Obj(object):\r\n\r\n # Constructor\r\n def __init__(self, filename, filenameMaterial = None):\r\n # Para leer el archivo\r\n with open(filename) as f:\r\n self.lines = f.read().splitlines()\r\n # Para leer el archivo de materiales\r\n if filenameMaterial:\r\n with open(filenameMaterial) as f:\r\n self.linesMtl = f.read().splitlines()\r\n # Inicializar todo en cero y leer\r\n self.vertices = []\r\n self.tvertices = []\r\n self.nvertices = []\r\n self.caras = []\r\n self.materialesDic = {} # Diccionario de colores\r\n self.read()\r\n self.readMtl()\r\n\r\n \r\n # Leer e interpretar el archivo obj\r\n def read(self):\r\n materialActual = ''\r\n # Para cada linea leida en el documento\r\n for line in self.lines:\r\n # Si no esta vacia hacer lo siguiente\r\n if line:\r\n # Separar la primera letra del resto. Lo primero es el prefix v (vertice) o f (cara).\r\n prefix, value = line.split(' ', 1) # Se coloca 1 para que tome 1 linea a la vez\r\n # Si es un vertice, colocar en el array de vertices\r\n if prefix == 'v':\r\n # Separa los valores despues de la v por espacios, los mapea a un float (cast) y los vuelve una lista despues a los tres\r\n listaV = list(map(float, value.split(' ')))\r\n self.vertices.append(listaV)\r\n # Si es un vertice de textura, colocar en el array de vertices de textura\r\n elif prefix == 'vt':\r\n # Separa los valores despues de la vt por espacios, los mapea a un float (cast) y los vuelve una lista despues a los tres\r\n listaVt = list(map(float, value.split(' ')))\r\n self.tvertices.append(listaVt)\r\n elif prefix == 'vn':\r\n # Separa los valores despues de la vt por espacios, los mapea a un float (cast) y los vuelve una lista despues a los tres\r\n listaVN = list(map(float, value.split(' ')))\r\n self.nvertices.append(listaVN)\r\n # Si es una cara, colocar en el array de caras. Este sera un array de arrays\r\n elif prefix == 'f':\r\n # Separar por espacio\r\n listaF1 = value.split(' ')\r\n listaX = []\r\n # Ahora separar por guiones y castear a int\r\n for cara in listaF1:\r\n listaF2 = cara.split('/')\r\n listaF = []\r\n for l2 in listaF2:\r\n if l2:\r\n listaF.append(int(l2))\r\n else:\r\n listaF.append(0)\r\n # Se guarda el material antes de las caras a las que se aplicaran\r\n listaF.append(materialActual)\r\n listaX.append(listaF)\r\n self.caras.append(listaX)\r\n # Para ver que material es el que toca a ciertas caras\r\n elif prefix == 'usemtl':\r\n materialActual = value\r\n\r\n # Leer e interpretar el archivo mtl\r\n def readMtl(self):\r\n # Guardar el nombre del material\r\n nombreMaterial = ''\r\n for line in self.linesMtl:\r\n # Si no esta vacia hacer lo siguiente\r\n if line:\r\n prefix, value = line.split(' ', 1) # Se coloca 1 para que tome 1 linea a la vez\r\n # Guardar el nombre de material\r\n if prefix == 'newmtl':\r\n nombreMaterial = value\r\n # Guardar los valores rgb de ese material en un diccionario\r\n elif prefix == 'Kd':\r\n coloresStr = value.split(' ')\r\n listaColores = list(map(float, coloresStr))\r\n self.materialesDic[nombreMaterial] = listaColores\r\n\r\n # Funcion para modificar cada vector dado\r\n def transformar(self, vertice):\r\n\r\n # Se define un vector de 4 dimensiones al agregarle un 1 al final\r\n vertice4D = [[vertice.x, 0, 0, 0], \r\n [vertice.y, 0, 0, 0], \r\n [vertice.z, 0, 0, 0], \r\n [1, 0, 0, 0]]\r\n # Se aplican todas las matrices de transformacion\r\n vertice_t = imagen.matrixMult(self.ViewPort, imagen.matrixMult(self.Perspectiva, imagen.matrixMult(self.View, imagen.matrixMult(self.Modelo, vertice4D))))\r\n\r\n # Ahora, que ya se transformo el vertice, se debe regresar a 3D. Se divide por la cuarta componente\r\n vertice_t = [int((vertice_t[0][0]/vertice_t[3][0])),\r\n int((vertice_t[1][0]/vertice_t[3][0])),\r\n int((vertice_t[2][0]/vertice_t[3][0]))]\r\n return V3(*vertice_t)\r\n\r\n # Mandar los vertices y caras a la funcion glLine (en valores de -1 a 1 para traslacion y escala) (valores de 0 a 1 para textura)\r\n def load(self, traslacion = (0, 0, 0), escala = (1, 1, 1), rotacion = (0, 0, 0), textura = None):\r\n\r\n # Generar matriz de modelo ya modificado y del viewport\r\n self.PipelineModelo(traslacion, escala, rotacion)\r\n self.PipelineViewPort()\r\n\r\n luz = V3(0, 0, 1) # La luz solo vendra hacia la pantalla, eje z\r\n\r\n for cara in self.caras:\r\n # Se agrega el valor en z que nos interesa para el zbuffer\r\n x1 = (self.vertices[cara[0][0] - 1][0])\r\n y1 = (self.vertices[cara[0][0] - 1][1])\r\n z1 = (self.vertices[cara[0][0] - 1][2])\r\n x2 = (self.vertices[cara[1][0] - 1][0])\r\n y2 = (self.vertices[cara[1][0] - 1][1])\r\n z2 = (self.vertices[cara[1][0] - 1][2])\r\n x3 = (self.vertices[cara[2][0] - 1][0])\r\n y3 = (self.vertices[cara[2][0] - 1][1])\r\n z3 = (self.vertices[cara[2][0] - 1][2])\r\n\r\n # Ya con los valores convertidos, se crean los vectores v1, v2 y v3\r\n v1 = self.transformar(V3(x1, y1, z1))\r\n v2 = self.transformar(V3(x2, y2, z2))\r\n v3 = self.transformar(V3(x3, y3, z3))\r\n\r\n nx1 = self.nvertices[cara[0][2] - 1][0]\r\n ny1 = self.nvertices[cara[0][2] - 1][1]\r\n nz1 = self.nvertices[cara[0][2] - 1][2]\r\n nx2 = self.nvertices[cara[1][2] - 1][0]\r\n ny2 = self.nvertices[cara[1][2] - 1][1]\r\n nz2 = self.nvertices[cara[1][2] - 1][2]\r\n nx3 = self.nvertices[cara[2][2] - 1][0]\r\n ny3 = self.nvertices[cara[2][2] - 1][1]\r\n nz3 = self.nvertices[cara[2][2] - 1][2]\r\n\r\n n1 = V3(nx1, ny1, nz1)\r\n n2 = V3(nx2, ny2, nz2)\r\n n3 = V3(nx3, ny3, nz3)\r\n\r\n # Si no hay textura, colocar el color de los materiales\r\n if not textura:\r\n # Pintar el color del material guardado por la intensidad para darle luz\r\n colorbg = V3(self.materialesDic[cara[0][3]][0], self.materialesDic[cara[0][3]][1], self.materialesDic[cara[0][3]][2])\r\n imagen.triangle(v1, v2, v3, n1, n2, n3, colorbg)\r\n else:\r\n # Como los valores en la textura van de 0 a 1, ya no se necesitan convertir. Solo se resta 1 porque comienza en 1\r\n eq1 = int(textura.width * ((self.tvertices[cara[0][1] - 1][0]))) - 1\r\n ye1 = int(textura.height * ((self.tvertices[cara[0][1] - 1][1]))) - 1\r\n eq2 = int(textura.width * ((self.tvertices[cara[1][1] - 1][0]))) - 1\r\n ye2 = int(textura.height * ((self.tvertices[cara[1][1] - 1][1]))) - 1\r\n eq3 = int(textura.width * ((self.tvertices[cara[2][1] - 1][0]))) - 1\r\n ye3 = int(textura.height * ((self.tvertices[cara[2][1] - 1][1]))) - 1\r\n\r\n # Se crean los nuevos vectores de texturas\r\n t1 = V3(eq1, ye1, 0)\r\n t2 = V3(eq2, ye2, 0)\r\n t3 = V3(eq3, ye3, 0)\r\n\r\n # Hacer el triangulo\r\n imagen.triangle(v1, v2, v3, n1, n2, n3, t1, t2, t3, textura)\r\n\r\n # Funcion que manda en donde se encuentra la camara\r\n def VistaCam(self, observador, centro, arriba):\r\n\r\n # La definicion de cada ecuacion se vio en clase de forma grafica\r\n z = imagen.norm(imagen.resta(observador, centro))\r\n x = imagen.norm(imagen.cruz(arriba, z))\r\n y = imagen.norm(imagen.cruz(z, x))\r\n\r\n # Llamar a las matrices\r\n # El coeficiente para la perspectiva es estandar\r\n self.PipelineView(x, y, z, centro)\r\n self.PipelinePerspectiva(-1/(imagen.largov(imagen.resta(observador, centro))))\r\n \r\n # Se obtiene una matriz que modifica el modelo en si (se traslada, rota y escala)\r\n # Pasamos a WORLD SPACE, todos los puntos relativos al centro del mundo\r\n def PipelineModelo(self, traslacion, escala, rotacion):\r\n \r\n # Como los parametros se pasan como puntos, se deben convertir a V3\r\n traslacion = V3(*traslacion)\r\n escala = V3(*escala)\r\n rotacion = V3(*rotacion)\r\n\r\n # Matriz de traslacion (se mostro en la pp la matriz)\r\n traslacion_m = [[1, 0, 0, traslacion.x],\r\n [0, 1, 0, traslacion.y],\r\n [0, 0, 1, traslacion.z],\r\n [0, 0, 0, 1]]\r\n\r\n # Matriz de escala (se mostro en la pp la matriz)\r\n escala_m = [[escala.x, 0, 0, 0],\r\n [0, escala.y, 0, 0],\r\n [0, 0, escala.z, 0],\r\n [0, 0, 0, 1]]\r\n \r\n # Definir angulos de rotacion\r\n ax = rotacion.x\r\n ay = rotacion.y\r\n az = rotacion.z\r\n\r\n # Matriz X de rotacion (se mostro en la pp la matriz)\r\n rotacion_mX = [[1, 0, 0, 0],\r\n [0, cos(ax), -sin(ax), 0],\r\n [0, sin(ax), cos(ax), 0],\r\n [0, 0, 0, 1]]\r\n \r\n # Matriz Y de rotacion (se mostro en la pp la matriz)\r\n rotacion_mY = [[cos(ay), 0, sin(ay), 0],\r\n [0, 1, 0, 0],\r\n [-sin(ay), 0, cos(ay), 0],\r\n [0, 0, 0, 1]]\r\n \r\n # Matriz Z de rotacion (se mostro en la pp la matriz)\r\n rotacion_mZ = [[cos(az), -sin(az), 0, 0],\r\n [sin(az), cos(az), 0, 0],\r\n [0, 0, 1, 0],\r\n [0, 0, 0, 1]]\r\n \r\n # Matriz de rotacion total (se mostro en la pp la matriz)\r\n rotacion_m = imagen.matrixMult(rotacion_mX, imagen.matrixMult(rotacion_mY, rotacion_mZ))\r\n\r\n # Generar la matriz con las operaciones deseadas\r\n self.Modelo = imagen.matrixMult(traslacion_m, imagen.matrixMult(rotacion_m, escala_m))\r\n\r\n # Se obtiene una matriz que modifica el origen de la vista\r\n # Pasamos a CAMERA SPACE, todos los puntos relativos a la posicion de la camara\r\n def PipelineView(self, x, y, z, centro):\r\n\r\n # Como los parametros se pasan como puntos, se deben convertir a V3\r\n x = V3(*x)\r\n y = V3(*y)\r\n z = V3(*z)\r\n centro = V3(*centro)\r\n\r\n # Matriz inversa M vista en pp\r\n M = [[x.x, x.y, x.z, 0],\r\n [y.x, y.y, y.z, 0],\r\n [z.x, z.y, z.z, 0],\r\n [0, 0, 0, 1]]\r\n\r\n # Matriz para definir origen de camara vista en pp\r\n O = [[1, 0, 0, -centro.x],\r\n [0, 1, 0, -centro.y],\r\n [0, 0, 1, -centro.z],\r\n [0, 0, 0, 1]]\r\n \r\n # Matriz de view\r\n self.View = imagen.matrixMult(M, O)\r\n\r\n # Se agrega perspectiva al modelo\r\n def PipelinePerspectiva(self, coeficiente):\r\n \r\n # Matriz perspectiva al modelo\r\n self.Perspectiva = [[1, 0, 0, 0],\r\n [0, 1, 0, 0],\r\n [0, 0, 1, 0],\r\n [0, 0, coeficiente, 1]]\r\n\r\n # Por ultimo, se modifica el viewport donde se dibujara el modelo\r\n def PipelineViewPort(self, x = 0, y = 0):\r\n self.ViewPort = [[imagen.bm.width/2, 0, 0, x + imagen.bm.width/2],\r\n [0, imagen.bm.height/2, 0, y + imagen.bm.height/2],\r\n [0, 0, 128, 128],\r\n [0, 0, 0, 1]]\r\n\r\n\r\n\r\n# Clase para colocar una textura sobre el modelo\r\nclass Texture(object):\r\n\r\n # Inicializar\r\n def __init__(self, path):\r\n self.path = path\r\n self.read()\r\n \r\n # Leer archivo de textura (visto en clase)\r\n def read(self):\r\n # Se debe seguir el formato de bmp\r\n image = open(self.path, \"rb\")\r\n image.seek(10)\r\n header_size = struct.unpack(\"=l\", image.read(4))[0]\r\n image.seek(18)\r\n self.width = struct.unpack(\"=l\", image.read(4))[0]\r\n self.height = struct.unpack(\"=l\", image.read(4))[0]\r\n self.pixels = []\r\n image.seek(header_size)\r\n # Se lee el color de cada pixel y se guarda en un array\r\n for y in range(self.height):\r\n self.pixels.append([])\r\n for x in range(self.width):\r\n b = ord(image.read(1))\r\n g = ord(image.read(1))\r\n r = ord(image.read(1))\r\n self.pixels[y].append(imagen.color(r, g, b))\r\n image.close()\r\n\r\n # Obtener el color del pixel\r\n def get_Color(self, tx, ty):\r\n x = int(tx)\r\n y = int(ty)\r\n return self.pixels[y][x]\r\n\r\n# ------------------------------------- Fondo --------------------------------\r\n\r\ndef Background(imagen):\r\n background = Texture('bg.bmp')\r\n for x in range(imagen.bm.width):\r\n for y in range(imagen.bm.height):\r\n imagen.bm.framebuffer[y][x] = background.pixels[y][x]\r\n\r\n\r\n\r\n# ------------------------------------- Personajes --------------------------------\r\n\r\ndef Characters():\r\n \r\n # ------ FIGHTER KIRBY ------\r\n objFighterKirby = Obj('FighterKirby.obj', 'FighterKirby.mtl') # Cargar el contenido del obj\r\n # Donde se encuentra la camara en general para todos los modelos\r\n objFighterKirby.VistaCam(V3(0, 0, 2.5), V3(0, 0, 0), V3(0, 1, 0))\r\n # Dibujar el contenido del obj segun posicion en pantalla\r\n objFighterKirby.load((0.5, -0.2, 0), (0.5, 0.5, 0.5), (0, -0.5, 0))\r\n\r\n # ------ SLEEPY KIRBY ------\r\n objSleepKirby = Obj('SleepKirby.obj', 'SleepKirby.mtl') # Cargar el contenido del obj\r\n # Donde se encuentra la camara en general para todos los modelos\r\n objSleepKirby.VistaCam(V3(0, 0, 2.5), V3(0, 0, 0), V3(0, 1, 0))\r\n # Dibujar el contenido del obj segun posicion en pantalla\r\n objSleepKirby.load((-0.5, -0.05, 0), (0.5, 0.5, 0.5), (0, 0.3, 0))\r\n\r\n # ------ ICE KIRBY ------\r\n objIceKirby = Obj('IceKirby.obj', 'IceKirby.mtl') # Cargar el contenido del obj\r\n # Donde se encuentra la camara en general para todos los modelos\r\n objIceKirby.VistaCam(V3(0, 0, 2.5), V3(0, 0, 0), V3(0, 1, 0))\r\n # Dibujar el contenido del obj segun posicion en pantalla\r\n objIceKirby.load((-0.5, -0.85, 0), (0.2, 0.2, 0.2), (0, 0, 0))\r\n\r\n # ------ TORNADO KIRBY ------\r\n objTornadoKirby = Obj('TornadoKirby.obj', 'TornadoKirby.mtl') # Cargar el contenido del obj\r\n # Donde se encuentra la camara en general para todos los modelos\r\n objTornadoKirby.VistaCam(V3(0, 0, 2.5), V3(0, 0, 0), V3(0, 1, 0))\r\n # Dibujar el contenido del obj segun posicion en pantalla\r\n objTornadoKirby.load((0, -0.85, 0), (0.2, 0.2, 0.2), (0, 0, 0))\r\n\r\n # ------ WING KIRBY ------\r\n objWingKirby = Obj('WingKirby.obj', 'WingKirby.mtl') # Cargar el contenido del obj\r\n # Donde se encuentra la camara en general para todos los modelos\r\n objWingKirby.VistaCam(V3(0, 0, 2.5), V3(0, 0, 0), V3(0, 1, 0))\r\n # Dibujar el contenido del obj segun posicion en pantalla\r\n objWingKirby.load((0.5, -0.85, 0), (0.2, 0.2, 0.2), (0, 0, 0))\r\n\r\n\r\n\r\n\r\n\r\n\r\n# ------ Configuracion pantalla ------\r\nimagen.glInit() # Inicializar SR1\r\nimagen.glCreateWindow(1000,1000) # Cambia el tamano del window a 1500x1500\r\nimagen.glClearColor(0, 0, 0) # Cambia el color de la ventana a negro\r\nimagen.glClear() # Clear a ventana\r\nimagen.glViewPort(0, 0, 1000, 1000) # Especificar en donde se dibujara\r\nBackground(imagen)# Poner fondo\r\nCharacters() # Poner personajes\r\nimagen.glFinish() # Generar la imagen","sub_path":"SR6Obj2.py","file_name":"SR6Obj2.py","file_ext":"py","file_size_in_byte":16790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"235485721","text":"#!/usr/bin/env python\nimport re\nfrom sys import argv\nimport os.path\nimport ROOT\n\nROOT.gROOT.SetBatch(True)\n\nfrom pprint import pprint\nfrom optparse import OptionParser\nfrom tdrStyle import setTDRStyle\nimport CMS_lumi\nparser = OptionParser()\nparser.add_option(\"-i\", type=\"string\", dest=\"indir\" , default=\"./\", help=\"combine output file\")\nparser.add_option(\"-n\", type=\"string\", dest=\"outnm\" , default=\"nuisances\", help=\"the filename for the plot\")\nparser.add_option(\"-o\", type=\"string\", dest=\"outdir\" , default=\"./\", help=\"the base filename for the plot\")\nparser.add_option(\"--extraText\", type=\"string\", dest=\"exText\" , default=\"\", help=\"additional text to plot\")\n\n(options, args) = parser.parse_args()\n\nfIn = ROOT.TFile(options.indir)\nws = fIn.Get(\"w\")\nsnap = ws.getSnapshot(\"HybridNew_mc_s__snapshot\")\nc = ROOT.TCanvas(\"\",\"\",1000,400)\n\n# create base arrays for eventual tgraph\nnPoints = snap.getSize()\n\nx = ROOT.TVector(nPoints)\nex = ROOT.TVector(nPoints)\nexs = ROOT.TVector(nPoints)\ny = ROOT.TVector(nPoints)\nz = ROOT.TVector(nPoints)\ney = ROOT.TVector(nPoints) # nuisance pulls\nsg1 = ROOT.TVector(nPoints) # background graphs\nsg2 = ROOT.TVector(nPoints)\n\nxAxTitles=[]\n\n# initialize standard arrays\nfor i in xrange(0,nPoints) :\n x[i] = 0.25 + 0.5*i\n ex[i] = 0.3\n exs[i] = 0.25\n y[i] = 0\n z[i] = 0\n sg1[i] = 1\n sg2[i] = 2\n\n# get pull information and errors\nit = snap.createIterator()\nvar = it.Next()\nwhile var :\n xAxTitles+=[var.GetName()]\n var = it.Next()\n\nfor i in xrange(0,len(xAxTitles)) :\n y[i] = snap.find(xAxTitles[i]).getValV()\n ey[i] = snap.find(xAxTitles[i]).getError()\n\n# create graphs\npullGraph = ROOT.TGraphErrors(x,y,exs,ey);\nsig1Graph = ROOT.TGraphErrors(x,z,ex,sg1);\nsig2Graph = ROOT.TGraphErrors(x,z,ex,sg2);\n\n# create canvas\nc.cd()\nsetTDRStyle()\nc.SetRightMargin(0.03)\nc.SetLeftMargin(0.06)\nc.SetBottomMargin(0.25)\nc.SetGrid(0,1)\nc.cd()\n\n# format all graphs: color\npullGraph.SetFillColor(ROOT.kBlack)\npullGraph.SetLineColor(ROOT.kBlack)\npullGraph.SetMarkerStyle(20)\npullGraph.SetMarkerSize(1)\n\nsig1Graph.SetFillColor(15)\nsig2Graph.SetFillColor(17)\nsig1Graph.SetLineColor(ROOT.kNone)\nsig2Graph.SetLineColor(ROOT.kNone)\n\n# draw as a multigraph\ntotalGraph=ROOT.TMultiGraph()\ntotalGraph.Add(sig2Graph)\ntotalGraph.Add(sig1Graph)\ntotalGraph.Add(pullGraph,'p')\ntotalGraph.Draw(\"a2\")\n\n# set the bin and axis labels\nxax=totalGraph.GetXaxis()\nxax.SetTitle(\"\")\ni=0\nfor label in xAxTitles :\n bin_index = xax.FindBin(0.25+0.5*i)\n xax.SetBinLabel(bin_index,label)\n i+=1\nxax.SetRangeUser(0.088,0.5+0.5*(nPoints-1)-0.088)\nxax.SetNdivisions(0)\n\nyax=totalGraph.GetYaxis()\nyax.SetTitle(\"Pull (#sigma)\")\nyax.SetTitleOffset(0.4);\n\nCMS_lumi.relPosX = 0.090\nCMS_lumi.extraText = \"Preliminary\"\nCMS_lumi.lumiTextSize = 0.55\nCMS_lumi.extraOverCmsTextSize=0.90\nCMS_lumi.CMS_lumi(c,4,0)\n\nltx = ROOT.TLatex(0.6,0.935,options.exText)\nltx.SetNDC(ROOT.kTRUE)\nltx.SetTextSize(0.05)\nltx.Draw()\n\n# save plots\nc.Modified()\nc.Update()\nc.SaveAs(options.outdir+\"%s.pdf\"%options.outnm)\nc.SaveAs(options.outdir+\"%s.png\"%options.outnm)\n","sub_path":"TopAnalysis/test/TopWidthAnalysis/getNuisances.py","file_name":"getNuisances.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"454267155","text":"from Configuration import PARAMETERS_SIZE\nfrom FileReader import read_image_parameters\nfrom Pairs import Pair\nimport math\nimport os\nclass ImageHolder:\n def __init__(self,raw_image,path):\n self.raw_image = raw_image\n self.points = read_image_parameters(path)\n\n def get_pairs(self,image_holder):\n\n #Calculation nearest point first picture to second\n for x in range(len(self.points)):\n best_distane = float(\"inf\")\n print('Searching par for first photo{elem}/{len}'.format(elem=x,len=len(self.points)))\n for y in range(len(image_holder.points)):\n curr_value = euclides_distance(self.points[x],image_holder.points[y])\n if curr_value\")\n","sub_path":"zigpy_deconz_parser/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"88208040","text":"import os\nimport glob\nimport base64\nfrom jinja2 import Environment, PackageLoader, select_autoescape\nimport click\n\nenv = Environment(\n loader=PackageLoader('imgflat', 'templates'),\n autoescape=select_autoescape(['html', '.md']),\n)\n\n@click.command(help='A tool for creating a flat file containing all of the images in a directory inline.')\n@click.option('--output',\n default='default.md',\n help='output filename and extension')\n@click.option('--recursive',\n is_flag=True,\n default=False,\n help='Recurse through file system or use top level directory only')\ndef inline(\n output,\n recursive,\n img_types=['*.png', '*.jpg'],\n):\n \n basename = os.path.basename(os.getcwd())\n \n if output == 'default.md':\n output = f'images in {basename}.md'\n\n output_type = os.path.splitext(output)[1]\n\n if output_type in ['.markdown', '.md', '.multimarkdown', '.multi-markdown']:\n template = env.get_template('markdown.md')\n elif output_type in ['.html', '.htm']:\n template = env.get_template('html.html')\n else:\n click.echo(f'output type {output_type} not supported')\n\n if recursive:\n img_types = [f'**/*{img_type}' for img_type in img_types]\n\n files = []\n for type in img_types:\n files.extend(glob.glob(type, recursive=recursive))\n\n encoded = {}\n for file in files:\n with open(file, 'rb') as f:\n encoded[file] = base64.b64encode(f.read()).decode('utf-8')\n\n body = template.render(directory=basename, files=encoded)\n\n with open(output, 'wb') as f:\n f.write(body.encode('utf-8'))\n\nif __name__ == '__main__':\n\n inline()\n","sub_path":"imgflat/inline_img.py","file_name":"inline_img.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543029776","text":"import requests\nimport bs4\nfrom urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\n# from bs4 import BeautifulSoup\n\nmy_url = \"https://www.cbssports.com/nfl/stats/playersort/nfl/year-2018-season-post-category-touchdowns\"\n\nuClient = uReq(my_url)\n\npage_html = uClient.read()\n\nuClient.close()\n\npage_soup = soup(page_html, \"html.parser\")\n\n# print(page_soup)\n\ncontainers = page_soup.findAll(\"div\", {\"id\": \"sortableContent\"})\n\nfor container in containers:\n\trs_container = container.findAll(\"tr\",)\n\tplayer_num = 3\n\tteam_num = 3\n\tstatus = True\n\tprint (\"PLAYER\", \" | \", \"POS\", \" | \", \"TEAM\", \" | \", \"TD\")\n\twhile status:\n\t\ttry:\n\t\t\tprint (rs_container[player_num].findAll(\"td\")[0].text, \" | \", rs_container[player_num].findAll(\"td\")[1].text, \" | \", rs_container[player_num].findAll(\"td\")[2].text, \" | \", rs_container[player_num].findAll(\"td\")[6].text)\n\t\t\tplayer_num += 1\n\t\texcept:\n\t\t\tstatus = False\n\t\t\tbreak;","sub_path":"football_stats.py","file_name":"football_stats.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"12015297","text":"# 477. 汉明距离总和\n\n\nclass Solution:\n\n \"\"\"\n 统计每一bit的0的数量,然后与同位bit为1的数量相乘则为两两num比较,当前位不一样的总数\n \"\"\"\n def totalHammingDistance(self, nums: list[int]) -> int:\n max_num = max(nums)\n l = len(bin(max_num))-2\n arr = [0] * l\n for i in nums:\n for j in range(l):\n if i & 1 << (l-1-j) == 0:\n arr[j] += 1\n res = 0\n for i in arr:\n res += (i * (len(nums)-i))\n return res\n\n\n\nif __name__ == '__main__':\n print(Solution().totalHammingDistance([4,14,2]))","sub_path":"answers/totalHammingDistance.py","file_name":"totalHammingDistance.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"619945980","text":"from __future__ import division # Python 2 users only\nimport nltk, re, pprint\nfrom nltk import word_tokenize\n\n# -*- coding: cp1252 -*-\nimport os\n\n#http://stackoverflow.com/questions/5725278/python-help-using-pdfminer-as-a-library\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import TextConverter\nfrom pdfminer.layout import LAParams\nfrom pdfminer.pdfpage import PDFPage\nfrom cStringIO import StringIO\n\n#convertis le texte d'un pdf en string\ndef convert_pdf_to_txt(path):\n rsrcmgr = PDFResourceManager()\n retstr = StringIO()\n codec = 'utf-8'\n laparams = LAParams()\n device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)\n fp = file(path, 'rb')\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n password = \"\"\n maxpages = 0\n caching = True\n pagenos=set()\n for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):\n interpreter.process_page(page)\n fp.close()\n device.close()\n str = retstr.getvalue()\n retstr.close()\n return str\n\n# fait l'appel a la méthode de conversion pdf -> texte en chemin relatif\ndef convert_pdf_to_txt_from_file(pdf_path) :\n root = os.path.dirname(__file__)\n rel_path = os.path.join(pdf_path)\n abs_path = os.path.join(root, rel_path)\n return convert_pdf_to_txt(abs_path)\n\n#Stress, vigilance, communication, workload, consciousness of situation, fatigue, confidence(trust), watch out, teamwork\n# compte le nombre de mots clé choisis dans un texte.\ndef count_all(txt):\n res = txt.count(\"stress\")\n res += txt.count(\"vigilance\")\n res += txt.count(\"communication\")\n res += txt.count(\"workload\")\n res += txt.count(\"consciousness of situation\")\n res += txt.count(\"fatigue\")\n res += txt.count(\"confidence\")\n res += txt.count(\"trust\")\n res += txt.count(\"watch out\")\n res += txt.count(\"teamwork\")\n return res\n\n#de 0 à 90\ndef sortDir(nb):\n # acces au noms de tous les rapports\n root = os.path.dirname(__file__)\n rel_path = os.path.join(\"Australie\")\n abs_path = os.path.join(root, rel_path)\n FILES = os.listdir(abs_path)\n f_path = os.path.join(abs_path,FILES[nb])\n doc = convert_pdf_to_txt(f_path)\n return [FILES[nb],count_all(doc)]\n \n#tentative de gestion d'erreur qui marche pas\ndef sortDir2():\n # acces au noms de tous les rapports\n root = os.path.dirname(__file__)\n rel_path = os.path.join(\"Australie\")\n abs_path = os.path.join(root, rel_path)\n FILES = os.listdir(abs_path)\n best =[\"\",0]\n for f in FILES:\n f_path = os.path.join(abs_path,f)\n doc = convert_pdf_to_txt(f_path)\n val = count_all(doc)\n if val > best[1]:\n best = [f,val]\n print [f,val]\n return best\n\ndef getNLTKformat(texte):\n texte = texte.decode('utf8')\n return nltk.Text(word_tokenize(raw))\n\ndef getNLTKfromPDF(pdf):\n return nltk.Text(word_tokenize(convert_pdf_to_txt_from_file(pdf).decode('utf-8')))\n","sub_path":"testsubstring.py","file_name":"testsubstring.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"386662826","text":"'''Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.\n\n \n\nExample 1:\n\nInput: c = 5\nOutput: true\nExplanation: 1 * 1 + 2 * 2 = 5\nExample 2:\n\nInput: c = 3\nOutput: false\n \n\nConstraints:\n\n0 <= c <= 231 - 1'''\nclass Solution:\n def judgeSquareSum(self, c: int) -> bool:\n for i in range(int(c ** 0.5) + 1):\n j = (c - i * i) ** 0.5\n if j == int(j):\n return True\n return False\n\nprint(Solution().judgeSquareSum(5))","sub_path":"leetcode/LC633. Sum of Square Numbers.py","file_name":"LC633. Sum of Square Numbers.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"214746120","text":"#############################################################################\n# split.py\n#\n# Description: Contains functions/classess for splitting data into training/testing.\n# Options include: time-series split (sequential split) or storm split\n#############################################################################\n\nimport logging\nimport re\nfrom collections import namedtuple\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom utils import is_pandas\nfrom hydra.utils import to_absolute_path\n\nfrom storm_utils import StormAccessor, StormIndexAccessor\n\nlogger = logging.getLogger(__name__)\n\n\nTRAIN = namedtuple(\"TRAIN\", [\"X\", \"y\"])\nTEST = namedtuple(\"TEST\", [\"X\", \"y\"])\n\n\nclass StormSplitter:\n def __init__(self, times_path, seed=None):\n self.storm_times = pd.read_csv(times_path, index_col=0)\n self.rng = np.random.default_rng(seed)\n\n @property\n def storms(self):\n return self.storm_times.index\n\n @property\n def n_storms(self):\n return len(self.storms)\n\n def _storm_iter(self):\n return self.storm_times.iterrows()\n\n def _subset_data(self, X, row):\n # Subset X by one storm\n\n storm_num, storm = row\n\n if isinstance(X, pd.Series):\n X = X.to_frame()\n\n start, end = storm[\"start_time\"], storm[\"end_time\"]\n X_ = X[start:end]\n X_[\"storm\"] = storm_num\n\n return X_\n\n def _storm_label(self, X, row):\n # There's probably a more memory efficient way to do this\n return self._subset_data(X, row)[\"storm\"]\n\n def _threshold_storms(self, y, n_storms, threshold, threshold_less_than):\n\n y_groupby = y.groupby(level=\"storm\")\n\n if threshold_less_than:\n logger.debug(\"Test storms will be chosen such that min y < %s\", threshold)\n min_y = y_groupby.min()\n mask = min_y < threshold\n storms_threshold = min_y[mask.values].index\n else:\n logger.debug(\"Test storms will be chosen such that max y > %s\", threshold)\n max_y = y_groupby.max()\n mask = max_y > threshold\n storms_threshold = max_y[mask.values].index\n\n n_threshold = len(storms_threshold)\n\n # XXX\n # If # of storms that meet threshold is less than number of test storms\n # to sample, then set number of test storms to # of threshold storms\n if n_threshold < n_storms:\n n_storms = n_threshold\n logger.debug(\n \"n_storms is greater than number of thresholded storms. Setting n_storms to be %s\",\n n_storms,\n )\n\n # Randomly sample thresholded storms\n test_storms = self.rng.choice(storms_threshold, size=n_storms, replace=False)\n\n return test_storms\n\n def _storms_subsetted(self, x):\n # Check if data has been subsetted for storms\n subsetted = False\n\n if isinstance(x.index, pd.MultiIndex):\n # Has MultiIndex\n\n if \"storm\" in x.index.names and \"times\" in x.index.names:\n # MultiIndex has level 'storm' and \"times\"\n subsetted = True\n\n return subsetted\n\n def get_storm_labels(self, x):\n\n if self._storms_subsetted(x):\n return x.index.to_frame().set_index([\"times\"])\n else:\n storm_labels_iter = (\n self._storm_label(x, row) for row in self._storm_iter()\n )\n return pd.concat(storm_labels_iter)\n\n def train_test_split(\n self,\n X,\n y,\n test_size=0.2,\n train_storms=None,\n test_storms=None,\n delete_storms=None,\n threshold=None,\n threshold_less_than=True,\n ):\n\n # If data doesn't have storm index yet, subset it using subset_data\n if not self._storms_subsetted(X):\n X = self.subset_data(X)\n if not self._storms_subsetted(y):\n y = self.subset_data(y)\n\n if \"test\" in self.storm_times:\n test_storms = self.storm_times.query(\"test == True\").index\n elif test_storms is None:\n\n is_float = isinstance(test_size, float)\n is_int = isinstance(test_size, int)\n assert is_float or is_int\n\n if is_int and test_size >= 1:\n n_test = test_size\n elif test_size < 1:\n n_test = int(round(test_size * self.n_storms))\n\n if threshold is None:\n # Choose test storms randomly\n test_storms = self.rng.choice(self.storms, size=n_test)\n else:\n # Choose test storms that cross threshold\n test_storms = self._threshold_storms(\n y, n_test, threshold, threshold_less_than\n )\n\n if \"train\" in self.storm_times:\n train_storms = self.storm_times.query(\"test == False\").index\n if train_storms is None or len(train_storms) == 0:\n train_mask = ~self.storms.isin(test_storms)\n train_storms = self.storms[train_mask]\n\n if delete_storms is not None:\n test_storms = np.setdiff1d(test_storms, delete_storms)\n train_storms = np.setdiff1d(train_storms, delete_storms)\n\n logger.debug(\"There are %s test storms.\", len(test_storms))\n logger.debug(\"There are %s train storms.\", len(train_storms))\n\n X_train = X.reindex(train_storms, level=\"storm\")\n y_train = y.reindex(train_storms, level=\"storm\")\n X_test = X.reindex(test_storms, level=\"storm\")\n y_test = y.reindex(test_storms, level=\"storm\")\n\n return TRAIN(X_train, y_train), TEST(X_test, y_test)\n\n def subset_data(self, X):\n\n X_storms_iter = (self._subset_data(X, row) for row in self._storm_iter())\n\n X_storms = pd.concat(X_storms_iter)\n X_storms.set_index([X_storms[\"storm\"], X_storms.index], inplace=True)\n X_storms.drop(columns=[\"storm\"], inplace=True)\n\n return X_storms\n\n\ndef split_data_storms(\n X,\n y,\n test_size=0.2,\n storm_times=\"data/stormtimes.csv\",\n train_storms=None,\n test_storms=None,\n delete_storms=None,\n threshold=None,\n threshold_less_than=True,\n seed=None,\n **kwargs,\n):\n # Wrapper around StormSplitter.train_test_split\n\n storm_times = to_absolute_path(storm_times)\n\n splitter = StormSplitter(storm_times, seed=seed)\n groups = splitter.get_storm_labels(y)\n train, test = splitter.train_test_split(\n X,\n y,\n test_size=test_size,\n train_storms=train_storms,\n test_storms=test_storms,\n delete_storms=delete_storms,\n threshold=threshold,\n threshold_less_than=threshold_less_than,\n )\n\n return train, test, groups\n\n\ndef split_data_ts(X, y, test_size=0.2, seed=None, **kwargs):\n # NOTE: **kwargs is used to absorb unused keyword arguments from Hydra\n\n test_start_idx = round(y.shape[0] * (1 - test_size))\n test_start = y.index[test_start_idx]\n\n def _split(x):\n if is_pandas(x):\n x_train, x_test = x.loc[:test_start], x.loc[test_start:]\n\n # HACK: Remove overlaps if there are any\n overlap = x_train.index.intersection(x_test.index)\n x_test.drop(index=overlap, inplace=True)\n else:\n raise TypeError(\"x must be a pandas DataFrame or series.\")\n\n # FIXME: Data is split before processed so it looks like there is time\n # overlap if times are resampled\n\n return x_train, x_test\n\n X_train, X_test = _split(X)\n y_train, y_test = _split(y)\n\n # Groups is none\n return TRAIN(X_train, y_train), TEST(X_test, y_test), None\n\n\n# Wrapper for the available split methods\ndef split_data(method, X, y, test_size=0.2, seed=None, **kwargs):\n\n logger.debug(f\"Splitting data by method: {method}\")\n\n # if method == \"storms\":\n if re.match(\"storms_.\", method):\n return split_data_storms(X, y, test_size=test_size, seed=seed, **kwargs)\n elif method == \"timeseries\":\n return split_data_ts(X, y, test_size=test_size, seed=seed, **kwargs)\n else:\n raise ValueError(f\"Split method {method} is not supported.\")\n\n\nif __name__ == \"__main__\":\n # Test\n\n from src.preprocessing.loading import load_solar_wind, load_symh\n\n X = load_solar_wind(end=\"2012-12-31\")\n y = load_symh(end=\"2012-12-31\")\n splitter = StormSplitter(\"data/stormtimes.csv\")\n\n storm_labels = splitter.get_storm_labels(y)\n\n threshold = -100\n train, test = splitter.train_test_split(X, y, test_size=5, threshold=threshold)\n assert np.all(test.y.groupby(level=\"storm\").min() < threshold)\n\n print(\"Passed!\")\n","sub_path":"split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":8645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"64075418","text":"import pygame\n\n\nclass second_NPC:\n def __init__(self, game_screen):\n self.cont_dialogue = 1\n self.game_screen = game_screen\n self.image = pygame.image.load('images/npc2.png')\n self.rect = self.image.get_rect()\n self.rect_screen = game_screen.get_rect()\n self.rect.centerx = 300\n self.rect.centery = 100\n self.dialogue_text = ''\n self.image_item = pygame.image.load('images/item2.png')\n self.rect_item = self.image_item.get_rect()\n self.rect_item_screen = game_screen.get_rect()\n self.rect_item.centerx = 300\n self.rect_item.centery = 250\n\n\n def draw(self):\n self.game_screen.blit(self.image, self.rect)\n\n\n def dialogue(self):\n if self.cont_dialogue == 1:\n self.dialogue_text = 'Olá'\n if self.cont_dialogue == 2:\n self.dialogue_text = 'Mundo'\n\n def item(self):\n self.game_screen.blit(self.image_item, self.rect_item)","sub_path":"npc_2.py","file_name":"npc_2.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"431447075","text":"from collections import Counter\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\nclass Plots:\n\n @staticmethod\n def plot_data(train: pd.DataFrame, test: pd.DataFrame) -> None:\n Plots.plot_lengths(train, 'Lengths of tweets in train dataset unmodified data')\n Plots.plot_lengths(test, 'Lengths of tweets in test dataset unmodified data')\n Plots.plot_most_popular_words(train, \"Most popular 30 words for train unmodified data\")\n Plots.plot_most_popular_words(test, \"Most popular 30 words for test unmodified data\")\n\n\n @staticmethod\n def plot_lengths(data: pd.DataFrame, title: str) -> None:\n lenghts = data['text'].str.len().value_counts()\n plt.boxplot(lenghts)\n plt.title(title)\n plt.show()\n\n @staticmethod\n def plot_most_popular_words(data: pd.DataFrame, title: str) -> None:\n most_popular_words = data['text'].str.split(expand=True).stack().value_counts()[:30]\n most_popular_words.plot.bar(x=0, y=1)\n plt.title(title)\n plt.show()\n","sub_path":"tweet-sentimental-extraction/test/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"134071520","text":"#!/usr/bin/env python\n\n# -----------------------------------------------------------------------------\n#\n# XOR dataset\n#\n# Pablo Cingolani\n# -----------------------------------------------------------------------------\n\nimport math\nimport numpy as np\nimport random\nimport tensorflow as tf\n\n# Batch size. Must be evenly dividable by dataset sizes.\nBATCH_SIZE = 100\n\n# Maximum number of training steps.\n# Note: For the XOR 2 input problem we should be able to do it using ~200 epochs\nMAX_STEPS = 1000\n\n# Number of samples (input dataset is created randomly)\nNUM_SAMPLES = 10\n\nINPUT_NAMES = ['x1', 'x2']\n\n\ndef batch(data_set, batch_size):\n \"\"\"\n Batch a dataset\n Note: Manual implementation, far from optimal, but easy to understand\n \"\"\"\n num_samples = data_set[0].shape[0]\n m = (num_samples / batch_size) - 1\n if num_samples % batch_size != 0:\n m += 1\n r = random.randint(0, m)\n rmin, rmax = r * batch_size, (r + 1) * batch_size - 1\n rmax = min(rmax, num_samples - 1)\n return data_set[0][rmin:rmax], data_set[1][rmin:rmax]\n\n\ndef create_data_set(num_samples=NUM_SAMPLES):\n \"\"\"\n Create training dataset.\n Note: Numbers are converted to float32 which is the default in tensorflow\n \"\"\"\n print(\"Create dataset\")\n x_data = (2 * np.random.rand(num_samples, 2) - 1).astype(np.float32)\n y_data = np.asarray([xor(xi) for xi in x_data], np.float32)\n y_data.shape = (num_samples, 1)\n return x_data, y_data\n\n\ndef create_input_features():\n \"\"\" Create feature columns \"\"\"\n feature_columns = []\n for x in INPUT_NAMES:\n feature_columns.append(tf.feature_column.numeric_column(x))\n return feature_columns\n\n\ndef input_fn(num_samples=NUM_SAMPLES, batch_size=BATCH_SIZE, repeat=True):\n \"\"\"\n Data input function for Tensorflow's Estimator.\n Creates a Dataset\n \"\"\"\n x_data = 2 * np.random.rand(num_samples, 2).astype(np.float32) - 1\n x1 = x_data[:, 0]\n x2 = x_data[:, 1]\n y_data = [xor(xi) for xi in x_data]\n y_data = np.asarray(y_data, dtype=np.float32)\n features = {'x1': x1, 'x2': x2}\n dataset = tf.data.Dataset.from_tensor_slices((features, y_data))\n if repeat:\n dataset = dataset.repeat()\n return dataset.batch(batch_size)\n\n\ndef xor(x):\n \"\"\" Xor function for two inputs \"\"\"\n if(x[0] >= 0) ^ (x[1] >= 0):\n return 1.0\n return 0.0\n\n\ndef weight_init(num_units, num_inputs):\n \"\"\" Initialzie weight tensor \"\"\"\n return tf.truncated_normal([num_inputs, num_units], stddev=1.0 / math.sqrt(float(num_inputs)))\n\n\ndef zeros_init(num_units, num_inputs=None):\n \"\"\" Initialzie with zeros tensor \"\"\"\n if num_inputs:\n return tf.zeros([num_inputs, num_units])\n return tf.zeros([num_units])\n","sub_path":"src/tensorflow/xor/xor_data.py","file_name":"xor_data.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"593349118","text":"#!/usr/bin/env python\n# encoding:utf-8\n\nimport time\n\nfrom users import Users\n\n\nclass Follow(Users):\n\n def __init__(self, user_id, follow_details):\n\n Users.__init__(self,user_id)\n self.flow = follow_details #\n\n\n\n def create_node(self):\n '''\n 创建friend的节点. 删除该所有的friend数据,再重新建立\n :return:\n '''\n self.delete_node()\n items = []\n\n for item in self.flow:\n\n obj = Users(user_id=item['user_id'])\n items.append(\n {\n 'uid': obj.get_uid()['data'],\n \"friend|since\": time.strftime(\"%Y-%m-%dT%H:%M:%S\", time.gmtime(item['follow_at']))\n }\n )\n del obj\n\n\n data = {\n \"uid\": self.get_uid()['data'],\n 'friend': items\n }\n\n return self.user.add(data)\n\n\n def delete_node(self):\n\n p = {\n 'uid':self.get_uid()['data'],\n 'friend': None\n }\n\n return self.user.delete(p)\n\n","sub_path":"cols/follow.py","file_name":"follow.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"138980844","text":"\"\"\"\n Isaac CSPRNG\n Usage:\n import Isaac()\n x = Isaac.Isaac(noblock=False)\n y = x.rand(42) # 0<= y <= 41\n Warning: If you don't have /dev/random(noblock=False) nor /dev/urandom(noblock=True) Pythons builtin Random() will be used\n\"\"\"\nimport random\nimport os\nfrom math import ceil\nfrom hashlib import sha512\n\ntry:\n import psyco\n psyco.full()\nexcept:\n pass\n\nclass Isaac(object):\n def __init__(self, noblock = False, miniseed = True):\n self.mm = [0]*256\n self.randrsl = [0]*256\n self.randcnt = None\n self.aa = 0\n self.bb = 0\n self.cc = 0\n random.seed()\n\n # If noblock is set to \"True\" on init it will seed from /dev/urandom\n rnd_source = '/dev/urandom' if noblock else '/dev/random'\n if os.path.exists(rnd_source):\n f = open(rnd_source, 'r')\n if miniseed:\n # Reads 16 bytes = 128 bits and expands it to 8192 bits with hashing\n z = f.read(16)\n digests = \"\"\n for i in xrange(2048/128): # ensures we run the hash enough times to get 8192 bits\n z = sha512(z).hexdigest()\n digests += z\n out = \"\"\n marker = 0\n for i in xrange(0,len(digests), 8):\n y = int(bin(int(digests[i:i+8], base=16))[2:].rjust(32, \"0\"), base=2)\n self.randrsl[marker] = y\n marker += 1\n \n else:\n # Reads 4 bytes for every integer. => 4*256= 1024 bytes=8192 bits\n for x in xrange(256):\n z = f.read(4)\n # String to binary and back to larger integer\n y = int(\"\".join([bin(ord(i))[2:].rjust(8,\"0\") for i in list(z)]), base=2)\n self.randrsl[x] = y\n f.close()\n else:\n for x in xrange(256):\n self.randrsl[x] = random.__randint__(1,4294967294)\n \n self.__randinit__(True)\n\n def rand(self, num):\n if self.randcnt == 1:\n self.__isaac__()\n self.randcnt = 256\n\n self.randcnt -= 1\n\n return self.randrsl[self.randcnt]%num\n\n def bits(self, num):\n count = ceil(num/32.0)\n bitlist = \"\"\n \n for x in xrange(count):\n bitlist += (bin(self.rand(4294967294))[2:].rjust(32, \"0\"))\n return bitlist[:num]\n\n def __isaac__(self):\n x = 0\n y = 0\n i = 0\n \n self.cc += 1\n self.bb += self.cc\n self.bb &= 0xffffffff\n\n \n while i < 256:\n x = self.mm[i]\n self.aa = (self.mm[(i + 128) & 255] + (self.aa^(self.aa << 13)) ) & 0xffffffff\n self.mm[i] = y = (self.mm[(x>>2)&255] + self.aa + self.bb ) & 0xffffffff\n self.randrsl[i] = self.bb = (self.mm[(y>>10)&255] + x ) & 0xffffffff\n i += 1\n \n x = self.mm[i]\n self.aa = (self.mm[(i+128)&255] + (self.aa^(0x03ffffff & (self.aa >> 6))) ) & 0xffffffff\n self.mm[i] = y = (self.mm[(x>>2)&255] + self.aa + self.bb ) & 0xffffffff\n self.randrsl[i] = self.bb = (self.mm[(y>>10)&255] + x ) & 0xffffffff\n i += 1\n \n x = self.mm[i]\n self.aa = (self.mm[(i + 128)&255] + (self.aa^(self.aa << 2)) ) & 0xffffffff\n self.mm[i] = y = (self.mm[(x>>2)&255] + self.aa + self.bb ) & 0xffffffff\n self.randrsl[i] = self.bb = (self.mm[(y>>10)&255] + x ) & 0xffffffff\n i += 1\n \n x = self.mm[i]\n self.aa = (self.mm[(i+128)&255] + (self.aa^(0x0000ffff & (self.aa >> 16))) ) & 0xffffffff\n self.mm[i] = y = (self.mm[(x>>2)&255] + self.aa + self.bb ) & 0xffffffff\n self.randrsl[i] = self.bb = (self.mm[(y>>10)&255] + x ) & 0xffffffff\n i += 1\n\n def __randinit__(self, flag):\n a=b=c=d=e=f=g=h = int(\"9e3779b9\", base=16)\n self.aa = self.bb = self.cc = 0\n\n for x in xrange(4):\n a ^= b<<1\n d += a\n b += c\n b ^= 0x3fffffff & (c>>2)\n e += b\n c += d\n c ^= d << 8\n f += c\n d += e\n d ^= 0x0000ffff & (e >> 16)\n g += d\n e += f\n e ^= f << 10\n h += e\n f += g\n f ^= 0x0fffffff & (g >> 4)\n a += f\n g += h\n g ^= h << 8\n b += g\n h += a\n h ^= 0x007fffff & (a >> 9)\n c += h\n a += b\n\n i = 0\n while i < 256:\n if flag:\n a+=int(self.randrsl[i])\n b+=int(self.randrsl[i+1])\n c+=self.randrsl[i+2]\n d+=self.randrsl[i+3]\n e+=self.randrsl[i+4]\n f+=self.randrsl[i+5]\n g+=self.randrsl[i+6]\n h+=self.randrsl[i+7]\n\n a^=b<<11\n d+=a\n b+=c\n b^=0x3fffffff & (c>>2)\n e+=b\n c+=d\n c^=d<<8\n f+=c\n d+=e\n d^=0x0000ffff & (e>>16)\n g+=d\n e+=f\n e^=f<<10\n h+=e\n f+=g\n f^=0x0fffffff & (g>>4)\n a+=f\n g+=h\n g^=h<<8\n b+=g\n h+=a\n h^=0x007fffff & (a>>9)\n c+=h\n a+=b\n self.mm[i]=a\n self.mm[i+1]=b\n self.mm[i+2]=c\n self.mm[i+3]=d\n self.mm[i+4]=e\n self.mm[i+5]=f\n self.mm[i+6]=g\n self.mm[i+7]=h\n i += 8\n\n if flag:\n i = 0\n while i < 256:\n a+=self.mm[i]\n b+=self.mm[i+1]\n c+=self.mm[i+2]\n d+=self.mm[i+3]\n e+=self.mm[i+4]\n f+=self.mm[i+5]\n g+=self.mm[i+6]\n h+=self.mm[i+7]\n a^=b<<11\n d+=a\n b+=c\n b^=0x3fffffff & (c>>2)\n e+=b\n c+=d\n c^=d<<8\n f+=c\n d+=e\n d^=0x0000ffff & (e>>16)\n g+=d\n e+=f\n e^=f<<10\n h+=e\n f+=g\n f^=0x0fffffff & (g>>4)\n a+=f\n g+=h\n g^=h<<8\n b+=g\n h+=a\n h^=0x007fffff & (a>>9)\n c+=h\n a+=b\n self.mm[i]=a\n self.mm[i+1]=b\n self.mm[i+2]=c\n self.mm[i+3]=d\n self.mm[i+4]=e\n self.mm[i+5]=f\n self.mm[i+6]=g\n self.mm[i+7]=h\n i += 8\n self.__isaac__()\n self.randcnt=256\n","sub_path":"Isaac.py","file_name":"Isaac.py","file_ext":"py","file_size_in_byte":6947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"54449934","text":"# -*- coding:utf-8 -*-\r\n\r\nfrom . import ht\r\nfrom app import main\r\n\r\nfrom flask import render_template, flash, request, redirect, url_for\r\nfrom flask_security.decorators import login_required\r\nfrom flask_login import current_user\r\nfrom werkzeug.utils import secure_filename\r\n\r\nimport os, app\r\n\r\nfrom forms import NewForm, NameForm, DTForm, DTItemForm, ChuHuoForm, ChuHuoItemForm\r\nfrom app.models import Kehu, Hetong, HetongChanpin, HetongBianhao, HetongImage, Wuliu\r\nfrom app import db\r\n\r\n\r\ndef hetong_query_paginate(page, id):\r\n ret = Hetong.query\r\n if id > 0:\r\n ret = ret.filter_by(duifang=id)\r\n ret = ret.order_by(Hetong.id.desc()).paginate(page, error_out=False)\r\n return ret\r\n\r\n\r\n@ht.route('/', methods=['GET', 'POST'])\r\ndef index():\r\n form = NameForm()\r\n\r\n page = request.args.get('page', 1, type=int)\r\n id = request.args.get('id', 0, type=int)\r\n pagination = hetong_query_paginate(page, id)\r\n hetongs = pagination.items\r\n\r\n if form.validate_on_submit():\r\n form = NameForm()\r\n\r\n page = 1 # request.args.get('page', 1, type=int) 这里有BUG,能用,暂时不改.\r\n id = form.danwei.data\r\n pagination = hetong_query_paginate(page, id)\r\n hetongs = pagination.items\r\n\r\n return render_template('hetong/index.html', form=form, hetongs=hetongs, pagination=pagination, ind=id)\r\n return render_template('hetong/index.html', form=form, hetongs=hetongs, pagination=pagination, ind=id)\r\n\r\n\r\n@ht.route('/dt//')\r\ndef ht_dt(id):\r\n ht = Hetong.query.filter_by(id=id).first()\r\n form = DTForm()\r\n form.hetongbianhao.data = ht.hetongid\r\n form.duifangdanwei.data = ht.gongsi.gsmc\r\n form.zongjia.data = ht.zongjia\r\n form.hetongriqi.data = ht.dingdanriqi\r\n form.jiaohuoriqi.data = ht.jiaohuoriqi\r\n form.qitaxinxi.data = ht.beizhu\r\n chanpins = HetongChanpin.query.filter_by(hetong_id=id).all()\r\n for foo in chanpins:\r\n et = DTItemForm()\r\n et.chanpinmingcheng = foo.mingcheng\r\n et.chanpinxinghao = foo.xinghao\r\n et.danjia = foo.danjia\r\n et.shuliang = foo.shuliang\r\n et.xiaoji = foo.xiaoji\r\n form.items.append_entry(et)\r\n\r\n\r\n chuhuoform = ChuHuoForm()\r\n chchanpins = Wuliu.query.filter_by(hetong_id=ht.id).all()\r\n for foo in chchanpins:\r\n cpf = ChuHuoItemForm()\r\n cpf.fahuojine = foo.fahuojine\r\n cpf.fahuoriqi = foo.fahuoriqi\r\n cpf.wuliudanwei = foo.wuliudanwei.danweimingcheng\r\n cpf.wuliudanhao = foo.wuliudanhao\r\n cpf.id = foo.id\r\n chuhuoform.items.append_entry(cpf)\r\n\r\n images = HetongImage.query.filter_by(hetong_id=id).all()\r\n flag = ht.dzd\r\n return render_template('hetong/dt.html', form=form, images=images, htid=id, chuhuoform=chuhuoform, flag=flag)\r\n\r\n\r\n@ht.route('/del//')\r\ndef ht_del(id):\r\n ht = Hetong.query.filter_by(id=id).first()\r\n if ht:\r\n db.session.delete(ht)\r\n db.session.commit()\r\n flash(u'删除成功')\r\n return redirect(url_for('ht.index'))\r\n\r\n\r\n@ht.route('/upload/', methods=['GET', 'POST'])\r\ndef ht_upload(htid, id):\r\n files = request.files.getlist('file')\r\n\r\n for file in files:\r\n if file:\r\n UPLOAD_FOLDER = app.config['product'].HETONG_UPLOAD_FOLDER\r\n upload_folder = os.path.join(UPLOAD_FOLDER, htid)\r\n # Floder exists\r\n if os.path.exists(upload_folder) == False:\r\n os.mkdir(upload_folder)\r\n\r\n backname = file.filename\r\n filename = secure_filename(file.filename)\r\n dirname = os.path.join(upload_folder, backname)\r\n wwwname = os.path.join('hetongfiles', htid, backname)\r\n hetong_id = id\r\n file.save(dirname)\r\n rt = HetongImage(hetong_id=hetong_id, backname=backname, filename=filename, dirname=dirname,\r\n wwwname=wwwname)\r\n db.session.add(rt)\r\n if files:\r\n db.session.commit()\r\n\r\n\r\n@ht.route('/new/', methods=['GET', 'POST'])\r\ndef ht_new():\r\n form = NewForm()\r\n if form.validate_on_submit():\r\n dfdw = form.duifangdanwei.data\r\n jhrq = form.jiaohuoriqi.data\r\n htrq = form.hetongriqi.data\r\n qtxx = form.qitaxinxi.data\r\n htje = 0\r\n htbh = 0\r\n import datetime\r\n qianzhui = 'HT' + datetime.datetime.now().strftime(\"%Y%m%d\")\r\n for mws in range(1, 1000):\r\n bianhao = qianzhui + (\"%04d\") % mws\r\n rt = HetongBianhao.query.filter_by(bianhao=bianhao).first()\r\n if rt is None:\r\n htbh = bianhao\r\n rt = HetongBianhao(bianhao=bianhao)\r\n db.session.add(rt)\r\n db.session.commit()\r\n break\r\n\r\n ht = Hetong(hetongid=htbh, duifang=dfdw, zongjia=htje, dingdanriqi=htrq, jiaohuoriqi=jhrq, beizhu=qtxx)\r\n db.session.add(ht)\r\n db.session.commit()\r\n ht_upload(htbh, ht.id)\r\n for foo in form.items:\r\n xj = ((float)(foo.danjia.data)) * ((int)(foo.shuliang.data))\r\n htcp = HetongChanpin(xinghao=foo.chanpinxinghao.data, mingcheng=foo.chanpinmingcheng.data,\r\n danjia=foo.danjia.data, shuliang=foo.shuliang.data, xiaoji=xj, hetong_id=ht.id)\r\n\r\n db.session.add(htcp)\r\n htje += xj\r\n ht.zongjia = htje\r\n db.session.add(ht)\r\n db.session.commit()\r\n flash(u'添加成功!')\r\n return redirect(url_for('ht.index'))\r\n return render_template('hetong/new.html', form=form)\r\n","sub_path":"app/hetong/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"330918596","text":"# Author: ninuxer\n# Date: 2018/04/18 10:15\n# File: func1.py\n\n\n# f = open(\"test\")\n# data =compile(f.read(),'','exec')\n# exec(data)\n\n\n\nmsg = \"又回到最初的起点\"\nf = open(\"tofile\",\"wb\")\nprint(msg,\"记忆中你青涩的脸\",sep=\"|\",end=\"\",file=f,)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"2018-04-18/func1.py","file_name":"func1.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"264511925","text":"\n\n#calss header\nclass _REPLETE():\n\tdef __init__(self,): \n\t\tself.name = \"REPLETE\"\n\t\tself.definitions = [u'full, especially with food: ', u'well supplied: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_replete.py","file_name":"_replete.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"460938611","text":"import tldextract\r\nimport argparse\r\nimport sys\r\nimport bs4\r\nfrom pprint import pprint\r\nfrom bs4 import BeautifulSoup as bs\r\nfrom urllib.parse import urljoin\r\nimport requests\r\nimport urllib3\r\n\r\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\r\n\r\n\r\nR = '\\033[31m' # red\r\nG = '\\033[32m' # green\r\nC = '\\033[36m' # cyan\r\nW = '\\033[0m' # white\r\nY = '\\033[33m' # yellow\r\n\r\n\r\ndef get_all_forms(url):\r\n \"\"\"Given a `url`, it returns all forms from the HTML content\"\"\"\r\n soup = bs(requests.get(url).content, \"html.parser\")\r\n return soup.find_all(\"form\")\r\n\r\n\r\ndef get_form_details(form):\r\n \"\"\"\r\n This function extracts all possible useful information about an HTML `form`\r\n \"\"\"\r\n details = {}\r\n try:\r\n # get the form action (target url)\r\n action = form.attrs.get(\"action\").lower()\r\n # get the form method (POST, GET, etc.)\r\n method = form.attrs.get(\"method\", \"get\").lower()\r\n # get all the input details such as type and name\r\n inputs = []\r\n for input_tag in form.find_all(\"input\"):\r\n input_type = input_tag.attrs.get(\"type\", \"text\")\r\n input_name = input_tag.attrs.get(\"name\")\r\n inputs.append({\"type\": input_type, \"name\": input_name})\r\n # put everything to the resulting dictionary\r\n details[\"action\"] = action\r\n details[\"method\"] = method\r\n details[\"inputs\"] = inputs\r\n return details\r\n except Exception as e:\r\n print('\\n' + R + '[-] Exception : ' + C + str(e) + W)\r\n\r\n\r\ndef submit_form(form_details, url, value):\r\n \"\"\"\r\n Submits a form given in `form_details`\r\n Params:\r\n form_details (list): a dictionary that contain form information\r\n url (str): the original URL that contain that form\r\n value (str): this will be replaced to all text and search inputs\r\n Returns the HTTP Response after form submission\r\n \"\"\"\r\n # construct the full URL (if the url provided in action is relative)\r\n try:\r\n target_url = urljoin(url, form_details[\"action\"])\r\n # get the inputs\r\n inputs = form_details[\"inputs\"]\r\n data = {}\r\n for input in inputs:\r\n # replace all text and search values with `value`\r\n if input[\"type\"] == \"text\" or input[\"type\"] == \"search\":\r\n input[\"value\"] = value\r\n input_name = input.get(\"name\")\r\n input_value = input.get(\"value\")\r\n if input_name and input_value:\r\n # if input name and value are not None,\r\n # then add them to the data of form submission\r\n data[input_name] = input_value\r\n\r\n if form_details[\"method\"] == \"post\":\r\n return requests.post(target_url, data=data)\r\n else:\r\n # GET request\r\n return requests.get(target_url, params=data)\r\n except Exception as e:\r\n print('\\n' + R + '[-] Exception : ' + C + str(e) + W)\r\n\r\n\r\ndef scan_xss(url, value_forms_malforms, xss_data):\r\n \"\"\"\r\n Given a `url`, it prints all XSS vulnerable forms and\r\n returns True if any is vulnerable, False otherwise\r\n \"\"\"\r\n try:\r\n\r\n # get all the forms from the URL\r\n forms = get_all_forms(url)\r\n print(G + \"[+]\" + C + f\" Detected {len(forms)} forms on {url}\" + W)\r\n xss_data.append(f\"Detected {len(forms)} forms on {url}\")\r\n value_forms_malforms[0] = value_forms_malforms[0] + len(forms)\r\n js_script = \"\"\r\n # returning value\r\n is_vulnerable = False\r\n # iterate over all forms\r\n for form in forms:\r\n form_details = get_form_details(form)\r\n content = submit_form(form_details, url, js_script).content.decode('latin-1')\r\n if js_script in content:\r\n print(R + f\"[-] XSS Detected on {url}\" + W)\r\n print(R + \"[-]\" + C + \" Form details:\" + W)\r\n pprint(form_details)\r\n xss_data.append(f\"XSS Detected on {url} | Form details: {form_details}\")\r\n print(W)\r\n value_forms_malforms[1] = value_forms_malforms[1] + 1\r\n is_vulnerable = True\r\n # won't break because we want to print other available vulnerable forms\r\n\r\n if is_vulnerable == True:\r\n print(R + \"[-]\" + f\" XSS detected on {url}\" + W)\r\n xss_data.append(f\"XSS detected on {url}\\n\")\r\n else:\r\n print(G + \"[+]\" + f\" XSS not detected on {url}\" + W)\r\n xss_data.append(f\"XSS not detected on {url}\\n\")\r\n \r\n except Exception as e:\r\n print(R + '[-] Exception : ' + C + str(e) + W)\r\n\r\n\r\ndef xss(target, output, data):\r\n result = {}\r\n xss_data = []\r\n\r\n try:\r\n print ('\\n\\n' + G + '[+]' + Y + ' Cross-Site Scripting XSS :' + W + '\\n')\r\n \r\n user_agent = {\r\n 'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0'\r\n }\r\n # get soup\r\n try:\r\n rqst = requests.get(target, headers=user_agent, verify=False)\r\n except Exception as e:\r\n print(R + '[-] Exception : ' + C + str(e) + W)\r\n exit()\r\n\r\n sc = rqst.status_code\r\n if sc == 200:\r\n int_total = []\r\n value_forms_malforms = [0,0]\r\n\r\n page = rqst.content\r\n soup = bs4.BeautifulSoup(page, 'lxml')\r\n \r\n ext = tldextract.extract(target)\r\n domain = ext.registered_domain\r\n\r\n links = soup.find_all('a')\r\n for link in links:\r\n url = link.get('href')\r\n if url != None:\r\n if domain in url:\r\n int_total.append(url)\r\n \r\n int_total = set(int_total)\r\n \r\n scan_xss(target, value_forms_malforms, xss_data)\r\n for int in int_total:\r\n scan_xss(int, value_forms_malforms, xss_data)\r\n\r\n print(\"\\n\" + G + \"[+] \" + str(len(int_total) + 1) + C + \" total urls tested\" + W)\r\n print(G + \"[+] \" + str(value_forms_malforms[0]) + C + \" total forms detected\" + W)\r\n if value_forms_malforms[1] == 0:\r\n print(G + \"[+] \" + str(value_forms_malforms[1]) + C + \" total malicious forms detected\" + W)\r\n else:\r\n print(R + \"[-] \" + str(value_forms_malforms[1]) + C + \" total malicious forms detected\" + W)\r\n \r\n else:\r\n print(R + '[-]' + C + ' Response code returned is not 200' + W)\r\n\r\n if output != 'None':\r\n result['XSS'] = xss_data\r\n\r\n except Exception as e:\r\n print(R + '[-] Exception : ' + C + str(e) + W)\r\n if output != 'None':\r\n result.update({'Exception':str(e)})\r\n \r\n if output != 'None':\r\n xss_output(output, data, result)\r\n print()\r\n\r\n\r\ndef xss_output(output, data, result):\r\n data['module-Cross Site Scripting (XSS)'] = result\r\n","sub_path":"modules/owasps/xss.py","file_name":"xss.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"45702150","text":"# The MIT License (MIT)\n#\n# Copyright (C) 2015 - Julien Desfossez \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport re\nimport time\nimport datetime\nimport socket\nimport struct\n\nNSEC_PER_SEC = 1000000000\nNSEC_PER_MSEC = 1000000\nNSEC_PER_USEC = 1000\n\nBYTES_PER_TIB = 1099511627776\nBYTES_PER_GIB = 1073741824\nBYTES_PER_MIB = 1048576\nBYTES_PER_KIB = 1024\n\nO_CLOEXEC = 0o2000000\n\n\ndef get_syscall_name(event):\n name = event.name\n\n if name.startswith('sys_'):\n # Strip first 4 because sys_ is 4 chars long\n return name[4:]\n\n # Name begins with syscall_entry_ (14 chars long)\n return name[14:]\n\n\ndef is_multi_day_trace_collection(handles):\n time_begin = None\n\n for handle in handles.values():\n if time_begin is None:\n time_begin = time.localtime(handle.timestamp_begin / NSEC_PER_SEC)\n year_begin = time_begin.tm_year\n month_begin = time_begin.tm_mon\n day_begin = time_begin.tm_mday\n\n time_end = time.localtime(handle.timestamp_end / NSEC_PER_SEC)\n year_end = time_end.tm_year\n month_end = time_end.tm_mon\n day_end = time_end.tm_mday\n\n if year_begin != year_end:\n return True\n elif month_begin != month_end:\n return True\n elif day_begin != day_end:\n return True\n\n return False\n\n\ndef trace_collection_date(handles):\n if is_multi_day_trace_collection(handles):\n return None\n\n for handle in handles.values():\n trace_time = time.localtime(handle.timestamp_begin / NSEC_PER_SEC)\n year = trace_time.tm_year\n month = trace_time.tm_mon\n day = trace_time.tm_mday\n return (year, month, day)\n\n\ndef extract_timerange(handles, timerange, gmt):\n pattern = re.compile(r'^\\[(?P.*),(?P.*)\\]$')\n if not pattern.match(timerange):\n return None, None\n begin_str = pattern.search(timerange).group('begin').strip()\n end_str = pattern.search(timerange).group('end').strip()\n begin = date_to_epoch_nsec(handles, begin_str, gmt)\n end = date_to_epoch_nsec(handles, end_str, gmt)\n return (begin, end)\n\n\ndef date_to_epoch_nsec(handles, date, gmt):\n # match 2014-12-12 17:29:43.802588035 or 2014-12-12T17:29:43.802588035\n pattern1 = re.compile(r'^(?P\\d{4})-(?P[01]\\d)-'\n r'(?P[0-3]\\d)[\\sTt]'\n r'(?P\\d{2}):(?P\\d{2}):(?P\\d{2})\\.'\n r'(?P\\d{9})$')\n # match 2014-12-12 17:29:43 or 2014-12-12T17:29:43\n pattern2 = re.compile(r'^(?P\\d{4})-(?P[01]\\d)-'\n r'(?P[0-3]\\d)[\\sTt]'\n r'(?P\\d{2}):(?P\\d{2}):(?P\\d{2})$')\n # match 17:29:43.802588035\n pattern3 = re.compile(r'^(?P\\d{2}):(?P\\d{2}):(?P\\d{2})\\.'\n r'(?P\\d{9})$')\n # match 17:29:43\n pattern4 = re.compile(r'^(?P\\d{2}):(?P\\d{2}):(?P\\d{2})$')\n\n # match 93847238974923874\n pattern5 = re.compile(r'^\\d+$')\n\n if pattern1.match(date):\n year = pattern1.search(date).group('year')\n month = pattern1.search(date).group('mon')\n day = pattern1.search(date).group('day')\n hour = pattern1.search(date).group('hour')\n minute = pattern1.search(date).group('min')\n sec = pattern1.search(date).group('sec')\n nsec = pattern1.search(date).group('nsec')\n elif pattern2.match(date):\n year = pattern2.search(date).group('year')\n month = pattern2.search(date).group('mon')\n day = pattern2.search(date).group('day')\n hour = pattern2.search(date).group('hour')\n minute = pattern2.search(date).group('min')\n sec = pattern2.search(date).group('sec')\n nsec = 0\n elif pattern3.match(date):\n collection_date = trace_collection_date(handles)\n if collection_date is None:\n print(\"Use the format 'yyyy-mm-dd hh:mm:ss[.nnnnnnnnn]' \"\n \"for multi-day traces\")\n return None\n (year, month, day) = collection_date\n hour = pattern3.search(date).group('hour')\n minute = pattern3.search(date).group('min')\n sec = pattern3.search(date).group('sec')\n nsec = pattern3.search(date).group('nsec')\n elif pattern4.match(date):\n collection_date = trace_collection_date(handles)\n if collection_date is None:\n print(\"Use the format 'yyyy-mm-dd hh:mm:ss[.nnnnnnnnn]' \"\n \"for multi-day traces\")\n return None\n (year, month, day) = collection_date\n hour = pattern4.search(date).group('hour')\n minute = pattern4.search(date).group('min')\n sec = pattern4.search(date).group('sec')\n nsec = 0\n elif pattern5.match(date):\n return int(date)\n else:\n return None\n\n date_time = datetime.datetime(int(year), int(month), int(day), int(hour),\n int(minute), int(sec))\n if gmt:\n date_time = date_time + datetime.timedelta(seconds=time.timezone)\n return int(date_time.timestamp()) * NSEC_PER_SEC + int(nsec)\n\n\ndef ns_to_asctime(ns):\n return time.asctime(time.localtime(ns/NSEC_PER_SEC))\n\n\ndef ns_to_hour(ns):\n date = time.localtime(ns / NSEC_PER_SEC)\n return '%02d:%02d:%02d' % (date.tm_hour, date.tm_min, date.tm_sec)\n\n\ndef ns_to_hour_nsec(ns, multi_day=False, gmt=False):\n if gmt:\n date = time.gmtime(ns / NSEC_PER_SEC)\n else:\n date = time.localtime(ns / NSEC_PER_SEC)\n if multi_day:\n return ('%04d-%02d-%02d %02d:%02d:%02d.%09d' %\n (date.tm_year, date.tm_mon, date.tm_mday, date.tm_hour,\n date.tm_min, date.tm_sec, ns % NSEC_PER_SEC))\n else:\n return ('%02d:%02d:%02d.%09d' %\n (date.tm_hour, date.tm_min, date.tm_sec, ns % NSEC_PER_SEC))\n\n\ndef ns_to_sec(ns):\n return '%lu.%09u' % (ns / NSEC_PER_SEC, ns % NSEC_PER_SEC)\n\n\ndef ns_to_day(ns):\n date = time.localtime(ns/NSEC_PER_SEC)\n return '%04d-%02d-%02d' % (date.tm_year, date.tm_mon, date.tm_mday)\n\n\ndef sec_to_hour(ns):\n date = time.localtime(ns)\n return '%02d:%02d:%02d' % (date.tm_hour, date.tm_min, date.tm_sec)\n\n\ndef sec_to_nsec(sec):\n return sec * NSEC_PER_SEC\n\n\ndef seq_to_ipv4(ip):\n return '{}.{}.{}.{}'.format(ip[0], ip[1], ip[2], ip[3])\n\n\ndef int_to_ipv4(ip):\n return socket.inet_ntoa(struct.pack('!I', ip))\n\n\ndef size_str_to_bytes(size_str):\n try:\n units_index = next(i for i, c in enumerate(size_str) if c.isalpha())\n except StopIteration:\n # no units found\n units_index = None\n\n if units_index is not None:\n size = size_str[:units_index]\n units = size_str[units_index:]\n else:\n size = size_str\n units = None\n\n try:\n size = float(size)\n except ValueError:\n raise ValueError('invalid size: {}'.format(size))\n\n # no units defaults to bytes\n if units is not None:\n if units in ['t', 'T', 'tB', 'TB']:\n size *= BYTES_PER_TIB\n elif units in ['g', 'G', 'gB', 'GB']:\n size *= BYTES_PER_GIB\n elif units in ['m', 'M', 'mB', 'MB']:\n size *= BYTES_PER_MIB\n elif units in ['k', 'K', 'kB', 'KB']:\n size *= BYTES_PER_KIB\n elif units == 'B':\n # bytes is already the target unit\n pass\n else:\n raise ValueError('unrecognised units: {}'.format(units))\n\n size = int(size)\n\n return size\n\n\ndef duration_str_to_ns(duration_str):\n try:\n units_index = next(i for i, c in enumerate(duration_str)\n if c.isalpha())\n except StopIteration:\n # no units found\n units_index = None\n\n if units_index is not None:\n duration = duration_str[:units_index]\n units = duration_str[units_index:].lower()\n else:\n duration = duration_str\n units = None\n\n try:\n duration = float(duration)\n except ValueError:\n raise ValueError('invalid duration: {}'.format(duration))\n\n if units is not None:\n if units == 's':\n duration *= NSEC_PER_SEC\n elif units == 'ms':\n duration *= NSEC_PER_MSEC\n elif units in ['us', 'µs']:\n duration *= NSEC_PER_USEC\n elif units == 'ns':\n # ns is already the target unit\n pass\n else:\n raise ValueError('unrecognised units: {}'.format(units))\n else:\n # no units defaults to seconds\n duration *= NSEC_PER_SEC\n\n duration = int(duration)\n\n return duration\n\n\ndef get_v4_addr_str(ip):\n # depending on the version of lttng-modules, the v4addr is a\n # string (< 2.6) or sequence (>= 2.6)\n try:\n return seq_to_ipv4(ip)\n except TypeError:\n return int_to_ipv4(ip)\n","sub_path":"lttnganalyses/linuxautomaton/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":9860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"493996595","text":"# main.py\n# Author: Hanbo Wang\n\nimport sys\nfrom view import GameBoard\nfrom controller import ViewController\nfrom PyQt5.QtWidgets import *\n\ndef main():\n app = QApplication(sys.argv)\n gameBoard = GameBoard()\n viewController = ViewController(gameBoard)\n gameBoard.clickedOn.connect(viewController.onSquareClicked)\n gameBoard.newGameActionClicked.connect(viewController.newGame)\n gameBoard.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()","sub_path":"hw1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"553344857","text":"from agent import Agent\nimport gym\nimport numpy as np\nimport sys\n\nenv = gym.make('Taxi-v2')\nenv.render()\nprint(env.action_space)\nprint(env.observation_space)\n\naverage_score = 0\n\nfor a in range(10):\n\n agent = Agent(env, 6, .1, .9, 20000, 1.0, .999, .05).q_learning()\n # agent = Agent(env, 6,.1,.9,20000,1.0,.999,.01).expecsarsa()\n Q_sarsamax = agent[0]\n policy_sarsamax = np.array([\n np.argmax(Q_sarsamax[key]) if key in Q_sarsamax else -1\n for key in np.arange(48)\n ]).reshape(4, 12)\n\n # print(policy_sarsamax)\n\n V_sarsa = ([\n np.max(Q_sarsamax[key]) if key in Q_sarsamax else 0\n for key in np.arange(48)\n ])\n # print(V_sarsa)\n average_score += agent[1]\n print('[INFO] ep_no: {}',a)\nprint('\\n[INFO] {}'.format(average_score/100))\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"75253107","text":"from django.http import HttpResponse\nprint(\"jai mataji\")\nl = 10 #Global variable\n\n'''\ndef Function1(n):\n # l = 5 #Local Variable\n m = 8 # Local Variable\n global l\n l = l+1\n print(l,m)\n print(n,\"I have printed\")\nFunction1(\"Hello Gohil\")\n'''\n\ndef Gohil():\n x = 20\n def Ramesh():\n global x\n x =88\n print(\"Before Calling Ramesh()\",x)\n Ramesh()\n print(\"After Calling Rmaesh()\",x)\nGohil()\nprint(x)\n\n\n","sub_path":"Scope_Global_Variable_Global_KeyWord.py","file_name":"Scope_Global_Variable_Global_KeyWord.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"58558474","text":"#!/usr/bin/env python3\n\nimport requests\nimport tempfile\nimport filecmp\nimport sys\nimport time\nimport datetime\nfrom git import Repo\n\n\"\"\" Grab data files from Google docs\n Paul \"Worthless\" Nijjar, 2019-09-22\n\"\"\"\n\n### --- Sources ---\n\n# format: localfile: remotesource\nsources = {\n 'nominees.csv': 'https://docs.google.com/spreadsheets/d/1rsQksqAJjyVzjs9pA49dRij-fC-hwG8nORMmlTx_9_I/export?format=csv&id=1rsQksqAJjyVzjs9pA49dRij-fC-hwG8nORMmlTx_9_I&gid=917247882',\n 'events.csv': 'https://docs.google.com/spreadsheets/d/1sIfYfey7D72Uyi1NOAxrAFbU6yn9HvIUjINCqYGHwMw/export?format=csv&id=1sIfYfey7D72Uyi1NOAxrAFbU6yn9HvIUjINCqYGHwMw&gid=103989638',\n 'media.csv': 'https://docs.google.com/spreadsheets/d/1sIfYfey7D72Uyi1NOAxrAFbU6yn9HvIUjINCqYGHwMw/export?format=csv&id=1sIfYfey7D72Uyi1NOAxrAFbU6yn9HvIUjINCqYGHwMw&gid=1989058875',\n }\n\nTMPDIR=tempfile.TemporaryDirectory()\n\nGITDIR='/home/pnijjar/wrvotesfed'\nTARGETDIR=\"docs/_data/sync\"\n\n# Probably I should use a module for this? Whatever.\nDEBUG_SCREEN=True\nDEBUG_LOG=True \nDEBUG_FILE='/home/pnijjar/logs/gdocs-get.log'\nDEBUG_FILEHANDLE=None\nDEBUG_LOG_THRESHOLD=1\nDEBUG_SCREEN_THRESHOLD=0\nDEBUG_DEFAULT_LEVEL=3\n\n# --- Why open here?? ---\n\nif DEBUG_LOG:\n DEBUG_FILEHANDLE = open(DEBUG_FILE, 'a', newline='') \n # What if this fails?\n if not DEBUG_FILEHANDLE:\n print(\"Unable to write to {}\".format(DEBUG_FILE))\n sys.exit(1)\n\n# --- FUNCTIONS ---\n\ndef debug(msg,level=DEBUG_DEFAULT_LEVEL):\n \"\"\" Add debug information to screen and or file. \"\"\"\n\n if DEBUG_SCREEN and level <= DEBUG_SCREEN_THRESHOLD:\n print(msg)\n\n if DEBUG_LOG and level <= DEBUG_LOG_THRESHOLD:\n DEBUG_FILEHANDLE.write(\"{}: \".format(\n datetime.datetime.now())\n )\n DEBUG_FILEHANDLE.write(msg)\n DEBUG_FILEHANDLE.write('\\n')\n\ndef cleanup():\n \"\"\" Clean up file handles. \"\"\"\n if DEBUG_FILEHANDLE:\n DEBUG_FILEHANDLE.close()\n\n# --- END FUNCTIONS ---\n\ndebug(\"---- Beginning run ----\",1)\n\nchanged_files = []\n\nfor syncfile in sources:\n debug(\"file: {}, target: {}\".format(\n syncfile,\n sources[syncfile],\n ),\n 3)\n r = requests.get(sources[syncfile])\n \n # Check that we actually got the file. Otherwise \n # just continue.\n\n # https://stackabuse.com/download-files-with-python/\n if r.status_code == 200:\n\n candidate=\"{}/{}\".format(TMPDIR.name,syncfile)\n\n with open(candidate, 'wb') as f:\n f.write(r.content)\n f.close()\n\n origfile=\"{}/{}/{}\".format(GITDIR,TARGETDIR,syncfile)\n\n if not filecmp.cmp(candidate, origfile):\n debug(\"Found different files: \"\n \"{}. Overwriting.\".format(syncfile),\n 2)\n changed_files.append(syncfile)\n\n with open(origfile, 'wb') as f_orig:\n f_orig.write(r.content)\n f_orig.close()\n else:\n debug(\"{}: files are the same\".format(syncfile),2)\n\n else:\n debug(\"Oops. Received status \"\n \"{} when downloading {} \"\n \"from {} .\".format(\n r.status_code,\n syncfile,\n sources[syncfile]\n ),\n 0,\n )\n\nif changed_files:\n repo = Repo(GITDIR)\n\n\n commit_msg = \"Auto-commit: updated \"\n commit_msg += \"{} from Google Docs\".format( \n \", \".join(changed_files))\n\n debug(commit_msg, 1)\n\n changed_with_path = map(\n lambda x: \"{}/{}\".format(TARGETDIR, x),\n changed_files)\n\n repo.index.add(changed_with_path)\n repo.index.commit(commit_msg)\n origin = repo.remote('origin')\n origin.push()\nelse:\n debug(\"All files are the same. Not committing.\", 2)\n\ncleanup()\n","sub_path":"scripts/gdocs-get-csv.py","file_name":"gdocs-get-csv.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"315397968","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import font_manager,rc\n\ndataName = 'C:/Users/rladp/OneDrive/바탕 화면/판다스 데이터분석/DataAnalytics/source/part4/시도별 전출입 인구수.xlsx'\n\nfont_path = 'C:/Users/rladp/OneDrive/바탕 화면/판다스 데이터분석/DataAnalytics/source/part4/malgun.ttf'\nfont_name = font_manager.FontProperties(fname=font_path).get_name()\nrc('font', family=font_name)\n\ndf = pd.read_excel(dataName, engine='openpyxl', header=0) \ndf = df.fillna(method='ffill') # 전 데이터로 결측값 채우기\ndf.tail()\n\n# 서울에서 다른 지역으로 이동한 데이터만 추출하여 정리 => 파트 6에서 자세히 다룰 예정\nmask = (df['전출지별'] == '서울특별시') & (df['전입지별'] != '서울특별시')\ndf_seoul = df[mask]\ndf_seoul = df_seoul.drop(['전출지별'], axis = 1)\ndf_seoul.rename({'전입지별':'전입지'}, axis=1, inplace = True)\ndf_seoul.set_index('전입지', inplace = True)\n\n# 서울에서 경기도로 이동한 인구 데이터 값만 선택\nsr_one = df_seoul.loc['경기도']\n\nsr_one = df_seoul.loc['경기도']\n\nplt.style.use('ggplot')\n\nplt.figure(figsize = (14, 5)) # 인치 단위\n\nplt.xticks(rotation='vertical') # x 눈금 라벨 회전하기\n\nplt.plot(sr_one.index, sr_one.values, marker='o', markersize=10)\n\nplt.title('서울 -> 경기 인구 이동')\nplt.xlabel('기간')\nplt.ylabel('이동 인구수')\n\nplt.legend(labels=['서울 -> 경기'], loc = 'best')\n\nplt.show()","sub_path":"데이터분석 Study/Pandas Data Analytics/4. 시각화 도구/4-05. 스타일 서식 지정 등.py","file_name":"4-05. 스타일 서식 지정 등.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"623838582","text":"import numpy as np \nimport pandas as pd \nimport psycopg2\nfrom sklearn.metrics import average_precision_score, precision_recall_curve, \\\n auc, roc_auc_score, brier_score_loss\nfrom sklearn.ensemble.partial_dependence import plot_partial_dependence, partial_dependence\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.preprocessing import scale\nimport matplotlib.pyplot as plt \nimport seaborn as sns\nfrom sklearn.decomposition import PCA\nfrom imblearn.base import BaseSampler\n\ndef process(df, start=None, end=None, keep_train=True, keep_metadata=False):\n \n if start is None:\n start = np.min(df.charge_date_created)\n if end is None:\n end = np.max(df.charge_date_created)\n \n # keep all fraud, and all fraud team false positives\n if keep_train:\n df = df.query('(charge_date_created >= @start & charge_date_created <= @end)\\\n | (charge_date_created < @start & fraud == 1)\\\n | (charge_date_created < @start & kount_auto_response in [2,3] & fraud == 0)')\n else:\n df = df.query('(charge_date_created >= @start & charge_date_created <= @end)')\n \n if not keep_metadata:\n df = df.drop(df.columns[0:np.argmax(df.columns == 'fraud')], axis=1)\\\n .dropna()\n \n return df\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom imblearn.over_sampling.base import BaseOverSampler\n\nclass DuplicateDropper(BaseSampler):\n def __init__(self, features=['charge_amount', \n 'srq_reward_program_id', \n 'total_rewards',\n 'language_id',\n 'country_id',\n 'nightly_charge_amount',\n 'number_of_adults',\n 'number_of_rooms',\n 'default_reward_program_id',\n 'charge_days_advanced',\n 'hotel_latitude',\n 'hotel_longitude',\n 'fraud']):\n super(DuplicateDropper, self).__init__()\n self.features = features\n def fit(self, X=None, y=None):\n return self\n def sample(self, X, y):\n return self._sample(X, y)\n def _sample(self, X, y):\n df = X.assign(y=y)\n self.prior_rows_ = df.shape[0]\n self.prior_fraud_ = df.query('y == 1').shape[0]\n df = df.drop_duplicates(self.features)\n self.post_rows_ = df.shape[0]\n self.post_fraud_ = df.query('y == 1').shape[0]\n X = df.drop('y', axis=1)\n y = df['y']\n return X, y\n def fit_sample(self, X, y):\n return self.fit(X, y).sample(X, y)\n\nfrom scipy.stats import bernoulli\nclass TimeUnderSampler(BaseSampler):\n # default has last nonfraud 1 in 10 chance of being picked\n # last fraud 1 in 2 chance of being picked\n def __init__(self, k_maj=.5, k_min=.1, random_state=None):\n super(TimeUnderSampler, self).__init__()\n self.k_maj=k_maj\n self.k_min=k_min\n def fit(self, X=None, y=None):\n return self\n def sample(self, X, y):\n return self._sample(X, y)\n def _sample(self, X, y):\n df = X.assign(y=y)\n rows_range = np.arange(df.shape[0])\n rows_maj = rows_range[df['y'] == 0]\n rows_min = rows_range[df['y'] == 1]\n probability_maj = np.float_power(10, np.multiply(np.arange(rows_maj.size), -self.k_maj / rows_maj.size))\n probability_min = np.float_power(10, np.multiply(np.arange(rows_min.size), -self.k_min / rows_min.size))\n picked_maj = np.where(np.random.binomial(1, p=probability_maj) == 1, True, False)\n picked_min = np.where(np.random.binomial(1, p=probability_min) == 1, True, False)\n picked = pd.Series(rows_maj[picked_maj]).append(pd.Series(rows_min[picked_min]))\n df = df.iloc[picked]\n X = df.drop('y', axis=1)\n y = df['y']\n return X, y\n def fit_sample(self, X, y):\n return self.fit(X, y).sample(X, y)\n \nclass FeatureSelector(BaseEstimator, TransformerMixin):\n def __init__(self, features):\n self.features = features\n def fit(self, X, y=None):\n return self\n def transform(self, X):\n X = X[self.features]\n return X\n def fit_transform(self, X, y):\n return self.fit(X, y).transform(X)\n\n# return model and feature importance information\ndef train_model(model, df, train_start=None, train_end=None):\n if train_start is None:\n train_start = np.min(df.charge_date_created)\n if train_end is None:\n train_end = np.max(df.charge_date_created)\n \n df = process(df, train_start, train_end)\n \n X = df.drop('fraud', axis=1)\n y = df.fraud\n \n model.fit(X, y)\n \n # Feature importance data frame + train_start + train_end\n importance = pd.DataFrame({\"Importance\":model.feature_importances_}, \n index=X.columns).transpose()\n importance = importance.assign(train_start_date = train_start, train_end_date = train_end)\n \n return model, importance, X, y\n\n# return comparison of model with baseline\ndef test_model(model, df, features, test_start=None, test_end=None):\n if test_start is None:\n test_start = np.min(df.charge_date_created)\n if test_end is None:\n test_end = np.max(df.charge_date_created)\n \n features = features.copy()\n features.append('fraud')\n \n # get data corresponding to correct time period\n df = df.query('charge_date_created >= @test_start & charge_date_created <= @test_end')\n # filter out NaNs\n df = df.loc[df[features]\\\n .dropna().index]\n\n test = df[features].drop('fraud', axis=1)\n \n # get fraud team decision\n df = df.assign(kount_decision = df.kount_auto_response.isin([2,3]))\n num_fraud_decisions = np.sum(df.kount_decision)\n \n # establish baseline\n nrows = df.shape[0]\n # cost of missed fraud charges, and $2.50 for checking a transaction\n kount_fraud_loss = np.sum(df.charge_amount * ((df.kount_decision != df.fraud) & (df.fraud == 1)))\n kount_pct_check = np.sum(df.kount_decision) / df.kount_decision.size\n kount_recall = np.sum((df.kount_decision == df.fraud) & (df.fraud == 1)) / np.sum(df.fraud)\n kount_precision = np.sum((df.kount_decision == df.fraud) & \\\n (df.kount_decision == 1)) / np.sum(df.kount_decision)\n \n df = df.assign(pred = model.predict_proba(test)[:,1])\n model_decision_cutoff = df.pred.sort_values(ascending=False).iloc[num_fraud_decisions - 1]\n df = df.assign(model_decision = df.pred >= model_decision_cutoff)\n \n precision, recall, _ = precision_recall_curve(df.fraud, df.pred)\n \n AUC_PR = auc(x=recall, y=precision, reorder=True)\n AUC_ROC = roc_auc_score(df.fraud, df.pred)\n # brier = brier_score_loss(df.fraud, df.pred)\n \n # compare with baseline \n #model_pct_check = np.sum(df.model_decision) / df.model_decision.size\n model_fraud_loss = np.sum(df.charge_amount * ((df.model_decision != df.fraud) & (df.fraud == 1)))\n #model_fraud_loss_less_autoapprove = np.sum(df.charge_amount * ((df.model_decision != df.fraud) & \n# (df.fraud == 1) & \n# (df.triggered_approve_rule == 0)))\n model_recall = np.sum((df.model_decision == df.fraud) & (df.fraud == 1)) / np.sum(df.fraud)\n model_precision = np.sum((df.model_decision == df.fraud) & \\\n (df.model_decision == 1)) / np.sum(df.model_decision)\n intersect_recall = np.sum((df.model_decision == df.fraud) \\\n & (df.fraud == 1) \\\n & (df.model_decision == df.kount_decision))\\\n / np.sum(df.fraud)\n intersect_precision = np.sum((df.model_decision == 1) & \\\n (df.fraud == 1) & \\\n (df.kount_decision == 1)) / \\\n np.sum((df.model_decision==1) & (df.kount_decision==1))\n intersect_pct_check = np.sum((df.model_decision == 1) & (df.kount_decision == 1)) / df.model_decision.size\n union_recall = np.sum(((df.model_decision == 1) | (df.kount_decision == 1)) & (df.fraud == 1))\\\n / np.sum(df.fraud)\n union_precision = np.sum(((df.model_decision == 1) | (df.kount_decision == 1)) & (df.fraud == 1))\\\n / np.sum((df.model_decision == 1) | (df.kount_decision == 1))\n union_pct_check = np.sum((df.model_decision == 1) | (df.kount_decision == 1)) / df.model_decision.size\n kount_model_correlation = np.corrcoef(df.model_decision, df.kount_decision)[1,0]\n false_negatives_captured = np.sum((df.model_decision == df.fraud) & \\\n (df.fraud == 1) & \\\n (df.kount_decision != df.fraud)) / \\\n np.sum((df.kount_decision != df.fraud) & (df.fraud == 1))\n \n return pd.DataFrame(data = \n {'Area under Precision-Recall':AUC_PR,\n 'Area under ROC':AUC_ROC,\n 'Fraud Loss of Model':model_fraud_loss, 'Fraud Loss of Kount':kount_fraud_loss, \n #'Model Fraud Loss Less AutoApprove':model_fraud_loss_less_autoapprove,\n 'Percent of Kount False Negatives Identified':false_negatives_captured,\n 'Recall of Model':model_recall, 'Recall of Kount':kount_recall, \n 'Precision of Model':model_precision, 'Precision of Kount':kount_precision,\n 'Percent Checked - Kount':kount_pct_check,\n 'Percent Checked - Intersection':intersect_pct_check, 'Percent Checked - Union':union_pct_check,\n 'Recall of Intersection':intersect_recall, 'Precision of Intersection':intersect_precision,\n 'Recall of Union': union_recall, 'Precision of Union': union_precision,\n 'Kount-Model Correlation':kount_model_correlation,\n 'Test Date Begin':test_start, 'Test Date Conclude':test_end, \n 'Probability Cutoff':model_decision_cutoff},\n index=[0]), df.pred\n\n# plot AuPR curves\ndef plot_pr(model, df, test_start=None, test_end=None, title=None):\n if test_start is None:\n test_start = np.min(df.charge_date_created)\n if test_end is None:\n test_end = np.max(df.charge_date_created)\n df = df.query('charge_date_created >= @test_start & charge_date_created <= @test_end')\n # filter out NaNs\n df = df.loc[df.drop(df.columns[0:np.argmax(df.columns == 'fraud')], axis=1)\\\n .dropna().index]\n\n test = df.drop(df.columns[0:np.argmax(df.columns == 'fraud') + 1], axis=1)\n\n df = df.assign(pred = model.predict_proba(test)[:,1])\n\n precision, recall, _ = precision_recall_curve(df.fraud, df.pred)\n AuPR = auc(x=recall, y=precision, reorder=True)\n \n plt.step(recall, precision, color='b', alpha=0.2,\n where='post',\n label='AuPR = %0.3f' % AuPR)\n plt.fill_between(recall, precision, step='post', alpha=0.2,\n color='b')\n\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n if title is None:\n title = 'Precision-Recall Curve'\n plt.title(title)\n plt.legend(loc=\"lower right\")\n plt.ylim([0.0, 1.05])\n plt.xlim([0.0, 1.0])\n \n# plot partial dependence curves\ndef plot_pd(model, X, n):\n feature_importances = pd.DataFrame({'feature':X.columns,\n 'importance':model.feature_importances_})\n \n feature_indices = feature_importances\\\n .query(\"feature != 'hotel_latitude' & feature != 'hotel_longitude'\")\\\n .sort_values(['importance'], ascending=False)\\\n .reset_index()\\\n .loc[0:n]['index']\n \n fig = plt.figure()\n fig.set_size_inches(20, 10)\n \n num_plots = 1\n \n for feature_index in feature_indices:\n feature_name = feature_importances.loc[feature_index]['feature']\n partial_dep, feature_value = partial_dependence(gbrt = model,\n target_variables = feature_index,\n X = X)\n # scale log-odds output\n partial_dep = partial_dep.tolist()[0]\n partial_dep = scale(partial_dep)\n \n partial_dependence_grid = pd.DataFrame({feature_name:feature_value[0],\n 'Prediction':partial_dep})\n plt.subplot(2, 3, num_plots)\n ax = sns.regplot(data=partial_dependence_grid,\n x=feature_name, \n y='Prediction',\n fit_reg=False,\n line_kws = {'linestyle' : 'solid'})\n ax.set_ylabel('')\n \n num_plots += 1\n \n return None\n\n# measures percent of missed fraud captured as a function of additional transactions checked using model decision rule\ndef missed_fraud_captured(model, df, date_start=None, date_end=None):\n if date_start is None:\n date_start = np.min(df.charge_date_created)\n if date_end is None:\n date_end = np.max(df.charge_date_created)\n metadata = process(df, start = date_start, end = date_end, keep_train=False, keep_metadata=True)\n X_test = process(df, start = date_start, end = date_end, keep_train=False).drop('fraud', axis=1)\n \n # add model probability prediction, whether Kount system failed to flag fraudulent transaction\n metadata = metadata.assign(pred = model.predict_proba(X_test)[:,1],\n kount_missed = (metadata.fraud & (metadata.kount_auto_response == 1)))\n\n # filter out the positive transactions on which Kount and model agree\n metadata = metadata.assign(kount_decision = metadata.kount_auto_response.isin([2,3]))\n num_fraud_decisions = np.sum(metadata.kount_decision)\n #model_decision_cutoff = metadata.pred.sort_values(ascending=False).iloc[num_fraud_decisions - 1]\n #metadata = metadata.assign(model_decision = metadata.pred >= model_decision_cutoff)\n\n no_agree = metadata.query('kount_decision == 0')\n no_agree = no_agree.sort_values('pred', ascending=False)\n\n # calculate proportion of dollars of missed fraud incrementally captured by model\n no_agree = no_agree.assign(missed_fraud_captured = ((no_agree.charge_amount * no_agree.fraud).cumsum()) / \n np.sum(no_agree.fraud * no_agree.charge_amount),\n rank_prob = np.arange(0, no_agree.shape[0]))\n\n # calculate percent of additional checks required by the fraud team to undertake\n num_fraud_decisions = metadata.query(\"kount_decision == 1\").shape[0]\n no_agree = no_agree.assign(additional_pct_checked = (no_agree.rank_prob) \\\n / num_fraud_decisions)\n # sns.pointplot(x = no_agree.additional_pct_checked, y = no_agree.missed_fraud_captured)\n # plt.xlim(np.min(no_agree.additional_pct_checked), 2 * np.min(no_agree.additional_pct_checked))\n return no_agree[['fraud', 'kount_missed', 'kount_decision', 'pred',\n 'missed_fraud_captured', 'rank_prob', 'additional_pct_checked', \n 'charge_amount']]\n\ndef plot_missed_fraud(df, title):\n plt.scatter(x=df.additional_pct_checked, y = df.missed_fraud_captured)\n plt.xlim(xmin=0, xmax=1)\n plt.xlabel(\"Percent Increase in Checked Transactions\")\n plt.ylabel(\"Percent of Missed Fraud Captured\")\n plt.title(title)\n \ndef correlation_matrix(df, drop_duplicates = True):\n # Your dataset is already a correlation matrix.\n # If you have a dateset where you need to include the calculation\n # of a correlation matrix, just uncomment the line below:\n df = df.corr()\n\n # Exclude duplicate correlations by masking upper right values\n if drop_duplicates: \n mask = np.zeros_like(df, dtype=np.bool)\n mask[np.triu_indices_from(mask)] = True\n\n # Set background color / chart style\n sns.set_style(style = 'white')\n\n # Set up matplotlib figure\n f, ax = plt.subplots(figsize=(11, 9))\n\n # Add diverging colormap from red to blue\n cmap = sns.diverging_palette(250, 10, as_cmap=True)\n\n # Draw correlation plot with or without duplicates\n if drop_duplicates:\n sns.heatmap(df, mask=mask, cmap=cmap, \n square=True,\n linewidth=.5, cbar_kws={\"shrink\": .5}, ax=ax)\n else:\n sns.heatmap(df, cmap=cmap, \n square=True,\n linewidth=.5, cbar_kws={\"shrink\": .5}, ax=ax)\n \ndef display_user(user_id, product, df):\n with pd.option_context('display.max_rows', None):\n display(df.query(\"user_id==@user_id & product==@product\")\\\n .sort_values('charge_date_created')\\\n [['user_id', \n 'search_request_id',\n 'charge_id',\n 'product', \n 'charge_date_created', \n 'kount_flagged_fraud', \n 'account_age', \n 'charge_amount', \n 'charge_count_past_week',\n 'triggered_review_rule',\n 'triggered_decline_rule',\n 'triggered_approve_rule',\n 'triggered_important_decline_rule']]\\\n .reset_index(drop=True))\n\n# call the fig.suptitle() on the FacetGrid return object to set the title\ndef plot_pca(df, start_date):\n processed = process(df, start=start_date)\n y = processed['fraud']\n X = processed.drop('fraud', axis=1)\n pca = PCA(n_components=2).fit_transform(X)\n pca_df = pd.DataFrame(pca, columns=['First Component', 'Second Component'])\\\n .assign(Fraud=y)\n return sns.lmplot(data=pca_df, \n x='First Component', \n y='Second Component', \n hue='Fraud',\n fit_reg=False)","sub_path":"modules/convenience_functions.py","file_name":"convenience_functions.py","file_ext":"py","file_size_in_byte":17729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"638447415","text":"#Example 4.3.2 (A)\n\nfrom tkinter import *\n\nc = Canvas (None, width = 400, height = 200)\nc.pack()\n\nc.config (background = \"peach puff\")\nc.create_line (0,100,400,100,fill = \"red\")\n\nfor i in range(1,4):\n c.create_line (100*i,0,100*i,400,fill = \"RoyalBlue1\")\n \nc.create_arc (20,20,80,80,start = 45,extent = 270, outline = \"black\",fill = \"white\", style = PIESLICE)\nc.create_arc (120,20,180,80,start = 45,extent = 90, outline = \"black\",width = 3.5, style = CHORD)\nc.create_arc (220,20,280,80,start = 315,extent = -90, outline = \"blue\",width = 2.0, style = ARC)\nc.create_text(320,70,anchor=SW,text = \"Arcs\",font = (\"Arial\", \"24\", \"bold italic\"))\nc.create_rectangle(20,120,80,180,width=2.5,outline=\"green\", fill=\"red\")\nc.create_oval(120,120,180,180,width=1.5,outline=\"black\", fill = \"\")\nc.create_polygon(230,120,270,120,290,150,270,180,230,180,210,150,width = 5, outline = \"purple\")\n\nmainloop()\n","sub_path":"4.3 GUI Sample Code Examples (Python3)/Ex432A.py","file_name":"Ex432A.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"459187952","text":"#réalisé le 14/04/2020\r\nimport os\r\nimport random\r\nfrom math import *\r\n\r\nnotes = []\r\nwhile True:\r\n nb = (input(\" Ajoutez un nombre : \"))\r\n nb = float(nb) # MAJ : inclure un Try: except / ValueError:\r\n\r\n notes.append(nb) #on stocke le nombre choisi dans une liste\r\n notes.sort() #on trie les nombres dans l'ordre croissant\r\n print(notes)\r\n med = ceil(len(notes)/2) #on détermine le nombre médian (taille du tableau divisée par 2, arrondie au supérieur)\r\n if len(notes) %2 == 0: #si le tableau a un nombre pair d'éléments\r\n print(\"La médiane se situe dans la liste entre les places \", med, \" et \", med + 1)\r\n print(\"La valeur de la médiane est donc : \", (notes[med] + notes[med-1])/2)\r\n else: #si le tableau a un nombre impair d'éléments\r\n print(\"La médiane se situe dans la liste à la place \", med)\r\n print(\"La valeur de la médiane est donc : \", notes[med-1])\r\n continue\r\n\r\nprint(\"Fin du programme\")\r\n\r\nos.system(\"pause\")\r\n","sub_path":"calculerMediane1.0.py","file_name":"calculerMediane1.0.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"162752752","text":"import csv\nimport math\nclass grafo:\n def __init__(self, matriz,ids):\n self.matriz = matriz\n self.ids = ids\n\n\ndef lerCSV(caminho):\n matriz = []\n with open(caminho) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n ids = csv_reader.__next__()\n ids.pop(0)\n for row in csv_reader:\n aux = []\n for a in row[1:]:\n if(a==\"i\"):\n aux.append(math.inf)\n else:\n aux.append(int(a))\n matriz = matriz + [aux]\n return grafo(matriz, ids)\n\n\ndef bellmanFord(s, grafo):\n d = []*len(grafo.matriz)\n p = [-1]*len(grafo.matriz)\n for i in range(len(grafo.matriz)):\n d.append(math.inf) \n d[s] = 0\n \n for i in range(len(grafo.matriz)-1):\n c = 0\n for j in range(len(grafo.matriz)):\n if(d[j] != math.inf):\n for k in range(len(grafo.matriz)):\n if(grafo.matriz[j][k]!=math.inf):\n soma = d[j] + grafo.matriz[j][k]\n if(somad[i] + grafo.matriz[i][j]):\n print(\"Grafo possui ciclo negativo\")\n print(i)\n return\n \n printDistances(d, p, s, grafo)\n \n \n\ndef printDistances(distance, previous, s, grafo):\n print(\"**********************************************\")\n print(\"Distancias a partir do vertice \", grafo.ids[s], end=\"\\n\\n\")\n for i in range (len(distance)):\n route = []\n aux = previous[i]\n while(aux != -1):\n route.append(aux)\n aux = previous[aux]\n route.reverse()\n print(\"Vertice \", grafo.ids[i],\" = \", distance[i])\n for r in route:\n print(grafo.ids[r], \" => \", end=\"\")\n print(grafo.ids[i])\n print(\"-----------------------------------------------\")\n\n \n\n# 9.2\n# grafo2 = lerCSV(\"Atividade 10\\Atividade 10 - Grafos - 9.2.csv\")\n# bellmanFord(6, grafo2)\n\n# 9.3\n# grafo3 = lerCSV(\"Atividade 10\\Atividade 10 - Grafos - 9.3.csv\")\n# bellmanFord(5, grafo3)\n\n# #teste\n# grafoTeste = lerCSV(\"Atividade 10\\grafo_ciclo_negativo.csv\")\n# bellmanFord(0, grafoTeste)\n","sub_path":"Atividade 10/ativ10.py","file_name":"ativ10.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"108650894","text":"from typing import List, Any, Callable, Tuple\nfrom expungeservice.util import DateWithFuture as date\n\nfrom expungeservice.models.case import OeciCase, CaseSummary\nfrom expungeservice.models.charge import OeciCharge\nfrom expungeservice.models.charge_types.misdemeanor import Misdemeanor\nfrom expungeservice.models.record import Record\nfrom expungeservice.models.disposition import Disposition, DispositionStatus, DispositionCreator\nfrom expungeservice.record_creator import RecordCreator\n\n\ncase_1 = OeciCase(\n CaseSummary(\n name=\"John Doe\",\n birth_year=1980,\n case_number=\"X0001\",\n citation_number=\"X0001\",\n location=\"earth\",\n date=date(2001, 1, 1),\n violation_type=\"Something\",\n current_status=\"CLOSED\",\n case_detail_link=\"alink\",\n balance_due_in_cents=0,\n ),\n (\n OeciCharge(\n ambiguous_charge_id=\"X0001-1\",\n name=\"manufacturing\",\n statute=\"100.000\",\n level=\"Felony Class B\",\n date=date(2000, 1, 1),\n disposition=Disposition(\n date=date(2001, 1, 1), ruling=\"Convicted\", status=DispositionStatus.CONVICTED, amended=False,\n ),\n probation_revoked=None,\n balance_due_in_cents=0,\n ),\n OeciCharge(\n ambiguous_charge_id=\"X0001-2\",\n name=\"assault 3\",\n statute=\"200.000\",\n level=\"Felony Class C\",\n date=date(2001, 1, 1),\n disposition=DispositionCreator.empty(),\n probation_revoked=None,\n balance_due_in_cents=0,\n ),\n ),\n)\ncase_2 = OeciCase(\n CaseSummary(\n name=\"John Albert Doe\",\n birth_year=1970,\n case_number=\"X0002\",\n citation_number=\"X0002\",\n location=\"america\",\n date=date(2001, 1, 1),\n violation_type=\"Something Else\",\n current_status=\"CLOSED\",\n case_detail_link=\"alink\",\n balance_due_in_cents=0,\n ),\n (\n OeciCharge(\n ambiguous_charge_id=\"X0002-1\",\n name=\"driving\",\n statute=\"100.000\",\n level=\"Misdemeanor\",\n date=date(2000, 1, 1),\n disposition=Disposition(\n date=date(2001, 1, 1), ruling=\"Convicted\", status=DispositionStatus.CONVICTED, amended=False,\n ),\n probation_revoked=None,\n balance_due_in_cents=0,\n ),\n OeciCharge(\n ambiguous_charge_id=\"X0002-2\",\n name=\"assault 3\",\n statute=\"200.000\",\n level=\"Violation\",\n date=date(2001, 1, 1),\n disposition=DispositionCreator.empty(),\n probation_revoked=None,\n balance_due_in_cents=0,\n ),\n ),\n)\nmock_search_results = {\"empty\": [], \"single_case_two_charges\": [case_1], \"two_cases_two_charges_each\": [case_1, case_2]}\n\n\ndef search(mocked_record_name) -> Callable[[Any, Any, Any], Tuple[List[OeciCase], List[str]]]:\n def _build_search_results(username, password, aliases):\n return mock_search_results[mocked_record_name], []\n\n return _build_search_results\n\n\ndef test_no_op():\n record, questions = RecordCreator.build_record(search(\"two_cases_two_charges_each\"), \"username\", \"password\", (), {})\n assert len(record.cases) == 2\n assert len(record.cases[0].charges) == 2\n assert record.cases[0].charges[1].disposition.status == DispositionStatus.UNKNOWN\n\n\ndef test_edit_some_fields_on_case():\n record, questions = RecordCreator.build_record(\n search(\"two_cases_two_charges_each\"),\n \"username\",\n \"password\",\n (),\n {\"X0002\": {\"action\": \"edit\", \"summary\": {\"location\": \"ocean\", \"balance_due\": \"100\", \"date\": \"1/1/1001\",}}},\n )\n assert len(record.cases) == 2\n assert record.cases[0].summary.location == \"earth\"\n assert record.cases[1].summary.location == \"ocean\"\n assert record.cases[1].summary.balance_due_in_cents == 10000\n assert record.cases[1].summary.date == date(1001, 1, 1)\n\n\ndef test_delete_case():\n record, questions = RecordCreator.build_record(\n search(\"single_case_two_charges\"), \"username\", \"password\", (), {\"X0001\": {\"action\": \"delete\"}},\n )\n assert record == Record((), ())\n\n\ndef test_add_disposition():\n record, questions = RecordCreator.build_record(\n search(\"single_case_two_charges\"),\n \"username\",\n \"password\",\n (),\n {\n \"X0001\": {\n \"action\": \"edit\",\n \"charges\": {\"X0001-2\": {\"disposition\": {\"date\": \"1/1/2001\", \"ruling\": \"Convicted\"}}},\n }\n },\n )\n assert record.cases[0].charges[1].disposition.status == DispositionStatus.CONVICTED\n\n\ndef test_edit_charge_type_of_charge():\n record, questions = RecordCreator.build_record(\n search(\"single_case_two_charges\"),\n \"username\",\n \"password\",\n (),\n {\"X0001\": {\"action\": \"edit\", \"charges\": {\"X0001-2\": {\"charge_type\": \"Misdemeanor\"}},}},\n )\n assert isinstance(record.cases[0].charges[1].charge_type, Misdemeanor)\n\n\ndef test_add_new_charge():\n record, questions = RecordCreator.build_record(\n search(\"single_case_two_charges\"),\n \"username\",\n \"password\",\n (),\n {\n \"X0001\": {\n \"action\": \"edit\",\n \"charges\": {\n \"X0001-3\": {\n \"charge_type\": \"Misdemeanor\",\n \"date\": \"1/1/2001\",\n \"disposition\": {\"date\": \"2/1/2020\", \"ruling\": \"Convicted\"},\n }\n },\n }\n },\n )\n assert isinstance(record.cases[0].charges[2].charge_type, Misdemeanor)\n assert record.cases[0].charges[2].date == date(2001, 1, 1)\n","sub_path":"src/backend/tests/test_edit_results.py","file_name":"test_edit_results.py","file_ext":"py","file_size_in_byte":5769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"255313742","text":"from opengever.base.interfaces import INoSeparateConnectionForSequenceNumbers\nfrom opengever.base.interfaces import ISequenceNumber\nfrom opengever.base.interfaces import ISequenceNumberGenerator\nfrom opengever.base.protect import unprotected_write\nfrom opengever.setup.interfaces import IDuringSetup\nfrom persistent.dict import PersistentDict\nfrom plone.dexterity.interfaces import IDexterityContent\nfrom Products.CMFCore.interfaces import ISiteRoot\nfrom ZODB.DemoStorage import DemoStorage\nfrom ZODB.POSException import ConflictError\nfrom zope.annotation.interfaces import IAnnotations\nfrom zope.component import adapter\nfrom zope.component import getAdapter\nfrom zope.component import getUtility\nfrom zope.globalrequest import getRequest\nfrom zope.interface import implementer\nimport logging\nimport transaction\n\n\nSEQUENCE_NUMBER_ANNOTATION_KEY = 'ISequenceNumber.sequence_number'\nLOG = logging.getLogger('opengever.base.sequence')\n\n\n@implementer(ISequenceNumber)\nclass SequenceNumber(object):\n \"\"\" The sequence number utility provides a getNumber(obj) method\n which returns a unique number for each object.\n \"\"\"\n\n def get_number(self, obj):\n ann = unprotected_write(IAnnotations(obj))\n if SEQUENCE_NUMBER_ANNOTATION_KEY not in ann.keys():\n generator = getAdapter(obj, ISequenceNumberGenerator)\n value = generator.generate()\n ann[SEQUENCE_NUMBER_ANNOTATION_KEY] = value\n return ann.get(SEQUENCE_NUMBER_ANNOTATION_KEY)\n\n def remove_number(self, obj):\n ann = unprotected_write(IAnnotations(obj))\n if SEQUENCE_NUMBER_ANNOTATION_KEY in ann.keys():\n del ann[SEQUENCE_NUMBER_ANNOTATION_KEY]\n\n\n@implementer(ISequenceNumberGenerator)\n@adapter(IDexterityContent)\nclass DefaultSequenceNumberGenerator(object):\n \"\"\" Provides a default sequence number generator.\n The portal_type of the object is used as *unique-key*\n \"\"\"\n\n def __init__(self, context):\n self.context = context\n\n def generate(self):\n return self.get_next(self.key)\n\n @property\n def key(self):\n return u'DefaultSequenceNumberGenerator.%s' % self.context.portal_type\n\n def get_next(self, key):\n return SequenceNumberIncrementer()(key)\n\n\nclass SequenceNumberIncrementer(object):\n \"\"\"The sequence number increment creates and returns the next\n sequence number for a given key when called.\n\n It does this in a separate connection to the ZODB.\n When the integer value is returned, the incrementation is\n already committed and the value will be unique and not raise\n any conflict when committing the main transaction of the\n requesting code.\n\n This behavior is important in order to eliminate conflicts of\n content-creation request and to provide safe, unique sequence\n numbers.\n When the requesting transaction is aborted or repeated, the\n sequence number which was requested in this transaction will\n not be used, which results in gaps in the sequence numbering\n system. These gaps are expected and accepted.\n \"\"\"\n\n maximum_retries = 10\n\n def __call__(self, sequence_number_key):\n portal = getUtility(ISiteRoot)\n request = getRequest()\n\n if isinstance(portal._p_jar.db().storage, DemoStorage):\n # We use DemoStorage (probably in tests), which\n # do not allow concurrent DB connections,\n # thus we don't spawn a new database connection.\n return self._increment_number(portal, sequence_number_key)\n\n if any([IDuringSetup.providedBy(request),\n INoSeparateConnectionForSequenceNumbers.providedBy(request)]):\n # During setup, the Plone site will just have been created in that\n # very transaction. That means it's not available for us to fetch\n # from a separate ZODB connection during setup. So no separate\n # ZODB connection for sequence numbers during setup.\n #\n # In addition, there's other cases where we don't want to use\n # a separate connection to issue sequence numbers, like during\n # OGGBundle import\n return self._increment_number(portal, sequence_number_key)\n\n return self._separate_zodb_connection(\n self._increment_number,\n sequence_number_key)\n\n def _increment_number(self, portal, key):\n ann = unprotected_write(IAnnotations(portal))\n if SEQUENCE_NUMBER_ANNOTATION_KEY not in ann:\n ann[SEQUENCE_NUMBER_ANNOTATION_KEY] = unprotected_write(\n PersistentDict())\n\n mapping = unprotected_write(ann.get(SEQUENCE_NUMBER_ANNOTATION_KEY))\n if key not in mapping:\n mapping[key] = 0\n\n mapping[key] += 1\n return mapping[key]\n\n def _separate_zodb_connection(self, callback, *args, **kwargs):\n main_connection_portal = getUtility(ISiteRoot)\n manager = transaction.TransactionManager()\n connection = main_connection_portal._p_jar.db().open(\n transaction_manager=manager)\n try:\n\n for _r in range(self.maximum_retries):\n manager.begin()\n portal = connection[main_connection_portal._p_oid]\n result = callback(portal, *args, **kwargs)\n\n try:\n manager.commit()\n except ConflictError:\n LOG.info('SequenceNumberIncrementer'\n ' ConflictError; retrying')\n manager.abort()\n else:\n return result\n\n # Maximum retries exceeded, raise conflict to main\n # transaction / actual request.\n raise\n\n finally:\n connection.close()\n","sub_path":"opengever/base/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"204528372","text":"\"\"\"\nGiven an array nums of n integers where n > 1, return an array output such\nthat output[i] is equal to the product of all the elements of nums except\nnums[i].\n\nExample:\n\nInput: [1,2,3,4]\nOutput: [24,12,8,6]\nNote: Please solve it without division and in O(n).\n\nFollow up:\nCould you solve it with constant space complexity? (The output array does not\ncount as extra space for the purpose of space complexity analysis.)\n\"\"\"\n\n# from functools import reduce\nclass Solution:\n def productExceptSelf(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n len_nums = len(nums)\n forward = [1] * len_nums\n backward = [1] * len_nums\n\n f_product = 1\n b_product = 1\n for pos in range(0, len_nums):\n forward[pos] = f_product\n f_product *= nums[pos]\n\n backward[len_nums-pos-1] = b_product\n b_product *= nums[len_nums-pos-1]\n\n return list(map(lambda f,b:f*b, forward, backward))\n\n# This solution exceeds time limit on leetcode\n # output = []\n # for pos in range(0,len(nums)):\n # temp = list(nums)\n # temp[pos] = 1\n # output.append(reduce((lambda x,y: x*y),temp))\n # return output\n \nif __name__ == \"__main__\":\n S = Solution()\n print(S.productExceptSelf([1,2,3,4]))\n print(S.productExceptSelf([0,0]))\n print(S.productExceptSelf([1,2,0,4]))","sub_path":"LC/python/238_product_of_array_except_self.py","file_name":"238_product_of_array_except_self.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"333628940","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 6 16:11:51 2018\n\n@author: li\n\"\"\"\n\nimport socket\n\ntarget_host = '10.42.0.243'\ntarget_port = 50007\n\n#建立一个socket对象\nclient = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\n#链接客户端\nclient.connect((target_host,target_port))\n\n\nwhile True:\n data = input('> ')\n client.send(data.encode(\"utf-8\"))\n \n \n print (data)","sub_path":"send_to_50007port.py","file_name":"send_to_50007port.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"359856023","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nfrom pydpiper.application import AbstractApplication\nfrom pydpiper.pipeline import Pipeline, CmdStage, InputFile, OutputFile, LogFile\nimport pydpiper.file_handling as fh\nimport atoms_and_modules.registration_functions as rf\nimport atoms_and_modules.registration_file_handling as rfh\nimport atoms_and_modules.minc_atoms as ma\nimport atoms_and_modules.minc_parameters as mp\nfrom os.path import abspath\nfrom os.path import dirname\nfrom os.path import exists\nfrom os.path import basename\nimport string\nimport logging\nimport sys\n\nlogger = logging.getLogger(__name__)\n\ndef verifyCorrectLSQ6TargetOptions(bootstrap, init_model, lsq6_target):\n \"\"\"\n This function can be called using the parameters that are set using \n the flags:\n --bootstrap\n --init-model\n --lsq6-target\n \n it will check that exactly one of the options is provided and exits \n otherwise. \n \"\"\"\n # check how many options have been specified that can be used as the initial target\n number_of_target_options = sum((bootstrap != False,\n init_model != None,\n lsq6_target != None))\n if(number_of_target_options == 0):\n print(\"\\nError: please specify a target for the 6 parameter alignmnet. Options are: --lsq6-target, --init-model, --bootstrap.\\n\")\n sys.exit()\n if(number_of_target_options > 1):\n print(\"\\nError: please specify only one of the following options: --lsq6-target, --init-model, --bootstrap. Don't know which target to use...\\n\")\n sys.exit()\n\ndef addLSQ6ArgumentGroup(parser):\n \"\"\"\n standard options for the LSQ6 module\n \"\"\"\n group = parser.add_argument_group(\"LSQ6-registration options\", \"Options for performing a 6 parameter (rigid) registration.\")\n group.add_argument(\"--lsq6-target\", dest=\"lsq6_target\",\n type=str, default=None,\n help=\"File to be used as the target for the 6 parameter alignment. [Default = %(default)s]\")\n group.add_argument(\"--init-model\", dest=\"init_model\",\n type=str, default=None,\n help=\"File in standard space in the initial model. The initial model \"\n \"can also have a file in native space and potentially a transformation \"\n \"file. See our wiki for detailed information on initial models. [Default = %(default)s]\")\n group.add_argument(\"--bootstrap\", dest=\"bootstrap\",\n action=\"store_true\", default=False,\n help=\"Use the first inputfile to the pipeline as the target for the 6 parameter alignment. [Default = %(default)s]\")\n group.add_argument(\"--lsq6-alternate-data-prefix\", dest=\"lsq6_alternate_prefix\",\n type=str, default=None,\n help=\"Specify a prefix for an augmented data set to use for the 6 parameter \"\n \"alignment. Assumptions: there is a matching alternate file for each regular input \"\n \"file, e.g. input files are: input_1.mnc input_2.mnc ... input_n.mnc. If the \"\n \"string provided for this flag is \\\"aug_\\\", then the following files should exists: \"\n \"aug_input_1.mnc aug_input_2.mnc ... aug_input_n.mnc. These files are assumed to be \"\n \"in the same orientation/location as the regular input files. They will be used for \"\n \"for the 6 parameter alignment. The transformations will then be used to transform \"\n \"the regular input files, with which the pipeline will continue.\")\n parser.set_defaults(lsq6_method=\"lsq6_large_rotations\")\n parser.set_defaults(nuc=True)\n parser.set_defaults(inormalize=True)\n parser.set_defaults(copy_header_info=False)\n group.add_argument(\"--lsq6-simple\", dest=\"lsq6_method\",\n action=\"store_const\", const=\"lsq6_simple\",\n help=\"Run a 6 parameter alignment assuming that the input files are roughly \"\n \"aligned: same space, similar orientation. Keep in mind that if you use an \"\n \"initial model with both a standard and a native space, the assumption is \"\n \"that the input files are already roughly aligned to the native space. \"\n \"Three iterations are run: 1st is 17 times stepsize blur, 2nd is 9 times \"\n \"stepsize gradient, 3rd is 4 times stepsize blur. [Default = %(default)s]\")\n group.add_argument(\"--lsq6-centre-estimation\", dest=\"lsq6_method\",\n action=\"store_const\", const=\"lsq6_centre_estimation\",\n help=\"Run a 6 parameter alignment assuming that the input files have a \"\n \"similar orientation, but are scanned in different coils/spaces. [Default = %(default)s]\")\n group.add_argument(\"--lsq6-large-rotations\", dest=\"lsq6_method\",\n action=\"store_const\", const=\"lsq6_large_rotations\",\n help=\"Run a 6 parameter alignment assuming that the input files have a random \"\n \"orientation and are scanned in different coils/spaces. A brute force search over \"\n \"the x,y,z rotation space is performed to find the best 6 parameter alignment. \"\n \"[Default = %(default)s]\")\n group.add_argument(\"--lsq6-large-rotations-parameters\", dest=\"large_rotation_parameters\",\n type=str, default=\"10,4,10,8\",\n help=\"Settings for the large rotation alignment. factor=factor based on smallest file \"\n \"resolution: 1) blur factor, 2) resample step size factor, 3) registration step size \"\n \"factor, 4) w_translations factor ***** if you are working with mouse brain data \"\n \" the defaults do not have to be based on the file resolution; a default set of \"\n \" settings works for all mouse brain. In order to use those setting, specify: \\\"mousebrain\\\"\"\n \" as the argument for this option. ***** [default = %(default)s]\")\n group.add_argument(\"--lsq6-rotational-range\", dest=\"large_rotation_range\",\n type=int, default=50,\n help=\"Settings for the rotational range in degrees when running the large rotation alignment.\"\n \" [Default = %(default)s]\")\n group.add_argument(\"--lsq6-rotational-interval\", dest=\"large_rotation_interval\",\n type=int, default=10,\n help=\"Settings for the rotational interval in degrees when running the large rotation alignment.\"\n \" [Default = %(default)s]\")\n group.add_argument(\"--nuc\", dest=\"nuc\",\n action=\"store_true\", \n help=\"Perform non-uniformity correction. [Default = %(default)s]\")\n group.add_argument(\"--no-nuc\", dest=\"nuc\",\n action=\"store_false\", \n help=\"If specified, do not perform non-uniformity correction. Opposite of --nuc.\")\n group.add_argument(\"--inormalize\", dest=\"inormalize\",\n action=\"store_true\", \n help=\"Normalize the intensities after lsq6 alignment and nuc, if done. [Default = %(default)s] \")\n group.add_argument(\"--no-inormalize\", dest=\"inormalize\",\n action=\"store_false\", \n help=\"If specified, do not perform intensity normalization. Opposite of --inormalize.\")\n group.add_argument(\"--copy-header-info-to-average\", dest=\"copy_header_info\",\n action=\"store_true\", \n help=\"Copy the MINC header information of the first input file into the \"\n \"average that is created. [Default = %(default)s] \")\n group.add_argument(\"--no-copy-header-info-to-average\", dest=\"copy_header_info\",\n action=\"store_false\", \n help=\"Opposite of --copy-header-info-to-average.\")\n group.add_argument(\"--lsq6-protocol\", dest=\"lsq6_protocol\",\n type=str, default=None,\n help=\"Specify an lsq6 protocol that overrides the default setting for stages in \"\n \"the 6 parameter minctracc call. Parameters must be specified as in the following \\n\"\n \"example: applications_testing/test_data/minctracc_example_linear_protocol.csv \\n\"\n \"[Default = %(default)s].\")\n\nclass LSQ6Registration(AbstractApplication):\n \"\"\" \n This class handles a 6 parameter (rigid) registration between one or more files\n and a single target or an initial model. \n \n Source:\n One or more files with or without a mask\n \n Target:\n Single input file:\n The target can be a single input file with or without a mask\n \n Initial model:\n An initial model can be specified. Here, you are required \n to have a mask and an optional transformation. This option \n can be used if the \"native space\" (scanner space) is different\n from the \"standard space\", the space where you want to register\n your files. Alternatively, the standard space can be in the\n same space as your native space, but have a tighter crop to\n save disk space and processing time.\n \n Complexity of registration:\n 1) (--lsq6-simple) single coil, same position for all files. If for \n example all samples are scanned in the same coil and the orientation \n is fixed, e.g., the subjects always enter the scanner in the same \n position. This implies that the input files are more or less aligned \n to begin with.\n \n 2) (--lsq6-centre-estimation) multiple coils, same position/orientation \n for all files. Think here for example about multiple coil live mice \n scans. Even though the files from different coils reside in a different \n part in space, the orientation is the same. This means that aligning \n the centre of gravity for the input files gets them in option 1)\n \n 3) (--lsq6-large-rotations) multiple (or single) coil with random scan \n orientation. In this case, the input files are in the most random \n orientation/location. The procedure here is to do a brute force search \n in the x,y,z rotation space in order to find the best alignment. \n \"\"\"\n def setup_options(self):\n \"\"\"Add option groups from specific modules\"\"\"\n rf.addGenRegArgumentGroup(self.parser)\n addLSQ6ArgumentGroup(self.parser)\n\n def setup_appName(self):\n appName = \"LSQ6-registration\"\n return appName\n \n def run(self):\n options = self.options\n\n rf.checkInputFiles(options.files)\n\n verifyCorrectLSQ6TargetOptions(options.bootstrap,\n options.init_model,\n options.lsq6_target)\n\n # Setup output directories for LSQ6 registration. \n dirs = rf.setupDirectories(self.outputDir, options.pipeline_name, module=\"LSQ6\")\n \n # create file handles for the input file(s) \n inputFiles = rf.initializeInputFiles(options.files, dirs.processedDir, maskDir=options.mask_dir)\n\n # if we are running a bootstrap or lsq6_target option, pass in the correct target\n target_file_for_lsq6 = None\n target_file_directory = None\n if(options.bootstrap):\n target_file_for_lsq6 = inputFiles[0].inputFileName\n target_file_directory = fh.createSubDir(self.outputDir,options.pipeline_name + \"_bootstrap_file\")\n if(options.lsq6_target):\n target_file_for_lsq6 = options.lsq6_target\n target_file_directory = fh.createSubDir(self.outputDir,options.pipeline_name + \"_target_file\")\n\n #Setup init model and inital target. Function also exists if no target was specified.\n initModel, targetPipeFH = rf.setInitialTarget(options.init_model, \n target_file_for_lsq6, \n target_file_directory,\n self.outputDir,\n options.pipeline_name)\n \n # Initialize LSQ6, NonUniformityCorrection and IntensityNormalization classes and\n # construct their pipelines. Note that because we read in the options directly, running\n # NUC and inormalize is still optional \n runLSQ6NucInorm = LSQ6NUCInorm(inputFiles,\n targetPipeFH,\n initModel, \n dirs.lsq6Dir, \n options)\n self.pipeline.addPipeline(runLSQ6NucInorm.p)\n \n\ndef getLSQ6Module(inputFiles,\n targetPipeFH,\n options, # TODO could narrow this to only queue_type\n lsq6Directory = None,\n initialTransform = None,\n initModel = None,\n lsq6Protocol = None,\n largeRotationParameters = None,\n largeRotationRange = None,\n largeRotationInterval = None):\n \"\"\"\n This function serves as a switch that will return the appropriate lsq6 module depending\n on the parameters provided. The switch is based on the parameter initialTransform. If\n that parameter is not given, by default a large rotations lsq6 is performed. \n \n Assumptions:\n * inputFiles are expected to be file handlers\n * targetFile is expected to be a file handler\n * the lsq6Directory is required when at least 2 inputFiles are given\n * initialTransform can have the following string values:\n - \"lsq6_simple\"\n - \"lsq6_centre_estimation\"\n - \"lsq6_large_rotations\"\n if none is provided, lsq6_large_rotations is taken as the default\n * lsq6Protocol: see the LSQ6HierarchicalMinctracc class for more information\n about what this can be\n * largeRotationParameters: see the RotationalMinctracc CmdStage for more information\n \"\"\"\n lsq6module = None\n if(initialTransform == None):\n initialTransform = \"lsq6_large_rotations\"\n \n \"\"\"\n Option 1) run a simple lsq6: the input files are assumed to be in the\n same space and roughly in the same orientation.\n \"\"\"\n if(initialTransform == \"lsq6_simple\"):\n lsq6module = LSQ6HierarchicalMinctracc(inputFiles,\n targetPipeFH,\n options,\n initial_model = initModel,\n lsq6OutputDir = lsq6Directory,\n initial_transform = \"identity\",\n lsq6_protocol = lsq6Protocol)\n \"\"\"\n Option 2) run an lsq6 registration where the centre of the input files\n is estimated. Orientation is assumed to be similar, space is not.\n \"\"\"\n if(initialTransform == \"lsq6_centre_estimation\"):\n lsq6module = LSQ6HierarchicalMinctracc(inputFiles,\n targetPipeFH,\n options,\n initial_model = initModel,\n lsq6OutputDir = lsq6Directory,\n initial_transform = \"estimate\",\n lsq6_protocol = lsq6Protocol)\n \"\"\"\n Option 3) run a brute force rotational minctracc. Input files can be\n in any random orientation and space.\n \"\"\"\n if(initialTransform == \"lsq6_large_rotations\"):\n lsq6module = LSQ6RotationalMinctracc(inputFiles,\n targetPipeFH,\n options,\n initial_model = initModel,\n lsq6OutputDir = lsq6Directory,\n large_rotation_parameters = largeRotationParameters,\n large_rotation_range = largeRotationRange,\n large_rotation_interval = largeRotationInterval)\n return lsq6module\n\nclass LSQ6NUCInorm(object):\n \"\"\"Because LSQ6 is often called in conjunction with NUC and IntensityNormalization, this class\n enables the calling of both in a single class. This is intended to reduce repeated code and \n simplify reading/writing at the highest levels.\"\"\"\n def __init__(self, \n inputFiles, \n targetPipeFH,\n initModel, \n lsq6Directory,\n options):\n self.p = Pipeline()\n self.inputFiles = inputFiles\n if not (options.lsq6_alternate_prefix is None):\n # we should use a separate data set for the 6 parameter alignment\n self.alternateInputFiles = self.setAlternateInputFiles(inputFiles, options.lsq6_alternate_prefix)\n self.target = targetPipeFH\n self.initModel = initModel\n self.lsq6Dir = lsq6Directory\n self.options = options \n self.lsq6Avg = None # add the average from the lsq6 module here\n \n self.setupPipeline()\n\n\n def setAlternateInputFiles(self, mainInputFiles, alternate_prefix):\n # first make sure we have an alternate file for each of the \n # actual input files\n alternateInputs = []\n for i in range(len(mainInputFiles)):\n alternate = dirname(mainInputFiles[i].inputFileName)\n alternate += '/' + alternate_prefix\n alternate += basename(mainInputFiles[i].inputFileName)\n if(exists(alternate)):\n alternateInputs.append(alternate)\n else:\n print(\"Error: could not find alternative input file for: %s\" % mainInputFiles[i].inputFileName)\n raise\n # create file handlers for the alternate input files, get the base directory\n # from the first main input file\n return rf.initializeInputFiles(alternateInputs, mainInputFiles[0].basedir)\n\n \"\"\"\n This function is called when a separate set of input files is used to determine\n the LSQ6 transformations. When those have been determined (in the alternateInputFiles)\n they have to be assigned to the (main) inputFiles. For this the group \"lsq6\" needs to be\n added to the inputFiles and we set the last transform based on the alternateInputFiles\n \"\"\"\n def setGroupAndTransformsFromAlternateToMain(self):\n # 1) create an lsq6 group for the mainInputs:\n for i in range(len(self.inputFiles)):\n self.inputFiles[i].newGroup(groupName=\"lsq6\")\n # 2) set the transforms for the main input files\n found = 0\n alternate_target = self.options.lsq6_alternate_prefix + basename(self.inputFiles[i].inputFileName)\n for j in range(len(self.alternateInputFiles)):\n if (basename(self.alternateInputFiles[j].inputFileName) == alternate_target):\n found = 1\n # because all future filenames are based on previous (input) filenames\n # it's better to create a symlink to the transform to be used for \n # the main input file with the correct name (other wise all hell will\n # break loose later on when we are resampling files...)\n transformDir = self.inputFiles[i].transformsDir\n currentTransBase = basename(self.alternateInputFiles[j].getLastXfm(self.target))\n # only replace 1 occurence of the prefix in case it occurs more often...\n newTransBase = string.replace(currentTransBase, \n self.options.lsq6_alternate_prefix,\n \"\", 1)\n newTrans = transformDir + '/' + newTransBase\n cmd = [\"ln\", \"-s\", \n InputFile(self.alternateInputFiles[j].getLastXfm(self.target)), \n OutputFile(newTrans)]\n lnCmd = CmdStage(cmd)\n lnCmd.setLogFile(LogFile(fh.logFromFile(self.inputFiles[i].logDir,newTrans)))\n self.p.addStage(lnCmd)\n self.inputFiles[i].setLastXfm(self.target,newTrans)\n if not found:\n print(\"Error: was not able to find a transform for: %s based on the alternate input files\" % self.inputFiles[i].inputFileName)\n raise\n \n\n\n def setupPipeline(self):\n inputFilesForModule = self.inputFiles\n # switch the input files when alternate files are provided. We will\n # deal with the true input files after the alternate files have gone\n # through the LSQ6 module\n if not (self.options.lsq6_alternate_prefix is None):\n inputFilesForModule = self.alternateInputFiles\n lsq6module = getLSQ6Module(inputFilesForModule,\n self.target,\n options=self.options,\n lsq6Directory=self.lsq6Dir,\n initialTransform = self.options.lsq6_method,\n initModel = self.initModel,\n lsq6Protocol = self.options.lsq6_protocol,\n largeRotationParameters = self.options.large_rotation_parameters,\n largeRotationRange = self.options.large_rotation_range,\n largeRotationInterval = self.options.large_rotation_interval) \n # after the correct module has been set, get the transformation and\n # deal with resampling and potential model building\n lsq6module.createLSQ6Transformation()\n prefix_for_average = None\n if not (self.options.lsq6_alternate_prefix is None):\n prefix_for_average = self.options.lsq6_alternate_prefix\n lsq6module.finalize(prefix_for_average)\n self.p.addPipeline(lsq6module.p)\n # assign this average for now. If we are running alternate files\n # we will overwrite self.lsq6Avg later on\n self.lsq6Avg = lsq6module.lsq6Avg\n\n # if alternate files were provided for the 6 parameter alignment, \n # we will run through a similar procedure, but without creating the\n # transformation. That will be transferred from the alternate files\n if not (self.options.lsq6_alternate_prefix is None):\n mainInputFiles = self.inputFiles\n lsq6moduleForResampling = getLSQ6Module(mainInputFiles,\n self.target,\n options=self.options,\n lsq6Directory=self.lsq6Dir,\n initialTransform = self.options.lsq6_method,\n initModel = self.initModel,\n lsq6Protocol = self.options.lsq6_protocol,\n largeRotationParameters = self.options.large_rotation_parameters,\n largeRotationRange = self.options.large_rotation_range,\n largeRotationInterval = self.options.large_rotation_interval)\n # assign \"lsq6\" group and the transformations from the alternate inputs to the main inputs\n self.setGroupAndTransformsFromAlternateToMain()\n # this time we do not have to create the transformation, just resampling and averaging:\n lsq6moduleForResampling.addNativeToStandardFromInitModel()\n lsq6moduleForResampling.resampleInputFilesAndSetLastBasevol(self.options.lsq6_alternate_prefix)\n lsq6moduleForResampling.createAverage()\n self.p.addPipeline(lsq6moduleForResampling.p)\n # update the average:\n self.lsq6Avg = lsq6moduleForResampling.lsq6Avg\n \n if self.options.nuc:\n already_resample_to_LSQ6 = False\n if not self.options.inormalize:\n # the non uniformity correction is performed in native space \n # by default (useOriginalInput=True). If we are not also \n # performing intensity normalization, we need to already\n # resample the non uniformity corrected file into LSQ6 space\n already_resample_to_LSQ6 = True\n nucorrection = NonUniformityCorrection(self.inputFiles, \n initial_model=self.initModel,\n resampleNUCtoLSQ6=already_resample_to_LSQ6,\n targetForLSQ6=self.target)\n nucorrection.finalize()\n self.p.addPipeline(nucorrection.p)\n \n if self.options.inormalize:\n need_to_resample_to_LSQ6 = True;\n # Currently when no non-uniformity correction is applied, the input \n # file is intensity normalized in lsq6 space, not native space. This \n # means that in that case, we do not need to resample to LSQ6 anymore\n # since the file is already in that space:\n if not self.options.nuc:\n need_to_resample_to_LSQ6 = False\n intensity_normalization = IntensityNormalization(self.inputFiles,\n initial_model=self.initModel,\n resampleINORMtoLSQ6=need_to_resample_to_LSQ6,\n targetForLSQ6=self.target, options=self.options)\n self.p.addPipeline(intensity_normalization.p)\n\nclass NonUniformityCorrection(object):\n \"\"\"\n \n * inputFiles: a list of either strings or file handlers. \n \n * multiple input files possible\n \n * group name: if useOriginalInput -> nuc-native\n if also resampleNUCtoLSQ6Space -> nuc-lsq6\n if not(useOriginalInput) -> nuc\n \n if the input files are file handlers, a \"nuc\" group will be added\n \n * initial model can be given in order to use its mask \n - assumption: if an initial model is provided, the input files are assumed\n to be registered towards the standard space file\n \n * targetForLSQ6: if no initial model is used, but there is a target file (either specified\n through --lsq6-target or --bootstrap), we can get the lsq6 transformation based on that\n file in case we want to resample to LSQ6 space\n \n #TODO: you should use the following boolean only if the file is not in its original\n space anymore \n \n * useOriginalInput: this is a boolean argument which determines whether we should\n use the original input file (file_handle.inputFileName). If this\n option is set to False, the last base volume will be used. I.e.\n there are two spaces allowed to be used:\n \n - native/inputfile\n - last base volume \n \n * mask... a single mask used for all? not yet determined...\n * if the input files have masks associated with them, the assumption is that all\n input files have an input mask (we only test the first file for the presence\n of an original input mask)\n \n masking options...\n - if an initial model is given, the assumption is that the input files\n have been registered towards the \"standard\" space. This space is required\n to have a mask. This is the mask we will for the non uniformity correction\n if no individual mask is given. It will need to be resampled to the native\n space of the input file if *useOriginalInput* is set to True\n \n \"\"\"\n def __init__(self,\n inputFiles,\n singlemask = None,\n useOriginalInput = True,\n resampleNUCtoLSQ6 = False,\n initial_model = None,\n targetForLSQ6 = None):\n # TODO: allow for a single single target instead of using an initial model??\n self.p = Pipeline()\n self.inputs = inputFiles\n self.initial_model = initial_model\n self.targetForLSQ6 = targetForLSQ6\n self.useOriginalInput = useOriginalInput\n self.resampleNUCtoLSQ6 = resampleNUCtoLSQ6\n self.singlemask = singlemask\n self.masks = None\n self.inputFilenames = []\n self.impFields = []\n self.NUCorrected = []\n self.NUCorrectedLSQ6 = []\n self.NUCorrectedLSQ6Masks = []\n \n # check consistency in input files\n if(self.singlemask != None):\n if(rf.isFileHandler(self.inputs[0]) and not(rf.isFileHandler(self.singlemask))):\n print(\"Error: the input files and single mask file for NonUniformityCorrection should be the same type. Here, inputs are file handlers, but the single mask is not (perhaps you wanted to associate this mask with the input files using the file handler?).\\n\")\n sys.exit()\n if(not(rf.isFileHandler(self.inputs[0])) and rf.isFileHandler(self.singlemask)):\n print(\"Error: the input files and single mask file for NonUniformityCorrection should be the same type. Here, inputs are not file handlers, but the single mask is.\\n\")\n sys.exit()\n \n if(not(self.useOriginalInput) and self.resampleNUCtoLSQ6):\n print(\"Warning: in NonUniformityCorrection the native files are not used, however resampleNUCtoLSQ6Space is specified. This is not necessary. Disabling this latter option. Only the \\\"nuc\\\" group will be added if file handlers are used.\\n\")\n self.resampleNUCtoLSQ6 = False\n \n # add the first group name (this will either be \"nuc\" or \"nuc-native\"\n if(rf.isFileHandler(self.inputs[0])):\n self.addInitialNUCGroupToInputs()\n \n # now that a new group has been added, we can use the LastBasevol in case of file handlers\n filenames = []\n if(rf.isFileHandler(self.inputs[0])):\n for inputFH in self.inputs:\n filenames.append(inputFH.getLastBasevol())\n else:\n # input files are string\n for inputFile in self.inputs:\n filenames.append(inputFile)\n self.inputFilenames = filenames\n \n # deal with masking\n if(self.singlemask != None):\n # a mask is provided that should be used for all input files\n self.masks = [self.singlemask] * len(self.inputs)\n elif(rf.isFileHandler(self.inputs[0])):\n if(self.inputs[0].getMask() != None):\n self.masks = []\n # the input files have a mask associated with them which we will use\n for inputFH in self.inputs:\n self.masks.append(inputFH.getMask())\n elif(self.initial_model != None):\n self.setupMaskArrayWithInitialModel()\n else:\n pass\n else:\n pass\n \n self.estimateNonUniformity()\n self.evaluateNonUniformity()\n \n if(self.resampleNUCtoLSQ6):\n self.resampleNUCtoLSQ6Space()\n \n def addInitialNUCGroupToInputs(self):\n \"\"\"\n adds the initial group to the file handlers. If useOriginalInput is True, \n the group name will be \"nuc-native\", otherwise it will be \"nuc\".\n \n Be carefule here: if we use the original file as the target for the non uniformity correction,\n the new group needs to be instantiated using that file as well as with its mask.\n \"\"\"\n # create a new group to indicate in the output file names that this is the lsq6 stage\n for i in range(len(self.inputs)):\n if(self.useOriginalInput):\n self.inputs[i].newGroup(groupName=\"nuc-native\", inputVolume=self.inputs[i].inputFileName, mask=self.inputs[i].mask)\n else:\n self.inputs[i].newGroup(groupName=\"nuc\")\n \n def addLSQ6NUCGroupToInputs(self):\n \"\"\"\n The assumption is that the input files have been corrected for non uniformity in native space. This function\n is called just before these corrected files will be resampled to LSQ6 space. \n \n The group name will be \"nuc-lsq6\"\n \"\"\"\n # create a new group to indicate in the output file names that this is the lsq6 stage\n for i in range(len(self.inputs)):\n self.inputs[i].newGroup(groupName=\"nuc-lsq6\", inputVolume=self.NUCorrected[i], mask=self.inputs[i].mask)\n \n \n def setupMaskArrayWithInitialModel(self):\n \"\"\"\n This function is called when no individual masks are present for the input\n files. However, there is an initial model available, and thus we are able\n to use the mask that is part of that.\n \n The mask to be used is the \"standard space mask\". Whether or not that \n mask needs to be resampled, depends on whether we are dealing with the\n non uniformity correction in the native image space (useOriginalInput)\n \"\"\"\n masks = []\n if(self.useOriginalInput):\n # for each input file, we need to resample the standard space mask\n # to its native space\n standardModelFile = self.initial_model[0]\n for inputFH in self.inputs:\n # current assumption is that an lsq6 registration is performed and an lsq6 group is present\n # TODO: allow for differently named 6 paramter groups\n indexLsq6 = None \n for index, value in inputFH.groupNames.iteritems():\n if(value == \"lsq6\"):\n indexLsq6 = index\n if(indexLsq6 != None):\n # find the last transform that is associated with the standard space model\n if(inputFH.groupedFiles[indexLsq6].transforms.has_key(standardModelFile)):\n transformToStandardModel = inputFH.getLastXfm(standardModelFile, groupIndex=indexLsq6)\n rs = ma.mincresampleMask(standardModelFile, \n inputFH, \n likeFile=inputFH, \n argArray=[\"-invert\"], \n transform=transformToStandardModel, \n outputLocation=inputFH)\n rs.name = \"mincresample mask for NUC\"\n self.p.addStage(rs)\n masks.append(rs.outfile)\n # add this mask to the file handler of the input file (to the original)\n inputFH.mask = rs.outfile\n else:\n print(\"Error: could not determine the transformation towards the standard-space initial model using the lsq6 group. Exiting for now.\\n\")\n sys.exit()\n else:\n # if we are not using the original files, we must be using the last input files. Given that the assumption is \n # that the input files are aligned to the standard space, we can simply use that mask for all files\n masks = [self.initial_model[0].mask] * len(self.inputs)\n self.masks = masks\n \n def estimateNonUniformity(self):\n \"\"\"\n more info... create the imp non uniformity estimation\n \"\"\"\n # TODO: base things on the input file size (and allow for overwritten defaults)\n impFields = []\n for i in range(len(self.inputs)):\n inputName = self.inputFilenames[i]\n outFileBase = fh.removeBaseAndExtension(inputName) + \"_nu_estimate.imp\"\n outFileDir = self.inputs[i].tmpDir\n outFile = fh.createBaseName(outFileDir, outFileBase)\n impFields.append(outFile)\n cmd = [\"nu_estimate\", \"-clobber\"]\n cmd += [\"-distance\", \"8\"]\n cmd += [\"-iterations\", \"100\"]\n cmd += [\"-stop\", \"0.0001\"]\n cmd += [\"-fwhm\", \"0.15\"]\n cmd += [\"-shrink\", \"4\"]\n cmd += [\"-lambda\", \"5.0e-02\"]\n if(self.masks):\n mask = self.masks[i]\n cmd += [\"-mask\", InputFile(mask)]\n cmd += [InputFile(inputName)]\n cmd += [OutputFile(outFile)]\n nu_estimate = CmdStage(cmd)\n nu_estimate.colour = \"red\"\n nu_estimate.setLogFile(LogFile(fh.logFromFile(self.inputs[i].logDir, outFile)))\n self.p.addStage(nu_estimate)\n self.impFields = impFields\n\n def evaluateNonUniformity(self):\n \"\"\"\n more info... evaluate / apply the imp field from the \n non uniformity estimation to the input files \n \"\"\"\n nuCorrected = []\n for i in range(len(self.inputs)):\n impField = self.impFields[i]\n inputName = self.inputFilenames[i]\n outFileBase = fh.removeBaseAndExtension(inputName) + \"_nuc.mnc\"\n outFileDir = self.inputs[i].resampledDir\n outFile = fh.createBaseName(outFileDir, outFileBase)\n nuCorrected.append(outFile)\n cmd = [\"nu_evaluate\", \"-clobber\"]\n cmd += [\"-mapping\", InputFile(impField)]\n cmd += [InputFile(inputName)]\n cmd += [OutputFile(outFile)]\n nu_evaluate = CmdStage(cmd)\n nu_evaluate.colour = \"blue\"\n nu_evaluate.setLogFile(LogFile(fh.logFromFile(self.inputs[i].logDir, outFile)))\n self.p.addStage(nu_evaluate)\n self.NUCorrected = nuCorrected\n\n\n def resampleNUCtoLSQ6Space(self):\n \"\"\"\n This function is called when useOriginalInput is True. That means that the \n non uniformity correction was applied to the native files. In order to get\n to the native space, we used the \"lsq6\" group. We will use that group again \n now to resample the NUC file back to lsq6 space.\n \n Can only be called on file handlers \n \"\"\"\n if(not(rf.isFileHandler(self.inputs[0]))):\n print(\"Error: resampleNUCtoLSQ6Space can only be called on file handlers. Goodbye.\\n\")\n sys.exit() \n\n if(self.initial_model == None and self.targetForLSQ6 == None):\n print(\"Error: resampleNUCtoLSQ6Space does not know what to do without an initial model and without a target file for the LSQ6 stage. Sorry. Goodbye.\\n\")\n sys.exit()\n \n # create a new group for these files\n self.addLSQ6NUCGroupToInputs()\n \n nuCorrectedLSQ6 = []\n nuCorrectedLSQ6Masks = []\n lsq6SpaceTarget = None\n if self.initial_model:\n lsq6SpaceTarget = self.initial_model[0]\n else:\n lsq6SpaceTarget = self.targetForLSQ6\n for inputFH in self.inputs:\n # find the lsq6 group again\n indexLsq6 = None \n for index, value in inputFH.groupNames.iteritems():\n if(value == \"lsq6\"):\n indexLsq6 = index\n if(indexLsq6 != None):\n # find the last transform that is associated with the standard space model\n if(inputFH.groupedFiles[indexLsq6].transforms.has_key(lsq6SpaceTarget)):\n transformToLSQ6 = inputFH.getLastXfm(lsq6SpaceTarget, groupIndex=indexLsq6)\n outFileBase = fh.removeBaseAndExtension(inputFH.getLastBasevol()) + \"_lsq6.mnc\"\n outFileDir = inputFH.resampledDir\n outFile = fh.createBaseName(outFileDir, outFileBase)\n nuCorrectedLSQ6.append(outFile)\n resamplings = ma.mincresampleFileAndMask(inputFH,\n lsq6SpaceTarget,\n nameForStage=\"mincresample NUC to LSQ6\",\n likeFile=lsq6SpaceTarget, \n transform=transformToLSQ6,\n output=outFile,\n argArray=[\"-sinc\"])\n nuCorrectedLSQ6Masks.append(resamplings.outputFilesMask[0])\n self.p.addPipeline(resamplings.p)\n else:\n # not good either...\n print(\"\\nError: can not find the 6 parameter transformation between: %s and %s (in the function: resampleNUCtoLSQ6Space). Exiting now...\\n\" % (inputFH.inputFileName, lsq6SpaceTarget.inputFileName))\n sys.exit()\n else:\n #oops...\n print(\"\\nError: we were not able to find the \\\"lsq6\\\" class of files during the non uniformity correction stage. Were trying to determine the transformation that resamples the non uniformity corrected file in native space to LSQ6 space. Exiting now...\\n\\n\")\n sys.exit()\n self.NUCorrectedLSQ6 = nuCorrectedLSQ6\n self.NUCorrectedLSQ6Masks = nuCorrectedLSQ6Masks\n\n def finalize(self):\n \"\"\"\n Sets the last base volume based on how this object was called/created. If the files have\n been resampled to LSQ6 space, the last base volume should be NUCorrectedLSQ6, otherwise\n it should be NUCorrected\n \"\"\"\n if(self.resampleNUCtoLSQ6):\n for i in range(len(self.inputs)):\n # the NUC (and potentially the mask) files have been\n # resampled to LSQ6 space. That means that we can set\n # the last basevol using the last resampled files (i.e.,\n # no arguments to setLastBasevol)\n self.inputs[i].setLastBasevol()\n else:\n for i in range(len(self.inputs)):\n # specify the last basevol explicitly, because applying\n # the non uniformity correction does not resampled the file \n self.inputs[i].setLastBasevol(self.NUCorrected[i])\n if(self.masks != None):\n self.inputs[i].setMask(self.masks[i]) \n\nclass IntensityNormalization(object):\n \"\"\"\n * mask potential single mask to be used for all input files \n \n * inputFiles can be provided as a list of strings, or a list\n of file handlers\n \n * if the input files are file handlers, a group inorm will be added\n \n * possible options for the method (for ease of use they are simply the flag \n used for inormalize):\n - \"-ratioOfMeans\"\n - \"-ratioOfMedians\"\n - \"-meanOfRatios\"\n - \"-meanOfLogRatios\"\n - \"-medianOfRatios\"\n\n * similarly to what is done in the non uniformity correction class, a target file for \n the LSQ6 stage can be specified. That way we still know which transformation to use \n when resampleINORMtoLSQ6 is provided. \n\n * resampleINORMtoLSQ6 - \n \n === can only be called on file handlers ===\n \n In a way this is a special option for the class. The intensity normalization\n class can be used on any kind of input at any stage in a pipeline. But when running an\n image registration pipeline we use the intensity normalization right after the input\n files have been registered using 6 parameters (lsq6). When the registration is run using\n an initial model, there will be a mask present, and after aligning the input files to that\n model, we can use that mask for the intensity normalization. To reduce the amount of \n resampling error in the entire pipeline, the intensity normalization (as well as the non-\n uniformity correction) should be applied in native space. If that is the situation that\n this class is called in, resampleINORMtoLSQ6 can be set to True, and the normalized file\n will be resampled in lsq6 space, in order to continue there with the lsq12 stage. Keep in\n mind that after lsq12, the native inormalized (and non-uniformity correction) file should \n be resampled to lsq12. That way we avoid one resampling step, i.e., wrong way:\n \n native-normalized -> native-normalized-in-lsq6 -> native-normalized-in-lsq6-in-lsq12 (when starting non linear stages)\n \n right way:\n \n native-normalized -> native-normalized-in-lsq6 (when starting lsq12)\n native-normalized -> native-normlaized-in-lsq12 (when starting non linear stages)\n \"\"\"\n def __init__(self,\n inputFiles,\n options,\n mask = None,\n inorm_const = 1000,\n method = \"-ratioOfMedians\",\n resampleINORMtoLSQ6 = False,\n initial_model = None,\n targetForLSQ6 = None):\n self.p = Pipeline()\n self.options = options\n self.inputs = inputFiles\n self.masks = None\n self.inormconst = inorm_const\n self.method = method\n self.resampleINORMtoLSQ6 = resampleINORMtoLSQ6\n self.initial_model = initial_model\n self.targetForLSQ6 = targetForLSQ6\n self.INORM = []\n self.INORMLSQ6 = []\n self.INORMLSQ6Masks = []\n self.inputFilenames = []\n \n # deal with input files\n if(rf.isFileHandler(self.inputs[0])):\n for inputFH in self.inputs:\n self.inputFilenames.append(inputFH.getLastBasevol())\n self.setINORMGroupToInputs()\n else:\n for inputName in self.inputs:\n self.inputFilenames.append(inputName)\n \n # once again, sort out the masking business \n if(mask != None):\n self.masks = [mask] * len(self.inputs)\n else:\n # check whether the input files have masks associated with\n # them already\n if(self.inputs[0].getMask() != None):\n masks = []\n for i in range(len(self.inputs)):\n masks.append(self.inputs[i].getMask())\n self.masks = masks\n \n # add the \"inorm\" group name\n if(rf.isFileHandler(self.inputs[0])):\n self.setINORMGroupToInputs()\n \n self.runNormalization()\n \n if(self.resampleINORMtoLSQ6):\n self.resampleINORMtoLSQ6Space()\n \n if(rf.isFileHandler(self.inputs[0])):\n self.setINORMasLastBaseVolume()\n \n def setINORMGroupToInputs(self):\n \"\"\"\n make sure that by default any input file handler is \n given the group \"inorm\"\n \"\"\"\n # create a new group to indicate in the output file names that this is the lsq6 stage\n for i in range(len(self.inputs)):\n self.inputs[i].newGroup(groupName=\"inorm\") \n \n def addLSQ6INORMGroupToInputs(self):\n \"\"\"\n The assumption is that the input files have been intensity normalized in native space. This function\n is called just before these normalized files will be resampled to LSQ6 space. \n \n The group name will be \"inorm-lsq6\"\n \"\"\"\n # create a new group to indicate in the output file names that this is the lsq6 stage\n for i in range(len(self.inputs)):\n self.inputs[i].newGroup(groupName=\"inorm-lsq6\", inputVolume=self.INORM[i], mask=self.inputs[i].getMask())\n \n \n def runNormalization(self):\n \"\"\"\n \"\"\"\n normalized = []\n for i in range(len(self.inputFilenames)): \n inputName = self.inputFilenames[i]\n outFileBase = fh.removeBaseAndExtension(inputName) + \"_inorm.mnc\"\n outFileDir = self.inputs[i].resampledDir\n outFile = fh.createBaseName(outFileDir, outFileBase)\n normalized.append(outFile)\n cmd = [\"inormalize\", \"-clobber\"]\n cmd += [\"-const\", self.inormconst]\n cmd += [self.method]\n if(self.masks != None):\n cmd += [\"-mask\", self.masks[i]]\n cmd += [InputFile(inputName)]\n cmd += [OutputFile(outFile)]\n inormalize = CmdStage(cmd)\n inormalize.colour = \"yellow\"\n inormalize.setLogFile(LogFile(fh.logFromFile(self.inputs[i].logDir, outFile)))\n self.p.addStage(inormalize)\n self.INORM = normalized\n\n def resampleINORMtoLSQ6Space(self):\n \"\"\"\n Can only be called on file handlers\n \n The assumption is that an lsq6 registration has been performed, and that there\n is a transformation from the native input file to the standard space in the \n initial model /// or that we have the 6 parameter transform from native to\n the pipeline target (possibly given by --lsq6-target or --bootstrap)\n \"\"\"\n if(not(rf.isFileHandler(self.inputs[0]))):\n print(\"Error: resampleINORMtoLSQ6Space can only be called on file handlers. Goodbye.\\n\")\n sys.exit()\n \n if(self.initial_model == None and self.targetForLSQ6 == None):\n print(\"Error: resampleINORMtoLSQ6Space does not know what to do without an initial model and without a target file for the LSQ6 stage. Sorry. Goodbye.\\n\")\n sys.exit()\n \n # create a new group for these files\n self.addLSQ6INORMGroupToInputs()\n \n INORMLSQ6 = []\n INORMLSQ6Masks = []\n if self.initial_model:\n lsq6SpaceTarget = self.initial_model[0]\n else:\n lsq6SpaceTarget = self.targetForLSQ6\n for inputFH in self.inputs:\n # find the lsq6 group again\n indexLsq6 = None \n for index, value in inputFH.groupNames.iteritems():\n if(value == \"lsq6\"):\n indexLsq6 = index\n if(indexLsq6 != None):\n # find the last transform that is associated with the standard space model\n if(inputFH.groupedFiles[indexLsq6].transforms.has_key(lsq6SpaceTarget)):\n transformToLSQ6 = inputFH.getLastXfm(lsq6SpaceTarget, groupIndex=indexLsq6)\n outFileBase = fh.removeBaseAndExtension(inputFH.getLastBasevol()) + \"_lsq6.mnc\"\n outFileDir = inputFH.resampledDir\n outFile = fh.createBaseName(outFileDir, outFileBase)\n INORMLSQ6.append(outFile)\n resamplings = ma.mincresampleFileAndMask(inputFH, \n lsq6SpaceTarget, \n nameForStage = \"mincresample INORM to LSQ6\",\n likeFile=lsq6SpaceTarget, \n transform=transformToLSQ6,\n output=outFile,\n argArray=[\"-sinc\"])\n INORMLSQ6Masks.append(resamplings.outputFilesMask[0])\n self.p.addPipeline(resamplings.p)\n else:\n # not good either...\n print(\"\\nError: can not find the 6 parameter transformation between: %s and %s (in the function: resampleINORMtoLSQ6Space). Exiting now...\\n\" % (inputFH.inputFileName, lsq6SpaceTarget.inputFileName))\n sys.exit()\n else:\n # oops...\n print(\"\\nError: we were not able to find the \\\"lsq6\\\" class of files during the inormalize stage. Were trying to determine the transformation that resamples the intensity normalized file in native space to LSQ6 space. Exiting now...\\n\\n\")\n sys.exit()\n self.INORMLSQ6 = INORMLSQ6\n self.INORMLSQ6Masks = INORMLSQ6Masks\n\n def setINORMasLastBaseVolume(self):\n if(self.resampleINORMtoLSQ6):\n for i in range(len(self.inputs)):\n # the INORM (and potentially the mask) files have been\n # resampled to LSQ6 space. That means that we can set\n # the last basevol using the last resampled files (i.e.,\n # no arguments to setLastBasevol)\n self.inputs[i].setLastBasevol() \n else:\n for i in range(len(self.inputs)):\n self.inputs[i].setLastBasevol(self.INORM[i])\n \n \n\nclass LSQ6Base(object):\n \"\"\"\n This is the parent class for any lsq6 registration method. It implements the following:\n \n - check input files (at the moment assumed to be file handlers\n - check whether an lsq6 directory is provided when more than 1 input file is given\n - creates a new group for the input files: \"lsq6\"\n \n (the child classes will fill in the function createLSQ6Transform)\n \n - handle a potential ...native_to_standard.xfm transform from an initial model\n - resample the input files\n - create an average if at least 2 input files are given\n \n Assumptions:\n * inputFiles are expected to be file handlers\n * targetFile is expected to be a file handler\n * the lsq6OutputDir is required when at least 2 inputFiles are given\n \n Output:\n - (self.lsq6Avg) if at least 2 input files were provided, this class will \n store the file handler for the average in the variable lsq6Avg \n \"\"\"\n def __init__(self,\n inputFiles,\n targetFile,\n options,\n initial_model = None,\n lsq6OutputDir = None):\n self.p = Pipeline()\n self.options = options\n self.inputs = inputFiles\n self.target = targetFile\n self.initial_model = initial_model\n self.lsq6OutputDir = lsq6OutputDir \n self.lsq6Avg = None # will contain file handler to lsq6 average\n self.filesToAvg = [] # store the resampled lsq6 files in order to create an average at the end\n \n self.check_inputs()\n self.check_lsq6_folder()\n self.setLSQ6GroupToInputs()\n \n # Get file resolution for each file: will need for subclasses. \n # We base a number of parameters on the resolution of the target files / input files.\n # This is mostly for minctracc calls which needs input files to be blurred and we set\n # the -step parameter for minctracc based on the resolution of the target for the \n # registration. As such, we should simply use the targetFile for the registration \n # to base these parameters on\n self.fileRes = rf.returnFinestResolution(self.target)\n \n def check_inputs(self):\n \"\"\"\n Currently only file handlers are covered in these classes. This function\n check whether both input and target files are given as file handlers \n \"\"\"\n # input file checking... \n if(not(type(self.inputs) is list)):\n if(not rf.isFileHandler(self.inputs)):\n print(\"My apologies... the LSQ6 modules currently only work with file handlers (input file)...\\nGoodbye\")\n sys.exit()\n else:\n # for ease of use, turn into a list\n self.inputs = [self.inputs]\n else:\n for inputfile in self.inputs:\n if(not rf.isFileHandler(inputfile)):\n print(\"My apologies... the LSQ6 modules currently only work with file handlers (input files)...\\nGoodbye\")\n sys.exit()\n if(not rf.isFileHandler(self.target)):\n print(\"My apologies... the LSQ6 modules currently only work with file handlers (target file)...\\nGoodbye\")\n sys.exit()\n \n def check_lsq6_folder(self):\n \"\"\"\n Make sure that the output directory for the lsq6 average is \n defined is at least 2 input files are provided\n \"\"\"\n if(len(self.inputs) > 1 and not(self.lsq6OutputDir)):\n print(\"Error: \", len(self.inputs), \" input files were provided to the LSQ6 module but no output directory for the average was given. Don't know where to put it...\\nGoodbye.\")\n sys.exit()\n \n # just in case this directory was not created yet\n if(self.lsq6OutputDir):\n fh.makedirsIgnoreExisting(self.lsq6OutputDir)\n\n def setLSQ6GroupToInputs(self):\n \"\"\"\n make sure that by default any input file handler is \n given the group \"lsq6\"\n \"\"\"\n # create a new group to indicate in the output file names that this is the lsq6 stage\n for i in range(len(self.inputs)):\n self.inputs[i].newGroup(groupName=\"lsq6\")\n\n def createLSQ6Transformation(self):\n \"\"\"\n This function is to be filled in the child classes. For instance\n a rotational minctracc could be called here, or a hierarchical\n 6 parameter minctracc call\n \"\"\"\n pass\n\n def addNativeToStandardFromInitModel(self):\n \"\"\"\n If an initial model is used, we might have to concatenate\n the 6 parameter transformation that was created with the \n transformation from the inital model. This function does\n that if necessary\n \"\"\"\n if(self.initial_model != None):\n if(self.initial_model[2] != None):\n for inputFH in self.inputs:\n if not isinstance(inputFH, rfh.RegistrationPipeFH):\n raise TypeError(\"only works with file handlers\")\n else:\n prevxfm = inputFH.getLastXfm(self.target) # pylint: disable=E1101\n newxfm = inputFH.registerVolume(self.initial_model[0], \"transforms\") # pylint: disable=E1101\n logFile = fh.logFromFile(inputFH.logDir, newxfm) # pylint: disable=E1101\n self.p.addStage(ma.xfmConcat([prevxfm, self.initial_model[2]],\n newxfm,\n logFile))\n \n def resampleInputFilesAndSetLastBasevol(self, prefix_to_change_output = None):\n \"\"\"\n resample input files using the last transformation, and then\n set the last basevolume for the inputfile to be the output\n of the mincresample call\n \"\"\"\n for inputfile in self.inputs:\n likeFileForResample = self.target\n targetFHforResample = self.target\n if(self.initial_model != None):\n if(self.initial_model[1] != None):\n likeFileForResample = self.initial_model[0]\n targetFHforResample = self.initial_model[0]\n resamplings = ma.mincresampleFileAndMask(inputfile,\n targetFHforResample,\n likeFile=likeFileForResample,\n argArray=[\"-sinc\"])\n self.filesToAvg.append(resamplings.outputFiles[0])\n self.p.addPipeline(resamplings.p)\n # no arguments need to be provided to setLastBasevol: the last\n # resampled file will be used. If a mask was also resampled\n # during the last stage, this will be updated as well.\n inputfile.setLastBasevol() # pylint: disable=E1101\n \n\n def createAverage(self, alternate_lsq6_average=None):\n \"\"\"\n Create the lsq6 average if at least 2 input files have been given\n \"\"\"\n if(len(self.filesToAvg) > 1):\n if alternate_lsq6_average is None:\n lsq6AvgOutput = abspath(self.lsq6OutputDir) + \"/\" + \"lsq6_average.mnc\"\n else:\n # a different set of input files was used for the 6 parameter \n # alignment. An average will be created for these files, but \n # it's not the one we care about for the overall pipeline. Its\n # name will reflect that:\n lsq6AvgOutput = abspath(self.lsq6OutputDir) + \"/\" + alternate_lsq6_average + \"lsq6_average.mnc\"\n # TODO: fix mask issue\n lsq6FH = rfh.RegistrationPipeFH(lsq6AvgOutput, mask=None, basedir=self.lsq6OutputDir)\n logBase = fh.removeBaseAndExtension(lsq6AvgOutput)\n avgLog = fh.createLogFile(lsq6FH.logDir, logBase)\n # Note: We are calling mincAverage here with filenames rather than file handlers\n avg = ma.average(self.filesToAvg, outputAvg=lsq6AvgOutput, logFile=avgLog,\n queue_type=self.options.queue_type, \n copyHeaderInfo=self.options.copy_header_info)\n self.p.addStage(avg)\n self.lsq6Avg = lsq6FH\n\n def finalize(self, alternate_lsq6_average=None):\n \"\"\"\n Within one call, take care of the potential initial model transformation,\n the resampling of input files and create an average \n \"\"\"\n self.addNativeToStandardFromInitModel()\n self.resampleInputFilesAndSetLastBasevol()\n self.createAverage(alternate_lsq6_average)\n\nclass LSQ6RotationalMinctracc(LSQ6Base):\n \"\"\"\n This class performs an lsq6 registration using rotational minctracc\n from start to end. That means that it takes care of blurring the\n input files and target, running RotationalMinctracc, resample the \n input files, and create an average if at least 2 input files are provided.\n \n * Assumptions/input:\n - inputFiles are provided in the form of file handlers\n - targetFile is provided as a file handler\n - large_rotation_parameters is the same as RotationalMinctracc() in minc_atoms,\n please see that module for more information\n - if an initial model is provided, the input to the parameter\n initial_model is assumed to be the output of the function \n setupInitModel()\n - lsq6OutputDir is a string indicating where the the potential average should go\n \n Output:\n - (self.lsq6Avg) if at least 2 input files were provided, this class will \n store the file handler for the average in the variable lsq6Avg \n \n \"\"\"\n def __init__(self, \n inputFiles,\n targetFile,\n options,\n initial_model = None,\n lsq6OutputDir = None,\n large_rotation_parameters=\"10,4,10,8\",\n large_rotation_range = 50,\n large_rotation_interval = 10):\n # initialize all the defaults in parent class\n LSQ6Base.__init__(self, inputFiles, targetFile, options,\n initial_model=initial_model,\n lsq6OutputDir=lsq6OutputDir)\n \n self.parameters = large_rotation_parameters\n self.rotation_range = large_rotation_range\n self.rotation_interval = large_rotation_interval\n \n def createLSQ6Transformation(self): \n # We should take care of the appropriate amount of blurring\n # for the input files here\n \n # assumption: all files have the same resolution, so we take input file 1\n highestResolution = self.fileRes\n blurAtResolution = -1\n resampleStepFactor = -1\n registrationStepFactor = -1\n wTranslationsFactor = -1\n \n # first... if we are dealing with mouse brains, we should set the defaults\n # not on the actual resolution of the files, but on the best parameter set\n # for mouse brains. Still we have to feed those in as factors, so we have\n # to do a bit of a silly conversion from resolution to factors now \n if(self.parameters == \"mousebrain\"):\n # the amount of blurring should simply be 0.56 mm\n blurAtResolution = 0.56\n # the resample stepsize should be 0.224\n resampleStepFactor = 0.224 / highestResolution\n # the registration stepsize should be 0.56\n registrationStepFactor = 0.56 / highestResolution\n # w_translations should be 0.448\n wTranslationsFactor = 0.448 / highestResolution\n else:\n parameterList = self.parameters.split(',')\n blurFactor= float(parameterList[0])\n if(blurFactor != -1):\n blurAtResolution = blurFactor * highestResolution\n resampleStepFactor = float(parameterList[1])\n registrationStepFactor = float(parameterList[2])\n wTranslationsFactor = float(parameterList[3])\n \n self.p.addStage(ma.blur(self.target, fwhm=blurAtResolution))\n \n for inputFH in self.inputs: \n self.p.addStage(ma.blur(inputFH, fwhm=blurAtResolution))\n self.p.addStage((ma.RotationalMinctracc(inputFH,\n self.target,\n blur = blurAtResolution,\n resample_step = resampleStepFactor,\n registration_step = registrationStepFactor,\n w_translations = wTranslationsFactor,\n rotational_range = self.rotation_range,\n rotational_interval= self.rotation_interval )))\n\n\nclass LSQ6HierarchicalMinctracc(LSQ6Base):\n \"\"\"\n This class performs an lsq6 registration using a series of 6 parameter\n minctracc calls.\n \n * Assumptions/input\n - inputFiles are provided in the form of file handlers\n - targetFile is provided as a file handler\n - if an initial model is provided, the input to the parameter\n initial_model is assumed to be the output of the function \n setupInitModel()\n - lsq6OutputDir is a string indicating where the the potential average should go\n only needs to be provided if at least 2 input files are given\n \n - initial_transform\n This parameter can be either \"estimate\" or \"identity\". When \"estimate\" is \n provided, the assumption is that the files are not in the same part in space,\n and the centre of gravity of the files will be used to determine the initial\n alignment. When \"identity\" is given, the input files are already assumed to \n be roughly aligned.\n \n - lsq6_protocol\n By default the minctracc calls that will be run are based on the resolution \n of the input files. 5 generations are run for \"estimate\", and 3 generations\n are run in the case of \"identity\". If you want to override these default\n settings, you can specify the path to a csv file containing the desired \n settings using this parameter. For more information about the defaults,\n see below. For an example of an lsq6 protocol, see the help for the \n LSQ6Registration class. \n \n Output:\n - (self.lsq6Avg) if at least 2 input files were provided, this class will \n store the file handler for the average in the variable lsq6Avg \n \"\"\"\n def __init__(self,\n inputFiles,\n targetFile,\n options,\n initial_model = None,\n lsq6OutputDir = None,\n initial_transform = \"estimate\",\n lsq6_protocol = None):\n # initialize all the defaults in the parent class\n LSQ6Base.__init__(self, inputFiles, targetFile, options,\n initial_model=initial_model,\n lsq6OutputDir=lsq6OutputDir)\n self.initial_transform = initial_transform \n self.lsq6_protocol = lsq6_protocol\n \n #Read parameters from input file or setup defaults. \n self.lsq6Params = mp.setLSQ6MinctraccParams(self.fileRes, \n initial_transform=initial_transform, \n reg_protocol=lsq6_protocol)\n self.blurs = self.lsq6Params.blurs\n self.stepSize = self.lsq6Params.stepSize\n self.useGradient = self.lsq6Params.useGradient\n self.simplex = self.lsq6Params.simplex\n self.w_translations = self.lsq6Params.w_translations\n self.generations = self.lsq6Params.generations\n \n # Setup linearparams for minctracc atom\n self.setupLinearParams()\n \n def setupLinearParams(self):\n #All linearparams should be \"lsq6\" except first, which is based on initial_transform. \n self.linearParams=[]\n for i in range(self.generations - 1):\n self.linearParams.append(\"lsq6\")\n if self.initial_transform == \"estimate\":\n self.linearParams.insert(0,\"lsq6\")\n elif self.initial_transform == \"identity\":\n self.linearParams.insert(0, \"lsq6-identity\")\n else:\n print(\"Error: unknown option used for initial_transform in LSQ6HierarchicalMinctracc: \", self.initial_transform)\n sys.exit()\n \n def createLSQ6Transformation(self):\n \"\"\"\n Assumption: setLSQ6MinctraccParams has been called prior to running. \n \"\"\"\n # create all blurs first\n for i in range(self.generations):\n self.p.addStage(ma.blur(self.target, self.blurs[i], gradient=True))\n for inputfile in self.inputs:\n # create blur for input\n self.p.addStage(ma.blur(inputfile, self.blurs[i], gradient=True))\n \n # now perform the registrations\n for inputfile in self.inputs:\n for i in range(self.generations):\n mt = ma.minctracc(inputfile,\n self.target,\n blur = self.blurs[i],\n simplex = self.simplex[i],\n step = self.stepSize[i],\n gradient = self.useGradient[i],\n w_translations = self.w_translations[i],\n linearparam = self.linearParams[i]) \n self.p.addStage(mt)\n\n\n \n\nif __name__ == \"__main__\":\n application = LSQ6Registration()\n application.start()\n","sub_path":"atoms_and_modules/LSQ6.py","file_name":"LSQ6.py","file_ext":"py","file_size_in_byte":72891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"23002534","text":"import tushare as ts\nfrom pandas import read_csv\nimport sqlite3\nimport time\nimport datetime as dt\nimport sys\n\npro = ts.set_token('6d9ac99d25b0157dcbb1ee3d35ef1250e5295ff80bb59741e1a56b35')\npro1 = ts.pro_api('6d9ac99d25b0157dcbb1ee3d35ef1250e5295ff80bb59741e1a56b35')\n\n# 获取完整股票列表\ndef SaveAllStockList():\n pro = ts.pro_api('6d9ac99d25b0157dcbb1ee3d35ef1250e5295ff80bb59741e1a56b35')\n df = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol')\n allstocklistdic = dict()\n for col in df.values:\n allstocklistdic[col[0]] = col[1]\n print('AllStockList has save')\n return allstocklistdic\n\n# 批量写入多条数据库\ndef writeSqlList_db(constr, sqllist):\n try:\n conn = getconn(constr)\n cursor = conn.cursor()\n for sql in sqllist:\n cursor.execute(sql)\n conn.commit()\n conn.close()\n except Exception as e:\n print(e)\n\n# 获取数据库连接\ndef getconn(conStr):\n try:\n conn = sqlite3.connect(conStr)\n return conn\n except Exception as e:\n raise e\n\n# 删除数据\ndef del_db(constr):\n try:\n conn = getconn(constr)\n cursor = conn.cursor()\n cursor.execute('''delete from daylevel''')\n cursor.close()\n conn.commit()\n conn.close()\n except Exception as e:\n print(e)\n\ndef SaveDataToSqlite(constr, stocklistdic, begindate, enddate):\n try:\n count = 0\n sqlstrlist = list()\n finishlist = list()\n for code in stocklistdic.keys():\n df = ts.pro_bar(ts_code=code, start_date=begindate, end_date=enddate)\n count += 1\n if len(df.values) < 6:\n continue\n for i in range(len(df.values)):\n value = df.values[i]\n param = {'symbol':value[0], 'tdate':value[1], 'open':value[2], 'high':value[3], \\\n 'low':value[4], 'close':value[5], 'lclose':value[6], 'vol':value[9], 'amount':value[10] }\n sqlstrlist.append('''insert into DayLevel (symbol, tdate, open, high, low, close, lclose, vol, amount) values ('%s' , '%s' , '%s' , '%s' , '%s' , '%s' , '%s' , '%s' , '%s' );'''\\\n %(param[\"symbol\"],param[\"tdate\"],param[\"open\"],param[\"high\"],param[\"low\"],param[\"close\"],param[\"lclose\"],param[\"vol\"],param[\"amount\"]))\n finishlist.append(code)\n if count % 100 == 0:\n writeSqlList_db(constr, sqlstrlist)\n print(count, ' finish', dt.datetime.now())\n sqlstrlist = list()\n if count % 500 == 0:\n print('因为贫穷导致的休眠1min')\n time.sleep(30)\n if len(sqlstrlist) > 0:\n writeSqlList_db(constr, sqlstrlist)\n print(count, ' finish', dt.datetime.now())\n print('finish all')\n except Exception as e:\n print(e)\n print(finishlist)\n\n\nif __name__ == '__main__':\n #print(\"input begindate and enddate, use ',' to split date, such as: '20210512,20210519'\")\n #inputdate = input()\n #inputdatelist = inputdate.split(\",\")\n #startdate = inputdatelist[0]\n #enddate = inputdatelist[1] \n stocklistdic = SaveAllStockList()\n startdate = dt.datetime.today() - dt.timedelta(8)\n enddate = dt.datetime.today() - dt.timedelta(1)\n constr = \"E:\\MyGit\\BigDataFile\\QSstrategy\\HistoryData.db3\"\n # 每次更新前,先删除历史数据\n del_db(constr)\n # 删除后在重新下载最近6天的历史数据\n SaveDataToSqlite(constr, stocklistdic, startdate.strftime('%Y%m%d'), enddate.strftime('%Y%m%d'))\n print('finish')\n #sys.exit(0)\n \n \n ","sub_path":"GetAPIData/GetTushareData/04DownloadHistoryData.py","file_name":"04DownloadHistoryData.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"486886909","text":"def preorder(node): # (루트) (왼쪽 자식) (오른쪽 자식)\n if node == '.':\n return\n print(node,end='')\n preorder(my_dict[node][0])\n preorder(my_dict[node][1])\n\ndef inorder(node): # (왼쪽 자식) (루트) (오른쪽 자식)\n if node == '.':\n return\n inorder(my_dict[node][0])\n print(node, end='')\n inorder(my_dict[node][1])\n\ndef postorder(node): # (왼쪽 자식) (오른쪽 자식) (루트)\n if node == '.':\n return\n postorder(my_dict[node][0])\n postorder(my_dict[node][1])\n print(node, end='')\n\nN = int(input())\nmy_dict = {}\nfor _ in range(N):\n root, left, right = input().split()\n my_dict[root] = [left, right]\n\npreorder('A')\nprint()\ninorder('A')\nprint()\npostorder('A')\nprint()","sub_path":"doyeon/BOJ/★트리/20210302_boj_1991_트리 순회.py","file_name":"20210302_boj_1991_트리 순회.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"376771454","text":"from pico2d import *\r\nimport random\r\nimport game_framework\r\nimport title_state\r\nimport Game_over\r\nimport char_sellect\r\nimport WITCH\r\nfrom WITCH import Witch # import Boy class from boy.py\r\nfrom WITCH import Witch_R\r\nfrom WITCH import Witch_B\r\nfrom BG import Grass\r\nfrom FireBall import FireBall1\r\nfrom FireBall import FireBall2\r\nfrom FireBall import FireBall3\r\nfrom FireBall import FireBall4\r\nfrom WAND import Wand\r\nfrom item import Coin\r\nfrom item import Potion\r\n\r\nname = \"collision\"\r\nwand = None\r\nFB1 = []\r\nFB2 = []\r\nFB3 = []\r\nFB4 = []\r\nFB5 = []\r\ngrass = None\r\nballs = None\r\nfont = None\r\nitem = []\r\npotion = []\r\nTime = 0.0\r\nGameScore = 0\r\n\r\nbgm = None\r\nclass Timer:\r\n def __init__(self):\r\n self.Whattime = 0\r\n self.itemtime = 0\r\n self.potintime =0\r\n self.Scoretime = 0\r\n def update(self, frame_time):\r\n self.Whattime += frame_time\r\n self.itemtime += frame_time\r\n self.Scoretime += frame_time\r\n self.potintime += frame_time\r\n self.add()\r\n def add(self):\r\n if self.Whattime >= 1.3:\r\n new_fireball1 = FireBall1()\r\n FB5.append(new_fireball1)\r\n new_fireball2 = FireBall2()\r\n FB5.append(new_fireball2)\r\n new_fireball3 = FireBall3()\r\n FB5.append(new_fireball3)\r\n new_fireball4 = FireBall4()\r\n FB5.append(new_fireball4)\r\n self.Whattime = 0\r\n if self.potintime >= 3.3 :\r\n new_potion = Potion()\r\n potion.append(new_potion)\r\n self.potintime =0\r\n if self.itemtime >= 2:\r\n new_item = Coin()\r\n item.append(new_item)\r\n self.itemtime = 0\r\n\r\ndef create_world():\r\n global witch, grass, FB1, FB2, FB3 ,wand ,FB4, Fireballnum, timer, FB5,GameScore, bgm, select_witch, font\r\n timer = Timer()\r\n wand = Wand()\r\n GameScore =0\r\n font = load_font('ENCR10B.TTF')\r\n if char_sellect.select_witch == 1 :\r\n witch = Witch_R()\r\n bgm = load_music('FL_BGM_C.mp3')\r\n bgm.set_volume(64)\r\n bgm.repeat_play()\r\n elif char_sellect.select_witch == 2 :\r\n witch = Witch_B()\r\n bgm = load_music('FL_BGM_D.mp3')\r\n bgm.set_volume(64)\r\n bgm.repeat_play()\r\n elif char_sellect.select_witch == 3 :\r\n witch = Witch()\r\n bgm = load_music('FL_BGM_E.mp3')\r\n bgm.set_volume(64)\r\n bgm.repeat_play()\r\n FB1 = []\r\n FB2 = []\r\n FB3 = []\r\n FB4 = []\r\n FB5 = []\r\n grass = Grass()\r\n\r\n\r\ndef destroy_world():\r\n global witch, grass, FB5 , timer, bgm\r\n del(witch)\r\n del(FB5)\r\n del(grass)\r\n del(bgm)\r\n\r\n\r\n\r\ndef enter():\r\n\r\n game_framework.reset_time()\r\n create_world()\r\n\r\n\r\n\r\ndef exit():\r\n destroy_world()\r\n\r\n\r\ndef pause():\r\n pass\r\n\r\n\r\ndef resume():\r\n pass\r\n\r\ndef handle_events(frame_time):\r\n events = get_events()\r\n for event in events:\r\n if event.type == SDL_QUIT:\r\n game_framework.quit()\r\n else:\r\n if (event.type, event.key) == (SDL_KEYDOWN, SDLK_ESCAPE):\r\n game_framework.quit()\r\n else:\r\n witch.handle_event(event)\r\n\r\n\r\n\r\n\r\ndef collide(a, b):\r\n left_a, bottom_a,right_a, top_a = a.get_bb()\r\n left_b, bottom_b,right_b, top_b = b.get_bb()\r\n\r\n if left_a > right_b : return False\r\n if right_a < left_b : return False\r\n if top_a < bottom_b : return False\r\n if bottom_a > top_b : return False\r\n\r\n return True\r\ndef get_time(frame_time):\r\n global Time, Fireballnum\r\n\r\n Time += frame_time\r\n return Time\r\n\r\ndef update(frame_time):\r\n for Score in item :\r\n Score.update(frame_time)\r\n for Score in potion:\r\n Score.update(frame_time)\r\n\r\n\r\n for ball in FB5:\r\n ball.update(frame_time)\r\n\r\n for ball in FB5 :\r\n if collide(ball, witch):\r\n FB5.remove(ball)\r\n witch.HP()\r\n\r\n for Score in item:\r\n if collide(Score, witch):\r\n item.remove(Score)\r\n witch.eat(Score)\r\n for Score in potion:\r\n if collide(Score, witch):\r\n potion.remove(Score)\r\n witch.eat_p(Score)\r\n\r\n witch.update(frame_time)\r\n timer.update(frame_time)\r\n\r\n\r\n\r\n\r\ndef draw(frame_time):\r\n clear_canvas()\r\n grass.draw()\r\n witch.draw()\r\n font.draw(620,580,'life = %d' %(witch.life))\r\n font.draw(620,560, 'Score = %d'%(witch.Score))\r\n\r\n for Score in item :\r\n Score.draw()\r\n\r\n for Score in potion :\r\n Score.draw()\r\n for ball in FB5:\r\n ball.draw()\r\n\r\n # grass.draw_bb()\r\n witch.draw_bb()\r\n for ball in FB5 :\r\n ball.draw_bb()\r\n\r\n update_canvas()\r\n\r\n\r\n","sub_path":"collision.py","file_name":"collision.py","file_ext":"py","file_size_in_byte":4638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"276906820","text":"import numpy as np\nimport cv2\nfrom scipy.interpolate import interp1d\nfrom utils import *\nfrom evaluator import Evaluator\n\nimg = loadImage('final_image.tif')\n\n# Isolate region A\n# Step 1: extract the region from the main image\nlength = 80\nwidth = 60\nstartY = (img.shape[0] - width) // 2\nstartX = (img.shape[1] - length) // 2\n\nregA = img[startY:startY + width, startX:startX + length]\n\n# Isolate region B\nregB = img\n\nevalA = Evaluator(regA, \"Region A\", 8)\nevalA.analyzeRegion()\n\nevalB = Evaluator(regB, \"Region B\", 14)\nevalB.analyzeRegion()\n\ncv2.imshow(\"RegionA\", regA)\ncv2.imshow(\"RegionB\", regB)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"}